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,395 @@
1
+ """The private pinned GitHub cache and its pin check (design v1.4.5 §12.5 D7-2c; build step 7
2
+ slice 3; DECISIONS-7-github G3).
3
+
4
+ Layout under ``$FORGE_GATE_SCOUT_DIR/github-cache/``:
5
+ - ``.objects/<org>/<repo>.git``: a bare object store WE create. The fetch box hands back only
6
+ its ``objects/`` files and ``shallow``; nothing it wrote is run or read as git config, hooks
7
+ or refs.
8
+ - ``<org>/<repo>@<commit>/``: the tree exported from that store at the pin, read-only. Regular
9
+ files only; symlinks and anything else are left out and listed.
10
+ - ``<org>/<repo>@<commit>.pin.json``: {commit, tree, line_sha256, files, skipped, built_at}.
11
+
12
+ The pin check (any difference is BLIND(pin-mismatch), until the cache is rebuilt):
13
+ - WHOLE CACHE (:func:`check_cache`, before any lens reads):
14
+ - the pin file names this commit;
15
+ - the commit is in the store, with the recorded tree;
16
+ - the pin file's ``line_sha256`` equals the CURRENTLY verified signed line's hash.
17
+ - ``full=True`` also requires the exported files to equal the tree, path for path and blob
18
+ for blob. It runs at build time and on demand.
19
+ - PER FILE (:func:`read_file`, at every read): the file's git blob sha, recomputed from the
20
+ bytes on disk, equals the tree's entry at the pin.
21
+
22
+ Every git call is hardened:
23
+ - no system/global config, no hooks;
24
+ - ``protocol.allow=never`` except ``file`` for a local carry, so git can never reach a network
25
+ from here;
26
+ - no terminal prompt, no lazy fetch.
27
+
28
+ Failure contract (step-7 crew review, 6E F1-F3): every failure of :func:`build` and of the checks is
29
+ a PinMismatch, never a bare OSError, a timeout or a parse error, so a caller that catches PinMismatch reports
30
+ BLIND instead of dying. One build at a time per cache root (a ``flock`` on ``.build.lock``).
31
+
32
+ Derived and rebuildable: never in git, never in the public repo (standard §4).
33
+ """
34
+ from __future__ import annotations
35
+
36
+ import fcntl
37
+ import hashlib
38
+ import json
39
+ import os
40
+ import re
41
+ import shutil
42
+ import stat
43
+ import subprocess
44
+ import tempfile
45
+ import time
46
+ from dataclasses import dataclass
47
+ from pathlib import Path, PurePosixPath
48
+
49
+ from .. import config
50
+ from . import ratify
51
+
52
+ _HEX40 = re.compile(r"^[0-9a-f]{40}$")
53
+ _LSTREE = re.compile(r"^(\d{6}) (blob|tree|commit) ([0-9a-f]{40})\t(.+)$")
54
+ # 6E F4: the carried-copy path has no box in front, so ghcache bounds what it copies itself. Same
55
+ # figure as box.KEEP_MAX_BYTES. A depth-1 fetch writes one line to `shallow`; 64 KiB holds ~1600.
56
+ MAX_STORE_BYTES = 1 << 30
57
+ MAX_SHALLOW_BYTES = 64 * 1024
58
+ _NOFOLLOW = getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0)
59
+
60
+
61
+ class PinMismatch(Exception):
62
+ """The cache does not match its pin or the verified line: BLIND(pin-mismatch)."""
63
+
64
+
65
+ def cache_root() -> Path:
66
+ return config.scout_dir() / "github-cache"
67
+
68
+
69
+ def _paths(root: Path, org: str, repo: str, commit: str) -> tuple[Path, Path, Path]:
70
+ for part in (org, repo):
71
+ if not ratify._NAME.fullmatch(part) or ".." in part:
72
+ raise PinMismatch(f"not a plain GitHub name: {part!r}")
73
+ if not _HEX40.fullmatch(commit):
74
+ raise PinMismatch(f"commit must be 40 hex: {commit!r}")
75
+ return (root / ".objects" / org / f"{repo}.git", root / org / f"{repo}@{commit}",
76
+ root / org / f"{repo}@{commit}.pin.json")
77
+
78
+
79
+ def git(store: Path, *args: str, input: bytes | None = None, allow_file: bool = False,
80
+ timeout: float = 600) -> subprocess.CompletedProcess:
81
+ with tempfile.TemporaryDirectory() as home:
82
+ env = {"PATH": os.environ.get("PATH", "/usr/bin:/bin"), "HOME": home, "GIT_CONFIG_NOSYSTEM": "1",
83
+ "GIT_CONFIG_GLOBAL": os.devnull, "GIT_TERMINAL_PROMPT": "0", "GIT_NO_LAZY_FETCH": "1",
84
+ "GIT_ATTR_NOSYSTEM": "1", "LC_ALL": "C"}
85
+ cmd = ["git", "-c", "core.hooksPath=" + os.devnull, "-c", "protocol.allow=never",
86
+ "-c", f"protocol.file.allow={'always' if allow_file else 'never'}",
87
+ "-c", "safe.directory=" + str(store), "--git-dir", str(store), *args]
88
+ try:
89
+ return subprocess.run(cmd, input=input, capture_output=True, env=env, timeout=timeout)
90
+ except subprocess.TimeoutExpired: # 6E F2
91
+ raise PinMismatch(f"git {args[0] if args else ''}: no answer within {timeout:g} s") from None
92
+ except OSError as e:
93
+ raise PinMismatch(f"git {args[0] if args else ''}: could not run: {e}") from None
94
+
95
+
96
+ def _ok(r: subprocess.CompletedProcess, what: str) -> bytes:
97
+ if r.returncode != 0:
98
+ raise PinMismatch(f"{what}: git exit {r.returncode}: {r.stderr.decode(errors='replace')[-300:]}")
99
+ return r.stdout
100
+
101
+
102
+ def blob_sha(data: bytes) -> str:
103
+ return hashlib.sha1(b"blob %d\0" % len(data) + data).hexdigest()
104
+
105
+
106
+ def line_sha256(verdict: ratify.Verdict) -> str:
107
+ return hashlib.sha256(ratify.canonical(verdict.fields)).hexdigest()
108
+
109
+
110
+ def tree_files(store: Path, commit: str) -> dict[str, tuple[str, str]]:
111
+ """{path: (mode, blob sha)} for every blob in the commit's tree (recursive)."""
112
+ out = _ok(git(store, "ls-tree", "-r", "--full-tree", "-z", commit), "ls-tree")
113
+ files = {}
114
+ for rec in out.split(b"\0"):
115
+ if not rec:
116
+ continue
117
+ m = _LSTREE.fullmatch(rec.decode("utf-8", "surrogateescape"))
118
+ if not m:
119
+ raise PinMismatch(f"unparsable ls-tree record: {rec[:120]!r}")
120
+ mode, kind, sha, path = m.groups()
121
+ if kind == "blob":
122
+ files[path] = (mode, sha)
123
+ return files
124
+
125
+
126
+ def _copy_regular(src: Path, dst: Path, budget: int | None = None) -> int:
127
+ """Copy one REGULAR file; a symlink or anything else (even one swapped in after a check) is
128
+ skipped. O_NOFOLLOW + fstat on the open descriptor (review F8). Returns the bytes copied;
129
+ more than ``budget`` is a PinMismatch (6E F4)."""
130
+ try:
131
+ # O_NONBLOCK: a FIFO planted in the fetched store must not hang the open (mutant C5)
132
+ fd = os.open(src, os.O_RDONLY | _NOFOLLOW)
133
+ except OSError:
134
+ return 0
135
+ n, budget = 0, MAX_STORE_BYTES if budget is None else budget
136
+ try:
137
+ if not stat.S_ISREG(os.fstat(fd).st_mode):
138
+ return 0
139
+ with os.fdopen(fd, "rb", closefd=False) as fh, open(dst, "xb") as out:
140
+ while chunk := fh.read(1 << 20):
141
+ n += len(chunk)
142
+ if n > budget:
143
+ raise PinMismatch(f"the fetched store is over {MAX_STORE_BYTES} bytes")
144
+ out.write(chunk)
145
+ finally:
146
+ os.close(fd)
147
+ return n
148
+
149
+
150
+ def _import_objects(kept: Path, store: Path) -> None:
151
+ """Copy ONLY object files and the shallow list from an untrusted store into ours."""
152
+ used = 0
153
+ src_objects = kept / "objects"
154
+ if not src_objects.is_dir() or src_objects.is_symlink():
155
+ raise PinMismatch(f"no objects/ in {kept}")
156
+ for dirpath, dirnames, filenames in os.walk(src_objects, followlinks=False):
157
+ rel = Path(dirpath).relative_to(src_objects)
158
+ if rel.parts and rel.parts[0] == "info":
159
+ dirnames[:] = [] # info/alternates would point git at objects elsewhere: never copied
160
+ continue
161
+ for d in list(dirnames):
162
+ if (Path(dirpath) / d).is_symlink():
163
+ dirnames.remove(d)
164
+ else:
165
+ (store / "objects" / rel / d).mkdir(exist_ok=True)
166
+ for f in filenames:
167
+ used += _copy_regular(Path(dirpath) / f, store / "objects" / rel / f, MAX_STORE_BYTES - used)
168
+ shallow = kept / "shallow"
169
+ if shallow.is_file() and not shallow.is_symlink():
170
+ fd = os.open(shallow, os.O_RDONLY | _NOFOLLOW)
171
+ with os.fdopen(fd, "rb") as fh:
172
+ raw = fh.read(MAX_SHALLOW_BYTES + 1) # 6E F4: bounded BEFORE it is checked
173
+ if len(raw) > MAX_SHALLOW_BYTES:
174
+ raise PinMismatch(f"shallow file is over {MAX_SHALLOW_BYTES} bytes")
175
+ try:
176
+ text = raw.decode("ascii")
177
+ except UnicodeDecodeError:
178
+ raise PinMismatch("shallow file is not a list of commit ids") from None
179
+ if not all(_HEX40.fullmatch(x) for x in text.split()):
180
+ raise PinMismatch("shallow file is not a list of commit ids")
181
+ (store / "shallow").write_text(text)
182
+
183
+
184
+ def _extract(store: Path, commit: str, dest: Path) -> list[str]:
185
+ """Write the pin's REGULAR blobs (modes 100644/100755) into dest, byte for byte from the object
186
+ store (cat-file --batch). Never git archive: the repo's own .gitattributes (export-ignore,
187
+ export-subst, eol, ident) would change the bytes (review F2). Symlinks (120000) and anything
188
+ else are listed, not written."""
189
+ files = tree_files(store, commit)
190
+ want, skipped = [], []
191
+ for path, (mode, sha) in sorted(files.items()):
192
+ p = PurePosixPath(path)
193
+ if p.is_absolute() or ".." in p.parts or not path or p.as_posix() != path:
194
+ raise PinMismatch(f"unsafe path in tree: {path!r}")
195
+ if any(part.casefold() == ".git" for part in p.parts): # 6E F6: fsck only warns (hasDotgit)
196
+ raise PinMismatch(f"a .git entry in the tree: {path!r}")
197
+ if mode in ("100644", "100755"):
198
+ want.append((path, sha))
199
+ else:
200
+ skipped.append(path)
201
+ out = _ok(git(store, "cat-file", "--batch", input="".join(f"{sha}\n" for _, sha in want).encode()), "cat-file")
202
+ pos = 0
203
+ for path, sha in want:
204
+ nl = out.index(b"\n", pos)
205
+ head = out[pos:nl].decode().split()
206
+ if len(head) != 3 or head[0] != sha or head[1] != "blob":
207
+ raise PinMismatch(f"cat-file answered {head} for {path}")
208
+ size = int(head[2])
209
+ data = out[nl + 1: nl + 1 + size]
210
+ pos = nl + 1 + size + 1
211
+ target = dest.joinpath(*PurePosixPath(path).parts)
212
+ target.parent.mkdir(parents=True, exist_ok=True)
213
+ with open(target, "xb") as fh:
214
+ fh.write(data)
215
+ return skipped
216
+
217
+
218
+ def _read_only(top: Path) -> None:
219
+ for dirpath, dirnames, filenames in os.walk(top):
220
+ for f in filenames:
221
+ os.chmod(Path(dirpath) / f, 0o444)
222
+ os.chmod(dirpath, 0o555)
223
+
224
+
225
+ def _real_dirs(root: Path, *dirs: Path) -> None:
226
+ """Every folder from ``root`` down to each of ``dirs`` is a real folder, not a symlink (6E F5:
227
+ a symlinked ``root/<org>`` would carry the build and its pin file outside the cache root)."""
228
+ for d in dirs:
229
+ cur = root
230
+ for part in d.relative_to(root).parts:
231
+ cur = cur / part
232
+ if cur.is_symlink() or not cur.is_dir():
233
+ raise PinMismatch(f"{cur} is not a real folder under the cache root")
234
+
235
+
236
+ def build(kept: Path, org: str, repo: str, commit: str, verdict: ratify.Verdict, *,
237
+ root: Path | None = None) -> dict:
238
+ """Build the cache for org/repo@commit from an untrusted fetched store ``kept`` (the box's
239
+ output, or a carried copy). The verified line must be for exactly this pin. Returns the pin
240
+ record. Raises PinMismatch and leaves nothing behind on any failure."""
241
+ if not verdict.ok or (verdict.fields.get("org"), verdict.fields.get("repo"), verdict.fields.get("commit")) \
242
+ != (org, repo, commit):
243
+ raise PinMismatch(f"no verified signed line for {org}/{repo}@{commit}: {verdict.reason or 'other pin'}")
244
+ root = Path(root) if root is not None else cache_root()
245
+ store, tree_dir, pin = _paths(root, org, repo, commit)
246
+ try:
247
+ root.mkdir(parents=True, exist_ok=True) # 7b review F3: a fresh host has no cache root yet
248
+ fd = os.open(root / ".build.lock", os.O_RDWR | os.O_CREAT | _NOFOLLOW, 0o600)
249
+ except OSError as e:
250
+ raise PinMismatch(f"cache lock: {e}") from None
251
+ try:
252
+ if not stat.S_ISREG(os.fstat(fd).st_mode): # 7b review F7: a planted FIFO is not "another build"
253
+ raise PinMismatch(f"{root / '.build.lock'} is not a regular file")
254
+ try:
255
+ fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) # 6E F1: the checks below are check-then-use
256
+ except OSError:
257
+ raise PinMismatch(f"another build holds {root / '.build.lock'}") from None
258
+ return _build(kept, org, repo, commit, verdict, root, store, tree_dir, pin)
259
+ except (OSError, subprocess.TimeoutExpired) as e: # 6E F1-F3: the contract is PinMismatch
260
+ raise PinMismatch(f"build failed: {type(e).__name__}: {e}") from None
261
+ finally:
262
+ os.close(fd)
263
+
264
+
265
+ def _build(kept, org, repo, commit, verdict, root, store, tree_dir, pin) -> dict:
266
+ # lexists: a DANGLING symlink at the pin path is "present" too (7b review F1)
267
+ if os.path.lexists(tree_dir) or os.path.lexists(pin):
268
+ raise PinMismatch(f"cache already present for {org}/{repo}@{commit}: archive it before a rebuild")
269
+ if os.path.lexists(store):
270
+ raise PinMismatch(f"object store already present: {store}: archive it before a rebuild")
271
+ store.parent.mkdir(parents=True, exist_ok=True)
272
+ tree_dir.parent.mkdir(parents=True, exist_ok=True)
273
+ _real_dirs(root, store.parent, tree_dir.parent)
274
+ tmp = Path(tempfile.mkdtemp(prefix=".build-", dir=root))
275
+ try:
276
+ new_store, new_tree = tmp / "store.git", tmp / "tree"
277
+ r = subprocess.run(["git", "init", "-q", "--bare", str(new_store)], capture_output=True,
278
+ env={"PATH": os.environ.get("PATH", "/usr/bin:/bin"), "GIT_CONFIG_NOSYSTEM": "1",
279
+ "GIT_CONFIG_GLOBAL": os.devnull, "HOME": str(tmp)}, timeout=60)
280
+ _ok(r, "init")
281
+ shutil.rmtree(new_store / "hooks", ignore_errors=True) # git init's samples: never needed
282
+ _import_objects(Path(kept), new_store)
283
+ if _ok(git(new_store, "cat-file", "-t", commit), "cat-file").strip() != b"commit":
284
+ raise PinMismatch(f"{commit} is not a commit in the fetched store")
285
+ _ok(git(new_store, "fsck", "--full", "--no-dangling", "--no-progress"), "fsck") # re-hashes every object
286
+ tree = _ok(git(new_store, "rev-parse", f"{commit}^{{tree}}"), "rev-parse").decode().strip()
287
+ new_tree.mkdir()
288
+ skipped = _extract(new_store, commit, new_tree)
289
+ record = {"org": org, "repo": repo, "commit": commit, "tree": tree,
290
+ "line_sha256": line_sha256(verdict), "ratified_by": sorted(verdict.key_ids),
291
+ "skipped": skipped, "built_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())}
292
+ record["files"] = _full_check(new_store, commit, new_tree, skipped)
293
+ os.replace(new_store, store)
294
+ os.replace(new_tree, tree_dir) # a folder must be writable to move it: read-only after
295
+ _read_only(tree_dir)
296
+ _read_only(store) # review F8: nothing rewrites the objects after the build
297
+ # O_EXCL|O_NOFOLLOW: never written through a link planted after the check (7b review F1)
298
+ with os.fdopen(os.open(pin, os.O_WRONLY | os.O_CREAT | os.O_EXCL | _NOFOLLOW, 0o444), "w") as fh:
299
+ fh.write(json.dumps(record, indent=1, sort_keys=True) + "\n")
300
+ os.chmod(pin, 0o444)
301
+ return record
302
+ finally:
303
+ shutil.rmtree(tmp, ignore_errors=True) # our own build folder, created above
304
+
305
+
306
+ def _full_check(store: Path, commit: str, tree_dir: Path, skipped: list[str]) -> int:
307
+ want = tree_files(store, commit)
308
+ have = {}
309
+ for dirpath, _dirs, files in os.walk(tree_dir):
310
+ for f in files:
311
+ p = Path(dirpath) / f
312
+ have[p.relative_to(tree_dir).as_posix()] = p
313
+ missing = sorted(set(want) - set(have) - set(skipped))
314
+ extra = sorted(set(have) - set(want))
315
+ if missing or extra:
316
+ raise PinMismatch(f"exported tree differs from {commit}: missing {missing[:5]}, extra {extra[:5]}")
317
+ for rel, p in have.items():
318
+ if p.is_symlink() or blob_sha(p.read_bytes()) != want[rel][1]:
319
+ raise PinMismatch(f"{rel}: bytes differ from the pinned blob")
320
+ return len(have)
321
+
322
+
323
+ _CHECK_ERRORS = (OSError, ValueError, TypeError, AttributeError, KeyError, subprocess.TimeoutExpired)
324
+
325
+
326
+ def check_cache(org: str, repo: str, commit: str, verdict: ratify.Verdict, *, full: bool = False,
327
+ root: Path | None = None) -> dict:
328
+ """The whole-cache pin check. Returns the pin record, or raises PinMismatch (and nothing else:
329
+ a corrupt pin file or an unreadable cache is BLIND, not a traceback; 7b review F2)."""
330
+ try:
331
+ return _check_cache(org, repo, commit, verdict, full=full, root=root)
332
+ except _CHECK_ERRORS as e:
333
+ raise PinMismatch(f"cache check failed: {type(e).__name__}: {e}") from None
334
+
335
+
336
+ def _check_cache(org, repo, commit, verdict, *, full, root) -> dict:
337
+ root = Path(root) if root is not None else cache_root()
338
+ store, tree_dir, pin = _paths(root, org, repo, commit)
339
+ if not verdict.ok:
340
+ raise PinMismatch(f"line not verified: {verdict.reason}")
341
+ if (verdict.fields.get("org"), verdict.fields.get("repo"), verdict.fields.get("commit")) != (org, repo, commit):
342
+ raise PinMismatch("the verified line is for another pin")
343
+ if pin.is_symlink():
344
+ raise PinMismatch("the pin file is a symlink")
345
+ try:
346
+ record = json.loads(pin.read_text())
347
+ except (OSError, ValueError) as e:
348
+ raise PinMismatch(f"pin file unreadable: {e}") from None
349
+ if not isinstance(record, dict) or not isinstance(record.get("skipped", []), list):
350
+ raise PinMismatch("pin file is not a pin record")
351
+ if (record.get("org"), record.get("repo"), record.get("commit")) != (org, repo, commit):
352
+ raise PinMismatch(f"pin file names {record.get('org')}/{record.get('repo')}@{record.get('commit')}")
353
+ if record.get("line_sha256") != line_sha256(verdict):
354
+ raise PinMismatch("the signed line changed since the cache was built")
355
+ if not store.is_dir() or not tree_dir.is_dir() or tree_dir.is_symlink() or store.is_symlink():
356
+ raise PinMismatch("store or tree missing")
357
+ _real_dirs(root, store.parent, tree_dir.parent)
358
+ if _ok(git(store, "cat-file", "-t", commit), "cat-file").strip() != b"commit":
359
+ raise PinMismatch(f"{commit} is not a commit in the store")
360
+ tree = _ok(git(store, "rev-parse", f"{commit}^{{tree}}"), "rev-parse").decode().strip()
361
+ if tree != record.get("tree"):
362
+ raise PinMismatch(f"tree {tree} differs from the pin file's {record.get('tree')}")
363
+ if full:
364
+ _full_check(store, commit, tree_dir, record.get("skipped", []))
365
+ return record
366
+
367
+
368
+ def read_file(org: str, repo: str, commit: str, path: str, verdict: ratify.Verdict, *,
369
+ root: Path | None = None) -> bytes:
370
+ """One file's bytes from the cache, after the whole-cache check and the per-file blob check.
371
+ Raises PinMismatch and nothing else (7b review F2)."""
372
+ try:
373
+ return _read_file(org, repo, commit, path, verdict, root=root)
374
+ except _CHECK_ERRORS as e:
375
+ raise PinMismatch(f"read failed: {type(e).__name__}: {e}") from None
376
+
377
+
378
+ def _read_file(org, repo, commit, path, verdict, *, root) -> bytes:
379
+ root = Path(root) if root is not None else cache_root()
380
+ check_cache(org, repo, commit, verdict, root=root)
381
+ store, tree_dir, _ = _paths(root, org, repo, commit)
382
+ p = PurePosixPath(path)
383
+ if p.is_absolute() or ".." in p.parts or not path or path != p.as_posix():
384
+ raise PinMismatch(f"not a plain relative path: {path!r}")
385
+ want = _ok(git(store, "ls-tree", "--full-tree", "-z", commit, "--", path), "ls-tree").rstrip(b"\0")
386
+ m = _LSTREE.fullmatch(want.decode("utf-8", "surrogateescape")) if want else None
387
+ if not m or m.group(2) != "blob" or m.group(4) != path:
388
+ raise PinMismatch(f"{path} is not a file at {commit}")
389
+ f = tree_dir.joinpath(*p.parts)
390
+ if f.is_symlink() or not f.is_file():
391
+ raise PinMismatch(f"{path} missing from the exported tree")
392
+ data = f.read_bytes()
393
+ if blob_sha(data) != m.group(3):
394
+ raise PinMismatch(f"{path}: bytes differ from the pinned blob")
395
+ return data
@@ -0,0 +1,253 @@
1
+ """The GitHub pool's admission gate for ``forgeproof learn --github`` (design §12.5; build step
2
+ 7 slice 4; DECISIONS-7-github G4, G5, G7; lifts L2's "for now" for the GitHub pool ONLY).
3
+
4
+ A file is admitted only if every check holds, in this order. Each failure is its own BLIND
5
+ reason, and nothing is written:
6
+ 1. the spec is ``org/repo@<40 hex>``, and a signed line verifies for exactly that pin:
7
+ BLIND(unsigned);
8
+ 2. the whole-cache pin check passes: BLIND(pin-mismatch);
9
+ 3. the repo licence is on the allowlist, and the signed ``licence_blob`` is the blob of a
10
+ top-level licence file at the pin: BLIND(licence);
11
+ 4. the per-file pin check passes at the read (its bytes are needed by 5 and 6):
12
+ BLIND(pin-mismatch);
13
+ 5. per-file inclusion (extension, source tree, not generated): BLIND(not-included);
14
+ 6. the file carries no licence marker of its own that is off the allowlist:
15
+ BLIND(licence-file).
16
+
17
+ The admitted file becomes an ``item`` that learn's engines take exactly as they take a corpus
18
+ item, so the battery, the survival gate and chaos's rules (KD-12 j: BLIND unless a probed library
19
+ file, and BLIND then as a library copy) are the same code path for both pools (G6).
20
+ """
21
+ from __future__ import annotations
22
+
23
+ import re
24
+ from dataclasses import dataclass, field
25
+ from pathlib import Path, PurePosixPath
26
+
27
+ from . import fetchproxy, ghcache, ratify
28
+
29
+ POOL = "github"
30
+ # KD-13 (f): the signed list and its signer file are found through config.scout_list_dir()
31
+ # (FORGE_GATE_SCOUT_LIST_DIR, default <checkout>/scout), never through this file's position, so an
32
+ # installed ForgeProof can be pointed at them. Both are tracked and public-safe (G8).
33
+ LIST_NAME = "trusted_repos.jsonl"
34
+ SIGNERS_NAME = "allowed_signers"
35
+ # Test-only overrides, None in real use: a test may point admit() at its own files.
36
+ LIST_FILE: Path | None = None
37
+ SIGNERS_FILE: Path | None = None
38
+
39
+
40
+ def list_files() -> tuple[Path, Path]:
41
+ """(trusted_repos.jsonl, allowed_signers). Raises config.NotConfigured naming the key when no
42
+ folder can be found (KD-13 f)."""
43
+ if LIST_FILE is not None and SIGNERS_FILE is not None:
44
+ return LIST_FILE, SIGNERS_FILE
45
+ from .. import config
46
+ d = config.scout_list_dir()
47
+ return (LIST_FILE or d / LIST_NAME), (SIGNERS_FILE or d / SIGNERS_NAME)
48
+
49
+ # G4 (the maintainer 2026-11-14): a CLOSED set. Copyleft and anything unknown stay out (§12.8 Q5).
50
+ # KD-13 (d) (the maintainer 2026-11-15): PSF-2.0 added; it is a component of the Python-2.0 stack.
51
+ ALLOWLIST = frozenset({"Apache-2.0", "MIT", "BSD-2-Clause", "BSD-3-Clause", "ISC", "Python-2.0", "PSF-2.0"})
52
+ LICENCE_FILES = ("LICENSE", "LICENSE.txt", "LICENSE.md", "LICENCE", "COPYING")
53
+ EXTENSIONS = {".py": "python", ".r": "r", ".R": "r", ".cpp": "cpp", ".go": "go", ".rs": "rust", ".js": "javascript"}
54
+ NOT_SOURCE = frozenset({"test", "tests", "testing", "example", "examples", "doc", "docs", "Doc",
55
+ "demo", "demos", "benchmarks", "bench"})
56
+ GENERATED = re.compile(rb"(?i)(do not edit|@generated|autogenerated|auto-generated|generated by|"
57
+ rb"this file was generated|code generated)")
58
+ _SPDX_LINE = re.compile(r"SPDX-License-Identifier:\s*(.+?)\s*(?:\*/|-->)?\s*$", re.M) # review F1: re.M
59
+ _OTHER_LICENCE = re.compile(
60
+ r"(?i)(GNU (Lesser |Library |Affero )?General Public|\b[AL]?GPL|Mozilla Public|\bMPL\b|Eclipse Public|"
61
+ r"\bEPL\b|\bEUPL\b|\bCDDL\b|\bOSL\b|Open Software License|Creative Commons|\bCC-BY|\bSSPL\b|"
62
+ r"Server Side Public|Business Source|\bBUSL\b|Elastic License|LicenseRef-|proprietary|"
63
+ r"all rights reserved\.?\s*(no|not)|Commons Clause)")
64
+ _SPEC = re.compile(r"([^/@\s]+)/([^/@\s]+)@([0-9a-f]{40})") # used with fullmatch (review F6)
65
+ _TOKEN = re.compile(r"\(|\)|[A-Za-z0-9.+-]+")
66
+
67
+
68
+ class NotAdmitted(Exception):
69
+ """The file is not admitted; str(e) is the BLIND reason."""
70
+
71
+
72
+ def spdx_allowed(expr: str) -> bool:
73
+ """An SPDX expression over the allowlist: OR passes if any branch passes, AND needs every
74
+ branch, parentheses group. WITH, '+' or anything unparsable is refused (fail closed)."""
75
+ toks = _TOKEN.findall(expr or "")
76
+ if "".join(toks) != re.sub(r"\s+", "", expr or "") or not toks:
77
+ return False
78
+ pos = 0
79
+
80
+ def atom():
81
+ nonlocal pos
82
+ if pos >= len(toks):
83
+ raise ValueError("end")
84
+ t = toks[pos]
85
+ pos += 1
86
+ if t == "(":
87
+ v = disj()
88
+ if pos >= len(toks) or toks[pos] != ")":
89
+ raise ValueError(")")
90
+ pos += 1
91
+ return v
92
+ if t in ("AND", "OR", "WITH", ")") or t.endswith("+"):
93
+ raise ValueError(t)
94
+ return t in ALLOWLIST
95
+
96
+ def conj():
97
+ nonlocal pos
98
+ v = atom()
99
+ while pos < len(toks) and toks[pos] == "AND":
100
+ pos += 1
101
+ v = atom() and v
102
+ return v
103
+
104
+ def disj():
105
+ nonlocal pos
106
+ v = conj()
107
+ while pos < len(toks) and toks[pos] == "OR":
108
+ pos += 1
109
+ v = conj() or v
110
+ return v
111
+
112
+ try:
113
+ v = disj()
114
+ except ValueError:
115
+ return False
116
+ return v if pos == len(toks) else False
117
+
118
+
119
+ def file_licence(text: str) -> str:
120
+ """'' when the file carries no licence marker of its own (it inherits the repo's), else the
121
+ reason it is not admitted. Only the first 40 lines are read."""
122
+ head = "\n".join(text.splitlines()[:40])
123
+ for m in _SPDX_LINE.finditer(head):
124
+ if not spdx_allowed(m.group(1)):
125
+ return f"licence-file: SPDX {m.group(1)!r} is not on the allowlist"
126
+ m = _OTHER_LICENCE.search(head) # ALWAYS, SPDX line or not (G4 c; review F1)
127
+ if m:
128
+ return f"licence-file: header names {m.group(0)!r}"
129
+ return ""
130
+
131
+
132
+ def included(path: str, data: bytes) -> str:
133
+ """'' when §12.5's per-file inclusion holds, else the reason."""
134
+ p = PurePosixPath(path)
135
+ if p.suffix not in EXTENSIONS:
136
+ return f"not-included: extension {p.suffix!r}"
137
+ hit = [d for d in p.parts[:-1] if d in NOT_SOURCE or d.lower() in NOT_SOURCE]
138
+ if hit:
139
+ return f"not-included: under {hit[0]}/ (test, example or docs)"
140
+ if p.name.startswith("test_") or p.name.endswith("_test" + p.suffix):
141
+ return "not-included: a test file"
142
+ if GENERATED.search(data[:2048]):
143
+ return "not-included: a generated-code marker in the first 2 KB"
144
+ return ""
145
+
146
+
147
+ THRESHOLDS = {"first_commit_age_years": (">=", 3), "last_commit_age_days": ("<=", 180),
148
+ "contributors": (">=", 10), "closed_issues": (">=", 50), "dependents": (">=", 100)}
149
+
150
+
151
+ def trust_score(signals: dict) -> dict:
152
+ """§12.5's signals as met/known (G7): an unknown signal is shown as unknown, never as met.
153
+ Each signal is {"value": number or null, "source": text}."""
154
+ met, known, unknown = 0, 0, []
155
+ for k, (op, t) in THRESHOLDS.items():
156
+ v = (signals.get(k) or {}).get("value") if isinstance(signals.get(k), dict) else None
157
+ if not isinstance(v, (int, float)) or isinstance(v, bool):
158
+ unknown.append(k)
159
+ continue
160
+ known += 1
161
+ met += (v >= t) if op == ">=" else (v <= t)
162
+ return {"met": met, "known": known, "unknown": unknown, "of": len(THRESHOLDS)}
163
+
164
+
165
+ @dataclass
166
+ class Admitted:
167
+ org: str
168
+ repo: str
169
+ commit: str
170
+ path: str
171
+ lang: str
172
+ data: bytes
173
+ verdict: ratify.Verdict
174
+ trust: dict = field(default_factory=dict)
175
+
176
+ @property
177
+ def source(self) -> str:
178
+ return f"{self.org}/{self.repo}"
179
+
180
+ def item(self) -> dict:
181
+ return {"item_id": self.source, "body": self.data.decode("utf-8"), "file": self.path,
182
+ "lang": self.lang}
183
+
184
+
185
+ TRUST_PIN_KEY = "FORGE_GATE_RATIFY_PIN" # untracked config: "operator=<16-hex key id>" (review open question)
186
+
187
+
188
+ def trust_pin(raw: str | None) -> tuple[str, str] | None:
189
+ m = re.fullmatch(r"([a-z][a-z0-9-]{0,31})=([0-9a-f]{16})", (raw or "").strip())
190
+ return (m.group(1), m.group(2)) if m else None
191
+
192
+
193
+ def admit(spec: str, path: str, *, list_file: Path | None = None, signers_file: Path | None = None,
194
+ cache_root: Path | None = None, host_sets_file: Path | None = None,
195
+ trust_pin_value: str | None = None) -> Admitted:
196
+ m = _SPEC.fullmatch(spec or "")
197
+ if not m:
198
+ raise NotAdmitted(f"unsigned: --github must be org/repo@<40-hex commit>: {spec!r}")
199
+ org, repo, commit = m.groups()
200
+ try:
201
+ sets, _ = fetchproxy.load_host_sets(host_sets_file or fetchproxy.HOST_SETS_FILE)
202
+ except (OSError, ValueError) as e:
203
+ raise NotAdmitted(f"unsigned: host sets unreadable: {e}") from None
204
+ if list_file is None or signers_file is None:
205
+ from .. import config
206
+ try:
207
+ found_list, found_signers = list_files()
208
+ except config.NotConfigured as e: # loud, names the key; nothing is read or written
209
+ raise NotAdmitted(f"unsigned: no signed list: {e}") from None
210
+ list_file = list_file or found_list
211
+ signers_file = signers_file or found_signers
212
+ v = ratify.ratified(list_file, signers_file, org, repo, commit, sets)
213
+ if not v.ok:
214
+ raise NotAdmitted(f"unsigned: {org}/{repo}@{commit}: {v.reason}")
215
+ # The signer file is in the repo, so whoever can commit could swap the key under "operator". The
216
+ # required signer's key id is therefore ALSO pinned in the host's untracked config.
217
+ from .. import config
218
+ pin = trust_pin(trust_pin_value if trust_pin_value is not None else config.configured(TRUST_PIN_KEY))
219
+ if pin is None or pin[0] != ratify.REQUIRED_PRINCIPAL:
220
+ raise NotAdmitted(f"unsigned: {TRUST_PIN_KEY} must be set to '{ratify.REQUIRED_PRINCIPAL}=<key id>' "
221
+ "in the host's config (the trust root is pinned outside the repo)")
222
+ signed = dict(zip(v.principals, v.key_ids))
223
+ if signed.get(pin[0]) != pin[1]:
224
+ raise NotAdmitted(f"unsigned: {pin[0]}'s signature is by key {signed.get(pin[0])}, the host pins {pin[1]}")
225
+ try:
226
+ ghcache.check_cache(org, repo, commit, v, root=cache_root)
227
+ store = (Path(cache_root) if cache_root is not None else ghcache.cache_root()) / ".objects" / org / f"{repo}.git"
228
+ tree = ghcache.tree_files(store, commit)
229
+ except ghcache.PinMismatch as e:
230
+ raise NotAdmitted(f"pin-mismatch: {e}") from None
231
+ spdx = v.fields["licence_spdx"]
232
+ if not spdx_allowed(spdx):
233
+ raise NotAdmitted(f"licence: {spdx!r} is not on the allowlist")
234
+ present = [n for n in LICENCE_FILES if n in tree]
235
+ if not present or any(tree[n][1] != v.fields["licence_blob"] for n in present):
236
+ raise NotAdmitted(f"licence: the top-level licence file(s) {present} at {commit[:12]} are not all "
237
+ f"the signed blob {v.fields['licence_blob'][:12]} (review F5: every one must be)")
238
+ try:
239
+ data = ghcache.read_file(org, repo, commit, path, v, root=cache_root)
240
+ except ghcache.PinMismatch as e:
241
+ raise NotAdmitted(f"pin-mismatch: {e}") from None
242
+ why = included(path, data)
243
+ if why:
244
+ raise NotAdmitted(why)
245
+ try:
246
+ text = data.decode("utf-8")
247
+ except UnicodeDecodeError:
248
+ raise NotAdmitted("not-included: not UTF-8 text") from None
249
+ why = file_licence(text)
250
+ if why:
251
+ raise NotAdmitted(why)
252
+ return Admitted(org, repo, commit, path, EXTENSIONS[PurePosixPath(path).suffix], data, v,
253
+ trust_score(v.fields.get("trust_signals") or {}))