@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.
@@ -2,7 +2,10 @@
2
2
  """softure-doctor: check the `context/` contract of a project (WORKFLOW.md §12) and exit non-zero on drift.
3
3
 
4
4
  doctor.py [--root <dir>] [--json]
5
- npx softure-skills doctor (the same, from the installed package)
5
+ doctor.py --fix [--write] [--json] mechanical repairs of history (dry run unless --write)
6
+ doctor.py --sweep [--json] every remaining failure as a worklist with evidence (read-only)
7
+ doctor.py --baseline last resort: accept today's failures in context/doctor-baseline.json
8
+ npx softure-skills doctor [...] (the same, from the installed package)
6
9
 
7
10
  Adopting projects run it in their CI check, documentation-only changes included (that is where the
8
11
  drift happens). `softure-archive` and `softure-roadmap --close` run it before their commit and fix
@@ -11,20 +14,40 @@ what they own. Each problem is one line `FAIL <code> <path>: <what>`; the codes:
11
14
  roadmap-archived-not-removed roadmap.md is still there although the same roadmap is in foundation/archive/
12
15
  roadmap-status-mismatch roadmap.md `status` contradicts its rows (done with open rows; waiting)
13
16
  archived-change-status an archived change.md whose status is not `archived`
14
- archived-change-progress an archived plan.md with unticked Automated items in `## Progress`
17
+ archived-change-progress an archived plan.md with unticked Automated items in `## Progress` (an item
18
+ struck through or noted dropped/cancelled/not applicable is dropped, not open)
15
19
  archived-roadmap-open-items an archived roadmap with rows that are not done, done_code, dropped or carried
16
- archived-roadmap-summary an archived roadmap whose `## Summary` merge column holds placeholders, not SHAs
20
+ archived-roadmap-summary an archived roadmap whose `## Summary` item table holds a placeholder in its merge
21
+ column (a SHA, a release tag, carried, dropped or a dash with a reason pass)
22
+ archived-roadmap-open-checks an archived roadmap with unticked owner decisions or checks (or pre-release
23
+ steps, once its release is recorded or a later roadmap was closed)
17
24
  queued-roadmap-done a queued roadmap in foundation/roadmaps/ whose rows are all done
18
25
  backlog-without-roadmap a backlog/roadmap-<slug>/ folder without its queued (or promoted) roadmap
19
26
  index-missing-file an index row (README.md / INDEX.md table under context/) links a missing file
27
+ (a markdown link, or a cell that is only a path in a file column; a mention
28
+ in a description cell is not a link)
20
29
  state-missing context/state.json is missing although the project has written it before
21
30
  state-stale context/state.json does not match the markdown
31
+ baseline-stale context/doctor-baseline.json lists a failure that is fixed (remove it), or is unreadable
32
+
33
+ `--fix` repairs what is mechanical (an archived change's status; an archived index row whose target
34
+ moved or was deleted on purpose, found through git history; a dropped Progress item, normalised) and prints every edit; see doctor_fix.py. It is a dry run unless
35
+ `--write` is given, and it writes only under `context/`. `--sweep` lists every remaining failure with
36
+ the evidence an agent needs to settle it from the repository alone, classed `evidence`, `superseded` (later
37
+ work made it obsolete; the agent closes it) or `owner`; see doctor_sweep.py.
38
+
39
+ `--baseline` is a last resort for a project that cannot finish the sweep at once: it writes the failures
40
+ that remain to `context/doctor-baseline.json`, and the check then fails only on new failures and on
41
+ baseline entries that were fixed but not removed. It only shrinks: run again, it drops the fixed
42
+ entries and never adds one. State findings are never baselined. The recommended path is the sweep to zero.
22
43
 
23
44
  A project that has never written `context/state.json` (it adopted the package before the file existed)
24
45
  gets a note, not a failure: the first run of `wt-roadmap.py`, `softure-archive` or `softure-roadmap`
25
46
  creates it. Fix a stale or missing file with `npx softure-skills state` (or
26
47
  `python3 .claude/skills/softure-doctor/scripts/context_state.py write`) and commit it.
27
48
 
49
+ Piped into a reader that stops early (`doctor --sweep | head`), it ends quietly with exit 141, no traceback.
50
+
28
51
  Importable: `from doctor import run_checks` (takes any reader of context_state).
29
52
  """
30
53
  from __future__ import annotations
@@ -38,18 +61,25 @@ import sys
38
61
  sys.dont_write_bytecode = True # no __pycache__ inside the consumer's .claude/skills
39
62
  sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
40
63
  from context_state import ( # noqa: E402
41
- ARCHIVE_ROADMAPS_DIR, CHANGES_DIR, QUEUED_DIR, ROADMAP_PATH, STATE_PATH, FsReader, frontmatter,
42
- roadmap_rows, sections, staleness,
64
+ ARCHIVE_ROADMAPS_DIR, CHANGES_DIR, OWNER_SECTION, QUEUED_DIR, RELEASE_SECTION, ROADMAP_PATH, STATE_PATH,
65
+ FsReader, frontmatter, open_checkboxes, pending_release_roadmap, quiet_broken_pipe, roadmap_rows, sections,
66
+ staleness,
43
67
  )
44
68
 
45
69
  ARCHIVE_DIR = "context/archive"
70
+ BASELINE_PATH = "context/doctor-baseline.json"
71
+ NEVER_BASELINED = ("state-missing", "state-stale", "baseline-stale")
46
72
  BACKLOG_DIR = "context/backlog"
47
73
  CLOSED_STATUSES = ("done", "done_code", "dropped", "carried")
48
74
  SHA_RE = re.compile(r"\b[0-9a-f]{7,40}\b")
49
75
  EMPTY_MERGE = {"—", "-", "–", "n/a", "none", "no merge", "not merged"}
76
+ RELEASE_TAG_RE = re.compile(r"(?<![\w.])v?\d+\.\d+\.\d+(?:-[\w.]+)?(?![\w.])")
77
+ MERGE_COLUMN_RE = re.compile(r"\bmerge")
50
78
  LINK_RE = re.compile(r"\[[^\]]*\]\(([^)\s]+)(?:\s+\"[^\"]*\")?\)")
51
79
  INDEX_NAMES = ("README.md", "INDEX.md")
52
- CODE_PATH_RE = re.compile(r"`((?:\.{1,2}/)?(?:[\w.-]+/)*[\w.-]+\.md|(?:\.{1,2}/)?(?:[\w.-]+/)+)`")
80
+ _PATH = r"(?:\.{1,2}/)?(?:[\w.-]+/)*[\w.-]+\.md|(?:\.{1,2}/)?(?:[\w.-]+/)+"
81
+ WHOLE_PATH_RE = re.compile(r"(?P<tick>`?)(?P<path>" + _PATH + r")(?P=tick)") # a cell that is only a path
82
+ FILE_COLUMN_RE = re.compile(r"\b(?:files?|paths?|documents?|docs?|links?|artifacts?)\b")
53
83
 
54
84
 
55
85
  class Finding:
@@ -60,7 +90,7 @@ class Finding:
60
90
  return {"code": self.code, "path": self.path, "message": self.message, "severity": self.severity}
61
91
 
62
92
  def __str__(self) -> str:
63
- label = "FAIL" if self.severity == "fail" else "note"
93
+ label = {"fail": "FAIL", "baselined": "baselined"}.get(self.severity, "note")
64
94
  return f"{label} {self.code} {self.path}: {self.message}"
65
95
 
66
96
 
@@ -126,10 +156,45 @@ def check_archived_changes(reader) -> list[Finding]:
126
156
  return findings
127
157
 
128
158
 
159
+ DROP_WORDS = r"(?:dropped|cancell?ed|not applicable|n/a|obsolete|won't do|wontfix|skipped|replaced by)"
160
+ DROP_NOTE_RE = re.compile(r"\s+(?:—|–|--?)\s+(?P<note>" + DROP_WORDS + r"\b.*)$", re.IGNORECASE)
161
+ DROP_PAREN_RE = re.compile(r"\s*\((?P<note>" + DROP_WORDS + r"\b[^)]*)\)\s*$", re.IGNORECASE)
162
+ STRUCK_RE = re.compile(r"^~~(?P<body>.+?)~~(?P<rest>.*)$")
163
+
164
+
165
+ def dropped_item(text: str) -> tuple[str, str] | None:
166
+ """(item, note) when a checkbox text says the item was dropped; None otherwise.
167
+
168
+ Dropped by its own text: struck through (`~~1.1 ...~~`, with or without a note after it), or carrying an
169
+ explicit note after a dash or in parentheses (`— cancelled, replaced by 1.12`, `(not applicable)`).
170
+ """
171
+ text = text.strip()
172
+ struck = STRUCK_RE.match(text)
173
+ if struck:
174
+ rest = re.sub(r"^\s*(?:—|–|--?|:)?\s*", "", struck.group("rest")).strip()
175
+ return struck.group("body").strip(), rest or "struck through, no reason recorded"
176
+ for pattern in (DROP_NOTE_RE, DROP_PAREN_RE):
177
+ found = pattern.search(text)
178
+ if found and found.start() > 0:
179
+ return text[:found.start()].strip(), found.group("note").strip()
180
+ return None
181
+
182
+
183
+ def dropped_line(text: str) -> str | None:
184
+ """The normalised `~~<item>~~ — dropped: <note>` for a dropped checkbox text; None when it is not dropped."""
185
+ found = dropped_item(text)
186
+ if not found:
187
+ return None
188
+ item, note = found
189
+ note = re.sub(r"^dropped\s*:?\s*", "", note, flags=re.IGNORECASE) or "no reason recorded"
190
+ return f"~~{item}~~ — dropped: {note}"
191
+
192
+
129
193
  def unticked_automated(plan: str) -> list[str]:
130
- """Open `- [ ]` items of `## Progress` that are not under a `#### Manual` heading.
194
+ """Open `- [ ]` items of `## Progress` that are not under a `#### Manual` heading and not dropped.
131
195
 
132
- Open Manual items are legitimate in an archived plan (manual mode carries them to the owner).
196
+ Open Manual items are legitimate in an archived plan (manual mode carries them to the owner). An item
197
+ struck through or carrying a dropped/cancelled/not-applicable note is dropped by its own text.
133
198
  """
134
199
  progress = sections(plan).get("Progress", [])
135
200
  open_items = []
@@ -142,13 +207,23 @@ def unticked_automated(plan: str) -> list[str]:
142
207
  manual = False
143
208
  continue
144
209
  match = re.match(r"^\s*- \[ \] (.+)$", line)
145
- if match and not manual:
210
+ if match and not manual and not dropped_item(match.group(1)):
146
211
  open_items.append(match.group(1).strip())
147
212
  return open_items
148
213
 
149
214
 
215
+ def open_checks(text: str, include_release: bool = True) -> list[str]:
216
+ """Unticked entries of an archived roadmap's owner section (and its pre-release section)."""
217
+ parts = sections(text)
218
+ found = open_checkboxes(parts.get(OWNER_SECTION, []))
219
+ if include_release:
220
+ found += open_checkboxes(parts.get(RELEASE_SECTION, []))
221
+ return found
222
+
223
+
150
224
  def check_archived_roadmaps(reader) -> list[Finding]:
151
225
  findings: list[Finding] = []
226
+ pending = pending_release_roadmap(reader)
152
227
  for path in _archived_roadmaps(reader):
153
228
  text = reader.read(path) or ""
154
229
  open_rows = [f"{row['id']} ({row['status']})" for row in roadmap_rows(text)
@@ -156,34 +231,65 @@ def check_archived_roadmaps(reader) -> list[Finding]:
156
231
  if open_rows:
157
232
  findings.append(Finding("archived-roadmap-open-items", path,
158
233
  f"rows not done, done_code, dropped or carried: {', '.join(open_rows)}"))
234
+ checks = open_checks(text, include_release=path != pending)
235
+ if checks:
236
+ listed = "; ".join(checks[:3]) + ("; …" if len(checks) > 3 else "")
237
+ findings.append(Finding("archived-roadmap-open-checks", path,
238
+ f"{len(checks)} unticked owner entr{'y' if len(checks) == 1 else 'ies'} in an "
239
+ f"archived roadmap (settle, mark obsolete or carry over): {listed}"))
159
240
  bad = summary_placeholders(text)
160
241
  if bad:
161
242
  findings.append(Finding("archived-roadmap-summary", path,
162
- "## Summary merge column holds placeholders instead of merge SHAs: "
243
+ "## Summary merge column holds placeholders instead of merge SHAs or outcomes: "
163
244
  + "; ".join(bad[:4])))
164
245
  return findings
165
246
 
166
247
 
167
- def summary_placeholders(text: str) -> list[str]:
168
- """Rows of the `## Summary` table whose `Merge` cell holds no SHA (and is not an explicit dash)."""
169
- lines = sections(text).get("Summary", [])
170
- header = None
171
- bad = []
172
- for line in lines:
248
+ def summary_rows(text: str) -> list[dict]:
249
+ """Rows of the item table under `## Summary`: the table whose header has a merge column.
250
+
251
+ Other tables under `## Summary` (finding numbers, test counts) are not the item table and are skipped.
252
+ Each row: `line` (1-based in `text`), `text`, `item` (first cell), `cell` (the merge cell) and `ok`.
253
+ """
254
+ rows: list[dict] = []
255
+ in_summary = False
256
+ header: list[str] | None = None
257
+ merge = None
258
+ for number, line in enumerate((text or "").split("\n"), start=1):
259
+ if line.startswith("## "):
260
+ in_summary = line[3:].strip() == "Summary"
261
+ header = None
262
+ continue
263
+ if not in_summary:
264
+ continue
173
265
  if not line.strip().startswith("|"):
266
+ header = None
174
267
  continue
175
- parts = [cell.strip() for cell in line.strip().strip("|").split("|")]
268
+ cells = _table_cells(line)
176
269
  if header is None:
177
- header = [cell.lower() for cell in parts]
270
+ header = [cell.strip("*` ").lower() for cell in cells]
271
+ merge = next((index for index, name in enumerate(header) if MERGE_COLUMN_RE.search(name)), None)
178
272
  continue
179
- if all(re.fullmatch(r":?-{3,}:?", cell) for cell in parts if cell):
273
+ if merge is None or _is_separator(cells):
180
274
  continue
181
- index = header.index("merge") if "merge" in header else len(parts) - 1
182
- cell = parts[index] if index < len(parts) else ""
183
- if SHA_RE.search(cell) or cell.strip("`* ").lower() in EMPTY_MERGE:
184
- continue
185
- bad.append(f"{parts[0]}: \"{cell}\"")
186
- return bad
275
+ cell = cells[merge] if merge < len(cells) else ""
276
+ rows.append({"line": number, "text": line, "item": cells[0], "cell": cell, "ok": merge_cell_ok(cell)})
277
+ return rows
278
+
279
+
280
+ def merge_cell_ok(cell: str) -> bool:
281
+ """A merge cell records an outcome: a SHA, a release tag, carried/dropped, or a dash (with or without a reason)."""
282
+ value = cell.strip("`* ").lower()
283
+ if SHA_RE.search(cell) or RELEASE_TAG_RE.search(cell):
284
+ return True
285
+ if value in EMPTY_MERGE or value[:1] in ("—", "–", "-"):
286
+ return True
287
+ return bool(re.match(r"(?:carried|dropped|obsolete|superseded|cancell?ed|not merged|no merge)\b", value))
288
+
289
+
290
+ def summary_placeholders(text: str) -> list[str]:
291
+ """Item-table rows of `## Summary` whose merge cell is a placeholder, not an outcome."""
292
+ return [f"{row['item']}: \"{row['cell']}\"" for row in summary_rows(text) if not row["ok"]]
187
293
 
188
294
 
189
295
  def check_queued_and_backlog(reader) -> list[Finding]:
@@ -211,14 +317,39 @@ def check_queued_and_backlog(reader) -> list[Finding]:
211
317
  return findings
212
318
 
213
319
 
214
- def check_indexes(reader) -> list[Finding]:
215
- findings: list[Finding] = []
320
+ def _table_cells(line: str) -> list[str]:
321
+ return [cell.strip() for cell in line.strip().strip("|").split("|")]
322
+
323
+
324
+ def _is_separator(cells: list[str]) -> bool:
325
+ return all(re.fullmatch(r":?-{3,}:?", cell) for cell in cells if cell) and any(cells)
326
+
327
+
328
+ def missing_index_targets(reader) -> list[dict]:
329
+ """Every real link in an index row (README.md / INDEX.md table under context/) whose target does not exist.
330
+
331
+ A real link is a markdown link anywhere in the row, or a cell whose whole content is a path (in backticks
332
+ or bare) in a column that indexes files (`File`, `Path`, `Document`, `Link`, ...). A path merely mentioned
333
+ in a description cell (see `change.md`) is not a link and never fails.
334
+
335
+ Each entry: `path` (the index), `line` (1-based), `text` (the line), `kind` (`link` or `code`), `target`
336
+ (as written), `base` (the index folder) and `candidates` (the repository paths the target may mean).
337
+ """
338
+ out: list[dict] = []
216
339
  for path in _walk(reader, "context"):
217
340
  if os.path.basename(path) not in INDEX_NAMES:
218
341
  continue
219
342
  base = os.path.dirname(path)
220
- for line in (reader.read(path) or "").splitlines():
343
+ header: list[str] | None = None
344
+ for number, line in enumerate((reader.read(path) or "").splitlines(), start=1):
221
345
  if not line.strip().startswith("|"):
346
+ header = None
347
+ continue
348
+ cells = _table_cells(line)
349
+ if header is None:
350
+ header = [cell.strip("*` ").lower() for cell in cells]
351
+ continue
352
+ if _is_separator(cells):
222
353
  continue
223
354
  for target in LINK_RE.findall(line):
224
355
  if re.match(r"^[a-z][a-z0-9+.-]*:", target, re.IGNORECASE) or target.startswith("#"):
@@ -230,14 +361,31 @@ def check_indexes(reader) -> list[Finding]:
230
361
  if resolved.startswith("..") or not resolved.startswith("context/"):
231
362
  continue # outside context/: not this check's business
232
363
  if not reader.exists(resolved.rstrip("/")):
233
- findings.append(Finding("index-missing-file", path, f"row links `{target}`, which does not exist"))
234
- for target in CODE_PATH_RE.findall(line):
235
- # A path in backticks: relative to the index, to context/ or to the repository root.
364
+ out.append({"path": path, "line": number, "text": line, "kind": "link", "target": target,
365
+ "base": base, "candidates": [resolved.rstrip("/")]})
366
+ for column, cell in enumerate(cells):
367
+ if column >= len(header) or not FILE_COLUMN_RE.search(header[column]):
368
+ continue
369
+ whole = WHOLE_PATH_RE.fullmatch(cell)
370
+ if not whole:
371
+ continue
372
+ target = whole.group("path")
373
+ # A path cell: relative to the index, to context/ or to the repository root.
236
374
  candidates = [os.path.normpath(os.path.join(prefix, target)).replace(os.sep, "/").rstrip("/")
237
375
  for prefix in (base, "context", ".")]
238
376
  inside = [c for c in candidates if c.startswith("context/")]
239
377
  if inside and not any(reader.exists(c) for c in inside):
240
- findings.append(Finding("index-missing-file", path, f"row names `{target}`, which does not exist"))
378
+ out.append({"path": path, "line": number, "text": line, "kind": "code", "target": target,
379
+ "base": base, "candidates": inside})
380
+ return out
381
+
382
+
383
+ def check_indexes(reader) -> list[Finding]:
384
+ findings: list[Finding] = []
385
+ for missing in missing_index_targets(reader):
386
+ verb = "links" if missing["kind"] == "link" else "names"
387
+ findings.append(Finding("index-missing-file", missing["path"],
388
+ f"row {verb} `{missing['target']}`, which does not exist"))
241
389
  return findings
242
390
 
243
391
 
@@ -282,8 +430,12 @@ def check_state(reader, root: str | None) -> list[Finding]:
282
430
  f"{problem}; regenerate it (`npx softure-skills state`) and commit")]
283
431
 
284
432
 
285
- def run_checks(reader, root: str | None = None) -> list[Finding]:
286
- """Every finding for the project `reader` sees. `root` (a git checkout) enables the history check."""
433
+ def run_checks(reader, root: str | None = None, baseline: bool = True) -> list[Finding]:
434
+ """Every finding for the project `reader` sees. `root` (a git checkout) enables the history check.
435
+
436
+ With `baseline` (the default) a failure listed in context/doctor-baseline.json is reported with severity
437
+ `baselined` instead of `fail`, and a listed failure that no longer occurs is a `baseline-stale` failure.
438
+ """
287
439
  if not reader.exists("context"):
288
440
  return []
289
441
  findings: list[Finding] = []
@@ -291,7 +443,178 @@ def run_checks(reader, root: str | None = None) -> list[Finding]:
291
443
  check_queued_and_backlog, check_indexes):
292
444
  findings += check(reader)
293
445
  findings += check_state(reader, root)
294
- return findings
446
+ return apply_baseline(reader, findings) if baseline else findings
447
+
448
+
449
+ def _key(code: str, path: str) -> tuple[str, str]:
450
+ return code, path
451
+
452
+
453
+ def read_baseline(reader) -> tuple[list[dict] | None, str | None]:
454
+ """(entries, problem): entries None when there is no baseline; problem when the file is unreadable."""
455
+ raw = reader.read(BASELINE_PATH)
456
+ if raw is None:
457
+ return None, None
458
+ try:
459
+ data = json.loads(raw)
460
+ entries = data["entries"]
461
+ if not isinstance(entries, list) or not all(isinstance(e, dict) and "code" in e and "path" in e
462
+ for e in entries):
463
+ raise ValueError("entries must be objects with code and path")
464
+ return entries, None
465
+ except (json.JSONDecodeError, KeyError, TypeError, ValueError) as exc:
466
+ return [], f"not a valid baseline ({exc}); restore it from git or remove it"
467
+
468
+
469
+ def apply_baseline(reader, findings: list[Finding]) -> list[Finding]:
470
+ entries, problem = read_baseline(reader)
471
+ if entries is None:
472
+ return findings
473
+ if problem:
474
+ return findings + [Finding("baseline-stale", BASELINE_PATH, problem)]
475
+ accepted = {_key(entry["code"], entry["path"]) for entry in entries}
476
+ present = set()
477
+ out = []
478
+ for finding in findings:
479
+ key = _key(finding.code, finding.path)
480
+ if finding.severity == "fail" and key in accepted and finding.code not in NEVER_BASELINED:
481
+ present.add(key)
482
+ out.append(Finding(finding.code, finding.path, finding.message, severity="baselined"))
483
+ else:
484
+ out.append(finding)
485
+ for entry in entries:
486
+ key = _key(entry["code"], entry["path"])
487
+ if key not in present:
488
+ out.append(Finding("baseline-stale", BASELINE_PATH,
489
+ f"`{entry['code']} {entry['path']}` is fixed but still in the baseline: remove the "
490
+ "entry (`doctor --baseline` rewrites the file without it)"))
491
+ return out
492
+
493
+
494
+ def build_baseline(reader, root: str | None) -> tuple[dict, dict]:
495
+ """The baseline file to write and what changed: {"kept", "dropped", "refused"} (lists of keys)."""
496
+ import datetime as dt
497
+
498
+ failures = [f for f in run_checks(reader, root, baseline=False)
499
+ if f.severity == "fail" and f.code not in NEVER_BASELINED]
500
+ current: dict[tuple, Finding] = {}
501
+ for finding in failures:
502
+ current.setdefault(_key(finding.code, finding.path), finding)
503
+ previous, problem = read_baseline(reader)
504
+ if problem:
505
+ raise ValueError(f"{BASELINE_PATH}: {problem}")
506
+ if previous is None:
507
+ keep = list(current)
508
+ dropped: list[tuple] = []
509
+ refused: list[tuple] = []
510
+ created = dt.date.today().isoformat()
511
+ else:
512
+ old = [_key(entry["code"], entry["path"]) for entry in previous]
513
+ keep = [key for key in old if key in current]
514
+ dropped = [key for key in old if key not in current]
515
+ refused = [key for key in current if key not in old]
516
+ created = (json.loads(reader.read(BASELINE_PATH) or "{}").get("created")) or dt.date.today().isoformat()
517
+ data = {
518
+ "note": "Last resort (WORKFLOW §12.2): failures accepted while the history is swept. It only shrinks: "
519
+ "`doctor --baseline` drops fixed entries and never adds one. The goal is an empty file, then none.",
520
+ "created": created,
521
+ "entries": [{"code": key[0], "path": key[1], "message": current[key].message} for key in sorted(keep)],
522
+ }
523
+ return data, {"kept": keep, "dropped": dropped, "refused": refused}
524
+
525
+
526
+ def _take(args: list[str], flag: str) -> bool:
527
+ if flag in args:
528
+ args.remove(flag)
529
+ return True
530
+ return False
531
+
532
+
533
+ def run_fix(reader, root: str, git_root: str | None, write: bool, as_json: bool) -> int:
534
+ """`--fix`: print (and with `write` apply) the mechanical repairs; exit 0."""
535
+ import doctor_fix
536
+
537
+ plan = doctor_fix.plan_fixes(reader, git_root)
538
+ after = FsReader(root, plan["files"])
539
+ remaining = [f for f in run_checks(after, git_root, baseline=False) if f.severity == "fail"]
540
+ if write and plan["files"]:
541
+ doctor_fix.apply_fixes(root, plan["files"])
542
+ if as_json:
543
+ print(json.dumps({"root": root, "written": write, "edits": plan["edits"], "skipped": plan["skipped"],
544
+ "remaining": [f.as_dict() for f in remaining]}, indent=2))
545
+ return 0
546
+ mode = "applied" if write else "dry run"
547
+ print(f"softure-doctor --fix ({mode}): {len(plan['edits'])} edit(s) in {len(plan['files'])} file(s)")
548
+ for edit in plan["edits"]:
549
+ line = f":{edit['line']}" if edit.get("line") else ""
550
+ print(f"edit {edit['path']}{line}: {edit['what']}")
551
+ for skip in plan["skipped"]:
552
+ print(f"skip {skip['path']}: `{skip['target']}`: {skip['why']}")
553
+ print(f"after these edits: {len(remaining)} failure(s) remain"
554
+ + (" (`doctor --sweep` lists them with evidence)" if remaining else ""))
555
+ if plan["files"] and not write:
556
+ print("run again with --write to apply")
557
+ return 0
558
+
559
+
560
+ def run_baseline(reader, root: str, git_root: str | None) -> int:
561
+ """`--baseline`: write context/doctor-baseline.json; it never grows once it exists."""
562
+ try:
563
+ data, change = build_baseline(reader, git_root)
564
+ except ValueError as exc:
565
+ print(f"softure-doctor --baseline: {exc}", file=sys.stderr)
566
+ return 1
567
+ target = os.path.join(root, BASELINE_PATH)
568
+ if not data["entries"]:
569
+ if os.path.exists(target):
570
+ os.remove(target)
571
+ print(f"softure-doctor --baseline: every entry is fixed; removed {BASELINE_PATH}")
572
+ else:
573
+ print("softure-doctor --baseline: nothing fails, no baseline written")
574
+ return 0
575
+ with open(target, "w", encoding="utf-8") as fh:
576
+ fh.write(json.dumps(data, indent=2, ensure_ascii=False) + "\n")
577
+ print(f"softure-doctor --baseline: wrote {BASELINE_PATH} with {len(data['entries'])} entr"
578
+ f"{'y' if len(data['entries']) == 1 else 'ies'} (last resort: sweep them to zero, WORKFLOW §12.2)")
579
+ for key in change["dropped"]:
580
+ print(f"dropped (fixed): {key[0]} {key[1]}")
581
+ for key in change["refused"]:
582
+ print(f"not added (the baseline only shrinks; fix it): {key[0]} {key[1]}")
583
+ return 1 if change["refused"] else 0
584
+
585
+
586
+ def run_sweep(reader, root: str, git_root: str | None, as_json: bool) -> int:
587
+ """`--sweep`: the worklist of every failure with its evidence; exit 1 while anything is left."""
588
+ import doctor_sweep
589
+
590
+ entries = doctor_sweep.sweep(reader, git_root)
591
+ owner = [entry for entry in entries if entry["class"] == "owner"]
592
+ superseded = [entry for entry in entries if entry["class"] == "superseded"]
593
+ with_evidence = len(entries) - len(owner) - len(superseded)
594
+ if as_json:
595
+ print(json.dumps({"root": root, "entries": entries,
596
+ "summary": {"total": len(entries), "with_evidence": with_evidence,
597
+ "superseded": len(superseded), "owner": len(owner)}},
598
+ indent=2, ensure_ascii=False))
599
+ return 1 if entries else 0
600
+ if not entries:
601
+ print("softure-doctor --sweep: nothing to settle, the context/ contract is OK")
602
+ return 0
603
+ for entry in entries:
604
+ where = f"{entry['path']}:{entry['line']}" if entry.get("line") else entry["path"]
605
+ print(f"{entry['code']} {where}: {entry['subject']}")
606
+ for evidence in entry["evidence"]:
607
+ print(f" evidence {evidence['kind']} {evidence['ref']}: {evidence['note']}")
608
+ if entry["class"] == "superseded":
609
+ print(" superseded: later work made it obsolete; close it yourself, never forward it")
610
+ if entry["owner"]:
611
+ print(f" owner ({entry['owner_reason']}): only the owner can settle it")
612
+ for tried in entry["tried"]:
613
+ print(f" tried: {tried}")
614
+ print(f" settle: {entry['settle']}")
615
+ print(f"softure-doctor --sweep: {len(entries)} entr{'y' if len(entries) == 1 else 'ies'} to settle, "
616
+ f"{with_evidence} with evidence, {len(superseded)} superseded, {len(owner)} for the owner")
617
+ return 1
295
618
 
296
619
 
297
620
  def main(argv: list[str] | None = None) -> int:
@@ -299,14 +622,17 @@ def main(argv: list[str] | None = None) -> int:
299
622
  if "-h" in args or "--help" in args:
300
623
  print(__doc__)
301
624
  return 0
302
- as_json = "--json" in args
303
- args = [arg for arg in args if arg != "--json"]
625
+ as_json = _take(args, "--json")
626
+ fix = _take(args, "--fix")
627
+ write = _take(args, "--write")
628
+ do_sweep = _take(args, "--sweep")
629
+ do_baseline = _take(args, "--baseline")
304
630
  root = None
305
631
  if "--root" in args:
306
632
  k = args.index("--root")
307
633
  root = os.path.abspath(args[k + 1])
308
634
  del args[k:k + 2]
309
- if args:
635
+ if args or (write and not fix) or sum((fix, do_sweep, do_baseline)) > 1:
310
636
  print(__doc__, file=sys.stderr)
311
637
  return 2
312
638
  top = subprocess.run(["git", "-C", root or os.getcwd(), "rev-parse", "--show-toplevel"],
@@ -321,6 +647,12 @@ def main(argv: list[str] | None = None) -> int:
321
647
  else:
322
648
  print(f"softure-doctor: no context/ directory in {root}, nothing to check")
323
649
  return 0
650
+ if fix:
651
+ return run_fix(reader, root, git_root, write, as_json)
652
+ if do_sweep:
653
+ return run_sweep(reader, root, git_root, as_json)
654
+ if do_baseline:
655
+ return run_baseline(reader, root, git_root)
324
656
  findings = run_checks(reader, git_root)
325
657
  failures = [f for f in findings if f.severity == "fail"]
326
658
  if as_json:
@@ -329,12 +661,18 @@ def main(argv: list[str] | None = None) -> int:
329
661
  return 1 if failures else 0
330
662
  for finding in findings:
331
663
  print(finding)
664
+ baselined = sum(1 for f in findings if f.severity == "baselined")
665
+ if baselined:
666
+ print(f"softure-doctor: {baselined} failure(s) accepted by {BASELINE_PATH} (last resort; sweep them to zero)")
332
667
  if failures:
333
668
  print(f"softure-doctor: {len(failures)} problem(s) in the context/ contract (WORKFLOW.md §12)")
669
+ mechanical = sum(1 for f in failures if f.code in ("archived-change-status", "index-missing-file"))
670
+ if mechanical:
671
+ print(f"softure-doctor: {mechanical} of them may be mechanical: `doctor --fix` shows the edits")
334
672
  return 1
335
673
  print("softure-doctor: context/ contract OK")
336
674
  return 0
337
675
 
338
676
 
339
677
  if __name__ == "__main__":
340
- sys.exit(main())
678
+ sys.exit(quiet_broken_pipe(main))