diff --git a/CHANGELOG.md b/CHANGELOG.md index 338b008..a5b6f4c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -30,9 +30,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 enforced by a byte-diff regression test (`test_builder_pipeline_wiring.py`). Deferred: `forge explain`, a recovery state machine beyond progress.md + resume, broader "enterprise artifact" files, AI-agnostic provider adapters, and builder - modes beyond single-task + milestone-batch. Configurable context depth beyond the - default spec+plan (architecture, or the full Stage 1-5 chain) is designed but - tracked as a follow-on, not yet wired. Ref: T-241..T-251. + modes beyond single-task + milestone-batch. Context-resolution depth is + configurable: `spec_plan` (default), `spec_arch_plan` (adds scoped architecture + excerpts), or `full_chain` (adds PRD/user-stories/user-flows/latest-sprint-plan + excerpts, informational only) — chosen once via a new `/forge:plan-pro` Stage 5 + pre-flight prompt (`scripts/set-context-depth.py`) and persisted to + `pipeline/state.md`. Ref: T-241..T-253. ### Planned - Claude Code marketplace publication (pending marketplace availability) diff --git a/build/04-plan/task-dag-v0.8.0.md b/build/04-plan/task-dag-v0.8.0.md index c420911..8b062bf 100644 --- a/build/04-plan/task-dag-v0.8.0.md +++ b/build/04-plan/task-dag-v0.8.0.md @@ -216,13 +216,15 @@ dependency. TDD red-first per task. Full unit suite green after every task. --- -## Follow-On (tracked, not blocking the Critical Path) +## Follow-On (tracked, not blocking the Critical Path) — DONE Discovered mid-build (REQ-BUILDCTX-002): context-resolution depth should be configurable rather than fixed forever at spec+plan. Design lives in `references/build/02-context-resolution.md` and the SRS; these two tasks implement the Stage 5 prompt/persist UX and the widening logic. Sequenced after T-251 — -Phase 2 ships and is fully usable with the `spec_plan` default before either lands. +Phase 2 shipped and was fully usable with the `spec_plan` default before either +landed. **Both now complete**: T-252 `412fba8`, T-253 `0442b88` — see +`build/05-implementation/progress.md`. ### T-252 [S] `forge-plan-pro` Stage 5 entry: prompt + persist `build_context_depth` diff --git a/build/05-implementation/progress.md b/build/05-implementation/progress.md index 568a62e..c2c3b7d 100644 --- a/build/05-implementation/progress.md +++ b/build/05-implementation/progress.md @@ -5,7 +5,7 @@ ## Current State -- **v0.8.0 Revision 2 (Builder Pro) COMPLETE — T-241..T-251.** Revision 1 below +- **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 script) — **superseded, not deleted from history**. `build/01-srs/srs-v0.8.0.md` @@ -42,11 +42,24 @@ 0, `full-pipeline.sh` 12/12 gates + traceability intact.** `agents/builder.md` and `skills/forge-build/SKILL.md` verified byte-identical to the pre-T-235 `6a22fa1` baseline throughout. Worktree `.claude/worktrees/recursive-wobbling-sky`, branch - `builder-pro-plan-execution`. **NEXT**: T-252/T-253 (REQ-BUILDCTX-002 — Stage 5 - `forge-plan-pro` context-depth prompt + wiring `build_context_depth` into - `build_executor.py`'s context-resolve), tracked follow-on, not urgent — Phase 2 - ships fully working at the `spec_plan` default. Then merge this branch and open - the PR (develop base, per repo convention). + `builder-pro-plan-execution`. PR #63 pushed and CI-green (unit/integration/lint) + after a follow-up fix: the wiring test's byte-identical baseline check depended on + `git show 6a22fa1:path`, which needs an ancestor's objects that CI's default + shallow `actions/checkout` (fetch-depth 1) never fetches — swapped for a literal + fixture snapshot (`tests/fixtures/pre_pro_tier_baseline/`), no history-depth + dependency. **REQ-BUILDCTX-002 follow-on now also DONE**: T-252 `412fba8` — + `scripts/set-context-depth.py` + a new "Context Depth for Stage 6" pre-flight + section in `skills/forge-plan-pro/SKILL.md` (prompts once when + `build_context_depth` is unset, never re-prompts). T-253 `0442b88` — + `read_context_depth()` (fail-soft, defaults `spec_plan`) wired into + `resolve_context()`: `spec_arch_plan` resolves scoped architecture excerpts, + `full_chain` additionally resolves a `full_chain_excerpts` dict (PRD, user + stories, user flows, latest numbered sprint plan when present) — informational + only, the hard REQ-ID invariant is unchanged by depth. TDD red-first, +18 tests + (7 for T-252, 11 for T-253). Full unit suite **1949 pass**, `validate-plugin.py` + exit 0. **v0.8.0 Revision 2 is now fully complete, T-241..T-253, nothing tracked + and outstanding.** NEXT: push these commits, confirm CI green, then this branch is + ready to merge. - **v0.8.0 Revision 1 (Builder Phase 1: Pro-tier sub-agent pipeline) SUPERSEDED — T-235..T-240.** Scoped from `docs/builder-pro-plan-analysis.md`'s verdict on `BUILDER_PRO-PLAN.md` (execute Phase 1 only). T-235 `7327f28` Context Loader (read-only, resolves only diff --git a/references/build/02-context-resolution.md b/references/build/02-context-resolution.md index e0bacac..90d44c3 100644 --- a/references/build/02-context-resolution.md +++ b/references/build/02-context-resolution.md @@ -69,13 +69,14 @@ this repo): | Depth | Additionally resolves | |---|---| | `spec_plan` (default) | nothing beyond Inputs 1-5 above | -| `spec_arch_plan` | `pipeline/03-architecture/*` (via `read-doc.py`) — matching excerpts fold into the bundle's Architecture excerpt(s) field | -| `full_chain` | the full Stage 1-5 canonical set: SRS+traceability, PRD+user-stories+flows, full architecture, full spec, full plan, sprint-plan when present — informational context only | +| `spec_arch_plan` | `pipeline/03-architecture/architecture` (via `read-doc.py`) — matching excerpts fold into the bundle's Architecture excerpt(s) field | +| `full_chain` | `spec_arch_plan`'s architecture excerpts, plus a `full_chain_excerpts` dict: PRD, user stories, user flows, and the highest-numbered `pipeline/05-plan/sprints/sprint-NNN.md` when one exists — each scoped to the task's REQ-IDs/Files the same way spec/architecture excerpts are; informational context only | -The prompt/persist UX at Stage 5 entry (`forge-plan-pro`'s pre-flight) and the -`spec_arch_plan`/`full_chain` widening logic are **T-252/T-253** — sequenced after -T-251, not blocking this phase's critical path. Phase 2 ships fully working at the -`spec_plan` default. +`scripts/set-context-depth.py` (T-252) is what `forge-plan-pro`'s Stage 5 pre-flight +calls to persist the answer, prompting once when `build_context_depth` is unset and +never re-prompting or overwriting an explicit prior choice +(AC-BUILDCTX-002c). `read_context_depth()` and the `spec_arch_plan`/`full_chain` +widening in `resolve_context()` (T-253) are both wired end to end. ## Hard Requirement Invariant @@ -100,8 +101,9 @@ LLM-persona-to-script move: | REQ-IDs | the task-dag entry's declared REQ-IDs | | Task description | the entry's Description and Done-when text, verbatim | | Spec excerpt(s) | matching section(s) from the `read-doc.py`-resolved `pipeline/04-spec/technical-spec`, quoted not paraphrased; only task-relevant sections | -| Architecture excerpt(s) | `(not resolved at this depth)` at the default `spec_plan` depth; at `spec_arch_plan`/`full_chain`, matching excerpts from the `read-doc.py`-resolved `pipeline/03-architecture/*`, quoted not paraphrased, or `(none found)` if no matching section exists | +| Architecture excerpt(s) | `None` at the default `spec_plan` depth; at `spec_arch_plan`/`full_chain`, matching excerpts from the `read-doc.py`-resolved `pipeline/03-architecture/architecture` (an empty list, not `None`, if the doc is missing or has no matching section) | | Applicable additional_criteria | Stage 6 `additional_criteria` entries (id, description, severity) from the active profile; `(none)` if no profile is active | +| full_chain_excerpts | `None` except at the `full_chain` depth; there, a dict keyed `prd`/`user_stories`/`user_flows`/`sprint_plan` (the last key present only when a numbered sprint file exists), each value the task-scoped matching sections | Only files/sections tied to the task's declared `Files`/`REQ-IDs` are included — never the entire spec or architecture doc (AC-BUILDEXEC-001a). diff --git a/scripts/build_executor.py b/scripts/build_executor.py index 294800e..ec47693 100644 --- a/scripts/build_executor.py +++ b/scripts/build_executor.py @@ -35,14 +35,30 @@ _PLUGIN_DIR = Path(__file__).resolve().parent.parent sys.path.insert(0, str(_PLUGIN_DIR / "scripts")) import parallel_build as _pb # noqa: E402 (batch path delegates here — AC-BUILDEXEC-001c) +import _state_lib as _state # noqa: E402 (build_context_depth — REQ-BUILDCTX-002, T-253) DAG_BASE = "pipeline/05-plan/task-dag" SPEC_BASE = "pipeline/04-spec/technical-spec" -ARCH_BASE = "pipeline/03-architecture/architecture" # only at spec_arch_plan/full_chain (T-253) +ARCH_BASE = "pipeline/03-architecture/architecture" # only at spec_arch_plan/full_chain SRS_BASE = "pipeline/01-srs/srs" PROGRESS_RELPATH = "pipeline/06-implementation/progress.md" TRACE_RELPATH = "pipeline/05-plan/traceability.md" BUILD_LOG_RELPATH = "pipeline/06-implementation/build-log.jsonl" +SPRINTS_DIR_RELPATH = "pipeline/05-plan/sprints" + +# REQ-BUILDCTX-002: context-resolution depth, read from pipeline/state.md's optional +# build_context_depth field. Default (and only depth T-248 originally wired) is +# spec_plan; spec_arch_plan/full_chain widen what resolve_context additionally loads. +CONTEXT_DEPTHS = ("spec_plan", "spec_arch_plan", "full_chain") + +# The full Stage 1-5 canonical set resolved at the full_chain depth -- informational +# only, never gates the hard requirement invariant. Sprint plan is resolved +# separately (numbered files under pipeline/05-plan/sprints/, not a fixed base path). +FULL_CHAIN_BASES = { + "prd": "pipeline/02-product-ux/prd", + "user_stories": "pipeline/02-product-ux/user-stories", + "user_flows": "pipeline/02-product-ux/user-flows", +} TASK_HEADING = re.compile(r"^#{2,4}\s+.*?\b(T-\d+)\b.*$", re.MULTILINE) TASK_ID = re.compile(r"\bT-\d+\b") @@ -84,6 +100,7 @@ class ContextBundle: spec_excerpts: list architecture_excerpts: Optional[list] # None => "(not resolved at this depth)" additional_criteria: list + full_chain_excerpts: Optional[dict] = None # only at the full_chain depth @dataclass @@ -240,6 +257,63 @@ def _stage6_additional_criteria(cwd: Path, *, plugin_dir: Path = _PLUGIN_DIR) -> return criteria or [] +def read_context_depth(cwd: Path) -> str: + """Read build_context_depth from pipeline/state.md via _state_lib. Fail-soft + (REQ-BUILDCTX-002, AC-BUILDCTX-002b): missing state.md, an unset field, or an + unrecognized value all default to 'spec_plan' -- the depth set-context-depth.py + (T-252) never writes anything but one of CONTEXT_DEPTHS, so an unrecognized + value only occurs from hand-edited or corrupted state, and defaulting is the + safe behavior there (same posture as every other optional config field in this + repo -- e.g. project_type).""" + try: + state = _state.read_state(str(cwd)) + except SystemExit: + return "spec_plan" + except Exception: + return "spec_plan" + depth = state.get("build_context_depth") if isinstance(state, dict) else None + return depth if depth in CONTEXT_DEPTHS else "spec_plan" + + +def _latest_sprint_base(cwd: Path) -> Optional[str]: + """The highest-numbered pipeline/05-plan/sprints/sprint-NNN base path, or None + if the directory doesn't exist or has no numbered sprint file. Only the + sprint-NNN.md plan itself -- not -capacity/-dependencies/-risk-register/-review/ + -retrospective/-metrics siblings (references/sprint-plan/01-foundation.md's + Sprint Deliverables list).""" + sprints_dir = cwd / SPRINTS_DIR_RELPATH + if not sprints_dir.is_dir(): + return None + pattern = re.compile(r"^sprint-(\d{3})\.md$") + numbered = [] + for p in sprints_dir.glob("sprint-*.md"): + m = pattern.match(p.name) + if m: + numbered.append((int(m.group(1)), p.stem)) + if not numbered: + return None + numbered.sort(key=lambda t: t[0]) + return f"{SPRINTS_DIR_RELPATH}/{numbered[-1][1]}" + + +def _resolve_full_chain_excerpts( + cwd: Path, needles: list, *, plugin_dir: Path, +) -> dict: + """Informational-only widening at the full_chain depth: PRD, user stories, user + flows, and (when present) the latest sprint plan, each scoped to the task's + REQ-IDs/Files the same way spec/architecture excerpts are. Does not affect the + hard requirement invariant (SRS/task-dag stay the source of truth for that).""" + bases = dict(FULL_CHAIN_BASES) + sprint_base = _latest_sprint_base(cwd) + if sprint_base: + bases["sprint_plan"] = sprint_base + out: dict = {} + for name, base in bases.items(): + text = read_doc(cwd, base, plugin_dir=plugin_dir) or "" + out[name] = matching_sections(text, needles) + return out + + def resolve_context( cwd: Path, task_id: str, *, plugin_dir: Path = _PLUGIN_DIR, ) -> ContextBundle: @@ -272,14 +346,24 @@ def resolve_context( if task.done_when: description = f"{description}\nDone when: {task.done_when}" + depth = read_context_depth(cwd) + architecture_excerpts: Optional[list] = None + full_chain_excerpts: Optional[dict] = None + if depth in ("spec_arch_plan", "full_chain"): + arch_text = read_doc(cwd, ARCH_BASE, plugin_dir=plugin_dir) or "" + architecture_excerpts = matching_sections(arch_text, needles) + if depth == "full_chain": + full_chain_excerpts = _resolve_full_chain_excerpts(cwd, needles, plugin_dir=plugin_dir) + return ContextBundle( task_id=task.id, files=task.files, req_ids=task.req_ids, description=description, spec_excerpts=spec_excerpts, - architecture_excerpts=None, # spec_plan depth only this phase — T-253 widens + architecture_excerpts=architecture_excerpts, additional_criteria=additional_criteria, + full_chain_excerpts=full_chain_excerpts, ) @@ -651,6 +735,7 @@ def _bundle_to_json(bundle: ContextBundle) -> str: "spec_excerpts": bundle.spec_excerpts, "architecture_excerpts": bundle.architecture_excerpts, "additional_criteria": bundle.additional_criteria, + "full_chain_excerpts": bundle.full_chain_excerpts, }, indent=2) diff --git a/scripts/set-context-depth.py b/scripts/set-context-depth.py new file mode 100644 index 0000000..1e43386 --- /dev/null +++ b/scripts/set-context-depth.py @@ -0,0 +1,64 @@ +#!/usr/bin/env python3 +"""`/forge:plan-pro`'s Stage 5 entry sets `build_context_depth` in pipeline/state.md +(T-252, REQ-BUILDCTX-002). + +Validates the requested depth against the three allowed values and updates +state.md atomically via _state_lib, mirroring set-profile.py's project_type +pattern. `--dry-run` previews without writing. Refuses to overwrite an +already-set value unless `--force` is passed -- the skill only calls this once, +when the field is absent (AC-BUILDCTX-002c: never re-prompt). +""" + +from __future__ import annotations + +import argparse +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).parent)) +import _state_lib as lib # noqa: E402 + +VALID_DEPTHS = ("spec_plan", "spec_arch_plan", "full_chain") + + +def set_context_depth( + cwd: str, depth: str, *, force: bool = False, dry_run: bool = False +) -> tuple[int, str]: + """Set build_context_depth. Returns (exit_code, message). Never sys.exits.""" + state_path = Path(cwd) / "pipeline" / "state.md" + if not state_path.exists(): + return 1, "pipeline/state.md not found — run /forge:init first." + + if depth not in VALID_DEPTHS: + return 1, f"unknown depth '{depth}'. Valid depths: {', '.join(VALID_DEPTHS)}" + + current = lib.read_state(cwd) + existing = current.get("build_context_depth") + if existing and not force: + return 0, ( + f"build_context_depth is already '{existing}' — not re-prompting " + "(pass --force to override an explicit prior choice)." + ) + if dry_run: + return 0, f"[dry-run] would set build_context_depth: {existing or '(unset)'} → {depth}" + + current["build_context_depth"] = depth + lib.write_state(cwd, current) + return 0, f"build_context_depth set: {existing or '(unset)'} → {depth}" + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(prog="set-context-depth") + parser.add_argument("depth", choices=VALID_DEPTHS) + parser.add_argument("--cwd", default=".") + parser.add_argument("--force", action="store_true", help="overwrite an already-set value") + parser.add_argument("--dry-run", action="store_true") + args = parser.parse_args(argv if argv is not None else sys.argv[1:]) + + code, message = set_context_depth(args.cwd, args.depth, force=args.force, dry_run=args.dry_run) + print(message) + return code + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/skills/forge-plan-pro/SKILL.md b/skills/forge-plan-pro/SKILL.md index 69705d4..2ddc77f 100644 --- a/skills/forge-plan-pro/SKILL.md +++ b/skills/forge-plan-pro/SKILL.md @@ -91,6 +91,36 @@ reference controls handling of `replace_with`, `additional_artifacts`, `additional_steps`, `additional_concerns`, and `skip_steps`. Never let a profile bypass entry, ownership, traceability, validation, quality, or advancement gates. +## Context Depth for Stage 6 (REQ-BUILDCTX-002) + +Stage 6 Pro (`/forge:build-pro`) resolves per-task context at one of three depths: +`spec_plan` (default), `spec_arch_plan`, or `full_chain` — see +`references/build/02-context-resolution.md`. This is decided once, here, at Stage 5 +entry, not re-derived per build. + +Read `pipeline/state.md`. If `build_context_depth` is already set, skip this step +silently — never re-prompt or overwrite an explicit prior choice +(AC-BUILDCTX-002c). + +If unset, ask the user which depth Stage 6 should use for this project: + +- **`spec_plan`** (recommended default) — spec + plan only. Matches Builder Pro's + own principle that Stage 4's spec is already the distilled, implementation-ready + contract; Stage 6 does not need to re-derive architecture. +- **`spec_arch_plan`** — also resolves matching architecture excerpts per task. +- **`full_chain`** — resolves the full Stage 1–5 canonical set (SRS, PRD/user + stories/flows, architecture, spec, plan, sprint plan when present) as additional + informational context per task. + +Persist the answer: + +```bash +python3 ${CLAUDE_PLUGIN_ROOT}/scripts/set-context-depth.py --cwd . +``` + +If the user has no preference, use the recommended default and move on — do not +block Stage 5 planning on this decision. + ## Load Planner Pro and References Read `agents/planner-pro.md`, adopt Planner Pro, and follow its Reference Loading diff --git a/tasks/lessons.md b/tasks/lessons.md index 014f41b..ebd253b 100644 --- a/tasks/lessons.md +++ b/tasks/lessons.md @@ -247,6 +247,29 @@ in `3269a3b`, keeping the substance as directly-stated rules instead of quotes. - **Tags**: [architecture, documentation, pro-tier, references, T-242, T-246] +### 2026-08-05 — A test that shells out to `git show :path` can pass locally and fail in CI on the identical commit + +- **Trigger**: Writing a regression guard that compares a file's current content + against an older commit via `git show :` (or any `git` command that + needs an ancestor's objects, not just the working tree). +- **Rule**: Check `.github/workflows/*.yml` for the checkout step's `fetch-depth` + before writing a test like this. No `fetch-depth` set means `actions/checkout`'s + default of `1` — a shallow clone with only the tip commit's objects, even though + `git log` on that same ref shows a full, real ancestor chain. `git show ` + fails there with exit 128 ("bad object"), not a content mismatch — a different + failure mode than the test is meant to catch. Prefer a committed literal fixture + snapshot (`tests/fixtures/...`) over any git-history lookup for a "this file must + stay byte-identical to some earlier point" check; it has no checkout-depth + dependency and works identically locally and in CI. +- **Why**: `test_builder_pipeline_wiring.py`'s two baseline-diff tests (inherited + from Revision 1's original version of the file) passed in every local run (full + git history available in the dev worktree) but failed on PR #63's actual GitHub + Actions run with `git show 6a22fa1:... returned non-zero exit status 128` — + `tests.yml` has no `fetch-depth` override. Local pytest runs are not a reliable + signal for git-history-shape assumptions; only the real CI checkout is. Fixed by + switching to `tests/fixtures/pre_pro_tier_baseline/` (`8e183d1`). +- **Tags**: [testing, ci, git, github-actions, T-250] + ## Patterns by Category ### Plugin Development diff --git a/tests/unit/test_build_executor.py b/tests/unit/test_build_executor.py index 2f0ec8a..a2dfe41 100644 --- a/tests/unit/test_build_executor.py +++ b/tests/unit/test_build_executor.py @@ -131,6 +131,127 @@ def test_resolve_context_missing_task_raises(tmp_path: Path) -> None: be.resolve_context(tmp_path, "T-999") +# --------------------------------------------------------------------------- # +# read_context_depth / REQ-BUILDCTX-002 -- fail-soft, default spec_plan +# --------------------------------------------------------------------------- # + + +def _seed_state(tmp_path: Path, depth: str | None = None) -> None: + (tmp_path / "pipeline").mkdir(parents=True, exist_ok=True) + body = f"---\nbuild_context_depth: {depth}\n---\n\n# Pipeline State\n" if depth else ( + "---\nschema_version: 1\n---\n\n# Pipeline State\n" + ) + (tmp_path / "pipeline" / "state.md").write_text(body) + + +def test_read_context_depth_defaults_to_spec_plan_when_state_missing(tmp_path: Path) -> None: + assert be.read_context_depth(tmp_path) == "spec_plan" + + +def test_read_context_depth_defaults_to_spec_plan_when_unset(tmp_path: Path) -> None: + _seed_state(tmp_path) + assert be.read_context_depth(tmp_path) == "spec_plan" + + +def test_read_context_depth_defaults_to_spec_plan_on_malformed_value(tmp_path: Path) -> None: + _seed_state(tmp_path, "bogus-depth") + assert be.read_context_depth(tmp_path) == "spec_plan" + + +@pytest.mark.parametrize("depth", ["spec_plan", "spec_arch_plan", "full_chain"]) +def test_read_context_depth_reads_valid_value(tmp_path: Path, depth: str) -> None: + _seed_state(tmp_path, depth) + assert be.read_context_depth(tmp_path) == depth + + +# --------------------------------------------------------------------------- # +# resolve_context at spec_arch_plan / full_chain (REQ-BUILDCTX-002, T-253) +# --------------------------------------------------------------------------- # + +ARCH_TEXT = """\ +## Component: first-service + +Covers REQ-FIRST-001. Owns `pkg/first.py`. + +## Component: second-service + +Covers REQ-SECOND-001. Owns `pkg/second.py`. +""" + +PRD_TEXT = "## Feature: first thing\n\nCovers REQ-FIRST-001.\n" +USER_STORIES_TEXT = "## Story: first thing\n\nCovers REQ-FIRST-001.\n" +USER_FLOWS_TEXT = "## Flow: first thing\n\nCovers REQ-FIRST-001.\n" + + +def _seed_full_chain_docs(tmp_path: Path) -> None: + (tmp_path / "pipeline" / "03-architecture").mkdir(parents=True, exist_ok=True) + (tmp_path / "pipeline" / "03-architecture" / "architecture.md").write_text(ARCH_TEXT) + (tmp_path / "pipeline" / "02-product-ux").mkdir(parents=True, exist_ok=True) + (tmp_path / "pipeline" / "02-product-ux" / "prd.md").write_text(PRD_TEXT) + (tmp_path / "pipeline" / "02-product-ux" / "user-stories.md").write_text(USER_STORIES_TEXT) + (tmp_path / "pipeline" / "02-product-ux" / "user-flows.md").write_text(USER_FLOWS_TEXT) + + +def test_resolve_context_spec_arch_plan_populates_architecture_scoped(tmp_path: Path) -> None: + _seed_project(tmp_path) + _seed_full_chain_docs(tmp_path) + _seed_state(tmp_path, "spec_arch_plan") + bundle = be.resolve_context(tmp_path, "T-001") + assert bundle.architecture_excerpts is not None + assert any("first-service" in s for s in bundle.architecture_excerpts) + assert not any("second-service" in s for s in bundle.architecture_excerpts), ( + "architecture excerpts must stay scoped to the task, same as spec excerpts" + ) + assert bundle.full_chain_excerpts is None + + +def test_resolve_context_spec_arch_plan_missing_architecture_doc_is_empty_not_error( + tmp_path: Path, +) -> None: + _seed_project(tmp_path) + _seed_state(tmp_path, "spec_arch_plan") + bundle = be.resolve_context(tmp_path, "T-001") + assert bundle.architecture_excerpts == [] + + +def test_resolve_context_full_chain_populates_architecture_and_full_chain_excerpts( + tmp_path: Path, +) -> None: + _seed_project(tmp_path) + _seed_full_chain_docs(tmp_path) + _seed_state(tmp_path, "full_chain") + bundle = be.resolve_context(tmp_path, "T-001") + assert bundle.architecture_excerpts is not None + assert bundle.full_chain_excerpts is not None + assert set(bundle.full_chain_excerpts) == {"prd", "user_stories", "user_flows"} + assert any("first thing" in s for s in bundle.full_chain_excerpts["prd"]) + + +def test_resolve_context_full_chain_includes_latest_sprint_plan_when_present( + tmp_path: Path, +) -> None: + _seed_project(tmp_path) + _seed_full_chain_docs(tmp_path) + _seed_state(tmp_path, "full_chain") + sprints_dir = tmp_path / "pipeline" / "05-plan" / "sprints" + sprints_dir.mkdir(parents=True) + (sprints_dir / "sprint-001.md").write_text("## Sprint 1\n\nCovers REQ-FIRST-001.\n") + (sprints_dir / "sprint-002.md").write_text("## Sprint 2\n\nCovers REQ-FIRST-001, latest.\n") + bundle = be.resolve_context(tmp_path, "T-001") + assert "sprint_plan" in bundle.full_chain_excerpts + assert any("latest" in s for s in bundle.full_chain_excerpts["sprint_plan"]), ( + "must resolve the highest-numbered sprint file, not the first one found" + ) + + +def test_resolve_context_full_chain_omits_sprint_plan_when_absent(tmp_path: Path) -> None: + _seed_project(tmp_path) + _seed_full_chain_docs(tmp_path) + _seed_state(tmp_path, "full_chain") + bundle = be.resolve_context(tmp_path, "T-001") + assert "sprint_plan" not in bundle.full_chain_excerpts + + # --------------------------------------------------------------------------- # # Gate — AC-BUILDEXEC-001b per-check reporting, never one aggregate boolean # --------------------------------------------------------------------------- # diff --git a/tests/unit/test_set_context_depth.py b/tests/unit/test_set_context_depth.py new file mode 100644 index 0000000..e790fe0 --- /dev/null +++ b/tests/unit/test_set_context_depth.py @@ -0,0 +1,92 @@ +"""Tests for scripts/set-context-depth.py (T-252, REQ-BUILDCTX-002). + +`/forge:plan-pro`'s Stage 5 entry sets `build_context_depth` in pipeline/state.md +(atomic, validated, never re-prompts) after checking the depth against the three +allowed values. +""" + +from __future__ import annotations + +import datetime +import importlib.util +import re +import sys +from pathlib import Path + +_root = Path(__file__).resolve().parent.parent.parent +_spec = importlib.util.spec_from_file_location( + "set_context_depth", _root / "scripts" / "set-context-depth.py" +) +_scd = importlib.util.module_from_spec(_spec) +sys.modules["set_context_depth"] = _scd +_spec.loader.exec_module(_scd) + + +def _make_state(tmp_path: Path) -> None: + (tmp_path / "pipeline").mkdir(parents=True, exist_ok=True) + now = datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") + (tmp_path / "pipeline" / "state.md").write_text( + f"---\nschema_version: 1\nproject_type: api\ncycle: 1\n" + f"current_stage: 5\ncurrent_task: null\ncurrent_milestone: null\n" + f"total_tasks: null\nlast_updated: {now}\nblockers: []\n---\n\n# Pipeline State\n" + ) + + +def _depth(tmp_path: Path) -> str | None: + text = (tmp_path / "pipeline" / "state.md").read_text() + m = re.search(r"build_context_depth:\s*(\S+)", text) + return m.group(1) if m else None + + +def test_set_valid_depth_updates_state(tmp_path: Path) -> None: + _make_state(tmp_path) + code, msg = _scd.set_context_depth(str(tmp_path), "spec_arch_plan") + assert code == 0 + assert _depth(tmp_path) == "spec_arch_plan" + + +def test_invalid_depth_rejected(tmp_path: Path) -> None: + _make_state(tmp_path) + code, msg = _scd.set_context_depth(str(tmp_path), "bogus-depth") + assert code == 1 + assert "bogus-depth" in msg or "unknown depth" in msg.lower() + assert _depth(tmp_path) is None + + +def test_dry_run_does_not_write(tmp_path: Path) -> None: + _make_state(tmp_path) + code, msg = _scd.set_context_depth(str(tmp_path), "full_chain", dry_run=True) + assert code == 0 + assert "would" in msg.lower() + assert _depth(tmp_path) is None + + +def test_missing_state_graceful(tmp_path: Path) -> None: + code, msg = _scd.set_context_depth(str(tmp_path), "spec_plan") + assert code == 1 + assert "state.md" in msg.lower() or "init" in msg.lower() + + +def test_already_set_is_not_reprompted(tmp_path: Path) -> None: + """AC-BUILDCTX-002c: never re-prompt or silently overwrite an explicit prior choice.""" + _make_state(tmp_path) + _scd.set_context_depth(str(tmp_path), "spec_arch_plan") + code, msg = _scd.set_context_depth(str(tmp_path), "full_chain") + assert code == 0 + assert "already" in msg.lower() + assert _depth(tmp_path) == "spec_arch_plan" # unchanged + + +def test_force_overwrites_an_already_set_value(tmp_path: Path) -> None: + _make_state(tmp_path) + _scd.set_context_depth(str(tmp_path), "spec_arch_plan") + code, msg = _scd.set_context_depth(str(tmp_path), "full_chain", force=True) + assert code == 0 + assert _depth(tmp_path) == "full_chain" + + +def test_main_cli(tmp_path: Path) -> None: + _make_state(tmp_path) + rc = _scd.main(["spec_plan", "--cwd", str(tmp_path)]) + assert rc == 0 + assert _depth(tmp_path) == "spec_plan"