abacist 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
abacist/__init__.py ADDED
@@ -0,0 +1,50 @@
1
+ """Abacist: a deterministic reasoning ledger for AI agents.
2
+
3
+ Record facts together with their evidence, describe what can be done, then ask what is
4
+ reachable, what is missing, and what each answer rests on. No language model is called.
5
+ """
6
+ from .core import (
7
+ Action,
8
+ Clock,
9
+ Constraint,
10
+ Entity,
11
+ Goal,
12
+ Observation,
13
+ PropagationRule,
14
+ Relation,
15
+ SearchCancelled,
16
+ StateEffect,
17
+ StatePredicate,
18
+ WorldState,
19
+ check,
20
+ counterfactual,
21
+ enumerate_actions,
22
+ explain,
23
+ plan,
24
+ propagate,
25
+ search_guard,
26
+ simulate,
27
+ )
28
+ from .concurrent import actor_threads, enumerate_joint_steps, interference, plan_concurrent, simulate_concurrent
29
+ from .knowledge import (
30
+ believes,
31
+ believes_truth,
32
+ does_not_know,
33
+ forget_effects,
34
+ knowledge_changes,
35
+ knowledge_table,
36
+ knows,
37
+ learn_effects,
38
+ lie_effects,
39
+ misbeliefs,
40
+ seed_knowledge,
41
+ tell_effects,
42
+ tell_schema,
43
+ who_knows,
44
+ )
45
+ from .queries import basis_of, check_now, missing_facts, reachable, simulate_summary, what_if, without_actor
46
+ from .schemas import ActionSchema, ParamDomain, ground_all, ground_schema
47
+ from .store import StaleRevision, Store, UnknownWorld, parse_handle
48
+ from .world import Built, WorldError, build, revisions, validate_entries
49
+
50
+ __version__ = "0.1.0"
abacist/_mcp_cli.py ADDED
@@ -0,0 +1,12 @@
1
+ """Launch Abacist's optional MCP server."""
2
+ from __future__ import annotations
3
+
4
+
5
+ def main(argv: list[str] | None = None) -> None:
6
+ try:
7
+ from .mcp_server import main as serve
8
+ except ModuleNotFoundError as exc:
9
+ if exc.name not in {"mcp", "mcp_types"}:
10
+ raise
11
+ raise SystemExit('MCP support is not installed. Run pip install "abacist[mcp]"') from None
12
+ serve(argv)
abacist/cli.py ADDED
@@ -0,0 +1,185 @@
1
+ """`abacist`: the same operations as the MCP tools, from the command line, with JSON output.
2
+
3
+ For agents that can run commands but cannot connect to an MCP server. Every command prints one
4
+ JSON object (or, for `guide`, the guide text) on standard output:
5
+
6
+ abacist new "release" -> {"world": "release-1a2b3c@..."}
7
+ abacist record <handle> entries.json (or "-" to read the entries from stdin)
8
+ abacist record <handle> --entries-json '[...]'
9
+ abacist ask <handle> migrated
10
+ abacist ask <handle> --when '[["entity.db.schema", "eq", 2]]'
11
+ abacist ask-concurrent <handle> migrated --max-ticks 3
12
+ abacist what-if <handle> --changes @changes.json --goals '["migrated"]'
13
+
14
+ Most JSON options accept literal JSON or "@file". --entries-json takes a literal JSON list.
15
+ The exit status is 0 on success, 1 when the request is refused (the JSON has "error"),
16
+ 3 when --max-seconds stops a search (the JSON has "error" and "stopped" set to true),
17
+ or 2 for a malformed command line.
18
+ """
19
+ from __future__ import annotations
20
+
21
+ import argparse
22
+ import json
23
+ import sys
24
+ import time
25
+ from pathlib import Path
26
+ from typing import Any
27
+
28
+ from . import __version__
29
+ from .core import SearchCancelled, search_guard
30
+ from .service import MAX_JOINT_STEPS, Service, UsageError
31
+ from .store import Store
32
+
33
+
34
+ def _json_arg(text: str, what: str, *, allow_file: bool = True) -> Any:
35
+ if allow_file and text.startswith("@"):
36
+ try:
37
+ text = Path(text[1:]).read_text(encoding="utf-8")
38
+ except OSError as exc:
39
+ raise UsageError(f"{what}: cannot read {text[1:]!r}: {exc.strerror}") from exc
40
+ try:
41
+ return json.loads(text)
42
+ except json.JSONDecodeError as exc:
43
+ raise UsageError(f"{what}: not valid JSON ({exc.msg} at line {exc.lineno} column {exc.colno})") from exc
44
+
45
+
46
+ def _goal(args: argparse.Namespace) -> str | dict[str, Any]:
47
+ if (args.goal is None) == (args.when is None):
48
+ raise UsageError("give either a goal id or --when (not both)")
49
+ return args.goal if args.goal is not None else {"when": _json_arg(args.when, "--when")}
50
+
51
+
52
+ def _deadline(seconds: float | None) -> Any:
53
+ if seconds is None:
54
+ return lambda n: None
55
+ end = time.monotonic() + seconds
56
+
57
+ def guard(n: int) -> None:
58
+ if time.monotonic() > end:
59
+ raise SearchCancelled(f"stopped after {seconds:g} s (--max-seconds)")
60
+ return guard
61
+
62
+
63
+ def _parser() -> argparse.ArgumentParser:
64
+ p = argparse.ArgumentParser(prog="abacist", description=__doc__.split("\n\n")[0],
65
+ formatter_class=argparse.RawDescriptionHelpFormatter)
66
+ p.add_argument("--root", help="directory holding world files (default: $ABACIST_HOME or ~/.abacist/worlds)")
67
+ p.add_argument("--version", action="version", version=f"abacist {__version__}")
68
+ sub = p.add_subparsers(dest="command", required=True, metavar="command")
69
+
70
+ sub.add_parser("list", help="list worlds with their current handles")
71
+ s = sub.add_parser("new", help="create an empty world")
72
+ s.add_argument("title")
73
+ s = sub.add_parser("record", help="append entries (a JSON list) to a world")
74
+ s.add_argument("world", help="handle '<id>@<revision>' you last received")
75
+ entry_source = s.add_mutually_exclusive_group()
76
+ entry_source.add_argument("entries", nargs="?", help="JSON file with the entries, or '-' for stdin (default)")
77
+ entry_source.add_argument("--entries-json", help="JSON list of entries supplied directly")
78
+ s = sub.add_parser("show", help="show a world")
79
+ s.add_argument("world")
80
+ s.add_argument("--section", default="summary", choices=["summary", "claims", "entries"])
81
+ s.add_argument("--prefix", default="", help="with --section claims: only refs starting with this")
82
+
83
+ def search_opts(s: argparse.ArgumentParser, goal: bool = True, *, depth_arg: str = "--max-depth") -> None:
84
+ if goal:
85
+ s.add_argument("goal", nargs="?", help="goal id (or use --when)")
86
+ s.add_argument("--when", help="ad-hoc goal: JSON list of [ref, op, value], or @file")
87
+ s.add_argument(depth_arg, type=int, default=6)
88
+ s.add_argument("--max-states", type=int, default=20_000)
89
+ s.add_argument("--max-seconds", type=float, help="stop the search after this many seconds")
90
+
91
+ s = sub.add_parser("ask", help="can a goal be reached, how, and on what evidence")
92
+ s.add_argument("world")
93
+ search_opts(s)
94
+ s.add_argument("--require-proven", action="store_true")
95
+ s.add_argument("--without", nargs="*", default=[], metavar="ACTOR", help="leave these actors out")
96
+ s = sub.add_parser("ask-concurrent", help="find the earliest goal and proven plans with simultaneous actions")
97
+ s.add_argument("world")
98
+ search_opts(s, depth_arg="--max-ticks")
99
+ s.add_argument("--max-joint-steps", type=int, default=4096,
100
+ help=f"limit legal combinations per state (1 to {MAX_JOINT_STEPS:,})")
101
+ s.add_argument("--without", nargs="*", default=[], metavar="ACTOR", help="leave these actors out")
102
+ s = sub.add_parser("without", help="does the goal still happen if one actor does nothing")
103
+ s.add_argument("world")
104
+ s.add_argument("actor")
105
+ search_opts(s)
106
+ s = sub.add_parser("what-if", help="re-answer goals with some fields changed (nothing is recorded)")
107
+ s.add_argument("world")
108
+ s.add_argument("--changes", required=True, help="JSON list of {ref, value}, or @file")
109
+ s.add_argument("--goals", required=True, help="JSON list of goal ids or {when: ...}, or @file")
110
+ search_opts(s, goal=False)
111
+ s = sub.add_parser("check", help="which constraints hold now")
112
+ s.add_argument("world")
113
+ s = sub.add_parser("simulate", help="run every course of events for a few steps")
114
+ s.add_argument("world")
115
+ s.add_argument("--horizon", type=int, default=3)
116
+ s.add_argument("--concurrent", action="store_true")
117
+ s.add_argument("--goals", help="JSON list of goal ids or {when: ...}, or @file (default: all goals)")
118
+ s.add_argument("--max-branches", type=int, default=2048)
119
+ s.add_argument("--without", nargs="*", default=[], metavar="ACTOR")
120
+ s.add_argument("--max-seconds", type=float, help="stop the run after this many seconds")
121
+ s = sub.add_parser("guide", help="print a usage guide ('index' lists them)")
122
+ s.add_argument("topic", nargs="?", default="index")
123
+ return p
124
+
125
+
126
+ def run(args: argparse.Namespace, svc: Service) -> Any:
127
+ c = args.command
128
+ if c == "list":
129
+ return svc.world_list()
130
+ if c == "new":
131
+ return svc.world_new(args.title)
132
+ if c == "record":
133
+ if args.entries_json is not None:
134
+ entries = _json_arg(args.entries_json, "--entries-json", allow_file=False)
135
+ elif args.entries in (None, "-"):
136
+ entries = _json_arg(sys.stdin.read(), "entries", allow_file=False)
137
+ else:
138
+ entries = _json_arg("@" + args.entries, "entries")
139
+ return svc.world_record(args.world, entries)
140
+ if c == "show":
141
+ return svc.world_show(args.world, args.section, args.prefix)
142
+ if c == "check":
143
+ return svc.check_constraints(args.world)
144
+ if c == "guide":
145
+ return svc.guide(args.topic)
146
+ with search_guard(_deadline(args.max_seconds)):
147
+ if c == "ask":
148
+ return svc.ask_reachable(args.world, _goal(args), args.max_depth, args.max_states,
149
+ args.require_proven, args.without)
150
+ if c == "ask-concurrent":
151
+ return svc.ask_concurrent(args.world, _goal(args), args.max_ticks, args.max_states,
152
+ args.max_joint_steps, args.without)
153
+ if c == "without":
154
+ return svc.ask_without(args.world, _goal(args), args.actor, args.max_depth, args.max_states)
155
+ if c == "what-if":
156
+ return svc.ask_what_if(args.world, _json_arg(args.changes, "--changes"), _json_arg(args.goals, "--goals"),
157
+ args.max_depth, args.max_states)
158
+ if c == "simulate":
159
+ goals = _json_arg(args.goals, "--goals") if args.goals is not None else None
160
+ return svc.simulate(args.world, args.horizon, args.concurrent, args.without, args.max_branches, goals)
161
+ raise UsageError(f"unknown command {c!r}")
162
+
163
+
164
+ def _emit(obj: Any) -> None:
165
+ # ASCII-only JSON: readable by any program on any console code page.
166
+ sys.stdout.write(obj if isinstance(obj, str) else json.dumps(obj, indent=2))
167
+ sys.stdout.write("\n")
168
+ sys.stdout.flush()
169
+
170
+
171
+ def main(argv: list[str] | None = None) -> int:
172
+ args = _parser().parse_args(argv)
173
+ try:
174
+ _emit(run(args, Service(Store(args.root))))
175
+ return 0
176
+ except SearchCancelled as exc:
177
+ _emit({"error": f"search stopped: {exc}", "stopped": True})
178
+ return 3
179
+ except UsageError as exc:
180
+ _emit({"error": str(exc)})
181
+ return 1
182
+
183
+
184
+ if __name__ == "__main__":
185
+ sys.exit(main())