armelhbobdad/bmad-module-ultracode-goal / skills/ultracode-goal
ultracode-goal
FlaggedRuns 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'.
scripts/preflight_check.py
View on GitHub#!/usr/bin/env -S uv run --script
# /// script
# requires-python = ">=3.11"
# dependencies = []
# ///
"""Mechanical preflight for an UltraCode-Goal epic run.
Plumbing ONLY. This script parses tool versions, inspects git state, checks
file/directory existence, and reads TEA config flags. It reports mechanical
facts plus a `budget` count of mechanical blockers. It does NOT decide whether
to intervene, remediate, or block on semantic grounds — that judgment lives in
references/preflight.md (the LLM). The "auto-remediation then hard-gate"
posture is the LLM's to run; this script only tells it what is
mechanically true right now.
What counts as a mechanical blocker (each adds 1 to `budget`):
- the Claude Code primitives needed for an unattended run are below the
minimum versions the run depends on (`/goal`, dynamic workflows, auto memory,
and the hook setting `"onFailure": "block"` that makes a guard which cannot
run refuse the tool call),
- no test framework is detected (no playwright/cypress/jest/vitest config,
no pytest config/conftest.py, and no real package.json `test` script),
- a story skill the run delegates story creation or implementation to
(`ucg-create-story`, `ucg-dev-story`, which UCG ships) is not installed
where Claude Code loads skills,
- a TEA skill the run's profile (`--profile`, production by default)
delegates to is not installed there: UCG calls TEA 1.27.x, the release
BMAD Method 6.12.2 and later install, by its `bmad-testarch-*` names,
- HEAD has no commit yet (a fresh `git init`, or an orphan branch): the
operator commits a baseline on the base branch first, because the run never
makes the commit its Epic branch would start from,
- the working tree is dirty (a per-green-story commit needs a clean base),
- the current branch is a protected branch (the epic must run on its own
branch; an unborn HEAD's branch is read from its symbolic ref).
Reported, never a blocker: `impl_artifacts_tracked`, whether git would track a
file the run newly writes under the impl-artifacts dir (`false` on a project
that gitignores its BMAD output, or keeps that dir outside the repository or
behind a symlink; `null` only when there is no repository). The run's
undo and its acceptance criteria depend on it; its readiness does not.
`green` is true iff `budget == 0`. A green preflight means there is nothing
MECHANICAL left to clear; the LLM still owns the true-RED hard gate
(undecided architecture/product, unresolvable secrets), which this script
cannot and does not evaluate.
Severity is advisory metadata for the LLM, not a gate. `remediable` flags
blockers the remediation pass can plausibly auto-clear (e.g. scaffold the
framework, branch off, commit/stash) vs. ones that need a human (the Claude
Code version, a broken git repo, an unborn HEAD, a missing UCG story skill,
a missing TEA skill; true-RED items never reach this script).
Version gates (from the grounded constraints in .decision-log.md):
/goal >= 2.1.139, dynamic workflows >= 2.1.154, auto memory >= 2.1.59,
hook onFailure >= 2.1.295 (older versions ignore the key, so a guard that
crashes, cannot start or times out lets the call through there).
Output: JSON to stdout. Exit 0 whenever a payload is produced (a non-green
preflight is a valid result, not an error). Exit 2 is reserved for invocation
errors where no useful payload can be produced.
Rollup mode (`--rollup`): a separate, cheaper read used by Stage 1
(references/ingest-and-scope.md, "Resolve the Epic and its artifacts" step 1).
It parses ONLY sprint-status.yaml and emits a compact per-Epic story-status
summary so the LLM selects the target Epic from a small structured summary
instead of parsing raw YAML. None of the mechanical preflight checks run in
this mode; `--epic`, `--tea-config`, and `--protected-branch` are not required.
Absence of sprint-status.yaml is a reportable fact (sprint_status_present:
false, epics: []), not an error — rollup still exits 0.
uv run preflight_check.py --rollup --project-root <path> --impl-artifacts <path>
Resume-manifest mode (`--assert-armed`): the one deterministic read a resumed
run makes in place of the tool-action-per-fact environment sweep the resume
rule otherwise costs (references/execute.md, resume). It asserts the epic
branch, both hooks with the all-tools PreToolUse matcher, `"onFailure":
"block"` on every guard item (an arming made by UCG 3.x or earlier has none,
and its resume re-merges the hooks, unless a reason that is the operator's to
fix stands beside that one (the story skills, or the Claude Code version):
the resume escalates it first, and those reasons come first in `reasons`;
references/execute.md), each UCG hook command splitting, the way the shell
splits it, into `<env> uv run <script>` (an unquoted path with a space, or an
assignment quoted with its name, does not, and that hook never starts; a
shell operator, redirection or expansion fails it too), the five injected hook env vars
(accepted from the hook command strings OR the inherited process env, both
of which preflight step 5 permits), the UCG
story skills (a manual deletion between spawns, or an interrupted UCG install
or update, can remove them), and the Claude Code version against the
minimums step 1 enforces (`checks.cc_version`: below 2.1.295 Claude Code
ignores the guard's "onFailure", and a version `claude --version` cannot
give is reported with `read: false` and fails nothing), reports the recall latch WITHOUT
certifying it (re-latching stays a model-owned Stage 1 step on every resume;
a present latch also reports its `latch_version` and a derived `store_ok`
colour, red for anything but a green latch v2),
reports `impl_artifacts_tracked` as step 1 does (a resumed session has no
step-1 report to read it from), and, given --story, derives the story's resume route from artifacts alone:
decision-pending (an open escalation-<story>.json, which outranks the rest),
story-boundary (no baseline), gate-owed (committed, green, un-gated, which
requires --trace-output evidence and never fires without it; or a re-gate owed,
a .regate-<story> marker naming HEAD), or mid-story.
Exit 0 iff branch+hooks+env+skills are armed and the Claude Code version is
not below a minimum; the latch, the tracked fact and
the story block never move the exit code, because they inform model-owned actions rather than certify
them. `armed` certifies what `.claude/settings.local.json` holds, not that
the running Claude Code session loaded those hooks, which no script can see:
preflight step 5's last bullet proves that with a `git commit --dry-run` the
guard must refuse (references/preflight.md).
uv run preflight_check.py --assert-armed --project-root <path> \
--impl-artifacts <path> [--story <id>] [--run-id <rid>] \
[--trace-output <dir>] [--protected-branch <name>]...
"""
from __future__ import annotations
import argparse
import json
import os
import re
import subprocess
import sys
from pathlib import Path
# Minimum Claude Code versions the unattended run depends on.
MIN_GOAL = (2, 1, 139)
MIN_WORKFLOWS = (2, 1, 154)
MIN_AUTOMEMORY = (2, 1, 59)
# `"onFailure": "block"` on a command hook: a guard that cannot start, exits
# with a code other than 0 or 2, or times out refuses the call (2.1.295 added
# it; older versions drop the key silently and let such a call through).
MIN_HOOK_ONFAILURE = (2, 1, 295)
# Each minimum by the name the cc_version blocker and the resume manifest give
# it, in the order they list them.
_CC_MINIMUMS = (
("/goal", MIN_GOAL),
("workflows", MIN_WORKFLOWS),
("auto-memory", MIN_AUTOMEMORY),
("hook-onFailure", MIN_HOOK_ONFAILURE),
)
# Root-level config filenames that signal a scaffolded JS/browser test framework
# (playwright / cypress / jest / vitest). Pytest and npm-driven harnesses are
# detected separately in _detect_framework — a config file is only one of the
# shapes a real test framework takes.
FRAMEWORK_MARKERS = (
"playwright.config.ts",
"playwright.config.js",
"playwright.config.mjs",
"cypress.config.ts",
"cypress.config.js",
"cypress.config.mjs",
"cypress.json",
"jest.config.ts",
"jest.config.js",
"vitest.config.ts",
"vitest.config.js",
)
# TEA test-artifact subdirectories the gates write into (relative to test_artifacts root).
TEA_ARTIFACT_DIRS = ("test-design", "test-reviews", "traceability")
# TEA config flags worth surfacing to the LLM verbatim (mechanical read, no interpretation).
TEA_FLAG_KEYS = (
"test_execution_mode",
"tea_execution_mode",
"test_framework",
"test_stack_type",
"ci_platform",
"risk_threshold",
"tea_browser_automation",
"tea_capability_probe",
"test_artifacts",
)
# Default protected branches when the caller doesn't override (mirrors customize.toml).
DEFAULT_PROTECTED = ("main", "master")
# The story-status vocabulary BMad's sprint-planning writes into
# sprint-status.yaml (see its sprint-status-template.yaml STATUS DEFINITIONS).
# Order here is the order counts are reported in the rollup; "done" first so the
# in-scope decision (not-yet-done) reads off the leading count.
STORY_STATUSES = ("done", "in-progress", "ready-for-dev", "review", "backlog")
# The story skills the run delegates story creation (Stage 2 remediation, Stage 3)
# and implementation (Stage 4) to. UCG ships both, adapted from BMAD Method's
# bmad-create-story and bmad-dev-story, which 6.12 made deprecated shims (a fresh
# install leaves them out unless asked for) and v7 removes. UCG's installer copies
# them beside the ultracode-goal skill, so a missing one means a partial or older
# UCG install. The BMAD toolbox the run uses installs without shims, so no BMAD
# skill is probed.
# (bmad-generate-project-context is a shim too: from 6.12 it forwards to
# bmad-project-context, which writes a block into AGENTS.md rather than a
# project-context.md. The project-context count is advisory and never blocks.)
STORY_SKILLS = ("ucg-create-story", "ucg-dev-story")
# The TEA skills each run profile can delegate to, by the names TEA 1.27.x
# installs. Production can call all eight: framework (preflight step 2, when no
# test framework is found), ci (preflight step 2, production only), test-design
# (Stage 3, once per Epic), atdd (Stage 3, per story), test-review (Execute, per
# story) and automate, nfr and trace (the Stage 5 gate). --light skips ci,
# atdd, automate, test-review and nfr, and keeps framework, test-design and
# trace. TEA 2.0 moved to BMAD 7's module format and TEA 3.0 renamed every
# bmad-testarch-* skill to bmad-tea-*, so UCG supports TEA 1.27.x only, the
# release BMAD Method 6.12.2 and later install. The check reads skill names,
# not a TEA version: TEA 2.x keeps the bmad-testarch-* names and passes it.
# TEA's own agent and teaching skills (bmad-tea, bmad-teach-me-testing) are
# never delegated to, so they are not probed.
TEA_SKILLS = {
"production": (
"bmad-testarch-framework",
"bmad-testarch-ci",
"bmad-testarch-test-design",
"bmad-testarch-atdd",
"bmad-testarch-automate",
"bmad-testarch-test-review",
"bmad-testarch-nfr",
"bmad-testarch-trace",
),
"light": (
"bmad-testarch-framework",
"bmad-testarch-test-design",
"bmad-testarch-trace",
),
}
PROFILES = tuple(TEA_SKILLS)
# The prefix TEA 3.0 and later publish those skills under. The trailing hyphen
# keeps TEA 1.27.x's own bmad-tea and bmad-teach-me-testing out of the match.
TEA_RENAMED_PREFIX = "bmad-tea-"
def _run(cmd: list[str], cwd: Path | None = None) -> tuple[int, str, str]:
"""Run a command, returning (returncode, stdout, stderr). 127 if it cannot
be started (not found, no execute bit, no program) or times out."""
try:
proc = subprocess.run(
cmd,
cwd=str(cwd) if cwd else None,
capture_output=True,
text=True,
timeout=30,
)
return proc.returncode, proc.stdout.strip(), proc.stderr.strip()
except (OSError, subprocess.TimeoutExpired) as exc:
return 127, "", str(exc)
def _parse_semver(text: str) -> tuple[int, int, int] | None:
"""Extract the first dotted three-part version from text."""
match = re.search(r"(\d+)\.(\d+)\.(\d+)", text or "")
if not match:
return None
return tuple(int(g) for g in match.groups()) # type: ignore[return-value]
def _cc_version() -> tuple[str | None, tuple[int, int, int] | None]:
"""Best-effort read of the installed Claude Code version."""
code, out, _ = _run(["claude", "--version"])
if code != 0:
return None, None
return out, _parse_semver(out)
def _meets(version: tuple[int, int, int] | None, minimum: tuple[int, int, int]) -> bool:
return version is not None and version >= minimum
def _below_minimums(version: tuple[int, int, int] | None) -> list[str]:
"""Each minimum the version does not meet, as `<name>>=<minimum>`."""
return ["%s>=%d.%d.%d" % (name, *minimum) for name, minimum in _CC_MINIMUMS if not _meets(version, minimum)]
def _cc_version_detail(cc_raw: str | None, below: list[str]) -> str:
"""The cc_version blocker's words, which the resume manifest's reason opens with."""
return "Claude Code %s is below the minimum for: %s" % (cc_raw or "(version unreadable)", ", ".join(below))
def _git(args: list[str], project_root: Path) -> tuple[int, str]:
code, out, _ = _run(["git", *args], cwd=project_root)
return code, out
def _git_branch(project_root: Path) -> str | None:
code, out = _git(["rev-parse", "--abbrev-ref", "HEAD"], project_root)
if code != 0 or not out:
return None
return out
def _git_unborn(project_root: Path) -> bool:
"""True when HEAD names a branch with no commit yet (a fresh `git init`).
`rev-parse --verify -q HEAD` exits 1 on an unborn HEAD and 128 outside a
repository, so only the 1 reads as unborn: a missing or broken repository
is the `git_repo` blocker's to report, not this one's.
"""
code, _ = _git(["rev-parse", "--verify", "-q", "HEAD"], project_root)
return code == 1
def _git_unborn_branch(project_root: Path) -> str | None:
"""The branch an unborn HEAD names, read from the symbolic ref.
`_git_branch` needs HEAD to resolve to a commit, so on an unborn HEAD it
returns None, and that None used to hide the protected-branch blocker on a
repository with nothing committed. `_git_branch` itself keeps returning None
there so `--assert-armed` still fails closed on an unborn Epic branch.
"""
code, out = _git(["symbolic-ref", "--short", "-q", "HEAD"], project_root)
if code != 0 or not out:
return None
return out
def _git_clean(project_root: Path) -> bool | None:
code, out = _git(["status", "--porcelain"], project_root)
if code != 0:
return None
return out == ""
def _impl_artifacts_tracked(project_root: Path, impl_artifacts: Path) -> bool | None:
"""Whether git would track a file the run newly writes under impl_artifacts.
`git check-ignore` on a probe name that does not exist: exit 0 means an
ignore rule covers it (False), exit 1 means none does (True). git refuses a
path outside the work tree or beyond a symlink, and such a tree is not in
git at all, the same hazard as an ignored one (False). Only with no
repository to ask is the answer unknown (None). The probe is a plain
story-like name, since story files are what the run writes there most.
The probe goes to git in `/` form: exit 128 reads as untracked too, so a
Windows path git could not read would pass for an ignored tree unseen.
"""
probe = impl_artifacts / "ucg-tracked-probe.md"
code, _ = _git(["check-ignore", "-q", "--", probe.as_posix()], project_root)
if code == 0:
return False
if code == 1:
return True
inside, out = _git(["rev-parse", "--is-inside-work-tree"], project_root)
return False if inside == 0 and out == "true" else None
def _read_toml_or_yaml_flags(tea_config: Path, keys: tuple[str, ...] = TEA_FLAG_KEYS) -> dict:
"""Read flat key: value scalars from the TEA config.
The TEA config is YAML in practice. To stay stdlib-only we parse the flat
`key: value` scalar lines we care about ourselves (no nesting is needed for
these flags). If `tomllib` ever applies (a .toml config) we try that first.
`keys` names the scalars read: TEA's flags by default, and `test_artifacts`
and `trace_output` when formalize_check.py reads TEA's test-artifacts root
and the folders its leak check exempts.
"""
if not tea_config.is_file():
return {}
text = tea_config.read_text(encoding="utf-8", errors="replace")
if tea_config.suffix.lower() == ".toml":
try:
import tomllib
data = tomllib.loads(text)
return {k: data[k] for k in keys if k in data}
except Exception:
pass
flags: dict = {}
for raw in text.splitlines():
line = raw.strip()
if not line or line.startswith("#") or ":" not in line:
continue
key, _, value = line.partition(":")
key = key.strip()
if key not in keys:
continue
value = _strip_inline_comment(value).strip().strip('"').strip("'")
if value.lower() in ("true", "false"):
flags[key] = value.lower() == "true"
else:
flags[key] = value
return flags
def _strip_inline_comment(value: str) -> str:
"""Drop a YAML inline comment from a scalar, respecting a quoted value.
The sibling `_parse_development_status` already does this, because a
hand-written config routinely annotates its keys. This reader did not, so
`test_artifacts: <path> # where TEA writes` resolved to a directory whose
name literally carried " # where TEA writes". `ULTRACODE_TEST_ARTIFACTS`
then pointed nowhere, the guard's un-skip proof found no
`atdd-checklist-<story>.md` to read, and it enforced nothing — while
preflight still reported green. An inert control, not a cosmetic parse bug.
Every other annotated key, `tea_execution_mode` among them, carried its
comment into the value reported in `tea_flags` the same way.
Whitespace-preceded rather than a bare `split("#")`, which is what YAML
actually specifies, so a `#` inside a value survives. A `#` that opens the
stripped value is a comment too: the strip took the whitespace before it,
so `test_artifacts: # set by TEA` once read `# set by TEA` as its value
rather than none, and the root became a folder named after the comment.
"""
value = value.strip()
if value[:1] in ('"', "'"):
quote = value[0]
end = value.find(quote, 1)
if end != -1:
return value[: end + 1]
return value
return re.sub(r"(?:^|\s+)#.*$", "", value)
def _tea_artifacts_root(project_root: Path, tea_flags: dict) -> Path:
"""Resolve the test_artifacts root, honoring a tea-config override if present."""
configured = tea_flags.get("test_artifacts")
if isinstance(configured, str) and configured:
resolved = configured.replace("{project-root}", str(project_root))
path = Path(resolved)
return path if path.is_absolute() else (project_root / path)
return project_root / "_bmad-output" / "test-artifacts"
# The npm-init placeholder `test` script ("...no test specified..."); not a real harness.
_NPM_TEST_PLACEHOLDER = "no test specified"
def _safe_read_text(path: Path) -> str:
"""Read a file as UTF-8, returning "" on any OS error (missing, unreadable)."""
try:
return path.read_text(encoding="utf-8")
except OSError:
return ""
def _pytest_present(project_root: Path) -> bool:
"""True when the project root carries a pytest config, conftest, or [pytest] table."""
if (project_root / "pytest.ini").is_file():
return True
if (project_root / "conftest.py").is_file():
return True
tox = project_root / "tox.ini"
if tox.is_file() and "[pytest]" in _safe_read_text(tox):
return True
setup_cfg = project_root / "setup.cfg"
if setup_cfg.is_file() and "[tool:pytest]" in _safe_read_text(setup_cfg):
return True
pyproject = project_root / "pyproject.toml"
if pyproject.is_file() and "[tool.pytest" in _safe_read_text(pyproject):
return True
return False
def _npm_test_script(project_root: Path) -> bool:
"""True when package.json has a real `test` script (not the npm-init placeholder)."""
pkg = project_root / "package.json"
if not pkg.is_file():
return False
try:
data = json.loads(pkg.read_text(encoding="utf-8"))
except (ValueError, OSError):
return False
if not isinstance(data, dict):
return False
scripts = data.get("scripts")
script = scripts.get("test") if isinstance(scripts, dict) else None
if not isinstance(script, str) or not script.strip():
return False
return _NPM_TEST_PLACEHOLDER not in script
def _detect_framework(project_root: Path) -> str | None:
"""Identify the project's test harness, returning its kind or None.
Returns "js-config" (a scaffolded playwright/cypress/jest/vitest config),
"pytest" (a pytest config or root conftest), or "npm-test" (a package.json
with a real `test` script) — whichever is found first, in that order — and
None when no harness is recognized.
Detection is deliberately broad. The gate asks "does this project have a
test framework the unattended run can target?", and a pytest or npm-driven
harness answers yes just as a browser-E2E config does. A pure-Python or
CLI/markdown module has no playwright.config, so flagging it
"framework absent" was a false-positive no remediation could honestly
clear — the blocker could only be satisfied by scaffolding an
inappropriate browser harness. (Note: this answers *presence*, not
*fitness* — TEA's ATDD/automate flow still assumes a browser/E2E stack;
that fitness gap is tracked separately.)
"""
for marker in FRAMEWORK_MARKERS:
if (project_root / marker).is_file():
return "js-config"
if _pytest_present(project_root):
return "pytest"
if _npm_test_script(project_root):
return "npm-test"
return None
def _test_artifacts_dirs(artifacts_root: Path) -> dict:
"""Map each TEA artifact subdir to whether it exists."""
return {name: (artifacts_root / name).is_dir() for name in TEA_ARTIFACT_DIRS}
def _locate_sprint_status(project_root: Path, impl_artifacts: Path) -> Path | None:
"""Return the path to sprint-status.yaml, or None if it is not found.
BMad writes it under the output tree; search the common locations rather
than hardcoding one path that may drift between installs.
"""
candidates = [
impl_artifacts / "sprint-status.yaml",
project_root / "_bmad-output" / "sprint-status.yaml",
]
for path in candidates:
if path.is_file():
return path
# Fall back to a bounded glob under the output tree.
output = project_root / "_bmad-output"
if output.is_dir():
for hit in output.rglob("sprint-status.yaml"):
if hit.is_file():
return hit
return None
def _sprint_status_present(project_root: Path, impl_artifacts: Path) -> bool:
"""sprint-status.yaml controls test-design's System/Epic prompt (must exist to auto-run)."""
return _locate_sprint_status(project_root, impl_artifacts) is not None
def _parse_development_status(text: str) -> dict[str, str]:
"""Hand-parse the flat `key: status` scalars under `development_status:`.
Mirrors how this script already reads YAML (flat scalar lines, stdlib-only).
sprint-status.yaml is a single `development_status:` map of one-key-per-line
`name: status` entries (story keys like `1-1-foo`, epic rows like `epic-1`,
retrospective and BUG rows). Trailing `# ...` comments and surrounding
quotes are stripped. Returns the map in file order.
"""
entries: dict[str, str] = {}
in_block = False
block_indent = 0
for raw in text.splitlines():
# The map is one top-level key; detect entering/leaving its body by
# indentation rather than tracking nesting (the file is flat).
stripped = raw.strip()
if not stripped or stripped.startswith("#"):
continue
indent = len(raw) - len(raw.lstrip(" \t"))
if not in_block:
if stripped.rstrip().rstrip(":") == "development_status" and stripped.endswith(":"):
in_block = True
block_indent = indent
continue
# Inside the block: any line indented at or below the key's own
# indentation ends it. Ending only at column 0 let a sibling map that
# followed a nested development_status: get swallowed into the story
# set, and a duplicate key there overwrote a real row last-wins.
if indent <= block_indent:
break
if ":" not in stripped:
continue
key, _, value = stripped.partition(":")
key = key.strip().strip('"').strip("'")
# Drop trailing inline comment, then quotes/whitespace.
value = value.split("#", 1)[0].strip().strip('"').strip("'")
if key and value:
entries[key] = value
return entries
def _epic_id_of(story_key: str) -> str | None:
"""Epic id = the number prefix before the first separator (`-` or `.`).
`1-1-user-authentication` -> "1", `2.3` -> "2". Non-story rows that carry no
leading number (none in practice) map to None and are skipped by the caller.
"""
match = re.match(r"^(\d+)", story_key)
return match.group(1) if match else None
def _is_story_key(key: str) -> bool:
"""True for per-story rows; False for epic/retrospective/bug bookkeeping rows.
Story keys begin with the epic number prefix (`1-1-...`, `2.3`). The
`epic-N`, `epic-N-retrospective`, and `BUG-...` rows are not stories and must
not be counted toward an Epic's story totals.
"""
return _epic_id_of(key) is not None
def build_rollup(project_root: Path, impl_artifacts: Path) -> dict:
"""Compact per-Epic story-status summary parsed from sprint-status.yaml.
Stage 1 selects the target Epic from this summary and computes in-scope as
the stories whose status is not `done`. Absence of the file is reported, not
raised.
"""
sprint_status = _locate_sprint_status(project_root, impl_artifacts)
if sprint_status is None:
return {"sprint_status_present": False, "epics": []}
text = sprint_status.read_text(encoding="utf-8", errors="replace")
entries = _parse_development_status(text)
# Group story rows by epic prefix, preserving first-seen epic order.
epics: dict[str, list[dict]] = {}
for key, status in entries.items():
if not _is_story_key(key):
continue
epic_id = _epic_id_of(key)
assert epic_id is not None # _is_story_key guarantees this
epics.setdefault(epic_id, []).append({"id": key, "status": status})
rollup_epics: list[dict] = []
for epic_id, stories in epics.items():
counts = {name: 0 for name in STORY_STATUSES}
for story in stories:
if story["status"] in counts:
counts[story["status"]] += 1
rollup_epics.append(
{
"epic": epic_id,
"story_count": len(stories),
"counts": counts,
"stories": stories,
"all_done": all(s["status"] == "done" for s in stories),
}
)
return {"sprint_status_present": True, "epics": rollup_epics}
def _project_context_count(project_root: Path) -> int:
"""Count project-context.md files (the persistent-facts source)."""
return sum(1 for _ in project_root.rglob("project-context.md"))
def _skill_roots(project_root: Path) -> tuple[Path, ...]:
"""Where Claude Code loads a skill that a bare-name invocation reaches: the
project's .claude/skills (where the UCG and BMAD installers copy skills)
and the personal skills dir, under $CLAUDE_CONFIG_DIR when that relocates
Claude Code's home-directory files, else ~/.claude."""
roots = [project_root / ".claude" / "skills"]
config_dir = os.environ.get("CLAUDE_CONFIG_DIR")
if config_dir:
# Taken as given, the way Claude Code takes it: no ~ expansion, which
# would also raise on a ~user this machine does not have.
roots.append(Path(config_dir) / "skills")
else:
try:
roots.append(Path.home() / ".claude" / "skills")
except RuntimeError:
# No resolvable home directory: the project root is the only place.
pass
return tuple(roots)
def _skill_file_present(path: Path) -> bool:
try:
return path.is_file()
except OSError:
# A root this process cannot traverse holds no skill it can confirm;
# reporting the skill missing beats crashing without a payload.
return False
def _skills_installed(project_root: Path, skill_ids: tuple[str, ...]) -> dict[str, bool]:
"""Per skill, whether a SKILL.md exists under any skill root.
The skill directory is the evidence, not an install manifest: a manifest
row does not prove Claude Code can load the skill, and a skill directory
without its SKILL.md is not a skill Claude Code loads.
"""
roots = _skill_roots(project_root)
return {
skill_id: any(_skill_file_present(root / skill_id / "SKILL.md") for root in roots)
for skill_id in skill_ids
}
def _story_skills_installed(project_root: Path) -> dict[str, bool]:
"""Per story skill, whether Claude Code can load it."""
return _skills_installed(project_root, STORY_SKILLS)
def _tea_skills_installed(project_root: Path, profile: str) -> dict[str, bool]:
"""Per TEA skill the profile delegates to, whether Claude Code can load it."""
return _skills_installed(project_root, TEA_SKILLS[profile])
def _renamed_tea_skills(project_root: Path) -> list[str]:
"""The `bmad-tea-*` skills under any skill root, sorted.
Read only to word the blocker: TEA 3.0 publishes the skills UCG calls under
these names, so finding them where a `bmad-testarch-*` skill is missing
says which TEA the project has. A root that cannot be listed holds none.
"""
found: set[str] = set()
for root in _skill_roots(project_root):
try:
entries = list(root.iterdir())
except OSError:
continue
for entry in entries:
if entry.name.startswith(TEA_RENAMED_PREFIX) and _skill_file_present(
entry / "SKILL.md"
):
found.add(entry.name)
return sorted(found)
def _story_skills_detail(project_root: Path, missing: list[str]) -> str:
"""One line (the headless `reason` flattens a blocker to one): what is
missing, why the run cannot proceed without it, and the fix."""
return (
"UCG story skill(s) not installed: %s. The run delegates story creation "
"to ucg-create-story and implementation to ucg-dev-story, which UCG's "
"installer copies beside the ultracode-goal skill, and has no substitute "
"for either (looked for <skill>/SKILL.md under %s). Operator fix (the run "
"never installs them itself), from the project root: "
"`npx bmad-module-ultracode-goal update`, or `install` where UCG was never "
"installed in the project (a plugin-marketplace install ships only the "
"ultracode-goal skill), so both land in .claude/skills. BMAD's deprecated "
"bmad-create-story and bmad-dev-story shims are not a stand-in."
% (", ".join(missing), " and ".join(str(r) for r in _skill_roots(project_root)))
)
def _tea_skills_detail(
project_root: Path, profile: str, missing: list[str], renamed: list[str]
) -> str:
"""One line, as the story-skills detail is: what is missing, the TEA
release UCG supports, and the operator's fix. When `bmad-tea-*` skills
are installed, it says which TEA that looks like."""
found = (
" Found %s instead: that looks like TEA 3.0 or later, which renamed "
"these skills and which UCG does not support yet." % ", ".join(renamed)
if renamed
else ""
)
return (
"TEA skill(s) the %s profile delegates to not installed: %s.%s UCG "
"supports BMAD 6 with TEA 1.27.x, calls these skills by their "
"bmad-testarch-* names, and has no substitute for them (looked for "
"<skill>/SKILL.md under %s). Operator fix (the run never installs TEA "
"itself), from the project root: install TEA 1.27.x with BMAD Method "
"6.12.2 or later (`npx bmad-method install`, module `tea`), which "
"installs TEA 1.27.2 into .claude/skills (an older BMAD 6 installer can "
"pick a later TEA)."
% (
profile,
", ".join(missing),
found,
" and ".join(str(r) for r in _skill_roots(project_root)),
)
)
def build_report(
project_root: Path,
epic: str,
tea_config: Path,
impl_artifacts: Path,
protected_branches: tuple[str, ...],
profile: str = "production",
) -> dict:
cc_raw, cc_ver = _cc_version()
goal_ok = _meets(cc_ver, MIN_GOAL)
workflows_ok = _meets(cc_ver, MIN_WORKFLOWS)
automemory_ok = _meets(cc_ver, MIN_AUTOMEMORY)
hook_onfailure_ok = _meets(cc_ver, MIN_HOOK_ONFAILURE)
git_unborn = _git_unborn(project_root)
git_branch = _git_branch(project_root)
if git_branch is None and git_unborn:
git_branch = _git_unborn_branch(project_root)
git_clean = _git_clean(project_root)
tea_flags = _read_toml_or_yaml_flags(tea_config)
artifacts_root = _tea_artifacts_root(project_root, tea_flags)
framework_kind = _detect_framework(project_root)
framework_present = framework_kind is not None
test_artifacts_dirs = _test_artifacts_dirs(artifacts_root)
sprint_status_present = _sprint_status_present(project_root, impl_artifacts)
project_context_count = _project_context_count(project_root)
story_skills = _story_skills_installed(project_root)
tea_skills = _tea_skills_installed(project_root, profile)
impl_artifacts_tracked = _impl_artifacts_tracked(project_root, impl_artifacts)
checks = {
"cc_version": cc_raw,
"goal_ok": goal_ok,
"workflows_ok": workflows_ok,
"automemory_ok": automemory_ok,
"hook_onfailure_ok": hook_onfailure_ok,
"git_branch": git_branch,
"git_clean": git_clean,
"git_unborn": git_unborn,
"framework_present": framework_present,
"framework_kind": framework_kind,
"test_artifacts_dirs": test_artifacts_dirs,
"sprint_status_present": sprint_status_present,
"project_context_count": project_context_count,
"tea_flags": tea_flags,
"story_skills": story_skills,
"tea_skills": tea_skills,
"impl_artifacts_tracked": impl_artifacts_tracked,
}
blockers: list[dict] = []
# --- Mechanical blockers (each counts toward the budget) ---
# Primitive versions: any one being below minimum blocks the unattended run.
if not (goal_ok and workflows_ok and automemory_ok and hook_onfailure_ok):
detail = _cc_version_detail(cc_raw, _below_minimums(cc_ver))
blockers.append(
{
"id": "cc_version",
"kind": "version",
"severity": "high",
"detail": detail,
# The script can't upgrade the host; the LLM prompts the user.
"remediable": False,
}
)
missing_skills = [s for s, present in story_skills.items() if not present]
if missing_skills:
blockers.append(
{
"id": "story_skills",
"kind": "dependency",
"severity": "high",
"detail": _story_skills_detail(project_root, missing_skills),
# Re-running UCG's installer is the operator's call; the
# remediation pass neither installs the skills nor works
# around their absence.
"remediable": False,
}
)
missing_tea = [s for s, present in tea_skills.items() if not present]
if missing_tea:
blockers.append(
{
"id": "tea_skills",
"kind": "dependency",
"severity": "high",
"detail": _tea_skills_detail(
project_root, profile, missing_tea, _renamed_tea_skills(project_root)
),
# The run cannot install TEA: BMAD's installer does, and which
# TEA release a project runs is the operator's call. Nor can it
# work around a missing one: no other skill writes the
# artifacts Stage 3 and the gate read.
"remediable": False,
}
)
if not framework_present:
blockers.append(
{
"id": "framework_present",
"kind": "framework",
"severity": "medium",
"detail": "No test framework detected at project root "
"(looked for a playwright/cypress/jest/vitest config, a pytest "
"config or conftest.py, or a package.json `test` script). "
"ATDD halts without one.",
# Remediation pass scaffolds via bmad-testarch-framework.
"remediable": True,
}
)
if git_unborn:
baseline = "a baseline of the project (its BMAD install, planning artifacts and skeleton)"
if git_branch in protected_branches:
where = "Commit %s on '%s' yourself, then re-run." % (baseline, git_branch)
else:
# A baseline committed on an unborn Epic branch would be that
# branch's root, with no protected base under it: deleting the
# branch, the run's only undo, would delete the pre-run tree too.
base = protected_branches[0] if protected_branches else "main"
where = (
"Point HEAD at your base branch first (`git symbolic-ref HEAD "
"refs/heads/%s`), commit %s there yourself, then re-run; never "
"commit the baseline on an Epic branch." % (base, baseline)
)
blockers.append(
{
"id": "git_unborn",
"kind": "git",
"severity": "high",
"detail": "HEAD on '%s' has no commit yet (a fresh `git init`, or an "
"orphan branch). %s The run never makes the commit its Epic branch "
"would start from: that commit would sit outside its only rollback, "
"the Epic branch." % (git_branch or "HEAD", where),
# What the baseline holds is the operator's call. A remediation
# commit here would become the root commit, on the protected
# branch or on an Epic branch with nothing under it.
"remediable": False,
}
)
if git_clean is False:
blockers.append(
{
"id": "git_clean",
"kind": "git",
"severity": "medium",
"detail": "Working tree is dirty; a per-green-story commit needs a clean base.",
"remediable": True,
}
)
elif git_clean is None:
blockers.append(
{
"id": "git_repo",
"kind": "git",
"severity": "high",
"detail": "git status failed; project-root may not be a git repository.",
"remediable": False,
}
)
if git_branch is not None and git_branch in protected_branches:
blockers.append(
{
"id": "git_branch",
"kind": "git",
"severity": "medium",
"detail": "On protected branch '%s'; the epic must run on its own branch."
% git_branch,
"remediable": True,
}
)
budget = len(blockers)
return {
"green": budget == 0,
"budget": budget,
"blockers": blockers,
"checks": checks,
}
# --- Resume manifest (--assert-armed) ----------------------------------------
# One deterministic read of the environment a resume must re-assert, replacing
# the tool-action-per-fact sweep the resume rule otherwise spends turns on.
# The script ASSERTS; it never acts: the two model-owned writes on a resume
# (re-latching from this run's own measurement, and writing a boundary story's
# fresh baseline) stay with the conductor, and exit 0 certifies neither.
# The five env vars preflight step 5 injects so the hooks enforce the resolved
# config rather than their hardcoded fallbacks. A var may live either in the
# hook command string in settings.local.json or in the process env the hooks
# inherit (preflight.md permits both); this checker accepts both, because
# fail-closing on a legitimate arming would teach operators to skip the check.
HOOK_ENV_VARS = (
"ULTRACODE_PROTECTED_BRANCHES",
"ULTRACODE_IMPL_ARTIFACTS",
"ULTRACODE_MAX_TURNS",
"ULTRACODE_EPIC_BRANCH_PREFIX",
"ULTRACODE_TEST_ARTIFACTS",
)
_GUARD_SCRIPT = "guard_pretooluse.py"
_BUDGET_SCRIPT = "budget_stop.py"
def _hook_entries(settings: dict) -> list[tuple[str, str | None, dict]]:
"""Every (event, matcher, inner item) nested under hooks.<Event>[].hooks[]
whose item carries a string `command`.
The entries are nested, not top-level (preflight.md's stale-hook bullet
documents the shape); a malformed layer contributes nothing rather than
raising, because an unreadable arming must read as NOT armed, never crash.
The EVENT is part of the identity on purpose: a guard command sitting under
hooks.Stop is never invoked before a tool call, so an event-blind read would
certify an arming that enforces nothing.
"""
out: list[tuple[str, str | None, dict]] = []
hooks = settings.get("hooks")
if not isinstance(hooks, dict):
return out
for event, groups in hooks.items():
if not isinstance(event, str) or not isinstance(groups, list):
continue
for group in groups:
if not isinstance(group, dict):
continue
matcher = group.get("matcher")
inner = group.get("hooks")
if not isinstance(inner, list):
continue
for entry in inner:
if isinstance(entry, dict) and isinstance(entry.get("command"), str):
out.append((event, matcher if isinstance(matcher, str) else None, entry))
return out
def _hook_commands(settings: dict) -> list[tuple[str, str | None, str]]:
"""Every (event, matcher, command) triple nested under hooks.<Event>[].hooks[]."""
return [(e, m, entry["command"]) for e, m, entry in _hook_entries(settings)]
# A leading `NAME=value` word: an assignment the shell applies to the command
# that follows it, not a command of its own. It is read on the word as written:
# the shell takes a word for one only when its name and its "=" are unquoted
# (`KEY='a b'` is one; `'KEY=a b'`, `"KEY=a b"`, `KEY"=v"` and `\KEY=v` are
# the command dash and bash run, and exit 127 for).
_ASSIGNMENT = re.compile(r"[A-Za-z_][A-Za-z0-9_]*=")
# The operators a shell reads outside quotes, longest first: those that end a
# command or join it to another (POSIX sh's, a newline, and bash's `|&`), and
# those that redirect its input or output (POSIX sh's, and bash's `&>`, `&>>`
# and `<<<`). Claude Code runs a hook command through a shell, so any of them
# makes the hook more than `<env> uv run <script>`.
_CONTROL_OPERATORS = frozenset({"&&", "||", ";;", "|&", ";", "&", "|", "(", ")", "\n"})
_SHELL_OPERATORS = tuple(
sorted(
_CONTROL_OPERATORS | {"<<<", "<<-", "&>>", "<<", ">>", "<&", ">&", "<>", ">|", "&>", "<", ">"},
key=len,
reverse=True,
)
)
def _last_path_part(word: str) -> str:
return re.split(r"[/\\]", word)[-1]
# A `$` the shell expands before it runs the command: a parameter (`$HOME`,
# `$1`, `$@`), `${...}`, `$(...)`, `$((...))` or bash's `$[...]`, in double
# quotes or outside them, and outside them bash's `$'...'` and `$"..."` too,
# which dash reads as a `$` and a quoted word (`$'25'` is `25` in bash, `$25`
# in dash). A `$` before anything else (a space, the end of the word) stays a
# `$`. A backtick starts a command substitution in double quotes or outside
# them; outside them a `*`, `?` or `[` makes a word a pattern the shell
# matches against file names, and a `{` may start bash's brace expansion
# (`{a,b}`).
_EXPANDS_IN_DOUBLE_QUOTES = re.compile(r"\$[A-Za-z0-9_{(\[@*#?$!-]|`")
_EXPANDS = re.compile(r"\$[A-Za-z0-9_{(\[@*#?$!'\"-]|[`*?[{]")
_PARAMETER = re.compile(r"\$(?:[A-Za-z_][A-Za-z0-9_]*|[0-9@*#?$!-])")
_BRACKET = re.compile(r"\[[^\]\s]*\]?")
def _expansion_end(command: str, index: int) -> int:
"""Where the expansion that starts at `index` (`_EXPANDS`) ends, to show
it in a problem: past its closing backtick, quote, parenthesis, brace or
bracket, nested parentheses and braces counted and quotes not read, or at
the end of the command where none closes it."""
opener = command[index : index + 2]
if opener[0] == "{" or opener in ("$(", "${"):
bracket = "(" if opener == "$(" else "{"
depth = 0
for cursor in range(index, len(command)):
if command[cursor] == bracket:
depth += 1
elif command[cursor] == (")" if bracket == "(" else "}"):
depth -= 1
if depth == 0:
return cursor + 1
return len(command)
if opener[0] == "`" or opener in ("$'", '$"'):
quote = opener[-1] if opener[0] == "$" else "`"
close = command.find(quote, index + (2 if opener[0] == "$" else 1))
return len(command) if close < 0 else close + 1
if opener == "$[":
match = _BRACKET.match(command, index + 1)
else:
match = (_BRACKET if opener[0] == "[" else _PARAMETER).match(command, index)
return match.end() if match is not None else index + 1
def _substitutes_a_command(expansion: str) -> bool:
"""Is this expansion a command substitution, which runs a command that
reads the stdin the script would read (`$(cat)`, a backtick), rather
than arithmetic (`$((1+1))`) or a parameter?"""
return expansion.startswith("`") or (expansion.startswith("$(") and not expansion.startswith("$(("))
def _shell_tokens(command: str) -> list[tuple[str, str, str, int, int]] | None:
"""The command's tokens as a POSIX shell reads them, or None when its
quoting does not parse (a quote left open).
Each is (kind, text, raw, start, end): kind "word", with its text the word
once its quotes and escapes are removed and raw the word as written, or
"control" or "redirect" for an operator, with a redirection's file
descriptor (`2>`) in it, or "expansion" for what the shell expands
(`_EXPANDS`), with its text as far as `_expansion_end` reads it,
right after the word that holds it. start and end place the token in
`command`. Single quotes keep everything to the next one; in double quotes
a backslash escapes only `$`, a backtick, `"`, `\\` and a newline; outside
them it escapes the next character, and a backslash before a newline joins
the two lines. A `#` that starts a word starts a comment, to the end of
the line. Nothing is expanded: a word holds `$NAME` as written, beside the
expansion token that names it.
"""
tokens: list[tuple[str, str, str, int, int]] = []
expansions: list[tuple[str, str, str, int, int]] = [] # in the word under way
text: list[str] = []
raw: list[str] = []
start = -1 # where the word under way starts; -1 while there is none
index, size = 0, len(command)
def flush(end: int) -> None:
nonlocal start
if start >= 0:
tokens.append(("word", "".join(text), "".join(raw), start, end))
tokens.extend(expansions)
expansions.clear()
text.clear()
raw.clear()
start = -1
def expansion(at: int) -> None:
end = _expansion_end(command, at)
expansions.append(("expansion", command[at:end], command[at:end], at, end))
while index < size:
char = command[index]
if start < 0 and char == "#":
newline = command.find("\n", index)
index = size if newline < 0 else newline
continue
if char in " \t":
flush(index)
index += 1
continue
if char == "\\" and command.startswith("\\\n", index):
index += 2
continue
operator = next((o for o in _SHELL_OPERATORS if command.startswith(o, index)), None)
if operator is not None:
begin = index
# A redirection's file descriptor: digits alone, right before it.
if operator not in _CONTROL_OPERATORS and start >= 0 and re.fullmatch(r"[0-9]+", "".join(raw)):
begin, start = start, -1
text.clear()
raw.clear()
flush(index)
kind = "control" if operator in _CONTROL_OPERATORS else "redirect"
tokens.append((kind, command[begin : index + len(operator)], operator, begin, index + len(operator)))
index += len(operator)
continue
if start < 0:
start = index
if char == "\\":
escaped = command[index + 1 : index + 2]
text.append(escaped or "\\") # a backslash that ends the command stays
raw.append(command[index : index + 2])
index += 2
elif char == "'":
close = command.find("'", index + 1)
if close < 0:
return None
text.append(command[index + 1 : close])
raw.append(command[index : close + 1])
index = close + 1
elif char == '"':
cursor = index + 1
while cursor < size and command[cursor] != '"':
if command[cursor] == "\\" and command[cursor + 1 : cursor + 2] in ("$", "`", '"', "\\", "\n"):
if command[cursor + 1] != "\n":
text.append(command[cursor + 1])
cursor += 2
continue
if _EXPANDS_IN_DOUBLE_QUOTES.match(command, cursor):
expansion(cursor)
text.append(command[cursor])
cursor += 1
if cursor >= size:
return None
raw.append(command[index : cursor + 1])
index = cursor + 1
else:
if _EXPANDS.match(command, index):
expansion(index)
text.append(char)
raw.append(char)
index += 1
flush(size)
return tokens
# How uv reads the options of a hook command, as uv 0.12.15 defines them (the
# global ones, and those of `uv run` and of each argument group it reads, the
# ones `--help` hides too), each tried against that binary. Before `run` uv
# takes its global options alone (`uv --python 3.12 run` exits 2), after it
# those and `uv run`'s own. A flag takes no value (`--offline=true` exits 2);
# an option that takes one takes it glued (`--python=3.12`, `-p3.12`) or in
# the next word, which must not start with "-" (`--python -q` exits 2). Read
# as flags, values took the script's place, and read as uv's, an option uv
# refuses there passed. An option a later uv adds reads as one uv does not
# take, which fails safe: the re-merge rewrites the command as preflight does.
_UV_GLOBAL_FLAGS = frozenset(
{
"--allow-python-downloads", "--isolated", "--managed-python", "-n", "--native-tls", "--no-cache",
"--no-cache-dir", "--no-color", "--no-config", "--no-installer-metadata", "--no-managed-python",
"--no-native-tls", "--no-offline", "--no-preview", "--no-progress", "--no-python-downloads",
"--no-system-certs", "--offline", "--preview", "-q", "--quiet", "--system-certs", "-v", "--verbose",
}
)
_UV_GLOBAL_VALUES = frozenset(
{
"--allow-insecure-host", "--cache-dir", "--color", "--config-file", "--directory", "--preview-feature",
"--preview-features", "--project", "--python-fetch", "--python-preference", "--trusted-host",
}
)
_UV_RUN_FLAGS = frozenset(
{
"--active", "--all-extras", "--all-groups", "--all-packages", "--binary", "--build", "--build-isolation",
"--compile", "--compile-bytecode", "--dev", "--editable", "--exact", "--force-reinstall", "--frozen",
"--gui-script", "--inexact", "--locked", "--no-active", "--no-all-extras", "--no-binary", "--no-build",
"--no-build-isolation", "--no-compile", "--no-compile-bytecode", "--no-default-groups", "--no-dev",
"--no-editable", "--no-env-file", "--no-exact", "--no-frozen", "--no-index", "--no-locked", "--no-project",
"--no-refresh", "--no-reinstall", "--no-sources", "--no-sync", "--no-upgrade", "--no_workspace",
"--only-dev", "--pre", "--refresh", "--reinstall", "-s", "--script", "--show-resolution", "-U", "--upgrade",
}
)
_UV_RUN_VALUES = frozenset(
{
"-C", "--config-setting", "--config-settings", "--config-settings-package", "--default-index", "--env-file",
"--exclude-newer", "--exclude-newer-package", "--extra", "--extra-index-url", "-f", "--find-links",
"--fork-strategy", "--group", "-i", "--index", "--index-strategy", "--index-url", "--keyring-provider",
"--link-mode", "--max-recursion-depth", "--no-binary-package", "--no-build-isolation-package",
"--no-build-package", "--no-editable-package", "--no-extra", "--no-group", "--no-sources-package",
"--only-group", "-P", "-p", "--package", "--prerelease", "--prerelease-package", "--python",
"--python-platform", "--refresh-package", "--reinstall-package", "--resolution", "--upgrade-group",
"--upgrade-package", "-w", "--with", "--with-editable", "--with-requirements",
}
)
# The spellings of an option uv names another way in its errors.
_UV_ALIASES = {
"--trusted-host": "--allow-insecure-host", "--compile": "--compile-bytecode",
"--config-settings": "--config-setting", "-C": "--config-setting", "-f": "--find-links", "-i": "--index-url",
"--no-exact": "--inexact", "--no-cache-dir": "--no-cache", "-n": "--no-cache",
"--no-compile": "--no-compile-bytecode", "--no_workspace": "--no-project",
"--preview-feature": "--preview-features", "-p": "--python", "-q": "--quiet",
"--force-reinstall": "--reinstall", "-s": "--script", "-U": "--upgrade", "-P": "--upgrade-package",
"-v": "--verbose", "-w": "--with",
}
# The options uv takes twice in one place. It refuses any other given twice
# there (`--offline --offline` exits 2), though once before `run` and once
# after it is fine.
_UV_REPEATABLE = frozenset(
{
"--allow-insecure-host", "--config-setting", "--config-settings-package", "--env-file",
"--exclude-newer-package", "--extra", "--extra-index-url", "--find-links", "--group", "--index",
"--no-binary-package", "--no-build-isolation-package", "--no-build-package", "--no-editable-package",
"--no-extra", "--no-group", "--no-sources-package", "--only-group", "--prerelease-package",
"--preview-features", "--quiet", "--refresh-package", "--reinstall-package", "--upgrade-group",
"--upgrade-package", "--verbose", "--with", "--with-editable", "--with-requirements",
}
)
# The pairs of options uv 0.12.15 refuses together, by the names uv gives
# them, measured by running every pair of its options through `sh -c`, each
# with a value it takes alone: those it refuses in one place, on either side
# of `run` ("cannot be used with", exit 2), and those it refuses with one
# before `run` and the other after it. The two lists differ. clap's own pairs
# hold in one place only (`uv -q run -v` runs the script), and uv's own
# (`--offline` with `--refresh`, `--managed-python` with
# `--python-preference`) in both. A flag beside its negation uv reads
# last-wins in one place (`uv run --offline --no-offline` runs the script),
# but for `--allow-python-downloads`, and refuses across `run` ("Boolean
# flags on different levels are currently not supported").
_UV_CONFLICTS = frozenset(
frozenset(pair)
for pair in (
("--all-extras", "--extra"),
("--all-extras", "--only-group"),
("--all-groups", "--only-dev"),
("--all-groups", "--only-group"),
("--all-packages", "--package"),
("--allow-python-downloads", "--no-python-downloads"),
("--color", "--no-color"),
("--dev", "--only-group"),
("--extra", "--only-group"),
("--frozen", "--locked"),
("--frozen", "--no-sources"),
("--frozen", "--upgrade"),
("--group", "--only-dev"),
("--group", "--only-group"),
("--gui-script", "--script"),
("--locked", "--upgrade"),
("--managed-python", "--python-preference"),
("--no-dev", "--only-dev"),
("--no-managed-python", "--python-preference"),
("--no-project", "--package"),
("--offline", "--refresh"),
("--offline", "--refresh-package"),
("--quiet", "--verbose"),
)
)
_UV_ACROSS_CONFLICTS = frozenset(
frozenset(pair)
for pair in (
("--allow-python-downloads", "--no-python-downloads"),
("--managed-python", "--python-preference"),
("--native-tls", "--no-native-tls"),
("--no-managed-python", "--python-preference"),
("--offline", "--no-offline"),
("--offline", "--refresh"),
("--offline", "--refresh-package"),
("--preview", "--no-preview"),
("--system-certs", "--no-system-certs"),
)
)
# The options that end a command line without running the script, as the
# predicate the problem names. Each prints and exits 0, so a guard handed to
# one never runs and Claude Code reads its exit as no objection: uv's version
# and help before `run`, its help after it, and `--show-settings` in either
# place. `uv run -m <name>` runs a module, not a script file.
_PRINTS_VERSION = "print its version and exit, not run a script"
_PRINTS_HELP = "print its help and exit, not run a script"
_PRINTS_SETTINGS = "print its settings and exit, not run a script"
_UV_STOPS = {
"-V": _PRINTS_VERSION, "--version": _PRINTS_VERSION, "-h": _PRINTS_HELP, "--help": _PRINTS_HELP,
"--show-settings": _PRINTS_SETTINGS,
}
_UV_RUN_STOPS = {
"-m": "run a module, not a script", "--module": "run a module, not a script",
"-h": _PRINTS_HELP, "--help": _PRINTS_HELP, "--show-settings": _PRINTS_SETTINGS,
}
# The values uv 0.12.15 takes for each option whose value is one of a set:
# clap's names and aliases, hidden ones included, read from uv's sources, and
# each run against the binary in both spellings (`--color never`,
# `--color=never`) and, for a global one, on both sides of `run`. Case
# counts. Any other value is a usage error, exit 2, before uv runs anything.
_MANYLINUX = ["manylinux2014"] + ["manylinux_2_%d" % minor for minor in (17, 28, *range(31, 41))]
_UV_CHOICES = {
"--color": frozenset({"auto", "always", "never"}),
"--fork-strategy": frozenset({"fewest", "requires-python"}),
"--index-strategy": frozenset(
{"first-index", "first-match", "unsafe-first-match", "unsafe-any-match", "unsafe-best-match"}
),
"--keyring-provider": frozenset({"disabled", "subprocess"}),
"--link-mode": frozenset({"clone", "reflink", "copy", "hardlink", "symlink"}),
"--prerelease": frozenset({"disallow", "allow", "if-necessary", "explicit", "if-necessary-or-explicit"}),
"--python-fetch": frozenset({"automatic", "manual", "never"}),
"--python-preference": frozenset({"only-managed", "managed", "system", "only-system"}),
"--resolution": frozenset({"highest", "lowest", "lowest-direct"}),
"--python-platform": frozenset(
[
"windows", "linux", "macos", "x86_64-pc-windows-msvc", "aarch64-pc-windows-msvc", "i686-pc-windows-msvc",
"x86_64-unknown-linux-gnu", "aarch64-unknown-linux-gnu", "x86_64-unknown-linux-musl",
"aarch64-unknown-linux-musl", "s390x-unknown-linux-gnu", "powerpc64le-unknown-linux-gnu",
"loongarch64-unknown-linux-gnu", "riscv64-unknown-linux", "x86_64-apple-darwin", "aarch64-apple-darwin",
"x86_64-linux-android", "aarch64-linux-android", "wasm32-pyodide2024", "wasm32-pyodide2025",
"arm64-apple-ios", "arm64-apple-ios-simulator", "x86_64-apple-ios-simulator",
]
+ ["%s-%s" % (arch, tag) for arch in ("x86_64", "aarch64", "ppc64le", "s390x") for tag in _MANYLINUX]
+ ["%s_%s" % (tag, arch) for arch in ("x86_64", "aarch64", "ppc64le", "s390x") for tag in _MANYLINUX]
+ ["loongarch64-manylinux_2_%d" % minor for minor in range(36, 41)]
+ ["manylinux_2_%d_loongarch64" % minor for minor in range(36, 41)]
),
}
# The options whose value is a whole number, with the largest uv takes. clap
# reads it as a signed number before it checks the range, so `+5`, `007` and a
# glued `=-0` pass, while `5.0`, `1_000` and ` 5` exit 2.
_UV_NUMBERS = {"--max-recursion-depth": 4294967295}
_WHOLE_NUMBER = re.compile(r"[+-]?[0-9]+")
# The value options uv 0.12.15 takes an empty value for, in its own word
# (`--with ''`) or glued (`--with=`), by the name uv gives each. Each of the
# others, given one, exits 2 before uv runs anything ("a value is required",
# or "invalid value ''"). An empty `--python` asks for no Python, so the
# script's header chooses it.
_UV_EMPTY_OK = frozenset(
{
"--allow-insecure-host", "--default-index", "--env-file", "--extra-index-url", "--find-links", "--index",
"--index-url", "--python", "--with", "--with-editable", "--with-requirements",
}
)
# The options that make `uv run` read the script's lockfile (`<script>.lock`
# beside it), which preflight never writes and the skill does not ship: uv
# 0.12.15 exits 2 on either, "Unable to find lockfile for Python script".
_UV_LOCKFILE_FLAGS = ("--frozen", "--locked")
# The Python both hooks' headers require (`requires-python = ">=3.11"`), as
# (major, minor). Given `--python`, uv runs the script on the Python that
# request selects, the newest installed one it admits, with only a warning
# when the header does not allow it: uv 0.12.15 ran `--python 3.10` on 3.10.21
# and `--python '<=3.11'` on 3.10.21 where no 3.11.0 was installed, and on
# 3.9 the guard crashes at import (exit 1). Which Python a request selects
# depends on what the machine has installed, so the minimum holds everywhere
# only for a request whose every Python meets it.
_SCRIPT_PYTHON_MINIMUM = (3, 11)
# How uv reads a `--python` request as a version, in any case, trimmed: an
# optional implementation name, joined by nothing, "@" or "-", then a version
# (`3.10`, `v3.10.21`, `310`, with a suffix such as `t`, `+gil`, `rc1` or a
# platform) or a set of specifiers (`>=3.11,<3.13`). uv 0.12.15 reads
# whitespace after the name or its "@" or "-" as nothing (`cpython 3.10`,
# `cpython@ 3.10` and `cpython- 3.10` ran 3.10), and none before them
# (`cpython @3.10` named no Python it found). It joins a name to a set of
# specifiers as it joins one to a version (`cpython-<3.11` and
# `cpython@<3.11` ran 3.10). A name alone, `any` or
# `default` asks for any version. A path or a program name names none.
_PY_IMPLEMENTATION = r"(?:cpython|cp|python|pypy|pp|graalpy|gp|pyodide)"
_PY_ANY_VERSION = re.compile(r"%s@?|any|default" % _PY_IMPLEMENTATION, re.IGNORECASE | re.ASCII)
_PY_VERSION = re.compile(
r"(?:%s[@-]?\s*)?v?(?P<version>[0-9]+(?:\.[0-9]+){0,2})[a-z0-9_+.-]*" % _PY_IMPLEMENTATION,
re.IGNORECASE | re.ASCII,
)
_PY_SPECIFIERS = re.compile(
r"(?:%s[@-]?\s*)?(?P<specifiers>[<>=!~].*)" % _PY_IMPLEMENTATION, re.IGNORECASE | re.ASCII
)
_PY_SPECIFIER = re.compile(
r"\s*(?P<operator>===|==|!=|~=|<=|>=|<|>)\s*v?(?P<version>[0-9]+(?:\.[0-9]+)*)(?:\.\*)?\s*", re.ASCII
)
# A word that names a Python, by name or by path. `uv run` reads the script's
# inline metadata (its `# /// script` header) only when it runs the script
# itself. Handed to `python`, or to any other program, the script runs as that
# program's argument, so the header's Python minimum does not hold, and the
# script is no longer isolated from the project it runs in. uv 0.12.15, given
# `uv run python <script>`, ran Python 3.10 where a `.python-version` named it,
# created a project's `.venv` and `uv.lock`, and exited 1 without running the
# script when that project failed to build; and it found no `python3.12` to
# spawn, with a 3.12 it manages installed, whenever it selected another Python.
_PYTHON = re.compile(r"^python(?:\d+(?:\.\d+)?)?w?(?:\.exe)?$", re.IGNORECASE)
def _number(digits: str) -> int:
"""A run of ASCII digits as a number, one too long for int() to read
from a string (past 4300 digits) read as the largest a version holds."""
digits = digits.lstrip("0") or "0"
return int(digits) if len(digits) <= 9 else 999_999_999
def _release(version: str) -> tuple[int, int]:
"""(major, minor) of a version uv reads, `0` for a minor it leaves out.
Without a dot uv reads the first digit as the major (`310` is 3.10,
`0312` 3.12). A specifier's version is read the same way, which can only
lower its bound (`>=310` reads as 3.10, never as 310)."""
if "." not in version:
version = version.lstrip("0") or "0"
version = version[0] + ("." + version[1:] if len(version) > 1 else "")
parts = [_number(part) for part in version.split(".")]
return parts[0], parts[1] if len(parts) > 1 else 0
def _python_admits_older(request: str) -> bool:
"""Does this `--python` request admit a Python below the hooks' minimum?
True for a version below it, a set of specifiers whose lower bound is
below it (`<3.12`, `>=3.9`, `!=3.12` set none above it), and a request
for any version. False for an empty request, which leaves the choice to
the script's header, and for one this cannot read as a version (a path,
a program name), which is not judged.
"""
request = request.strip()
if not request:
return False
if _PY_ANY_VERSION.fullmatch(request):
return True
plain = _PY_VERSION.fullmatch(request)
if plain is not None:
return _release(plain.group("version")) < _SCRIPT_PYTHON_MINIMUM
specified = _PY_SPECIFIERS.fullmatch(request)
if specified is None:
return False
lowest = (0, 0)
for specifier in specified.group("specifiers").split(","):
clause = _PY_SPECIFIER.fullmatch(specifier)
if clause is None:
return False
if clause.group("operator") not in ("<", "<=", "!="):
lowest = max(lowest, _release(clause.group("version")))
return lowest < _SCRIPT_PYTHON_MINIMUM
def _uv_options(words: list[str], index: int, after_run: bool) -> tuple[int, str | None, list[str]]:
"""(index of the first word past uv's options, why uv would not run the
script as its header asks or None, each option read by the name uv gives
it).
Before `run` the options are uv's global ones, and `--` there leaves uv no
command; after it `uv run`'s own join them, and `--` ends them. A short
cluster (`-qp`) reads letter by letter: a letter that takes a value takes
the rest of the word, or the next word when it is the last. A value is
judged where uv's parser judges it, against a fixed set, as a number or
as empty (`_UV_CHOICES`, `_UV_NUMBERS`, `_UV_EMPTY_OK`), and a Python
request against the minimum the hooks' headers set
(`_SCRIPT_PYTHON_MINIMUM`).
"""
who = "uv run" if after_run else "uv"
flags = _UV_GLOBAL_FLAGS | _UV_RUN_FLAGS if after_run else _UV_GLOBAL_FLAGS
values = _UV_GLOBAL_VALUES | _UV_RUN_VALUES if after_run else _UV_GLOBAL_VALUES
stops = _UV_RUN_STOPS if after_run else _UV_STOPS
read: list[str] = []
def refuse(what: str) -> str:
return "%s would %s, and run no script" % (who, what)
def unknown(name: str) -> str:
if not after_run and (name in _UV_RUN_FLAGS or name in _UV_RUN_VALUES or name in _UV_RUN_STOPS):
return refuse('refuse "%s", an option it takes only after run' % name)
return refuse('refuse "%s", an option it does not take' % name)
def note(name: str) -> str | None:
option = _UV_ALIASES.get(name, name)
if option in read and option not in _UV_REPEATABLE:
return refuse('refuse "%s" twice' % option)
for earlier in read:
if frozenset((earlier, option)) in _UV_CONFLICTS:
return refuse('refuse "%s" beside "%s"' % (earlier, option))
read.append(option)
return None
def value_problem(name: str, value: str | None, separate: bool) -> str | None:
"""Why uv would not take `value`, glued on or the next word (None when
the command ends first, which leaves no script to find)."""
if value is None:
return None
bad = refuse('not take "%s" as the value of "%s"' % (value, name))
if separate and value.startswith("-") and value != "-":
return bad # uv reads the word as an option
option = _UV_ALIASES.get(name, name)
if value == "" and option not in _UV_EMPTY_OK:
return bad
if option == "--python" and _python_admits_older(value):
return (
'uv run would let "%s %s" select a Python below the %d.%d minimum the script\'s header sets, and '
"uv runs the script on one with only a warning, so that minimum would not hold"
% ((name, value.strip()) + _SCRIPT_PYTHON_MINIMUM)
)
if name in _UV_CHOICES:
return None if value in _UV_CHOICES[name] else bad
if name in _UV_NUMBERS:
# Its digits past the sign and leading zeros, so no word is too
# long for int() to read.
digits = value.lstrip("+-").lstrip("0") or "0"
whole = _WHOLE_NUMBER.fullmatch(value) is not None and (digits == "0" or not value.startswith("-"))
return None if whole and len(digits) <= 10 and int(digits) <= _UV_NUMBERS[name] else bad
return None
while index < len(words):
word = words[index]
if word == "--":
if after_run:
return index + 1, None, read
return index, 'uv would take no command after "--", and run no script', read
if not word.startswith("-") or word == "-":
return index, None, read
index += 1
if word.startswith("--"):
name, glued, value = word.partition("=")
if name in stops:
return index - 1, "%s would %s" % (who, stops[name]), read
if name in values:
if glued:
problem = value_problem(name, value, separate=False)
else:
problem = value_problem(name, words[index] if index < len(words) else None, separate=True)
index += 1 # its value is the next word
elif name in flags:
problem = refuse('refuse "%s", a value for an option that takes none' % word) if glued else None
else:
problem = unknown(name)
problem = problem or note(name)
if problem is not None:
return index - 1, problem, read
continue
for position, letter in enumerate(word[1:], start=1):
name = "-" + letter
if name in stops:
return index - 1, "%s would %s" % (who, stops[name]), read
if name not in values and name not in flags:
return index - 1, unknown(name), read
problem = None
if name in values:
if position < len(word) - 1:
# clap takes `-p=3.12` as `-p3.12`: one "=" after the
# letter is no part of the value (`-C=` gives an empty one).
glued = word[position + 1 :]
problem = value_problem(name, glued[1:] if glued.startswith("=") else glued, separate=False)
else:
problem = value_problem(name, words[index] if index < len(words) else None, separate=True)
index += 1 # its value is the next word
problem = problem or note(name)
if problem is not None:
return index - 1, problem, read
if name in values:
break
return index, None, read
def _command_problem(command: str, script: str) -> str | None:
"""Why `script` would not run from this hook command as preflight writes
it, or None.
Preflight writes each UCG hook as `<env> uv run '<path to the script>'`:
leading NAME=value words, then `uv run` and the script path, with each
injected value and the path in single quotes. Claude Code hands the string
to a shell, which splits it at every unquoted space, so an unquoted value
or path that holds one (a project under `~/My Projects`) makes the rest of
it the command the shell runs (exit 127), or the file `uv run` is given
(uv exits 2, or 1 where the project it syncs first fails to build or its
requirements cannot be satisfied, though 2 where the network fails), and
the hook never starts. Under the guard's `"onFailure": "block"` each
refuses every tool call. On Stop, exit 127 and exit 1 are non-blocking
errors, so each stop goes through uncounted, and exit 2 sends each stop
back, up to eight times in a row. The command is read as a POSIX shell
reads it (`_shell_tokens`) and never run, so the script path is not
opened: a moved skill is not this check's to find.
A leading word is an assignment only as the shell takes one, with its
name and "=" unquoted: `'KEY=a b'` is the command the shell runs. A
control operator (`;`, `&`, `&&`, `||`, `|`, a newline, a parenthesis)
or a redirection (`<`, `>`, `2>&1`) outside quotes fails the command,
before or after the script: preflight writes none, and with one the
script may read no hook event (`< /dev/null`, or `&`, which hands it an
empty stdin), its verdict or reason may not reach Claude Code (`>
/dev/null`, `2>&1`), or its exit code may be another command's (`||
true`, `; true`). Even a harmless one (`&& true`) is read as a problem,
since the re-merge that answers it costs nothing. A comment that starts a
word ends the command there, as it does in the shell.
So does an expansion (`_EXPANDS`): a `$` that starts one outside single
quotes (`$HOME`, `${A}`, `"$(cat)"`, `$((1))`, bash's `$'...'`), a
backtick outside single quotes, or outside any quotes a `*`, `?`, `[` or
`{`. The shell replaces it before uv starts, so the words uv and the
script get are not the ones read here: a command substitution can read
the hook event first (`"$(cat)"` leaves the guard an empty stdin, and the
guard then allows the call), `KEY=${A:- uv run <script> }` is one
assignment, so the shell runs nothing, `-p $X` with X unset hands `-p`
the script, and `--with *` hands uv a file in the hook's folder as the
script. Preflight writes none outside single quotes, so even one the
shell leaves as written (`KEY=a*`) is read as a problem. A leading `~`,
which the shell turns into the home folder, is read as written: it
moves no word and runs nothing.
uv's options are read as uv reads them (`uv run --python 3.12 <script>`
starts the script; `_uv_options`). A command uv would refuse, or one where
it prints a version, help or settings and exits (`uv --version`, `uv run
--help`), starts nothing: under the guard's key the first refuses every
call, and the second's exit 0 reads as no objection. So does one with
`--frozen` or `--locked`, which makes uv look for a lockfile beside the
script that preflight never writes (`_UV_LOCKFILE_FLAGS`), and one with a
pair of options uv refuses together, in one place or across `run`
(`_UV_CONFLICTS`, `_UV_ACROSS_CONFLICTS`). A command that
hands the script to a Python (`uv run python <script>`) fails too, since
the script then runs without its inline metadata (`_PYTHON`), and so does
a Python request that admits one below the minimum the script's header
sets (`--python 3.10`, `-p 3`, `--python '<3.12'`), since uv runs the
script on the Python a request selects with only a warning.
A value is judged where uv's parser judges it before it runs anything:
against a fixed set (`--color`, `--link-mode`, the others in
`_UV_CHOICES`), as a whole number (`--max-recursion-depth`), or as empty
(refused for every option but those in `_UV_EMPTY_OK`). The values of the
other options take forms this check does not enumerate (a path, a URL, a
host, a requirement, a package, extra or group name, a date or a span of
time, a `KEY=VALUE` setting, a Python named by a path or a program name),
so one uv's parser refuses (an `--extra` name with a space in it, `-w-x`)
passes here, as does one uv refuses only when it runs (a `--python 3.99`
it cannot find, `-p-3`). The values of the leading NAME=value words are
not read either: what a variable does to uv or Python (`PATH`,
`UV_PYTHON`, `UV_FROZEN`, `PYTHONINSPECT`) is theirs to find when the hook
runs.
"""
tokens = _shell_tokens(command)
if tokens is None:
return "its quoting does not parse"
for position, (kind, shown, _, _, _) in enumerate(tokens):
if kind == "expansion":
reads_stdin = (
", and the command it runs for it can read the hook event Claude Code sends before the script does"
if _substitutes_a_command(shown)
else ""
)
return (
"the shell would expand %s before uv starts, so the words uv and the script get need not be the "
"ones written here%s" % (json.dumps(shown), reads_stdin)
)
if kind == "control":
return (
"the shell would read %s as a control operator, so the command would be more than <env> uv run "
"<script>, and the exit code and output Claude Code reads need not be the script's" % json.dumps(shown)
)
if kind == "redirect":
target = tokens[position + 1] if position + 1 < len(tokens) else None
if target is not None and target[0] == "word":
shown = command[tokens[position][3] : target[4]]
return (
"the shell would read %s as a redirection, so the script would not read the hook event Claude "
"Code sends, or what it writes would not reach Claude Code where it reads it" % json.dumps(shown)
)
index = 0
while index < len(tokens) and _ASSIGNMENT.match(tokens[index][2]):
index += 1
words = [word for _, word, _, _, _ in tokens[index:]]
if words and _ASSIGNMENT.match(words[0]):
return (
'the shell would run %s as the command, not uv, since a word whose name or "=" is quoted is no '
"assignment" % json.dumps(words[0])
)
if not words or _last_path_part(words[0]) not in ("uv", "uv.exe"):
return "the shell would run %s as the command, not uv" % (json.dumps(words[0]) if words else "nothing")
index, problem, before = _uv_options(words, 1, after_run=False)
if problem is not None:
return problem
if index >= len(words) or words[index] != "run":
return "uv is given %s, not run" % (json.dumps(words[index]) if index < len(words) else "nothing")
index, problem, read = _uv_options(words, index + 1, after_run=True)
if problem is not None:
return problem
for later in read:
for earlier in before:
if frozenset((earlier, later)) in _UV_ACROSS_CONFLICTS:
return 'uv would refuse "%s" before run beside "%s" after it, and run no script' % (earlier, later)
for flag in _UV_LOCKFILE_FLAGS:
if flag in read:
return (
'uv run would find no lockfile for the script, which "%s" needs and preflight never writes, '
"and run no script" % flag
)
# `uv run --script` (or `-s`, or `--gui-script`) runs the word after its
# options as the script, even when that word is `python`.
if (
index < len(words)
and "--script" not in read
and "--gui-script" not in read
and _PYTHON.match(_last_path_part(words[index]))
):
return (
"uv run would hand the script to %s without reading its inline metadata, so the Python minimum "
"its header sets would not hold, and the script would run in the project's environment, where "
"there is one, not an isolated one" % json.dumps(words[index])
)
if index >= len(words) or _last_path_part(words[index]) != script:
return "uv run would be given %s as the script, not a path ending in %s" % (
json.dumps(words[index]) if index < len(words) else "nothing",
script,
)
return None
def _assert_hooks(project_root: Path) -> dict:
"""Are both UCG hooks armed, with the PreToolUse matcher in all-tools form,
`"onFailure": "block"` on every guard item, and every UCG hook command one
the shell splits into `<env> uv run <script>`?
Matcher assertion mirrors preflight step 5: `*` or an absent matcher key both
select every tool; anything narrower (the observed `Bash`-only arming) leaves
the Cross-Session Recall invariant enforcing nothing. The failure policy is
compared exactly: without the key (every arming UCG 3.x or earlier made) a
guard that crashes, cannot start or times out lets the call through, and a
value other than "continue" or "block" (`"Block"`) makes Claude Code drop
the whole item, so the guard does not run at all. The Stop budget hook's
item is not read for it: Claude Code ignores the key on Stop. Each UCG
command, the budget hook's too, is read the way the shell splits it
(`_command_problem`). Fail-closed: a missing or unparseable settings file
is NOT armed.
"""
settings_path = project_root / ".claude" / "settings.local.json"
try:
settings = json.loads(settings_path.read_text(encoding="utf-8"))
except (OSError, ValueError, UnicodeDecodeError):
return {
"settings_readable": False,
"guard_present": False,
"budget_present": False,
"matcher_all_tools": False,
"guard_on_failure_block": False,
"guard_on_failure": [],
"commands_start_scripts": False,
"command_problems": [],
"ok": False,
}
entries = _hook_entries(settings)
guard = [(m, entry) for e, m, entry in entries if _GUARD_SCRIPT in entry["command"] and e == "PreToolUse"]
budget = [entry for e, _, entry in entries if _BUDGET_SCRIPT in entry["command"] and e == "Stop"]
matcher_ok = bool(guard) and all(m is None or m == "*" for m, _ in guard)
# One value per guard item, in file order: None where the key is absent.
on_failure = [entry.get("onFailure") for _, entry in guard]
on_failure_ok = bool(guard) and all(v == "block" for v in on_failure)
# One line per UCG item, in file order, whose command would not start its
# script; empty when every one would (or when there is none to read).
problems: list[str] = []
for event, script, entry in [("PreToolUse", _GUARD_SCRIPT, e) for _, e in guard] + [
("Stop", _BUDGET_SCRIPT, e) for e in budget
]:
problem = _command_problem(entry["command"], script)
if problem is not None:
problems.append("%s under %s: %s" % (script, event, problem))
return {
"settings_readable": True,
"guard_present": bool(guard),
"budget_present": bool(budget),
"matcher_all_tools": matcher_ok,
"guard_on_failure_block": on_failure_ok,
"guard_on_failure": on_failure,
"commands_start_scripts": not problems,
"command_problems": problems,
"ok": bool(guard) and bool(budget) and matcher_ok and on_failure_ok and not problems,
}
# How a reason that is the operator's to fix (the story skills, the Claude
# Code version) ends on a resume, and how a hooks reason defers to one: the
# re-assertion sweep in references/execute.md escalates it before it fixes
# any other, since the run stops on it either way and a hooks re-merge writes
# a protected file that a headless session may be refused.
_ESCALATE_FIRST = (
"Escalate the story about to be driven before fixing any other reason this "
"assertion names, as execute.md's re-assertion sweep says: a hooks re-merge "
"waits for the resume after the operator's fix"
)
_RE_MERGE_WAITS = (
"unless a reason that is the operator's to fix (story skills not installed, "
"or a Claude Code below the minimum) stands beside this one: that one is "
"escalated first, and the resume after the operator's fix re-merges"
)
def _on_failure_reason(values: list) -> str:
"""The named reason for a guard item without `"onFailure": "block"`."""
shown = ", ".join("missing" if v is None else json.dumps(v) for v in values)
return (
'PreToolUse guard is not armed with "onFailure": "block" on every item '
"(found: %s): without it a guard that crashes, cannot start or times out "
"lets the tool call run unchecked, and a value other than \"continue\" or "
'"block" makes Claude Code drop the item, so the guard does not run at '
"all. Re-merge the hooks as preflight.md step 5's Hooks bullet says "
"(replace, never append; on a resume purge nothing, as execute.md's "
"re-assertion sweep says), then assert again, %s" % (shown, _RE_MERGE_WAITS)
)
def _command_reason(problems: list[str]) -> str:
"""The named reason for a UCG hook command that would not run its script
as preflight writes it. Each problem says what uv or the shell would do
instead; the reason says what that costs under each hook's event."""
return (
"UCG hook command would not run its script as preflight writes it (%s). "
"Claude Code runs a hook command through a shell, which splits it at "
"every unquoted space, so a value or path left unquoted becomes the "
"command the shell runs, or the script uv is given. A guard command "
"that does not start the guard refuses every tool call under its "
"\"onFailure\": \"block\", and one that prints and exits 0 lets every "
"call through unchecked. A budget command the shell cannot start lets "
"each stop through uncounted, and one uv refuses sends each stop back "
"with uv's error, up to eight times in a row, unless the project uv "
"syncs first fails to build, or its requirements cannot be satisfied, "
"when uv exits 1 and each stop goes through uncounted too; a network "
"failure in that sync exits 2, and sends each stop back. Re-merge the hooks as "
"preflight.md step 5's Hooks bullet says, each injected value and the "
"script path in single quotes (KEY='value' uv run '<path>'; replace, "
"never append; on a resume purge nothing, as execute.md's re-assertion "
"sweep says), then assert again, %s" % ("; ".join(problems), _RE_MERGE_WAITS)
)
def _assert_hook_env(project_root: Path) -> dict:
"""Where each injected hook var lives: the hook command string, the process
env, or nowhere. `ok` is all-five-present — a missing var is an invariant
silently enforcing nothing, which is the exact state this mode exists to
surface."""
settings_path = project_root / ".claude" / "settings.local.json"
try:
settings = json.loads(settings_path.read_text(encoding="utf-8"))
commands = [c for _, _, c in _hook_commands(settings)]
except (OSError, ValueError, UnicodeDecodeError):
commands = []
sources: dict[str, str] = {}
for var in HOOK_ENV_VARS:
# Boundary-anchored per command: `X_ULTRACODE_MAX_TURNS=1` must not
# certify ULTRACODE_MAX_TURNS as injected.
pattern = re.compile(r"(^|[\s;\"'`])" + re.escape(var) + "=")
if any(pattern.search(c) for c in commands):
sources[var] = "settings"
elif var in os.environ:
sources[var] = "process"
else:
sources[var] = "absent"
missing = [v for v, s in sources.items() if s == "absent"]
return {"sources": sources, "missing": missing, "ok": not missing}
def _assert_story_skills(project_root: Path) -> dict:
"""The story skills a resumed spawn will delegate to, still installed. A
manual deletion between spawns, or a UCG install or update interrupted
between removing the UCG skills and copying them back, can leave a run
that passed preflight without them."""
installed = _story_skills_installed(project_root)
missing = [s for s, present in installed.items() if not present]
return {"installed": installed, "missing": missing, "ok": not missing}
def _assert_cc_version() -> dict:
"""The Claude Code version a resume runs on, against the minimums a fresh
preflight's cc_version blocker enforces.
Below 2.1.295 Claude Code ignores the guard's `"onFailure": "block"`, so a
run in flight that re-arms on an older one passes every hook check while a
guard that cannot run lets the call through. A version `claude --version`
cannot give is reported with `read: false` and fails nothing: the fresh
preflight read one at launch, and a spawn that `drive_epic.py
--claude-bin` started can lack `claude` on its PATH.
Like the fresh preflight, it runs the `claude` first on PATH, not the
binary that runs the session (nothing documented names that one): with
two installs, or a `--claude-bin` that names another, it reads the one on
PATH. docs/troubleshooting.md says so where the floor is explained.
"""
cc_raw, cc_ver = _cc_version()
below = _below_minimums(cc_ver) if cc_ver is not None else []
return {
"version": cc_raw,
"read": cc_ver is not None,
"minimum": "%d.%d.%d" % max(minimum for _, minimum in _CC_MINIMUMS),
"below": below,
"ok": not below,
}
def _cc_version_reason(version: dict) -> str:
"""The named reason for a Claude Code below the minimums."""
return (
"%s. Claude Code before %s ignores the guard's \"onFailure\": \"block\", "
"so a guard that cannot start, crashes or times out lets the tool call "
"run unchecked, and a fresh preflight refuses to launch below it. A "
"resume does not fix this: updating Claude Code (claude update) is the "
"operator's call, and a session keeps the version it started with. %s"
% (_cc_version_detail(version["version"], version["below"]), version["minimum"], _ESCALATE_FIRST)
)
def _assert_branch(
project_root: Path, epic_branch_prefix: str, protected: tuple[str, ...]
) -> dict:
branch = _git_branch(project_root)
ok = bool(branch) and branch.startswith(epic_branch_prefix) and branch not in protected
return {
"current": branch,
"expected_prefix": epic_branch_prefix,
"protected": list(protected),
"ok": ok,
}
def _mem_common():
"""lib/mem_common.py, imported the way _story_gate_artifacts_present imports
gate_eval: sibling module, path set here, never at module load."""
scripts_dir = str(Path(__file__).resolve().parent)
if scripts_dir not in sys.path:
sys.path.insert(0, scripts_dir)
from lib import mem_common # noqa: PLC0415 (sibling package, path set above)
return mem_common
def _latch_view(data: dict) -> dict:
"""lib/mem_common.py's latch_view(), so this report reads a latch the way
the store module (and, by its parity test, the guard) does."""
return _mem_common().latch_view(data)
def _read_latch(impl_artifacts: Path, run_id: str | None) -> dict:
"""The on-disk recall latch, REPORTED and never certified.
`certifies` is a literal None on purpose: a green manifest must not become an
inherited-latch claim by proxy. Whatever this reports, the resume re-latches
from its own measurement (Stage 1's latch step), and a latch whose run_id is
not this run's is another run's artifact (references/execute.md, resume).
A present latch also reports `latch_version` and the derived `store_ok`
colour of latch v2 (the local run store): true only for a v2 latch whose
store_ok is true with recall on, the jsonl backend and an absolute store
path. A v1 latch, or any other version, reads as red. Both are reporting
only: they never move the exit code, never add a blocker, and `certifies`
stays None.
"""
path = impl_artifacts / ".mem-state.json"
try:
# A FIFO under the latch's name is never opened (that blocks with no
# writer): read_regular_file returns None for anything but a file.
raw = _mem_common().read_regular_file(path)
except OSError:
return {"state": "absent", "certifies": None}
if raw is None:
return {"state": "unreadable", "certifies": None}
try:
data = json.loads(raw.decode("utf-8"))
except (ValueError, RecursionError): # RecursionError: JSON nested too deep
return {"state": "unreadable", "certifies": None}
if not isinstance(data, dict):
# Valid JSON that is not an object is still not a latch; reporting it
# must not crash the manifest (the latch never moves the exit code).
return {"state": "unreadable", "certifies": None}
latch_run = data.get("run_id")
out: dict = {
"state": "present",
"claude_mem": data.get("claude_mem"),
"recall": data.get("recall"),
"run_id": latch_run,
"certifies": None,
}
if run_id is not None:
out["owned_by_this_run"] = latch_run == run_id
view = _latch_view(data)
out["latch_version"] = view["latch_version"]
out["store_ok"] = view["store_ok"]
return out
def _marker_line(path: Path) -> str | None:
try:
return path.read_text(encoding="utf-8").strip() or None
except (OSError, UnicodeDecodeError):
return None
def _tests_ran_baseline(path: Path) -> str | None:
try:
text = path.read_text(encoding="utf-8")
except (OSError, UnicodeDecodeError):
return None
match = re.search(r"^baseline=(.*)$", text, re.MULTILINE)
return match.group(1).strip() if match else None
def _commits_past(project_root: Path, baseline_sha: str) -> int | None:
code, out = _git(["rev-list", "--count", f"{baseline_sha}..HEAD"], project_root)
if code != 0:
return None
try:
return int(out.strip())
except ValueError:
return None
def _story_gate_artifacts_present(trace_output: Path, story: str) -> bool | None:
"""Does a trace/gate-decision artifact resolve for this story? None = unknown.
Resolution identity is imported from gate_eval rather than re-implemented,
so the manifest and the gate cannot disagree about what names a story:
a story-named artifact matches by gate_eval's own stem rule, and in a
directory gate_eval would treat as NOT per-story-named (TEA's untouched
generic output), the generic artifacts count as this story's, exactly as
gate_eval's documented unscoped fallback reads them. An unreadable or
nonexistent directory returns None: unverifiable is never verified-absent.
"""
sys.path.insert(0, str(Path(__file__).resolve().parent))
import gate_eval # noqa: PLC0415 (sibling script, path set above)
if not trace_output.is_dir():
return None
generic_stems = {"-".join(prefix) for prefix in gate_eval._ARTIFACT_PREFIXES}
saw_generic = False
for path in trace_output.iterdir():
if not path.is_file():
continue
stem = path.stem
if stem.startswith(("trace-", "gate-decision-")) and gate_eval._stem_matches_story(
stem, story
):
return True
if stem in generic_stems:
saw_generic = True
if saw_generic and not gate_eval._is_per_story_named(trace_output):
return True
return False
# Typed escalation sidecar kinds that hand work to the next invocation rather
# than ask a human for a decision (references/execute.md, "durable work and
# advanced no row"). A subset of drive_epic.HANDOFF_KINDS, pinned by a test:
# `operator-evidence-owed` is a handoff to the driver but not to a resume,
# which stops on it until /ucg-resolve closes it, since re-driving the story
# cannot record the evidence an operator owes.
_HANDOFF_KINDS = frozenset({"story-decomposed", "defined-not-driven"})
# A legitimate sidecar is four short strings (drive_epic reads it the same way).
_SIDECAR_MAX_BYTES = 64 * 1024
def _red_ids():
"""scripts/red_ids.py, imported the way _mem_common imports lib/mem_common:
sibling module, path set here, never at module load."""
scripts_dir = str(Path(__file__).resolve().parent)
if scripts_dir not in sys.path:
sys.path.insert(0, scripts_dir)
import red_ids # noqa: PLC0415 (sibling script, path set above)
return red_ids
def _sidecar_ids(data: dict, path: Path, project_root: Path) -> list[str]:
"""The ids a /ucg-resolve close of this sidecar may be recorded under.
First the documented one, minted from the sidecar's own `source` field.
Then the same kind and decision minted from the sidecar file's own path,
project-root-relative and absolute, since real closes were keyed that way.
The digest still binds the decision's wording, so none of these can close
another decision. Raises UnicodeError when a field cannot be encoded.
"""
for field in ("source", "kind", "decision_needed"):
data[field].encode("utf-8")
try:
resolved = path.parent.resolve() / path.name
except (OSError, RuntimeError): # RuntimeError: a symlink loop
resolved = path
spellings = [str(path), path.as_posix(), str(resolved), resolved.as_posix()]
for candidate in (path, resolved):
try:
relative = candidate.relative_to(project_root)
except ValueError:
continue
spellings += [relative.as_posix(), str(relative)]
mint = _red_ids().mint_id
ids = [mint(data["kind"], data["source"], data["decision_needed"])]
for spelling in spellings:
minted = mint(data["kind"], spelling, data["decision_needed"])
if minted not in ids:
ids.append(minted)
return ids
def _escalation_of(impl_artifacts: Path, story: str, project_root: Path) -> dict | None:
"""The re-entry story's typed escalation sidecar, read as /ucg-resolve reads it.
None when `escalation-<story>.json` is absent. Otherwise `state` is:
- `open`: a decision nobody has closed. /ucg-resolve deletes the sidecar
when it closes one and leaves it on disk on a `defer`, so presence is
pending, unless the id /ucg-resolve keys the answer by (red_ids.py's,
from the sidecar's own kind, source and decision_needed, or the same
minted from the sidecar's own path; see _sidecar_ids) is closed in
`.decisions.json`: /ucg-resolve never re-asks a closed id, so routing on
that residue would stop the resume on a question no surface offers.
A sidecar that cannot be read is `open` too (fail closed): something
escalated, and nothing here can say it was answered. So is one whose
fields no id can be minted from (a lone surrogate, which parses from a
JSON `\\ud800` escape but encodes to no UTF-8).
- `closed`: present, but one of its ids is closed in `.decisions.json`.
- `handoff`: a `story-decomposed` or `defined-not-driven` sidecar, work
handed to this invocation rather than a decision.
An `open` sidecar also carries `blocker`, the one {source, decision_needed}
pair a headless stop hands the adapter so its `reason` names the sidecar.
"""
path = impl_artifacts / f"escalation-{story}.json"
try:
# A FIFO under the sidecar's name is never opened (that blocks with no
# writer): read_regular_file returns None for anything but a file.
raw = _mem_common().read_regular_file(path, limit=_SIDECAR_MAX_BYTES + 1)
except FileNotFoundError:
if not path.is_symlink():
return None
raw = None # a dangling link under the sidecar's name
except OSError:
raw = None
out: dict = {"path": str(path), "state": "open", "readable": False, "kind": None}
data = None
if raw is not None and len(raw) <= _SIDECAR_MAX_BYTES:
try:
data = json.loads(raw.decode("utf-8"))
except (ValueError, RecursionError): # RecursionError: nested too deep
data = None
fields = ("source", "kind", "decision_needed")
minted: list[str] | None = None
if isinstance(data, dict) and all(isinstance(data.get(f), str) for f in fields):
try:
minted = _sidecar_ids(data, path, project_root)
except UnicodeError:
minted = None
if minted is not None:
out["readable"] = True
out["kind"] = data["kind"]
if data["kind"] in _HANDOFF_KINDS:
out["state"] = "handoff"
else:
out["id"] = minted[0]
decisions = impl_artifacts / ".decisions.json"
try:
closed = _red_ids().closed_ids(decisions) if decisions.is_file() else set()
except Exception: # noqa: BLE001 - an unreadable record closes nothing
closed = set()
if any(rid in closed for rid in minted):
out["state"] = "closed"
if out["state"] == "open":
what = (
"still carries an open escalation (kind %s)" % out["kind"]
if out["readable"]
else "carries an escalation sidecar that cannot be read"
)
out["blocker"] = {
"source": str(path),
"decision_needed": "decision-pending: the re-entry story %s %s; "
"answer it with /ucg-resolve, then resume" % (story, what),
}
return out
# A legitimate re-gate marker is two short lines.
_REGATE_MAX_BYTES = 4 * 1024
# A commit id as git prints one, never a ref name: `sha=HEAD` must not match.
_COMMIT_ID = re.compile(r"[0-9a-f]{7,64}")
def _regate_of(project_root: Path, impl_artifacts: Path, story: str) -> dict | None:
"""The story's `.regate-<story>` marker, which /ucg-resolve writes when it
closes an `operator-evidence-owed` escalation (skills/ucg-resolve/SKILL.md).
It holds `sha=<the assessed commit>` and `decision=<the closed id>`. None
when absent. Otherwise `state` is:
- `fresh`: `sha=` resolves to HEAD, the commit the operator's records were
made at, so the story owes a re-gate of that commit and nothing else.
- `stale`: anything else. A later commit makes the records stale
(references/gate.md), and a marker that cannot be read, or names no
commit id, says nothing about HEAD: the route is then what it would be
without the marker.
"""
path = impl_artifacts / f".regate-{story}"
try:
raw = _mem_common().read_regular_file(path, limit=_REGATE_MAX_BYTES + 1)
except FileNotFoundError:
if not path.is_symlink():
return None
raw = None # a dangling link under the marker's name
except OSError:
raw = None
out: dict = {"path": str(path), "state": "stale", "sha": None, "decision": None}
text = None
if raw is not None and len(raw) <= _REGATE_MAX_BYTES:
try:
text = raw.decode("utf-8")
except UnicodeDecodeError:
text = None
if text is None:
return out
for key in ("sha", "decision"):
match = re.search(r"^%s=(.*)$" % key, text, re.MULTILINE)
if match and match.group(1).strip():
out[key] = match.group(1).strip()
sha = (out["sha"] or "").lower()
if not _COMMIT_ID.fullmatch(sha):
return out
code, named = _git(["rev-parse", "--verify", "-q", sha + "^{commit}"], project_root)
head_code, head = _git(["rev-parse", "--verify", "-q", "HEAD"], project_root)
if code == 0 and head_code == 0 and named and named == head:
out["state"] = "fresh"
return out
def _assert_story(
project_root: Path,
impl_artifacts: Path,
story: str,
trace_output: Path | None,
) -> dict:
"""Classify the resume story by artifacts, never by prose.
Routes mirror the artifact-derived cases of references/execute.md's resume
rule. Its fifth case (a gate stopped between automate and trace) is read
from the story's .decision-log.md, which this script never reads, so it is
the conductor's call: such a story is reported here as gate-owed or
mid-story, and execute.md takes the fifth case instead of either.
- `decision-pending`: the story's escalation-<story>.json is open (see
_escalation_of); it outranks the three below, because driving or
gating the story would act on a decision nobody closed.
- `story-boundary`: no baseline marker — the normal `--max-stories` case;
step 0 writes the baseline fresh.
- `gate-owed`: committed, green and un-gated (commits past the baseline,
a tests-ran marker still matching it, and NO per-story gate artifact) —
enter at step 5. This route REQUIRES --trace-output: with no artifact
evidence the discriminator cannot hold in full, and skipping steps 1-4
on a guess is the fail-open this mode must not introduce. A baselined
story whose `.regate-<story>` is `fresh` (see _regate_of) takes it
too, with or without --trace-output, since the marker and HEAD are its
evidence: /ucg-resolve closed its `operator-evidence-owed` escalation, its
FAIL gate's artifacts are on disk, and it owes a re-gate of HEAD, never
a re-drive that could commit past the operator's records.
- `mid-story`: everything else — re-read the baseline, run the ordinary
loop from step 0.
"""
baseline_path = impl_artifacts / f".baseline-{story}"
marker_path = impl_artifacts / f".tests-ran-{story}"
baseline = _marker_line(baseline_path)
marker_baseline = _tests_ran_baseline(marker_path)
out: dict = {
"id": story,
"baseline": "present" if baseline else "absent",
"tests_ran": "present" if marker_path.is_file() else "absent",
"tests_ran_fresh": bool(baseline) and marker_baseline == baseline,
}
commits = _commits_past(project_root, baseline) if baseline else None
out["commits_past_baseline"] = commits
if trace_output is not None and baseline:
gated = _story_gate_artifacts_present(trace_output, story)
if gated is None:
out["gate_artifacts"] = "unknown"
else:
out["gate_artifacts"] = "present" if gated else "absent"
else:
out["gate_artifacts"] = "unknown"
escalation = _escalation_of(impl_artifacts, story, project_root)
out["escalation"] = escalation
regate = _regate_of(project_root, impl_artifacts, story)
out["regate"] = regate
if escalation is not None and escalation["state"] == "open":
out["route"] = "decision-pending"
elif baseline and regate is not None and regate["state"] == "fresh":
out["route"] = "gate-owed"
elif not baseline:
out["route"] = "story-boundary"
elif (
out["gate_artifacts"] == "absent"
and out["tests_ran_fresh"]
and (commits or 0) > 0
):
out["route"] = "gate-owed"
else:
out["route"] = "mid-story"
return out
def build_assert_armed(
*,
project_root: Path,
impl_artifacts: Path,
epic_branch_prefix: str,
protected: tuple[str, ...],
story: str | None,
run_id: str | None,
trace_output: Path | None,
) -> dict:
branch = _assert_branch(project_root, epic_branch_prefix, protected)
hooks = _assert_hooks(project_root)
hook_env = _assert_hook_env(project_root)
skills = _assert_story_skills(project_root)
cc_version = _assert_cc_version()
checks: dict = {
"branch": branch,
"hooks": hooks,
"hook_env": hook_env,
"skills": skills,
"cc_version": cc_version,
"latch": _read_latch(impl_artifacts, run_id),
# Reported, never a reason to fail: a resumed session has no step-1
# report, and execute.md's ignored-tree rule keys on this fact.
"impl_artifacts_tracked": _impl_artifacts_tracked(project_root, impl_artifacts),
}
if story:
checks["story"] = _assert_story(project_root, impl_artifacts, story, trace_output)
# The reasons that are the operator's to fix come first: the sweep
# escalates them before it fixes any other, and a conductor reads the
# first reason first.
reasons: list[str] = []
if not skills["ok"]:
reasons.append(
"%s On a resume, installing them is the operator's call. %s"
% (_story_skills_detail(project_root, skills["missing"]), _ESCALATE_FIRST)
)
if not cc_version["ok"]:
reasons.append(_cc_version_reason(cc_version))
if not branch["ok"]:
reasons.append(
"branch %r is not an epic branch under prefix %r (or is protected)"
% (branch["current"], epic_branch_prefix)
)
if not hooks["ok"]:
if not hooks["settings_readable"]:
reasons.append("settings.local.json is missing or unreadable; hooks NOT armed")
if not hooks["guard_present"]:
reasons.append("PreToolUse guard (guard_pretooluse.py) not armed")
if not hooks["budget_present"]:
reasons.append("Stop budget hook (budget_stop.py) not armed")
if hooks["guard_present"] and not hooks["matcher_all_tools"]:
reasons.append(
"PreToolUse matcher is not the all-tools form; the recall "
"invariant enforces nothing (preflight.md step 5)"
)
if hooks["guard_present"] and not hooks["guard_on_failure_block"]:
reasons.append(_on_failure_reason(hooks["guard_on_failure"]))
if hooks["command_problems"]:
reasons.append(_command_reason(hooks["command_problems"]))
if not hook_env["ok"]:
reasons.append(
"hook env not fully injected; enforcing hardcoded fallbacks for: %s"
% ", ".join(hook_env["missing"])
)
armed = branch["ok"] and hooks["ok"] and hook_env["ok"] and skills["ok"] and cc_version["ok"]
return {"armed": armed, "checks": checks, "reasons": reasons}
def _resolve(path_arg: str, project_root: Path) -> Path:
"""Expand a possible {project-root} token and resolve relative to project_root."""
resolved = path_arg.replace("{project-root}", str(project_root))
path = Path(resolved)
return path if path.is_absolute() else (project_root / path)
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(
description="Mechanical preflight for an UltraCode-Goal epic run "
"(use --rollup for the Stage 1 per-Epic story-status summary)."
)
parser.add_argument("--project-root", required=True)
parser.add_argument(
"--rollup",
action="store_true",
help="Emit only the per-Epic story-status summary parsed from "
"sprint-status.yaml (Stage 1 scope selection). When set, --epic, "
"--tea-config, and --protected-branch are not required and the "
"mechanical preflight checks do not run.",
)
# Required only in the normal (non-rollup) mode; validated manually below so
# rollup mode can omit them. --impl-artifacts is required in both modes.
parser.add_argument("--epic")
parser.add_argument("--tea-config")
parser.add_argument("--impl-artifacts", required=True)
parser.add_argument(
"--protected-branch",
action="append",
default=None,
help="Protected branch name; repeatable. Defaults to main, master.",
)
parser.add_argument(
"--profile",
choices=PROFILES,
default="production",
help="Normal mode only: the run profile, which picks the TEA skills "
"the check requires (production needs all eight bmad-testarch-* "
"skills UCG can call, light needs framework, test-design and trace). "
"Defaults to production.",
)
parser.add_argument(
"--assert-armed",
action="store_true",
help="Emit only the resume manifest: branch, hooks (incl. the all-tools "
"matcher, the guard's \"onFailure\": \"block\", and each hook command "
"splitting into <env> uv run <script>), injected hook env, "
"the UCG story "
"skills (ucg-create-story, ucg-dev-story), the Claude Code version "
"(claude --version, against the minimums the cc_version blocker "
"enforces), the recall latch "
"(reported, never certified), and, with --story, the story's "
"artifact-derived resume route. Exit 0 iff branch+hooks+env+skills are "
"armed and the version is not below a minimum (one it cannot read "
"fails nothing). When set, --epic, --tea-config, and the other "
"mechanical preflight checks do not run.",
)
parser.add_argument(
"--story",
help="assert-armed only: the story the resume will drive; adds the "
"artifact-derived route (decision-pending / story-boundary / mid-story / "
"gate-owed), the story's escalation sidecar state and its re-gate "
"marker state.",
)
parser.add_argument(
"--run-id",
help="assert-armed only: this run's id, for reporting whether the "
"on-disk latch is owned by this run (reported, never certified).",
)
parser.add_argument(
"--trace-output",
help="assert-armed only: the per-story trace artifacts dir; required "
"evidence for the gate-owed route (without it that route never fires).",
)
parser.add_argument(
"--epic-branch-prefix",
default=os.environ.get("ULTRACODE_EPIC_BRANCH_PREFIX", "ultracode/epic-"),
help="assert-armed only: the resolved epic branch prefix. Defaults to "
"$ULTRACODE_EPIC_BRANCH_PREFIX, then the shipped default.",
)
args = parser.parse_args(argv)
# Preserve the normal-mode contract: --epic and --tea-config are required
# unless --rollup is in effect. parser.error() reproduces argparse's usage
# line + "error:" message and exits 2, exactly as required=True did.
if not args.rollup and not args.assert_armed:
missing = [
name
for name, value in (("--epic", args.epic), ("--tea-config", args.tea_config))
if value is None
]
if missing:
parser.error(
"the following arguments are required: %s" % ", ".join(missing)
)
project_root = Path(args.project_root).expanduser()
if not project_root.is_dir():
print(
json.dumps({"error": "project-root not found: %s" % project_root}),
file=sys.stderr,
)
return 2
project_root = project_root.resolve()
impl_artifacts = _resolve(args.impl_artifacts, project_root)
if args.rollup:
rollup = build_rollup(project_root=project_root, impl_artifacts=impl_artifacts)
print(json.dumps(rollup, indent=2))
return 0
if args.assert_armed:
manifest = build_assert_armed(
project_root=project_root,
impl_artifacts=impl_artifacts,
epic_branch_prefix=args.epic_branch_prefix,
protected=tuple(args.protected_branch)
if args.protected_branch
else DEFAULT_PROTECTED,
story=args.story,
run_id=args.run_id,
trace_output=_resolve(args.trace_output, project_root)
if args.trace_output
else None,
)
print(json.dumps(manifest, indent=2))
return 0 if manifest["armed"] else 1
tea_config = _resolve(args.tea_config, project_root)
protected = tuple(args.protected_branch) if args.protected_branch else DEFAULT_PROTECTED
report = build_report(
project_root=project_root,
epic=args.epic,
tea_config=tea_config,
impl_artifacts=impl_artifacts,
protected_branches=protected,
profile=args.profile,
)
print(json.dumps(report, indent=2))
return 0
if __name__ == "__main__":
sys.exit(main())
Related skills
| Skill | Stars | Updated | Works with | Status | Install |
|---|---|---|---|---|---|
| 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: 198k | Updated | Claude CodeCodex | Verified | Install |
| 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: 194k | Updated | Claude CodeCodex | Verified | Install |
| ponytail-debtDietrichGebert/ponytailHarvest every shortcut: comment into one debt ledger, so deferrals get tracked instead of forgotten. One-shot report. | Stars: 194k | Updated | Claude CodeCodex | Verified | Install |
| 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: 194k | Updated | Claude CodeCodex | Verified | Install |