bmad-module-ultracode-goal 2.0.0 → 2.2.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.
Files changed (43) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/README.md +5 -5
  3. package/docs/404.md +1 -1
  4. package/docs/_internal/STABILITY.md +13 -9
  5. package/docs/architecture.md +17 -12
  6. package/docs/comparison.md +19 -11
  7. package/docs/gate-model.md +24 -0
  8. package/docs/getting-started.md +1 -1
  9. package/docs/how-it-works.md +3 -3
  10. package/docs/index.md +0 -1
  11. package/docs/operating-tips.md +4 -2
  12. package/docs/troubleshooting.md +9 -5
  13. package/docs/why-ultracode-goal.md +1 -1
  14. package/package.json +5 -4
  15. package/skills/ucg-formalize/SKILL.md +136 -39
  16. package/skills/ucg-resolve/SKILL.md +86 -58
  17. package/skills/ucg-status/SKILL.md +64 -30
  18. package/skills/ultracode-goal/SKILL.md +9 -11
  19. package/skills/ultracode-goal/assets/module-help.csv +1 -1
  20. package/skills/ultracode-goal/assets/module.yaml +8 -3
  21. package/skills/ultracode-goal/assets/ucg-awareness/bmad-testarch-test-design.toml +8 -0
  22. package/skills/ultracode-goal/customize.toml +12 -7
  23. package/skills/ultracode-goal/references/define-done.md +3 -3
  24. package/skills/ultracode-goal/references/execute.md +40 -53
  25. package/skills/ultracode-goal/references/finalize.md +12 -12
  26. package/skills/ultracode-goal/references/gate.md +42 -11
  27. package/skills/ultracode-goal/references/health-check.md +7 -4
  28. package/skills/ultracode-goal/references/ingest-and-scope.md +4 -4
  29. package/skills/ultracode-goal/references/preflight.md +10 -9
  30. package/skills/ultracode-goal/scripts/gate_eval.py +684 -39
  31. package/skills/ultracode-goal/scripts/gate_trail.py +131 -32
  32. package/skills/ultracode-goal/scripts/health_check_fp.py +98 -3
  33. package/skills/ultracode-goal/scripts/hooks/guard_pretooluse.py +56 -14
  34. package/skills/ultracode-goal/scripts/mem_observation.py +48 -10
  35. package/skills/ultracode-goal/scripts/mutate_check.py +353 -0
  36. package/skills/ultracode-goal/scripts/preflight_check.py +397 -3
  37. package/skills/ultracode-goal/scripts/status_render.py +20 -2
  38. package/skills/ultracode-goal/scripts/story_sizing.py +193 -0
  39. package/tools/build-docs.js +24 -1
  40. package/tools/validate-docs-links.js +169 -8
  41. package/website/astro.config.mjs +0 -1
  42. package/docs/parallel-mode.md +0 -68
  43. package/skills/ultracode-goal/assets/execute-epic.workflow.js +0 -249
@@ -48,12 +48,31 @@ Absence of sprint-status.yaml is a reportable fact (sprint_status_present:
48
48
  false, epics: []), not an error — rollup still exits 0.
49
49
 
50
50
  uv run preflight_check.py --rollup --project-root <path> --impl-artifacts <path>
51
+
52
+ Resume-manifest mode (`--assert-armed`): the one deterministic read a resumed
53
+ run makes in place of the tool-action-per-fact environment sweep the resume
54
+ rule otherwise costs (references/execute.md, resume). It asserts the epic
55
+ branch, both hooks with the all-tools PreToolUse matcher, and the five injected
56
+ hook env vars (accepted from the hook command strings OR the inherited process
57
+ env, both of which preflight step 5 permits), reports the recall latch WITHOUT
58
+ certifying it (re-latching stays a model-owned Stage 1 step on every resume),
59
+ and, given --story, derives the story's resume route from artifacts alone:
60
+ story-boundary (no baseline), gate-owed (committed, green, un-gated - requires
61
+ --trace-output evidence; without it that route never fires), or mid-story.
62
+ Exit 0 iff branch+hooks+env are armed; the latch and story blocks never move
63
+ the exit code, because they inform model-owned actions rather than certify
64
+ them.
65
+
66
+ uv run preflight_check.py --assert-armed --project-root <path> \
67
+ --impl-artifacts <path> [--story <id>] [--run-id <rid>] \
68
+ [--trace-output <dir>] [--protected-branch <name>]...
51
69
  """
52
70
 
53
71
  from __future__ import annotations
54
72
 
55
73
  import argparse
56
74
  import json
75
+ import os
57
76
  import re
58
77
  import subprocess
59
78
  import sys
@@ -354,18 +373,24 @@ def _parse_development_status(text: str) -> dict[str, str]:
354
373
  """
355
374
  entries: dict[str, str] = {}
356
375
  in_block = False
376
+ block_indent = 0
357
377
  for raw in text.splitlines():
358
378
  # The map is one top-level key; detect entering/leaving its body by
359
379
  # indentation rather than tracking nesting (the file is flat).
360
380
  stripped = raw.strip()
361
381
  if not stripped or stripped.startswith("#"):
362
382
  continue
383
+ indent = len(raw) - len(raw.lstrip(" \t"))
363
384
  if not in_block:
364
385
  if stripped.rstrip().rstrip(":") == "development_status" and stripped.endswith(":"):
365
386
  in_block = True
387
+ block_indent = indent
366
388
  continue
367
- # Inside the block: a non-indented line ends it.
368
- if raw[:1] not in (" ", "\t"):
389
+ # Inside the block: any line indented at or below the key's own
390
+ # indentation ends it. Ending only at column 0 let a sibling map that
391
+ # followed a nested development_status: get swallowed into the story
392
+ # set, and a duplicate key there overwrote a real row last-wins.
393
+ if indent <= block_indent:
369
394
  break
370
395
  if ":" not in stripped:
371
396
  continue
@@ -569,6 +594,328 @@ def build_report(
569
594
  }
570
595
 
571
596
 
597
+ # --- Resume manifest (--assert-armed) ----------------------------------------
598
+ # One deterministic read of the environment a resume must re-assert, replacing
599
+ # the tool-action-per-fact sweep the resume rule otherwise spends turns on.
600
+ # The script ASSERTS; it never acts: the two model-owned writes on a resume
601
+ # (re-latching from this run's own measurement, and writing a boundary story's
602
+ # fresh baseline) stay with the conductor, and exit 0 certifies neither.
603
+
604
+ # The five env vars preflight step 5 injects so the hooks enforce the resolved
605
+ # config rather than their hardcoded fallbacks. A var may live either in the
606
+ # hook command string in settings.local.json or in the process env the hooks
607
+ # inherit (preflight.md permits both); this checker accepts both, because
608
+ # fail-closing on a legitimate arming would teach operators to skip the check.
609
+ HOOK_ENV_VARS = (
610
+ "ULTRACODE_PROTECTED_BRANCHES",
611
+ "ULTRACODE_IMPL_ARTIFACTS",
612
+ "ULTRACODE_MAX_TURNS",
613
+ "ULTRACODE_EPIC_BRANCH_PREFIX",
614
+ "ULTRACODE_TEST_ARTIFACTS",
615
+ )
616
+
617
+ _GUARD_SCRIPT = "guard_pretooluse.py"
618
+ _BUDGET_SCRIPT = "budget_stop.py"
619
+
620
+
621
+ def _hook_commands(settings: dict) -> list[tuple[str, str | None, str]]:
622
+ """Every (event, matcher, command) triple nested under hooks.<Event>[].hooks[].
623
+
624
+ The entries are nested, not top-level (preflight.md's stale-hook bullet
625
+ documents the shape); a malformed layer contributes nothing rather than
626
+ raising, because an unreadable arming must read as NOT armed, never crash.
627
+ The EVENT is part of the identity on purpose: a guard command sitting under
628
+ hooks.Stop is never invoked before a tool call, so an event-blind read would
629
+ certify an arming that enforces nothing.
630
+ """
631
+ out: list[tuple[str, str | None, str]] = []
632
+ hooks = settings.get("hooks")
633
+ if not isinstance(hooks, dict):
634
+ return out
635
+ for event, groups in hooks.items():
636
+ if not isinstance(event, str) or not isinstance(groups, list):
637
+ continue
638
+ for group in groups:
639
+ if not isinstance(group, dict):
640
+ continue
641
+ matcher = group.get("matcher")
642
+ inner = group.get("hooks")
643
+ if not isinstance(inner, list):
644
+ continue
645
+ for entry in inner:
646
+ if isinstance(entry, dict) and isinstance(entry.get("command"), str):
647
+ out.append(
648
+ (
649
+ event,
650
+ matcher if isinstance(matcher, str) else None,
651
+ entry["command"],
652
+ )
653
+ )
654
+ return out
655
+
656
+
657
+ def _assert_hooks(project_root: Path) -> dict:
658
+ """Are both UCG hooks armed, with the PreToolUse matcher in all-tools form?
659
+
660
+ Matcher assertion mirrors preflight step 5: `*` or an absent matcher key both
661
+ select every tool; anything narrower (the observed `Bash`-only arming) leaves
662
+ the Cross-Session Recall invariant enforcing nothing. Fail-closed: a missing
663
+ or unparseable settings file is NOT armed.
664
+ """
665
+ settings_path = project_root / ".claude" / "settings.local.json"
666
+ try:
667
+ settings = json.loads(settings_path.read_text(encoding="utf-8"))
668
+ except (OSError, ValueError, UnicodeDecodeError):
669
+ return {
670
+ "settings_readable": False,
671
+ "guard_present": False,
672
+ "budget_present": False,
673
+ "matcher_all_tools": False,
674
+ "ok": False,
675
+ }
676
+ triples = _hook_commands(settings)
677
+ guard = [(m, c) for e, m, c in triples if _GUARD_SCRIPT in c and e == "PreToolUse"]
678
+ budget = [c for e, _, c in triples if _BUDGET_SCRIPT in c and e == "Stop"]
679
+ matcher_ok = bool(guard) and all(m is None or m == "*" for m, _ in guard)
680
+ return {
681
+ "settings_readable": True,
682
+ "guard_present": bool(guard),
683
+ "budget_present": bool(budget),
684
+ "matcher_all_tools": matcher_ok,
685
+ "ok": bool(guard) and bool(budget) and matcher_ok,
686
+ }
687
+
688
+
689
+ def _assert_hook_env(project_root: Path) -> dict:
690
+ """Where each injected hook var lives: the hook command string, the process
691
+ env, or nowhere. `ok` is all-five-present — a missing var is an invariant
692
+ silently enforcing nothing, which is the exact state this mode exists to
693
+ surface."""
694
+ settings_path = project_root / ".claude" / "settings.local.json"
695
+ try:
696
+ settings = json.loads(settings_path.read_text(encoding="utf-8"))
697
+ commands = [c for _, _, c in _hook_commands(settings)]
698
+ except (OSError, ValueError, UnicodeDecodeError):
699
+ commands = []
700
+ sources: dict[str, str] = {}
701
+ for var in HOOK_ENV_VARS:
702
+ # Boundary-anchored per command: `X_ULTRACODE_MAX_TURNS=1` must not
703
+ # certify ULTRACODE_MAX_TURNS as injected.
704
+ pattern = re.compile(r"(^|[\s;\"'`])" + re.escape(var) + "=")
705
+ if any(pattern.search(c) for c in commands):
706
+ sources[var] = "settings"
707
+ elif var in os.environ:
708
+ sources[var] = "process"
709
+ else:
710
+ sources[var] = "absent"
711
+ missing = [v for v, s in sources.items() if s == "absent"]
712
+ return {"sources": sources, "missing": missing, "ok": not missing}
713
+
714
+
715
+ def _assert_branch(
716
+ project_root: Path, epic_branch_prefix: str, protected: tuple[str, ...]
717
+ ) -> dict:
718
+ branch = _git_branch(project_root)
719
+ ok = bool(branch) and branch.startswith(epic_branch_prefix) and branch not in protected
720
+ return {
721
+ "current": branch,
722
+ "expected_prefix": epic_branch_prefix,
723
+ "protected": list(protected),
724
+ "ok": ok,
725
+ }
726
+
727
+
728
+ def _read_latch(impl_artifacts: Path, run_id: str | None) -> dict:
729
+ """The on-disk recall latch, REPORTED and never certified.
730
+
731
+ `certifies` is a literal None on purpose: a green manifest must not become an
732
+ inherited-latch claim by proxy. Whatever this reports, the resume re-latches
733
+ from its own measurement (Stage 1's latch step), and a latch whose run_id is
734
+ not this run's is another run's artifact (references/execute.md, resume).
735
+ """
736
+ path = impl_artifacts / ".mem-state.json"
737
+ try:
738
+ data = json.loads(path.read_text(encoding="utf-8"))
739
+ except OSError:
740
+ return {"state": "absent", "certifies": None}
741
+ except (ValueError, UnicodeDecodeError):
742
+ return {"state": "unreadable", "certifies": None}
743
+ if not isinstance(data, dict):
744
+ # Valid JSON that is not an object is still not a latch; reporting it
745
+ # must not crash the manifest (the latch never moves the exit code).
746
+ return {"state": "unreadable", "certifies": None}
747
+ latch_run = data.get("run_id")
748
+ out: dict = {
749
+ "state": "present",
750
+ "claude_mem": data.get("claude_mem"),
751
+ "recall": data.get("recall"),
752
+ "run_id": latch_run,
753
+ "certifies": None,
754
+ }
755
+ if run_id is not None:
756
+ out["owned_by_this_run"] = latch_run == run_id
757
+ return out
758
+
759
+
760
+ def _marker_line(path: Path) -> str | None:
761
+ try:
762
+ return path.read_text(encoding="utf-8").strip() or None
763
+ except (OSError, UnicodeDecodeError):
764
+ return None
765
+
766
+
767
+ def _tests_ran_baseline(path: Path) -> str | None:
768
+ try:
769
+ text = path.read_text(encoding="utf-8")
770
+ except (OSError, UnicodeDecodeError):
771
+ return None
772
+ match = re.search(r"^baseline=(.*)$", text, re.MULTILINE)
773
+ return match.group(1).strip() if match else None
774
+
775
+
776
+ def _commits_past(project_root: Path, baseline_sha: str) -> int | None:
777
+ code, out = _git(["rev-list", "--count", f"{baseline_sha}..HEAD"], project_root)
778
+ if code != 0:
779
+ return None
780
+ try:
781
+ return int(out.strip())
782
+ except ValueError:
783
+ return None
784
+
785
+
786
+ def _story_gate_artifacts_present(trace_output: Path, story: str) -> bool | None:
787
+ """Does a trace/gate-decision artifact resolve for this story? None = unknown.
788
+
789
+ Resolution identity is imported from gate_eval rather than re-implemented,
790
+ so the manifest and the gate cannot disagree about what names a story:
791
+ a story-named artifact matches by gate_eval's own stem rule, and in a
792
+ directory gate_eval would treat as NOT per-story-named (TEA's untouched
793
+ generic output), the generic artifacts count as this story's, exactly as
794
+ gate_eval's documented unscoped fallback reads them. An unreadable or
795
+ nonexistent directory returns None: unverifiable is never verified-absent.
796
+ """
797
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
798
+ import gate_eval # noqa: PLC0415 (sibling script, path set above)
799
+
800
+ if not trace_output.is_dir():
801
+ return None
802
+ generic_stems = {"-".join(prefix) for prefix in gate_eval._ARTIFACT_PREFIXES}
803
+ saw_generic = False
804
+ for path in trace_output.iterdir():
805
+ if not path.is_file():
806
+ continue
807
+ stem = path.stem
808
+ if stem.startswith(("trace-", "gate-decision-")) and gate_eval._stem_matches_story(
809
+ stem, story
810
+ ):
811
+ return True
812
+ if stem in generic_stems:
813
+ saw_generic = True
814
+ if saw_generic and not gate_eval._is_per_story_named(trace_output):
815
+ return True
816
+ return False
817
+
818
+
819
+ def _assert_story(
820
+ project_root: Path,
821
+ impl_artifacts: Path,
822
+ story: str,
823
+ trace_output: Path | None,
824
+ ) -> dict:
825
+ """Classify the resume story by artifacts, never by prose.
826
+
827
+ Routes mirror references/execute.md's resume rule exactly:
828
+ - `story-boundary`: no baseline marker — the normal `--max-stories` case;
829
+ step 0 writes the baseline fresh.
830
+ - `gate-owed`: committed, green and un-gated (commits past the baseline,
831
+ a tests-ran marker still matching it, and NO per-story gate artifact) —
832
+ enter at step 5. This route REQUIRES --trace-output: with no artifact
833
+ evidence the discriminator cannot hold in full, and skipping steps 1-4
834
+ on a guess is the fail-open this mode must not introduce.
835
+ - `mid-story`: everything else — re-read the baseline, run the ordinary
836
+ loop from step 0.
837
+ """
838
+ baseline_path = impl_artifacts / f".baseline-{story}"
839
+ marker_path = impl_artifacts / f".tests-ran-{story}"
840
+ baseline = _marker_line(baseline_path)
841
+ marker_baseline = _tests_ran_baseline(marker_path)
842
+ out: dict = {
843
+ "id": story,
844
+ "baseline": "present" if baseline else "absent",
845
+ "tests_ran": "present" if marker_path.is_file() else "absent",
846
+ "tests_ran_fresh": bool(baseline) and marker_baseline == baseline,
847
+ }
848
+ commits = _commits_past(project_root, baseline) if baseline else None
849
+ out["commits_past_baseline"] = commits
850
+ if trace_output is not None and baseline:
851
+ gated = _story_gate_artifacts_present(trace_output, story)
852
+ if gated is None:
853
+ out["gate_artifacts"] = "unknown"
854
+ else:
855
+ out["gate_artifacts"] = "present" if gated else "absent"
856
+ else:
857
+ out["gate_artifacts"] = "unknown"
858
+ if not baseline:
859
+ out["route"] = "story-boundary"
860
+ elif (
861
+ out["gate_artifacts"] == "absent"
862
+ and out["tests_ran_fresh"]
863
+ and (commits or 0) > 0
864
+ ):
865
+ out["route"] = "gate-owed"
866
+ else:
867
+ out["route"] = "mid-story"
868
+ return out
869
+
870
+
871
+ def build_assert_armed(
872
+ *,
873
+ project_root: Path,
874
+ impl_artifacts: Path,
875
+ epic_branch_prefix: str,
876
+ protected: tuple[str, ...],
877
+ story: str | None,
878
+ run_id: str | None,
879
+ trace_output: Path | None,
880
+ ) -> dict:
881
+ branch = _assert_branch(project_root, epic_branch_prefix, protected)
882
+ hooks = _assert_hooks(project_root)
883
+ hook_env = _assert_hook_env(project_root)
884
+ checks: dict = {
885
+ "branch": branch,
886
+ "hooks": hooks,
887
+ "hook_env": hook_env,
888
+ "latch": _read_latch(impl_artifacts, run_id),
889
+ }
890
+ if story:
891
+ checks["story"] = _assert_story(project_root, impl_artifacts, story, trace_output)
892
+ reasons: list[str] = []
893
+ if not branch["ok"]:
894
+ reasons.append(
895
+ "branch %r is not an epic branch under prefix %r (or is protected)"
896
+ % (branch["current"], epic_branch_prefix)
897
+ )
898
+ if not hooks["ok"]:
899
+ if not hooks["settings_readable"]:
900
+ reasons.append("settings.local.json is missing or unreadable; hooks NOT armed")
901
+ if not hooks["guard_present"]:
902
+ reasons.append("PreToolUse guard (guard_pretooluse.py) not armed")
903
+ if not hooks["budget_present"]:
904
+ reasons.append("Stop budget hook (budget_stop.py) not armed")
905
+ if hooks["guard_present"] and not hooks["matcher_all_tools"]:
906
+ reasons.append(
907
+ "PreToolUse matcher is not the all-tools form; the recall "
908
+ "invariant enforces nothing (preflight.md step 5)"
909
+ )
910
+ if not hook_env["ok"]:
911
+ reasons.append(
912
+ "hook env not fully injected; enforcing hardcoded fallbacks for: %s"
913
+ % ", ".join(hook_env["missing"])
914
+ )
915
+ armed = branch["ok"] and hooks["ok"] and hook_env["ok"]
916
+ return {"armed": armed, "checks": checks, "reasons": reasons}
917
+
918
+
572
919
  def _resolve(path_arg: str, project_root: Path) -> Path:
573
920
  """Expand a possible {project-root} token and resolve relative to project_root."""
574
921
  resolved = path_arg.replace("{project-root}", str(project_root))
@@ -601,12 +948,42 @@ def main(argv: list[str] | None = None) -> int:
601
948
  default=None,
602
949
  help="Protected branch name; repeatable. Defaults to main, master.",
603
950
  )
951
+ parser.add_argument(
952
+ "--assert-armed",
953
+ action="store_true",
954
+ help="Emit only the resume manifest: branch, hooks (incl. the all-tools "
955
+ "matcher), injected hook env, the recall latch (reported, never "
956
+ "certified), and, with --story, the story's artifact-derived resume "
957
+ "route. Exit 0 iff branch+hooks+env are armed. When set, --epic, "
958
+ "--tea-config, and the mechanical preflight checks do not run.",
959
+ )
960
+ parser.add_argument(
961
+ "--story",
962
+ help="assert-armed only: the story the resume will drive; adds the "
963
+ "artifact-derived route (story-boundary / mid-story / gate-owed).",
964
+ )
965
+ parser.add_argument(
966
+ "--run-id",
967
+ help="assert-armed only: this run's id, for reporting whether the "
968
+ "on-disk latch is owned by this run (reported, never certified).",
969
+ )
970
+ parser.add_argument(
971
+ "--trace-output",
972
+ help="assert-armed only: the per-story trace artifacts dir; required "
973
+ "evidence for the gate-owed route (without it that route never fires).",
974
+ )
975
+ parser.add_argument(
976
+ "--epic-branch-prefix",
977
+ default=os.environ.get("ULTRACODE_EPIC_BRANCH_PREFIX", "ultracode/epic-"),
978
+ help="assert-armed only: the resolved epic branch prefix. Defaults to "
979
+ "$ULTRACODE_EPIC_BRANCH_PREFIX, then the shipped default.",
980
+ )
604
981
  args = parser.parse_args(argv)
605
982
 
606
983
  # Preserve the normal-mode contract: --epic and --tea-config are required
607
984
  # unless --rollup is in effect. parser.error() reproduces argparse's usage
608
985
  # line + "error:" message and exits 2, exactly as required=True did.
609
- if not args.rollup:
986
+ if not args.rollup and not args.assert_armed:
610
987
  missing = [
611
988
  name
612
989
  for name, value in (("--epic", args.epic), ("--tea-config", args.tea_config))
@@ -633,6 +1010,23 @@ def main(argv: list[str] | None = None) -> int:
633
1010
  print(json.dumps(rollup, indent=2))
634
1011
  return 0
635
1012
 
1013
+ if args.assert_armed:
1014
+ manifest = build_assert_armed(
1015
+ project_root=project_root,
1016
+ impl_artifacts=impl_artifacts,
1017
+ epic_branch_prefix=args.epic_branch_prefix,
1018
+ protected=tuple(args.protected_branch)
1019
+ if args.protected_branch
1020
+ else DEFAULT_PROTECTED,
1021
+ story=args.story,
1022
+ run_id=args.run_id,
1023
+ trace_output=_resolve(args.trace_output, project_root)
1024
+ if args.trace_output
1025
+ else None,
1026
+ )
1027
+ print(json.dumps(manifest, indent=2))
1028
+ return 0 if manifest["armed"] else 1
1029
+
636
1030
  tea_config = _resolve(args.tea_config, project_root)
637
1031
  protected = tuple(args.protected_branch) if args.protected_branch else DEFAULT_PROTECTED
638
1032
 
@@ -66,6 +66,13 @@ MACHINE = "[machine-derived]"
66
66
  # evidence of a real escalation; it just never got typed.
67
67
  UNPROMOTED = "escalation (unpromoted: session ended before Execute promoted it)"
68
68
 
69
+ # The other thin record: the typed sidecar IS on disk but is empty or does not
70
+ # parse, so there is nothing to render out of it. Distinct from UNPROMOTED
71
+ # because the typed file was written - two of the three escalation routes write
72
+ # it with no raw marker beside it - so "never promoted" would be a false account
73
+ # of a run that promoted just fine and then wrote badly.
74
+ UNREADABLE = "escalation (typed record present but unreadable)"
75
+
69
76
  # The typed sidecar's four fields, rendered in this order.
70
77
  SIDECAR_FIELDS = ("kind", "source", "decision_needed", "evidence")
71
78
 
@@ -378,7 +385,14 @@ def render(
378
385
  if sha:
379
386
  lines.append(f" - baseline `{sha}`")
380
387
  if viewer:
381
- lines.append(f" - {VIEWER} show {sha}")
388
+ # The affordance has to point at THIS story's diff, so it shows
389
+ # the end commit `.commit-<story>` records. The baseline is the
390
+ # commit that preceded the story's work, so showing it renders
391
+ # the previous story's diff - silently, since it is a real diff
392
+ # from the same repo. Only where no end commit was recorded is
393
+ # the anchor the sole sha there is to hand the reader.
394
+ end = gate_trail.commit_sha(impl, story) or sha
395
+ lines.append(f" - {VIEWER} show {end}")
382
396
  lines.append("")
383
397
 
384
398
  # Escalations.
@@ -390,7 +404,11 @@ def render(
390
404
  lines.append(f"### {story}")
391
405
  lines.append("")
392
406
  if payload is None:
393
- lines.append(f"- {UNPROMOTED}")
407
+ # Two different states arrive with no payload, and the path is the
408
+ # discriminator: the Stop hook's raw marker means the escalation was
409
+ # never promoted, while a typed sidecar that would not parse means
410
+ # the record is there and cannot be read. Report what was observed.
411
+ lines.append(f"- {UNREADABLE if path.suffix == '.json' else UNPROMOTED}")
394
412
  lines.append(f"- source: {path.name}")
395
413
  else:
396
414
  for key in SIDECAR_FIELDS:
@@ -0,0 +1,193 @@
1
+ #!/usr/bin/env -S uv run --script
2
+ # /// script
3
+ # requires-python = ">=3.11"
4
+ # ///
5
+ """Sizing arithmetic and parent-AC claim reconciliation for a story decomposition.
6
+
7
+ `references/execute.md` ("Sizing: a story too large to drive") asks for two
8
+ computations and, until this module, shipped neither:
9
+
10
+ - the sizing ratio, which decides whether a row is implausible to drive; and
11
+ - the claim map check, "every parent AC claimed exactly once", which the prose
12
+ explicitly requires to be done **mechanically** rather than by eye.
13
+
14
+ Leaving the second in the prompt meant every decomposition improvised a parser.
15
+ One of those improvisations reported two false double-claims by matching the `1`
16
+ inside `REQ-1` -- a substring match where an identity match was needed. That is
17
+ the failure this module retires, and it retires it by construction: ids are
18
+ tokenized into whole tokens and compared for EQUALITY, never with `in`. `REQ-1`
19
+ and `1` are two different ids here, and no amount of shared characters makes
20
+ them the same one.
21
+
22
+ What stays in the prompt is the judgment the prose reserves: "implausible" is an
23
+ override in both directions, and which child owns which AC is an authoring
24
+ decision. This module computes the counts, the ratio and the exactly-once
25
+ reconciliation. It never decides the split.
26
+
27
+ Exit codes: 0 the claim map reconciles, 1 it does not (unclaimed, double-claimed
28
+ or unknown ids), 2 usage error. The JSON is written on 0 and 1 alike, because a
29
+ failing reconciliation is a result to read, not a crash.
30
+ """
31
+
32
+ from __future__ import annotations
33
+
34
+ import argparse
35
+ import json
36
+ import re
37
+ import sys
38
+
39
+ # An id is a whole token: a `<word>-<number>` form (`AC-1`, `REQ-1`, `FR-2.1`) or
40
+ # a bare number (`1`). Anchored at both ends, so a token either IS an id or is
41
+ # rejected -- there is no partial match, which is what makes the `REQ-1` vs `1`
42
+ # confusion unrepresentable rather than merely unlikely.
43
+ _ID = re.compile(r"^(?:[A-Za-z][A-Za-z0-9_]*-\d+(?:\.\d+)*|\d+)$")
44
+
45
+ _SPLIT = re.compile(r"[,\s]+")
46
+
47
+
48
+ def parse_ids(raw: str, *, field: str) -> list[str]:
49
+ """Split a comma/whitespace separated id list into validated whole tokens.
50
+
51
+ Rejects a token that is not a well-formed id rather than silently dropping
52
+ it: a typo'd id that vanished would read downstream as an AC nobody claimed,
53
+ turning a usage error into a false reconciliation failure.
54
+ """
55
+ tokens = [t for t in _SPLIT.split(raw.strip()) if t]
56
+ bad = [t for t in tokens if not _ID.match(t)]
57
+ if bad:
58
+ raise ValueError("%s: not well-formed ids: %s" % (field, ", ".join(bad)))
59
+ return tokens
60
+
61
+
62
+ def _dedupe(ids: list[str]) -> tuple[list[str], list[str]]:
63
+ """Preserve order, and report ids repeated WITHIN one list separately."""
64
+ seen: dict[str, int] = {}
65
+ for i in ids:
66
+ seen[i] = seen.get(i, 0) + 1
67
+ return list(seen), sorted(i for i, n in seen.items() if n > 1)
68
+
69
+
70
+ def reconcile(parent_acs: list[str], children: dict[str, list[str]]) -> dict:
71
+ """Map each parent AC to the children claiming it, by token equality."""
72
+ parent_unique, parent_dupes = _dedupe(parent_acs)
73
+ parent_set = set(parent_unique)
74
+
75
+ claims: dict[str, list[str]] = {ac: [] for ac in parent_unique}
76
+ unknown: dict[str, list[str]] = {}
77
+ for child, claimed in children.items():
78
+ for ac in claimed:
79
+ if ac in parent_set:
80
+ if child not in claims[ac]:
81
+ claims[ac].append(child)
82
+ else:
83
+ unknown.setdefault(child, []).append(ac)
84
+
85
+ unclaimed = [ac for ac in parent_unique if not claims[ac]]
86
+ double = [ac for ac in parent_unique if len(claims[ac]) > 1]
87
+ return {
88
+ "claims": claims,
89
+ "unclaimed": unclaimed,
90
+ "double_claimed": double,
91
+ "unknown_claims": unknown,
92
+ "parent_ac_duplicates": parent_dupes,
93
+ "exactly_once": not (unclaimed or double or unknown or parent_dupes),
94
+ }
95
+
96
+
97
+ def size(ac_count: int, task_count: int, turn_ceiling: int | None) -> dict:
98
+ """The first-pass implausibility test execute.md states.
99
+
100
+ load = AC count + task count; implausible once load reaches roughly half the
101
+ per-story turn ceiling. With no ceiling supplied the ratio is undecidable, so
102
+ `implausible` is None -- never False, which would read as "checked, fine".
103
+ """
104
+ load = ac_count + task_count
105
+ if not turn_ceiling:
106
+ return {
107
+ "ac_count": ac_count,
108
+ "task_count": task_count,
109
+ "turn_ceiling": None,
110
+ "load": load,
111
+ "ratio": None,
112
+ "implausible": None,
113
+ }
114
+ return {
115
+ "ac_count": ac_count,
116
+ "task_count": task_count,
117
+ "turn_ceiling": turn_ceiling,
118
+ "load": load,
119
+ "ratio": round(load / turn_ceiling, 4),
120
+ "implausible": load >= turn_ceiling / 2,
121
+ }
122
+
123
+
124
+ def _parse_child(spec: str) -> tuple[str, list[str]]:
125
+ if "=" not in spec:
126
+ raise ValueError("--child expects <row-id>=<ac,ac,...>, got: %s" % spec)
127
+ row, _, claimed = spec.partition("=")
128
+ row = row.strip()
129
+ if not row:
130
+ raise ValueError("--child is missing the row id: %s" % spec)
131
+ return row, parse_ids(claimed, field="--child %s" % row)
132
+
133
+
134
+ def build_parser() -> argparse.ArgumentParser:
135
+ parser = argparse.ArgumentParser(
136
+ description=(
137
+ "Size a story row and reconcile a decomposition's parent-AC claim "
138
+ "map. Every parent AC must be claimed exactly once."
139
+ ),
140
+ epilog=(
141
+ "example: story_sizing.py --parent-acs 'AC-1,AC-2,REQ-1' "
142
+ "--child '7-1a=AC-1,AC-2' --child '7-1b=REQ-1' --tasks 4 "
143
+ "--turn-ceiling 25"
144
+ ),
145
+ )
146
+ parser.add_argument(
147
+ "--parent-acs",
148
+ default="",
149
+ help="the parent row's acceptance criteria ids, comma or space separated",
150
+ )
151
+ parser.add_argument(
152
+ "--child",
153
+ action="append",
154
+ default=[],
155
+ metavar="ROW=ACS",
156
+ help="one child row and the parent ACs it claims; repeatable",
157
+ )
158
+ parser.add_argument("--tasks", type=int, default=0, help="task count on the row")
159
+ parser.add_argument(
160
+ "--turn-ceiling",
161
+ type=int,
162
+ default=None,
163
+ help="{workflow.max_turns_per_story}; omit to skip the implausibility test",
164
+ )
165
+ return parser
166
+
167
+
168
+ def main(argv: list[str] | None = None) -> int:
169
+ parser = build_parser()
170
+ args = parser.parse_args(argv)
171
+
172
+ try:
173
+ parent_acs = parse_ids(args.parent_acs, field="--parent-acs")
174
+ children = dict(_parse_child(spec) for spec in args.child)
175
+ except ValueError as exc:
176
+ print("usage error: %s" % exc, file=sys.stderr)
177
+ return 2
178
+
179
+ result = size(len(set(parent_acs)), args.tasks, args.turn_ceiling)
180
+ # Reconciliation only means something once a split exists. Sizing alone is
181
+ # the pre-decomposition call, and it must not report a clean claim map it
182
+ # never checked.
183
+ result["reconciled"] = bool(children)
184
+ result.update(reconcile(parent_acs, children) if children else {})
185
+
186
+ print(json.dumps(result, indent=2, sort_keys=True))
187
+ if children and not result["exactly_once"]:
188
+ return 1
189
+ return 0
190
+
191
+
192
+ if __name__ == "__main__":
193
+ sys.exit(main())