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
forgeproof/ledger.py
ADDED
|
@@ -0,0 +1,633 @@
|
|
|
1
|
+
"""ForgeProof's two ledgers: exposure and outcome (design v1.4.5 §4a.5, build step 8a).
|
|
2
|
+
|
|
3
|
+
Decisions: ``~/aura-docs/Forge Gate/DECISIONS-8a-ledgers-20261115.md`` G1-G8 (the maintainer, 2026-11-15).
|
|
4
|
+
|
|
5
|
+
* **exposure** (``exposure.jsonl``): one row per result scout showed (query, result id, rank,
|
|
6
|
+
the lens that surfaced it, time). Writer ``scout-search``.
|
|
7
|
+
* **outcome** (``outcome.jsonl``): three kinds, each with ONE named writer (V4-2):
|
|
8
|
+
``oracle`` by ``oracle-run`` (an oracle run passing on the reused code where it was reused);
|
|
9
|
+
``person-mark`` and ``person-event`` by ``person-mark`` (a person's "kept and it worked" mark,
|
|
10
|
+
which scores only once an event the tool itself ran and measured passes after it).
|
|
11
|
+
|
|
12
|
+
Only outcomes score; being shown never does. This module holds the only code that appends to
|
|
13
|
+
either ledger. Which modules may call which writer is pinned by ``tests/test_ledger_routes.py``
|
|
14
|
+
(an AST scan), so scout's search path cannot write the outcome ledger. A writer sets ``writer``
|
|
15
|
+
itself; callers cannot pass it. Every row is checked by the same :func:`check_row` when written
|
|
16
|
+
and again when read, so a hand-appended row with the wrong writer never scores.
|
|
17
|
+
|
|
18
|
+
Files and locking (G6, the 3b/6b lessons):
|
|
19
|
+
|
|
20
|
+
* ``FORGE_GATE_LEDGER_DIR`` has no default. Unset = the ledgers are switched OFF and nothing is
|
|
21
|
+
written anywhere. The folder, both ledger files and ``ledger.lock`` must already exist: the
|
|
22
|
+
switch-on creates them with their owner and ACL, never a writer (a typo'd folder must not get a
|
|
23
|
+
fresh ledger nobody reads, and the first writer must not decide the owner).
|
|
24
|
+
* All writers live here and take the same ``flock`` on ``ledger.lock``, so the lock is shared by
|
|
25
|
+
construction.
|
|
26
|
+
* Append only: ``O_APPEND``, never ``O_CREAT``, never ``os.replace``, never a rewrite. The file
|
|
27
|
+
keeps its inode, owner and ACL. All rows of one call go in one buffer, then ``fsync``; a
|
|
28
|
+
failure that raises cuts the file back to its old size (still under the lock).
|
|
29
|
+
* Readers take no lock. A last line without ``\\n`` is an append in flight: skipped, reported as
|
|
30
|
+
torn, never parsed.
|
|
31
|
+
|
|
32
|
+
Privacy (G2): no query text, no file path text and no code in either ledger: hashes and ids only.
|
|
33
|
+
"""
|
|
34
|
+
from __future__ import annotations
|
|
35
|
+
|
|
36
|
+
import datetime as _dt
|
|
37
|
+
import fcntl
|
|
38
|
+
import hashlib
|
|
39
|
+
import json
|
|
40
|
+
import os
|
|
41
|
+
import re
|
|
42
|
+
import secrets
|
|
43
|
+
import socket
|
|
44
|
+
import subprocess
|
|
45
|
+
import time
|
|
46
|
+
from contextlib import contextmanager
|
|
47
|
+
from dataclasses import dataclass, field
|
|
48
|
+
from pathlib import Path
|
|
49
|
+
|
|
50
|
+
from . import config
|
|
51
|
+
from . import paths
|
|
52
|
+
|
|
53
|
+
SCHEMA = "fg-ledger/v1"
|
|
54
|
+
EXPOSURE_NAME = "exposure.jsonl"
|
|
55
|
+
OUTCOME_NAME = "outcome.jsonl"
|
|
56
|
+
LOCK_NAME = "ledger.lock"
|
|
57
|
+
|
|
58
|
+
# writer names (G3)
|
|
59
|
+
W_SEARCH = "scout-search"
|
|
60
|
+
W_ORACLE = "oracle-run"
|
|
61
|
+
W_PERSON = "person-mark"
|
|
62
|
+
# row kinds
|
|
63
|
+
K_EXPOSURE = "exposure"
|
|
64
|
+
K_ORACLE = "oracle"
|
|
65
|
+
K_MARK = "person-mark"
|
|
66
|
+
K_EVENT = "person-event"
|
|
67
|
+
|
|
68
|
+
WRITER_OF = {K_EXPOSURE: W_SEARCH, K_ORACLE: W_ORACLE, K_MARK: W_PERSON, K_EVENT: W_PERSON}
|
|
69
|
+
FILE_OF = {K_EXPOSURE: EXPOSURE_NAME, K_ORACLE: OUTCOME_NAME, K_MARK: OUTCOME_NAME, K_EVENT: OUTCOME_NAME}
|
|
70
|
+
COMMON = ("schema", "writer", "kind", "host", "time")
|
|
71
|
+
FIELDS = {
|
|
72
|
+
K_EXPOSURE: ("query_id", "query_sha256", "query_lang", "result_id", "pool", "trust", "item",
|
|
73
|
+
"lens", "rank", "score", "band", "slot"),
|
|
74
|
+
K_ORACLE: ("result_id", "run_id", "oracle", "verdict", "reused_at"),
|
|
75
|
+
K_MARK: ("mark_id", "result_id", "item", "who"),
|
|
76
|
+
K_EVENT: ("mark_id", "event_id", "event_time", "event_kind", "rc", "cmd_sha256", "root_sha256"),
|
|
77
|
+
}
|
|
78
|
+
SLOTS = ("top", "explore") # 8a writes only "top"; 8b adds the one-in-ten explore slot
|
|
79
|
+
EVENT_KINDS = ("build", "tests")
|
|
80
|
+
|
|
81
|
+
_HEX12 = r"[0-9a-f]{12}"
|
|
82
|
+
# Every pattern is ASCII-only and used with fullmatch (review F4: `$` takes a trailing newline,
|
|
83
|
+
# `\d` takes non-ASCII digits; either would let one id or time be spelt two ways).
|
|
84
|
+
_A = re.ASCII
|
|
85
|
+
QUERY_ID = re.compile(_HEX12, _A)
|
|
86
|
+
LENS = re.compile(r"[a-z][a-z0-9]{0,23}", _A)
|
|
87
|
+
RESULT_ID = re.compile(rf"fgr-({_HEX12})-([a-z][a-z0-9]{{0,23}})-([1-9][0-9]{{0,5}})", _A)
|
|
88
|
+
RUN_ID = re.compile(rf"fgv-{_HEX12}", _A)
|
|
89
|
+
MARK_ID = re.compile(rf"fgm-{_HEX12}", _A)
|
|
90
|
+
EVENT_ID = re.compile(rf"fge-{_HEX12}", _A)
|
|
91
|
+
SHA256 = re.compile(r"[0-9a-f]{64}", _A)
|
|
92
|
+
TIME = re.compile(r"[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}\.[0-9]{6}Z", _A) # fixed width: compares as text
|
|
93
|
+
# The one-line comment a handed-out snippet carries (V41-2). Python/shell `#`, C-family `//`.
|
|
94
|
+
RESULT_COMMENT = re.compile(r"^[ \t]*(?:#|//)[ \t]*forge-gate-result:[ \t]*(fgr-[0-9a-z-]+)[ \t]*$", re.M | re.A)
|
|
95
|
+
TEXT_MAX = 512
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
class LedgerError(RuntimeError):
|
|
99
|
+
"""The ledger cannot be written as asked. Nothing was kept."""
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
class Refused(LedgerError):
|
|
103
|
+
"""A writer's own rule refused the row (independence, unknown id, wrong verdict...)."""
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
class LockBusy(LedgerError):
|
|
107
|
+
"""Another writer holds ``ledger.lock`` longer than we waited."""
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
# ---------------------------------------------------------------- ids, time, the folder
|
|
111
|
+
|
|
112
|
+
def now_utc() -> str:
|
|
113
|
+
return _dt.datetime.now(_dt.timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%fZ")
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def new_query_id() -> str:
|
|
117
|
+
return secrets.token_hex(6)
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def new_run_id() -> str:
|
|
121
|
+
"""A run id for an oracle run (``forgeproof verify`` mints one per run)."""
|
|
122
|
+
return "fgv-" + secrets.token_hex(6)
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def make_result_id(query_id: str, lens: str, rank: int) -> str:
|
|
126
|
+
rid = f"fgr-{query_id}-{lens}-{rank}"
|
|
127
|
+
m = RESULT_ID.fullmatch(rid)
|
|
128
|
+
if m is None or m.groups() != (query_id, lens, str(rank)):
|
|
129
|
+
raise Refused(f"cannot make a result id from {query_id!r}, {lens!r}, {rank!r}")
|
|
130
|
+
return rid
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def result_ids_in(text: str) -> list[str]:
|
|
134
|
+
"""Result ids named by ``forge-gate-result:`` comment lines, in order, valid ones only."""
|
|
135
|
+
out = []
|
|
136
|
+
for m in RESULT_COMMENT.finditer(text):
|
|
137
|
+
rid = m.group(1)
|
|
138
|
+
if RESULT_ID.fullmatch(rid) and rid not in out:
|
|
139
|
+
out.append(rid)
|
|
140
|
+
return out
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def enabled() -> bool:
|
|
144
|
+
"""True when ``FORGE_GATE_LEDGER_DIR`` is set (it may still be wrong: writers check)."""
|
|
145
|
+
return config.configured(config.LEDGER_KEY) is not None
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def _dir(d) -> Path:
|
|
149
|
+
return Path(d) if d is not None else config.ledger_dir()
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def _sha(text: str) -> str:
|
|
153
|
+
return hashlib.sha256(text.encode("utf-8", "surrogateescape")).hexdigest()
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def _text(v, what: str) -> str:
|
|
157
|
+
if not isinstance(v, str) or not v.strip() or len(v) > TEXT_MAX or "\n" in v:
|
|
158
|
+
raise Refused(f"{what} must be one non-empty line of at most {TEXT_MAX} characters")
|
|
159
|
+
return v
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
# ---------------------------------------------------------------- one row check, both ways
|
|
163
|
+
|
|
164
|
+
def check_row(row, file_name: str) -> str:
|
|
165
|
+
"""'' when ``row`` is a well-formed row that belongs in ``file_name``, else the reason."""
|
|
166
|
+
if not isinstance(row, dict):
|
|
167
|
+
return "not a JSON object"
|
|
168
|
+
if row.get("schema") != SCHEMA:
|
|
169
|
+
return f"schema is {row.get('schema')!r}, not {SCHEMA!r}"
|
|
170
|
+
kind = row.get("kind")
|
|
171
|
+
if not isinstance(kind, str) or kind not in WRITER_OF: # review F1: a list is unhashable
|
|
172
|
+
return f"unknown kind {kind!r}"
|
|
173
|
+
if row.get("writer") != WRITER_OF[kind]:
|
|
174
|
+
return f"kind {kind!r} has writer {WRITER_OF[kind]!r}, not {row.get('writer')!r}"
|
|
175
|
+
if FILE_OF[kind] != file_name:
|
|
176
|
+
return f"kind {kind!r} belongs in {FILE_OF[kind]}, not {file_name}"
|
|
177
|
+
want = set(COMMON) | set(FIELDS[kind])
|
|
178
|
+
if set(row) != want:
|
|
179
|
+
return f"fields {sorted(set(row) ^ want)} missing or unexpected"
|
|
180
|
+
if not isinstance(row["host"], str) or not row["host"]:
|
|
181
|
+
return "host empty"
|
|
182
|
+
if not isinstance(row["time"], str) or not TIME.fullmatch(row["time"]):
|
|
183
|
+
return f"time {row['time']!r} not in the fixed UTC form"
|
|
184
|
+
return _check_kind(kind, row)
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def _check_kind(kind: str, r: dict) -> str:
|
|
188
|
+
def ok_text(v):
|
|
189
|
+
return isinstance(v, str) and v.strip() and len(v) <= TEXT_MAX and "\n" not in v
|
|
190
|
+
|
|
191
|
+
if kind == K_EXPOSURE:
|
|
192
|
+
m = RESULT_ID.fullmatch(r["result_id"]) if isinstance(r["result_id"], str) else None
|
|
193
|
+
if not (isinstance(r["query_id"], str) and QUERY_ID.fullmatch(r["query_id"])):
|
|
194
|
+
return "bad query_id"
|
|
195
|
+
if not (isinstance(r["query_sha256"], str) and SHA256.fullmatch(r["query_sha256"])):
|
|
196
|
+
return "bad query_sha256"
|
|
197
|
+
if not (isinstance(r["lens"], str) and LENS.fullmatch(r["lens"])):
|
|
198
|
+
return "bad lens"
|
|
199
|
+
if not (isinstance(r["rank"], int) and not isinstance(r["rank"], bool) and r["rank"] >= 1):
|
|
200
|
+
return "bad rank"
|
|
201
|
+
if m is None or (m.group(1), m.group(2), int(m.group(3))) != (r["query_id"], r["lens"], r["rank"]):
|
|
202
|
+
return "result_id does not name this query, lens and rank"
|
|
203
|
+
if not all(ok_text(r[k]) for k in ("query_lang", "pool", "trust", "item")):
|
|
204
|
+
return "query_lang, pool, trust and item must be non-empty one-line text"
|
|
205
|
+
if not isinstance(r["score"], (int, float)) or isinstance(r["score"], bool):
|
|
206
|
+
return "bad score"
|
|
207
|
+
if r["band"] is not None:
|
|
208
|
+
return "band must be null until 8b"
|
|
209
|
+
if r["slot"] not in SLOTS:
|
|
210
|
+
return f"slot {r['slot']!r} not in {SLOTS}"
|
|
211
|
+
return ""
|
|
212
|
+
if kind == K_ORACLE:
|
|
213
|
+
if not (isinstance(r["result_id"], str) and RESULT_ID.fullmatch(r["result_id"])):
|
|
214
|
+
return "bad result_id"
|
|
215
|
+
if not (isinstance(r["run_id"], str) and RUN_ID.fullmatch(r["run_id"])):
|
|
216
|
+
return "bad run_id"
|
|
217
|
+
if r["verdict"] != "PASS":
|
|
218
|
+
return "an oracle outcome is a PASS, nothing else"
|
|
219
|
+
if not ok_text(r["oracle"]):
|
|
220
|
+
return "bad oracle"
|
|
221
|
+
ra = r["reused_at"]
|
|
222
|
+
if not (isinstance(ra, dict) and set(ra) == {"file_sha256", "root_sha256", "content_sha256"}
|
|
223
|
+
and all(isinstance(v, str) and SHA256.fullmatch(v) for v in ra.values())):
|
|
224
|
+
return "bad reused_at"
|
|
225
|
+
return ""
|
|
226
|
+
if kind == K_MARK:
|
|
227
|
+
if not (isinstance(r["mark_id"], str) and MARK_ID.fullmatch(r["mark_id"])):
|
|
228
|
+
return "bad mark_id"
|
|
229
|
+
if r["result_id"] is not None and not (isinstance(r["result_id"], str) and RESULT_ID.fullmatch(r["result_id"])):
|
|
230
|
+
return "bad result_id"
|
|
231
|
+
if not ok_text(r["item"]) or not ok_text(r["who"]):
|
|
232
|
+
return "item and who must be non-empty one-line text"
|
|
233
|
+
return ""
|
|
234
|
+
# K_EVENT
|
|
235
|
+
if not (isinstance(r["mark_id"], str) and MARK_ID.fullmatch(r["mark_id"])):
|
|
236
|
+
return "bad mark_id"
|
|
237
|
+
if not (isinstance(r["event_id"], str) and EVENT_ID.fullmatch(r["event_id"])):
|
|
238
|
+
return "bad event_id"
|
|
239
|
+
if not (isinstance(r["event_time"], str) and TIME.fullmatch(r["event_time"])):
|
|
240
|
+
return "bad event_time"
|
|
241
|
+
if r["event_kind"] not in EVENT_KINDS:
|
|
242
|
+
return f"event_kind not in {EVENT_KINDS}"
|
|
243
|
+
if not isinstance(r["rc"], int) or isinstance(r["rc"], bool):
|
|
244
|
+
return "rc must be an integer"
|
|
245
|
+
if not all(isinstance(r[k], str) and SHA256.fullmatch(r[k]) for k in ("cmd_sha256", "root_sha256")):
|
|
246
|
+
return "cmd_sha256 and root_sha256 must be sha256 hex" # 8a F5 (decided 2026-11-16)
|
|
247
|
+
return ""
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
_run = subprocess.run # the event's measurement; module-private (review F3), tests patch it
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def _row(kind: str, now: str | None, **fields) -> dict:
|
|
254
|
+
row = {"schema": SCHEMA, "writer": WRITER_OF[kind], "kind": kind,
|
|
255
|
+
"host": socket.gethostname(), "time": now or now_utc(), **fields}
|
|
256
|
+
why = check_row(row, FILE_OF[kind])
|
|
257
|
+
if why:
|
|
258
|
+
raise Refused(f"{kind} row refused before writing: {why}")
|
|
259
|
+
return row
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
# ---------------------------------------------------------------- lock and append
|
|
263
|
+
|
|
264
|
+
@contextmanager
|
|
265
|
+
def _locked(d: Path, wait: float):
|
|
266
|
+
if not d.is_dir():
|
|
267
|
+
raise LedgerError(f"ledger folder {d} does not exist (the switch-on creates it)")
|
|
268
|
+
lock = d / LOCK_NAME
|
|
269
|
+
try:
|
|
270
|
+
fd = os.open(lock, os.O_RDONLY) # never O_CREAT: the switch-on creates the lock
|
|
271
|
+
except OSError as e:
|
|
272
|
+
raise LedgerError(f"cannot open {lock}: {e} (the switch-on creates it)") from None
|
|
273
|
+
try:
|
|
274
|
+
deadline = time.monotonic() + max(0.0, wait)
|
|
275
|
+
while True:
|
|
276
|
+
try:
|
|
277
|
+
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
|
278
|
+
break
|
|
279
|
+
except BlockingIOError:
|
|
280
|
+
if time.monotonic() >= deadline:
|
|
281
|
+
raise LockBusy(f"another ledger writer holds {lock}; waited {wait:g} s. "
|
|
282
|
+
"Nothing was written.") from None
|
|
283
|
+
time.sleep(0.05)
|
|
284
|
+
yield
|
|
285
|
+
finally:
|
|
286
|
+
os.close(fd)
|
|
287
|
+
|
|
288
|
+
|
|
289
|
+
def _append(path: Path, rows: list) -> None:
|
|
290
|
+
try:
|
|
291
|
+
fd = os.open(path, os.O_WRONLY | os.O_APPEND) # never O_CREAT, never a new inode
|
|
292
|
+
except OSError as e:
|
|
293
|
+
raise LedgerError(f"cannot open {path}: {e} (the switch-on creates it)") from None
|
|
294
|
+
try:
|
|
295
|
+
size = os.fstat(fd).st_size
|
|
296
|
+
if size:
|
|
297
|
+
with open(path, "rb") as fh:
|
|
298
|
+
fh.seek(size - 1)
|
|
299
|
+
if fh.read(1) != b"\n":
|
|
300
|
+
raise LedgerError(f"{path} does not end in a newline: an append would glue two "
|
|
301
|
+
"rows into one line. Nothing was written.")
|
|
302
|
+
data = b"".join(json.dumps(r, ensure_ascii=False, sort_keys=True).encode("utf-8") + b"\n"
|
|
303
|
+
for r in rows)
|
|
304
|
+
try:
|
|
305
|
+
view = memoryview(data)
|
|
306
|
+
while view:
|
|
307
|
+
n = os.write(fd, view)
|
|
308
|
+
view = view[n:]
|
|
309
|
+
os.fsync(fd)
|
|
310
|
+
except BaseException:
|
|
311
|
+
os.ftruncate(fd, size) # our own rows only: we hold the lock
|
|
312
|
+
os.fsync(fd)
|
|
313
|
+
raise
|
|
314
|
+
finally:
|
|
315
|
+
os.close(fd)
|
|
316
|
+
|
|
317
|
+
|
|
318
|
+
# ---------------------------------------------------------------- reading (no lock)
|
|
319
|
+
|
|
320
|
+
@dataclass
|
|
321
|
+
class Contents:
|
|
322
|
+
rows: dict = field(default_factory=lambda: {EXPOSURE_NAME: [], OUTCOME_NAME: []})
|
|
323
|
+
line: dict = field(default_factory=dict) # id(row) -> its line number (review F6)
|
|
324
|
+
refused: list = field(default_factory=list) # (file, line, reason)
|
|
325
|
+
torn: list = field(default_factory=list) # (file, line): an append in flight
|
|
326
|
+
|
|
327
|
+
|
|
328
|
+
def read(d=None) -> Contents:
|
|
329
|
+
"""Both ledgers, every line checked by :func:`check_row`. Raises LedgerError if unreadable."""
|
|
330
|
+
d = _dir(d)
|
|
331
|
+
out = Contents()
|
|
332
|
+
for name in (EXPOSURE_NAME, OUTCOME_NAME):
|
|
333
|
+
p = d / name
|
|
334
|
+
try:
|
|
335
|
+
data = p.read_bytes()
|
|
336
|
+
except OSError as e:
|
|
337
|
+
raise LedgerError(f"cannot read {p}: {e}") from None
|
|
338
|
+
lines = data.split(b"\n")
|
|
339
|
+
last = lines.pop()
|
|
340
|
+
if last:
|
|
341
|
+
out.torn.append((name, len(lines) + 1))
|
|
342
|
+
for n, raw in enumerate(lines, 1):
|
|
343
|
+
try:
|
|
344
|
+
row = json.loads(raw.decode("utf-8"))
|
|
345
|
+
except (UnicodeDecodeError, ValueError, RecursionError): # review F1
|
|
346
|
+
out.refused.append((name, n, "not a JSON line"))
|
|
347
|
+
continue
|
|
348
|
+
why = check_row(row, name)
|
|
349
|
+
if why:
|
|
350
|
+
out.refused.append((name, n, why))
|
|
351
|
+
else:
|
|
352
|
+
out.rows[name].append(row)
|
|
353
|
+
out.line[id(row)] = n
|
|
354
|
+
return out
|
|
355
|
+
|
|
356
|
+
|
|
357
|
+
@dataclass
|
|
358
|
+
class View:
|
|
359
|
+
"""The ledgers joined: result_id -> exposure, and the outcomes that can be placed."""
|
|
360
|
+
exposure: dict = field(default_factory=dict) # result_id -> first exposure row
|
|
361
|
+
oracle: dict = field(default_factory=dict) # (result_id, run_id) -> row
|
|
362
|
+
marks: dict = field(default_factory=dict) # mark_id -> row
|
|
363
|
+
events: dict = field(default_factory=dict) # mark_id -> [event rows]
|
|
364
|
+
refused: list = field(default_factory=list)
|
|
365
|
+
torn: list = field(default_factory=list)
|
|
366
|
+
orphans: list = field(default_factory=list) # outcome rows naming an id unknown here
|
|
367
|
+
|
|
368
|
+
|
|
369
|
+
def view(d=None) -> View:
|
|
370
|
+
c = read(d)
|
|
371
|
+
v = View(refused=list(c.refused), torn=list(c.torn))
|
|
372
|
+
for r in c.rows[EXPOSURE_NAME]:
|
|
373
|
+
old = v.exposure.get(r["result_id"])
|
|
374
|
+
if old is None:
|
|
375
|
+
v.exposure[r["result_id"]] = r
|
|
376
|
+
elif old["item"] != r["item"]:
|
|
377
|
+
v.refused.append((EXPOSURE_NAME, c.line[id(r)], f"{r['result_id']} names a second item"))
|
|
378
|
+
for r in c.rows[OUTCOME_NAME]:
|
|
379
|
+
if r["kind"] == K_ORACLE:
|
|
380
|
+
if r["result_id"] not in v.exposure:
|
|
381
|
+
v.orphans.append(r)
|
|
382
|
+
else:
|
|
383
|
+
v.oracle.setdefault((r["result_id"], r["run_id"]), r)
|
|
384
|
+
elif r["kind"] == K_MARK:
|
|
385
|
+
rid = r["result_id"]
|
|
386
|
+
if rid is not None and rid not in v.exposure:
|
|
387
|
+
v.orphans.append(r)
|
|
388
|
+
elif rid is not None and v.exposure[rid]["item"] != r["item"]:
|
|
389
|
+
v.refused.append((OUTCOME_NAME, c.line[id(r)], f"{r['mark_id']} item differs from {rid}'s"))
|
|
390
|
+
else:
|
|
391
|
+
v.marks.setdefault(r["mark_id"], r)
|
|
392
|
+
for r in c.rows[OUTCOME_NAME]:
|
|
393
|
+
if r["kind"] == K_EVENT:
|
|
394
|
+
if r["mark_id"] not in v.marks:
|
|
395
|
+
v.orphans.append(r)
|
|
396
|
+
else:
|
|
397
|
+
v.events.setdefault(r["mark_id"], []).append(r)
|
|
398
|
+
return v
|
|
399
|
+
|
|
400
|
+
|
|
401
|
+
def _scores(mark: dict, events: list) -> bool:
|
|
402
|
+
"""A mark scores once an event the tool ran passed AFTER the mark was made."""
|
|
403
|
+
return any(e["rc"] == 0 and e["event_time"] >= mark["time"] for e in events)
|
|
404
|
+
|
|
405
|
+
|
|
406
|
+
@dataclass(frozen=True)
|
|
407
|
+
class Counts:
|
|
408
|
+
"""Three counts side by side, never blended (V42-2), plus pending marks (never scored)."""
|
|
409
|
+
oracle: int = 0
|
|
410
|
+
person_with_id: int = 0
|
|
411
|
+
person_without_id: int = 0
|
|
412
|
+
pending: int = 0
|
|
413
|
+
blind: str = "" # non-empty: the ledger could not be read; counts mean nothing
|
|
414
|
+
|
|
415
|
+
|
|
416
|
+
def uncounted_outcomes(v: "View") -> int:
|
|
417
|
+
"""Outcome rows that were written but are not counted: refused rows and torn lines of the outcome
|
|
418
|
+
ledger, plus orphans (8b s6, re-check N1/N2; torn lines: 8b crew review, 6E T1). A reader shows BLIND instead of a 0 it cannot vouch for; exposure
|
|
419
|
+
refusals do not touch the counts and are not included. Read-only."""
|
|
420
|
+
return (sum(1 for f, _, _ in v.refused if f == OUTCOME_NAME) + len(v.orphans)
|
|
421
|
+
+ len(torn_outcome_lines(v))) # 8b crew review, 6E T1
|
|
422
|
+
|
|
423
|
+
|
|
424
|
+
def torn_outcome_lines(v: "View") -> list:
|
|
425
|
+
"""Line numbers of the outcome ledger's torn lines: an append in flight, or one a killed writer
|
|
426
|
+
left (then every later append is refused until the file is repaired). Read-only."""
|
|
427
|
+
return [n for f, n in v.torn if f == OUTCOME_NAME]
|
|
428
|
+
|
|
429
|
+
|
|
430
|
+
def counts(item: str, d=None, *, v: View | None = None) -> Counts:
|
|
431
|
+
if v is None:
|
|
432
|
+
try:
|
|
433
|
+
v = view(d)
|
|
434
|
+
except (LedgerError, config.NotConfigured) as e:
|
|
435
|
+
return Counts(blind=str(e))
|
|
436
|
+
# D1 as amended after the crew review (6E A9, A8) and N3 (the maintainer 2026-11-16): one reuse SITE is
|
|
437
|
+
# one PROJECT ROOT, whatever files and ids it holds and however often verify ran in it; one
|
|
438
|
+
# PERSON counts once per item, "with id" if any of their scored marks named a result id.
|
|
439
|
+
oracle = len({r["reused_at"]["root_sha256"] for (rid, _run), r in v.oracle.items()
|
|
440
|
+
if v.exposure[rid]["item"] == item})
|
|
441
|
+
scored, waiting = {}, set()
|
|
442
|
+
for mid, m in v.marks.items():
|
|
443
|
+
if m["item"] != item:
|
|
444
|
+
continue
|
|
445
|
+
who = m["who"]
|
|
446
|
+
if _scores(m, v.events.get(mid, [])):
|
|
447
|
+
scored[who] = scored.get(who, False) or m["result_id"] is not None
|
|
448
|
+
else:
|
|
449
|
+
waiting.add(who)
|
|
450
|
+
with_id = sum(1 for has_id in scored.values() if has_id)
|
|
451
|
+
without_id = len(scored) - with_id
|
|
452
|
+
return Counts(oracle, with_id, without_id, len(waiting - set(scored)))
|
|
453
|
+
|
|
454
|
+
|
|
455
|
+
def exposures(item: str, d=None, *, v: View | None = None) -> list:
|
|
456
|
+
v = view(d) if v is None else v
|
|
457
|
+
return [r for r in v.exposure.values() if r["item"] == item]
|
|
458
|
+
|
|
459
|
+
|
|
460
|
+
# ---------------------------------------------------------------- the three writers
|
|
461
|
+
|
|
462
|
+
def record_exposure(*, query_sha256: str, query_lang: str, hits: list, d=None,
|
|
463
|
+
wait: float = 10.0) -> tuple[str, list]:
|
|
464
|
+
"""Writer ``scout-search``. ``hits``: dicts with lens, rank, score, pool, trust, item.
|
|
465
|
+
|
|
466
|
+
Returns ``(query_id, rows)``; each row's ``result_id`` is what scout prints and hands out.
|
|
467
|
+
No hits: nothing is written (nothing was shown)."""
|
|
468
|
+
qid = new_query_id()
|
|
469
|
+
rows = [_row(K_EXPOSURE, None, query_id=qid, query_sha256=query_sha256, query_lang=query_lang,
|
|
470
|
+
result_id=make_result_id(qid, h["lens"], h["rank"]), pool=h["pool"], trust=h["trust"],
|
|
471
|
+
item=h["item"], lens=h["lens"], rank=h["rank"], score=h["score"], band=None,
|
|
472
|
+
slot=h.get("slot", "top"))
|
|
473
|
+
for h in hits]
|
|
474
|
+
if rows:
|
|
475
|
+
d = _dir(d)
|
|
476
|
+
with _locked(d, wait):
|
|
477
|
+
_append(d / EXPOSURE_NAME, rows)
|
|
478
|
+
return qid, rows
|
|
479
|
+
|
|
480
|
+
|
|
481
|
+
_real = paths.real
|
|
482
|
+
_canon = paths.canonical
|
|
483
|
+
_under = paths.is_under
|
|
484
|
+
|
|
485
|
+
|
|
486
|
+
def _surfaced_roots(d: Path) -> list:
|
|
487
|
+
"""Folders whose files are pool copies scout surfaced, not code where it was reused."""
|
|
488
|
+
roots = [_real(d)]
|
|
489
|
+
for key in (config.CORPUS_KEY, config.SCOUT_DIR_KEY): # the GitHub cache is under the scout dir
|
|
490
|
+
raw = config.configured(key)
|
|
491
|
+
if raw is not None:
|
|
492
|
+
roots.append(_real(config._as_path(raw)))
|
|
493
|
+
return roots
|
|
494
|
+
|
|
495
|
+
|
|
496
|
+
def _project_root(p: Path) -> Path:
|
|
497
|
+
for parent in p.parents:
|
|
498
|
+
if (parent / ".git").exists():
|
|
499
|
+
return parent
|
|
500
|
+
return p.parent
|
|
501
|
+
|
|
502
|
+
|
|
503
|
+
def _folder_root(p: Path) -> Path:
|
|
504
|
+
"""The project root of a FOLDER: itself or its nearest ancestor holding ``.git``; else itself.
|
|
505
|
+
In a git project, a file anywhere inside it gets the same answer from :func:`_project_root`
|
|
506
|
+
(both hashed through :func:`_canon`),
|
|
507
|
+
so an event and an oracle row in one project carry one ``root_sha256`` (without ``.git`` the
|
|
508
|
+
two can differ: a file's fallback is its own folder)."""
|
|
509
|
+
for q in (p, *p.parents):
|
|
510
|
+
if (q / ".git").exists():
|
|
511
|
+
return q
|
|
512
|
+
return p
|
|
513
|
+
|
|
514
|
+
|
|
515
|
+
def cmd_sha256(cmd: list) -> str:
|
|
516
|
+
"""The event's command as a hash of its argv in canonical JSON (8a F5): auditable by anyone who
|
|
517
|
+
knows the claimed command. The text is not stored, but a guessable argv is confirmable from its
|
|
518
|
+
hash (unsalted, KD-14 h). ensure_ascii stays on: an undecodable POSIX argv byte (surrogateescape)
|
|
519
|
+
is escaped, never an encode error that would lose the row."""
|
|
520
|
+
return _sha(json.dumps(cmd, separators=(",", ":")))
|
|
521
|
+
|
|
522
|
+
|
|
523
|
+
def record_oracle(*, result_id: str, run_id: str, oracle: str, verdict: str, verified_file,
|
|
524
|
+
content_sha256: str, d=None, wait: float = 10.0) -> dict:
|
|
525
|
+
"""Writer ``oracle-run``: an oracle run PASSED on reused code where it was reused (V4-2).
|
|
526
|
+
|
|
527
|
+
Refused: any verdict but PASS; a file inside the ledger folder, the corpus export or scout's
|
|
528
|
+
folder (that is code where scout surfaced it, not where it was reused); a result id the local
|
|
529
|
+
exposure ledger does not hold; the same (result_id, run_id) twice; a file with more than one
|
|
530
|
+
hard link; a file whose bytes are not ``content_sha256`` (the bytes the run judged, read before
|
|
531
|
+
it ran). The hook's snippet and looseness checks (D3) are NOT repeated here (KD-14 a)."""
|
|
532
|
+
if verdict != "PASS":
|
|
533
|
+
raise Refused(f"only a PASS is an oracle outcome, not {verdict!r}")
|
|
534
|
+
d = _dir(d)
|
|
535
|
+
f = _real(verified_file)
|
|
536
|
+
if not f.is_file():
|
|
537
|
+
raise Refused(f"verified file {verified_file} is not a file")
|
|
538
|
+
links = f.stat().st_nlink
|
|
539
|
+
if links > 1: # crew review 6E A3: a hard link has no surfaced
|
|
540
|
+
raise Refused(f"verified file {verified_file} has {links} hard links, so it cannot be shown "
|
|
541
|
+
"not to be a surfaced copy; verify a copy of its own") # ancestor to find
|
|
542
|
+
if hashlib.sha256(f.read_bytes()).hexdigest() != content_sha256: # 6E A1
|
|
543
|
+
raise Refused("the file's bytes are not the bytes the run judged (changed during the run, or "
|
|
544
|
+
"content_sha256 was not computed from this file); nothing was recorded")
|
|
545
|
+
for root in _surfaced_roots(d):
|
|
546
|
+
if _under(f, root):
|
|
547
|
+
raise Refused("the verified file lies where scout surfaced the code, not where it was "
|
|
548
|
+
"reused: not independent (design §4a.5)")
|
|
549
|
+
row = _row(K_ORACLE, None, result_id=result_id, run_id=run_id, oracle=_text(oracle, "oracle"),
|
|
550
|
+
verdict="PASS",
|
|
551
|
+
reused_at={"file_sha256": _sha(str(_canon(f))), "root_sha256": _sha(str(_canon(_project_root(f)))),
|
|
552
|
+
"content_sha256": content_sha256})
|
|
553
|
+
with _locked(d, wait):
|
|
554
|
+
v = view(d)
|
|
555
|
+
if result_id not in v.exposure:
|
|
556
|
+
raise Refused(f"{result_id} is not in this host's exposure ledger")
|
|
557
|
+
if (result_id, run_id) in v.oracle:
|
|
558
|
+
raise Refused(f"{result_id} already has an outcome from run {run_id}")
|
|
559
|
+
_append(d / OUTCOME_NAME, [row])
|
|
560
|
+
return row
|
|
561
|
+
|
|
562
|
+
|
|
563
|
+
def record_mark(*, who: str, result_id: str | None = None, item: str | None = None, d=None,
|
|
564
|
+
wait: float = 10.0) -> dict:
|
|
565
|
+
"""Writer ``person-mark``: "kept and it worked". Pending until :func:`record_event` passes.
|
|
566
|
+
|
|
567
|
+
Name the result (``result_id``) or, without one, the code itself (``item``), never both."""
|
|
568
|
+
if (result_id is None) == (item is None):
|
|
569
|
+
raise Refused("name exactly one: the result id, or (without one) the item")
|
|
570
|
+
d = _dir(d)
|
|
571
|
+
with _locked(d, wait):
|
|
572
|
+
if result_id is not None:
|
|
573
|
+
v = view(d)
|
|
574
|
+
if result_id not in v.exposure:
|
|
575
|
+
raise Refused(f"{result_id} is not in this host's exposure ledger")
|
|
576
|
+
item = v.exposure[result_id]["item"]
|
|
577
|
+
row = _row(K_MARK, None, mark_id="fgm-" + secrets.token_hex(6), result_id=result_id,
|
|
578
|
+
item=_text(item, "item"), who=_text(who, "who"))
|
|
579
|
+
_append(d / OUTCOME_NAME, [row])
|
|
580
|
+
return row
|
|
581
|
+
|
|
582
|
+
|
|
583
|
+
def record_event(*, mark_id: str, project, cmd: list, event_kind: str, d=None,
|
|
584
|
+
wait: float = 60.0) -> dict:
|
|
585
|
+
"""Writer ``person-mark``: the external event, RUN and MEASURED here, never typed in (G5 a).
|
|
586
|
+
|
|
587
|
+
Runs ``cmd`` (the reusing project's build or tests) in ``project`` as the calling user, and
|
|
588
|
+
records its exit code. The command is the person's own, with the trust of typing it in a
|
|
589
|
+
shell; it is never pool code (KD-14). Refused before running: an unknown mark, a mark dated
|
|
590
|
+
after now, a project inside a surfaced location. Checked again after the run, under the lock:
|
|
591
|
+
the event is not older than its mark (a clock stepped back during the run). The command
|
|
592
|
+
runs BEFORE the lock is taken (a test run can be long); if another writer then holds the lock
|
|
593
|
+
longer than ``wait``, the result is dropped with LockBusy and the event must be run again.
|
|
594
|
+
Neither the time nor the exit code can be passed in (review F3). The row keeps the command and
|
|
595
|
+
the project only as hashes, ``cmd_sha256`` and ``root_sha256`` (8a F5): for audit, not scoring."""
|
|
596
|
+
if event_kind not in EVENT_KINDS:
|
|
597
|
+
raise Refused(f"event kind {event_kind!r} not in {EVENT_KINDS}")
|
|
598
|
+
if not cmd or not all(isinstance(a, str) for a in cmd):
|
|
599
|
+
raise Refused("no command to run")
|
|
600
|
+
d = _dir(d)
|
|
601
|
+
proj = Path(project)
|
|
602
|
+
if not proj.is_dir():
|
|
603
|
+
raise Refused(f"project {project} is not a folder")
|
|
604
|
+
for root in _surfaced_roots(d): # never pool code (G5; 8a s4 review F1)
|
|
605
|
+
if _under(_real(proj), root):
|
|
606
|
+
raise Refused(f"project {project} lies where scout surfaced code ({root}), not where it "
|
|
607
|
+
"was reused: pool code is never run; nothing was run")
|
|
608
|
+
mark = view(d).marks.get(mark_id)
|
|
609
|
+
if mark is None:
|
|
610
|
+
raise Refused(f"{mark_id} is not a mark in this host's outcome ledger; nothing was run")
|
|
611
|
+
if now_utc() < mark["time"]: # 8a crew review (5S C5): refused BEFORE the run
|
|
612
|
+
raise Refused(f"the mark is dated {mark['time']}, after now: an event now would be older "
|
|
613
|
+
"than its mark; nothing was run")
|
|
614
|
+
# hashed BEFORE the run (8a s7 review F3): the command must not choose its own audit root
|
|
615
|
+
argv_hash, root_hash = cmd_sha256(cmd), _sha(str(_canon(_folder_root(_real(proj)))))
|
|
616
|
+
try:
|
|
617
|
+
# the command's own output goes to stderr (fd 2): stdout carries only forgeproof's line,
|
|
618
|
+
# so nothing the command prints can pass for a recorded result (8a s4 review F4)
|
|
619
|
+
rc = _run(cmd, cwd=str(proj), stdout=2).returncode
|
|
620
|
+
except OSError as e:
|
|
621
|
+
raise LedgerError(f"could not run {cmd[0]!r}: {e}. Nothing was recorded.") from None
|
|
622
|
+
t = now_utc()
|
|
623
|
+
row = _row(K_EVENT, t, mark_id=mark_id, event_id="fge-" + secrets.token_hex(6), event_time=t,
|
|
624
|
+
event_kind=event_kind, rc=rc, cmd_sha256=argv_hash, root_sha256=root_hash)
|
|
625
|
+
with _locked(d, wait):
|
|
626
|
+
v = view(d)
|
|
627
|
+
mark = v.marks.get(mark_id)
|
|
628
|
+
if mark is None:
|
|
629
|
+
raise Refused(f"{mark_id} vanished from the outcome ledger; nothing was recorded")
|
|
630
|
+
if t < mark["time"]:
|
|
631
|
+
raise Refused(f"the event ({t}) is older than its mark ({mark['time']})")
|
|
632
|
+
_append(d / OUTCOME_NAME, [row])
|
|
633
|
+
return row
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
"""The lens tools: metamorphic, invariant, twin-consensus and guard.
|
|
2
|
+
|
|
3
|
+
They ship inside the package (KNOWN-DEBT KD-2, done 2026-11-25), so an installed ForgeProof
|
|
4
|
+
runs every lens without a source checkout and without FORGE_GATE_HOME. ``forgeproof.lenses``
|
|
5
|
+
imports metamorphic, invariant_gate and twin_consensus from here, and runs guard_lens.py as a
|
|
6
|
+
script by its file path (``GUARD_LENS``) in a child process.
|
|
7
|
+
"""
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
HERE = Path(__file__).resolve().parent
|
|
11
|
+
GUARD_LENS = HERE / "guard_lens.py"
|