Metadata-Version: 2.4
Name: abacist
Version: 0.1.0
Summary: A deterministic reasoning ledger for AI agents: record facts with their evidence, then ask what is reachable, what is missing, and what an answer rests on.
License-Expression: Apache-2.0
Project-URL: Repository, https://github.com/strmforge/Abacist
Keywords: mcp,planning,reachability,provenance,agents,hallucination
Classifier: Programming Language :: Python :: 3
Classifier: Operating System :: OS Independent
Classifier: Intended Audience :: Developers
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Provides-Extra: mcp
Requires-Dist: mcp<3,>=2.3; extra == "mcp"
Dynamic: license-file

# Abacist

A deterministic reasoning ledger for AI agents, usable as a Python library, a command-line
tool or an MCP server. It calls no language model and works with any agent that can call MCP
tools or run a command.

Language models are good at proposing what might happen and poor at keeping track of what
is actually known. Abacist does the second part. You record facts together with their
evidence, describe what can be done and what must stay true, and ask:

- Can this goal be reached from what is known? By which steps?
- What is the earliest tick at which several actors can reach a goal together?
- What does that answer rest on, and how solid is each fact?
- Which facts are missing, and which sources contradict each other?
- Does it still happen if one actor does nothing? What if a fact were different?

It never guesses. A field nobody recorded is *unknown*, not false. Two sources that disagree
are reported, not silently resolved. Every answer names its weakest fact.

The name comes from the abacists, who calculated on counting boards step by step, in plain
sight, so anyone could check the work.

## Install

```bash
pip install abacist          # library and the `abacist` command, no dependencies
pip install "abacist[mcp]"   # adds the MCP server `abacist-mcp` (uses the official MCP Python SDK)
```

Python 3.10 or later. Until the first release, install from a clone with `pip install -e ".[mcp]"`.
See [CHANGELOG.md](CHANGELOG.md) for changes since the initial public source version.

## A small example

```python
from abacist import build, reachable

entries = [
    {"kind": "entity", "id": "db", "type": "store"},
    {"kind": "entity", "id": "api", "type": "service"},
    {"kind": "claim", "id": "c1", "ref": "entity.db.schema", "value": 1,
     "evidence": "observed", "source": "SELECT max(version) FROM schema_migrations -> 1"},
    {"kind": "claim", "id": "c2", "ref": "entity.api.max_schema", "value": 1,
     "evidence": "reported", "source": "the api owner said so"},
    {"kind": "action", "id": "deploy_api", "effects": [["entity.api.max_schema", "set", 2]]},
    {"kind": "action", "id": "migrate", "effects": [["entity.db.schema", "set", 2]]},
    {"kind": "constraint", "id": "readable", "scope": "path",
     "when": [["entity.api.max_schema", "gte_ref", "entity.db.schema"]]},
    {"kind": "goal", "id": "migrated", "when": [["entity.db.schema", "eq", 2]]},
]

r = reachable(build(entries), "migrated")
r["answer"]                              # "yes"
[s["action"] for s in r["plan"]["steps"]]  # ["deploy_api", "migrate"]
r["basis"]                               # "depends_on_reports"
r["dependsOn"][0]["ref"]                 # "entity.api.max_schema" - the weakest fact
```

More in [`examples/`](examples): a release migration, story threads with who-knows-what, and
a decision with unknown facts.

## Answers

| answer | meaning |
|---|---|
| `yes` | a plan exists and every hard constraint on it can be evaluated |
| `yes_if_facts` | a plan exists, but facts its hard constraints need are not recorded |
| `not_within_depth` | no plan within the search depth; deeper plans were not searched |
| `no` | a definitive hard path-invariant violation at the start |
| `undetermined` | a budget cut the search short, or the search found no plan and encountered rule-order conflicts |

| basis | meaning |
|---|---|
| `observed` | every fact used was seen directly, or is a declared closed-world default |
| `depends_on_reports` | at least one fact is only reported |
| `depends_on_assumptions` | at least one fact is assumed, or an unrecorded field was read as absent (by a precondition or by a propagation rule) |
| `hypothetical` | the answer uses a what-if value |

Propagation rules fire once after every step, after that step's action. By default a rule is
a reaction and does not run on the recorded state, so an action can still come first. A rule
marked `"settle": true` is a standing derivation (it may only assign values): it already
holds in the recorded state, so it is also applied once before the first step. The planner,
the simulator and `check_constraints` all start from that same state. If a settling rule
replaces a recorded value, the answer lists it under `startOverwrites`; if a field's value
depends on the order in which settling rules run, under `startWriteConflicts`.

Rules that fire in the same round are applied in rule-id order, and a field whose value
would differ under some other order is reported as a write conflict: the answer then depends
only on rule ids, so fix the rules. Every order is covered, not a sample: rules that share no
field cannot affect each other and are checked apart, partial orders that leave the same values
are explored once, and pure additions (or pure maxima) of 4-decimal amounts from sources the
group does not change are known to give the same result in any order. If a group is too large
to check within the budget, its fields are still reported, with `"orderVerified": false`.
Values are compared as JSON values: `true` and `1` differ, `2` and `2.0` do not. A rule that
reads a field it wrote itself in an earlier effect reads its own value, which is no conflict.

Every answer carries `dependsOnRuleOrder`. When it is true, the reported result may differ
under another rule order. `ask_reachable` prefers a plan without conflicts and lists any
conflicts on the plan shown under `planWriteConflicts`, with the step, hop, actual writes
and `orderVerified`. If no plan was found, the flag still records conflicts encountered
before the search stopped, including when it ran out of budget. In strict mode a plan
with conflicts alone can still be evaluated under the current order, but it cannot prove
reachability. Missing hard-constraint facts are reported separately.
In Python's `plan()`, a plan with write conflicts and otherwise proven hard constraints
has `hardConstraintStatus` set to `unknown_rule_order`.

In `simulate`, `branchesWithWriteConflicts` counts returned branches with a conflict at
step 0 or later. The flag also covers conflicts found before a branch was merged or dropped.
In Python's `counterfactual()`, the top-level flag covers both simulations and the goal
comparison. The flag inside `goalDelta` applies to reachability only. An Agent that needs a
result independent of rule ids can use the flag to decide when to inspect the rules.

Facts that rules read and that can affect the plan, the goal or a hard constraint count
toward the basis whether or not the rule fired, and a recorded fact counts even when some
rule could overwrite it. A field nobody recorded is flagged when a rule tests it, unless
something fills it later on the path; an `exists` or `missing` test always counts. A rule
whose relation stayed inactive was never tested, so only that relation's `active` field
matters. Values the rules actually produced are listed under `derived`.

### Concurrent planning

Use the MCP tool `ask_concurrent(world, goal)` or `abacist ask-concurrent <handle> <goal>`
to find the earliest tick that a goal can be reached. Each tick lets different actors take
one action each when those actions can safely run together. Use `max_ticks` (default 6),
`max_states` (default 20,000) and `max_joint_steps` (1 to 16,384 per state, default 4,096)
to bound the search.
The CLI accepts `--max-ticks`, `--max-states` and `--max-joint-steps`.

Every action checks its `pre` against the state at the start of its tick. If a migration
requires earlier compatibility checks, put those requirements in the migration action's `pre`.
A final constraint checks the goal state. When it is the only compatibility requirement,
the check actions and the migration can share a tick.

`minTicks` is the earliest tick with a goal witness. `minProvenTicks` is the earliest tick
with a witness whose hard constraints are satisfied in their required scope and whose rules
have no write conflicts. A missing witness is `null`. The main `plan` shows the earliest
proven route if one was found, with actions grouped by tick. Otherwise it shows an earliest
conditional route when available. A faster conditional route alongside a proven one appears
under `fasterUnprovenPlan`, with `pendingHardFacts` and any `planWriteConflicts` explaining
what needs checking. `dependsOnRuleOrder` describes the main answer and is also reported for
the faster route when present. Conflicts and overwritten values at tick 0 are shared by all
routes and reported under `startWriteConflicts` and `startOverwrites` when present.

Each shown route has its own `basis` and `dependsOn` evidence. A proven route can have
`basis: "depends_on_reports"` when it relies on a reported fact. The `search` object separates
`stateBudgetTruncated` from `jointStepEnumerationTruncated`. Either sets `search.truncated`.
When truncated, tick counts apply to the witnesses found. With no witness, the answer is
`undetermined` with `reachabilityStatus: "undetermined_truncated"`.

#### Python API

`plan_concurrent()` searches by tick and reports the earliest goal witness in `minTicks`
and the earliest proven witness in `minProvenTicks`. It keeps searching for proof when an
early witness has missing hard facts or rule-order conflicts. `plans` contains the earliest
witnesses from both groups without duplicates, and `provenPlans` contains only the earliest
proven routes. A missing witness has a tick value of `None`. When a conflict-free proof is
found, `dependsOnRuleOrder` is false for reachability even if a quicker route still lists
its full conflicts under `writeConflicts`.

With `require_hard_constraints=False`, a route can meet the goal despite a known hard
violation, including at tick 0. If every returned route has a known violation, the status
is `reachable_relaxed_constraints` and `provenReachable` is false. Each plan reports
`firstInvariantViolationDepth` as the first tick that violated a hard path constraint,
or `None`. Later recovery cannot clear an earlier path violation. Final hard constraints
are checked at the goal witness.

`max_joint_steps` limits the number of legal joint steps examined per state (default 4096).
When the limit omits combinations, `jointStepEnumerationTruncated` and `truncated` are true.
When the state budget cuts the search short, `stateBudgetTruncated` and `truncated` are true.
If no goal witness was found, the planner reports `undetermined_truncated` with
`joint_step_budget_truncated`. With either search budget exhausted, reported minima apply
to the routes found.

## The ledger

A world is an ordered list of entries: `entity`, `relation`, `claim`, `closed`, `action`,
`schema`, `constraint`, `rule`, `goal`, `retract`. Each claim carries `evidence`
(`observed`, `reported`, `assumed`) and a `source`. A `closed` entry declares that a search
was complete, so missing values of that field mean a stated default rather than "unknown".

Worlds are stored as JSON-lines files. Revisions are a hash chain over the entries, so a
handle `id@revision` names exactly one state of the ledger, the same entries give the same
revision anywhere, and every answer can be recomputed later. Writes name the revision they
were based on and are refused if the world has moved on.

See [`src/abacist/world.py`](src/abacist/world.py) for the full entry format.

## MCP server

```bash
abacist-mcp --root ./worlds
```

It speaks MCP over stdio (protocol 2026-07-28, with fallback for older clients through the
SDK). The thirteen tools are `world_new`, `world_list`, `world_record`, `world_show`,
`ask_reachable`, `ask_concurrent`, `ask_without`, `ask_what_if`, `check_constraints`, `simulate`,
`job_status`, `job_cancel`, `abacist_guide`. Everything works with plain tool calls, so any
MCP client can use all of it; two MCP extensions improve it where the client supports them.

**Guides.** `abacist_guide` returns the usage guides: `abacist-basics`,
`abacist-code-changes`, `abacist-story-threads`, `abacist-decisions`. They also ship as skills
through the MCP Skills extension (`io.modelcontextprotocol/skills`), for hosts that load
skills on demand.

**Long searches.** The search tools (`ask_reachable`, `ask_concurrent`, `ask_without`, `ask_what_if`,
`simulate`) take `wait_seconds` (default 20). A search still running after that long returns
`{"job": <id>, "status": "working"}` instead of its answer and keeps running in the
background; `job_status` reports its progress and, when it has finished, the answer exactly
as the tool would have returned it; `job_cancel` stops it. `wait_seconds: 0` starts a search
in the background at once. Clients that declare the MCP Tasks extension
(`io.modelcontextprotocol/tasks`) on the call get a search that runs past two seconds
(`--task-after`) back as an MCP task instead, polled with `tasks/get`.

Jobs and tasks are kept in memory by the server process. They live an hour from creation and
end with the server: for a stdio server, when the client disconnects. A client that starts a
new server for every call (some command-line clients do, unless told to keep it running) keeps
the worlds, which are files, but loses its job ids. A cancelled or expired search stops at its
next step rather than running on in the background.

Several agents can share one server. It computes at most four searches at once
(`--max-running`); further ones wait in line and report `"status": "queued"` with their
position, and can be cancelled while they wait. When 32 are already waiting (`--max-waiting`),
a new search is refused at once with a "busy" tool error, rather than left waiting until the
client times out.

Example client configuration (adjust to your host):

```json
{"mcpServers": {"abacist": {"command": "abacist-mcp", "args": ["--root", "/path/to/worlds"]}}}
```

### Tested hosts

These counts describe the runs on 2026-11-30. Those builds listed ten or twelve tools.
The current server lists thirteen, including `ask_concurrent`.

| Host | Protocol | Tools called / listed | Guides | Long searches |
|---|---|---|---|---|
| Claude Code 2.1.332, interactive | 2026-07-28 | 4 / 10 \* | `abacist_guide`; skills listed | MCP tasks, polled by the host |
| Claude Code 2.1.332, `claude -p` | 2026-07-28 | 4 / 10 \* | `abacist_guide` | not tried |
| Codex CLI 0.172, `codex exec` | 2025-06-18 | 6 / 12 | `abacist_guide` | jobs: start, progress, cancel, result |
| DeepSeek Harness 0.2.2-rc.5, `dsh headless` | 2026-07-28 | 6 / 12 | `abacist_guide`, or the `skill://` resources | jobs: start, progress, cancel, result |
| mcporter 0.12 (no model) | 2025-11-25 | 11 / 12 | `abacist_guide` | jobs, with the server kept alive between calls |

\* Run before `job_status` and `job_cancel` existed, when the server had ten tools.

In the Claude Code, Codex and DeepSeek Harness runs, the model read the basics guide, recorded
a small migration with the right evidence kinds and sources, and reported the answer with its
weakest fact. DeepSeek Harness was run through two DeepSeek connections (its default API
model and a relay serving `deepseek-v4.1-flash`).

## Command line

For agents that can run commands but not connect to MCP servers, `abacist` offers the same
operations and prints JSON (ASCII only, so any console can read it):

```bash
abacist --root ./worlds new "release"                    # {"world": "release-...@..."}
abacist --root ./worlds record <handle> entries.json     # or "-" to read stdin
abacist --root ./worlds ask <handle> migrated
abacist --root ./worlds ask <handle> --when '[["entity.db.schema", "eq", 2]]'
abacist --root ./worlds ask-concurrent <handle> migrated --max-ticks 3 --max-joint-steps 4096
abacist --root ./worlds what-if <handle> --changes @changes.json --goals '["migrated"]'
abacist --root ./worlds check <handle>
abacist --root ./worlds simulate <handle> --horizon 3
abacist guide abacist-basics
```

Most JSON options accept literal JSON or `@file`. For `record`, choose a JSON file, `-`
(or no source argument) to read standard input, or `--entries-json` with a literal JSON list.
The [basics guide](src/abacist/skills/abacist-basics/SKILL.md#from-the-command-line) shows
single-command examples for Git Bash and PowerShell. Searches accept `--max-seconds`
to stop after a time limit. Exit status is 0 on success, 1 for a refusal (with `"error"` in
the JSON), 3 for a stopped search, or 2 for a malformed command.

### Hand off a world from MCP to the CLI

Point the MCP server and CLI at the same world directory. Give the receiving agent the
question and evidence, and pass the exact `world` field (`id@revision`) from the previous
response verbatim. Keep the full ID, including its suffix, and the full revision. An incomplete
handle is refused. If the world can be identified, the error shows its current complete handle
for reference. Retrieve the original `world` field to replay the intended revision.

The receiving agent can read `abacist guide abacist-basics` and inspect the claims with
`abacist show <handle> --section claims`. Record new evidence with
`abacist record <handle> correction.json` or `--entries-json`, then pass the write's
`world` field to the next query. A complete historical handle still reads that revision.
Use `world_list` or `abacist list` to get the current handle explicitly.

Run the [MCP-to-CLI handoff example](examples/mcp_cli_handoff.py) from a checkout with the
MCP extra installed:

```bash
python examples/mcp_cli_handoff.py
```

The script builds a temporary world over MCP stdio, updates it through the CLI, and
checks that both interfaces agree at both revisions. A failed CLI capability probe initially
blocks a modeled offline audit. A passing probe after the CLI change replaces that evidence
and makes the goal reachable in one tick. The example needs no model or API key.

## Limits

- Abacist checks consistency, not modelling. A wrongly written action gives a wrong answer
  that is consistent with it.
- Search is exhaustive within a budget. It suits a handful of actors and a few steps at a
  time; large models come back `undetermined`.
- It has no probabilities. Costs are what you give it.
- Background jobs and tasks do not survive a server restart, and never ask for input while
  they run. The command line runs each search in the foreground.

## Development

```bash
python -m unittest discover -s tests     # with PYTHONPATH=src, or after pip install -e .
```

## License

Apache License 2.0. See [LICENSE](LICENSE).
