Skip to content

armelhbobdad/bmad-module-ultracode-goal / skills/ultracode-goal

ultracode-goal

Flagged

Runs a BMAD Epic autonomously to a machine-checked Definition-of-Done. Use when the user requests to 'run an epic autonomously', 'execute this epic', 'ultracode goal', or 'autonomously deliver the epic'.

FileKindSize
SKILL.mdskill md15.9 KB
assets/module-help.csvother2.1 KB
assets/module-setup.mdmarkdown5.9 KB
assets/module.yamlconfig1.9 KB
assets/ucg-awareness/bmad-architecture.tomlconfig2.5 KB
assets/ucg-awareness/bmad-create-epics-and-stories.tomlconfig3.3 KB
assets/ucg-awareness/bmad-prd.tomlconfig2.1 KB
assets/ucg-awareness/bmad-testarch-nfr.tomlconfig1.8 KB
assets/ucg-awareness/bmad-testarch-test-design.tomlconfig3.1 KB
assets/ucg-awareness/shaping-decision.mdmarkdown6.8 KB
assets/ucg-awareness/ucg-create-story.tomlconfig3.3 KB
customize.tomlconfig9.8 KB
references/define-done.mdmarkdown15.4 KB
references/execute.mdmarkdown116.7 KB
references/finalize.mdmarkdown39.2 KB
references/gate.mdmarkdown134.5 KB
references/health-check.mdmarkdown27.0 KB
references/ingest-and-scope.mdmarkdown28.2 KB
references/preflight.mdmarkdown83.6 KB
scripts/carry_build_cache.pyscript18.6 KB
scripts/claim_check.pyscript36.3 KB
scripts/drive_epic.pyexecutablescript64.1 KB
scripts/formalize_check.pyscript83.7 KB
scripts/gate_eval.pyexecutablescript67.8 KB
scripts/gate_trail.pyexecutablescript52.6 KB
scripts/headless_envelope.pyscript12.6 KB
scripts/health_check_fp.pyscript66.5 KB
scripts/hooks/budget_stop.pyexecutablescript18.7 KB
scripts/hooks/guard_pretooluse.pyexecutablescript180.1 KB
scripts/lib/mem_common.pyscript64.6 KB
scripts/link_worktree_deps.pyscript7.1 KB
scripts/mem_observation.pyscript35.5 KB
scripts/mem_recall.pyscript19.9 KB
scripts/merge_config.pyexecutablescript13.8 KB
scripts/merge_customization.pyscript18.7 KB
scripts/merge_help_csv.pyscript9.5 KB
scripts/moved_ac_check.pyscript10.0 KB
scripts/mutate_check.pyscript64.4 KB
scripts/operator_owed.pyscript17.0 KB
scripts/preflight_check.pyscript115.2 KB
scripts/probe_servers.pyscript38.7 KB
scripts/red_ids.pyscript14.0 KB
scripts/status_render.pyscript26.0 KB
scripts/story_sizing.pyexecutablescript11.7 KB
scripts/tests/bench_ucg_formalize.mdmarkdown7.3 KB
scripts/tests/fixtures/claude_mem_real_payload.jsonconfig3.4 KB
scripts/tests/fixtures/engine-6.12/README.mdmarkdown957 B
scripts/tests/fixtures/engine-6.12/config_utils.pyscript4.1 KB
scripts/tests/fixtures/engine-6.12/resolve_customization.pyexecutablescript5.1 KB
scripts/tests/fixtures/engine/README.mdmarkdown1.0 KB
scripts/tests/fixtures/engine/resolve_customization.pyexecutablescript8.0 KB
scripts/tests/fixtures/execute_pre_verification_axes.mdmarkdown29.1 KB
scripts/tests/fixtures/execute_resume_clause_no_baseline.mdmarkdown215 B
scripts/tests/fixtures/execute_run_status_preedit.mdmarkdown1.2 KB
scripts/tests/fixtures/execute_spine_end_no_escalation_fire.mdmarkdown194 B
scripts/tests/fixtures/execute_step0_baseline_no_sha.mdmarkdown1.0 KB
scripts/tests/fixtures/execute_ticker_line.mdmarkdown332 B
scripts/tests/fixtures/finalize_epic_complete_hook_no_escalation.mdmarkdown579 B
scripts/tests/fixtures/finalize_headless_output_hand_composed.mdmarkdown1.2 KB
scripts/tests/fixtures/finalize_no_graphify_section.mdmarkdown19.4 KB
scripts/tests/fixtures/floor/all_clean/impl-artifacts/7-1-clean.mdmarkdown477 B
scripts/tests/fixtures/floor/all_clean/impl-artifacts/sprint-status.yamlconfig88 B
scripts/tests/fixtures/floor/all_clean/planning-artifacts/architecture-fixture.mdmarkdown236 B
scripts/tests/fixtures/floor/all_clean/planning-artifacts/prd-fixture.mdmarkdown225 B
scripts/tests/fixtures/floor/all_clean/tea/config.yamlconfig104 B
scripts/tests/fixtures/floor/all_clean/tea/traceability/e2e-trace-summary.jsonconfig48 B
scripts/tests/fixtures/floor/invented_threshold/impl-artifacts/61-1-threshold.mdmarkdown564 B
scripts/tests/fixtures/floor/invented_threshold/impl-artifacts/sprint-status.yamlconfig94 B
scripts/tests/fixtures/floor/invented_threshold/planning-artifacts/architecture-fixture.mdmarkdown236 B
scripts/tests/fixtures/floor/invented_threshold/planning-artifacts/prd-fixture.mdmarkdown225 B
scripts/tests/fixtures/floor/invented_threshold/tea/config.yamlconfig104 B
scripts/tests/fixtures/floor/invented_threshold/tea/traceability/e2e-trace-summary.jsonconfig48 B
scripts/tests/fixtures/floor/invented_threshold_unknown/impl-artifacts/61-1-threshold.mdmarkdown644 B
scripts/tests/fixtures/floor/invented_threshold_unknown/impl-artifacts/sprint-status.yamlconfig94 B
scripts/tests/fixtures/floor/invented_threshold_unknown/planning-artifacts/architecture-fixture.mdmarkdown236 B
scripts/tests/fixtures/floor/invented_threshold_unknown/planning-artifacts/prd-fixture.mdmarkdown225 B
scripts/tests/fixtures/floor/invented_threshold_unknown/tea/config.yamlconfig104 B
scripts/tests/fixtures/floor/invented_threshold_unknown/tea/traceability/e2e-trace-summary.jsonconfig48 B
scripts/tests/fixtures/floor/leaked_tea/impl-artifacts/9-1-leak.mdmarkdown475 B
scripts/tests/fixtures/floor/leaked_tea/impl-artifacts/sprint-status.yamlconfig87 B
scripts/tests/fixtures/floor/leaked_tea/impl-artifacts/test-design-9-1.mdmarkdown291 B
scripts/tests/fixtures/floor/leaked_tea/planning-artifacts/architecture-fixture.mdmarkdown236 B
scripts/tests/fixtures/floor/leaked_tea/planning-artifacts/prd-fixture.mdmarkdown225 B
scripts/tests/fixtures/floor/leaked_tea/tea/config.yamlconfig104 B
scripts/tests/fixtures/floor/leaked_tea/tea/traceability/e2e-trace-summary.jsonconfig48 B
scripts/tests/fixtures/floor/leaked_tea_clean/impl-artifacts/9-1-leak.mdmarkdown475 B
scripts/tests/fixtures/floor/leaked_tea_clean/impl-artifacts/sprint-status.yamlconfig87 B
scripts/tests/fixtures/floor/leaked_tea_clean/planning-artifacts/architecture-fixture.mdmarkdown236 B
scripts/tests/fixtures/floor/leaked_tea_clean/planning-artifacts/prd-fixture.mdmarkdown225 B
scripts/tests/fixtures/floor/leaked_tea_clean/tea/config.yamlconfig104 B
scripts/tests/fixtures/floor/leaked_tea_clean/tea/traceability/e2e-trace-summary.jsonconfig48 B
scripts/tests/fixtures/floor/leaked_tea_clean/tea/traceability/test-design-9-1.mdmarkdown296 B
scripts/tests/fixtures/floor/orphaned_index/impl-artifacts/10-1-orphan.mdmarkdown513 B
scripts/tests/fixtures/floor/orphaned_index/impl-artifacts/sprint-status.yamlconfig91 B
scripts/tests/fixtures/floor/orphaned_index/planning-artifacts/architecture-fixture.mdmarkdown236 B
scripts/tests/fixtures/floor/orphaned_index/planning-artifacts/prd-fixture.mdmarkdown225 B
scripts/tests/fixtures/floor/orphaned_index/tea/config.yamlconfig104 B
scripts/tests/fixtures/floor/orphaned_index/tea/traceability/e2e-trace-summary.jsonconfig48 B
scripts/tests/fixtures/floor/orphaned_index_resolved/impl-artifacts/10-1-orphan.mdmarkdown508 B
scripts/tests/fixtures/floor/orphaned_index_resolved/impl-artifacts/10-2-helper.mdmarkdown479 B
scripts/tests/fixtures/floor/orphaned_index_resolved/impl-artifacts/sprint-status.yamlconfig120 B
scripts/tests/fixtures/floor/orphaned_index_resolved/planning-artifacts/architecture-fixture.mdmarkdown236 B
scripts/tests/fixtures/floor/orphaned_index_resolved/planning-artifacts/prd-fixture.mdmarkdown225 B
scripts/tests/fixtures/floor/orphaned_index_resolved/tea/config.yamlconfig104 B
scripts/tests/fixtures/floor/orphaned_index_resolved/tea/traceability/e2e-trace-summary.jsonconfig48 B
scripts/tests/fixtures/floor/sourced_threshold/impl-artifacts/61-1-threshold.mdmarkdown609 B
scripts/tests/fixtures/floor/sourced_threshold/impl-artifacts/sprint-status.yamlconfig94 B
scripts/tests/fixtures/floor/sourced_threshold/planning-artifacts/architecture-fixture.mdmarkdown236 B
scripts/tests/fixtures/floor/sourced_threshold/planning-artifacts/prd-fixture.mdmarkdown225 B
scripts/tests/fixtures/floor/sourced_threshold/tea/config.yamlconfig104 B
scripts/tests/fixtures/floor/sourced_threshold/tea/traceability/e2e-trace-summary.jsonconfig48 B
scripts/tests/fixtures/floor/unclassified_signal/impl-artifacts/12-1-signal.mdmarkdown552 B
scripts/tests/fixtures/floor/unclassified_signal/impl-artifacts/sprint-status.yamlconfig91 B
scripts/tests/fixtures/floor/unclassified_signal/planning-artifacts/architecture-fixture.mdmarkdown236 B
scripts/tests/fixtures/floor/unclassified_signal/planning-artifacts/prd-fixture.mdmarkdown225 B
scripts/tests/fixtures/floor/unclassified_signal/tea/config.yamlconfig104 B
scripts/tests/fixtures/floor/unclassified_signal/tea/traceability/e2e-trace-summary.jsonconfig48 B
scripts/tests/fixtures/floor/unclassified_signal_removed/impl-artifacts/12-1-signal.mdmarkdown483 B
scripts/tests/fixtures/floor/unclassified_signal_removed/impl-artifacts/sprint-status.yamlconfig91 B
scripts/tests/fixtures/floor/unclassified_signal_removed/planning-artifacts/architecture-fixture.mdmarkdown236 B
scripts/tests/fixtures/floor/unclassified_signal_removed/planning-artifacts/prd-fixture.mdmarkdown225 B
scripts/tests/fixtures/floor/unclassified_signal_removed/tea/config.yamlconfig104 B
scripts/tests/fixtures/floor/unclassified_signal_removed/tea/traceability/e2e-trace-summary.jsonconfig48 B
scripts/tests/fixtures/floor/vacuous_ac/impl-artifacts/8-1-vacuous.mdmarkdown435 B
scripts/tests/fixtures/floor/vacuous_ac/impl-artifacts/sprint-status.yamlconfig90 B
scripts/tests/fixtures/floor/vacuous_ac/planning-artifacts/architecture-fixture.mdmarkdown236 B
scripts/tests/fixtures/floor/vacuous_ac/planning-artifacts/prd-fixture.mdmarkdown225 B
scripts/tests/fixtures/floor/vacuous_ac/tea/config.yamlconfig104 B
scripts/tests/fixtures/floor/vacuous_ac/tea/traceability/e2e-trace-summary.jsonconfig48 B
scripts/tests/fixtures/floor/vacuous_ac_sound/impl-artifacts/8-1-vacuous.mdmarkdown482 B
scripts/tests/fixtures/floor/vacuous_ac_sound/impl-artifacts/sprint-status.yamlconfig90 B
scripts/tests/fixtures/floor/vacuous_ac_sound/planning-artifacts/architecture-fixture.mdmarkdown236 B
scripts/tests/fixtures/floor/vacuous_ac_sound/planning-artifacts/prd-fixture.mdmarkdown225 B
scripts/tests/fixtures/floor/vacuous_ac_sound/tea/config.yamlconfig104 B
scripts/tests/fixtures/floor/vacuous_ac_sound/tea/traceability/e2e-trace-summary.jsonconfig48 B
scripts/tests/fixtures/formalize/epic-clean-control/LABEL.mdmarkdown751 B
scripts/tests/fixtures/formalize/epic-clean-control/impl-artifacts/7-1-clean.mdmarkdown477 B
scripts/tests/fixtures/formalize/epic-clean-control/impl-artifacts/sprint-status.yamlconfig88 B
scripts/tests/fixtures/formalize/epic-clean-control/planning-artifacts/architecture-fixture.mdmarkdown236 B
scripts/tests/fixtures/formalize/epic-clean-control/planning-artifacts/prd-fixture.mdmarkdown225 B
scripts/tests/fixtures/formalize/epic-clean-control/tea/config.yamlconfig104 B
scripts/tests/fixtures/formalize/epic-clean-control/tea/traceability/e2e-trace-summary.jsonconfig48 B
scripts/tests/fixtures/formalize/epic-judgment-seed/LABEL.mdmarkdown1.1 KB
scripts/tests/fixtures/formalize/epic-judgment-seed/impl-artifacts/61-1-threshold.mdmarkdown564 B
scripts/tests/fixtures/formalize/epic-judgment-seed/impl-artifacts/sprint-status.yamlconfig94 B
scripts/tests/fixtures/formalize/epic-judgment-seed/planning-artifacts/architecture-fixture.mdmarkdown236 B
scripts/tests/fixtures/formalize/epic-judgment-seed/planning-artifacts/prd-fixture.mdmarkdown225 B
scripts/tests/fixtures/formalize/epic-judgment-seed/tea/config.yamlconfig104 B
scripts/tests/fixtures/formalize/epic-judgment-seed/tea/traceability/e2e-trace-summary.jsonconfig48 B
scripts/tests/fixtures/formalize/low_ratio_zero_gap_epic/impl-artifacts/6-1-experience.mdmarkdown1.3 KB
scripts/tests/fixtures/formalize/low_ratio_zero_gap_epic/impl-artifacts/sprint-status.yamlconfig93 B
scripts/tests/fixtures/formalize/low_ratio_zero_gap_epic/planning-artifacts/architecture-fixture.mdmarkdown93 B
scripts/tests/fixtures/formalize/low_ratio_zero_gap_epic/planning-artifacts/prd-fixture.mdmarkdown84 B
scripts/tests/fixtures/formalize/low_ratio_zero_gap_epic/tea/config.yamlconfig104 B
scripts/tests/fixtures/formalize/low_ratio_zero_gap_epic/tea/traceability/.keepother32 B
scripts/tests/fixtures/formalize/ready_epic/impl-artifacts/1-1-kernel.mdmarkdown848 B
scripts/tests/fixtures/formalize/ready_epic/impl-artifacts/1-2-floor.mdmarkdown538 B
scripts/tests/fixtures/formalize/ready_epic/impl-artifacts/sprint-status.yamlconfig110 B
scripts/tests/fixtures/formalize/ready_epic/planning-artifacts/architecture-fixture.mdmarkdown218 B
scripts/tests/fixtures/formalize/ready_epic/planning-artifacts/prd-fixture.mdmarkdown207 B
scripts/tests/fixtures/formalize/ready_epic/tea/config.yamlconfig104 B
scripts/tests/fixtures/formalize/ready_epic/tea/traceability/e2e-trace-summary.jsonconfig49 B
scripts/tests/fixtures/formalize/remediable_epic/impl-artifacts/2-1-thin.mdmarkdown202 B
scripts/tests/fixtures/formalize/remediable_epic/impl-artifacts/sprint-status.yamlconfig87 B
scripts/tests/fixtures/formalize/remediable_epic/planning-artifacts/architecture-fixture.mdmarkdown94 B
scripts/tests/fixtures/formalize/remediable_epic/planning-artifacts/prd-fixture.mdmarkdown85 B
scripts/tests/fixtures/formalize/remediable_epic/tea/config.yamlconfig104 B
scripts/tests/fixtures/formalize/remediable_epic/tea/traceability/.keepother32 B
scripts/tests/fixtures/formalize/unclassified_signal_epic/impl-artifacts/4-1-signal.mdmarkdown546 B
scripts/tests/fixtures/formalize/unclassified_signal_epic/impl-artifacts/sprint-status.yamlconfig89 B
scripts/tests/fixtures/formalize/unclassified_signal_epic/planning-artifacts/architecture-fixture.mdmarkdown103 B
scripts/tests/fixtures/formalize/unclassified_signal_epic/planning-artifacts/prd-fixture.mdmarkdown94 B
scripts/tests/fixtures/formalize/unclassified_signal_epic/tea/config.yamlconfig104 B
scripts/tests/fixtures/formalize/unclassified_signal_epic/tea/traceability/.keepother32 B
scripts/tests/fixtures/formalize/unreadable_epic/impl-artifacts/3-1-broken.mdbinary28 B
scripts/tests/fixtures/formalize/unreadable_epic/impl-artifacts/sprint-status.yamlconfig89 B
scripts/tests/fixtures/formalize/unreadable_epic/tea/config.yamlconfig85 B
scripts/tests/fixtures/formalize/unreadable_epic/tea/traceability/.keepother14 B
scripts/tests/fixtures/formalize/wrong_root_epic/impl-artifacts/5-1-place.mdmarkdown420 B
scripts/tests/fixtures/formalize/wrong_root_epic/impl-artifacts/prd-fixture.mdmarkdown226 B
scripts/tests/fixtures/formalize/wrong_root_epic/impl-artifacts/sprint-status.yamlconfig88 B
scripts/tests/fixtures/formalize/wrong_root_epic/planning-artifacts/architecture-fixture.mdmarkdown187 B
scripts/tests/fixtures/formalize/wrong_root_epic/tea/config.yamlconfig104 B
scripts/tests/fixtures/formalize/wrong_root_epic/tea/traceability/.keepother32 B
scripts/tests/fixtures/gate_run_the_gate_no_ticker.mdmarkdown5.7 KB
scripts/tests/fixtures/gate_trail/light/decision-log.mdmarkdown341 B
scripts/tests/fixtures/gate_trail/light/impl-artifacts/.baseline-2-4other41 B
scripts/tests/fixtures/gate_trail/light/impl-artifacts/.baseline-2-6other41 B
scripts/tests/fixtures/gate_trail/light/test-artifacts/traceability/gate-decision-2-4.jsonconfig751 B
scripts/tests/fixtures/gate_trail/light/test-artifacts/traceability/gate-decision-2-6.jsonconfig755 B
scripts/tests/fixtures/gate_trail/light/test-artifacts/traceability/trace-2-4.mdmarkdown1.4 KB
scripts/tests/fixtures/gate_trail/light/test-artifacts/traceability/trace-2-6.mdmarkdown1.3 KB
scripts/tests/fixtures/gate_trail/production/decision-log.mdmarkdown783 B
scripts/tests/fixtures/gate_trail/production/impl-artifacts/.baseline-7-1other41 B
scripts/tests/fixtures/gate_trail/production/impl-artifacts/.baseline-7-2other41 B
scripts/tests/fixtures/gate_trail/production/impl-artifacts/.baseline-7-3other41 B
scripts/tests/fixtures/gate_trail/production/test-artifacts/atdd-checklist-7-1.mdmarkdown509 B
scripts/tests/fixtures/gate_trail/production/test-artifacts/atdd-checklist-7-2.mdmarkdown300 B
scripts/tests/fixtures/gate_trail/production/test-artifacts/traceability/gate-decision-7-1.jsonconfig648 B
scripts/tests/fixtures/gate_trail/production/test-artifacts/traceability/gate-decision-7-2.jsonconfig679 B

scripts/gate_trail.py

View on GitHub
#!/usr/bin/env -S uv run --script
# /// script
# requires-python = ">=3.11"
# dependencies = []
# ///
"""Synthesize the per-story evidence trail a finished Epic leaves behind.

Writes `gate-trail.md` into the run folder (a peer of `run-report.md` and
`.decision-log.md`) so a reader can audit a green Epic without re-running it.
Each in-scope story gets a section whose table traces five columns:

    acceptance criterion -> planned test -> result -> gate verdict -> commit

PURE SYNTHESIS. Every cell is read out of an artifact the run already wrote;
this script forms no judgment of its own and produces no verdict:

    | column                | production source        | light source            |
    | acceptance criterion  | acceptance checklist     | trace report coverage   |
    | planned test          | acceptance checklist     | trace report coverage   |
    | result                | acceptance checklist     | trace report coverage   |
    | gate verdict          | `escalate` while its escalation is open, else   |
    |                       | the recorded verdict, else gate_status mapped   |
    |                       | through gate_eval.GATE_VERDICT                  |
    | commit                | git log over the story's baseline range         |

The verdict cell is `gate_eval.GATE_VERDICT[gate_status]` and nothing else. An
unrecognized gate_status is rendered verbatim rather than re-classified, and the
production AND is NEVER re-applied here: it already ran when the gate decided,
and re-running it at finalize would be a second, later judgment. When the run
recorded its own verdict for a story (a JSON object carrying a `verdict` key,
fenced or inline in backticks, under that story's heading in `.decision-log.md`,
which `references/gate.md` has the run write before each gate cycle as
`### Story <story_id>: gate`), that recorded verdict wins over the mapped one,
because it is what the run actually acted on - including any downgrade the gate
applied at decision time.

A story whose escalation is still open renders `escalate`, whatever verdict the
log or the gate artifact holds. The `escalate` route stops AFTER logging the
verdict it escalated from: a FAIL only operator evidence can change, or a
re-loop past the turn ceiling, leaves `gate_eval.py`'s `reloop` as the only
verdict JSON in the log, and FAIL maps to `reloop` too, so without this the
trail showed a story waiting on operator evidence as one owing a code fix. Open
is read exactly as a resume reads it (`preflight_check._escalation_of`): the
typed sidecar `escalation-<story>.json` is on disk, its id is not closed, and
its kind is not a handoff. A story whose sprint-status row reads `done`
advanced, so a sidecar beside it is not where it stopped: one an older run left
beside a story that later advanced is residue, and is not rendered. The one
kind the advance route itself writes, `evidence-commit-rejected`, owes a commit
and not a verdict: the story keeps the verdict it advanced on, and its
verdict-source line names the open escalation.

The recorded verdict is honoured ONLY for a story whose own gate artifact
resolved. A verdict with no artifact behind it - recorded by an earlier
invocation whose artifacts are gone, or one this invocation cannot resolve -
would render `advance` beside `Gate artifact: n/a` while `gate_eval.py` itself
would refuse the same story with NOT_EVALUATED -> escalate. The trail must not
disagree with the gate in the gate's own column, so such a story renders `n/a`
and its verdict-source line says why. The decision log still holds the verdict;
what this report declines to do is present it as gated evidence. An open
escalation is not bound by this rule: with no artifact the gate returns
`escalate` too, so the story renders `escalate` and its verdict-source line
says that no gate artifact resolved.

FAIL-SOFT. Every source is optional. A missing, short or unparseable file
renders `n/a` in its cell and the synthesis continues. This is the opposite of
`gate_eval.py`, which fails closed, and the asymmetry is deliberate: the gate has
authority and must not advance on evidence it could not read, while this report
has none - failing closed here would turn a reporting bug into a blocked run.

That covers the SOURCES, not the invocation. The story list is an argument, not
an artifact to be read: with no ids this script would write a well-formed
document carrying no sections at all, an evidence trail that traces nothing and
that the stage then names in the run report as delivered evidence. So the ids
are refused up front - exit 2, nothing written - which is the invocation-error
lane `--run-dir` and `--profile` already occupy, and costs a re-issued command
rather than a run.

Gate-artifact resolution is imported from `gate_eval.py` rather than
re-implemented, so the trail always describes the same file that decided.

    python3 gate_trail.py --run-dir DIR --impl-artifacts DIR --trace-output DIR \
        --profile light --story 4-1 --story 4-2
"""

from __future__ import annotations

import argparse
import json
import re
import subprocess
import sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent))

import gate_eval  # noqa: E402  (sibling script, path set above)

OUTPUT_NAME = "gate-trail.md"

# The five columns this trail exists to trace. Every rendered row carries all
# five: drop one and the trail stops being an audit trail.
COLUMNS = (
    "Acceptance criterion",
    "Planned test",
    "Result",
    "Gate verdict",
    "Commit",
)

# Rendered in any cell whose source artifact is absent or unreadable.
NA = "n/a"

# The un-suffixed artifact names `references/gate.md` documents for a directory
# holding a single story's artifacts. They carry no story id, so they can only be
# matched by name.
# The stems that carry NO story id, derived from the gate's own artifact-prefix
# table rather than restated. A hand-maintained copy drifted the moment that
# table learned a new prefix: `traceability-matrix` (TEA's own default trace
# report filename) was added there and not here, so TEA's real isolated
# single-story directory stopped counting as isolated on THIS side only -
# `gate_eval` read its `gate-decision.json` as PASS while the trail rendered
# `n/a` for the same file. Deriving it means the two readers cannot disagree
# about what "generically named" means, which is the property the trail's own
# `gate_status_for` docstring asks for.
GENERIC_ARTIFACT_STEMS = frozenset("-".join(prefix) for prefix in gate_eval._ARTIFACT_PREFIXES)

# Column headers are matched by NAME, never by position: the house trace table
# carries an extra split column that a future trace author may drop, and a
# positional parser would then read the wrong column as the planned test.
_AC_HEADERS = {"ac", "acs", "ac #", "id", "criterion", "criteria", "acceptance criterion", "criterion id"}
# Ordered by preference, because a TEA trace matrix can carry several matching
# columns (`Test ID` beside `Test (node)`, `Result` beside `Coverage`): the house
# names first, then TEA's node and file columns, and a bare test id last.
_TEST_HEADER_PREFERENCE = (
    "verification",
    "planned test",
    "planned tests",
    "named verification",
    "test",
    "tests",
    "test (node)",
    "test file:line",
    "test file",
    "test id",
)
_RESULT_HEADER_PREFERENCE = ("result", "status", "outcome", "coverage", "coverage status")
# Bare criterion headers that also key tables that are not acceptance criteria:
# TEA's gate-threshold tables read `| Criterion | Threshold | Actual | Status |`.
# Keyed only by one of these, a table counts only when it names a planned test.
_AMBIGUOUS_AC_HEADERS = frozenset({"id", "criterion", "criteria"})
# Keys that may make a trace report's tested table win over its first one. A
# bare `ID` keys case lists (`| ID | Test | Status |`) and an `ACs` column is a
# cross-reference in a file inventory (`| # | File | Tests | Level | ACs |`):
# either would render test ids or file numbers as criteria.
_OVERRIDE_AC_HEADERS = frozenset(_AC_HEADERS - {"id", "acs"})

# A heading whose first word is `Story`, with the id after it and the rest of the
# line. Which of these name a story is `_story_heading_id`'s call: most are prose
# (`### Story SCOPE: one step moved`), and a prose heading must not end a story's
# entries.
_STORY_HEADING = re.compile(
    r"^(#{2,4})[ \t]+story[ \t]+([\w.\-]*\w)(.*)$", re.IGNORECASE | re.MULTILINE
)
# The rest of the line in the heading `references/gate.md` ("Run the gate") has
# the run write before each gate cycle: `### Story <story_id>: gate`.
_GATE_HEADING_TAIL = re.compile(r":[ \t]*gate\s*", re.IGNORECASE)
# The same tail as a later cycle's heading may carry it: `gate`, `re-gate` or
# `regate` alone, or followed by a cycle number (`2`, `#2` or `cycle 2`, after
# a blank, a comma, a semicolon, a colon or a dash: `: gate - cycle 2`), which a
# note in parentheses may follow (`: gate 2 (after the fix)`), or by a note in
# parentheses that says `cycle` or `re-gate`, or holds only a number
# (`: gate (cycle 2)`, `: gate (2)`). Anything else after `gate` is no cycle:
# `: gate-gap`, `: gate notes`, and a note that names no cycle, such as
# `: gate (skipped)` or `: gate (evidence commit)`. Read as a cycle with no
# verdict object under it, such a note would drop a recorded `reloop` or
# `defer` and show the gate file's mapped `advance`. No blank run stands beside
# another (the separator, or one blank, comes between them), so a long run of
# blanks is read once, not split every way it can be.
_GATE_CYCLE_TAIL = re.compile(
    r":[ \t]*(?:re-?)?gate"
    r"(?:"
    r"(?:[ \t]*[,;:\-\u2013\u2014]|[ \t])[ \t]*(?:cycle[ \t]*)?#?\d+(?:[ \t]*\([^()\r\n]*\))?"
    r"|[ \t]*\((?:(?=[^()\r\n]*\b(?:cycles?|re-?gate)\b)[^()\r\n]*|[ \t]*#?\d+[ \t]*)\)"
    r")?\s*",
    re.IGNORECASE,
)
_JSON_FENCE = re.compile(r"```(?:json)?\s*\n(\{.*?\})\s*\n```", re.DOTALL)
# A JSON object as a single-backtick code span, the way some runs log
# `gate_eval.py`'s result inside a sentence. `[^`]` keeps it inside one span.
_INLINE_JSON = re.compile(r"(?<!`)`(\{[^`]*\})`(?!`)")
# The per-story gate file a `gate_eval.py` result says it read, in its `reasons`
# (`gate read from gate-decision-<story>.json`). That wording is not a contract
# (docs/_internal/STABILITY.md), so it is used only to refuse a verdict object
# that names another story's file, never to accept one.
_GATE_READ_FROM = re.compile(
    r"gate\s+read\s+from\s+(?:gate-decision|e2e-trace-summary)-([\w.\-]+?)\.json"
)

# The one escalation kind the gate's advance route writes (references/gate.md,
# "Commit the gate's evidence before the next story starts"), which the `defer`
# route takes too: the story keeps the verdict it advanced on (`advance`, or
# `defer`), and only the evidence commit is owed.
EVIDENCE_COMMIT_REJECTED = "evidence-commit-rejected"


# --------------------------------------------------------------------------
# fail-soft reads
# --------------------------------------------------------------------------


def read_text(path: Path | None) -> str | None:
    """Return a file's text, or None when it is absent or unreadable.

    The fail-soft boundary for every source this script reads. Removing it turns
    a missing artifact into a raised error instead of an `n/a` cell.
    """
    if path is None:
        return None
    try:
        return path.read_text(encoding="utf-8")
    except (OSError, UnicodeDecodeError):
        return None


def read_json(path: Path | None) -> dict | None:
    """Return a JSON object from a file, or None when absent or unparseable."""
    text = read_text(path)
    if text is None:
        return None
    try:
        loaded = json.loads(text)
    except (ValueError, TypeError):
        return None
    return loaded if isinstance(loaded, dict) else None


# --------------------------------------------------------------------------
# markdown table parsing (by header name)
# --------------------------------------------------------------------------


def _cells(line: str) -> list[str]:
    stripped = line.strip()
    if stripped.startswith("|"):
        stripped = stripped[1:]
    if stripped.endswith("|"):
        stripped = stripped[:-1]
    return [c.strip() for c in stripped.split("|")]


def _is_separator(line: str) -> bool:
    return bool(re.fullmatch(r"\|?[\s:|-]*-[\s:|-]*\|?", line.strip())) and "-" in line


def _normalize_header(cell: str) -> str:
    return cell.strip().strip("*`_").strip().lower()


def _tables(text: str) -> list[tuple[list[str], list[list[str]]]]:
    """Every pipe table in the text as (headers, rows)."""
    out: list[tuple[list[str], list[list[str]]]] = []
    lines = text.splitlines()
    index = 0
    while index < len(lines) - 1:
        line = lines[index]
        if line.strip().startswith("|") and _is_separator(lines[index + 1]):
            headers = [_normalize_header(c) for c in _cells(line)]
            rows: list[list[str]] = []
            cursor = index + 2
            while cursor < len(lines) and lines[cursor].strip().startswith("|"):
                rows.append(_cells(lines[cursor]))
                cursor += 1
            out.append((headers, rows))
            index = cursor
            continue
        index += 1
    return out


def _column(headers: list[str], preference: tuple[str, ...]) -> int | None:
    """The index of the most preferred header present, by name, never by position."""
    for name in preference:
        if name in headers:
            return headers.index(name)
    return None


def _result_column(headers: list[str]) -> int | None:
    """The result column: an exact result name, else a pass count, else coverage.

    A TEA matrix may name its pass count only as `Pytest items (passed)` or
    `Cases (passed)`; that is a result, while `Coverage` is not, so a header
    carrying "passed" is preferred before the coverage names.
    """
    exact = _column(headers, _RESULT_HEADER_PREFERENCE[:3])
    if exact is not None:
        return exact
    passed = next((i for i, h in enumerate(headers) if "passed" in h), None)
    if passed is not None:
        return passed
    return _column(headers, _RESULT_HEADER_PREFERENCE[3:])


def criterion_rows(text: str | None, *, prefer_tested: bool = False) -> list[tuple[str, str, str]]:
    """Extract (criterion, planned test, result) triples from a markdown table.

    By default the first criterion-keyed table wins: an acceptance checklist's
    first such table is its AC table, and a later one is an inventory or a
    case list whose first column is not an acceptance criterion. A trace
    report is different (`prefer_tested`): TEA puts an AC-to-design summary
    with no test column ahead of its matrix, so there the first criterion-keyed
    table that also names a planned test wins, and the first criterion-keyed
    table only when none does. A table keyed by a bare `ID`, or only by an
    `ACs` cross-reference column, never wins that way: a case list keyed
    `| ID | Test | Status |` would render its test ids as criteria with a PASS
    beside each, and a file inventory would render file numbers.

    In either mode, a table keyed only by a bare `Criterion`, `Criteria` or
    `ID` header counts only when it names a planned test, so TEA's
    gate-threshold tables never render as acceptance criteria. Columns are
    located by header name; any column the table does not carry renders `n/a`.
    """
    if not text:
        return []
    first: list[tuple[str, str, str]] = []
    skipped_ambiguous = False
    for headers, rows in _tables(text):
        ac_cols = [i for i, h in enumerate(headers) if h in _AC_HEADERS]
        if not ac_cols:
            continue
        # The criterion text comes from the first criterion-like column, but the
        # table's KEYS are all of them: TEA 1.27.2's own checklist AC table reads
        # `| ID | ID source | Acceptance criterion |`, so judging it by `ID`
        # alone skipped the one table that names the acceptance criteria.
        ac_at = ac_cols[0]
        keys = {headers[i] for i in ac_cols}
        test_at = _column(headers, _TEST_HEADER_PREFERENCE)
        result_at = _result_column(headers)
        # Coverage is not a pass: where it is the only result-like column, its
        # cells are labelled so `FULL` cannot read as a passing result.
        coverage_only = result_at is not None and headers[result_at] in _RESULT_HEADER_PREFERENCE[3:]
        if test_at is None and keys <= _AMBIGUOUS_AC_HEADERS:
            skipped_ambiguous = True
            continue
        if skipped_ambiguous and keys <= {"id"}:
            # A criterion table was already set aside for naming no test, so a
            # later table keyed only by `ID` is a case list, never the criteria:
            # taking it would render test ids with a PASS beside each.
            continue

        def pick(row: list[str], at: int | None) -> str:
            if at is None or at >= len(row):
                return NA
            return row[at].strip() or NA

        extracted: list[tuple[str, str, str]] = []
        for row in rows:
            if ac_at >= len(row):
                continue
            criterion = row[ac_at].strip()
            if not criterion:
                continue
            result = pick(row, result_at)
            if coverage_only and result != NA:
                result = f"coverage: {result}"
            extracted.append((criterion, pick(row, test_at), result))
        if not extracted:
            continue
        if not prefer_tested:
            return extracted
        if test_at is not None and keys & _OVERRIDE_AC_HEADERS:
            return extracted
        if not first:
            first = extracted
    return first


# --------------------------------------------------------------------------
# per-story sources
# --------------------------------------------------------------------------


def numeric_prefix(story: str) -> str:
    """The leading numeric components of a story id (`4-1-some-slug` -> `4-1`)."""
    parts = [p for p in re.split(r"[-._]", (story or "").strip()) if p]
    lead = []
    for part in parts:
        if not part.isdigit():
            break
        lead.append(part)
    return "-".join(lead)


def checklist_path(test_artifacts: Path | None, story: str) -> Path | None:
    """The story's acceptance checklist, which exists in production runs only."""
    if test_artifacts is None:
        return None
    return test_artifacts / f"atdd-checklist-{story}.md"


def _only_generic_artifacts(trace_output: Path) -> bool:
    """True iff every trace / gate candidate here is generically named.

    That is the isolated single-story directory `references/gate.md` tells a run
    to build when its TEA output is not named per story. It is the ONLY place a
    generically-named artifact may be accepted without an id match, because it is
    the only place such a file provably belongs to the story being rendered.
    """
    candidates = list(trace_output.glob("*.md")) + list(trace_output.glob("*.json"))
    return bool(candidates) and all(path.stem in GENERIC_ARTIFACT_STEMS for path in candidates)


def _is_trace_report(report: Path) -> bool:
    """True iff a markdown file declares itself a trace report in its frontmatter.

    The same predicate `gate_eval._resolve_gate_file` applies before honoring a
    file's `gateDecisionFile` hint, so the two readers agree on what a trace
    report *is* rather than only on how a story id is spelled.
    """
    try:
        fm = gate_eval._frontmatter(report.read_text(encoding="utf-8"))
    except (OSError, UnicodeDecodeError):
        return False
    return fm.get("workflowType") in ("testarch-trace", "trace")


def _prefix_scope(story: str) -> str | None:
    """The numeric-prefix fallback scope, or None when it collapses to the epic.

    `numeric_prefix` keeps only LEADING numeric components, so it treats two very
    different ids identically. For `4-1-some-slug` it yields `4-1` — the same
    story minus a slug, which is the fallback this scope exists for. For
    `52-7f-never-driven`, whose SECOND component is alphanumeric (the shape every
    split story takes), it yields `52`: the bare EPIC id. That is not a shorter
    spelling of the story, it is a DIFFERENT artifact set — the epic roll-up —
    so a never-driven child story resolved the epic's PASS as its own verdict.

    The fallback is therefore offered only while it still carries an epic AND a
    story component.
    """
    prefix = numeric_prefix(story)
    if not prefix or prefix == story:
        return None
    if len(prefix.split("-")) < 2:
        return None
    return prefix


def _has_own_trace_report(trace_output: Path, story: str) -> bool:
    """True iff the story has its OWN declared trace report in this directory.

    Deliberately stricter than `trace_report_path`, which exists to RENDER a
    story's report and may fall back to any id-matching markdown. Here the answer
    authorizes accepting an artifact that is NOT named for this story, so every
    leniency fails the trail OPEN:

    - matching through `numeric_prefix` let a child story (`52-7f-…`) match the
      EPIC's `trace-52.md`; and
    - falling back to any id-matching `*.md` let a story that wrote only its
      `nfr-assessment-<id>.md` — which `references/gate.md` ORDERS the non-web
      author to write into this same directory — claim a trace report it never
      produced.

    Either one made `belongs()` return True unconditionally, so an undriven story
    rendered a neighbour's, or the epic roll-up's, PASS as its own.
    """
    return any(
        gate_eval._stem_matches_story(report.stem, story) and _is_trace_report(report)
        for report in sorted(trace_output.glob("*.md"))
    )


def trace_report_path(trace_output: Path | None, story: str) -> Path | None:
    """The story's trace report, matched by id components the way the gate does.

    Among the files whose id matches, a DECLARED trace report always wins over a
    merely alphabetical first match. The non-web-stack path in `references/gate.md`
    tells a run to author `nfr-assessment-<id>.md`, `test-review-<id>.md` and
    `trace-<id>.md` into one directory; all three carry the story id, and
    `nfr-assessment-` sorts first. Selecting by sort order therefore returned the
    NFR file as the trace report, which carries no `gateDecisionFile` hint, so no
    gate decision resolved and the whole per-AC table dropped out of the trail.

    A directory whose reports declare no `workflowType` at all keeps the previous
    sorted-first behaviour rather than resolving nothing.

    THE PREFIX FALLBACK IS `_prefix_scope`, NOT `numeric_prefix`, and the
    difference is the whole epic-versus-child distinction. `_has_own_trace_report`
    was fixed to make exactly this swap - raw `numeric_prefix('52-7f-...')` is
    `'52'`, the BARE EPIC id, so a never-driven child story matched the epic's
    roll-up report - but this function kept the raw call and stayed wrong in the
    same way. Measured: every child of epic 52 (`52-0a`, `52-4b-<slug>`,
    `52-7f-never-driven`) resolved `trace-52.md`, and `criterion_rows` then
    rendered the EPIC's per-AC row under the child story's own heading in the
    evidence trail. `_prefix_scope` offers the fallback only while it still
    carries an epic AND a story component, which is the slug-suffix case it
    exists for and not a collapse to the roll-up.
    """
    if trace_output is None or not trace_output.is_dir():
        return None
    scopes = [story]
    prefix = _prefix_scope(story)
    if prefix:
        scopes.append(prefix)
    candidates = [
        report
        for report in sorted(trace_output.glob("*.md"))
        if any(gate_eval._stem_matches_story(report.stem, scope) for scope in scopes)
    ]
    if not candidates:
        return None
    declared = [report for report in candidates if _is_trace_report(report)]
    return (declared or candidates)[0]


def gate_status_for(trace_output: Path | None, story: str) -> tuple[str | None, str | None]:
    """Return (gate_status, source filename) for a story, or (None, None).

    Resolution is delegated to the gate's own resolver so the trail can never
    describe a different file than the one that decided. A gate artifact that is
    absent yields None - the cell renders `n/a` rather than being classified.

    One narrowing on top of that resolver, and it is load-bearing. In a shared
    directory holding many stories' artifacts, the resolver's last-resort
    fallback is an unscoped one: for a story that wrote no artifacts at all it
    can hand back a DIFFERENT story's gate file, which would render an
    unevaluated story with someone else's verdict - silently green. So a
    resolved artifact is only accepted when it is named for this story, or when
    this story has its own trace report in the directory (a single-story
    directory, or a report that hints at the file by name). Anything else is
    read as absent.
    """
    if trace_output is None or not trace_output.is_dir():
        return None, None
    own_trace = _has_own_trace_report(trace_output, story)

    # Try the FULL story id before the numeric prefix, which is the order
    # `gate_eval.py` itself uses. The prefix stays only as a fallback for ids
    # that genuinely resolve that way — a slug suffix on an otherwise complete
    # `<epic>-<story>` id — because `gate_eval.py`, given the same id and
    # directory, reads such a file without difficulty and two readers
    # disagreeing about one file is a defect. `_prefix_scope` is what stops that
    # fallback from collapsing an alphanumeric child id to the bare epic number.
    scopes = [story]
    prefix = _prefix_scope(story)
    if prefix:
        scopes.append(prefix)

    # A generically-named artifact carries no id to match, so it can only be
    # accepted by name - and ONLY in the isolated single-story directory
    # `references/gate.md` sanctions, where every candidate is generic. Keying on
    # the filename alone fails the trail OPEN: a per-story directory usually also
    # holds the always-written `e2e-trace-summary.json`, and an undriven story
    # would then inherit ITS status and render `advance` for work nobody did.
    isolated = _only_generic_artifacts(trace_output)

    def belongs(path: Path, scope: str) -> bool:
        return (
            own_trace
            or (isolated and path.stem in GENERIC_ARTIFACT_STEMS)
            or gate_eval._stem_matches_story(path.stem, scope)
        )

    # TWO PASSES, and the order is load-bearing. A single pass per scope lets the
    # FULL id's summary fallback fire before the numeric prefix's real gate file
    # is ever looked for, so a story with `gate-decision-4-1.json` saying CONCERNS
    # rendered the epic-wide summary's PASS instead. Every scope's authoritative
    # gate file is tried before any scope's fallback summary.
    for scope in scopes:
        # The resolver itself returns None when this story is absent from a
        # per-story-named directory; that is already "absent", so it skips the read.
        gate_file = gate_eval._resolve_gate_file(trace_output, scope)
        if gate_file is not None and belongs(gate_file, scope):
            slim = read_json(gate_file)
            if slim is not None and slim.get("gate_status"):
                return str(slim["gate_status"]).strip(), gate_file.name

    # THE SUMMARY LANE DOES NOT GET `own_trace`, and that is the difference
    # between this reader and the gate's. `_resolve_summary_file` NEVER returns
    # None - with no per-story summary it hands back the generic
    # `e2e-trace-summary.json` unconditionally - and `belongs` was True for any
    # path at all whenever `own_trace` was set. So a story that wrote its own
    # trace report but no gate artifact read the SHARED, run-wide summary as its
    # own verdict. `gate_eval.load_gate` refuses precisely this read; going
    # through `_resolve_summary_file` directly walked around the refusal, and the
    # two readers then disagreed about one file, which this module's own
    # docstring calls a defect. Measured: `gate_eval` said `escalate` for a story
    # while the rendered trail said `advance` for the same story.
    #
    # A generic summary is therefore accepted only where a generic artifact
    # provably belongs to the story being rendered: the isolated single-story
    # directory. Anywhere else it must be named for the scope.
    def summary_belongs(path: Path, scope: str) -> bool:
        return (isolated and path.stem in GENERIC_ARTIFACT_STEMS) or gate_eval._stem_matches_story(
            path.stem, scope
        )

    for scope in scopes:
        summary_file = gate_eval._resolve_summary_file(trace_output, scope)
        if summary_belongs(summary_file, scope):
            summary = read_json(summary_file)
            if summary is not None and summary.get("gate_status"):
                return str(summary["gate_status"]).strip(), summary_file.name
    return None, None


def verdict_for(gate_status: str | None, recorded: str | None) -> str:
    """The verdict cell: recorded if the run wrote one, else the gate's own map.

    Never re-derived and never re-judged - an unrecognized gate_status renders
    verbatim instead of being defaulted into a classification this script would
    then own.
    """
    if recorded:
        return recorded
    if not gate_status:
        return NA
    return gate_eval.GATE_VERDICT.get(gate_status.upper(), gate_status)


def _is_gate_heading(match: re.Match[str]) -> bool:
    """True iff a `_STORY_HEADING` match is the heading `references/gate.md` has
    the run write before each gate cycle, `### Story <story_id>: gate`."""
    level, _, tail = match.groups()
    return level == "###" and bool(_GATE_HEADING_TAIL.fullmatch(tail))


def _is_gate_cycle_heading(match: re.Match[str]) -> bool:
    """True iff a story heading opens a gate cycle: the prescribed heading at
    any level `_STORY_HEADING` reads (`## Story 7-1: gate`), as `re-gate`, or
    with a cycle number or a note that names a cycle after `gate`
    (`### Story 7-1: gate - cycle 2`, `### Story 7-1: gate (cycle 2)`), as
    `_GATE_CYCLE_TAIL` reads it. A note that names no cycle
    (`### Story 7-1: gate (skipped)`) opens none.

    Only the cycle reading takes these shapes. Which headings name a story at
    all is still `_story_heading_id`'s call, where the shape that names any id,
    listed or not, is the prescribed one alone.
    """
    return bool(_GATE_CYCLE_TAIL.fullmatch(match.group(3)))


def _story_heading_id(match: re.Match[str], keys: set[str]) -> str | None:
    """The story id a `_STORY_HEADING` match names, or None for a prose heading.

    Three shapes name a story: an id that starts with a digit, as a numeric
    sprint key does (`7-1`, `52-0a`), the shape this reader has always read; an
    id that is one of `keys`, the keys sprint-status lists, so a letter-prefixed
    key (`ex-0-1-...`) is read too; and the gate-cycle heading
    (`_is_gate_heading`), whatever its id. Any other heading
    (`### Story checks rerun after the fix`) is prose, and ends no story's
    entries.
    """
    ident = match.group(2)
    if ident[0].isdigit() or ident in keys or _is_gate_heading(match):
        return ident
    return None


def _names_another_story(payload: dict, ident: str) -> bool:
    """True iff the object's `reasons` say it read another story's gate file.

    A heading's span can run far past its own entries in a log that heads its
    stories in another shape: measured on a real epic, one story's span held two
    later stories' verdicts and none of its own.
    """
    reasons = payload.get("reasons")
    if not isinstance(reasons, list):
        return False
    for named in _GATE_READ_FROM.findall(" ".join(str(reason) for reason in reasons)):
        if _components(named) and not (
            _heading_matches_story(ident, named) or _heading_matches_story(named, ident)
        ):
            return True
    return False


def _first_verdict(span: str, ident: str) -> str | None:
    """The verdict of the first JSON object in `span` that is story `ident`'s.

    Read fenced or inline, in the order they stand. An object carrying
    `"epic_level": true` is the Epic-level gate's roll-up, which follows the
    last story's entries under no story heading of its own, so it is never a
    story's verdict, and neither is one whose `reasons` name another story's
    gate file. `strict=False` lets a string a log wrapped across lines still
    parse.
    """
    found = sorted(
        [(m.start(), m.group(1)) for m in _JSON_FENCE.finditer(span)]
        + [(m.start(), m.group(1)) for m in _INLINE_JSON.finditer(span)]
    )
    for _, raw in found:
        try:
            payload = json.loads(raw, strict=False)
        except (ValueError, TypeError):
            continue
        if not isinstance(payload, dict) or not payload.get("verdict"):
            continue
        if payload.get("epic_level") or _names_another_story(payload, ident):
            continue
        return str(payload["verdict"])
    return None


def recorded_verdicts(decision_log: Path | None, keys: set[str] | None = None) -> dict[str, str]:
    """Verdicts the run recorded per story in its decision log.

    A story heading (`_story_heading_id`, with `keys` the sprint-status keys)
    followed by a JSON object carrying a `verdict` key, fenced or inline in
    backticks, is read as the verdict the run acted on. Prose headings without
    such an object contribute nothing, which is the common case.

    A heading's entries run to the next story heading, so the FIRST verdict
    object after it is its own: a log whose later stories are headed in another
    shape puts their verdicts in an earlier story's span, and the Epic-level
    roll-up follows the last story's (`_first_verdict` skips the roll-up, and
    any object whose `reasons` name another story's gate file). A later heading
    for the same id whose span holds a verdict object replaces the earlier
    verdict. `references/gate.md` ("Run the gate") has the run write
    `### Story <story_id>: gate` before each gate cycle, so a later heading in
    that shape is a later cycle, and when its span holds no verdict object it
    drops the earlier one: the trail falls back to the gate artifact rather
    than show an earlier cycle's verdict, and the story's last cycle decides.
    A later heading at another level (`## Story 7-1: gate`), as `re-gate`, or
    with a cycle number or a note that names a cycle after `gate`
    (`: gate (cycle 2)`) is a later cycle too (`_is_gate_cycle_heading`).
    Any other later heading for the id (`### Story 7-1: re-loop 1`, a note on
    what the re-loop owes, `: gate-gap`, `: gate (skipped)`) is no cycle, so
    with no verdict object of its own it keeps the verdict before it: a
    downgraded or capped `reloop` followed by a re-loop's notes must not read
    as the gate file's mapped `advance`.

    Keyed by the heading's id VERBATIM. It used to be keyed by
    `numeric_prefix(...)`, which collapsed every alphanumeric child id of one
    epic (`52-0a`, `52-3b`, `52-7f`) into the single bucket `52`, so one story's
    verdict was rendered as the verdict of every sibling in the `--story` list,
    including stories the invocation never drove. Matching a heading id to a
    story id is `resolve_recorded_verdicts`' job, because it needs the story list
    to tell an unambiguous match from a colliding one.
    """
    text = read_text(decision_log)
    if not text:
        return {}
    listed = keys or set()
    headings = [
        (match, ident)
        for match in _STORY_HEADING.finditer(text)
        if (ident := _story_heading_id(match, listed))
    ]
    out: dict[str, str] = {}
    for index, (match, ident) in enumerate(headings):
        end = headings[index + 1][0].start() if index + 1 < len(headings) else len(text)
        verdict = _first_verdict(text[match.end() : end], ident)
        if verdict:
            out[ident] = verdict
        elif _is_gate_cycle_heading(match):
            out.pop(ident, None)
    return out


def _components(story: str) -> list[str]:
    return [p for p in re.split(r"[-._]", (story or "").strip()) if p]


def _heading_matches_story(heading: str, story: str) -> bool:
    """True iff a decision-log heading id names this story.

    Headings in a real log carry the SHORT id (`### Story 52-0a - the first
    batch`) while `--story` carries the full slugged id
    (`52-0a-the-first-batch`), so an equality test would find nothing
    and blank the column. The heading's components must be a leading run of the
    story's.
    """
    head, tail = _components(heading), _components(story)
    return bool(head) and len(head) <= len(tail) and tail[: len(head)] == head


def resolve_recorded_verdicts(recorded: dict[str, str], stories: list[str]) -> dict[str, str]:
    """Map each story id to the verdict its OWN decision-log heading recorded.

    THE UNIQUENESS RULE IS THE WHOLE POINT, so do not "simplify" it away: a
    heading that matches more than one story in the list names none of them, and
    every story it touches renders `n/a`. A bare `## Story 52` heading in an epic
    of seventy-six children matches all of them, and rendering its verdict on all
    of them is exactly the fabrication this function exists to prevent — the
    trail's header promises that an absent verdict reads `n/a`, and a reader who
    trusts that promise therefore trusts every cell that is not `n/a`.

    Where several headings match one story, the most specific (longest component
    run) wins, since a run that logged both `52-3` and `52-3b` meant the latter
    for `52-3b-the-export-step`.
    """
    out: dict[str, str] = {}
    for story in stories:
        hits = [
            heading
            for heading in recorded
            if _heading_matches_story(heading, story)
            and sum(1 for other in stories if _heading_matches_story(heading, other)) == 1
        ]
        if hits:
            out[story] = recorded[max(hits, key=lambda h: len(_components(h)))]
    return out


def sprint_rows(impl_artifacts: Path | None, repo: Path) -> dict[str, str]:
    """sprint-status.yaml's rows, key to status, located and read as a resume
    reads them (`preflight_check`). Fail-soft: no impl-artifacts dir, or no
    readable file, reads as no rows."""
    if impl_artifacts is None:
        return {}
    import preflight_check  # noqa: PLC0415  (sibling script, path set above)

    text = read_text(preflight_check._locate_sprint_status(repo, impl_artifacts))
    return preflight_check._parse_development_status(text) if text else {}


def open_escalations(impl_artifacts: Path | None, stories: list[str], repo: Path) -> dict[str, str]:
    """Each story whose escalation is still open, mapped to its sidecar's kind.

    Imported from `preflight_check.py` rather than re-implemented, so the trail
    calls a sidecar open exactly when a resume would stop on it. A story whose
    sprint-status row reads `done` is left out (module docstring), unless its
    sidecar is the advance route's own `evidence-commit-rejected`. Fail-soft like
    every other source: no impl-artifacts dir reads as no escalation, and an
    unreadable sprint-status reads as no row, so an open sidecar still renders
    `escalate` (never quietly green). An unreadable sidecar is open, as the
    resume reads it, and its kind renders as `unreadable`.
    """
    if impl_artifacts is None:
        return {}
    import preflight_check  # noqa: PLC0415  (sibling script, path set above)

    rows = sprint_rows(impl_artifacts, repo)
    out: dict[str, str] = {}
    for story in stories:
        escalation = preflight_check._escalation_of(impl_artifacts, story, repo)
        if escalation is None or escalation["state"] != "open":
            continue
        kind = escalation["kind"] or "unreadable"
        if kind == EVIDENCE_COMMIT_REJECTED or rows.get(story) != "done":
            out[story] = kind
    return out


def _marker_sha(impl_artifacts: Path | None, name: str) -> str | None:
    """The first SHA-looking token in a marker file, or None when there is none."""
    if impl_artifacts is None:
        return None
    text = read_text(impl_artifacts / name)
    if not text:
        return None
    for line in text.splitlines():
        match = re.search(r"\b([0-9a-f]{7,40})\b", line.strip(), re.IGNORECASE)
        if match:
            return match.group(1)
    return None


def baseline_sha(impl_artifacts: Path | None, story: str) -> str | None:
    """The story's recorded baseline commit, or None when it was never written."""
    return _marker_sha(impl_artifacts, f".baseline-{story}")


def commit_sha(impl_artifacts: Path | None, story: str) -> str | None:
    """The story's recorded END commit, or None when the run wrote no such marker.

    `references/execute.md` step 4 writes `.commit-<story>` once the commit lands,
    step 5 refreshes it after any amend or remediation re-commit, the gate
    refreshes it after it commits a test `bmad-testarch-automate` backfilled
    (`references/gate.md`, "When automate backfills"), and the gate's advance
    route refreshes it after its evidence commit, so it names the story's LAST
    commit. Reading it is what lets the trail stop inferring a
    range end from the next story's baseline.

    The inference it replaces could not be made correct from baselines alone. Two
    stories share a SHA both when the later story's marker is residue AND when
    this story legitimately committed nothing (step 0 anchors before any
    implementation and never overwrites, so an escalated story leaves exactly
    that), and nothing in the baselines distinguishes them - so the range
    collapsed to `X..X` and a story that DID commit rendered
    `(no commits in range)`. This marker is the missing signal rather than a
    heuristic on top of the old one: it is written by the step that made the
    commit, so it is a statement about what this run drove, not a guess.
    """
    return _marker_sha(impl_artifacts, f".commit-{story}")


def _git_log(repo: Path, start: str, end: str) -> list[str] | None:
    try:
        proc = subprocess.run(
            ["git", "-C", str(repo), "log", "--format=%h", f"{start}..{end}"],
            capture_output=True,
            text=True,
            check=False,
            timeout=30,
        )
    except (OSError, ValueError, subprocess.SubprocessError):
        return None
    if proc.returncode != 0:
        return None
    return [line.strip() for line in proc.stdout.splitlines() if line.strip()]


def commit_cell(repo: Path, start: str | None, end: str | None) -> str:
    """The commits a story's baseline range contains.

    A story with no recorded baseline renders `n/a`. A readable but empty range
    is reported as such and nothing more: an observation for the reader, never a
    verdict and never a denial.
    """
    if not start:
        return NA
    end_ref = end or "HEAD"
    span = f"`{start[:7]}..{end[:7] if end else 'HEAD'}`"
    shas = _git_log(repo, start, end_ref)
    if shas is None:
        return span
    if not shas:
        return f"{span} (no commits in range)"
    return ", ".join(f"`{sha}`" for sha in shas)


# --------------------------------------------------------------------------
# rendering
# --------------------------------------------------------------------------


def _row(cells: list[str]) -> str:
    return "| " + " | ".join(cells) + " |"


def _escape(cell: str) -> str:
    return cell.replace("|", "\\|").strip() or NA


def story_section(
    story: str,
    *,
    profile: str,
    impl_artifacts: Path | None,
    test_artifacts: Path | None,
    trace_output: Path | None,
    repo: Path,
    recorded: dict[str, str],
    range_end: str | None,
    escalated: dict[str, str] | None = None,
) -> str:
    checklist = checklist_path(test_artifacts, story) if profile == "production" else None
    checklist_text = read_text(checklist)
    trace = trace_report_path(trace_output, story)
    trace_text = read_text(trace)

    rows = criterion_rows(checklist_text)
    criteria_source = checklist.name if (rows and checklist is not None) else None
    if not rows:
        rows = criterion_rows(trace_text, prefer_tested=True)
        criteria_source = trace.name if (rows and trace is not None) else criteria_source

    gate_status, gate_source = gate_status_for(trace_output, story)
    # A recorded verdict is honoured only when this story's own gate artifact
    # resolved (module docstring): with no artifact the gate itself would refuse
    # the story, and the trail must not out-vote the gate in the gate's column.
    recorded_verdict = recorded.get(story) if gate_source else None
    # An open escalation is where the run stopped, after logging the verdict it
    # escalated from, so it outranks that verdict, with or without a gate
    # artifact (module docstring). An `evidence-commit-rejected` one owes a
    # commit, not a verdict, so it changes no cell and is only named below.
    kind = (escalated or {}).get(story)
    stopped = bool(kind) and kind != EVIDENCE_COMMIT_REJECTED
    verdict = "escalate" if stopped else verdict_for(gate_status, recorded_verdict)
    start = baseline_sha(impl_artifacts, story)
    commits = commit_cell(repo, start, range_end)

    sidecar = f"`escalation-{story}.json` (kind `{kind}`)"
    if stopped:
        source = f"the open escalation {sidecar}"
        if not gate_source:
            source += ", and no gate artifact resolved for this story"
    elif recorded_verdict:
        source = "recorded in the decision log"
    elif recorded.get(story):
        source = (
            "n/a (the decision log records a verdict, but no gate artifact resolved "
            "for this story, so it is not rendered as gated evidence)"
        )
    else:
        source = "the gate artifact's status, mapped by the gate's own table"
    if kind == EVIDENCE_COMMIT_REJECTED:
        source += (
            f"; the escalation {sidecar} is still open, and owes the evidence "
            "commit, not a verdict"
        )

    lines = [f"## Story {story}", ""]
    lines.append(f"- Criteria and planned tests: {criteria_source or NA}")
    lines.append(f"- Gate artifact: {gate_source or NA} (gate status `{gate_status or NA}`)")
    lines.append(f"- Verdict source: {source}")
    lines.append(f"- Baseline: `{start}`" if start else f"- Baseline: {NA}")
    lines.append("")
    lines.append(_row(list(COLUMNS)))
    lines.append(_row(["---"] * len(COLUMNS)))
    if not rows:
        lines.append(_row([NA, NA, NA, _escape(verdict), commits]))
    else:
        for criterion, planned, result in rows:
            lines.append(
                _row(
                    [
                        _escape(criterion),
                        _escape(planned),
                        _escape(result),
                        _escape(verdict),
                        commits,
                    ]
                )
            )
    lines.append("")
    return "\n".join(lines)


def render(
    stories: list[str],
    *,
    epic: str,
    profile: str,
    impl_artifacts: Path | None,
    test_artifacts: Path | None,
    trace_output: Path | None,
    decision_log: Path | None,
    repo: Path,
) -> str:
    # Resolved against the story list, so `recorded` below is keyed by the SAME
    # full story ids the sections are rendered for and every lookup is exact.
    # The sprint-status keys and the story list tell a heading that names a
    # letter-prefixed key from a prose one.
    keys = set(sprint_rows(impl_artifacts, repo)) | set(stories)
    recorded = resolve_recorded_verdicts(recorded_verdicts(decision_log, keys), stories)
    baselines = {story: baseline_sha(impl_artifacts, story) for story in stories}
    escalated = open_escalations(impl_artifacts, stories, repo)

    header = [
        f"# Gate trail: Epic {epic}",
        "",
        "Synthesized at finalize from the artifacts this run already wrote: the per-story "
        "acceptance checklist (production runs), the trace report, the gate decision file, "
        "the decision log, the open escalations and the recorded baseline and end commits.",
        "",
        "It renders the gate's verdicts; it never forms one. A cell whose source artifact "
        f"was absent or unreadable reads `{NA}`.",
        "",
        f"- Profile: {profile}",
        f"- Stories: {len(stories)}",
        "",
    ]

    sections = []
    for index, story in enumerate(stories):
        # The range end is the story's OWN recorded end sha when the run wrote
        # one, and only otherwise the next story's baseline (whose start is this
        # story's end), and HEAD for the last story in sprint order.
        #
        # The `.commit-<story>` marker is the signal this comment used to say the
        # trail was waiting for. Inferring the end from a NEIGHBOUR's marker
        # could not be made correct: a later story anchored at THIS story's own
        # sha collapses the range to `X..X`, so a story that did commit rendered
        # `(no commits in range)` - and skipping such a candidate was not the fix
        # either, because two stories share a sha both when the later marker is
        # residue AND when this story legitimately committed nothing (step 0
        # anchors before any implementation and never overwrites, so an escalated
        # story leaves exactly that). Those two are indistinguishable from
        # baselines alone, and skipping would have traded a false negative the
        # docstring calls "an observation, never a denial" for a false positive
        # in an evidence artifact - one story credited with the next story's
        # commit, the same sha rendered under both.
        #
        # The own-marker read has neither problem, because it is not an inference:
        # step 4 writes it after the commit it made and step 5 refreshes it, so a
        # story that committed nothing has no marker and still renders from the
        # old path. The fallback is kept for exactly that case, and for stories
        # driven by a run that predates the marker.
        range_end = commit_sha(impl_artifacts, story)
        if range_end is None:
            for later in stories[index + 1 :]:
                if baselines.get(later):
                    range_end = baselines[later]
                    break
        sections.append(
            story_section(
                story,
                profile=profile,
                impl_artifacts=impl_artifacts,
                test_artifacts=test_artifacts,
                trace_output=trace_output,
                repo=repo,
                recorded=recorded,
                range_end=range_end,
                escalated=escalated,
            )
        )
    return "\n".join(header + sections).rstrip() + "\n"


def main(argv: list[str] | None = None) -> int:
    parser = argparse.ArgumentParser(
        description="Synthesize the per-story evidence trail into the run folder."
    )
    parser.add_argument("--run-dir", required=True, help="The run folder; the trail is written here.")
    parser.add_argument("--profile", required=True, choices=["light", "production"])
    parser.add_argument(
        "--story",
        action="append",
        default=[],
        dest="stories",
        required=True,
        help="A story id, repeatable, in sprint order. At least one is required.",
    )
    parser.add_argument("--impl-artifacts", help="Directory holding the recorded baselines.")
    parser.add_argument("--trace-output", help="Directory holding the trace and gate artifacts.")
    parser.add_argument(
        "--test-artifacts",
        help="Test-artifacts root holding the acceptance checklists. "
        "Defaults to the parent of --trace-output.",
    )
    parser.add_argument(
        "--decision-log",
        help="Path to this run's decision log. Defaults to .decision-log.md in the run folder.",
    )
    parser.add_argument("--epic", help="Epic id for the heading. Defaults to the run folder name.")
    parser.add_argument("--repo", default=".", help="Repository root for the commit range.")
    args = parser.parse_args(argv)

    # The same invocation-error lane, for the same error wearing a value.
    # `required=True` catches "no ids at all"; a blank id otherwise renders an
    # anonymous `## Story ` section of nothing but `n/a` - a story that reads as
    # gated and empty rather than as never named.
    if any(not story.strip() for story in args.stories):
        parser.error("--story values must be non-empty story ids")

    run_dir = Path(args.run_dir)
    trace_output = Path(args.trace_output) if args.trace_output else None
    if args.test_artifacts:
        test_artifacts: Path | None = Path(args.test_artifacts)
    else:
        test_artifacts = trace_output.parent if trace_output else None
    decision_log = Path(args.decision_log) if args.decision_log else run_dir / ".decision-log.md"
    epic = args.epic or re.sub(r"^epic-", "", run_dir.name) or run_dir.name

    text = render(
        list(args.stories),
        epic=epic,
        profile=args.profile,
        impl_artifacts=Path(args.impl_artifacts) if args.impl_artifacts else None,
        test_artifacts=test_artifacts,
        trace_output=trace_output,
        decision_log=decision_log,
        repo=Path(args.repo),
    )

    run_dir.mkdir(parents=True, exist_ok=True)
    out = run_dir / OUTPUT_NAME
    out.write_text(text, encoding="utf-8")
    print(str(out))
    return 0


if __name__ == "__main__":
    sys.exit(main())
slack-gif-creatoranthropics/skillsKnowledge and utilities for creating animated GIFs optimized for Slack. Provides constraints, validation tools, and animation concepts. Use when users request animated GIFs for Slack like "make me a GIF of X doing Y for Slack."Stars: 198kUpdated Claude CodeCodexVerifiedInstall
ponytailDietrichGebert/ponytailLazy senior dev mode for any coding task: the smallest change that fully solves it, and a reply a busy human understands in one read.Stars: 194kUpdated Claude CodeCodexVerifiedInstall
ponytail-debtDietrichGebert/ponytailHarvest every shortcut: comment into one debt ledger, so deferrals get tracked instead of forgotten. One-shot report.Stars: 194kUpdated Claude CodeCodexVerifiedInstall
ponytail-debtDietrichGebert/ponytailList every `shortcut:` comment (and older `ponytail:` ones) as a debt ledger. One-shot report, changes nothing. Use for "ponytail debt", "what did ponytail defer", "list the shortcuts", /ponytail-debt.Stars: 194kUpdated Claude CodeCodexVerifiedInstall