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,874 @@
1
+ #!/usr/bin/env python3
2
+ """The grammar of the lines the owner writes into a review's decision copy and into a confirmation file (plan WP-20
3
+ K1; design §10.1, §10.3; settled S-11; lead decision E1).
4
+
5
+ A render (`review.ko.v<n>.md`, `confirm.ko.v<n>.md`) is immutable. Beside it the renderer writes a copy (`copy_of`):
6
+ the render's bytes under one header line that names the render and its sha256. The owner edits the copy, and only
7
+ inside its owner blocks. A block opens with `<!-- owner-block review item=<item id> sha=<item sha> -->` (one per
8
+ review row, `review_block`) or `<!-- owner-block confirm set=<set sha> -->` (one per confirmation file,
9
+ `confirm_block`) and closes with `<!-- /owner-block -->`. Every byte outside the blocks, the markers included, must
10
+ equal the render's: an edit there is refused by its line number (EDIT_OUTSIDE_EDITABLE), and the same text inside a
11
+ block's note is accepted. What is editable is decided by position, never by what a line looks like, so a payload
12
+ line that happens to begin with `결정:` is as fixed as any other.
13
+
14
+ Inside a review block each non-blank line is one of
15
+
16
+ 결정: <verb> 승인 | 수정 | 보류 | 기각 | 판정, or empty for undecided; 수정 may name
17
+ S7b's alternative as `수정 대안 <id>`
18
+ 메모: <text> the note; repeatable, joined by newlines
19
+ 판정 <label>: A | B | <value> one disputed judgment: judge A's side, judge B's, or the owner's own value
20
+ keep 해제: <record id> <grounds> releases a keep record the proposal reduces or merges over
21
+
22
+ and inside a confirmation block
23
+
24
+ 확인: 확정 | 반려 confirm the final set or return it, or empty for undecided
25
+ 메모: <text>
26
+
27
+ A line that is none of these, a second `결정:` or `확인:` line, a verb with words after it, a filled `판정` line under
28
+ another verb, a release under anything but 승인: each is refused by its line number, never read as the nearest thing
29
+ it resembles (the LLM/capability rule). The colon may be ASCII or full-width, and an editable line is read after
30
+ Unicode NFC, so an editor's normalization of Hangul does not change what it says.
31
+
32
+ With a `spec` - the current rows, from the stage that renders and parses them - each block is also held to its row:
33
+ an anchor whose sha is no longer the item's makes the item `stale` (DECISION_STALE: decided again in a new review
34
+ version, never applied from this one), and a judgment label or value the row does not carry, an alternative S7b did
35
+ not offer, a keep record the proposal does not override, a disputed row approved without adjudication, and an approval
36
+ over a keep record nobody released are each refused by line.
37
+
38
+ Named owner_lines rather than the plan's `decisions.py`: the lexicon's concept slug `decision` homes this repo's own
39
+ decision record under `decisions/` (`gates/check-lexicon.py` judges every path that carries it).
40
+
41
+ owner_lines.py --self-test
42
+ """
43
+ import hashlib
44
+ import pathlib
45
+ import re
46
+ import sys
47
+ import unicodedata
48
+
49
+ if __package__ in (None, ""): # run as a script: put session-distill/ on the import path
50
+ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
51
+ from runlib.records import Refused # noqa: E402
52
+
53
+ # §10.1's sentence, copied once and held to VERBS by the self-test, so neither changes alone.
54
+ DESIGN_10_1 = ("Per row the owner writes `결정:` followed by one of `승인`, `수정`, `보류`, `기각`, `판정`, with a "
55
+ "note.")
56
+ VERBS = {"승인": "approve", "수정": "revise", "보류": "defer", "기각": "reject", "판정": "adjudicate"}
57
+ CONFIRM_VERBS = {"확정": "confirm", "반려": "return"} # lead decision E1: one 확인 line per confirmation file
58
+ ALTERNATIVE_WORD = "대안"
59
+ JUDGES = ("A", "B")
60
+ FIELDS = {"review": ("item", "sha"), "confirm": ("set",)}
61
+ # What approving does in release 1, in the owner's words (D-20261113-f22b7d and its dated record): S11 edits files
62
+ # and nothing else, and the commit and the install are the owner's. S9's review page and S10b's confirmation page both say this sentence.
63
+ # Codex WP-20 r2 F4, F5: an approval is provisional until the final set is confirmed (S10b) and applied (S11); a
64
+ # `none` on a candidate with no ledger entry is kept in the run's close record alone (F-40); commands are shown only
65
+ # when the application changed files (`stage_apply` names none otherwise).
66
+ APPROVAL_EFFECT = ("승인은 아직 적용이 아닙니다. 승인한 항목으로 만든 최종 집합을 확정(S10b)하고 적용(S11)하면, 파일을 바꾸는 "
67
+ "제안만 선언된 체크아웃의 파일을 바꿉니다. `none`(바꾸지 않음)과 대장에만 남는 처리(keep·incubate·"
68
+ "drop)는 파일을 바꾸지 않고, 대장에 항목이 없는 새 후보의 `none`은 대장에 줄을 만들지 않고 이번 "
69
+ "실행의 마무리 기록(close.json)에만 남습니다. 커밋과 설치는 소유자가 직접 합니다 — 적용으로 파일이 "
70
+ "바뀌면 실행할 명령을 그대로 보여 드립니다.")
71
+ CONFIRM_EFFECT = ("확정하면 S11이 이 집합에서 파일을 바꾸는 항목(F)만 선언된 체크아웃에 적용합니다. `none`(바꾸지 않음)과 "
72
+ "대장에만 남는 처리(keep·incubate·drop)는 파일을 바꾸지 않습니다. 커밋과 설치는 소유자가 직접 합니다 — "
73
+ "적용으로 파일이 바뀌면 실행할 명령을 그대로 보여 드립니다.")
74
+ # The same two sentences for release 1, which changes no library file (D-20261116-7853bc): S7 and S7b refuse a change,
75
+ # S10b refuses to confirm one and S11 writes none, so nothing the owner approves or confirms changes a library file.
76
+ # The pages choose by `placement.release_scope()`; the sentences above are the design's, read under the scope `all`.
77
+ RELEASE_1_APPROVAL_EFFECT = ("승인은 아직 적용이 아닙니다. 승인한 항목으로 만든 최종 집합을 확정(S10b)하면 S12가 결정을 "
78
+ "대장(결정 기록 파일)에 남깁니다. 이번 릴리스는 라이브러리 파일을 바꾸지 않으므로, 어떤 "
79
+ "승인도 체크아웃의 라이브러리 파일을 바꾸지 않습니다. 대장에 항목이 없는 새 후보의 `none`은 "
80
+ "대장에 줄을 만들지 않고 이번 실행의 마무리 기록(close.json)에만 남습니다.")
81
+ RELEASE_1_CONFIRM_EFFECT = ("확정하면 S12가 이 집합의 결정을 대장(결정 기록 파일)에 남깁니다. 이번 릴리스는 라이브러리 "
82
+ "파일을 바꾸지 않으므로 S11은 체크아웃의 라이브러리 파일을 하나도 바꾸지 않습니다. 대장의 "
83
+ "변경을 커밋하는 일은 소유자가 직접 합니다.")
84
+ CLOSE = "<!-- /owner-block -->"
85
+ _VALUE = r"[^\s=<>]+"
86
+ OPEN = re.compile(rf"^<!-- owner-block (review|confirm)((?: [a-z]+={_VALUE})+) -->$")
87
+ LOOKS_LIKE_MARKER = re.compile(r"^\s*<!--\s*/?\s*owner-(?:block|copy)\b")
88
+ HEADER = re.compile(r"^<!-- owner-copy of=(\S+) sha256=([0-9a-f]{64}) -->$")
89
+ TOKEN = re.compile(rf"^{_VALUE}$")
90
+ _LABEL = r"[0-9A-Za-z_.\-]+"
91
+ LABEL = re.compile(rf"^{_LABEL}$")
92
+ _COLON = "[::]"
93
+ DECISION_LINE = re.compile(rf"^결정\s*{_COLON}(.*)$")
94
+ NOTE_LINE = re.compile(rf"^메모\s*{_COLON}(.*)$")
95
+ JUDGMENT_LINE = re.compile(rf"^판정\s+({_LABEL})\s*{_COLON}(.*)$")
96
+ KEEP_LINE = re.compile(rf"^(?i:keep)\s*해제\s*{_COLON}(.*)$")
97
+ CONFIRM_LINE = re.compile(rf"^확인\s*{_COLON}(.*)$")
98
+ GROUNDS_LEAD = "—–-:: " # a dash or colon the owner may put between a record id and its grounds
99
+
100
+
101
+ def owner_shaped(line):
102
+ """Whether `line` reads, as the parser reads an editable line (NFC, stripped), as an owner line or a block marker.
103
+ The parser reads by position, so such a line outside a block decides nothing; a renderer uses this to keep text it
104
+ did not write from standing where the owner would read a decision (`stage_render.page_problems`)."""
105
+ text = unicodedata.normalize("NFC", str(line)).strip()
106
+ return bool(LOOKS_LIKE_MARKER.match(text) or any(p.match(text) for p in (DECISION_LINE, NOTE_LINE, JUDGMENT_LINE,
107
+ KEEP_LINE, CONFIRM_LINE)))
108
+
109
+
110
+ def sha256_text(text):
111
+ return hashlib.sha256(text.encode("utf-8")).hexdigest()
112
+
113
+
114
+ def _token(name, value):
115
+ if not isinstance(value, str) or not TOKEN.match(value):
116
+ raise Refused(f"BLOCK_ARGUMENT_INVALID {name}: {value!r} is not one token without whitespace, '=', '<' or '>'")
117
+ return value
118
+
119
+
120
+ def _shown(word):
121
+ return repr(word[:24])
122
+
123
+
124
+ def review_block(item_id, item_sha, labels=()):
125
+ """One review row's owner block as a render writes it: its markers, an empty `결정:` and `메모:`, and one empty
126
+ `판정 <label>:` per disputed judgment the row carries, in the order given."""
127
+ labels = list(labels)
128
+ for label in labels:
129
+ if not isinstance(label, str) or not LABEL.match(label):
130
+ raise Refused(f"BLOCK_ARGUMENT_INVALID label: {label!r} is not letters, digits, '_', '.' or '-'")
131
+ if len(set(labels)) != len(labels):
132
+ raise Refused(f"BLOCK_ARGUMENT_INVALID labels: {labels} repeat a label")
133
+ return [f"<!-- owner-block review item={_token('item', item_id)} sha={_token('sha', item_sha)} -->",
134
+ "결정:", "메모:", *[f"판정 {label}:" for label in labels], CLOSE]
135
+
136
+
137
+ def confirm_block(set_sha):
138
+ """A confirmation file's one owner block as a render writes it."""
139
+ return [f"<!-- owner-block confirm set={_token('set', set_sha)} -->", "확인:", "메모:", CLOSE]
140
+
141
+
142
+ def segments(lines, first=1):
143
+ """`(fixed, blocks, problems)` over a text's lines numbered from `first`: `fixed` holds `(line, text)` of every line
144
+ outside a block and of every marker; `blocks` each block's `{kind, fields, line, lines}`; `problems` the breaks of
145
+ the block structure, by line."""
146
+ fixed, blocks, problems, held = [], [], [], None
147
+ for n, text in enumerate(lines, first):
148
+ opened = OPEN.match(text)
149
+ if held is None:
150
+ fixed.append((n, text))
151
+ if opened:
152
+ pairs = opened.group(2).split()
153
+ fields = dict(pair.split("=", 1) for pair in pairs)
154
+ held = {"kind": opened.group(1), "fields": fields, "line": n, "lines": []}
155
+ if sorted(fields) != sorted(FIELDS[held["kind"]]) or len(pairs) != len(fields):
156
+ problems.append(f"BLOCK_MALFORMED line {n}: a {held['kind']} block names {sorted(fields)}, not "
157
+ f"{list(FIELDS[held['kind']])}")
158
+ elif text == CLOSE:
159
+ problems.append(f"BLOCK_UNOPENED line {n}: a block end with no block open")
160
+ elif LOOKS_LIKE_MARKER.match(text):
161
+ problems.append(f"BLOCK_MALFORMED line {n}: shaped like an owner-block marker but not one as the "
162
+ "render writes it")
163
+ elif text == CLOSE:
164
+ fixed.append((n, text))
165
+ blocks.append(held)
166
+ held = None
167
+ elif opened or LOOKS_LIKE_MARKER.match(text):
168
+ fixed.append((n, text))
169
+ problems.append(f"BLOCK_NESTED line {n}: a block marker inside the block opened at line {held['line']}")
170
+ else:
171
+ held["lines"].append((n, text))
172
+ if held is not None:
173
+ problems.append(f"BLOCK_UNTERMINATED line {held['line']}: the block opened here has no end marker")
174
+ return fixed, blocks, problems
175
+
176
+
177
+ def render_problems(text):
178
+ """What makes `text` no render a copy can be made of, by name: bytes other than LF-terminated UTF-8, a copy's
179
+ header, a broken block structure, review and confirmation blocks in one file, an item with two blocks, a second
180
+ confirmation block, and a block other than `review_block` or `confirm_block` writes."""
181
+ if not isinstance(text, str):
182
+ return [f"RENDER_NOT_TEXT: a render is text, not {type(text).__name__}"]
183
+ problems = []
184
+ if text.startswith("") or "\r" in text:
185
+ problems.append("RENDER_BYTES_INVALID: a render is LF-terminated UTF-8 with no byte-order mark and no carriage "
186
+ "return")
187
+ if text.split("\n", 1)[0].startswith("<!-- owner-copy"):
188
+ problems.append("RENDER_IS_COPY line 1: the text carries a copy's header, so it is a copy, not a render")
189
+ _fixed, blocks, found = segments(text.split("\n"))
190
+ problems += found
191
+ if len({b["kind"] for b in blocks}) > 1:
192
+ problems.append("FILE_KINDS_MIXED: a render holds review blocks or one confirmation block, never both")
193
+ seen = {}
194
+ for b in blocks:
195
+ if b["kind"] == "review" and "item" in b["fields"]:
196
+ item = b["fields"]["item"]
197
+ if item in seen:
198
+ problems.append(f"ITEM_TWICE line {b['line']}: item {item} has its block at line {seen[item]} already")
199
+ seen.setdefault(item, b["line"])
200
+ interior = [t for _n, t in b["lines"]]
201
+ labels = [m.group(1) for m in (JUDGMENT_LINE.match(t) for t in interior[2:]) if m]
202
+ want = (["결정:", "메모:", *[f"판정 {label}:" for label in labels]] if b["kind"] == "review"
203
+ else ["확인:", "메모:"])
204
+ if interior != want or len(set(labels)) != len(labels):
205
+ problems.append(f"RENDER_BLOCK_INVALID line {b['line']}: the block is not as "
206
+ f"{'review_block' if b['kind'] == 'review' else 'confirm_block'} writes it (empty lines only)")
207
+ confirms = [b for b in blocks if b["kind"] == "confirm"]
208
+ if len(confirms) > 1:
209
+ problems.append(f"CONFIRM_BLOCK_TWICE line {confirms[1]['line']}: a confirmation file has one block")
210
+ return problems
211
+
212
+
213
+ def copy_of(render_text, render_name):
214
+ """The owner's copy of a render: one header line naming `render_name` and the render's sha256, then the render's
215
+ bytes unchanged. A render with any `render_problems` is refused."""
216
+ found = render_problems(render_text)
217
+ if found:
218
+ raise Refused("RENDER_INVALID " + "\n".join(found))
219
+ return f"<!-- owner-copy of={_token('render name', render_name)} sha256={sha256_text(render_text)} -->\n" + render_text
220
+
221
+
222
+ def first_difference(render_fixed, copy_fixed):
223
+ """The first fixed line where the copy departs from the render, by the copy's line number, or None."""
224
+ for (rn, rt), (cn, ct) in zip(render_fixed, copy_fixed):
225
+ if rt == ct:
226
+ continue
227
+ if unicodedata.normalize("NFC", rt) == unicodedata.normalize("NFC", ct):
228
+ return (f"NORMALIZATION_CHANGED line {cn}: the line's Hangul is in another Unicode normalization than the "
229
+ f"render's line {rn}; save the copy without re-normalizing it")
230
+ how = "only its trailing whitespace" if rt.rstrip() == ct.rstrip() else "its text"
231
+ return (f"EDIT_OUTSIDE_EDITABLE line {cn}: {how} differs from the render's line {rn}, and only lines inside "
232
+ "an owner block may change")
233
+ if len(copy_fixed) > len(render_fixed):
234
+ return (f"EDIT_OUTSIDE_EDITABLE line {copy_fixed[len(render_fixed)][0]}: a line the render does not have, "
235
+ "outside every owner block")
236
+ if len(copy_fixed) < len(render_fixed):
237
+ rn, rt = render_fixed[len(copy_fixed)]
238
+ last = copy_fixed[-1][0] if copy_fixed else 1
239
+ if rt == "" and len(render_fixed) == len(copy_fixed) + 1:
240
+ return f"EDIT_OUTSIDE_EDITABLE line {last}: the copy lacks the render's final newline"
241
+ return f"EDIT_OUTSIDE_EDITABLE line {last + 1}: the copy ends where the render's line {rn} continues"
242
+ return None
243
+
244
+
245
+ def _said(verb):
246
+ return f"says {verb}" if verb else "is empty"
247
+
248
+
249
+ def review_rules(held, problems):
250
+ """The rules a review block's lines obey among themselves, whatever the row."""
251
+ verb, at = held["verb"], held["decision_line"]
252
+ filled = [j for j in held["judgments"] if j["choice"] is not None]
253
+ if verb != "판정" and filled:
254
+ problems.append(f"ADJUDICATION_WITHOUT_VERB line {filled[0]['line']}: a 판정 value is filled and the 결정 line "
255
+ f"{_said(verb)}; write 결정: 판정, or empty the value")
256
+ if verb == "판정":
257
+ if not held["judgments"]:
258
+ problems.append(f"ADJUDICATION_INCOMPLETE line {at}: 결정: 판정 resolves no 판정 line")
259
+ for j in held["judgments"]:
260
+ if j["choice"] is None:
261
+ problems.append(f"ADJUDICATION_INCOMPLETE line {j['line']}: 판정 {j['label']} has no value (A, B or "
262
+ "the owner's own)")
263
+ if not held["note"]:
264
+ problems.append(f"NOTE_REQUIRED line {at}: 판정 records its rationale in a 메모 line")
265
+ if verb == "수정" and held["alternative"] is None and not held["note"]:
266
+ problems.append(f"NOTE_REQUIRED line {at}: 수정 returns the item to S7 with a 메모 line, or names S7b's "
267
+ f"alternative as 수정 {ALTERNATIVE_WORD} <id>")
268
+ if verb != "승인":
269
+ for k in held["keep_releases"]:
270
+ problems.append(f"KEEP_RELEASE_UNUSED line {k['line']}: keep 해제 releases a keep record for an approval, "
271
+ f"and the 결정 line {_said(verb)}")
272
+
273
+
274
+ def read_review(block, problems):
275
+ """One review block's lines, read: `{item_id, item_sha, line, state, decision, verb, alternative, note, judgments,
276
+ keep_releases, decision_line}`; every line it refuses goes to `problems` by its number."""
277
+ held = {"item_id": block["fields"].get("item"), "item_sha": block["fields"].get("sha"), "line": block["line"],
278
+ "state": "undecided", "decision": None, "verb": None, "alternative": None, "note": "",
279
+ "judgments": [], "keep_releases": [], "decision_line": None}
280
+ notes = []
281
+ for n, raw in block["lines"]:
282
+ text = unicodedata.normalize("NFC", raw).strip()
283
+ if not text:
284
+ continue
285
+ hit = DECISION_LINE.match(text)
286
+ if hit:
287
+ if held["decision_line"] is not None:
288
+ problems.append(f"DECISION_TWICE line {n}: the block has its 결정 line at line {held['decision_line']}")
289
+ continue
290
+ held["decision_line"] = n
291
+ words = hit.group(1).split()
292
+ if not words:
293
+ continue
294
+ verb, rest = words[0], words[1:]
295
+ if verb not in VERBS:
296
+ problems.append(f"DECISION_VERB_UNKNOWN line {n}: {_shown(verb)} is not one of {', '.join(VERBS)}")
297
+ continue
298
+ if verb == "수정" and rest[:1] == [ALTERNATIVE_WORD]:
299
+ if len(rest) != 2:
300
+ problems.append(f"DECISION_ARGUMENT_INVALID line {n}: 수정 {ALTERNATIVE_WORD} takes one "
301
+ "alternative id and nothing after it")
302
+ continue
303
+ held["alternative"] = rest[1]
304
+ elif rest:
305
+ problems.append(f"DECISION_ARGUMENT_INVALID line {n}: {verb} takes no words after it"
306
+ + (f" but {ALTERNATIVE_WORD} <id>" if verb == "수정" else ""))
307
+ continue
308
+ held.update(verb=verb, decision=VERBS[verb], state="decided")
309
+ continue
310
+ hit = NOTE_LINE.match(text)
311
+ if hit:
312
+ notes.append(hit.group(1).strip())
313
+ continue
314
+ hit = JUDGMENT_LINE.match(text)
315
+ if hit:
316
+ label, value = hit.group(1), hit.group(2).strip()
317
+ earlier = next((j for j in held["judgments"] if j["label"] == label), None)
318
+ if earlier is not None:
319
+ problems.append(f"JUDGMENT_TWICE line {n}: 판정 {label} is at line {earlier['line']} already")
320
+ continue
321
+ choice = None if not value else value if value in JUDGES else "own"
322
+ held["judgments"].append({"label": label, "choice": choice, "value": value if choice == "own" else None,
323
+ "line": n})
324
+ continue
325
+ hit = KEEP_LINE.match(text)
326
+ if hit:
327
+ words = hit.group(1).strip().split(None, 1)
328
+ if not words:
329
+ continue
330
+ record = words[0]
331
+ grounds = words[1].lstrip(GROUNDS_LEAD).strip() if len(words) > 1 else ""
332
+ earlier = next((k for k in held["keep_releases"] if k["record_id"] == record), None)
333
+ if earlier is not None:
334
+ problems.append(f"KEEP_RELEASE_TWICE line {n}: keep 해제 {record} is at line {earlier['line']} already")
335
+ continue
336
+ if not grounds:
337
+ problems.append(f"KEEP_RELEASE_GROUNDLESS line {n}: keep 해제 {record} needs its grounds after the "
338
+ "record id")
339
+ continue
340
+ held["keep_releases"].append({"record_id": record, "grounds": grounds, "line": n})
341
+ continue
342
+ if CONFIRM_LINE.match(text):
343
+ problems.append(f"LINE_NOT_EDITABLE line {n}: a 확인 line belongs to a confirmation file, not a review row")
344
+ continue
345
+ problems.append(f"LINE_NOT_EDITABLE line {n}: inside a review block a line is 결정, 메모, 판정 <label> or "
346
+ "keep 해제; write a note as a 메모: line")
347
+ held["note"] = "\n".join(x for x in notes if x)
348
+ review_rules(held, problems)
349
+ return held
350
+
351
+
352
+ def read_confirm(block, problems, confirm_set=None):
353
+ """A confirmation block's lines, read: `{set_sha, line, state, decision, verb, note, confirm_line}`. With
354
+ `confirm_set`, a block confirming another set is `stale` (CONFIRM_STALE)."""
355
+ held = {"set_sha": block["fields"].get("set"), "line": block["line"], "state": "undecided", "decision": None,
356
+ "verb": None, "note": "", "confirm_line": None}
357
+ notes = []
358
+ for n, raw in block["lines"]:
359
+ text = unicodedata.normalize("NFC", raw).strip()
360
+ if not text:
361
+ continue
362
+ hit = CONFIRM_LINE.match(text)
363
+ if hit:
364
+ if held["confirm_line"] is not None:
365
+ problems.append(f"CONFIRM_TWICE line {n}: the block has its 확인 line at line {held['confirm_line']}")
366
+ continue
367
+ held["confirm_line"] = n
368
+ words = hit.group(1).split()
369
+ if not words:
370
+ continue
371
+ if len(words) != 1 or words[0] not in CONFIRM_VERBS:
372
+ problems.append(f"CONFIRM_VERB_UNKNOWN line {n}: 확인 takes one of {', '.join(CONFIRM_VERBS)} and "
373
+ "nothing after it")
374
+ continue
375
+ held.update(verb=words[0], decision=CONFIRM_VERBS[words[0]], state="decided")
376
+ continue
377
+ hit = NOTE_LINE.match(text)
378
+ if hit:
379
+ notes.append(hit.group(1).strip())
380
+ continue
381
+ problems.append(f"LINE_NOT_EDITABLE line {n}: inside a confirmation block a line is 확인 or 메모")
382
+ held["note"] = "\n".join(x for x in notes if x)
383
+ if held["verb"] == "반려" and not held["note"]:
384
+ problems.append(f"NOTE_REQUIRED line {held['confirm_line']}: 반려 says why in a 메모 line")
385
+ if confirm_set is not None and held["set_sha"] != confirm_set:
386
+ held["state"] = "stale"
387
+ held["code"] = (f"CONFIRM_STALE line {held['line']}: the block confirms set {held['set_sha'][:12]}, and the "
388
+ f"final set is {confirm_set[:12]} now; it is confirmed again in a new confirmation file")
389
+ return held
390
+
391
+
392
+ def spec_problems(spec):
393
+ """What makes `spec` no set of current rows: it is the calling stage's, so a bad one is refused, not reported."""
394
+ if not isinstance(spec, dict):
395
+ return [f"SPEC_INVALID: the rows are a mapping of item id to row, not {type(spec).__name__}"]
396
+ out = []
397
+ for ident, row in spec.items():
398
+ if not (isinstance(row, dict) and isinstance(row.get("item_sha"), str)
399
+ and isinstance(row.get("judgments", {}), dict)
400
+ and all(isinstance(v, list) for v in row.get("judgments", {}).values())
401
+ and isinstance(row.get("alternatives", []), list) and isinstance(row.get("guarded_keeps", []), list)):
402
+ out.append(f"SPEC_INVALID {ident}: a row is {{item_sha, judgments: {{label: [values]}}, alternatives, "
403
+ "guarded_keeps}")
404
+ return out
405
+
406
+
407
+ def hold_to_spec(items, spec, problems):
408
+ """Each read review block held to its current row. A changed row makes its item `stale` with DECISION_STALE and
409
+ nothing else is judged of it, since its lines answered the row as it was rendered."""
410
+ for item in items:
411
+ row = spec.get(item["item_id"])
412
+ if row is None:
413
+ problems.append(f"ITEM_UNKNOWN line {item['line']}: item {item['item_id']} is not among the current rows")
414
+ continue
415
+ if item["item_sha"] != row["item_sha"]:
416
+ item["state"] = "stale"
417
+ item["code"] = (f"DECISION_STALE line {item['line']}: item {item['item_id']} changed after this render "
418
+ f"({item['item_sha'][:12]} rendered, {row['item_sha'][:12]} now); it is decided again in "
419
+ "a new review version and never applied from this one")
420
+ continue
421
+ labels = row.get("judgments") or {}
422
+ verb, at = item["verb"], item["decision_line"]
423
+ for j in item["judgments"]:
424
+ if j["label"] not in labels:
425
+ problems.append(f"JUDGMENT_UNKNOWN line {j['line']}: the row has no disputed judgment {j['label']}")
426
+ elif j["choice"] == "own" and j["value"] not in labels[j["label"]]:
427
+ problems.append(f"JUDGMENT_VALUE_INVALID line {j['line']}: 판정 {j['label']} takes A, B or one of "
428
+ f"{', '.join(labels[j['label']])}")
429
+ if verb == "판정":
430
+ if not labels:
431
+ problems.append(f"DECISION_NOT_ALLOWED line {at}: the row has no disputed judgment to 판정")
432
+ for label in sorted(set(labels) - {j["label"] for j in item["judgments"]}):
433
+ problems.append(f"ADJUDICATION_INCOMPLETE line {at}: disputed judgment {label} has no 판정 line")
434
+ if verb == "승인" and labels:
435
+ problems.append(f"DISPUTE_UNRESOLVED line {at}: the row is disputed; 판정 each disputed judgment, or "
436
+ "보류 or 기각 it")
437
+ if item["alternative"] is not None and item["alternative"] not in (row.get("alternatives") or []):
438
+ problems.append(f"ALTERNATIVE_UNKNOWN line {at}: S7b offered no alternative {_shown(item['alternative'])}")
439
+ guarded = row.get("guarded_keeps") or []
440
+ for k in item["keep_releases"]:
441
+ if k["record_id"] not in guarded:
442
+ problems.append(f"KEEP_UNKNOWN line {k['line']}: the proposal overrides no keep record "
443
+ f"{_shown(k['record_id'])}")
444
+ if verb == "승인":
445
+ released = {k["record_id"] for k in item["keep_releases"]}
446
+ for record in guarded:
447
+ if record not in released:
448
+ problems.append(f"KEEP_GUARDED line {at}: the proposal reduces or merges over keep record {record}, "
449
+ f"and approving it needs `keep 해제: {record} <grounds>`")
450
+ listed = {i["item_id"] for i in items}
451
+ for ident in sorted(set(spec) - listed):
452
+ problems.append(f"ITEM_NOT_RENDERED {ident}: a current row with no block in this render")
453
+
454
+
455
+ def parse(render_text, copy_text, spec=None, render_name=None, confirm_set=None):
456
+ """`(result, problems)` of the owner's copy of a render. `result` is None when the copy is not the render with only
457
+ its blocks edited (the header, the bytes, the fixed lines); else `{render, render_sha256, items, confirm}`, the
458
+ items in the render's order. `problems` empty means every line was read; any problem refuses the file."""
459
+ found = render_problems(render_text)
460
+ if found:
461
+ return None, [f"RENDER_INVALID {p}" for p in found]
462
+ if not isinstance(copy_text, str):
463
+ return None, [f"COPY_NOT_TEXT: a copy is text, not {type(copy_text).__name__}"]
464
+ if spec is not None and spec_problems(spec):
465
+ raise Refused("\n".join(spec_problems(spec)))
466
+ if copy_text.startswith(""):
467
+ return None, ["ENCODING_CHANGED line 1: the copy starts with a byte-order mark the render does not have; save "
468
+ "it as UTF-8 without one"]
469
+ lines = copy_text.split("\n")
470
+ for n, text in enumerate(lines, 1):
471
+ if text.endswith("\r"):
472
+ return None, [f"LINE_ENDINGS_CHANGED line {n}: the copy's lines end in CRLF where the render's end in LF; "
473
+ "save it with LF line endings"]
474
+ head = HEADER.match(lines[0])
475
+ if not head:
476
+ return None, ["COPY_HEADER_MISSING line 1: the first line is not the header naming the render this copies"]
477
+ sha = sha256_text(render_text)
478
+ if head.group(2) != sha or (render_name is not None and head.group(1) != render_name):
479
+ return None, [f"COPY_UNBOUND line 1: the copy names {head.group(1)} at {head.group(2)[:12]}, not "
480
+ f"{render_name or 'this render'} at {sha[:12]}"]
481
+ render_fixed, _blocks, _found = segments(render_text.split("\n"))
482
+ copy_fixed, blocks, found = segments(lines[1:], first=2)
483
+ if found:
484
+ return None, found
485
+ differs = first_difference(render_fixed, copy_fixed)
486
+ if differs:
487
+ return None, [differs]
488
+ problems = []
489
+ result = {"render": head.group(1), "render_sha256": sha, "items": [], "confirm": None}
490
+ for block in blocks:
491
+ if block["kind"] == "review":
492
+ result["items"].append(read_review(block, problems))
493
+ else:
494
+ result["confirm"] = read_confirm(block, problems, confirm_set)
495
+ if spec is not None:
496
+ hold_to_spec(result["items"], spec, problems)
497
+ return result, problems
498
+
499
+
500
+ def require(render_text, copy_text, **kwargs):
501
+ """`parse`'s result, or Refused naming every problem, the first line first."""
502
+ result, problems = parse(render_text, copy_text, **kwargs)
503
+ if problems:
504
+ raise Refused("\n".join(problems))
505
+ return result
506
+
507
+
508
+ def self_test():
509
+ """Positive controls first; then each verb and line kind read; then one planted violation per rule, each named by
510
+ its code and, where the rule is a line's, by the exact line. Every control builds its own copy from the fixture."""
511
+ failures, ran, reporting = [], [], []
512
+
513
+ def record(name):
514
+ if reporting:
515
+ raise RuntimeError(f"CONTROL_AFTER_SUMMARY {name}")
516
+ ran.append(name)
517
+
518
+ def control(name, got, want):
519
+ record(name)
520
+ if not isinstance(got, str):
521
+ raise TypeError(f"CONTROL_GOT_NOT_STR {name}: {type(got).__name__}")
522
+ if want not in got:
523
+ failures.append((name, f"expected {want!r} in {got[:400]!r}"))
524
+
525
+ def equal(name, got, want):
526
+ record(name)
527
+ if got != want:
528
+ failures.append((name, f"expected {want!r}, got {got!r}"))
529
+
530
+ def clean(name, problems):
531
+ record(name)
532
+ if not isinstance(problems, list):
533
+ raise TypeError(f"CLEAN_PROBLEMS_NOT_LIST {name}: {type(problems).__name__}")
534
+ if problems:
535
+ failures.append((name, f"expected nothing, got {problems}"))
536
+
537
+ def refusal(call):
538
+ try:
539
+ call()
540
+ except Refused as exc:
541
+ return str(exc)
542
+ return ""
543
+
544
+ name = "review.ko.v1.md"
545
+ head = ["# 검토 v1 (fixture)", "", "이 파일은 고정 자료입니다.", ""]
546
+ rows = [("k-aaa", "s1", [], ["## 1. k-aaa", "무엇이 있었나: 브랜치를 묻지 않고 지웠다.", "제안: 지우기 전에 묻는다.",
547
+ "결정: 이 줄은 인용이고 블록 밖에 있다."]),
548
+ ("k-bbb", "s2", ["1", "2"], ["## 2. k-bbb (판정 필요)", "판정 1 - bounded: A 충족, B 미충족",
549
+ "판정 2 - recognizable: A 미충족, B 충족"]),
550
+ ("k-ccc", "s3", [], ["## 3. k-ccc", "제안: keep 기록 R-1을 줄인다."])]
551
+
552
+ def render_of(held_rows):
553
+ lines = list(head)
554
+ for item, sha, labels, text in held_rows:
555
+ lines += text + review_block(item, sha, labels) + [""]
556
+ return "\n".join(lines) + "\n"
557
+
558
+ render = render_of(rows)
559
+ blank = copy_of(render, name)
560
+
561
+ def spec_of(**over):
562
+ held = {"k-aaa": {"item_sha": "s1", "judgments": {}, "alternatives": ["alt-1"], "guarded_keeps": []},
563
+ "k-bbb": {"item_sha": "s2", "judgments": {"1": ["met", "unmet"], "2": ["met", "unmet"]},
564
+ "alternatives": [], "guarded_keeps": []},
565
+ "k-ccc": {"item_sha": "s3", "judgments": {}, "alternatives": [], "guarded_keeps": ["R-1"]}}
566
+ for ident, row in over.items():
567
+ if row is None:
568
+ held.pop(ident)
569
+ else:
570
+ held[ident] = {**held.get(ident, {"judgments": {}, "alternatives": [], "guarded_keeps": []}), **row}
571
+ return held
572
+
573
+ def fill(item, *lines_, base=None):
574
+ text = (base or blank).split("\n")
575
+ start = next(i for i, t in enumerate(text) if t.startswith(f"<!-- owner-block review item={item} "))
576
+ end = next(i for i in range(start + 1, len(text)) if text[i] == CLOSE)
577
+ return "\n".join(text[:start + 1] + list(lines_) + text[end:])
578
+
579
+ def run(copy, spec="default", **kwargs):
580
+ return parse(render, copy, spec=spec_of() if spec == "default" else spec, render_name=name, **kwargs)
581
+
582
+ def said(copy, spec="default", **kwargs):
583
+ return "\n".join(run(copy, spec, **kwargs)[1]) or "(none)"
584
+
585
+ def item_of(copy, ident, spec="default"):
586
+ result, problems = run(copy, spec)
587
+ if result is None:
588
+ return {"problems": problems}
589
+ return next((i for i in result["items"] if i["item_id"] == ident), {"absent": ident})
590
+
591
+ def number(copy, text):
592
+ return copy.split("\n").index(text) + 1
593
+
594
+ # ---- positive controls ---------------------------------------------------------------------------------------
595
+ clean("the fixture render is a render", render_problems(render))
596
+ clean("the unedited copy parses with nothing refused", run(blank)[1])
597
+ result, _p = run(blank)
598
+ equal("the unedited copy holds the render's three rows, in its order (the controls below judge real blocks)",
599
+ [i["item_id"] for i in (result or {"items": []})["items"]], ["k-aaa", "k-bbb", "k-ccc"])
600
+ equal("and every row of an unedited copy is undecided, with no decision",
601
+ [(i["state"], i["decision"]) for i in (result or {"items": []})["items"]], [("undecided", None)] * 3)
602
+ control("the copy's first line names the render and its sha256", blank.split("\n", 1)[0],
603
+ f"of={name} sha256={sha256_text(render)}")
604
+ equal("and every other byte of the copy is the render's", blank.split("\n", 1)[1], render)
605
+ equal("§10.1's five verbs are VERBS, in the design's order",
606
+ re.findall(r"`([^`]+)`", DESIGN_10_1)[1:], list(VERBS))
607
+
608
+ # ---- each verb and line kind ---------------------------------------------------------------------------------
609
+ got = item_of(fill("k-aaa", "결정: 승인", "메모:"), "k-aaa")
610
+ equal("결정: 승인 is an approval", (got.get("state"), got.get("decision"), got.get("verb")),
611
+ ("decided", "approve", "승인"))
612
+ got = item_of(fill("k-aaa", "결정: 수정", "메모: 묻는 대상을 원격 브랜치로 좁힌다."), "k-aaa")
613
+ equal("결정: 수정 with a note returns the note", (got.get("decision"), got.get("note"), got.get("alternative")),
614
+ ("revise", "묻는 대상을 원격 브랜치로 좁힌다.", None))
615
+ got = item_of(fill("k-aaa", "결정: 수정 대안 alt-1", "메모:"), "k-aaa")
616
+ equal("결정: 수정 대안 <id> adopts S7b's alternative and needs no note", (got.get("decision"), got.get("alternative")),
617
+ ("revise", "alt-1"))
618
+ got = item_of(fill("k-aaa", "결정: 보류", "메모:"), "k-aaa")
619
+ equal("결정: 보류 defers", got.get("decision"), "defer")
620
+ got = item_of(fill("k-aaa", "결정: 기각", "메모:"), "k-aaa")
621
+ equal("결정: 기각 rejects", got.get("decision"), "reject")
622
+ got = item_of(fill("k-bbb", "결정: 판정", "메모: 상황이 미리 알아볼 수 있다.", "판정 1: A", "판정 2: unmet"), "k-bbb")
623
+ equal("결정: 판정 reads each judgment: judge A's side, and the owner's own value",
624
+ (got.get("decision"), [(j["label"], j["choice"], j["value"]) for j in got.get("judgments", [])]),
625
+ ("adjudicate", [("1", "A", None), ("2", "own", "unmet")]))
626
+ got = item_of(fill("k-bbb", "결정: 판정", "메모: 근거", "판정 1: B", "판정 2: B"), "k-bbb")
627
+ equal("and judge B's side", [j["choice"] for j in got.get("judgments", [])], ["B", "B"])
628
+ got = item_of(fill("k-ccc", "결정: 승인", "메모:", "keep 해제: R-1 — 사용자가 직접 줄이기로 했다."), "k-ccc")
629
+ equal("keep 해제: <record> <grounds> releases the record with its grounds, the dash dropped",
630
+ (got.get("decision"), [(k["record_id"], k["grounds"]) for k in got.get("keep_releases", [])]),
631
+ ("approve", [("R-1", "사용자가 직접 줄이기로 했다.")]))
632
+ copy = fill("k-ccc", "결정: 승인", "메모:", "keep 해제: R-1 근거")
633
+ equal("and the release's line is the copy's own line number",
634
+ [k.get("line") for k in item_of(copy, "k-ccc").get("keep_releases") or []], [number(copy, "keep 해제: R-1 근거")])
635
+ got = item_of(fill("k-aaa", "결정: 승인"), "k-aaa")
636
+ equal("a full-width colon reads as the colon", got.get("decision"), "approve")
637
+ got = item_of(fill("k-aaa", unicodedata.normalize("NFD", "결정: 승인")), "k-aaa")
638
+ equal("a decision line in NFD Hangul reads as its NFC", got.get("decision"), "approve")
639
+ got = item_of(fill("k-aaa", " 결정: 승인 ", "", " 메모: 하나", "메모: 둘"), "k-aaa")
640
+ equal("indentation, blank lines and repeated notes inside a block: the notes joined in order",
641
+ (got.get("decision"), got.get("note")), ("approve", "하나\n둘"))
642
+ got = item_of(fill("k-aaa"), "k-aaa")
643
+ equal("a block emptied of every line is undecided, not refused", (got.get("state"), got.get("problems")),
644
+ ("undecided", None))
645
+ clean("and nothing is refused of it", run(fill("k-aaa"))[1])
646
+
647
+ # ---- edits outside the editable parts ------------------------------------------------------------------------
648
+ copy = blank.replace("제안: 지우기 전에 묻는다.", "제안: 지우기 전에 꼭 묻는다.")
649
+ control("a changed payload word is refused by its line number", said(copy),
650
+ f"EDIT_OUTSIDE_EDITABLE line {number(copy, '제안: 지우기 전에 꼭 묻는다.')}: its text differs")
651
+ clean("the same words inside a note are accepted",
652
+ run(fill("k-aaa", "결정: 승인", "메모: 제안: 지우기 전에 꼭 묻는다."))[1])
653
+ copy = blank.replace("결정: 이 줄은 인용이고 블록 밖에 있다.", "결정: 승인")
654
+ control("a payload line shaped like a 결정 line is fixed by its position: editing it is refused", said(copy),
655
+ f"EDIT_OUTSIDE_EDITABLE line {number(copy, '결정: 승인')}:")
656
+ copy = blank.replace("## 2. k-bbb (판정 필요)", "결정: 승인\n## 2. k-bbb (판정 필요)")
657
+ control("a 결정 line written outside every block is refused at its line", said(copy),
658
+ f"EDIT_OUTSIDE_EDITABLE line {number(copy, '결정: 승인')}:")
659
+ copy = blank.replace("무엇이 있었나: 브랜치를 묻지 않고 지웠다.\n", "")
660
+ control("a deleted payload line is refused where the copy departs", said(copy),
661
+ f"EDIT_OUTSIDE_EDITABLE line {number(copy, '제안: 지우기 전에 묻는다.')}:")
662
+ control("a removed final newline is named", said(blank[:-1]), "lacks the render's final newline")
663
+ copy = blank + "\n"
664
+ control("a line past the render's end is refused at its line", said(copy),
665
+ f"EDIT_OUTSIDE_EDITABLE line {len(copy.split(chr(10)))}: a line the render does not have")
666
+ copy = blank.replace("제안: 지우기 전에 묻는다.", "제안: 지우기 전에 묻는다. ")
667
+ control("trailing whitespace on a fixed line is refused and named", said(copy), "only its trailing whitespace")
668
+ control("CRLF line endings are refused by name", said(blank.replace("\n", "\r\n")), "LINE_ENDINGS_CHANGED line 1")
669
+ copy = blank.replace("무엇이 있었나: 브랜치를 묻지 않고 지웠다.",
670
+ unicodedata.normalize("NFD", "무엇이 있었나: 브랜치를 묻지 않고 지웠다."))
671
+ control("a fixed line re-normalized to NFD is refused by name", said(copy), "NORMALIZATION_CHANGED line")
672
+ control("a byte-order mark is refused by name", said("" + blank), "ENCODING_CHANGED line 1")
673
+ control("a copy without its header is refused", said(blank.split("\n", 1)[1]), "COPY_HEADER_MISSING line 1")
674
+ other = render_of(rows[:2])
675
+ control("a copy of another render is refused: the sha names another render", said(copy_of(other, name)),
676
+ "COPY_UNBOUND line 1")
677
+ control("and a copy naming another render's file is refused", said(copy_of(render, "review.ko.v2.md")),
678
+ "COPY_UNBOUND line 1")
679
+ control("a marker's sha edited is an edit outside the editable parts",
680
+ said(blank.replace("item=k-aaa sha=s1", "item=k-aaa sha=s9")), "EDIT_OUTSIDE_EDITABLE line")
681
+ copy = blank.replace("메모:\n" + CLOSE + "\n\n## 2.", "메모:\n\n## 2.", 1)
682
+ control("a deleted block end lets the next block open inside it: refused by line", said(copy),
683
+ f"BLOCK_NESTED line {number(copy, '<!-- owner-block review item=k-bbb sha=s2 -->')}")
684
+ last = blank.rsplit(CLOSE, 1)
685
+ control("the last block's end deleted is refused as unterminated", said(last[0] + last[1]), "BLOCK_UNTERMINATED line")
686
+
687
+ # ---- ambiguous lines, refused by line ------------------------------------------------------------------------
688
+ copy = fill("k-aaa", "결정: 승인 기각")
689
+ control("two verbs on one line are refused, not read as the first", said(copy),
690
+ f"DECISION_ARGUMENT_INVALID line {number(copy, '결정: 승인 기각')}")
691
+ copy = fill("k-aaa", "결정: 승인함")
692
+ control("a word that is not a verb is refused, not read as the verb it resembles", said(copy),
693
+ f"DECISION_VERB_UNKNOWN line {number(copy, '결정: 승인함')}")
694
+ copy = fill("k-aaa", "결정: 승인", "좋습니다")
695
+ control("a free line inside a block is refused: a note is a 메모: line", said(copy),
696
+ f"LINE_NOT_EDITABLE line {number(copy, '좋습니다')}")
697
+ copy = fill("k-aaa", "결정: 승인", "메모:", "결정: 기각")
698
+ control("a second 결정 line is refused at its line", said(copy),
699
+ f"DECISION_TWICE line {number(copy, '결정: 기각')}")
700
+ copy = fill("k-bbb", "결정: 판정", "메모: 근거", "판정: A")
701
+ control("a 판정 line without its label is refused", said(copy), f"LINE_NOT_EDITABLE line {number(copy, '판정: A')}")
702
+ copy = fill("k-aaa", "결정: 승인", "확인: 확정")
703
+ control("a 확인 line in a review row is refused", said(copy), f"LINE_NOT_EDITABLE line {number(copy, '확인: 확정')}")
704
+ copy = fill("k-aaa", "결정: 수정 대안")
705
+ control("수정 대안 without its id is refused", said(copy),
706
+ f"DECISION_ARGUMENT_INVALID line {number(copy, '결정: 수정 대안')}")
707
+
708
+ # ---- the rules among a block's lines (no rows needed) --------------------------------------------------------
709
+ copy = fill("k-bbb", "결정: 보류", "판정 1: A")
710
+ control("a filled 판정 value under another verb is refused at the value's line", said(copy, spec=None),
711
+ f"ADJUDICATION_WITHOUT_VERB line {number(copy, '판정 1: A')}")
712
+ copy = fill("k-bbb", "결정: 판정", "메모: 근거", "판정 1: A", "판정 2:")
713
+ control("결정: 판정 with an empty judgment is refused at the empty line", said(copy, spec=None),
714
+ f"ADJUDICATION_INCOMPLETE line {number(copy, '판정 2:')}")
715
+ copy = fill("k-bbb", "결정: 판정", "메모: 근거")
716
+ control("결정: 판정 with no judgment line at all is refused", said(copy, spec=None),
717
+ f"ADJUDICATION_INCOMPLETE line {number(copy, '결정: 판정')}")
718
+ copy = fill("k-bbb", "결정: 판정", "판정 1: A", "판정 2: B")
719
+ control("판정 without its rationale is refused", said(copy, spec=None),
720
+ f"NOTE_REQUIRED line {number(copy, '결정: 판정')}")
721
+ copy = fill("k-aaa", "결정: 수정", "메모:")
722
+ control("수정 with neither a note nor an alternative is refused", said(copy, spec=None),
723
+ f"NOTE_REQUIRED line {number(copy, '결정: 수정')}")
724
+ copy = fill("k-ccc", "결정: 승인", "keep 해제: R-1")
725
+ control("keep 해제 without grounds is refused", said(copy, spec=None),
726
+ f"KEEP_RELEASE_GROUNDLESS line {number(copy, 'keep 해제: R-1')}")
727
+ copy = fill("k-ccc", "결정: 보류", "keep 해제: R-1 근거")
728
+ control("keep 해제 under anything but 승인 is refused", said(copy, spec=None),
729
+ f"KEEP_RELEASE_UNUSED line {number(copy, 'keep 해제: R-1 근거')}")
730
+ copy = fill("k-bbb", "결정: 판정", "메모: 근거", "판정 1: A", "판정 1: B", "판정 2: A")
731
+ control("one judgment answered twice is refused at the second", said(copy, spec=None),
732
+ f"JUDGMENT_TWICE line {number(copy, '판정 1: B')}")
733
+ copy = fill("k-ccc", "결정: 승인", "keep 해제: R-1 하나", "keep 해제: R-1 둘")
734
+ control("one record released twice is refused at the second", said(copy, spec=None),
735
+ f"KEEP_RELEASE_TWICE line {number(copy, 'keep 해제: R-1 둘')}")
736
+ got = item_of(fill("k-bbb", "결정: 판정", "메모: 근거", "판정 1: a", "판정 2: B"), "k-bbb", spec=None)
737
+ equal("a lower-case a is the owner's own value, never read as judge A",
738
+ [(j["choice"], j["value"]) for j in got.get("judgments", [])], [("own", "a"), ("B", None)])
739
+
740
+ # ---- each line held to its current row -----------------------------------------------------------------------
741
+ copy = fill("k-aaa", "결정: 승인")
742
+ got = item_of(copy, "k-aaa", spec=spec_of(**{"k-aaa": {"item_sha": "s1-changed"}}))
743
+ equal("an item whose sha changed after rendering is stale, and its approval is not a decision",
744
+ (got.get("state"), (got.get("code") or "").split(" ", 1)[0]), ("stale", "DECISION_STALE"))
745
+ clean("and a stale item refuses nothing else of the file", run(copy, spec=spec_of(**{"k-aaa": {"item_sha": "x"}}))[1])
746
+ got = item_of(fill("k-bbb", "결정: 승인"), "k-bbb", spec=spec_of(**{"k-bbb": {"item_sha": "s2-changed"}}))
747
+ equal("and a stale disputed row is not judged by its old lines", got.get("state"), "stale")
748
+ clean("so its approval raises no DISPUTE_UNRESOLVED",
749
+ run(fill("k-bbb", "결정: 승인"), spec=spec_of(**{"k-bbb": {"item_sha": "s2-changed"}}))[1])
750
+ copy = fill("k-bbb", "결정: 판정", "메모: 근거", "판정 1: A", "판정 2: B", "판정 3: A")
751
+ control("a judgment label the row does not carry is refused", said(copy),
752
+ f"JUDGMENT_UNKNOWN line {number(copy, '판정 3: A')}")
753
+ copy = fill("k-bbb", "결정: 판정", "메모: 근거", "판정 1: maybe", "판정 2: B")
754
+ control("an own value outside the judgment's values is refused", said(copy),
755
+ f"JUDGMENT_VALUE_INVALID line {number(copy, '판정 1: maybe')}")
756
+ copy = fill("k-aaa", "결정: 판정", "메모: 근거", "판정 1: A")
757
+ control("판정 on a row with no disputed judgment is refused", said(copy),
758
+ f"DECISION_NOT_ALLOWED line {number(copy, '결정: 판정')}")
759
+ copy = fill("k-bbb", "결정: 판정", "메모: 근거", "판정 1: A")
760
+ control("판정 that leaves one of the row's disputed judgments without a line is refused", said(copy),
761
+ f"ADJUDICATION_INCOMPLETE line {number(copy, '결정: 판정')}: disputed judgment 2")
762
+ copy = fill("k-bbb", "결정: 승인")
763
+ control("a disputed row approved without adjudication is refused", said(copy),
764
+ f"DISPUTE_UNRESOLVED line {number(copy, '결정: 승인')}")
765
+ copy = fill("k-aaa", "결정: 수정 대안 alt-9")
766
+ control("an alternative S7b did not offer is refused", said(copy),
767
+ f"ALTERNATIVE_UNKNOWN line {number(copy, '결정: 수정 대안 alt-9')}")
768
+ copy = fill("k-ccc", "결정: 승인", "keep 해제: R-1 근거", "keep 해제: R-9 근거")
769
+ control("a release of a record the proposal does not override is refused", said(copy),
770
+ f"KEEP_UNKNOWN line {number(copy, 'keep 해제: R-9 근거')}")
771
+ copy = fill("k-ccc", "결정: 승인")
772
+ control("an approval over a keep record nobody released is refused (KEEP_GUARDED)", said(copy),
773
+ f"KEEP_GUARDED line {number(copy, '결정: 승인')}: the proposal reduces or merges over keep record R-1")
774
+ clean("and the same approval with the release is accepted", run(fill("k-ccc", "결정: 승인", "keep 해제: R-1 근거"))[1])
775
+ control("a rendered item the current rows do not hold is refused", said(blank, spec=spec_of(**{"k-ccc": None})),
776
+ "ITEM_UNKNOWN line")
777
+ control("a current row the render does not hold is named", said(blank, spec=spec_of(**{"k-ddd": {"item_sha": "s4"}})),
778
+ "ITEM_NOT_RENDERED k-ddd")
779
+ control("rows that are not rows are refused as the caller's error, not reported as the owner's",
780
+ refusal(lambda: run(blank, spec={"k-aaa": {"judgments": {}}})), "SPEC_INVALID k-aaa")
781
+
782
+ # ---- the confirmation file (lead decision E1) ----------------------------------------------------------------
783
+ confirm = "\n".join(["# 최종 확인 v1 (fixture)", "", "항목 k-aaa, k-ccc", "", *confirm_block("f1"), ""]) + "\n"
784
+ cname = "confirm.ko.v1.md"
785
+ cblank = copy_of(confirm, cname)
786
+
787
+ def cfill(*lines_):
788
+ text = cblank.split("\n")
789
+ start = next(i for i, t in enumerate(text) if t.startswith("<!-- owner-block confirm "))
790
+ end = next(i for i in range(start + 1, len(text)) if text[i] == CLOSE)
791
+ return "\n".join(text[:start + 1] + list(lines_) + text[end:])
792
+
793
+ def crun(copy, **kwargs):
794
+ return parse(confirm, copy, render_name=cname, **kwargs)
795
+
796
+ def cheld(copy, **kwargs):
797
+ result, problems = crun(copy, **kwargs)
798
+ return (result or {}).get("confirm") or {"problems": problems}
799
+
800
+ clean("the confirmation fixture is a render", render_problems(confirm))
801
+ equal("an unedited confirmation copy is undecided", (cheld(cblank).get("state"), cheld(cblank).get("decision")),
802
+ ("undecided", None))
803
+ equal("확인: 확정 confirms the set", (cheld(cfill("확인: 확정")).get("decision")), "confirm")
804
+ equal("확인: 반려 with a note returns it", (cheld(cfill("확인: 반려", "메모: k-ccc를 빼고 다시")).get("decision")),
805
+ "return")
806
+ copy = cfill("확인: 반려")
807
+ control("반려 without a note is refused", "\n".join(crun(copy)[1]),
808
+ f"NOTE_REQUIRED line {number(copy, '확인: 반려')}")
809
+ copy = cfill("확인: 예")
810
+ control("a 확인 word that is not 확정 or 반려 is refused", "\n".join(crun(copy)[1]),
811
+ f"CONFIRM_VERB_UNKNOWN line {number(copy, '확인: 예')}")
812
+ copy = cfill("확인: 확정", "확인: 반려")
813
+ control("a second 확인 line is refused", "\n".join(crun(copy)[1]),
814
+ f"CONFIRM_TWICE line {number(copy, '확인: 반려')}")
815
+ copy = cfill("확인: 확정", "결정: 승인")
816
+ control("a 결정 line in a confirmation block is refused", "\n".join(crun(copy)[1]),
817
+ f"LINE_NOT_EDITABLE line {number(copy, '결정: 승인')}")
818
+ got = cheld(cfill("확인: 확정"), confirm_set="f2")
819
+ equal("a confirmation of a set that is no longer the final set is stale",
820
+ (got.get("state"), (got.get("code") or "").split(" ", 1)[0]), ("stale", "CONFIRM_STALE"))
821
+
822
+ # ---- what a render is ----------------------------------------------------------------------------------------
823
+ control("a payload line shaped like a marker is refused in a render",
824
+ "\n".join(render_problems(render.replace("이 파일은 고정 자료입니다.", "<!-- owner-block 안내 -->"))),
825
+ "BLOCK_MALFORMED line 3")
826
+ control("a block end with no block open is refused in a render",
827
+ "\n".join(render_problems(render.replace("이 파일은 고정 자료입니다.", CLOSE))), "BLOCK_UNOPENED line 3")
828
+ control("a prefilled render is refused", "\n".join(render_problems(render.replace("결정:\n메모:", "결정: 승인\n메모:", 1))),
829
+ "RENDER_BLOCK_INVALID line")
830
+ control("two blocks for one item are refused", "\n".join(render_problems(render_of(rows + rows[:1]))), "ITEM_TWICE line")
831
+ control("a copy is not a render", "\n".join(render_problems(blank)), "RENDER_IS_COPY line 1")
832
+ control("review and confirmation blocks in one file are refused",
833
+ "\n".join(render_problems(render + "\n".join(confirm_block("f1")) + "\n")), "FILE_KINDS_MIXED")
834
+ control("a confirmation file with two blocks is refused",
835
+ "\n".join(render_problems(confirm + "\n".join(confirm_block("f2")) + "\n")), "CONFIRM_BLOCK_TWICE line")
836
+ control("a render with a carriage return is refused", "\n".join(render_problems(render.replace("\n", "\r\n", 1))),
837
+ "RENDER_BYTES_INVALID")
838
+ control("a review block missing its sha is refused",
839
+ "\n".join(render_problems(render.replace(" sha=s1 -->", " -->"))), "BLOCK_MALFORMED line")
840
+ control("copy_of refuses an invalid render", refusal(lambda: copy_of(blank, name)), "RENDER_INVALID")
841
+ control("parse refuses a copy of an invalid render as the render's fault", "\n".join(parse(blank, blank)[1]),
842
+ "RENDER_INVALID RENDER_IS_COPY")
843
+ control("a label with a space is refused when the block is made", refusal(lambda: review_block("k", "s", ["a b"])),
844
+ "BLOCK_ARGUMENT_INVALID label")
845
+ control("an item id with '=' is refused when the block is made", refusal(lambda: review_block("k=1", "s")),
846
+ "BLOCK_ARGUMENT_INVALID item")
847
+ control("a repeated label is refused when the block is made", refusal(lambda: review_block("k", "s", ["1", "1"])),
848
+ "BLOCK_ARGUMENT_INVALID labels")
849
+ control("require names every problem, the first first",
850
+ refusal(lambda: require(render, fill("k-aaa", "결정: 승인함", "좋습니다"), render_name=name)),
851
+ "DECISION_VERB_UNKNOWN line")
852
+ try:
853
+ approved = require(render, fill("k-aaa", "결정: 승인"), render_name=name)["items"][0]["decision"]
854
+ except Refused as exc: # a refusal here is this control failing by name, not the suite dying
855
+ approved = f"refused: {str(exc)[:160]}"
856
+ equal("and returns the result when nothing is refused", approved, "approve")
857
+
858
+ reporting.append(True)
859
+ if failures:
860
+ for label, detail in failures:
861
+ print(f"owner_lines --self-test [FAIL] {label}: {detail}", file=sys.stderr)
862
+ print(f"owner_lines --self-test: FAILED ({len(failures)} of {len(ran)} controls)", file=sys.stderr)
863
+ return 1
864
+ print(f"owner_lines --self-test: OK ({len(ran)} controls: the copy is the render under its header; each of the "
865
+ f"five verbs, 수정 대안, 판정 A/B/own, keep 해제 and 확인 read; edits outside a block refused by line and the "
866
+ f"same words in a note accepted; every ambiguous line refused by line; DECISION_STALE, KEEP_GUARDED and the "
867
+ f"row rules held to the current rows)")
868
+ return 0
869
+
870
+
871
+ if __name__ == "__main__":
872
+ if sys.argv[1:2] == ["--self-test"]:
873
+ sys.exit(self_test())
874
+ sys.exit("usage: owner_lines.py --self-test")