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,248 @@
1
+ """Scout over the GitHub pool (GitHub-lane loop 2026-11, slice S2; DESIGN §5 row S2).
2
+
3
+ `forgeproof scout <file>` shows functions from ratified GitHub repos that LOOK like the query,
4
+ through the same shape lens as the corpus pool. GitHub code is read as TEXT only: ``ast.parse``
5
+ turns it into a tree to find function spans, and nothing is imported, compiled to code or run.
6
+
7
+ Per query, in this order (the admission rules of ``ghpool.admit``, paid once instead of per file):
8
+ 1. the cache root and the signed list must exist; else BLIND(no-cache) / BLIND(unsigned);
9
+ 2. the signed list is verified ONCE (``ratify.verify_list``: every signature of every line is
10
+ checked once per query); no verified line → BLIND(unsigned);
11
+ 3. the host's trust pin (``FORGE_GATE_RATIFY_PIN``) must name the key that signed each line as
12
+ the required principal; ANY line that fails 2 or 3 makes the whole pool BLIND(unsigned) (review
13
+ F2: a dropped line must not read as a clean search);
14
+ 4. per verified line: ``ghcache.check_cache`` ONCE for that cache and one ``ls-tree``. Any
15
+ failure → the WHOLE pool is BLIND(pin-mismatch): a cache that fails its pin is not searched
16
+ around;
17
+ 5. the repo licence (allowlist + signed licence blob of every top-level licence file), as admit;
18
+ a repo that fails it is left out and listed;
19
+ 6. per file read: its git blob sha, recomputed from the bytes on disk, must equal the tree's
20
+ entry at the pin, else the WHOLE pool is BLIND(pin-mismatch); then inclusion and the file's
21
+ own licence marker, as admit (a file that fails them is left out and counted);
22
+ 7. a planted control: a deterministic member of the pool is ranked against the pool and must
23
+ come back FIRST, as itself, at J=1.0; else the pool is BLIND(control-failed);
24
+ 8. the shape lens ranks every member; its FOUND / LOOKED-CLEAN is the pool's outcome.
25
+
26
+ Each member is one function, named by its scout id ``scout:github:<org/repo>@<commit>:<path>::<qualname>``.
27
+ Hits print as ``pool=github trust=raw``. Wall time is measured and carried in the result.
28
+ """
29
+ from __future__ import annotations
30
+
31
+ import ast
32
+ import os
33
+ import stat
34
+ import time
35
+ from dataclasses import dataclass, field
36
+ from pathlib import Path, PurePosixPath
37
+
38
+ from .. import config
39
+ from . import fetchproxy, ghcache, ghpool, ratify, shape, shape_lens
40
+ from .ids import BadScoutId, make_id
41
+ from .outcomes import FOUND, Outcome, blind
42
+
43
+ POOL = ghpool.POOL # "github"
44
+ TRUST = "raw" # report.OTHER_POOLS: the GitHub pool's trust label
45
+ LANGS = {"python": ".py"} # the shape lens reads Python members only in this slice
46
+ CONTROL_MIN_TOKENS = 40 # as the corpus control: long enough to shingle reliably
47
+
48
+
49
+ @dataclass
50
+ class GhResult:
51
+ outcome: Outcome
52
+ hits: list = field(default_factory=list)
53
+ looked_at: int = 0
54
+ control: Outcome = field(default_factory=lambda: blind("not run"))
55
+ repos: list = field(default_factory=list) # one dict per verified line: what was read / left out
56
+ seconds: float = 0.0
57
+
58
+
59
+ def _functions(tree: ast.AST):
60
+ """(qualname, node) for every function, classes and enclosing functions joined by '.'."""
61
+ stack = [("", tree)]
62
+ while stack:
63
+ prefix, node = stack.pop()
64
+ for child in ast.iter_child_nodes(node):
65
+ if isinstance(child, (ast.FunctionDef, ast.AsyncFunctionDef)):
66
+ q = prefix + child.name
67
+ yield q, child
68
+ stack.append((q + ".", child))
69
+ elif isinstance(child, ast.ClassDef):
70
+ stack.append((prefix + child.name + ".", child))
71
+ else:
72
+ stack.append((prefix, child))
73
+
74
+
75
+ def members_of(text: str, org: str, repo: str, commit: str, path: str) -> list:
76
+ """The file's functions as pool members (text only). Raises SyntaxError and friends."""
77
+ tree = ast.parse(text, filename=path)
78
+ lines = text.splitlines(keepends=True)
79
+ out, seen = [], set()
80
+ for q, node in sorted(_functions(tree), key=lambda qn: (qn[1].lineno, qn[0])):
81
+ name = q if q not in seen else f"{q}#L{node.lineno}" # a redefined name keeps its own id
82
+ seen.add(q)
83
+ body = "".join(lines[node.lineno - 1:node.end_lineno])
84
+ out.append({"item_id": make_id(POOL, f"{org}/{repo}", commit, path, name), "body": body,
85
+ "lang": "python", "kind": "function"})
86
+ return out
87
+
88
+
89
+ def _read_pinned(tree_dir: Path, path: str, want_sha: str) -> bytes:
90
+ """One exported file's bytes, checked against its pinned blob (raises PinMismatch)."""
91
+ p = PurePosixPath(path)
92
+ if p.is_absolute() or ".." in p.parts or path != p.as_posix():
93
+ raise ghcache.PinMismatch(f"not a plain relative path: {path!r}")
94
+ f = tree_dir.joinpath(*p.parts)
95
+ try:
96
+ st = os.lstat(f)
97
+ if not stat.S_ISREG(st.st_mode):
98
+ raise ghcache.PinMismatch(f"{path} is not a regular file in the exported tree")
99
+ data = f.read_bytes()
100
+ except OSError as e:
101
+ raise ghcache.PinMismatch(f"{path}: unreadable: {e}") from None
102
+ if ghcache.blob_sha(data) != want_sha:
103
+ raise ghcache.PinMismatch(f"{path}: bytes differ from the pinned blob")
104
+ return data
105
+
106
+
107
+ def _repo_members(v: ratify.Verdict, root: Path, suffix: str, info: dict) -> list:
108
+ """Members of one verified line's cache. Raises PinMismatch for any pin failure; returns []
109
+ with ``info['left_out']`` set when the repo's licence does not admit it."""
110
+ org, repo, commit = v.fields["org"], v.fields["repo"], v.fields["commit"]
111
+ record = ghcache.check_cache(org, repo, commit, v, root=root) # ONCE per cache
112
+ store = root / ".objects" / org / f"{repo}.git"
113
+ tree_dir = root / org / f"{repo}@{commit}"
114
+ tree = ghcache.tree_files(store, commit) # one ls-tree
115
+ spdx = v.fields.get("licence_spdx")
116
+ present = [n for n in ghpool.LICENCE_FILES if n in tree]
117
+ if not ghpool.spdx_allowed(spdx or ""):
118
+ info["left_out"] = f"licence: {spdx!r} is not on the allowlist"
119
+ return []
120
+ if not present or any(tree[n][1] != v.fields.get("licence_blob") for n in present):
121
+ info["left_out"] = f"licence: top-level licence file(s) {present} are not all the signed blob"
122
+ return []
123
+ skipped = set(record.get("skipped") or [])
124
+ out, excluded, unparsable = [], {}, 0
125
+ for path in sorted(tree):
126
+ if PurePosixPath(path).suffix != suffix or path in skipped:
127
+ continue
128
+ why = ghpool.included(path, b"") # path rules first: no read needed
129
+ if not why:
130
+ data = _read_pinned(tree_dir, path, tree[path][1]) # per-file pin check
131
+ why = ghpool.included(path, data)
132
+ if not why:
133
+ try:
134
+ text = data.decode("utf-8")
135
+ except UnicodeDecodeError:
136
+ why = "not-included: not UTF-8 text"
137
+ else:
138
+ why = ghpool.file_licence(text)
139
+ if why:
140
+ k = why.split(":", 1)[0]
141
+ excluded[k] = excluded.get(k, 0) + 1
142
+ continue
143
+ info["files_read"] += 1
144
+ try:
145
+ out.extend(members_of(text, org, repo, commit, path))
146
+ except (SyntaxError, ValueError, RecursionError, MemoryError, BadScoutId):
147
+ unparsable += 1
148
+ info.update(members=len(out), excluded=excluded, unparsable=unparsable)
149
+ return out
150
+
151
+
152
+ def _control_member(members):
153
+ """The run's planted control: the first member by id that is long enough to shingle."""
154
+ for m in sorted(members, key=lambda m: m["item_id"]):
155
+ if len(shape.normalize(m["body"])) >= CONTROL_MIN_TOKENS:
156
+ return m
157
+ return None
158
+
159
+
160
+ def _memo_score():
161
+ """shape_lens.score with each text's shingles computed once per query (control + query share them)."""
162
+ memo: dict = {}
163
+
164
+ def sh(t):
165
+ s = memo.get(t)
166
+ if s is None:
167
+ s = memo[t] = shape.shingles(t)
168
+ return s
169
+ return lambda a, b: shape.jaccard(sh(a), sh(b))
170
+
171
+
172
+ def search(query: str | None, *, lang: str | None = "python", list_file: Path | None = None,
173
+ signers_file: Path | None = None, cache_root: Path | None = None,
174
+ host_sets_file: Path | None = None, trust_pin_value: str | None = None) -> GhResult:
175
+ t0 = time.monotonic()
176
+ res = _search(query, lang, list_file, signers_file, cache_root, host_sets_file, trust_pin_value)
177
+ res.seconds = round(time.monotonic() - t0, 3)
178
+ return res
179
+
180
+
181
+ def _search(query, lang, list_file, signers_file, cache_root, host_sets_file, trust_pin_value) -> GhResult:
182
+ R = GhResult
183
+ if lang not in LANGS:
184
+ return R(blind(f"language: {lang or 'unknown'} not searched in the GitHub pool (python only)"))
185
+ if query is None:
186
+ return R(blind("unreadable: not UTF-8"))
187
+ try:
188
+ root = Path(cache_root) if cache_root is not None else ghcache.cache_root()
189
+ except config.NotConfigured as e:
190
+ return R(blind(f"no-cache: {e}"))
191
+ if not root.is_dir():
192
+ return R(blind(f"no-cache: {root} does not exist on this host"))
193
+ if list_file is None or signers_file is None:
194
+ try:
195
+ found_list, found_signers = ghpool.list_files()
196
+ except config.NotConfigured as e:
197
+ return R(blind(f"unsigned: no signed list: {e}"))
198
+ list_file, signers_file = list_file or found_list, signers_file or found_signers
199
+ try:
200
+ sets, _ = fetchproxy.load_host_sets(host_sets_file or fetchproxy.HOST_SETS_FILE)
201
+ verdicts = ratify.verify_list(list_file, signers_file, sets) # ONCE per query
202
+ except (OSError, ValueError) as e: # BadSigners is a ValueError
203
+ return R(blind(f"unsigned: list or signers unusable: {e}"))
204
+ pin = ghpool.trust_pin(trust_pin_value if trust_pin_value is not None
205
+ else config.configured(ghpool.TRUST_PIN_KEY))
206
+ if pin is None or pin[0] != ratify.REQUIRED_PRINCIPAL:
207
+ return R(blind(f"unsigned: {ghpool.TRUST_PIN_KEY} must be set to "
208
+ f"'{ratify.REQUIRED_PRINCIPAL}=<key id>' in the host's config"))
209
+ use, refused = {}, []
210
+ for v in verdicts:
211
+ if not v.ok:
212
+ refused.append(f"line {v.line_no}: {v.reason}")
213
+ elif dict(zip(v.principals, v.key_ids)).get(pin[0]) != pin[1]:
214
+ refused.append(f"line {v.line_no}: {pin[0]}'s key is not the host's pinned {pin[1]}")
215
+ else: # every line passed (any refused line blinds the pool below); the last for a pin wins
216
+ use[(v.fields["org"], v.fields["repo"], v.fields["commit"])] = v
217
+ if not use:
218
+ return R(blind(f"unsigned: no verified line ({len(verdicts)} in the list)", *refused[:5]))
219
+ if refused: # review F2/F7: a refused line is never searched around; it would read as clean
220
+ return R(blind(f"unsigned: {len(refused)} line(s) of the list refused; the pool is not searched "
221
+ "until the list verifies", *refused[:5]))
222
+ members, repos = [], []
223
+ for (org, repo, commit), v in sorted(use.items()):
224
+ info = {"repo": f"{org}/{repo}@{commit}", "line": v.line_no, "files_read": 0}
225
+ repos.append(info)
226
+ try:
227
+ members += _repo_members(v, root, LANGS[lang], info)
228
+ except ghcache.PinMismatch as e:
229
+ return R(blind(f"pin-mismatch: {org}/{repo}@{commit[:12]}: {e}"), repos=repos)
230
+ ev = [f"{i['repo'][:-28]}: " + (i.get("left_out") or
231
+ f"{i['members']} functions from {i['files_read']} files, "
232
+ f"{i['unparsable']} unparsable, left out {i['excluded']}")
233
+ for i in repos] + [f"not used: {r}" for r in refused[:5]]
234
+ ctl = _control_member(members)
235
+ if ctl is None:
236
+ return R(blind("control-failed: no pool member long enough to plant", *ev),
237
+ control=blind("control-failed: no pool member long enough to plant"), repos=repos)
238
+ sc = _memo_score()
239
+ c = shape_lens.rank(ctl["body"], members, pool=POOL, trust=TRUST, scorer=sc)
240
+ ok = (c.outcome.kind == FOUND and c.hits and c.hits[0].item_id == ctl["item_id"]
241
+ and c.hits[0].score == 1.0)
242
+ if not ok:
243
+ why = f"control-failed: planted {ctl['item_id']} came back {c.outcome.label()}"
244
+ return R(blind(why, *ev), control=blind(why), repos=repos)
245
+ control = Outcome(FOUND, "", (f"planted {ctl['item_id']} came back first at J=1.0",))
246
+ out = shape_lens.rank(query, members, pool=POOL, trust=TRUST, scorer=sc)
247
+ return R(Outcome(out.outcome.kind, out.outcome.reason, out.outcome.evidence + tuple(ev)),
248
+ out.hits, out.looked_at, control, repos)
@@ -0,0 +1,82 @@
1
+ """Scout's namespaced ids (design v1.4.5 §4.4.1 item 3, build step 3a).
2
+
3
+ A scout id names exactly one function at one commit of one source:
4
+
5
+ scout:<pool>:<source>@<commit>:<path>::<function>
6
+
7
+ Every component is percent-encoded with nothing left safe, so ``/``, ``:`` and ``@``
8
+ never appear inside a component. Two consequences, both tested:
9
+
10
+ 1. The id has no ``/`` at all. The Brain's honest_pass joins validator cards to rows
11
+ by ``stem()`` = basename minus the last extension (honest_pass.py:21-23). On a raw
12
+ ``…/Lib/urllib/request.py:urlopen`` that yields ``request`` and the card would back
13
+ any library row called ``request`` (F41's new hazard). On a scout id, ``stem()``
14
+ can only trim text after the last dot; the ``scout:`` prefix always survives, so a
15
+ scout id never reduces to a bare stem, even through code that ignores D7-5.
16
+ 2. Ids are compared verbatim (D7-5 item 2). ``parse_id`` is exact: it rejects anything
17
+ ``make_id`` would not produce, so two ids that differ by one character never match.
18
+ """
19
+ from __future__ import annotations
20
+
21
+ import re
22
+ from dataclasses import dataclass
23
+ from urllib.parse import quote, unquote
24
+
25
+ PREFIX = "scout"
26
+ POOLS = frozenset({"corpus", "github"}) # §4a: the corpus lane and the GitHub lane (step 7)
27
+ # A full git object id (40 hex, or 64 in a SHA-256 repo) or a corpus export stamp. Never an
28
+ # abbreviated hash: one commit must have exactly one id, or a card and its row stop joining
29
+ # (6E review B3a-1).
30
+ _COMMIT = re.compile(r"^[0-9a-f]{40}$|^[0-9a-f]{64}$|^[0-9]{8}T[0-9]{6}Z$")
31
+ _ID = re.compile(r"^scout:([^:/@]+):([^:/@]+)@([^:/@]+):([^:/@]+)::([^:/@]+)$")
32
+
33
+
34
+ class BadScoutId(ValueError):
35
+ """An id or id component scout must not emit or accept."""
36
+
37
+
38
+ @dataclass(frozen=True)
39
+ class ScoutId:
40
+ pool: str # "corpus" | "github"
41
+ source: str # corpus id, or GitHub "owner/repo"
42
+ commit: str # git commit hash, or corpus export stamp (e.g. 20261111T130229Z)
43
+ path: str # file path inside the source, "/"-separated, relative
44
+ function: str # qualified function name, e.g. "Request.get_method"
45
+
46
+ def __str__(self) -> str:
47
+ return make_id(self.pool, self.source, self.commit, self.path, self.function)
48
+
49
+
50
+ def _enc(part: str, what: str) -> str:
51
+ if not isinstance(part, str) or not part or part != part.strip():
52
+ raise BadScoutId(f"{what} must be a non-empty string without outer spaces: {part!r}")
53
+ return quote(part, safe="")
54
+
55
+
56
+ def make_id(pool: str, source: str, commit: str, path: str, function: str) -> str:
57
+ if pool not in POOLS:
58
+ raise BadScoutId(f"pool {pool!r} not in {sorted(POOLS)}")
59
+ if not _COMMIT.match(commit or ""):
60
+ raise BadScoutId(f"commit {commit!r} is neither a git hash nor an export stamp")
61
+ if path.startswith("/") or "\\" in path or any(p in ("", ".", "..") for p in path.split("/")):
62
+ raise BadScoutId(f"path {path!r} must be relative, '/'-separated, without '.' or '..' parts")
63
+ return (f"{PREFIX}:{_enc(pool, 'pool')}:{_enc(source, 'source')}@{_enc(commit, 'commit')}"
64
+ f":{_enc(path, 'path')}::{_enc(function, 'function')}")
65
+
66
+
67
+ def parse_id(text: str) -> ScoutId:
68
+ m = _ID.match(text) if isinstance(text, str) else None
69
+ if not m:
70
+ raise BadScoutId(f"not a scout id: {text!r}")
71
+ sid = ScoutId(*(unquote(g) for g in m.groups()))
72
+ if make_id(sid.pool, sid.source, sid.commit, sid.path, sid.function) != text:
73
+ raise BadScoutId(f"not in canonical form: {text!r}") # e.g. '%2f' vs '%2F'
74
+ return sid
75
+
76
+
77
+ def is_scout_id(text: str) -> bool:
78
+ try:
79
+ parse_id(text)
80
+ return True
81
+ except BadScoutId:
82
+ return False
@@ -0,0 +1,170 @@
1
+ """Lens 5, intent (design §4a.3; build step 8b s3; DECISIONS-8b H6, H7).
2
+
3
+ "Related" means written for the same purpose. Intent compares PURPOSE TEXTS only, never code: the
4
+ query's purpose is what the person states (``forgeproof scout FILE --intent "TEXT"``); a member's is
5
+ its pool's intent field (corpus = the scrubbed request, library = the pattern's description, GitHub =
6
+ docstrings + commit message). Today no pool scout searches carries one (DECISIONS-8b F7, F8): the
7
+ corpus export has no request text, and the library and GitHub are not scout pools yet. So on a real
8
+ run this lens is BLIND: rule2-failed on the deploy host whenever --intent is given (no tau separates its
9
+ set on the pinned model, KD-15 m), and no-input for every pool until a pool supplies purpose text.
10
+
11
+ Score = cosine of the pinned local embedder's vectors of the two purpose texts. The Rule-2 set
12
+ (written first, H7) runs before the lens is used; a red set means BLIND(rule2-failed).
13
+ """
14
+ from __future__ import annotations
15
+
16
+ from dataclasses import dataclass, field
17
+
18
+ from . import embed, meaning_lens, rule2, shape_lens, slots
19
+ from .outcomes import Outcome, blind, clean, found
20
+
21
+ NAME = "intent"
22
+ # NOT calibrated: no tau passes this set on the pinned model. Live on the deploy host (2026-11-16,
23
+ # digest 0a109f422b47): min same-purpose cos 0.579 (backup_py~backup_rsync) < max must-not cos 0.599
24
+ # (keyword trap -> backup_rsync), separation -0.020. The set is red at every tau and the lens ships OFF
25
+ # (BLIND rule2-failed), like meaning (KD-15 m). 0.75 is the builder's prior, kept so the red stays loud.
26
+ TAU = 0.75
27
+ MIN_WORDS = 3
28
+ TEXT_MAX = 2000
29
+
30
+ # ---------------------------------------------------------------- Rule 2 (H7), written first
31
+
32
+ DISKALERT_PY = """import shutil
33
+ for mount in ("/", "/home"):
34
+ u = shutil.disk_usage(mount)
35
+ if u.used / u.total > 0.9:
36
+ print("ALERT", mount)
37
+ """
38
+
39
+ DISKALERT_SH = """df -P | awk 'NR>1 && $5+0 > 90 {print "ALERT", $6}'
40
+ """
41
+
42
+ # The code each purpose belongs to (shape and the keyword baseline are measured on it in the tests,
43
+ # to show the only-intent pair is invisible to them); intent itself reads only REQUESTS.
44
+ CODE = dict(meaning_lens.POOL, diskalert_py=DISKALERT_PY, diskalert_sh=DISKALERT_SH)
45
+
46
+ # One request per pool member, written by the builder (the crew review should attack these).
47
+ REQUESTS = {
48
+ "backup_tar": "back up my home folder every night into a dated tarball and throw away copies older than two weeks",
49
+ "backup_py": "python script that archives a source directory to a timestamped gzip file in a target "
50
+ "folder and deletes archives more than fourteen days old",
51
+ "backup_rsync": "keep a daily backup copy of a directory using rsync snapshots with hard links",
52
+ "area": "return the area of a rectangle given its width and height, rejecting negative sides",
53
+ "kmeans": "assign each point to its nearest cluster centre",
54
+ "json_stats": "summarise a JSON file of transactions: row count, total and mean amount",
55
+ "errcount_py": "count the ERROR lines in each log file and list the files with the most errors first",
56
+ "errcount_sh": "for every log I pass, tell me how many errors it has, worst first",
57
+ "diskalert_py": "warn me when a disk is almost full",
58
+ "diskalert_sh": "send an alert if any filesystem goes above ninety percent used",
59
+ }
60
+ GROUPS = {"backup": ("backup_tar", "backup_py", "backup_rsync"), "errcount": ("errcount_py", "errcount_sh"),
61
+ "diskalert": ("diskalert_py", "diskalert_sh")}
62
+ MUST_NOT = {
63
+ "same look, other purpose (tax vs area)": "compute the sales tax owed on a price at a given rate, rejecting negative inputs",
64
+ "null (a stack)": "a last-in first-out stack with push and pop",
65
+ "keyword trap (lists backups)": "list my backup archives by size",
66
+ }
67
+
68
+
69
+ def rule2_cases(score, tau: float, baseline=None) -> list:
70
+ """Failed cases for ``score(a, b)`` over purpose texts (empty = may be switched on)."""
71
+ fails = []
72
+
73
+ def ranked(q, exclude=None):
74
+ return sorted(((score(q, t), n) for n, t in REQUESTS.items() if n != exclude), key=lambda x: (-x[0], x[1]))
75
+ # 1. same purpose / different look (and different words): partners first, at or above tau. The
76
+ # diskalert pair is the only-intent case: its code shares nothing (shape and keyword miss it).
77
+ for g, names in GROUPS.items():
78
+ for n in names:
79
+ want = set(names) - {n}
80
+ r = ranked(REQUESTS[n], exclude=n)[:len(want)]
81
+ if {name for _, name in r} != want or any(s < tau for s, _ in r):
82
+ fails.append(f"same-purpose: {n}'s top {len(want)} are {[f'{name} {s:.3f}' for s, name in r]}; "
83
+ f"must be {sorted(want)} >= {tau}")
84
+ # 2. same look / different purpose, the null case, the keyword trap: nothing at or above tau.
85
+ for what, q in MUST_NOT.items():
86
+ s, n = ranked(q)[0]
87
+ if s >= tau:
88
+ fails.append(f"{what}: matched {n} at {s:.3f} >= {tau}")
89
+ # 3. the keyword baseline over the same purpose texts must separate worse; the trap must lure it.
90
+ # NOTE (8b s2 review F1): with tau between them, the cases above force the lens's separation
91
+ # above 0 while the baseline's is negative on these fixtures, so 'beats the baseline' is IMPLIED
92
+ # by them here and is not separate evidence (KD-15 j). The trap-lure check is independent.
93
+ if baseline is not None:
94
+ sep_l, sep_b = separation(score), separation(baseline)
95
+ if not sep_l > sep_b:
96
+ fails.append(f"baseline: lens separation {sep_l:.3f} does not beat the keyword baseline's {sep_b:.3f}")
97
+ trap = MUST_NOT["keyword trap (lists backups)"]
98
+ if not max((baseline(trap, t), n) for n, t in REQUESTS.items())[1].startswith("backup"):
99
+ fails.append("baseline: the keyword trap did not lure the baseline; the trap tests nothing")
100
+ return fails
101
+
102
+
103
+ def separation(score) -> float:
104
+ pos = [score(REQUESTS[a], REQUESTS[b]) for names in GROUPS.values()
105
+ for i, a in enumerate(names) for b in names[i + 1:]]
106
+ neg = [score(q, t) for q in MUST_NOT.values() for t in REQUESTS.values()]
107
+ return min(pos) - max(neg)
108
+
109
+
110
+ def _texts() -> list:
111
+ return [t[:TEXT_MAX] for t in list(REQUESTS.values()) + list(MUST_NOT.values())]
112
+
113
+
114
+ def rule2_run(emb) -> list:
115
+ texts = _texts()
116
+ vecs = dict(zip(texts, emb.embed(texts)))
117
+ return rule2_cases(lambda a, b: embed.cosine(vecs[a[:TEXT_MAX]], vecs[b[:TEXT_MAX]]), TAU,
118
+ shape_lens.keyword_score)
119
+
120
+
121
+ # ---------------------------------------------------------------- the lens
122
+
123
+ @dataclass
124
+ class LensResult:
125
+ outcome: Outcome
126
+ hits: list = field(default_factory=list)
127
+ looked_at: int = 0
128
+
129
+
130
+ def rank(intent: str, members: list, *, emb, pool: str, trust: str) -> LensResult:
131
+ """members: dicts with item_id and ``intent`` (the pool's purpose text). A member without one is
132
+ not compared; if none has one, the pool gives BLIND(no-input), never 'unrelated'."""
133
+ if len((intent or "").split()) < MIN_WORDS:
134
+ return LensResult(blind(f"no-input: the stated intent has fewer than {MIN_WORDS} words"))
135
+ usable = [m for m in members if isinstance(m.get("intent"), str) and len(m["intent"].split()) >= MIN_WORDS]
136
+ if not usable:
137
+ return LensResult(blind(f"no-input: no {pool} member carries purpose text"))
138
+ vecs = emb.embed([intent[:TEXT_MAX]] + [m["intent"][:TEXT_MAX] for m in usable])
139
+ q, rest = vecs[0], vecs[1:]
140
+ hits = [shape_lens.Hit(m["item_id"], round(embed.cosine(q, v), 4), pool, trust, m.get("lang", ""),
141
+ m.get("kind", "")) for m, v in zip(usable, rest)]
142
+ hits.sort(key=lambda h: (-h.score, h.item_id))
143
+ top, explore = slots.split(hits, lens=NAME, query=intent)
144
+ over = [h for h in top if h.score >= TAU]
145
+ note = f" ({len(members) - len(usable)} member(s) without purpose text not compared)" if len(usable) < len(members) else ""
146
+ shown = top + ([explore] if explore else [])
147
+ if over:
148
+ return LensResult(found(f"{len(over)} at or above cos={TAU}{note}"), shown, len(usable))
149
+ return LensResult(clean(f"best cos={top[0].score} < {TAU}{note}"), shown, len(usable))
150
+
151
+
152
+ def run_for(intent, members: list, *, pool: str, trust: str, checks: dict) -> LensResult:
153
+ """The report's entry point: stated intent -> embedder -> Rule 2 -> the pool's purpose texts."""
154
+ if not intent:
155
+ checks["rule2-intent"] = blind("not run: no stated intent (give --intent \"TEXT\")")
156
+ return LensResult(blind("no-input: no stated intent (give --intent \"TEXT\")"))
157
+ try:
158
+ emb = embed.get()
159
+ fails = rule2_run(emb)
160
+ except embed.EmbedError as e:
161
+ checks["rule2-intent"] = blind(str(e))
162
+ return LensResult(blind(str(e)))
163
+ if fails:
164
+ checks["rule2-intent"] = found(f"{len(fails)} case(s) failed: lens not switched on", *fails)
165
+ return LensResult(blind(f"rule2-failed: lens not switched on ({len(fails)} case(s))"))
166
+ checks["rule2-intent"] = clean("all known cases hold; lens may be switched on")
167
+ try:
168
+ return rank(intent, members, emb=emb, pool=pool, trust=trust)
169
+ except embed.EmbedError as e:
170
+ return LensResult(blind(str(e)))