canon-cli 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.
- canon/__init__.py +3 -0
- canon/__main__.py +6 -0
- canon/activate.py +143 -0
- canon/audit.py +418 -0
- canon/brief.py +235 -0
- canon/cli.py +1143 -0
- canon/gitx.py +263 -0
- canon/ledger.py +418 -0
- canon/mcp.py +337 -0
- canon/prompt.py +45 -0
- canon/scope.py +589 -0
- canon/select.py +173 -0
- canon/verify.py +399 -0
- canon_cli-0.1.0.dist-info/METADATA +360 -0
- canon_cli-0.1.0.dist-info/RECORD +19 -0
- canon_cli-0.1.0.dist-info/WHEEL +5 -0
- canon_cli-0.1.0.dist-info/entry_points.txt +2 -0
- canon_cli-0.1.0.dist-info/licenses/LICENSE +21 -0
- canon_cli-0.1.0.dist-info/top_level.txt +1 -0
canon/mcp.py
ADDED
|
@@ -0,0 +1,337 @@
|
|
|
1
|
+
"""MCP server: canon spoken as a protocol.
|
|
2
|
+
|
|
3
|
+
Why this exists
|
|
4
|
+
---------------
|
|
5
|
+
A CLI is only used if the agent thinks to use it. In an MCP-capable harness the
|
|
6
|
+
server's tools are placed in the model's tool list on *every* turn, and the
|
|
7
|
+
handshake carries an `instructions` string the client is expected to surface.
|
|
8
|
+
Both live in the protocol, not in one vendor's configuration format, which makes
|
|
9
|
+
this the closest thing to a harness-agnostic injection channel that exists.
|
|
10
|
+
|
|
11
|
+
Two honest caveats, because they matter:
|
|
12
|
+
|
|
13
|
+
* `instructions` is advisory. Clients may ignore it, truncate it, or drop it.
|
|
14
|
+
* A tool can be offered and still not be called.
|
|
15
|
+
|
|
16
|
+
So this layer raises the probability a lot and guarantees nothing. The layer
|
|
17
|
+
that guarantees something is the commit gate (`canon hook install`), because
|
|
18
|
+
agents must go through git. Use both.
|
|
19
|
+
|
|
20
|
+
Run: canon mcp (stdio; the client supplies the project as cwd)
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
from __future__ import annotations
|
|
24
|
+
|
|
25
|
+
import json
|
|
26
|
+
import sys
|
|
27
|
+
from pathlib import Path
|
|
28
|
+
from typing import Any
|
|
29
|
+
|
|
30
|
+
from . import __version__
|
|
31
|
+
from . import brief as B
|
|
32
|
+
from .audit import debt
|
|
33
|
+
from .gitx import footprint, is_repo, repo_root, tracked_files
|
|
34
|
+
from .ledger import Ledger, LedgerError
|
|
35
|
+
from .scope import compile_pattern
|
|
36
|
+
from .select import applicable, jurisdiction
|
|
37
|
+
from .verify import aggregate, run as run_check
|
|
38
|
+
|
|
39
|
+
PROTOCOL = "2024-11-05"
|
|
40
|
+
|
|
41
|
+
TOOLS: list[dict] = [
|
|
42
|
+
{
|
|
43
|
+
"name": "canon_brief",
|
|
44
|
+
"description": (
|
|
45
|
+
"Call this FIRST, before your first edit in this repository. Returns the "
|
|
46
|
+
"rules that govern the change you are about to make, compiled from the "
|
|
47
|
+
"repository's rulebook and scoped to the current diff. HARD rules are "
|
|
48
|
+
"binding: if canon_check fails one, the change is invalid and must be "
|
|
49
|
+
"fixed rather than waived."
|
|
50
|
+
),
|
|
51
|
+
"inputSchema": {
|
|
52
|
+
"type": "object",
|
|
53
|
+
"properties": {
|
|
54
|
+
"task": {
|
|
55
|
+
"type": "string",
|
|
56
|
+
"description": "The task you were given, in your own words.",
|
|
57
|
+
}
|
|
58
|
+
},
|
|
59
|
+
"additionalProperties": False,
|
|
60
|
+
},
|
|
61
|
+
},
|
|
62
|
+
{
|
|
63
|
+
"name": "canon_check",
|
|
64
|
+
"description": (
|
|
65
|
+
"Prove that the current change satisfies the rulebook. Call this before "
|
|
66
|
+
"you commit. Returns a verdict per applicable rule: PASS, FAIL, UNKNOWN "
|
|
67
|
+
"(declared but not mechanically checkable) or WAIVED. `isError` is true "
|
|
68
|
+
"when a hard rule fails; when it is, fix the change — never edit the rule, "
|
|
69
|
+
"never bypass with --no-verify."
|
|
70
|
+
),
|
|
71
|
+
"inputSchema": {"type": "object", "properties": {}, "additionalProperties": False},
|
|
72
|
+
},
|
|
73
|
+
{
|
|
74
|
+
"name": "canon_remember",
|
|
75
|
+
"description": (
|
|
76
|
+
"Record ONE durable, non-obvious fact you learned about this repository "
|
|
77
|
+
"(a surprising module, a deploy constraint, a command that must be used). "
|
|
78
|
+
"It is stored as UNREVIEWED until a human confirms it, and it is shown to "
|
|
79
|
+
"teammates marked as provisional. Do not record what a brief already says."
|
|
80
|
+
),
|
|
81
|
+
"inputSchema": {
|
|
82
|
+
"type": "object",
|
|
83
|
+
"properties": {
|
|
84
|
+
"text": {"type": "string", "description": "One sentence, max 400 chars."},
|
|
85
|
+
"scope": {
|
|
86
|
+
"type": "string",
|
|
87
|
+
"description": "Optional path glob this is about, e.g. 'services/api/**'.",
|
|
88
|
+
},
|
|
89
|
+
},
|
|
90
|
+
"required": ["text"],
|
|
91
|
+
"additionalProperties": False,
|
|
92
|
+
},
|
|
93
|
+
},
|
|
94
|
+
{
|
|
95
|
+
"name": "canon_explain",
|
|
96
|
+
"description": "Explain one rule: its text, rationale, scope, predicate and history.",
|
|
97
|
+
"inputSchema": {
|
|
98
|
+
"type": "object",
|
|
99
|
+
"properties": {"id": {"type": "string", "description": "e.g. R4k9x2"}},
|
|
100
|
+
"required": ["id"],
|
|
101
|
+
"additionalProperties": False,
|
|
102
|
+
},
|
|
103
|
+
},
|
|
104
|
+
{
|
|
105
|
+
"name": "canon_status",
|
|
106
|
+
"description": (
|
|
107
|
+
"Cheap orientation: how many rules are in force, how many hard rules have "
|
|
108
|
+
"no mechanical check (normative debt), and the rulebook snapshot id."
|
|
109
|
+
),
|
|
110
|
+
"inputSchema": {"type": "object", "properties": {}, "additionalProperties": False},
|
|
111
|
+
},
|
|
112
|
+
]
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
class Ctx:
|
|
116
|
+
def __init__(self, repo: Path) -> None:
|
|
117
|
+
self.repo = repo
|
|
118
|
+
self._ledger: Ledger | None = None
|
|
119
|
+
|
|
120
|
+
@property
|
|
121
|
+
def ledger(self) -> Ledger:
|
|
122
|
+
if self._ledger is None:
|
|
123
|
+
self._ledger = Ledger.open(self.repo / ".canon" / "ledger.jsonl")
|
|
124
|
+
return self._ledger
|
|
125
|
+
|
|
126
|
+
@property
|
|
127
|
+
def has_rules(self) -> bool:
|
|
128
|
+
return (self.repo / ".canon" / "ledger.jsonl").exists()
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def _text(payload: str, *, is_error: bool = False) -> dict:
|
|
132
|
+
return {"content": [{"type": "text", "text": payload}], "isError": is_error}
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def _instructions(ctx: Ctx) -> str:
|
|
136
|
+
head = (
|
|
137
|
+
"canon governs this repository's rules. They are a database, not a document: "
|
|
138
|
+
"call canon_brief BEFORE your first edit and canon_check BEFORE you commit. "
|
|
139
|
+
"A HARD rule that fails canon_check makes the change invalid."
|
|
140
|
+
)
|
|
141
|
+
if not ctx.has_rules:
|
|
142
|
+
return (
|
|
143
|
+
head
|
|
144
|
+
+ " No rulebook exists here yet; the user can create one with `canon init`."
|
|
145
|
+
)
|
|
146
|
+
try:
|
|
147
|
+
led = ctx.ledger
|
|
148
|
+
js = [j for j in led.active("rule")]
|
|
149
|
+
d = debt(led)
|
|
150
|
+
hard = [j for j in js if j.sev == "hard"]
|
|
151
|
+
lines = [
|
|
152
|
+
head,
|
|
153
|
+
f"In force now: {len(js)} rule(s), {len(hard)} hard. "
|
|
154
|
+
f"Normative debt: {d['unproven']}/{d['hard']} hard rule(s) have no mechanical check.",
|
|
155
|
+
]
|
|
156
|
+
if hard:
|
|
157
|
+
lines.append("Hard rules (binding):")
|
|
158
|
+
budget = 1600
|
|
159
|
+
for rec in hard:
|
|
160
|
+
line = f"- {rec.id}: {rec.text}"
|
|
161
|
+
if len(line) > budget:
|
|
162
|
+
lines.append("- … (brief carries the rest)")
|
|
163
|
+
break
|
|
164
|
+
budget -= len(line)
|
|
165
|
+
lines.append(line)
|
|
166
|
+
return "\n".join(lines)[:4000]
|
|
167
|
+
except (LedgerError, OSError) as exc: # never fail a handshake over a bad ledger
|
|
168
|
+
return head + f" (The rulebook could not be read: {exc})"
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def handle(msg: dict, ctx: Ctx) -> dict | None:
|
|
172
|
+
"""One JSON-RPC message in, one response out (None for notifications)."""
|
|
173
|
+
method = msg.get("method")
|
|
174
|
+
msg_id = msg.get("id")
|
|
175
|
+
params = msg.get("params") or {}
|
|
176
|
+
|
|
177
|
+
def ok(result: Any) -> dict:
|
|
178
|
+
return {"jsonrpc": "2.0", "id": msg_id, "result": result}
|
|
179
|
+
|
|
180
|
+
def err(code: int, message: str) -> dict:
|
|
181
|
+
return {"jsonrpc": "2.0", "id": msg_id, "error": {"code": code, "message": message}}
|
|
182
|
+
|
|
183
|
+
if msg_id is None:
|
|
184
|
+
return None # notification
|
|
185
|
+
|
|
186
|
+
if method == "initialize":
|
|
187
|
+
return ok(
|
|
188
|
+
{
|
|
189
|
+
"protocolVersion": params.get("protocolVersion") or PROTOCOL,
|
|
190
|
+
"capabilities": {"tools": {"listChanged": False}},
|
|
191
|
+
"serverInfo": {"name": "canon", "version": __version__},
|
|
192
|
+
"instructions": _instructions(ctx),
|
|
193
|
+
}
|
|
194
|
+
)
|
|
195
|
+
if method == "ping":
|
|
196
|
+
return ok({})
|
|
197
|
+
if method == "tools/list":
|
|
198
|
+
return ok({"tools": TOOLS})
|
|
199
|
+
if method == "resources/list":
|
|
200
|
+
return ok({"resources": []})
|
|
201
|
+
if method == "prompts/list":
|
|
202
|
+
return ok({"prompts": []})
|
|
203
|
+
if method == "tools/call":
|
|
204
|
+
name = str(params.get("name", ""))
|
|
205
|
+
args = params.get("arguments") or {}
|
|
206
|
+
try:
|
|
207
|
+
return ok(_call(name, args, ctx))
|
|
208
|
+
except KeyError:
|
|
209
|
+
return err(-32602, f"unknown tool: {name}")
|
|
210
|
+
except (LedgerError, OSError) as exc:
|
|
211
|
+
return ok(_text(f"canon: {exc}", is_error=True))
|
|
212
|
+
return err(-32601, f"method not found: {method}")
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def _call(name: str, args: dict, ctx: Ctx) -> dict:
|
|
216
|
+
if name == "canon_brief":
|
|
217
|
+
fp = footprint(ctx.repo)
|
|
218
|
+
kept, omitted, entries, orientation = B.compile_for(
|
|
219
|
+
ctx.ledger, fp, max_tokens=1500
|
|
220
|
+
)
|
|
221
|
+
out = B.render(
|
|
222
|
+
kept,
|
|
223
|
+
omitted,
|
|
224
|
+
fp,
|
|
225
|
+
ctx.ledger.snapshot(),
|
|
226
|
+
task=str(args.get("task", "")),
|
|
227
|
+
orientation=orientation,
|
|
228
|
+
map_entries=entries,
|
|
229
|
+
)
|
|
230
|
+
return _text(out.text)
|
|
231
|
+
|
|
232
|
+
if name == "canon_check":
|
|
233
|
+
fp = footprint(ctx.repo)
|
|
234
|
+
js = applicable(ctx.ledger, fp, kinds=("rule",))
|
|
235
|
+
results = [run_check(j, fp, ctx.repo, ledger=ctx.ledger) for j in js]
|
|
236
|
+
outcome = aggregate(results, strict=False)
|
|
237
|
+
if not results:
|
|
238
|
+
return _text(f"canon check: nothing governs this change ({fp.summary()}).")
|
|
239
|
+
lines: list[str] = []
|
|
240
|
+
for r in outcome.failures:
|
|
241
|
+
lines.append(f"FAIL {r.id} [{r.sev}] {r.jurisdiction.rec.text}")
|
|
242
|
+
if r.jurisdiction.rec.why:
|
|
243
|
+
lines.append(f" why: {r.jurisdiction.rec.why}")
|
|
244
|
+
lines.append(f" check: {r.evidence.detail}")
|
|
245
|
+
for raw in r.evidence.out.strip().splitlines()[-6:]:
|
|
246
|
+
lines.append(f" | {raw}")
|
|
247
|
+
for r in outcome.unknowns:
|
|
248
|
+
lines.append(f"UNKNOWN {r.id}: no mechanical check (declared, not proven)")
|
|
249
|
+
lines.append(f"canon check: {outcome.summary()} (snapshot {ctx.ledger.snapshot()})")
|
|
250
|
+
if outcome.failures:
|
|
251
|
+
lines.append("The change is invalid. Fix it; do not edit the rule.")
|
|
252
|
+
return _text("\n".join(lines), is_error=not outcome.ok)
|
|
253
|
+
|
|
254
|
+
if name == "canon_remember":
|
|
255
|
+
text = str(args.get("text", "")).strip()
|
|
256
|
+
if not text:
|
|
257
|
+
return _text("canon: text is required", is_error=True)
|
|
258
|
+
scope: dict = {"paths": [], "ops": ["write", "delete", "commit"]}
|
|
259
|
+
if args.get("scope"):
|
|
260
|
+
scope = {"paths": [str(args["scope"])], "ops": ["write", "delete", "commit"]}
|
|
261
|
+
rec = ctx.ledger.append(
|
|
262
|
+
{
|
|
263
|
+
"v": 1,
|
|
264
|
+
"id": ctx.ledger.next_id("F"),
|
|
265
|
+
"kind": "fact",
|
|
266
|
+
"sev": "advice",
|
|
267
|
+
"text": text[:400],
|
|
268
|
+
"why": "recorded by an agent while working in this repository",
|
|
269
|
+
"scope": scope,
|
|
270
|
+
"reviewed": False,
|
|
271
|
+
}
|
|
272
|
+
)
|
|
273
|
+
return _text(
|
|
274
|
+
f"{rec.id} remembered (unreviewed). A teammate confirms it with "
|
|
275
|
+
f"`canon review {rec.id}`."
|
|
276
|
+
)
|
|
277
|
+
|
|
278
|
+
if name == "canon_explain":
|
|
279
|
+
rid = str(args.get("id", ""))
|
|
280
|
+
rec = ctx.ledger.get(rid)
|
|
281
|
+
if rec is None:
|
|
282
|
+
return _text(f"canon: no rule {rid}", is_error=True)
|
|
283
|
+
scope = jurisdiction(rec)
|
|
284
|
+
lines = [f"{rec.id} [{rec.sev}] rev {rec.rev} {rec.status}", rec.text]
|
|
285
|
+
if rec.why:
|
|
286
|
+
lines.append(f"why: {rec.why}")
|
|
287
|
+
lines.append(f"when: {scope.describe()}")
|
|
288
|
+
check = rec.get("check")
|
|
289
|
+
lines.append(f"check: {check if check else 'none — can only ever be UNKNOWN'}")
|
|
290
|
+
if rec.get("author"):
|
|
291
|
+
lines.append(f"by: {rec.get('author')} {rec.get('ts', '')}")
|
|
292
|
+
if rec.prior:
|
|
293
|
+
lines.append(f"prior revisions: {len(rec.prior)} (see `canon history {rec.id}`)")
|
|
294
|
+
return _text("\n".join(lines))
|
|
295
|
+
|
|
296
|
+
if name == "canon_status":
|
|
297
|
+
led = ctx.ledger
|
|
298
|
+
d = debt(led)
|
|
299
|
+
files = tracked_files(ctx.repo)
|
|
300
|
+
return _text(
|
|
301
|
+
f"snapshot {led.snapshot()}\n"
|
|
302
|
+
f"rules {len(led.active('rule'))} · facts {len(led.active('fact'))} · "
|
|
303
|
+
f"tracked files {len(files)}\n"
|
|
304
|
+
f"normative debt {d['unproven']}/{d['hard']} hard rules unproven ({d['ratio']}%)"
|
|
305
|
+
)
|
|
306
|
+
|
|
307
|
+
raise KeyError(name)
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
def serve(repo: Path | None = None) -> int:
|
|
311
|
+
"""stdio transport: one JSON-RPC message per line, nothing else on stdout."""
|
|
312
|
+
target = repo or Path.cwd()
|
|
313
|
+
if not is_repo(target):
|
|
314
|
+
sys.stderr.write("canon mcp: not a git repository; starting without a rulebook\n")
|
|
315
|
+
ctx = Ctx(target)
|
|
316
|
+
else:
|
|
317
|
+
ctx = Ctx(repo_root(target))
|
|
318
|
+
|
|
319
|
+
out = sys.stdout
|
|
320
|
+
for line in sys.stdin:
|
|
321
|
+
line = line.strip()
|
|
322
|
+
if not line:
|
|
323
|
+
continue
|
|
324
|
+
try:
|
|
325
|
+
msg = json.loads(line)
|
|
326
|
+
except json.JSONDecodeError:
|
|
327
|
+
out.write(json.dumps({"jsonrpc": "2.0", "id": None,
|
|
328
|
+
"error": {"code": -32700, "message": "parse error"}}) + "\n")
|
|
329
|
+
out.flush()
|
|
330
|
+
continue
|
|
331
|
+
if not isinstance(msg, dict):
|
|
332
|
+
continue
|
|
333
|
+
response = handle(msg, ctx)
|
|
334
|
+
if response is not None:
|
|
335
|
+
out.write(json.dumps(response, separators=(",", ":")) + "\n")
|
|
336
|
+
out.flush()
|
|
337
|
+
return 0
|
canon/prompt.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
"""The bootstrap block. This is the entire harness integration.
|
|
2
|
+
|
|
3
|
+
Everything else is a CLI. That is a deliberate constraint: an agent with a shell
|
|
4
|
+
can use canon, which means every harness — and every harness that will exist
|
|
5
|
+
next year — supports it on day one, with no plugin, protocol or vendor
|
|
6
|
+
cooperation. The block is generated, small, and the one string in the system
|
|
7
|
+
that is not derived from the ledger (because it has to be readable *before* the
|
|
8
|
+
tool is invoked).
|
|
9
|
+
|
|
10
|
+
Budget: under 160 words. Every extra word here is paid on every session.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
BLOCK = """\
|
|
16
|
+
## Rules
|
|
17
|
+
|
|
18
|
+
This repository's rules are a database in `.canon/ledger.jsonl`, read with `canon`.
|
|
19
|
+
|
|
20
|
+
- Before your first edit: `canon brief --task "<the task you were given>"`
|
|
21
|
+
- Before you commit: `canon check`
|
|
22
|
+
- If `canon_brief` / `canon_check` appear as tools, use those instead.
|
|
23
|
+
|
|
24
|
+
Every line `canon brief` prints is binding. A HARD rule that fails makes the
|
|
25
|
+
change invalid: fix the change, never the rule. If `canon` is not installed,
|
|
26
|
+
use `python3 -m canon`. For a rule's reason: `canon explain <id>`.
|
|
27
|
+
To keep a durable rule: `canon add "<one sentence>" --scope '<glob>' --why "<why>"`.
|
|
28
|
+
When you learn something non-obvious: `canon remember "<one sentence>"`.
|
|
29
|
+
|
|
30
|
+
Never edit `.canon/ledger.jsonl` by hand, and never bypass the check.
|
|
31
|
+
"""
|
|
32
|
+
|
|
33
|
+
FALLBACK = BLOCK
|
|
34
|
+
|
|
35
|
+
DISCOVERY_NOTE = """\
|
|
36
|
+
<!-- canon: generated integration block. Do not edit; run `canon render` to update. -->
|
|
37
|
+
"""
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def block() -> str:
|
|
41
|
+
return BLOCK
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def with_marker() -> str:
|
|
45
|
+
return BLOCK + "\n" + DISCOVERY_NOTE
|