@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.
@@ -0,0 +1,622 @@
1
+ #!/usr/bin/env python3
2
+ """Build `context/state.json`: the machine-readable state of a project (WORKFLOW.md §12).
3
+
4
+ context_state.py write [--root <dir>] [--staged] regenerate context/state.json
5
+ context_state.py print [--root <dir>] [--staged] print what `write` would write
6
+ context_state.py check [--root <dir>] exit 1 when the file is missing or stale
7
+
8
+ The file is written only by scripts, never by hand: `wt-roadmap.py` (every mode) commits it together
9
+ with `roadmap.md`, and `softure-archive` and `softure-roadmap` (record, promote, close) run
10
+ `write --staged` right before their commit. `--staged` reads what is staged (the index) instead of
11
+ the working tree, so someone else's uncommitted edits never leak into the file, and stages the result.
12
+
13
+ Everything in the file is derived from the markdown under `context/` (and `context/workflow.json`):
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 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
19
+ (`../references/state.schema.json`). A reader needs this one file per repository instead of parsing
20
+ the markdown.
21
+
22
+ `since` of an owner-queue entry is kept from the previous file for an entry that is still there, so
23
+ "oldest first" stays true across rewrites. `updated_at` changes only when the content does.
24
+
25
+ Importable: `from context_state import build_state, render_state, FsReader, GitReader, IndexReader`.
26
+ """
27
+ from __future__ import annotations
28
+
29
+ import datetime as dt
30
+ import json
31
+ import os
32
+ import re
33
+ import subprocess
34
+ import sys
35
+
36
+ sys.dont_write_bytecode = True # no __pycache__ inside the consumer's .claude/skills
37
+
38
+ SCHEMA_VERSION = 1
39
+ STATE_PATH = "context/state.json"
40
+ WORKFLOW_PATH = "context/workflow.json"
41
+ ROADMAP_PATH = "context/foundation/roadmap.md"
42
+ QUEUED_DIR = "context/foundation/roadmaps"
43
+ ARCHIVE_ROADMAPS_DIR = "context/foundation/archive"
44
+ CHANGES_DIR = "context/changes"
45
+ # Fields a script rewrites without the markdown changing: never a reason to call the file stale.
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>.+)$")
51
+
52
+ ROW_RE = re.compile(r"^\|\s*\*\*(?P<id>[A-Z]+-\d+)\*\*\s*\|")
53
+ ID_RE = re.compile(r"\b[A-Z]+-\d+\b")
54
+ DATE_RE = re.compile(r"\b(\d{4}-\d{2}-\d{2})\b")
55
+ STATUS_RE = re.compile(r"^(proposed|ready_to_merge|ready|blocked|in_progress|done_code|done|dropped|carried)\b")
56
+ SINCE_RE = re.compile(r"since (\d{4}-\d{2}-\d{2})")
57
+ DONE_CODE_DATE_RE = re.compile(r"^done_code \((\d{4}-\d{2}-\d{2})")
58
+ CHECKBOX_RE = re.compile(r"^\s*- \[(?P<mark>[ xX])\] (?P<text>.+)$")
59
+ ITEM_REF_RE = re.compile(r"\*\*(?P<id>[A-Z]+-\d+)\*\*")
60
+ SECRET_RE = re.compile(r"\b(secret|api[ -]?key|token|credential|password|private key)s?\b", re.IGNORECASE)
61
+ RELEASE_LINE_RE = re.compile(
62
+ r"^(?:- )?\**Release:?\**:?\s*(?P<version>v?\d+\.\d+\.\d+[0-9A-Za-z.+-]*)(?:\s*\((?P<date>\d{4}-\d{2}-\d{2})\))?")
63
+ OWNER_SECTION = "Owner decisions and checks"
64
+ RELEASE_SECTION = "Before the next release"
65
+ DONE_STATUSES = ("done", "done_code")
66
+
67
+
68
+ # ---------------------------------------------------------------- readers
69
+
70
+
71
+ class FsReader:
72
+ """Reads the working tree under `root`; `overrides` maps a path to replacement text (None: absent)."""
73
+
74
+ def __init__(self, root: str, overrides: dict | None = None) -> None:
75
+ self.root = os.path.abspath(root)
76
+ self.overrides = dict(overrides or {})
77
+
78
+ def read(self, rel: str) -> str | None:
79
+ if rel in self.overrides:
80
+ return self.overrides[rel]
81
+ try:
82
+ with open(os.path.join(self.root, rel), encoding="utf-8") as fh:
83
+ return fh.read()
84
+ except (FileNotFoundError, NotADirectoryError, IsADirectoryError, UnicodeDecodeError):
85
+ return None
86
+
87
+ def listdir(self, rel: str) -> list[tuple[str, bool]]:
88
+ """Entries of a directory as (name, is_dir), sorted; [] when it does not exist."""
89
+ full = os.path.join(self.root, rel)
90
+ entries: dict[str, bool] = {}
91
+ if os.path.isdir(full):
92
+ for name in os.listdir(full):
93
+ entries[name] = os.path.isdir(os.path.join(full, name))
94
+ _merge_overrides(entries, rel, self.overrides)
95
+ return sorted(entries.items())
96
+
97
+ def exists(self, rel: str) -> bool:
98
+ if rel in self.overrides:
99
+ return self.overrides[rel] is not None
100
+ return os.path.exists(os.path.join(self.root, rel))
101
+
102
+
103
+ class GitReader:
104
+ """Reads a commit (`rev`) of the repository at `repo`, plus `overrides`."""
105
+
106
+ def __init__(self, repo: str, rev: str, overrides: dict | None = None) -> None:
107
+ self.repo = repo
108
+ self.rev = rev
109
+ self.overrides = dict(overrides or {})
110
+ self._tree: dict[str, str] | None = None
111
+
112
+ def _git(self, *args: str) -> subprocess.CompletedProcess:
113
+ return subprocess.run(["git", "-C", self.repo, *args], capture_output=True, text=True)
114
+
115
+ def _paths(self) -> dict[str, str]:
116
+ if self._tree is None:
117
+ listed = self._git("ls-tree", "-r", "-t", self.rev, "--", "context").stdout
118
+ tree: dict[str, str] = {}
119
+ for line in listed.splitlines():
120
+ meta, _, path = line.partition("\t")
121
+ fields = meta.split()
122
+ tree[path] = fields[1] if len(fields) > 1 else "blob"
123
+ self._tree = tree
124
+ return self._tree
125
+
126
+ def read(self, rel: str) -> str | None:
127
+ if rel in self.overrides:
128
+ return self.overrides[rel]
129
+ if self._paths().get(rel) != "blob":
130
+ return None
131
+ shown = self._git("show", f"{self.rev}:{rel}")
132
+ return shown.stdout if shown.returncode == 0 else None
133
+
134
+ def listdir(self, rel: str) -> list[tuple[str, bool]]:
135
+ prefix = rel.rstrip("/") + "/"
136
+ entries: dict[str, bool] = {}
137
+ for path, kind in self._paths().items():
138
+ if path.startswith(prefix) and "/" not in path[len(prefix):]:
139
+ entries[path[len(prefix):]] = kind == "tree"
140
+ _merge_overrides(entries, rel, self.overrides)
141
+ return sorted(entries.items())
142
+
143
+ def exists(self, rel: str) -> bool:
144
+ if rel in self.overrides:
145
+ return self.overrides[rel] is not None
146
+ return rel in self._paths()
147
+
148
+
149
+ class IndexReader(GitReader):
150
+ """Reads what is staged (the index) of the repository at `repo`."""
151
+
152
+ def __init__(self, repo: str, overrides: dict | None = None) -> None:
153
+ super().__init__(repo, "", overrides)
154
+
155
+ def _paths(self) -> dict[str, str]:
156
+ if self._tree is None:
157
+ files = self._git("ls-files", "--", "context").stdout.splitlines()
158
+ tree: dict[str, str] = {}
159
+ for path in files:
160
+ tree[path] = "blob"
161
+ parts = path.split("/")
162
+ for depth in range(1, len(parts)):
163
+ tree.setdefault("/".join(parts[:depth]), "tree")
164
+ self._tree = tree
165
+ return self._tree
166
+
167
+ def read(self, rel: str) -> str | None:
168
+ if rel in self.overrides:
169
+ return self.overrides[rel]
170
+ if self._paths().get(rel) != "blob":
171
+ return None
172
+ shown = self._git("show", f":{rel}")
173
+ return shown.stdout if shown.returncode == 0 else None
174
+
175
+
176
+ def _merge_overrides(entries: dict[str, bool], rel: str, overrides: dict) -> None:
177
+ prefix = rel.rstrip("/") + "/"
178
+ for path, text in overrides.items():
179
+ if not path.startswith(prefix):
180
+ continue
181
+ rest = path[len(prefix):]
182
+ name, _, deeper = rest.partition("/")
183
+ if deeper:
184
+ entries[name] = True
185
+ elif text is None:
186
+ entries.pop(name, None)
187
+ else:
188
+ entries[name] = False
189
+
190
+
191
+ # ---------------------------------------------------------------- markdown parsing
192
+
193
+
194
+ def frontmatter(text: str) -> dict:
195
+ """The `key: value` lines of a leading `---` block; quotes stripped, `null` -> None."""
196
+ match = re.match(r"^---\n(.*?)\n---", text or "", re.DOTALL)
197
+ fields: dict = {}
198
+ if not match:
199
+ return fields
200
+ for line in match.group(1).splitlines():
201
+ pair = re.match(r"^([A-Za-z_][\w-]*):\s*(.*?)\s*(?:#.*)?$", line)
202
+ if not pair:
203
+ continue
204
+ value = pair.group(2).strip()
205
+ if len(value) >= 2 and value[0] == value[-1] and value[0] in "\"'":
206
+ value = value[1:-1]
207
+ fields[pair.group(1)] = None if value in ("", "null", "~") else value
208
+ return fields
209
+
210
+
211
+ def sections(text: str) -> dict[str, list[str]]:
212
+ """Lines under each `## <heading>` (the heading itself excluded); later duplicates append."""
213
+ result: dict[str, list[str]] = {}
214
+ current = None
215
+ for line in (text or "").splitlines():
216
+ if line.startswith("## "):
217
+ current = line[3:].strip()
218
+ result.setdefault(current, [])
219
+ continue
220
+ if current is not None:
221
+ result[current].append(line)
222
+ return result
223
+
224
+
225
+ def title_of(text: str) -> str | None:
226
+ for line in (text or "").splitlines():
227
+ if line.startswith("# "):
228
+ return line[2:].strip()
229
+ return None
230
+
231
+
232
+ def cells(line: str) -> list[str]:
233
+ return [cell.strip() for cell in line.strip().strip("|").split("|")]
234
+
235
+
236
+ def parse_status(raw: str) -> dict:
237
+ """`**in_progress** (plan, since 2026-10-01; …)` -> keyword, detail, stage, since."""
238
+ text = raw.replace("**", "").strip()
239
+ match = STATUS_RE.match(text)
240
+ keyword = match.group(1) if match else (text.split(" ", 1)[0] if text else "unknown")
241
+ detail = None
242
+ paren = re.search(r"\((.*)\)\s*$", text)
243
+ if paren:
244
+ detail = paren.group(1).strip()
245
+ stage = None
246
+ if keyword == "in_progress" and detail:
247
+ stage = re.split(r"[,;]", detail, maxsplit=1)[0].strip() or None
248
+ since = None
249
+ found = SINCE_RE.search(text) or DONE_CODE_DATE_RE.match(text)
250
+ if found:
251
+ since = found.group(1)
252
+ return {"status": keyword, "detail": detail, "stage": stage, "since": since}
253
+
254
+
255
+ def roadmap_rows(text: str) -> list[dict]:
256
+ """Table rows `| **ID** | `change-id` | outcome | depends on | mode | status |` (WORKFLOW §5)."""
257
+ rows = []
258
+ seen = set()
259
+ for line in (text or "").splitlines():
260
+ if not ROW_RE.match(line):
261
+ continue
262
+ parts = cells(line)
263
+ if len(parts) < 3:
264
+ continue
265
+ rid = ID_RE.search(parts[0]).group(0)
266
+ if rid in seen:
267
+ continue
268
+ seen.add(rid)
269
+ change = parts[1].strip("` ") if len(parts) > 1 else None
270
+ status = parse_status(parts[-1])
271
+ rows.append({
272
+ "id": rid,
273
+ "change_id": change or None,
274
+ "outcome": parts[2] if len(parts) > 3 else None,
275
+ "prerequisites": ID_RE.findall(parts[3]) if len(parts) > 4 else [],
276
+ "mode": parts[4] if len(parts) > 5 else None,
277
+ **status,
278
+ })
279
+ return rows
280
+
281
+
282
+ def open_checkboxes(lines: list[str]) -> list[str]:
283
+ out = []
284
+ for line in lines:
285
+ match = CHECKBOX_RE.match(line)
286
+ if match and match.group("mark") == " ":
287
+ out.append(match.group("text").strip())
288
+ return out
289
+
290
+
291
+ # ---------------------------------------------------------------- state
292
+
293
+
294
+ def _today() -> str:
295
+ return dt.datetime.now(dt.timezone.utc).date().isoformat()
296
+
297
+
298
+ def _owner_entries(path: str, text: str, rows: list[dict], fallback_since: str,
299
+ archived: bool = False) -> list[dict]:
300
+ """Every open entry of one live roadmap file that waits for the owner.
301
+
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).
304
+ """
305
+ entries: list[dict] = []
306
+ parts = sections(text)
307
+ ids_with_entry: set[str] = set()
308
+ for line in ([] if archived else open_checkboxes(parts.get(OWNER_SECTION, []))):
309
+ ref = ITEM_REF_RE.search(line)
310
+ item = ref.group("id") if ref else None
311
+ lowered = line.lower()
312
+ if "owner step:" in lowered:
313
+ kind = "secret" if SECRET_RE.search(line) else "step"
314
+ elif re.search(r"\(Manual \d", line):
315
+ kind = "step"
316
+ else:
317
+ kind = "decision"
318
+ if item:
319
+ ids_with_entry.add(item)
320
+ entries.append({"kind": kind, "source": f"{path}#{OWNER_SECTION}", "item": item,
321
+ "since": _date_in(line) or fallback_since, "text": line})
322
+ for line in open_checkboxes(parts.get(RELEASE_SECTION, [])):
323
+ ref = ITEM_REF_RE.search(line)
324
+ entries.append({"kind": "secret" if SECRET_RE.search(line) else "step",
325
+ "source": f"{path}#{RELEASE_SECTION}", "item": ref.group("id") if ref else None,
326
+ "since": _date_in(line) or fallback_since, "text": line})
327
+ waiting_release = []
328
+ for row in ([] if archived else rows):
329
+ if row["status"] != "done_code":
330
+ continue
331
+ waiting = re.sub(r"^\d{4}-\d{2}-\d{2};\s*", "", row["detail"] or "")
332
+ waiting = re.sub(r"^waiting:\s*", "", waiting)
333
+ if "release" in waiting.lower():
334
+ waiting_release.append(row)
335
+ elif "owner" in waiting.lower() and row["id"] not in ids_with_entry:
336
+ entries.append({"kind": "secret" if SECRET_RE.search(waiting) else "step",
337
+ "source": f"{path}#At a glance", "item": row["id"],
338
+ "since": row["since"] or fallback_since, "text": f"{row['id']}: {waiting}"})
339
+ if waiting_release:
340
+ ids = ", ".join(row["id"] for row in waiting_release)
341
+ dates = [row["since"] for row in waiting_release if row["since"]]
342
+ entries.append({"kind": "word", "source": f"{path}#At a glance", "item": None,
343
+ "since": min(dates) if dates else fallback_since,
344
+ "text": f"release: {ids} merged and waiting for a release"})
345
+ return entries
346
+
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
+
380
+ def _date_in(text: str) -> str | None:
381
+ match = DATE_RE.search(text)
382
+ return match.group(1) if match else None
383
+
384
+
385
+ def _summary(rows: list[dict]) -> tuple[int, int]:
386
+ return sum(1 for row in rows if row["status"] in DONE_STATUSES), len(rows)
387
+
388
+
389
+ def _roadmap_files(reader, directory: str, pattern: str) -> list[str]:
390
+ return [f"{directory}/{name}" for name, is_dir in reader.listdir(directory)
391
+ if not is_dir and re.match(pattern, name)]
392
+
393
+
394
+ def _last_release(reader) -> dict | None:
395
+ for path in reversed(archived_roadmap_files(reader)):
396
+ text = reader.read(path) or ""
397
+ for line in reversed(sections(text).get("Summary", [])):
398
+ match = RELEASE_LINE_RE.match(line.strip())
399
+ if match:
400
+ return {"version": match.group("version"), "date": match.group("date"), "source": path}
401
+ return None
402
+
403
+
404
+ def build_state(reader, prior: dict | None = None, now: str | None = None) -> dict:
405
+ """The state of the project that `reader` sees. `prior` keeps the `since` of entries still present."""
406
+ today = _today()
407
+ workflow: dict = {}
408
+ raw = reader.read(WORKFLOW_PATH)
409
+ if raw:
410
+ try:
411
+ loaded = json.loads(raw)
412
+ workflow = loaded if isinstance(loaded, dict) else {}
413
+ except json.JSONDecodeError:
414
+ workflow = {}
415
+
416
+ owner_queue: list[dict] = []
417
+ active = None
418
+ roadmap_text = reader.read(ROADMAP_PATH)
419
+ rows_by_change: dict[str, dict] = {}
420
+ if roadmap_text is not None:
421
+ meta = frontmatter(roadmap_text)
422
+ rows = roadmap_rows(roadmap_text)
423
+ done, total = _summary(rows)
424
+ rows_by_change = {row["change_id"]: row for row in rows if row["change_id"]}
425
+ active = {
426
+ "slug": meta.get("roadmap"),
427
+ "title": title_of(roadmap_text),
428
+ "status": meta.get("status"),
429
+ "version": meta.get("version"),
430
+ "path": ROADMAP_PATH,
431
+ "done": done,
432
+ "total": total,
433
+ "items": [{key: row[key] for key in ("id", "change_id", "outcome", "status", "stage", "since",
434
+ "detail", "prerequisites", "mode")}
435
+ for row in rows if row["status"] not in DONE_STATUSES],
436
+ }
437
+ owner_queue += _owner_entries(ROADMAP_PATH, roadmap_text, rows, meta.get("updated") or today)
438
+
439
+ queued = []
440
+ for path in _roadmap_files(reader, QUEUED_DIR, r"^roadmap-.+\.md$"):
441
+ text = reader.read(path) or ""
442
+ meta = frontmatter(text)
443
+ rows = roadmap_rows(text)
444
+ done, total = _summary(rows)
445
+ slug = meta.get("roadmap") or os.path.basename(path)[len("roadmap-"):-len(".md")]
446
+ condition = meta.get("trigger") or _start_order(text)
447
+ since = meta.get("created") or meta.get("updated") or today
448
+ queued.append({
449
+ "slug": slug,
450
+ "title": title_of(text),
451
+ "status": meta.get("status"),
452
+ "path": path,
453
+ "start_condition": condition,
454
+ "done": done,
455
+ "total": total,
456
+ "items": [{key: row[key] for key in ("id", "change_id", "outcome", "status")} for row in rows],
457
+ })
458
+ owner_queue.append({"kind": "word", "source": path, "item": None, "since": since,
459
+ "text": f"start queued roadmap {slug}" + (f": {condition}" if condition else "")})
460
+ owner_queue += _owner_entries(path, text, rows, meta.get("updated") or today)
461
+
462
+ pending = pending_release_roadmap(reader)
463
+ if pending:
464
+ text = reader.read(pending) or ""
465
+ meta = frontmatter(text)
466
+ owner_queue += _owner_entries(pending, text, roadmap_rows(text),
467
+ meta.get("updated") or pending.split("/")[-1][:10], archived=True)
468
+
469
+ open_changes = []
470
+ for name, is_dir in reader.listdir(CHANGES_DIR):
471
+ if not is_dir:
472
+ continue
473
+ text = reader.read(f"{CHANGES_DIR}/{name}/change.md")
474
+ if text is None:
475
+ continue
476
+ meta = frontmatter(text)
477
+ change_id = meta.get("change_id") or name
478
+ row = rows_by_change.get(change_id)
479
+ open_changes.append({
480
+ "change_id": change_id,
481
+ "title": meta.get("title"),
482
+ "status": meta.get("status"),
483
+ "roadmap_item": meta.get("roadmap_item"),
484
+ "updated": meta.get("updated"),
485
+ "stage": (row["stage"] or row["status"]) if row else None,
486
+ })
487
+ owner_queue += _handoff_entries(f"{CHANGES_DIR}/{name}/change.md", text, meta.get("roadmap_item"),
488
+ meta.get("updated") or today)
489
+
490
+ previous = {_entry_key(entry): entry.get("since") for entry in (prior or {}).get("owner_queue", [])}
491
+ for entry in owner_queue:
492
+ entry["since"] = previous.get(_entry_key(entry)) or entry["since"]
493
+ owner_queue.sort(key=lambda entry: (entry["since"] or "", entry["source"], entry["text"]))
494
+
495
+ state = {
496
+ "schema_version": SCHEMA_VERSION,
497
+ "project": workflow.get("project") or (frontmatter(roadmap_text).get("project") if roadmap_text else None),
498
+ "mode": workflow.get("mode") or "manual",
499
+ "main_branch": workflow.get("mainBranch"),
500
+ "updated_at": now or dt.datetime.now(dt.timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z"),
501
+ "active_roadmap": active,
502
+ "queued": queued,
503
+ "open_changes": open_changes,
504
+ "owner_queue": owner_queue,
505
+ "last_release": _last_release(reader),
506
+ }
507
+ return state
508
+
509
+
510
+ def _start_order(text: str) -> str | None:
511
+ """A run-wide order about starting the roadmap (`> - Start: …`), when the header has one."""
512
+ for line in (text or "").splitlines():
513
+ match = re.match(r"^>\s*-\s*(Start[^:]*):\s*(.+)$", line, re.IGNORECASE)
514
+ if match:
515
+ return match.group(2).strip()
516
+ return None
517
+
518
+
519
+ def _entry_key(entry: dict) -> tuple:
520
+ return (entry.get("kind"), entry.get("source"), entry.get("text"))
521
+
522
+
523
+ def comparable(state: dict | None) -> dict | None:
524
+ """The state without what a rewrite may change on its own (VOLATILE_FIELDS, VOLATILE_SOURCES)."""
525
+ if state is None:
526
+ return None
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
531
+
532
+
533
+ def serialize(state: dict) -> str:
534
+ return json.dumps(state, indent=2, ensure_ascii=False) + "\n"
535
+
536
+
537
+ def load_prior(reader) -> dict | None:
538
+ raw = reader.read(STATE_PATH)
539
+ if not raw:
540
+ return None
541
+ try:
542
+ loaded = json.loads(raw)
543
+ except json.JSONDecodeError:
544
+ return None
545
+ return loaded if isinstance(loaded, dict) else None
546
+
547
+
548
+ def render_state(reader) -> str:
549
+ """The text of `context/state.json` for what `reader` sees; the previous text when nothing changed."""
550
+ prior = load_prior(reader)
551
+ state = build_state(reader, prior)
552
+ if prior is not None and prior.get("updated_at") and json.dumps(_stable(prior)) == json.dumps(_stable(state)):
553
+ state["updated_at"] = prior["updated_at"]
554
+ return serialize(state)
555
+
556
+
557
+ def _stable(state: dict) -> dict:
558
+ return {key: value for key, value in state.items() if key != "updated_at"}
559
+
560
+
561
+ def staleness(reader) -> str | None:
562
+ """None when `context/state.json` matches the markdown; otherwise why not."""
563
+ prior = load_prior(reader)
564
+ if prior is None:
565
+ return "missing or not valid JSON" if reader.exists(STATE_PATH) else "missing"
566
+ if prior.get("schema_version") != SCHEMA_VERSION:
567
+ return f"schema_version {prior.get('schema_version')!r}, expected {SCHEMA_VERSION}"
568
+ fresh = build_state(reader, prior)
569
+ old, new = comparable(prior), comparable(fresh)
570
+ if old == new:
571
+ return None
572
+ changed = sorted(key for key in set(old) | set(new) if old.get(key) != new.get(key))
573
+ return "out of date with the markdown (" + ", ".join(changed) + ")"
574
+
575
+
576
+ # ---------------------------------------------------------------- command line
577
+
578
+
579
+ def repo_root(start: str) -> str:
580
+ out = subprocess.run(["git", "-C", start, "rev-parse", "--show-toplevel"], capture_output=True, text=True)
581
+ return out.stdout.strip() if out.returncode == 0 else os.path.abspath(start)
582
+
583
+
584
+ def main(argv: list[str] | None = None) -> int:
585
+ args = list(sys.argv[1:] if argv is None else argv)
586
+ root = None
587
+ if "--root" in args:
588
+ k = args.index("--root")
589
+ root = args[k + 1]
590
+ del args[k:k + 2]
591
+ staged = "--staged" in args
592
+ args = [arg for arg in args if arg != "--staged"]
593
+ if len(args) != 1 or args[0] not in ("write", "print", "check"):
594
+ print(__doc__, file=sys.stderr)
595
+ return 2
596
+ root = os.path.abspath(root) if root else repo_root(os.getcwd())
597
+ if not os.path.isdir(os.path.join(root, "context")):
598
+ print(f"no context/ directory in {root}: nothing to do", file=sys.stderr)
599
+ return 0 if args[0] != "check" else 1
600
+ reader = IndexReader(root) if staged else FsReader(root)
601
+ if args[0] == "check":
602
+ problem = staleness(FsReader(root))
603
+ if problem:
604
+ print(f"{STATE_PATH}: {problem}", file=sys.stderr)
605
+ return 1
606
+ print(f"{STATE_PATH}: up to date")
607
+ return 0
608
+ text = render_state(reader)
609
+ if args[0] == "print":
610
+ sys.stdout.write(text)
611
+ return 0
612
+ target = os.path.join(root, STATE_PATH)
613
+ with open(target, "w", encoding="utf-8") as fh:
614
+ fh.write(text)
615
+ if staged:
616
+ subprocess.run(["git", "-C", root, "add", "--", STATE_PATH], check=True)
617
+ print(f"wrote {STATE_PATH}" + (" (staged)" if staged else ""))
618
+ return 0
619
+
620
+
621
+ if __name__ == "__main__":
622
+ sys.exit(main())