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.
- forge_gate/__init__.py +44 -0
- forge_gate/_deprecated_cli.py +16 -0
- forgeproof/__init__.py +3 -0
- forgeproof/catalog.py +110 -0
- forgeproof/cli.py +560 -0
- forgeproof/config.py +339 -0
- forgeproof/data/gate_catalog.json +66 -0
- forgeproof/data/host_sets.json +7 -0
- forgeproof/debug_caller.py +271 -0
- forgeproof/debug_core.py +368 -0
- forgeproof/fixture_engine.py +81 -0
- forgeproof/fixtures/__init__.py +19 -0
- forgeproof/fixtures/decision_tree_id3.py +90 -0
- forgeproof/fixtures/gradient_descent_momentum.py +73 -0
- forgeproof/fixtures/kmeans_clustering.py +98 -0
- forgeproof/fixtures/knn_classifier.py +79 -0
- forgeproof/fixtures/linear_regression_gd.py +77 -0
- forgeproof/fixtures/logistic_regression.py +85 -0
- forgeproof/fixtures/naive_bayes_text.py +114 -0
- forgeproof/fixtures/perceptron.py +84 -0
- forgeproof/fixtures/polynomial_regression.py +67 -0
- forgeproof/fixtures/ridge_regression_normal_eq.py +75 -0
- forgeproof/ledger.py +633 -0
- forgeproof/lens_tools/__init__.py +11 -0
- forgeproof/lens_tools/guard_lens.py +1250 -0
- forgeproof/lens_tools/invariant_contracts/linear_regression_gd.json +74 -0
- forgeproof/lens_tools/invariant_contracts/polynomial_regression.json +86 -0
- forgeproof/lens_tools/invariant_contracts/ridge_regression_normal_eq.json +86 -0
- forgeproof/lens_tools/invariant_gate.py +199 -0
- forgeproof/lens_tools/metamorphic/__init__.py +9 -0
- forgeproof/lens_tools/metamorphic/relations.py +962 -0
- forgeproof/lens_tools/metamorphic/runner.py +112 -0
- forgeproof/lens_tools/twin_consensus.py +395 -0
- forgeproof/lenses.py +923 -0
- forgeproof/paths.py +56 -0
- forgeproof/reference/ORIGIN.md +29 -0
- forgeproof/reference/decision_tree_id3.py +197 -0
- forgeproof/reference/gradient_descent_momentum.py +141 -0
- forgeproof/reference/kmeans_clustering.py +139 -0
- forgeproof/reference/knn_classifier.py +118 -0
- forgeproof/reference/linear_regression_gd.py +106 -0
- forgeproof/reference/logistic_regression.py +141 -0
- forgeproof/reference/naive_bayes_text.py +152 -0
- forgeproof/reference/perceptron.py +123 -0
- forgeproof/reference/polynomial_regression.py +125 -0
- forgeproof/reference/ridge_regression_normal_eq.py +165 -0
- forgeproof/runner.py +147 -0
- forgeproof/scout/__init__.py +7 -0
- forgeproof/scout/behaviour.py +365 -0
- forgeproof/scout/box.py +581 -0
- forgeproof/scout/cards.py +180 -0
- forgeproof/scout/contract.py +37 -0
- forgeproof/scout/corpus.py +104 -0
- forgeproof/scout/embed.py +217 -0
- forgeproof/scout/engines/__init__.py +1 -0
- forgeproof/scout/engines/chaos.py +454 -0
- forgeproof/scout/engines/chaos_port.py +1331 -0
- forgeproof/scout/engines/chaos_runner.py +178 -0
- forgeproof/scout/engines/executor_port.py +239 -0
- forgeproof/scout/envfit.py +54 -0
- forgeproof/scout/experience.py +161 -0
- forgeproof/scout/fetchproxy.py +368 -0
- forgeproof/scout/ghcache.py +395 -0
- forgeproof/scout/ghpool.py +253 -0
- forgeproof/scout/ghsearch.py +248 -0
- forgeproof/scout/ids.py +82 -0
- forgeproof/scout/intent_lens.py +170 -0
- forgeproof/scout/learn.py +583 -0
- forgeproof/scout/meaning_lens.py +231 -0
- forgeproof/scout/outcomes.py +42 -0
- forgeproof/scout/plant.py +327 -0
- forgeproof/scout/ratify.py +214 -0
- forgeproof/scout/report.py +448 -0
- forgeproof/scout/rule2.py +177 -0
- forgeproof/scout/shape.py +107 -0
- forgeproof/scout/shape_lens.py +71 -0
- forgeproof/scout/signature.py +52 -0
- forgeproof/scout/slots.py +39 -0
- forgeproof/scout/upstream_facts.py +536 -0
- forgeproof/unsupported.py +83 -0
- forgeproof/verifier.py +208 -0
- forgeproof/view_coverage.py +166 -0
- forgeproof_cli-0.2.0.dist-info/METADATA +285 -0
- forgeproof_cli-0.2.0.dist-info/RECORD +89 -0
- forgeproof_cli-0.2.0.dist-info/WHEEL +5 -0
- forgeproof_cli-0.2.0.dist-info/entry_points.txt +3 -0
- forgeproof_cli-0.2.0.dist-info/licenses/LICENSE +201 -0
- forgeproof_cli-0.2.0.dist-info/licenses/NOTICE +23 -0
- forgeproof_cli-0.2.0.dist-info/top_level.txt +2 -0
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
"""Scout's report cards (design v1.4.5 §4.4.1 item 1, build step 3a).
|
|
2
|
+
|
|
3
|
+
A card is the validator's card, field for field, so the registry build can read scout's
|
|
4
|
+
report with the code that reads the validator's (D1b, D7-5). The validator's shape was
|
|
5
|
+
taken from the bytes of its reports on the deploy host on 2026-11-11 (chaos,
|
|
6
|
+
metamorphic, twin_divergence, invariant_mine; see tests/fixtures/scout/). Scout adds
|
|
7
|
+
two fields and never removes one:
|
|
8
|
+
|
|
9
|
+
- ``id``: the namespaced scout id (ids.py). The registry build matches it verbatim.
|
|
10
|
+
- ``source``: always ``"scout"``.
|
|
11
|
+
- ``kind``: the oracle kind again, equal to ``oracle_coverage_kind``. The deployed reader
|
|
12
|
+
(Brain 6be79ec, ``honest_pass.apply_scout_cards``) reads the kind from ``kind`` (or
|
|
13
|
+
``oracle_kind``), never from ``oracle_coverage_kind``; a card without it makes the whole
|
|
14
|
+
registry build fail with "unknown kind None". Found in step 6b-1 (2026-11-13): 3a's
|
|
15
|
+
cards carried no ``kind``, so not one of them could have been read.
|
|
16
|
+
|
|
17
|
+
``pattern`` carries the same id, so a reader that still joins by ``stem(pattern)``
|
|
18
|
+
gets a key that keeps its ``scout:`` prefix and can match no library row.
|
|
19
|
+
|
|
20
|
+
A report is ``{"cards": [...]}``, the top-level shape every validator card report has.
|
|
21
|
+
"""
|
|
22
|
+
from __future__ import annotations
|
|
23
|
+
|
|
24
|
+
import json
|
|
25
|
+
import os
|
|
26
|
+
import tempfile
|
|
27
|
+
from pathlib import Path
|
|
28
|
+
|
|
29
|
+
from .ids import BadScoutId, parse_id
|
|
30
|
+
|
|
31
|
+
# Present on every validator card read on 2026-11-11 (``why`` and ``ratified`` are optional).
|
|
32
|
+
VALIDATOR_FIELDS = (
|
|
33
|
+
"pattern", "technique", "severity", "class", "fixture", "expected", "actual",
|
|
34
|
+
"verdict", "verdict_target", "confidence", "repro_cmd", "oracle_coverage_kind",
|
|
35
|
+
)
|
|
36
|
+
OPTIONAL_FIELDS = ("why", "ratified")
|
|
37
|
+
SCOUT_FIELDS = ("id", "source", "kind")
|
|
38
|
+
SOURCE = "scout"
|
|
39
|
+
|
|
40
|
+
# Oracle kinds honest_pass knows (honest_pass.py: xlang, positive, chaos, metamorphic,
|
|
41
|
+
# invariant) plus the three D1 restores (roundtrip, reseed, reseed_ref; F42).
|
|
42
|
+
KINDS = frozenset({"xlang", "positive", "chaos", "metamorphic", "invariant",
|
|
43
|
+
"roundtrip", "reseed", "reseed_ref"})
|
|
44
|
+
VERDICTS = frozenset({"PASS", "FAIL", "UNSTABLE", "UNSUPPORTED", "PROPOSAL", "RATIFIED"})
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class BadCard(ValueError):
|
|
48
|
+
"""A card scout must not write or accept."""
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def check_validator_shape(card: dict) -> None:
|
|
52
|
+
"""The fields every validator card has, with string values. Raises BadCard."""
|
|
53
|
+
if not isinstance(card, dict):
|
|
54
|
+
raise BadCard(f"card is {type(card).__name__}, not dict")
|
|
55
|
+
missing = [k for k in VALIDATOR_FIELDS if k not in card]
|
|
56
|
+
if missing:
|
|
57
|
+
raise BadCard(f"missing validator fields {missing}")
|
|
58
|
+
wrong = [k for k in VALIDATOR_FIELDS if not isinstance(card[k], str)]
|
|
59
|
+
if wrong:
|
|
60
|
+
raise BadCard(f"non-string validator fields {wrong}")
|
|
61
|
+
if "ratified" in card and not isinstance(card["ratified"], bool):
|
|
62
|
+
raise BadCard("ratified must be a bool")
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def check_scout_card(card: dict) -> None:
|
|
66
|
+
"""A scout card: validator shape + a canonical scout id in both id and pattern."""
|
|
67
|
+
check_validator_shape(card)
|
|
68
|
+
if card.get("source") != SOURCE:
|
|
69
|
+
raise BadCard(f"source must be {SOURCE!r}, got {card.get('source')!r}")
|
|
70
|
+
try:
|
|
71
|
+
parse_id(card.get("id"))
|
|
72
|
+
except BadScoutId as e:
|
|
73
|
+
raise BadCard(str(e)) from None
|
|
74
|
+
if card["pattern"] != card["id"]:
|
|
75
|
+
raise BadCard("pattern must equal id (a stem() reader must never see a bare path)")
|
|
76
|
+
if card["oracle_coverage_kind"] not in KINDS:
|
|
77
|
+
raise BadCard(f"oracle_coverage_kind {card['oracle_coverage_kind']!r} not in {sorted(KINDS)}")
|
|
78
|
+
if card.get("kind") != card["oracle_coverage_kind"]: # the field the Brain's reader joins on
|
|
79
|
+
raise BadCard(f"kind {card.get('kind')!r} must equal oracle_coverage_kind "
|
|
80
|
+
f"{card['oracle_coverage_kind']!r}")
|
|
81
|
+
if card["verdict"] not in VERDICTS:
|
|
82
|
+
raise BadCard(f"verdict {card['verdict']!r} not in {sorted(VERDICTS)}")
|
|
83
|
+
extra = set(card) - set(VALIDATOR_FIELDS) - set(OPTIONAL_FIELDS) - set(SCOUT_FIELDS)
|
|
84
|
+
if extra:
|
|
85
|
+
raise BadCard(f"fields the validator shape does not have: {sorted(extra)}")
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def make_card(scout_id: str, *, kind: str, verdict: str, technique: str, fixture: str,
|
|
89
|
+
expected: str, actual: str, repro_cmd: str, why: str | None = None,
|
|
90
|
+
severity: str = "info", card_class: str | None = None,
|
|
91
|
+
verdict_target: str = "PATTERN", confidence: str = "high") -> dict:
|
|
92
|
+
card = {
|
|
93
|
+
"id": scout_id,
|
|
94
|
+
"source": SOURCE,
|
|
95
|
+
"kind": kind,
|
|
96
|
+
"pattern": scout_id,
|
|
97
|
+
"technique": technique,
|
|
98
|
+
"severity": severity,
|
|
99
|
+
"class": card_class or f"{kind}-coverage",
|
|
100
|
+
"fixture": fixture,
|
|
101
|
+
"expected": expected,
|
|
102
|
+
"actual": actual,
|
|
103
|
+
"verdict": verdict,
|
|
104
|
+
"verdict_target": verdict_target,
|
|
105
|
+
"confidence": confidence,
|
|
106
|
+
"repro_cmd": repro_cmd,
|
|
107
|
+
"oracle_coverage_kind": kind,
|
|
108
|
+
}
|
|
109
|
+
if why is not None:
|
|
110
|
+
card["why"] = why
|
|
111
|
+
check_scout_card(card)
|
|
112
|
+
return card
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
# The registry build reads the report as another user (au writes, bu reads on the deploy host):
|
|
116
|
+
# mkstemp's 0600 would make the hourly build fail with PermissionError (6b-1 review F4).
|
|
117
|
+
REPORT_MODE = 0o644
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def check_report(cards: list[dict]) -> None:
|
|
121
|
+
"""Every check write_report makes, without writing. Raises BadCard."""
|
|
122
|
+
for c in cards:
|
|
123
|
+
check_scout_card(c)
|
|
124
|
+
kinds_by_id: dict = {}
|
|
125
|
+
for c in cards:
|
|
126
|
+
kinds_by_id.setdefault(c["id"], []).append(c["oracle_coverage_kind"])
|
|
127
|
+
dup = sorted(i for i, ks in kinds_by_id.items() if len(ks) != len(set(ks)))
|
|
128
|
+
if dup:
|
|
129
|
+
raise BadCard(f"two cards for the same id and kind: {dup}")
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def stage_report(path: Path, cards: list[dict]) -> Path:
|
|
133
|
+
"""Check the cards and write them to a temp file next to ``path``; return the temp file.
|
|
134
|
+
The caller swaps it in with ``os.replace`` (or deletes it). Lets a writer that changes two
|
|
135
|
+
files (learn: registry + report) run every check and every write that can fail before
|
|
136
|
+
the first file changes (6b-1 review F2)."""
|
|
137
|
+
check_report(cards)
|
|
138
|
+
path = Path(path)
|
|
139
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
140
|
+
fd, tmp = tempfile.mkstemp(prefix=path.name + ".", suffix=".tmp", dir=path.parent)
|
|
141
|
+
try:
|
|
142
|
+
os.fchmod(fd, REPORT_MODE)
|
|
143
|
+
with os.fdopen(fd, "w", encoding="utf-8") as fh:
|
|
144
|
+
json.dump({"cards": cards}, fh, ensure_ascii=False, indent=1)
|
|
145
|
+
fh.write("\n")
|
|
146
|
+
fh.flush()
|
|
147
|
+
os.fsync(fh.fileno())
|
|
148
|
+
except BaseException:
|
|
149
|
+
Path(tmp).unlink(missing_ok=True)
|
|
150
|
+
raise
|
|
151
|
+
return Path(tmp)
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def write_report(path: Path, cards: list[dict]) -> Path:
|
|
155
|
+
"""Write ``{"cards": [...]}`` atomically (temp file + rename, as honest_pass does)."""
|
|
156
|
+
tmp = stage_report(path, cards)
|
|
157
|
+
try:
|
|
158
|
+
os.replace(tmp, path)
|
|
159
|
+
except BaseException:
|
|
160
|
+
tmp.unlink(missing_ok=True)
|
|
161
|
+
raise
|
|
162
|
+
return Path(path)
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def load_report(path: Path) -> list[dict]:
|
|
166
|
+
"""Read a scout report; every card is checked, the first bad one raises."""
|
|
167
|
+
data = json.loads(Path(path).read_text(encoding="utf-8"))
|
|
168
|
+
if not isinstance(data, dict) or not isinstance(data.get("cards"), list):
|
|
169
|
+
raise BadCard(f"{path}: not a card report (needs a top-level 'cards' list)")
|
|
170
|
+
seen: dict = {}
|
|
171
|
+
for i, c in enumerate(data["cards"]):
|
|
172
|
+
try:
|
|
173
|
+
check_scout_card(c)
|
|
174
|
+
except BadCard as e:
|
|
175
|
+
raise BadCard(f"{path}: card {i}: {e}") from None
|
|
176
|
+
key = (c["id"], c["oracle_coverage_kind"])
|
|
177
|
+
if key in seen: # the reader enforces what write_report does (6E review B3a-2)
|
|
178
|
+
raise BadCard(f"{path}: card {i}: same id and kind as card {seen[key]}")
|
|
179
|
+
seen[key] = i
|
|
180
|
+
return data["cards"]
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
"""The contract gate (design §4a.3, lens 3): takes and returns the same kinds of things.
|
|
2
|
+
|
|
3
|
+
A gate filters, it does not vote. Behaviour calls the candidate with the query's REQUIRED
|
|
4
|
+
positional arguments, so the candidate must accept that many. Types are compared only where
|
|
5
|
+
BOTH sides are annotated; an unannotated side is unknown, and unknown passes (the behaviour run
|
|
6
|
+
then decides). Returns (fits, reason).
|
|
7
|
+
"""
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import re
|
|
11
|
+
|
|
12
|
+
_ALIASES = {"List": "list", "Dict": "dict", "Tuple": "tuple", "Set": "set", "Sequence": "list",
|
|
13
|
+
"Iterable": "list", "Optional": "", "typing.": ""}
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def norm(t: str | None) -> str | None:
|
|
17
|
+
if not t:
|
|
18
|
+
return None
|
|
19
|
+
s = t.replace(" ", "")
|
|
20
|
+
for k, v in _ALIASES.items():
|
|
21
|
+
s = s.replace(k, v)
|
|
22
|
+
s = re.sub(r"\[.*\]", "", s) # compare the outer kind only: list[float] ~ list
|
|
23
|
+
return s.lower() or None
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def fits(q: dict, c: dict) -> tuple[bool, str]:
|
|
27
|
+
n = q["required"]
|
|
28
|
+
if not (c["required"] <= n <= c["total"]):
|
|
29
|
+
return False, f"arity: query passes {n}, {c['entry']} takes {c['required']}-{c['total']}"
|
|
30
|
+
for i in range(n):
|
|
31
|
+
tq, tc = norm(q["consumes"][i]["type"]), norm(c["consumes"][i]["type"])
|
|
32
|
+
if tq and tc and tq != tc:
|
|
33
|
+
return False, f"type: arg {i} {tq} vs {tc}"
|
|
34
|
+
rq, rc = norm(q["produces"]["type"]), norm(c["produces"]["type"])
|
|
35
|
+
if rq and rc and rq != rc:
|
|
36
|
+
return False, f"type: returns {rq} vs {rc}"
|
|
37
|
+
return True, "fits"
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
"""Crew-corpus intake (design v1.4.5 §12.4; build step 5).
|
|
2
|
+
|
|
3
|
+
Reads the newest ``<run_id>/`` under the export root whose manifest says
|
|
4
|
+
``schema = code-corpus-export/v1`` and ``run_status = OK``, re-checks every file's sha256,
|
|
5
|
+
byte count and row count against the manifest, and returns the items. Any failure makes
|
|
6
|
+
the whole source BLIND(reason) for the run: never clean, never partly read (P1).
|
|
7
|
+
|
|
8
|
+
Reads only. Scout never writes into the corpus. Item bodies are text: nothing here
|
|
9
|
+
compiles, imports or runs them.
|
|
10
|
+
"""
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import hashlib
|
|
14
|
+
import json
|
|
15
|
+
import re
|
|
16
|
+
from dataclasses import dataclass, field
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
|
|
19
|
+
from .. import config
|
|
20
|
+
from .outcomes import BLIND_FLAG_SHARE, Outcome, blind, clean, found
|
|
21
|
+
|
|
22
|
+
SCHEMA = "code-corpus-export/v1"
|
|
23
|
+
_RUN_ID = re.compile(r"^[0-9]{8}T[0-9]{6}Z$")
|
|
24
|
+
POOL = "corpus"
|
|
25
|
+
TRUST = "raw"
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@dataclass
|
|
29
|
+
class Intake:
|
|
30
|
+
outcome: Outcome # FOUND = items read; BLIND(reason) otherwise
|
|
31
|
+
run_id: str = ""
|
|
32
|
+
items: list = field(default_factory=list)
|
|
33
|
+
skipped: list = field(default_factory=list) # (run_id, why) for newer runs not used
|
|
34
|
+
unreadable: int = 0 # items without a usable body
|
|
35
|
+
flagged: bool = False # unreadable share > 10%
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _verify(run: Path, manifest: dict):
|
|
39
|
+
"""Return None when every file matches the manifest, else the first mismatch."""
|
|
40
|
+
files = manifest.get("files")
|
|
41
|
+
if not isinstance(files, dict) or not files:
|
|
42
|
+
return "manifest has no files table"
|
|
43
|
+
for name, meta in sorted(files.items()):
|
|
44
|
+
p = run / name
|
|
45
|
+
if not p.is_file():
|
|
46
|
+
return f"missing {name}"
|
|
47
|
+
b = p.read_bytes()
|
|
48
|
+
got = hashlib.sha256(b).hexdigest()
|
|
49
|
+
if got != meta.get("sha256"):
|
|
50
|
+
return f"sha256 mismatch {name}"
|
|
51
|
+
if len(b) != meta.get("bytes"):
|
|
52
|
+
return f"bytes mismatch {name}"
|
|
53
|
+
if name.endswith(".jsonl") and "rows" not in meta: # 6E review S1-1: never a weaker check
|
|
54
|
+
return f"schema: no rows for {name}"
|
|
55
|
+
if "rows" in meta and b.count(b"\n") != meta["rows"]:
|
|
56
|
+
return f"rows mismatch {name}"
|
|
57
|
+
return None
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def read_export(root: Path | None = None) -> Intake:
|
|
61
|
+
if root is None:
|
|
62
|
+
try:
|
|
63
|
+
root = config.corpus_export_dir()
|
|
64
|
+
except config.NotConfigured as e:
|
|
65
|
+
return Intake(blind(f"not-configured: {config.CORPUS_KEY}", str(e)))
|
|
66
|
+
root = Path(root)
|
|
67
|
+
runs = sorted((p for p in root.iterdir() if p.is_dir() and _RUN_ID.match(p.name)),
|
|
68
|
+
key=lambda p: p.name, reverse=True)
|
|
69
|
+
if not runs:
|
|
70
|
+
return Intake(blind("no-export", str(root)))
|
|
71
|
+
skipped = []
|
|
72
|
+
for run in runs:
|
|
73
|
+
try:
|
|
74
|
+
manifest = json.loads((run / "manifest.json").read_text(encoding="utf-8"))
|
|
75
|
+
except (OSError, ValueError) as e:
|
|
76
|
+
skipped.append((run.name, f"manifest unreadable: {type(e).__name__}"))
|
|
77
|
+
continue
|
|
78
|
+
if manifest.get("schema") != SCHEMA:
|
|
79
|
+
skipped.append((run.name, f"schema {manifest.get('schema')!r}"))
|
|
80
|
+
continue
|
|
81
|
+
if manifest.get("run_status") != "OK" or manifest.get("run_id") != run.name:
|
|
82
|
+
skipped.append((run.name, f"run_status {manifest.get('run_status')!r}"))
|
|
83
|
+
continue
|
|
84
|
+
# The newest OK run is THE source. A bad sha here is BLIND, never a fallback to an
|
|
85
|
+
# older run: falling back would hide the damage behind a clean-looking read.
|
|
86
|
+
bad = _verify(run, manifest)
|
|
87
|
+
if bad:
|
|
88
|
+
return Intake(blind(f"sha-recheck: {bad}", run.name), run.name, skipped=skipped)
|
|
89
|
+
items, unreadable = [], 0
|
|
90
|
+
for line in (run / "items.jsonl").read_text(encoding="utf-8").splitlines():
|
|
91
|
+
try:
|
|
92
|
+
d = json.loads(line)
|
|
93
|
+
except ValueError:
|
|
94
|
+
unreadable += 1
|
|
95
|
+
continue
|
|
96
|
+
if not isinstance(d, dict) or not isinstance(d.get("body"), str) or not d.get("item_id"):
|
|
97
|
+
unreadable += 1
|
|
98
|
+
continue
|
|
99
|
+
items.append(d)
|
|
100
|
+
total = len(items) + unreadable
|
|
101
|
+
flagged = total == 0 or unreadable / total > BLIND_FLAG_SHARE
|
|
102
|
+
return Intake(found(f"{len(items)} items", run.name), run.name, items, skipped,
|
|
103
|
+
unreadable, flagged)
|
|
104
|
+
return Intake(blind("no-OK-export", *(f"{r}: {w}" for r, w in skipped)), skipped=skipped)
|
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
"""The embedder behind the language-meaning and intent lenses (design §4a.3 lenses 4-5, build step 8b s1).
|
|
2
|
+
|
|
3
|
+
One engine: a LOCAL Ollama serving ``nomic-embed-text`` at the pinned digest (DECISIONS-8b H1 a),
|
|
4
|
+
reached at ``FORGE_GATE_EMBED_URL`` (env > config.toml, no default; unset = the lenses are BLIND).
|
|
5
|
+
Corpus bodies are private: before any text is sent, ``check()`` refuses
|
|
6
|
+
|
|
7
|
+
- a URL that is not plain http on a loopback address (config.embed_url),
|
|
8
|
+
- a model that Ollama marks remote (``remote_host`` / ``remote_model``: the same Ollama on the deploy host also
|
|
9
|
+
serves ``:cloud`` models whose input leaves the host, DECISIONS-8b F9),
|
|
10
|
+
- a digest other than the pin (another model scores differently: its Rule-2 run would mean nothing),
|
|
11
|
+
|
|
12
|
+
and every request goes through an opener with NO proxy handler, so an ``http_proxy`` in the
|
|
13
|
+
environment cannot route a body off the host.
|
|
14
|
+
|
|
15
|
+
Vectors are cached (H4 b) in one append-only file per model digest under
|
|
16
|
+
``FORGE_GATE_EMBED_CACHE_DIR``. A scout run only READS the cache; ``fill()`` (a separate, explicit
|
|
17
|
+
command) is the only writer. A row is keyed by ``sha256(digest NUL text)`` and checked when read.
|
|
18
|
+
"""
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
import fcntl
|
|
22
|
+
import http.client
|
|
23
|
+
import hashlib
|
|
24
|
+
import json
|
|
25
|
+
import math
|
|
26
|
+
import os
|
|
27
|
+
import urllib.error
|
|
28
|
+
import urllib.request
|
|
29
|
+
from pathlib import Path
|
|
30
|
+
|
|
31
|
+
from .. import config
|
|
32
|
+
|
|
33
|
+
MODEL = "nomic-embed-text:latest"
|
|
34
|
+
# /api/tags digest of the model on the deploy host, Ollama 0.31.2, read 2026-11-16 (DECISIONS-8b F9).
|
|
35
|
+
DIGEST = "0a109f422b47e3a30ba2b10eca18548e944e8a23073ee3f3e947efcf3c45e59f"
|
|
36
|
+
TIMEOUT = 600.0 # a batch of corpus bodies costs ~4 s each on the deploy host's CPU (F14)
|
|
37
|
+
BATCH = 16
|
|
38
|
+
MAX_ROW = 64 * 1024 # a cache line longer than this is refused, not parsed
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class EmbedError(RuntimeError):
|
|
42
|
+
"""The embedder cannot be used for this run; the message is the BLIND reason."""
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _opener():
|
|
46
|
+
return urllib.request.build_opener(urllib.request.ProxyHandler({}))
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class Embedder:
|
|
50
|
+
def __init__(self, url: str, *, model: str = MODEL, digest: str = DIGEST, timeout: float = TIMEOUT):
|
|
51
|
+
try: # the loopback rule holds for every caller (s1 review F2)
|
|
52
|
+
url = config.loopback_url(url)
|
|
53
|
+
except config.NotConfigured as e:
|
|
54
|
+
raise EmbedError(f"embedder-url: {e}") from None
|
|
55
|
+
self.url, self.model, self.digest, self.timeout = url, model, digest, timeout
|
|
56
|
+
self._checked = False
|
|
57
|
+
|
|
58
|
+
def _call(self, path: str, body: dict | None = None):
|
|
59
|
+
data = None if body is None else json.dumps(body).encode()
|
|
60
|
+
req = urllib.request.Request(self.url + path, data, {"Content-Type": "application/json"})
|
|
61
|
+
try:
|
|
62
|
+
with _opener().open(req, timeout=self.timeout) as r:
|
|
63
|
+
return json.load(r)
|
|
64
|
+
except (urllib.error.URLError, OSError, ValueError, http.client.HTTPException) as e:
|
|
65
|
+
raise EmbedError(f"embedder-unreachable: {path}: {e}") from None
|
|
66
|
+
|
|
67
|
+
def check(self) -> None:
|
|
68
|
+
"""Raise EmbedError unless the pinned LOCAL model is what this URL serves."""
|
|
69
|
+
tags = self._call("/api/tags")
|
|
70
|
+
models = tags.get("models") if isinstance(tags, dict) else None
|
|
71
|
+
if not isinstance(models, list):
|
|
72
|
+
raise EmbedError("embedder-unexpected: /api/tags has no model list")
|
|
73
|
+
m = next((m for m in models if isinstance(m, dict) and m.get("name") == self.model), None)
|
|
74
|
+
if m is None:
|
|
75
|
+
raise EmbedError(f"embedder-no-model: {self.model} is not served at {self.url}")
|
|
76
|
+
if m.get("remote_host") or m.get("remote_model"):
|
|
77
|
+
raise EmbedError(f"embedder-remote: {self.model} is served from {m.get('remote_host')!r}; "
|
|
78
|
+
"private text is never sent off the host")
|
|
79
|
+
if m.get("digest") != self.digest:
|
|
80
|
+
raise EmbedError(f"embedder-digest: {self.model} is {str(m.get('digest'))[:12]}, pinned "
|
|
81
|
+
f"{self.digest[:12]}")
|
|
82
|
+
show = self._call("/api/show", {"model": self.model})
|
|
83
|
+
if not isinstance(show, dict) or show.get("remote_host") or show.get("remote_model"):
|
|
84
|
+
raise EmbedError(f"embedder-remote: /api/show for {self.model} names a remote host")
|
|
85
|
+
self._checked = True
|
|
86
|
+
|
|
87
|
+
def embed(self, texts: list) -> list:
|
|
88
|
+
"""Vectors for ``texts``, in order. Checks the model first (once per Embedder)."""
|
|
89
|
+
if not self._checked:
|
|
90
|
+
self.check()
|
|
91
|
+
out = []
|
|
92
|
+
for i in range(0, len(texts), BATCH):
|
|
93
|
+
chunk = texts[i:i + BATCH]
|
|
94
|
+
r = self._call("/api/embed", {"model": self.model, "input": chunk})
|
|
95
|
+
vecs = r.get("embeddings") if isinstance(r, dict) else None
|
|
96
|
+
if not _vectors_ok(vecs, len(chunk)):
|
|
97
|
+
raise EmbedError(f"embedder-unexpected: /api/embed gave no {len(chunk)} finite vectors")
|
|
98
|
+
out += vecs
|
|
99
|
+
return out
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def _vectors_ok(vecs, n: int) -> bool:
|
|
103
|
+
if not isinstance(vecs, list) or len(vecs) != n or not vecs:
|
|
104
|
+
return False
|
|
105
|
+
dim = len(vecs[0]) if isinstance(vecs[0], list) else 0
|
|
106
|
+
return dim > 0 and all(
|
|
107
|
+
isinstance(v, list) and len(v) == dim and
|
|
108
|
+
all(isinstance(x, (int, float)) and not isinstance(x, bool) and math.isfinite(x) for x in v)
|
|
109
|
+
and any(x != 0 for x in v)
|
|
110
|
+
for v in vecs)
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def get() -> Embedder:
|
|
114
|
+
"""The configured embedder. Raises EmbedError (BLIND reason) when it cannot be used."""
|
|
115
|
+
try:
|
|
116
|
+
return Embedder(config.embed_url())
|
|
117
|
+
except config.NotConfigured as e:
|
|
118
|
+
raise EmbedError(f"not-configured: {config.EMBED_URL_KEY}: {e}") from None
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def cosine(a: list, b: list) -> float:
|
|
122
|
+
na, nb = math.sqrt(sum(x * x for x in a)), math.sqrt(sum(y * y for y in b))
|
|
123
|
+
if na == 0 or nb == 0 or len(a) != len(b):
|
|
124
|
+
return 0.0
|
|
125
|
+
return sum(x * y for x, y in zip(a, b)) / (na * nb)
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
# ---------------------------------------------------------------- the vector cache (H4 b)
|
|
129
|
+
|
|
130
|
+
def key(text: str, digest: str = DIGEST) -> str:
|
|
131
|
+
return hashlib.sha256(digest.encode() + b"\0" + text.encode("utf-8", "surrogatepass")).hexdigest() # F5
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def _cache_file(d: Path, digest: str) -> Path:
|
|
135
|
+
return Path(d) / f"vectors-{digest[:12]}.jsonl"
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def _safe_dir(d) -> Path:
|
|
139
|
+
"""The cache folder must be the caller's own and not writable by others (s1 review F4): anyone
|
|
140
|
+
who can write into it could plant a symlink or rows."""
|
|
141
|
+
d = Path(d)
|
|
142
|
+
try:
|
|
143
|
+
st = os.stat(d)
|
|
144
|
+
except OSError as e:
|
|
145
|
+
raise EmbedError(f"cache-unreadable: {d}: {e}") from None
|
|
146
|
+
if st.st_uid != os.getuid() or st.st_mode & 0o022:
|
|
147
|
+
raise EmbedError(f"cache-unsafe: {d} must be owned by uid {os.getuid()} and not group/world "
|
|
148
|
+
f"writable (uid {st.st_uid}, mode {oct(st.st_mode & 0o777)})")
|
|
149
|
+
return d
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def read_cache(d=None, digest: str = DIGEST) -> dict:
|
|
153
|
+
"""{key: vector} from the cache file. Unset dir -> EmbedError; a missing file -> {} (nothing
|
|
154
|
+
embedded yet). A malformed or oversized line is skipped (a torn tail from a killed fill)."""
|
|
155
|
+
if d is None:
|
|
156
|
+
try:
|
|
157
|
+
d = config.embed_cache_dir()
|
|
158
|
+
except config.NotConfigured as e:
|
|
159
|
+
raise EmbedError(f"not-configured: {config.EMBED_CACHE_KEY}: {e}") from None
|
|
160
|
+
p = _cache_file(_safe_dir(d), digest)
|
|
161
|
+
out = {}
|
|
162
|
+
try:
|
|
163
|
+
fh = os.fdopen(os.open(p, os.O_RDONLY | os.O_NOFOLLOW), "rb") # F4: never through a symlink
|
|
164
|
+
except FileNotFoundError:
|
|
165
|
+
return out
|
|
166
|
+
except OSError as e:
|
|
167
|
+
raise EmbedError(f"cache-unreadable: {p}: {e}") from None
|
|
168
|
+
with fh:
|
|
169
|
+
for line in fh:
|
|
170
|
+
if len(line) > MAX_ROW or not line.endswith(b"\n"):
|
|
171
|
+
continue
|
|
172
|
+
try:
|
|
173
|
+
row = json.loads(line)
|
|
174
|
+
except ValueError:
|
|
175
|
+
continue
|
|
176
|
+
k, v = (row.get("k"), row.get("v")) if isinstance(row, dict) else (None, None)
|
|
177
|
+
if isinstance(k, str) and len(k) == 64 and _vectors_ok([v], 1):
|
|
178
|
+
out[k] = v
|
|
179
|
+
return out
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def fill(texts: list, emb: Embedder, d=None) -> tuple[int, int]:
|
|
183
|
+
"""Embed the texts the cache does not hold yet and append them. The ONLY cache writer.
|
|
184
|
+
Returns (added, already). One lock for the whole fill, so two fills never interleave."""
|
|
185
|
+
d = _safe_dir(d if d is not None else config.embed_cache_dir())
|
|
186
|
+
p = _cache_file(d, emb.digest)
|
|
187
|
+
try:
|
|
188
|
+
lfd = os.open(d / "embed.lock", os.O_WRONLY | os.O_CREAT | os.O_APPEND | os.O_NOFOLLOW, 0o600)
|
|
189
|
+
except OSError as e:
|
|
190
|
+
raise EmbedError(f"cache-unsafe: {d}/embed.lock: {e}") from None
|
|
191
|
+
with os.fdopen(lfd, "a") as lk:
|
|
192
|
+
try:
|
|
193
|
+
fcntl.flock(lk, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
|
194
|
+
except BlockingIOError:
|
|
195
|
+
raise EmbedError(f"cache-busy: another fill holds {d}/embed.lock") from None
|
|
196
|
+
have = read_cache(d, emb.digest)
|
|
197
|
+
todo, seen = [], set()
|
|
198
|
+
for t in texts:
|
|
199
|
+
k = key(t, emb.digest)
|
|
200
|
+
if k not in have and k not in seen:
|
|
201
|
+
seen.add(k)
|
|
202
|
+
todo.append((k, t))
|
|
203
|
+
try:
|
|
204
|
+
fd = os.open(p, os.O_WRONLY | os.O_APPEND | os.O_CREAT | os.O_NOFOLLOW, 0o600)
|
|
205
|
+
except OSError as e:
|
|
206
|
+
raise EmbedError(f"cache-unsafe: {p}: {e}") from None
|
|
207
|
+
try:
|
|
208
|
+
for i in range(0, len(todo), BATCH):
|
|
209
|
+
part = todo[i:i + BATCH]
|
|
210
|
+
vecs = emb.embed([t for _, t in part])
|
|
211
|
+
emb.check() # the tag may have moved mid-fill: re-pin BEFORE writing (s1 review F1)
|
|
212
|
+
os.write(fd, b"".join(json.dumps({"k": k, "v": v}, separators=(",", ":")).encode() + b"\n"
|
|
213
|
+
for (k, _), v in zip(part, vecs)))
|
|
214
|
+
os.fsync(fd)
|
|
215
|
+
finally:
|
|
216
|
+
os.close(fd)
|
|
217
|
+
return len(todo), len(texts) - len(todo)
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Engines ported into scout (design §2.3): source text frozen, with a header naming its origin."""
|