Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 6 additions & 3 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
6 changes: 4 additions & 2 deletions build/04-plan/task-dag-v0.8.0.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`

Expand Down
25 changes: 19 additions & 6 deletions build/05-implementation/progress.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`
Expand Down Expand Up @@ -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
Expand Down
16 changes: 9 additions & 7 deletions references/build/02-context-resolution.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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).
Expand Down
89 changes: 87 additions & 2 deletions scripts/build_executor.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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,
)


Expand Down Expand Up @@ -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)


Expand Down
64 changes: 64 additions & 0 deletions scripts/set-context-depth.py
Original file line number Diff line number Diff line change
@@ -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())
30 changes: 30 additions & 0 deletions skills/forge-plan-pro/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <depth> --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
Expand Down
23 changes: 23 additions & 0 deletions tasks/lessons.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <ancestor-sha>: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 <sha>:<path>` (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 <old-sha>`
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
Expand Down
Loading
Loading