diff --git a/README.md b/README.md index 4cfa589..76d32e0 100644 --- a/README.md +++ b/README.md @@ -23,6 +23,9 @@ sequencing**. Forge gives you: carry from one repo to the next, so your mistake rate drops over time. - **A dynamic workflow engine** — run arbitrary **parallel agent DAGs** beyond the fixed pipeline, opt-in (new in v0.4.0). +- **Docker and tooling preflight** — advisory Docker hygiene checks and a declarative CLI + registry (`docker`, `gh`, …) that detects what's missing and offers to install it, only + after you confirm (new in v0.7.0). Nothing advances silently and nothing is untraceable. When you *do* need to skip a gate, `/forge:force-advance` records **why** — the override is explicit and audited. @@ -343,6 +346,7 @@ See [`references/daemon-bus.md`](references/daemon-bus.md). | `/forge:status` | Current stage, task, blockers, daemon status, recent history | | `/forge:resume` | Restore context after a session restart | | `/forge:doctor` | Diagnose environment / plugin / gate health and name the fix | +| `/forge:preflight` | Detect missing required CLIs (docker, docker compose, gh) and offer to install one, only after you confirm — see [`references/docker-and-tooling.md`](references/docker-and-tooling.md) | | `/forge:why` | Explain a gate criterion, lesson tag, stage, or current blocker | | `/forge:retro` | Cycle-completion retrospective after Stage 12 | | `/forge:set-profile` | Set the project-type profile | diff --git a/ROADMAP.md b/ROADMAP.md index aad5611..28d716d 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -167,6 +167,7 @@ producing all 12 stage artifacts with traceability intact. ✅ | **v0.5.0** | 🟢 released | **Unified `~/.forge` graduation layer** — generalizes the T-022 lesson promoter into one tier-agnostic core (`scripts/_graduation.py`: registry · atomic IO · 30-day TTL · idempotent keyed merge · `Tier` protocol · fail-soft `graduate()` driver), then adds **skills** and **workflows** tiers behind **per-tier gates** (breadth for lessons; approved + ExpeL `weight>0` + `use≥2` for skills; validates-clean + ≥2 successful `workflow_run` records for workflows). **Project-wins** recall in every tier; skill recall = **symlink** (ADR-009), workflows recall via the loader search path. Automatic, silent, fail-soft at session-start (`FORGE_NO_GRADUATE=1` escape); new `/forge:graduate` (dry-run / list / scan). Behavior-preserving for lessons. ADR-008 + ADR-009. Tag `v0.5.0`, both remotes. SRS `build/01-srs/srs-v0.5.0.md`, DAG `build/04-plan/task-dag-v0.5.0.md` (T-207–T-213). | | **v0.6.0** | 🟢 released | **Engine made real I — per-node session reuse** (cost-reduction, **zero default behavior change**). Drives the already-built-but-unused `_background_agent.dispatch(resume=...)` path from the v0.4.0 DAG engine: capture each node's first-attempt `session_id` and `--resume` it into **that same node's** retry/heal re-dispatches (same prompt + model), lowering their realized floor from `FRESH_FLOOR_USD` `$0.06` to `RESUME_FLOOR_USD` `$0.01`. **Within-node only**; the independent verifier is **never** reused (REQ-WF-002); admission stays on `FRESH_FLOOR_USD` so the estimator/admitted-set split is identical on vs off (AC-WF-014); a stale session **falls back to fresh** within the attempt budget. Opt-in `orchestration.session_reuse` (strict `is True`, default off ⇒ byte-identical to v0.4.x). ADR-010. **Deferred follow-ups**: per-branch/cross-node reuse (trio item 1's other half, measurement-gated), trio items 2–3 (top-level generation · pipeline-as-WorkflowSpec), and **caveman mode** (orthogonal prompt-compression, candidate v0.6.1). ADR-010. Tag `v0.6.0`, both remotes. SRS `build/01-srs/srs-v0.6.0.md`, DAG `build/04-plan/task-dag-v0.6.0.md` (T-214–T-219). | | **v0.6.1** | 🟢 released | **Caveman mode — measured and rejected; static prompt tightening only** (**zero default behavior change**). Investigated the `caveman` token-reduction approach: the one stdlib-legal lever (a terse-output preamble at the dispatch chokepoint) was built behind a default-off `orchestration.caveman_mode` toggle and **measured** against the `_cost_cap` output-token ledger — a real before/after on the Dreamer free-prose prompt (`haiku`, N=5/arm) showed **mean −52.9%**, no saving, well under the REQ-CM-005 ≥10% gate (Forge's free-prose prompts are already length-bounded). Per the gate the **runtime toggle was dropped** (config + `_caveman.py` + wiring reverted; dispatch byte-identical to v0.6.0); v0.6.1 ships only the **deterministic static tightening** of verbose non-verdict prompt constants (`dreamer`/`autopilot`/`parallel_build`) — verify/skeptic/gate/observer untouched. The measurement gate worked as designed. ADR-011. Tag `v0.6.1`, both remotes. SRS `build/01-srs/srs-v0.6.1.md`, DAG `build/04-plan/task-dag-v0.6.1.md` (T-220–T-226). | +| ~~v0.7.0~~ | ⚪ folded | **Docker workflow enforcement + extensible tooling preflight** (fail-soft, never-block) — a declarative tool registry (`references/tool-registry.md`) + `scripts/tool_preflight.py` (detect via `shutil.which` + version probe, cached like the capability probe), an advisory `scripts/check_docker_readiness.py` wired **unconditionally** into `/forge:deploy` (cross-cutting — every project gets it, regardless of profile), the sole confirm-then-install surface `/forge:preflight`, and an opt-in `docker` profile (never auto-assigned over a real app type). ADR-012. Built as T-227–T-233 but **folded into the v0.8.0 release** alongside Builder Pro rather than tagged separately. SRS `build/01-srs/srs-v0.7.0.md`, DAG `build/04-plan/task-dag-v0.7.0.md`. | --- diff --git a/build/02-architecture/adr/012-docker-and-tooling.md b/build/02-architecture/adr/012-docker-and-tooling.md new file mode 100644 index 0000000..1fa77fa --- /dev/null +++ b/build/02-architecture/adr/012-docker-and-tooling.md @@ -0,0 +1,111 @@ +# ADR-012: Docker Workflow Enforcement — Cross-Cutting Handling + an Opt-In Profile, Advisory and Never-Blocking, with a Declarative Tool Registry + +**Status**: Accepted +**Date**: 2026-06-24 + +## Context + +Forge can manage a containerized project, but until now had no awareness of Docker as a +workflow: no check that a project's `Dockerfile`/compose is hygienic (pinned base image, +healthcheck, non-root user, `.dockerignore`), and no verification that the CLIs a workflow +needs — `docker`, `docker compose`, `gh` for git/GitHub flows — are actually installed. A user +could hit a wall at the deploy or release stage because a required tool was missing, with no +early signal and no guided install. There was also no first-class way to tell Forge "this is a +Docker project." + +Two constraints bound the design, both confirmed against the code before implementation: + +1. **Docker is orthogonal to the profile cascade.** `scripts/detect-project-type.py:detect()` + returns exactly one mutually-exclusive `type`, so a containerized FastAPI app classifies as + `api`. A literal "9th docker profile" in the auto-detect cascade would only ever fire for + pure-infra repos — the common "app that ships a container" case would get **no** Docker + treatment. Docker handling must therefore be **cross-cutting**, not gated on a profile. +2. **Hooks run non-interactively.** A hook can detect a missing tool and surface a message, but + it cannot pop an installer. Running an install (`brew`/`apt`/`winget`) must happen in a + **skill turn** where the user can confirm. So detection and offering-to-install are separate + surfaces. + +## Decision + +**Ship a fail-soft, never-block Docker-and-tooling layer**: a declarative, extensible tool +registry with detection cached like the existing capability probe; an advisory Docker hygiene +check wired cross-cutting into deploy; and an opt-in `docker` profile that never auto-overrides +a real app type. + +Four load-bearing decisions: + +- **Cross-cutting, not a mutually-exclusive profile.** Because `detect()` returns one type and + Docker is orthogonal, Docker hygiene + tool checks attach to **any** project — via the + self-no-op'ing `scripts/check_docker_readiness.py` run unconditionally at deploy + (`skills/forge-deploy/SKILL.md`), and the tool registry's `docker_artifacts_present` + condition — rather than only to a `docker`-typed project. The `docker` profile + (`references/project-type-profiles.md`) is an **opt-in overlay** (stage emphasis + the + advisory hygiene criterion) and a **suggestion-only** hint from `detect-project-type.py` + (`suggested_profile: "docker"`, only when the type is otherwise `unknown` and Docker + dominates) — it never auto-overrides a real app type. +- **Advisory, never block.** The hygiene check is **agent-surfaced** (the deploy skill relays + its `WARN:` lines, and the profile's `additional_criteria` entry documents the concern for + the stage agent), **not** a mechanical `gate-criteria.md` entry — so it can never fail a gate. + `check_docker_readiness.py` exits 0 even when it finds problems. +- **Detect in a hook; install in a skill.** `hooks/session-start.py` and `scripts/doctor.py` + only ever detect and report a missing tool. `skills/forge-preflight/SKILL.md` is the **sole** + surface that runs an installer, and only after the user explicitly confirms which tool to + install. Auto-install was considered and rejected. +- **Declarative + extensible registry.** Tools live as data in + `references/tool-registry.md` — adding a new required CLI is a registry entry, not new code. + The detection/cache/TTL machinery reuses the capability-probe pattern + (`hooks/_background_agent.py`: `shutil.which` + `.forge/*.json` + 24h TTL + detached refresh, + T-138) rather than inventing a second one. + +## Rationale + +1. **The common case gets coverage without misclassification.** Cross-cutting hygiene means a + Dockerized FastAPI app is checked for Docker hygiene *and* still gets the `api` profile's + spec/eval treatment — neither is sacrificed for the other. +2. **Nothing in this layer can regress an existing project.** Every script here is fail-soft and + exits 0; a project with no Docker artifacts and all tools present is byte-identical in + behavior to the pre-v0.7.0 baseline (no advisory output, no new blocking path). +3. **Consent before any install.** The non-interactive/interactive split (detect in a hook, + install only in a confirmed skill turn) is the only way to offer installs without ever running + a command the user hasn't seen and approved. +4. **One detection pattern, not two.** Reusing the capability-probe's cache/TTL/detached-refresh + shape for tool status keeps the hot-path cost (a session-start hook read) identical in kind to + an already-shipped, already-measured pattern. + +## Alternatives considered + +- **A literal 9th cascade profile (`docker` as a mutually-exclusive `type`).** Rejected: would + only fire for pure-infrastructure repos with no other signal; the common "app that ships a + container" case (a Dockerized API, a Dockerized fullstack app) would get no Docker treatment + at all, since `detect()`'s cascade already classifies those as `api`/`fullstack`. + A hybrid two-path design was also considered and rejected as YAGNI for the rare pure-infra + repo — the cross-cutting-plus-opt-in-overlay shape already covers it. +- **Auto-installing missing tools without confirmation.** Rejected during brainstorming — running + an installer non-interactively on a user's machine without consent is unacceptable regardless + of how the tool was detected as missing. +- **A mechanical, blocking Docker gate in base `gate-criteria.md`.** Rejected: this release's + Docker hygiene is explicitly advisory; a hard-coded blocking entry there would fail every + containerized project on day one for issues the user may not be ready to fix yet, contradicting + the never-block decision the rest of this layer is built around. +- **Generating Dockerfiles/compose/CI as the mandatory deploy output.** Not chosen — the deploy + agent may still author them, but Forge does not enforce a generated containerized deploy path + as part of this layer. + +## Consequences + +- New: `references/tool-registry.md` (declarative registry), `scripts/tool_preflight.py` + (detection + `.forge/tool-status.json` cache), `scripts/check_docker_readiness.py` (advisory + hygiene), `skills/forge-preflight/SKILL.md` (the sole install surface). +- Changed: `scripts/doctor.py` gains `check_required_tools`; `hooks/session-start.py` gains a + budget-aware tool advisory (dropped first under token pressure, ahead of lessons/rules — a + stricter budget posture than the existing capability/health/traceability notes, which are not + currently budget-counted); `skills/forge-deploy/SKILL.md` runs the hygiene check + unconditionally; `scripts/detect-project-type.py` emits `has_docker`/`docker_indicators` and + a `docker` suggestion hint; `references/project-type-profiles.md` gains `## Profile: docker`. +- Out of scope (recorded, not silently dropped): running agents **inside** Docker containers + (sandboxed execution — a separate, larger track, closest to the existing `worktree_isolation` + toggle); auto-installing tools without confirmation; a mechanical/blocking Docker gate; the + engine trio (`build/01-srs/srs-v0.6.0.md` §6) and the standing non-goals + (`build/01-srs/srs-v0.4.1.md` §5.4) — unchanged. +- See `references/docker-and-tooling.md` for the user-facing reference on the registry format, + the required-tool resolution rules, and the advisory hygiene checks. diff --git a/build/05-implementation/decisions.md b/build/05-implementation/decisions.md index 545f734..0228ce4 100644 --- a/build/05-implementation/decisions.md +++ b/build/05-implementation/decisions.md @@ -24,6 +24,51 @@ ## Decisions +## 2026-08-10 T-233 — Docker/tooling: cross-cutting handling + opt-in profile (ADR-012); v0.7.0 folded into v0.8.0 + +**Context**: Forge had no Docker workflow awareness — no hygiene check on `Dockerfile`/ +compose, no verification that `docker`/`gh` were installed before a workflow needed them. +`detect-project-type.py:detect()` returns exactly one mutually-exclusive `type`, so a +literal 9th "docker" cascade profile would only ever fire for pure-infra repos — a +Dockerized FastAPI app would still classify as `api` and get no Docker treatment. +Separately, the user asked to complete v0.7.0 and release it together with the +already-merged v0.8.0 Builder Pro work rather than as its own tag. + +**Decision**: Cross-cutting Docker handling (an advisory `check_docker_readiness.py` run +**unconditionally** at deploy, self-no-op without artifacts) plus an **opt-in** `docker` +profile that is suggestion-only and never auto-assigned over a real app type. A +declarative tool registry (`references/tool-registry.md`) + `tool_preflight.py` reuse the +existing capability-probe cache pattern (T-138); the only installer surface is +`/forge:preflight`, gated on explicit per-tool confirmation. v0.7.0 (T-227–T-233) is +**folded into the v0.8.0 release** rather than tagged separately — same precedent as +v0.3.2 folding into v0.3.3. + +**Why**: Cross-cutting handling covers the common "app that ships a container" case +without misclassifying it; a mutually-exclusive profile would have missed it entirely. +Advisory-only (the hygiene script always exits 0) keeps the never-block guarantee that +every prior release in this program has held. Detect-in-a-hook / install-in-a-skill is the +only way to offer an install without ever running a command the user hasn't confirmed. +Folding the two versions into one release avoids a near-immediate second version bump for +work that landed in the same sitting. + +**Alternatives considered**: A literal 9th cascade profile — rejected, would miss the +common containerized-app case. Auto-installing missing tools — rejected outright during +2026-06-24 brainstorming. A mechanical blocking gate in base `gate-criteria.md` for Docker +hygiene — rejected, contradicts the advisory/never-block design this layer is built +around. Tagging v0.7.0 separately before v0.8.0 — rejected per explicit user direction; +folding avoids churn for two versions released in the same sitting. + +**Consequences**: New `references/tool-registry.md`, `scripts/tool_preflight.py`, +`scripts/check_docker_readiness.py`, `skills/forge-preflight/SKILL.md`. Changed: +`scripts/doctor.py` (`check_required_tools`), `hooks/session-start.py` (tool advisory, +dropped first under token pressure), `skills/forge-deploy/SKILL.md` (unconditional hygiene +check), `scripts/detect-project-type.py` (`has_docker`/`docker_indicators` + docker +suggestion), `references/project-type-profiles.md` (`## Profile: docker`). ADR-012. +`ROADMAP.md` marks v0.7.0 `⚪ folded`; the next release ships as **v0.8.0** covering both +Builder Pro (T-241–T-253) and this Docker/tooling layer (T-227–T-233). + +--- + ## 2026-06-24 T-224 — Caveman runtime toggle DROPPED by the measurement gate; ship only static tightening **Context**: v0.6.1 added an opt-in `orchestration.caveman_mode` that prepends a terse-output preamble diff --git a/build/05-implementation/progress.md b/build/05-implementation/progress.md index c2c3b7d..8dc0bc6 100644 --- a/build/05-implementation/progress.md +++ b/build/05-implementation/progress.md @@ -5,6 +5,35 @@ ## Current State +- **v0.7.0 (Docker workflow enforcement + tooling preflight) COMPLETE — T-227..T-233.** + Fail-soft, never-block capability layer, orthogonal to the Builder Pro work below (no + shared files). M1 Detection core: T-227 `references/tool-registry.md` (declarative, + seeded `docker`/`docker compose`/`gh`) + `scripts/tool_preflight.py` (shutil.which + + optional version_probe, `.forge/tool-status.json` 24h-TTL cache, mirrors the T-138 + capability-probe pattern) — 21 tests. T-228 `scripts/check_docker_readiness.py` + (advisory hygiene: pinned base image, HEALTHCHECK, non-root USER, `.dockerignore`, + compose parse+`services:` — always exits 0, even with findings) — 13 tests. M2 + Surfacing: T-229 `doctor.py` `check_required_tools` (one warn per missing required + tool, install command as `fix`) — 5 tests. T-230 `session-start.py` tool advisory + (budget-aware, dropped **first** under token pressure, ahead of lessons/rules — a + stricter posture than the existing capability/health/traceability notes) — 10 tests. + T-231 `skills/forge-preflight/SKILL.md` (`/forge:preflight` — the sole surface that + runs an installer, only after per-tool user confirmation) — 6 tests. T-232 `## + Profile: docker` (opt-in, stage_3/8/9 overrides, never auto-assigned) + + `forge-deploy/SKILL.md` unconditional hygiene wiring + `detect-project-type.py` + `has_docker`/`docker_indicators`/`suggested_profile: docker` (FastAPI-in-Docker stays + `api`) — 23 tests across 5 files. T-233 (this entry): ADR-012, `references/ + docker-and-tooling.md`, README (`/forge:preflight` row + capability bullet), ROADMAP + (v0.7.0 marked `⚪ folded` into v0.8.0), `decisions.md`. Full unit suite **2017 pass** + (baseline 1949 → +68 across T-227..T-232), `validate-plugin.py` exit 0. **Per user + direction: v0.7.0 is not tagged separately — it ships as part of the next release, + v0.8.0, alongside Builder Pro below.** SRS `build/01-srs/srs-v0.7.0.md`, DAG + `build/04-plan/task-dag-v0.7.0.md`. Worktree `.claude/worktrees/ + recursive-wobbling-sky`, branch `feat/v0.7.0-docker-tooling`, branched from + `develop` (`4f74d32`). **NEXT**: full regression sweep (`full-pipeline.sh`), open the + PR against `develop`, then the combined v0.8.0 release (bump-version, CHANGELOG, + tag, both remotes). + - **v0.8.0 Revision 2 (Builder Pro) COMPLETE — T-241..T-253.** Revision 1 below (T-235..T-240) was scoped from a secondary analysis doc and got the shape wrong (three LLM sub-agent personas instead of one thin-router agent + a deterministic diff --git a/hooks/session-start.py b/hooks/session-start.py index 24ec113..450c4de 100755 --- a/hooks/session-start.py +++ b/hooks/session-start.py @@ -102,6 +102,59 @@ def _ensure_capabilities(cwd: Path) -> None: return +_TOOL_TTL_SECONDS = 86400 # re-probe registry tools at most once/day, same TTL as the capability probe + + +def _ensure_tool_status(cwd: Path) -> None: + """Keep .forge/tool-status.json fresh without blocking (REQ-TR-004). + + Mirrors _ensure_capabilities: this hook only ever reads the cached file — the + actual shutil.which + version-probe detection is offloaded to a detached + `tool_preflight.py refresh` subprocess, fired only when the cache is missing + or older than the TTL. Never raises. + """ + if os.environ.get("FORGE_NO_BACKGROUND") == "1": + return # kill switch — no background work at all (also keeps tests hermetic) + forge = cwd / ".forge" + status_file = forge / "tool-status.json" + try: + if status_file.exists() and (time.time() - status_file.stat().st_mtime) < _TOOL_TTL_SECONDS: + return # fresh enough + subprocess.Popen( + [sys.executable, str(_PLUGIN_DIR / "scripts" / "tool_preflight.py"), + "refresh", "--forge-dir", str(forge), "--cwd", str(cwd)], + stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, + start_new_session=True, + ) + except Exception: # noqa: BLE001 — tool-status upkeep must never break startup + return + + +def _tool_preflight_block(cwd: Path) -> str: + """One advisory line per missing **required** tool, read from the cached + .forge/tool-status.json (stdlib only — detection runs detached, never + inline in this hook). '' when nothing is missing, outside a Forge project, + or the cache is absent/unreadable (REQ-TR-004). Never raises. + """ + path = cwd / ".forge" / "tool-status.json" + try: + if not path.exists(): + return "" + data = json.loads(path.read_text()) + except (OSError, ValueError): + return "" + if not isinstance(data, dict): + return "" + lines = [] + for name, status in data.items(): + if name.startswith("_") or not isinstance(status, dict): + continue # metadata key (_checked_at) or malformed entry + if status.get("required") and not status.get("present"): + reason = status.get("reason", "") + lines.append(f"[Forge] ⚠ Required tool `{name}` not found ({reason}) — run /forge:preflight") + return "\n".join(lines) + + def _unread_findings_note(cwd: Path) -> str: """One-line note when the Observer (T-142) has left **unread** findings; '' otherwise. @@ -396,6 +449,7 @@ def _compose( design: str, gate: str, rules_text: str = "", + tool_text: str = "", ) -> str: stage = state.get("current_stage", 0) stage_name = STAGE_NAMES.get(stage, "unknown") @@ -430,6 +484,9 @@ def _compose( if gate: lines.append(f"[Forge] Next gate criteria: {gate}") + if tool_text: + lines.append(tool_text) + return "\n".join(lines) @@ -477,6 +534,7 @@ def run(cwd: Path, session_id: str = "", source: str = "") -> Optional[str]: _sync_lessons_if_stale(cwd) _register_and_promote(cwd) _ensure_capabilities(cwd) # REQ-F-001 — refresh the cached capability probe + _ensure_tool_status(cwd) # REQ-TR-004 — refresh the cached tool-status probe _poll_observer_if_running(cwd) # REQ-F-008 — lazy Observer poll, detached # Lessons: up to 5 project-level + 3 global @@ -498,15 +556,20 @@ def run(cwd: Path, session_id: str = "", source: str = "") -> Optional[str]: gate = _gate_summary(_PLUGIN_DIR, stage) rules_text = _rules_block(cwd, stage) - context = _compose(state, lessons, design, gate, rules_text) + tool_text = _tool_preflight_block(cwd) + context = _compose(state, lessons, design, gate, rules_text, tool_text) - # Enforce token budget (REQ-NF-011): trim lessons first, then drop rules as a - # last resort, so the block always stays within budget. + # Enforce token budget (REQ-NF-011, REQ-TR-004/AC-TR-003): drop the tool + # advisory first, then trim lessons, then drop rules as a last resort, so + # the block always stays within budget. + if _token_estimate(context) > _MAX_TOKENS: + tool_text = "" + context = _compose(state, lessons, design, gate, rules_text, tool_text) if _token_estimate(context) > _MAX_TOKENS: lessons = lessons[:2] - context = _compose(state, lessons, design, gate, rules_text) + context = _compose(state, lessons, design, gate, rules_text, tool_text) if _token_estimate(context) > _MAX_TOKENS: - context = _compose(state, lessons, design, gate, "") + context = _compose(state, lessons, design, gate, "", tool_text) # REQ-F-012: surface unread Observer findings; REQ-F-026: Health auto-disable alert context += _unread_findings_note(cwd) diff --git a/references/docker-and-tooling.md b/references/docker-and-tooling.md new file mode 100644 index 0000000..d741297 --- /dev/null +++ b/references/docker-and-tooling.md @@ -0,0 +1,71 @@ +# Docker and Tooling (v0.7.0) + +A fail-soft, never-block capability layer: a declarative tool registry + preflight +(detect missing CLIs, offer to install in a confirmed skill turn, never auto-run), an +advisory Docker hygiene check wired cross-cutting into deploy, and an opt-in `docker` +profile. See ADR-012 for the full design rationale. + +## Tool Registry (`references/tool-registry.md`) + +Declares each external CLI Forge workflows may need as a YAML data entry — `name`, +`which` (binary), an optional `version_probe` (to confirm a specific capability, not +just the binary — e.g. the `docker compose` plugin), `required_when` +(`always` | `docker_artifacts_present` | `release_stage`), and per-OS `install` +commands. Adding a new required tool ("gh or anything required") is a registry entry, +not new code. + +## Detection (`scripts/tool_preflight.py`) + +Pure, never-raising detection: `shutil.which` plus the optional version probe, cached +to `.forge/tool-status.json` with a 24h TTL and a detached refresh — the same pattern +`hooks/_background_agent.py` already uses for the background-capability probe (T-138). +`required_when` is resolved against project state (`docker_artifacts_present` walks the +tree for Docker artifacts; `release_stage` reads `pipeline/state.md`'s +`current_stage`). The CLI (`check` / `install` / `refresh`) never runs an install +command — `install` only ever returns the resolved string. + +## Surfacing + +- **`hooks/session-start.py`** injects one advisory line per missing required tool, + read from the cache with stdlib only. It is the first thing dropped under token + pressure — ahead of lessons and rules — and stays silent when nothing is missing, + outside a Forge project, or the cache is unreadable. +- **`scripts/doctor.py`** reports one `warn`-level result per missing required tool + with the install command as the fix. Doctor stays read-only. + +## Installing (`/forge:preflight`) + +The **only** surface that runs an installer. It shows each missing required tool's +exact per-OS install command and runs it via Bash only after the user explicitly +confirms that specific tool. A declined tool is never installed. + +## Docker Hygiene (`scripts/check_docker_readiness.py`) + +Advisory only — it exits 0 whether or not Docker artifacts are present, and exits 0 +even when it reports findings. Checks, per `Dockerfile` found: the base image is +pinned (a digest pin or a reference to an earlier build stage both count; an untagged +or `:latest` registry image doesn't), a `HEALTHCHECK` instruction is present, and the +last `USER` directive isn't root. Project-level: `.dockerignore` exists, and each +compose file parses with a top-level `services:` key. + +`skills/forge-deploy/SKILL.md` runs this check **unconditionally** in pre-flight — +every project gets it, regardless of profile, since the check self-no-ops without +Docker artifacts. Findings are relayed as advisory `WARN:` notes; they never block +deployment. + +## The `docker` Profile + +An opt-in overlay (`references/project-type-profiles.md`, `## Profile: docker`) — +select it with `/forge:set-profile docker`, or accept the suggestion +`detect-project-type.py` offers when a project has Docker artifacts and no other +profile matched. **Never auto-assigned** over a real app type: a Dockerized FastAPI +service still classifies as `api` and still gets the cross-cutting hygiene check — +the profile only adds architecture/deploy emphasis and the `G8-DOCKER-001` advisory +criterion on top. + +## Out of Scope + +Running agents **inside** Docker containers (sandboxed execution — a separate, +larger track); auto-installing tools without confirmation; a mechanical/blocking +Docker gate in base `references/gate-criteria.md`; generating Dockerfiles/compose/CI +as Forge's mandatory deploy output. diff --git a/references/project-type-profiles.md b/references/project-type-profiles.md index 137c1b8..acee799 100644 --- a/references/project-type-profiles.md +++ b/references/project-type-profiles.md @@ -620,6 +620,50 @@ stage_overrides: --- +## Profile: docker + +```yaml +name: docker +description: Opt-in overlay for any containerized project. Docker handling is + cross-cutting — check_docker_readiness.py runs unconditionally at deploy for + every project regardless of profile — so this profile is never required to + get that coverage. Select it explicitly (/forge:set-profile docker) or + accept the suggestion when Docker artifacts dominate an otherwise-unknown + project. Never auto-assigned over a real app type (a Dockerized FastAPI + service stays `api`). + +stage_emphasis: + high: [architecture, deploy] + low: [] + +stage_overrides: + stage_3: + additional_concerns: + - "Multi-stage build strategy" + - "Base image and version pinning strategy" + - "Build secrets and volume handling" + - "Layer caching strategy" + + stage_8: + additional_steps: + - "Build the image(s)" + - "Scan the image(s) for known vulnerabilities" + - "Push to the target registry" + additional_criteria: + - id: G8-DOCKER-001 + description: Docker hygiene check passes (pinned base image, HEALTHCHECK, non-root USER, .dockerignore present) + check: script_returns_zero + args: { script: "scripts/check_docker_readiness.py" } + severity: warning + + stage_9: + additional_concerns: + - "Container restart / OOM-kill monitoring" + - "Resource limit (CPU/memory) alerting" +``` + +--- + ## Profile: unknown ```yaml diff --git a/references/tool-registry.md b/references/tool-registry.md new file mode 100644 index 0000000..1be15b0 --- /dev/null +++ b/references/tool-registry.md @@ -0,0 +1,57 @@ +# Tool Registry (REQ-TR-001) + +Declarative registry of external CLIs a Forge workflow may need. A new tool is a +**data entry** here, not new code — `scripts/tool_preflight.py` reads this file. + +Fields per entry: + +- `name` — the tool's identifier (used as the key everywhere: cache, CLI, criteria). +- `which` — the binary `shutil.which` looks up. +- `version_probe` (optional) — argv run to confirm the specific capability is present + (not just the binary) and to read a version string; a non-zero exit means the + probed capability is absent even if `which` found the binary (e.g. `docker` present + but the `compose` plugin isn't). +- `workflows` — informal tags for which Forge workflows use this tool. +- `stages` — pipeline stage numbers where this tool matters. +- `required_when` — `always` | `docker_artifacts_present` | `release_stage`. +- `install` — per-OS (`darwin`/`linux`/`win32`) install command **string**. Surfaced, + never executed except by `/forge:preflight` after explicit user confirmation. + +Malformed or incomplete entries (missing `name`/`which`) are skipped, not fatal — +the registry never blocks detection of the entries that do parse. + +```yaml +tools: + - name: docker + which: docker + version_probe: ["docker", "--version"] + workflows: [build, deploy] + stages: [8] + required_when: docker_artifacts_present + install: + darwin: "brew install --cask docker" + linux: "curl -fsSL https://get.docker.com | sh" + win32: "winget install Docker.DockerDesktop" + + - name: docker compose + which: docker + version_probe: ["docker", "compose", "version"] + workflows: [build, deploy] + stages: [8] + required_when: docker_artifacts_present + install: + darwin: "brew install --cask docker" + linux: "sudo apt-get install docker-compose-plugin" + win32: "winget install Docker.DockerDesktop" + + - name: gh + which: gh + version_probe: ["gh", "--version"] + workflows: [release] + stages: [12] + required_when: release_stage + install: + darwin: "brew install gh" + linux: "sudo apt-get install gh" + win32: "winget install GitHub.cli" +``` diff --git a/scripts/check_docker_readiness.py b/scripts/check_docker_readiness.py new file mode 100644 index 0000000..b1b9440 --- /dev/null +++ b/scripts/check_docker_readiness.py @@ -0,0 +1,157 @@ +#!/usr/bin/env python3 +"""Advisory Docker hygiene check (T-228, REQ-DK-001). + +Mirrors check_store_readiness.py's no-op-when-absent template, but this one is +**purely advisory**: it exits 0 whether or not it finds Docker artifacts, and +exits 0 even when it reports findings. Findings are printed as `WARN:` lines — +never a blocking gate. + +Checks, per Dockerfile found: + - base image pinned (no `:latest`, no untagged `FROM`; a digest pin or a + reference to an earlier build stage both count as pinned) + - `HEALTHCHECK` present + - the last `USER` directive is not root (`root` or `0`); no `USER` at all + also flags (the image runs as root by default) +Project-level: + - `.dockerignore` exists when any Docker artifact is present + - each compose file parses and has a top-level `services:` key + +Robust to unreadable files (skipped, not fatal) and to PyYAML being absent +(compose parse check degrades to skipped, not a crash). + +Ref: T-228 / REQ-DK-001 +""" + +from __future__ import annotations + +import argparse +import os +import re +import sys +from dataclasses import dataclass, field + +try: + import yaml +except ImportError: # fail-soft — compose parse check degrades to skipped + yaml = None + +_IGNORE_DIRS = frozenset({ + ".git", "node_modules", ".venv", "venv", "__pycache__", ".forge", "pipeline", + "build", "dist", +}) +_COMPOSE_NAMES = frozenset({"docker-compose.yml", "docker-compose.yaml", "compose.yml", "compose.yaml"}) + +_FROM_RE = re.compile(r"(?im)^\s*FROM\s+(?:--platform=\S+\s+)?(\S+)") +_STAGE_NAME_RE = re.compile(r"(?im)\bAS\s+(\S+)\s*$") +_HEALTHCHECK_RE = re.compile(r"(?im)^\s*HEALTHCHECK\b") +_USER_RE = re.compile(r"(?im)^\s*USER\s+(\S+)") + + +@dataclass +class DockerFindings: + has_artifacts: bool + warnings: list = field(default_factory=list) + + +def _read(path: str) -> str | None: + try: + with open(path, encoding="utf-8", errors="ignore") as f: + return f.read() + except OSError: + return None + + +def _walk_files(cwd: str, matches) -> list: + found = [] + for root, dirs, files in os.walk(cwd): + dirs[:] = [d for d in dirs if d not in _IGNORE_DIRS] + for name in files: + if matches(name): + found.append(os.path.join(root, name)) + return found + + +def _check_dockerfile(path: str, warnings: list) -> None: + text = _read(path) + if text is None: + return # unreadable — skip, don't crash + + stage_names = {m.group(1) for m in _STAGE_NAME_RE.finditer(text)} + for image in _FROM_RE.findall(text): + base = image.split("@")[0] + if "@sha256:" in image: + continue # digest-pinned + if base in stage_names: + continue # refers to an earlier build stage, not a registry image + if ":" not in base or base.rsplit(":", 1)[1] == "latest": + warnings.append(f"{path}: base image not pinned ({image!r}) — pin to a specific tag or digest") + + if not _HEALTHCHECK_RE.search(text): + warnings.append(f"{path}: no HEALTHCHECK instruction") + + users = _USER_RE.findall(text) + last_user = users[-1] if users else None + if last_user is None: + warnings.append(f"{path}: no USER directive — image runs as root by default") + elif last_user in ("root", "0"): + warnings.append(f"{path}: USER is {last_user!r} — runs as root") + + +def _check_compose(path: str, warnings: list) -> None: + text = _read(path) + if text is None: + return + if yaml is None: + return # fail-soft — cannot verify without PyYAML, not a crash + try: + data = yaml.safe_load(text) + except yaml.YAMLError: + warnings.append(f"{path}: does not parse as valid YAML") + return + if not isinstance(data, dict) or "services" not in data: + warnings.append(f"{path}: missing top-level 'services:' key") + + +def check_docker_readiness(cwd) -> DockerFindings: + cwd = str(cwd) + dockerfiles = _walk_files(cwd, lambda n: n == "Dockerfile" or n.startswith("Dockerfile.")) + compose_files = _walk_files(cwd, lambda n: n in _COMPOSE_NAMES) + has_artifacts = bool(dockerfiles or compose_files) + if not has_artifacts: + return DockerFindings(has_artifacts=False, warnings=[]) + + warnings: list = [] + for path in dockerfiles: + _check_dockerfile(path, warnings) + for path in compose_files: + _check_compose(path, warnings) + + if not os.path.isfile(os.path.join(cwd, ".dockerignore")): + warnings.append(".dockerignore not found at project root") + + return DockerFindings(has_artifacts=True, warnings=warnings) + + +def main(argv: list | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--cwd", default=".", help="project root to inspect (default: .)") + args = parser.parse_args(argv if argv is not None else sys.argv[1:]) + + findings = check_docker_readiness(args.cwd) + + if not findings.has_artifacts: + print("check_docker_readiness: no Docker artifacts found — nothing to check.") + return 0 + + if not findings.warnings: + print("check_docker_readiness PASS: no hygiene findings.") + return 0 + + print("check_docker_readiness: advisory findings (never blocking):") + for w in findings.warnings: + print(f" WARN: {w}") + return 0 # always 0 — this check can never block a stage + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/detect-project-type.py b/scripts/detect-project-type.py index 45681d9..fe744c8 100755 --- a/scripts/detect-project-type.py +++ b/scripts/detect-project-type.py @@ -49,6 +49,14 @@ _SCRIPT_FILE_COUNT_THRESHOLD = 20 _SCRIPT_CONFIDENCE = 0.85 +# Docker is cross-cutting (REQ-DK-004): detected regardless of `type`, never part +# of the mutually-exclusive cascade. Top-level files only, matching the scope of +# the other file-presence signals in detect(). +_DOCKER_FILES = frozenset({ + "docker-compose.yml", "docker-compose.yaml", "compose.yml", "compose.yaml", +}) +_DOCKER_CONFIDENCE = 0.85 + def _read(path: str) -> str: try: @@ -447,13 +455,28 @@ def _detect_script(cwd: str, files: set) -> dict | None: } +def _detect_docker_artifacts(files: set) -> dict | None: + """Return Docker artifact info if a Dockerfile or compose file is present at + the top level, else None. Cross-cutting (REQ-DK-004) — this is a pure + presence check, independent of the mutually-exclusive `type` cascade.""" + found = sorted( + f for f in files + if f == "Dockerfile" or f.startswith("Dockerfile.") or f in _DOCKER_FILES + ) + if not found: + return None + return {"indicators": [f"{f} present" for f in found]} + + def _finalize(result: dict, cwd: str) -> dict: """Post-process detect() output. Adds: - `project_type` alias (mirrors `type` — matches state.md field name). - - `suggested_profile: "script"` (and related fields) when nothing else - matched and the project looks tiny enough. + - `has_docker` / `docker_indicators` (REQ-DK-004) — cross-cutting, applied + regardless of `type`; never overrides a real app type. + - `suggested_profile: "script"` or `"docker"` (and related fields) when + nothing else matched and the project looks tiny / Docker-dominant. """ result = dict(result) @@ -461,18 +484,29 @@ def _finalize(result: dict, cwd: str) -> dict: if "type" in result and "project_type" not in result: result["project_type"] = result["type"] - # Only suggest `script` when nothing else matched. + try: + files = set(os.listdir(cwd)) + except OSError: + result["has_docker"] = False + return result + + docker_match = _detect_docker_artifacts(files) + result["has_docker"] = docker_match is not None + if docker_match is not None: + result["docker_indicators"] = docker_match["indicators"] + + # Only suggest a profile when nothing else matched. if result.get("type") == "unknown": - try: - files = set(os.listdir(cwd)) - except OSError: - return result script_match = _detect_script(cwd, files) if script_match is not None: result["suggested_profile"] = "script" result["suggested_profile_confidence"] = _SCRIPT_CONFIDENCE result["suggested_profile_indicators"] = script_match["indicators"] result["suggested_profile_metadata"] = {"loc": script_match["loc"]} + elif docker_match is not None: + result["suggested_profile"] = "docker" + result["suggested_profile_confidence"] = _DOCKER_CONFIDENCE + result["suggested_profile_indicators"] = docker_match["indicators"] return result diff --git a/scripts/doctor.py b/scripts/doctor.py index 0e42c92..8b3cb4f 100755 --- a/scripts/doctor.py +++ b/scripts/doctor.py @@ -30,6 +30,9 @@ from pathlib import Path from typing import Optional +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import tool_preflight # noqa: E402 (check_required_tools — T-229, REQ-TR-003) + MIN_PYTHON = (3, 11) MIN_CLAUDE_CODE = (2, 1, 0) EXPECTED_HOOKS = [ @@ -377,6 +380,27 @@ def check_state_read_failures(cwd: Path) -> CheckResult: ) +def check_required_tools(forge_root: Path, cwd: Path) -> list[CheckResult]: + """One warn-level CheckResult per missing **required** tool_preflight tool + (T-229, REQ-TR-003) — a present or not-required tool produces no result. + Doctor stays read-only: it reports the install command as `fix`, it never + runs it. Never raises — a tool_preflight error degrades to no results.""" + try: + statuses = tool_preflight.check_all(cwd) + except Exception: # noqa: BLE001 — doctor must never crash on tool detection + return [] + results: list[CheckResult] = [] + for name, status in statuses.items(): + if status.required and not status.present: + slug = re.sub(r"\W+", "_", name).strip("_") + results.append(CheckResult( + f"tool_{slug}", "project", "warn", + f"Required tool {name!r} not found ({status.reason})", + fix=status.install_cmd or f"Install {name}", + )) + return results + + def check_hook_errors(cwd: Path) -> CheckResult: log = cwd / ".forge" / "hook-errors.log" if not log.exists(): @@ -526,6 +550,7 @@ def run_checks(forge_root: Path, cwd: Path) -> list[CheckResult]: if gi: results.append(gi) results.append(check_state_read_failures(cwd)) + results.extend(check_required_tools(forge_root, cwd)) gate = check_current_stage_gate(forge_root, cwd) if gate: results.append(gate) diff --git a/scripts/tool_preflight.py b/scripts/tool_preflight.py new file mode 100644 index 0000000..1ab9314 --- /dev/null +++ b/scripts/tool_preflight.py @@ -0,0 +1,295 @@ +#!/usr/bin/env python3 +"""Tool preflight — declarative registry detection + cache (T-227, REQ-TR-001/002). + +Pure detection (shutil.which + optional version probe) for each tool declared in +references/tool-registry.md, cached to .forge/tool-status.json with a 24h TTL and +detached refresh — mirrors hooks/_background_agent.py's capability-probe pattern +(T-138: shutil.which + Capability dataclass + cache file + never raises). This +module never installs anything — install_command() only ever returns a string. + +required_when is resolved against project state: `docker_artifacts_present` walks +the tree for Docker artifacts; `release_stage` reads pipeline/state.md's +current_stage. Never raises: a missing binary is "not present"; an unreadable +registry or cache degrades to an empty/needs-refresh result, never crashes the +caller. + +CLI: + tool_preflight.py check --cwd . -> JSON {tool: {...}} + tool_preflight.py install --cwd . -> the OS install command + (string only, never runs it) + tool_preflight.py refresh --forge-dir DIR --cwd . -> probe + write cache + (for the detached refresh) +""" + +from __future__ import annotations + +import argparse +import datetime as dt +import json +import os +import platform +import re +import shutil +import subprocess +import sys +from dataclasses import dataclass, field +from pathlib import Path +from typing import Optional + +try: + import yaml +except ImportError: # fail-soft — PyYAML is declared but must degrade cleanly if absent + yaml = None + +_PLUGIN_DIR = Path(__file__).resolve().parent.parent +_DEFAULT_REGISTRY_REL = "references/tool-registry.md" +_STATUS_NAME = "tool-status.json" +_TTL_SECONDS = 86400 # re-probe tools at most once/day, same TTL as the capability probe + +_DOCKER_ARTIFACT_NAMES = frozenset({ + "docker-compose.yml", "docker-compose.yaml", "compose.yml", "compose.yaml", +}) +_IGNORE_DIRS = frozenset({ + ".git", "node_modules", ".venv", "venv", "__pycache__", ".forge", "pipeline", + "build", "dist", +}) +_OS_KEYS = {"Darwin": "darwin", "Linux": "linux", "Windows": "win32"} + + +@dataclass +class ToolEntry: + name: str + which: str + version_probe: Optional[list] = None + workflows: list = field(default_factory=list) + stages: list = field(default_factory=list) + required_when: str = "always" + install: dict = field(default_factory=dict) + + +@dataclass +class ToolStatus: + present: bool + version: Optional[str] + required: bool + reason: str + install_cmd: Optional[str] + + +# --------------------------------------------------------------------------- # +# Registry parsing — malformed/missing degrades to [], never raises +# --------------------------------------------------------------------------- # + + +def load_registry(path: Optional[Path] = None) -> list: + registry_path = path or (_PLUGIN_DIR / _DEFAULT_REGISTRY_REL) + if yaml is None or not registry_path.exists(): + return [] + try: + text = registry_path.read_text() + except OSError: + return [] + m = re.search(r"```yaml\n(.*?)\n```", text, re.DOTALL) + if not m: + return [] + try: + data = yaml.safe_load(m.group(1)) + except yaml.YAMLError: + return [] + if not isinstance(data, dict): + return [] + entries = [] + for raw in data.get("tools", []) or []: + if not isinstance(raw, dict) or "name" not in raw or "which" not in raw: + continue # malformed entry — skipped, not fatal + entries.append(ToolEntry( + name=raw["name"], + which=raw["which"], + version_probe=raw.get("version_probe"), + workflows=raw.get("workflows") or [], + stages=raw.get("stages") or [], + required_when=raw.get("required_when", "always"), + install=raw.get("install") or {}, + )) + return entries + + +# --------------------------------------------------------------------------- # +# required_when resolution against project state +# --------------------------------------------------------------------------- # + + +def _has_docker_artifacts(cwd: Path) -> bool: + for root, dirs, files in os.walk(cwd): + dirs[:] = [d for d in dirs if d not in _IGNORE_DIRS] + if any(f.startswith("Dockerfile") or f in _DOCKER_ARTIFACT_NAMES for f in files): + return True + return False + + +def _current_stage(cwd: Path) -> Optional[int]: + try: + sys.path.insert(0, str(_PLUGIN_DIR / "scripts")) + import _state_lib as lib # noqa: PLC0415 + state = lib.read_state(str(cwd)) + except SystemExit: # _state_lib.read_state exits 1 when pipeline/state.md is missing + return None + except Exception: # noqa: BLE001 — never raises (bad value, unreadable file, etc.) + return None + stage = state.get("current_stage") if isinstance(state, dict) else None + try: + return int(stage) if stage is not None else None + except (TypeError, ValueError): + return None + + +def resolve_required(entry: ToolEntry, cwd: Path) -> tuple: + if entry.required_when == "always": + return True, "always required" + if entry.required_when == "docker_artifacts_present": + present = _has_docker_artifacts(cwd) + return present, ("Docker artifacts present" if present else "no Docker artifacts") + if entry.required_when == "release_stage": + stage = _current_stage(cwd) + at_release = stage == 12 + return at_release, (f"current stage is {stage}" if at_release else "not at the release stage") + return False, f"unknown required_when: {entry.required_when!r}" + + +# --------------------------------------------------------------------------- # +# Detection — shutil.which + optional version_probe; never raises +# --------------------------------------------------------------------------- # + + +def _install_cmd_for_entry(entry: ToolEntry) -> Optional[str]: + os_key = _OS_KEYS.get(platform.system()) + return entry.install.get(os_key) if os_key else None + + +def detect_tool(entry: ToolEntry, cwd: Path) -> ToolStatus: + required, reason = resolve_required(entry, cwd) + path = shutil.which(entry.which) + present = path is not None + version = None + if present and entry.version_probe: + try: + result = subprocess.run(entry.version_probe, capture_output=True, text=True, timeout=5) + except (OSError, subprocess.TimeoutExpired): + present = False + else: + present = result.returncode == 0 + if present: + first_line = (result.stdout or result.stderr).strip().splitlines() + version = first_line[0] if first_line else None + install_cmd = None if present else _install_cmd_for_entry(entry) + return ToolStatus(present=present, version=version, required=required, reason=reason, install_cmd=install_cmd) + + +def check_all(cwd: Path, *, registry_path: Optional[Path] = None) -> dict: + entries = load_registry(registry_path) + return {e.name: detect_tool(e, cwd) for e in entries} + + +# --------------------------------------------------------------------------- # +# TTL cache — mirrors hooks/_background_agent.py's write_capabilities/ +# read_capabilities pattern +# --------------------------------------------------------------------------- # + + +def write_status_cache(forge_dir: Path, cwd: Path, *, registry_path: Optional[Path] = None) -> dict: + """Probe every registry tool and atomically write the cache. Never raises.""" + statuses = check_all(cwd, registry_path=registry_path) + data = { + name: { + "present": s.present, "version": s.version, "required": s.required, + "reason": s.reason, "install_cmd": s.install_cmd, + } + for name, s in statuses.items() + } + data["_checked_at"] = dt.datetime.now(dt.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") + try: + forge_dir.mkdir(parents=True, exist_ok=True) + tmp = forge_dir / (_STATUS_NAME + ".tmp") + tmp.write_text(json.dumps(data)) + os.replace(tmp, forge_dir / _STATUS_NAME) + except OSError: + pass # advisory cache — never crash the caller + return data + + +def read_status_cache(forge_dir: Path) -> Optional[dict]: + path = forge_dir / _STATUS_NAME + try: + if not path.exists(): + return None + data = json.loads(path.read_text()) + return data if isinstance(data, dict) else None + except (OSError, ValueError): + return None + + +def cache_is_fresh(forge_dir: Path) -> bool: + path = forge_dir / _STATUS_NAME + try: + return path.exists() and (dt.datetime.now().timestamp() - path.stat().st_mtime) < _TTL_SECONDS + except OSError: + return False + + +# --------------------------------------------------------------------------- # +# install_command — string only, never executes anything +# --------------------------------------------------------------------------- # + + +def install_command(tool_name: str, cwd: Path, *, registry_path: Optional[Path] = None) -> Optional[str]: + for entry in load_registry(registry_path): + if entry.name == tool_name: + return _install_cmd_for_entry(entry) + return None + + +# --------------------------------------------------------------------------- # +# CLI +# --------------------------------------------------------------------------- # + + +def main(argv: Optional[list] = None) -> int: + parser = argparse.ArgumentParser(prog="tool_preflight") + sub = parser.add_subparsers(dest="command", required=True) + + p_check = sub.add_parser("check", help="detect every registry tool, print JSON") + p_check.add_argument("--cwd", default=".") + + p_install = sub.add_parser("install", help="print the install command for one tool") + p_install.add_argument("tool") + p_install.add_argument("--cwd", default=".") + + p_refresh = sub.add_parser("refresh", help="probe + write the status cache") + p_refresh.add_argument("--forge-dir", required=True) + p_refresh.add_argument("--cwd", default=".") + + args = parser.parse_args(argv if argv is not None else sys.argv[1:]) + cwd = Path(args.cwd) + + if args.command == "check": + statuses = check_all(cwd) + print(json.dumps({name: vars(s) for name, s in statuses.items()}, indent=2)) + return 0 + + if args.command == "install": + cmd = install_command(args.tool, cwd) + if cmd is None: + print(f"no install command for {args.tool!r} on this platform", file=sys.stderr) + return 1 + print(cmd) + return 0 + + if args.command == "refresh": + write_status_cache(Path(args.forge_dir), cwd) + return 0 + + return 2 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/skills/forge-deploy/SKILL.md b/skills/forge-deploy/SKILL.md index ca5d51d..d418a75 100644 --- a/skills/forge-deploy/SKILL.md +++ b/skills/forge-deploy/SKILL.md @@ -32,6 +32,11 @@ intentionally). If eval-report is missing or shows failures: "Stage 7 evaluation must pass before deploying." 3. Run `python3 ${CLAUDE_PLUGIN_ROOT}/scripts/check-gate.py --stage 7` to check gate status. 4. Run `python3 ${CLAUDE_PLUGIN_ROOT}/scripts/load-profile.py --cwd . --stage 8` to load project-type overrides. **If the profile sets `skip: true` (CLI, library) the conventional service-deploy is replaced by `package-publish` — produce a package-spec artifact instead of a deployment runbook.** +5. Run `python3 ${CLAUDE_PLUGIN_ROOT}/scripts/check_docker_readiness.py --cwd .` + **unconditionally** — every project gets this, regardless of profile (it + self-no-ops with no Docker artifacts). This is **advisory only**: it exits 0 + even with findings, and any `WARN:` lines it prints must be relayed to the + user as advisory notes — it never blocks and does not gate this stage. ## Steps diff --git a/skills/forge-preflight/SKILL.md b/skills/forge-preflight/SKILL.md new file mode 100644 index 0000000..ab7a0d3 --- /dev/null +++ b/skills/forge-preflight/SKILL.md @@ -0,0 +1,68 @@ +--- +name: preflight +description: Detect missing required CLIs (docker, docker compose, gh) for the + current project and offer to install them. Use whenever the user runs + /forge:preflight, session-start's tool advisory points here, or the user asks + "do I have the tools I need", "is docker installed", or "can I deploy this". + Never auto-runs an installer — every install happens only after the user + explicitly confirms it. +allowed-tools: [Read, Bash] +--- + +# forge-preflight + +Surfaces which required tools are missing for this project and, only after the +user confirms, runs the exact install command for one of them. This is the +**only** surface in Forge that runs an installer — `hooks/session-start.py` and +`scripts/doctor.py` only ever detect and report. + +## When to Use + +- User runs `/forge:preflight` +- `session-start`'s tool advisory line points here (`⚠ Required tool ... run /forge:preflight`) +- `/forge:doctor` reports a missing required tool +- User asks whether a needed CLI is installed, or hits a wall at deploy/release + because a tool turned out to be missing + +## Detect + +```bash +python3 ${CLAUDE_PLUGIN_ROOT}/scripts/tool_preflight.py check --cwd . +``` + +This prints JSON — one entry per registry tool (`references/tool-registry.md`), +each with `present`, `version`, `required`, `reason`, and `install_cmd` fields. +Present the tools where `required` is true and `present` is false. If none, tell +the user everything required is already installed and stop here. + +## Confirm, Then Install — Never Auto-Run + +For each missing required tool, show its exact install command +(`install_cmd` from the JSON above — this is per-OS, resolved by +`tool_preflight.py` from the registry, never invented) and ask the user to +confirm **before running anything**. Only once the user explicitly confirms a +specific tool, run that tool's exact command via Bash. If the user declines a +tool, or does not respond affirmatively, do not run its install command — move +on to the next tool or stop. Never run an install command the user has not +seen and approved, and never install a tool the user has declined. + +If a tool has no `install_cmd` for the current OS (an unsupported platform), +say so and point at the tool's own documentation instead of guessing a command. + +## Report + +After any installs, re-run `tool_preflight.py check --cwd .` and confirm the +tool now shows `present: true`. Summarize what was installed, what was +declined, and what remains missing. + +## Orchestration Rules + +This skill SHALL detect via `tool_preflight.py check` first; show every missing +required tool's exact install command before running it; run an install +command only after the user's explicit confirmation for that specific tool; +and re-check after installing. + +This skill SHALL NOT run any install command without prior confirmation; +install a tool the user declined; invent an install command not sourced from +the registry; or treat a missing optional (non-required) tool as blocking +anything. diff --git a/tests/unit/test_check_docker_readiness.py b/tests/unit/test_check_docker_readiness.py new file mode 100644 index 0000000..cd4370d --- /dev/null +++ b/tests/unit/test_check_docker_readiness.py @@ -0,0 +1,136 @@ +"""T-228 / REQ-DK-001: scripts/check_docker_readiness.py, the advisory Docker +hygiene check. + +Covers AC-DK-001: unpinned/no-healthcheck/no-user/no-dockerignore fixture -> WARN: +lines, exit 0; clean Dockerfile -> pass line, exit 0; no-Docker dir -> no-op, exit +0; unreadable files don't crash. +""" + +from __future__ import annotations + +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent.parent.parent / "scripts")) + +import check_docker_readiness as cdr # noqa: E402 + + +UNPINNED_DOCKERFILE = """\ +FROM python:latest +COPY . /app +CMD ["python", "app.py"] +""" + +CLEAN_DOCKERFILE = """\ +FROM python:3.12.4-slim@sha256:abc123 AS builder +COPY . /app + +FROM builder AS final +HEALTHCHECK CMD curl -f http://localhost/ || exit 1 +USER appuser +CMD ["python", "app.py"] +""" + + +def test_no_docker_artifacts_no_op(tmp_path: Path) -> None: + findings = cdr.check_docker_readiness(tmp_path) + assert findings.has_artifacts is False + assert findings.warnings == [] + + +def test_unpinned_no_healthcheck_no_user_no_dockerignore_all_flagged(tmp_path: Path) -> None: + (tmp_path / "Dockerfile").write_text(UNPINNED_DOCKERFILE) + findings = cdr.check_docker_readiness(tmp_path) + assert findings.has_artifacts is True + joined = " ".join(findings.warnings).lower() + assert "latest" in joined or "pin" in joined + assert "healthcheck" in joined + assert "user" in joined + assert "dockerignore" in joined + + +def test_clean_dockerfile_no_warnings(tmp_path: Path) -> None: + (tmp_path / "Dockerfile").write_text(CLEAN_DOCKERFILE) + (tmp_path / ".dockerignore").write_text(".git\n__pycache__\n") + findings = cdr.check_docker_readiness(tmp_path) + assert findings.has_artifacts is True + assert findings.warnings == [] + + +def test_multi_stage_from_referencing_earlier_stage_not_flagged(tmp_path: Path) -> None: + """`FROM builder AS final` refers to an earlier build stage, not a registry + image -- must not be flagged as unpinned.""" + (tmp_path / "Dockerfile").write_text(CLEAN_DOCKERFILE) + (tmp_path / ".dockerignore").write_text("x\n") + findings = cdr.check_docker_readiness(tmp_path) + assert not any("builder" in w.lower() and "pin" in w.lower() for w in findings.warnings) + + +def test_digest_pinned_from_not_flagged(tmp_path: Path) -> None: + (tmp_path / "Dockerfile").write_text( + "FROM python@sha256:abc123def456\nHEALTHCHECK CMD true\nUSER appuser\n" + ) + (tmp_path / ".dockerignore").write_text("x\n") + findings = cdr.check_docker_readiness(tmp_path) + assert findings.warnings == [] + + +def test_root_user_directive_flagged(tmp_path: Path) -> None: + (tmp_path / "Dockerfile").write_text( + "FROM python:3.12.4\nHEALTHCHECK CMD true\nUSER root\n" + ) + (tmp_path / ".dockerignore").write_text("x\n") + findings = cdr.check_docker_readiness(tmp_path) + assert any("user" in w.lower() for w in findings.warnings) + + +def test_compose_parses_and_has_services(tmp_path: Path) -> None: + (tmp_path / "docker-compose.yml").write_text("services:\n web:\n image: nginx\n") + findings = cdr.check_docker_readiness(tmp_path) + assert findings.has_artifacts is True + assert not any("compose" in w.lower() for w in findings.warnings) + + +def test_compose_missing_services_key_flagged(tmp_path: Path) -> None: + (tmp_path / "docker-compose.yml").write_text("version: '3'\n") + findings = cdr.check_docker_readiness(tmp_path) + assert any("services" in w.lower() or "compose" in w.lower() for w in findings.warnings) + + +def test_compose_unparseable_flagged_not_crash(tmp_path: Path) -> None: + (tmp_path / "docker-compose.yml").write_text("not: valid: yaml: at: all: [\n") + findings = cdr.check_docker_readiness(tmp_path) # must not raise + assert findings.has_artifacts is True + + +def test_unreadable_dockerfile_does_not_crash(tmp_path: Path, monkeypatch) -> None: + (tmp_path / "Dockerfile").write_text(UNPINNED_DOCKERFILE) + real_open = open + + def _boom(path, *a, **k): + if "Dockerfile" in str(path): + raise OSError("permission denied") + return real_open(path, *a, **k) + + monkeypatch.setattr("builtins.open", _boom) + findings = cdr.check_docker_readiness(tmp_path) # must not raise + assert findings.has_artifacts is True + + +def test_main_always_exits_zero_even_with_findings(tmp_path: Path) -> None: + (tmp_path / "Dockerfile").write_text(UNPINNED_DOCKERFILE) + rc = cdr.main(["--cwd", str(tmp_path)]) + assert rc == 0 + + +def test_main_exits_zero_no_docker(tmp_path: Path) -> None: + rc = cdr.main(["--cwd", str(tmp_path)]) + assert rc == 0 + + +def test_main_exits_zero_clean(tmp_path: Path) -> None: + (tmp_path / "Dockerfile").write_text(CLEAN_DOCKERFILE) + (tmp_path / ".dockerignore").write_text("x\n") + rc = cdr.main(["--cwd", str(tmp_path)]) + assert rc == 0 diff --git a/tests/unit/test_deploy_skill.py b/tests/unit/test_deploy_skill.py new file mode 100644 index 0000000..f470a59 --- /dev/null +++ b/tests/unit/test_deploy_skill.py @@ -0,0 +1,40 @@ +"""Structural tests for the /forge:deploy skill's cross-cutting Docker wiring +(T-232, REQ-DK-002). + +Covers AC-DK-002: skills/forge-deploy/SKILL.md invokes check_docker_readiness.py +--cwd . unconditionally in pre-flight and relays findings as advisory, worded +non-blocking. +""" + +from __future__ import annotations + +from pathlib import Path + +_ROOT = Path(__file__).resolve().parent.parent.parent +_SKILL = _ROOT / "skills" / "forge-deploy" / "SKILL.md" + + +def test_skill_exists() -> None: + assert _SKILL.exists() + + +def test_skill_runs_docker_readiness_check_unconditionally() -> None: + body = _SKILL.read_text() + assert "check_docker_readiness.py --cwd ." in body + + +def test_docker_check_is_in_pre_flight_not_gated_on_profile() -> None: + body = _SKILL.read_text() + pre_flight_idx = body.index("## Pre-flight Check") + check_idx = body.index("check_docker_readiness.py --cwd .") + steps_idx = body.index("## Steps") + assert pre_flight_idx < check_idx < steps_idx, ( + "the Docker readiness check must run unconditionally in pre-flight, " + "for every project regardless of profile — not gated behind a profile check" + ) + + +def test_docker_check_worded_as_advisory_never_blocking() -> None: + body = _SKILL.read_text().lower() + assert "advisory" in body + assert "never block" in body or "not block" in body or "does not block" in body diff --git a/tests/unit/test_detect_project_type.py b/tests/unit/test_detect_project_type.py index a58ec2a..300ca0c 100644 --- a/tests/unit/test_detect_project_type.py +++ b/tests/unit/test_detect_project_type.py @@ -168,6 +168,74 @@ def test_forge_dirs_excluded_from_count(self, tmp_path): assert result.get("suggested_profile") == "script" +# ---------- T-232 / REQ-DK-004: cross-cutting Docker detection ---------- + + +class TestDockerDetection: + def test_has_docker_true_when_dockerfile_present(self, tmp_path): + (tmp_path / "Dockerfile").write_text("FROM python:3.12\n") + result = detect_mod._finalize( + {"type": "unknown", "confidence": 0.0, "indicators": []}, + str(tmp_path), + ) + assert result["has_docker"] is True + assert any("Dockerfile" in i for i in result["docker_indicators"]) + + def test_has_docker_true_when_compose_present(self, tmp_path): + (tmp_path / "docker-compose.yml").write_text("services:\n web:\n") + result = detect_mod._finalize( + {"type": "unknown", "confidence": 0.0, "indicators": []}, + str(tmp_path), + ) + assert result["has_docker"] is True + + def test_has_docker_false_when_absent(self, tmp_path): + result = detect_mod._finalize( + {"type": "unknown", "confidence": 0.0, "indicators": []}, + str(tmp_path), + ) + assert result["has_docker"] is False + assert "docker_indicators" not in result + + def test_docker_detected_alongside_a_real_app_type_never_overrides_it(self, tmp_path): + """A FastAPI-in-Docker project stays `api` — has_docker is informational, + never auto-assigned as the profile (AC-DK-004).""" + (tmp_path / "Dockerfile").write_text("FROM python:3.12\n") + result = detect_mod._finalize( + {"type": "api", "confidence": 0.9, "indicators": []}, + str(tmp_path), + ) + assert result["type"] == "api" + assert result["project_type"] == "api" + assert result["has_docker"] is True + assert "suggested_profile" not in result + + def test_suggested_profile_docker_only_when_type_unknown_and_docker_present(self, tmp_path): + (tmp_path / "Dockerfile").write_text("FROM python:3.12\n") + result = detect_mod._finalize( + {"type": "unknown", "confidence": 0.0, "indicators": []}, + str(tmp_path), + ) + assert result.get("suggested_profile") == "docker" + assert result["suggested_profile_confidence"] == detect_mod._DOCKER_CONFIDENCE + assert any("Dockerfile" in i for i in result["suggested_profile_indicators"]) + + def test_no_docker_suggestion_when_type_unknown_but_no_docker_artifacts(self, tmp_path): + result = detect_mod._finalize( + {"type": "unknown", "confidence": 0.0, "indicators": []}, + str(tmp_path), + ) + assert "suggested_profile" not in result + + def test_docker_never_suggested_when_type_already_classified(self, tmp_path): + (tmp_path / "Dockerfile").write_text("FROM python:3.12\n") + result = detect_mod._finalize( + {"type": "fullstack", "confidence": 0.9, "indicators": []}, + str(tmp_path), + ) + assert "suggested_profile" not in result + + # ---------- _count_loc / _is_language_subset helpers ---------- class TestHelpers: diff --git a/tests/unit/test_doctor.py b/tests/unit/test_doctor.py index c011357..3d4831a 100644 --- a/tests/unit/test_doctor.py +++ b/tests/unit/test_doctor.py @@ -264,4 +264,77 @@ def test_quiet_suppresses_passes(self, tmp_path, capsys, monkeypatch): # The python_version check passes; pyyaml passes; claude_code may fail/warn # We just check that the output doesn't include passing "✓" rows for env when all pass # (this test is a smoke test; details vary by host) - assert "Result:" in out \ No newline at end of file + assert "Result:" in out + + +# ---------- check_required_tools (T-229, REQ-TR-003) ---------- + + +def test_check_required_tools_flags_missing_required( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + fake_status = doctor.tool_preflight.ToolStatus( + present=False, version=None, required=True, + reason="always required", install_cmd="brew install gh", + ) + monkeypatch.setattr(doctor.tool_preflight, "check_all", lambda cwd, **k: {"gh": fake_status}) + results = doctor.check_required_tools(tmp_path, tmp_path) + assert len(results) == 1 + assert results[0].status == "warn" + assert results[0].fix == "brew install gh" + + +def test_check_required_tools_no_result_for_present_tool( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + fake_status = doctor.tool_preflight.ToolStatus( + present=True, version="1.0", required=True, reason="x", install_cmd=None, + ) + monkeypatch.setattr(doctor.tool_preflight, "check_all", lambda cwd, **k: {"gh": fake_status}) + assert doctor.check_required_tools(tmp_path, tmp_path) == [] + + +def test_check_required_tools_no_result_for_not_required_tool( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + fake_status = doctor.tool_preflight.ToolStatus( + present=False, version=None, required=False, reason="x", install_cmd=None, + ) + monkeypatch.setattr(doctor.tool_preflight, "check_all", lambda cwd, **k: {"docker": fake_status}) + assert doctor.check_required_tools(tmp_path, tmp_path) == [] + + +def test_check_required_tools_never_raises_on_error( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + def _boom(cwd, **k): + raise RuntimeError("boom") + + monkeypatch.setattr(doctor.tool_preflight, "check_all", _boom) + assert doctor.check_required_tools(tmp_path, tmp_path) == [] + + +def test_run_checks_includes_required_tools_result(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + forge_root = tmp_path / "forge" + forge_root.mkdir() + (forge_root / ".claude-plugin").mkdir() + (forge_root / ".claude-plugin" / "plugin.json").write_text('{"name": "forge"}') + (forge_root / "hooks").mkdir() + for h in doctor.EXPECTED_HOOKS: + (forge_root / "hooks" / h).touch() + (forge_root / "agents").mkdir() + for i in range(doctor.EXPECTED_STAGE_AGENTS): + (forge_root / "agents" / f"a{i}.md").touch() + (forge_root / "references").mkdir() + (forge_root / "references" / "gate-criteria.md").write_text( + "```yaml\nstage: 1\nname: srs\ncriteria:\n - id: G1-001\n```\n" + ) + project = tmp_path / "project" + project.mkdir() + + fake_status = doctor.tool_preflight.ToolStatus( + present=False, version=None, required=True, reason="x", install_cmd="brew install gh", + ) + monkeypatch.setattr(doctor.tool_preflight, "check_all", lambda cwd, **k: {"gh": fake_status}) + results = doctor.run_checks(forge_root, project) + assert any(r.name.startswith("tool_") for r in results) \ No newline at end of file diff --git a/tests/unit/test_load_profile.py b/tests/unit/test_load_profile.py index ddfed1d..c705cc0 100644 --- a/tests/unit/test_load_profile.py +++ b/tests/unit/test_load_profile.py @@ -234,6 +234,7 @@ def test_custom_profiles_file(self, tmp_path): @pytest.mark.parametrize("ptype", [ "api", "fullstack", "ml-pipeline", "cli", "library", "monorepo", "mobile", "data-contract", # v0.1.7 + "docker", # v0.7.0 / T-232 ]) def test_all_standard_profiles_parse(tmp_path, ptype): _make_state(tmp_path, ptype) diff --git a/tests/unit/test_preflight_skill.py b/tests/unit/test_preflight_skill.py new file mode 100644 index 0000000..868844a --- /dev/null +++ b/tests/unit/test_preflight_skill.py @@ -0,0 +1,58 @@ +"""Structural tests for the /forge:preflight skill (T-231, REQ-TR-005). + +Covers AC-TR-004: frontmatter parses (no ': ' YAML trap -- lesson 2026-06-22), +allowed-tools: [Read, Bash], documents the detect -> confirm -> install flow, +and states it never auto-runs an installer. +""" + +from __future__ import annotations + +import re +from pathlib import Path + +import yaml + +_ROOT = Path(__file__).resolve().parent.parent.parent +_SKILL = _ROOT / "skills" / "forge-preflight" / "SKILL.md" + + +def _frontmatter(text: str) -> dict: + m = re.match(r"^---\n(.*?)\n---\n", text, re.DOTALL) + assert m, "SKILL.md must start with YAML frontmatter" + return yaml.safe_load(m.group(1)) + + +def test_skill_exists_with_valid_frontmatter() -> None: + assert _SKILL.exists() + fm = _frontmatter(_SKILL.read_text()) + assert fm.get("name") == "preflight" + assert fm.get("description") + + +def test_skill_declares_read_and_bash_only() -> None: + fm = _frontmatter(_SKILL.read_text()) + assert fm.get("allowed-tools") == ["Read", "Bash"] + + +def test_skill_documents_detect_confirm_install_flow() -> None: + body = _SKILL.read_text().lower() + assert "tool_preflight.py check" in body + assert "confirm" in body + assert "install" in body + + +def test_skill_states_never_auto_runs() -> None: + body = _SKILL.read_text().lower() + assert "never" in body and "auto" in body + + +def test_skill_never_installs_a_declined_tool() -> None: + body = _SKILL.read_text().lower() + assert "declin" in body + + +def test_skill_does_not_run_install_command_without_confirmation_language() -> None: + """Structural guard: every install invocation the skill instructs must be + gated behind explicit confirmation wording nearby.""" + body = _SKILL.read_text() + assert "only after" in body.lower() or "only once" in body.lower() diff --git a/tests/unit/test_session_start.py b/tests/unit/test_session_start.py index a48a23f..feeaa1b 100644 --- a/tests/unit/test_session_start.py +++ b/tests/unit/test_session_start.py @@ -510,6 +510,121 @@ def test_no_health_surface_no_alert(self, tmp_path): assert "Health alert" not in r.stdout +class TestToolPreflightAdvisory: + """T-230 / REQ-TR-004: session-start surfaces one advisory line per missing + required tool, read from the cached .forge/tool-status.json (stdlib only), + dropped first under token pressure, silent when nothing missing / no cache.""" + + def test_missing_required_tool_surfaced(self, tmp_path): + _make_state(tmp_path, stage=8, project_type="api") + forge = tmp_path / ".forge" + forge.mkdir(exist_ok=True) + (forge / "tool-status.json").write_text(json.dumps({ + "docker": {"present": False, "version": None, "required": True, + "reason": "Docker artifacts present", "install_cmd": "brew install docker"}, + })) + r = _run(str(tmp_path)) + assert "docker" in r.stdout + assert "/forge:preflight" in r.stdout + + def test_present_required_tool_not_surfaced(self, tmp_path): + _make_state(tmp_path, stage=8, project_type="api") + forge = tmp_path / ".forge" + forge.mkdir(exist_ok=True) + (forge / "tool-status.json").write_text(json.dumps({ + "docker": {"present": True, "version": "27.0", "required": True, + "reason": "x", "install_cmd": None}, + })) + r = _run(str(tmp_path)) + assert "/forge:preflight" not in r.stdout + + def test_missing_but_not_required_tool_not_surfaced(self, tmp_path): + _make_state(tmp_path, stage=1, project_type="api") + forge = tmp_path / ".forge" + forge.mkdir(exist_ok=True) + (forge / "tool-status.json").write_text(json.dumps({ + "docker": {"present": False, "version": None, "required": False, + "reason": "no Docker artifacts", "install_cmd": "brew install docker"}, + })) + r = _run(str(tmp_path)) + assert "/forge:preflight" not in r.stdout + + def test_no_cache_file_no_advisory_no_crash(self, tmp_path): + _make_state(tmp_path, stage=1, project_type="api") + r = _run(str(tmp_path)) + assert r.returncode == 0 + assert "/forge:preflight" not in r.stdout + + def test_unreadable_cache_no_advisory_no_crash(self, tmp_path): + _make_state(tmp_path, stage=1, project_type="api") + forge = tmp_path / ".forge" + forge.mkdir(exist_ok=True) + (forge / "tool-status.json").write_text("{not valid json") + r = _run(str(tmp_path)) + assert r.returncode == 0 + assert "/forge:preflight" not in r.stdout + + def test_tool_block_dropped_first_under_token_pressure(self, tmp_path): + """A large tool-status.json alone must not push output over budget -- + it is dropped before lessons/rules trim, not after (AC-TR-003).""" + _make_state(tmp_path, stage=8, project_type="api") + forge = tmp_path / ".forge" + forge.mkdir(exist_ok=True) + many_missing = { + f"tool-{i}": {"present": False, "version": None, "required": True, + "reason": "x" * 50, "install_cmd": "y" * 50} + for i in range(80) + } + (forge / "tool-status.json").write_text(json.dumps(many_missing)) + r = _run(str(tmp_path)) + assert r.returncode == 0 + assert len(r.stdout) < 8000 # stays under the ~2000-token budget + assert "[Forge] Pipeline: Stage 8" in r.stdout # core context untouched + assert "/forge:preflight" not in r.stdout # the oversized tool block was dropped + + def test_ensure_tool_status_skips_fresh_cache(self, tmp_path, monkeypatch): + mod = _load_hook_module() + forge = tmp_path / ".forge" + forge.mkdir(parents=True) + (forge / "tool-status.json").write_text("{}") + calls = [] + monkeypatch.setattr(mod.subprocess, "Popen", lambda *a, **k: calls.append(a)) + mod._ensure_tool_status(tmp_path) + assert calls == [] + + def test_ensure_tool_status_refreshes_stale_cache(self, tmp_path, monkeypatch): + mod = _load_hook_module() + forge = tmp_path / ".forge" + forge.mkdir(parents=True) + stale = forge / "tool-status.json" + stale.write_text("{}") + old = os.path.getmtime(stale) - mod._TOOL_TTL_SECONDS - 10 + os.utime(stale, (old, old)) + calls = [] + monkeypatch.setattr(mod.subprocess, "Popen", lambda *a, **k: calls.append(a) or object()) + mod._ensure_tool_status(tmp_path) + assert len(calls) == 1 + assert "tool_preflight.py" in calls[0][0][1] + assert "refresh" in calls[0][0] + + def test_ensure_tool_status_respects_kill_switch(self, tmp_path, monkeypatch): + mod = _load_hook_module() + monkeypatch.setenv("FORGE_NO_BACKGROUND", "1") + calls = [] + monkeypatch.setattr(mod.subprocess, "Popen", lambda *a, **k: calls.append(a)) + mod._ensure_tool_status(tmp_path) + assert calls == [] + + def test_ensure_tool_status_never_raises(self, tmp_path, monkeypatch): + mod = _load_hook_module() + + def _boom(*a, **k): + raise OSError("boom") + + monkeypatch.setattr(mod.subprocess, "Popen", _boom) + mod._ensure_tool_status(tmp_path) # must not raise + + class TestRulesInjection: """T-159 / REQ-RULES-009: session-start injects always + current-stage rules within the token budget; absent rules dir is a clean no-op.""" diff --git a/tests/unit/test_set_profile.py b/tests/unit/test_set_profile.py index d6ec448..49bd14b 100644 --- a/tests/unit/test_set_profile.py +++ b/tests/unit/test_set_profile.py @@ -39,9 +39,16 @@ def _project_type(tmp_path: Path) -> str: def test_known_profiles_lists_all(tmp_path: Path) -> None: names = _sp.known_profiles(PLUGIN_DIR) - for expected in ("api", "fullstack", "ml-pipeline", "monorepo", "mobile", "data-contract"): + for expected in ("api", "fullstack", "ml-pipeline", "monorepo", "mobile", "data-contract", "docker"): assert expected in names - assert len(names) >= 10 + assert len(names) >= 11 + + +def test_set_profile_docker_accepted(tmp_path: Path) -> None: + _make_state(tmp_path, "unknown") + code, msg = _sp.set_profile(str(tmp_path), "docker", plugin_dir=PLUGIN_DIR) + assert code == 0 + assert _project_type(tmp_path) == "docker" def test_set_valid_profile_updates_state(tmp_path: Path) -> None: diff --git a/tests/unit/test_tool_preflight.py b/tests/unit/test_tool_preflight.py new file mode 100644 index 0000000..55ed890 --- /dev/null +++ b/tests/unit/test_tool_preflight.py @@ -0,0 +1,258 @@ +"""T-227 / REQ-TR-001/002: scripts/tool_preflight.py, the declarative tool registry ++ detection + cache. + +Covers AC-TR-001: registry parses; presence/version via monkeypatched shutil.which ++ version_probe; required per required_when (Docker-artifact fixture marks docker +required, bare dir does not); TTL cache reused; missing/unreadable registry or +cache -> no-op, never raises; install returns the string and runs nothing. +""" + +from __future__ import annotations + +import json +import subprocess +import sys +from pathlib import Path + +import pytest + +ROOT = Path(__file__).resolve().parent.parent.parent +sys.path.insert(0, str(ROOT / "scripts")) + +import tool_preflight as tp # noqa: E402 + + +REGISTRY_TEXT = """\ +# Tool Registry + +```yaml +tools: + - name: docker + which: docker + version_probe: ["docker", "--version"] + workflows: [build, deploy] + stages: [8] + required_when: docker_artifacts_present + install: + darwin: "brew install --cask docker" + linux: "curl -fsSL https://get.docker.com | sh" + win32: "winget install Docker.DockerDesktop" + + - name: gh + which: gh + version_probe: ["gh", "--version"] + workflows: [release] + stages: [12] + required_when: release_stage + install: + darwin: "brew install gh" + linux: "sudo apt-get install gh" + win32: "winget install GitHub.cli" +``` +""" + + +def _write_registry(tmp_path: Path) -> Path: + path = tmp_path / "tool-registry.md" + path.write_text(REGISTRY_TEXT) + return path + + +# --------------------------------------------------------------------------- # +# load_registry +# --------------------------------------------------------------------------- # + + +def test_load_registry_parses_seeded_tools(tmp_path: Path) -> None: + entries = tp.load_registry(_write_registry(tmp_path)) + names = [e.name for e in entries] + assert "docker" in names + assert "gh" in names + + +def test_load_registry_missing_file_returns_empty_not_raise(tmp_path: Path) -> None: + assert tp.load_registry(tmp_path / "does-not-exist.md") == [] + + +def test_load_registry_malformed_yaml_returns_empty_not_raise(tmp_path: Path) -> None: + path = tmp_path / "tool-registry.md" + path.write_text("```yaml\ntools: [this is not: valid: yaml: at all\n```\n") + assert tp.load_registry(path) == [] + + +def test_load_registry_skips_malformed_entry_keeps_valid_ones(tmp_path: Path) -> None: + path = tmp_path / "tool-registry.md" + path.write_text( + "```yaml\ntools:\n - description: missing name and which\n" + " - name: docker\n which: docker\n```\n" + ) + entries = tp.load_registry(path) + assert [e.name for e in entries] == ["docker"] + + +# --------------------------------------------------------------------------- # +# detect_tool — presence/version via monkeypatched shutil.which + version_probe +# --------------------------------------------------------------------------- # + + +def test_detect_tool_present_when_which_and_probe_succeed(tmp_path: Path, monkeypatch) -> None: + entry = tp.ToolEntry(name="docker", which="docker", version_probe=["docker", "--version"]) + monkeypatch.setattr(tp.shutil, "which", lambda name: "/usr/bin/docker") + monkeypatch.setattr( + tp.subprocess, "run", + lambda *a, **k: subprocess.CompletedProcess(a, 0, stdout="Docker version 27.0.0\n", stderr=""), + ) + status = tp.detect_tool(entry, tmp_path) + assert status.present is True + assert "27.0.0" in status.version + + +def test_detect_tool_absent_when_which_finds_nothing(tmp_path: Path, monkeypatch) -> None: + entry = tp.ToolEntry(name="docker", which="docker") + monkeypatch.setattr(tp.shutil, "which", lambda name: None) + status = tp.detect_tool(entry, tmp_path) + assert status.present is False + assert status.install_cmd is None or isinstance(status.install_cmd, str) + + +def test_detect_tool_absent_when_binary_present_but_probe_fails(tmp_path: Path, monkeypatch) -> None: + """docker present but the compose plugin isn't -- probe failure means absent, + even though `which` found the docker binary.""" + entry = tp.ToolEntry(name="docker compose", which="docker", version_probe=["docker", "compose", "version"]) + monkeypatch.setattr(tp.shutil, "which", lambda name: "/usr/bin/docker") + monkeypatch.setattr( + tp.subprocess, "run", + lambda *a, **k: subprocess.CompletedProcess(a, 1, stdout="", stderr="unknown command"), + ) + status = tp.detect_tool(entry, tmp_path) + assert status.present is False + + +# --------------------------------------------------------------------------- # +# resolve_required — required_when +# --------------------------------------------------------------------------- # + + +def test_required_always_is_always_true(tmp_path: Path) -> None: + entry = tp.ToolEntry(name="x", which="x", required_when="always") + required, _ = tp.resolve_required(entry, tmp_path) + assert required is True + + +def test_docker_artifacts_present_required_when_dockerfile_exists(tmp_path: Path) -> None: + (tmp_path / "Dockerfile").write_text("FROM python:3.12\n") + entry = tp.ToolEntry(name="docker", which="docker", required_when="docker_artifacts_present") + required, reason = tp.resolve_required(entry, tmp_path) + assert required is True + assert "docker" in reason.lower() + + +def test_docker_artifacts_present_not_required_on_bare_dir(tmp_path: Path) -> None: + entry = tp.ToolEntry(name="docker", which="docker", required_when="docker_artifacts_present") + required, _ = tp.resolve_required(entry, tmp_path) + assert required is False + + +def test_release_stage_required_only_at_stage_12(tmp_path: Path) -> None: + (tmp_path / "pipeline").mkdir() + (tmp_path / "pipeline" / "state.md").write_text( + "---\nschema_version: 1\ncurrent_stage: 12\n---\n\n# Pipeline State\n" + ) + entry = tp.ToolEntry(name="gh", which="gh", required_when="release_stage") + required, _ = tp.resolve_required(entry, tmp_path) + assert required is True + + +def test_release_stage_not_required_at_other_stages(tmp_path: Path) -> None: + (tmp_path / "pipeline").mkdir() + (tmp_path / "pipeline" / "state.md").write_text( + "---\nschema_version: 1\ncurrent_stage: 3\n---\n\n# Pipeline State\n" + ) + entry = tp.ToolEntry(name="gh", which="gh", required_when="release_stage") + required, _ = tp.resolve_required(entry, tmp_path) + assert required is False + + +# --------------------------------------------------------------------------- # +# TTL cache — write_status_cache / read_status_cache +# --------------------------------------------------------------------------- # + + +def test_write_and_read_status_cache_roundtrip(tmp_path: Path, monkeypatch) -> None: + monkeypatch.setattr(tp.shutil, "which", lambda name: None) + forge_dir = tmp_path / ".forge" + tp.write_status_cache(forge_dir, tmp_path, registry_path=_write_registry(tmp_path)) + cached = tp.read_status_cache(forge_dir) + assert cached is not None + assert "docker" in cached + + +def test_read_status_cache_missing_returns_none(tmp_path: Path) -> None: + assert tp.read_status_cache(tmp_path / ".forge") is None + + +def test_read_status_cache_unreadable_json_returns_none(tmp_path: Path) -> None: + forge_dir = tmp_path / ".forge" + forge_dir.mkdir() + (forge_dir / "tool-status.json").write_text("{not valid json") + assert tp.read_status_cache(forge_dir) is None + + +def test_write_status_cache_never_raises_on_unwritable_dir(tmp_path: Path, monkeypatch) -> None: + monkeypatch.setattr(tp.shutil, "which", lambda name: None) + # Point forge_dir at a path that can't be created (a file, not a directory). + blocker = tmp_path / "blocker" + blocker.write_text("x") + tp.write_status_cache(blocker / "sub", tmp_path, registry_path=_write_registry(tmp_path)) + # Must not raise -- reaching this line is the assertion. + + +# --------------------------------------------------------------------------- # +# install_command — string only, never runs anything +# --------------------------------------------------------------------------- # + + +def test_install_command_returns_string_for_known_tool(tmp_path: Path, monkeypatch) -> None: + monkeypatch.setattr(tp.platform, "system", lambda: "Linux") + cmd = tp.install_command("docker", tmp_path, registry_path=_write_registry(tmp_path)) + assert isinstance(cmd, str) and cmd + + +def test_install_command_none_for_unknown_tool(tmp_path: Path) -> None: + assert tp.install_command("not-a-real-tool", tmp_path, registry_path=_write_registry(tmp_path)) is None + + +def test_install_command_never_executes_anything(tmp_path: Path, monkeypatch) -> None: + calls = [] + monkeypatch.setattr(tp.subprocess, "run", lambda *a, **k: calls.append(a) or (_ for _ in ()).throw( + AssertionError("install_command must never run a subprocess") + )) + tp.install_command("docker", tmp_path, registry_path=_write_registry(tmp_path)) + assert calls == [] + + +# --------------------------------------------------------------------------- # +# CLI +# --------------------------------------------------------------------------- # + + +def test_cli_check_emits_json(tmp_path: Path, monkeypatch, capsys) -> None: + monkeypatch.setattr(tp, "_PLUGIN_DIR", tmp_path) + monkeypatch.setattr(tp, "_DEFAULT_REGISTRY_REL", "tool-registry.md") + _write_registry(tmp_path) + monkeypatch.setattr(tp.shutil, "which", lambda name: None) + rc = tp.main(["check", "--cwd", str(tmp_path)]) + assert rc == 0 + out = json.loads(capsys.readouterr().out) + assert "docker" in out + + +def test_cli_refresh_writes_cache(tmp_path: Path, monkeypatch) -> None: + monkeypatch.setattr(tp, "_PLUGIN_DIR", tmp_path) + monkeypatch.setattr(tp, "_DEFAULT_REGISTRY_REL", "tool-registry.md") + _write_registry(tmp_path) + monkeypatch.setattr(tp.shutil, "which", lambda name: None) + forge_dir = tmp_path / ".forge" + rc = tp.main(["refresh", "--forge-dir", str(forge_dir), "--cwd", str(tmp_path)]) + assert rc == 0 + assert tp.read_status_cache(forge_dir) is not None