@softure-ai/skills 0.20.0 → 0.22.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.
@@ -0,0 +1,530 @@
1
+ #!/usr/bin/env python3
2
+ """softure-doctor --sweep: every remaining failure as a worklist entry with the evidence to settle it.
3
+
4
+ doctor.py --sweep [--json] [--root <dir>]
5
+ npx softure-skills doctor --sweep [--json]
6
+
7
+ Read-only. One entry per thing to settle (an unticked Progress item, a Summary placeholder, an open
8
+ row, an open owner check, ...), each with `path`, `line` and the exact `text` of the line, the
9
+ evidence found in the repository, and how to settle it:
10
+
11
+ archived-change-progress commits that touched the phase's files after the plan's date, the SHA
12
+ ticked items of the same phase cite, and the change's merge commit
13
+ archived-roadmap-summary the merge (or squash) commit of the item's change on the main branch
14
+ archived-roadmap-open-items the item's archived change folder, merge commit, the release that
15
+ contains it, and later roadmaps that mention the item
16
+ archived-roadmap-open-checks the same for the item the check names, plus the first release after
17
+ the roadmap was closed
18
+ anything else the file to fix (and `--fix` for the mechanical shapes)
19
+
20
+ Every entry has a `class`:
21
+
22
+ evidence the repository holds evidence that settles it (above); the agent settles it with that proof
23
+ superseded no direct evidence, but later work made it obsolete: for an owner check or open row of an
24
+ archived roadmap, a later roadmap was closed and a release shipped after it, or the same
25
+ item ID or file area appears in a later archived change; for a Progress item, a later
26
+ phase of the same plan is ticked (or a later archived change has the item's area). The
27
+ agent closes it as `obsolete: superseded by <ref>` itself, never forwards it
28
+ owner only the owner can settle it: a decision about future work, a secret, account or connector,
29
+ or a step outside the repository whose effect the agent cannot see (`owner_reason` says
30
+ which; `unsettled` when nothing at all was found), with `tried`: what the sweep looked for
31
+
32
+ `"owner": true` marks the owner class. The skill section "Sweep history to zero" tells an agent how to
33
+ work the list: settle every entry with its evidence, never without.
34
+
35
+ Importable: `from doctor_sweep import sweep`.
36
+ """
37
+ from __future__ import annotations
38
+
39
+ import os
40
+ import re
41
+ import subprocess
42
+ import sys
43
+
44
+ sys.dont_write_bytecode = True
45
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
46
+ from context_state import ( # noqa: E402
47
+ ARCHIVE_ROADMAPS_DIR, OWNER_SECTION, QUEUED_DIR, RELEASE_LINE_RE, RELEASE_SECTION, ROADMAP_PATH, CHECKBOX_RE,
48
+ ITEM_REF_RE, SECRET_RE, archived_roadmap_files, frontmatter, pending_release_roadmap, roadmap_rows, sections,
49
+ )
50
+
51
+ SHA_TAIL_RE = re.compile(r"\b([0-9a-f]{7,40})\b")
52
+ PATH_RE = re.compile(r"`((?:[\w.-]+/)+[\w.-]+\.\w+|[\w.-]+\.(?:ts|tsx|js|jsx|mjs|py|cs|go|rs|java|kt|rb|php|sql|css|scss|html|json|yml|yaml|sh))`")
53
+ SEMVER_TAG_RE = re.compile(r"^v?\d+\.\d+\.\d+")
54
+ AREA_RE = re.compile(r"`((?:\.{0,2}/)?(?:[\w.@-]+/)+[\w.@-]*)`")
55
+ LIMIT = 3
56
+
57
+ # What only the owner can settle (WORKFLOW §12.4); everything else is the agent's.
58
+ OWNER_KINDS = (
59
+ ("decision", re.compile(r"\b(?:decide|decision|choose|agree on|sign[- ]off)\b", re.IGNORECASE)),
60
+ ("secret", re.compile(SECRET_RE.pattern + r"|\b(?:accounts?|connectors?|oauth|dns|domains?|certificates?|billing"
61
+ r"|subscriptions?|licen[cs]es?)\b|`[A-Z][A-Z0-9]*_[A-Z0-9_]+`", re.IGNORECASE)),
62
+ ("outside", re.compile(r"\b(?:in production|on production|production (?:environment|settings?)|in staging"
63
+ r"|app store|play store|real (?:phone|device)|with the (?:client|customer|vendor)"
64
+ r"|support ticket|by (?:e-?mail|phone) to)\b", re.IGNORECASE)),
65
+ )
66
+
67
+ SETTLE = {
68
+ "archived-change-progress": "tick it with the SHA that did it (`- [x] <text> — <sha>`), or, when the work was "
69
+ "never done, `- [x] ~~<text>~~ — dropped: <reason>`",
70
+ "archived-roadmap-summary": "put the merge SHA into the row's Merge cell (a release tag where the roadmap records "
71
+ "a release instead; `carried`, `dropped` or `— <reason>` for a row with no merge)",
72
+ "archived-roadmap-open-items": "set the row's status to `done` when the evidence shows it shipped, "
73
+ "`carried (to <path>)` when a later roadmap took it, or `dropped (<reason>)`",
74
+ "archived-roadmap-open-checks": "tick it with its evidence (`— done: <sha | release | path>`), as obsolete "
75
+ "(`— obsolete: <reason>`), or carry it to a live roadmap or an owner-word issue "
76
+ "and tick it with where it went (`— carried to <path | #N>`)",
77
+ }
78
+
79
+ SETTLE_SUPERSEDED = {
80
+ "archived-change-progress": "close it yourself: `- [x] <text> — obsolete: superseded by <ref>` (never forward it)",
81
+ "archived-roadmap-open-items": "set the row's status to `dropped (obsolete: superseded by <ref>)` (never forward it)",
82
+ "archived-roadmap-open-checks": "close it yourself: `- [x] <text> — obsolete: superseded by <ref>` "
83
+ "(never forward it to the owner)",
84
+ }
85
+
86
+ SETTLE_OWNER = {
87
+ "archived-roadmap-open-checks": "the owner's: carry it to the live roadmap's `## Owner decisions and checks` (or "
88
+ "an owner-word issue) and tick it `— carried to <path | #N>`",
89
+ "archived-change-status": "mechanical: `doctor --fix --write`",
90
+ "index-missing-file": "point the row at the file's current path, or drop the row",
91
+ "roadmap-archived-not-removed": "remove roadmap.md (the close moved it)",
92
+ "roadmap-status-mismatch": "set `status` to match the rows",
93
+ "queued-roadmap-done": "archive the finished queued roadmap to foundation/archive/",
94
+ "backlog-without-roadmap": "move live entries to a queued roadmap, then remove the folder",
95
+ "state-missing": "`npx softure-skills state`, commit context/state.json",
96
+ "state-stale": "`npx softure-skills state`, commit context/state.json",
97
+ }
98
+
99
+
100
+ class Git:
101
+ """Read-only questions to the repository's history; every answer is [] without full history."""
102
+
103
+ def __init__(self, root: str | None) -> None:
104
+ self.root = root
105
+ self.usable = False
106
+ self.shallow = False
107
+ if root:
108
+ probe = self._run("rev-parse", "--is-shallow-repository")
109
+ self.usable = probe.returncode == 0
110
+ self.shallow = probe.stdout.strip() == "true"
111
+
112
+ def _run(self, *args: str) -> subprocess.CompletedProcess:
113
+ return subprocess.run(["git", "-C", self.root or ".", *args], capture_output=True, text=True)
114
+
115
+ def _commits(self, *args: str) -> list[dict]:
116
+ if not self.usable:
117
+ return []
118
+ out = self._run("log", "--format=%h%x09%ad%x09%s", "--date=short", *args)
119
+ commits = []
120
+ for line in out.stdout.splitlines():
121
+ parts = line.split("\t", 2)
122
+ if len(parts) == 3:
123
+ commits.append({"sha": parts[0], "date": parts[1], "subject": parts[2]})
124
+ return commits
125
+
126
+ def touching(self, files: list[str], since: str | None) -> list[dict]:
127
+ if not files:
128
+ return []
129
+ args = ["--no-merges", f"-n{LIMIT}"] + ([f"--since={since}"] if since else []) + ["--", *files]
130
+ return self._commits(*args)
131
+
132
+ def merges_for(self, change_id: str | None) -> list[dict]:
133
+ """First-parent commits of the main line that name the change (merge commits and squash merges)."""
134
+ if not change_id:
135
+ return []
136
+ return self._commits("--first-parent", "-i", "--fixed-strings", f"--grep={change_id}", f"-n{LIMIT}")
137
+
138
+ def release_containing(self, sha: str) -> str | None:
139
+ if not self.usable:
140
+ return None
141
+ out = self._run("tag", "--contains", sha, "--sort=v:refname")
142
+ tags = [tag for tag in out.stdout.split() if SEMVER_TAG_RE.match(tag)]
143
+ return tags[0] if tags else None
144
+
145
+ def release_after(self, day: str | None, strict: bool = False) -> dict | None:
146
+ """The first release tag created on or after `day` (after it, with `strict`)."""
147
+ if not self.usable or not day:
148
+ return None
149
+ out = self._run("for-each-ref", "--sort=creatordate", "--format=%(refname:short)\t%(creatordate:short)",
150
+ "refs/tags")
151
+ for line in out.stdout.splitlines():
152
+ tag, _, date = line.partition("\t")
153
+ if SEMVER_TAG_RE.match(tag) and (date > day if strict else date >= day):
154
+ return {"tag": tag, "date": date}
155
+ return None
156
+
157
+
158
+ def _evidence(kind: str, ref: str, note: str) -> dict:
159
+ return {"kind": kind, "ref": ref, "note": note}
160
+
161
+
162
+ def _commit_evidence(commits: list[dict], note: str) -> list[dict]:
163
+ return [_evidence("commit", c["sha"], f"{note}: {c['date']} {c['subject']}") for c in commits]
164
+
165
+
166
+ def _lines(text: str) -> list[str]:
167
+ return (text or "").split("\n")
168
+
169
+
170
+ def _archived_change_folder(reader, change_id: str | None) -> str | None:
171
+ if not change_id:
172
+ return None
173
+ for name, is_dir in reader.listdir("context/archive"):
174
+ if is_dir and re.sub(r"^\d{4}-\d{2}-\d{2}-", "", name) == change_id:
175
+ return f"context/archive/{name}"
176
+ return None
177
+
178
+
179
+ def _date_of(path: str, meta: dict) -> str | None:
180
+ match = re.search(r"(\d{4}-\d{2}-\d{2})", os.path.basename(path.rstrip("/")))
181
+ return meta.get("created") or meta.get("updated") or (match.group(1) if match else None)
182
+
183
+
184
+ def _later_mentions(reader, path: str, needles: list[str]) -> list[dict]:
185
+ """Roadmaps other than `path` (later archived ones, queued, the live one) that mention a needle."""
186
+ candidates = [p for p in archived_roadmap_files(reader) if p > path]
187
+ candidates += [f"{QUEUED_DIR}/{name}" for name, is_dir in reader.listdir(QUEUED_DIR)
188
+ if not is_dir and name.endswith(".md")]
189
+ candidates.append(ROADMAP_PATH)
190
+ found = []
191
+ for candidate in candidates:
192
+ text = reader.read(candidate)
193
+ if text is None:
194
+ continue
195
+ for number, line in enumerate(_lines(text), start=1):
196
+ if any(needle and re.search(r"(?<![\w-])" + re.escape(needle) + r"(?![\w-])", line)
197
+ for needle in needles):
198
+ found.append(_evidence("file", f"{candidate}:{number}", line.strip()[:160]))
199
+ break
200
+ return found
201
+
202
+
203
+ def _item_evidence(reader, git: Git, path: str, item: str | None, change_id: str | None) -> list[dict]:
204
+ evidence: list[dict] = []
205
+ folder = _archived_change_folder(reader, change_id)
206
+ if folder:
207
+ evidence.append(_evidence("file", folder + "/", "the item's change was archived"))
208
+ merges = git.merges_for(change_id)
209
+ evidence += _commit_evidence(merges, "merge of the item's change")
210
+ for commit in merges[:1]:
211
+ release = git.release_containing(commit["sha"])
212
+ if release:
213
+ evidence.append(_evidence("release", release, f"the first release that contains {commit['sha']}"))
214
+ evidence += _later_mentions(reader, path, [item, change_id] if item else [change_id])
215
+ return evidence
216
+
217
+
218
+ def owner_kind(text: str) -> str | None:
219
+ """`decision`, `secret` or `outside` when the line is something only the owner can settle; None otherwise."""
220
+ for kind, pattern in OWNER_KINDS:
221
+ if pattern.search(text or ""):
222
+ return kind
223
+ return None
224
+
225
+
226
+ def _entry(code: str, path: str, line: int | None, text: str, subject: str, evidence: list[dict],
227
+ superseded: list[dict] | None = None, tried: list[str] | None = None, owner_text: str | None = None,
228
+ **extra) -> dict:
229
+ """One worklist entry, classed `evidence`, `superseded` or `owner` (in that order of proof).
230
+
231
+ `owner_text` (the line, for checks and Progress items) lets a decision, a secret or a step outside the
232
+ repository stay the owner's even when later work exists; anything else without direct evidence is
233
+ superseded when later work made it obsolete, and the owner's (`unsettled`) only when nothing was found.
234
+ """
235
+ kind = owner_kind(owner_text) if owner_text is not None else None
236
+ if evidence:
237
+ klass, reason, settle = "evidence", None, SETTLE.get(code, "fix the file it names")
238
+ elif kind:
239
+ klass, reason, settle = "owner", kind, SETTLE_OWNER.get(code, SETTLE.get(code, "fix the file it names"))
240
+ elif superseded:
241
+ klass, reason, settle = "superseded", None, SETTLE_SUPERSEDED.get(code, SETTLE.get(code, "fix the file it names"))
242
+ evidence = superseded
243
+ else:
244
+ klass, reason, settle = "owner", "unsettled", SETTLE.get(code, "fix the file it names")
245
+ return {"code": code, "path": path, "line": line, "text": text, "subject": subject, "evidence": evidence,
246
+ "class": klass, "owner": klass == "owner", "owner_reason": reason,
247
+ "tried": [] if klass == "evidence" else (tried or []), "settle": settle, **extra}
248
+
249
+
250
+ # ---------------------------------------------------------------- superseded
251
+
252
+
253
+ def _areas(text: str) -> list[str]:
254
+ """File areas a line names: the folder of each backticked path (`src/booking/page.tsx` -> `src/booking/`)."""
255
+ areas = []
256
+ for path in AREA_RE.findall(text or "") + PATH_RE.findall(text or ""):
257
+ folder = path if path.endswith("/") else (os.path.dirname(path) + "/" if "/" in path else "")
258
+ if folder and folder not in areas and folder.strip("./"):
259
+ areas.append(folder.lstrip("./") if folder.startswith("./") else folder)
260
+ return areas
261
+
262
+
263
+ def _later_changes(reader, day: str | None, needles: list[str], exclude: str | None = None) -> list[dict]:
264
+ """Archived changes dated after `day` whose change.md or plan.md names an item ID, change ID or file area."""
265
+ needles = [needle for needle in needles if needle]
266
+ if not day or not needles:
267
+ return []
268
+ found = []
269
+ for name, is_dir in sorted(reader.listdir("context/archive")):
270
+ date = re.match(r"^(\d{4}-\d{2}-\d{2})-", name)
271
+ folder = f"context/archive/{name}"
272
+ if not is_dir or not date or date.group(1) <= day or folder == exclude:
273
+ continue
274
+ for rel in ("change.md", "plan.md"):
275
+ text = reader.read(f"{folder}/{rel}") or ""
276
+ hit = next((needle for needle in needles
277
+ if re.search(r"(?<![\w-])" + re.escape(needle) + (r"" if needle.endswith("/") else r"(?![\w-])"),
278
+ text)), None)
279
+ if hit:
280
+ found.append(_evidence("file", f"{folder}/", f"a later archived change on the same "
281
+ f"{'area' if hit.endswith('/') else 'item'} (`{hit}`)"))
282
+ break
283
+ if found:
284
+ break
285
+ return found
286
+
287
+
288
+ def _later_release(reader, git: Git, day: str, later: list[str]) -> dict | None:
289
+ """The first release after `day`: a release tag, else a `Release:` line of a later archived roadmap."""
290
+ tag = git.release_after(day, strict=True)
291
+ if tag:
292
+ return _evidence("release", tag["tag"], f"released {tag['date']}, after {day}")
293
+ for path in later:
294
+ for line in sections(reader.read(path) or "").get("Summary", []):
295
+ match = RELEASE_LINE_RE.match(line.strip())
296
+ if match and (match.group("date") or "9999") > day:
297
+ return _evidence("release", match.group("version"), f"released {match.group('date') or 'later'}, "
298
+ f"recorded in {path}")
299
+ return None
300
+
301
+
302
+ def _superseded_roadmap_entry(reader, git: Git, path: str, text: str, needles: list[str]) -> tuple[list, list]:
303
+ """(superseded evidence, what was tried) for an open check or row of the archived roadmap `path`."""
304
+ closed_on = _date_of(path, frontmatter(reader.read(path) or "")) or ""
305
+ later = [p for p in archived_roadmap_files(reader) if p > path and roadmap_rows(reader.read(p) or "")]
306
+ tried = []
307
+ evidence: list[dict] = []
308
+ release = _later_release(reader, git, closed_on, later) if later else None
309
+ if later and release:
310
+ evidence = [_evidence("file", later[0], f"a later roadmap, closed after {closed_on}"), release]
311
+ tried.append(f"a later closed roadmap: {later[0] if later else 'none'}; a release after {closed_on}: "
312
+ f"{release['ref'] if release else 'none'}")
313
+ areas = _areas(text)
314
+ if not evidence:
315
+ evidence = _later_changes(reader, closed_on, needles + areas)
316
+ tried.append(f"later archived changes naming {', '.join(f'`{n}`' for n in needles + areas) or 'its item or area'}: "
317
+ + ("found" if evidence else "none"))
318
+ if git.shallow:
319
+ tried.append("the history is a shallow clone; `git fetch --deepen <n>` may find more")
320
+ return evidence, tried
321
+
322
+
323
+ # ---------------------------------------------------------------- per failure code
324
+
325
+
326
+ def _progress_entries(reader, git: Git, path: str) -> list[dict]:
327
+ import doctor
328
+
329
+ text = reader.read(path) or ""
330
+ folder = os.path.dirname(path)
331
+ change = frontmatter(reader.read(f"{folder}/change.md") or "")
332
+ change_id = change.get("change_id") or re.sub(r"^\d{4}-\d{2}-\d{2}-", "", os.path.basename(folder))
333
+ since = _date_of(folder, change)
334
+ phase_files: dict[str, list[str]] = {}
335
+ current = None
336
+ for line in _lines(text):
337
+ heading = re.match(r"^## Phase (\d+)", line)
338
+ if heading:
339
+ current = heading.group(1)
340
+ continue
341
+ if line.startswith("## "):
342
+ current = None
343
+ if current:
344
+ phase_files.setdefault(current, []).extend(PATH_RE.findall(line))
345
+ open_items = set(doctor.unticked_automated(text))
346
+ entries = []
347
+ in_progress = False
348
+ phase = None
349
+ phase_shas: dict[str, list[str]] = {}
350
+ phase_marks: dict[str, list[bool]] = {}
351
+ phase_lines: dict[str, int] = {}
352
+ pending: list[tuple[int, str, str, str]] = []
353
+ for number, line in enumerate(_lines(text), start=1):
354
+ if line.startswith("## "):
355
+ in_progress = line[3:].strip() == "Progress"
356
+ continue
357
+ if not in_progress:
358
+ continue
359
+ heading = re.match(r"^### Phase (\d+)", line)
360
+ if heading:
361
+ phase = heading.group(1)
362
+ phase_lines.setdefault(phase, number)
363
+ continue
364
+ box = CHECKBOX_RE.match(line)
365
+ if not box:
366
+ continue
367
+ phase_marks.setdefault(phase or "", []).append(box.group("mark") != " ")
368
+ if box.group("mark") != " ":
369
+ tail = line.rsplit(" — ", 1)[-1] if " — " in line else ""
370
+ phase_shas.setdefault(phase or "", []).extend(SHA_TAIL_RE.findall(tail))
371
+ elif box.group("text").strip() in open_items:
372
+ pending.append((number, line, box.group("text").strip(), phase or ""))
373
+ merges = git.merges_for(change_id)
374
+ for number, line, subject, phase in pending:
375
+ evidence = [_evidence("commit", sha, f"cited by a ticked item of phase {phase}")
376
+ for sha in dict.fromkeys(phase_shas.get(phase, []))]
377
+ files = sorted(set(phase_files.get(phase, [])))
378
+ evidence += _commit_evidence(git.touching(files, since), f"touched {', '.join(files)} after {since}")
379
+ evidence += _commit_evidence(merges, "merge of the change")
380
+ later = [p for p, marks in phase_marks.items() if p.isdigit() and phase.isdigit() and int(p) > int(phase)
381
+ and marks and all(marks)]
382
+ superseded = [_evidence("file", f"{path}:{phase_lines[p]}", f"phase {p}, later in the same plan, is ticked")
383
+ for p in sorted(later, key=int)[:1]]
384
+ tried = [f"commits citing or touching phase {phase or '?'} and merges naming `{change_id}`: none",
385
+ f"a later phase of the plan, all ticked: {'phase ' + later[0] if later else 'none'}"]
386
+ if not superseded:
387
+ superseded = _later_changes(reader, since, _areas(subject), exclude=folder)
388
+ tried.append(f"later archived changes on its area ({', '.join(_areas(subject)) or 'no area named'}): "
389
+ + ("found" if superseded else "none"))
390
+ if git.shallow:
391
+ tried.append("the history is a shallow clone; `git fetch --deepen <n>` may find more")
392
+ entries.append(_entry("archived-change-progress", path, number, line, subject, evidence,
393
+ superseded=superseded, tried=tried, owner_text=subject))
394
+ return entries
395
+
396
+
397
+ def _roadmap_rows_by_id(text: str) -> dict[str, dict]:
398
+ return {row["id"]: row for row in roadmap_rows(text)}
399
+
400
+
401
+ def _summary_entries(reader, git: Git, path: str) -> list[dict]:
402
+ import doctor
403
+
404
+ text = reader.read(path) or ""
405
+ rows = _roadmap_rows_by_id(text)
406
+ entries = []
407
+ for row in doctor.summary_rows(text):
408
+ if row["ok"]:
409
+ continue
410
+ item, cell = row["item"], row["cell"]
411
+ change_id = (rows.get(item) or {}).get("change_id")
412
+ evidence = _commit_evidence(git.merges_for(change_id), "merge of the item's change")
413
+ folder = _archived_change_folder(reader, change_id)
414
+ if folder:
415
+ shas = SHA_TAIL_RE.findall(reader.read(f"{folder}/plan.md") or "")
416
+ if shas:
417
+ evidence.append(_evidence("commit", shas[-1], f"last SHA in {folder}/plan.md (not a merge; prefer the merge)"))
418
+ entries.append(_entry("archived-roadmap-summary", path, row["line"], row["text"], f"{item}: {cell}", evidence,
419
+ cell=cell, item=item, change_id=change_id))
420
+ return entries
421
+
422
+
423
+ def _open_item_entries(reader, git: Git, path: str) -> list[dict]:
424
+ import doctor
425
+
426
+ text = reader.read(path) or ""
427
+ entries = []
428
+ rows = {row["id"]: row for row in roadmap_rows(text) if row["status"] not in doctor.CLOSED_STATUSES}
429
+ for number, line in enumerate(_lines(text), start=1):
430
+ match = re.match(r"^\|\s*\*\*([A-Z]+-\d+)\*\*\s*\|", line)
431
+ if not match or match.group(1) not in rows:
432
+ continue
433
+ row = rows.pop(match.group(1))
434
+ status = [cell.strip() for cell in line.strip().strip("|").split("|")][-1]
435
+ evidence = _item_evidence(reader, git, path, row["id"], row["change_id"])
436
+ superseded, tried = ([], []) if evidence else _superseded_roadmap_entry(
437
+ reader, git, path, line, [row["id"], row["change_id"]])
438
+ entries.append(_entry("archived-roadmap-open-items", path, number, line, f"{row['id']} ({row['status']})",
439
+ evidence, superseded=superseded, tried=tried, item=row["id"],
440
+ change_id=row["change_id"], status=status))
441
+ return entries
442
+
443
+
444
+ def _open_check_entries(reader, git: Git, path: str) -> list[dict]:
445
+ text = reader.read(path) or ""
446
+ rows = _roadmap_rows_by_id(text)
447
+ include_release = path != pending_release_roadmap(reader)
448
+ wanted = {OWNER_SECTION} | ({RELEASE_SECTION} if include_release else set())
449
+ closed_on = _date_of(path, frontmatter(text))
450
+ release = git.release_after(closed_on)
451
+ entries = []
452
+ section = None
453
+ for number, line in enumerate(_lines(text), start=1):
454
+ if line.startswith("## "):
455
+ section = line[3:].strip()
456
+ continue
457
+ box = CHECKBOX_RE.match(line)
458
+ if section not in wanted or not box or box.group("mark") != " ":
459
+ continue
460
+ ref = ITEM_REF_RE.search(line)
461
+ item = ref.group("id") if ref else None
462
+ change_id = (rows.get(item) or {}).get("change_id") if item else None
463
+ evidence = _item_evidence(reader, git, path, item, change_id) if item else []
464
+ if release and section == RELEASE_SECTION:
465
+ evidence.append(_evidence("release", release["tag"], f"released {release['date']}, after the close"))
466
+ superseded, tried = ([], []) if evidence else _superseded_roadmap_entry(
467
+ reader, git, path, line, [item, change_id] if item else [])
468
+ entries.append(_entry("archived-roadmap-open-checks", path, number, line, box.group("text").strip(),
469
+ evidence, superseded=superseded, tried=tried, owner_text=box.group("text"),
470
+ item=item, change_id=change_id, section=section))
471
+ return entries
472
+
473
+
474
+ def _index_entries(reader, root: str | None) -> list[dict]:
475
+ import doctor
476
+ import doctor_fix
477
+
478
+ history = doctor_fix.History(root)
479
+ entries = []
480
+ for missing in doctor.missing_index_targets(reader):
481
+ evidence = []
482
+ for candidate in missing["candidates"]:
483
+ traced = history.trace(candidate)
484
+ if traced and traced[0] == "moved":
485
+ evidence.append(_evidence("file", traced[1], f"`{missing['target']}` moved here (git rename history)"))
486
+ break
487
+ if traced:
488
+ evidence.append(_evidence("commit", traced[1], f"deleted `{candidate}` on purpose (no rename); "
489
+ "`doctor --fix --write` marks the row (removed in it)"))
490
+ break
491
+ if not evidence:
492
+ evidence.append(_evidence("file", f"{missing['path']}:{missing['line']}",
493
+ "git shows no move or deletion of the target: fix the link or drop the row"))
494
+ entries.append(_entry("index-missing-file", missing["path"], missing["line"], missing["text"],
495
+ f"`{missing['target']}`", evidence, target=missing["target"]))
496
+ return entries
497
+
498
+
499
+ def _file_entry(failure, reader) -> dict:
500
+ target = failure.path.rstrip("/")
501
+ evidence = [_evidence("file", failure.path, failure.message)] if reader.exists(target) or failure.code in (
502
+ "state-missing",) else []
503
+ return _entry(failure.code, failure.path, None, "", failure.message, evidence)
504
+
505
+
506
+ def sweep(reader, root: str | None) -> list[dict]:
507
+ """Every failure the doctor reports on `reader`, as worklist entries with evidence."""
508
+ import doctor
509
+
510
+ git = Git(root)
511
+ entries: list[dict] = []
512
+ indexes_done = False
513
+ for failure in doctor.run_checks(reader, root, baseline=False):
514
+ if failure.severity != "fail":
515
+ continue
516
+ if failure.code == "index-missing-file":
517
+ if not indexes_done:
518
+ entries += _index_entries(reader, root)
519
+ indexes_done = True
520
+ elif failure.code == "archived-change-progress":
521
+ entries += _progress_entries(reader, git, failure.path)
522
+ elif failure.code == "archived-roadmap-summary":
523
+ entries += _summary_entries(reader, git, failure.path)
524
+ elif failure.code == "archived-roadmap-open-items":
525
+ entries += _open_item_entries(reader, git, failure.path)
526
+ elif failure.code == "archived-roadmap-open-checks":
527
+ entries += _open_check_entries(reader, git, failure.path)
528
+ else:
529
+ entries.append(_file_entry(failure, reader))
530
+ return entries
@@ -71,10 +71,17 @@ Read the PRD in full, not in excerpts.
71
71
  roadmap, `git mv` the queued file to `roadmap.md`, set `status: ready`, and take its ready entries
72
72
  (`git mv …/change.md context/changes/<id>/backlog-input.md`, then the `softure-new` format).
73
73
  Never promote on your own initiative, not even in `--auto`.
74
- - **`--close`**: the main roadmap is realised; archive it per WORKFLOW §5.2. Check the three gates
74
+ - **`--close`**: the main roadmap is realised; archive it per WORKFLOW §5.2. Check the four gates
75
75
  first and report every failing one at once: rows not `done` / `done_code` and not carried over,
76
76
  leftover folders in `context/changes/` (archive each through `softure-archive`, a change without a
77
- plan included, before continuing), and the full integration result on `<main>` when configured.
77
+ plan included, before continuing), the full integration result on `<main>` when configured, and
78
+ open checks: the close **refuses** to archive while a `- [ ]` is left under `## Owner decisions and
79
+ checks`. Settle each one first: tick it with its evidence (`— done: <sha | release | path>`), tick it
80
+ as obsolete with the reason (`— obsolete: <reason>`), or carry it to the next or a queued roadmap's
81
+ owner section (or an `owner-word` issue) and tick it with where it went (`— carried to <path | #N>`).
82
+ An archived roadmap with an open check is the doctor's `archived-roadmap-open-checks` and never an
83
+ owner-queue entry, so nothing that waits for the owner may stay behind in it. Open
84
+ `## Before the next release` steps stay: they wait for the release the close comes before.
78
85
  Then write `## Summary` (`| ID | Item | What changed | Merge |`, the merge SHA from
79
86
  `git log --merges --grep "<change-id>"` on `<main>`, plus the integration line), move the file to
80
87
  `foundation/archive/<YYYY-MM-DD>-roadmap.md`, clean up the promoted roadmap's backlog folder and