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