@softure-ai/skills 0.19.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.
- package/ONBOARD.md +1 -1
- package/README.md +44 -0
- package/WORKFLOW.md +210 -6
- package/package.json +2 -1
- package/rules/AGENTS.md +26 -1
- package/scripts/install.mjs +70 -1
- package/scripts/portfolio.py +328 -0
- package/skills/softure-archive/SKILL.md +15 -6
- package/skills/softure-doctor/SKILL.md +146 -0
- package/skills/softure-doctor/references/state.schema.json +125 -0
- package/skills/softure-doctor/scripts/context_state.py +622 -0
- package/skills/softure-doctor/scripts/doctor.py +573 -0
- package/skills/softure-doctor/scripts/doctor_fix.py +227 -0
- package/skills/softure-doctor/scripts/doctor_sweep.py +386 -0
- package/skills/softure-roadmap/SKILL.md +21 -3
- package/skills/softure-worktree/scripts/wt-roadmap.py +66 -5
- package/skills/softure-worktree-manager/SKILL.md +7 -1
- package/skills/softure-worktree-manager/references/report-routine.md +3 -1
|
@@ -0,0 +1,573 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""softure-doctor: check the `context/` contract of a project (WORKFLOW.md §12) and exit non-zero on drift.
|
|
3
|
+
|
|
4
|
+
doctor.py [--root <dir>] [--json]
|
|
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)
|
|
9
|
+
|
|
10
|
+
Adopting projects run it in their CI check, documentation-only changes included (that is where the
|
|
11
|
+
drift happens). `softure-archive` and `softure-roadmap --close` run it before their commit and fix
|
|
12
|
+
what they own. Each problem is one line `FAIL <code> <path>: <what>`; the codes:
|
|
13
|
+
|
|
14
|
+
roadmap-archived-not-removed roadmap.md is still there although the same roadmap is in foundation/archive/
|
|
15
|
+
roadmap-status-mismatch roadmap.md `status` contradicts its rows (done with open rows; waiting)
|
|
16
|
+
archived-change-status an archived change.md whose status is not `archived`
|
|
17
|
+
archived-change-progress an archived plan.md with unticked Automated items in `## Progress`
|
|
18
|
+
archived-roadmap-open-items an archived roadmap with rows that are not done, done_code, dropped or carried
|
|
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)
|
|
22
|
+
queued-roadmap-done a queued roadmap in foundation/roadmaps/ whose rows are all done
|
|
23
|
+
backlog-without-roadmap a backlog/roadmap-<slug>/ folder without its queued (or promoted) roadmap
|
|
24
|
+
index-missing-file an index row (README.md / INDEX.md table under context/) links a missing file
|
|
25
|
+
state-missing context/state.json is missing although the project has written it before
|
|
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.
|
|
38
|
+
|
|
39
|
+
A project that has never written `context/state.json` (it adopted the package before the file existed)
|
|
40
|
+
gets a note, not a failure: the first run of `wt-roadmap.py`, `softure-archive` or `softure-roadmap`
|
|
41
|
+
creates it. Fix a stale or missing file with `npx softure-skills state` (or
|
|
42
|
+
`python3 .claude/skills/softure-doctor/scripts/context_state.py write`) and commit it.
|
|
43
|
+
|
|
44
|
+
Importable: `from doctor import run_checks` (takes any reader of context_state).
|
|
45
|
+
"""
|
|
46
|
+
from __future__ import annotations
|
|
47
|
+
|
|
48
|
+
import json
|
|
49
|
+
import os
|
|
50
|
+
import re
|
|
51
|
+
import subprocess
|
|
52
|
+
import sys
|
|
53
|
+
|
|
54
|
+
sys.dont_write_bytecode = True # no __pycache__ inside the consumer's .claude/skills
|
|
55
|
+
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
|
56
|
+
from context_state import ( # noqa: E402
|
|
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,
|
|
59
|
+
)
|
|
60
|
+
|
|
61
|
+
ARCHIVE_DIR = "context/archive"
|
|
62
|
+
BASELINE_PATH = "context/doctor-baseline.json"
|
|
63
|
+
NEVER_BASELINED = ("state-missing", "state-stale", "baseline-stale")
|
|
64
|
+
BACKLOG_DIR = "context/backlog"
|
|
65
|
+
CLOSED_STATUSES = ("done", "done_code", "dropped", "carried")
|
|
66
|
+
SHA_RE = re.compile(r"\b[0-9a-f]{7,40}\b")
|
|
67
|
+
EMPTY_MERGE = {"—", "-", "–", "n/a", "none", "no merge", "not merged"}
|
|
68
|
+
LINK_RE = re.compile(r"\[[^\]]*\]\(([^)\s]+)(?:\s+\"[^\"]*\")?\)")
|
|
69
|
+
INDEX_NAMES = ("README.md", "INDEX.md")
|
|
70
|
+
CODE_PATH_RE = re.compile(r"`((?:\.{1,2}/)?(?:[\w.-]+/)*[\w.-]+\.md|(?:\.{1,2}/)?(?:[\w.-]+/)+)`")
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
class Finding:
|
|
74
|
+
def __init__(self, code: str, path: str, message: str, severity: str = "fail") -> None:
|
|
75
|
+
self.code, self.path, self.message, self.severity = code, path, message, severity
|
|
76
|
+
|
|
77
|
+
def as_dict(self) -> dict:
|
|
78
|
+
return {"code": self.code, "path": self.path, "message": self.message, "severity": self.severity}
|
|
79
|
+
|
|
80
|
+
def __str__(self) -> str:
|
|
81
|
+
label = {"fail": "FAIL", "baselined": "baselined"}.get(self.severity, "note")
|
|
82
|
+
return f"{label} {self.code} {self.path}: {self.message}"
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _files(reader, directory: str, pattern: str) -> list[str]:
|
|
86
|
+
return [f"{directory}/{name}" for name, is_dir in reader.listdir(directory)
|
|
87
|
+
if not is_dir and re.match(pattern, name)]
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _archived_roadmaps(reader) -> list[str]:
|
|
91
|
+
"""Archived roadmap files: `<date>-roadmap*.md` in foundation/archive/ that carry a roadmap table."""
|
|
92
|
+
paths = _files(reader, ARCHIVE_ROADMAPS_DIR, r"^\d{4}-\d{2}-\d{2}-roadmap.*\.md$")
|
|
93
|
+
return [path for path in paths if roadmap_rows(reader.read(path) or "")]
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def check_main_roadmap(reader) -> list[Finding]:
|
|
97
|
+
findings: list[Finding] = []
|
|
98
|
+
text = reader.read(ROADMAP_PATH)
|
|
99
|
+
if text is None:
|
|
100
|
+
return findings
|
|
101
|
+
meta = frontmatter(text)
|
|
102
|
+
slug, version = meta.get("roadmap"), meta.get("version")
|
|
103
|
+
if slug:
|
|
104
|
+
for path in _archived_roadmaps(reader):
|
|
105
|
+
archived = frontmatter(reader.read(path) or "")
|
|
106
|
+
if archived.get("roadmap") == slug and (not version or not archived.get("version")
|
|
107
|
+
or archived.get("version") == version):
|
|
108
|
+
findings.append(Finding("roadmap-archived-not-removed", ROADMAP_PATH,
|
|
109
|
+
f"roadmap `{slug}` is already archived as {path}; remove roadmap.md "
|
|
110
|
+
"(the close moves it, WORKFLOW §5.2)"))
|
|
111
|
+
break
|
|
112
|
+
rows = roadmap_rows(text)
|
|
113
|
+
status = meta.get("status")
|
|
114
|
+
open_rows = [row["id"] for row in rows if row["status"] not in CLOSED_STATUSES]
|
|
115
|
+
if status == "done" and open_rows:
|
|
116
|
+
findings.append(Finding("roadmap-status-mismatch", ROADMAP_PATH,
|
|
117
|
+
f"status is done but rows are open: {', '.join(open_rows)}"))
|
|
118
|
+
if status == "waiting":
|
|
119
|
+
findings.append(Finding("roadmap-status-mismatch", ROADMAP_PATH,
|
|
120
|
+
"status is waiting, which belongs to a queued roadmap; the main roadmap is "
|
|
121
|
+
"draft, ready or done (a promote sets ready)"))
|
|
122
|
+
return findings
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def check_archived_changes(reader) -> list[Finding]:
|
|
126
|
+
findings: list[Finding] = []
|
|
127
|
+
for name, is_dir in reader.listdir(ARCHIVE_DIR):
|
|
128
|
+
if not is_dir:
|
|
129
|
+
continue
|
|
130
|
+
folder = f"{ARCHIVE_DIR}/{name}"
|
|
131
|
+
change = reader.read(f"{folder}/change.md")
|
|
132
|
+
if change is not None:
|
|
133
|
+
status = frontmatter(change).get("status")
|
|
134
|
+
if status != "archived":
|
|
135
|
+
findings.append(Finding("archived-change-status", f"{folder}/change.md",
|
|
136
|
+
f"status is {status or 'missing'}, expected archived"))
|
|
137
|
+
plan = reader.read(f"{folder}/plan.md")
|
|
138
|
+
if plan is not None:
|
|
139
|
+
open_items = unticked_automated(plan)
|
|
140
|
+
if open_items:
|
|
141
|
+
listed = "; ".join(open_items[:3]) + ("; …" if len(open_items) > 3 else "")
|
|
142
|
+
findings.append(Finding("archived-change-progress", f"{folder}/plan.md",
|
|
143
|
+
f"{len(open_items)} unticked Automated item(s) in ## Progress: {listed}"))
|
|
144
|
+
return findings
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def unticked_automated(plan: str) -> list[str]:
|
|
148
|
+
"""Open `- [ ]` items of `## Progress` that are not under a `#### Manual` heading.
|
|
149
|
+
|
|
150
|
+
Open Manual items are legitimate in an archived plan (manual mode carries them to the owner).
|
|
151
|
+
"""
|
|
152
|
+
progress = sections(plan).get("Progress", [])
|
|
153
|
+
open_items = []
|
|
154
|
+
manual = False
|
|
155
|
+
for line in progress:
|
|
156
|
+
if line.startswith("#### "):
|
|
157
|
+
manual = line[5:].strip().lower().startswith("manual")
|
|
158
|
+
continue
|
|
159
|
+
if line.startswith("### "):
|
|
160
|
+
manual = False
|
|
161
|
+
continue
|
|
162
|
+
match = re.match(r"^\s*- \[ \] (.+)$", line)
|
|
163
|
+
if match and not manual:
|
|
164
|
+
open_items.append(match.group(1).strip())
|
|
165
|
+
return open_items
|
|
166
|
+
|
|
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
|
+
|
|
177
|
+
def check_archived_roadmaps(reader) -> list[Finding]:
|
|
178
|
+
findings: list[Finding] = []
|
|
179
|
+
pending = pending_release_roadmap(reader)
|
|
180
|
+
for path in _archived_roadmaps(reader):
|
|
181
|
+
text = reader.read(path) or ""
|
|
182
|
+
open_rows = [f"{row['id']} ({row['status']})" for row in roadmap_rows(text)
|
|
183
|
+
if row["status"] not in CLOSED_STATUSES]
|
|
184
|
+
if open_rows:
|
|
185
|
+
findings.append(Finding("archived-roadmap-open-items", path,
|
|
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}"))
|
|
193
|
+
bad = summary_placeholders(text)
|
|
194
|
+
if bad:
|
|
195
|
+
findings.append(Finding("archived-roadmap-summary", path,
|
|
196
|
+
"## Summary merge column holds placeholders instead of merge SHAs: "
|
|
197
|
+
+ "; ".join(bad[:4])))
|
|
198
|
+
return findings
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def summary_placeholders(text: str) -> list[str]:
|
|
202
|
+
"""Rows of the `## Summary` table whose `Merge` cell holds no SHA (and is not an explicit dash)."""
|
|
203
|
+
lines = sections(text).get("Summary", [])
|
|
204
|
+
header = None
|
|
205
|
+
bad = []
|
|
206
|
+
for line in lines:
|
|
207
|
+
if not line.strip().startswith("|"):
|
|
208
|
+
continue
|
|
209
|
+
parts = [cell.strip() for cell in line.strip().strip("|").split("|")]
|
|
210
|
+
if header is None:
|
|
211
|
+
header = [cell.lower() for cell in parts]
|
|
212
|
+
continue
|
|
213
|
+
if all(re.fullmatch(r":?-{3,}:?", cell) for cell in parts if cell):
|
|
214
|
+
continue
|
|
215
|
+
index = header.index("merge") if "merge" in header else len(parts) - 1
|
|
216
|
+
cell = parts[index] if index < len(parts) else ""
|
|
217
|
+
if SHA_RE.search(cell) or cell.strip("`* ").lower() in EMPTY_MERGE:
|
|
218
|
+
continue
|
|
219
|
+
bad.append(f"{parts[0]}: \"{cell}\"")
|
|
220
|
+
return bad
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def check_queued_and_backlog(reader) -> list[Finding]:
|
|
224
|
+
findings: list[Finding] = []
|
|
225
|
+
queued_slugs = set()
|
|
226
|
+
for path in _files(reader, QUEUED_DIR, r"^roadmap-.+\.md$"):
|
|
227
|
+
text = reader.read(path) or ""
|
|
228
|
+
slug = os.path.basename(path)[len("roadmap-"):-len(".md")]
|
|
229
|
+
queued_slugs.add(slug)
|
|
230
|
+
rows = roadmap_rows(text)
|
|
231
|
+
if rows and all(row["status"] in ("done", "done_code") for row in rows):
|
|
232
|
+
findings.append(Finding("queued-roadmap-done", path,
|
|
233
|
+
f"all {len(rows)} rows are done but the roadmap is still queued; "
|
|
234
|
+
"archive it to foundation/archive/ (WORKFLOW §5.2)"))
|
|
235
|
+
main = frontmatter(reader.read(ROADMAP_PATH) or "")
|
|
236
|
+
for name, is_dir in reader.listdir(BACKLOG_DIR):
|
|
237
|
+
if not is_dir or not name.startswith("roadmap-"):
|
|
238
|
+
continue
|
|
239
|
+
slug = name[len("roadmap-"):]
|
|
240
|
+
promoted = main.get("roadmap") == slug or (main.get("backlog") or "").rstrip("/").endswith(name)
|
|
241
|
+
if slug not in queued_slugs and not promoted:
|
|
242
|
+
findings.append(Finding("backlog-without-roadmap", f"{BACKLOG_DIR}/{name}/",
|
|
243
|
+
f"no {QUEUED_DIR}/roadmap-{slug}.md and the main roadmap is not `{slug}`; "
|
|
244
|
+
"move live entries to a queued roadmap or remove the folder (WORKFLOW §5.1)"))
|
|
245
|
+
return findings
|
|
246
|
+
|
|
247
|
+
|
|
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] = []
|
|
255
|
+
for path in _walk(reader, "context"):
|
|
256
|
+
if os.path.basename(path) not in INDEX_NAMES:
|
|
257
|
+
continue
|
|
258
|
+
base = os.path.dirname(path)
|
|
259
|
+
for number, line in enumerate((reader.read(path) or "").splitlines(), start=1):
|
|
260
|
+
if not line.strip().startswith("|"):
|
|
261
|
+
continue
|
|
262
|
+
for target in LINK_RE.findall(line):
|
|
263
|
+
if re.match(r"^[a-z][a-z0-9+.-]*:", target, re.IGNORECASE) or target.startswith("#"):
|
|
264
|
+
continue
|
|
265
|
+
rel = target.split("#", 1)[0]
|
|
266
|
+
if not rel:
|
|
267
|
+
continue
|
|
268
|
+
resolved = os.path.normpath(os.path.join(base, rel)).replace(os.sep, "/")
|
|
269
|
+
if resolved.startswith("..") or not resolved.startswith("context/"):
|
|
270
|
+
continue # outside context/: not this check's business
|
|
271
|
+
if not reader.exists(resolved.rstrip("/")):
|
|
272
|
+
out.append({"path": path, "line": number, "text": line, "kind": "link", "target": target,
|
|
273
|
+
"base": base, "candidates": [resolved.rstrip("/")]})
|
|
274
|
+
for target in CODE_PATH_RE.findall(line):
|
|
275
|
+
# A path in backticks: relative to the index, to context/ or to the repository root.
|
|
276
|
+
candidates = [os.path.normpath(os.path.join(prefix, target)).replace(os.sep, "/").rstrip("/")
|
|
277
|
+
for prefix in (base, "context", ".")]
|
|
278
|
+
inside = [c for c in candidates if c.startswith("context/")]
|
|
279
|
+
if inside and not any(reader.exists(c) for c in inside):
|
|
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"))
|
|
291
|
+
return findings
|
|
292
|
+
|
|
293
|
+
|
|
294
|
+
def _walk(reader, directory: str) -> list[str]:
|
|
295
|
+
out = []
|
|
296
|
+
for name, is_dir in reader.listdir(directory):
|
|
297
|
+
path = f"{directory}/{name}"
|
|
298
|
+
if is_dir:
|
|
299
|
+
out += _walk(reader, path)
|
|
300
|
+
else:
|
|
301
|
+
out.append(path)
|
|
302
|
+
return out
|
|
303
|
+
|
|
304
|
+
|
|
305
|
+
def ever_written(root: str | None) -> bool | None:
|
|
306
|
+
"""Whether git history has ever held context/state.json; None when that cannot be told."""
|
|
307
|
+
if not root:
|
|
308
|
+
return None
|
|
309
|
+
probe = subprocess.run(["git", "-C", root, "rev-parse", "--is-shallow-repository"],
|
|
310
|
+
capture_output=True, text=True)
|
|
311
|
+
if probe.returncode != 0 or probe.stdout.strip() == "true":
|
|
312
|
+
return None
|
|
313
|
+
log = subprocess.run(["git", "-C", root, "log", "--all", "-1", "--format=%H", "--", STATE_PATH],
|
|
314
|
+
capture_output=True, text=True)
|
|
315
|
+
return log.returncode == 0 and bool(log.stdout.strip())
|
|
316
|
+
|
|
317
|
+
|
|
318
|
+
def check_state(reader, root: str | None) -> list[Finding]:
|
|
319
|
+
if not reader.exists("context"):
|
|
320
|
+
return []
|
|
321
|
+
problem = staleness(reader)
|
|
322
|
+
if problem is None:
|
|
323
|
+
return []
|
|
324
|
+
if problem == "missing":
|
|
325
|
+
if ever_written(root):
|
|
326
|
+
return [Finding("state-missing", STATE_PATH,
|
|
327
|
+
"missing, but git history holds it: regenerate it (`npx softure-skills state`) and commit")]
|
|
328
|
+
return [Finding("state-missing", STATE_PATH,
|
|
329
|
+
"not written yet; the next wt-roadmap.py, softure-archive or softure-roadmap run creates it",
|
|
330
|
+
severity="note")]
|
|
331
|
+
return [Finding("state-stale", STATE_PATH,
|
|
332
|
+
f"{problem}; regenerate it (`npx softure-skills state`) and commit")]
|
|
333
|
+
|
|
334
|
+
|
|
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
|
+
"""
|
|
341
|
+
if not reader.exists("context"):
|
|
342
|
+
return []
|
|
343
|
+
findings: list[Finding] = []
|
|
344
|
+
for check in (check_main_roadmap, check_archived_changes, check_archived_roadmaps,
|
|
345
|
+
check_queued_and_backlog, check_indexes):
|
|
346
|
+
findings += check(reader)
|
|
347
|
+
findings += check_state(reader, root)
|
|
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
|
|
513
|
+
|
|
514
|
+
|
|
515
|
+
def main(argv: list[str] | None = None) -> int:
|
|
516
|
+
args = list(sys.argv[1:] if argv is None else argv)
|
|
517
|
+
if "-h" in args or "--help" in args:
|
|
518
|
+
print(__doc__)
|
|
519
|
+
return 0
|
|
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")
|
|
525
|
+
root = None
|
|
526
|
+
if "--root" in args:
|
|
527
|
+
k = args.index("--root")
|
|
528
|
+
root = os.path.abspath(args[k + 1])
|
|
529
|
+
del args[k:k + 2]
|
|
530
|
+
if args or (write and not fix) or sum((fix, do_sweep, do_baseline)) > 1:
|
|
531
|
+
print(__doc__, file=sys.stderr)
|
|
532
|
+
return 2
|
|
533
|
+
top = subprocess.run(["git", "-C", root or os.getcwd(), "rev-parse", "--show-toplevel"],
|
|
534
|
+
capture_output=True, text=True)
|
|
535
|
+
toplevel = os.path.realpath(top.stdout.strip()) if top.returncode == 0 else None
|
|
536
|
+
root = root or toplevel or os.getcwd()
|
|
537
|
+
git_root = root if toplevel and toplevel == os.path.realpath(root) else None
|
|
538
|
+
reader = FsReader(root)
|
|
539
|
+
if not reader.exists("context"):
|
|
540
|
+
if as_json:
|
|
541
|
+
print(json.dumps({"root": root, "failures": [], "notes": ["no context/ directory"]}, indent=2))
|
|
542
|
+
else:
|
|
543
|
+
print(f"softure-doctor: no context/ directory in {root}, nothing to check")
|
|
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)
|
|
551
|
+
findings = run_checks(reader, git_root)
|
|
552
|
+
failures = [f for f in findings if f.severity == "fail"]
|
|
553
|
+
if as_json:
|
|
554
|
+
print(json.dumps({"root": root, "failures": [f.as_dict() for f in failures],
|
|
555
|
+
"notes": [f.as_dict() for f in findings if f.severity != "fail"]}, indent=2))
|
|
556
|
+
return 1 if failures else 0
|
|
557
|
+
for finding in findings:
|
|
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)")
|
|
562
|
+
if failures:
|
|
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")
|
|
567
|
+
return 1
|
|
568
|
+
print("softure-doctor: context/ contract OK")
|
|
569
|
+
return 0
|
|
570
|
+
|
|
571
|
+
|
|
572
|
+
if __name__ == "__main__":
|
|
573
|
+
sys.exit(main())
|