@softure-ai/skills 0.23.0 → 0.25.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.
@@ -4,6 +4,7 @@
4
4
  context_state.py write [--root <dir>] [--staged] regenerate context/state.json
5
5
  context_state.py print [--root <dir>] [--staged] print what `write` would write
6
6
  context_state.py check [--root <dir>] exit 1 when the file is missing or stale
7
+ context_state.py pin-project [--root <dir>] write the derived `project` into context/workflow.json
7
8
 
8
9
  The file is written only by scripts, never by hand: `wt-roadmap.py` (every mode) commits it together
9
10
  with `roadmap.md`, and `softure-archive` and `softure-roadmap` (record, promote, close) run
@@ -19,14 +20,24 @@ release is recorded. An unticked entry left in any other archived roadmap is his
19
20
  (`../references/state.schema.json`). A reader needs this one file per repository instead of parsing
20
21
  the markdown.
21
22
 
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.
23
+ Every owner-queue entry has an `id`: a short hash of its `source`, `item` and text, taken when the entry first
24
+ appears. `id` and `since` are kept from the previous file for an entry that is still there, also when only its
25
+ wording changed or its heading moved within the same file (the same item, or text that is still close enough),
26
+ so a reader can follow one entry across rewrites and "oldest first" stays true. `updated_at` changes only when the
27
+ content does.
28
+
29
+ `project` is workflow.json's `project`, else the active roadmap's, else the repository name. The repository name
30
+ depends on how the checkout was cloned (`owner/REPO` or `owner/repo`), so the first `write` that falls back to it
31
+ pins it in `context/workflow.json` (`project`), and `check` compares a name that came from the repository without
32
+ regard to letter case. `pin-project` does only the pinning (the installer runs it).
24
33
 
25
34
  Importable: `from context_state import build_state, render_state, FsReader, GitReader, IndexReader`.
26
35
  """
27
36
  from __future__ import annotations
28
37
 
29
38
  import datetime as dt
39
+ import difflib
40
+ import hashlib
30
41
  import json
31
42
  import os
32
43
  import re
@@ -35,7 +46,7 @@ import sys
35
46
 
36
47
  sys.dont_write_bytecode = True # no __pycache__ inside the consumer's .claude/skills
37
48
 
38
- SCHEMA_VERSION = 1
49
+ SCHEMA_VERSION = 2
39
50
  STATE_PATH = "context/state.json"
40
51
  WORKFLOW_PATH = "context/workflow.json"
41
52
  ROADMAP_PATH = "context/foundation/roadmap.md"
@@ -401,17 +412,43 @@ def _last_release(reader) -> dict | None:
401
412
  return None
402
413
 
403
414
 
415
+ def read_workflow(reader) -> dict:
416
+ """`context/workflow.json` as a dict; {} when it is absent or not a JSON object."""
417
+ raw = reader.read(WORKFLOW_PATH)
418
+ if not raw:
419
+ return {}
420
+ try:
421
+ loaded = json.loads(raw)
422
+ except json.JSONDecodeError:
423
+ return {}
424
+ return loaded if isinstance(loaded, dict) else {}
425
+
426
+
427
+ def resolve_project(reader, workflow: dict | None = None, roadmap_text: str | None = None,
428
+ prior: dict | None = None) -> tuple[str, bool]:
429
+ """`(project, from_repository)`: workflow.json `project`, else the active roadmap's, else the repository name.
430
+
431
+ `from_repository` is True for the last fallback. Its letter case depends on the clone, so when `prior` (the
432
+ state.json already written) holds the same name in another case, that spelling is kept.
433
+ """
434
+ workflow = read_workflow(reader) if workflow is None else workflow
435
+ if workflow.get("project"):
436
+ return workflow["project"], False
437
+ if roadmap_text is None:
438
+ roadmap_text = reader.read(ROADMAP_PATH)
439
+ if roadmap_text and frontmatter(roadmap_text).get("project"):
440
+ return frontmatter(roadmap_text)["project"], False
441
+ name = repository_name(reader)
442
+ previous = (prior or {}).get("project")
443
+ if isinstance(previous, str) and previous.casefold() == name.casefold():
444
+ name = previous
445
+ return name, True
446
+
447
+
404
448
  def build_state(reader, prior: dict | None = None, now: str | None = None) -> dict:
405
449
  """The state of the project that `reader` sees. `prior` keeps the `since` of entries still present."""
406
450
  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 = {}
451
+ workflow = read_workflow(reader)
415
452
 
416
453
  owner_queue: list[dict] = []
417
454
  active = None
@@ -487,15 +524,12 @@ def build_state(reader, prior: dict | None = None, now: str | None = None) -> di
487
524
  owner_queue += _handoff_entries(f"{CHANGES_DIR}/{name}/change.md", text, meta.get("roadmap_item"),
488
525
  meta.get("updated") or today)
489
526
 
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"]
527
+ owner_queue = carry_identity(owner_queue, (prior or {}).get("owner_queue") or [])
493
528
  owner_queue.sort(key=lambda entry: (entry["since"] or "", entry["source"], entry["text"]))
494
529
 
495
530
  state = {
496
531
  "schema_version": SCHEMA_VERSION,
497
- "project": (workflow.get("project") or (frontmatter(roadmap_text).get("project") if roadmap_text else None)
498
- or repository_name(reader)),
532
+ "project": resolve_project(reader, workflow, roadmap_text, prior)[0],
499
533
  "mode": workflow.get("mode") or "manual",
500
534
  "main_branch": workflow.get("mainBranch"),
501
535
  "updated_at": now or dt.datetime.now(dt.timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z"),
@@ -519,13 +553,54 @@ def repository_name(reader) -> str:
519
553
 
520
554
  The last fallback for `project`, so a project between roadmaps without `project` in workflow.json still
521
555
  has a name. The URL comes first because a checkout's folder can be named anything (a worktree, a clone
522
- into a temporary folder).
556
+ into a temporary folder). The URL's letter case is the clone's, not the forge's: in GitHub Actions the
557
+ forge's spelling (`GITHUB_REPOSITORY`) wins when it names the same repository.
523
558
  """
524
559
  folder = getattr(reader, "root", None) or getattr(reader, "repo", None) or os.getcwd()
525
560
  url = subprocess.run(["git", "-C", folder, "remote", "get-url", "origin"], capture_output=True,
526
561
  text=True).stdout.strip()
527
562
  name = re.split(r"[/:]", url.rstrip("/"))[-1] if url else os.path.basename(os.path.abspath(folder))
528
- return re.sub(r"\.git$", "", name) or "unnamed"
563
+ name = re.sub(r"\.git$", "", name) or "unnamed"
564
+ canonical = os.environ.get("GITHUB_REPOSITORY", "").rsplit("/", 1)[-1]
565
+ return canonical if canonical and canonical.casefold() == name.casefold() else name
566
+
567
+
568
+ def pin_project(root: str, staged: bool = False) -> str | None:
569
+ """Write the repository-derived `project` into `context/workflow.json`; the name written, else None.
570
+
571
+ Nothing is written when `project` does not come from the repository name (workflow.json or the active
572
+ roadmap names it). The spelling is the one `context/state.json` already holds when it matches, so the
573
+ pin never flips a committed name. With `staged` the file is read from and added to the index; a
574
+ workflow.json with unstaged edits is left alone, so nobody's uncommitted work is committed.
575
+ """
576
+ reader = IndexReader(root) if staged else FsReader(root)
577
+ project, from_repository = resolve_project(reader, prior=load_prior(reader))
578
+ if not from_repository:
579
+ return None
580
+ target = os.path.join(root, WORKFLOW_PATH)
581
+ raw = reader.read(WORKFLOW_PATH)
582
+ if staged:
583
+ on_disk = None
584
+ if os.path.exists(target):
585
+ with open(target, encoding="utf-8") as fh:
586
+ on_disk = fh.read()
587
+ if on_disk != raw:
588
+ return None
589
+ workflow: dict = {}
590
+ if raw:
591
+ try:
592
+ loaded = json.loads(raw)
593
+ except json.JSONDecodeError:
594
+ return None # a broken file is the doctor's to report, not ours to overwrite
595
+ if not isinstance(loaded, dict):
596
+ return None
597
+ workflow = loaded
598
+ workflow = {**workflow, "project": project} if "project" in workflow else {"project": project, **workflow}
599
+ with open(target, "w", encoding="utf-8") as fh:
600
+ fh.write(json.dumps(workflow, indent=2, ensure_ascii=False) + "\n")
601
+ if staged:
602
+ subprocess.run(["git", "-C", root, "add", "--", WORKFLOW_PATH], check=True)
603
+ return project
529
604
 
530
605
 
531
606
  def _start_order(text: str) -> str | None:
@@ -541,6 +616,93 @@ def _entry_key(entry: dict) -> tuple:
541
616
  return (entry.get("kind"), entry.get("source"), entry.get("text"))
542
617
 
543
618
 
619
+ # Text of an unmatched entry this close to a prior entry's text (difflib ratio) is the same entry reworded.
620
+ REWORD_RATIO = 0.6
621
+ # The same, across headings of one file (a moved entry): stricter, because the section changed too.
622
+ MOVED_RATIO = 0.8
623
+
624
+
625
+ def entry_id(entry: dict) -> str:
626
+ """A short id for a new owner-queue entry: a hash of its source, item and first line."""
627
+ first_line = (entry.get("text") or "").strip().splitlines()[0] if (entry.get("text") or "").strip() else ""
628
+ seed = "\n".join((entry.get("source") or "", entry.get("item") or "", first_line))
629
+ return "oq-" + hashlib.sha1(seed.encode("utf-8")).hexdigest()[:10]
630
+
631
+
632
+ def _file_of(source: str | None) -> str:
633
+ return (source or "").split("#", 1)[0]
634
+
635
+
636
+ def _same_entry_score(new: dict, old: dict) -> float | None:
637
+ """How surely `old` (prior file) is `new` reworded or moved; None when it is not."""
638
+ if _file_of(new.get("source")) != _file_of(old.get("source")):
639
+ return None
640
+ same_section = new.get("source") == old.get("source")
641
+ ratio = difflib.SequenceMatcher(None, new.get("text") or "", old.get("text") or "").ratio()
642
+ if new.get("item") and new.get("item") == old.get("item") and new.get("kind") == old.get("kind"):
643
+ return 1.0 + ratio + (1.0 if same_section else 0.0)
644
+ if new.get("item") != old.get("item"):
645
+ return None
646
+ if ratio >= (REWORD_RATIO if same_section else MOVED_RATIO):
647
+ return ratio + (1.0 if same_section else 0.0)
648
+ return None
649
+
650
+
651
+ def carry_identity(entries: list[dict], prior: list[dict]) -> list[dict]:
652
+ """Give every entry an `id` and keep `id` and `since` of the prior entry it continues.
653
+
654
+ An entry with the same kind, source and text as a prior one continues it. Each remaining entry continues the
655
+ prior one it matches best: the same file, and the same item and kind, or (without an item) text that is still
656
+ close enough (`REWORD_RATIO` under the same heading, `MOVED_RATIO` under another). A prior entry is continued
657
+ at most once. Anything else is new and gets a fresh id; ids stay unique within the queue.
658
+ """
659
+ unmatched = list(prior)
660
+ exact: dict[tuple, list[dict]] = {}
661
+ for old in unmatched:
662
+ exact.setdefault(_entry_key(old), []).append(old)
663
+ pending = []
664
+ for entry in entries:
665
+ candidates = exact.get(_entry_key(entry))
666
+ if candidates:
667
+ old = candidates.pop(0)
668
+ unmatched.remove(old)
669
+ _continue(entry, old)
670
+ else:
671
+ pending.append(entry)
672
+ pairs = []
673
+ for new_index, entry in enumerate(pending):
674
+ for old_index, old in enumerate(unmatched):
675
+ score = _same_entry_score(entry, old)
676
+ if score is not None:
677
+ pairs.append((score, new_index, old_index))
678
+ taken_new: set[int] = set()
679
+ taken_old: set[int] = set()
680
+ for _score, new_index, old_index in sorted(pairs, key=lambda pair: (-pair[0], pair[1], pair[2])):
681
+ if new_index in taken_new or old_index in taken_old:
682
+ continue
683
+ taken_new.add(new_index)
684
+ taken_old.add(old_index)
685
+ _continue(pending[new_index], unmatched[old_index])
686
+ used: set[str] = set()
687
+ result = []
688
+ for entry in entries:
689
+ ident = entry.get("id") if entry.get("id") not in used else None
690
+ if not ident:
691
+ base = entry_id(entry)
692
+ ident, suffix = base, 2
693
+ while ident in used:
694
+ ident, suffix = f"{base}-{suffix}", suffix + 1
695
+ used.add(ident)
696
+ result.append({"id": ident, **{key: value for key, value in entry.items() if key != "id"}})
697
+ return result
698
+
699
+
700
+ def _continue(entry: dict, old: dict) -> None:
701
+ if old.get("id"):
702
+ entry["id"] = old["id"]
703
+ entry["since"] = old.get("since") or entry["since"]
704
+
705
+
544
706
  def comparable(state: dict | None) -> dict | None:
545
707
  """The state without what a rewrite may change on its own (VOLATILE_FIELDS, VOLATILE_SOURCES)."""
546
708
  if state is None:
@@ -626,13 +788,24 @@ def main(argv: list[str] | None = None) -> int:
626
788
  del args[k:k + 2]
627
789
  staged = "--staged" in args
628
790
  args = [arg for arg in args if arg != "--staged"]
629
- if len(args) != 1 or args[0] not in ("write", "print", "check"):
791
+ if len(args) != 1 or args[0] not in ("write", "print", "check", "pin-project"):
630
792
  print(__doc__, file=sys.stderr)
631
793
  return 2
632
794
  root = os.path.abspath(root) if root else repo_root(os.getcwd())
633
795
  if not os.path.isdir(os.path.join(root, "context")):
634
796
  print(f"no context/ directory in {root}: nothing to do", file=sys.stderr)
635
797
  return 0 if args[0] != "check" else 1
798
+ if args[0] == "pin-project":
799
+ pinned = pin_project(root, staged)
800
+ if pinned:
801
+ print(f"wrote {WORKFLOW_PATH}: \"project\": {json.dumps(pinned, ensure_ascii=False)}"
802
+ + " (staged)" * staged)
803
+ return 0
804
+ if args[0] == "write":
805
+ pinned = pin_project(root, staged)
806
+ if pinned:
807
+ print(f"wrote {WORKFLOW_PATH}: \"project\": {json.dumps(pinned, ensure_ascii=False)} "
808
+ "(the repository name, fixed so it no longer depends on the clone)" + " (staged)" * staged)
636
809
  reader = IndexReader(root) if staged else FsReader(root)
637
810
  if args[0] == "check":
638
811
  problem = staleness(FsReader(root))
@@ -3,13 +3,16 @@
3
3
 
4
4
  doctor.py [--root <dir>] [--json]
5
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)
6
+ doctor.py --sweep [--json] [--no-forge] every remaining failure as a worklist with evidence (read-only;
7
+ asks the forge through `gh` about post-merge steps unless --no-forge)
7
8
  doctor.py --baseline last resort: accept today's failures in context/doctor-baseline.json
8
9
  npx softure-skills doctor [...] (the same, from the installed package)
9
10
 
10
11
  Adopting projects run it in a CI job named `context-doctor`, 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:
12
+ drift happens). In GitHub Actions it also writes the failure codes as annotations of that check run (the first one,
13
+ titled `context-doctor failure codes`, lists every code with its count) and as the job summary, so a reader of the
14
+ forge API sees the codes on the main branch's head without a checkout. `softure-archive` and `softure-roadmap
15
+ --close` run it before their commit and fix what they own. Each problem is one line `FAIL <code> <path>: <what>`; the codes:
13
16
 
14
17
  roadmap-archived-not-removed roadmap.md is still there although the same roadmap is in foundation/archive/
15
18
  roadmap-status-mismatch roadmap.md `status` contradicts its rows (done with open rows; waiting)
@@ -221,6 +224,40 @@ def open_checks(text: str, include_release: bool = True) -> list[str]:
221
224
  return found
222
225
 
223
226
 
227
+ # A carry marker: the line says which roadmap took the entry over (`→ roadmap-later`, `carried to
228
+ # roadmaps/roadmap-later.md`, `carried over to roadmap.md`).
229
+ CARRY_RE = re.compile(r"(?:→|->|\bcarried(?:\s+over)?\s+to)\s*\**\s*`?(?P<target>(?:[\w.-]+/)*roadmap"
230
+ r"(?:-[A-Za-z0-9][\w-]*?(?:\.md)?|\.md))(?![\w-])`?", re.IGNORECASE)
231
+
232
+
233
+ def carry_target(text: str) -> str | None:
234
+ """The roadmap a carry marker in `text` names (as written), or None."""
235
+ match = CARRY_RE.search(text or "")
236
+ return match.group("target") if match else None
237
+
238
+
239
+ def resolve_carry(reader, target: str | None) -> str | None:
240
+ """The file of the roadmap a carry marker names, when it exists (queued, archived, or the live one)."""
241
+ if not target:
242
+ return None
243
+ name = target.rsplit("/", 1)[-1]
244
+ if name == "roadmap.md":
245
+ text = reader.read(ROADMAP_PATH)
246
+ return ROADMAP_PATH if text is not None else None
247
+ slug = name[len("roadmap-"):]
248
+ slug = slug[:-3] if slug.endswith(".md") else slug
249
+ queued = f"{QUEUED_DIR}/roadmap-{slug}.md"
250
+ if reader.read(queued) is not None:
251
+ return queued
252
+ live = reader.read(ROADMAP_PATH)
253
+ if live is not None and frontmatter(live).get("roadmap") == slug:
254
+ return ROADMAP_PATH
255
+ for path in _files(reader, ARCHIVE_ROADMAPS_DIR, r"^\d{4}-\d{2}-\d{2}-roadmap.*\.md$"):
256
+ if frontmatter(reader.read(path) or "").get("roadmap") == slug or path.endswith(f"roadmap-{slug}.md"):
257
+ return path
258
+ return None
259
+
260
+
224
261
  def check_archived_roadmaps(reader) -> list[Finding]:
225
262
  findings: list[Finding] = []
226
263
  pending = pending_release_roadmap(reader)
@@ -583,18 +620,19 @@ def run_baseline(reader, root: str, git_root: str | None) -> int:
583
620
  return 1 if change["refused"] else 0
584
621
 
585
622
 
586
- def run_sweep(reader, root: str, git_root: str | None, as_json: bool) -> int:
623
+ def run_sweep(reader, root: str, git_root: str | None, as_json: bool, use_forge: bool = True) -> int:
587
624
  """`--sweep`: the worklist of every failure with its evidence; exit 1 while anything is left."""
588
625
  import doctor_sweep
589
626
 
590
- entries = doctor_sweep.sweep(reader, git_root)
627
+ entries = doctor_sweep.sweep(reader, git_root, doctor_sweep.Forge(git_root, enabled=use_forge))
591
628
  owner = [entry for entry in entries if entry["class"] == "owner"]
592
629
  superseded = [entry for entry in entries if entry["class"] == "superseded"]
593
- with_evidence = len(entries) - len(owner) - len(superseded)
630
+ forge = [entry for entry in entries if entry["class"] == "forge"]
631
+ with_evidence = len(entries) - len(owner) - len(superseded) - len(forge)
594
632
  if as_json:
595
633
  print(json.dumps({"root": root, "entries": entries,
596
634
  "summary": {"total": len(entries), "with_evidence": with_evidence,
597
- "superseded": len(superseded), "owner": len(owner)}},
635
+ "superseded": len(superseded), "forge": len(forge), "owner": len(owner)}},
598
636
  indent=2, ensure_ascii=False))
599
637
  return 1 if entries else 0
600
638
  if not entries:
@@ -607,16 +645,76 @@ def run_sweep(reader, root: str, git_root: str | None, as_json: bool) -> int:
607
645
  print(f" evidence {evidence['kind']} {evidence['ref']}: {evidence['note']}")
608
646
  if entry["class"] == "superseded":
609
647
  print(" superseded: later work made it obsolete; close it yourself, never forward it")
648
+ if entry["class"] == "forge":
649
+ print(" forge: check it with `gh` before anything goes to the owner")
650
+ for tried in entry["tried"]:
651
+ print(f" tried: {tried}")
610
652
  if entry["owner"]:
611
653
  print(f" owner ({entry['owner_reason']}): only the owner can settle it")
612
654
  for tried in entry["tried"]:
613
655
  print(f" tried: {tried}")
614
656
  print(f" settle: {entry['settle']}")
615
657
  print(f"softure-doctor --sweep: {len(entries)} entr{'y' if len(entries) == 1 else 'ies'} to settle, "
616
- f"{with_evidence} with evidence, {len(superseded)} superseded, {len(owner)} for the owner")
658
+ f"{with_evidence} with evidence, {len(superseded)} superseded, {len(forge)} to check with the forge, "
659
+ f"{len(owner)} for the owner")
617
660
  return 1
618
661
 
619
662
 
663
+ # The annotation that lists every failure code of a run; readers of the check run (portfolio --source api) find it
664
+ # by this title. GitHub keeps only the first few annotations of a step, so the codes come first, in one annotation.
665
+ CI_CODES_TITLE = "context-doctor failure codes"
666
+ CI_ANNOTATION_LIMIT = 9
667
+
668
+
669
+ def failure_codes(failures: list[Finding]) -> list[tuple[str, int]]:
670
+ counts: dict[str, int] = {}
671
+ for failure in failures:
672
+ counts[failure.code] = counts.get(failure.code, 0) + 1
673
+ return sorted(counts.items())
674
+
675
+
676
+ def _escape(value: str, property_value: bool = False) -> str:
677
+ value = value.replace("%", "%25").replace("\r", "%0D").replace("\n", "%0A")
678
+ return value.replace(":", "%3A").replace(",", "%2C") if property_value else value
679
+
680
+
681
+ def report_to_ci(failures: list[Finding], env: dict | None = None, out=None) -> None:
682
+ """In GitHub Actions: the failure codes as annotations of the check run, and a job summary.
683
+
684
+ The first annotation (title `CI_CODES_TITLE`) lists every code with its count, so a reader of the check run
685
+ through the forge API gets the codes without a checkout; one annotation per failure follows, up to the limit.
686
+ The job summary (`$GITHUB_STEP_SUMMARY`) holds the same table. Outside Actions nothing changes.
687
+ """
688
+ env = os.environ if env is None else env
689
+ out = out or sys.stdout
690
+ if env.get("GITHUB_ACTIONS") != "true":
691
+ return
692
+ codes = failure_codes(failures)
693
+ if codes:
694
+ listed = ", ".join(f"{code} ({count})" for code, count in codes)
695
+ print(f"::error title={_escape(CI_CODES_TITLE, True)}::{_escape(listed)}", file=out)
696
+ for failure in failures[:CI_ANNOTATION_LIMIT]:
697
+ print(f"::error file={_escape(failure.path, True)},title={_escape(failure.code, True)}::"
698
+ f"{_escape(failure.message)}", file=out)
699
+ target = env.get("GITHUB_STEP_SUMMARY")
700
+ if not target:
701
+ return
702
+ lines = ["### context-doctor", ""]
703
+ if codes:
704
+ lines += [f"{len(failures)} problem(s) in the context/ contract (WORKFLOW.md §12).", "",
705
+ "| Code | Count | First path |", "| --- | --- | --- |"]
706
+ for code, count in codes:
707
+ first = next(failure.path for failure in failures if failure.code == code)
708
+ lines.append(f"| `{code}` | {count} | `{first}` |")
709
+ else:
710
+ lines.append("context/ contract OK")
711
+ try:
712
+ with open(target, "a", encoding="utf-8") as fh:
713
+ fh.write("\n".join(lines) + "\n")
714
+ except OSError:
715
+ pass
716
+
717
+
620
718
  def main(argv: list[str] | None = None) -> int:
621
719
  args = list(sys.argv[1:] if argv is None else argv)
622
720
  if "-h" in args or "--help" in args:
@@ -626,13 +724,14 @@ def main(argv: list[str] | None = None) -> int:
626
724
  fix = _take(args, "--fix")
627
725
  write = _take(args, "--write")
628
726
  do_sweep = _take(args, "--sweep")
727
+ no_forge = _take(args, "--no-forge")
629
728
  do_baseline = _take(args, "--baseline")
630
729
  root = None
631
730
  if "--root" in args:
632
731
  k = args.index("--root")
633
732
  root = os.path.abspath(args[k + 1])
634
733
  del args[k:k + 2]
635
- if args or (write and not fix) or sum((fix, do_sweep, do_baseline)) > 1:
734
+ if args or (write and not fix) or sum((fix, do_sweep, do_baseline)) > 1 or (no_forge and not do_sweep):
636
735
  print(__doc__, file=sys.stderr)
637
736
  return 2
638
737
  top = subprocess.run(["git", "-C", root or os.getcwd(), "rev-parse", "--show-toplevel"],
@@ -650,7 +749,7 @@ def main(argv: list[str] | None = None) -> int:
650
749
  if fix:
651
750
  return run_fix(reader, root, git_root, write, as_json)
652
751
  if do_sweep:
653
- return run_sweep(reader, root, git_root, as_json)
752
+ return run_sweep(reader, root, git_root, as_json, use_forge=not no_forge)
654
753
  if do_baseline:
655
754
  return run_baseline(reader, root, git_root)
656
755
  findings = run_checks(reader, git_root)
@@ -661,6 +760,7 @@ def main(argv: list[str] | None = None) -> int:
661
760
  return 1 if failures else 0
662
761
  for finding in findings:
663
762
  print(finding)
763
+ report_to_ci(failures)
664
764
  baselined = sum(1 for f in findings if f.severity == "baselined")
665
765
  if baselined:
666
766
  print(f"softure-doctor: {baselined} failure(s) accepted by {BASELINE_PATH} (last resort; sweep them to zero)")
@@ -17,6 +17,11 @@ Three shapes are mechanical, and only files under `context/` are edited:
17
17
  dropped Progress item an unticked item of an archived plan's `## Progress` that is struck through or
18
18
  carries a dropped/cancelled/not-applicable note is normalised to
19
19
  `- [x] ~~<item>~~ — dropped: <note>` (the doctor already reads it as dropped)
20
+ carried entry an unticked owner check or pre-release step of an archived roadmap, or an open row,
21
+ whose text carries a carry marker (`→ roadmap-<slug>`, `carried to <roadmap>`) naming a
22
+ roadmap that exists (queued, archived or the live one): the check is ticked
23
+ `- [x] <text> — carried to <path>`, the row (and its item block) becomes
24
+ `carried (to <path>)`; a marker whose roadmap does not exist is left alone and named
20
25
 
21
26
  Everything else (an index row whose target is not in the history this checkout holds, a live index)
22
27
  is a judgement case: `doctor.py --sweep` lists it with evidence. A shallow clone works: what it cannot
@@ -221,6 +226,8 @@ def plan_fixes(reader, root: str | None) -> dict:
221
226
  if lines != text.split("\n"):
222
227
  files[rel] = "\n".join(lines)
223
228
 
229
+ _plan_carried(reader, files, edits, skipped)
230
+
224
231
  history = History(root)
225
232
  for missing in doctor.missing_index_targets(reader):
226
233
  if not missing["path"].startswith(ARCHIVE_PREFIXES):
@@ -263,6 +270,65 @@ def plan_fixes(reader, root: str | None) -> dict:
263
270
  return {"edits": edits, "skipped": skipped, "files": files}
264
271
 
265
272
 
273
+ def _foundation_relative(path: str) -> str:
274
+ prefix = "context/foundation/"
275
+ return path[len(prefix):] if path.startswith(prefix) else path
276
+
277
+
278
+ def _plan_carried(reader, files: dict[str, str], edits: list[dict], skipped: list[dict]) -> None:
279
+ """Tick carry-marked checks and close carry-marked rows of archived roadmaps whose target roadmap exists."""
280
+ import doctor # noqa: E402
281
+
282
+ from context_state import CHECKBOX_RE, OWNER_SECTION, RELEASE_SECTION, pending_release_roadmap, roadmap_rows
283
+
284
+ pending = pending_release_roadmap(reader)
285
+ for path in doctor._archived_roadmaps(reader):
286
+ text = files.get(path, reader.read(path) or "")
287
+ lines = text.split("\n")
288
+ wanted = {OWNER_SECTION} | ({RELEASE_SECTION} if path != pending else set())
289
+ open_rows = {row["id"]: row for row in roadmap_rows(text) if row["status"] not in doctor.CLOSED_STATUSES}
290
+ section = None
291
+ for index, line in enumerate(lines):
292
+ if line.startswith("## "):
293
+ section = line[3:].strip()
294
+ continue
295
+ box = CHECKBOX_RE.match(line)
296
+ row = re.match(r"^\|\s*\*\*([A-Z]+-\d+)\*\*\s*\|", line)
297
+ if box and box.group("mark") == " " and section in wanted:
298
+ subject = box.group("text")
299
+ elif row and row.group(1) in open_rows:
300
+ subject = [cell.strip() for cell in line.strip().strip("|").split("|")][-1]
301
+ else:
302
+ continue
303
+ target = doctor.carry_target(subject)
304
+ if not target:
305
+ continue
306
+ found = doctor.resolve_carry(reader, target)
307
+ if not found:
308
+ skipped.append({"code": "archived-roadmap-open-checks" if box else "archived-roadmap-open-items",
309
+ "path": path, "line": index + 1,
310
+ "why": f"carry marker names `{target}`, which is no queued, archived or live roadmap"})
311
+ continue
312
+ where = _foundation_relative(found)
313
+ if box:
314
+ lines[index] = line.replace("- [ ] ", "- [x] ", 1).rstrip() + f" — carried to {where}"
315
+ edits.append({"code": "archived-roadmap-open-checks", "path": path, "line": index + 1,
316
+ "what": f"carried check ticked: carried to {where}"})
317
+ else:
318
+ old_status = subject
319
+ new_status = f"carried (to {where})"
320
+ head = line.rstrip()
321
+ cut = head.rstrip("|").rstrip().rfind(old_status)
322
+ lines[index] = head[:cut] + new_status + head[cut + len(old_status):]
323
+ for block_index, block_line in enumerate(lines):
324
+ if block_line.strip() == f"- **Status:** {old_status}":
325
+ lines[block_index] = block_line.replace(old_status, new_status, 1)
326
+ edits.append({"code": "archived-roadmap-open-items", "path": path, "line": index + 1,
327
+ "what": f"{row.group(1)} {old_status} -> {new_status}"})
328
+ if lines != text.split("\n"):
329
+ files[path] = "\n".join(lines)
330
+
331
+
266
332
  def apply_fixes(root: str, files: dict[str, str]) -> None:
267
333
  for rel, text in files.items():
268
334
  if not rel.startswith("context/"):