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,214 @@
1
+ """The signed list of ratified GitHub repos (design v1.4.5 §12.5 D7-2a; build step 7 slice 2).
2
+
3
+ A ratified repo is one append-only JSON line of ``scout/trusted_repos.jsonl``, carrying its
4
+ pinned commit. Each line must be signed by the maintainer and by at least one crew seat
5
+ (DECISIONS-7-github G2, the maintainer 2026-11-14). Before any fetch, scout verifies every line against
6
+ the keys named in ``scout/allowed_signers`` and logs the verified key ids. An unsigned, unknown
7
+ or malformed line is BLIND(unsigned): never fetched, never read, never run.
8
+
9
+ Signatures: ``ssh-keygen -Y sign`` with Ed25519 keys, namespace ``forge-gate-ratify``. There is
10
+ no new Python dependency, and both hosts have OpenSSH >= 8.9.
11
+
12
+ What is signed: the line's CANONICAL bytes, the JSON of every field except ``signatures``
13
+ (sorted keys, no whitespace, ASCII). Any change to any field breaks every signature.
14
+
15
+ ``allowed_signers`` is stricter than OpenSSH's own format. Every line must be exactly
16
+ ``<principal> namespaces="forge-gate-ratify" ssh-ed25519 <base64> [comment]``. No other key
17
+ type, no other option (no cert-authority, no validity window), one key per principal, and one
18
+ principal per key.
19
+ """
20
+ from __future__ import annotations
21
+
22
+ import base64
23
+ import hashlib
24
+ import json
25
+ import re
26
+ import shutil
27
+ import subprocess
28
+ import tempfile
29
+ from dataclasses import dataclass, field
30
+ from pathlib import Path
31
+
32
+ NAMESPACE = "forge-gate-ratify"
33
+ REQUIRED_PRINCIPAL = "operator" # G2: one of the signatures must be the maintainer's
34
+ MIN_SIGNERS = 2 # D7-2a: the maintainer + at least one crew seat
35
+ FIELDS = ("org", "repo", "commit", "licence_spdx", "licence_blob", "host_set", "trust_signals",
36
+ "candidate_ref", "ratified_at")
37
+ _NAME = re.compile(r"^[A-Za-z0-9](?:[A-Za-z0-9._-]{0,98}[A-Za-z0-9])?$")
38
+ _HEX40 = re.compile(r"^[0-9a-f]{40}$")
39
+ _PRINCIPAL = re.compile(r"^[a-z][a-z0-9-]{0,31}$")
40
+ _SIGNER_LINE = re.compile(r'^([a-z][a-z0-9-]{0,31}) namespaces="forge-gate-ratify" ssh-ed25519 ([A-Za-z0-9+/]+={0,2})(?: .*)?$')
41
+
42
+
43
+ class BadSigners(ValueError):
44
+ """allowed_signers is malformed or breaks the one-key-per-principal rule."""
45
+
46
+
47
+ @dataclass(frozen=True)
48
+ class Signer:
49
+ principal: str
50
+ key_b64: str
51
+ key_id: str # sha256 of the key blob, first 16 hex: the id written into rows (ratified_by)
52
+
53
+
54
+ @dataclass
55
+ class Verdict:
56
+ line_no: int
57
+ ok: bool
58
+ reason: str = "" # why it is BLIND(unsigned), when not ok
59
+ fields: dict = field(default_factory=dict)
60
+ key_ids: list = field(default_factory=list)
61
+ principals: list = field(default_factory=list)
62
+
63
+ @property
64
+ def pin(self) -> str:
65
+ return f"{self.fields.get('org')}/{self.fields.get('repo')}@{self.fields.get('commit')}"
66
+
67
+
68
+ def key_id(key_b64: str) -> str:
69
+ return hashlib.sha256(base64.b64decode(key_b64)).hexdigest()[:16]
70
+
71
+
72
+ def load_signers(path: Path) -> dict[str, Signer]:
73
+ signers: dict[str, Signer] = {}
74
+ seen_keys: set[str] = set()
75
+ for n, raw in enumerate(Path(path).read_text().splitlines(), 1):
76
+ line = raw.strip()
77
+ if not line or line.startswith("#"):
78
+ continue
79
+ m = _SIGNER_LINE.fullmatch(line)
80
+ if not m:
81
+ raise BadSigners(f"{path}:{n}: not '<principal> namespaces=\"{NAMESPACE}\" ssh-ed25519 <key>'")
82
+ principal, key = m.groups()
83
+ try:
84
+ blob = base64.b64decode(key, validate=True)
85
+ except ValueError as e:
86
+ raise BadSigners(f"{path}:{n}: key is not base64: {e}") from None
87
+ if not blob.startswith(b"\x00\x00\x00\x0bssh-ed25519\x00\x00\x00\x20") or len(blob) != 51:
88
+ raise BadSigners(f"{path}:{n}: key blob is not exactly one ssh-ed25519 key (review F7)")
89
+ if principal in signers:
90
+ raise BadSigners(f"{path}:{n}: principal {principal!r} named twice (one key per principal)")
91
+ if blob in seen_keys: # decoded bytes, not the base64 text (review F7)
92
+ raise BadSigners(f"{path}:{n}: the same key under two principals")
93
+ seen_keys.add(blob)
94
+ signers[principal] = Signer(principal, key, key_id(key))
95
+ if not signers:
96
+ raise BadSigners(f"{path}: no signers")
97
+ return signers
98
+
99
+
100
+ def canonical(fields: dict) -> bytes:
101
+ """The bytes every signature covers: all fields except 'signatures'."""
102
+ body = {k: v for k, v in fields.items() if k != "signatures"}
103
+ return json.dumps(body, sort_keys=True, separators=(",", ":"), ensure_ascii=True).encode("ascii")
104
+
105
+
106
+ def check_fields(fields: dict, host_sets: dict | None = None) -> str:
107
+ """'' when the line's fields are well formed, else the reason."""
108
+ if not isinstance(fields, dict):
109
+ return "not a JSON object"
110
+ extra = set(fields) - set(FIELDS) - {"signatures"}
111
+ missing = [k for k in FIELDS if k not in fields]
112
+ if extra or missing:
113
+ return f"fields: missing {sorted(missing)}, unexpected {sorted(extra)}"
114
+ for k in ("org", "repo"):
115
+ if not isinstance(fields[k], str) or not _NAME.fullmatch(fields[k]) or ".." in fields[k]:
116
+ return f"{k} is not a plain GitHub name: {fields[k]!r}"
117
+ for k in ("commit", "licence_blob"):
118
+ if not isinstance(fields[k], str) or not _HEX40.fullmatch(fields[k]):
119
+ return f"{k} must be a full 40-hex sha: {fields[k]!r}"
120
+ if not isinstance(fields["licence_spdx"], str) or not fields["licence_spdx"].strip():
121
+ return "licence_spdx is empty"
122
+ if not isinstance(fields["trust_signals"], dict):
123
+ return "trust_signals must be an object"
124
+ for k in ("host_set", "candidate_ref", "ratified_at"):
125
+ if not isinstance(fields[k], str) or not fields[k]:
126
+ return f"{k} is empty"
127
+ if host_sets is not None and fields["host_set"] not in host_sets:
128
+ return f"host_set {fields['host_set']!r} is not a named host set"
129
+ return ""
130
+
131
+
132
+ def _ssh_verify(signers_file: Path, principal: str, data: bytes, sig: str) -> bool:
133
+ if shutil.which("ssh-keygen") is None:
134
+ return False
135
+ with tempfile.TemporaryDirectory() as d:
136
+ sf = Path(d) / "line.sig"
137
+ sf.write_text(sig)
138
+ try:
139
+ r = subprocess.run(["ssh-keygen", "-Y", "verify", "-f", str(signers_file), "-I", principal,
140
+ "-n", NAMESPACE, "-s", str(sf)], input=data, capture_output=True, timeout=30)
141
+ except (OSError, subprocess.TimeoutExpired):
142
+ return False
143
+ return r.returncode == 0
144
+
145
+
146
+ def verify_line(text: str, line_no: int, signers_file: Path, signers: dict[str, Signer],
147
+ host_sets: dict | None = None) -> Verdict:
148
+ try:
149
+ fields = json.loads(text)
150
+ except ValueError as e:
151
+ return Verdict(line_no, False, f"not JSON: {e}")
152
+ why = check_fields(fields, host_sets)
153
+ if why:
154
+ return Verdict(line_no, False, why, fields if isinstance(fields, dict) else {})
155
+ sigs = fields.get("signatures")
156
+ if not isinstance(sigs, list) or not sigs:
157
+ return Verdict(line_no, False, "no signatures", fields)
158
+ data = canonical(fields)
159
+ principals, key_ids, bad = [], [], []
160
+ for s in sigs:
161
+ if not isinstance(s, dict) or set(s) != {"signer", "sig"} or not isinstance(s.get("sig"), str):
162
+ bad.append("malformed signature entry")
163
+ continue
164
+ who = s["signer"]
165
+ if not isinstance(who, str) or who not in signers:
166
+ bad.append(f"unknown signer {who!r}")
167
+ continue
168
+ if who in principals:
169
+ bad.append(f"{who} signed twice")
170
+ continue
171
+ if _ssh_verify(signers_file, who, data, s["sig"]):
172
+ principals.append(who)
173
+ key_ids.append(signers[who].key_id)
174
+ else:
175
+ bad.append(f"bad signature by {who}")
176
+ if bad: # any bad entry poisons the line: a signer list is not a vote
177
+ return Verdict(line_no, False, "; ".join(bad), fields, key_ids, principals)
178
+ if REQUIRED_PRINCIPAL not in principals:
179
+ return Verdict(line_no, False, f"not signed by {REQUIRED_PRINCIPAL}", fields, key_ids, principals)
180
+ if len(set(key_ids)) < MIN_SIGNERS:
181
+ return Verdict(line_no, False, f"{len(set(key_ids))} distinct signer(s), need {MIN_SIGNERS}",
182
+ fields, key_ids, principals)
183
+ return Verdict(line_no, True, "", fields, key_ids, principals)
184
+
185
+
186
+ def verify_list(list_file: Path, signers_file: Path, host_sets: dict | None = None) -> list[Verdict]:
187
+ """Every line of the list, verified. Raises BadSigners when the signer file is unusable (no
188
+ line can then be trusted). A missing list file is an empty list."""
189
+ signers = load_signers(signers_file)
190
+ if not Path(list_file).exists():
191
+ return []
192
+ out = []
193
+ for n, raw in enumerate(Path(list_file).read_text().splitlines(), 1):
194
+ if raw.strip():
195
+ out.append(verify_line(raw, n, signers_file, signers, host_sets))
196
+ return out
197
+
198
+
199
+ def ratified(list_file: Path, signers_file: Path, org: str, repo: str, commit: str,
200
+ host_sets: dict | None = None) -> Verdict:
201
+ """The verified line for exactly org/repo@commit. A Verdict that is not ok when there is
202
+ none, or when the list or the signer file cannot be trusted (BLIND(unsigned))."""
203
+ try:
204
+ verdicts = verify_list(list_file, signers_file, host_sets)
205
+ except (OSError, BadSigners) as e:
206
+ return Verdict(0, False, f"signers unusable: {e}")
207
+ want = (org, repo, commit)
208
+ hits = [v for v in verdicts if (v.fields.get("org"), v.fields.get("repo"), v.fields.get("commit")) == want]
209
+ good = [v for v in hits if v.ok]
210
+ if good:
211
+ return good[-1]
212
+ if hits:
213
+ return hits[-1]
214
+ return Verdict(0, False, f"no line for {org}/{repo}@{commit}")
@@ -0,0 +1,448 @@
1
+ """`forgeproof scout <file>`, slice 1 (design v1.4.5 §5, build step 5): advisory only.
2
+
3
+ Python files; the corpus pool; the shape lens. No verdict, no `learn`, no registry write,
4
+ and no pool or query code executed: bodies are read as text. Every check ends FOUND,
5
+ LOOKED-CLEAN or BLIND(reason) (P1), and every run carries a control that must come back
6
+ FOUND.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import hashlib
11
+ import json
12
+ from pathlib import Path
13
+
14
+ from .. import config, ledger
15
+ from . import behaviour, box, corpus, embed, experience, ghsearch, intent_lens, meaning_lens, rule2, shape, shape_lens
16
+ from .outcomes import BLIND, FOUND, blind, clean, found
17
+
18
+ # §4a.4 rule 1: n is fixed BEFORE the query as the similarity lenses that apply to the
19
+ # pool. For the corpus pool: shape + language meaning (they read the same bytes and count
20
+ # once together), behaviour, intent. Only shape is built in slice 1.
21
+ CORPUS_LENSES = ("shape (+ language meaning, counted once)", "behaviour", "intent")
22
+ OTHER_POOLS = (("library", "signed"), ("registry", "tier")) # github: ghsearch (GitHub-lane S2)
23
+ LANG_BY_SUFFIX = {".py": "python"}
24
+
25
+
26
+ def _control_member(members):
27
+ """A deterministic pool member long enough to shingle: the run's planted case."""
28
+ for m in sorted(members, key=lambda m: m["item_id"]):
29
+ if len(shape.normalize(m["body"])) >= 40:
30
+ return m
31
+ return None
32
+
33
+
34
+ def run(path: Path, export_root: Path | None = None, intent: str | None = None,
35
+ gh_opts: dict | None = None) -> dict:
36
+ data = Path(path).read_bytes()
37
+ lang = LANG_BY_SUFFIX.get(Path(path).suffix)
38
+ rep = {"file": str(path), "language": lang or "unknown",
39
+ "sha256": hashlib.sha256(data).hexdigest(), "checks": {}, "related": {}, "change": None}
40
+ checks = rep["checks"]
41
+
42
+ # Rule 2: the lens is tested before it is trusted, on every run.
43
+ fails = rule2.evaluate(shape_lens.score, shape_lens.TAU, shape_lens.keyword_score)
44
+ checks["rule2-shape"] = (found(f"{len(fails)} case(s) failed", *fails) if fails
45
+ else clean("all known cases hold; lens may be switched on"))
46
+
47
+ intake = corpus.read_export(export_root)
48
+ checks["corpus-intake"] = intake.outcome
49
+ if intake.outcome.kind == FOUND:
50
+ checks["corpus-sha-recheck"] = clean(f"every file of {intake.run_id} matches its manifest")
51
+ checks["corpus-unreadable-items"] = (
52
+ found(f"{intake.unreadable} unreadable, over 10%: run flagged") if intake.flagged
53
+ else clean(f"{intake.unreadable} unreadable"))
54
+ elif intake.outcome.reason.startswith("sha-recheck"):
55
+ checks["corpus-sha-recheck"] = found(intake.outcome.reason)
56
+ else:
57
+ checks["corpus-sha-recheck"] = blind("no export read")
58
+
59
+ try:
60
+ query = data.decode("utf-8")
61
+ except UnicodeDecodeError:
62
+ query = None
63
+
64
+ members = [m for m in intake.items if m.get("lang") == lang] if lang else []
65
+ if fails:
66
+ shape_out = shape_lens.LensResult(blind("rule2-failed: lens not switched on"))
67
+ elif intake.outcome.kind != FOUND:
68
+ shape_out = shape_lens.LensResult(blind(f"corpus: {intake.outcome.reason}"))
69
+ elif lang is None:
70
+ shape_out = shape_lens.LensResult(blind(f"language: {Path(path).suffix or 'none'} not in slice 1 (python only)"))
71
+ elif query is None:
72
+ shape_out = shape_lens.LensResult(blind("unreadable: not UTF-8"))
73
+ else:
74
+ ctl = _control_member(members)
75
+ if ctl is None:
76
+ checks["control"] = blind("no pool member long enough to plant")
77
+ shape_out = shape_lens.LensResult(blind("control could not be planted"))
78
+ else:
79
+ c = shape_lens.rank(ctl["body"], members, pool=corpus.POOL, trust=corpus.TRUST)
80
+ ok = c.outcome.kind == FOUND and c.hits and c.hits[0].score == 1.0
81
+ checks["control"] = (found(f"planted {ctl['item_id']} came back at J=1.0") if ok
82
+ else blind(f"control-failed: planted {ctl['item_id']} came back {c.outcome.label()}"))
83
+ shape_out = (shape_lens.rank(query, members, pool=corpus.POOL, trust=corpus.TRUST) if ok
84
+ else shape_lens.LensResult(blind("control-failed")))
85
+ if "control" not in checks:
86
+ checks["control"] = blind("not run: " + shape_out.outcome.label())
87
+
88
+ # Behaviour (build step 6a): runs code, so only inside the isolation box, and only after its
89
+ # own Rule-2 set passes on this run.
90
+ beh = behaviour.BehaviourResult(blind("not run"))
91
+ why_box = box.available()
92
+ if why_box:
93
+ checks["rule2-behaviour"] = blind(why_box)
94
+ beh = behaviour.BehaviourResult(blind(why_box))
95
+ else:
96
+ bfails = behaviour.rule2()
97
+ checks["rule2-behaviour"] = (found(f"{len(bfails)} case(s) failed", *bfails) if bfails
98
+ else clean("all known cases hold; lens may be switched on"))
99
+ if bfails:
100
+ beh = behaviour.BehaviourResult(blind("rule2-failed: lens not switched on"))
101
+ elif intake.outcome.kind != FOUND:
102
+ beh = behaviour.BehaviourResult(blind(f"corpus: {intake.outcome.reason}"))
103
+ elif lang != "python" or query is None:
104
+ beh = behaviour.BehaviourResult(blind("query: not readable Python"))
105
+ else:
106
+ beh = behaviour.rank(query, members, pool=corpus.POOL, trust=corpus.TRUST)
107
+ mean = _meaning(query, intake, checks)
108
+ # Intent (8b s3): the person's stated purpose vs each member's purpose text. The corpus export
109
+ # carries none (DECISIONS-8b F8), so members reach the lens with no ``intent`` field: BLIND(no-input).
110
+ if intake.outcome.kind == FOUND or not intent:
111
+ inten = intent_lens.run_for(intent, intake.items, pool=corpus.POOL, trust=corpus.TRUST, checks=checks)
112
+ else: # 8b s3 review F5: the check row says why, on every path
113
+ checks["rule2-intent"] = blind(f"not run: corpus: {intake.outcome.reason}")
114
+ inten = intent_lens.LensResult(blind(f"corpus: {intake.outcome.reason}"))
115
+ rep["intent"] = intent
116
+ lenses = {"shape": shape_out.outcome, "meaning": mean.outcome, "behaviour": beh.outcome,
117
+ "intent": inten.outcome}
118
+ groups = {"shape+meaning": group_outcome(shape_out.outcome, mean.outcome), "behaviour": beh.outcome,
119
+ "intent": lenses["intent"]}
120
+ agree = sum(1 for o in groups.values() if o.kind == FOUND)
121
+ n_blind = sum(1 for o in groups.values() if o.kind == BLIND)
122
+ rep["related"]["corpus"] = {
123
+ "export": intake.run_id, "lenses": lenses, "groups": groups, "n": len(CORPUS_LENSES), "agree": agree,
124
+ "blind": n_blind, "shape_hits": [vars(h) for h in shape_out.hits], "looked_at": shape_out.looked_at,
125
+ "meaning_hits": [vars(h) for h in mean.hits], "meaning_scorer": mean.scorer,
126
+ "intent_hits": [vars(h) for h in inten.hits],
127
+ "behaviour_hits": [vars(h) for h in beh.hits], "behaviour_gates": beh.gates,
128
+ "skipped": [blind(f"newer export {r} not used: {w}") for r, w in intake.skipped]}
129
+ for pool, trust in OTHER_POOLS:
130
+ rep["related"][pool] = {"trust": trust, "outcome": blind("pool not in slice 1")}
131
+ # GitHub pool (GitHub-lane S2): the same shape lens over ratified, pin-checked text; its own
132
+ # planted control. Not exposed in the ledger (S2 DOC-GAP: exposure stays corpus-only).
133
+ gh = (ghsearch.GhResult(blind("rule2-failed: lens not switched on")) if fails
134
+ else ghsearch.search(query, lang=lang, **(gh_opts or {})))
135
+ checks["control-github"] = gh.control
136
+ rep["related"]["github"] = {"trust": ghsearch.TRUST, "outcome": gh.outcome,
137
+ "shape_hits": [vars(h) for h in gh.hits], "looked_at": gh.looked_at,
138
+ "repos": gh.repos, "seconds": gh.seconds}
139
+ rep["change"] = blind("no baseline: not built in slice 1")
140
+ checks["rule2-experience"], checks["experience"] = _experience(rep)
141
+ checks["exposure"] = _expose(rep)
142
+ return rep
143
+
144
+
145
+ def _experience(rep: dict):
146
+ """Lens 6 (8b s5): evidence beside each shown hit, never a vote (DECISIONS-8b H8, H9, H11).
147
+ Returns (its Rule-2 check, its outcome). Its Rule-2 set runs on every invocation, in memory."""
148
+ fails = experience.rule2()
149
+ r2 = (found(f"{len(fails)} case(s) failed: lens not switched on", *fails) if fails
150
+ else clean("all known cases hold and every selection-rewarding variant is red"))
151
+ if fails:
152
+ return r2, blind("rule2-failed: lens not switched on")
153
+ if not ledger.enabled():
154
+ return r2, blind(f"ledger-off: {config.LEDGER_KEY} unset; no outcome history to show")
155
+ try:
156
+ v = ledger.view()
157
+ except (ledger.LedgerError, config.NotConfigured) as e:
158
+ return r2, blind(f"ledger-unreadable: {e}")
159
+ # 8b s5 review F3 + re-check N1/N2: outcome rows that were written but not counted (refused or
160
+ # orphaned) with none accepted would read as 0 outcomes, which is a lie. Exposure refusals do not
161
+ # touch the counts, so they do not blind the lens.
162
+ lost = ledger.uncounted_outcomes(v)
163
+ if lost and not (v.marks or v.oracle):
164
+ return r2, blind(f"ledger-rows-refused: {lost} outcome row(s) refused, torn or orphaned, none accepted; "
165
+ "no count is shown", *(f"{f}:{n} {why}" for f, n, why in v.refused[:5]),
166
+ *(f"outcome line {n}: torn (an append in flight, or left by a killed writer; later "
167
+ "writes are refused until it is repaired)" for n in ledger.torn_outcome_lines(v)[:5]))
168
+ n, moved = experience.apply(rep["related"]["corpus"], v)
169
+ notes = [f"{len(v.orphans)} orphan, {len(v.refused)} refused, {len(v.torn)} torn row(s) not counted"]
170
+ if n:
171
+ return r2, found(f"{n} shown hit(s) have outcomes; {moved} list(s) reordered inside score+trust ties", *notes)
172
+ return r2, clean("no shown hit has an outcome yet", *notes)
173
+
174
+
175
+ def group_outcome(shape_o, meaning_o):
176
+ """Rule 1 / DECISIONS-8b H5: shape and language meaning read the same bytes and count ONCE
177
+ together. The group agrees if either is FOUND; it is BLIND only if both are BLIND."""
178
+ if FOUND in (shape_o.kind, meaning_o.kind):
179
+ return found("shape or meaning found", *(f"{n}: {o.label()}" for n, o in
180
+ (("shape", shape_o), ("meaning", meaning_o))))
181
+ if shape_o.kind == BLIND and meaning_o.kind == BLIND:
182
+ return blind("both shape and meaning blind")
183
+ return clean("neither shape nor meaning found")
184
+
185
+
186
+ def _meaning(query, intake, checks) -> meaning_lens.LensResult:
187
+ """Language meaning (build step 8b s2): its Rule-2 set runs on every invocation against the live
188
+ embedder; only a scorer that passes every case is switched on (DECISIONS-8b H2)."""
189
+ L = meaning_lens.LensResult
190
+ try:
191
+ emb = embed.get()
192
+ scorer, tried = meaning_lens.choose(emb)
193
+ except embed.EmbedError as e:
194
+ checks["rule2-meaning"] = blind(str(e))
195
+ return L(blind(str(e)))
196
+ if not scorer:
197
+ checks["rule2-meaning"] = found(
198
+ "every scorer failed: lens not switched on",
199
+ *(f"{sc}: {f}" for sc, fs in tried.items() for f in fs))
200
+ return L(blind("rule2-failed: lens not switched on (" +
201
+ ", ".join(f"{sc} {len(fs)} case(s)" for sc, fs in tried.items()) + ")"))
202
+ checks["rule2-meaning"] = clean(f"all known cases hold for scorer {scorer}; lens may be switched on")
203
+ if intake.outcome.kind != FOUND:
204
+ return L(blind(f"corpus: {intake.outcome.reason}"), scorer=scorer)
205
+ if query is None:
206
+ return L(blind("unreadable: not UTF-8"), scorer=scorer)
207
+ try:
208
+ cache = embed.read_cache(digest=emb.digest) # the file this embedder's fill wrote
209
+ ok, why = meaning_lens.control(intake.items, emb=emb, cache=cache, scorer=scorer)
210
+ checks["control-meaning"] = found(why) if ok else blind(f"control-failed: {why}")
211
+ if not ok:
212
+ return L(blind(f"control-failed: {why}"), scorer=scorer)
213
+ return meaning_lens.rank(query, intake.items, emb=emb, cache=cache, scorer=scorer,
214
+ pool=corpus.POOL, trust=corpus.TRUST)
215
+ except embed.EmbedError as e:
216
+ return L(blind(str(e)), scorer=scorer)
217
+
218
+
219
+ def embed_fill(export_root=None) -> tuple[int, str]:
220
+ """`forgeproof scout --embed-fill`: the ONLY writer of the vector cache (DECISIONS-8b H4). Fills
221
+ the switched-on scorer's text of every corpus item; refuses while the lens's Rule-2 set is red."""
222
+ try:
223
+ emb = embed.get()
224
+ scorer, tried = meaning_lens.choose(emb)
225
+ except embed.EmbedError as e:
226
+ return 2, f"embedder: {e}"
227
+ if not scorer:
228
+ return 2, ("the meaning lens is off (its Rule-2 set is red: " +
229
+ "; ".join(f"{sc}: {', '.join(fs)}" for sc, fs in tried.items()) + "): nothing to fill")
230
+ intake = corpus.read_export(export_root)
231
+ if intake.outcome.kind != FOUND:
232
+ return 2, f"corpus: {intake.outcome.label()}"
233
+ try:
234
+ use = meaning_lens.comparable(intake.items, scorer)
235
+ added, have = embed.fill([meaning_lens.lens_text(m["body"], scorer) for m in use], emb)
236
+ except (embed.EmbedError, config.NotConfigured) as e:
237
+ return 2, f"fill: {e}"
238
+ return 0, (f"export {intake.run_id}, scorer {scorer}: {added} embedded, {have} already cached, "
239
+ f"{len(intake.items) - len(use)} under {meaning_lens.MIN_WORDS} words skipped")
240
+
241
+
242
+ # Lens name in the ledger -> where its ranked hits sit in the report.
243
+ EXPOSED = (("shape", "shape_hits"), ("meaning", "meaning_hits"), ("behaviour", "behaviour_hits"),
244
+ ("intent", "intent_hits"))
245
+ # Scout is advisory: it waits at most this long for another ledger writer (8a s2 review F5).
246
+ EXPOSE_WAIT = 2.0
247
+ # The comment a handed-out snippet carries (V41-2): `#` unless the language uses `//`.
248
+ SLASH_LANGS = frozenset({"c", "cpp", "javascript", "typescript", "go", "rust", "java"})
249
+
250
+
251
+ def _expose(rep: dict):
252
+ """Writer ``scout-search`` (design §4a.5, build step 8a s2): every result this report SHOWS
253
+ gets one exposure row and a result id. Advisory: a ledger that is off or cannot be written
254
+ never changes the report's exit code; it shows as BLIND here (DECISIONS-8a G6)."""
255
+ c = rep["related"].get("corpus", {})
256
+ hits = [(h, {"lens": lens, "rank": rank, "score": h["score"], "pool": h["pool"], "trust": h["trust"],
257
+ "item": f"{h['pool']}:{h['item_id']}", "slot": h.get("slot", "top")})
258
+ for lens, key in EXPOSED for rank, h in enumerate(c.get(key) or [], 1)]
259
+ if not ledger.enabled():
260
+ return blind(f"ledger-off: {config.LEDGER_KEY} unset; nothing recorded")
261
+ if not hits:
262
+ return clean("no result shown; nothing to record")
263
+ try:
264
+ qid, rows = ledger.record_exposure(query_sha256=rep["sha256"], query_lang=rep["language"],
265
+ hits=[e for _, e in hits], wait=EXPOSE_WAIT)
266
+ except (ledger.LedgerError, config.NotConfigured, OSError) as e:
267
+ return blind(f"ledger-unwritable: {e}")
268
+ for (h, _), row in zip(hits, rows):
269
+ h["result_id"] = row["result_id"]
270
+ return found(f"query {qid}: {len(rows)} result(s) recorded")
271
+
272
+
273
+ def show(rid: str) -> tuple[int, str]:
274
+ """`forgeproof scout --show <result-id>`: hand out the code behind a result, with its result id
275
+ as the first line (V41-2). Reads only; showing or copying never scores (§4a.5)."""
276
+ if not ledger.RESULT_ID.fullmatch(rid or ""):
277
+ return 2, f"{rid!r} is not a result id (fgr-<query>-<lens>-<rank>)"
278
+ if not ledger.enabled():
279
+ return 2, f"the ledgers are off ({config.LEDGER_KEY} unset): result ids exist only in a ledger"
280
+ try:
281
+ row = ledger.view().exposure.get(rid)
282
+ except (ledger.LedgerError, config.NotConfigured) as e:
283
+ return 2, f"cannot read the exposure ledger: {e}"
284
+ if row is None:
285
+ return 2, f"{rid} is not in this host's exposure ledger"
286
+ pool, _, item_id = row["item"].partition(":")
287
+ if pool != corpus.POOL:
288
+ return 2, f"{rid}: pool {pool!r} is not handed out yet (8a: corpus only)"
289
+ intake = corpus.read_export()
290
+ if intake.outcome.kind != FOUND:
291
+ return 2, f"{rid}: corpus {intake.outcome.label()}"
292
+ m = next((i for i in intake.items if i["item_id"] == item_id), None)
293
+ if m is None:
294
+ return 2, f"{rid}: item {item_id} is not in the newest OK export {intake.run_id}"
295
+ if not _id_matches(item_id, m["body"]):
296
+ return 2, (f"{rid}: item {item_id} does not match its body's sha256 in export {intake.run_id}: "
297
+ "not handed out (the code might not be what was shown)")
298
+ mark = "//" if m.get("lang") in SLASH_LANGS else "#"
299
+ # An older id line inside the body (code handed out before, kept, and exported again) would
300
+ # credit that older result too: drop it, so the snippet names exactly one result (review F1).
301
+ lines = [ln for ln in m["body"].splitlines(keepends=True)
302
+ if not ledger.RESULT_COMMENT.fullmatch(ln.rstrip("\r\n"))]
303
+ if lines and not lines[-1].endswith("\n"):
304
+ lines[-1] += "\n"
305
+ head = f"{mark} forge-gate-result: {rid}\n"
306
+ at = 1 if lines and lines[0].startswith("#!") else 0 # keep a shebang first (review F6)
307
+ return 0, "".join(lines[:at] + [head] + lines[at:])
308
+
309
+
310
+ def _code_lines(text: str) -> list:
311
+ """Non-blank lines, stripped of indentation and trailing space, id comment lines dropped."""
312
+ return [ln.strip() for ln in text.splitlines()
313
+ if ln.strip() and not ledger.RESULT_COMMENT.fullmatch(ln.rstrip("\r\n"))]
314
+
315
+
316
+ def snippet_missing(rid: str, text: str) -> str:
317
+ """'' when the code behind ``rid`` is in ``text``, else why not (8a s3 review F1).
318
+
319
+ An oracle outcome credits the CODE, so the id comment alone is not enough: the handed-out
320
+ body's lines must appear in the file, contiguous, in order (indentation and blank lines may
321
+ differ, an edited line may not). Corpus items only; anything else cannot be checked."""
322
+ try:
323
+ row = ledger.view().exposure.get(rid)
324
+ except (ledger.LedgerError, config.NotConfigured) as e:
325
+ return f"cannot read the exposure ledger: {e}"
326
+ if row is None:
327
+ return f"{rid} is not in this host's exposure ledger"
328
+ pool, _, item_id = row["item"].partition(":")
329
+ if pool != corpus.POOL:
330
+ return f"pool {pool!r}: cannot check that its code is in the file"
331
+ intake = corpus.read_export()
332
+ if intake.outcome.kind != FOUND:
333
+ return f"cannot check that the code is in the file: corpus {intake.outcome.label()}"
334
+ m = next((i for i in intake.items if i["item_id"] == item_id), None)
335
+ if m is None or not _id_matches(item_id, m["body"]):
336
+ return f"cannot check that the code is in the file: item {item_id} not readable in {intake.run_id}"
337
+ want, have = _code_lines(m["body"]), _code_lines(text)
338
+ if not want:
339
+ return f"item {item_id} has no code lines"
340
+ n = len(want)
341
+ if any(have[i:i + n] == want for i in range(len(have) - n + 1)):
342
+ return ""
343
+ return f"the code of {item_id} is not in the file (the id comment alone does not count)"
344
+
345
+
346
+ def _id_matches(item_id: str, body: str) -> bool:
347
+ """A corpus item id is ``c_`` + the first 16 hex of sha256(body) (CODE-CORPUS-DESIGN §3; measured
348
+ on export 20261115T102505Z: 1431 of 1431)."""
349
+ return item_id == "c_" + hashlib.sha256(body.encode("utf-8")).hexdigest()[:16]
350
+
351
+
352
+ def _tail(h) -> str:
353
+ """What every hit line ends with: its slot label, its experience counts, its result id."""
354
+ t = " [explore: outside the top ranks]" if h.get("slot") == "explore" else ""
355
+ if h.get("_explore_none"):
356
+ t += f" [explore: none, only {h['_explore_none']} ranked, all shown]"
357
+ e = h.get("experience")
358
+ if e:
359
+ t += (f" experience: oracle {e['oracle']} · with-id {e['with_id']} · without-id {e['without_id']}"
360
+ f" · pending {e['pending']}")
361
+ return t + (f" id={h['result_id']}" if h.get("result_id") else "")
362
+
363
+
364
+ def _noted(hits) -> list:
365
+ """Copies of one shown list. A list with no explore hit says so on its last line (DECISIONS-8b
366
+ H10: a lens with too few ranked members has no explore slot AND SAYS SO; 8b crew review, 6E).
367
+ Copies, so rendering never changes the report."""
368
+ out = [dict(h) for h in hits or []]
369
+ if out and not any(h.get("slot") == "explore" for h in out):
370
+ out[-1]["_explore_none"] = len(out)
371
+ return out
372
+
373
+
374
+ def _lbl(o):
375
+ return o.label() + (f" {'; '.join(map(str, o.evidence))}" if o.evidence else "")
376
+
377
+
378
+ def render(rep: dict) -> str:
379
+ out = ["FORGEPROOF SCOUT REPORT — no verdict, advisory only",
380
+ "=" * 54, "",
381
+ f"file: {rep['file']} ({rep['language']})",
382
+ f"sha256: {rep['sha256']}", "", "CHECKS"]
383
+ for name, o in rep["checks"].items():
384
+ out.append(f" {name:<24} {_lbl(o)}")
385
+ out.append("RELATED")
386
+ c = rep["related"]["corpus"]
387
+ out.append(f" corpus (raw), export {c['export'] or '-'}: {c['agree']} of {c['n']} lenses agree, {c['blind']} BLIND")
388
+ for o in c["skipped"]: # 6E review S1-2: "newest usable", never silently "newest"
389
+ out.append(f" skipped {_lbl(o)}")
390
+ for name, o in c["lenses"].items():
391
+ out.append(f" {name:<10} {_lbl(o)}")
392
+ for h in _noted(c["shape_hits"]):
393
+ out.append(f" J={h['score']:.2f} {h['item_id']} pool={h['pool']} trust={h['trust']} kind={h['kind']} reason: shape shingles"
394
+ + _tail(h))
395
+ for h in _noted(c.get("meaning_hits")):
396
+ out.append(f" M={h['score']:.2f} {h['item_id']} pool={h['pool']} trust={h['trust']} lang={h['lang']} "
397
+ f"reason: same meaning ({c.get('meaning_scorer')} embedding)"
398
+ + _tail(h))
399
+ for h in _noted(c.get("intent_hits")):
400
+ out.append(f" I={h['score']:.2f} {h['item_id']} pool={h['pool']} trust={h['trust']} "
401
+ "reason: same stated purpose (intent embedding)" + _tail(h))
402
+ for h in _noted(c.get("behaviour_hits")): # 6E 6a pre-note: the pair is named, so it can be re-run
403
+ out.append(f" B={h['score']:.2f} {h['item_id']} pool={h['pool']} trust={h['trust']} kind={h['kind']} "
404
+ f"reason: same outputs on {h['agree']}/{h['considered']} inputs ({h['query_fn']} vs {h['cand_fn']})"
405
+ + _tail(h))
406
+ for pool in ("library", "registry"):
407
+ r = rep["related"][pool]
408
+ out.append(f" {pool} ({r['trust']}): {r['outcome'].label()}")
409
+ g = rep["related"]["github"]
410
+ out.append(f" github ({g['trust']}): {_lbl(g['outcome'])} [{g.get('looked_at', 0)} functions, "
411
+ f"{g.get('seconds', 0.0):.1f} s]")
412
+ for h in _noted(g.get("shape_hits")):
413
+ out.append(f" J={h['score']:.2f} {h['item_id']} pool={h['pool']} trust={h['trust']} kind={h['kind']} "
414
+ "reason: shape shingles" + _tail(h))
415
+ out.append(f"CHANGE {rep['change'].label()}")
416
+ out += ["", "NO VERDICT. This report tells you what the code DOES."]
417
+ return "\n".join(out)
418
+
419
+
420
+ def to_json(rep: dict) -> str:
421
+ def enc(o):
422
+ if hasattr(o, "label"):
423
+ return {"outcome": o.kind, "reason": o.reason, "label": o.label(), "evidence": list(o.evidence)}
424
+ raise TypeError(type(o))
425
+ return json.dumps(rep, default=enc, indent=1, ensure_ascii=False)
426
+
427
+
428
+ def check_report_outcomes(text: str) -> list[str]:
429
+ """§10.2 Rule 6 checker: every check/lens/pool line carries one of the three outcomes,
430
+ and no line prints an empty result."""
431
+ bad = []
432
+ in_block = False
433
+ for line in text.splitlines():
434
+ if line in ("CHECKS", "RELATED"):
435
+ in_block = True
436
+ continue
437
+ if line.startswith("CHANGE"):
438
+ in_block = False
439
+ if not any(k in line for k in ("FOUND", "LOOKED-CLEAN", "BLIND(")):
440
+ bad.append(line)
441
+ continue
442
+ if not in_block or not line.strip() or line.lstrip().startswith(("J=", "B=", "M=", "I=")):
443
+ continue
444
+ if line.strip().endswith(":") or "no related" in line.lower() or line.rstrip().endswith("[]"):
445
+ bad.append(line)
446
+ elif not any(k in line for k in ("FOUND", "LOOKED-CLEAN", "BLIND(")) and "lenses agree" not in line:
447
+ bad.append(line)
448
+ return bad