agent-bios 0.19.4 → 0.20.0
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.
- package/DEPENDENCIES.md +19 -5
- package/README.md +14 -19
- package/claude/agents/frontier.md +1 -1
- package/claude/guides/claude-prompting.md +475 -234
- package/claude/guides/cli-multi-model-workflow.md +4 -3
- package/claude/guides/gpt-prompting.md +235 -136
- package/claude/guides/session-distill-workflow.md +93 -43
- package/claude/guides/tooling-gotchas.md +3 -1
- package/codex/guides/claude-prompting.md +475 -234
- package/codex/guides/cli-multi-model-workflow.md +4 -3
- package/codex/guides/gpt-prompting.md +235 -136
- package/codex/guides/session-distill-workflow.md +93 -43
- package/codex/guides/tooling-gotchas.md +3 -1
- package/compose/assemble.py +4 -1
- package/compose/canary.sh +8 -6
- package/compose/host_platform.py +158 -15
- package/compose/instructions-state.py +183 -41
- package/compose/instructions_install.py +222 -27
- package/compose/instructions_session.py +250 -75
- package/compose/instructions_setup_cli.py +2 -36
- package/compose/instructions_store.py +160 -3
- package/compose/instructions_transaction.py +29 -5
- package/docs/advanced-launch.md +4 -0
- package/docs/releases/0.20.0.md +102 -0
- package/install.sh +42 -14
- package/launch/agent-launch.py +152 -18
- package/launch/agent-launch.toml +17 -7
- package/launch/agent-launch.zsh +104 -13
- package/launch/claude_subcommands.py +179 -0
- package/launch/shell_integration.py +7 -1
- package/learn/collect-learning.py +60 -9
- package/learn/migrate-learnings.py +70 -4
- package/learn/redact.py +2 -1
- package/package.json +36 -3
- package/provenance.json +1 -1
- package/session-cost.py +80 -9
- package/session-distill/coverage.json +6 -0
- package/session-distill/distill.py +2575 -0
- package/session-distill/grammar/__init__.py +0 -0
- package/session-distill/grammar/owner_lines.py +874 -0
- package/session-distill/originators.json +9 -0
- package/session-distill/packets/cross_review.md +31 -0
- package/session-distill/packets/form.md +86 -0
- package/session-distill/packets/judge.md +81 -0
- package/session-distill/packets/placement_contract.md +90 -0
- package/session-distill/packets/propose.md +124 -0
- package/session-distill/packets/read.md +57 -0
- package/session-distill/packets/reconsider.md +53 -0
- package/session-distill/packets/s7b.md +65 -0
- package/session-distill/packets/s9b.md +39 -0
- package/session-distill/packets/stitch.md +35 -0
- package/session-distill/packets/sweep.md +33 -0
- package/session-distill/runlib/__init__.py +0 -0
- package/session-distill/runlib/bound.py +1102 -0
- package/session-distill/runlib/breaker.py +467 -0
- package/session-distill/runlib/census.py +2347 -0
- package/session-distill/runlib/claims.py +420 -0
- package/session-distill/runlib/controls.py +902 -0
- package/session-distill/runlib/coverage.py +881 -0
- package/session-distill/runlib/declare.py +888 -0
- package/session-distill/runlib/delivery_evidence.py +1145 -0
- package/session-distill/runlib/derive.py +812 -0
- package/session-distill/runlib/destinations.py +3072 -0
- package/session-distill/runlib/dispatch.py +7939 -0
- package/session-distill/runlib/drift.py +1077 -0
- package/session-distill/runlib/entry.py +401 -0
- package/session-distill/runlib/evidence.py +890 -0
- package/session-distill/runlib/exposure.py +1162 -0
- package/session-distill/runlib/gate.py +2727 -0
- package/session-distill/runlib/gitread.py +79 -0
- package/session-distill/runlib/inventory.py +19624 -0
- package/session-distill/runlib/journal.py +1919 -0
- package/session-distill/runlib/ledger.py +3210 -0
- package/session-distill/runlib/ledger_compat.py +101 -0
- package/session-distill/runlib/ledger_migration.py +190 -0
- package/session-distill/runlib/lifecycle_intake.py +693 -0
- package/session-distill/runlib/lineage.py +454 -0
- package/session-distill/runlib/measures.py +249 -0
- package/session-distill/runlib/monitor.py +1180 -0
- package/session-distill/runlib/operations.py +522 -0
- package/session-distill/runlib/packet.py +838 -0
- package/session-distill/runlib/placement.py +1769 -0
- package/session-distill/runlib/projection.py +4090 -0
- package/session-distill/runlib/ranking.py +740 -0
- package/session-distill/runlib/receipts.py +200 -0
- package/session-distill/runlib/records.py +1965 -0
- package/session-distill/runlib/search.py +249 -0
- package/session-distill/runlib/sequencing.py +829 -0
- package/session-distill/runlib/sources.py +641 -0
- package/session-distill/runlib/stage_adjudicate.py +845 -0
- package/session-distill/runlib/stage_apply.py +1378 -0
- package/session-distill/runlib/stage_approvals.py +758 -0
- package/session-distill/runlib/stage_close.py +1220 -0
- package/session-distill/runlib/stage_confirm.py +929 -0
- package/session-distill/runlib/stage_delivery.py +3080 -0
- package/session-distill/runlib/stage_form.py +2576 -0
- package/session-distill/runlib/stage_judge.py +4248 -0
- package/session-distill/runlib/stage_propose.py +3307 -0
- package/session-distill/runlib/stage_read.py +5179 -0
- package/session-distill/runlib/stage_render.py +2739 -0
- package/session-distill/runlib/stage_retrieve.py +924 -0
- package/session-distill/runlib/stage_review_korean.py +1002 -0
- package/session-distill/runlib/stage_review_proposals.py +1292 -0
- package/session-distill/runlib/stagelock.py +412 -0
- package/session-distill/runlib/stop.py +1061 -0
- package/session-distill/runlib/targets.py +809 -0
- package/session-distill/runlib/usage.py +280 -0
- package/session-distill/runlib/validate.py +319 -0
- package/session-distill/runlib/views.py +4327 -0
- package/session-distill/schemas/adjudication.schema.json +35 -0
- package/session-distill/schemas/approval.schema.json +35 -0
- package/session-distill/schemas/census.schema.json +128 -0
- package/session-distill/schemas/checks.schema.json +207 -0
- package/session-distill/schemas/claim.schema.json +16 -0
- package/session-distill/schemas/confirmation.schema.json +24 -0
- package/session-distill/schemas/coverage.schema.json +66 -0
- package/session-distill/schemas/cross_review.schema.json +24 -0
- package/session-distill/schemas/event.schema.json +20 -0
- package/session-distill/schemas/evidence.schema.json +20 -0
- package/session-distill/schemas/expected_observation.schema.json +18 -0
- package/session-distill/schemas/form.schema.json +103 -0
- package/session-distill/schemas/intake.schema.json +71 -0
- package/session-distill/schemas/inventory.schema.json +872 -0
- package/session-distill/schemas/judge.schema.json +77 -0
- package/session-distill/schemas/ledger.schema.json +313 -0
- package/session-distill/schemas/observation.schema.json +16 -0
- package/session-distill/schemas/propose.schema.json +555 -0
- package/session-distill/schemas/read.schema.json +76 -0
- package/session-distill/schemas/reconsider.schema.json +122 -0
- package/session-distill/schemas/run.schema.json +150 -0
- package/session-distill/schemas/s7b.schema.json +200 -0
- package/session-distill/schemas/s9b.schema.json +28 -0
- package/session-distill/schemas/stitch.schema.json +25 -0
- package/session-distill/schemas/sweep.schema.json +25 -0
- package/session-distill/seats.json +149 -0
- package/session-distill/tables/allowed_pairs.json +257 -0
- package/session-distill/tables/controls.json +30 -0
- package/session-distill/tables/delivery_evidence.json +36 -0
- package/session-distill/tables/delivery_evidence_fixtures.json +731 -0
- package/session-distill/tables/destinations.json +684 -0
- package/session-distill/tables/drift_layers.json +68 -0
- package/session-distill/tables/exposure_rules.json +192 -0
- package/session-distill/tables/placement_rules.json +148 -0
- package/session-distill/tables/propose_fixtures.json +154 -0
- package/session-distill/tables/ranking.json +194 -0
- package/session-distill/tables/redundancy.json +10 -0
- package/session-distill/tables/structural_rules.json +44 -0
- package/session-distill/tables/transition_fixtures.json +398 -0
- package/session-distill/tables/transitions.json +69 -0
- package/session-distill/tables/unit_outcome.json +67 -0
- package/session-distill/tables/unit_outcome_fixtures.json +2364 -0
- package/wrappers/claude-run.sh +481 -33
- package/wrappers/claude_hermetic_evidence.py +1423 -0
- package/wrappers/codex-helm.sh +38 -7
- package/wrappers/codex-run.sh +183 -20
- package/wrappers/codex_frame_filter.py +1199 -0
- package/wrappers/codex_protocol.py +737 -0
- package/wrappers/jsonl_lines.py +65 -0
|
@@ -0,0 +1,693 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""S4's lifecycle intake (plan WP-09; design §7.1, §7.4): the lifecycle inputs produced by code before formation.
|
|
3
|
+
|
|
4
|
+
Five sources, each a list of lifecycle candidates with an id of its own (`<source>:<target>`), so two candidates from
|
|
5
|
+
one entry or unit are two rows of the population (lead, D5 scope):
|
|
6
|
+
|
|
7
|
+
- `due_decision`: every incubate decision a run made that no later decision of its entry resolves
|
|
8
|
+
(`ledger.unresolved_incubates`, design §7.1's `resolves`), whose expiry is on or before the window's last day: an
|
|
9
|
+
incubating entry's, or a pending intervention on a placed entry (§12.3). Each carries the decision it resolves and
|
|
10
|
+
the window's occasions S3 judged for its observation (`observations/<window>.jsonl`, `observations/resolutions.json`).
|
|
11
|
+
- `legacy`: every `incubating` entry that has received no applied decision of a run, marked `legacy, observation
|
|
12
|
+
unavailable` (design §7.1's legacy incubation), in every run until it receives one.
|
|
13
|
+
- `obsolete_hint`: a unit of the occasion index S12 writes (WP-21) with no match in its three latest windows, all of
|
|
14
|
+
basis source (`obsolete_hints`). The index does not exist yet; its rows are golden here, and a run with no index takes
|
|
15
|
+
none, saying so.
|
|
16
|
+
- `redundancy_hint`: every pair of operative units of the current library (S2's `inventory/current.json`, the layers
|
|
17
|
+
`tables/redundancy.json` excludes left out by name) whose similarity reaches the table's fixed threshold
|
|
18
|
+
(`redundancy_pairs`). More pairs than the table's ceiling are refused (REDUNDANCY_OVER_CEILING), never cut.
|
|
19
|
+
- `g_cluster`: design §7.4's upward distillation: at least three placed learnings whose top retrieval hit over the same
|
|
20
|
+
units is one unit (`upward_clusters`), the reading of "share retrieved principle text" lead decision D6 (iii)
|
|
21
|
+
adopted. An arc retrospective needs a declared arc, and the declaration has no field for one, so there is none.
|
|
22
|
+
|
|
23
|
+
The pinned ledger is read as S3 reads it (`stage_read.pinned_ledger`); a schema 1 ledger is migrated in memory by the
|
|
24
|
+
cutover's own function (`ledger_migration.migrate`, lead decision D4) and never written.
|
|
25
|
+
|
|
26
|
+
`intake_problems` holds an intake against a fresh derivation of every source by id (plan WP-09 done-when 3): an id a
|
|
27
|
+
source derives that the intake lacks, or one the intake holds that no source derives, is INTAKE_INCOMPLETE by name.
|
|
28
|
+
|
|
29
|
+
lifecycle_intake.py --self-test
|
|
30
|
+
"""
|
|
31
|
+
import collections
|
|
32
|
+
import copy
|
|
33
|
+
import datetime
|
|
34
|
+
import hashlib
|
|
35
|
+
import json
|
|
36
|
+
import math
|
|
37
|
+
import pathlib
|
|
38
|
+
import sys
|
|
39
|
+
import tempfile
|
|
40
|
+
|
|
41
|
+
if __package__ in (None, ""): # run as a script: put session-distill/ on the import path
|
|
42
|
+
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
|
43
|
+
from runlib import coverage, ledger as ledger_lib, ledger_migration, records, search, stagelock, validate
|
|
44
|
+
from runlib.records import Refused
|
|
45
|
+
|
|
46
|
+
HERE = pathlib.Path(__file__).resolve().parents[1]
|
|
47
|
+
TABLE_PATH = HERE / "tables" / "redundancy.json"
|
|
48
|
+
SCHEMA_PATH = HERE / "schemas" / "intake.schema.json"
|
|
49
|
+
SOURCES = ("due_decision", "legacy", "obsolete_hint", "redundancy_hint", "g_cluster") # = stage_form.INTAKE_SOURCES
|
|
50
|
+
LEGACY_MARK = "legacy, observation unavailable" # design §7.1
|
|
51
|
+
OBSOLETE_RUN = 3 # design §7.1: "no match in three consecutive windows of basis source"
|
|
52
|
+
UPWARD_MIN = 3 # design §7.4: "clusters of at least three placed learnings"
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
# The checkout ledger this module's D4 leg copies, set by an author-side caller
|
|
56
|
+
# (`gates/check-ledger.py`); None in an installed tree, where the leg copies nothing.
|
|
57
|
+
CHECKOUT_LEDGER = None
|
|
58
|
+
|
|
59
|
+
def table():
|
|
60
|
+
return json.loads(TABLE_PATH.read_text(encoding="utf-8"))
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
# ---- the pinned ledger -----------------------------------------------------------------------------
|
|
64
|
+
|
|
65
|
+
def ledger_of(declaration, ledger_ref=None):
|
|
66
|
+
"""`(schema 2 document, how it was had)` of the ledger the declaration pins: a schema 2 ledger as it is, a schema 1
|
|
67
|
+
ledger migrated in memory by the cutover's function. Nothing is written.
|
|
68
|
+
|
|
69
|
+
`ledger_ref` names the ledger inside the declaration's checkout; without one, the module-level `CHECKOUT_LEDGER`
|
|
70
|
+
the author-side caller sets. A packaged run has neither, and is then refused by name (LEDGER_UNNAMED S3) rather
|
|
71
|
+
than reading whatever file a guessed path lands on."""
|
|
72
|
+
from runlib import stage_read
|
|
73
|
+
doc = stage_read.pinned_ledger(declaration, ledger_ref or CHECKOUT_LEDGER)
|
|
74
|
+
if doc.get("schema") == 2:
|
|
75
|
+
return doc, "schema 2"
|
|
76
|
+
try:
|
|
77
|
+
migrated, _removed = ledger_migration.migrate(doc)
|
|
78
|
+
except ledger_migration.MigrationError as exc:
|
|
79
|
+
raise Refused(f"LEDGER_INVALID S4: the schema {doc.get('schema')} pin does not migrate: {exc}") from exc
|
|
80
|
+
return migrated, f"schema {doc.get('schema')}, migrated in memory"
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def last_day(window):
|
|
84
|
+
"""The last day a half-open window covers, in its own zone."""
|
|
85
|
+
_start, end, _id = coverage.window_bounds(window)
|
|
86
|
+
return (end - datetime.timedelta(microseconds=1)).date().isoformat()
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
# ---- (a) and (b): from the ledger ------------------------------------------------------------------
|
|
90
|
+
|
|
91
|
+
def due_decisions(doc, window, occasions=None):
|
|
92
|
+
"""Design §7.1's due decisions: every unresolved incubate whose expiry is on or before the window's last day, with
|
|
93
|
+
the window's occasions for its observation (`occasions` maps a decision id to them)."""
|
|
94
|
+
day, out = last_day(window), []
|
|
95
|
+
for d in ledger_lib.unresolved_incubates(doc):
|
|
96
|
+
if d["expiry"] <= day:
|
|
97
|
+
out.append({"candidate_id": f"due_decision:{d['decision_id']}", "source": "due_decision", "target_entry": d["entry"],
|
|
98
|
+
"resolves": d["decision_id"], "entry_status": d["status"], "expiry": d["expiry"],
|
|
99
|
+
"pending_intervention": d["status"] == "placed",
|
|
100
|
+
"occasions": (occasions or {}).get(d["decision_id"], {"instances": [], "resolution": None})})
|
|
101
|
+
return out
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def legacy_incubation(doc):
|
|
105
|
+
"""Design §7.1's legacy incubation: every incubating entry with no applied decision of a run."""
|
|
106
|
+
out = []
|
|
107
|
+
for entry in doc["entries"]:
|
|
108
|
+
if entry["status"] != "incubating":
|
|
109
|
+
continue
|
|
110
|
+
if any(not ledger_lib.is_legacy(d) and d["applied"] is not None for d in entry["decisions"]):
|
|
111
|
+
continue
|
|
112
|
+
out.append({"candidate_id": f"legacy:{entry['id']}", "source": "legacy", "target_entry": entry["id"],
|
|
113
|
+
"resolves": None, "marks": [LEGACY_MARK],
|
|
114
|
+
"type": (entry.get("classification") or {}).get("type")})
|
|
115
|
+
return sorted(out, key=lambda c: c["candidate_id"])
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def window_occasions(run_dir, window):
|
|
119
|
+
"""The occasions S3 judged in this window for each due observation, by its id, and the resolution it derived: read
|
|
120
|
+
through S3's own reader of its follow-up (`stage_read.stored_resolutions`), which believes the instances only when
|
|
121
|
+
their lines are the ones S3 recorded and each resolution only when they derive it again (INSTANCE_IMMUTABLE,
|
|
122
|
+
RESOLUTION_DRIFT). A follow-up of another window is refused by name (INPUT_INVALID)."""
|
|
123
|
+
from runlib import stage_read
|
|
124
|
+
run_dir = pathlib.Path(run_dir)
|
|
125
|
+
_s, _e, window_id = coverage.window_bounds(window)
|
|
126
|
+
doc = stage_read.stored_resolutions(run_dir)
|
|
127
|
+
if doc["window"] != window_id:
|
|
128
|
+
raise Refused(f"INPUT_INVALID {stage_read.RESOLUTIONS}: S3's follow-up is of {doc['window']!r}, and this run's "
|
|
129
|
+
f"window is {window_id!r}")
|
|
130
|
+
rows = [json.loads(line) for line in records.jsonl_read(stagelock.confine(run_dir, run_dir / doc["instances"]))
|
|
131
|
+
if line.strip()]
|
|
132
|
+
out = collections.defaultdict(lambda: {"instances": [], "resolution": None})
|
|
133
|
+
for r in rows:
|
|
134
|
+
out[r["expected_id"]]["instances"].append({k: r[k] for k in ("occasion_locator", "exposure", "verdict", "basis")})
|
|
135
|
+
for ident, r in doc["resolutions"].items():
|
|
136
|
+
out[ident]["resolution"] = r["resolution"]
|
|
137
|
+
return dict(out)
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
# ---- (c): the occasion index's hints --------------------------------------------------------------
|
|
142
|
+
|
|
143
|
+
def obsolete_hints(index_rows):
|
|
144
|
+
"""Design §7.1: a unit with no match in its three latest windows, each of basis source. `index_rows` are the
|
|
145
|
+
occasion index's rows `{window_start, unit_id, matched, basis}` (WP-21 writes them; golden until it does). A window of
|
|
146
|
+
another basis ends the run of source windows, as a match does: only consecutive source windows count."""
|
|
147
|
+
by_unit = collections.defaultdict(list)
|
|
148
|
+
for r in index_rows:
|
|
149
|
+
by_unit[r["unit_id"]].append(r)
|
|
150
|
+
out = []
|
|
151
|
+
for unit, rows in sorted(by_unit.items()):
|
|
152
|
+
run = 0
|
|
153
|
+
for r in sorted(rows, key=lambda r: r["window_start"]):
|
|
154
|
+
run = run + 1 if (r["basis"] == "source" and not r["matched"]) else 0
|
|
155
|
+
if run >= OBSOLETE_RUN:
|
|
156
|
+
out.append({"candidate_id": f"obsolete_hint:{unit}", "source": "obsolete_hint", "target_unit": unit,
|
|
157
|
+
"windows_without_match": run})
|
|
158
|
+
return out
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
# ---- (d) and (e): BM25 over the current library's units -------------------------------------------
|
|
162
|
+
|
|
163
|
+
def keys_tf(text):
|
|
164
|
+
"""A unit's keys with their counts, as the full-source search keys a block (search.keys_of): lowercase words, and
|
|
165
|
+
the character bigrams of a Hangul or CJK run."""
|
|
166
|
+
counts = collections.Counter(w.lower() for w in search.WORD.findall(text) if len(w) <= search.MAX_KEY)
|
|
167
|
+
for run in search.CJK.findall(text):
|
|
168
|
+
counts.update(run[i:i + 2] for i in range(len(run) - 1))
|
|
169
|
+
return counts, len(search.WORD.findall(text))
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
class Library:
|
|
173
|
+
"""BM25 (search.K1, search.B) over a set of documents `{id: text}`: `scores(query keys)` is every document's score
|
|
174
|
+
for a query's distinct keys, through an inverted index."""
|
|
175
|
+
|
|
176
|
+
def __init__(self, docs):
|
|
177
|
+
self.ids = sorted(docs)
|
|
178
|
+
self.tf, self.length = {}, {}
|
|
179
|
+
postings = collections.defaultdict(list)
|
|
180
|
+
for ident in self.ids:
|
|
181
|
+
counts, n = keys_tf(docs[ident])
|
|
182
|
+
self.tf[ident], self.length[ident] = counts, max(n, 1)
|
|
183
|
+
for key in counts:
|
|
184
|
+
postings[key].append(ident)
|
|
185
|
+
self.postings = dict(postings)
|
|
186
|
+
self.avg = (sum(self.length.values()) / len(self.ids)) if self.ids else 1.0
|
|
187
|
+
size = len(self.ids)
|
|
188
|
+
self.idf = {k: math.log(1 + (size - len(p) + 0.5) / (len(p) + 0.5)) for k, p in self.postings.items()}
|
|
189
|
+
|
|
190
|
+
def scores(self, keys):
|
|
191
|
+
out = collections.defaultdict(float)
|
|
192
|
+
for key in keys:
|
|
193
|
+
for ident in self.postings.get(key, ()):
|
|
194
|
+
tf = self.tf[ident][key]
|
|
195
|
+
out[ident] += self.idf[key] * tf * (search.K1 + 1) / (
|
|
196
|
+
tf + search.K1 * (1 - search.B + search.B * self.length[ident] / self.avg))
|
|
197
|
+
return out
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def relative_path(unit):
|
|
201
|
+
"""Where a unit's text sits, relative to the checkout or project that holds it (lead, D5 scope after X round 1). A
|
|
202
|
+
native unit's path is recorded as `<host>:<type>:<path the host reported>` (inventory.member_carrier) and its
|
|
203
|
+
provenance names its scope, the session's working directory, masked as the path is; a path under the scope is taken
|
|
204
|
+
from it, so one file's copies in two checkouts read the same, and any other path is kept whole. Every other layer's
|
|
205
|
+
path is already the checkout's own (a catalog guide, `<ledger>#<entry>`, an overlay)."""
|
|
206
|
+
path = unit.get("path") or ""
|
|
207
|
+
if not unit["layer"].startswith("native_"):
|
|
208
|
+
return path
|
|
209
|
+
reported = path.split(":", 2)[2] if path.count(":") >= 2 else path
|
|
210
|
+
scope = ((unit.get("provenance") or {}).get("scope") or "").rstrip("/")
|
|
211
|
+
return reported[len(scope) + 1:] if scope and reported.startswith(scope + "/") else reported
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def eligible_units(units, spec):
|
|
215
|
+
"""The current library's units a hint reads, and what was left out, counted: operative units outside the table's
|
|
216
|
+
excluded layers, one per fragment sha, with at least the table's `min_keys` distinct keys. Identical text is read
|
|
217
|
+
once: where its copies share one layer and one relative path (`relative_path`) they are one file's copies, folded and
|
|
218
|
+
counted; where they sit in more than one place, the group is returned as well, as identical text the owner can
|
|
219
|
+
reduce. Returns `(kept, counts, identical groups)`, each group the unit ids of one unit per place, the kept one first."""
|
|
220
|
+
operative = [u for u in units if u["class"] == "operative"]
|
|
221
|
+
left = collections.Counter(u["layer"] for u in operative if u["layer"] in spec["excluded_layers"])
|
|
222
|
+
groups = collections.defaultdict(list)
|
|
223
|
+
for u in sorted((u for u in operative if u["layer"] not in spec["excluded_layers"]), key=lambda u: u["unit_id"]):
|
|
224
|
+
groups[u["sha"]].append(u)
|
|
225
|
+
distinct, places_of, copies = [], {}, 0
|
|
226
|
+
for members in groups.values():
|
|
227
|
+
places = {}
|
|
228
|
+
for u in members:
|
|
229
|
+
places.setdefault((u["layer"], relative_path(u)), u)
|
|
230
|
+
copies += len(members) - len(places)
|
|
231
|
+
distinct.append(members[0])
|
|
232
|
+
places_of[members[0]["unit_id"]] = sorted(u["unit_id"] for u in places.values())
|
|
233
|
+
kept = sorted((u for u in distinct if len(keys_tf(u["text"])[0]) >= spec["min_keys"]), key=lambda u: u["unit_id"])
|
|
234
|
+
identical = [places_of[u["unit_id"]] for u in kept if len(places_of[u["unit_id"]]) > 1]
|
|
235
|
+
return kept, {"excluded_layers": dict(sorted(left.items())), "identical_copies_folded": copies,
|
|
236
|
+
"identical_groups": len(identical), "below_min_keys": len(distinct) - len(kept),
|
|
237
|
+
"eligible": len(kept)}, identical
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
def similarities(units):
|
|
241
|
+
"""Every pair of `units` sharing a key, with its similarity: the smaller of the two directions, each one unit's
|
|
242
|
+
BM25 over the other divided by its BM25 over itself. Returns `{(a, b): score}` with a < b."""
|
|
243
|
+
lib = Library({u["unit_id"]: u["text"] for u in units})
|
|
244
|
+
selfs, cross = {}, {}
|
|
245
|
+
for a in lib.ids:
|
|
246
|
+
row = lib.scores(lib.tf[a])
|
|
247
|
+
selfs[a] = row.get(a, 0.0)
|
|
248
|
+
cross[a] = row
|
|
249
|
+
out = {}
|
|
250
|
+
for a in lib.ids:
|
|
251
|
+
if selfs[a] <= 0:
|
|
252
|
+
continue
|
|
253
|
+
for b, s in cross[a].items():
|
|
254
|
+
if b <= a or selfs[b] <= 0:
|
|
255
|
+
continue
|
|
256
|
+
back = cross[b].get(a, 0.0)
|
|
257
|
+
out[(a, b)] = min(s / selfs[a], back / selfs[b])
|
|
258
|
+
return out
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
def redundancy_pairs(units, spec=None):
|
|
262
|
+
"""Design §7.1's redundancy hints over the current library, both operative by construction: every group of
|
|
263
|
+
identical text in more than one place (`eligible_units`), one hint per group at similarity 1.0, and every pair of
|
|
264
|
+
eligible units whose similarity reaches the fixed threshold. More hints than the ceiling is REDUNDANCY_OVER_CEILING.
|
|
265
|
+
Returns `(candidates, excluded counts)`."""
|
|
266
|
+
spec = table() if spec is None else spec
|
|
267
|
+
kept, left, identical = eligible_units(units, spec)
|
|
268
|
+
pairs = sorted((pair, score) for pair, score in similarities(kept).items() if score >= spec["threshold"])
|
|
269
|
+
if len(pairs) + len(identical) > spec["ceiling"]:
|
|
270
|
+
raise Refused(f"REDUNDANCY_OVER_CEILING {len(pairs) + len(identical)} redundancy hints ({len(identical)} groups of "
|
|
271
|
+
f"identical text, {len(pairs)} pairs at the threshold {spec['threshold']}), more than the ceiling "
|
|
272
|
+
f"{spec['ceiling']} tables/redundancy.json allows; the threshold is re-measured, never the list cut")
|
|
273
|
+
same = [{"candidate_id": "redundancy_hint:" + "|".join(group), "source": "redundancy_hint", "target_units": group,
|
|
274
|
+
"similarity": 1.0, "match": "identical"} for group in identical]
|
|
275
|
+
near = [{"candidate_id": f"redundancy_hint:{a}|{b}", "source": "redundancy_hint", "target_units": [a, b],
|
|
276
|
+
"similarity": round(score, 4), "match": "near"} for (a, b), score in pairs]
|
|
277
|
+
return sorted(same + near, key=lambda c: c["candidate_id"]), left
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
def entry_text(entry):
|
|
281
|
+
"""The text of a ledger entry a retrieval reads: its lesson and its principle (the rule it states), as the upward
|
|
282
|
+
clusters match it and S5's top ledger entries rank it (runlib/stage_retrieve.py)."""
|
|
283
|
+
return " ".join(t for t in (entry.get("lesson"), entry.get("principle")) if t)
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
def upward_clusters(doc, units, spec=None):
|
|
287
|
+
"""Design §7.4's upward distillation: the placed learnings of the ledger whose top retrieval hit over the eligible
|
|
288
|
+
units is one unit, at least three of them (lead decision D6 (iii)). A learning whose text matches no unit is in
|
|
289
|
+
no cluster. Returns the candidates, each with the lessons the formation packet shows."""
|
|
290
|
+
spec = table() if spec is None else spec
|
|
291
|
+
kept, _left, _identical = eligible_units(units, spec)
|
|
292
|
+
lib = Library({u["unit_id"]: u["text"] for u in kept})
|
|
293
|
+
groups = collections.defaultdict(list)
|
|
294
|
+
for entry in doc["entries"]:
|
|
295
|
+
if entry["status"] != "placed":
|
|
296
|
+
continue
|
|
297
|
+
counts, _n = keys_tf(entry_text(entry))
|
|
298
|
+
row = lib.scores(counts)
|
|
299
|
+
if not row:
|
|
300
|
+
continue
|
|
301
|
+
top = max(row.values())
|
|
302
|
+
best = min(i for i, s in row.items() if s == top)
|
|
303
|
+
groups[best].append(entry)
|
|
304
|
+
out = []
|
|
305
|
+
for unit, entries in sorted(groups.items()):
|
|
306
|
+
if len(entries) >= UPWARD_MIN:
|
|
307
|
+
ordered = sorted(entries, key=lambda e: e["id"])
|
|
308
|
+
out.append({"candidate_id": f"g_cluster:{unit}", "source": "g_cluster", "target_unit": unit,
|
|
309
|
+
"entries": [e["id"] for e in ordered], "lessons": [e["lesson"] for e in ordered],
|
|
310
|
+
# what the formation packet shows of each entry, under a label of its own (lead decision after X
|
|
311
|
+
# round 1, F2): its lesson, where its stored evidence is, and the lineages its record names
|
|
312
|
+
"members": [{"entry": e["id"], "lesson": e["lesson"], "evidence": copy.deepcopy(e.get("evidence") or []),
|
|
313
|
+
"independent_lineages": e.get("independent_lineages")} for e in ordered]})
|
|
314
|
+
return out
|
|
315
|
+
|
|
316
|
+
|
|
317
|
+
# ---- the intake --------------------------------------------------------------------------------------
|
|
318
|
+
|
|
319
|
+
def derive(doc, window, units, occasions=None, index_rows=None, spec=None):
|
|
320
|
+
"""Every source's candidates, and what the intake says beside them."""
|
|
321
|
+
spec = table() if spec is None else spec
|
|
322
|
+
redundancy, left = redundancy_pairs(units, spec)
|
|
323
|
+
sources = {"due_decision": due_decisions(doc, window, occasions), "legacy": legacy_incubation(doc),
|
|
324
|
+
"obsolete_hint": obsolete_hints(index_rows or []), "redundancy_hint": redundancy,
|
|
325
|
+
"g_cluster": upward_clusters(doc, units, spec)}
|
|
326
|
+
notes = {"obsolete_hint": "the occasion index S12 writes (WP-21) does not exist yet; no hint" if index_rows is None else None,
|
|
327
|
+
"g_cluster_arc": "an arc retrospective needs a declared arc, and the declaration has no field for one",
|
|
328
|
+
"excluded_layers": {layer: {"operative_units": left["excluded_layers"].get(layer, 0), "reason": reason}
|
|
329
|
+
for layer, reason in sorted(spec["excluded_layers"].items())},
|
|
330
|
+
"library_units": {k: left[k] for k in ("eligible", "identical_copies_folded", "identical_groups", "below_min_keys")}}
|
|
331
|
+
return sources, notes
|
|
332
|
+
|
|
333
|
+
|
|
334
|
+
def build(run_dir, declaration, index_rows=None, ledger_ref=None):
|
|
335
|
+
"""`intake.json`'s document for a run: the pinned ledger (as `ledger_of` has it), the window's occasions S3 judged,
|
|
336
|
+
the current library S2 left, and the golden occasion index rows when given. `declaration` is the one S4 was
|
|
337
|
+
admitted against (`records.StageRun.declaration`), never a read of run.json (records.DECLARATION_READERS)."""
|
|
338
|
+
run_dir = pathlib.Path(run_dir)
|
|
339
|
+
doc, had = ledger_of(declaration, ledger_ref)
|
|
340
|
+
units = records.read_json(run_dir / "inventory" / "current.json")["units"]
|
|
341
|
+
sources, notes = derive(doc, declaration["window"], units, window_occasions(run_dir, declaration["window"]), index_rows)
|
|
342
|
+
candidates = [c for s in SOURCES for c in sources[s]]
|
|
343
|
+
doc = {"window": declaration["window"], "ledger": {"sha256": declaration["starting_hashes"]["ledger"], "read": had},
|
|
344
|
+
"candidates": candidates, "notes": notes, "counts": {s: len(sources[s]) for s in SOURCES}}
|
|
345
|
+
problems = schema_problems(doc)
|
|
346
|
+
if problems:
|
|
347
|
+
raise Refused("INTAKE_INVALID " + "; ".join(problems[:5]))
|
|
348
|
+
return doc
|
|
349
|
+
|
|
350
|
+
|
|
351
|
+
def schema_problems(doc):
|
|
352
|
+
"""`intake.json`'s document against its schema, each violation a line."""
|
|
353
|
+
return validate.validate_instance(validate.compile_schema(json.loads(SCHEMA_PATH.read_text(encoding="utf-8"))), doc)
|
|
354
|
+
|
|
355
|
+
|
|
356
|
+
def intake_problems(intake, sources):
|
|
357
|
+
"""The intake against a derivation of every source by id (done-when 3): INTAKE_INCOMPLETE names an id a source
|
|
358
|
+
derives that the intake lacks, and one the intake holds that no source derives."""
|
|
359
|
+
want = {c["candidate_id"]: s for s in SOURCES for c in sources[s]}
|
|
360
|
+
have = collections.Counter(c["candidate_id"] for c in intake["candidates"])
|
|
361
|
+
errors = [f"INTAKE_INCOMPLETE {ident}: {want[ident]} derives it and the intake lacks it" for ident in sorted(set(want) - set(have))]
|
|
362
|
+
errors += [f"INTAKE_INCOMPLETE {ident}: the intake holds it and no source derives it" for ident in sorted(set(have) - set(want))]
|
|
363
|
+
errors += [f"INTAKE_INCOMPLETE {ident}: the intake holds it {n} times" for ident, n in sorted(have.items()) if n > 1]
|
|
364
|
+
return errors
|
|
365
|
+
|
|
366
|
+
|
|
367
|
+
# ---- self-test ---------------------------------------------------------------------------------------
|
|
368
|
+
|
|
369
|
+
def fx_unit(unit_id, text, layer="catalog", cls="operative", path=None, scope=None):
|
|
370
|
+
"""A unit as S2's inventory records one: a native unit's path is `<host>:<type>:<path>`, its scope the session's."""
|
|
371
|
+
unit = {"unit_id": unit_id, "layer": layer, "class": cls, "text": text, "sha": hashlib.sha256(text.encode("utf-8")).hexdigest(),
|
|
372
|
+
"path": path if path is not None else f"claude/guides/{unit_id}.md"}
|
|
373
|
+
if scope is not None:
|
|
374
|
+
unit["provenance"] = {"scope": scope}
|
|
375
|
+
return unit
|
|
376
|
+
|
|
377
|
+
|
|
378
|
+
FX_LIBRARY = [
|
|
379
|
+
fx_unit("u-push", "Ask the person before you push to a shared remote; a push cannot be taken back quietly."),
|
|
380
|
+
fx_unit("u-push2", "Ask the person before you push to the shared remote; a push cannot be taken back quietly."),
|
|
381
|
+
fx_unit("u-glob", "Quote a glob in a zsh command line, or the shell expands it before the tool sees it."),
|
|
382
|
+
fx_unit("u-tests", "Run the tests that cover the change before calling the change done."),
|
|
383
|
+
fx_unit("u-ref", "Ask the person before you push to any shared remote; a push cannot be taken back quietly.", cls="reference"),
|
|
384
|
+
fx_unit("u-codex", "Run the tests that cover a change before calling the change done.", layer="native_undivided"),
|
|
385
|
+
fx_unit("u-codex2", "Run the tests that cover the change before you call the change done.", layer="native_undivided"),
|
|
386
|
+
# u-glob's text again, in a project's AGENTS.md: identical text in two places, which the owner can reduce
|
|
387
|
+
fx_unit("u-quote", "Quote a glob in a zsh command line, or the shell expands it before the tool sees it.", layer="native_project",
|
|
388
|
+
path="claude:Project:<HOME>/b/AGENTS.md", scope="<HOME>/b"),
|
|
389
|
+
# one project file in two checkouts of it: the same relative path, so one file's copies
|
|
390
|
+
fx_unit("u-wt1", "Write the changelog entry beside the change it describes.", layer="native_project",
|
|
391
|
+
path="claude:Project:<HOME>/a/CLAUDE.md", scope="<HOME>/a"),
|
|
392
|
+
fx_unit("u-wt2", "Write the changelog entry beside the change it describes.", layer="native_project",
|
|
393
|
+
path="claude:Project:<HOME>/a-wt/CLAUDE.md", scope="<HOME>/a-wt"),
|
|
394
|
+
fx_unit("u-short", "Ask the person before you push."),
|
|
395
|
+
fx_unit("u-true", "true"),
|
|
396
|
+
fx_unit("u-true2", "true,"),
|
|
397
|
+
]
|
|
398
|
+
|
|
399
|
+
|
|
400
|
+
def fx_ledger(window_last="2026-11-05", due_expiry="2026-11-04"):
|
|
401
|
+
"""A schema 2 ledger with every case the intake tells apart: incubates due (expiring `due_expiry`) and not due, one
|
|
402
|
+
resolved, a pending intervention on a placed entry, legacy entries with and without a run's decision, and placed
|
|
403
|
+
learnings."""
|
|
404
|
+
L = ledger_lib
|
|
405
|
+
due = L.sample_element("r1", "incubate", observation=L.sample_observation(due_expiry))
|
|
406
|
+
late = L.sample_element("r1", "incubate", observation=L.sample_observation("2026-12-31"))
|
|
407
|
+
settled = L.sample_element("r2", "drop", reason="expired and not seen", resolves="N-3@r1")
|
|
408
|
+
legacy = lambda eid, status: L.sample_entry(eid, status, decisions=[ # noqa: E731
|
|
409
|
+
ledger_migration.element(f"legacy-{window_last}", "status", "unknown", "unavailable", window_last, status,
|
|
410
|
+
kind="legacy_migration", legacy_status=status)])
|
|
411
|
+
placed = lambda eid, lesson: L.sample_entry(eid, "placed", lesson=lesson, decisions=[L.sample_element("r0", "place")]) # noqa: E731
|
|
412
|
+
return L.sample_ledger(
|
|
413
|
+
L.sample_entry("N-1", "incubating", decisions=[copy.deepcopy(due)]),
|
|
414
|
+
L.sample_entry("N-2", "incubating", decisions=[copy.deepcopy(late)]),
|
|
415
|
+
L.sample_entry("N-3", "retired", decisions=[copy.deepcopy(due), settled]),
|
|
416
|
+
L.sample_entry("P-1", "placed", decisions=[L.sample_element("r0", "place"), copy.deepcopy(due)]),
|
|
417
|
+
legacy("M-1", "incubating"), legacy("M-2", "incubating"), legacy("M-3", "placed"),
|
|
418
|
+
placed("S-1", "run the tests before you call the change done"),
|
|
419
|
+
placed("S-2", "a change is done only after the tests that cover it ran"),
|
|
420
|
+
placed("S-3", "call a change done after running the tests that cover the change"),
|
|
421
|
+
placed("S-4", "quote a glob in a zsh command line"),
|
|
422
|
+
placed("S-5", "zsh expands an unquoted glob before the tool sees it"))
|
|
423
|
+
|
|
424
|
+
|
|
425
|
+
FX_WINDOW = {"start": "2026-11-05T00:00:00", "end": "2026-11-06T00:00:00", "tz": "Asia/Seoul"}
|
|
426
|
+
|
|
427
|
+
|
|
428
|
+
def self_test():
|
|
429
|
+
failures, ran = [], []
|
|
430
|
+
|
|
431
|
+
def control(name, condition, detail=""):
|
|
432
|
+
ran.append(name)
|
|
433
|
+
if not condition:
|
|
434
|
+
failures.append(f"{name}: {detail}")
|
|
435
|
+
|
|
436
|
+
def guarded(action, default):
|
|
437
|
+
try:
|
|
438
|
+
return action()
|
|
439
|
+
except Exception as exc: # noqa: BLE001 - reported by the control that reads the default
|
|
440
|
+
return default(exc) if callable(default) else default
|
|
441
|
+
|
|
442
|
+
def refusal(action):
|
|
443
|
+
try:
|
|
444
|
+
action()
|
|
445
|
+
except Refused as exc:
|
|
446
|
+
return str(exc)
|
|
447
|
+
except Exception as exc: # noqa: BLE001
|
|
448
|
+
return f"RAISED {exc!r}"
|
|
449
|
+
return ""
|
|
450
|
+
|
|
451
|
+
spec = {"threshold": 0.7, "min_keys": 3, "ceiling": 10, "excluded_layers": {"native_undivided": "the host's own instructions"}}
|
|
452
|
+
doc = guarded(fx_ledger, None)
|
|
453
|
+
control("positive control: the fixture ledger validates", doc is not None and guarded(lambda: ledger_lib.validate_ledger(doc), ["RAISED"]) == [],
|
|
454
|
+
f"{guarded(lambda: ledger_lib.validate_ledger(doc), ['RAISED'])[:3]}")
|
|
455
|
+
occasions = {"N-1@r1": {"instances": [{"occasion_locator": "v#3", "exposure": "eligible", "verdict": "observed", "basis": "source"}],
|
|
456
|
+
"resolution": "observed"}}
|
|
457
|
+
sources, notes = guarded(lambda: derive(doc, FX_WINDOW, FX_LIBRARY, occasions, None, spec), lambda exc: ({}, {"problem": repr(exc)}))
|
|
458
|
+
ids = {s: [c["candidate_id"] for c in sources.get(s, [])] for s in SOURCES}
|
|
459
|
+
|
|
460
|
+
# (a) due decisions
|
|
461
|
+
control("done-when 3 (a): an incubate whose expiry is on or before the window's last day enters, with the window's "
|
|
462
|
+
"occasions for its observation",
|
|
463
|
+
"due_decision:N-1@r1" in ids["due_decision"]
|
|
464
|
+
and next(c for c in sources["due_decision"] if c["target_entry"] == "N-1")["occasions"]["resolution"] == "observed",
|
|
465
|
+
f"{ids['due_decision']} {notes.get('problem')}")
|
|
466
|
+
control("done-when 3: a pending intervention on a placed entry enters, not only incubating entries",
|
|
467
|
+
"due_decision:P-1@r1" in ids["due_decision"]
|
|
468
|
+
and next((c for c in sources["due_decision"] if c["target_entry"] == "P-1"), {}).get("pending_intervention") is True,
|
|
469
|
+
f"{ids['due_decision']}")
|
|
470
|
+
control("done-when 3 (a): an incubate whose expiry lies after the window, and one a later decision resolves, do not "
|
|
471
|
+
"enter; each due decision names the decision it resolves",
|
|
472
|
+
"due_decision:N-2@r1" not in ids["due_decision"] and "due_decision:N-3@r1" not in ids["due_decision"]
|
|
473
|
+
and all(c["resolves"] == c["candidate_id"].split(":", 1)[1] for c in sources["due_decision"]),
|
|
474
|
+
f"{ids['due_decision']}")
|
|
475
|
+
control("the window's last day is the day before a half-open window's end at midnight",
|
|
476
|
+
guarded(lambda: last_day(FX_WINDOW), None) == "2026-11-05"
|
|
477
|
+
and guarded(lambda: last_day({**FX_WINDOW, "end": "2026-11-06T09:00:00"}), None) == "2026-11-06",
|
|
478
|
+
f"{guarded(lambda: last_day(FX_WINDOW), None)}")
|
|
479
|
+
# (b) legacy incubation
|
|
480
|
+
control("done-when 3 (b): every incubating entry with no applied decision of a run enters as legacy, observation "
|
|
481
|
+
"unavailable; a placed legacy entry and an entry with a run's decision do not",
|
|
482
|
+
ids["legacy"] == ["legacy:M-1", "legacy:M-2"]
|
|
483
|
+
and all(c["marks"] == [LEGACY_MARK] for c in sources["legacy"]), f"{ids['legacy']}")
|
|
484
|
+
# the two scratch runs: an entry that received an applied decision in the previous run does not re-enter
|
|
485
|
+
after = copy.deepcopy(doc) if doc else None
|
|
486
|
+
if after:
|
|
487
|
+
m1 = next(e for e in after["entries"] if e["id"] == "M-1")
|
|
488
|
+
m1["decisions"].append(ledger_lib.sample_element("r5", "incubate", observation=ledger_lib.sample_observation("2027-01-31")))
|
|
489
|
+
second = guarded(lambda: derive(after, FX_WINDOW, FX_LIBRARY, None, None, spec)[0], {})
|
|
490
|
+
control("done-when 3 (two scratch runs): an entry that received an applied decision in the previous run does not "
|
|
491
|
+
"re-enter, as legacy or as due",
|
|
492
|
+
"legacy:M-1" in ids["legacy"] and guarded(lambda: ledger_lib.validate_ledger(after), ["RAISED"]) == []
|
|
493
|
+
and "legacy:M-1" not in [c["candidate_id"] for c in second.get("legacy", [])]
|
|
494
|
+
and not any(c["target_entry"] == "M-1" for c in second.get("due_decision", [])),
|
|
495
|
+
f"{[c['candidate_id'] for c in second.get('legacy', [])]}")
|
|
496
|
+
# (c) obsolete hints over the golden occasion index
|
|
497
|
+
row = lambda day, unit, matched, basis="source": {"window_start": day, "unit_id": unit, "matched": matched, "basis": basis} # noqa: E731
|
|
498
|
+
index = [row("2026-10-01", "u-a", False), row("2026-10-08", "u-a", False), row("2026-10-15", "u-a", False),
|
|
499
|
+
row("2026-10-08", "u-b", False), row("2026-10-15", "u-b", False),
|
|
500
|
+
row("2026-10-01", "u-c", False), row("2026-10-08", "u-c", False, "view"), row("2026-10-15", "u-c", False),
|
|
501
|
+
row("2026-10-22", "u-c", False),
|
|
502
|
+
row("2026-10-01", "u-d", False), row("2026-10-08", "u-d", False), row("2026-10-15", "u-d", False),
|
|
503
|
+
row("2026-10-22", "u-d", True)]
|
|
504
|
+
hints = [c["candidate_id"] for c in guarded(lambda: obsolete_hints(index), [])]
|
|
505
|
+
control("done-when 3 (c): a unit with no match in three consecutive source-basis windows is an obsolete hint; two "
|
|
506
|
+
"are not; a view-basis window breaks the run; a later match ends it",
|
|
507
|
+
hints == ["obsolete_hint:u-a"], f"{hints}")
|
|
508
|
+
control("with no occasion index, the intake takes no obsolete hint and says why",
|
|
509
|
+
ids["obsolete_hint"] == [] and "WP-21" in (notes.get("obsolete_hint") or ""), f"{notes.get('obsolete_hint')}")
|
|
510
|
+
# (d) redundancy hints
|
|
511
|
+
near_hints = [c["candidate_id"] for c in sources.get("redundancy_hint", []) if c.get("match") == "near"]
|
|
512
|
+
control("done-when 3 (d): a near-duplicate pair of operative units reaches the threshold and is a redundancy hint",
|
|
513
|
+
near_hints == ["redundancy_hint:u-push|u-push2"], f"{ids['redundancy_hint']}")
|
|
514
|
+
control("D5 scope: a reference unit and the excluded layer's units are no part of a pair, and the units the layer "
|
|
515
|
+
"left out are counted with its reason",
|
|
516
|
+
not any("u-ref" in i or "u-codex" in i for i in ids["redundancy_hint"])
|
|
517
|
+
and notes.get("excluded_layers", {}).get("native_undivided", {}).get("operative_units") == 2,
|
|
518
|
+
f"{notes.get('excluded_layers')}")
|
|
519
|
+
same_hints = [c for c in sources.get("redundancy_hint", []) if c.get("match") == "identical"]
|
|
520
|
+
control("one file's copies in two checkouts (one layer, one path relative to its scope) are folded and counted, and "
|
|
521
|
+
"are no hint",
|
|
522
|
+
not any("u-wt" in i for i in ids["redundancy_hint"]) and notes.get("library_units", {}).get("identical_copies_folded") == 1
|
|
523
|
+
and guarded(lambda: [relative_path(u) for u in FX_LIBRARY if u["unit_id"].startswith("u-wt")], []) == ["CLAUDE.md"] * 2,
|
|
524
|
+
f"{notes.get('library_units')} {ids['redundancy_hint']}")
|
|
525
|
+
control("identical text in two places (another layer, or another relative path) is one redundancy hint at similarity "
|
|
526
|
+
"1.0 naming one unit of each place, and is paired no further",
|
|
527
|
+
[(c["candidate_id"], c["similarity"], c["target_units"]) for c in same_hints]
|
|
528
|
+
== [("redundancy_hint:u-glob|u-quote", 1.0, ["u-glob", "u-quote"])]
|
|
529
|
+
and notes.get("library_units", {}).get("identical_groups") == 1
|
|
530
|
+
and sum("u-quote" in i for i in ids["redundancy_hint"]) == 1, f"{[c['candidate_id'] for c in same_hints]}")
|
|
531
|
+
control("a unit of fewer than min_keys keys is left out, counted, and never paired",
|
|
532
|
+
not any("u-true" in i for i in ids["redundancy_hint"])
|
|
533
|
+
and notes.get("library_units", {}).get("below_min_keys") == 2, f"{notes.get('library_units')}")
|
|
534
|
+
table_now = guarded(table, {})
|
|
535
|
+
control("the table's threshold, floor and ceiling are numbers with the measurement they rest on, and each excluded "
|
|
536
|
+
"layer carries its reason",
|
|
537
|
+
isinstance(table_now.get("threshold"), (int, float)) and isinstance(table_now.get("min_keys"), int)
|
|
538
|
+
and isinstance(table_now.get("ceiling"), int) and "measured" in table_now.get("basis", "")
|
|
539
|
+
and table_now.get("excluded_layers") and all(r for r in table_now["excluded_layers"].values()), f"{table_now}")
|
|
540
|
+
sims = guarded(lambda: similarities([u for u in FX_LIBRARY if u["layer"] == "catalog" and u["class"] == "operative"
|
|
541
|
+
and not u["unit_id"].startswith("u-true")]), {})
|
|
542
|
+
control("the similarity of a pair is one number for both orders, at most 1, and the near-duplicate's is far above "
|
|
543
|
+
"an unrelated pair's",
|
|
544
|
+
sims and all(a < b and 0 <= s <= 1.0000001 for (a, b), s in sims.items())
|
|
545
|
+
and sims.get(("u-push", "u-push2"), 0) >= 0.7 and sims.get(("u-glob", "u-push"), 0) < 0.3,
|
|
546
|
+
f"{ {k: round(v, 3) for k, v in sims.items()} }")
|
|
547
|
+
control("a short unit whose every key a longer one holds is no pair: the similarity is the smaller direction",
|
|
548
|
+
not any("u-short" in i for i in ids["redundancy_hint"]) and sims.get(("u-push", "u-short"), 1) < 0.7,
|
|
549
|
+
f"{ids['redundancy_hint']} {sims.get(('u-push', 'u-short'))}")
|
|
550
|
+
control("more pairs than the ceiling are refused by name, never cut",
|
|
551
|
+
refusal(lambda: redundancy_pairs(FX_LIBRARY, {**spec, "threshold": 0.0, "ceiling": 1})).startswith("REDUNDANCY_OVER_CEILING"),
|
|
552
|
+
refusal(lambda: redundancy_pairs(FX_LIBRARY, {**spec, "threshold": 0.0, "ceiling": 1})))
|
|
553
|
+
control("a group of identical text is a hint the ceiling counts: one near pair and one group over a ceiling of 1 are "
|
|
554
|
+
"refused by name",
|
|
555
|
+
refusal(lambda: redundancy_pairs(FX_LIBRARY, {**spec, "ceiling": 1})).startswith("REDUNDANCY_OVER_CEILING 2 redundancy hints (1 groups"),
|
|
556
|
+
refusal(lambda: redundancy_pairs(FX_LIBRARY, {**spec, "ceiling": 1})))
|
|
557
|
+
# (e) G clusters
|
|
558
|
+
control("done-when 3 (e): three placed learnings whose top hit is one unit are a G cluster with their lessons; two "
|
|
559
|
+
"sharing a unit are not",
|
|
560
|
+
ids["g_cluster"] == ["g_cluster:u-tests"]
|
|
561
|
+
and next(c for c in sources["g_cluster"])["entries"] == ["S-1", "S-2", "S-3"], f"{sources.get('g_cluster')}")
|
|
562
|
+
control("an arc retrospective needs a declared arc; there is none, and the intake says why",
|
|
563
|
+
"arc" in (notes.get("g_cluster_arc") or ""), f"{notes.get('g_cluster_arc')}")
|
|
564
|
+
# done-when 3: the intake equals the sources' union by id
|
|
565
|
+
intake = {"candidates": [c for s in SOURCES for c in sources.get(s, [])]}
|
|
566
|
+
control("done-when 3: an intake holding every source's candidates passes", guarded(lambda: intake_problems(intake, sources), ["RAISED"]) == [],
|
|
567
|
+
f"{guarded(lambda: intake_problems(intake, sources), ['RAISED'])}")
|
|
568
|
+
short = {"candidates": [c for c in intake["candidates"] if c["candidate_id"] != "due_decision:N-1@r1"]}
|
|
569
|
+
control("done-when 3: one due decision removed from the produced intake is INTAKE_INCOMPLETE naming it",
|
|
570
|
+
any(p.startswith("INTAKE_INCOMPLETE due_decision:N-1@r1:") for p in guarded(lambda: intake_problems(short, sources), [])),
|
|
571
|
+
f"{guarded(lambda: intake_problems(short, sources), [])}")
|
|
572
|
+
stray = {"candidates": intake["candidates"] + [{"candidate_id": "legacy:Z-9", "source": "legacy"}]}
|
|
573
|
+
control("an intake candidate no source derives is INTAKE_INCOMPLETE naming it",
|
|
574
|
+
any(p.startswith("INTAKE_INCOMPLETE legacy:Z-9:") for p in guarded(lambda: intake_problems(stray, sources), [])),
|
|
575
|
+
f"{guarded(lambda: intake_problems(stray, sources), [])}")
|
|
576
|
+
# one entry, two candidates: told apart by id, both in the population
|
|
577
|
+
from runlib import stage_form
|
|
578
|
+
two = [{"candidate_id": "legacy:M-1", "source": "legacy"}, {"candidate_id": "redundancy_hint:L-M-1|u-push", "source": "redundancy_hint"}]
|
|
579
|
+
pop = guarded(lambda: stage_form.population({"candidates": [], "rejected_findings": [], "non_findings": []},
|
|
580
|
+
{"events": [], "carried_forward": [], "not_formed": [], "units": {}}, "r9", two), {})
|
|
581
|
+
control("two lifecycle candidates of one entry are two rows of the population, told apart by id",
|
|
582
|
+
pop.get("candidate_ids") == ["legacy:M-1", "redundancy_hint:L-M-1|u-push"]
|
|
583
|
+
and guarded(lambda: stage_form.population_problems(pop, {"events": [], "carried_forward": [], "not_formed": [],
|
|
584
|
+
"units": {}}, two), ["RAISED"]) == [],
|
|
585
|
+
f"{pop.get('candidate_ids')}")
|
|
586
|
+
# done-when 7: the sources equal the formation contract's closed list, and the intake schema holds them
|
|
587
|
+
schema = guarded(lambda: json.loads(SCHEMA_PATH.read_text(encoding="utf-8")), {})
|
|
588
|
+
enum = schema.get("$defs", {}).get("candidate", {}).get("properties", {}).get("source", {}).get("enum")
|
|
589
|
+
control("done-when 7: the intake's sources equal design §7.1's list (stage_form.INTAKE_SOURCES), in code and in the "
|
|
590
|
+
"intake schema", SOURCES == stage_form.INTAKE_SOURCES and enum == list(SOURCES), f"{SOURCES} {enum}")
|
|
591
|
+
built = {"candidates": intake["candidates"], "window": FX_WINDOW, "ledger": {"sha256": "0" * 64, "read": "schema 2"},
|
|
592
|
+
"notes": notes, "counts": {s: len(sources.get(s, [])) for s in SOURCES}}
|
|
593
|
+
from runlib import validate
|
|
594
|
+
control("the intake document passes its schema", guarded(lambda: validate.validate_instance(validate.compile_schema(schema), built), ["RAISED"]) == [],
|
|
595
|
+
f"{guarded(lambda: validate.validate_instance(validate.compile_schema(schema), built), ['RAISED'])[:3]}")
|
|
596
|
+
|
|
597
|
+
def bent_build():
|
|
598
|
+
"""build over a derivation bent to return a redundancy hint naming one unit, which the intake schema refuses."""
|
|
599
|
+
bad = {s: [] for s in SOURCES}
|
|
600
|
+
bad["redundancy_hint"] = [{"candidate_id": "redundancy_hint:u-one", "source": "redundancy_hint", "target_units": ["u-one"],
|
|
601
|
+
"similarity": 1.0, "match": "identical"}]
|
|
602
|
+
saved = {name: globals()[name] for name in ("ledger_of", "window_occasions", "derive")}
|
|
603
|
+
globals().update(ledger_of=lambda declaration, ledger_ref=None: (doc, "schema 2"),
|
|
604
|
+
window_occasions=lambda run_dir, window: {},
|
|
605
|
+
derive=lambda *args, **kwargs: (bad, notes))
|
|
606
|
+
try:
|
|
607
|
+
with tempfile.TemporaryDirectory(prefix="intake-") as td:
|
|
608
|
+
(pathlib.Path(td) / "inventory").mkdir()
|
|
609
|
+
(pathlib.Path(td) / "inventory" / "current.json").write_text('{"units": []}', encoding="utf-8")
|
|
610
|
+
return build(td, {"window": FX_WINDOW, "starting_hashes": {"ledger": "0" * 64}})
|
|
611
|
+
finally:
|
|
612
|
+
globals().update(saved)
|
|
613
|
+
control("build refuses an intake document its schema refuses (INTAKE_INVALID), before any stage writes it",
|
|
614
|
+
refusal(bent_build).startswith("INTAKE_INVALID"), refusal(bent_build))
|
|
615
|
+
# D4: the pinned ledger is had as it is when it is schema 2 and migrated in memory when it is
|
|
616
|
+
# schema 1, and its file is never written. The repository's own file was schema 1 until the
|
|
617
|
+
# WP-22 cutover moved it, so this leg judges the file by the schema it actually carries and
|
|
618
|
+
# keeps a schema 1 FIXTURE beside it: a control that only knew the migration path stopped
|
|
619
|
+
# testing the migration the moment the real file stopped being schema 1.
|
|
620
|
+
with tempfile.TemporaryDirectory(prefix="intake-") as td:
|
|
621
|
+
checkout = pathlib.Path(td)
|
|
622
|
+
# The fixture writes the ledger where the READ will look for it: the reference the
|
|
623
|
+
# author-side caller injected, so the path is named once and in one place.
|
|
624
|
+
rel = checkout / (CHECKOUT_LEDGER or ledger_lib.STATE_LEDGER_REL)
|
|
625
|
+
rel.parent.mkdir(parents=True, exist_ok=True)
|
|
626
|
+
# The owner's own ledger when this runs from a checkout, and nothing when it does not: the
|
|
627
|
+
# path of a checkout's ledger is not a thing shipped code may name (WP-24).
|
|
628
|
+
real = pathlib.Path(CHECKOUT_LEDGER) if CHECKOUT_LEDGER else None
|
|
629
|
+
raw = real.read_bytes() if real is not None and real.is_file() else b""
|
|
630
|
+
rel.write_bytes(raw)
|
|
631
|
+
declaration = {"destinations": {"checkout": str(checkout)},
|
|
632
|
+
"starting_hashes": {"ledger": hashlib.sha256(raw).hexdigest()}}
|
|
633
|
+
had = guarded(lambda: ledger_of(declaration), lambda exc: (None, repr(exc)))
|
|
634
|
+
migrated, how = had
|
|
635
|
+
pinned = json.loads(raw) if raw else {}
|
|
636
|
+
incubating = sum(1 for e in pinned.get("entries", []) if str(e.get("status", "")).startswith("incubating"))
|
|
637
|
+
legacy_ids = [c["candidate_id"] for c in guarded(lambda: legacy_incubation(migrated), [])] if migrated else []
|
|
638
|
+
expected_how = {1: "schema 1, migrated in memory", 2: "schema 2"}.get(pinned.get("schema"))
|
|
639
|
+
if not raw:
|
|
640
|
+
# The owner's schema 1 ledger lives in a checkout, which shipped code may not name
|
|
641
|
+
# (WP-24): the author-side caller sets CHECKOUT_LEDGER, and without it this leg is
|
|
642
|
+
# reported as skipped by name rather than passing over an empty file.
|
|
643
|
+
print("lifecycle_intake --self-test SKIPPED: D4, the migration of the repository's schema 1 "
|
|
644
|
+
"ledger (set CHECKOUT_LEDGER, as gates/check-ledger.py does)")
|
|
645
|
+
else:
|
|
646
|
+
control("D4: the repository's ledger is had by the schema it carries, and its every incubating entry is a "
|
|
647
|
+
"legacy candidate, its file unchanged",
|
|
648
|
+
expected_how is not None and how == expected_how and incubating > 0
|
|
649
|
+
and len(legacy_ids) == incubating and hashlib.sha256(rel.read_bytes()).hexdigest() == hashlib.sha256(raw).hexdigest(),
|
|
650
|
+
f"schema={pinned.get('schema')} {how} incubating={incubating} legacy={len(legacy_ids)}")
|
|
651
|
+
# The migration path, on a subject this suite owns: whatever schema the repository's file
|
|
652
|
+
# carries today, a schema 1 pin is still migrated in memory and its entries still arrive.
|
|
653
|
+
fixture = checkout / "fx-schema1-pin.json"
|
|
654
|
+
fx_raw = json.dumps({"schema": 1, "framework": "f",
|
|
655
|
+
"window": "census ending 2026-08-25 (previous: census 21d ending 2026-07-18)",
|
|
656
|
+
"entries": [{"id": "FX-1", "lesson": "a legacy candidate\n", "status": "incubating",
|
|
657
|
+
"window": "2026-08-25", "surfaced": "2026-08-25", "classification": None},
|
|
658
|
+
{"id": "FX-2", "lesson": "a placed one\n", "status": "placed",
|
|
659
|
+
"window": "2026-08-25", "surfaced": "2026-08-25", "classification": None}]},
|
|
660
|
+
ensure_ascii=False).encode()
|
|
661
|
+
fixture.write_bytes(fx_raw)
|
|
662
|
+
fx_declaration = {"destinations": {"checkout": str(checkout)},
|
|
663
|
+
"starting_hashes": {"ledger": hashlib.sha256(fx_raw).hexdigest()}}
|
|
664
|
+
fx_doc, fx_how = guarded(lambda: ledger_of(fx_declaration, "fx-schema1-pin.json"), lambda exc: (None, repr(exc)))
|
|
665
|
+
fx_ids = [c["candidate_id"] for c in guarded(lambda: legacy_incubation(fx_doc), [])] if fx_doc else []
|
|
666
|
+
control("D4: a schema 1 pin is migrated in memory by the cutover's function, its one incubating entry becomes "
|
|
667
|
+
"a legacy candidate, and its file is not written",
|
|
668
|
+
fx_how == "schema 1, migrated in memory" and len(fx_ids) == 1
|
|
669
|
+
and (fx_doc or {}).get("schema") == 2 and fixture.read_bytes() == fx_raw,
|
|
670
|
+
f"{fx_how} candidates={fx_ids}")
|
|
671
|
+
control("the suite leaves no temporary tree", not checkout.exists(), str(checkout))
|
|
672
|
+
|
|
673
|
+
for failure in failures:
|
|
674
|
+
print(f"lifecycle_intake --self-test [FAIL] {failure}")
|
|
675
|
+
if failures:
|
|
676
|
+
return 1
|
|
677
|
+
print(f"lifecycle_intake --self-test: OK ({len(ran)} controls: " + "; ".join(ran) + ")")
|
|
678
|
+
return 0
|
|
679
|
+
|
|
680
|
+
|
|
681
|
+
if __name__ == "__main__":
|
|
682
|
+
# `--checkout-ledger` is how an author-side caller hands this suite the owner's schema 1 ledger;
|
|
683
|
+
# shipped code names no path under `design/` (WP-24), and without the flag the D4 leg is skipped
|
|
684
|
+
# by name — which is also what an installed tree gets.
|
|
685
|
+
if "--self-test" not in sys.argv[1:]:
|
|
686
|
+
sys.exit("usage: lifecycle_intake.py --self-test [--checkout-ledger PATH]")
|
|
687
|
+
given = sys.argv[1:]
|
|
688
|
+
if "--checkout-ledger" in given:
|
|
689
|
+
at = given.index("--checkout-ledger")
|
|
690
|
+
if at + 1 >= len(given):
|
|
691
|
+
sys.exit("usage: --checkout-ledger takes a path")
|
|
692
|
+
CHECKOUT_LEDGER = given[at + 1]
|
|
693
|
+
sys.exit(self_test())
|