@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,271 @@
1
+ #!/usr/bin/env python3
2
+ """softure-doctor --fix: the mechanical repairs of history, as a dry run unless `--write` is given.
3
+
4
+ doctor.py --fix [--write] [--json] [--root <dir>]
5
+ npx softure-skills doctor --fix [--write]
6
+
7
+ Three shapes are mechanical, and only files under `context/` are edited:
8
+
9
+ archived-change-status an archived change.md gets `status: archived`; the old value is kept as
10
+ `legacy_status` in its front matter (a missing status gets none)
11
+ index-missing-file a row of an index inside an archive folder (`context/archive/`,
12
+ `context/foundation/archive/`) that links a missing file is rewritten to the
13
+ file's current path when git history shows where it moved (rename detection,
14
+ followed across several moves); a file that was deleted on purpose (git shows
15
+ the deletion, no rename) is marked `(removed in <sha>)` with the deleting commit
16
+
17
+ dropped Progress item an unticked item of an archived plan's `## Progress` that is struck through or
18
+ carries a dropped/cancelled/not-applicable note is normalised to
19
+ `- [x] ~~<item>~~ — dropped: <note>` (the doctor already reads it as dropped)
20
+
21
+ Everything else (an index row whose target is not in the history this checkout holds, a live index)
22
+ is a judgement case: `doctor.py --sweep` lists it with evidence. A shallow clone works: what it cannot
23
+ see is skipped and named, never guessed.
24
+ Every edit is printed; a second run after `--write` changes nothing.
25
+
26
+ Importable: `from doctor_fix import plan_fixes, apply_fixes`.
27
+ """
28
+ from __future__ import annotations
29
+
30
+ import os
31
+ import re
32
+ import subprocess
33
+ import sys
34
+
35
+ sys.dont_write_bytecode = True
36
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
37
+ from context_state import frontmatter # noqa: E402
38
+
39
+ ARCHIVE_PREFIXES = ("context/archive/", "context/foundation/archive/")
40
+ REMOVED_MARK = "removed in"
41
+ MAX_HOPS = 10
42
+
43
+
44
+ # ---------------------------------------------------------------- git history
45
+
46
+
47
+ class History:
48
+ """Where files under a git checkout went. `usable` is False without git; `shallow` marks a shallow
49
+ clone, whose answers cover only the commits it holds."""
50
+
51
+ def __init__(self, root: str | None) -> None:
52
+ self.root = root
53
+ self.usable = False
54
+ self.shallow = False
55
+ if root:
56
+ probe = self._git("rev-parse", "--is-shallow-repository")
57
+ self.usable = probe.returncode == 0
58
+ self.shallow = probe.stdout.strip() == "true"
59
+
60
+ def _git(self, *args: str) -> subprocess.CompletedProcess:
61
+ return subprocess.run(["git", "-C", self.root or ".", *args], capture_output=True, text=True)
62
+
63
+ def short(self, sha: str) -> str:
64
+ out = self._git("rev-parse", "--short", sha)
65
+ return out.stdout.strip() if out.returncode == 0 else sha[:7]
66
+
67
+ def exists_now(self, rel: str) -> bool:
68
+ return os.path.exists(os.path.join(self.root or ".", rel))
69
+
70
+ def trace(self, rel: str) -> tuple[str, str] | None:
71
+ """("moved", <current path>) or ("removed", <short sha of the commit that deleted it>); None when
72
+ the history this checkout holds shows neither (never there, or past a shallow clone's edge)."""
73
+ if not self.usable:
74
+ return None
75
+ current = rel.rstrip("/")
76
+ last = None
77
+ for _ in range(MAX_HOPS):
78
+ if current != rel.rstrip("/") and self.exists_now(current):
79
+ return "moved", current
80
+ log = self._git("log", "-1", "--no-merges", "--format=%H", "--", current)
81
+ sha = log.stdout.strip()
82
+ if log.returncode != 0 or not sha:
83
+ break
84
+ last = (sha, current)
85
+ moved_to = self._renamed_in(sha, current)
86
+ if not moved_to or moved_to == current:
87
+ break
88
+ current = moved_to
89
+ if last is None:
90
+ return None
91
+ if current != rel.rstrip("/") and self.exists_now(current):
92
+ return "moved", current
93
+ sha, path = last
94
+ if self.exists_now(path) or not self._deleted_in(sha, path):
95
+ return None
96
+ return "removed", self.short(sha)
97
+
98
+ def _deleted_in(self, sha: str, path: str) -> bool:
99
+ """Whether commit `sha` deletes `path` (a file, or every file under a folder)."""
100
+ shown = self._git("show", "-M", "--name-status", "--format=", sha)
101
+ statuses = [line.split("\t") for line in shown.stdout.splitlines()]
102
+ hits = [parts[0] for parts in statuses if len(parts) >= 2
103
+ and (parts[1] == path or parts[1].startswith(path + "/"))]
104
+ return bool(hits) and all(status == "D" for status in hits)
105
+
106
+ def _renamed_in(self, sha: str, path: str) -> str | None:
107
+ shown = self._git("show", "-M", "--name-status", "--format=", sha)
108
+ moves: dict[str, int] = {}
109
+ for line in shown.stdout.splitlines():
110
+ parts = line.split("\t")
111
+ if len(parts) != 3 or not parts[0].startswith("R"):
112
+ continue
113
+ old, new = parts[1], parts[2]
114
+ if old == path:
115
+ return new
116
+ if old.startswith(path + "/"): # a folder: where most of its files went
117
+ rest = old[len(path):]
118
+ if new.endswith(rest):
119
+ target = new[: len(new) - len(rest)]
120
+ moves[target] = moves.get(target, 0) + 1
121
+ return max(moves, key=moves.get) if moves else None
122
+
123
+
124
+ # ---------------------------------------------------------------- the edits
125
+
126
+
127
+ def fix_change_status(text: str) -> tuple[str, str] | None:
128
+ """The change.md text with `status: archived` (and `legacy_status`), and what changed; None when fine."""
129
+ match = re.match(r"^---\n(.*?)\n---", text, re.DOTALL)
130
+ if not match:
131
+ return "---\nstatus: archived\n---\n\n" + text, "status missing -> archived (front matter added)"
132
+ lines = match.group(1).split("\n")
133
+ meta = frontmatter(text)
134
+ old = meta.get("status")
135
+ if old == "archived":
136
+ return None
137
+ index = next((i for i, line in enumerate(lines) if re.match(r"^status:", line)), None)
138
+ if index is None:
139
+ lines.append("status: archived")
140
+ what = "status missing -> archived"
141
+ else:
142
+ raw = re.sub(r"^status:\s*", "", lines[index]).split(" #", 1)[0].strip()
143
+ lines[index] = "status: archived"
144
+ if "legacy_status" not in meta and raw:
145
+ lines.insert(index + 1, f"legacy_status: {raw}")
146
+ what = f"status {old or 'empty'} -> archived" + (f" (legacy_status: {raw})" if raw else "")
147
+ body = "---\n" + "\n".join(lines) + "\n---" + text[match.end():]
148
+ return body, what
149
+
150
+
151
+ def _relative(new_path: str, missing: dict, original_candidate: str) -> str:
152
+ """`new_path` written the way the row wrote the old one (relative to the index, context/ or the root)."""
153
+ target = missing["target"]
154
+ anchor = ""
155
+ if missing["kind"] == "link" and "#" in target:
156
+ anchor = "#" + target.split("#", 1)[1]
157
+ trailing = "/" if target.split("#", 1)[0].endswith("/") else ""
158
+ if missing["kind"] == "link":
159
+ start = missing["base"]
160
+ else:
161
+ base = missing["base"]
162
+ joined = os.path.normpath(os.path.join(base, target)).replace(os.sep, "/").rstrip("/")
163
+ context_joined = os.path.normpath(os.path.join("context", target)).replace(os.sep, "/").rstrip("/")
164
+ start = base if joined == original_candidate else ("context" if context_joined == original_candidate else ".")
165
+ rel = os.path.relpath(new_path, start).replace(os.sep, "/") if start != "." else new_path
166
+ return rel + trailing + anchor
167
+
168
+
169
+ def _replace_target(line: str, missing: dict, replacement: str | None, gone_note: str | None) -> str:
170
+ target = missing["target"]
171
+ if missing["kind"] == "link":
172
+ pattern = re.compile(r"\[([^\]]*)\]\(" + re.escape(target) + r"((?:\s+\"[^\"]*\")?)\)")
173
+ if replacement is not None:
174
+ return pattern.sub(lambda m: f"[{m.group(1)}]({replacement}{m.group(2)})", line, count=1)
175
+ return pattern.sub(lambda m: f"{m.group(1)} ({gone_note}: {target})", line, count=1)
176
+ cell = re.compile(r"(\|\s*)`?" + re.escape(target) + r"`?(\s*\|)")
177
+ if replacement is not None:
178
+ return cell.sub(lambda m: f"{m.group(1)}`{replacement}`{m.group(2)}", line, count=1)
179
+ return cell.sub(lambda m: f"{m.group(1)}{target} ({gone_note}){m.group(2)}", line, count=1)
180
+
181
+
182
+ def plan_fixes(reader, root: str | None) -> dict:
183
+ """The edits `--fix` would make: {"edits": [...], "skipped": [...], "files": {path: new text}}."""
184
+ import doctor # noqa: E402 (doctor imports this module lazily too)
185
+
186
+ edits: list[dict] = []
187
+ skipped: list[dict] = []
188
+ files: dict[str, str] = {}
189
+
190
+ for name, is_dir in reader.listdir(doctor.ARCHIVE_DIR):
191
+ if not is_dir:
192
+ continue
193
+ rel = f"{doctor.ARCHIVE_DIR}/{name}/change.md"
194
+ text = reader.read(rel)
195
+ if text is None:
196
+ continue
197
+ fixed = fix_change_status(text)
198
+ if fixed:
199
+ files[rel] = fixed[0]
200
+ edits.append({"code": "archived-change-status", "path": rel, "what": fixed[1]})
201
+
202
+ for name, is_dir in reader.listdir(doctor.ARCHIVE_DIR):
203
+ if not is_dir:
204
+ continue
205
+ rel = f"{doctor.ARCHIVE_DIR}/{name}/plan.md"
206
+ text = reader.read(rel)
207
+ if text is None:
208
+ continue
209
+ lines = text.split("\n")
210
+ in_progress = False
211
+ for index, line in enumerate(lines):
212
+ if line.startswith("## "):
213
+ in_progress = line[3:].strip() == "Progress"
214
+ continue
215
+ box = re.match(r"^(\s*)- \[ \] (.+)$", line) if in_progress else None
216
+ normalised = doctor.dropped_line(box.group(2)) if box else None
217
+ if normalised:
218
+ lines[index] = f"{box.group(1)}- [x] {normalised}"
219
+ edits.append({"code": "archived-change-progress", "path": rel, "line": index + 1,
220
+ "what": f"dropped item normalised: {normalised}"})
221
+ if lines != text.split("\n"):
222
+ files[rel] = "\n".join(lines)
223
+
224
+ history = History(root)
225
+ for missing in doctor.missing_index_targets(reader):
226
+ if not missing["path"].startswith(ARCHIVE_PREFIXES):
227
+ skipped.append({"code": "index-missing-file", "path": missing["path"], "target": missing["target"],
228
+ "why": "a live index: fix or drop the row by hand (--sweep)"})
229
+ continue
230
+ if not history.usable:
231
+ skipped.append({"code": "index-missing-file", "path": missing["path"], "target": missing["target"],
232
+ "why": "not a git checkout"})
233
+ continue
234
+ found = None
235
+ for candidate in missing["candidates"]:
236
+ traced = history.trace(candidate)
237
+ if traced:
238
+ found = (candidate, traced)
239
+ break
240
+ if not found:
241
+ why = ("not moved or deleted in the history this shallow clone holds (fetch more with "
242
+ "`git fetch --deepen`), or never in git: fix or drop the row (--sweep)" if history.shallow
243
+ else "git shows no move or deletion (never in git?): fix or drop the row (--sweep)")
244
+ skipped.append({"code": "index-missing-file", "path": missing["path"], "target": missing["target"],
245
+ "why": why})
246
+ continue
247
+ candidate, (kind, value) = found
248
+ text = files.get(missing["path"], reader.read(missing["path"]) or "")
249
+ lines = text.split("\n")
250
+ index = missing["line"] - 1
251
+ if index >= len(lines):
252
+ continue
253
+ if kind == "moved":
254
+ new_target = _relative(value, missing, candidate)
255
+ lines[index] = _replace_target(lines[index], missing, new_target, None)
256
+ what = f"`{missing['target']}` -> `{new_target}` (moved to {value})"
257
+ else:
258
+ note = f"{REMOVED_MARK} {value}"
259
+ lines[index] = _replace_target(lines[index], missing, None, note)
260
+ what = f"`{missing['target']}` marked ({note})"
261
+ files[missing["path"]] = "\n".join(lines)
262
+ edits.append({"code": "index-missing-file", "path": missing["path"], "line": missing["line"], "what": what})
263
+ return {"edits": edits, "skipped": skipped, "files": files}
264
+
265
+
266
+ def apply_fixes(root: str, files: dict[str, str]) -> None:
267
+ for rel, text in files.items():
268
+ if not rel.startswith("context/"):
269
+ raise ValueError(f"--fix writes only under context/, not {rel}")
270
+ with open(os.path.join(root, rel), "w", encoding="utf-8") as fh:
271
+ fh.write(text)