forgeproof-cli 0.2.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.
Files changed (89) hide show
  1. forge_gate/__init__.py +44 -0
  2. forge_gate/_deprecated_cli.py +16 -0
  3. forgeproof/__init__.py +3 -0
  4. forgeproof/catalog.py +110 -0
  5. forgeproof/cli.py +560 -0
  6. forgeproof/config.py +339 -0
  7. forgeproof/data/gate_catalog.json +66 -0
  8. forgeproof/data/host_sets.json +7 -0
  9. forgeproof/debug_caller.py +271 -0
  10. forgeproof/debug_core.py +368 -0
  11. forgeproof/fixture_engine.py +81 -0
  12. forgeproof/fixtures/__init__.py +19 -0
  13. forgeproof/fixtures/decision_tree_id3.py +90 -0
  14. forgeproof/fixtures/gradient_descent_momentum.py +73 -0
  15. forgeproof/fixtures/kmeans_clustering.py +98 -0
  16. forgeproof/fixtures/knn_classifier.py +79 -0
  17. forgeproof/fixtures/linear_regression_gd.py +77 -0
  18. forgeproof/fixtures/logistic_regression.py +85 -0
  19. forgeproof/fixtures/naive_bayes_text.py +114 -0
  20. forgeproof/fixtures/perceptron.py +84 -0
  21. forgeproof/fixtures/polynomial_regression.py +67 -0
  22. forgeproof/fixtures/ridge_regression_normal_eq.py +75 -0
  23. forgeproof/ledger.py +633 -0
  24. forgeproof/lens_tools/__init__.py +11 -0
  25. forgeproof/lens_tools/guard_lens.py +1250 -0
  26. forgeproof/lens_tools/invariant_contracts/linear_regression_gd.json +74 -0
  27. forgeproof/lens_tools/invariant_contracts/polynomial_regression.json +86 -0
  28. forgeproof/lens_tools/invariant_contracts/ridge_regression_normal_eq.json +86 -0
  29. forgeproof/lens_tools/invariant_gate.py +199 -0
  30. forgeproof/lens_tools/metamorphic/__init__.py +9 -0
  31. forgeproof/lens_tools/metamorphic/relations.py +962 -0
  32. forgeproof/lens_tools/metamorphic/runner.py +112 -0
  33. forgeproof/lens_tools/twin_consensus.py +395 -0
  34. forgeproof/lenses.py +923 -0
  35. forgeproof/paths.py +56 -0
  36. forgeproof/reference/ORIGIN.md +29 -0
  37. forgeproof/reference/decision_tree_id3.py +197 -0
  38. forgeproof/reference/gradient_descent_momentum.py +141 -0
  39. forgeproof/reference/kmeans_clustering.py +139 -0
  40. forgeproof/reference/knn_classifier.py +118 -0
  41. forgeproof/reference/linear_regression_gd.py +106 -0
  42. forgeproof/reference/logistic_regression.py +141 -0
  43. forgeproof/reference/naive_bayes_text.py +152 -0
  44. forgeproof/reference/perceptron.py +123 -0
  45. forgeproof/reference/polynomial_regression.py +125 -0
  46. forgeproof/reference/ridge_regression_normal_eq.py +165 -0
  47. forgeproof/runner.py +147 -0
  48. forgeproof/scout/__init__.py +7 -0
  49. forgeproof/scout/behaviour.py +365 -0
  50. forgeproof/scout/box.py +581 -0
  51. forgeproof/scout/cards.py +180 -0
  52. forgeproof/scout/contract.py +37 -0
  53. forgeproof/scout/corpus.py +104 -0
  54. forgeproof/scout/embed.py +217 -0
  55. forgeproof/scout/engines/__init__.py +1 -0
  56. forgeproof/scout/engines/chaos.py +454 -0
  57. forgeproof/scout/engines/chaos_port.py +1331 -0
  58. forgeproof/scout/engines/chaos_runner.py +178 -0
  59. forgeproof/scout/engines/executor_port.py +239 -0
  60. forgeproof/scout/envfit.py +54 -0
  61. forgeproof/scout/experience.py +161 -0
  62. forgeproof/scout/fetchproxy.py +368 -0
  63. forgeproof/scout/ghcache.py +395 -0
  64. forgeproof/scout/ghpool.py +253 -0
  65. forgeproof/scout/ghsearch.py +248 -0
  66. forgeproof/scout/ids.py +82 -0
  67. forgeproof/scout/intent_lens.py +170 -0
  68. forgeproof/scout/learn.py +583 -0
  69. forgeproof/scout/meaning_lens.py +231 -0
  70. forgeproof/scout/outcomes.py +42 -0
  71. forgeproof/scout/plant.py +327 -0
  72. forgeproof/scout/ratify.py +214 -0
  73. forgeproof/scout/report.py +448 -0
  74. forgeproof/scout/rule2.py +177 -0
  75. forgeproof/scout/shape.py +107 -0
  76. forgeproof/scout/shape_lens.py +71 -0
  77. forgeproof/scout/signature.py +52 -0
  78. forgeproof/scout/slots.py +39 -0
  79. forgeproof/scout/upstream_facts.py +536 -0
  80. forgeproof/unsupported.py +83 -0
  81. forgeproof/verifier.py +208 -0
  82. forgeproof/view_coverage.py +166 -0
  83. forgeproof_cli-0.2.0.dist-info/METADATA +285 -0
  84. forgeproof_cli-0.2.0.dist-info/RECORD +89 -0
  85. forgeproof_cli-0.2.0.dist-info/WHEEL +5 -0
  86. forgeproof_cli-0.2.0.dist-info/entry_points.txt +3 -0
  87. forgeproof_cli-0.2.0.dist-info/licenses/LICENSE +201 -0
  88. forgeproof_cli-0.2.0.dist-info/licenses/NOTICE +23 -0
  89. forgeproof_cli-0.2.0.dist-info/top_level.txt +2 -0
forgeproof/cli.py ADDED
@@ -0,0 +1,560 @@
1
+ #!/usr/bin/env python3
2
+ """CLI entry point for ForgeProof."""
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import re
8
+ import sys
9
+ from pathlib import Path
10
+
11
+ from .catalog import list_patterns, resolve_pattern, CatalogError
12
+ from .lenses import ALL_LENSES, DEFAULT_LENSES, evaluate, parse_lens_selection, render
13
+ from .runner import run_file
14
+ from .verifier import verdict
15
+
16
+ VERIFY_TIMEOUT = 60.0 # verify's defaults; a run above either is looser (8a crew review, 6E D3)
17
+ VERIFY_MEMORY_MB = 512
18
+ CORPUS_ITEM = re.compile(r"corpus:c_[0-9a-f]{16}", re.ASCII) # D2: content-addressed corpus item
19
+
20
+
21
+ def _fixture_script(name: str) -> Path:
22
+ """Return the path to a fixture script inside the package."""
23
+ return Path(__file__).resolve().parent / "fixtures" / f"{name}.py"
24
+
25
+
26
+ def cmd_list(_args: argparse.Namespace) -> int:
27
+ """List gate-ready patterns."""
28
+ patterns = list_patterns()
29
+ print(f"ForgeProof v1 catalog: {len(patterns)} patterns ready")
30
+ print("-" * 50)
31
+ for name, meta in sorted(patterns.items()):
32
+ print(f" {name:30} {meta['category']:15} {meta['description']}")
33
+ return 0
34
+
35
+
36
+ def cmd_verify(args: argparse.Namespace) -> int:
37
+ """Verify a user file against a pattern oracle."""
38
+ user_file = Path(args.user_file).expanduser().resolve()
39
+ if not user_file.exists():
40
+ print(f"FAIL: user file not found: {user_file}", file=sys.stderr)
41
+ return 2
42
+
43
+ try:
44
+ pattern_meta = resolve_pattern(args.pattern)
45
+ except CatalogError as exc:
46
+ print(f"UNSUPPORTED: {exc}", file=sys.stderr)
47
+ return 3
48
+
49
+ fixture_script = _fixture_script(pattern_meta["fixture"])
50
+ if not fixture_script.exists():
51
+ print(f"UNSUPPORTED: fixture missing for {args.pattern}", file=sys.stderr)
52
+ return 3
53
+
54
+ # The bytes the oracle hook may credit are read ONCE, before anything runs (8a s3 review F3).
55
+ try:
56
+ judged = user_file.read_bytes()
57
+ except OSError:
58
+ judged = None
59
+
60
+ # Run the user's implementation through the fixture harness.
61
+ user_result = run_file(
62
+ fixture_script,
63
+ extra_args=[str(user_file)],
64
+ timeout=args.timeout,
65
+ no_network=not args.allow_network,
66
+ memory_mb=args.memory_mb,
67
+ )
68
+
69
+ # Run the signed AURA oracle itself as the ground-truth reference.
70
+ oracle_result = run_file(
71
+ pattern_meta["aura_path"],
72
+ timeout=args.timeout,
73
+ no_network=not args.allow_network,
74
+ memory_mb=args.memory_mb,
75
+ )
76
+
77
+ v = verdict(
78
+ pattern=args.pattern,
79
+ user_file=user_file,
80
+ oracle_result=oracle_result,
81
+ user_result=user_result,
82
+ tolerance=args.tolerance,
83
+ )
84
+
85
+ # KEYSTONE: one verdict from every selected lens. See forgeproof/lenses.py for
86
+ # the algebra. Supplementary lenses may only DOWNGRADE a property-primary PASS;
87
+ # they can never overturn a property-primary FAIL.
88
+ try:
89
+ selected = parse_lens_selection(args.lenses)
90
+ except ValueError as exc:
91
+ print(f"UNSUPPORTED: {exc}", file=sys.stderr)
92
+ return 3
93
+
94
+ gate = evaluate(
95
+ pattern=args.pattern,
96
+ user_file=user_file,
97
+ base_status=v.status,
98
+ base_reason=v.reason,
99
+ base_metrics=v.metrics,
100
+ lenses=selected,
101
+ timeout=args.timeout,
102
+ short_circuit=not args.no_short_circuit,
103
+ )
104
+
105
+ if args.json:
106
+ print(json.dumps(gate.as_dict(), indent=2, sort_keys=True, default=str))
107
+ else:
108
+ print(render(gate, show_table=not args.quiet))
109
+
110
+ note = _oracle_outcome(user_file, args.pattern, gate.status, _looser_than_default(args, selected), judged)
111
+ if note:
112
+ print(f"forgeproof verify: {note}", file=sys.stderr)
113
+ return 0 if gate.status == "PASS" else 1
114
+
115
+
116
+ # Writer ``oracle-run`` waits at most this long for another ledger writer.
117
+ ORACLE_WAIT = 10.0
118
+
119
+
120
+ def _looser_than_default(args, selected) -> str:
121
+ """'' for a run at least as strict as the default, else how it was looser (review F4)."""
122
+ why = []
123
+ if args.tolerance > 1e-5:
124
+ why.append(f"tolerance {args.tolerance:g}")
125
+ if args.allow_network:
126
+ why.append("network allowed")
127
+ if args.timeout > VERIFY_TIMEOUT:
128
+ why.append(f"timeout {args.timeout:g} s")
129
+ if args.memory_mb > VERIFY_MEMORY_MB:
130
+ why.append(f"memory {args.memory_mb} MB")
131
+ missing = [x for x in DEFAULT_LENSES if x not in selected]
132
+ if missing:
133
+ why.append("lenses off: " + ",".join(missing))
134
+ return "; ".join(why)
135
+
136
+
137
+ def _oracle_outcome(user_file: Path, pattern: str, status: str, looser: str, judged) -> str:
138
+ """Writer ``oracle-run`` (design §4a.5 V4-2, build step 8a s3, DECISIONS-8a G4 a).
139
+
140
+ After the final verdict: a PASS on a file that carries ``forge-gate-result`` ids (handed out by
141
+ ``scout --show``) appends one oracle outcome per id, all with this run's id. The verdict and
142
+ exit code never depend on the ledger. Returns a note for stderr ("" when there is nothing to
143
+ say). Called only from cmd_verify (tests/test_ledger_routes.py)."""
144
+ from . import ledger
145
+
146
+ if not ledger.enabled():
147
+ return "" # ledgers off: verify behaves exactly as before 8a
148
+ try:
149
+ return "ledger: " + _oracle_notes(user_file, pattern, status, looser, judged)
150
+ except Exception as e: # the verdict is printed already; never break it (F5)
151
+ return f"ledger: BLIND(unexpected {type(e).__name__}: {e}); outcomes not all recorded"
152
+
153
+
154
+ def _oracle_notes(user_file: Path, pattern: str, status: str, looser: str, judged) -> str:
155
+ import hashlib
156
+ import time
157
+
158
+ from . import config, ledger
159
+ from .scout import report
160
+
161
+ if status != "PASS":
162
+ return f"verdict {status} is not an outcome; nothing recorded"
163
+ if looser:
164
+ return f"run looser than the default ({looser}): not an outcome; nothing recorded"
165
+ if judged is None:
166
+ return f"could not read {user_file.name} before the run; nothing recorded"
167
+ text = judged.decode("utf-8", errors="replace")
168
+ rids = ledger.result_ids_in(text)
169
+ if not rids:
170
+ return "no forge-gate-result id in the file; nothing recorded"
171
+ run_id, digest = ledger.new_run_id(), hashlib.sha256(judged).hexdigest()
172
+ deadline = time.monotonic() + ORACLE_WAIT # one wait for all ids (review F7)
173
+ notes = []
174
+ for rid in rids:
175
+ why = report.snippet_missing(rid, text)
176
+ if why:
177
+ notes.append(f"{rid}: refused: {why}")
178
+ continue
179
+ try:
180
+ ledger.record_oracle(result_id=rid, run_id=run_id, oracle=f"verify:{pattern}", verdict=status,
181
+ verified_file=user_file, content_sha256=digest,
182
+ wait=max(0.0, deadline - time.monotonic()))
183
+ notes.append(f"{rid}: oracle outcome recorded (run {run_id})")
184
+ except ledger.Refused as e:
185
+ notes.append(f"{rid}: refused: {e}")
186
+ except (ledger.LedgerError, config.NotConfigured, OSError) as e:
187
+ notes.append(f"{rid}: BLIND(ledger-unwritable: {e})")
188
+ return "; ".join(notes)
189
+
190
+
191
+ def main(argv: list[str] | None = None) -> int:
192
+ argv = list(sys.argv[1:] if argv is None else argv)
193
+ # `ledger event ... -- <cmd...>`: the person's command is split off HERE, before argparse, so
194
+ # none of its words can be read as our options (argparse's REMAINDER after a positional rejects
195
+ # `event MARK --project P -- cmd`, measured on 3.10 and 3.11).
196
+ event_cmd = None
197
+ if argv[:2] == ["ledger", "event"] and "--" in argv:
198
+ cut = argv.index("--")
199
+ argv, event_cmd = argv[:cut], argv[cut + 1:]
200
+ ap = argparse.ArgumentParser(
201
+ prog="forgeproof",
202
+ description="Deterministic regression gate for code-generating agents.",
203
+ )
204
+ sub = ap.add_subparsers(dest="command", required=True)
205
+
206
+ list_parser = sub.add_parser("list", help="list gate-ready patterns")
207
+ list_parser.set_defaults(func=cmd_list)
208
+
209
+ verify_parser = sub.add_parser("verify", help="verify a user file against a pattern oracle")
210
+ verify_parser.add_argument("user_file", help="Python file to verify")
211
+ verify_parser.add_argument("--pattern", required=True, help="pattern name from catalog")
212
+ verify_parser.add_argument("--timeout", type=float, default=VERIFY_TIMEOUT, help="seconds (default 60)")
213
+ verify_parser.add_argument("--tolerance", type=float, default=1e-5, help="numeric comparison tolerance")
214
+ verify_parser.add_argument("--allow-network", action="store_true", help="do not drop network namespace")
215
+ verify_parser.add_argument("--memory-mb", type=int, default=VERIFY_MEMORY_MB, help="memory limit in MB")
216
+ verify_parser.add_argument(
217
+ "--lenses",
218
+ default="default",
219
+ help="'default'/'all' = every lens ("
220
+ + ", ".join(ALL_LENSES)
221
+ + "), or a comma-separated subset",
222
+ )
223
+ verify_parser.add_argument(
224
+ "--show-lenses", action="store_true", help="(deprecated: the per-lens table is now shown by default)"
225
+ )
226
+ verify_parser.add_argument(
227
+ "--quiet", action="store_true", help="suppress the per-lens table, print the verdict only"
228
+ )
229
+ verify_parser.add_argument(
230
+ "--no-short-circuit",
231
+ action="store_true",
232
+ help="run every lens even after property-primary fails (evidence gathering; verdict unchanged)",
233
+ )
234
+ verify_parser.add_argument("--json", action="store_true", help="emit the verdict as JSON")
235
+ verify_parser.set_defaults(func=cmd_verify)
236
+
237
+ scout_parser = sub.add_parser(
238
+ "scout", help="advisory: what is this code related to? (no verdict; slice 1: python, corpus pool, shape lens)")
239
+ scout_parser.add_argument("file", nargs="?", help="file to scout (read as text, never run)")
240
+ scout_parser.add_argument("--show", metavar="RESULT_ID",
241
+ help="print the code behind a result id, its id as the first line (step 8a)")
242
+ scout_parser.add_argument("--json", action="store_true", help="emit the report as JSON")
243
+ scout_parser.add_argument("--intent", metavar="TEXT",
244
+ help="what the code is FOR, in your words: the intent lens compares it with each "
245
+ "pool member's purpose text (step 8b)")
246
+ scout_parser.add_argument("--embed-fill", action="store_true",
247
+ help="fill the meaning lens's vector cache from the corpus export (the cache's "
248
+ "only writer; refuses while the lens's Rule-2 set is red; step 8b)")
249
+ scout_parser.set_defaults(func=cmd_scout)
250
+
251
+ learn_parser = sub.add_parser(
252
+ "learn", help="learn a corpus file into the logic registry (step 6b-1: plumbing; no engine can PASS)")
253
+ learn_parser.add_argument("file", help="a file whose bytes are an item of the corpus export; with "
254
+ "--github, a path inside that pinned repo (read from the private cache)")
255
+ learn_parser.add_argument("--author", help="crew code only: the seat that wrote it, e.g. 4Q")
256
+ learn_parser.add_argument("--github", metavar="ORG/REPO@COMMIT",
257
+ help="learn from the GitHub pool: a ratified repo at its signed pin (step 7)")
258
+ learn_parser.add_argument("--lock-wait", type=float, default=10.0,
259
+ help="seconds to wait for the registry build's lock before failing (default 10)")
260
+ learn_parser.add_argument("--json", action="store_true", help="emit the report as JSON")
261
+ learn_parser.set_defaults(func=cmd_learn)
262
+
263
+ cal_parser = sub.add_parser(
264
+ "chaos-calibrate",
265
+ help="run the validator's chaos negative-control gate on THIS machine and record it "
266
+ "(writes only the scout's chaos_gate_history.json; KD-12 c/m)")
267
+ cal_parser.add_argument("--runs", type=int, default=None,
268
+ help="gate runs to record (default: the calibration size, CALIBRATION_N)")
269
+ cal_parser.set_defaults(func=cmd_chaos_calibrate)
270
+
271
+ box_parser = sub.add_parser(
272
+ "box-selftest", help="run the isolation box's red arm in the open: each attempt, boxed and unboxed")
273
+ box_parser.add_argument("--json", action="store_true")
274
+ box_parser.set_defaults(func=cmd_box_selftest)
275
+
276
+ facts_parser = sub.add_parser(
277
+ "github-facts",
278
+ help="measure whether a ratified repo's own tests notice planted bugs, per function, in the box "
279
+ "(writes only $FORGE_GATE_SCOUT_DIR/github_facts.jsonl; a fact row, never a PASS)")
280
+ facts_parser.add_argument("spec", metavar="ORG/REPO@SHA", help="a ratified repo at its signed pin")
281
+ facts_parser.add_argument("--functions", nargs="+", metavar="NAME",
282
+ help="only these functions: NAME, PATH::NAME or MODULE:NAME (default: every "
283
+ "admitted top-level function)")
284
+ facts_parser.add_argument("--json", action="store_true", help="print the rows as JSON lines")
285
+ facts_parser.set_defaults(func=cmd_github_facts)
286
+
287
+ led = sub.add_parser(
288
+ "ledger", help="the outcome ledgers (step 8a): mark kept code, run its build/tests, show counts")
289
+ lsub = led.add_subparsers(dest="ledger_cmd", required=True)
290
+ mark_p = lsub.add_parser("mark", help="you kept a scout result and it worked: a pending mark (prints its id)")
291
+ mark_p.add_argument("result_id", nargs="?", help="the forge-gate-result id the code came with")
292
+ mark_p.add_argument("--item", help="without an id: the corpus item, e.g. corpus:c_0123456789abcdef")
293
+ mark_p.add_argument("--who", required=True, help="who kept it")
294
+ event_p = lsub.add_parser(
295
+ "event", help="run your project's build or tests for a mark; the tool records the exit code")
296
+ event_p.add_argument("mark_id", help="the id `ledger mark` printed")
297
+ event_p.add_argument("--project", required=True, help="your project's folder (the command runs there)")
298
+ event_p.add_argument("--kind", required=True, choices=("build", "tests"))
299
+ event_p.epilog = "The command follows `--`: forgeproof ledger event MARK --project DIR --kind tests -- pytest -q"
300
+ show_p = lsub.add_parser("show", help="the counts for an item or a result id (read-only)")
301
+ show_p.add_argument("target", help="corpus:<item_id> or a forge-gate-result id")
302
+ show_p.add_argument("--json", action="store_true")
303
+ led.set_defaults(func=cmd_ledger)
304
+
305
+ args = ap.parse_args(argv)
306
+ args.event_cmd = event_cmd
307
+ return args.func(args)
308
+
309
+
310
+ def cmd_box_selftest(args) -> int:
311
+ """Anyone can run this as themselves (design §4a.6; 6E's request 2026-11-11): the box needs
312
+ no root. Exit 0 only when every boxed attempt is blocked AND every unboxed attempt leaks
313
+ (the unboxed run proves the targets are real, so "blocked" is not vacuous)."""
314
+ import getpass
315
+ import json as _json
316
+
317
+ from .scout import box
318
+
319
+ why = box.available()
320
+ if why:
321
+ print(f"BLIND({why})")
322
+ return 2
323
+ cannot = box.start_failure()
324
+ if cannot:
325
+ print(f"BLIND(box-unavailable: bwrap cannot start: {cannot})")
326
+ return 2
327
+ boxed, unboxed = box.red_arm("run"), box.red_arm("run", unboxed=True)
328
+ keys = ("secret", "write", "network")
329
+ # The network control is our own loopback listener (B4-1): it must be reached unboxed, so the
330
+ # verdict does not depend on this host having internet. Public hosts are extra evidence only.
331
+ ok = (boxed["ok"] and unboxed["secret"] == "LEAKED" and unboxed["write"] == "LEAKED"
332
+ and unboxed["control_target"] in unboxed["network"])
333
+ if args.json:
334
+ print(_json.dumps({"user": getpass.getuser(), "box_user": box.box_user(), "boxed": boxed,
335
+ "unboxed_control": unboxed, "ok": ok}, indent=1))
336
+ else:
337
+ print(f"box self-test user={getpass.getuser()} box_user={box.box_user() or '(none: bwrap as this user)'}")
338
+ for k in keys:
339
+ print(f" {k:<8} boxed: {boxed[k]:<28} unboxed control: {unboxed[k]}")
340
+ print(f" probe said (boxed): {boxed['probe']}")
341
+ user = box.box_user()
342
+ depth = (f"box user {user}" if user else
343
+ f"namespaces only; FORGE_GATE_BOX_USER unset, so an escape lands as {getpass.getuser()}")
344
+ print(f" control: unboxed reached our own listener {unboxed['control_target']}")
345
+ print(f"PASS: every boxed attempt blocked, every unboxed attempt leaked ({depth})" if ok else
346
+ "FAIL: " + ("a boxed attempt got through" if not boxed["ok"] else "the unboxed control did not leak: targets not real"))
347
+ return 0 if ok else 1
348
+
349
+
350
+ def cmd_github_facts(args) -> int:
351
+ """Exit 0 when at least one function was MEASURED, 3 when every row is BLIND, 2 when there
352
+ is no place for the rows ($FORGE_GATE_SCOUT_DIR)."""
353
+ from . import config
354
+ from .scout import upstream_facts
355
+
356
+ try:
357
+ res = upstream_facts.run(args.spec, args.functions)
358
+ except config.NotConfigured as e:
359
+ print(f"github-facts: {e}", file=sys.stderr)
360
+ return 2
361
+ for row in res.rows:
362
+ if args.json:
363
+ print(json.dumps(row, sort_keys=True))
364
+ else:
365
+ what = row.get("function") or "(run)"
366
+ counts = f" m={row['m']} k={row['k']} s={row['s']} u={row['u']}" if "m" in row else ""
367
+ print(f"{row['outcome']:<40} {row.get('file') or ''}::{what}{counts}")
368
+ print(f"github-facts: run {res.run_id}: {res.measured} MEASURED of {len(res.rows)} rows -> {res.facts_file}",
369
+ file=sys.stderr)
370
+ return 0 if res.measured else 3
371
+
372
+
373
+ def cmd_learn(args) -> int:
374
+ from .scout import learn
375
+
376
+ if args.github is not None: # a path INSIDE the pinned repo, not a local file
377
+ res = learn.run(args.file, args.author, lock_wait=args.lock_wait, github=args.github)
378
+ print(json.dumps(res.report, indent=1, sort_keys=True) if args.json else learn.render(res))
379
+ if res.code not in (learn.EXIT_OK,):
380
+ print(f"forgeproof learn: {res.outcome}", file=sys.stderr)
381
+ return res.code
382
+
383
+ if args.author is None: # as before step 7: a usage error (exit 2), not a run (review F9)
384
+ print("forgeproof learn: error: the following arguments are required: --author "
385
+ "(crew code; a GitHub file takes --github instead)", file=sys.stderr)
386
+ return 2
387
+ p = Path(args.file)
388
+ if not p.is_file():
389
+ print(f"forgeproof learn: {p}: not a file", file=sys.stderr)
390
+ return learn.EXIT_BLIND
391
+ res = learn.run(p, args.author, lock_wait=args.lock_wait)
392
+ print(json.dumps(res.report, indent=1, sort_keys=True) if args.json else learn.render(res))
393
+ if res.code not in (learn.EXIT_OK,):
394
+ print(f"forgeproof learn: {res.outcome}", file=sys.stderr)
395
+ return res.code
396
+
397
+
398
+ def cmd_chaos_calibrate(args) -> int:
399
+ """Record N gate runs (no probe, no registry write) under learn's singleton lock, so it never
400
+ meets a learn writing the same history. Stops early at the first survival (the machine is
401
+ then latched BLIND, and more runs cannot unlatch it)."""
402
+ import os
403
+
404
+ from . import config
405
+ from .scout import learn
406
+ from .scout.engines import chaos
407
+
408
+ runs = args.runs if args.runs is not None else chaos.CALIBRATION_N
409
+ if runs < 1:
410
+ print("forgeproof chaos-calibrate: --runs must be at least 1", file=sys.stderr)
411
+ return learn.EXIT_CONFIG
412
+ try:
413
+ fd = learn._singleton(config.scout_dir())
414
+ except config.NotConfigured as e:
415
+ print(f"forgeproof chaos-calibrate: {e}", file=sys.stderr)
416
+ return learn.EXIT_CONFIG
417
+ except learn.LearnError as e: # LockBusy -> EXIT_LOCK; a lock it cannot open -> config
418
+ print(f"forgeproof chaos-calibrate: {e}", file=sys.stderr)
419
+ return e.code
420
+ try:
421
+ res = chaos.calibrate(runs)
422
+ except config.NotConfigured as e:
423
+ print(f"forgeproof chaos-calibrate: {e}", file=sys.stderr)
424
+ return learn.EXIT_CONFIG
425
+ except chaos.Blind as e:
426
+ print(f"forgeproof chaos-calibrate: {e}", file=sys.stderr)
427
+ return learn.EXIT_BLIND
428
+ except OSError as e:
429
+ print(f"forgeproof chaos-calibrate: {e}", file=sys.stderr)
430
+ return learn.EXIT_CONFIG
431
+ finally:
432
+ os.close(fd)
433
+ print(json.dumps(res, indent=1, sort_keys=True))
434
+ clean = (res.get("config") or {}).get("clean_runs", 0)
435
+ if res.get("survived") or clean < chaos.CALIBRATION_N: # review F1: never "ok" when not calibrated
436
+ print(f"forgeproof chaos-calibrate: NOT calibrated: survived={res.get('survived') or {}}, "
437
+ f"{clean}/{chaos.CALIBRATION_N} clean gate runs; chaos stays BLIND here", file=sys.stderr)
438
+ return learn.EXIT_BLIND
439
+ return learn.EXIT_OK
440
+
441
+
442
+ def cmd_scout(args) -> int:
443
+ from .scout import report
444
+
445
+ if args.embed_fill:
446
+ if args.file is not None or args.show is not None:
447
+ print("forgeproof scout: --embed-fill takes no file and no --show", file=sys.stderr)
448
+ return 2
449
+ rc, text = report.embed_fill()
450
+ print(f"forgeproof scout --embed-fill: {text}", file=sys.stderr if rc else sys.stdout)
451
+ return rc
452
+ if args.show is not None:
453
+ if args.file is not None:
454
+ print("forgeproof scout: give a file OR --show, not both", file=sys.stderr)
455
+ return 2
456
+ rc, text = report.show(args.show)
457
+ if rc:
458
+ print(f"forgeproof scout: {text}", file=sys.stderr)
459
+ else:
460
+ print(text, end="")
461
+ return rc
462
+ if args.file is None:
463
+ print("forgeproof scout: a file to scout (or --show RESULT_ID) is required", file=sys.stderr)
464
+ return 2
465
+ p = Path(args.file)
466
+ if not p.is_file():
467
+ print(f"forgeproof scout: {p}: not a file", file=sys.stderr)
468
+ return 2
469
+ rep = report.run(p, intent=args.intent)
470
+ print(report.to_json(rep) if args.json else report.render(rep))
471
+ return 0 # advisory: a report is a success, whatever it found
472
+
473
+
474
+ def cmd_ledger(args) -> int:
475
+ """``forgeproof ledger mark|event|show`` (step 8a; DECISIONS-8a G5 a, G7). ``mark`` and
476
+ ``event`` are the person-mark writer's only named place; ``show`` only reads.
477
+
478
+ Exit codes: 2 = refused or off, nothing written (or, for ``event``, nothing recorded); a
479
+ recorded event exits 0/1 with its command's pass/fail; ``show`` exits 1 when the ledgers
480
+ cannot be read (BLIND: counts unknown, never printed as zeros)."""
481
+ from . import config, ledger
482
+
483
+ def refuse(msg: str) -> int:
484
+ print(f"forgeproof ledger {args.ledger_cmd}: {msg}", file=sys.stderr)
485
+ return 2
486
+
487
+ if not ledger.enabled():
488
+ return refuse(f"{config.LEDGER_KEY} is not set: the ledgers are off; nothing was read or written")
489
+ errors = (ledger.LedgerError, config.NotConfigured, OSError)
490
+
491
+ if args.ledger_cmd == "mark":
492
+ try: # record_mark refuses both/neither
493
+ row = ledger.record_mark(who=args.who, result_id=args.result_id, item=args.item)
494
+ except errors as e:
495
+ return refuse(f"{e}; nothing was recorded")
496
+ if args.item is not None:
497
+ try:
498
+ seen = bool(ledger.exposures(row["item"]))
499
+ except errors:
500
+ seen = True # cannot tell: say nothing
501
+ if not seen:
502
+ print(f"forgeproof ledger mark: note: {row['item']} was never shown on this host; "
503
+ "the mark is kept but counts only under that exact item", file=sys.stderr)
504
+ print(row["mark_id"])
505
+ return 0
506
+
507
+ if args.ledger_cmd == "event":
508
+ if not args.event_cmd:
509
+ return refuse("give the command to run after `--`, e.g. -- pytest -q; nothing was run")
510
+ try:
511
+ row = ledger.record_event(mark_id=args.mark_id, project=args.project, cmd=args.event_cmd,
512
+ event_kind=args.kind)
513
+ except errors as e:
514
+ return refuse(f"{e} (no event recorded)")
515
+ print(f"{row['event_id']}: {row['event_kind']} rc={row['rc']} recorded for {row['mark_id']}")
516
+ return 0 if row["rc"] == 0 else 1
517
+
518
+ item = args.target # show: read-only
519
+ # A mistyped name must not read as the clean zero of "no evidence" (8a s4 review F3).
520
+ if item.startswith("fgr-") and not ledger.RESULT_ID.fullmatch(item):
521
+ return refuse(f"{item!r} is not a well-formed result id (fgr-<12 hex>-<lens>-<rank>)")
522
+ if item.startswith("corpus:") and not CORPUS_ITEM.fullmatch(item):
523
+ return refuse(f"{item!r} is not a well-formed corpus item (corpus:c_<16 hex>)")
524
+ try:
525
+ v = ledger.view()
526
+ except errors as e:
527
+ why = f"the ledgers could not be read ({e}); the counts are unknown, not zero"
528
+ print(json.dumps({"blind": why}) if args.json else f"BLIND: {why}")
529
+ return 1
530
+ if ledger.RESULT_ID.fullmatch(item):
531
+ if item not in v.exposure:
532
+ return refuse(f"{item} is not in this host's exposure ledger")
533
+ item = v.exposure[item]["item"]
534
+ c = ledger.counts(item, v=v)
535
+ if not ledger.exposures(item, v=v):
536
+ print(f"forgeproof ledger show: note: {item} was never shown on this host", file=sys.stderr)
537
+ out = {"item": item, "exposures": len(ledger.exposures(item, v=v)), "oracle": c.oracle,
538
+ "person_with_id": c.person_with_id, "person_without_id": c.person_without_id,
539
+ "pending": c.pending,
540
+ "ledger": {"refused": [list(x) for x in v.refused], "torn": [list(x) for x in v.torn],
541
+ "orphans": len(v.orphans)}}
542
+ if args.json:
543
+ print(json.dumps(out, indent=2, sort_keys=True))
544
+ return 0
545
+ lines = [f"item {item}",
546
+ f"exposures {out['exposures']} (shown on this host)",
547
+ f"oracle {c.oracle} person with id {c.person_with_id} "
548
+ f"person without id {c.person_without_id} (three counts, never added up)",
549
+ f"pending {c.pending} (marked, no passing event yet; not counted)"]
550
+ if v.refused or v.torn or v.orphans:
551
+ lines.append(f"ledger {len(v.refused)} refused row(s), {len(v.torn)} torn line(s), "
552
+ f"{len(v.orphans)} orphan(s): left out of every count")
553
+ lines += [f" refused {f}:{n}: {why}" for f, n, why in v.refused]
554
+ lines += [f" torn {f}:{n}" for f, n in v.torn]
555
+ print("\n".join(lines))
556
+ return 0
557
+
558
+
559
+ if __name__ == "__main__":
560
+ sys.exit(main())