@softure-ai/skills 0.20.0 → 0.21.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.
@@ -12,7 +12,10 @@ the working tree, so someone else's uncommitted edits never leak into the file,
12
12
 
13
13
  Everything in the file is derived from the markdown under `context/` (and `context/workflow.json`):
14
14
  the active roadmap, the queued roadmaps, the change folders, and one `owner_queue` that lists every
15
- entry that waits for the owner. The schema ships next to this script
15
+ entry that waits for the owner. The queue is built only from what is live: the active roadmap, the
16
+ queued roadmaps, the open changes, and the pre-release steps of the newest closed roadmap until its
17
+ release is recorded. An unticked entry left in any other archived roadmap is history to settle
18
+ (the doctor's `archived-roadmap-open-checks`), never an owner-queue item. The schema ships next to this script
16
19
  (`../references/state.schema.json`). A reader needs this one file per repository instead of parsing
17
20
  the markdown.
18
21
 
@@ -41,6 +44,10 @@ ARCHIVE_ROADMAPS_DIR = "context/foundation/archive"
41
44
  CHANGES_DIR = "context/changes"
42
45
  # Fields a script rewrites without the markdown changing: never a reason to call the file stale.
43
46
  VOLATILE_FIELDS = ("updated_at", "open_changes")
47
+ # Owner-queue entries from these sources are refreshed like open_changes: a change branch edits them.
48
+ VOLATILE_SOURCES = ("context/changes/",)
49
+ HANDOFF_SECTION = "Roadmap handoff"
50
+ HANDOFF_OWNER_RE = re.compile(r"^- \*\*Owner (?P<what>step|check):\*\*\s*(?P<text>.+)$")
44
51
 
45
52
  ROW_RE = re.compile(r"^\|\s*\*\*(?P<id>[A-Z]+-\d+)\*\*\s*\|")
46
53
  ID_RE = re.compile(r"\b[A-Z]+-\d+\b")
@@ -290,15 +297,15 @@ def _today() -> str:
290
297
 
291
298
  def _owner_entries(path: str, text: str, rows: list[dict], fallback_since: str,
292
299
  archived: bool = False) -> list[dict]:
293
- """Every open entry of one roadmap file that waits for the owner.
300
+ """Every open entry of one live roadmap file that waits for the owner.
294
301
 
295
- An archived roadmap keeps its `done_code` rows as a record for the release notes, so only its open
296
- checkboxes count, and its `## Before the next release` only until its `## Summary` records a release.
302
+ With `archived` (only the newest closed roadmap whose `## Summary` records no release yet), just its
303
+ open `## Before the next release` steps count: the close comes before the release (WORKFLOW §5.2).
297
304
  """
298
305
  entries: list[dict] = []
299
306
  parts = sections(text)
300
307
  ids_with_entry: set[str] = set()
301
- for line in open_checkboxes(parts.get(OWNER_SECTION, [])):
308
+ for line in ([] if archived else open_checkboxes(parts.get(OWNER_SECTION, []))):
302
309
  ref = ITEM_REF_RE.search(line)
303
310
  item = ref.group("id") if ref else None
304
311
  lowered = line.lower()
@@ -312,8 +319,7 @@ def _owner_entries(path: str, text: str, rows: list[dict], fallback_since: str,
312
319
  ids_with_entry.add(item)
313
320
  entries.append({"kind": kind, "source": f"{path}#{OWNER_SECTION}", "item": item,
314
321
  "since": _date_in(line) or fallback_since, "text": line})
315
- released = archived and any(RELEASE_LINE_RE.match(line.strip()) for line in parts.get("Summary", []))
316
- for line in ([] if released else open_checkboxes(parts.get(RELEASE_SECTION, []))):
322
+ for line in open_checkboxes(parts.get(RELEASE_SECTION, [])):
317
323
  ref = ITEM_REF_RE.search(line)
318
324
  entries.append({"kind": "secret" if SECRET_RE.search(line) else "step",
319
325
  "source": f"{path}#{RELEASE_SECTION}", "item": ref.group("id") if ref else None,
@@ -339,6 +345,38 @@ def _owner_entries(path: str, text: str, rows: list[dict], fallback_since: str,
339
345
  return entries
340
346
 
341
347
 
348
+ def released(text: str) -> bool:
349
+ """Whether an archived roadmap's `## Summary` records the release that shipped it."""
350
+ return any(RELEASE_LINE_RE.match(line.strip()) for line in sections(text).get("Summary", []))
351
+
352
+
353
+ def archived_roadmap_files(reader) -> list[str]:
354
+ """Archived roadmaps (`<date>-roadmap*.md` in foundation/archive/), oldest first."""
355
+ return _roadmap_files(reader, ARCHIVE_ROADMAPS_DIR, r"^\d{4}-\d{2}-\d{2}-roadmap.*\.md$")
356
+
357
+
358
+ def pending_release_roadmap(reader) -> str | None:
359
+ """The newest archived roadmap when its release is not recorded yet: its pre-release steps are live."""
360
+ paths = [path for path in archived_roadmap_files(reader) if roadmap_rows(reader.read(path) or "")]
361
+ if not paths:
362
+ return None
363
+ newest = paths[-1]
364
+ return None if released(reader.read(newest) or "") else newest
365
+
366
+
367
+ def _handoff_entries(path: str, text: str, item: str | None, since: str) -> list[dict]:
368
+ """Owner steps and checks an open change records in its `## Roadmap handoff` (WORKFLOW §4)."""
369
+ entries = []
370
+ for line in sections(text).get(HANDOFF_SECTION, []):
371
+ match = HANDOFF_OWNER_RE.match(line.strip())
372
+ if match:
373
+ body = match.group("text").strip()
374
+ entries.append({"kind": "secret" if SECRET_RE.search(body) else "step",
375
+ "source": f"{path}#{HANDOFF_SECTION}", "item": item,
376
+ "since": _date_in(body) or since, "text": f"owner {match.group('what')}: {body}"})
377
+ return entries
378
+
379
+
342
380
  def _date_in(text: str) -> str | None:
343
381
  match = DATE_RE.search(text)
344
382
  return match.group(1) if match else None
@@ -354,7 +392,7 @@ def _roadmap_files(reader, directory: str, pattern: str) -> list[str]:
354
392
 
355
393
 
356
394
  def _last_release(reader) -> dict | None:
357
- for path in reversed(_roadmap_files(reader, ARCHIVE_ROADMAPS_DIR, r"^\d{4}-\d{2}-\d{2}-roadmap.*\.md$")):
395
+ for path in reversed(archived_roadmap_files(reader)):
358
396
  text = reader.read(path) or ""
359
397
  for line in reversed(sections(text).get("Summary", [])):
360
398
  match = RELEASE_LINE_RE.match(line.strip())
@@ -421,11 +459,12 @@ def build_state(reader, prior: dict | None = None, now: str | None = None) -> di
421
459
  "text": f"start queued roadmap {slug}" + (f": {condition}" if condition else "")})
422
460
  owner_queue += _owner_entries(path, text, rows, meta.get("updated") or today)
423
461
 
424
- for path in _roadmap_files(reader, ARCHIVE_ROADMAPS_DIR, r"^\d{4}-\d{2}-\d{2}-roadmap.*\.md$"):
425
- text = reader.read(path) or ""
462
+ pending = pending_release_roadmap(reader)
463
+ if pending:
464
+ text = reader.read(pending) or ""
426
465
  meta = frontmatter(text)
427
- owner_queue += _owner_entries(path, text, roadmap_rows(text), meta.get("updated") or path.split("/")[-1][:10],
428
- archived=True)
466
+ owner_queue += _owner_entries(pending, text, roadmap_rows(text),
467
+ meta.get("updated") or pending.split("/")[-1][:10], archived=True)
429
468
 
430
469
  open_changes = []
431
470
  for name, is_dir in reader.listdir(CHANGES_DIR):
@@ -445,6 +484,8 @@ def build_state(reader, prior: dict | None = None, now: str | None = None) -> di
445
484
  "updated": meta.get("updated"),
446
485
  "stage": (row["stage"] or row["status"]) if row else None,
447
486
  })
487
+ owner_queue += _handoff_entries(f"{CHANGES_DIR}/{name}/change.md", text, meta.get("roadmap_item"),
488
+ meta.get("updated") or today)
448
489
 
449
490
  previous = {_entry_key(entry): entry.get("since") for entry in (prior or {}).get("owner_queue", [])}
450
491
  for entry in owner_queue:
@@ -480,10 +521,13 @@ def _entry_key(entry: dict) -> tuple:
480
521
 
481
522
 
482
523
  def comparable(state: dict | None) -> dict | None:
483
- """The state without the fields a rewrite may change on its own (see VOLATILE_FIELDS)."""
524
+ """The state without what a rewrite may change on its own (VOLATILE_FIELDS, VOLATILE_SOURCES)."""
484
525
  if state is None:
485
526
  return None
486
- return {key: value for key, value in state.items() if key not in VOLATILE_FIELDS}
527
+ kept = {key: value for key, value in state.items() if key not in VOLATILE_FIELDS}
528
+ kept["owner_queue"] = [entry for entry in kept.get("owner_queue") or []
529
+ if not str(entry.get("source", "")).startswith(VOLATILE_SOURCES)]
530
+ return kept
487
531
 
488
532
 
489
533
  def serialize(state: dict) -> str:
@@ -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
@@ -14,11 +17,24 @@ what they own. Each problem is one line `FAIL <code> <path>: <what>`; the codes:
14
17
  archived-change-progress an archived plan.md with unticked Automated items in `## Progress`
15
18
  archived-roadmap-open-items an archived roadmap with rows that are not done, done_code, dropped or carried
16
19
  archived-roadmap-summary an archived roadmap whose `## Summary` merge column holds placeholders, not SHAs
20
+ archived-roadmap-open-checks an archived roadmap with unticked owner decisions or checks (or pre-release
21
+ steps, once its release is recorded or a later roadmap was closed)
17
22
  queued-roadmap-done a queued roadmap in foundation/roadmaps/ whose rows are all done
18
23
  backlog-without-roadmap a backlog/roadmap-<slug>/ folder without its queued (or promoted) roadmap
19
24
  index-missing-file an index row (README.md / INDEX.md table under context/) links a missing file
20
25
  state-missing context/state.json is missing although the project has written it before
21
26
  state-stale context/state.json does not match the markdown
27
+ baseline-stale context/doctor-baseline.json lists a failure that is fixed (remove it), or is unreadable
28
+
29
+ `--fix` repairs what is mechanical (an archived change's status; an archived index row whose target
30
+ moved, found through git history) and prints every edit; see doctor_fix.py. It is a dry run unless
31
+ `--write` is given, and it writes only under `context/`. `--sweep` lists every remaining failure with
32
+ the evidence an agent needs to settle it from the repository alone; see doctor_sweep.py.
33
+
34
+ `--baseline` is a last resort for a project that cannot finish the sweep at once: it writes the failures
35
+ that remain to `context/doctor-baseline.json`, and the check then fails only on new failures and on
36
+ baseline entries that were fixed but not removed. It only shrinks: run again, it drops the fixed
37
+ entries and never adds one. State findings are never baselined. The recommended path is the sweep to zero.
22
38
 
23
39
  A project that has never written `context/state.json` (it adopted the package before the file existed)
24
40
  gets a note, not a failure: the first run of `wt-roadmap.py`, `softure-archive` or `softure-roadmap`
@@ -38,11 +54,13 @@ import sys
38
54
  sys.dont_write_bytecode = True # no __pycache__ inside the consumer's .claude/skills
39
55
  sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
40
56
  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,
57
+ ARCHIVE_ROADMAPS_DIR, CHANGES_DIR, OWNER_SECTION, QUEUED_DIR, RELEASE_SECTION, ROADMAP_PATH, STATE_PATH,
58
+ FsReader, frontmatter, open_checkboxes, pending_release_roadmap, roadmap_rows, sections, staleness,
43
59
  )
44
60
 
45
61
  ARCHIVE_DIR = "context/archive"
62
+ BASELINE_PATH = "context/doctor-baseline.json"
63
+ NEVER_BASELINED = ("state-missing", "state-stale", "baseline-stale")
46
64
  BACKLOG_DIR = "context/backlog"
47
65
  CLOSED_STATUSES = ("done", "done_code", "dropped", "carried")
48
66
  SHA_RE = re.compile(r"\b[0-9a-f]{7,40}\b")
@@ -60,7 +78,7 @@ class Finding:
60
78
  return {"code": self.code, "path": self.path, "message": self.message, "severity": self.severity}
61
79
 
62
80
  def __str__(self) -> str:
63
- label = "FAIL" if self.severity == "fail" else "note"
81
+ label = {"fail": "FAIL", "baselined": "baselined"}.get(self.severity, "note")
64
82
  return f"{label} {self.code} {self.path}: {self.message}"
65
83
 
66
84
 
@@ -147,8 +165,18 @@ def unticked_automated(plan: str) -> list[str]:
147
165
  return open_items
148
166
 
149
167
 
168
+ def open_checks(text: str, include_release: bool = True) -> list[str]:
169
+ """Unticked entries of an archived roadmap's owner section (and its pre-release section)."""
170
+ parts = sections(text)
171
+ found = open_checkboxes(parts.get(OWNER_SECTION, []))
172
+ if include_release:
173
+ found += open_checkboxes(parts.get(RELEASE_SECTION, []))
174
+ return found
175
+
176
+
150
177
  def check_archived_roadmaps(reader) -> list[Finding]:
151
178
  findings: list[Finding] = []
179
+ pending = pending_release_roadmap(reader)
152
180
  for path in _archived_roadmaps(reader):
153
181
  text = reader.read(path) or ""
154
182
  open_rows = [f"{row['id']} ({row['status']})" for row in roadmap_rows(text)
@@ -156,6 +184,12 @@ def check_archived_roadmaps(reader) -> list[Finding]:
156
184
  if open_rows:
157
185
  findings.append(Finding("archived-roadmap-open-items", path,
158
186
  f"rows not done, done_code, dropped or carried: {', '.join(open_rows)}"))
187
+ checks = open_checks(text, include_release=path != pending)
188
+ if checks:
189
+ listed = "; ".join(checks[:3]) + ("; …" if len(checks) > 3 else "")
190
+ findings.append(Finding("archived-roadmap-open-checks", path,
191
+ f"{len(checks)} unticked owner entr{'y' if len(checks) == 1 else 'ies'} in an "
192
+ f"archived roadmap (settle, mark obsolete or carry over): {listed}"))
159
193
  bad = summary_placeholders(text)
160
194
  if bad:
161
195
  findings.append(Finding("archived-roadmap-summary", path,
@@ -211,13 +245,18 @@ def check_queued_and_backlog(reader) -> list[Finding]:
211
245
  return findings
212
246
 
213
247
 
214
- def check_indexes(reader) -> list[Finding]:
215
- findings: list[Finding] = []
248
+ def missing_index_targets(reader) -> list[dict]:
249
+ """Every link or backticked path in an index row (README.md / INDEX.md under context/) that does not exist.
250
+
251
+ Each entry: `path` (the index), `line` (1-based), `text` (the line), `kind` (`link` or `code`), `target`
252
+ (as written), `base` (the index folder) and `candidates` (the repository paths the target may mean).
253
+ """
254
+ out: list[dict] = []
216
255
  for path in _walk(reader, "context"):
217
256
  if os.path.basename(path) not in INDEX_NAMES:
218
257
  continue
219
258
  base = os.path.dirname(path)
220
- for line in (reader.read(path) or "").splitlines():
259
+ for number, line in enumerate((reader.read(path) or "").splitlines(), start=1):
221
260
  if not line.strip().startswith("|"):
222
261
  continue
223
262
  for target in LINK_RE.findall(line):
@@ -230,14 +269,25 @@ def check_indexes(reader) -> list[Finding]:
230
269
  if resolved.startswith("..") or not resolved.startswith("context/"):
231
270
  continue # outside context/: not this check's business
232
271
  if not reader.exists(resolved.rstrip("/")):
233
- findings.append(Finding("index-missing-file", path, f"row links `{target}`, which does not exist"))
272
+ out.append({"path": path, "line": number, "text": line, "kind": "link", "target": target,
273
+ "base": base, "candidates": [resolved.rstrip("/")]})
234
274
  for target in CODE_PATH_RE.findall(line):
235
275
  # A path in backticks: relative to the index, to context/ or to the repository root.
236
276
  candidates = [os.path.normpath(os.path.join(prefix, target)).replace(os.sep, "/").rstrip("/")
237
277
  for prefix in (base, "context", ".")]
238
278
  inside = [c for c in candidates if c.startswith("context/")]
239
279
  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"))
280
+ out.append({"path": path, "line": number, "text": line, "kind": "code", "target": target,
281
+ "base": base, "candidates": inside})
282
+ return out
283
+
284
+
285
+ def check_indexes(reader) -> list[Finding]:
286
+ findings: list[Finding] = []
287
+ for missing in missing_index_targets(reader):
288
+ verb = "links" if missing["kind"] == "link" else "names"
289
+ findings.append(Finding("index-missing-file", missing["path"],
290
+ f"row {verb} `{missing['target']}`, which does not exist"))
241
291
  return findings
242
292
 
243
293
 
@@ -282,8 +332,12 @@ def check_state(reader, root: str | None) -> list[Finding]:
282
332
  f"{problem}; regenerate it (`npx softure-skills state`) and commit")]
283
333
 
284
334
 
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."""
335
+ def run_checks(reader, root: str | None = None, baseline: bool = True) -> list[Finding]:
336
+ """Every finding for the project `reader` sees. `root` (a git checkout) enables the history check.
337
+
338
+ With `baseline` (the default) a failure listed in context/doctor-baseline.json is reported with severity
339
+ `baselined` instead of `fail`, and a listed failure that no longer occurs is a `baseline-stale` failure.
340
+ """
287
341
  if not reader.exists("context"):
288
342
  return []
289
343
  findings: list[Finding] = []
@@ -291,7 +345,171 @@ def run_checks(reader, root: str | None = None) -> list[Finding]:
291
345
  check_queued_and_backlog, check_indexes):
292
346
  findings += check(reader)
293
347
  findings += check_state(reader, root)
294
- return findings
348
+ return apply_baseline(reader, findings) if baseline else findings
349
+
350
+
351
+ def _key(code: str, path: str) -> tuple[str, str]:
352
+ return code, path
353
+
354
+
355
+ def read_baseline(reader) -> tuple[list[dict] | None, str | None]:
356
+ """(entries, problem): entries None when there is no baseline; problem when the file is unreadable."""
357
+ raw = reader.read(BASELINE_PATH)
358
+ if raw is None:
359
+ return None, None
360
+ try:
361
+ data = json.loads(raw)
362
+ entries = data["entries"]
363
+ if not isinstance(entries, list) or not all(isinstance(e, dict) and "code" in e and "path" in e
364
+ for e in entries):
365
+ raise ValueError("entries must be objects with code and path")
366
+ return entries, None
367
+ except (json.JSONDecodeError, KeyError, TypeError, ValueError) as exc:
368
+ return [], f"not a valid baseline ({exc}); restore it from git or remove it"
369
+
370
+
371
+ def apply_baseline(reader, findings: list[Finding]) -> list[Finding]:
372
+ entries, problem = read_baseline(reader)
373
+ if entries is None:
374
+ return findings
375
+ if problem:
376
+ return findings + [Finding("baseline-stale", BASELINE_PATH, problem)]
377
+ accepted = {_key(entry["code"], entry["path"]) for entry in entries}
378
+ present = set()
379
+ out = []
380
+ for finding in findings:
381
+ key = _key(finding.code, finding.path)
382
+ if finding.severity == "fail" and key in accepted and finding.code not in NEVER_BASELINED:
383
+ present.add(key)
384
+ out.append(Finding(finding.code, finding.path, finding.message, severity="baselined"))
385
+ else:
386
+ out.append(finding)
387
+ for entry in entries:
388
+ key = _key(entry["code"], entry["path"])
389
+ if key not in present:
390
+ out.append(Finding("baseline-stale", BASELINE_PATH,
391
+ f"`{entry['code']} {entry['path']}` is fixed but still in the baseline: remove the "
392
+ "entry (`doctor --baseline` rewrites the file without it)"))
393
+ return out
394
+
395
+
396
+ def build_baseline(reader, root: str | None) -> tuple[dict, dict]:
397
+ """The baseline file to write and what changed: {"kept", "dropped", "refused"} (lists of keys)."""
398
+ import datetime as dt
399
+
400
+ failures = [f for f in run_checks(reader, root, baseline=False)
401
+ if f.severity == "fail" and f.code not in NEVER_BASELINED]
402
+ current: dict[tuple, Finding] = {}
403
+ for finding in failures:
404
+ current.setdefault(_key(finding.code, finding.path), finding)
405
+ previous, problem = read_baseline(reader)
406
+ if problem:
407
+ raise ValueError(f"{BASELINE_PATH}: {problem}")
408
+ if previous is None:
409
+ keep = list(current)
410
+ dropped: list[tuple] = []
411
+ refused: list[tuple] = []
412
+ created = dt.date.today().isoformat()
413
+ else:
414
+ old = [_key(entry["code"], entry["path"]) for entry in previous]
415
+ keep = [key for key in old if key in current]
416
+ dropped = [key for key in old if key not in current]
417
+ refused = [key for key in current if key not in old]
418
+ created = (json.loads(reader.read(BASELINE_PATH) or "{}").get("created")) or dt.date.today().isoformat()
419
+ data = {
420
+ "note": "Last resort (WORKFLOW §12.2): failures accepted while the history is swept. It only shrinks: "
421
+ "`doctor --baseline` drops fixed entries and never adds one. The goal is an empty file, then none.",
422
+ "created": created,
423
+ "entries": [{"code": key[0], "path": key[1], "message": current[key].message} for key in sorted(keep)],
424
+ }
425
+ return data, {"kept": keep, "dropped": dropped, "refused": refused}
426
+
427
+
428
+ def _take(args: list[str], flag: str) -> bool:
429
+ if flag in args:
430
+ args.remove(flag)
431
+ return True
432
+ return False
433
+
434
+
435
+ def run_fix(reader, root: str, git_root: str | None, write: bool, as_json: bool) -> int:
436
+ """`--fix`: print (and with `write` apply) the mechanical repairs; exit 0."""
437
+ import doctor_fix
438
+
439
+ plan = doctor_fix.plan_fixes(reader, git_root)
440
+ after = FsReader(root, plan["files"])
441
+ remaining = [f for f in run_checks(after, git_root, baseline=False) if f.severity == "fail"]
442
+ if write and plan["files"]:
443
+ doctor_fix.apply_fixes(root, plan["files"])
444
+ if as_json:
445
+ print(json.dumps({"root": root, "written": write, "edits": plan["edits"], "skipped": plan["skipped"],
446
+ "remaining": [f.as_dict() for f in remaining]}, indent=2))
447
+ return 0
448
+ mode = "applied" if write else "dry run"
449
+ print(f"softure-doctor --fix ({mode}): {len(plan['edits'])} edit(s) in {len(plan['files'])} file(s)")
450
+ for edit in plan["edits"]:
451
+ line = f":{edit['line']}" if edit.get("line") else ""
452
+ print(f"edit {edit['path']}{line}: {edit['what']}")
453
+ for skip in plan["skipped"]:
454
+ print(f"skip {skip['path']}: `{skip['target']}`: {skip['why']}")
455
+ print(f"after these edits: {len(remaining)} failure(s) remain"
456
+ + (" (`doctor --sweep` lists them with evidence)" if remaining else ""))
457
+ if plan["files"] and not write:
458
+ print("run again with --write to apply")
459
+ return 0
460
+
461
+
462
+ def run_baseline(reader, root: str, git_root: str | None) -> int:
463
+ """`--baseline`: write context/doctor-baseline.json; it never grows once it exists."""
464
+ try:
465
+ data, change = build_baseline(reader, git_root)
466
+ except ValueError as exc:
467
+ print(f"softure-doctor --baseline: {exc}", file=sys.stderr)
468
+ return 1
469
+ target = os.path.join(root, BASELINE_PATH)
470
+ if not data["entries"]:
471
+ if os.path.exists(target):
472
+ os.remove(target)
473
+ print(f"softure-doctor --baseline: every entry is fixed; removed {BASELINE_PATH}")
474
+ else:
475
+ print("softure-doctor --baseline: nothing fails, no baseline written")
476
+ return 0
477
+ with open(target, "w", encoding="utf-8") as fh:
478
+ fh.write(json.dumps(data, indent=2, ensure_ascii=False) + "\n")
479
+ print(f"softure-doctor --baseline: wrote {BASELINE_PATH} with {len(data['entries'])} entr"
480
+ f"{'y' if len(data['entries']) == 1 else 'ies'} (last resort: sweep them to zero, WORKFLOW §12.2)")
481
+ for key in change["dropped"]:
482
+ print(f"dropped (fixed): {key[0]} {key[1]}")
483
+ for key in change["refused"]:
484
+ print(f"not added (the baseline only shrinks; fix it): {key[0]} {key[1]}")
485
+ return 1 if change["refused"] else 0
486
+
487
+
488
+ def run_sweep(reader, root: str, git_root: str | None, as_json: bool) -> int:
489
+ """`--sweep`: the worklist of every failure with its evidence; exit 1 while anything is left."""
490
+ import doctor_sweep
491
+
492
+ entries = doctor_sweep.sweep(reader, git_root)
493
+ owner = [entry for entry in entries if entry["owner"]]
494
+ if as_json:
495
+ print(json.dumps({"root": root, "entries": entries,
496
+ "summary": {"total": len(entries), "with_evidence": len(entries) - len(owner),
497
+ "owner": len(owner)}}, indent=2, ensure_ascii=False))
498
+ return 1 if entries else 0
499
+ if not entries:
500
+ print("softure-doctor --sweep: nothing to settle, the context/ contract is OK")
501
+ return 0
502
+ for entry in entries:
503
+ where = f"{entry['path']}:{entry['line']}" if entry.get("line") else entry["path"]
504
+ print(f"{entry['code']} {where}: {entry['subject']}")
505
+ for evidence in entry["evidence"]:
506
+ print(f" evidence {evidence['kind']} {evidence['ref']}: {evidence['note']}")
507
+ if entry["owner"]:
508
+ print(" owner: no evidence in the repository; only the owner can settle it")
509
+ print(f" settle: {entry['settle']}")
510
+ print(f"softure-doctor --sweep: {len(entries)} entr{'y' if len(entries) == 1 else 'ies'} to settle, "
511
+ f"{len(entries) - len(owner)} with evidence, {len(owner)} for the owner")
512
+ return 1
295
513
 
296
514
 
297
515
  def main(argv: list[str] | None = None) -> int:
@@ -299,14 +517,17 @@ def main(argv: list[str] | None = None) -> int:
299
517
  if "-h" in args or "--help" in args:
300
518
  print(__doc__)
301
519
  return 0
302
- as_json = "--json" in args
303
- args = [arg for arg in args if arg != "--json"]
520
+ as_json = _take(args, "--json")
521
+ fix = _take(args, "--fix")
522
+ write = _take(args, "--write")
523
+ do_sweep = _take(args, "--sweep")
524
+ do_baseline = _take(args, "--baseline")
304
525
  root = None
305
526
  if "--root" in args:
306
527
  k = args.index("--root")
307
528
  root = os.path.abspath(args[k + 1])
308
529
  del args[k:k + 2]
309
- if args:
530
+ if args or (write and not fix) or sum((fix, do_sweep, do_baseline)) > 1:
310
531
  print(__doc__, file=sys.stderr)
311
532
  return 2
312
533
  top = subprocess.run(["git", "-C", root or os.getcwd(), "rev-parse", "--show-toplevel"],
@@ -321,6 +542,12 @@ def main(argv: list[str] | None = None) -> int:
321
542
  else:
322
543
  print(f"softure-doctor: no context/ directory in {root}, nothing to check")
323
544
  return 0
545
+ if fix:
546
+ return run_fix(reader, root, git_root, write, as_json)
547
+ if do_sweep:
548
+ return run_sweep(reader, root, git_root, as_json)
549
+ if do_baseline:
550
+ return run_baseline(reader, root, git_root)
324
551
  findings = run_checks(reader, git_root)
325
552
  failures = [f for f in findings if f.severity == "fail"]
326
553
  if as_json:
@@ -329,8 +556,14 @@ def main(argv: list[str] | None = None) -> int:
329
556
  return 1 if failures else 0
330
557
  for finding in findings:
331
558
  print(finding)
559
+ baselined = sum(1 for f in findings if f.severity == "baselined")
560
+ if baselined:
561
+ print(f"softure-doctor: {baselined} failure(s) accepted by {BASELINE_PATH} (last resort; sweep them to zero)")
332
562
  if failures:
333
563
  print(f"softure-doctor: {len(failures)} problem(s) in the context/ contract (WORKFLOW.md §12)")
564
+ mechanical = sum(1 for f in failures if f.code in ("archived-change-status", "index-missing-file"))
565
+ if mechanical:
566
+ print(f"softure-doctor: {mechanical} of them may be mechanical: `doctor --fix` shows the edits")
334
567
  return 1
335
568
  print("softure-doctor: context/ contract OK")
336
569
  return 0