keelspec 0.7.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.
keelspec/__init__.py ADDED
@@ -0,0 +1,92 @@
1
+ """KeelSpec — the rubric, the gate, and the line that builds against them.
2
+
3
+ Declare your typed product artifacts (features, decisions, terms, rules, whatever
4
+ your project needs) in a ``product.config.yaml``; KeelSpec loads them, enforces the
5
+ schema + cross-references, compiles a JSON bundle, and fails CI if the committed
6
+ bundle drifts — turning a folder of hopeful markdown into code.
7
+
8
+ Three surfaces, in increasing order of ambition:
9
+
10
+ * ``build`` / ``validate`` — the compiler and the gate. Deterministic, two
11
+ dependencies, no network. This is what CI runs.
12
+ * ``evidence`` — a content-addressed record of what was checked, when, on which
13
+ commit, and with what result.
14
+ * ``index`` / ``lsp`` / ``mcp`` — the same validated graph, answered for an editor
15
+ and for an agent. Both delegate every verdict to ``validate``: there is one judge.
16
+ * ``orchestration`` — the agent-built lifecycle: Understand → Disambiguate (a
17
+ human gate) → Design → Develop → Test → adversarial Verify, with bounded repair.
18
+ Needs ``keelspec[agents]``; nothing else does.
19
+
20
+ The gate is never an agent. A judge that could be persuaded could not produce
21
+ evidence, so every station past it is deterministic or human by construction.
22
+ """
23
+ from __future__ import annotations
24
+
25
+ from .config import ArtifactType, Config, Reference, load_config
26
+ from .diagnostics import CODES, Diagnostic, Report, register
27
+ from .engine import build, load, render_bundle, validate
28
+ from .evidence import build_record
29
+ from .evidence import render as render_evidence
30
+ from .evidence import verify as verify_evidence
31
+ from .index import Artifact, Edge, Location, ProductIndex
32
+ from .orchestration import (
33
+ CLEAN_SCHEMA,
34
+ LENSES,
35
+ ROSTER,
36
+ Orchestrator,
37
+ Runner,
38
+ RunReport,
39
+ Station,
40
+ StubRunner,
41
+ Verdict,
42
+ read_resolutions,
43
+ save_report,
44
+ write_questions,
45
+ )
46
+ from .plugin import Registry, load_plugin
47
+
48
+ __version__ = "0.7.0"
49
+
50
+ __all__ = [
51
+ # the agent-built lifecycle
52
+ "CLEAN_SCHEMA",
53
+ # diagnostics
54
+ "CODES",
55
+ "LENSES",
56
+ "ROSTER",
57
+ # the resolved graph, with positions
58
+ "Artifact",
59
+ # config
60
+ "ArtifactType",
61
+ "Config",
62
+ "Diagnostic",
63
+ "Edge",
64
+ "Location",
65
+ "Orchestrator",
66
+ "ProductIndex",
67
+ "Reference",
68
+ # plugins
69
+ "Registry",
70
+ "Report",
71
+ "RunReport",
72
+ "Runner",
73
+ "Station",
74
+ "StubRunner",
75
+ "Verdict",
76
+ "__version__",
77
+ # engine
78
+ "build",
79
+ # evidence
80
+ "build_record",
81
+ "load",
82
+ "load_config",
83
+ "load_plugin",
84
+ "read_resolutions",
85
+ "register",
86
+ "render_bundle",
87
+ "render_evidence",
88
+ "save_report",
89
+ "validate",
90
+ "verify_evidence",
91
+ "write_questions",
92
+ ]
keelspec/cli.py ADDED
@@ -0,0 +1,239 @@
1
+ """The ``keelspec`` command line: build | validate.
2
+
3
+ keelspec build # regenerate the JSON bundle
4
+ keelspec validate # schema + graph + staleness (CI gate)
5
+ keelspec validate --watch # the same gate, on every save
6
+ keelspec evidence -o build/ev.json # content-addressed audit record
7
+ keelspec lsp # language server, on stdio
8
+ keelspec mcp # the graph as tools, for an agent
9
+ keelspec -c product.config.yaml -p product_hooks.py validate
10
+
11
+ Exit code is non-zero iff validation found errors — wire ``keelspec validate`` into CI.
12
+ """
13
+ from __future__ import annotations
14
+
15
+ import argparse
16
+ import json
17
+ import pathlib
18
+ import sys
19
+
20
+ from . import engine, evidence, orchestration
21
+ from .config import load_config
22
+ from .plugin import load_plugin
23
+
24
+
25
+ def _build_parser() -> argparse.ArgumentParser:
26
+ p = argparse.ArgumentParser(prog="keelspec", description="Product-as-code as a validated graph.")
27
+ p.add_argument("-c", "--config", default="product.config.yaml", help="path to product.config.yaml")
28
+ p.add_argument("-C", "--root", default=".", help="project root (paths are resolved from here)")
29
+ p.add_argument("-p", "--plugin", default=None, help="project plugin module or .py file")
30
+ sub = p.add_subparsers(dest="cmd", required=True)
31
+ sub.add_parser("build", help="regenerate the committed JSON bundle(s)")
32
+ val = sub.add_parser("validate", help="schema + graph + staleness checks (CI gate)")
33
+ val.add_argument("--json", action="store_true", dest="as_json",
34
+ help="emit findings as JSON — codes are an API, so make them parseable")
35
+ val.add_argument("--watch", action="store_true",
36
+ help="re-validate on every change until interrupted (not a gate)")
37
+ ev = sub.add_parser(
38
+ "evidence",
39
+ help="emit a content-addressed record of what was checked, when, and on what",
40
+ )
41
+ ev.add_argument("-o", "--output", default=None,
42
+ help="write the record here instead of stdout")
43
+ ev.add_argument("--verify", metavar="RECORD", default=None,
44
+ help="recompute the digests in an existing record instead of making one")
45
+
46
+ sub.add_parser("lsp", help="run the language server on stdio (needs keelspec[lsp])")
47
+ sub.add_parser("mcp", help="serve the product graph over MCP on stdio (needs keelspec[mcp])")
48
+
49
+ orc = sub.add_parser(
50
+ "orchestrate",
51
+ help="run the agent-built lifecycle over one artifact (ST-01..ST-06)",
52
+ )
53
+ orc.add_argument("feature", help="the artifact id to build, e.g. FEAT-refunds")
54
+ orc.add_argument("--dry-run", action="store_true",
55
+ help="use the offline stub runner: exercises the pipeline, calls no model")
56
+ orc.add_argument("--resolve", action="append", default=[], metavar="ID=ANSWER",
57
+ help="answer a Disambiguate question (repeatable)")
58
+ orc.add_argument("--max-repair", type=int, default=None,
59
+ help=f"bounded repair rounds (default {orchestration.Orchestrator.MAX_REPAIR})")
60
+ orc.add_argument("--write", action="store_true",
61
+ help="let the Develop station actually edit files (default: propose only)")
62
+ orc.add_argument("--no-clean", action="store_true",
63
+ help="skip ST-04b Clean (one fewer model call per run)")
64
+ orc.add_argument("--cross-provider", action="store_true",
65
+ help="add a non-Claude critic via OpenRouter (needs OPENROUTER_API_KEY)")
66
+ orc.add_argument("-o", "--output", default=None,
67
+ help="write the run report here instead of stdout")
68
+ return p
69
+
70
+
71
+ def main(argv: list[str] | None = None) -> int:
72
+ args = _build_parser().parse_args(argv)
73
+ config_path = f"{args.root}/{args.config}" if args.root != "." else args.config
74
+ config = load_config(config_path)
75
+ registry = load_plugin(args.plugin)
76
+
77
+ if args.cmd == "validate" and args.watch:
78
+ if args.as_json:
79
+ # A tick-per-document JSON stream is not a format anything consumes.
80
+ # Editors want the language server; CI wants one-shot --json.
81
+ print("--watch and --json are mutually exclusive", file=sys.stderr)
82
+ return 2
83
+ from .watch import watch
84
+ return watch(config_path, args.root, registry)
85
+
86
+ if args.cmd == "lsp":
87
+ from .lsp import serve
88
+ return serve(args.config, args.root, args.plugin)
89
+
90
+ if args.cmd == "mcp":
91
+ from .mcp import serve
92
+ return serve(args.config, args.root, args.plugin)
93
+
94
+ if args.cmd == "build":
95
+ for path in engine.build(config, args.root, registry):
96
+ print(f"wrote {path}")
97
+ return 0
98
+
99
+ if args.cmd == "orchestrate":
100
+ resolutions = {}
101
+ for pair in args.resolve:
102
+ key, _, value = pair.partition("=")
103
+ if not value:
104
+ print(f"--resolve expects ID=ANSWER, got: {pair}", file=sys.stderr)
105
+ return 2
106
+ resolutions[key.strip()] = value.strip()
107
+
108
+ if args.dry_run:
109
+ runner = orchestration.StubRunner()
110
+ else:
111
+ # Develop needs tools; every other station is one structured call.
112
+ from .coding import CodingRunner
113
+ runner = CodingRunner(root=args.root, write=args.write)
114
+
115
+ extra_lens = None
116
+ if args.cross_provider:
117
+ from .runners import CrossProviderLens
118
+ lens = CrossProviderLens()
119
+ if not lens.enabled:
120
+ print("cross-provider lens skipped: OPENROUTER_API_KEY not set",
121
+ file=sys.stderr)
122
+ else:
123
+ extra_lens = lens.verdict
124
+
125
+ # The human gate as a file: answers a person has already written win over
126
+ # anything passed on the command line only where the flag is absent.
127
+ stored = orchestration.read_resolutions(args.root, args.feature)
128
+ stored.update(resolutions)
129
+ resolutions = stored
130
+
131
+ try:
132
+ bundle = engine.load(config, args.root)
133
+ brief = json.dumps({name: [r.get("id") for r in recs]
134
+ for name, recs in bundle.items()})[:4000]
135
+ except Exception:
136
+ brief = ""
137
+
138
+ report = orchestration.Orchestrator(
139
+ runner, brief=brief, resolutions=resolutions,
140
+ max_repair=args.max_repair, extra_lens=extra_lens,
141
+ clean=not args.no_clean,
142
+ on_phase=lambda phase: print(f"── {phase}", file=sys.stderr),
143
+ ).run(args.feature)
144
+
145
+ if report.status == "blocked":
146
+ path = orchestration.write_questions(
147
+ args.root, args.feature, report.disambiguation)
148
+ print(f"\nHuman gate: {len(report.disambiguation)} open question(s).",
149
+ file=sys.stderr)
150
+ print(f"Answer them in {path}, then run this again.", file=sys.stderr)
151
+
152
+ saved = orchestration.save_report(args.root, report)
153
+ print(f"── run saved to {saved}", file=sys.stderr)
154
+
155
+ text = report.render()
156
+ if args.output:
157
+ out = pathlib.Path(args.root) / args.output
158
+ out.parent.mkdir(parents=True, exist_ok=True)
159
+ out.write_text(text, encoding="utf-8", newline="\n")
160
+ print(f"wrote {out}")
161
+ else:
162
+ sys.stdout.write(text)
163
+
164
+ # blocked and refuted are both non-zero: the line did not propose a change.
165
+ return 0 if report.status == "proposed" else 1
166
+
167
+ if args.cmd == "evidence":
168
+ if args.verify:
169
+ path = pathlib.Path(args.root) / args.verify
170
+ try:
171
+ record = json.loads(path.read_text(encoding="utf-8"))
172
+ except (OSError, ValueError) as exc:
173
+ print(f"cannot read {path}: {exc}", file=sys.stderr)
174
+ return 2
175
+ problems = evidence.verify(record, args.root)
176
+ if problems:
177
+ print(f"EVIDENCE DOES NOT MATCH THIS TREE — {len(problems)} problem(s)\n")
178
+ for problem in problems:
179
+ print(f" {problem}")
180
+ return 1
181
+ made = record.get("generated_at", "?")
182
+ print(f"evidence verified: every digest still matches (recorded {made})")
183
+ return 0
184
+
185
+ record = evidence.build_record(config, args.root, registry)
186
+ text = evidence.render(record)
187
+ if args.output:
188
+ out = pathlib.Path(args.root) / args.output
189
+ out.parent.mkdir(parents=True, exist_ok=True)
190
+ out.write_text(text, encoding="utf-8", newline="\n")
191
+ print(f"wrote {out}")
192
+ else:
193
+ sys.stdout.write(text)
194
+ # Same gating semantics as validate: an evidence record of a failing run is
195
+ # still worth having, but CI must not go green because you asked for one.
196
+ return 1 if record["result"] == "fail" else 0
197
+
198
+ report = engine.validate(config, args.root, registry)
199
+ counts = {name: len(recs) for name, recs in engine.load(config, args.root).items()}
200
+
201
+ if getattr(args, "as_json", False):
202
+ # Diagnostics are an API. Making a consumer regex the prose to find a code
203
+ # defeats the point of having stable codes at all.
204
+ json.dump(
205
+ {
206
+ "schema": "keelspec-report/1",
207
+ "result": "pass" if report.ok else "fail",
208
+ "counts": counts,
209
+ "errors": len(report.errors),
210
+ "warnings": len(report.warnings),
211
+ "findings": [
212
+ {
213
+ "code": d.code,
214
+ "severity": d.severity,
215
+ "where": d.where,
216
+ "message": d.message,
217
+ }
218
+ for d in report.diagnostics
219
+ ],
220
+ },
221
+ sys.stdout, indent=2, ensure_ascii=False, sort_keys=True,
222
+ )
223
+ sys.stdout.write("\n")
224
+ return 1 if report.errors else 0
225
+
226
+ for w in report.warnings:
227
+ print(f"WARN {w.render()}")
228
+ for e in report.errors:
229
+ print(f"ERROR {e.render()}")
230
+ summary = ", ".join(f"{n} {c}" for n, c in counts.items())
231
+ print(
232
+ f"\nkeelspec: {summary} — "
233
+ f"{len(report.errors)} error(s), {len(report.warnings)} warning(s)."
234
+ )
235
+ return 1 if report.errors else 0
236
+
237
+
238
+ if __name__ == "__main__":
239
+ sys.exit(main())