agent-bios 0.19.3 → 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.
Files changed (172) hide show
  1. package/DEPENDENCIES.md +62 -20
  2. package/INSTALL.md +1 -1
  3. package/README.md +16 -21
  4. package/claude/agents/frontier.md +1 -1
  5. package/claude/agents/sweep.md +2 -1
  6. package/claude/agents/workhorse.md +2 -2
  7. package/claude/guides/claude-prompting.md +494 -167
  8. package/claude/guides/cli-multi-model-workflow.md +8 -7
  9. package/claude/guides/gpt-prompting.md +241 -111
  10. package/claude/guides/session-distill-workflow.md +93 -43
  11. package/claude/guides/tooling-gotchas.md +3 -1
  12. package/codex/agents/reviewer.toml +2 -2
  13. package/codex/agents/sweep.toml +1 -1
  14. package/codex/agents/workhorse.toml +2 -2
  15. package/codex/guides/claude-prompting.md +494 -167
  16. package/codex/guides/cli-multi-model-workflow.md +8 -7
  17. package/codex/guides/gpt-prompting.md +241 -111
  18. package/codex/guides/session-distill-workflow.md +93 -43
  19. package/codex/guides/tooling-gotchas.md +3 -1
  20. package/compose/assemble.py +4 -1
  21. package/compose/canary.sh +8 -6
  22. package/compose/host_platform.py +158 -15
  23. package/compose/instructions-state.py +183 -41
  24. package/compose/instructions_app.py +2 -2
  25. package/compose/instructions_install.py +222 -27
  26. package/compose/instructions_session.py +250 -75
  27. package/compose/instructions_setup.py +6 -6
  28. package/compose/instructions_setup_cli.py +2 -36
  29. package/compose/instructions_setup_i18n.py +3 -3
  30. package/compose/instructions_store.py +160 -3
  31. package/compose/instructions_transaction.py +29 -5
  32. package/compose/instructions_ui_runtime.py +2 -2
  33. package/compose/setup/START.md +1 -1
  34. package/docs/advanced-launch.md +4 -0
  35. package/docs/releases/0.19.4.md +99 -0
  36. package/docs/releases/0.20.0.md +102 -0
  37. package/docs/setup.md +4 -4
  38. package/install.sh +54 -20
  39. package/launch/agent-launch.py +171 -22
  40. package/launch/agent-launch.toml +64 -29
  41. package/launch/agent-launch.zsh +104 -13
  42. package/launch/claude_subcommands.py +179 -0
  43. package/launch/provision-venv.sh +1 -1
  44. package/launch/shell_integration.py +7 -1
  45. package/learn/collect-learning.py +60 -9
  46. package/learn/migrate-learnings.py +70 -4
  47. package/learn/redact.py +2 -1
  48. package/package.json +37 -4
  49. package/provenance.json +1 -1
  50. package/session-cost.py +141 -18
  51. package/session-distill/coverage.json +6 -0
  52. package/session-distill/distill.py +2575 -0
  53. package/session-distill/grammar/__init__.py +0 -0
  54. package/session-distill/grammar/owner_lines.py +874 -0
  55. package/session-distill/originators.json +9 -0
  56. package/session-distill/packets/cross_review.md +31 -0
  57. package/session-distill/packets/form.md +86 -0
  58. package/session-distill/packets/judge.md +81 -0
  59. package/session-distill/packets/placement_contract.md +90 -0
  60. package/session-distill/packets/propose.md +124 -0
  61. package/session-distill/packets/read.md +57 -0
  62. package/session-distill/packets/reconsider.md +53 -0
  63. package/session-distill/packets/s7b.md +65 -0
  64. package/session-distill/packets/s9b.md +39 -0
  65. package/session-distill/packets/stitch.md +35 -0
  66. package/session-distill/packets/sweep.md +33 -0
  67. package/session-distill/runlib/__init__.py +0 -0
  68. package/session-distill/runlib/bound.py +1102 -0
  69. package/session-distill/runlib/breaker.py +467 -0
  70. package/session-distill/runlib/census.py +2347 -0
  71. package/session-distill/runlib/claims.py +420 -0
  72. package/session-distill/runlib/controls.py +902 -0
  73. package/session-distill/runlib/coverage.py +881 -0
  74. package/session-distill/runlib/declare.py +888 -0
  75. package/session-distill/runlib/delivery_evidence.py +1145 -0
  76. package/session-distill/runlib/derive.py +812 -0
  77. package/session-distill/runlib/destinations.py +3072 -0
  78. package/session-distill/runlib/dispatch.py +7939 -0
  79. package/session-distill/runlib/drift.py +1077 -0
  80. package/session-distill/runlib/entry.py +401 -0
  81. package/session-distill/runlib/evidence.py +890 -0
  82. package/session-distill/runlib/exposure.py +1162 -0
  83. package/session-distill/runlib/gate.py +2727 -0
  84. package/session-distill/runlib/gitread.py +79 -0
  85. package/session-distill/runlib/inventory.py +19624 -0
  86. package/session-distill/runlib/journal.py +1919 -0
  87. package/session-distill/runlib/ledger.py +3210 -0
  88. package/session-distill/runlib/ledger_compat.py +101 -0
  89. package/session-distill/runlib/ledger_migration.py +190 -0
  90. package/session-distill/runlib/lifecycle_intake.py +693 -0
  91. package/session-distill/runlib/lineage.py +454 -0
  92. package/session-distill/runlib/measures.py +249 -0
  93. package/session-distill/runlib/monitor.py +1180 -0
  94. package/session-distill/runlib/operations.py +522 -0
  95. package/session-distill/runlib/packet.py +838 -0
  96. package/session-distill/runlib/placement.py +1769 -0
  97. package/session-distill/runlib/projection.py +4090 -0
  98. package/session-distill/runlib/ranking.py +740 -0
  99. package/session-distill/runlib/receipts.py +200 -0
  100. package/session-distill/runlib/records.py +1965 -0
  101. package/session-distill/runlib/search.py +249 -0
  102. package/session-distill/runlib/sequencing.py +829 -0
  103. package/session-distill/runlib/sources.py +641 -0
  104. package/session-distill/runlib/stage_adjudicate.py +845 -0
  105. package/session-distill/runlib/stage_apply.py +1378 -0
  106. package/session-distill/runlib/stage_approvals.py +758 -0
  107. package/session-distill/runlib/stage_close.py +1220 -0
  108. package/session-distill/runlib/stage_confirm.py +929 -0
  109. package/session-distill/runlib/stage_delivery.py +3080 -0
  110. package/session-distill/runlib/stage_form.py +2576 -0
  111. package/session-distill/runlib/stage_judge.py +4248 -0
  112. package/session-distill/runlib/stage_propose.py +3307 -0
  113. package/session-distill/runlib/stage_read.py +5179 -0
  114. package/session-distill/runlib/stage_render.py +2739 -0
  115. package/session-distill/runlib/stage_retrieve.py +924 -0
  116. package/session-distill/runlib/stage_review_korean.py +1002 -0
  117. package/session-distill/runlib/stage_review_proposals.py +1292 -0
  118. package/session-distill/runlib/stagelock.py +412 -0
  119. package/session-distill/runlib/stop.py +1061 -0
  120. package/session-distill/runlib/targets.py +809 -0
  121. package/session-distill/runlib/usage.py +280 -0
  122. package/session-distill/runlib/validate.py +319 -0
  123. package/session-distill/runlib/views.py +4327 -0
  124. package/session-distill/schemas/adjudication.schema.json +35 -0
  125. package/session-distill/schemas/approval.schema.json +35 -0
  126. package/session-distill/schemas/census.schema.json +128 -0
  127. package/session-distill/schemas/checks.schema.json +207 -0
  128. package/session-distill/schemas/claim.schema.json +16 -0
  129. package/session-distill/schemas/confirmation.schema.json +24 -0
  130. package/session-distill/schemas/coverage.schema.json +66 -0
  131. package/session-distill/schemas/cross_review.schema.json +24 -0
  132. package/session-distill/schemas/event.schema.json +20 -0
  133. package/session-distill/schemas/evidence.schema.json +20 -0
  134. package/session-distill/schemas/expected_observation.schema.json +18 -0
  135. package/session-distill/schemas/form.schema.json +103 -0
  136. package/session-distill/schemas/intake.schema.json +71 -0
  137. package/session-distill/schemas/inventory.schema.json +872 -0
  138. package/session-distill/schemas/judge.schema.json +77 -0
  139. package/session-distill/schemas/ledger.schema.json +313 -0
  140. package/session-distill/schemas/observation.schema.json +16 -0
  141. package/session-distill/schemas/propose.schema.json +555 -0
  142. package/session-distill/schemas/read.schema.json +76 -0
  143. package/session-distill/schemas/reconsider.schema.json +122 -0
  144. package/session-distill/schemas/run.schema.json +150 -0
  145. package/session-distill/schemas/s7b.schema.json +200 -0
  146. package/session-distill/schemas/s9b.schema.json +28 -0
  147. package/session-distill/schemas/stitch.schema.json +25 -0
  148. package/session-distill/schemas/sweep.schema.json +25 -0
  149. package/session-distill/seats.json +149 -0
  150. package/session-distill/tables/allowed_pairs.json +257 -0
  151. package/session-distill/tables/controls.json +30 -0
  152. package/session-distill/tables/delivery_evidence.json +36 -0
  153. package/session-distill/tables/delivery_evidence_fixtures.json +731 -0
  154. package/session-distill/tables/destinations.json +684 -0
  155. package/session-distill/tables/drift_layers.json +68 -0
  156. package/session-distill/tables/exposure_rules.json +192 -0
  157. package/session-distill/tables/placement_rules.json +148 -0
  158. package/session-distill/tables/propose_fixtures.json +154 -0
  159. package/session-distill/tables/ranking.json +194 -0
  160. package/session-distill/tables/redundancy.json +10 -0
  161. package/session-distill/tables/structural_rules.json +44 -0
  162. package/session-distill/tables/transition_fixtures.json +398 -0
  163. package/session-distill/tables/transitions.json +69 -0
  164. package/session-distill/tables/unit_outcome.json +67 -0
  165. package/session-distill/tables/unit_outcome_fixtures.json +2364 -0
  166. package/wrappers/claude-run.sh +481 -33
  167. package/wrappers/claude_hermetic_evidence.py +1423 -0
  168. package/wrappers/codex-helm.sh +44 -13
  169. package/wrappers/codex-run.sh +183 -20
  170. package/wrappers/codex_frame_filter.py +1199 -0
  171. package/wrappers/codex_protocol.py +737 -0
  172. package/wrappers/jsonl_lines.py +65 -0
@@ -0,0 +1,758 @@
1
+ #!/usr/bin/env python3
2
+ """S10 parse decisions (plan WP-20 K3; design §10.1, §13.4; settled S-11; lead decisions E1, E2, E7).
3
+
4
+ The owner's copy of a review version (`decisions.ko.v<n>.md`) is read by `grammar/owner_lines.py` against that
5
+ version's own rows (`review.v<n>.json`'s spec); nothing in it is guessed, and a copy with any refused line writes
6
+ nothing. What it decides becomes rows:
7
+
8
+ - `approvals.jsonl`, one row per decided item: design §10.1's fields (`approval_id` code-generated, `item_id`,
9
+ `item_sha`, `review_version_sha` = the render's sha256, `configuration_sha`, `manifest_sha`, `results_sha`,
10
+ `decision`, `superseded_keeps`, `note`, `at`) and the plan's `decision_input_sha` (the copy's sha256). Release 1
11
+ has no S8, so `manifest_sha` and `results_sha` are the named state `untested: s8_deferred` (E2). A group row's one
12
+ decision is one row per member, each naming its group (`member_of`); a 수정 naming S7b's alternative carries it.
13
+ - `adjudications.jsonl`, one row per 판정: each resolved judgment's reference (the review's label resolved through
14
+ the version's spec) and the side or value chosen, with the value the derivation is recomputed with. Choosing a
15
+ judge whose own mark is `uncertain` resolves nothing, and is refused by line (ADJUDICATION_UNCERTAIN).
16
+ - `parsed.v<n>.json`: every item's state (decided, undecided, or stale with DECISION_STALE), the counts, F as this
17
+ parse leaves it, and §13.4's two measures this stage can compute: the owner's review time for the version (render to
18
+ parse, an upper bound) and the overturn rate over S9's frozen first-render proposals, wording-only changes apart.
19
+
20
+ An item with no approval row is undecided and is never applied (O8): nothing downstream may read the absence of a row
21
+ as anything else. A stale item is decided again in a new review version. A version is parsed once
22
+ (VERSION_PARSED_ALREADY): a changed mind is a decision in a new version, never an edit of an old one.
23
+
24
+ `configuration_sha` (E2) is the sha256 of F as this parse leaves it: B's configuration manifest (the declaration's
25
+ `config_manifest_B`) and, in the version's rank order, the operations (type, target, before-state hash) of every
26
+ approved item that changes the library and is not awaiting R (D-20261111-c48e9a). Every row of one parse carries the
27
+ same value, and S10b binds its confirmation to it.
28
+
29
+ The copy is the owner's input, not a stage artifact: its bytes are what the owner wrote, so it is bound by
30
+ `decision_input_sha` rather than declared as an input S9 recorded. The render, the rows and the frozen proposals are
31
+ S9's recorded outputs, so a version S9 has since superseded by a newer render is refused by the shared mechanism.
32
+
33
+ stage_approvals.py --self-test
34
+ """
35
+ import collections
36
+ import datetime
37
+ import hashlib
38
+ import json
39
+ import pathlib
40
+ import re
41
+ import sys
42
+
43
+ if __package__ in (None, ""): # run as a script: put session-distill/ on the import path
44
+ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
45
+ from grammar import owner_lines # noqa: E402
46
+ from runlib import records, stage_render, validate # noqa: E402
47
+ from runlib.records import Refused # noqa: E402
48
+
49
+ HERE = pathlib.Path(__file__).resolve().parents[1]
50
+ STAGE, PART = "S10", "parse"
51
+ APPROVALS, ADJUDICATIONS = "approvals.jsonl", "adjudications.jsonl"
52
+ S8_DEFERRED = "untested: s8_deferred"
53
+ # §13.4: "above one in three, the filter failed".
54
+ OVERTURN_BAR = (1, 3)
55
+ # The design's lists, copied once and held to the schemas' required sets by the self-test (plan WP-20 done-when 9).
56
+ DESIGN_10_1_APPROVAL = ("approval_id", "item_id", "item_sha", "review_version_sha", "configuration_sha",
57
+ "manifest_sha", "results_sha", "decision", "superseded_keeps", "note", "at")
58
+ PLAN_APPROVAL_ADDS = ("decision_input_sha",) # plan WP-20, settled S-11
59
+ DESIGN_10_1_ADJUDICATION = ("adjudication_id", "candidate_id", "resolved", "rationale")
60
+ _VALIDATORS = {}
61
+
62
+
63
+ def canonical(obj):
64
+ return json.dumps(obj, ensure_ascii=False, sort_keys=True, separators=(",", ":"))
65
+
66
+
67
+ def sha256_of(obj):
68
+ return hashlib.sha256(canonical(obj).encode("utf-8")).hexdigest()
69
+
70
+
71
+ def schema_of(name):
72
+ return json.loads((HERE / "schemas" / f"{name}.schema.json").read_text(encoding="utf-8"))
73
+
74
+
75
+ def validator(name):
76
+ if name not in _VALIDATORS:
77
+ _VALIDATORS[name] = validate.compile_schema(schema_of(name))
78
+ return _VALIDATORS[name]
79
+
80
+
81
+ def schema_problems(name, rows, key):
82
+ """Each row against its schema (SCHEMA_INVALID, by row and path)."""
83
+ return [f"SCHEMA_INVALID {name} {row.get(key) or '<no id>'}: {v}" for row in rows
84
+ for v in validate.validate_instance(validator(name), row)]
85
+
86
+
87
+ def inputs_of(version):
88
+ """The current review version's files, S9's recorded outputs: an older version is reached from them (`chain_to`)."""
89
+ return ({"artifact": f"review.ko.v{version}.md", "producer_stage": "S9"},
90
+ {"artifact": f"review.v{version}.json", "producer_stage": "S9"},
91
+ {"artifact": stage_render.frozen_name(version), "producer_stage": "S9"})
92
+
93
+
94
+ def latest_version(run_dir):
95
+ """The version S9's record names as its output: the current review."""
96
+ rec = records.stage_records(pathlib.Path(run_dir)).get("S9") or {}
97
+ held = [int(m.group(1)) for o in rec.get("outputs") or []
98
+ for m in [re.fullmatch(r"review\.v(\d+)\.json", o.get("artifact", ""))] if m]
99
+ if not held:
100
+ raise Refused("RENDER_ABSENT S10: S9's record names no review version to parse")
101
+ return max(held)
102
+
103
+
104
+ def chain_to(run_dir, current, version):
105
+ """`review.v<version>.json`, reached from the current rows through each version's `previous` binding (stage_render
106
+ writes it): an older version's copy is held to the current rows, and its rows file is the one the chain bound."""
107
+ rows = current
108
+ while rows["version"] > version:
109
+ prev = rows.get("previous") or {}
110
+ path = pathlib.Path(run_dir) / f"review.v{prev.get('version')}.json"
111
+ if not prev or prev["version"] < version:
112
+ raise Refused(f"VERSION_UNBOUND v{version}: the current review v{current['version']} does not reach it "
113
+ "through its earlier versions; decide in the current version's copy")
114
+ if not path.is_file() or records.sha256_file(path) != prev["rows_sha256"]:
115
+ raise Refused(f"VERSION_UNBOUND v{prev['version']}: its rows file is not the one v{rows['version']} bound")
116
+ rows = records.read_json(path)
117
+ return rows
118
+
119
+
120
+ def parsed_in(run_dir):
121
+ """Every committed parse, in the order the parses were made: `parsed.v<n>.json`, each written once."""
122
+ held = [records.read_json(p) for p in sorted(pathlib.Path(run_dir).glob("parsed.v*.json"))]
123
+ seqs = collections.Counter(p.get("parse_seq") for p in held)
124
+ twice = sorted(str(s) for s, n in seqs.items() if n > 1)
125
+ if twice:
126
+ raise Refused(f"PARSE_SEQ_DUPLICATED {', '.join(twice)}: two parses claim one place in the order")
127
+ return sorted(held, key=lambda p: p["parse_seq"])
128
+
129
+
130
+ def parse_part(run_dir):
131
+ """S10's parse part as its record holds it now, read before this parse replaces it."""
132
+ rec = records.stage_records(pathlib.Path(run_dir)).get(STAGE) or {}
133
+ return (rec.get("parts") or {}).get(PART) or {}
134
+
135
+
136
+ # ---- F and its hash -----------------------------------------------------------------------------------------------
137
+
138
+ def f_of(current, approvals):
139
+ """F as the parses leave it: in the current rank order, every item whose last approval row approves it, at the
140
+ item_sha the current rows carry, that changes the library and is not awaiting R (D-20261111-c48e9a), with its
141
+ operations' type, target and before-state hash."""
142
+ final = {}
143
+ for a in approvals:
144
+ final[a["item_id"]] = a
145
+ return [{"item_id": r["item_id"],
146
+ "operations": [{"type": op.get("type"), "target": op.get("target"),
147
+ "before_state_sha256": op.get("before_state_sha256")}
148
+ for op in (r.get("proposal") or {}).get("operations") or []]}
149
+ for r in current["rows"]
150
+ if (final.get(r["item_id"]) or {}).get("decision") == "approve"
151
+ and final[r["item_id"]]["item_sha"] == r["item_sha"]
152
+ and r.get("changes_library") and not r.get("awaiting_R")]
153
+
154
+
155
+ def configuration_sha(declaration, f):
156
+ return sha256_of({"B": (declaration or {}).get("config_manifest_B"), "F": f})
157
+
158
+
159
+ # ---- the rows -----------------------------------------------------------------------------------------------------
160
+
161
+ def approvals_of(items, rows_doc, current, copy_sha, config_sha, at):
162
+ """One §10.1 row per decided item (`items` are the decided ones), one per member for a group row (its members as
163
+ the current rows list them)."""
164
+ by_id = {r["item_id"]: r for r in current["rows"]}
165
+ out = []
166
+ for item in items:
167
+ base = {"item_sha": item["item_sha"], "review_version_sha": rows_doc["render_sha256"],
168
+ "configuration_sha": config_sha, "manifest_sha": S8_DEFERRED, "results_sha": S8_DEFERRED,
169
+ "decision": item["decision"],
170
+ "superseded_keeps": [{"record_id": k["record_id"], "grounds": k["grounds"]}
171
+ for k in item["keep_releases"]],
172
+ "note": item["note"], "at": at, "decision_input_sha": copy_sha}
173
+ if item.get("alternative"):
174
+ base["alternative"] = item["alternative"]
175
+ members = (by_id.get(item["item_id"]) or {}).get("members") or []
176
+ for ident, extra in ([(m, {"member_of": item["item_id"]}) for m in members] or [(item["item_id"], {})]):
177
+ row = {"item_id": ident, **base, **extra}
178
+ out.append({"approval_id": "A-" + sha256_of({k: v for k, v in row.items() if k != "at"})[:16], **row})
179
+ return out
180
+
181
+
182
+ def adjudications_of(items, rows_doc, current, copy_sha, problems):
183
+ """One §10.1 row per 판정: each label resolved through the current rows' disputed judgments (the item is not stale,
184
+ so they are the ones its version rendered)."""
185
+ by_id = {r["item_id"]: r for r in current["rows"]}
186
+ out = []
187
+ for item in items:
188
+ if item["decision"] != "adjudicate":
189
+ continue
190
+ disputed = {d["label"]: d for d in (by_id.get(item["item_id"]) or {}).get("disputed") or []}
191
+ resolved = []
192
+ for j in item["judgments"]:
193
+ d = disputed[j["label"]]
194
+ value = d.get(j["choice"]) if j["choice"] in ("A", "B") else j["value"]
195
+ if value not in ("met", "unmet"):
196
+ problems.append(f"ADJUDICATION_UNCERTAIN line {j['line']}: judge {j['choice']} marked {d['ref']} "
197
+ f"{value}, so choosing that side resolves nothing; write met or unmet")
198
+ continue
199
+ resolved.append({"judgment_ref": d["ref"], "choice": {"side": j["choice"], "value": value}})
200
+ row = {"candidate_id": item["item_id"], "resolved": resolved, "rationale": item["note"],
201
+ "review_version_sha": rows_doc["render_sha256"], "decision_input_sha": copy_sha}
202
+ out.append({"adjudication_id": "J-" + sha256_of(row)[:16], **row})
203
+ return out
204
+
205
+
206
+ # ---- §13.4 --------------------------------------------------------------------------------------------------------
207
+
208
+ def _instant(stamp):
209
+ return datetime.datetime.fromisoformat(stamp.replace("Z", "+00:00"))
210
+
211
+
212
+ def measures_of(rows_doc, current_doc, frozen, approvals, at):
213
+ """The owner's review time for this version, and the overturn rate over the frozen first-render proposals: per item,
214
+ its final decision (the last approval row deciding approve or reject); overturned when finally rejected, or approved
215
+ with its disposition, destination, operation targets or behavior contract changed from the frozen proposal;
216
+ wording-only changes counted apart."""
217
+ seconds = int((_instant(at) - _instant(rows_doc["rendered_at"])).total_seconds())
218
+ final = {}
219
+ for row in approvals:
220
+ if row["decision"] in ("approve", "reject") and not row.get("member_of"):
221
+ final[row["item_id"]] = row["decision"]
222
+ current = {r["item_id"]: r for r in current_doc["rows"]}
223
+ decided, overturned, wording = [], [], []
224
+ for item_id, choice in sorted(final.items()):
225
+ held = ((frozen or {}).get("items") or {}).get(item_id)
226
+ if held is None:
227
+ continue
228
+ decided.append(item_id)
229
+ proposal = (current.get(item_id) or {}).get("proposal") or {}
230
+ if choice == "reject" or (proposal and not stage_render.same_material(stage_render.material_of(proposal),
231
+ held["material"])):
232
+ overturned.append(item_id)
233
+ elif proposal and sha256_of({"reasons": proposal.get("reasons"), "artifact_set": proposal.get("artifact_set")}) \
234
+ != held["wording_sha256"]:
235
+ wording.append(item_id)
236
+ bar_n, bar_d = OVERTURN_BAR
237
+ return {"review_time": {"version": rows_doc["version"], "seconds_at_most": seconds,
238
+ "from": rows_doc["rendered_at"], "to": at},
239
+ "overturn": {"decided": len(decided), "overturned": len(overturned), "wording_only": len(wording),
240
+ "rate": f"{len(overturned)} / {len(decided)}" if decided else "none decided",
241
+ "filter_failed": bool(decided) and len(overturned) * bar_d > bar_n * len(decided),
242
+ "overturned_items": overturned, "wording_only_items": wording}}
243
+
244
+
245
+ # ---- the stage ----------------------------------------------------------------------------------------------------
246
+
247
+ def parse_document(declaration, render_text, rows_doc, current, frozen, copy_text, prior_approvals, at):
248
+ """`(approvals, adjudications, parsed, problems)` of one copy of version `rows_doc`, held to the `current` rows:
249
+ pure, every input given. An item whose sha the current rows no longer carry is stale, never decided from it."""
250
+ name = rows_doc["render"]
251
+ if rows_doc.get("render_sha256") != owner_lines.sha256_text(render_text):
252
+ return [], [], None, [f"RENDER_UNBOUND {name}: the rows file binds another render than the one on disk"]
253
+ result, problems = owner_lines.parse(render_text, copy_text, spec=current["spec"], render_name=name)
254
+ if result is None or problems:
255
+ return [], [], None, problems
256
+ items = result["items"]
257
+ copy_sha = owner_lines.sha256_text(copy_text)
258
+ decided = [i for i in items if i["state"] == "decided"]
259
+ provisional = approvals_of(decided, rows_doc, current, copy_sha, "0" * 64, at)
260
+ f = f_of(current, list(prior_approvals) + provisional)
261
+ config = configuration_sha(declaration, f)
262
+ adjudications = adjudications_of(decided, rows_doc, current, copy_sha, problems)
263
+ approvals = approvals_of(decided, rows_doc, current, copy_sha, config, at)
264
+ problems += schema_problems("approval", approvals, "approval_id")
265
+ problems += schema_problems("adjudication", adjudications, "adjudication_id")
266
+ if problems:
267
+ return [], [], None, problems
268
+ states = collections.Counter(i["state"] for i in items)
269
+ parsed = {"stage": STAGE, "version": rows_doc["version"], "current_version": current["version"], "render": name,
270
+ "render_sha256": rows_doc["render_sha256"], "decision_input_sha": copy_sha, "at": at,
271
+ "configuration_sha": config, "F": f,
272
+ "items": [{"item_id": i["item_id"], "state": i["state"], "decision": i["decision"],
273
+ **({"code": i["code"]} if i.get("code") else {})} for i in items],
274
+ "counts": {"items": len(items), "decided": states["decided"], "undecided": states["undecided"],
275
+ "stale": states["stale"], "approval_rows": len(approvals), "adjudications": len(adjudications),
276
+ "decision": dict(sorted(collections.Counter(i["decision"] for i in decided).items()))},
277
+ # the owner's review apart from the stage's parts (Codex WP-20 r1 F6): `complete` only when the copy
278
+ # left no row undecided and none stale; an undecided row is never applied, whatever this says
279
+ "review_state": review_state_of(states),
280
+ "measures": measures_of(rows_doc, current, frozen, list(prior_approvals) + approvals, at),
281
+ "approvals": approvals, "adjudications": adjudications}
282
+ return approvals, adjudications, parsed, []
283
+
284
+
285
+ def review_state_of(states):
286
+ """`partial` when any row of the version is undecided or stale, `complete` otherwise."""
287
+ return "partial" if states["undecided"] or states["stale"] else "complete"
288
+
289
+
290
+ def rows_in(path):
291
+ """The rows a JSONL file holds, each line one JSON object; none when the file is not there."""
292
+ return [json.loads(line) for line in records.jsonl_read(path) if line.strip()] if path.is_file() else []
293
+
294
+
295
+ def jsonl_text(rows):
296
+ return "".join(canonical(r) + "\n" for r in rows)
297
+
298
+
299
+ def run(run_dir, version=None, copy_path=None):
300
+ """S10's parse part through the shared mechanism. A parse is committed when its `parsed.v<n>.json` is written (once,
301
+ after every check); `approvals.jsonl` and `adjudications.jsonl` are then made again from every committed parse, in
302
+ the order they were made. A version parsed under a complete record is refused (VERSION_PARSED_ALREADY); one whose
303
+ parse was cut short after its commit is finished without parsing again (the record says `resumed`)."""
304
+ run_dir = pathlib.Path(run_dir)
305
+ latest = latest_version(run_dir)
306
+ version = version or latest
307
+ if not 1 <= version <= latest:
308
+ raise Refused(f"VERSION_UNKNOWN v{version}: the reviews are v1 to v{latest}")
309
+ marker = run_dir / f"parsed.v{version}.json"
310
+ state = {}
311
+
312
+ def once():
313
+ # Under the stage's lock too, before its record is replaced (`records.run_stage`'s `admit`): checked only
314
+ # before it, a second invocation passed while the first was committing and then overwrote the first's
315
+ # decisions (Codex WP-20 r1 F2). A committed parse whose publication was cut short is finished, never redone.
316
+ state["resumed"] = marker.is_file()
317
+ if state["resumed"] and parse_part(run_dir).get("status") == "complete":
318
+ raise Refused(f"VERSION_PARSED_ALREADY v{version}: a version's decisions are parsed once; a changed "
319
+ "decision is made in a new review version")
320
+ once()
321
+ with records.run_stage(run_dir, STAGE, inputs_of(latest), part=PART, admit=once) as stage:
322
+ resumed = state["resumed"]
323
+ if not resumed:
324
+ current = records.read_json(run_dir / f"review.v{latest}.json")
325
+ frozen = records.read_json(run_dir / stage_render.frozen_name(latest))
326
+ rows_doc = chain_to(run_dir, current, version)
327
+ render_text = (run_dir / rows_doc["render"]).read_text(encoding="utf-8")
328
+ source = pathlib.Path(copy_path) if copy_path else run_dir / rows_doc["copy"]
329
+ try:
330
+ copy_text = source.read_bytes().decode("utf-8")
331
+ except (OSError, UnicodeDecodeError) as exc:
332
+ raise Refused(f"COPY_UNREADABLE {source.name}: {type(exc).__name__}; the copy is UTF-8 text") from exc
333
+ committed = parsed_in(run_dir)
334
+ prior = [a for p in committed for a in p["approvals"]]
335
+ _a, _j, parsed, problems = parse_document(stage.declaration, render_text, rows_doc, current, frozen,
336
+ copy_text, prior, records.now())
337
+ if problems:
338
+ raise Refused("\n".join(problems))
339
+ if not parsed["counts"]["decided"]:
340
+ raise Refused(f"NOTHING_DECIDED v{version}: the copy decides no item, and a version is parsed once; "
341
+ f"write the 결정: lines in {source.name} first")
342
+ parsed["parse_seq"] = 1 + max((p["parse_seq"] for p in committed), default=0)
343
+ records.write_json(run_dir, marker, parsed)
344
+ committed = parsed_in(run_dir)
345
+ records.write_text(run_dir, run_dir / APPROVALS, jsonl_text([a for p in committed for a in p["approvals"]]))
346
+ records.write_text(run_dir, run_dir / ADJUDICATIONS,
347
+ jsonl_text([j for p in committed for j in p["adjudications"]]))
348
+ for rel in [APPROVALS, ADJUDICATIONS] + [f"parsed.v{p['version']}.json" for p in committed]:
349
+ stage.output(rel)
350
+ mine = next(p for p in committed if p["version"] == version)
351
+ return {"version": version, "current_version": mine["current_version"], "resumed": resumed,
352
+ "review_state": mine.get("review_state"), **mine["counts"]}
353
+
354
+
355
+ # ---- self-test ----------------------------------------------------------------------------------------------------
356
+
357
+ def fixture():
358
+ """A review version made by S9's own writers (rows by `stage_render._row`, hashes by `keyed`, the text by
359
+ `render_text`), ranked by hand so this suite does not depend on the order's table."""
360
+ sr = stage_render
361
+ t = "untested: s8_deferred"
362
+ o6 = {k: f"{k} 내용" for k in sr.o6_fields()}
363
+ place = {"disposition": "place", "consequence": "quality",
364
+ "operations": [{"type": "create", "target": "claude/guides/g.md", "before_state_sha256": "absent",
365
+ "content": "text"}],
366
+ "destination": {"layer": "guides", "carrier": "claude/guides/g.md"}, "reasons": dict(o6), "unknowns": []}
367
+ reduce = {**place, "disposition": "reduce", "keep_record_named": "R-1",
368
+ "operations": [{"type": "delete", "target": "claude/guides/k.md", "before_state_sha256": "b" * 64}]}
369
+ reviewed = {"state": "reviewed", "verdict": "disagree", "disposition_holds": True, "destination_holds": False,
370
+ "bars_failing": [], "faithful_merge": "n/a", "disagreement": True, "owner_resolves": True,
371
+ "notes": "다른 자리가 싸다", "alternative": {"disposition": "incubate", "reason": "관찰을 더 모은다"}}
372
+ rows = [sr._row("k-place", "candidate", "proposed", t, dict(o6), disposition="place", changes_library=True,
373
+ proposal=place, kind="gap", diagnosis="gap", source="formed", s7b=reviewed),
374
+ sr._row("k-keep", "candidate", "proposed", t, dict(o6), disposition="keep", proposal={**place,
375
+ "disposition": "keep", "operations": []}, kind="confirmed", diagnosis="covered", source="formed"),
376
+ sr._row("k-reduce", "candidate", "proposed", t, dict(o6), disposition="reduce", changes_library=True,
377
+ proposal=reduce, guarded_keeps=["R-1"], kind="misfire", diagnosis="covered", source="formed"),
378
+ sr._row("k-awaits", "candidate", "proposed", t, dict(o6), disposition="place", changes_library=True,
379
+ proposal={**place, "operations": [{"type": "create", "target": "claude/guides/r.md",
380
+ "before_state_sha256": "absent"}]},
381
+ awaiting_R=True, awaiting_R_reason="core, adjudicated", kind="gap", diagnosis="gap", source="formed"),
382
+ sr._row("k-disp", "candidate", "disputed", t, dict(o6), source="formed",
383
+ disputed=[{"label": "1", "ref": "requirement/bounded", "A": "unmet", "B": "met",
384
+ "values": ["met", "unmet"]},
385
+ {"label": "2", "ref": "requirement/positioned", "A": "met", "B": "uncertain",
386
+ "values": ["met", "unmet"]}]),
387
+ sr._row("group:legacy:incubating", "legacy_group", None, t, dict(o6), source="legacy",
388
+ members=["legacy:L-1", "legacy:L-2"])]
389
+ keyed = [dict(sr.keyed(r), rank=n, status_group="proposed_and_tested" if r["status"] == "proposed" else
390
+ "disputed" if r["status"] == "disputed" else "already_resolved_and_unclassified")
391
+ for n, r in enumerate(rows, 1)]
392
+ doc = {"rows": keyed, "appendix": {"non_findings": [], "group_members": {"group:legacy:incubating":
393
+ ["legacy:L-1", "legacy:L-2"]}},
394
+ "counts": {"disposition": {}, "status": {}, "candidates": {}, "candidate_members": 0, "rejected_findings": 0,
395
+ "rejected_finding_members": 0, "non_findings": {}}}
396
+ meta = {"version": 1, "run_id": "fx", "declaration": {}, "census": {}, "window_flags": None, "spent": {},
397
+ "resolutions": "없음", "rejection_share": "없음", "controls": "없음", "legacy_unexpected": []}
398
+ text = sr.render_text(doc, meta, {})
399
+ spec = sr.spec_of(doc)
400
+ rows_doc = {"stage": "S9", "version": 1, "render": "review.ko.v1.md", "render_sha256": owner_lines.sha256_text(text),
401
+ "copy": "decisions.ko.v1.md", "rendered_at": "2026-11-12T00:00:00+00:00", "rows": keyed,
402
+ "appendix": doc["appendix"], "counts": doc["counts"], "spec": spec}
403
+ frozen = sr.frozen_after(None, keyed, 1, "2026-11-12T00:00:00+00:00")
404
+ return text, rows_doc, frozen, {"config_manifest_B": {"global": "b" * 64}}
405
+
406
+
407
+ def self_test():
408
+ """Positive controls first; then each verb and binding; then one planted violation per rule, each named."""
409
+ import copy
410
+ failures, ran, reporting = [], [], []
411
+
412
+ def mark(name):
413
+ if reporting:
414
+ raise RuntimeError(f"CONTROL_AFTER_SUMMARY {name}")
415
+ ran.append(name)
416
+
417
+ def control(name, got, want):
418
+ mark(name)
419
+ if not isinstance(got, str):
420
+ raise TypeError(f"CONTROL_GOT_NOT_STR {name}: {type(got).__name__}")
421
+ if want not in got:
422
+ failures.append((name, f"expected {want!r} in {got[:500]!r}"))
423
+
424
+ def equal(name, got, want):
425
+ mark(name)
426
+ if got != want:
427
+ failures.append((name, f"expected {want!r}, got {got!r}"))
428
+
429
+ def clean(name, problems):
430
+ mark(name)
431
+ if not isinstance(problems, list):
432
+ raise TypeError(f"CLEAN_PROBLEMS_NOT_LIST {name}: {type(problems).__name__}")
433
+ if problems:
434
+ failures.append((name, f"expected nothing, got {problems}"))
435
+
436
+ text, rows_doc, frozen, declaration = fixture()
437
+ blank = owner_lines.copy_of(text, "review.ko.v1.md")
438
+ at = "2026-11-12T00:30:00+00:00"
439
+
440
+ def fill(item, *lines, base=None):
441
+ held = (base or blank).split("\n")
442
+ start = next(i for i, x in enumerate(held) if x.startswith(f"<!-- owner-block review item={item} "))
443
+ end = next(i for i in range(start + 1, len(held)) if held[i] == owner_lines.CLOSE)
444
+ return "\n".join(held[:start + 1] + list(lines) + held[end:])
445
+
446
+ def parsed_of(copy_text, current=None, prior=()):
447
+ return parse_document(declaration, text, rows_doc, current or rows_doc, frozen, copy_text, list(prior), at)
448
+
449
+ def said(copy_text, rows=None):
450
+ return "\n".join(parsed_of(copy_text, rows)[3]) or "(none)"
451
+
452
+ def approval(copy_text, ident, rows=None):
453
+ return next((a for a in parsed_of(copy_text, rows)[0] if a["item_id"] == ident), {})
454
+
455
+ # ---- positive controls ---------------------------------------------------------------------------------------
456
+ approvals, adjudications, parsed, problems = parsed_of(blank)
457
+ clean("the unedited copy parses with nothing refused", problems)
458
+ equal("and every item is undecided, so no approval row is written for any (O8)",
459
+ ((parsed or {}).get("counts", {}).get("undecided"), len(approvals), len(adjudications)), (6, 0, 0))
460
+ equal("every item of the version is listed with its state", [i["item_id"] for i in (parsed or {}).get("items", [])],
461
+ [r["item_id"] for r in rows_doc["rows"]])
462
+ equal("the approval schema's required set is §10.1's list plus the plan's decision_input_sha",
463
+ sorted(schema_of("approval")["required"]), sorted(DESIGN_10_1_APPROVAL + PLAN_APPROVAL_ADDS))
464
+ equal("the adjudication schema's required set is §10.1's list exactly", sorted(schema_of("adjudication")["required"]),
465
+ sorted(DESIGN_10_1_ADJUDICATION))
466
+
467
+ # ---- each verb, and the bindings ---------------------------------------------------------------------------
468
+ copy_place = fill("k-place", "결정: 승인", "메모:")
469
+ a = approval(copy_place, "k-place")
470
+ equal("승인 is an approval row with every §10.1 field and the copy's sha",
471
+ sorted(a), sorted(DESIGN_10_1_APPROVAL + PLAN_APPROVAL_ADDS))
472
+ equal("it binds the render, the copy and the item",
473
+ (a.get("review_version_sha"), a.get("decision_input_sha"), a.get("item_sha")),
474
+ (rows_doc["render_sha256"], owner_lines.sha256_text(copy_place), rows_doc["spec"]["k-place"]["item_sha"]))
475
+ equal("release 1's S8 hashes are the named state, never null", (a.get("manifest_sha"), a.get("results_sha")),
476
+ (S8_DEFERRED, S8_DEFERRED))
477
+ equal("the approval id is code-generated and stable for the same decision", approval(copy_place, "k-place")
478
+ .get("approval_id"), a.get("approval_id"))
479
+ control("and has its shape", str(a.get("approval_id")), "A-")
480
+ equal("수정 대안 <id> adopts S7b's alternative", approval(fill("k-place", "결정: 수정 대안 s7b"), "k-place")
481
+ .get("alternative"), "s7b")
482
+ equal("수정 with a note returns it to S7 with the note",
483
+ (approval(fill("k-place", "결정: 수정", "메모: 대상을 좁힌다"), "k-place").get("decision"),
484
+ approval(fill("k-place", "결정: 수정", "메모: 대상을 좁힌다"), "k-place").get("note")),
485
+ ("revise", "대상을 좁힌다"))
486
+ equal("보류 and 기각", (approval(fill("k-keep", "결정: 보류"), "k-keep").get("decision"),
487
+ approval(fill("k-keep", "결정: 기각"), "k-keep").get("decision")), ("defer", "reject"))
488
+ a = approval(fill("k-reduce", "결정: 승인", "keep 해제: R-1 사용자가 직접 줄인다"), "k-reduce")
489
+ equal("an approval over a keep record carries its release as superseded_keeps", a.get("superseded_keeps"),
490
+ [{"record_id": "R-1", "grounds": "사용자가 직접 줄인다"}])
491
+ control("and without the release it is refused KEEP_GUARDED", said(fill("k-reduce", "결정: 승인")), "KEEP_GUARDED line")
492
+ rows = parsed_of(fill("group:legacy:incubating", "결정: 승인"))[0]
493
+ equal("a group row's one decision is one row per member, each naming its group",
494
+ [(r["item_id"], r.get("member_of")) for r in rows],
495
+ [("legacy:L-1", "group:legacy:incubating"), ("legacy:L-2", "group:legacy:incubating")])
496
+ both = fill("k-keep", "결정: 승인", base=copy_place)
497
+ rows = parsed_of(both)[0]
498
+ equal("every row of one parse carries the same configuration_sha", len({r["configuration_sha"] for r in rows}) == 1
499
+ and len(rows) == 2, True)
500
+ p1 = parsed_of(copy_place)[2] or {}
501
+ p2 = parsed_of(both)[2] or {}
502
+ equal("F holds the approved item that changes the library; a ledger-only approval leaves F as it was",
503
+ ([x["item_id"] for x in p1.get("F", [])], p1.get("configuration_sha") == p2.get("configuration_sha")),
504
+ (["k-place"], True))
505
+ p3 = parsed_of(fill("k-awaits", "결정: 승인", base=copy_place))[2] or {}
506
+ equal("an approved item awaiting R enters no F (D-20261111-c48e9a)", [x["item_id"] for x in p3.get("F", [])],
507
+ ["k-place"])
508
+ f1 = p1.get("F") or [{"item_id": "none", "operations": [{"before_state_sha256": "x"}]}]
509
+ f2 = copy.deepcopy(f1)
510
+ f2[0]["operations"][0]["before_state_sha256"] = "c" * 64
511
+ equal("an approved operation's before-state is part of configuration_sha",
512
+ configuration_sha(declaration, f1) != configuration_sha(declaration, f2), True)
513
+ equal("and so is B's configuration manifest", configuration_sha(declaration, f1)
514
+ != configuration_sha({"config_manifest_B": {"global": "c" * 64}}, f1), True)
515
+ later = parsed_of(fill("k-keep", "결정: 보류"), prior=parsed_of(copy_place)[0])[2] or {}
516
+ equal("F holds what earlier parses approved, not only this one's", [x["item_id"] for x in later.get("F", [])],
517
+ ["k-place"])
518
+ equal("F carries each approved operation's type, target and before-state",
519
+ (p1.get("F") or [{}])[0].get("operations"),
520
+ [{"type": "create", "target": "claude/guides/g.md", "before_state_sha256": "absent"}])
521
+ undone = parsed_of(fill("k-place", "결정: 보류"), prior=parsed_of(copy_place)[0])[2] or {}
522
+ equal("an item approved and then deferred in a later parse is not in F: the last decision is the item's",
523
+ undone.get("F"), [])
524
+ old = [dict(a, item_sha="0" * 64) for a in parsed_of(copy_place)[0]]
525
+ moved_on = parsed_of(fill("k-keep", "결정: 보류"), prior=old)[2] or {}
526
+ equal("an earlier approval of an item that has changed since is not in F", moved_on.get("F"), [])
527
+
528
+ # ---- the stale, the adjudicated, the schema -------------------------------------------------------------------
529
+ stale = copy.deepcopy(rows_doc)
530
+ stale["spec"]["k-place"]["item_sha"] = "0" * 64
531
+ a, _j, p, problems = parse_document(declaration, text, rows_doc, stale, frozen, copy_place, [], at)
532
+ equal("an item whose sha changed after rendering is stale: no approval row, its code listed",
533
+ (len(a), [i.get("code", "").split(" ", 1)[0] for i in (p or {}).get("items", []) if i["state"] == "stale"]),
534
+ (0, ["DECISION_STALE"]))
535
+ adj = fill("k-disp", "결정: 판정", "메모: 경계가 분명하다", "판정 1: A", "판정 2: met")
536
+ _a, j, _p, problems = parsed_of(adj)
537
+ equal("판정 is one adjudication row: each label's reference and the side or value, with the value used",
538
+ [(r["judgment_ref"], r["choice"]) for r in (j[0]["resolved"] if j else [])],
539
+ [("requirement/bounded", {"side": "A", "value": "unmet"}),
540
+ ("requirement/positioned", {"side": "own", "value": "met"})])
541
+ equal("its rationale is the owner's note, and it binds the render and the copy",
542
+ ((j or [{}])[0].get("rationale"), (j or [{}])[0].get("decision_input_sha")),
543
+ ("경계가 분명하다", owner_lines.sha256_text(adj)))
544
+ copy_b = fill("k-disp", "결정: 판정", "메모: 근거", "판정 1: A", "판정 2: B")
545
+ control("choosing a judge whose own mark is uncertain resolves nothing, refused by line", said(copy_b),
546
+ f"ADJUDICATION_UNCERTAIN line {copy_b.split(chr(10)).index('판정 2: B') + 1}")
547
+ built = approvals_of([{"item_id": "k-place", "item_sha": "a" * 64, "state": "decided", "decision": "approve",
548
+ "keep_releases": [], "note": "", "alternative": None}], rows_doc, rows_doc, "c" * 64,
549
+ "d" * 64, at)
550
+ broken = [{k: v for k, v in built[0].items() if k != "configuration_sha"}]
551
+ control("a row missing configuration_sha is SCHEMA_INVALID", "\n".join(schema_problems("approval", broken,
552
+ "approval_id")),
553
+ "SCHEMA_INVALID approval")
554
+ control("a null results_sha is SCHEMA_INVALID",
555
+ "\n".join(schema_problems("approval", [dict(built[0], results_sha=None)], "approval_id")), "results_sha")
556
+ control("a results_sha that is neither a hash nor the named state is SCHEMA_INVALID",
557
+ "\n".join(schema_problems("approval", [dict(built[0], results_sha="pending")], "approval_id")), "results_sha")
558
+ clean("the rows this stage builds conform", schema_problems("approval", built, "approval_id"))
559
+ control("an edit outside a block refuses the whole copy by line, and nothing is built",
560
+ said(blank.replace("- 시험: untested: s8_deferred", "- 시험: passed", 1)), "EDIT_OUTSIDE_EDITABLE line")
561
+ control("a render the rows file does not bind is refused",
562
+ "\n".join(parse_document(declaration, text + "x\n", rows_doc, rows_doc, frozen, blank, [], at)[3]),
563
+ "RENDER_UNBOUND")
564
+
565
+ # ---- §13.4 ----------------------------------------------------------------------------------------------------
566
+ m = (parsed_of(blank)[2] or {}).get("measures", {})
567
+ equal("the review time is render to parse, an upper bound in seconds", m.get("review_time", {}).get("seconds_at_most"),
568
+ 1800)
569
+ m = (parsed_of(fill("k-keep", "결정: 기각", base=copy_place))[2] or {}).get("measures", {}).get("overturn", {})
570
+ equal("a frozen proposal finally rejected is overturned; one approved as frozen is not",
571
+ (m.get("decided"), m.get("overturned"), m.get("overturned_items")), (2, 1, ["k-keep"]))
572
+ equal("and one in two is above the bar: the filter failed", m.get("filter_failed"), True)
573
+ three = fill("k-reduce", "결정: 기각", base=fill("k-keep", "결정: 승인", base=copy_place))
574
+ m = (parsed_of(three)[2] or {}).get("measures", {}).get("overturn", {})
575
+ equal("one in three is not above the bar", (m.get("decided"), m.get("overturned"), m.get("filter_failed")),
576
+ (3, 1, False))
577
+ moved = copy.deepcopy(rows_doc)
578
+ next(r for r in moved["rows"] if r["item_id"] == "k-place")["proposal"]["destination"] = {"layer": "personal",
579
+ "carrier": "x"}
580
+ m = (parse_document(declaration, text, rows_doc, moved, frozen, copy_place, [], at)[2] or {}).get("measures", {}) \
581
+ .get("overturn", {})
582
+ equal("an approval of a proposal changed materially since it was frozen is overturned", m.get("overturned_items"),
583
+ ["k-place"])
584
+ worded = copy.deepcopy(rows_doc)
585
+ next(r for r in worded["rows"] if r["item_id"] == "k-place")["proposal"]["reasons"]["reason"] = "다른 말"
586
+ m = (parse_document(declaration, text, rows_doc, worded, frozen, copy_place, [], at)[2] or {}).get("measures", {}) \
587
+ .get("overturn", {})
588
+ equal("a wording-only change is reported apart, not as an overturn",
589
+ (m.get("overturned"), m.get("wording_only_items")), (0, ["k-place"]))
590
+ prior = parsed_of(fill("k-keep", "결정: 기각"))[0]
591
+ m = (parsed_of(fill("k-keep", "결정: 승인"), prior=prior)[2] or {}).get("measures", {}).get("overturn", {})
592
+ equal("the final decision is the last one: a rejection approved in a later parse is not overturned",
593
+ m.get("overturned_items"), [])
594
+
595
+ # ---- the stage, end to end: S9 renders the golden run, S10 parses the owner's copies ----------------------------
596
+ import shutil
597
+ import subprocess
598
+ import tempfile
599
+ root = pathlib.Path(tempfile.mkdtemp(prefix="s10-"))
600
+
601
+ def decide(copy_text, choices):
602
+ """The copy with each `{item_id: line}` written into its block."""
603
+ held = copy_text.split("\n")
604
+ for item, line in choices.items():
605
+ start = next(i for i, x in enumerate(held) if x.startswith(f"<!-- owner-block review item={item} "))
606
+ end = next(i for i in range(start + 1, len(held)) if held[i] == owner_lines.CLOSE)
607
+ held = held[:start + 1] + [line] + held[end:]
608
+ return "\n".join(held)
609
+
610
+ def attempt(fn, *args, **kwargs):
611
+ try:
612
+ return fn(*args, **kwargs)
613
+ except (Refused, OSError, KeyError, StopIteration) as exc: # a reverted check fails its control by name
614
+ return f"{type(exc).__name__}: {exc}"
615
+ class SectionStopped(Exception):
616
+ pass
617
+ try:
618
+ try:
619
+ run_dir = stage_render.golden_run(root)
620
+ except Exception as exc: # an upstream stage that breaks fails this section's first control by name
621
+ equal("the golden run renders twice", f"GOLDEN_RUN_FAILED {type(exc).__name__}: {exc}"[:300], (1, 2))
622
+ raise SectionStopped from exc
623
+ v1 = attempt(stage_render.run, run_dir)
624
+ v2 = attempt(stage_render.run, run_dir)
625
+ equal("the golden run renders twice", (getattr(v1, "get", lambda k: v1)("version"),
626
+ getattr(v2, "get", lambda k: v2)("version")), (1, 2))
627
+ ids = [r["item_id"] for r in records.read_json(run_dir / "review.v2.json")["rows"]] if isinstance(v2, dict) \
628
+ else ["(none)"] * 3
629
+ copy1 = (run_dir / "decisions.ko.v1.md").read_text(encoding="utf-8") if isinstance(v1, dict) else ""
630
+ cli_out = root / "cli"
631
+ if copy1:
632
+ (run_dir / "decisions.ko.v1.md").write_text(decide(copy1, {ids[0]: "결정: 보류", ids[1]: "결정: 기각"}),
633
+ encoding="utf-8")
634
+ shutil.copytree(run_dir.parent, cli_out)
635
+ shutil.copytree(run_dir.parent, root / "race")
636
+ got = attempt(run, run_dir, 1)
637
+ equal("an older version's copy parses against the current rows: its two decisions, v2 current",
638
+ (getattr(got, "get", lambda k: got)("approval_rows"), getattr(got, "get", lambda k: None)("current_version")),
639
+ (2, 2))
640
+ rows = rows_in(run_dir / APPROVALS)
641
+ equal("approvals.jsonl holds them, bound to version 1's render",
642
+ sorted({(r["review_version_sha"], r["decision"]) for r in rows}),
643
+ sorted({(records.read_json(run_dir / "review.v1.json").get("render_sha256"), d)
644
+ for d in ("defer", "reject")}) if (run_dir / "review.v1.json").is_file() else [])
645
+ rec = parse_part(run_dir)
646
+ equal("S10's parse part records the approvals, the adjudications and the committed parse",
647
+ (rec.get("status"), sorted(o["artifact"] for o in rec.get("outputs") or [])),
648
+ ("complete", sorted([APPROVALS, ADJUDICATIONS, "parsed.v1.json"])))
649
+ control("a version parsed under a complete record is never parsed again", str(attempt(run, run_dir, 1)),
650
+ "VERSION_PARSED_ALREADY v1")
651
+ equal("the parse says the owner's review of the version is partial while a row is undecided (Codex WP-20 r1 "
652
+ "F6)", (getattr(got, "get", lambda k: got)("review_state"),
653
+ (records.read_json(run_dir / "parsed.v1.json") if (run_dir / "parsed.v1.json").is_file()
654
+ else {}).get("review_state")), ("partial", "partial"))
655
+ equal("and complete only when no row is undecided or stale",
656
+ [review_state_of(collections.Counter(c)) for c in
657
+ ({"decided": 3}, {"decided": 2, "undecided": 1}, {"decided": 2, "stale": 1})],
658
+ ["complete", "partial", "partial"])
659
+ # Codex WP-20 r1 F2: another invocation commits its parse of v1 after this one's first check and before its
660
+ # lock; the stand-in runs that parse as the lock is about to be taken, so only the check under it can see it
661
+ race_dir = root / "race" / run_dir.name
662
+ if race_dir.is_dir() and copy1:
663
+ other = root / "race-other.ko.md"
664
+ other.write_text(decide(copy1, {ids[0]: "결정: 기각"}), encoding="utf-8")
665
+ real_run_stage, raced = records.run_stage, []
666
+
667
+ def racing(run_dir_, stage_, *args, **kwargs):
668
+ if stage_ == STAGE and not raced:
669
+ raced.append("started") # before the inner parse, whose own lock passes through here
670
+ raced.append(attempt(run, race_dir, 1, other))
671
+ return real_run_stage(run_dir_, stage_, *args, **kwargs)
672
+ records.run_stage = racing
673
+ try:
674
+ lost = str(attempt(run, race_dir, 1))
675
+ finally:
676
+ records.run_stage = real_run_stage
677
+ control("a parse committed after this one's first check is seen under the stage's lock", lost,
678
+ "VERSION_PARSED_ALREADY v1")
679
+ kept = records.read_json(race_dir / "parsed.v1.json") if (race_dir / "parsed.v1.json").is_file() else {}
680
+ equal("and the committed parse is the first one's, not overwritten",
681
+ ([i.get("decision") for i in kept.get("items") or [] if i.get("state") == "decided"],
682
+ [r["decision"] for r in rows_in(race_dir / APPROVALS)]), (["reject"], ["reject"]))
683
+ else:
684
+ equal("the race copy of the golden run is made", race_dir.is_dir(), True)
685
+ copy2 = (run_dir / "decisions.ko.v2.md").read_text(encoding="utf-8") if isinstance(v2, dict) else ""
686
+ if copy2:
687
+ (run_dir / "decisions.ko.v2.md").write_text(decide(copy2, {ids[2]: "결정: 보류"}), encoding="utf-8")
688
+ got = attempt(run, run_dir)
689
+ rows = rows_in(run_dir / APPROVALS)
690
+ equal("a second parse adds its rows after the first's, in the order the parses were made",
691
+ [r["item_id"] for r in rows], ids[:3])
692
+ committed = attempt(parsed_in, run_dir)
693
+ equal("each committed parse has its place in the order",
694
+ [p.get("parse_seq") for p in committed] if isinstance(committed, list) else committed, [1, 2])
695
+ before = (run_dir / APPROVALS).read_bytes() if (run_dir / APPROVALS).is_file() else b""
696
+ marker2 = run_dir / "parsed.v2.json"
697
+ committed2 = marker2.read_bytes() if marker2.is_file() else b""
698
+ held = records.read_json(records.record_path(run_dir, STAGE))
699
+ ((held.get("parts") or {}).get(PART) or {})["status"] = "running"
700
+ records.write_json(run_dir, records.record_path(run_dir, STAGE), held)
701
+ (run_dir / APPROVALS).unlink(missing_ok=True)
702
+ got = attempt(run, run_dir, 2)
703
+ equal("a parse cut short after its commit is finished without parsing again, and its rows are made again",
704
+ (getattr(got, "get", lambda k: got)("resumed"),
705
+ (run_dir / APPROVALS).read_bytes() if (run_dir / APPROVALS).is_file() else b"(none)",
706
+ marker2.read_bytes() if marker2.is_file() else b"(none)", parse_part(run_dir).get("status")),
707
+ (True, before, committed2, "complete"))
708
+ rows1 = run_dir / "review.v1.json"
709
+ kept = rows1.read_bytes()
710
+ rows1.write_bytes(kept + b"\n")
711
+ control("a version whose rows file is not the one the next version bound is not reached",
712
+ str(attempt(chain_to, run_dir, records.read_json(run_dir / "review.v2.json"), 1)), "VERSION_UNBOUND v1")
713
+ rows1.write_bytes(kept)
714
+ v3 = attempt(stage_render.run, run_dir)
715
+ control("a copy that decides nothing is refused, and nothing of it is committed",
716
+ f"{attempt(run, run_dir)} {(run_dir / 'parsed.v3.json').exists()}", "NOTHING_DECIDED v3")
717
+ equal("and the version stays open to its decisions", (run_dir / "parsed.v3.json").exists() or v3 == {}, False)
718
+ control("a version no render made is refused by name", str(attempt(run, run_dir, 9)), "VERSION_UNKNOWN v9")
719
+ control("a copy that cannot be read is refused by name",
720
+ str(attempt(run, run_dir, 3, root / "no-such-copy.md")), "COPY_UNREADABLE no-such-copy.md")
721
+ if (run_dir / "parsed.v1.json").is_file():
722
+ planted = dict(records.read_json(run_dir / "parsed.v1.json"), version=7)
723
+ records.write_json(run_dir, run_dir / "parsed.v7.json", planted)
724
+ control("two parses claiming one place in the order are refused by name", str(attempt(parsed_in, run_dir)),
725
+ "PARSE_SEQ_DUPLICATED 1")
726
+ (run_dir / "parsed.v7.json").unlink()
727
+ if cli_out.is_dir():
728
+ done = subprocess.run([sys.executable, "-I", str(HERE / "distill.py"), "parse-decisions", "--run-id",
729
+ run_dir.name, "--out", str(cli_out), "--version", "1"],
730
+ capture_output=True, text=True, timeout=600)
731
+ said_cli = f"rc={done.returncode} {done.stdout}{done.stderr[-400:]}"
732
+ else:
733
+ said_cli = "no run to copy"
734
+ control("the driver's `parse-decisions` runs S10's parse as a process and prints what it recorded", said_cli,
735
+ "rc=0 S10 parse-decisions: version 1 (current 2): 2 decided")
736
+ except SectionStopped:
737
+ pass
738
+ except Exception as exc: # a later break fails this section by name, never the whole suite
739
+ failures.append(("the end-to-end section ran to its end", f"{type(exc).__name__}: {exc}"[:600]))
740
+ finally:
741
+ shutil.rmtree(root, ignore_errors=True)
742
+
743
+ reporting.append(True)
744
+ if failures:
745
+ for label, detail in failures:
746
+ print(f"stage_approvals --self-test [FAIL] {label}: {detail}", file=sys.stderr)
747
+ print(f"stage_approvals --self-test: FAILED ({len(failures)} of {len(ran)} controls)", file=sys.stderr)
748
+ return 1
749
+ print(f"stage_approvals --self-test: OK ({len(ran)} controls: §10.1's rows from the owner's copy, each bound to the "
750
+ f"render, the copy and the item; release 1's named S8 hashes; group rows per member; F and its hash; the "
751
+ f"stale, the adjudicated and the guarded; §13.4's review time and overturn rate)")
752
+ return 0
753
+
754
+
755
+ if __name__ == "__main__":
756
+ if sys.argv[1:2] == ["--self-test"]:
757
+ sys.exit(self_test())
758
+ sys.exit("usage: stage_approvals.py --self-test")