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_eval.py

View on GitHub
#!/usr/bin/env -S uv run --script
# /// script
# requires-python = ">=3.11"
# dependencies = []
# ///
"""Decide an Epic/story verdict from TEA's deterministic quality gate.

Completion truth for ultracode-goal: this script reads TEA's gate artifact and
maps the gate_status to a verdict. It NEVER re-derives the TEA thresholds
(P0=100%, P1>=90%, overall>=80%) — those are decided upstream by the trace
workflow and written into the artifact; here we read gate_status as given.

Verdict mapping (gate_status -> verdict):
    PASS | WAIVED  -> advance
    CONCERNS       -> defer
    FAIL           -> reloop
    NOT_EVALUATED  -> escalate

Profile:
    light       -> the trace gate is the whole decision.
    production  -> additionally AND two signals; any failure downgrades an
                   otherwise-advance verdict to reloop (never below — a CONCERNS
                   stays defer, a FAIL stays reloop):
                     - nfr-assessment.md  : Overall Status != FAIL
                     - test-review.md     : Quality Score >= 80 AND
                                            Recommendation != Block

Artifact resolution:
    Read gate-decision.json (the slim file). Its name is resolved from the trace
    report markdown frontmatter when it records one, else defaults to
    <trace-output>/gate-decision.json. The slim file is only written by TEA when
    the run is gate-eligible AND the decision is PASS/CONCERNS/FAIL/WAIVED, so
    its ABSENCE is normal, not an error: fall back to the always-written
    e2e-trace-summary.json and read its gate fields. When even the summary
    carries no gate fields (not gate-eligible), gate_status is NOT_EVALUATED.

    --story (multi-story shared dir): when many stories write per-story-named
    trace reports + gate decisions into ONE shared <trace-output>, an unscoped
    glob would resolve the first/oldest report's gate (the bug --story fixes).
    Pass --story <id> and resolution is scoped to that story's artifacts: the
    trace report whose filename carries the id (then its frontmatter hint), else
    a conventionally-named gate-decision-<id>.json / e2e-trace-summary-<id>.json.
    Matching is on id components (61-6 == 61.6 == 61_6) anchored to the stem's
    trailing components, so epic id 1 resolves trace-1 (never child story 1-1)
    and 61-6 is never confused with 1-61-6.

    With no per-story artifact found, what happens next depends on how the dir
    is NAMED — FAIL-CLOSED, deliberately. If any artifact there is named for SOME
    story or epic (a known artifact prefix followed by a component starting with
    a digit), the dir is per-story-named and the requested story is genuinely
    absent: resolution fails closed to NOT_EVALUATED rather than handing back an
    unrelated story's gate. If every candidate is generically named (trace.md,
    gate-decision.json), the dir holds one story's artifacts and the unscoped
    resolution still applies, so a single-story dir is unchanged. One exception,
    because the story is not absent: a story that wrote its own
    e2e-trace-summary-<id>.json is PRESENT, and resolution names its own slim
    path so the summary fallback below reads that file rather than the shared one.

    THE FRONTMATTER HINT IS BOUNDED. A `gateDecisionFile` must name a file
    directly inside <trace-output> — not a subdirectory, not a `..` path, not an
    absolute path elsewhere on disk — and, with --story in scope, must either
    carry that story's id or carry no id at all in a directory holding no OTHER
    story's artifacts. A hint that fails either test is skipped rather than
    followed; resolution continues to the story's own conventionally-named file
    and then to the fail-closed rule above. Following one verbatim let a story
    advance on a neighbour's gate, and on files outside the directory entirely.

    python3 gate_eval.py --trace-output DIR --profile production --story 61-6 \
        --nfr DIR/nfr-assessment.md --test-review DIR/test-review.md
"""

from __future__ import annotations

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

GATE_VERDICT = {
    "PASS": "advance",
    "WAIVED": "advance",
    "CONCERNS": "defer",
    "FAIL": "reloop",
    "NOT_EVALUATED": "escalate",
}

# Frontmatter keys a trace report may use to point at its slim gate file.
_FRONTMATTER_GATE_KEYS = ("gateDecisionFile", "gateDecisionPath", "gate_decision_path")


def _read_json(path: Path) -> dict | None:
    """The JSON object in a file, or None when it cannot be read as one.

    Unreadable, non-UTF-8, not JSON, and JSON that is not an object all land on
    None together, because they mean the same thing to the callers below: this
    file yields no gate fields, so it gets the fail-closed NOT_EVALUATED an
    absent artifact already gets. A bare ``json.loads`` here RAISED instead: a
    zero-byte or half-written gate file (the residue of a killed TEA write), a
    trailing comma in a hand-authored ``gate-decision-<id>.json``, or a JSON
    array crashed the gate with a traceback and no verdict JSON at all — and
    under ``--rollup`` one such file aborted the whole epic aggregate after
    every story was already done.
    """
    try:
        loaded = json.loads(path.read_text(encoding="utf-8"))
    except (OSError, ValueError):
        # ValueError covers JSONDecodeError and UnicodeDecodeError alike.
        return None
    return loaded if isinstance(loaded, dict) else None


def _read_text(path: Path) -> str | None:
    """The file's text, or None when it cannot be read.

    The production-signal scanners below declare a FAIL-CLOSED CONTRACT for
    evidence they cannot read; a bare ``read_text`` raised out of that function
    on an unreadable or non-UTF-8 artifact instead of failing closed.
    """
    try:
        return path.read_text(encoding="utf-8")
    except (OSError, ValueError):
        return None


def _frontmatter(text: str) -> dict[str, str]:
    """Parse the leading ``---`` YAML frontmatter as flat key: value scalars.

    Stdlib-only: we only need top-level string scalars (the gate-file hint), so
    a line scan is sufficient and avoids a yaml dependency.
    """
    match = re.match(r"^---\n(.*?)\n---", text, re.DOTALL)
    if not match:
        return {}
    out: dict[str, str] = {}
    for line in match.group(1).splitlines():
        kv = re.match(r"^([A-Za-z_][\w]*):\s*(.*)$", line)
        if not kv:
            continue
        value = kv.group(2).strip().strip("'\"")
        out[kv.group(1)] = value
    return out


def _story_variants(story: str | None) -> list[str]:
    """Separator-insensitive variants of a story id for filename matching.

    A story id like ``61-6`` is written into per-story artifact names with any of
    ``-`` / ``.`` / ``_`` as the separator depending on the producing tool; treat
    them as equal so ``--story 61-6`` matches ``trace-61.6.md`` and
    ``gate-decision-61_6.json`` alike. Order is stable and de-duplicated.
    """
    if not story or not story.strip():
        return []
    parts = re.split(r"[-._]", story.strip())
    variants = [sep.join(parts) for sep in ("-", ".", "_")]
    variants.append(story.strip())
    return list(dict.fromkeys(v for v in variants if v))


def _stem_matches_story(stem: str, story: str) -> bool:
    """True iff a filename stem's trailing id-components equal the story's.

    Components are the maximal ``[-._]``-separated runs (so ``61-6`` == ``61.6``
    == ``61_6``). The story's components must be a suffix of the stem's, AND the
    stem component immediately preceding that suffix (if any) must be
    non-numeric — a filename prefix like ``trace`` / ``gate-decision`` qualifies,
    a longer numeric id does not. This keeps epic id ``1`` (matches ``trace-1``,
    not child story ``trace-1-1``) apart from story ``1-1``, and story ``61-6``
    apart from ``1-61-6``. Component matching also rejects ``trace-161`` for id
    ``61`` (``161`` != ``61``).
    """
    story_parts = [p for p in re.split(r"[-._]", story.strip()) if p]
    stem_parts = [p for p in re.split(r"[-._]", stem) if p]
    if not story_parts or len(story_parts) > len(stem_parts):
        return False
    cut = len(stem_parts) - len(story_parts)
    if stem_parts[cut:] != story_parts:
        return False
    return cut == 0 or not stem_parts[cut - 1].isdigit()


# The artifact-name prefixes this module writes. A stem that is EXACTLY one of
# these carries no id; a stem that is one of these followed by something starting
# with a digit is named for a story or an epic.
#
# `traceability-matrix` is in this table and the `("trace",)` entry does NOT
# cover it: the components are `traceability` / `matrix`. `bmad-testarch-trace`'s
# `default_output_file` is the BARE `traceability-matrix.md` (verified in its
# workflow.yaml), so both spellings matter and they matter in opposite
# directions:
#
#   - bare `traceability-matrix.md` must read as GENERIC, which is what makes
#     TEA's own untouched output the sanctioned isolated single-story directory.
#     Listing the prefix is what puts it in `gate_trail.GENERIC_ARTIFACT_STEMS`,
#     which is derived from this table - without it the trail rendered `n/a` for
#     a file the gate read as PASS.
#   - `traceability-matrix-<id>.md`, the per-story spelling a run produces when
#     it names TEA's report per story in a shared directory, must read as NAMED.
#     It did not: `_has_trailing_id` returned False, so a directory of them read
#     as generic, the fail-closed branch switched off for the whole directory,
#     and never-driven stories resolved a neighbour's PASS.
#
# Both follow from one rule, which is why the entry is a prefix and not a special
# case: these entries carry an id only when a component FOLLOWS the prefix.
_ARTIFACT_PREFIXES = (
    ("gate", "decision"),
    ("e2e", "trace", "summary"),
    ("nfr", "assessment"),
    ("test", "review"),
    ("traceability", "matrix"),
    ("trace",),
    ("atdd", "checklist"),
)


def _has_trailing_id(stem: str) -> bool:
    """True iff a filename stem carries a story or epic id after its prefix.

    NOT "the last component is numeric". That was the original rule and it is
    wrong for every id this module actually produces once a story is split or
    slugged: ``trace-52-0a`` ends in ``0a`` and ``trace-5-8-some-slug`` ends in
    ``slug``, so both read as GENERIC. A directory full of them therefore
    reported itself as not-per-story-named, which switches OFF the fail-closed
    branch in :func:`_resolve_gate_file` - and an artifact-less story then
    resolved a neighbour's gate and advanced on it.

    Measured before the fix, in a directory holding only
    ``trace-52-0a-alpha.md`` + its PASS gate file: ``--story 52-7f-never-driven``
    returned ``PASS``. That story wrote nothing at all.

    The rule is now structural: match a known artifact prefix, then require the
    NEXT component to start with a digit. A stem that is EXACTLY a prefix carries
    no id and stays GENERIC, which keeps the documented unscoped fallback for a
    directory that names no story - so bare ``traceability-matrix.md`` is generic
    while ``traceability-matrix-<id>.md`` is named for a story. That pair is
    listed explicitly in the table because the ``("trace",)`` entry does NOT
    cover it: the components are ``traceability`` / ``matrix``, so every
    per-story file from a TEA build using its own default report filename read
    as generic, and the whole directory with it.
    """
    parts = [p for p in re.split(r"[-._]", stem) if p]
    if not parts:
        return False
    for prefix in _ARTIFACT_PREFIXES:
        if len(parts) > len(prefix) and tuple(parts[: len(prefix)]) == prefix:
            return parts[len(prefix)][:1].isdigit()
    return False


def _is_per_story_named(trace_output: Path) -> bool:
    """True iff any trace report / gate-decision file there is named for a story.

    Distinguishes a shared multi-story dir (where a story with no artifacts is
    genuinely absent) from the single-story dir whose generically-named files
    the unscoped fallback is documented to resolve.

    The glob is EVERY md and json here, not `*.md` plus `gate-decision*.json`.
    The narrower pair was blind to a directory whose per-story artifacts are
    spelled `e2e-trace-summary-<id>.json`: nothing matched, the directory read as
    generic, the fail-closed branch switched off, and a never-driven story
    resolved the shared roll-up `e2e-trace-summary.json` as its own PASS.
    `gate_trail._only_generic_artifacts`, which decides the same question from
    the other side, has always globbed both; the two now see one directory.
    """
    return _per_story_naming_kind(trace_output) is not None


def _per_story_naming_kind(trace_output: Path) -> str | None:
    """The artifact KIND whose per-story name makes this directory per-story-named.

    The boolean above answers "is it"; this answers "because of what", so a
    fail-closed reason can say which artifact class flipped the directory. That
    is not derivable from the docs: the rule counts every prefix in
    `_ARTIFACT_PREFIXES`, so a lone `nfr-assessment-<id>.md` or
    `test-review-<id>.md` — files `references/gate.md` ORDERS the non-web author
    to write into this same directory — is enough on its own, and an operator
    who reads only the two gate-bearing names goes hunting for a trace/gate stem
    mismatch that does not exist.

    The KIND only, never the filename: the story this reason is written for is
    ABSENT, and quoting a neighbour's id in its verdict is the shape of the
    fail-open this branch exists to prevent. Sorted, so the answer is stable.
    """
    candidates = sorted(list(trace_output.glob("*.md")) + list(trace_output.glob("*.json")))
    for path in candidates:
        if not _has_trailing_id(path.stem):
            continue
        parts = [p for p in re.split(r"[-._]", path.stem) if p]
        for prefix in _ARTIFACT_PREFIXES:
            if len(parts) > len(prefix) and tuple(parts[: len(prefix)]) == prefix:
                return "-".join(prefix)
    return None


def _per_story_slim(trace_output: Path, story: str | None) -> Path | None:
    """The conventionally-named per-story slim gate file, when one exists."""
    for v in _story_variants(story):
        candidate = trace_output / f"gate-decision-{v}.json"
        if candidate.is_file():
            return candidate
    return None


def _owns_a_per_story_summary(trace_output: Path, story: str | None) -> bool:
    """True iff this story wrote its own ``e2e-trace-summary-<id>.json`` here.

    The fail-closed branches below mean "this story is absent from a directory
    that names its artifacts per story". That is FALSE when the story wrote its
    own per-story summary, and reading it as absent was a liveness regression
    rather than a safety win: the summary is the ALWAYS-written artifact, so a
    story whose run was not gate-eligible has that file and nothing else, and
    refusing it reports NOT_EVALUATED for a story whose own evidence is sitting
    in the directory.

    Deliberately narrower than "owns any file here". `references/gate.md` has the
    non-web author write `nfr-assessment-<id>.md` and `test-review-<id>.md` into
    this same directory, and neither carries a gate decision - a story with only
    those must still fail closed, which is a behaviour with its own test. The
    slim file is not checked either, because every caller has already returned on
    it (`scoped_slim`) before reaching here.
    """
    if not story or not story.strip():
        return False
    return any(
        (trace_output / f"e2e-trace-summary-{v}.json").is_file() for v in _story_variants(story)
    )


# The `workflowType` values a trace report must declare. A report that declares
# neither is skipped by the hint loop, so it can carry no gate decision.
_TRACE_WORKFLOW_TYPES = ("testarch-trace", "trace")


def _declares_trace_report(report: Path) -> bool:
    """True iff this markdown file declares itself a trace report.

    Unreadable counts as NOT a trace report: the file could contribute no hint
    either way, and this predicate gates a fail-closed branch, so the safe
    answer is the one that keeps the branch reachable.
    """
    try:
        fm = _frontmatter(report.read_text(encoding="utf-8"))
    except (OSError, UnicodeDecodeError):
        return False
    return fm.get("workflowType") in _TRACE_WORKFLOW_TYPES


def _holds_another_storys_artifact(trace_output: Path, story: str) -> bool:
    """True iff some artifact here is named for a story OTHER than this one.

    The question a GENERIC filename raises is not "does this directory name
    anything per story" but "could this unnamed file be someone else's". Those
    differ on exactly the shape `references/gate.md` tells an operator to build:
    isolate one story's artifacts into a fresh directory. A TEA build that names
    the trace report per story but the gate decision generically produces
    `trace-<id>.md` + `gate-decision.json` there, which IS per-story-named and
    holds no other story - so the generic gate file provably belongs to the one
    story being gated, and refusing it escalates a story with a real PASS.
    """
    candidates = list(trace_output.glob("*.md")) + list(trace_output.glob("*.json"))
    return any(
        _has_trailing_id(p.stem) and not _stem_matches_story(p.stem, story) for p in candidates
    )


def _hinted_gate_file(trace_output: Path, hint: str, story: str | None) -> Path | None:
    """The file a ``gateDecisionFile`` hint names, or None when it must not be followed.

    A hint is a string inside a trace report, and the report is written by the
    same run whose completion it is evidence for. It was previously followed
    verbatim, with no name check and no containment check at all, so three
    distinct shapes each handed a story a PASS it did not own: a hint naming a
    NEIGHBOUR's ``gate-decision-<other>.json``, a relative hint escaping the
    artifact directory (``../other-epic/gate-decision.json``), and an ABSOLUTE
    hint naming any path on disk. All three were measured returning
    ``PASS -> advance`` for a story that owned no gate decision.

    Two conditions now, and both are the artifact-resolution property rather than
    new policy:

    - CONTAINMENT. The file must sit directly in ``trace_output``. ``--trace-output``
      is the boundary the caller drew around this run's evidence; a gate read from
      outside it is not this run's gate. Absolute hints stay legal, but only when
      they resolve back inside that directory.
    - OWNERSHIP. With a story in scope, a hinted file that carries an id must
      carry THIS story's id. A hinted file carrying NO id is accepted only when
      the directory holds no OTHER story's artifacts, which is the isolated
      single-story directory `references/gate.md` tells an operator to build -
      there the unnamed file provably belongs to the one story being gated. The
      test is "is anyone else here", not "is anything here named": keying on the
      latter escalated a story whose TEA build named its trace report per story
      and its gate decision generically, which is a shape that workflow produces.

    Returning None means "do not follow this hint". The caller still prefers the
    story's OWN ``gate-decision-<id>.json`` when one exists - that artifact is
    named for this story, so it is not a file nobody pointed at - but it resolves
    NOTHING else afterwards. A refused hint is not a missing hint: the run named
    a file and this reader declined it, so falling on to the next candidate can
    RAISE the verdict, and it did (a refused FAIL became an advance off the
    story's own summary). See the ``refused_hint`` latch in the caller.
    """
    hinted = Path(hint)
    candidate = hinted if hinted.is_absolute() else trace_output / hinted
    try:
        resolved = candidate.resolve()
        inside = resolved.relative_to(trace_output.resolve())
    except (ValueError, OSError):
        return None
    # Exactly one component: a plain filename sitting directly in the directory.
    # Testing `inside.parent != Path(".")` instead let a hint of `.` or `""`
    # through, because both resolve to the DIRECTORY, whose relative form is `.`
    # and whose parent is also `.` - so resolution returned the artifact
    # directory itself as the gate file.
    if len(inside.parts) != 1:
        return None
    if story and story.strip():
        if _has_trailing_id(resolved.stem):
            return candidate if _stem_matches_story(resolved.stem, story) else None
        return None if _holds_another_storys_artifact(trace_output, story) else candidate
    return candidate


def _resolve_gate_file(
    trace_output: Path, story: str | None = None, notes: list[str] | None = None
) -> Path | None:
    """Locate the slim gate-decision file, honoring a trace-report hint.

    With ``story`` set, scope resolution to that story's artifacts so a single
    shared multi-story ``trace_output`` does not resolve the first/oldest
    story's gate. Returns ``None`` when the story matches nothing in a
    per-story-named dir — the story is genuinely absent, and taking the unscoped
    fallback there would return a DIFFERENT story's gate as this story's
    verdict. A generically-named dir keeps the documented unscoped fallback.
    """
    reports = sorted(trace_output.glob("*.md"))
    scoped_slim = _per_story_slim(trace_output, story)
    refused_hint = False
    if story and story.strip():
        # A markdown file merely NAMED for this story is not a trace report, and
        # letting one count here suppresses the fail-closed branch below.
        # `references/gate.md` tells the non-web author to write
        # `nfr-assessment-<id>.md` and `test-review-<id>.md` into this same
        # directory, and both match `_stem_matches_story`. So a story that
        # produced its NFR and review but never authored its trace pair looked
        # "present": `scoped` was non-empty, the fail-closed return was skipped,
        # neither file carries a `gateDecisionFile` hint, and resolution fell
        # through to the UNSCOPED `gate-decision.json` / `e2e-trace-summary.json`
        # - handing an artifact-less story a PASS. Measured: the same directory
        # with the NFR named `nfr-assessment.md` fails closed, and with it named
        # `nfr-assessment-1-2.md` returns PASS.
        #
        # Declared trace reports only, therefore - the same predicate the hint
        # loop below already applies before honoring a hint, and the same one
        # `gate_trail.py` applies when it picks a story's trace report. A file
        # that would contribute no hint must not buy the story a pass out of the
        # fail-closed branch either.
        scoped = [
            r
            for r in reports
            if _stem_matches_story(r.stem, story) and _declares_trace_report(r)
        ]
        if scoped:
            reports = scoped
        elif scoped_slim is not None:
            # This story wrote no trace report but DID write its own slim gate
            # file. Falling through here would leave ``reports`` as every report
            # in the directory and let the hint loop below return a NEIGHBOUR's
            # gate — observed handing an unrelated epic's PASS back as this
            # story's verdict. The story's own file wins, before any hint is read.
            return scoped_slim
        elif _is_per_story_named(trace_output) and not _owns_a_per_story_summary(
            trace_output, story
        ):
            return None
    for report in reports:
        try:
            fm = _frontmatter(report.read_text(encoding="utf-8"))
        except (OSError, UnicodeDecodeError):
            # UnicodeDecodeError is NOT an OSError, so a single non-UTF-8 markdown
            # file anywhere in the directory crashed resolution here. Catching it
            # is right; treating it as "carries no hint" is NOT, and `reports` is
            # the UNFILTERED `*.md` glob on this path (the `_declares_trace_report`
            # filter applies only to the story-scoped branch above), so this reader
            # cannot know whether the file it failed to decode was a trace report
            # carrying a `gateDecisionFile` hint.
            #
            # An unreadable report is a hint that could not be READ, never a report
            # with no hint - the same distinction the `refused_hint` branch below
            # exists to hold. Skipping silently let resolution fall through to the
            # unscoped `gate-decision.json`: measured, a story whose hinted file
            # said FAIL advanced on a neighbour's PASS, and the log read like an
            # ordinary successful resolution because the fallback named a real file.
            if notes is not None:
                notes.append(
                    f"{report.name} could not be decoded; any gate hint it carries "
                    f"was not read, so no unpointed-at file is resolved in its place"
                )
            refused_hint = True
            continue
        if fm.get("workflowType") not in _TRACE_WORKFLOW_TYPES:
            continue
        for key in _FRONTMATTER_GATE_KEYS:
            hint = fm.get(key)
            if hint:
                hinted = _hinted_gate_file(trace_output, hint, story)
                if hinted is not None:
                    return hinted
                # A hint that names another story's file, or a path outside the
                # artifact directory, is not followed and is not fatal either:
                # fall through to this story's own conventionally-named file and,
                # failing that, to the fail-closed branch below.
                #
                # It is RECORDED, though. Refusing a hint and then resolving some
                # other file changes which artifact decided, and a reader who
                # cannot see that happened has no way to tell a gate read from
                # the intended file from one read from the fallback - which can
                # carry a different verdict.
                if notes is not None:
                    notes.append(
                        f"{report.name} hints at {hint!r}, which is not a file this story owns "
                        f"inside {trace_output}; the hint was not followed"
                    )
                refused_hint = True
                break
    # No frontmatter hint. With a story in scope, prefer the conventionally-named
    # per-story slim file before the shared default so the shared dir resolves
    # the right story even when no trace report points at it.
    if scoped_slim is not None:
        return scoped_slim
    if refused_hint:
        # A REFUSED HINT IS NOT A MISSING HINT. The run pointed at a specific
        # file and this reader declined to read it, so every remaining candidate
        # below is a file nobody pointed at. Resolving one anyway does not merely
        # lose information, it can RAISE the verdict: measured, a subdirectory
        # hint carrying FAIL was refused and the story then advanced on its own
        # summary's PASS, and an unscoped run whose hinted CONCERNS was refused
        # advanced on the generic summary. Both read as ordinary successful
        # resolutions in the log, because the fallback names a real file.
        #
        # The story's OWN slim file is the one exception, and it is already
        # returned above: that artifact is named for this story, so it is not a
        # file nobody pointed at. Everything after this line is.
        return None
    if story and _is_per_story_named(trace_output) and _owns_a_per_story_summary(trace_output, story):
        # THIS STORY IS PRESENT, but its only gate-bearing artifact is its own
        # summary. Falling through to the shared `gate-decision.json` below would
        # hand it the RUN-WIDE verdict: measured, a story whose own summary said
        # CONCERNS came back PASS -> advance off the generic file. Name this
        # story's own conventional slim path instead. It does not exist (a slim
        # file that did exist was returned as `scoped_slim` long before here), so
        # `load_gate` falls through to `_resolve_summary_file`, which resolves the
        # per-story summary this branch exists for.
        return trace_output / f"gate-decision-{story}.json"
    if story and _is_per_story_named(trace_output):
        # The SAME fail-closed rule as the branch above, applied to the last
        # resort. That `return None` is guarded by `elif`, so it is reachable
        # only when `scoped` is EMPTY — a story that authored a DECLARED trace
        # report but no resolvable gate file (no `gateDecisionFile` hint, and no
        # per-story slim file) skipped it entirely and landed here, where the
        # unscoped `gate-decision.json` is a NEIGHBOUR's, or the epic roll-up's,
        # verdict. Having written a trace report must not buy a story a pass out
        # of the fail-closed lane that a story with no artifacts at all gets.
        #
        # A story that wrote its OWN per-story summary is not in that lane: it
        # is present, its evidence is here, and `load_gate` reads that summary
        # one step below. Falling closed on it reported NOT_EVALUATED for a story
        # whose only artifact is the always-written one.
        return None
    return trace_output / "gate-decision.json"


def _gate_fields_from_summary(summary: dict) -> dict:
    """Lift gate fields from e2e-trace-summary.json.

    The summary only carries gate_status / gate_criteria when the run was
    gate-eligible; otherwise those keys are absent and the gate is NOT_EVALUATED.
    """
    criteria = summary.get("gate_criteria") or {}
    return {
        "gate_status": summary.get("gate_status", "NOT_EVALUATED"),
        "p0_status": criteria.get("p0_status"),
        "p1_status": criteria.get("p1_status"),
        "overall_status": criteria.get("overall_status"),
    }


def _resolve_summary_file(trace_output: Path, story: str | None) -> Path:
    """The summary fallback path, preferring a per-story summary when one exists."""
    for v in _story_variants(story):
        candidate = trace_output / f"e2e-trace-summary-{v}.json"
        if candidate.is_file():
            return candidate
    return trace_output / "e2e-trace-summary.json"


def load_gate(trace_output: Path, reasons: list[str], story: str | None = None) -> dict:
    """Return normalized gate fields, preferring the slim file, else the summary."""
    gate_file = _resolve_gate_file(trace_output, story, reasons)
    if gate_file is None:
        # Fail-closed: the dir names its artifacts per story and none is this
        # story's, so there is nothing to read. Do NOT fall back to the unscoped
        # read — it would report a neighbouring story's gate as this one's.
        # Name WHY the fallback was refused. "The directory is named per story"
        # alone is not diagnosable: the rule fires on any known artifact prefix
        # followed by an id, so a per-story NFR or test-review is enough, and a
        # reader who assumes only the gate-bearing names hunts for a stem
        # mismatch that is not there.
        kind = _per_story_naming_kind(trace_output)
        why = (
            f"the directory is named per story (a {kind}-* file there carries a story id)"
            if kind
            else "the gate file the trace report hinted at was refused above"
        )
        reasons.append(
            f"story {story} has no trace report or gate decision in {trace_output}; "
            f"{why}, so no unscoped fallback was taken"
        )
        return {
            "gate_status": "NOT_EVALUATED",
            "p0_status": None,
            "p1_status": None,
            "overall_status": None,
        }

    if gate_file.is_file():
        slim = _read_json(gate_file)
        if slim is None:
            # Present but unreadable is not "no artifact": the file exists, so no
            # fallback below is this story's gate either. Fail closed on it.
            reasons.append(
                f"{gate_file.name} in {trace_output} is present but is not readable as a "
                "JSON object (empty, malformed, or not an object); treated as no gate decision"
            )
            return {
                "gate_status": "NOT_EVALUATED",
                "p0_status": None,
                "p1_status": None,
                "overall_status": None,
            }
        reasons.append(f"gate read from {gate_file.name}")
        return {
            "gate_status": slim.get("gate_status", "NOT_EVALUATED"),
            "p0_status": slim.get("p0_status"),
            "p1_status": slim.get("p1_status"),
            "overall_status": slim.get("overall_status"),
        }

    summary_file = _resolve_summary_file(trace_output, story)
    if (
        story
        and summary_file.name == "e2e-trace-summary.json"
        and _is_per_story_named(trace_output)
    ):
        # The summary fallback is the same unscoped read, one file along. In a
        # per-story-named directory the GENERIC summary belongs to no story in
        # particular and is written for the whole run, so handing it back as
        # this story's gate is the neighbour's-verdict fail-open wearing a
        # different filename. A per-story-named summary is still honored above.
        reasons.append(
            f"story {story} has no per-story gate decision or summary in {trace_output}; "
            "the directory is named per story (a "
            f"{_per_story_naming_kind(trace_output)}-* file there carries a story id), "
            "so the shared e2e-trace-summary.json was not read as this story's gate"
        )
        return {
            "gate_status": "NOT_EVALUATED",
            "p0_status": None,
            "p1_status": None,
            "overall_status": None,
        }
    if summary_file.is_file():
        summary = _read_json(summary_file)
        if summary is None:
            reasons.append(
                f"{gate_file.name} absent and {summary_file.name} is not readable as a "
                "JSON object (empty, malformed, or not an object); treated as no gate decision"
            )
            return {
                "gate_status": "NOT_EVALUATED",
                "p0_status": None,
                "p1_status": None,
                "overall_status": None,
            }
        reasons.append(
            f"{gate_file.name} absent; gate read from {summary_file.name} (not a failure)"
        )
        return _gate_fields_from_summary(summary)

    reasons.append(
        f"neither {gate_file.name} nor e2e-trace-summary.json present in {trace_output}"
    )
    return {
        "gate_status": "NOT_EVALUATED",
        "p0_status": None,
        "p1_status": None,
        "overall_status": None,
    }


def _scan_nfr_overall_status(text: str) -> str | None:
    """Read the NFR audit's Overall Status (PASS | CONCERNS | FAIL)."""
    match = re.search(
        r"(?:Overall\s+Status|overallStatus)[*:_\s]*[`*]*\s*(PASS|CONCERNS|FAIL|NOT_ASSESSED)",
        text,
        re.IGNORECASE,
    )
    return match.group(1).upper() if match else None


def _scan_review_score(text: str) -> int | None:
    """Read the test-review Quality Score (``{score}/100``)."""
    match = re.search(r"(?:Quality\s+Score|score)[*:_\s]*[`*]*\s*(\d{1,3})\s*/\s*100", text, re.IGNORECASE)
    return int(match.group(1)) if match else None


def _scan_review_recommendation(text: str) -> str | None:
    """Read the test-review Recommendation (Approve / ... / Block)."""
    match = re.search(
        r"Recommendation[*:_\s]*[`*]*\s*"
        r"(Approve with Comments|Approve|Request Changes|Block)",
        text,
        re.IGNORECASE,
    )
    return match.group(1) if match else None


def apply_production_and(
    verdict: str,
    nfr_path: Path | None,
    review_path: Path | None,
    reasons: list[str],
) -> tuple[str, str | None, int | None]:
    """AND the production signals; downgrade an advance to reloop on any failure.

    Returns (verdict, nfr_status, review_score). The downgrade floor is reloop:
    only an otherwise-advance verdict moves; defer/reloop/escalate are unchanged.

    FAIL-CLOSED CONTRACT (deliberate — do not "relax"): a missing file or a
    field the scanners below cannot parse is treated as a *failing* signal, not
    a neutral/absent one (see the ``nfr_status is None`` / ``review_score is None``
    / file-not-found branches). TEA prose-format drift therefore degrades to a
    conservative reloop rather than a silent false-advance. The conservative
    direction is intentional: we would rather re-loop a green story than advance
    a story whose evidence we could not actually read.

    AN OMITTED PATH IS FAILING TOO, and that is the same rule rather than a new
    one. A ``None`` path used to be skipped in silence: the signal's AND simply
    did not run, the field rendered ``null``, and the verdict was computed
    WITHOUT it. So the fail-closed contract covered a signal that was unreadable
    but not a signal that was never asked for, and forgetting a flag bought a
    higher verdict than supplying a failing artifact would have. A ``null`` beside
    ``--profile production`` also reads as "the artifact is missing or malformed",
    which is the opposite of what it meant. The epic roll-up genuinely has no
    aggregate to AND - TEA writes both artifacts per story - so it says so with
    ``--epic-level`` instead of by omission.
    """
    nfr_status: str | None = None
    review_score: int | None = None
    failed = False

    if nfr_path is not None and nfr_path.is_file():
        nfr_text = _read_text(nfr_path)
        if nfr_text is None:
            # A file that exists but cannot be read is the fail-closed contract's
            # own case, not a crash: report it as its own failing signal rather
            # than as the "field not found" one two branches down.
            reasons.append(f"nfr file {nfr_path} could not be read; treated as failing")
            failed = True
        elif (nfr_status := _scan_nfr_overall_status(nfr_text)) == "FAIL":
            reasons.append("nfr overallStatus is FAIL")
            failed = True
        elif nfr_status == "NOT_ASSESSED":
            # NOT_ASSESSED is in the scanner's alternation, so it parses cleanly
            # and never reached the `is None` branch below: it read as "present
            # and not FAIL" and PASSED the AND. But it is the NFR audit saying
            # the NFRs were never evaluated - strictly weaker evidence than a
            # file this reader cannot parse, which already fails closed two
            # branches down. Advancing a story on it inverted the contract.
            reasons.append(
                f"nfr Overall Status is NOT_ASSESSED in {nfr_path.name}; "
                "treated as failing (the NFRs were never evaluated)"
            )
            failed = True
        elif nfr_status is None:
            reasons.append(f"nfr Overall Status not found in {nfr_path.name}; treated as failing")
            failed = True
    elif nfr_path is not None:
        reasons.append(f"nfr file {nfr_path} not found; treated as failing")
        failed = True
    else:
        reasons.append(
            "--nfr not supplied on a per-story production gate; treated as failing "
            "(pass --nfr, or --epic-level if this is the epic roll-up)"
        )
        failed = True

    if review_path is not None and review_path.is_file():
        review_text = _read_text(review_path)
        if review_text is None:
            # Same fail-closed case as the NFR read above: present but unreadable
            # is a failing signal, not an exception out of this function.
            reasons.append(f"test-review file {review_path} could not be read; treated as failing")
            failed = True
        else:
            review_score = _scan_review_score(review_text)
            recommendation = _scan_review_recommendation(review_text)
            if review_score is None:
                reasons.append(
                    f"test-review score not found in {review_path.name}; treated as failing"
                )
                failed = True
            elif review_score < 80:
                reasons.append(f"test-review score {review_score} < 80")
                failed = True
            if recommendation is not None and recommendation.lower() == "block":
                reasons.append("test-review recommendation is Block")
                failed = True
    elif review_path is not None:
        reasons.append(f"test-review file {review_path} not found; treated as failing")
        failed = True
    else:
        reasons.append(
            "--test-review not supplied on a per-story production gate; treated as failing "
            "(pass --test-review, or --epic-level if this is the epic roll-up)"
        )
        failed = True

    if failed and verdict == "advance":
        reasons.append("production signal failed; advance downgraded to reloop")
        verdict = "reloop"

    return verdict, nfr_status, review_score


# The marker's scope line, written by execute.md steps 2/5 beside baseline=.
_SWEEP_SCOPE_RE = re.compile(r"^scope=(\S+)\s*$", re.MULTILINE)


def apply_sweep_scope(
    verdict: str, tests_ran_path: Path, reasons: list[str]
) -> tuple[str, str | None]:
    """Cap a story-moving verdict at reloop unless the sweep behind it was full.

    Reads the story's ``.tests-ran-<story_id>`` marker for its
    ``scope=<full|scoped>`` line. ``full`` passes the verdict through;
    ``scoped`` is legitimate mid-loop evidence whose verdict is capped at
    reloop - a scoped sweep must not impersonate a full one at the one place
    the distinction pays. Unlike the production AND's floor, the cap moves
    ``defer`` as well as ``advance``, because defer's route ADVANCES the story
    (ledger, then advance anyway), and a story moving forward off mid-loop
    evidence is exactly what the cap exists to refuse.

    FAIL-CLOSED like every other signal: a missing or unreadable marker, a
    marker with no ``scope=`` line, and a value this reader does not recognise
    all get the same cap, with a reason naming what was wrong. Only the OMITTED
    FLAG is a no-op, and that is deliberate rather than a soft spot: making
    omission failing would change the verdict of documented invocations that
    predate the flag (docs/_internal/STABILITY.md carries the 2.0.0 lesson on
    exactly that), so the always-pass-it rule is the instruction layer's to
    state, not this reader's to retrofit.

    Returns ``(verdict, sweep_scope)`` where ``sweep_scope`` is the recognised
    value read from the marker, or None when none was.
    """
    scope: str | None = None
    problem: str | None = None
    text = _read_text(tests_ran_path) if tests_ran_path.is_file() else None
    if text is None:
        problem = f"tests-ran marker {tests_ran_path} missing or unreadable"
    else:
        values = _SWEEP_SCOPE_RE.findall(text)
        if not values:
            problem = (
                f"tests-ran marker {tests_ran_path.name} carries no scope= line "
                "(execute.md step 2 writes scope=full|scoped beside baseline=)"
            )
        elif len(set(values)) > 1:
            # Disagreeing duplicates are a marker that was APPENDED to rather
            # than rewritten - and picking either line would be a guess. Taking
            # the first is the trap specifically: a re-loop cycle appending its
            # scoped line under a first pass's scope=full would read as full,
            # which is the one impersonation this reader exists to refuse.
            problem = (
                f"tests-ran marker {tests_ran_path.name} carries "
                f"{len(values)} disagreeing scope= lines ({', '.join(values)}); "
                "rewrite the marker with exactly one"
            )
        elif values[0] not in ("full", "scoped"):
            problem = (
                f"tests-ran marker {tests_ran_path.name} carries unrecognised "
                f"scope={values[0]!r}"
            )
        else:
            scope = values[0]

    if scope == "full":
        return verdict, scope
    if verdict in ("advance", "defer"):
        reasons.append(
            f"{problem}; treated as failing" if problem is not None else "sweep scope is scoped"
        )
        reasons.append(
            f"{verdict} capped at reloop: a story only advances off a full-scope "
            "sweep - re-run the full three-axis sweep, refresh the marker with "
            "scope=full, and re-run the gate"
        )
        verdict = "reloop"
    elif problem is not None:
        # A verdict already at reloop/escalate is not moved, but the marker
        # problem still gets a line - the re-loop should fix the marker too.
        reasons.append(f"{problem} (verdict already {verdict}; not moved)")
    else:
        reasons.append(f"sweep scope scoped (verdict already {verdict}; not moved)")
    return verdict, scope


# Severity order for the roll-up aggregate: the epic's status is its WORST
# story's status, and an unknown status is treated as the worst there is.
_ROLLUP_SEVERITY = ("PASS", "WAIVED", "CONCERNS", "FAIL", "NOT_EVALUATED")

def _split_record(sprint_status: Path, key: str) -> tuple[list[str] | None, str | None]:
    """The children a decomposed parent's split record names, or why it cannot be read.

    `scripts/story_sizing.py --parent <key> --record <dir>` writes
    `.split-<key>.json` beside sprint-status.yaml once the split's claim map
    reconciles. It is the only evidence of a split the roll-up reads: a row's
    id, its place and which story files exist each waive a never-gated row's
    gate under some placement or file name, so none of them is read.

    Returns `(children, None)` for a well-formed record, `(None, problem)` for
    one that is present but unusable, and `(None, None)` when there is none.
    """
    path = sprint_status.parent / f".split-{key}.json"
    if not path.is_file():
        return None, None
    record = _read_json(path)
    children = record.get("children") if record is not None else None
    if (
        record is None
        or record.get("parent") != key
        or not isinstance(children, list)
        or not children
        or not all(isinstance(child, str) and child for child in children)
    ):
        return None, f"{path.name} is not a split record of {key} (parent and children), so it is not read"
    return children, None


def _rows_extending_above(stories: list[str], key: str) -> list[str]:
    """The rows above the first row of this key's id whose id extends it.

    Only a pointer for a reason line: a row with these and no split record may
    be a parent split before the record existed. It never decides a verdict.
    """
    import formalize_check  # noqa: PLC0415  (sibling script, path set by the caller)

    stem = formalize_check._story_stem(key)
    if stem is None:
        return []
    found = []
    for other in stories:
        other_stem = formalize_check._story_stem(other)
        if other_stem == stem:
            break
        ancestor = formalize_check._parent_stem(other_stem) if other_stem else None
        while ancestor is not None and ancestor != stem:
            ancestor = formalize_check._parent_stem(ancestor)
        if ancestor == stem:
            found.append(other)
    return found


def _own_gate_artifact(trace_output: Path, key: str) -> Path | None:
    """The gate artifact the per-story resolver finds as this key's own, or None.

    The identity is the one `--story <key>` resolves by, so this asks the
    resolver's own questions: a trace report named for the key that declares
    itself one, the key's gate decision, or its per-story trace summary. A
    parent with any of them was gated on its own, so it must resolve like any
    story whatever its split record says. Files the resolver never reads as
    the key's (its story file, its ATDD checklist, notes, the split record, a
    gate filed under a bare id or another slug) are not its gate, by the
    naming rule `references/gate.md` states for every per-story gate.
    """
    for report in sorted(trace_output.glob("*.md")):
        if _stem_matches_story(report.stem, key) and _declares_trace_report(report):
            return report
    slim = _per_story_slim(trace_output, key)
    if slim is not None:
        return slim
    for variant in _story_variants(key):
        summary = trace_output / f"e2e-trace-summary-{variant}.json"
        if summary.is_file():
            return summary
    return None


def _split_cycle(key: str, candidates: dict[str, list[str]]) -> list[str] | None:
    """The chain of split records that leads from this parent back to it, if any."""
    stack = [(child, [key, child]) for child in reversed(candidates[key])]
    seen: set[str] = set()
    while stack:
        row, chain = stack.pop()
        if row == key:
            return chain
        if row in seen or row not in candidates:
            continue
        seen.add(row)
        stack.extend((child, chain + [child]) for child in reversed(candidates[row]))
    return None


def _read_splits(
    trace_output: Path,
    sprint_status: Path,
    stories: list[str],
    ungated: set[str],
    epic: str,
) -> tuple[dict[str, list[str]], dict[str, str]]:
    """Which ungated rows are read through their children, and why each other record is not.

    Returns `(read, notes)`: `read` maps a parent read through to the children
    its record names; `notes` holds the reason line of every other row whose
    record is present and not read. A record is read when it is well-formed,
    names only other story rows of this epic, its parent has no gate artifact
    of its own (`_own_gate_artifact`), and no chain of records leads back to
    it. That last test is what keeps the aggregate honest: in a graph of
    records with no cycle, every parent read through bottoms out in rows the
    roll-up reads, so a PASS is never computed over parents alone.
    """
    candidates: dict[str, list[str]] = {}
    notes: dict[str, str] = {}
    for key in stories:
        if key not in ungated:
            continue
        children, problem = _split_record(sprint_status, key)
        if problem is not None:
            notes[key] = f"story {key}: {problem}"
            continue
        if children is None:
            continue
        strays = [child for child in children if child == key or child not in stories]
        if strays:
            notes[key] = (
                f"story {key}: .split-{key}.json names {', '.join(strays)}, "
                f"not another story row of epic {epic}, so it is not read"
            )
            continue
        owned = _own_gate_artifact(trace_output, key)
        if owned is not None:
            notes[key] = (
                f"story {key}: a decomposed parent ({', '.join(children)}), but "
                f"{owned.name} in {trace_output} is a gate artifact of its own, so "
                "its own gate must resolve"
            )
            continue
        candidates[key] = children
    read: dict[str, list[str]] = {}
    for key, children in candidates.items():
        cycle = _split_cycle(key, candidates)
        if cycle is not None:
            notes[key] = (
                f"story {key}: its split record leads back to it "
                f"({' -> '.join(cycle)}), so it is not read"
            )
        else:
            read[key] = children
    return read, notes


def rollup_gate(
    trace_output: Path, sprint_status: Path, epic: str, reasons: list[str]
) -> dict:
    """Aggregate the epic verdict from per-story artifacts, fail-closed.

    The story set comes from sprint-status.yaml (the authority on which stories
    the epic owes), never from a caller-typed list - a story omitted from a
    typed list would simply not be aggregated, which is the fabrication channel
    this reader exists to close. Refusals, all NOT_EVALUATED -> escalate:
    an unreadable sprint-status, an epic with no stories, any story not `done`
    (the roll-up's own trigger is every-story-done, so running it early is
    refused rather than answered), and any done story whose own gate artifact
    does not resolve - a `done` row nothing ever gated is exactly what this
    aggregate must surface, not paper over.

    One `done` row owes no gate of its own: a decomposed parent whose split
    record is read (`_read_splits`). Its children's gates count in its place,
    and a reason line names it with them. A parent whose record is not read is
    read like any story, with a reason line saying why.
    """
    sys.path.insert(0, str(Path(__file__).resolve().parent))
    import preflight_check  # noqa: PLC0415  (sibling script, path set above)

    try:
        text = sprint_status.read_text(encoding="utf-8")
    except (OSError, UnicodeDecodeError):
        reasons.append(f"sprint-status unreadable at {sprint_status}; roll-up refused")
        return {
            "gate_status": "NOT_EVALUATED",
            "p0_status": None,
            "p1_status": None,
            "overall_status": None,
        }
    statuses = preflight_check._parse_development_status(text)
    stories = [
        key
        for key in statuses
        if preflight_check._is_story_key(key)
        and preflight_check._epic_id_of(key) == str(epic)
    ]
    refused = None
    if not stories:
        refused = f"no stories for epic {epic} in {sprint_status.name}; roll-up refused"
    else:
        not_done = [key for key in stories if statuses[key] != "done"]
        if not_done:
            refused = (
                "roll-up refused: %d of %d stories not done (%s)"
                % (len(not_done), len(stories), ", ".join(not_done[:5]))
            )
    if refused:
        reasons.append(refused)
        return {
            "gate_status": "NOT_EVALUATED",
            "p0_status": None,
            "p1_status": None,
            "overall_status": None,
        }

    # A generically-named directory (TEA's untouched single-story output) has
    # exactly one gate artifact, and the unscoped fallback would hand that one
    # file to EVERY story here - a multi-story epic advancing on a single
    # artifact, each reason line asserting a per-story status the directory
    # cannot support. One story may legitimately live in such a directory
    # (gate_eval's documented isolated-dir rule); two or more cannot.
    if len(stories) > 1 and not _is_per_story_named(trace_output):
        reasons.append(
            "roll-up refused: %s is not per-story-named, so one shared artifact "
            "would decide all %d stories" % (trace_output, len(stories))
        )
        return {
            "gate_status": "NOT_EVALUATED",
            "p0_status": None,
            "p1_status": None,
            "overall_status": None,
        }

    gates = []
    for key in stories:
        sub: list[str] = []
        gate = load_gate(trace_output, sub, key)
        gates.append((key, sub, (gate["gate_status"] or "NOT_EVALUATED").upper()))
    read, notes = _read_splits(
        trace_output,
        sprint_status,
        stories,
        {key for key, _, status in gates if status == "NOT_EVALUATED"},
        str(epic),
    )

    read_through = 0
    worst = "PASS"
    for key, sub, status in gates:
        if key in read:
            reasons.append(
                f"story {key}: a decomposed parent, split into "
                f"{', '.join(read[key])} (.split-{key}.json); it owes no gate "
                "of its own, and theirs count in its place"
            )
            read_through += 1
            continue
        if key in notes:
            reasons.append(notes[key])
        elif status == "NOT_EVALUATED" and _own_gate_artifact(trace_output, key) is None:
            # The pointer names the record as the way out, which it is only for
            # a row with no gate artifact of its own: one that has one must
            # resolve it, record or not.
            above = _rows_extending_above(stories, key)
            if above:
                reasons.append(
                    f"story {key}: rows above it extend its id ({', '.join(above)}) "
                    "and no split record is beside sprint-status.yaml; if it was "
                    "decomposed, record the split with story_sizing.py --parent "
                    f"{key} --record and re-run the roll-up"
                )
        if status not in _ROLLUP_SEVERITY:
            reasons.append(
                f"story {key}: unrecognized gate_status {status!r}; treated as NOT_EVALUATED"
            )
            status = "NOT_EVALUATED"
        elif status == "NOT_EVALUATED":
            reasons.append(
                f"story {key}: gate_status NOT_EVALUATED - a done row with no "
                "resolvable gate artifact of its own"
            )
        else:
            reasons.append(f"story {key}: gate_status {status}")
        # The resolver's own record (which file decided, any refused hint) must
        # not be dropped by the aggregation - the trail has to agree with the
        # gate about which file decided. Surface it for every non-PASS story,
        # and always for a refused or honoured hint.
        for line in sub:
            if status != "PASS" or "hint" in line.lower():
                reasons.append(f"story {key}: {line}")
        if _ROLLUP_SEVERITY.index(status) > _ROLLUP_SEVERITY.index(worst):
            worst = status
    over = "%d stories" % len(stories)
    if read_through:
        over += " (%d decomposed parent%s read through %s children)" % (
            read_through,
            "" if read_through == 1 else "s",
            "its" if read_through == 1 else "their",
        )
    reasons.append("roll-up over %s: worst gate_status %s" % (over, worst))
    return {
        "gate_status": worst,
        "p0_status": None,
        "p1_status": None,
        "overall_status": None,
    }


def evaluate(args: argparse.Namespace) -> dict:
    reasons: list[str] = []
    trace_output = Path(args.trace_output)

    if getattr(args, "rollup", False):
        gate = rollup_gate(
            trace_output, Path(args.sprint_status), args.story, reasons
        )
    else:
        gate = load_gate(trace_output, reasons, getattr(args, "story", None))
    gate_status = (gate["gate_status"] or "NOT_EVALUATED").upper()
    verdict = GATE_VERDICT.get(gate_status, "escalate")
    if gate_status not in GATE_VERDICT:
        reasons.append(f"unrecognized gate_status {gate_status!r}; escalating")
    else:
        reasons.append(f"gate_status {gate_status} -> {verdict}")

    nfr_status: str | None = None
    review_score: int | None = None
    if args.profile == "production":
        if getattr(args, "epic_level", False):
            # The epic roll-up is a pure trace read. TEA produces NFR and
            # test-review PER STORY, so there is no aggregate to AND, and every
            # story already ANDed its own signals before reaching `done`.
            # Declared, never inferred from an absent flag - that is the whole
            # point of the flag.
            reasons.append(
                "epic-level roll-up: production ANDs not applied "
                "(TEA writes nfr and test-review per story, not per epic)"
            )
        else:
            nfr_path = Path(args.nfr) if args.nfr else None
            review_path = Path(args.test_review) if args.test_review else None
            verdict, nfr_status, review_score = apply_production_and(
                verdict, nfr_path, review_path, reasons
            )

    # `is not None`, never truthiness: an explicitly-passed empty value is a
    # caller error to fail closed on (Path("") is never a file, so it caps),
    # not a silent way back to the pre-flag behaviour. Only true omission skips.
    tests_ran = getattr(args, "tests_ran", None)
    sweep_scope: str | None = None
    if tests_ran is not None:
        verdict, sweep_scope = apply_sweep_scope(verdict, Path(tests_ran), reasons)

    # The delta cycle profile: a mid-loop gate that re-ran only the previously
    # failed assessor dimension(s) declares itself and is capped exactly as a
    # scoped sweep is - it may say "not yet, and here is why", never advance.
    # defer moves too, for the same reason as the sweep cap: defer's route
    # advances the story. The choices list means an unrecognised value is an
    # argparse error (exit 2), never a silently-full gate.
    cycle_profile = getattr(args, "cycle_profile", None)
    if cycle_profile == "delta" and verdict in ("advance", "defer"):
        reasons.append(
            f"{verdict} capped at reloop: a delta-profile gate re-ran only the "
            "previously failed dimension(s), so it may not move the story - "
            "run the full gate (every assessor, over a scope=full sweep) to advance"
        )
        verdict = "reloop"

    result = {
        "verdict": verdict,
        "gate_status": gate_status,
        "p0_status": gate["p0_status"],
        "p1_status": gate["p1_status"],
        "overall_status": gate["overall_status"],
        "nfr_status": nfr_status,
        "review_score": review_score,
        # Machine-readable, because the `reasons` wording explicitly is not
        # (docs/_internal/STABILITY.md). Without this key a consumer cannot tell
        # an advance that ANDed both production signals from one that skipped
        # them, and `nfr_status: null` alone does not say which.
        "epic_level": bool(getattr(args, "epic_level", False)),
    }
    if tests_ran is not None:
        # Present exactly when --tests-ran was supplied, absent otherwise - so
        # the printed shape of every pre-flag invocation is unchanged (the
        # stability policy classes a new key in a documented invocation's JSON
        # as a shape change; a caller only sees this one by opting in). The
        # value is the recognised scope= reading, or null when none was.
        result["sweep_scope"] = sweep_scope
    if cycle_profile is not None:
        # Same conditional-presence contract as sweep_scope, same reason.
        result["cycle_profile"] = cycle_profile
    # reasons goes last, after any conditional keys, so the printed object
    # reads verdict-first, evidence-last exactly as the documented examples
    # show. Key ORDER is cosmetic; the contract is the key SET.
    result["reasons"] = reasons
    return result


def main(argv: list[str] | None = None) -> int:
    parser = argparse.ArgumentParser(description="Evaluate the TEA quality gate into a verdict.")
    parser.add_argument("--trace-output", required=True, help="Directory holding the trace gate artifacts.")
    parser.add_argument("--profile", required=True, choices=["light", "production"])
    parser.add_argument(
        "--story",
        help="Current story id; scopes gate-file resolution to that story's "
        "artifacts in a shared multi-story trace dir. Omit for a single-story dir.",
    )
    parser.add_argument(
        "--nfr",
        help="PATH to the story's nfr-assessment markdown (production only) — a file "
        "path, never a status word. The file must carry a literal "
        "'**Overall Status:** <PASS|CONCERNS|FAIL|NOT_ASSESSED>' line; a value "
        "passed here instead of a path is read as a missing file and treated as "
        "failing.",
    )
    parser.add_argument(
        "--test-review",
        help="PATH to the story's test-review markdown (production only) — a file "
        "path, never a score. The file must carry '**Quality Score**: N/100' "
        "(the /100 denominator is required) and a '**Recommendation**:' line; a "
        "value passed here instead of a path is read as a missing file and "
        "treated as failing.",
    )
    parser.add_argument(
        "--tests-ran",
        help="PATH to the story's .tests-ran-<story_id> marker (per-story gates "
        "only). The marker must carry a scope=<full|scoped> line naming which "
        "sweep form its green run was (execute.md steps 2/5 write it beside "
        "baseline=). scope=full passes the verdict through; scope=scoped - and, "
        "fail-closed, a missing marker, a missing scope= line, or an "
        "unrecognised value - caps advance/defer at reloop. Omitting the flag "
        "skips the check (invocations that predate the flag keep their "
        "verdicts); the skill instructions require it on every per-story gate. "
        "Cannot be combined with --epic-level.",
    )
    parser.add_argument(
        "--cycle-profile",
        choices=["full", "delta"],
        help="Which gate cycle this is (per-story gates only). 'delta' declares "
        "a mid-loop gate that re-ran in full only the previously failed "
        "assessor dimension(s), the others re-checking their prior artifact "
        "against the diff: its verdict is capped at reloop - advance/defer "
        "require the full gate. Omitting the flag is the full behaviour; the "
        "JSON carries cycle_profile exactly when the flag was supplied. Cannot "
        "be combined with --epic-level.",
    )
    parser.add_argument(
        "--epic-level",
        action="store_true",
        help="This is the epic roll-up, not a story gate: skip the production "
        "NFR/test-review ANDs, which TEA writes per story and never per epic. "
        "Without it, --profile production requires both --nfr and --test-review.",
    )
    parser.add_argument(
        "--rollup",
        action="store_true",
        help="Compute the epic roll-up from the per-story gate artifacts and "
        "the sprint-status story set, instead of reading a single epic-named "
        "artifact. Requires --epic-level, --story <epic id> and "
        "--sprint-status. Fail-closed: any not-done story, and any done story "
        "with no resolvable gate artifact of its own, refuses to NOT_EVALUATED, "
        "except a decomposed parent whose split record (.split-<key>.json beside "
        "--sprint-status, written by story_sizing.py --record) names children that "
        "are each another story row of the epic, with no chain of records back to "
        "it, and which has no trace report, gate decision or trace summary of its "
        "own: its children's gates stand in for it.",
    )
    parser.add_argument(
        "--sprint-status",
        help="PATH to sprint-status.yaml (rollup only): the authority on which "
        "stories the epic owes, read so the story set can never be a "
        "caller-typed list with a story quietly left off.",
    )
    args = parser.parse_args(argv)

    if args.rollup and not (args.epic_level and args.story and args.sprint_status):
        parser.error(
            "--rollup is the epic roll-up computed from per-story artifacts: it "
            "requires --epic-level, --story <epic id> and --sprint-status"
        )
    if args.sprint_status and not args.rollup:
        parser.error("--sprint-status is only meaningful with --rollup")

    # Mutually exclusive by meaning: --epic-level asserts there is no aggregate to
    # AND, so supplying one anyway is a contradiction, and the flag would win
    # silently - discarding a FAILING artifact the caller explicitly named.
    # `references/gate.md` already calls the hybrid the mirror mistake; this is
    # the invocation-error lane a missing --story already occupies.
    if args.epic_level and (args.nfr or args.test_review):
        parser.error(
            "--epic-level asserts there is no epic-level aggregate to AND, so it "
            "cannot be combined with --nfr/--test-review; drop the flag for a "
            "per-story gate, or drop the paths for the epic roll-up"
        )

    # Same lane as the hybrid above: the epic roll-up gates no sweep of its own
    # (every story proved its own scope before reaching `done`), so an
    # epic-level --tests-ran is a contradiction to refuse, never to evaluate.
    # `is not None`, not truthiness: --epic-level --tests-ran "" is the same
    # contradiction spelled with an empty value, not a way around the refusal.
    if args.epic_level and args.tests_ran is not None:
        parser.error(
            "--epic-level is the epic roll-up: it gates no sweep of its own, so "
            "it cannot be combined with --tests-ran; drop the flag for a "
            "per-story gate, or drop the path for the epic roll-up"
        )

    # The roll-up is by definition the final full instrument over the per-story
    # record - a delta roll-up is a contradiction, and even an explicit 'full'
    # is per-story vocabulary the roll-up does not speak. Same refusal lane.
    if args.epic_level and args.cycle_profile is not None:
        parser.error(
            "--epic-level is the epic roll-up, always the full instrument: it "
            "cannot be combined with --cycle-profile; drop the flag for a "
            "per-story gate"
        )

    result = evaluate(args)
    print(json.dumps(result, indent=2))
    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