waymark-cli 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (92) hide show
  1. waymark/__init__.py +3 -0
  2. waymark/__main__.py +8 -0
  3. waymark/adapters/__init__.py +102 -0
  4. waymark/adapters/claude_code.py +238 -0
  5. waymark/assets/__init__.py +43 -0
  6. waymark/assets/agents/wm-implementer.md +45 -0
  7. waymark/assets/agents/wm-reviewer.md +43 -0
  8. waymark/assets/skills/wm-apply/SKILL.md +58 -0
  9. waymark/assets/skills/wm-archive/SKILL.md +32 -0
  10. waymark/assets/skills/wm-explore/SKILL.md +34 -0
  11. waymark/assets/skills/wm-kickoff/SKILL.md +34 -0
  12. waymark/assets/skills/wm-onboard/SKILL.md +27 -0
  13. waymark/assets/skills/wm-pr/SKILL.md +24 -0
  14. waymark/assets/skills/wm-propose/SKILL.md +32 -0
  15. waymark/assets/skills/wm-update/SKILL.md +31 -0
  16. waymark/cli.py +537 -0
  17. waymark/hooks/__init__.py +6 -0
  18. waymark/hooks/commands.py +190 -0
  19. waymark/hooks/decide.py +314 -0
  20. waymark/hooks/events.py +79 -0
  21. waymark/py.typed +0 -0
  22. waymark/record/__init__.py +5 -0
  23. waymark/record/atlas.py +156 -0
  24. waymark/record/changes.py +202 -0
  25. waymark/record/charter.py +75 -0
  26. waymark/record/commits.py +78 -0
  27. waymark/record/config.py +215 -0
  28. waymark/record/deltas.py +318 -0
  29. waymark/record/design.py +80 -0
  30. waymark/record/edits.py +95 -0
  31. waymark/record/evidence.py +58 -0
  32. waymark/record/explorations.py +66 -0
  33. waymark/record/files.py +75 -0
  34. waymark/record/fingerprint.py +73 -0
  35. waymark/record/git.py +167 -0
  36. waymark/record/githooks.py +106 -0
  37. waymark/record/links.py +104 -0
  38. waymark/record/milestones.py +84 -0
  39. waymark/record/moves.py +60 -0
  40. waymark/record/names.py +39 -0
  41. waymark/record/outline.py +144 -0
  42. waymark/record/pointer.py +56 -0
  43. waymark/record/problems.py +20 -0
  44. waymark/record/project.py +118 -0
  45. waymark/record/proposal.py +171 -0
  46. waymark/record/record.py +340 -0
  47. waymark/record/registry.py +158 -0
  48. waymark/record/specs.py +227 -0
  49. waymark/record/state.py +472 -0
  50. waymark/record/store.py +88 -0
  51. waymark/record/tasks.py +415 -0
  52. waymark/record/templates/charter.md +45 -0
  53. waymark/record/templates/ci-workflow.yml +29 -0
  54. waymark/record/templates/config-atlas.toml +8 -0
  55. waymark/record/templates/config.toml +19 -0
  56. waymark/record/templates/delta.md +29 -0
  57. waymark/record/templates/design.md +20 -0
  58. waymark/record/templates/exploration.md +22 -0
  59. waymark/record/templates/goal.md +13 -0
  60. waymark/record/templates/hook-commit-msg +8 -0
  61. waymark/record/templates/hook-pre-commit +8 -0
  62. waymark/record/templates/proposal.md +18 -0
  63. waymark/record/templates/roadmap.md +4 -0
  64. waymark/record/templates/tasks.md +10 -0
  65. waymark/record/templates.py +30 -0
  66. waymark/record/terms.py +51 -0
  67. waymark/record/text.py +197 -0
  68. waymark/services/__init__.py +1 -0
  69. waymark/services/atlas.py +162 -0
  70. waymark/services/check.py +129 -0
  71. waymark/services/ci.py +44 -0
  72. waymark/services/common.py +154 -0
  73. waymark/services/context.py +296 -0
  74. waymark/services/doctor.py +367 -0
  75. waymark/services/githooks.py +132 -0
  76. waymark/services/instructions.py +304 -0
  77. waymark/services/integration.py +170 -0
  78. waymark/services/lifecycle.py +454 -0
  79. waymark/services/migrations.py +90 -0
  80. waymark/services/pr.py +177 -0
  81. waymark/services/references.py +27 -0
  82. waymark/services/setup.py +127 -0
  83. waymark/views/__init__.py +5 -0
  84. waymark/views/payloads.py +568 -0
  85. waymark/views/render.py +506 -0
  86. waymark/views/schemas.py +413 -0
  87. waymark/views/style.py +102 -0
  88. waymark_cli-0.1.0.dist-info/METADATA +313 -0
  89. waymark_cli-0.1.0.dist-info/RECORD +92 -0
  90. waymark_cli-0.1.0.dist-info/WHEEL +4 -0
  91. waymark_cli-0.1.0.dist-info/entry_points.txt +2 -0
  92. waymark_cli-0.1.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,454 @@
1
+ """The lifecycle: accepting a change, recording evidence, syncing and archiving.
2
+
3
+ Every gate lives here. A refused command changes nothing and says what to do.
4
+ wm writes the evidence itself; these functions are the only way it gets written.
5
+ """
6
+
7
+ import datetime
8
+ from pathlib import Path
9
+
10
+ from waymark.record import git
11
+ from waymark.record.changes import Change
12
+ from waymark.record.deltas import merge_delta
13
+ from waymark.record.edits import edit_item, set_fact, set_outcome
14
+ from waymark.record.fingerprint import change_fingerprint
15
+ from waymark.record.milestones import ROADMAP_FILE
16
+ from waymark.record.moves import rewrite_links, tick_roadmap_lines
17
+ from waymark.record.names import ArchiveName
18
+ from waymark.record.proposal import (
19
+ ACCEPTED,
20
+ SYNCED,
21
+ Proposal,
22
+ format_acceptance,
23
+ format_synced,
24
+ parse_proposal,
25
+ )
26
+ from waymark.record.record import ARCHIVE, CHANGES, MILESTONES, SPECS, Record
27
+ from waymark.record.specs import Spec, parse_spec
28
+ from waymark.record.state import (
29
+ AcceptanceState,
30
+ ChangeState,
31
+ ConflictKind,
32
+ ItemState,
33
+ RoadmapStatus,
34
+ StepKind,
35
+ milestone_state,
36
+ )
37
+ from waymark.record.store import Transaction
38
+ from waymark.record.tasks import BLOCKED, SPEC_GAP, Tasks
39
+ from waymark.record.terms import ReviewLevel, Verdict
40
+ from waymark.record.text import Document
41
+ from waymark.services.common import (
42
+ Done,
43
+ Refusal,
44
+ commit,
45
+ find_change,
46
+ find_item,
47
+ one_line,
48
+ open_record,
49
+ state_of,
50
+ )
51
+
52
+ OVERRIDE_LABEL = "Review override"
53
+ _DRAFTING = (StepKind.PROPOSE, StepKind.SPECS, StepKind.DESIGN, StepKind.TASKS)
54
+
55
+
56
+ def _open(start: Path, name: str) -> tuple[Record, Change, ChangeState]:
57
+ record = open_record(start, writing=True)
58
+ change = find_change(record, name)
59
+ return record, change, state_of(record, change)
60
+
61
+
62
+ def _require_accepted(state: ChangeState) -> None:
63
+ """The accept gate: no item of an unaccepted change is applied."""
64
+ if state.acceptance is AcceptanceState.MISSING:
65
+ raise Refusal(
66
+ f'The change "{state.name}" is not accepted, so its items can\'t be applied yet. '
67
+ f'The human accepts it with "wm accept {state.name}".'
68
+ )
69
+ if state.acceptance is AcceptanceState.WITHDRAWN:
70
+ raise Refusal(
71
+ f'The acceptance of "{state.name}" was withdrawn: the change was edited after it '
72
+ "was accepted, or a spec it changes has moved on. The human accepts it again with "
73
+ f'"wm accept {state.name}".'
74
+ )
75
+
76
+
77
+ def _item_state(state: ChangeState, number: str) -> ItemState:
78
+ return next(item for item in state.items if item.number == number)
79
+
80
+
81
+ def _tasks(change: Change) -> Tasks:
82
+ assert change.tasks is not None
83
+ return change.tasks
84
+
85
+
86
+ def _write_tasks(record: Record, change: Change, text: str) -> tuple[str, ...]:
87
+ transaction = Transaction(record.files)
88
+ transaction.write(_tasks(change).doc.path, text)
89
+ return commit(transaction)
90
+
91
+
92
+ def _with_fact(proposal: Proposal, key: str, line: str) -> Proposal:
93
+ text = set_fact(proposal, key, line)
94
+ return parse_proposal(Document.parse(proposal.doc.path, text))
95
+
96
+
97
+ def accept(start: Path, name: str, today: datetime.date) -> Done:
98
+ """Accept a change: write the acceptance line with the change's fingerprint."""
99
+ record, change, state = _open(start, name)
100
+ step = state.next_step
101
+ if step.kind in _DRAFTING:
102
+ raise Refusal(
103
+ f'The change "{name}" isn\'t ready to accept: its next step is "{step.kind}". '
104
+ f"{step.reason}"
105
+ )
106
+ if step.kind is StepKind.RESOLVE_CONFLICT:
107
+ raise Refusal(f'The change "{name}" has a conflict to resolve first. {step.reason}')
108
+ if state.acceptance is AcceptanceState.VALID:
109
+ return Done(f'The change "{name}" is already accepted as it stands.')
110
+ who = git.user_name(record.project.root)
111
+ if not who:
112
+ raise Refusal(
113
+ "The acceptance records who accepted. Set your name in git: "
114
+ 'git config user.name "<name>".'
115
+ )
116
+ assert change.proposal is not None
117
+ fingerprint = change_fingerprint(change, record.specs, record.default_review)
118
+ text = set_fact(change.proposal, ACCEPTED, format_acceptance(today, who, fingerprint))
119
+ transaction = Transaction(record.files)
120
+ transaction.write(change.proposal.doc.path, text)
121
+ return Done(f'Accepted "{name}". Its items can now be applied.', commit(transaction))
122
+
123
+
124
+ def tick(start: Path, name: str, number: str) -> Done:
125
+ """Tick an item: it has been applied."""
126
+ record, change, state = _open(start, name)
127
+ _require_accepted(state)
128
+ item = find_item(change, number)
129
+ item_state = _item_state(state, number)
130
+ if item.ticked:
131
+ raise Refusal(f"Item {number} is already ticked.")
132
+ if item_state.escalated or item.blocked:
133
+ why = item_state.escalated or f"it is blocked: {item.blocked}"
134
+ raise Refusal(
135
+ f"Item {number} waits on the human: {why}. Once that is settled, run "
136
+ f'"wm resolve {name} {number} "<what was decided>"".'
137
+ )
138
+ if item_state.redo:
139
+ raise Refusal(
140
+ f"A review asked for changes to item {number}. Reopen it first with "
141
+ f'"wm reopen {name} {number}".'
142
+ )
143
+ paths = _write_tasks(record, change, edit_item(_tasks(change), number, ticked=True))
144
+ return Done(f"Ticked item {number} of {name}.", paths)
145
+
146
+
147
+ def _add_stopper(start: Path, name: str, number: str, label: str, text: str) -> Done:
148
+ record, change, state = _open(start, name)
149
+ _require_accepted(state)
150
+ item = find_item(change, number)
151
+ note = one_line(text, "a reason")
152
+ if item.ticked:
153
+ raise Refusal(f"Item {number} is already ticked, so there is nothing left to stop.")
154
+ if label in item.spans:
155
+ raise Refusal(
156
+ f'Item {number} already has a "{label}:" line. Resolve it first with '
157
+ f'"wm resolve {name} {number} "<what was decided>"".'
158
+ )
159
+ paths = _write_tasks(
160
+ record, change, edit_item(_tasks(change), number, add=[f"{label}: {note}"])
161
+ )
162
+ return Done(f'Wrote "{label}: {note}" under item {number} of {name}.', paths)
163
+
164
+
165
+ def block(start: Path, name: str, number: str, reason: str) -> Done:
166
+ """Record that an item is blocked, and why."""
167
+ return _add_stopper(start, name, number, BLOCKED, reason)
168
+
169
+
170
+ def report_gap(start: Path, name: str, number: str, note: str) -> Done:
171
+ """Record that the record wasn't enough to build an item: a spec gap."""
172
+ return _add_stopper(start, name, number, SPEC_GAP, note)
173
+
174
+
175
+ def add_note(start: Path, name: str, number: str, note: str) -> Done:
176
+ """Write a note under an item that is still to be finished, such as a partial result."""
177
+ record, change, state = _open(start, name)
178
+ _require_accepted(state)
179
+ item = find_item(change, number)
180
+ text = one_line(note, "a note")
181
+ if item.ticked:
182
+ raise Refusal(f"Item {number} is already ticked, so there is nothing left to note.")
183
+ paths = _write_tasks(record, change, edit_item(_tasks(change), number, add=[f"Note: {text}"]))
184
+ return Done(f'Wrote "Note: {text}" under item {number} of {name}. It is still to apply.', paths)
185
+
186
+
187
+ def self_review(start: Path, name: str, number: str, summary: str, today: datetime.date) -> Done:
188
+ """Record the planner's own review of an item."""
189
+ record, change, state = _open(start, name)
190
+ _require_accepted(state)
191
+ item = find_item(change, number)
192
+ item_state = _item_state(state, number)
193
+ text = one_line(summary, "a summary of the review")
194
+ if not item.ticked:
195
+ raise Refusal(f"Item {number} isn't ticked yet, so there is nothing to review.")
196
+ if item_state.level is ReviewLevel.NONE:
197
+ raise Refusal(f"Item {number} is at review level none and needs no review record.")
198
+ if item_state.level is ReviewLevel.INDEPENDENT:
199
+ raise Refusal(
200
+ f"Item {number} needs an independent review, so a self-review doesn't count. "
201
+ "Have a reviewer check it and record the verdict."
202
+ )
203
+ if item_state.reviewed:
204
+ raise Refusal(f"Item {number} already has the review record it needs.")
205
+ line = f"(self-review) {today.isoformat()}: {text}"
206
+ paths = _write_tasks(record, change, edit_item(_tasks(change), number, add=[line]))
207
+ return Done(f"Recorded the self-review of item {number} of {name}.", paths)
208
+
209
+
210
+ def verdict(
211
+ start: Path, name: str, number: str, result: Verdict, reasons: str, today: datetime.date
212
+ ) -> Done:
213
+ """Record a reviewer's verdict on an item."""
214
+ record, change, state = _open(start, name)
215
+ _require_accepted(state)
216
+ item = find_item(change, number)
217
+ item_state = _item_state(state, number)
218
+ text = one_line(reasons, "the reviewer's reasons")
219
+ if not item.ticked:
220
+ raise Refusal(f"Item {number} isn't ticked yet, so there is nothing to review.")
221
+ if item_state.redo or item_state.escalated:
222
+ raise Refusal(
223
+ f"Item {number} already has a verdict that is waiting to be dealt with. "
224
+ f'Reopen it ("wm reopen {name} {number}") or resolve it '
225
+ f'("wm resolve {name} {number} "<what was decided>"") first.'
226
+ )
227
+ line = f"(review) {today.isoformat()} {result.value}: {text}"
228
+ paths = _write_tasks(record, change, edit_item(_tasks(change), number, add=[line]))
229
+ return Done(f"Recorded the verdict {result.value} on item {number} of {name}.", paths)
230
+
231
+
232
+ def reopen(start: Path, name: str, number: str, today: datetime.date) -> Done:
233
+ """Reopen an item after a review asked for changes."""
234
+ record, change, state = _open(start, name)
235
+ _require_accepted(state)
236
+ find_item(change, number)
237
+ if not _item_state(state, number).redo:
238
+ raise Refusal(
239
+ f"Item {number} has no review asking for changes that is still open, "
240
+ "so there is nothing to reopen."
241
+ )
242
+ line = f"(reopened) {today.isoformat()}"
243
+ text = edit_item(_tasks(change), number, ticked=False, add=[line])
244
+ paths = _write_tasks(record, change, text)
245
+ return Done(
246
+ f"Reopened item {number} of {name}. It needs an independent review once redone.", paths
247
+ )
248
+
249
+
250
+ def resolve(start: Path, name: str, number: str, decision: str, today: datetime.date) -> Done:
251
+ """Record what was decided about an item that went to the human, and free it."""
252
+ record, change, state = _open(start, name)
253
+ item = find_item(change, number)
254
+ item_state = _item_state(state, number)
255
+ text = one_line(decision, "what was decided")
256
+ if not (item.blocked or item_state.escalated):
257
+ raise Refusal(
258
+ f"Item {number} isn't blocked and nothing about it went to the human, "
259
+ "so there is nothing to resolve."
260
+ )
261
+ line = f"(resolved) {today.isoformat()}: {text}"
262
+ new_text = edit_item(
263
+ _tasks(change), number, ticked=False, remove=[BLOCKED, SPEC_GAP], add=[line]
264
+ )
265
+ paths = _write_tasks(record, change, new_text)
266
+ return Done(f"Resolved item {number} of {name}. It is ready to be applied again.", paths)
267
+
268
+
269
+ def _merge_specs(record: Record, change: Change, transaction: Transaction) -> dict[str, Spec]:
270
+ """Stage every delta's merge; returns the specs as they will read afterwards."""
271
+ specs = dict(record.specs)
272
+ for domain in sorted(change.deltas):
273
+ merged = merge_delta(record.specs.get(domain), change.deltas[domain])
274
+ if merged.text is None:
275
+ raise Refusal(f'The delta for "{domain}" doesn\'t merge: {merged.problems[0].message}')
276
+ path = f"{SPECS}/{domain}.md"
277
+ transaction.write(path, merged.text)
278
+ specs[domain] = parse_spec(domain, Document.parse(path, merged.text))
279
+ return specs
280
+
281
+
282
+ def sync(start: Path, name: str, today: datetime.date) -> Done:
283
+ """Merge an applied change's deltas into the specs without archiving it.
284
+
285
+ The change stays active and accepted: its acceptance is stamped again for
286
+ the specs as they now read, and a ``Synced:`` line marks its deltas as merged.
287
+ """
288
+ record, change, state = _open(start, name)
289
+ if change.proposal is not None and change.proposal.synced is not None:
290
+ raise Refusal(f'The change "{name}" was already synced on {change.proposal.synced}.')
291
+ if not state.applied:
292
+ raise Refusal(
293
+ f'Only an applied change can be synced, and "{name}" is {state.phase}. '
294
+ f'Its next step is "{state.next_step.kind}". {state.next_step.reason}'.rstrip()
295
+ )
296
+ if not change.deltas:
297
+ raise Refusal(f'The change "{name}" has no deltas, so there is nothing to sync.')
298
+ assert change.proposal is not None
299
+ assert change.proposal.acceptance is not None
300
+ transaction = Transaction(record.files)
301
+ specs = _merge_specs(record, change, transaction)
302
+ fingerprint = change_fingerprint(change, specs, record.default_review)
303
+ accepted = change.proposal.acceptance
304
+ proposal = _with_fact(
305
+ change.proposal, ACCEPTED, format_acceptance(accepted.date, accepted.who, fingerprint)
306
+ )
307
+ transaction.write(proposal.doc.path, set_fact(proposal, SYNCED, format_synced(today)))
308
+ domains = ", ".join(sorted(change.deltas))
309
+ return Done(
310
+ f'Synced "{name}" into the specs ({domains}). The change stays active.',
311
+ commit(transaction),
312
+ )
313
+
314
+
315
+ def _archive_gate(state: ChangeState, override: str | None) -> None:
316
+ """The archive gate. Only missing review records can be overridden."""
317
+ name = state.name
318
+ if state.next_step.kind in _DRAFTING or state.acceptance is not AcceptanceState.VALID:
319
+ raise Refusal(
320
+ f'"{name}" can\'t be archived: it is not accepted as it stands (it is '
321
+ f"{state.phase}). This can't be overridden; the human accepts it with "
322
+ f'"wm accept {name}".'
323
+ )
324
+ blocking = [c for c in state.conflicts if c.kind is ConflictKind.MISMATCH]
325
+ if blocking:
326
+ raise Refusal(
327
+ f'"{name}" can\'t be archived: it has a conflict. {blocking[0].message} '
328
+ "This can't be overridden."
329
+ )
330
+ unticked = [item.number for item in state.items if not item.ticked]
331
+ if unticked:
332
+ raise Refusal(
333
+ f'"{name}" can\'t be archived: {_listed(unticked)} not ticked. '
334
+ "This can't be overridden; apply the items first."
335
+ )
336
+ unreviewed = [item.number for item in state.items if not item.reviewed]
337
+ if unreviewed and override is None:
338
+ raise Refusal(
339
+ f'"{name}" can\'t be archived: {_listed(unreviewed)} missing the review record '
340
+ "its level requires. Review the items, or the human can archive anyway with "
341
+ f'"wm archive {name} --override "<reason>"".'
342
+ )
343
+ if override is not None and not unreviewed:
344
+ raise Refusal(
345
+ f'"{name}" has every review record it needs, so there is nothing to override. '
346
+ "Archive it without --override."
347
+ )
348
+
349
+
350
+ def _listed(numbers: list[str]) -> str:
351
+ if len(numbers) == 1:
352
+ return f"item {numbers[0]} is"
353
+ return f"items {', '.join(numbers)} are"
354
+
355
+
356
+ def archive(
357
+ start: Path,
358
+ name: str,
359
+ today: datetime.date,
360
+ *,
361
+ outcome: str | None = None,
362
+ override: str | None = None,
363
+ ) -> Done:
364
+ """Archive a change: merge its deltas, write its outcome, move it to the dated archive."""
365
+ record, change, state = _open(start, name)
366
+ reason = one_line(override, "a reason for the override") if override is not None else None
367
+ _archive_gate(state, reason)
368
+ assert change.proposal is not None
369
+
370
+ existing = change.proposal.outcome
371
+ given = outcome.strip() if outcome else ""
372
+ if given and existing:
373
+ raise Refusal(
374
+ f'The proposal of "{name}" already has an outcome. Drop --outcome, or edit the '
375
+ "outcome in the proposal."
376
+ )
377
+ final = given or existing
378
+ if not final:
379
+ raise Refusal(
380
+ 'Archiving records what came of the change. Pass --outcome "<what happened>", '
381
+ 'or write the "## Outcome" section in the proposal.'
382
+ )
383
+ if reason is not None:
384
+ final += f"\n\n{OVERRIDE_LABEL}: {reason}"
385
+
386
+ source = change.path
387
+ target = f"{CHANGES}/{ARCHIVE}/{ArchiveName(today, name).folder}"
388
+ if record.files.entries(target):
389
+ raise Refusal(
390
+ f'A change named "{name}" was already archived today ({target}). '
391
+ "Archive this one tomorrow, or rename it."
392
+ )
393
+
394
+ transaction = Transaction(record.files)
395
+ if change.proposal.synced is None:
396
+ _merge_specs(record, change, transaction)
397
+ transaction.write(change.proposal.doc.path, set_outcome(change.proposal, final))
398
+ for doc in record.documents():
399
+ staged = transaction.staged(doc.path)
400
+ current = Document.parse(doc.path, staged) if staged is not None else doc
401
+ text = current.text
402
+ if doc.path.endswith(f"/{ROADMAP_FILE}"):
403
+ text = tick_roadmap_lines(current, source)
404
+ current = Document.parse(doc.path, text)
405
+ text = rewrite_links(current, source, target)
406
+ if text != doc.text:
407
+ transaction.write(doc.path, text)
408
+ transaction.move(source, target)
409
+ paths = commit(transaction)
410
+ return Done(f'Archived "{name}" as {target}. Its deltas are now part of the specs.', paths)
411
+
412
+
413
+ def close_milestone(start: Path, name: str, today: datetime.date) -> Done:
414
+ """Close a milestone: move it to the dated archive and rewrite the links to it.
415
+
416
+ Refused while a change its roadmap links to is still active or can't be
417
+ found. Lines for changes that were never proposed don't block.
418
+ """
419
+ record = open_record(start, writing=True)
420
+ milestone = record.milestones.get(name)
421
+ if milestone is None:
422
+ known = ", ".join(sorted(record.milestones)) or "none"
423
+ raise Refusal(f'There is no open milestone "{name}". Open milestones: {known}.')
424
+ lines = milestone_state(record, milestone).lines
425
+ active = [line.change for line in lines if line.status is RoadmapStatus.ACTIVE]
426
+ missing = [line.change for line in lines if line.status is RoadmapStatus.MISSING]
427
+ if active:
428
+ raise Refusal(
429
+ f'The milestone "{name}" stays open: {", ".join(filter(None, active))} '
430
+ "is still active. Archive it first, or take its line off the roadmap."
431
+ )
432
+ if missing:
433
+ raise Refusal(
434
+ f'The milestone "{name}" stays open: its roadmap links to '
435
+ f"{', '.join(filter(None, missing))}, which can't be found. Fix the link, or "
436
+ "take the line off the roadmap."
437
+ )
438
+ source = milestone.path
439
+ target = f"{MILESTONES}/{ARCHIVE}/{ArchiveName(today, name).folder}"
440
+ if record.files.entries(target):
441
+ raise Refusal(
442
+ f'A milestone named "{name}" was already closed today ({target}). '
443
+ "Close this one tomorrow, or rename it."
444
+ )
445
+ transaction = Transaction(record.files)
446
+ for doc in record.documents():
447
+ text = rewrite_links(doc, source, target)
448
+ if text != doc.text:
449
+ transaction.write(doc.path, text)
450
+ transaction.move(source, target)
451
+ paths = commit(transaction)
452
+ dropped = [line.text for line in lines if line.status is RoadmapStatus.PLANNED]
453
+ note = f" Never proposed: {'; '.join(dropped)}." if dropped else ""
454
+ return Done(f'Closed the milestone "{name}" as {target}.{note}', paths)
@@ -0,0 +1,90 @@
1
+ """Migrations: moving a record from one format to the next.
2
+
3
+ Each migration upgrades the record by exactly one format number. It is
4
+ deterministic, and it is applied together with the new format number or not at
5
+ all. Migrations run only when asked for; nothing here runs on its own.
6
+ """
7
+
8
+ import tomllib
9
+ from collections.abc import Callable, Sequence
10
+ from dataclasses import dataclass
11
+
12
+ from waymark.record.config import CONFIG_FILE, RECORD_FORMAT
13
+ from waymark.record.edits import set_record_format
14
+ from waymark.record.files import RecordFiles
15
+ from waymark.record.store import Transaction
16
+ from waymark.services.common import Refusal, commit
17
+
18
+
19
+ @dataclass(frozen=True)
20
+ class Migration:
21
+ """One step: from format ``source`` to ``source + 1``.
22
+
23
+ ``apply`` reads the record through the files and stages its writes in the
24
+ transaction; it never writes on its own.
25
+ """
26
+
27
+ source: int
28
+ summary: str
29
+ apply: Callable[[RecordFiles, Transaction], None]
30
+
31
+
32
+ MIGRATIONS: tuple[Migration, ...] = ()
33
+ """Every migration this version knows. Format 1 is the first, so there are none yet."""
34
+
35
+
36
+ def stored_format(files: RecordFiles) -> int:
37
+ """The format number in the settings, read without judging the other settings."""
38
+ text = files.read(CONFIG_FILE, [])
39
+ try:
40
+ value = tomllib.loads(text or "").get("record_format")
41
+ except tomllib.TOMLDecodeError:
42
+ value = None
43
+ if not isinstance(value, int) or isinstance(value, bool) or value < 1:
44
+ raise Refusal(
45
+ f'{CONFIG_FILE} has no usable "record_format" number, so wm can\'t tell which '
46
+ "format the record is in. Restore the line; it is written by wm."
47
+ )
48
+ return value
49
+
50
+
51
+ def pending(
52
+ current: int, migrations: Sequence[Migration] = MIGRATIONS, target: int = RECORD_FORMAT
53
+ ) -> tuple[Migration, ...]:
54
+ """The migrations that take a record from its format to the target, in order."""
55
+ if current > target:
56
+ raise Refusal(
57
+ f"The record is in format {current}, which is newer than this wm writes "
58
+ f"(format {target}). Install the wm version the project is pinned to."
59
+ )
60
+ by_source = {migration.source: migration for migration in migrations}
61
+ chain: list[Migration] = []
62
+ for number in range(current, target):
63
+ if number not in by_source:
64
+ raise Refusal(
65
+ f"There is no migration from record format {number} to {number + 1}. "
66
+ "This is a fault in wm; please report it."
67
+ )
68
+ chain.append(by_source[number])
69
+ return tuple(chain)
70
+
71
+
72
+ def migrate(
73
+ files: RecordFiles,
74
+ migrations: Sequence[Migration] = MIGRATIONS,
75
+ target: int = RECORD_FORMAT,
76
+ ) -> tuple[str, ...]:
77
+ """Run every pending migration; returns what each one did.
78
+
79
+ Each step and its new format number are written together, so a failure
80
+ leaves the record in the last format that fully applied.
81
+ """
82
+ done: list[str] = []
83
+ for migration in pending(stored_format(files), migrations, target):
84
+ transaction = Transaction(files)
85
+ migration.apply(files, transaction)
86
+ config = transaction.staged(CONFIG_FILE) or files.read(CONFIG_FILE, []) or ""
87
+ transaction.write(CONFIG_FILE, set_record_format(config, migration.source + 1))
88
+ commit(transaction)
89
+ done.append(f"format {migration.source} to {migration.source + 1}: {migration.summary}")
90
+ return tuple(done)