agent-bios 0.19.4 → 0.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (158) hide show
  1. package/DEPENDENCIES.md +19 -5
  2. package/README.md +14 -19
  3. package/claude/agents/frontier.md +1 -1
  4. package/claude/guides/claude-prompting.md +475 -234
  5. package/claude/guides/cli-multi-model-workflow.md +4 -3
  6. package/claude/guides/gpt-prompting.md +235 -136
  7. package/claude/guides/session-distill-workflow.md +93 -43
  8. package/claude/guides/tooling-gotchas.md +3 -1
  9. package/codex/guides/claude-prompting.md +475 -234
  10. package/codex/guides/cli-multi-model-workflow.md +4 -3
  11. package/codex/guides/gpt-prompting.md +235 -136
  12. package/codex/guides/session-distill-workflow.md +93 -43
  13. package/codex/guides/tooling-gotchas.md +3 -1
  14. package/compose/assemble.py +4 -1
  15. package/compose/canary.sh +8 -6
  16. package/compose/host_platform.py +158 -15
  17. package/compose/instructions-state.py +183 -41
  18. package/compose/instructions_install.py +222 -27
  19. package/compose/instructions_session.py +250 -75
  20. package/compose/instructions_setup_cli.py +2 -36
  21. package/compose/instructions_store.py +160 -3
  22. package/compose/instructions_transaction.py +29 -5
  23. package/docs/advanced-launch.md +4 -0
  24. package/docs/releases/0.20.0.md +102 -0
  25. package/install.sh +42 -14
  26. package/launch/agent-launch.py +152 -18
  27. package/launch/agent-launch.toml +17 -7
  28. package/launch/agent-launch.zsh +104 -13
  29. package/launch/claude_subcommands.py +179 -0
  30. package/launch/shell_integration.py +7 -1
  31. package/learn/collect-learning.py +60 -9
  32. package/learn/migrate-learnings.py +70 -4
  33. package/learn/redact.py +2 -1
  34. package/package.json +36 -3
  35. package/provenance.json +1 -1
  36. package/session-cost.py +80 -9
  37. package/session-distill/coverage.json +6 -0
  38. package/session-distill/distill.py +2575 -0
  39. package/session-distill/grammar/__init__.py +0 -0
  40. package/session-distill/grammar/owner_lines.py +874 -0
  41. package/session-distill/originators.json +9 -0
  42. package/session-distill/packets/cross_review.md +31 -0
  43. package/session-distill/packets/form.md +86 -0
  44. package/session-distill/packets/judge.md +81 -0
  45. package/session-distill/packets/placement_contract.md +90 -0
  46. package/session-distill/packets/propose.md +124 -0
  47. package/session-distill/packets/read.md +57 -0
  48. package/session-distill/packets/reconsider.md +53 -0
  49. package/session-distill/packets/s7b.md +65 -0
  50. package/session-distill/packets/s9b.md +39 -0
  51. package/session-distill/packets/stitch.md +35 -0
  52. package/session-distill/packets/sweep.md +33 -0
  53. package/session-distill/runlib/__init__.py +0 -0
  54. package/session-distill/runlib/bound.py +1102 -0
  55. package/session-distill/runlib/breaker.py +467 -0
  56. package/session-distill/runlib/census.py +2347 -0
  57. package/session-distill/runlib/claims.py +420 -0
  58. package/session-distill/runlib/controls.py +902 -0
  59. package/session-distill/runlib/coverage.py +881 -0
  60. package/session-distill/runlib/declare.py +888 -0
  61. package/session-distill/runlib/delivery_evidence.py +1145 -0
  62. package/session-distill/runlib/derive.py +812 -0
  63. package/session-distill/runlib/destinations.py +3072 -0
  64. package/session-distill/runlib/dispatch.py +7939 -0
  65. package/session-distill/runlib/drift.py +1077 -0
  66. package/session-distill/runlib/entry.py +401 -0
  67. package/session-distill/runlib/evidence.py +890 -0
  68. package/session-distill/runlib/exposure.py +1162 -0
  69. package/session-distill/runlib/gate.py +2727 -0
  70. package/session-distill/runlib/gitread.py +79 -0
  71. package/session-distill/runlib/inventory.py +19624 -0
  72. package/session-distill/runlib/journal.py +1919 -0
  73. package/session-distill/runlib/ledger.py +3210 -0
  74. package/session-distill/runlib/ledger_compat.py +101 -0
  75. package/session-distill/runlib/ledger_migration.py +190 -0
  76. package/session-distill/runlib/lifecycle_intake.py +693 -0
  77. package/session-distill/runlib/lineage.py +454 -0
  78. package/session-distill/runlib/measures.py +249 -0
  79. package/session-distill/runlib/monitor.py +1180 -0
  80. package/session-distill/runlib/operations.py +522 -0
  81. package/session-distill/runlib/packet.py +838 -0
  82. package/session-distill/runlib/placement.py +1769 -0
  83. package/session-distill/runlib/projection.py +4090 -0
  84. package/session-distill/runlib/ranking.py +740 -0
  85. package/session-distill/runlib/receipts.py +200 -0
  86. package/session-distill/runlib/records.py +1965 -0
  87. package/session-distill/runlib/search.py +249 -0
  88. package/session-distill/runlib/sequencing.py +829 -0
  89. package/session-distill/runlib/sources.py +641 -0
  90. package/session-distill/runlib/stage_adjudicate.py +845 -0
  91. package/session-distill/runlib/stage_apply.py +1378 -0
  92. package/session-distill/runlib/stage_approvals.py +758 -0
  93. package/session-distill/runlib/stage_close.py +1220 -0
  94. package/session-distill/runlib/stage_confirm.py +929 -0
  95. package/session-distill/runlib/stage_delivery.py +3080 -0
  96. package/session-distill/runlib/stage_form.py +2576 -0
  97. package/session-distill/runlib/stage_judge.py +4248 -0
  98. package/session-distill/runlib/stage_propose.py +3307 -0
  99. package/session-distill/runlib/stage_read.py +5179 -0
  100. package/session-distill/runlib/stage_render.py +2739 -0
  101. package/session-distill/runlib/stage_retrieve.py +924 -0
  102. package/session-distill/runlib/stage_review_korean.py +1002 -0
  103. package/session-distill/runlib/stage_review_proposals.py +1292 -0
  104. package/session-distill/runlib/stagelock.py +412 -0
  105. package/session-distill/runlib/stop.py +1061 -0
  106. package/session-distill/runlib/targets.py +809 -0
  107. package/session-distill/runlib/usage.py +280 -0
  108. package/session-distill/runlib/validate.py +319 -0
  109. package/session-distill/runlib/views.py +4327 -0
  110. package/session-distill/schemas/adjudication.schema.json +35 -0
  111. package/session-distill/schemas/approval.schema.json +35 -0
  112. package/session-distill/schemas/census.schema.json +128 -0
  113. package/session-distill/schemas/checks.schema.json +207 -0
  114. package/session-distill/schemas/claim.schema.json +16 -0
  115. package/session-distill/schemas/confirmation.schema.json +24 -0
  116. package/session-distill/schemas/coverage.schema.json +66 -0
  117. package/session-distill/schemas/cross_review.schema.json +24 -0
  118. package/session-distill/schemas/event.schema.json +20 -0
  119. package/session-distill/schemas/evidence.schema.json +20 -0
  120. package/session-distill/schemas/expected_observation.schema.json +18 -0
  121. package/session-distill/schemas/form.schema.json +103 -0
  122. package/session-distill/schemas/intake.schema.json +71 -0
  123. package/session-distill/schemas/inventory.schema.json +872 -0
  124. package/session-distill/schemas/judge.schema.json +77 -0
  125. package/session-distill/schemas/ledger.schema.json +313 -0
  126. package/session-distill/schemas/observation.schema.json +16 -0
  127. package/session-distill/schemas/propose.schema.json +555 -0
  128. package/session-distill/schemas/read.schema.json +76 -0
  129. package/session-distill/schemas/reconsider.schema.json +122 -0
  130. package/session-distill/schemas/run.schema.json +150 -0
  131. package/session-distill/schemas/s7b.schema.json +200 -0
  132. package/session-distill/schemas/s9b.schema.json +28 -0
  133. package/session-distill/schemas/stitch.schema.json +25 -0
  134. package/session-distill/schemas/sweep.schema.json +25 -0
  135. package/session-distill/seats.json +149 -0
  136. package/session-distill/tables/allowed_pairs.json +257 -0
  137. package/session-distill/tables/controls.json +30 -0
  138. package/session-distill/tables/delivery_evidence.json +36 -0
  139. package/session-distill/tables/delivery_evidence_fixtures.json +731 -0
  140. package/session-distill/tables/destinations.json +684 -0
  141. package/session-distill/tables/drift_layers.json +68 -0
  142. package/session-distill/tables/exposure_rules.json +192 -0
  143. package/session-distill/tables/placement_rules.json +148 -0
  144. package/session-distill/tables/propose_fixtures.json +154 -0
  145. package/session-distill/tables/ranking.json +194 -0
  146. package/session-distill/tables/redundancy.json +10 -0
  147. package/session-distill/tables/structural_rules.json +44 -0
  148. package/session-distill/tables/transition_fixtures.json +398 -0
  149. package/session-distill/tables/transitions.json +69 -0
  150. package/session-distill/tables/unit_outcome.json +67 -0
  151. package/session-distill/tables/unit_outcome_fixtures.json +2364 -0
  152. package/wrappers/claude-run.sh +481 -33
  153. package/wrappers/claude_hermetic_evidence.py +1423 -0
  154. package/wrappers/codex-helm.sh +38 -7
  155. package/wrappers/codex-run.sh +183 -20
  156. package/wrappers/codex_frame_filter.py +1199 -0
  157. package/wrappers/codex_protocol.py +737 -0
  158. package/wrappers/jsonl_lines.py +65 -0
@@ -0,0 +1,522 @@
1
+ #!/usr/bin/env python3
2
+ """What an operation does to a file's text: the one contract S7's check and S11's plan both read.
3
+
4
+ §7.3 names five operation types and the packet lists their fields; this module says what each does
5
+ to BYTES (lead decision D-20261113-1e6983). It is pure: text in, text out, no file opened. S11
6
+ (`stage_apply.py`) plans with it and S7's live check asks it whether a proposal's operations apply
7
+ to the checkout as it is, so a model learns in its one retry what S11 would have refused after the
8
+ owner approved.
9
+
10
+ target `path` or `path#heading`. The heading names one ATX heading of the file, by its
11
+ title with or without its `#` marks; it must occur exactly once outside fenced code.
12
+ Its SECTION runs from the heading's line to the next heading of the same or a higher
13
+ level, or to the end of the file.
14
+ create the file is absent; it becomes `content`.
15
+ edit with `anchor`: that exact text occurs once in the section (or the file), counting
16
+ overlapping occurrences, and is replaced by `content`. With a heading and no anchor:
17
+ the section is replaced by `content`, which must end its own last line when more of
18
+ the file follows (nothing is added to it). With neither: the file becomes `content`.
19
+ A `diff` is not applied.
20
+ delete with `anchor`: that text is removed. With a heading: the section. With neither: the
21
+ file.
22
+ merge each unit is removed (its section, or its file), except a unit that IS the target;
23
+ then the target takes `content` exactly as an edit does, or is created.
24
+ route `entry` is appended as one line to the section or the file, with the file's own line
25
+ ending; an entry already there is refused.
26
+
27
+ Headings and fences are read as CommonMark reads them, so a section is what a reader sees: an ATX
28
+ heading may be indented up to three spaces and may close with `#`s after a space; a fence opens with
29
+ three or more backticks or tildes and closes only with a line of the same character, at least as
30
+ long, and nothing after it; a line ending `\\r\\n` is a line.
31
+
32
+ Every refusal has its own code, and the text is never changed except where the operation names.
33
+
34
+ operations.py --self-test
35
+ """
36
+ import hashlib
37
+ import pathlib
38
+ import re
39
+ import sys
40
+
41
+ HERE = pathlib.Path(__file__).resolve().parents[1]
42
+ sys.path.insert(0, str(HERE))
43
+ from runlib import targets # noqa: E402
44
+ from runlib.records import Refused # noqa: E402
45
+
46
+ ABSENT = "absent"
47
+ TYPES = ("create", "edit", "delete", "merge", "route")
48
+ ATX = re.compile(r"^ {0,3}(#{1,6})(?:[ \t]+(.*?))?[ \t]*$")
49
+ CLOSING = re.compile(r"^(.*?)(?:^|[ \t]+)#+$")
50
+ FENCE_OPEN = re.compile(r"^ {0,3}(`{3,}|~{3,})(.*)$")
51
+
52
+
53
+ def sha_of(data):
54
+ return ABSENT if data is None else hashlib.sha256(data).hexdigest()
55
+
56
+
57
+ def split_target(target):
58
+ """`(path identity, heading | None)` of a target or a unit: `path` or `path#heading`."""
59
+ heading = str(target or "").partition("#")[2]
60
+ return targets.identity(targets.file_of(target or "")), (heading.strip() or None)
61
+
62
+
63
+ LINE = re.compile(r"[^\r\n]*(?:\r\n|\r|\n|\Z)")
64
+
65
+
66
+ def lines_of(text):
67
+ """`[(offset, line)]`: each line of `text` without its ending, at its own character offset. A line ends at
68
+ `\n`, `\r\n` or a lone `\r`, as CommonMark ends it: split on `\n` alone, a heading after a lone `\r` was part
69
+ of the line before it, and the section above ran through it (the S11 review, round 2)."""
70
+ out, at = [], 0
71
+ while at < len(text):
72
+ held = LINE.match(text, at)
73
+ out.append((at, held.group(0).rstrip("\r\n")))
74
+ at = held.end()
75
+ return out
76
+
77
+
78
+ def _title(text):
79
+ held = CLOSING.match(text or "")
80
+ return (held.group(1) if held else (text or "")).strip()
81
+
82
+
83
+ def headings(text):
84
+ """`[(line index, level, title)]` of the ATX headings of `text` outside fenced code."""
85
+ out, fence = [], None
86
+ for index, (_at, line) in enumerate(lines_of(text)):
87
+ if fence:
88
+ closing = re.match(r"^ {0,3}(" + re.escape(fence[0]) + "{" + str(len(fence)) + r",})[ \t]*$", line)
89
+ if closing:
90
+ fence = None
91
+ continue
92
+ opened = FENCE_OPEN.match(line)
93
+ if opened and not (opened.group(1)[0] == "`" and "`" in opened.group(2)):
94
+ fence = opened.group(1)
95
+ continue
96
+ held = ATX.match(line)
97
+ if held:
98
+ out.append((index, len(held.group(1)), _title(held.group(2))))
99
+ return out
100
+
101
+
102
+ def heading_key(heading):
103
+ """`(level | None, title)` of a heading as a target names it: with its marks, or its title alone."""
104
+ held = re.match(r"^(#{1,6})[ \t]+(.*)$", heading.strip())
105
+ return (len(held.group(1)), _title(held.group(2))) if held else (None, _title(heading))
106
+
107
+
108
+ def section_span(text, heading, who):
109
+ """`(start, end)` character offsets of the one section `heading` names, or Refused by name."""
110
+ level, title = heading_key(heading)
111
+ held = headings(text)
112
+ found = [(i, lvl) for i, lvl, name in held if name == title and level in (None, lvl)]
113
+ if not found:
114
+ raise Refused(f"HEADING_ABSENT {who}: the file holds no heading {heading!r} outside fenced code")
115
+ if len(found) > 1:
116
+ raise Refused(f"HEADING_AMBIGUOUS {who}: the file holds {len(found)} headings {heading!r}, and a "
117
+ f"section is named by one")
118
+ index, lvl = found[0]
119
+ after = next((i for i, other, _name in held if i > index and other <= lvl), None)
120
+ offsets = [at for at, _line in lines_of(text)]
121
+ return offsets[index], (len(text) if after is None else offsets[after])
122
+
123
+
124
+ def _scope(text, heading, who):
125
+ return section_span(text, heading, who) if heading else (0, len(text))
126
+
127
+
128
+ def _anchor_at(text, span, anchor, who):
129
+ start, end = span
130
+ first = text.find(anchor, start, end)
131
+ where = "the section" if (start, end) != (0, len(text)) else "the file"
132
+ if first < 0:
133
+ raise Refused(f"ANCHOR_ABSENT {who}: the anchor does not occur in {where}")
134
+ if text.find(anchor, first + 1, end) >= 0: # an overlapping second occurrence is a second one
135
+ raise Refused(f"ANCHOR_AMBIGUOUS {who}: the anchor occurs more than once in {where}, and a place is "
136
+ f"named by one")
137
+ return first
138
+
139
+
140
+ def _content(operation, who):
141
+ held = operation.get("content")
142
+ if not isinstance(held, str):
143
+ if operation.get("diff") is not None:
144
+ raise Refused(f"OPERATION_NOT_APPLICABLE {who}: it carries a diff and no content, and release 1 "
145
+ f"places text and applies no patch")
146
+ raise Refused(f"CONTENT_ABSENT {who}: a {operation.get('type')} names the text it writes in `content`")
147
+ return held
148
+
149
+
150
+ def placed(text, heading, anchor, content, who):
151
+ """`text` with `content` placed: over the anchor, over the section, or as the whole. Nothing is
152
+ added to `content`: a section's replacement that would run into the text after it is refused."""
153
+ if anchor:
154
+ at = _anchor_at(text, _scope(text, heading, who), anchor, who)
155
+ return text[:at] + content + text[at + len(anchor):]
156
+ if heading:
157
+ start, end = section_span(text, heading, who)
158
+ if content and end < len(text) and not content.endswith(("\n", "\r")):
159
+ raise Refused(f"SECTION_CONTENT_UNTERMINATED {who}: more of the file follows the section, and the "
160
+ f"content replacing it does not end its last line; end it with a newline")
161
+ return text[:start] + content + text[end:]
162
+ return content
163
+
164
+
165
+ def removed(text, heading, anchor, who):
166
+ """`text` without the anchor or the section; None when neither is named (the file goes)."""
167
+ if anchor:
168
+ at = _anchor_at(text, _scope(text, heading, who), anchor, who)
169
+ return text[:at] + text[at + len(anchor):]
170
+ if heading:
171
+ start, end = section_span(text, heading, who)
172
+ return text[:start] + text[end:]
173
+ return None
174
+
175
+
176
+ def routed(text, heading, entry, who):
177
+ """`text` with `entry` appended as one line to the section or the file, in the file's line ending."""
178
+ if not isinstance(entry, str) or not entry.strip() or "\n" in entry.strip("\r\n") or "\r" in entry.strip("\r\n"):
179
+ raise Refused(f"ROUTE_ENTRY_INVALID {who}: a route's `entry` is one non-empty line")
180
+ line = entry.strip("\r\n")
181
+ start, end = _scope(text, heading, who)
182
+ if line in [held for _at, held in lines_of(text[start:end])]:
183
+ raise Refused(f"ROUTE_ENTRY_PRESENT {who}: that entry is already there")
184
+ ending = "\r\n" if "\r\n" in text else "\n"
185
+ body = text[start:end]
186
+ joint = "" if not body or body.endswith(("\n", "\r")) else ending
187
+ return text[:end] + joint + line + ending + text[end:]
188
+
189
+
190
+ class Tree:
191
+ """Files as a plan sees them: read once from `read(path)` (bytes, or None when absent), then
192
+ changed in memory only."""
193
+
194
+ def __init__(self, read):
195
+ self.read, self.first, self.now = read, {}, {}
196
+
197
+ def initial(self, path):
198
+ if path not in self.first:
199
+ self.first[path] = self.read(path)
200
+ self.now[path] = self.first[path]
201
+ return self.first[path]
202
+
203
+ def get(self, path):
204
+ self.initial(path)
205
+ return self.now[path]
206
+
207
+ def text(self, path, who):
208
+ held = self.get(path)
209
+ if held is None:
210
+ return None
211
+ try:
212
+ return held.decode("utf-8")
213
+ except UnicodeDecodeError as exc:
214
+ raise Refused(f"APPLY_NOT_TEXT {who}: {path} is not UTF-8 text, and an operation places text") from exc
215
+
216
+ def put(self, path, text):
217
+ self.initial(path)
218
+ self.now[path] = None if text is None else text.encode("utf-8")
219
+
220
+
221
+ def _same_place(text, path, heading, unit_path, unit_heading, who):
222
+ """Whether a merge's unit names the very place its target does, however each is spelled."""
223
+ if unit_path != path:
224
+ return False
225
+ if not heading or not unit_heading:
226
+ return heading == unit_heading
227
+ if text is None:
228
+ return heading_key(heading)[1] == heading_key(unit_heading)[1]
229
+ return section_span(text, heading, who) == section_span(text, unit_heading, who)
230
+
231
+
232
+ def operation_effects(operation, tree, who):
233
+ """`[(path, bytes | None)]`: the files one operation leaves changed, in the order it changes
234
+ them, each with its new state. Refused by name where the operation does not apply."""
235
+ kind = operation.get("type")
236
+ if kind not in TYPES:
237
+ raise Refused(f"OPERATION_UNKNOWN {who}: {kind!r} is not one of {', '.join(TYPES)}")
238
+ path, heading = split_target(operation.get("target"))
239
+ if not path:
240
+ raise Refused(f"TARGET_ABSENT {who}: the operation names no file")
241
+ carried = operation.get("before_state_sha256")
242
+ if sha_of(tree.initial(path)) != carried:
243
+ raise Refused(f"APPLY_BEFORE_MISMATCH {who}: {path} is {sha_of(tree.initial(path))[:12]} now, and the "
244
+ f"proposal was written against {str(carried)[:12]}")
245
+ text = tree.text(path, who)
246
+ anchor = operation.get("anchor") or None
247
+ touched = []
248
+
249
+ def put(where, new):
250
+ tree.put(where, new)
251
+ touched.append((where, tree.get(where)))
252
+
253
+ if kind == "create":
254
+ if text is not None:
255
+ raise Refused(f"CREATE_TARGET_PRESENT {who}: {path} is there, and a create makes a file")
256
+ if heading or anchor:
257
+ raise Refused(f"CREATE_WITH_PLACE {who}: a create writes a whole file and names no heading or anchor")
258
+ put(path, _content(operation, who))
259
+ elif kind == "edit":
260
+ if text is None:
261
+ raise Refused(f"EDIT_TARGET_ABSENT {who}: {path} is not there")
262
+ put(path, placed(text, heading, anchor, _content(operation, who), who))
263
+ elif kind == "delete":
264
+ if text is None:
265
+ raise Refused(f"DELETE_TARGET_ABSENT {who}: {path} is not there")
266
+ put(path, removed(text, heading, anchor, who))
267
+ elif kind == "route":
268
+ if text is None:
269
+ raise Refused(f"ROUTE_TARGET_ABSENT {who}: {path} is not there")
270
+ put(path, routed(text, heading, operation.get("entry"), who))
271
+ else: # merge: the units first, the target after (`sequencing.apply_to`'s order)
272
+ content = _content(operation, who)
273
+ states = {row.get("unit"): row.get("state") for row in operation.get("unit_states") or ()
274
+ if isinstance(row, dict)}
275
+ for unit in operation.get("units") or ():
276
+ unit_path, unit_heading = split_target(unit)
277
+ if _same_place(tree.text(path, who), path, heading, unit_path, unit_heading, who):
278
+ continue # the unit that IS the target is replaced, not removed
279
+ if unit_path != path:
280
+ if unit not in states:
281
+ raise Refused(f"MERGE_UNIT_STATE_ABSENT {who}: {unit} is in another file than the target, "
282
+ f"and the operation carries no state for it")
283
+ if sha_of(tree.initial(unit_path)) != states[unit]:
284
+ raise Refused(f"APPLY_BEFORE_MISMATCH {who}: {unit_path} is "
285
+ f"{sha_of(tree.initial(unit_path))[:12]} now, and the proposal was written "
286
+ f"against {str(states[unit])[:12]}")
287
+ held = tree.text(unit_path, who)
288
+ if held is None:
289
+ raise Refused(f"MERGE_UNIT_ABSENT {who}: {unit_path} is not there")
290
+ put(unit_path, removed(held, unit_heading, None, who))
291
+ text = tree.text(path, who)
292
+ if text is None:
293
+ if anchor:
294
+ raise Refused(f"ANCHOR_ABSENT {who}: {path} is not there for the anchor to occur in")
295
+ put(path, content)
296
+ else:
297
+ put(path, placed(text, heading, anchor, content, who))
298
+ return touched
299
+
300
+
301
+ def plan_of(items, read):
302
+ """`(effects, problems)` for items in their order: every operation applied in memory to the
303
+ files `read` gives. An effect is one file's change by one operation — `item_id`, `approval_id`,
304
+ `operation` (its index), `type`, `path`, `before`, `after` and the bytes it leaves (`data`, None
305
+ for a removal). Any problem and nothing is to be written."""
306
+ tree, effects, problems = Tree(read), [], []
307
+ for item in items:
308
+ for index, operation in enumerate(item.get("operations") or []):
309
+ who = f"{item['item_id']} operations[{index}]"
310
+ before = {}
311
+ try:
312
+ paths = [split_target(operation.get("target"))[0]]
313
+ paths += [split_target(u)[0] for u in operation.get("units") or ()]
314
+ for path in paths:
315
+ if path:
316
+ before.setdefault(path, sha_of(tree.get(path)))
317
+ touched = operation_effects(operation, tree, who)
318
+ except Refused as exc:
319
+ problems.append(str(exc))
320
+ continue
321
+ for path, data in touched:
322
+ effects.append({"item_id": item["item_id"], "approval_id": item.get("approval_id"),
323
+ "operation": index, "type": operation.get("type"), "path": path,
324
+ "before": before[path], "after": sha_of(data), "data": data})
325
+ before[path] = sha_of(data)
326
+ return [e for e in effects if e["before"] != e["after"]], problems
327
+
328
+
329
+ def applicability_problems(operations, read, who="the proposal"):
330
+ """What S11 would refuse of one proposal's operations against the files as `read` gives them
331
+ now: the question S7's check asks, so the refusal reaches the model and not the owner."""
332
+ return plan_of([{"item_id": who, "approval_id": None, "operations": list(operations or [])}], read)[1]
333
+
334
+
335
+ # ---- self-test ---------------------------------------------------------------------------------------
336
+
337
+ def self_test():
338
+ failures, ran = [], []
339
+
340
+ def control(name, got, want):
341
+ ran.append(name)
342
+ if got != want:
343
+ failures.append((name, f"expected {want!r}, got {got!r}"[:900]))
344
+
345
+ def said(call):
346
+ try:
347
+ call()
348
+ except Refused as exc:
349
+ return (str(exc).split() or [""])[0]
350
+ except Exception as exc: # noqa: BLE001 - the exception IS the answer here
351
+ return f"RAISED {type(exc).__name__}: {exc}"
352
+ return ""
353
+
354
+ doc = "# Guide\n\nintro\n\n## One\n\nfirst body\n\n### Deep\n\ndeep body\n\n## Two\n\nsecond body\n"
355
+
356
+ control("a section runs from its heading to the next heading of the same or a higher level",
357
+ doc[slice(*section_span(doc, "One", "t"))], "## One\n\nfirst body\n\n### Deep\n\ndeep body\n\n")
358
+ control("the last section runs to the end of the file", doc[slice(*section_span(doc, "## Two", "t"))],
359
+ "## Two\n\nsecond body\n")
360
+ control("a heading is named with its marks or without, and the marks are held to its level",
361
+ [said(lambda: section_span(doc, "### One", "t")), said(lambda: section_span(doc, "Three", "t"))],
362
+ ["HEADING_ABSENT", "HEADING_ABSENT"])
363
+ control("two headings of one title are ambiguous, by name",
364
+ said(lambda: section_span(doc + "\n## One\n\nagain\n", "One", "t")), "HEADING_AMBIGUOUS")
365
+ control("a heading inside fenced code is not a heading",
366
+ [h[2] for h in headings("# A\n\n```\n# not\n```\n\n~~~\n## nor\n~~~\n## B\n")], ["A", "B"])
367
+ # the round-1 review's boundary cases
368
+ control("an ATX heading indented up to three spaces is a heading, so a section ends at it",
369
+ [headings("# A\nx\n # B\ny\n"), removed("# A\nx\n # B\ny\n", "A", None, "t")],
370
+ [[(0, 1, "A"), (2, 1, "B")], " # B\ny\n"])
371
+ control("four spaces of indent is code, not a heading",
372
+ [h[2] for h in headings("# A\n # code\n")], ["A"])
373
+ control("a fence closes only with its own character, at least as long, and nothing after it",
374
+ [[h[2] for h in headings("````\n```\n# fake\n````\n# real\n")],
375
+ [h[2] for h in headings("```\n``` not a close\n# still code\n```\n# real\n")],
376
+ [h[2] for h in headings("~~~\n```\n# still code\n~~~\n# real\n")]],
377
+ [["real"], ["real"], ["real"]])
378
+ control("a backtick fence whose info string holds a backtick is not a fence",
379
+ [h[2] for h in headings("``` a`b\n# heading\n")], ["heading"])
380
+ control("a CRLF file's headings are headings, and its section offsets are the file's own",
381
+ [headings("# A\r\nx\r\n# B\r\n"), "# A\r\nx\r\n# B\r\n"[slice(*section_span("# A\r\nx\r\n# B\r\n", "A", "t"))]],
382
+ [[(0, 1, "A"), (2, 1, "B")], "# A\r\nx\r\n"])
383
+ control("a lone CR ends a line, so a heading after one is a heading and the section above stops at it; mixed "
384
+ "endings keep each line's own offset",
385
+ [headings("# A\nx\r# B\ny\n"), removed("# A\nx\r# B\ny\n", "A", None, "t"),
386
+ lines_of("a\r\nb\rc\nd"), headings("```\r# code\r```\r# real\r")],
387
+ [[(0, 1, "A"), (2, 1, "B")], "# B\ny\n", [(0, "a"), (3, "b"), (5, "c"), (7, "d")], [(3, 1, "real")]])
388
+ control("closing marks belong to the heading only after a space: `# C#` is titled C#, `# C #` is titled C",
389
+ [headings("# C#\n")[0][2], headings("# C #\n")[0][2], headings("# C ## \n")[0][2], headings("#\n")[0][2]],
390
+ ["C#", "C", "C", ""])
391
+ control("an edit with a heading replaces the section with the content exactly",
392
+ placed(doc, "Two", None, "## Two\n\nnew", "t"), doc.replace("## Two\n\nsecond body\n", "## Two\n\nnew"))
393
+ control("content replacing a section in the middle must end its own last line: nothing is added to it",
394
+ [said(lambda: placed(doc, "### Deep", None, "### Deep\n\nX", "t")),
395
+ placed(doc, "### Deep", None, "### Deep\n\nX\n", "t"), placed(doc, "### Deep", None, "", "t")],
396
+ ["SECTION_CONTENT_UNTERMINATED", doc.replace("### Deep\n\ndeep body\n\n", "### Deep\n\nX\n"),
397
+ doc.replace("### Deep\n\ndeep body\n\n", "")])
398
+ control("an edit with an anchor replaces that text once, inside the section it names",
399
+ placed(doc, "One", "first body", "FIRST", "t"), doc.replace("first body", "FIRST"))
400
+ control("an anchor outside the named section is absent, and one occurring twice is ambiguous",
401
+ [said(lambda: placed(doc, "One", "second body", "x", "t")),
402
+ said(lambda: placed(doc, None, "body", "x", "t"))], ["ANCHOR_ABSENT", "ANCHOR_AMBIGUOUS"])
403
+ control("an anchor whose occurrences overlap occurs twice",
404
+ [said(lambda: placed("aaa", None, "aa", "X", "t")), said(lambda: removed("aaa", None, "aa", "t")),
405
+ placed("aab", None, "aa", "X", "t")], ["ANCHOR_AMBIGUOUS", "ANCHOR_AMBIGUOUS", "Xb"])
406
+ control("an edit with neither is the whole file", placed(doc, None, None, "whole\n", "t"), "whole\n")
407
+ control("a delete removes the anchor, the section, or - with neither - the file",
408
+ [removed(doc, None, "intro\n\n", "t"), removed(doc, "Two", None, "t"), removed(doc, None, None, "t")],
409
+ [doc.replace("intro\n\n", ""), doc.replace("## Two\n\nsecond body\n", ""), None])
410
+ control("a route appends one line to the section, to the file when no heading is named, and in a CRLF file "
411
+ "with its ending",
412
+ [routed(doc, "One", "- [x](x.md)", "t"), routed("a\nb", None, "c", "t"), routed("a\r\nb\r\n", None, "c", "t")],
413
+ [doc.replace("deep body\n\n", "deep body\n\n- [x](x.md)\n"), "a\nb\nc\n", "a\r\nb\r\nc\r\n"])
414
+ control("a route already there, an empty one and a two-line one are refused by name",
415
+ [said(lambda: routed("a\nb\n", None, "b", "t")), said(lambda: routed("a\r\nb\r\n", None, "b", "t")),
416
+ said(lambda: routed(doc, None, " ", "t")), said(lambda: routed(doc, None, "a\nb", "t"))],
417
+ ["ROUTE_ENTRY_PRESENT", "ROUTE_ENTRY_PRESENT", "ROUTE_ENTRY_INVALID", "ROUTE_ENTRY_INVALID"])
418
+ control("a target is its path and its heading, and the path is the file's one identity",
419
+ [split_target("g//a.md#One"), split_target("./g/a.md"), split_target("")],
420
+ [("g/a.md", "One"), ("g/a.md", None), (None, None)])
421
+
422
+ # ---- the plan --------------------------------------------------------------------------------
423
+ files = {"g/a.md": doc.encode(), "g/b.md": b"# B\n\nbody of b\n", "g/r.md": b"# Routes\n"}
424
+ A, B_, R = (hashlib.sha256(files[k]).hexdigest() for k in ("g/a.md", "g/b.md", "g/r.md"))
425
+
426
+ def item(*operations, item_id="i1", approval="P-1"):
427
+ return {"item_id": item_id, "approval_id": approval, "operations": list(operations)}
428
+
429
+ def planned(*items, held=None):
430
+ return plan_of(list(items), (held or files).get)
431
+
432
+ def codes(problems):
433
+ return [p.split()[0] for p in problems]
434
+
435
+ effects, problems = planned(item({"type": "create", "target": "g/new.md", "before_state_sha256": ABSENT,
436
+ "content": "# New\n"},
437
+ {"type": "route", "target": "g/r.md", "before_state_sha256": R,
438
+ "entry": "- g/new.md"}))
439
+ control("a create and a route are two effects, each with the state before and the state after",
440
+ [problems, [(e["path"], e["before"], e["after"], e["data"]) for e in effects]],
441
+ [[], [("g/new.md", ABSENT, hashlib.sha256(b"# New\n").hexdigest(), b"# New\n"),
442
+ ("g/r.md", R, hashlib.sha256(b"# Routes\n- g/new.md\n").hexdigest(), b"# Routes\n- g/new.md\n")]])
443
+ effects, problems = planned(item({"type": "edit", "target": "g/a.md#One", "before_state_sha256": A,
444
+ "anchor": "first body", "content": "1"},
445
+ {"type": "edit", "target": "g/a.md#Two", "before_state_sha256": A,
446
+ "anchor": "second body", "content": "2"}))
447
+ control("two operations on one file chain: each is held to the state the proposal read, and the second "
448
+ "starts where the first ended",
449
+ [problems, len(effects), [e["after"] for e in effects][:1] == [e["before"] for e in effects][1:],
450
+ [e["data"] for e in effects][-1:] == [doc.replace("first body", "1").replace("second body", "2").encode()]],
451
+ [[], 2, True, True])
452
+ control("a file that moved since the proposal was written is refused, not patched",
453
+ codes(planned(item({"type": "edit", "target": "g/a.md", "before_state_sha256": B_, "content": "x"}))[1]),
454
+ ["APPLY_BEFORE_MISMATCH"])
455
+ control("each type's own refusal, by name",
456
+ [codes(planned(item(op))[1]) for op in (
457
+ {"type": "create", "target": "g/a.md", "before_state_sha256": A, "content": "x"},
458
+ {"type": "create", "target": "g/n.md#H", "before_state_sha256": ABSENT, "content": "x"},
459
+ {"type": "edit", "target": "g/n.md", "before_state_sha256": ABSENT, "content": "x"},
460
+ {"type": "edit", "target": "g/a.md", "before_state_sha256": A, "diff": "@@"},
461
+ {"type": "edit", "target": "g/a.md", "before_state_sha256": A},
462
+ {"type": "delete", "target": "g/n.md", "before_state_sha256": ABSENT},
463
+ {"type": "route", "target": "g/n.md", "before_state_sha256": ABSENT, "entry": "x"},
464
+ {"type": "patch", "target": "g/a.md", "before_state_sha256": A},
465
+ {"type": "edit", "target": "", "before_state_sha256": A, "content": "x"})],
466
+ [["CREATE_TARGET_PRESENT"], ["CREATE_WITH_PLACE"], ["EDIT_TARGET_ABSENT"], ["OPERATION_NOT_APPLICABLE"],
467
+ ["CONTENT_ABSENT"], ["DELETE_TARGET_ABSENT"], ["ROUTE_TARGET_ABSENT"], ["OPERATION_UNKNOWN"],
468
+ ["TARGET_ABSENT"]])
469
+ merge = {"type": "merge", "target": "g/a.md#One", "before_state_sha256": A, "content": "## One\n\nmerged\n\n",
470
+ "units": ["g/a.md#One", "g/a.md#Two", "g/b.md"], "unit_states": [{"unit": "g/b.md", "state": B_}]}
471
+ effects, problems = planned(item(merge))
472
+ control("a merge removes its units - a section, a whole file - and leaves the target with the text; the unit "
473
+ "that is the target is replaced, not removed",
474
+ [problems, [(e["path"], e["data"]) for e in effects][-1:],
475
+ [(e["path"], e["after"]) for e in effects if e["path"] == "g/b.md"]],
476
+ [[], [("g/a.md", b"# Guide\n\nintro\n\n## One\n\nmerged\n\n")], [("g/b.md", ABSENT)]])
477
+ spelled = planned(item({**merge, "units": ["g/a.md### One", "g/a.md#Two", "g/b.md"]}))
478
+ control("the unit that is the target is recognised however its heading is spelled",
479
+ [spelled[1], [(e["path"], e["data"]) for e in spelled[0]][-1:]],
480
+ [[], [("g/a.md", b"# Guide\n\nintro\n\n## One\n\nmerged\n\n")]])
481
+ anchored = planned(item({"type": "merge", "target": "g/b.md", "before_state_sha256": B_, "anchor": "body of b",
482
+ "content": "NEW", "units": ["g/a.md#Two"],
483
+ "unit_states": [{"unit": "g/a.md#Two", "state": A}]}))
484
+ control("a merge places its content as an edit does: over the anchor, and not as the whole file",
485
+ [anchored[1], [(e["path"], e["data"]) for e in anchored[0]][-1:]], [[], [("g/b.md", b"# B\n\nNEW\n")]])
486
+ control("a merge unit in another file needs its own state, and that state is held to the file",
487
+ [codes(planned(item({**merge, "unit_states": []}))[1]),
488
+ codes(planned(item({**merge, "unit_states": [{"unit": "g/b.md", "state": A}]}))[1])],
489
+ [["MERGE_UNIT_STATE_ABSENT"], ["APPLY_BEFORE_MISMATCH"]])
490
+ control("a file that is not text is refused by name",
491
+ codes(planned(item({"type": "edit", "target": "g/x.bin", "anchor": "a", "content": "b",
492
+ "before_state_sha256": hashlib.sha256(b"\xff\xfe").hexdigest()}),
493
+ held={**files, "g/x.bin": b"\xff\xfe"})[1]), ["APPLY_NOT_TEXT"])
494
+ control("an operation that changes nothing is no effect",
495
+ planned(item({"type": "edit", "target": "g/a.md", "before_state_sha256": A, "content": doc}))[0], [])
496
+ control("the applicability question S7 asks is the plan's own answer",
497
+ [codes(applicability_problems([{"type": "edit", "target": "g/a.md#Nine", "before_state_sha256": A,
498
+ "content": "x\n"}], files.get)),
499
+ applicability_problems([{"type": "edit", "target": "g/a.md#Two", "before_state_sha256": A,
500
+ "content": "## Two\n\nx\n"}], files.get)],
501
+ [["HEADING_ABSENT"], []])
502
+
503
+ if failures:
504
+ for name, detail in failures:
505
+ print(f"operations --self-test [FAIL] {name}: {detail}", file=sys.stderr)
506
+ print(f"operations --self-test: FAILED ({len(failures)} of {len(ran)} controls)", file=sys.stderr)
507
+ return 1
508
+ print(f"operations --self-test: OK ({len(ran)} controls: sections and fences as CommonMark reads them, each "
509
+ f"operation type placed and refused by name, nothing added to the content, the plan held to the files' "
510
+ f"states, and the merge's units and target)")
511
+ return 0
512
+
513
+
514
+ def main(argv):
515
+ if argv[1:] == ["--self-test"]:
516
+ return self_test()
517
+ print(__doc__)
518
+ return 2
519
+
520
+
521
+ if __name__ == "__main__":
522
+ sys.exit(main(sys.argv))