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,227 @@
1
+ """Living specs: requirements, each with a SHALL statement and scenarios."""
2
+
3
+ import re
4
+ from dataclasses import dataclass
5
+
6
+ from waymark.record.outline import (
7
+ collect_sections,
8
+ content,
9
+ parse_facts,
10
+ require_title,
11
+ split_names,
12
+ )
13
+ from waymark.record.problems import Problem
14
+ from waymark.record.text import Document, Section
15
+
16
+ PURPOSE = "Purpose"
17
+ REQUIREMENTS = "Requirements"
18
+ REPOS_FACT = "Repos"
19
+
20
+ _REQUIREMENT = re.compile(r"^Requirement:\s*(\S.*)$")
21
+ _SCENARIO = re.compile(r"^Scenario:\s*(\S.*)$")
22
+ _STEP = re.compile(r"^\s*[-*]\s+(GIVEN|WHEN|THEN|AND|BUT)\b\s*(.*)$")
23
+ _SHALL = re.compile(r"\bSHALL\b")
24
+
25
+
26
+ @dataclass(frozen=True)
27
+ class Scenario:
28
+ """A Given/When/Then example of a requirement."""
29
+
30
+ name: str
31
+ steps: tuple[tuple[str, str], ...]
32
+ index: int
33
+
34
+
35
+ @dataclass(frozen=True)
36
+ class Requirement:
37
+ """One requirement, and where its lines are.
38
+
39
+ ``block`` holds its lines from the heading to its last non-blank line.
40
+ ``extent_end`` also takes in the blank lines that follow it.
41
+ """
42
+
43
+ name: str
44
+ statement: str
45
+ scenarios: tuple[Scenario, ...]
46
+ start: int
47
+ end: int
48
+ extent_end: int
49
+ block: tuple[str, ...]
50
+
51
+ @property
52
+ def key(self) -> str:
53
+ return requirement_key(self.name)
54
+
55
+
56
+ @dataclass(frozen=True)
57
+ class Spec:
58
+ """The living description of one area of the system."""
59
+
60
+ domain: str
61
+ doc: Document
62
+ title: str
63
+ repos: tuple[str, ...]
64
+ purpose: str
65
+ requirements: tuple[Requirement, ...]
66
+ problems: tuple[Problem, ...]
67
+
68
+ def requirement(self, name: str) -> Requirement | None:
69
+ key = requirement_key(name)
70
+ return next((item for item in self.requirements if item.key == key), None)
71
+
72
+
73
+ def requirement_key(name: str) -> str:
74
+ """What a requirement's heading is matched on: its words, ignoring case and spacing."""
75
+ return " ".join(name.split()).casefold()
76
+
77
+
78
+ def named_blocks(
79
+ doc: Document, parent: Section, problems: list[Problem]
80
+ ) -> list[tuple[str, Section]]:
81
+ """The ``Requirement: <name>`` sections directly under a section."""
82
+ sections = doc.sections(parent.heading.level + 1, parent.body_start, parent.end)
83
+ first = sections[0].start if sections else parent.end
84
+ if doc.text_between(parent.body_start, first):
85
+ problems.append(
86
+ Problem(
87
+ doc.path,
88
+ parent.body_start + 1,
89
+ "unexpected-text",
90
+ f'Text under "{parent.title}" must sit inside a "Requirement: <name>" heading.',
91
+ )
92
+ )
93
+ blocks: list[tuple[str, Section]] = []
94
+ for section in sections:
95
+ match = _REQUIREMENT.match(section.title)
96
+ if match is None:
97
+ problems.append(
98
+ Problem(
99
+ doc.path,
100
+ section.start + 1,
101
+ "requirement-format",
102
+ f'"{section.title}" is not a requirement heading. '
103
+ 'Write it as "Requirement: <name>".',
104
+ )
105
+ )
106
+ else:
107
+ blocks.append((match.group(1).strip(), section))
108
+ return blocks
109
+
110
+
111
+ def _parse_scenario(
112
+ doc: Document, name: str, section: Section, problems: list[Problem]
113
+ ) -> Scenario:
114
+ steps: list[tuple[str, str]] = []
115
+ for index in range(section.body_start, section.end):
116
+ line = doc.lines[index]
117
+ if line.is_blank:
118
+ continue
119
+ match = _STEP.match(line.text)
120
+ if match is None:
121
+ problems.append(
122
+ Problem(
123
+ doc.path,
124
+ index + 1,
125
+ "scenario-format",
126
+ "A scenario is a list of GIVEN, WHEN, THEN and AND lines. "
127
+ 'Write this line as "- WHEN ..." or move it out of the scenario.',
128
+ )
129
+ )
130
+ else:
131
+ steps.append((match.group(1), match.group(2).strip()))
132
+ keywords = {keyword for keyword, _ in steps}
133
+ if not {"WHEN", "THEN"} <= keywords:
134
+ problems.append(
135
+ Problem(
136
+ doc.path,
137
+ section.start + 1,
138
+ "scenario-incomplete",
139
+ f'Scenario "{name}" needs at least a "- WHEN ..." and a "- THEN ..." line.',
140
+ )
141
+ )
142
+ return Scenario(name, tuple(steps), section.start)
143
+
144
+
145
+ def parse_requirement(
146
+ doc: Document, name: str, section: Section, problems: list[Problem]
147
+ ) -> Requirement:
148
+ """Read one requirement: its statement and its scenarios."""
149
+ level = section.heading.level + 1
150
+ scenario_sections = doc.sections(level, section.body_start, section.end)
151
+ first = scenario_sections[0].start if scenario_sections else section.end
152
+ statement = doc.text_between(section.body_start, first)
153
+ if not _SHALL.search(statement):
154
+ problems.append(
155
+ Problem(
156
+ doc.path,
157
+ section.start + 1,
158
+ "requirement-without-shall",
159
+ f'Requirement "{name}" needs a statement of what the system SHALL do.',
160
+ )
161
+ )
162
+ scenarios: list[Scenario] = []
163
+ for scenario_section in scenario_sections:
164
+ match = _SCENARIO.match(scenario_section.title)
165
+ if match is None:
166
+ problems.append(
167
+ Problem(
168
+ doc.path,
169
+ scenario_section.start + 1,
170
+ "scenario-format",
171
+ f'"{scenario_section.title}" is not a scenario heading. '
172
+ 'Write it as "Scenario: <name>".',
173
+ )
174
+ )
175
+ else:
176
+ scenarios.append(
177
+ _parse_scenario(doc, match.group(1).strip(), scenario_section, problems)
178
+ )
179
+ if not scenarios:
180
+ problems.append(
181
+ Problem(
182
+ doc.path,
183
+ section.start + 1,
184
+ "requirement-without-scenario",
185
+ f'Requirement "{name}" has no scenario. Add at least one "Scenario: <name>".',
186
+ )
187
+ )
188
+ end = doc.content_end(section.start, section.end)
189
+ block = tuple(line.text for line in doc.lines[section.start : end])
190
+ return Requirement(name, statement, tuple(scenarios), section.start, end, section.end, block)
191
+
192
+
193
+ def parse_requirements(
194
+ doc: Document, parent: Section, problems: list[Problem]
195
+ ) -> tuple[Requirement, ...]:
196
+ """Read every requirement under a section; a heading used twice is a problem."""
197
+ requirements: list[Requirement] = []
198
+ seen: set[str] = set()
199
+ for name, section in named_blocks(doc, parent, problems):
200
+ requirement = parse_requirement(doc, name, section, problems)
201
+ if requirement.key in seen:
202
+ problems.append(
203
+ Problem(
204
+ doc.path,
205
+ section.start + 1,
206
+ "duplicate-requirement",
207
+ f'Requirement "{name}" appears twice. A requirement\'s heading is its key; '
208
+ "rename or merge one of them.",
209
+ )
210
+ )
211
+ seen.add(requirement.key)
212
+ requirements.append(requirement)
213
+ return tuple(requirements)
214
+
215
+
216
+ def parse_spec(domain: str, doc: Document) -> Spec:
217
+ """Read a living spec."""
218
+ problems: list[Problem] = []
219
+ title = require_title(doc, problems)
220
+ facts = parse_facts(doc, {REPOS_FACT}, problems, prose=False)
221
+ repos = split_names(facts[REPOS_FACT].value) if REPOS_FACT in facts else ()
222
+ sections = collect_sections(doc, (PURPOSE, REQUIREMENTS), problems, strict=True)
223
+ purpose = content(doc, sections, PURPOSE, problems)
224
+ requirements: tuple[Requirement, ...] = ()
225
+ if REQUIREMENTS in sections:
226
+ requirements = parse_requirements(doc, sections[REQUIREMENTS], problems)
227
+ return Spec(domain, doc, title, repos, purpose, requirements, tuple(problems))
@@ -0,0 +1,472 @@
1
+ """State, derived from the files on every call. Nothing here is stored.
2
+
3
+ A change's phase, acceptance, progress, conflicts and next step all follow from
4
+ which files exist and what they contain, so the same files always give the same
5
+ state.
6
+ """
7
+
8
+ from collections.abc import Mapping
9
+ from dataclasses import dataclass
10
+ from enum import StrEnum
11
+
12
+ from waymark.record.changes import DESIGN_FILE, PROPOSAL_FILE, SPECS_DIR, TASKS_FILE, Change
13
+ from waymark.record.deltas import delta_is_merged, delta_mismatches
14
+ from waymark.record.explorations import Exploration
15
+ from waymark.record.fingerprint import change_fingerprint
16
+ from waymark.record.links import resolve
17
+ from waymark.record.milestones import Milestone
18
+ from waymark.record.names import parse_archive_name
19
+ from waymark.record.record import ARCHIVE, CHANGES, MILESTONES, Record
20
+ from waymark.record.tasks import Item, RecordKind
21
+ from waymark.record.terms import Phase, ReviewLevel, Verdict
22
+
23
+ ESCALATE_AFTER_CHANGES = 2
24
+ """How many "changes" verdicts on one item send it to the human."""
25
+
26
+
27
+ class AcceptanceState(StrEnum):
28
+ """Whether a change is accepted as it now stands."""
29
+
30
+ MISSING = "missing"
31
+ VALID = "valid"
32
+ WITHDRAWN = "withdrawn"
33
+
34
+
35
+ class ConflictKind(StrEnum):
36
+ """How a change's deltas clash with the specs or with another change.
37
+
38
+ A mismatch is a delta that doesn't apply to its spec as it now stands; it
39
+ blocks the change. An overlap is two active changes naming the same
40
+ requirement; it is reported, and resolved when the first one is archived:
41
+ the other's acceptance is then withdrawn, or its delta becomes a mismatch.
42
+ """
43
+
44
+ MISMATCH = "mismatch"
45
+ OVERLAP = "overlap"
46
+
47
+
48
+ class StepKind(StrEnum):
49
+ """What comes next for a change."""
50
+
51
+ PROPOSE = "propose"
52
+ SPECS = "specs"
53
+ DESIGN = "design"
54
+ TASKS = "tasks"
55
+ RESOLVE_CONFLICT = "resolve-conflict"
56
+ ACCEPT = "accept"
57
+ APPLY = "apply"
58
+ REVIEW = "review"
59
+ RESOLVE_ITEMS = "resolve-items"
60
+ ARCHIVE = "archive"
61
+
62
+
63
+ class RoadmapStatus(StrEnum):
64
+ """Where a roadmap line's change stands."""
65
+
66
+ PLANNED = "planned"
67
+ ACTIVE = "active"
68
+ ARCHIVED = "archived"
69
+ MISSING = "missing"
70
+
71
+
72
+ class ExplorationStatus(StrEnum):
73
+ """Where an exploration went, read from its conclusion."""
74
+
75
+ OPEN = "open"
76
+ PARKED = "parked"
77
+ LED_TO = "led-to"
78
+ UNREADABLE = "unreadable"
79
+
80
+
81
+ @dataclass(frozen=True)
82
+ class Conflict:
83
+ """One clash, with the changes it involves and what to do about it."""
84
+
85
+ kind: ConflictKind
86
+ domain: str
87
+ requirement: str | None
88
+ changes: tuple[str, ...]
89
+ message: str
90
+
91
+
92
+ @dataclass(frozen=True)
93
+ class NextStep:
94
+ """The first thing missing on a change's way to being applied and archived.
95
+
96
+ ``human`` marks the steps only the human can take.
97
+ """
98
+
99
+ kind: StepKind
100
+ item: str | None = None
101
+ human: bool = False
102
+ reason: str = ""
103
+
104
+
105
+ @dataclass(frozen=True)
106
+ class ItemState:
107
+ """Where one task item stands.
108
+
109
+ ``level`` is the review the item now needs: its own level, or independent
110
+ once a reviewer has asked for changes. ``escalated`` says why the item has
111
+ gone to the human, if it has.
112
+ """
113
+
114
+ number: str
115
+ title: str
116
+ level: ReviewLevel
117
+ ticked: bool
118
+ reviewed: bool
119
+ blocked: str | None
120
+ redo: bool
121
+ escalated: str | None
122
+
123
+
124
+ @dataclass(frozen=True)
125
+ class ChangeState:
126
+ """Where one active change stands."""
127
+
128
+ name: str
129
+ owner: str | None
130
+ short_path: bool
131
+ phase: Phase
132
+ acceptance: AcceptanceState
133
+ ticked: int
134
+ total: int
135
+ items: tuple[ItemState, ...]
136
+ conflicts: tuple[Conflict, ...]
137
+ next_step: NextStep
138
+
139
+ @property
140
+ def applied(self) -> bool:
141
+ return self.phase is Phase.APPLIED
142
+
143
+
144
+ @dataclass(frozen=True)
145
+ class RoadmapLine:
146
+ """A roadmap line and the change it points at, if any."""
147
+
148
+ text: str
149
+ change: str | None
150
+ status: RoadmapStatus
151
+
152
+
153
+ @dataclass(frozen=True)
154
+ class MilestoneState:
155
+ """A milestone's member changes, and how many of them are archived."""
156
+
157
+ name: str
158
+ lines: tuple[RoadmapLine, ...]
159
+ archived: int
160
+ total: int
161
+
162
+
163
+ @dataclass(frozen=True)
164
+ class ExplorationState:
165
+ """An exploration's state, and what it led to or why it was parked."""
166
+
167
+ name: str
168
+ status: ExplorationStatus
169
+ detail: str | None
170
+
171
+
172
+ @dataclass(frozen=True)
173
+ class RecordState:
174
+ """The state of everything active in the record."""
175
+
176
+ changes: Mapping[str, ChangeState]
177
+ overlaps: tuple[Conflict, ...]
178
+ milestones: Mapping[str, MilestoneState]
179
+ explorations: Mapping[str, ExplorationState]
180
+
181
+
182
+ def item_state(item: Item, default: ReviewLevel) -> ItemState:
183
+ """Derive one item's state from its tick, its spec gap and its review records.
184
+
185
+ A ``(resolved)`` record closes whatever came before it: verdicts are counted
186
+ from the last one on.
187
+ """
188
+ records = item.records
189
+ last = records[-1] if records else None
190
+ resolved = [index for index, record in enumerate(records) if record.kind is RecordKind.RESOLVED]
191
+ recent = records[resolved[-1] + 1 :] if resolved else records
192
+ changes = sum(1 for record in recent if record.verdict is Verdict.CHANGES)
193
+ ever_changes = any(record.verdict is Verdict.CHANGES for record in records)
194
+ level = ReviewLevel.INDEPENDENT if ever_changes else item.level(default)
195
+
196
+ escalated: str | None = None
197
+ redo = False
198
+ if item.spec_gap is not None:
199
+ escalated = f"the implementer found a spec gap: {item.spec_gap}"
200
+ elif last is not None and last.verdict is Verdict.SPEC_GAP:
201
+ escalated = f"the reviewer found a spec gap: {last.text}"
202
+ elif last is not None and last.verdict is Verdict.CHANGES:
203
+ if changes >= ESCALATE_AFTER_CHANGES:
204
+ escalated = f"a second review asked for changes: {last.text}"
205
+ else:
206
+ redo = True
207
+
208
+ passed = last is not None and last.verdict is Verdict.PASS
209
+ if level is ReviewLevel.NONE:
210
+ reviewed = True
211
+ elif level is ReviewLevel.SELF:
212
+ reviewed = passed or (last is not None and last.kind is RecordKind.SELF_REVIEW)
213
+ else:
214
+ reviewed = passed
215
+ return ItemState(
216
+ number=item.number,
217
+ title=item.title,
218
+ level=level,
219
+ ticked=item.ticked,
220
+ reviewed=item.ticked and reviewed,
221
+ blocked=item.blocked,
222
+ redo=redo,
223
+ escalated=escalated,
224
+ )
225
+
226
+
227
+ def acceptance_state(record: Record, change: Change) -> AcceptanceState:
228
+ """Whether the change has an acceptance, and whether it still covers the change."""
229
+ acceptance = change.proposal.acceptance if change.proposal else None
230
+ if acceptance is None:
231
+ return AcceptanceState.MISSING
232
+ current = change_fingerprint(change, record.specs, record.default_review)
233
+ return AcceptanceState.VALID if acceptance.fingerprint == current else AcceptanceState.WITHDRAWN
234
+
235
+
236
+ def mismatches(record: Record, change: Change) -> tuple[Conflict, ...]:
237
+ """The change's deltas that don't apply to their specs as they now stand.
238
+
239
+ Once a change is synced, its deltas are already in the specs; a mismatch is
240
+ then a spec that has moved on since.
241
+ """
242
+ synced = change.proposal is not None and change.proposal.synced is not None
243
+ found: list[Conflict] = []
244
+ for domain in sorted(change.deltas):
245
+ delta = change.deltas[domain]
246
+ spec = record.specs.get(domain)
247
+ if delta.problems:
248
+ continue
249
+ if synced:
250
+ if not delta_is_merged(spec, delta):
251
+ message = (
252
+ f'The change was synced, but the spec "{domain}" no longer matches its '
253
+ "delta. Revise the delta to match the spec, or remove the "
254
+ '"Synced:" line from the proposal and sync again.'
255
+ )
256
+ found.append(Conflict(ConflictKind.MISMATCH, domain, None, (change.name,), message))
257
+ continue
258
+ found.extend(
259
+ Conflict(ConflictKind.MISMATCH, domain, None, (change.name,), problem.message)
260
+ for problem in delta_mismatches(spec, delta)
261
+ )
262
+ return tuple(found)
263
+
264
+
265
+ def overlaps(record: Record) -> tuple[Conflict, ...]:
266
+ """Requirements that more than one active change adds, modifies or removes."""
267
+ touched: dict[tuple[str, str], tuple[str, set[str]]] = {}
268
+ for name in sorted(record.changes):
269
+ for domain, delta in record.changes[name].deltas.items():
270
+ for key, requirement in delta.touched():
271
+ touched.setdefault((domain, key), (requirement, set()))[1].add(name)
272
+ found: list[Conflict] = []
273
+ for (domain, _), (requirement, names) in sorted(touched.items()):
274
+ if len(names) > 1:
275
+ changes = tuple(sorted(names))
276
+ message = (
277
+ f'{" and ".join(changes)} both change the requirement "{requirement}" in the '
278
+ f'spec "{domain}". Whichever is archived first wins; the other must then be '
279
+ "revised against the new spec and accepted again."
280
+ )
281
+ found.append(Conflict(ConflictKind.OVERLAP, domain, requirement, changes, message))
282
+ return tuple(found)
283
+
284
+
285
+ def _artifact_step(change: Change) -> tuple[Phase, NextStep] | None:
286
+ """The first artifact that is missing or has problems, with the phase reached so far."""
287
+
288
+ def reason(relative: str, missing: str) -> str:
289
+ found = change.problems_in(relative)
290
+ return found[0].message if found else missing
291
+
292
+ proposal = change.proposal
293
+ if proposal is None or change.problems_in(PROPOSAL_FILE):
294
+ step = NextStep(StepKind.PROPOSE, reason=reason(PROPOSAL_FILE, "Draft the proposal."))
295
+ return Phase.PROPOSED, step
296
+
297
+ no_deltas_needed = proposal.no_spec_changes and not change.deltas
298
+ if change.problems_in(SPECS_DIR) or not (change.deltas or no_deltas_needed):
299
+ missing = 'Draft the deltas, or state "No spec changes" under the proposal\'s impact.'
300
+ return Phase.PROPOSED, NextStep(StepKind.SPECS, reason=reason(SPECS_DIR, missing))
301
+
302
+ reached = Phase.SPECIFIED
303
+ if change.problems_in(DESIGN_FILE) or (change.design is None and not change.short_path):
304
+ step = NextStep(StepKind.DESIGN, reason=reason(DESIGN_FILE, "Draft the design."))
305
+ return reached, step
306
+ if not change.short_path:
307
+ reached = Phase.DESIGNED
308
+
309
+ tasks = change.tasks
310
+ if tasks is None or not tasks.items or change.problems_in(TASKS_FILE):
311
+ step = NextStep(StepKind.TASKS, reason=reason(TASKS_FILE, "Draft the task list."))
312
+ return reached, step
313
+ return None
314
+
315
+
316
+ def _item_step(items: tuple[ItemState, ...]) -> NextStep:
317
+ """The next item to apply or review, or what waits on the human."""
318
+ waiting: list[ItemState] = []
319
+ for item in items:
320
+ if item.escalated:
321
+ waiting.append(item)
322
+ elif item.redo:
323
+ return NextStep(
324
+ StepKind.APPLY, item.number, reason="Reopen the item: the review asked for changes."
325
+ )
326
+ elif not item.ticked:
327
+ if item.blocked:
328
+ waiting.append(item)
329
+ else:
330
+ return NextStep(StepKind.APPLY, item.number)
331
+ elif not item.reviewed:
332
+ return NextStep(StepKind.REVIEW, item.number, reason=f"Review level: {item.level}.")
333
+ if waiting:
334
+ first = waiting[0]
335
+ why = first.escalated or f"blocked: {first.blocked}"
336
+ return NextStep(StepKind.RESOLVE_ITEMS, first.number, human=True, reason=why)
337
+ return NextStep(StepKind.ARCHIVE, human=True)
338
+
339
+
340
+ def change_state(
341
+ record: Record, change: Change, record_overlaps: tuple[Conflict, ...] = ()
342
+ ) -> ChangeState:
343
+ """Derive one active change's state."""
344
+ default = record.default_review
345
+ items = tuple(
346
+ item_state(item, default) for item in (change.tasks.items if change.tasks else ())
347
+ )
348
+ blocking = mismatches(record, change)
349
+ conflicts = (*blocking, *(c for c in record_overlaps if change.name in c.changes))
350
+ acceptance = acceptance_state(record, change)
351
+
352
+ ticked = any(item.ticked for item in items)
353
+ drafting = _artifact_step(change)
354
+ if drafting is not None:
355
+ phase, next_step = drafting
356
+ elif acceptance is not AcceptanceState.VALID:
357
+ phase = Phase.PLANNED
358
+ why = (
359
+ "The change was edited after it was accepted, or a spec it changes has moved on."
360
+ if acceptance is AcceptanceState.WITHDRAWN
361
+ else ""
362
+ )
363
+ next_step = NextStep(StepKind.ACCEPT, human=True, reason=why)
364
+ else:
365
+ next_step = _item_step(items)
366
+ if next_step.kind is StepKind.ARCHIVE and not blocking:
367
+ phase = Phase.APPLIED
368
+ else:
369
+ phase = Phase.APPLYING if ticked else Phase.ACCEPTED
370
+ if drafting is None and blocking:
371
+ next_step = NextStep(StepKind.RESOLVE_CONFLICT, reason=blocking[0].message)
372
+
373
+ return ChangeState(
374
+ name=change.name,
375
+ owner=change.proposal.owner if change.proposal else None,
376
+ short_path=change.short_path,
377
+ phase=phase,
378
+ acceptance=acceptance,
379
+ ticked=sum(1 for item in items if item.ticked),
380
+ total=len(items),
381
+ items=items,
382
+ conflicts=tuple(conflicts),
383
+ next_step=next_step,
384
+ )
385
+
386
+
387
+ @dataclass(frozen=True)
388
+ class _Member:
389
+ """The change or milestone a link points into."""
390
+
391
+ name: str
392
+ folder: str
393
+ archived: bool
394
+
395
+
396
+ def _member(doc_path: str, target: str, kind: str) -> _Member | None:
397
+ """Read a link as pointing into a change or milestone folder, active or archived."""
398
+ resolved = resolve(doc_path, target)
399
+ parts = resolved.split("/") if resolved else []
400
+ if len(parts) > 1 and parts[0] == kind and parts[1] != ARCHIVE:
401
+ return _Member(parts[1], "/".join(parts[:2]), archived=False)
402
+ if len(parts) > 2 and parts[0] == kind: # noqa: PLR2004
403
+ archived = parse_archive_name(parts[2])
404
+ if archived is not None:
405
+ return _Member(archived.name, "/".join(parts[:3]), archived=True)
406
+ return None
407
+
408
+
409
+ def milestone_state(record: Record, milestone: Milestone) -> MilestoneState:
410
+ """Derive a milestone's membership and progress from its roadmap's links."""
411
+ lines: list[RoadmapLine] = []
412
+ archived_folders = {entry.path for entry in record.archived_changes}
413
+ roadmap = milestone.roadmap
414
+ for entry in roadmap.entries if roadmap else ():
415
+ member = (
416
+ _member(roadmap.doc.path, entry.target, CHANGES) if roadmap and entry.target else None
417
+ )
418
+ if member is None:
419
+ lines.append(RoadmapLine(entry.text, None, RoadmapStatus.PLANNED))
420
+ elif member.archived:
421
+ found = member.folder in archived_folders
422
+ status = RoadmapStatus.ARCHIVED if found else RoadmapStatus.MISSING
423
+ lines.append(RoadmapLine(entry.text, member.name, status))
424
+ else:
425
+ status = (
426
+ RoadmapStatus.ACTIVE if member.name in record.changes else RoadmapStatus.MISSING
427
+ )
428
+ lines.append(RoadmapLine(entry.text, member.name, status))
429
+ members = [line for line in lines if line.change is not None]
430
+ done = sum(1 for line in members if line.status is RoadmapStatus.ARCHIVED)
431
+ return MilestoneState(milestone.name, tuple(lines), done, len(members))
432
+
433
+
434
+ def exploration_state(record: Record, exploration: Exploration) -> ExplorationState:
435
+ """Derive an exploration's state from its conclusion."""
436
+ if not exploration.conclusion:
437
+ return ExplorationState(exploration.name, ExplorationStatus.OPEN, None)
438
+ if exploration.parked is not None:
439
+ return ExplorationState(exploration.name, ExplorationStatus.PARKED, exploration.parked)
440
+ for target in exploration.conclusion_links:
441
+ for folder in (CHANGES, MILESTONES):
442
+ member = _member(exploration.doc.path, target, folder)
443
+ if member is not None:
444
+ kind = "change" if folder == CHANGES else "milestone"
445
+ return ExplorationState(
446
+ exploration.name, ExplorationStatus.LED_TO, f"{kind} {member.name}"
447
+ )
448
+ return ExplorationState(
449
+ exploration.name,
450
+ ExplorationStatus.UNREADABLE,
451
+ 'The conclusion must be empty, "Parked: <reason>", or a link to a change or milestone.',
452
+ )
453
+
454
+
455
+ def derive_state(record: Record) -> RecordState:
456
+ """Derive the state of every active change, milestone and exploration."""
457
+ record_overlaps = overlaps(record)
458
+ return RecordState(
459
+ changes={
460
+ name: change_state(record, change, record_overlaps)
461
+ for name, change in record.changes.items()
462
+ },
463
+ overlaps=record_overlaps,
464
+ milestones={
465
+ name: milestone_state(record, milestone)
466
+ for name, milestone in record.milestones.items()
467
+ },
468
+ explorations={
469
+ name: exploration_state(record, exploration)
470
+ for name, exploration in record.explorations.items()
471
+ },
472
+ )