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
@@ -31,6 +31,15 @@ key under that story's heading in `.decision-log.md`), that recorded verdict
31
31
  wins over the mapped one, because it is what the run actually acted on -
32
32
  including any downgrade the gate applied at decision time.
33
33
 
34
+ The recorded verdict is honoured ONLY for a story whose own gate artifact
35
+ resolved. A verdict with no artifact behind it - recorded by an earlier
36
+ invocation whose artifacts are gone, or one this invocation cannot resolve -
37
+ would render `advance` beside `Gate artifact: n/a` while `gate_eval.py` itself
38
+ would refuse the same story with NOT_EVALUATED -> escalate. The trail must not
39
+ disagree with the gate in the gate's own column, so such a story renders `n/a`
40
+ and its verdict-source line says why. The decision log still holds the verdict;
41
+ what this report declines to do is present it as gated evidence.
42
+
34
43
  FAIL-SOFT. Every source is optional. A missing, short or unparseable file
35
44
  renders `n/a` in its cell and the synthesis continues. This is the opposite of
36
45
  `gate_eval.py`, which fails closed, and the asymmetry is deliberate: the gate has
@@ -83,7 +92,16 @@ NA = "n/a"
83
92
  # The un-suffixed artifact names `references/gate.md` documents for a directory
84
93
  # holding a single story's artifacts. They carry no story id, so they can only be
85
94
  # matched by name.
86
- GENERIC_ARTIFACT_STEMS = frozenset({"gate-decision", "trace", "e2e-trace-summary"})
95
+ # The stems that carry NO story id, derived from the gate's own artifact-prefix
96
+ # table rather than restated. A hand-maintained copy drifted the moment that
97
+ # table learned a new prefix: `traceability-matrix` (TEA's own default trace
98
+ # report filename) was added there and not here, so TEA's real isolated
99
+ # single-story directory stopped counting as isolated on THIS side only -
100
+ # `gate_eval` read its `gate-decision.json` as PASS while the trail rendered
101
+ # `n/a` for the same file. Deriving it means the two readers cannot disagree
102
+ # about what "generically named" means, which is the property the trail's own
103
+ # `gate_status_for` docstring asks for.
104
+ GENERIC_ARTIFACT_STEMS = frozenset("-".join(prefix) for prefix in gate_eval._ARTIFACT_PREFIXES)
87
105
 
88
106
  # Column headers are matched by NAME, never by position: the house trace table
89
107
  # carries an extra split column that a future trace author may drop, and a
@@ -312,14 +330,29 @@ def trace_report_path(trace_output: Path | None, story: str) -> Path | None:
312
330
 
313
331
  A directory whose reports declare no `workflowType` at all keeps the previous
314
332
  sorted-first behaviour rather than resolving nothing.
333
+
334
+ THE PREFIX FALLBACK IS `_prefix_scope`, NOT `numeric_prefix`, and the
335
+ difference is the whole epic-versus-child distinction. `_has_own_trace_report`
336
+ was fixed to make exactly this swap - raw `numeric_prefix('92-7f-...')` is
337
+ `'92'`, the BARE EPIC id, so a never-driven child story matched the epic's
338
+ roll-up report - but this function kept the raw call and stayed wrong in the
339
+ same way. Measured: every child of epic 92 (`92-0a`, `92-4b-<slug>`,
340
+ `92-7f-never-driven`) resolved `trace-92.md`, and `criterion_rows` then
341
+ rendered the EPIC's per-AC row under the child story's own heading in the
342
+ evidence trail. `_prefix_scope` offers the fallback only while it still
343
+ carries an epic AND a story component, which is the slug-suffix case it
344
+ exists for and not a collapse to the roll-up.
315
345
  """
316
346
  if trace_output is None or not trace_output.is_dir():
317
347
  return None
348
+ scopes = [story]
349
+ prefix = _prefix_scope(story)
350
+ if prefix:
351
+ scopes.append(prefix)
318
352
  candidates = [
319
353
  report
320
354
  for report in sorted(trace_output.glob("*.md"))
321
- if gate_eval._stem_matches_story(report.stem, story)
322
- or gate_eval._stem_matches_story(report.stem, numeric_prefix(story) or story)
355
+ if any(gate_eval._stem_matches_story(report.stem, scope) for scope in scopes)
323
356
  ]
324
357
  if not candidates:
325
358
  return None
@@ -389,9 +422,29 @@ def gate_status_for(trace_output: Path | None, story: str) -> tuple[str | None,
389
422
  if slim is not None and slim.get("gate_status"):
390
423
  return str(slim["gate_status"]).strip(), gate_file.name
391
424
 
425
+ # THE SUMMARY LANE DOES NOT GET `own_trace`, and that is the difference
426
+ # between this reader and the gate's. `_resolve_summary_file` NEVER returns
427
+ # None - with no per-story summary it hands back the generic
428
+ # `e2e-trace-summary.json` unconditionally - and `belongs` was True for any
429
+ # path at all whenever `own_trace` was set. So a story that wrote its own
430
+ # trace report but no gate artifact read the SHARED, run-wide summary as its
431
+ # own verdict. `gate_eval.load_gate` refuses precisely this read; going
432
+ # through `_resolve_summary_file` directly walked around the refusal, and the
433
+ # two readers then disagreed about one file, which this module's own
434
+ # docstring calls a defect. Measured: `gate_eval` said `escalate` for a story
435
+ # while the rendered trail said `advance` for the same story.
436
+ #
437
+ # A generic summary is therefore accepted only where a generic artifact
438
+ # provably belongs to the story being rendered: the isolated single-story
439
+ # directory. Anywhere else it must be named for the scope.
440
+ def summary_belongs(path: Path, scope: str) -> bool:
441
+ return (isolated and path.stem in GENERIC_ARTIFACT_STEMS) or gate_eval._stem_matches_story(
442
+ path.stem, scope
443
+ )
444
+
392
445
  for scope in scopes:
393
446
  summary_file = gate_eval._resolve_summary_file(trace_output, scope)
394
- if belongs(summary_file, scope):
447
+ if summary_belongs(summary_file, scope):
395
448
  summary = read_json(summary_file)
396
449
  if summary is not None and summary.get("gate_status"):
397
450
  return str(summary["gate_status"]).strip(), summary_file.name
@@ -491,11 +544,11 @@ def resolve_recorded_verdicts(recorded: dict[str, str], stories: list[str]) -> d
491
544
  return out
492
545
 
493
546
 
494
- def baseline_sha(impl_artifacts: Path | None, story: str) -> str | None:
495
- """The story's recorded baseline commit, or None when it was never written."""
547
+ def _marker_sha(impl_artifacts: Path | None, name: str) -> str | None:
548
+ """The first SHA-looking token in a marker file, or None when there is none."""
496
549
  if impl_artifacts is None:
497
550
  return None
498
- text = read_text(impl_artifacts / f".baseline-{story}")
551
+ text = read_text(impl_artifacts / name)
499
552
  if not text:
500
553
  return None
501
554
  for line in text.splitlines():
@@ -505,6 +558,32 @@ def baseline_sha(impl_artifacts: Path | None, story: str) -> str | None:
505
558
  return None
506
559
 
507
560
 
561
+ def baseline_sha(impl_artifacts: Path | None, story: str) -> str | None:
562
+ """The story's recorded baseline commit, or None when it was never written."""
563
+ return _marker_sha(impl_artifacts, f".baseline-{story}")
564
+
565
+
566
+ def commit_sha(impl_artifacts: Path | None, story: str) -> str | None:
567
+ """The story's recorded END commit, or None when the run wrote no such marker.
568
+
569
+ `references/execute.md` step 4 writes `.commit-<story>` once the commit lands
570
+ and step 5 refreshes it after any amend or remediation re-commit, so it names
571
+ the story's LAST commit. Reading it is what lets the trail stop inferring a
572
+ range end from the next story's baseline.
573
+
574
+ The inference it replaces could not be made correct from baselines alone. Two
575
+ stories share a SHA both when the later story's marker is residue AND when
576
+ this story legitimately committed nothing (step 0 anchors before any
577
+ implementation and never overwrites, so an escalated story leaves exactly
578
+ that), and nothing in the baselines distinguishes them - so the range
579
+ collapsed to `X..X` and a story that DID commit rendered
580
+ `(no commits in range)`. This marker is the missing signal rather than a
581
+ heuristic on top of the old one: it is written by the step that made the
582
+ commit, so it is a statement about what this run drove, not a guess.
583
+ """
584
+ return _marker_sha(impl_artifacts, f".commit-{story}")
585
+
586
+
508
587
  def _git_log(repo: Path, start: str, end: str) -> list[str] | None:
509
588
  try:
510
589
  proc = subprocess.run(
@@ -575,18 +654,28 @@ def story_section(
575
654
  criteria_source = trace.name if (rows and trace is not None) else criteria_source
576
655
 
577
656
  gate_status, gate_source = gate_status_for(trace_output, story)
578
- verdict = verdict_for(gate_status, recorded.get(story))
657
+ # A recorded verdict is honoured only when this story's own gate artifact
658
+ # resolved (module docstring): with no artifact the gate itself would refuse
659
+ # the story, and the trail must not out-vote the gate in the gate's column.
660
+ recorded_verdict = recorded.get(story) if gate_source else None
661
+ verdict = verdict_for(gate_status, recorded_verdict)
579
662
  start = baseline_sha(impl_artifacts, story)
580
663
  commits = commit_cell(repo, start, range_end)
581
664
 
582
665
  lines = [f"## Story {story}", ""]
583
666
  lines.append(f"- Criteria and planned tests: {criteria_source or NA}")
584
667
  lines.append(f"- Gate artifact: {gate_source or NA} (gate status `{gate_status or NA}`)")
585
- lines.append(
586
- "- Verdict source: recorded in the decision log"
587
- if recorded.get(story)
588
- else "- Verdict source: the gate artifact's status, mapped by the gate's own table"
589
- )
668
+ if recorded_verdict:
669
+ lines.append("- Verdict source: recorded in the decision log")
670
+ elif recorded.get(story):
671
+ lines.append(
672
+ "- Verdict source: n/a (the decision log records a verdict, but no gate "
673
+ "artifact resolved for this story, so it is not rendered as gated evidence)"
674
+ )
675
+ else:
676
+ lines.append(
677
+ "- Verdict source: the gate artifact's status, mapped by the gate's own table"
678
+ )
590
679
  lines.append(f"- Baseline: `{start}`" if start else f"- Baseline: {NA}")
591
680
  lines.append("")
592
681
  lines.append(_row(list(COLUMNS)))
@@ -631,7 +720,7 @@ def render(
631
720
  "",
632
721
  "Synthesized at finalize from the artifacts this run already wrote: the per-story "
633
722
  "acceptance checklist (production runs), the trace report, the gate decision file, "
634
- "the decision log and the recorded baseline commits.",
723
+ "the decision log and the recorded baseline and end commits.",
635
724
  "",
636
725
  "It renders the gate's verdicts; it never forms one. A cell whose source artifact "
637
726
  f"was absent or unreadable reads `{NA}`.",
@@ -643,25 +732,35 @@ def render(
643
732
 
644
733
  sections = []
645
734
  for index, story in enumerate(stories):
646
- # The range end is the next story's baseline (its start is this story's
647
- # end), and HEAD for the last story in sprint order.
735
+ # The range end is the story's OWN recorded end sha when the run wrote
736
+ # one, and only otherwise the next story's baseline (whose start is this
737
+ # story's end), and HEAD for the last story in sprint order.
648
738
  #
649
- # A later story anchored at THIS story's own sha collapses the range to
650
- # `X..X`, so a story that did commit renders `(no commits in range)`.
651
- # Skipping such a candidate is NOT the fix: two stories share a sha both
652
- # when the later marker is residue AND when this story legitimately
653
- # committed nothing (step 0 anchors before any implementation and never
654
- # overwrites, so an escalated story leaves exactly that), and the two are
655
- # indistinguishable from baselines alone. Skipping trades a false
656
- # negative the docstring calls "an observation, never a denial" for a
657
- # false positive in an evidence artifact - one story credited with the
658
- # next story's commit, the same sha rendered under both. Left as is until
659
- # the trail carries a signal for which stories this run actually drove.
660
- range_end = None
661
- for later in stories[index + 1 :]:
662
- if baselines.get(later):
663
- range_end = baselines[later]
664
- break
739
+ # The `.commit-<story>` marker is the signal this comment used to say the
740
+ # trail was waiting for. Inferring the end from a NEIGHBOUR's marker
741
+ # could not be made correct: a later story anchored at THIS story's own
742
+ # sha collapses the range to `X..X`, so a story that did commit rendered
743
+ # `(no commits in range)` - and skipping such a candidate was not the fix
744
+ # either, because two stories share a sha both when the later marker is
745
+ # residue AND when this story legitimately committed nothing (step 0
746
+ # anchors before any implementation and never overwrites, so an escalated
747
+ # story leaves exactly that). Those two are indistinguishable from
748
+ # baselines alone, and skipping would have traded a false negative the
749
+ # docstring calls "an observation, never a denial" for a false positive
750
+ # in an evidence artifact - one story credited with the next story's
751
+ # commit, the same sha rendered under both.
752
+ #
753
+ # The own-marker read has neither problem, because it is not an inference:
754
+ # step 4 writes it after the commit it made and step 5 refreshes it, so a
755
+ # story that committed nothing has no marker and still renders from the
756
+ # old path. The fallback is kept for exactly that case, and for stories
757
+ # driven by a run that predates the marker.
758
+ range_end = commit_sha(impl_artifacts, story)
759
+ if range_end is None:
760
+ for later in stories[index + 1 :]:
761
+ if baselines.get(later):
762
+ range_end = baselines[later]
763
+ break
665
764
  sections.append(
666
765
  story_section(
667
766
  story,
@@ -141,6 +141,49 @@ def _load_cache(cache: Path) -> dict:
141
141
  return data if isinstance(data, dict) else {}
142
142
 
143
143
 
144
+ def _prior_filing(queue_path: Path, fp: str) -> dict | None:
145
+ """The queued filing that carries this fingerprint, or None.
146
+
147
+ Searched so the handled branch can compare DEFECTS without a manual
148
+ retrieval step: the queue dir first, then its resolved/ subfolder (a
149
+ resolved filing is still the recorded prior for a collision judgement).
150
+ Identity is the frontmatter/underscored fingerprint line or the fp in the
151
+ filename - never a body-wide substring, which would match filings that
152
+ merely DISCUSS the fp. Fail-soft: an unreadable dir or file contributes
153
+ nothing; this helper informs a judgement and never blocks one.
154
+ """
155
+ fp_line = re.compile(
156
+ r"^(?:fingerprint|fp):\s*`?%s`?\s*$" % re.escape(fp), re.MULTILINE
157
+ )
158
+ for base in (queue_path, queue_path / "resolved"):
159
+ try:
160
+ entries = sorted(base.iterdir())
161
+ except OSError:
162
+ continue
163
+ for path in entries:
164
+ if not path.is_file() or path.suffix != ".md":
165
+ continue
166
+ named = fp in path.name
167
+ try:
168
+ text = path.read_text(encoding="utf-8", errors="replace")
169
+ except OSError:
170
+ continue
171
+ head = "\n".join(text.splitlines()[:40])
172
+ if not named and not fp_line.search(head):
173
+ continue
174
+ title = next(
175
+ (ln.lstrip("# ").strip() for ln in text.splitlines() if ln.startswith("# ")),
176
+ None,
177
+ )
178
+ slug_match = re.search(r"^defect_slug:\s*([a-z0-9-]+)\s*$", head, re.MULTILINE)
179
+ return {
180
+ "path": str(path),
181
+ "title": title,
182
+ "defect_slug": slug_match.group(1) if slug_match else None,
183
+ }
184
+ return None
185
+
186
+
144
187
  def cmd_seen(args: argparse.Namespace) -> int:
145
188
  if not FP_RE.match(args.fp):
146
189
  return _fail("invalid fp %r; expected ^fp-[0-9a-f]{7}$" % args.fp)
@@ -149,8 +192,15 @@ def cmd_seen(args: argparse.Namespace) -> int:
149
192
  data = _load_cache(cache)
150
193
  record = data.get(args.fp)
151
194
 
195
+ queue_path = getattr(args, "queue_path", None)
196
+ prior = _prior_filing(Path(queue_path).expanduser(), args.fp) if queue_path else None
197
+
152
198
  if not isinstance(record, dict):
153
- print(json.dumps({"seen": False, "status": "unseen", "record": None}))
199
+ print(
200
+ json.dumps(
201
+ {"seen": False, "status": "unseen", "record": None, "prior": prior}
202
+ )
203
+ )
154
204
  return 0
155
205
 
156
206
  action = record.get("action")
@@ -166,7 +216,15 @@ def cmd_seen(args: argparse.Namespace) -> int:
166
216
 
167
217
  print(
168
218
  json.dumps(
169
- {"seen": status == "handled", "status": status, "record": record}
219
+ {
220
+ "seen": status == "handled",
221
+ "status": status,
222
+ "record": record,
223
+ # The recorded prior filing, so the handled branch's mandated
224
+ # same-defect comparison starts from the text instead of from a
225
+ # retrieval step. Informational: it never changes the status.
226
+ "prior": prior,
227
+ }
170
228
  )
171
229
  )
172
230
  return 0
@@ -175,6 +233,11 @@ def cmd_seen(args: argparse.Namespace) -> int:
175
233
  def cmd_record(args: argparse.Namespace) -> int:
176
234
  if not FP_RE.match(args.fp):
177
235
  return _fail("invalid fp %r; expected ^fp-[0-9a-f]{7}$" % args.fp)
236
+ if getattr(args, "defect_slug", None) and not SLUG_RE.match(args.defect_slug):
237
+ return _fail(
238
+ "invalid defect-slug %r; expected kebab-case ^[a-z0-9]+(-[a-z0-9]+)*$"
239
+ % args.defect_slug
240
+ )
178
241
  if args.action not in ACTIONS:
179
242
  return _fail(
180
243
  "invalid action %r; expected one of %s"
@@ -186,11 +249,27 @@ def cmd_record(args: argparse.Namespace) -> int:
186
249
 
187
250
  # Merge: preserve every other fp; a corrupt/empty cache is treated as empty.
188
251
  data = _load_cache(cache)
189
- data[args.fp] = {
252
+ record = {
190
253
  "issue_url": args.issue_url,
191
254
  "action": args.action,
192
255
  "date": args.date,
193
256
  }
257
+ # Additive, informational only: names WHICH defect this record is about,
258
+ # so a REGRESSION title can be defect-accurate under a colliding fp. It
259
+ # never keys suppression - that judgement stays with the handled branch's
260
+ # mandated prior-text comparison (references/health-check.md).
261
+ #
262
+ # PRESERVED across later records for the same fp unless a new slug is
263
+ # supplied: the documented resolve recipe re-records the fp without the
264
+ # flag, and a plain replace would erase the slug at the exact moment the
265
+ # regression-naming feature needs it (the resolve that precedes the
266
+ # regression).
267
+ prior_record = data.get(args.fp)
268
+ prior_slug = prior_record.get("defect_slug") if isinstance(prior_record, dict) else None
269
+ slug = getattr(args, "defect_slug", None) or prior_slug
270
+ if slug:
271
+ record["defect_slug"] = slug
272
+ data[args.fp] = record
194
273
 
195
274
  # Atomic write: temp file in the same dir, then os.replace.
196
275
  fd, tmp_name = tempfile.mkstemp(dir=str(cache.parent), prefix=".hc-seen-", suffix=".tmp")
@@ -294,6 +373,14 @@ def main(argv: list[str] | None = None) -> int:
294
373
  seen_parser = sub.add_parser("seen", help="Check the seen-cache for a fingerprint.")
295
374
  seen_parser.add_argument("--fp", required=True)
296
375
  seen_parser.add_argument("--cache", required=True)
376
+ seen_parser.add_argument(
377
+ "--queue-path",
378
+ dest="queue_path",
379
+ help="Local queue dir; when given, the output's `prior` carries the "
380
+ "recorded filing (path, title, defect_slug) for this fp from the dir "
381
+ "or its resolved/ subfolder, so the handled branch's same-defect "
382
+ "comparison starts from text instead of a retrieval step.",
383
+ )
297
384
  seen_parser.set_defaults(func=cmd_seen)
298
385
 
299
386
  rec_parser = sub.add_parser("record", help="Record a fingerprint outcome to the cache.")
@@ -302,6 +389,14 @@ def main(argv: list[str] | None = None) -> int:
302
389
  rec_parser.add_argument("--issue-url", required=True, dest="issue_url")
303
390
  rec_parser.add_argument("--action", required=True)
304
391
  rec_parser.add_argument("--date", required=True)
392
+ rec_parser.add_argument(
393
+ "--defect-slug",
394
+ dest="defect_slug",
395
+ help="Optional kebab-case name for WHICH defect this record is about "
396
+ "(informational; never keys suppression). Makes a later REGRESSION "
397
+ "title defect-accurate under a colliding fp. A later record for the "
398
+ "same fp PRESERVES an existing slug unless a new one is supplied.",
399
+ )
305
400
  rec_parser.set_defaults(func=cmd_record)
306
401
 
307
402
  ver_parser = sub.add_parser("version", help="Resolve the module version off the probe ladder.")
@@ -317,6 +317,17 @@ _SUBSTITUTION_MARKERS = ("$(", "`", "<(")
317
317
  # Depth cap on `sh -c` recursion: a bound, not a behavior anyone should rely on.
318
318
  _MAX_SHELL_DEPTH = 4
319
319
 
320
+ # A short-option cluster that carries `-c`, whose operand is the command string.
321
+ # Matching only the bare `-c` token was a fail-open: every real combined form
322
+ # (`bash -lc`, `sh -lc`, `bash -cx`, `zsh -ic`, `bash -ec`) located no payload,
323
+ # so the segment classified as carrying no git write and took the allow path
324
+ # BEFORE the protected-branch, tests-ran, marker-freshness and empty-index gates.
325
+ # The `c` is matched anywhere in the cluster, not just at the end, because the
326
+ # shells treat it positionally-indifferently: `bash -cx` and `bash -xc` both run
327
+ # the next token (verified against bash, sh and dash). A long option (`--login`)
328
+ # cannot match, since the character after the lone leading dash must be a letter.
329
+ _PAYLOAD_FLAG = re.compile(r"^-[A-Za-z]*c[A-Za-z]*$")
330
+
320
331
 
321
332
  def _tokenize(segment: str) -> list[str]:
322
333
  """Split one shell segment into words; raises ValueError on bad quoting.
@@ -350,14 +361,25 @@ def _git_subcommand(tokens: list[str]) -> str | None:
350
361
  return None
351
362
 
352
363
 
353
- def _shell_payload_verbs(tokens: list[str], depth: int) -> set[str]:
354
- """Verbs written by the string payload of a `sh -c '…'`-style invocation."""
364
+ def _shell_payload_verbs(tokens: list[str], depth: int) -> set[str] | None:
365
+ """Verbs written by the string payload of a `sh -c '…'`-style invocation.
366
+
367
+ Returns ``None`` — not an empty set — when the payload cannot be located at
368
+ all, so the caller can fall back to the anywhere-scan instead of reading
369
+ "no payload found" as "no git write here". A LISTED shell wrapper failing
370
+ open is not part of the accepted residual (an UNLISTED one is; see
371
+ test_unlisted_wrapper_is_an_accepted_fail_open), and every other lane that
372
+ cannot honestly read a segment — unbalanced quotes, `$(…)`/backticks —
373
+ already biases toward the deny. This one now matches them.
374
+ """
355
375
  if depth >= _MAX_SHELL_DEPTH:
356
- return set()
376
+ # The cap is a recursion bound, not a verdict: refusing to look deeper
377
+ # is exactly the "cannot read it" case, so it fails closed too.
378
+ return None
357
379
  for index, token in enumerate(tokens):
358
- if token == "-c" and index + 1 < len(tokens):
380
+ if _PAYLOAD_FLAG.match(token) and index + 1 < len(tokens):
359
381
  return _command_write_verbs(tokens[index + 1], depth + 1)
360
- return set()
382
+ return None
361
383
 
362
384
 
363
385
  def _strip_leading_noise(tokens: list[str]) -> list[str]:
@@ -383,8 +405,12 @@ def _strip_leading_noise(tokens: list[str]) -> list[str]:
383
405
  tokens = stripped
384
406
 
385
407
 
386
- def _token_write_verbs(tokens: list[str], depth: int) -> set[str]:
387
- """Classify one tokenized segment: which write verbs would it actually run?"""
408
+ def _token_write_verbs(tokens: list[str], depth: int) -> set[str] | None:
409
+ """Classify one tokenized segment: which write verbs would it actually run?
410
+
411
+ ``None`` propagates the "cannot honestly read this" signal up to
412
+ :func:`_segment_write_verbs`, which owns the raw segment the fallback needs.
413
+ """
388
414
  tokens = _strip_leading_noise(tokens)
389
415
  if not tokens:
390
416
  return set()
@@ -427,7 +453,13 @@ def _segment_write_verbs(segment: str, depth: int) -> set[str]:
427
453
  # exception escape would exit non-zero, which is neither a clean allow
428
454
  # nor a clean deny.
429
455
  return _anywhere_write_verbs(segment)
430
- return _token_write_verbs(tokens, depth)
456
+ verbs = _token_write_verbs(tokens, depth)
457
+ if verbs is None:
458
+ # A listed shell wrapper whose payload could not be located. Same
459
+ # treatment as the two lanes above: scan the raw segment rather than
460
+ # let an unreadable invocation classify as carrying no write.
461
+ return _anywhere_write_verbs(segment)
462
+ return verbs
431
463
 
432
464
 
433
465
  def _command_write_verbs(command: str, depth: int) -> set[str]:
@@ -545,7 +577,10 @@ def _marker_freshness_gate(marker: Path, baseline: Path) -> None:
545
577
  "be a marker replayed from an earlier code state. Failing closed. "
546
578
  "Re-run the story's test/lint/build to green, then rewrite "
547
579
  f"{marker} with a `baseline=<sha>` line copied verbatim from "
548
- f"{baseline}, then commit."
580
+ f"{baseline}, then commit. The rewrite must be its own, prior tool "
581
+ "call: this guard pre-evaluates the command string, so a marker "
582
+ "written in the same compound command as the commit does not exist "
583
+ "yet when the commit is evaluated."
549
584
  )
550
585
  baseline_sha = _recorded_baseline_sha(baseline)
551
586
  if baseline_sha is None:
@@ -553,10 +588,14 @@ def _marker_freshness_gate(marker: Path, baseline: Path) -> None:
553
588
  "Marker-freshness guard: refusing `git commit` — this story's "
554
589
  f"recorded baseline {baseline} is missing or unreadable, so the "
555
590
  f"tests-ran marker {marker} cannot be checked against it. Failing "
556
- "closed. Restore that file (the full 40-hex commit this story "
557
- "started from, one line), re-run the story's test/lint/build to "
558
- f"green, then rewrite {marker} with a `baseline=<sha>` line copied "
559
- "verbatim from it, then commit."
591
+ "closed. If this story has already committed, restore that file "
592
+ "(the full 40-hex commit this story started from, one line); if it "
593
+ "has not yet committed — a fresh story at a resume boundary never "
594
+ "had one — write it now from `git rev-parse HEAD` exactly as step 0 "
595
+ "does. Then re-run the story's test/lint/build to green, rewrite "
596
+ f"{marker} with a `baseline=<sha>` line copied verbatim from it, "
597
+ "and commit — each write its own, prior tool call, never chained "
598
+ "into the commit command."
560
599
  )
561
600
  if marker_sha != baseline_sha:
562
601
  _deny(
@@ -568,7 +607,10 @@ def _marker_freshness_gate(marker: Path, baseline: Path) -> None:
568
607
  f"test/lint/build to green, then rewrite {marker} with a "
569
608
  f"`baseline=<sha>` line copied verbatim from {baseline} (copied, "
570
609
  "never re-derived from `git rev-parse HEAD` — the baseline does "
571
- "not move while the story runs), then commit."
610
+ "not move while the story runs), then commit. The rewrite must be "
611
+ "its own, prior tool call: the guard pre-evaluates the command "
612
+ "string, so a marker written in the same compound command as the "
613
+ "commit does not exist yet when the commit is evaluated."
572
614
  )
573
615
 
574
616
 
@@ -43,6 +43,7 @@ import tempfile
43
43
  from datetime import datetime, timezone
44
44
  from pathlib import Path
45
45
 
46
+ import gate_trail # sibling script; the ledger's table parser lives there
46
47
  from lib import mem_common as mc
47
48
 
48
49
  _DEAD_LETTER = "mem-outbox.dead.jsonl"
@@ -85,12 +86,34 @@ def _signature(cls: str, path: str, fingerprint: str | None) -> str:
85
86
  return hashlib.sha1(basis.encode("utf-8")).hexdigest()[:12]
86
87
 
87
88
 
88
- def _count_deferred(deferred_path: Path | None, epic: str) -> int:
89
- """Count '- ' list items under this epic's heading in a deferred ledger.
89
+ def _heading_names_epic(heading_text: str, epic_token: str) -> bool:
90
+ """True iff the heading names THIS epic, matched as a whole token.
90
91
 
91
- The heading is any markdown heading line whose text contains the epic id. We
92
- count '- ' bullet lines until the next heading of the same-or-shallower
93
- level. Absent file or no matching heading -> 0.
92
+ A plain substring test made every epic a prefix of its own successors: epic
93
+ `1` matched the heading "Epic 11", and `epic-1` matched "epic-10", so the
94
+ count reported a neighbour's parked items as this run's. The digits and
95
+ letters on either side are what distinguish them, so the boundary is
96
+ alphanumeric rather than `\\b` - `\\b` would not fire between `-` and `1`,
97
+ which is exactly where an `epic-1` token ends.
98
+ """
99
+ return bool(
100
+ re.search(
101
+ rf"(?<![0-9A-Za-z]){re.escape(epic_token)}(?![0-9A-Za-z])", heading_text
102
+ )
103
+ )
104
+
105
+
106
+ def _count_deferred(deferred_path: Path | None, epic: str) -> int:
107
+ """Count this epic's parked items in a deferred-work ledger.
108
+
109
+ The heading is any markdown heading line whose text contains the epic id; the
110
+ section runs until the next heading of the same-or-shallower level. The
111
+ ledger the run actually writes is a pipe TABLE (one row per parked item), so
112
+ rows carrying a non-empty `id` cell are counted first, through the same
113
+ parser `status_render.ledger_rows` reads the ledger with — a second format
114
+ guess here is how the two readers drift apart. A hand-written section with no
115
+ such table falls back to its '- ' bullets. Absent file or no matching
116
+ heading -> 0.
94
117
  """
95
118
  if deferred_path is None or not deferred_path.is_file():
96
119
  return 0
@@ -103,7 +126,7 @@ def _count_deferred(deferred_path: Path | None, epic: str) -> int:
103
126
  heading_re = re.compile(r"^(#{1,6})\s+(.*)$")
104
127
  in_section = False
105
128
  section_level = 0
106
- count = 0
129
+ section: list[str] = []
107
130
  epic_token = str(epic).strip()
108
131
 
109
132
  for line in lines:
@@ -114,13 +137,28 @@ def _count_deferred(deferred_path: Path | None, epic: str) -> int:
114
137
  if in_section and level <= section_level:
115
138
  # A sibling or shallower heading ends our section.
116
139
  in_section = False
117
- if not in_section and epic_token and epic_token in heading_text:
140
+ if not in_section and epic_token and _heading_names_epic(heading_text, epic_token):
118
141
  in_section = True
119
142
  section_level = level
143
+ if in_section:
144
+ # Keep a blank in the heading's place so a nested heading can
145
+ # never glue two adjacent tables into one.
146
+ section.append("")
147
+ continue
148
+ if in_section:
149
+ section.append(line)
150
+
151
+ count = 0
152
+ for headers, rows in gate_trail._tables("\n".join(section)):
153
+ if "id" not in headers:
120
154
  continue
121
- if in_section and line.lstrip().startswith("- "):
122
- count += 1
123
- return count
155
+ id_at = headers.index("id")
156
+ for row in rows:
157
+ if id_at < len(row) and row[id_at].strip():
158
+ count += 1
159
+ if count:
160
+ return count
161
+ return sum(1 for line in section if line.lstrip().startswith("- "))
124
162
 
125
163
 
126
164
  def cmd_build(args: argparse.Namespace) -> int: