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
@@ -0,0 +1,583 @@
1
+ """`forgeproof learn <file> --author=<seat>` (design v1.4.5 §3 learn pipeline, §4.5, §4.4.1;
2
+ build steps 6b-1 and 6b-2, decisions L1-L4 in DECISIONS-6b-learn-20261112.md, the maintainer 2026-11-13).
3
+
4
+ 6b-1 built the plumbing. 6b-2 wires ONE engine, chaos (L3). Only chaos can write a PASS card:
5
+
6
+ - The built-in chaos engine (:func:`chaos_engine`, ``engines/chaos.py``) gives PASS or FAIL
7
+ only where the validator's ``chaos_scan.py`` gives PASS or INVALID-CANDIDATE on the same bytes.
8
+ This is parity-tested against the validator (tests/test_scout_chaos_parity.py). Everything
9
+ else is BLIND:
10
+ - a file not byte-identical to a probed library file;
11
+ - a race/timing probe;
12
+ - a negative-control gate that did not pass cleanly;
13
+ - a harness error;
14
+ - a function the probe did not drive.
15
+ - Every other kind is ``BLIND(not wired)``. Metamorphic is wired later, the same way.
16
+ - :func:`_check` admits PASS only for kind ``chaos`` and only from the built-in chaos engine
17
+ object. Any other engine, built in or passed in by a caller, may return FAIL or BLIND only. Any
18
+ other verdict stops the run before anything is written (exit 5).
19
+
20
+ The pipeline, in order:
21
+
22
+ 1. SOURCE CAPTURE. Read the file's bytes, take their sha256.
23
+ 2. POOL. FOR NOW (L2, a temporary limit, not the design) the file must be a member of the
24
+ readable corpus export: its sha256 equals the sha256 of one item's body (UTF-8) in the
25
+ newest OK export, which ``corpus.read_export`` has re-checked against its manifest. Any
26
+ other file reports ``BLIND(not in a pool)`` and writes nothing. A local author file or a
27
+ GitHub file (step 7) needs its own pool and an id decision first (KNOWN-DEBT KD-11).
28
+ 3. SIGNATURE. Python only (``signature.extract``); other languages are BLIND.
29
+ 4. BATTERY. Every engine in :data:`ENGINES` runs on every function (6b-2: chaos wired; the
30
+ rest BLIND(not wired)).
31
+ 5. SURVIVAL GATE. A function with no engine verdict gets no row and no card.
32
+ 6. APPEND + CARDS. Rows go to scout's OWN ladder files in the Brain's data folder,
33
+ ``$FORGE_GATE_BRAIN_DATA/scout_registry{,_r,_rust,_sysadmin}.jsonl`` (6E's decision A,
34
+ 2026-11-13, for review finding F3). Only learn writes them; the Brain reads them after its
35
+ real ladders, so no extractor, reconcile or regate run can delete a learned row. learn never
36
+ writes a real ladder file: it reads all eight files for the duplicate check. All of it runs
37
+ under ``scout_learn.lock`` (learn-vs-learn singleton, LOCK_NB, fails fast) AND the registry
38
+ build's own lock (L1: the hourly build reads these files and rewrites the real ladders in
39
+ place). The build lock is waited for, then learn fails loudly. Rows whose id is already in any
40
+ of the eight files are skipped and reported, never duplicated. Cards go to ``$FORGE_GATE_SCOUT_DIR/learn_report.json`` through
41
+ ``cards.stage_report`` (write_report's checks and temp file), so every check runs before
42
+ the registry changes; then the rows are appended and the report swapped in. A failure
43
+ after the append cuts the registry back to its old size: nothing is kept.
44
+
45
+ learn does not ratify (§4.3) and does not promote: honest_pass derives tier, basis and
46
+ is_axiom; a learned row carries their initial values (``candidate``) only.
47
+
48
+ Exit codes: 0 ran (rows may be 0), 2 nothing learnable (BLIND input), 3 a lock is held,
49
+ 4 not configured / a precondition failed, 5 refused (an engine verdict 6b-1 does not admit).
50
+ """
51
+ from __future__ import annotations
52
+
53
+ import datetime as _dt
54
+ import fcntl
55
+ import hashlib
56
+ import json
57
+ import os
58
+ import re
59
+ import time
60
+ from dataclasses import dataclass, field
61
+ from pathlib import Path
62
+ from typing import Callable, Optional
63
+
64
+ from .. import config
65
+ from . import cards, corpus, ghpool, signature
66
+ from .engines import chaos
67
+ from .ids import BadScoutId, make_id
68
+ from .outcomes import FOUND
69
+
70
+ EXIT_OK, EXIT_BLIND, EXIT_LOCK, EXIT_CONFIG, EXIT_REFUSED = 0, 2, 3, 4, 5
71
+
72
+ LEARN_LOCK_NAME = "scout_learn.lock"
73
+ REPORT_NAME = "learn_report.json"
74
+ STAGE = "6b-2"
75
+
76
+ # Verdicts any engine's card may carry: FAIL only (the maintainer L3, 2026-11-13) ...
77
+ CARD_VERDICTS = frozenset({"FAIL"})
78
+ # ... except these, for one kind, and only from that kind's BUILT-IN engine (parity-tested).
79
+ PASS_KINDS = frozenset({"chaos"})
80
+ # Verdicts the deployed reader accepts (Brain 6be79ec, honest_pass.VERDICTS, read 2026-11-13).
81
+ # Any other verdict on a card makes the whole registry build raise, every hour.
82
+ READER_VERDICTS = frozenset({"PASS", "FAIL", "FLAG", "RATIFIED"})
83
+ assert "PASS" not in CARD_VERDICTS and "RATIFIED" not in CARD_VERDICTS
84
+ assert CARD_VERDICTS | {"PASS"} <= READER_VERDICTS & cards.VERDICTS
85
+ assert PASS_KINDS == {chaos.KIND}
86
+
87
+ # Scout's own ladder files (6E decision A, 2026-11-13, ANSWER-6E-F3.md): language -> file in
88
+ # the Brain's data folder. Only learn writes them; honest_pass.merge_registries reads them AFTER
89
+ # the real ladders, so a real row wins a duplicate id. They follow the real ladders' language split.
90
+ ROUTE = {"python": "scout_registry.jsonl", "javascript": "scout_registry.jsonl",
91
+ "go": "scout_registry.jsonl", "cpp": "scout_registry.jsonl",
92
+ "r": "scout_registry_r.jsonl",
93
+ "rust": "scout_registry_rust.jsonl",
94
+ **{k: "scout_registry_sysadmin.jsonl"
95
+ for k in ("shell", "bash", "json", "toml", "yaml", "plist", "systemd", "ini")}}
96
+ SCOUT_FILES = tuple(dict.fromkeys(ROUTE.values()))
97
+ # The Brain's real ladders (paths.LOGIC_REGISTRY, _R, RUST, SYSADMIN; all in paths.DATA). learn
98
+ # only READS them, for the duplicate check: their extractors rebuild them wholesale (review F3).
99
+ REAL_LADDERS = ("logic_registry.jsonl", "logic_registry_r.jsonl", "rust_registry.jsonl",
100
+ "sysadmin_registry.jsonl")
101
+ assert len(SCOUT_FILES) == 4 and not set(SCOUT_FILES) & set(REAL_LADDERS)
102
+ assert all(f.startswith("scout_registry") for f in SCOUT_FILES)
103
+ # The sphere tags the live canonical uses (PY, R, RUST, SYS read 2026-11-13); JS/GO/CPP have no
104
+ # rows yet (§4.4.0) and take the design's short tags.
105
+ SPHERE = {"python": "PY", "javascript": "JS", "go": "GO", "cpp": "CPP", "r": "R", "rust": "RUST"}
106
+ SIGNATURE_LANGS = frozenset({"python"})
107
+ _AUTHOR = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._@-]{0,63}$")
108
+
109
+
110
+ class LearnError(RuntimeError):
111
+ code = EXIT_CONFIG
112
+
113
+
114
+ class LockBusy(LearnError):
115
+ code = EXIT_LOCK
116
+
117
+
118
+ class Refused(LearnError):
119
+ code = EXIT_REFUSED
120
+
121
+
122
+ @dataclass(frozen=True)
123
+ class EngineResult:
124
+ """One engine's answer for one function: a verdict, or BLIND(reason). Never both."""
125
+ kind: str
126
+ verdict: Optional[str] = None
127
+ blind_reason: str = ""
128
+ technique: str = ""
129
+ fixture: str = ""
130
+ expected: str = ""
131
+ actual: str = ""
132
+ why: Optional[str] = None
133
+ severity: str = "info"
134
+ card_class: Optional[str] = None
135
+
136
+ def label(self) -> str:
137
+ return self.verdict if self.verdict is not None else f"BLIND({self.blind_reason})"
138
+
139
+
140
+ Engine = Callable[[dict, dict, str], EngineResult] # (corpus item, signature, scout id)
141
+
142
+
143
+ def _not_wired(kind: str) -> Engine:
144
+ def engine(_item: dict, _sig: dict, _sid: str) -> EngineResult:
145
+ return EngineResult(kind, blind_reason="not wired")
146
+ engine.__name__ = f"{kind}_not_wired"
147
+ return engine
148
+
149
+
150
+ def chaos_engine(item: dict, sig: dict, _sid: str) -> EngineResult:
151
+ """The validator's chaos verdict for this function, or BLIND (engines/chaos.py has the rules)."""
152
+ body = item["body"].encode("utf-8")
153
+ probe = chaos.probe_for(body)
154
+ if probe is None:
155
+ return EngineResult(chaos.KIND, blind_reason="no validator chaos probe for these bytes")
156
+ if not chaos.LEARN_LIBRARY_COPIES:
157
+ return EngineResult(chaos.KIND, blind_reason=f"library copy ({probe}): its evidence is the "
158
+ "library's own, not new evidence (KD-12 j)")
159
+ if probe in chaos.RACE:
160
+ return EngineResult(chaos.KIND, blind_reason=f"race/timing probe {probe}: parity with "
161
+ "the validator not shown")
162
+ try:
163
+ verdict, card = chaos.decide(chaos.result_for(body, probe), probe, sig["entry"])
164
+ chaos.check_host() # a host whose NCs ever survived gives no chaos verdict
165
+ except chaos.Blind as e:
166
+ return EngineResult(chaos.KIND, blind_reason=str(e))
167
+ return EngineResult(chaos.KIND, verdict=verdict, technique=card["technique"],
168
+ fixture=card["fixture"], expected=card["expected"], actual=card["actual"],
169
+ why=card.get("note"), severity=card["severity"], card_class=card["class"])
170
+
171
+
172
+ # 6b-2: one engine per oracle kind; chaos is wired (parity-tested), the rest are not.
173
+ ENGINES: tuple = tuple((k, chaos_engine if k == chaos.KIND else _not_wired(k))
174
+ for k in sorted(cards.KINDS))
175
+ _BUILTIN = dict(ENGINES)
176
+
177
+
178
+ @dataclass
179
+ class Learned:
180
+ code: int
181
+ outcome: str
182
+ report: dict = field(default_factory=dict)
183
+
184
+
185
+ def _now() -> _dt.datetime:
186
+ return _dt.datetime.now(_dt.timezone.utc).replace(microsecond=0)
187
+
188
+
189
+ def route(lang: str, data: Path) -> Path:
190
+ """Scout's ladder file for ``lang`` in the Brain's data folder. A missing file fails loudly,
191
+ naming it: learn never creates a registry file (the switch-on creates the four, empty,
192
+ before the Brain's scout reader is deployed)."""
193
+ if lang not in ROUTE:
194
+ raise KeyError(lang)
195
+ target = data / ROUTE[lang]
196
+ if not target.is_file():
197
+ raise LearnError(f"scout ladder file for {lang!r} does not exist: {target} "
198
+ "(learn never creates a registry file)")
199
+ return target
200
+
201
+
202
+ def build_row(sid: str, *, lang: str, sig: dict, item: dict, export_run: str, src: Path,
203
+ sha256: str, author: str, now: _dt.datetime, card_verdicts: list,
204
+ github: "ghpool.Admitted | None" = None) -> dict:
205
+ """A registry row in the §4.5 shape, with scout's initial values. honest_pass re-derives
206
+ is_axiom, prior_is_axiom, basis and the whole ``oracle`` dict on every build; the values
207
+ here are what it derives for a row no report card backs."""
208
+ types = [c["type"] for c in sig["consumes"] if c.get("type")]
209
+ if sig["produces"].get("type"):
210
+ types.append(sig["produces"]["type"])
211
+ entry = sig["entry"]
212
+ if github is None:
213
+ origin, who = f"crew-corpus item {item['item_id']}", "crew code"
214
+ extraction = {"method": "scout", "src": str(src), "author": author,
215
+ "attested_at": now.isoformat().replace("+00:00", "Z"),
216
+ "pool": corpus.POOL, "corpus_item": item["item_id"],
217
+ "corpus_export": export_run, "corpus_file": item["file"],
218
+ "sha256": sha256, "stage": STAGE}
219
+ else: # §12.5 row metadata; no author (no single human claims the file)
220
+ g = github
221
+ origin, who = f"GitHub {g.source}@{g.commit[:12]} {g.path}", "open-source code"
222
+ extraction = {"method": "scout-github", "src": f"github.com/{g.source}@{g.commit}/{g.path}",
223
+ "pool": ghpool.POOL, "license": f"{g.verdict.fields['licence_spdx']}@{g.commit}",
224
+ "ratified_by": sorted(g.verdict.key_ids), "repo_trust_score": g.trust,
225
+ "ingested_at": now.isoformat().replace("+00:00", "Z"),
226
+ "sha256": sha256, "stage": STAGE}
227
+ return {
228
+ "id": sid,
229
+ "sphere": SPHERE.get(lang, "SYS"),
230
+ "category": "scout", # classifier not read yet (DECISIONS-6b "small choices")
231
+ "signature": {"consumes": sig["consumes"], "produces": sig["produces"], "entry": entry},
232
+ "post_conditions": [],
233
+ "invariant_guards": [],
234
+ "core_idea": f"{entry}: learned by scout from {origin}; no human summary",
235
+ "belief_sentence": {"text": (f"{entry} is {who} scout has read; it survived the "
236
+ "validator's chaos probe" if "PASS" in card_verdicts else
237
+ f"{entry} is {who} scout has read; no oracle has backed it"),
238
+ "status": f"scout-{STAGE} (initial value; honest_pass derives the tier)"},
239
+ "type_nouns_raw": list(dict.fromkeys(types)),
240
+ # True only when a parity-tested engine ran the code green (a PASS card).
241
+ "verified_run": "PASS" in card_verdicts,
242
+ # §4.5: "weak" needs at least one PASS card (DECISIONS-6b); "none" silences the row
243
+ # from fusion, which is right for a row nothing backs.
244
+ "strength": "weak" if "PASS" in card_verdicts else "none",
245
+ "is_axiom": False,
246
+ "extraction": extraction,
247
+ "oracle": {"backed": False, "kinds": [], "verdicts": {}, "tier": "candidate",
248
+ "checked_against": f"scout-{STAGE}", "stamp": now.date().isoformat()},
249
+ "prior_is_axiom": False,
250
+ "basis": "green-run-candidate",
251
+ }
252
+
253
+
254
+ def _check(kind: str, r: EngineResult, engine=None) -> None:
255
+ """The verdict gate. Runs on every engine result before anything is written."""
256
+ if not isinstance(r, EngineResult) or r.kind != kind:
257
+ raise Refused(f"engine {kind!r} returned {r!r}, not an EngineResult for its own kind")
258
+ if r.verdict is None:
259
+ if not r.blind_reason:
260
+ raise Refused(f"engine {kind!r} returned neither a verdict nor a BLIND reason")
261
+ return
262
+ if r.blind_reason:
263
+ raise Refused(f"engine {kind!r} returned a verdict AND a BLIND reason")
264
+ if r.verdict in CARD_VERDICTS:
265
+ return
266
+ if r.verdict == "PASS" and kind in PASS_KINDS and engine is not None and engine is _BUILTIN[kind]:
267
+ return
268
+ raise Refused(f"engine {kind!r} returned {r.verdict!r}: step {STAGE} admits {sorted(CARD_VERDICTS)}, "
269
+ f"and PASS only for {sorted(PASS_KINDS)} from the built-in, parity-tested "
270
+ "engine. Nothing was written.")
271
+
272
+
273
+ def _ladder_ids(data: Path) -> dict:
274
+ """id -> file, over the real ladders AND scout's own (honest_pass merges all eight, first
275
+ writer wins, so an id in ANY of them would shadow or be shadowed)."""
276
+ seen: dict = {}
277
+ for f in [data / n for n in REAL_LADDERS + SCOUT_FILES]:
278
+ if not f.is_file():
279
+ continue
280
+ with f.open(encoding="utf-8") as fh:
281
+ for n, line in enumerate(fh, 1):
282
+ if not line.strip():
283
+ continue
284
+ try:
285
+ i = json.loads(line)["id"]
286
+ except (ValueError, KeyError, TypeError):
287
+ raise LearnError(f"{f}:{n}: not a registry row (the registry build would fail "
288
+ "on it too); nothing was written") from None
289
+ seen.setdefault(i, f)
290
+ return seen
291
+
292
+
293
+ def _singleton(scout_dir: Path) -> int:
294
+ p = scout_dir / LEARN_LOCK_NAME
295
+ try:
296
+ fd = os.open(p, os.O_RDWR | os.O_CREAT, 0o660)
297
+ except OSError as e:
298
+ raise LearnError(f"cannot open the learn lock {p}: {e}") from None
299
+ try:
300
+ fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
301
+ except BlockingIOError:
302
+ os.close(fd)
303
+ raise LockBusy(f"another `forgeproof learn` holds {p}: learn runs one at a time") from None
304
+ return fd
305
+
306
+
307
+ def _build_lock(path: Path, wait: float) -> int:
308
+ try:
309
+ fd = os.open(path, os.O_RDONLY) # never O_CREAT: config.registry_build_lock() says why
310
+ except OSError as e:
311
+ raise LearnError(f"cannot open the registry build lock {path}: {e}") from None
312
+ deadline = time.monotonic() + max(0.0, wait)
313
+ while True:
314
+ try:
315
+ fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
316
+ return fd
317
+ except BlockingIOError:
318
+ if time.monotonic() >= deadline:
319
+ os.close(fd)
320
+ raise LockBusy(f"the registry build holds {path}; waited {wait:g} s. "
321
+ "Nothing was written; run learn again after the build.") from None
322
+ time.sleep(0.1)
323
+
324
+
325
+ def _append(target: Path, rows: list) -> None:
326
+ with target.open("rb") as fh:
327
+ fh.seek(0, os.SEEK_END)
328
+ if fh.tell():
329
+ fh.seek(-1, os.SEEK_END)
330
+ if fh.read(1) != b"\n":
331
+ raise LearnError(f"{target} does not end in a newline: an append would glue "
332
+ "two rows into one line. Nothing was written.")
333
+ data = "".join(json.dumps(r, ensure_ascii=False) + "\n" for r in rows).encode("utf-8")
334
+ with target.open("ab") as fh:
335
+ fh.write(data)
336
+ fh.flush()
337
+ os.fsync(fh.fileno())
338
+
339
+
340
+ def _cut_back(target: Path, size: int) -> None:
341
+ """Undo learn's own append: the file goes back to the size it had before it."""
342
+ with target.open("r+b") as fh:
343
+ fh.truncate(size)
344
+ fh.flush()
345
+ os.fsync(fh.fileno())
346
+
347
+
348
+ def _commit_report(tmp: Path, report_path: Path) -> None:
349
+ os.replace(tmp, report_path)
350
+
351
+
352
+ def run(path, author: str | None, *, engines=None, lock_wait: float = 10.0,
353
+ export_root: Path | None = None, now: _dt.datetime | None = None,
354
+ github: str | None = None, gh_opts: dict | None = None) -> Learned:
355
+ """Learn one file. ``engines`` is for tests; the CLI always uses :data:`ENGINES`.
356
+
357
+ ``github="org/repo@<commit>"`` (step 7, G5): ``path`` is then a path INSIDE that pinned repo,
358
+ read from the private cache through ghpool's gate. A GitHub row has no author, so ``author``
359
+ must be None. ``gh_opts`` (list/signer files, cache root, host sets) is for tests only."""
360
+ engines = ENGINES if engines is None else tuple(engines)
361
+ now = now or _now()
362
+ rep: dict = {"file": str(path), "author": author, "stage": STAGE, "rows_appended": 0,
363
+ "cards_written": 0, "duplicates": [], "functions": []}
364
+
365
+ def done(code, outcome):
366
+ rep["outcome"] = outcome
367
+ return Learned(code, outcome, rep)
368
+
369
+ if github is not None:
370
+ if author is not None:
371
+ return done(EXIT_CONFIG, "--author is for crew code; a GitHub file has no single author (§12.5)")
372
+ elif not isinstance(author, str) or not _AUTHOR.match(author):
373
+ return done(EXIT_CONFIG, f"--author must be a seat handle ([A-Za-z0-9._@-], 1-64): {author!r}")
374
+ try:
375
+ bdir = config.brain_data()
376
+ sdir = config.scout_dir()
377
+ lock_path = config.registry_build_lock()
378
+ except config.NotConfigured as e:
379
+ return done(EXIT_CONFIG, f"not configured: {e}")
380
+ rep["brain_data"], rep["scout_dir"], rep["build_lock"] = str(bdir), str(sdir), str(lock_path)
381
+
382
+ try:
383
+ single = _singleton(sdir)
384
+ except LearnError as e:
385
+ return done(e.code, str(e))
386
+ try:
387
+ if github is not None:
388
+ return _run_locked(path, author, engines, lock_wait, export_root, now,
389
+ bdir, sdir, lock_path, rep, done, github, gh_opts or {})
390
+ return _run_locked(Path(path), author, engines, lock_wait, export_root, now,
391
+ bdir, sdir, lock_path, rep, done)
392
+ finally:
393
+ os.close(single)
394
+
395
+
396
+ def _run_locked(path, author, engines, lock_wait, export_root, now, bdir, sdir, lock_path,
397
+ rep, done, github=None, gh_opts=None):
398
+ if github is not None:
399
+ # 2. POOL: GitHub (step 7, G5). L2's "for now" is lifted for this pool only.
400
+ try:
401
+ adm = ghpool.admit(github, str(path), **gh_opts)
402
+ except ghpool.NotAdmitted as e:
403
+ return done(EXIT_BLIND, f"BLIND({e})")
404
+ rep["sha256"] = hashlib.sha256(adm.data).hexdigest()
405
+ rep["pool"] = {"pool": ghpool.POOL, "repo": adm.source, "commit": adm.commit, "file": adm.path,
406
+ "lang": adm.lang, "licence": adm.verdict.fields["licence_spdx"],
407
+ "ratified_by": sorted(adm.verdict.key_ids), "trust": adm.trust}
408
+ return _battery(adm.item(), adm.lang, ghpool.POOL, adm.source, adm.commit, path, author, engines,
409
+ lock_wait, now, bdir, sdir, lock_path, rep, done, github=adm,
410
+ repro=f"forgeproof learn --github {adm.source}@{adm.commit} {adm.path}")
411
+ data = path.read_bytes()
412
+ sha = hashlib.sha256(data).hexdigest()
413
+ rep["sha256"] = sha
414
+
415
+ # 2. POOL (L2, for now: corpus export members only; the GitHub pool is the branch above)
416
+ intake = corpus.read_export(export_root)
417
+ if intake.outcome.kind != FOUND:
418
+ return done(EXIT_BLIND, f"BLIND(not in a pool: corpus {intake.outcome.label()})")
419
+ members = [i for i in intake.items
420
+ if hashlib.sha256(i["body"].encode("utf-8")).hexdigest() == sha]
421
+ if not members:
422
+ return done(EXIT_BLIND, f"BLIND(not in a pool: sha256 matches no item of corpus export "
423
+ f"{intake.run_id})")
424
+ members.sort(key=lambda i: i["item_id"])
425
+ item = members[0]
426
+ rep["pool"] = {"pool": corpus.POOL, "export": intake.run_id, "item_id": item["item_id"],
427
+ "lang": item.get("lang"), "file": item.get("file"),
428
+ "also": [m["item_id"] for m in members[1:]]}
429
+ lang = item.get("lang") or ""
430
+ if not item.get("file"):
431
+ return done(EXIT_BLIND, f"BLIND(corpus item {item['item_id']} has no file path for its id)")
432
+ return _battery(item, lang, corpus.POOL, item["item_id"], intake.run_id, path, author, engines,
433
+ lock_wait, now, bdir, sdir, lock_path, rep, done,
434
+ repro=f"forgeproof learn <corpus {intake.run_id} item {item['item_id']}> --author={author}")
435
+
436
+
437
+ def _battery(item, lang, pool, source, run_id, path, author, engines, lock_wait, now, bdir, sdir,
438
+ lock_path, rep, done, *, github=None, repro: str):
439
+ """Steps 3-6, the same for every pool: signature, battery, survival gate, append + cards."""
440
+ try:
441
+ target = route(lang, bdir)
442
+ except KeyError:
443
+ return done(EXIT_BLIND, f"BLIND(language {lang!r} has no ladder file in the routing table)")
444
+ except LearnError as e:
445
+ return done(e.code, str(e))
446
+ rep["target"] = str(target)
447
+
448
+ # 3. SIGNATURE
449
+ if lang not in SIGNATURE_LANGS:
450
+ return done(EXIT_BLIND, f"BLIND(no signature extractor for {lang!r} yet)")
451
+ try:
452
+ sigs = signature.extract(item["body"])
453
+ except SyntaxError as e:
454
+ return done(EXIT_BLIND, f"BLIND(not parseable as {lang}: {e.msg})")
455
+ if not sigs:
456
+ return done(EXIT_OK, "LOOKED-CLEAN(no public top-level function with a positional argument)")
457
+
458
+ # 4-5. BATTERY + SURVIVAL GATE (nothing is written until every result passed the gate)
459
+ rows, new_cards = [], []
460
+ last = {sig["entry"]: n for n, sig in enumerate(sigs)}
461
+ for n, sig in enumerate(sigs):
462
+ try:
463
+ sid = make_id(pool, source, run_id, item["file"], sig["entry"])
464
+ except BadScoutId as e:
465
+ return done(EXIT_BLIND, f"BLIND(no honest id for {sig['entry']}: {e})")
466
+ fn = {"id": sid, "entry": sig["entry"], "engines": {}}
467
+ rep["functions"].append(fn)
468
+ if last[sig["entry"]] != n: # Python binds the LAST def of a name (6b-1 review F6)
469
+ fn["row"] = "shadowed by a later def of the same name: skipped"
470
+ rep["duplicates"].append(sid)
471
+ continue
472
+ results = []
473
+ for kind, engine in engines:
474
+ r = engine(item, sig, sid)
475
+ try:
476
+ _check(kind, r, engine)
477
+ except Refused as e:
478
+ return done(e.code, str(e))
479
+ fn["engines"][kind] = r.label()
480
+ results.append(r)
481
+ verdicts = [r for r in results if r.verdict is not None]
482
+ if not verdicts:
483
+ fn["row"] = "no engine verdict: no row"
484
+ continue
485
+ fn["row"] = "pending"
486
+ rows.append(build_row(sid, lang=lang, sig=sig, item=item, export_run=run_id,
487
+ src=Path(path).resolve() if github is None else Path(path), sha256=rep["sha256"],
488
+ author=author, now=now, card_verdicts=[r.verdict for r in verdicts],
489
+ github=github))
490
+ for r in verdicts:
491
+ new_cards.append(cards.make_card(
492
+ sid, kind=r.kind, verdict=r.verdict, technique=r.technique or f"scout-{r.kind}",
493
+ fixture=r.fixture, expected=r.expected, actual=r.actual, why=r.why,
494
+ severity=r.severity, card_class=r.card_class,
495
+ repro_cmd=repro))
496
+
497
+ if not rows:
498
+ return done(EXIT_OK, "0 rows: no function has an engine verdict "
499
+ f"(step {STAGE}: only chaos is wired, and it was BLIND)")
500
+
501
+ # 6. APPEND + CARDS, under the registry build's own lock (L1)
502
+ try:
503
+ bfd = _build_lock(lock_path, lock_wait)
504
+ except LearnError as e:
505
+ return done(e.code, str(e))
506
+ tmp = None
507
+ try:
508
+ have = _ladder_ids(bdir)
509
+ report_path = sdir / REPORT_NAME
510
+ old_cards = cards.load_report(report_path) if report_path.exists() else []
511
+ keep_rows, keep_ids = [], set()
512
+ for row in rows:
513
+ if row["id"] in have:
514
+ rep["duplicates"].append(row["id"])
515
+ _fn(rep, row["id"])["row"] = f"id already in {have[row['id']].name}: skipped"
516
+ else:
517
+ keep_rows.append(row)
518
+ keep_ids.add(row["id"])
519
+ keep_cards = [c for c in new_cards if c["id"] in keep_ids]
520
+ old_keys = {(c["id"], c["oracle_coverage_kind"]) for c in old_cards}
521
+ clash = sorted({c["id"] for c in keep_cards if (c["id"], c["oracle_coverage_kind"]) in old_keys})
522
+ if clash:
523
+ raise LearnError(f"{report_path} already has cards for ids that have no row: {clash}. "
524
+ "Nothing was written; inspect the report.")
525
+ if keep_rows:
526
+ # Every card check and the report's own write happen BEFORE the registry changes;
527
+ # a failure after the append cuts the registry back (review F2, F8).
528
+ tmp = cards.stage_report(report_path, old_cards + keep_cards)
529
+ size = target.stat().st_size
530
+ try:
531
+ _append(target, keep_rows)
532
+ _commit_report(tmp, report_path)
533
+ tmp = None
534
+ except BaseException:
535
+ _cut_back(target, size)
536
+ raise
537
+ rep["rows_appended"] = len(keep_rows)
538
+ rep["cards_written"] = len(keep_cards)
539
+ rep["report"] = str(report_path)
540
+ for row in keep_rows:
541
+ _fn(rep, row["id"])["row"] = f"appended to {target.name}"
542
+ except cards.BadCard as e:
543
+ return done(EXIT_CONFIG, f"{e}. Nothing was kept.")
544
+ except LearnError as e:
545
+ return done(e.code, str(e))
546
+ except OSError as e:
547
+ return done(EXIT_CONFIG, f"I/O error: {e}. Nothing was kept (registry cut back to its old size).")
548
+ finally:
549
+ if tmp is not None:
550
+ Path(tmp).unlink(missing_ok=True)
551
+ os.close(bfd)
552
+ dup = len(rep["duplicates"])
553
+ return done(EXIT_OK, f"{rep['rows_appended']} row(s) appended, {rep['cards_written']} card(s) "
554
+ f"written, {dup} duplicate id(s) skipped")
555
+
556
+
557
+ def _fn(rep: dict, sid: str) -> dict:
558
+ return next(f for f in reversed(rep["functions"]) if f["id"] == sid) # the last def is the live one
559
+
560
+
561
+ def render(res: Learned) -> str:
562
+ r = res.report
563
+ out = [f"forgeproof learn {r['file']} --author={r['author']} (step {STAGE}: only chaos can PASS, parity-tested)"]
564
+ if "sha256" in r:
565
+ out.append(f" sha256 {r['sha256']}")
566
+ if "pool" in r and r["pool"].get("pool") == ghpool.POOL:
567
+ p = r["pool"]
568
+ out.append(f" pool github {p['repo']}@{p['commit'][:12]} {p['file']} ({p['lang']}, {p['licence']}, "
569
+ f"ratified by {', '.join(p['ratified_by'])}; trust {p['trust']['met']}/{p['trust']['known']} known)")
570
+ elif "pool" in r:
571
+ p = r["pool"]
572
+ out.append(f" pool corpus export {p['export']} item {p['item_id']} ({p['lang']})"
573
+ + (f"; same bytes also in {p['also']}" if p["also"] else ""))
574
+ if "target" in r:
575
+ out.append(f" target {r['target']}")
576
+ for f in r["functions"]:
577
+ out.append(f" {f['entry']}: {f.get('row', '')}")
578
+ for k, v in sorted(f["engines"].items()):
579
+ out.append(f" {k:<12} {v}")
580
+ for d in r["duplicates"]:
581
+ out.append(f" duplicate (skipped): {d}")
582
+ out.append(f"{res.outcome}")
583
+ return "\n".join(out)