@garygentry/feature-forge 0.2.11 → 0.2.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. package/adapters/claude/.feature-forge-bundle.json +1 -1
  2. package/adapters/claude/references/shared-conventions.md +22 -0
  3. package/adapters/claude/scripts/forge-session.py +134 -1
  4. package/adapters/claude/skills/forge/SKILL.md +2 -0
  5. package/adapters/claude/skills/forge-1-prd/SKILL.md +20 -2
  6. package/adapters/claude/skills/forge-4-backlog/SKILL.md +2 -0
  7. package/adapters/codex/.feature-forge-bundle.json +1 -1
  8. package/adapters/codex/references/shared-conventions.md +22 -0
  9. package/adapters/codex/scripts/forge-session.py +134 -1
  10. package/adapters/codex/skills/forge/SKILL.md +2 -0
  11. package/adapters/codex/skills/forge-1-prd/SKILL.md +19 -1
  12. package/adapters/codex/skills/forge-4-backlog/SKILL.md +2 -0
  13. package/adapters/copilot/.feature-forge-bundle.json +1 -1
  14. package/adapters/copilot/references/shared-conventions.md +22 -0
  15. package/adapters/copilot/scripts/forge-session.py +134 -1
  16. package/adapters/copilot/skills/forge/forge.md +2 -0
  17. package/adapters/copilot/skills/forge-1-prd/forge-1-prd.md +19 -1
  18. package/adapters/copilot/skills/forge-4-backlog/forge-4-backlog.md +2 -0
  19. package/adapters/cursor/.feature-forge-bundle.json +1 -1
  20. package/adapters/cursor/references/shared-conventions.md +22 -0
  21. package/adapters/cursor/scripts/forge-session.py +134 -1
  22. package/adapters/cursor/skills/forge/forge.mdc +2 -0
  23. package/adapters/cursor/skills/forge-1-prd/forge-1-prd.mdc +19 -1
  24. package/adapters/cursor/skills/forge-4-backlog/forge-4-backlog.mdc +2 -0
  25. package/adapters/gemini/.feature-forge-bundle.json +1 -1
  26. package/adapters/gemini/gemini-extension.json +1 -1
  27. package/adapters/gemini/references/shared-conventions.md +22 -0
  28. package/adapters/gemini/scripts/forge-session.py +134 -1
  29. package/adapters/gemini/skills/forge/forge.md +2 -0
  30. package/adapters/gemini/skills/forge-1-prd/forge-1-prd.md +19 -1
  31. package/adapters/gemini/skills/forge-4-backlog/forge-4-backlog.md +2 -0
  32. package/package.json +1 -1
@@ -12,12 +12,30 @@ Create a thorough, requirements-only PRD through relentless structured interview
12
12
 
13
13
  Read and follow `references/shared-conventions.md` for feature name validation, configuration reading, and force mode handling before proceeding.
14
14
 
15
+ **`--force-standalone` (forge-1-prd only).** A distinct flag from `--force`: it bypasses only the **Mint Guard** in Step 1 (letting you intentionally fork a name that is a known epic member into a detached standalone feature). It does **not** imply `--force` — prerequisite checks and the Stage-Entry Guard still run. Use it only when you genuinely mean to create a standalone feature that shares a name with an epic member on another branch.
16
+
15
17
  ## Step 1: Read Configuration and Check State
16
18
 
17
19
  ### Branch Setup (if using git)
18
20
  Invoke the **Branch Setup** block in `references/shared-conventions.md` with `{label}` = `{feature}` and `{scope}` = `feature`. It self-gates (skips when not a git repo, when `branchPerFeature` is false, or for an epic member that inherits the epic's branch), detects whether you're on the default branch, and strongly recommends — still optionally — creating `{branchPrefix}{feature}` when you are. Do this before directory resolution.
19
21
 
20
- Set the working directory by invoking the **Feature Directory Resolution** block in `references/shared-conventions.md`, which yields `{resolvedFeatureDir}`. Note one PRD-specific caveat: at PRD time a brand-new standalone feature may have NO directory yet, so resolution is expected to fail `not-found` for a never-started standalone feature — in that case forge-1 creates `{specsDir}/{feature}/` as today. For an epic member the directory already exists (created empty by forge-0-epic with an `epic` back-pointer), so resolution succeeds and yields the nested path.
22
+ Set the working directory by invoking the **Feature Directory Resolution** block in `references/shared-conventions.md`, which yields `{resolvedFeatureDir}`. Note one PRD-specific caveat: at PRD time a brand-new standalone feature may have NO directory yet, so resolution is expected to fail for a never-started standalone feature — as `not-found` (exit 1) when `{specsDir}/` already exists (other features present), or as `specs dir not found` (exit 2) when `{specsDir}/` itself does not exist yet (the very first feature, or a branch that never had a specs tree). In **both** of those "about to create a brand-new standalone" cases forge-1 creates `{specsDir}/{feature}/` as today. (The *other* exit-2 errors — `unsafe-name`, a path-containment escape — are genuine STOPs, never a mint.) For an epic member the directory already exists (created empty by forge-0-epic with an `epic` back-pointer), so resolution succeeds and yields the nested path.
23
+
24
+ ### Mint Guard: refuse to fork a known epic member into a detached standalone (Issue #125)
25
+
26
+ Run this sub-step **whenever forge-1 is about to mint a brand-new flat standalone `{specsDir}/{feature}/`** — that is, when Feature Directory Resolution returned either `not-found` (exit 1) **or** `specs dir not found` (the exit-2 missing-specs-dir flavor, e.g. a clean default branch that has never had a specs tree). The exit-2 case is the *cleanest* split-brain trigger: on a branch that predates the epic, `{specsDir}/` may not exist at all, yet cross-branch discovery still sees the member on the epic branch. It prevents the split-brain-epic failure where a member of an epic (whose manifest lives on a *different, unmerged* branch) is silently forged as a disjoint standalone feature carrying no `epic` back-pointer. Skip it entirely when resolution succeeded (an epic member's directory already exists — resolution yields the nested path, so this never fires), on the other exit-2 errors (`unsafe-name` / path-containment — those STOP, they never mint), and when `--force-standalone` was passed (see below).
27
+
28
+ 1. Run cross-branch discovery for this exact name (branch-agnostic — it scans all refs regardless of current HEAD):
29
+ ```bash
30
+ R="$(bash -c 'for d in "${FEATURE_FORGE_ROOT:-}" "$HOME"/.claude/skills/feature-forge "$HOME"/.claude/plugins/cache/*/feature-forge/* "$HOME"/.claude/plugins/*/feature-forge "$HOME"/.agents/skills/feature-forge ./.agents/skills/feature-forge; do [ -x "$d/scripts/forge-root.sh" ] && exec "$d/scripts/forge-root.sh"; done')"
31
+ [ -n "$R" ] || { echo "feature-forge: cannot locate plugin root" >&2; exit 1; }
32
+ python3 "$R/scripts/forge-session.py" discover-feature "{feature}" --specs-dir "{specsDir}" --json
33
+ ```
34
+ 2. **If any candidate has `isEpicMember: true` → HARD STOP.** This is not the soft switch/fetch/treat-as-new menu from the Feature Directory Resolution block — do **not** create any directory and do **not** fall through to the interview. Emit verbatim (filling `{epic}` and `{stateBranch}` from that candidate's `epic` and `stateBranch`):
35
+ > `{feature}` is a member of epic `{epic}` (recorded on branch `{stateBranch}`). You appear to be on a branch that does not contain that epic. Switch to `{stateBranch}` and run `/feature-forge:forge-1-prd {feature}` there, or pass `--force-standalone` to intentionally fork a detached standalone feature.
36
+ 3. **If candidates exist but none are epic members** → keep today's soft behavior: this is the ordinary cross-branch-discovery case already handled by the Feature Directory Resolution block's **Candidates found** menu (switch / fetch+switch / treat-as-new / stop). Defer to it.
37
+ 4. **If nothing was found** (no candidates) → proceed to mint the flat standalone feature as today.
38
+ 5. **If `--force-standalone` was passed** → skip this guard entirely, log a one-line warning ("Forking `{feature}` as a detached standalone despite epic membership on `{stateBranch}`"), and proceed to create the flat feature. `--force-standalone` is distinct from `--force` and does **not** imply it (see the Force Mode note below).
21
39
 
22
40
  After resolution, invoke the **Stage-Entry Guard** block in `references/shared-conventions.md` with `{stage}` = `forge-1-prd`. It classifies re-entry (fresh / interrupted / re-authoring), runs the resume-vs-restart gate and the "create a new version?" warning as applicable, and applies the entry stamp on the authoring paths. For a brand-new standalone feature there is no state file yet, so the guard's **fresh** arm applies with nothing to prompt; the entry stamp lands when the state file is first created in Step 6.
23
41
 
@@ -40,6 +40,8 @@ Resolve the **loop runner** from the `loopRunner` block in `forge.config.json`,
40
40
 
41
41
  After the prerequisite check, invoke the **Stage-Entry Guard** block in `references/shared-conventions.md` with `{stage}` = `forge-4-backlog` — it detects an interrupted or complete `backlog.json`, runs the resume/restart or new-version gate, and stamps entry before Step 2 loads the specs. (The backlog is a single artifact, so "resume" means: reuse the existing `backlog.json` if the previous run wrote it, rather than re-authoring from scratch.)
42
42
 
43
+ Then invoke the **Epic-Member Base Guard** block in `references/shared-conventions.md` (this stage does not run Epic Context Injection, so invoke it explicitly here). It self-gates to a no-op for standalone features; for a nested epic member on a branch that lacks the epic manifest it stops with a home-branch pointer (Issue #125).
44
+
43
45
  **Verification check.** Check whether the specs have been verified. If not, use the host's question mechanism to warn with the cost of skipping: "Specs haven't been verified yet. Recommended: run `/feature-forge:forge-verify {feature}` first — unverified specs can carry gaps or contradictions that get baked into backlog items and only surface mid-loop, where they're far more expensive to fix. Continue anyway?" Offer **Verify first (recommended)** · **Continue without verifying**.
44
46
 
45
47
  ## Step 2: Load All Specs
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "feature-forge",
3
- "version": "0.12.6",
3
+ "version": "0.12.7",
4
4
  "agent": "copilot",
5
5
  "generatedBy": "python3 scripts/build-adapters.py"
6
6
  }
@@ -159,6 +159,28 @@ python3 "$R/scripts/epic-manifest.py" \
159
159
 
160
160
  If `render-status` fails, proceed with **only** EPIC.md + charter (a corrupt manifest must not silently inject stale dep specs — REQ-ROBUST-02): on **exit 1**, parse the `{findings[]}` JSON from stdout and surface each; on **exit 2**, surface the plain `Error:` line from stderr verbatim. Do not attempt to parse findings JSON on an exit-2 failure (stdout is empty).
161
161
 
162
+ **After injecting context, invoke the Epic-Member Base Guard block below** (it self-gates to a no-op for standalone features and features that do not resolve as a nested member).
163
+
164
+ ## Epic-Member Base Guard
165
+
166
+ Defense-in-depth for the split-brain-epic failure (Issue #125). Invoke this block in the authoring stages (`forge-1-prd`..`forge-4-backlog`) once the feature has resolved — right after **Epic Context Injection** for the stages that run it (`forge-1-prd`..`forge-3-specs`), and right after **Feature Directory Resolution** for `forge-4-backlog`. It confirms that a **resolved nested epic member** actually sits on a branch that contains the epic's manifest. Without this, a member reached from a branch cut *before* the epic-manifest commit (or that otherwise lacks it) would author specs against an epic decomposition that is not present — the exact drift that produces a disjoint, split-brain member. **Skip if not a git repo or `branchPerFeature` is false.**
167
+
168
+ ```bash
169
+ R="$(bash -c 'for d in "${CLAUDE_PLUGIN_ROOT:-}" "$HOME"/.claude/skills/feature-forge "$HOME"/.claude/plugins/cache/*/feature-forge/* "$HOME"/.claude/plugins/*/feature-forge "$HOME"/.agents/skills/feature-forge ./.agents/skills/feature-forge; do [ -x "$d/scripts/forge-root.sh" ] && exec "$d/scripts/forge-root.sh"; done')"
170
+ [ -n "$R" ] || { echo "feature-forge: cannot locate plugin root" >&2; exit 1; }
171
+ python3 "$R/scripts/forge-session.py" check-epic-base --feature "{feature}" --specs-dir "{specsDir}" --json
172
+ ```
173
+
174
+ Act on the emitted `action`:
175
+ - **`none`** — a standalone feature (no epic to check) or the manifest is present on the current branch. Proceed silently. This is the no-op path for standalone features (REQ-COMPAT-01), so standalone behavior is unchanged.
176
+ - **`not-resolved`** — the feature does not resolve on the current branch. Proceed silently (the caller's own resolution already handled that case).
177
+ - **`warn-detached-base`** — a nested member resolves here but the epic's `epic-manifest.json` is **absent on this branch**. **STOP** unless `--force` was passed, and surface verbatim (filling `{epic}` and `{homeBranch}` from the payload's `epic` and `homeBranch`):
178
+ > `{feature}` is a member of epic `{epic}`, but this branch does not contain the epic manifest (`{specsDir}/{epic}/epic-manifest.json`). This base predates or lacks the epic. Switch to the epic's home branch `{homeBranch}` and re-run, or pass `--force` to author against a detached base anyway.
179
+
180
+ With `--force`, log a one-line warning ("Authoring `{feature}` against a detached epic base — manifest not on this branch") and proceed, consistent with the other guards.
181
+
182
+ If the helper is unavailable (a non-Claude host without the resolver), skip this block — it is best-effort defense in depth, not a hard prerequisite.
183
+
162
184
  ## Pipeline State Protocol
163
185
 
164
186
  Write pipeline state conforming to `references/pipeline-state-schema.json`. Always update `updatedAt` when modifying pipeline state.
@@ -11,6 +11,8 @@ root navigator:
11
11
  python3 forge-session.py discover-feature [NAME | --all] [--specs-dir DIR] [--json]
12
12
  python3 forge-session.py reconcile-branch --feature F [--specs-dir DIR] \
13
13
  [--config FILE] [--epic E] [--json]
14
+ python3 forge-session.py check-epic-base --feature F [--specs-dir DIR] \
15
+ [--config FILE] [--epic E] [--json]
14
16
  python3 forge-session.py stage-exit --feature F --stage S [--specs-dir DIR] \
15
17
  [--config FILE] [--epic E] [--next-feature N] [--host claude|generic] [--json]
16
18
 
@@ -45,7 +47,17 @@ concluding it was never started. When nothing is found locally it also asks
45
47
  `git ls-remote --heads origin` about branches a single-branch clone never
46
48
  fetched, and emits the exact `git fetch`/`git switch` commands a caller could
47
49
  run. It is strictly read-only — it never checks anything out itself — and
48
- like `doctor` it always exits 0 and degrades to data.
50
+ like `doctor` it always exits 0 and degrades to data. Each candidate also
51
+ carries `epic`/`isEpicMember`, so a caller minting a new standalone feature can
52
+ refuse when the name is a known epic member discoverable on another branch
53
+ (the split-brain-epic guard, Issue #125).
54
+
55
+ `check-epic-base` is the defense-in-depth companion: given a feature that
56
+ resolves to a nested epic member on the current branch, it confirms the epic's
57
+ `epic-manifest.json` is actually present on HEAD. When it is absent, the member
58
+ was reached from a branch that predates or lacks the manifest commit (a detached
59
+ base) and the command emits `warn-detached-base` with the member's recorded home
60
+ branch. Read-only; always exits 0.
49
61
 
50
62
  `stage-exit` computes everything an authoring stage's closing used to derive
51
63
  in prose (the Scripted Stage Exit, `references/stage-exit-protocol.md`):
@@ -848,6 +860,26 @@ def _read_state_at_ref(ref: str, path: str) -> dict:
848
860
  return parsed if isinstance(parsed, dict) else {}
849
861
 
850
862
 
863
+ def _epic_membership(path: str, specs_rel: str, state: dict) -> tuple[str | None, bool]:
864
+ """Derive ``(epic, isEpicMember)`` for a discovered candidate.
865
+
866
+ A candidate is an epic member when its state carries an ``epic`` back-pointer
867
+ **or** its path is nested (``{specsDir}/{epic}/{name}/.pipeline-state.json``).
868
+ Nested-ness is structurally authoritative; the ``epic`` field is the recorded
869
+ back-pointer. When the state lacks the field, the nested directory name is used
870
+ so the signal is never "member of epic None".
871
+ """
872
+ prefix = specs_rel + "/"
873
+ nested_epic: str | None = None
874
+ if path.startswith(prefix):
875
+ segments = path[len(prefix):].split("/")
876
+ if len(segments) == 3: # [epic, name, state-file]
877
+ nested_epic = segments[0]
878
+ epic = state.get("epic")
879
+ epic = epic if isinstance(epic, str) and epic else nested_epic
880
+ return epic, bool(nested_epic) or bool(epic)
881
+
882
+
851
883
  def _list_refs(pattern: str) -> list[tuple[str, str]]:
852
884
  """Return ``(short_ref, committer_date)`` pairs under a ref namespace."""
853
885
  raw = _git_output([
@@ -908,6 +940,7 @@ def discover_feature(name: str, specs_dir: str) -> dict:
908
940
  state_branch = state.get("branch")
909
941
  state_branch = state_branch if isinstance(state_branch, str) else None
910
942
  updated = state.get("updatedAt")
943
+ epic, is_epic_member = _epic_membership(path, specs_rel, state)
911
944
  matched_branches.add(branch)
912
945
  candidates.append({
913
946
  "branch": branch,
@@ -918,6 +951,8 @@ def discover_feature(name: str, specs_dir: str) -> dict:
918
951
  "stateBranchMatches": state_branch == branch,
919
952
  "currentStage": state.get("currentStage"),
920
953
  "pipelineStatus": state.get("pipelineStatus", "active"),
954
+ "epic": epic,
955
+ "isEpicMember": is_epic_member,
921
956
  "updatedAt": updated if isinstance(updated, str) else None,
922
957
  "commitDate": commit_date or None,
923
958
  "isCurrentBranch": branch == current_branch,
@@ -988,6 +1023,8 @@ def _print_discover(payload: dict) -> None:
988
1023
  marks.append("remote-tracking")
989
1024
  if not cand["stateBranchMatches"] and cand["stateBranch"]:
990
1025
  marks.append(f"state records branch {cand['stateBranch']}")
1026
+ if cand.get("isEpicMember"):
1027
+ marks.append(f"member of epic {cand.get('epic') or '?'}")
991
1028
  suffix = f" ({'; '.join(marks)})" if marks else ""
992
1029
  print(
993
1030
  f" {cand['branch']}: stage={cand['currentStage'] or '?'} "
@@ -1054,6 +1091,7 @@ def discover_all(specs_dir: str) -> dict:
1054
1091
  state = _read_state_at_ref(ref, path)
1055
1092
  state_branch = state.get("branch")
1056
1093
  state_branch = state_branch if isinstance(state_branch, str) else None
1094
+ epic, is_epic_member = _epic_membership(path, specs_rel, state)
1057
1095
  seen.append({
1058
1096
  "branch": branch,
1059
1097
  "remoteTracking": is_remote,
@@ -1062,6 +1100,8 @@ def discover_all(specs_dir: str) -> dict:
1062
1100
  "stateBranchMatches": state_branch == branch,
1063
1101
  "currentStage": state.get("currentStage"),
1064
1102
  "pipelineStatus": state.get("pipelineStatus", "active"),
1103
+ "epic": epic,
1104
+ "isEpicMember": is_epic_member,
1065
1105
  "commitDate": commit_date or None,
1066
1106
  "isCurrentBranch": branch == current_branch,
1067
1107
  "switchCommand": f"git switch {branch}",
@@ -1097,6 +1137,8 @@ def _print_discover_all(payload: dict) -> None:
1097
1137
  marks.append("remote-tracking")
1098
1138
  if not cand["stateBranchMatches"] and cand["stateBranch"]:
1099
1139
  marks.append(f"state records branch {cand['stateBranch']}")
1140
+ if cand.get("isEpicMember"):
1141
+ marks.append(f"member of epic {cand.get('epic') or '?'}")
1100
1142
  suffix = f" ({'; '.join(marks)})" if marks else ""
1101
1143
  print(f" {cand['branch']}: stage={cand['currentStage'] or '?'} "
1102
1144
  f"status={cand['pipelineStatus']}{suffix}")
@@ -1191,6 +1233,77 @@ def _print_reconcile(payload: dict) -> None:
1191
1233
  print(f" → write state branch := {payload['newBranch']} ({payload['statePath']})")
1192
1234
 
1193
1235
 
1236
+ # --------------------------------------------------------------------------- #
1237
+ # Epic-member base guard (Issue #125) — detached-base detection
1238
+ # --------------------------------------------------------------------------- #
1239
+
1240
+
1241
+ def check_epic_base(
1242
+ name: str, specs_dir: Path, config_path: Path, epic: str | None = None
1243
+ ) -> dict:
1244
+ """Verify the current HEAD actually contains the epic manifest for a nested member.
1245
+
1246
+ Defense-in-depth for the split-brain-epic failure (Issue #125): when a feature
1247
+ resolves to a nested epic-member directory but the epic's ``epic-manifest.json``
1248
+ is absent from the current checkout, the member stub was reached from a branch
1249
+ that predates (or otherwise lacks) the manifest commit — a detached base. This
1250
+ is read-only: it emits a decision; the caller stops or warns.
1251
+
1252
+ Actions:
1253
+ - ``none`` — not a git repo, a standalone feature (no epic to check), or the
1254
+ manifest is present on HEAD. Nothing to do.
1255
+ - ``not-resolved`` — the feature does not resolve on the current branch.
1256
+ - ``warn-detached-base`` — nested member resolves here but the manifest is
1257
+ missing on HEAD; ``homeBranch`` is the member stub's recorded ``branch``.
1258
+ """
1259
+ base = {
1260
+ "feature": name,
1261
+ "gitRepo": True,
1262
+ "epic": epic,
1263
+ "isEpicMember": False,
1264
+ "manifestOnHead": None,
1265
+ "homeBranch": None,
1266
+ }
1267
+ if _git_output(["rev-parse", "--git-dir"]) is None:
1268
+ return {**base, "gitRepo": False, "action": "none",
1269
+ "reason": "not a git repository"}
1270
+ config = _load_config(config_path)
1271
+ row = next(
1272
+ (r for r in build_rows(specs_dir, config)
1273
+ if r["name"] == name and (epic is None or r["epic"] == epic)),
1274
+ None,
1275
+ )
1276
+ if row is None:
1277
+ return {**base, "action": "not-resolved",
1278
+ "reason": "feature state does not resolve on the current branch — "
1279
+ "use discover-feature to locate it"}
1280
+ member_epic = row["epic"]
1281
+ if not member_epic:
1282
+ return {**base, "action": "none",
1283
+ "reason": "standalone feature — no epic base to check"}
1284
+ base = {**base, "epic": member_epic, "isEpicMember": True,
1285
+ "homeBranch": row["branch"]}
1286
+ manifest = specs_dir / member_epic / MANIFEST_FILENAME
1287
+ if manifest.is_file():
1288
+ return {**base, "manifestOnHead": True, "action": "none",
1289
+ "reason": f"epic manifest present on the current branch "
1290
+ f"({member_epic}/{MANIFEST_FILENAME})"}
1291
+ return {**base, "manifestOnHead": False, "action": "warn-detached-base",
1292
+ "reason": f"member of epic {member_epic!r} resolves here, but "
1293
+ f"{member_epic}/{MANIFEST_FILENAME} is absent on the current "
1294
+ f"branch — this base predates or lacks the epic manifest"}
1295
+
1296
+
1297
+ def _print_check_epic_base(payload: dict) -> None:
1298
+ """Human-readable check-epic-base report."""
1299
+ if not payload["gitRepo"]:
1300
+ print(f"check-epic-base {payload['feature']}: not a git repository")
1301
+ return
1302
+ print(f"check-epic-base {payload['feature']}: {payload['action']} — {payload['reason']}")
1303
+ if payload["action"] == "warn-detached-base":
1304
+ print(f" → switch to the epic's home branch: {payload['homeBranch'] or '(unknown)'}")
1305
+
1306
+
1194
1307
  # --------------------------------------------------------------------------- #
1195
1308
  # Scripted Stage Exit
1196
1309
  # --------------------------------------------------------------------------- #
@@ -1587,6 +1700,16 @@ def main() -> int:
1587
1700
  p_recon.add_argument("--epic", default=None, help="Epic name for a nested member")
1588
1701
  p_recon.add_argument("--json", action="store_true", dest="json_output")
1589
1702
 
1703
+ p_base = sub.add_parser(
1704
+ "check-epic-base",
1705
+ help="Verify HEAD contains the epic manifest for a resolved nested member",
1706
+ )
1707
+ p_base.add_argument("--feature", required=True, help="Feature name")
1708
+ p_base.add_argument("--specs-dir", default="./specs", help="Specs directory")
1709
+ p_base.add_argument("--config", default="./forge.config.json", help="forge.config.json path")
1710
+ p_base.add_argument("--epic", default=None, help="Epic name for a nested member")
1711
+ p_base.add_argument("--json", action="store_true", dest="json_output")
1712
+
1590
1713
  p_exit = sub.add_parser(
1591
1714
  "stage-exit", help="Emit the Scripted Stage Exit directives + NEXT-STEPS block"
1592
1715
  )
@@ -1667,6 +1790,16 @@ def main() -> int:
1667
1790
  _print_reconcile(payload)
1668
1791
  return 0
1669
1792
 
1793
+ if args.cmd == "check-epic-base":
1794
+ payload = check_epic_base(
1795
+ args.feature, Path(args.specs_dir), Path(args.config), args.epic
1796
+ )
1797
+ if args.json_output:
1798
+ print(json.dumps(payload, indent=2, ensure_ascii=False))
1799
+ else:
1800
+ _print_check_epic_base(payload)
1801
+ return 0
1802
+
1670
1803
  if args.cmd == "stage-exit":
1671
1804
  payload = stage_exit(
1672
1805
  args.feature,
@@ -90,6 +90,8 @@ After rendering a **per-feature** dashboard for an **active** pipeline (skip thi
90
90
 
91
91
  **1. Read the next step.** From the `rank-features --json` output (above), find this feature's row and read its `nextStage`, `nextCommand`, `verifyPending`, `verifyCommand`, `verifyStage`, `verifyState`, `autoVerify`, `autoFix`, and `verifyGate` (the resolved gate: `none` → no verify action; `auto` → the §2b catch-up; `standard` → the §3 gate). If the feature is not in the `active` list (paused/abandoned), or `nextStage` is `null` (every production stage complete), skip the drive prompt — instead congratulate the user and, if `forge-6-docs` has not run, offer it; otherwise note the pipeline is complete. If the payload has a non-empty `invalidAutoVerifyKeys`, print a one-line warning first (e.g. "⚠️ forge.config.json `autoVerifyStages` has unknown keys: … — they are ignored; fix the typo").
92
92
 
93
+ **Detached-epic hint (completion of a *standalone* feature, Issue #125).** When `nextStage` is `null` for a feature whose row has no `epic` (a standalone completion), run `discover-feature "{feature}" --json` (via the standard prelude) *before* congratulating. If any candidate has `isEpicMember: true` on another branch, add an **additive, non-blocking** hint — it does not change the completion, only flags a likely split-brain: "⚠️ Heads-up: `{feature}` matches a member of epic `{epic}` on branch `{stateBranch}`. This standalone pipeline may have been forged detached from that epic. To reconcile, see `docs/recovery-detached-epic-member.md` (or continue — this is only a heads-up)." Skip the hint for epic-member rows (their `epic` is non-null) and when discovery surfaces no epic-member candidate.
94
+
93
95
  **2. Check the context window.** Run the context-usage helper so you can advise whether to continue here or start the next stage in a fresh session:
94
96
  ```bash
95
97
  R="$(bash -c 'for d in "${FEATURE_FORGE_ROOT:-}" "$HOME"/.claude/skills/feature-forge "$HOME"/.claude/plugins/cache/*/feature-forge/* "$HOME"/.claude/plugins/*/feature-forge "$HOME"/.agents/skills/feature-forge ./.agents/skills/feature-forge; do [ -x "$d/scripts/forge-root.sh" ] && exec "$d/scripts/forge-root.sh"; done')"
@@ -12,12 +12,30 @@ Create a thorough, requirements-only PRD through relentless structured interview
12
12
 
13
13
  Read and follow `references/shared-conventions.md` for feature name validation, configuration reading, and force mode handling before proceeding.
14
14
 
15
+ **`--force-standalone` (forge-1-prd only).** A distinct flag from `--force`: it bypasses only the **Mint Guard** in Step 1 (letting you intentionally fork a name that is a known epic member into a detached standalone feature). It does **not** imply `--force` — prerequisite checks and the Stage-Entry Guard still run. Use it only when you genuinely mean to create a standalone feature that shares a name with an epic member on another branch.
16
+
15
17
  ## Step 1: Read Configuration and Check State
16
18
 
17
19
  ### Branch Setup (if using git)
18
20
  Invoke the **Branch Setup** block in `references/shared-conventions.md` with `{label}` = `{feature}` and `{scope}` = `feature`. It self-gates (skips when not a git repo, when `branchPerFeature` is false, or for an epic member that inherits the epic's branch), detects whether you're on the default branch, and strongly recommends — still optionally — creating `{branchPrefix}{feature}` when you are. Do this before directory resolution.
19
21
 
20
- Set the working directory by invoking the **Feature Directory Resolution** block in `references/shared-conventions.md`, which yields `{resolvedFeatureDir}`. Note one PRD-specific caveat: at PRD time a brand-new standalone feature may have NO directory yet, so resolution is expected to fail `not-found` for a never-started standalone feature — in that case forge-1 creates `{specsDir}/{feature}/` as today. For an epic member the directory already exists (created empty by forge-0-epic with an `epic` back-pointer), so resolution succeeds and yields the nested path.
22
+ Set the working directory by invoking the **Feature Directory Resolution** block in `references/shared-conventions.md`, which yields `{resolvedFeatureDir}`. Note one PRD-specific caveat: at PRD time a brand-new standalone feature may have NO directory yet, so resolution is expected to fail for a never-started standalone feature — as `not-found` (exit 1) when `{specsDir}/` already exists (other features present), or as `specs dir not found` (exit 2) when `{specsDir}/` itself does not exist yet (the very first feature, or a branch that never had a specs tree). In **both** of those "about to create a brand-new standalone" cases forge-1 creates `{specsDir}/{feature}/` as today. (The *other* exit-2 errors — `unsafe-name`, a path-containment escape — are genuine STOPs, never a mint.) For an epic member the directory already exists (created empty by forge-0-epic with an `epic` back-pointer), so resolution succeeds and yields the nested path.
23
+
24
+ ### Mint Guard: refuse to fork a known epic member into a detached standalone (Issue #125)
25
+
26
+ Run this sub-step **whenever forge-1 is about to mint a brand-new flat standalone `{specsDir}/{feature}/`** — that is, when Feature Directory Resolution returned either `not-found` (exit 1) **or** `specs dir not found` (the exit-2 missing-specs-dir flavor, e.g. a clean default branch that has never had a specs tree). The exit-2 case is the *cleanest* split-brain trigger: on a branch that predates the epic, `{specsDir}/` may not exist at all, yet cross-branch discovery still sees the member on the epic branch. It prevents the split-brain-epic failure where a member of an epic (whose manifest lives on a *different, unmerged* branch) is silently forged as a disjoint standalone feature carrying no `epic` back-pointer. Skip it entirely when resolution succeeded (an epic member's directory already exists — resolution yields the nested path, so this never fires), on the other exit-2 errors (`unsafe-name` / path-containment — those STOP, they never mint), and when `--force-standalone` was passed (see below).
27
+
28
+ 1. Run cross-branch discovery for this exact name (branch-agnostic — it scans all refs regardless of current HEAD):
29
+ ```bash
30
+ R="$(bash -c 'for d in "${FEATURE_FORGE_ROOT:-}" "$HOME"/.claude/skills/feature-forge "$HOME"/.claude/plugins/cache/*/feature-forge/* "$HOME"/.claude/plugins/*/feature-forge "$HOME"/.agents/skills/feature-forge ./.agents/skills/feature-forge; do [ -x "$d/scripts/forge-root.sh" ] && exec "$d/scripts/forge-root.sh"; done')"
31
+ [ -n "$R" ] || { echo "feature-forge: cannot locate plugin root" >&2; exit 1; }
32
+ python3 "$R/scripts/forge-session.py" discover-feature "{feature}" --specs-dir "{specsDir}" --json
33
+ ```
34
+ 2. **If any candidate has `isEpicMember: true` → HARD STOP.** This is not the soft switch/fetch/treat-as-new menu from the Feature Directory Resolution block — do **not** create any directory and do **not** fall through to the interview. Emit verbatim (filling `{epic}` and `{stateBranch}` from that candidate's `epic` and `stateBranch`):
35
+ > `{feature}` is a member of epic `{epic}` (recorded on branch `{stateBranch}`). You appear to be on a branch that does not contain that epic. Switch to `{stateBranch}` and run `/feature-forge:forge-1-prd {feature}` there, or pass `--force-standalone` to intentionally fork a detached standalone feature.
36
+ 3. **If candidates exist but none are epic members** → keep today's soft behavior: this is the ordinary cross-branch-discovery case already handled by the Feature Directory Resolution block's **Candidates found** menu (switch / fetch+switch / treat-as-new / stop). Defer to it.
37
+ 4. **If nothing was found** (no candidates) → proceed to mint the flat standalone feature as today.
38
+ 5. **If `--force-standalone` was passed** → skip this guard entirely, log a one-line warning ("Forking `{feature}` as a detached standalone despite epic membership on `{stateBranch}`"), and proceed to create the flat feature. `--force-standalone` is distinct from `--force` and does **not** imply it (see the Force Mode note below).
21
39
 
22
40
  After resolution, invoke the **Stage-Entry Guard** block in `references/shared-conventions.md` with `{stage}` = `forge-1-prd`. It classifies re-entry (fresh / interrupted / re-authoring), runs the resume-vs-restart gate and the "create a new version?" warning as applicable, and applies the entry stamp on the authoring paths. For a brand-new standalone feature there is no state file yet, so the guard's **fresh** arm applies with nothing to prompt; the entry stamp lands when the state file is first created in Step 6.
23
41
 
@@ -40,6 +40,8 @@ Resolve the **loop runner** from the `loopRunner` block in `forge.config.json`,
40
40
 
41
41
  After the prerequisite check, invoke the **Stage-Entry Guard** block in `references/shared-conventions.md` with `{stage}` = `forge-4-backlog` — it detects an interrupted or complete `backlog.json`, runs the resume/restart or new-version gate, and stamps entry before Step 2 loads the specs. (The backlog is a single artifact, so "resume" means: reuse the existing `backlog.json` if the previous run wrote it, rather than re-authoring from scratch.)
42
42
 
43
+ Then invoke the **Epic-Member Base Guard** block in `references/shared-conventions.md` (this stage does not run Epic Context Injection, so invoke it explicitly here). It self-gates to a no-op for standalone features; for a nested epic member on a branch that lacks the epic manifest it stops with a home-branch pointer (Issue #125).
44
+
43
45
  **Verification check.** Check whether the specs have been verified. If not, use the host's question mechanism to warn with the cost of skipping: "Specs haven't been verified yet. Recommended: run `/feature-forge:forge-verify {feature}` first — unverified specs can carry gaps or contradictions that get baked into backlog items and only surface mid-loop, where they're far more expensive to fix. Continue anyway?" Offer **Verify first (recommended)** · **Continue without verifying**.
44
46
 
45
47
  ## Step 2: Load All Specs
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "feature-forge",
3
- "version": "0.12.6",
3
+ "version": "0.12.7",
4
4
  "agent": "cursor",
5
5
  "generatedBy": "python3 scripts/build-adapters.py"
6
6
  }
@@ -159,6 +159,28 @@ python3 "$R/scripts/epic-manifest.py" \
159
159
 
160
160
  If `render-status` fails, proceed with **only** EPIC.md + charter (a corrupt manifest must not silently inject stale dep specs — REQ-ROBUST-02): on **exit 1**, parse the `{findings[]}` JSON from stdout and surface each; on **exit 2**, surface the plain `Error:` line from stderr verbatim. Do not attempt to parse findings JSON on an exit-2 failure (stdout is empty).
161
161
 
162
+ **After injecting context, invoke the Epic-Member Base Guard block below** (it self-gates to a no-op for standalone features and features that do not resolve as a nested member).
163
+
164
+ ## Epic-Member Base Guard
165
+
166
+ Defense-in-depth for the split-brain-epic failure (Issue #125). Invoke this block in the authoring stages (`forge-1-prd`..`forge-4-backlog`) once the feature has resolved — right after **Epic Context Injection** for the stages that run it (`forge-1-prd`..`forge-3-specs`), and right after **Feature Directory Resolution** for `forge-4-backlog`. It confirms that a **resolved nested epic member** actually sits on a branch that contains the epic's manifest. Without this, a member reached from a branch cut *before* the epic-manifest commit (or that otherwise lacks it) would author specs against an epic decomposition that is not present — the exact drift that produces a disjoint, split-brain member. **Skip if not a git repo or `branchPerFeature` is false.**
167
+
168
+ ```bash
169
+ R="$(bash -c 'for d in "${CLAUDE_PLUGIN_ROOT:-}" "$HOME"/.claude/skills/feature-forge "$HOME"/.claude/plugins/cache/*/feature-forge/* "$HOME"/.claude/plugins/*/feature-forge "$HOME"/.agents/skills/feature-forge ./.agents/skills/feature-forge; do [ -x "$d/scripts/forge-root.sh" ] && exec "$d/scripts/forge-root.sh"; done')"
170
+ [ -n "$R" ] || { echo "feature-forge: cannot locate plugin root" >&2; exit 1; }
171
+ python3 "$R/scripts/forge-session.py" check-epic-base --feature "{feature}" --specs-dir "{specsDir}" --json
172
+ ```
173
+
174
+ Act on the emitted `action`:
175
+ - **`none`** — a standalone feature (no epic to check) or the manifest is present on the current branch. Proceed silently. This is the no-op path for standalone features (REQ-COMPAT-01), so standalone behavior is unchanged.
176
+ - **`not-resolved`** — the feature does not resolve on the current branch. Proceed silently (the caller's own resolution already handled that case).
177
+ - **`warn-detached-base`** — a nested member resolves here but the epic's `epic-manifest.json` is **absent on this branch**. **STOP** unless `--force` was passed, and surface verbatim (filling `{epic}` and `{homeBranch}` from the payload's `epic` and `homeBranch`):
178
+ > `{feature}` is a member of epic `{epic}`, but this branch does not contain the epic manifest (`{specsDir}/{epic}/epic-manifest.json`). This base predates or lacks the epic. Switch to the epic's home branch `{homeBranch}` and re-run, or pass `--force` to author against a detached base anyway.
179
+
180
+ With `--force`, log a one-line warning ("Authoring `{feature}` against a detached epic base — manifest not on this branch") and proceed, consistent with the other guards.
181
+
182
+ If the helper is unavailable (a non-Claude host without the resolver), skip this block — it is best-effort defense in depth, not a hard prerequisite.
183
+
162
184
  ## Pipeline State Protocol
163
185
 
164
186
  Write pipeline state conforming to `references/pipeline-state-schema.json`. Always update `updatedAt` when modifying pipeline state.
@@ -11,6 +11,8 @@ root navigator:
11
11
  python3 forge-session.py discover-feature [NAME | --all] [--specs-dir DIR] [--json]
12
12
  python3 forge-session.py reconcile-branch --feature F [--specs-dir DIR] \
13
13
  [--config FILE] [--epic E] [--json]
14
+ python3 forge-session.py check-epic-base --feature F [--specs-dir DIR] \
15
+ [--config FILE] [--epic E] [--json]
14
16
  python3 forge-session.py stage-exit --feature F --stage S [--specs-dir DIR] \
15
17
  [--config FILE] [--epic E] [--next-feature N] [--host claude|generic] [--json]
16
18
 
@@ -45,7 +47,17 @@ concluding it was never started. When nothing is found locally it also asks
45
47
  `git ls-remote --heads origin` about branches a single-branch clone never
46
48
  fetched, and emits the exact `git fetch`/`git switch` commands a caller could
47
49
  run. It is strictly read-only — it never checks anything out itself — and
48
- like `doctor` it always exits 0 and degrades to data.
50
+ like `doctor` it always exits 0 and degrades to data. Each candidate also
51
+ carries `epic`/`isEpicMember`, so a caller minting a new standalone feature can
52
+ refuse when the name is a known epic member discoverable on another branch
53
+ (the split-brain-epic guard, Issue #125).
54
+
55
+ `check-epic-base` is the defense-in-depth companion: given a feature that
56
+ resolves to a nested epic member on the current branch, it confirms the epic's
57
+ `epic-manifest.json` is actually present on HEAD. When it is absent, the member
58
+ was reached from a branch that predates or lacks the manifest commit (a detached
59
+ base) and the command emits `warn-detached-base` with the member's recorded home
60
+ branch. Read-only; always exits 0.
49
61
 
50
62
  `stage-exit` computes everything an authoring stage's closing used to derive
51
63
  in prose (the Scripted Stage Exit, `references/stage-exit-protocol.md`):
@@ -848,6 +860,26 @@ def _read_state_at_ref(ref: str, path: str) -> dict:
848
860
  return parsed if isinstance(parsed, dict) else {}
849
861
 
850
862
 
863
+ def _epic_membership(path: str, specs_rel: str, state: dict) -> tuple[str | None, bool]:
864
+ """Derive ``(epic, isEpicMember)`` for a discovered candidate.
865
+
866
+ A candidate is an epic member when its state carries an ``epic`` back-pointer
867
+ **or** its path is nested (``{specsDir}/{epic}/{name}/.pipeline-state.json``).
868
+ Nested-ness is structurally authoritative; the ``epic`` field is the recorded
869
+ back-pointer. When the state lacks the field, the nested directory name is used
870
+ so the signal is never "member of epic None".
871
+ """
872
+ prefix = specs_rel + "/"
873
+ nested_epic: str | None = None
874
+ if path.startswith(prefix):
875
+ segments = path[len(prefix):].split("/")
876
+ if len(segments) == 3: # [epic, name, state-file]
877
+ nested_epic = segments[0]
878
+ epic = state.get("epic")
879
+ epic = epic if isinstance(epic, str) and epic else nested_epic
880
+ return epic, bool(nested_epic) or bool(epic)
881
+
882
+
851
883
  def _list_refs(pattern: str) -> list[tuple[str, str]]:
852
884
  """Return ``(short_ref, committer_date)`` pairs under a ref namespace."""
853
885
  raw = _git_output([
@@ -908,6 +940,7 @@ def discover_feature(name: str, specs_dir: str) -> dict:
908
940
  state_branch = state.get("branch")
909
941
  state_branch = state_branch if isinstance(state_branch, str) else None
910
942
  updated = state.get("updatedAt")
943
+ epic, is_epic_member = _epic_membership(path, specs_rel, state)
911
944
  matched_branches.add(branch)
912
945
  candidates.append({
913
946
  "branch": branch,
@@ -918,6 +951,8 @@ def discover_feature(name: str, specs_dir: str) -> dict:
918
951
  "stateBranchMatches": state_branch == branch,
919
952
  "currentStage": state.get("currentStage"),
920
953
  "pipelineStatus": state.get("pipelineStatus", "active"),
954
+ "epic": epic,
955
+ "isEpicMember": is_epic_member,
921
956
  "updatedAt": updated if isinstance(updated, str) else None,
922
957
  "commitDate": commit_date or None,
923
958
  "isCurrentBranch": branch == current_branch,
@@ -988,6 +1023,8 @@ def _print_discover(payload: dict) -> None:
988
1023
  marks.append("remote-tracking")
989
1024
  if not cand["stateBranchMatches"] and cand["stateBranch"]:
990
1025
  marks.append(f"state records branch {cand['stateBranch']}")
1026
+ if cand.get("isEpicMember"):
1027
+ marks.append(f"member of epic {cand.get('epic') or '?'}")
991
1028
  suffix = f" ({'; '.join(marks)})" if marks else ""
992
1029
  print(
993
1030
  f" {cand['branch']}: stage={cand['currentStage'] or '?'} "
@@ -1054,6 +1091,7 @@ def discover_all(specs_dir: str) -> dict:
1054
1091
  state = _read_state_at_ref(ref, path)
1055
1092
  state_branch = state.get("branch")
1056
1093
  state_branch = state_branch if isinstance(state_branch, str) else None
1094
+ epic, is_epic_member = _epic_membership(path, specs_rel, state)
1057
1095
  seen.append({
1058
1096
  "branch": branch,
1059
1097
  "remoteTracking": is_remote,
@@ -1062,6 +1100,8 @@ def discover_all(specs_dir: str) -> dict:
1062
1100
  "stateBranchMatches": state_branch == branch,
1063
1101
  "currentStage": state.get("currentStage"),
1064
1102
  "pipelineStatus": state.get("pipelineStatus", "active"),
1103
+ "epic": epic,
1104
+ "isEpicMember": is_epic_member,
1065
1105
  "commitDate": commit_date or None,
1066
1106
  "isCurrentBranch": branch == current_branch,
1067
1107
  "switchCommand": f"git switch {branch}",
@@ -1097,6 +1137,8 @@ def _print_discover_all(payload: dict) -> None:
1097
1137
  marks.append("remote-tracking")
1098
1138
  if not cand["stateBranchMatches"] and cand["stateBranch"]:
1099
1139
  marks.append(f"state records branch {cand['stateBranch']}")
1140
+ if cand.get("isEpicMember"):
1141
+ marks.append(f"member of epic {cand.get('epic') or '?'}")
1100
1142
  suffix = f" ({'; '.join(marks)})" if marks else ""
1101
1143
  print(f" {cand['branch']}: stage={cand['currentStage'] or '?'} "
1102
1144
  f"status={cand['pipelineStatus']}{suffix}")
@@ -1191,6 +1233,77 @@ def _print_reconcile(payload: dict) -> None:
1191
1233
  print(f" → write state branch := {payload['newBranch']} ({payload['statePath']})")
1192
1234
 
1193
1235
 
1236
+ # --------------------------------------------------------------------------- #
1237
+ # Epic-member base guard (Issue #125) — detached-base detection
1238
+ # --------------------------------------------------------------------------- #
1239
+
1240
+
1241
+ def check_epic_base(
1242
+ name: str, specs_dir: Path, config_path: Path, epic: str | None = None
1243
+ ) -> dict:
1244
+ """Verify the current HEAD actually contains the epic manifest for a nested member.
1245
+
1246
+ Defense-in-depth for the split-brain-epic failure (Issue #125): when a feature
1247
+ resolves to a nested epic-member directory but the epic's ``epic-manifest.json``
1248
+ is absent from the current checkout, the member stub was reached from a branch
1249
+ that predates (or otherwise lacks) the manifest commit — a detached base. This
1250
+ is read-only: it emits a decision; the caller stops or warns.
1251
+
1252
+ Actions:
1253
+ - ``none`` — not a git repo, a standalone feature (no epic to check), or the
1254
+ manifest is present on HEAD. Nothing to do.
1255
+ - ``not-resolved`` — the feature does not resolve on the current branch.
1256
+ - ``warn-detached-base`` — nested member resolves here but the manifest is
1257
+ missing on HEAD; ``homeBranch`` is the member stub's recorded ``branch``.
1258
+ """
1259
+ base = {
1260
+ "feature": name,
1261
+ "gitRepo": True,
1262
+ "epic": epic,
1263
+ "isEpicMember": False,
1264
+ "manifestOnHead": None,
1265
+ "homeBranch": None,
1266
+ }
1267
+ if _git_output(["rev-parse", "--git-dir"]) is None:
1268
+ return {**base, "gitRepo": False, "action": "none",
1269
+ "reason": "not a git repository"}
1270
+ config = _load_config(config_path)
1271
+ row = next(
1272
+ (r for r in build_rows(specs_dir, config)
1273
+ if r["name"] == name and (epic is None or r["epic"] == epic)),
1274
+ None,
1275
+ )
1276
+ if row is None:
1277
+ return {**base, "action": "not-resolved",
1278
+ "reason": "feature state does not resolve on the current branch — "
1279
+ "use discover-feature to locate it"}
1280
+ member_epic = row["epic"]
1281
+ if not member_epic:
1282
+ return {**base, "action": "none",
1283
+ "reason": "standalone feature — no epic base to check"}
1284
+ base = {**base, "epic": member_epic, "isEpicMember": True,
1285
+ "homeBranch": row["branch"]}
1286
+ manifest = specs_dir / member_epic / MANIFEST_FILENAME
1287
+ if manifest.is_file():
1288
+ return {**base, "manifestOnHead": True, "action": "none",
1289
+ "reason": f"epic manifest present on the current branch "
1290
+ f"({member_epic}/{MANIFEST_FILENAME})"}
1291
+ return {**base, "manifestOnHead": False, "action": "warn-detached-base",
1292
+ "reason": f"member of epic {member_epic!r} resolves here, but "
1293
+ f"{member_epic}/{MANIFEST_FILENAME} is absent on the current "
1294
+ f"branch — this base predates or lacks the epic manifest"}
1295
+
1296
+
1297
+ def _print_check_epic_base(payload: dict) -> None:
1298
+ """Human-readable check-epic-base report."""
1299
+ if not payload["gitRepo"]:
1300
+ print(f"check-epic-base {payload['feature']}: not a git repository")
1301
+ return
1302
+ print(f"check-epic-base {payload['feature']}: {payload['action']} — {payload['reason']}")
1303
+ if payload["action"] == "warn-detached-base":
1304
+ print(f" → switch to the epic's home branch: {payload['homeBranch'] or '(unknown)'}")
1305
+
1306
+
1194
1307
  # --------------------------------------------------------------------------- #
1195
1308
  # Scripted Stage Exit
1196
1309
  # --------------------------------------------------------------------------- #
@@ -1587,6 +1700,16 @@ def main() -> int:
1587
1700
  p_recon.add_argument("--epic", default=None, help="Epic name for a nested member")
1588
1701
  p_recon.add_argument("--json", action="store_true", dest="json_output")
1589
1702
 
1703
+ p_base = sub.add_parser(
1704
+ "check-epic-base",
1705
+ help="Verify HEAD contains the epic manifest for a resolved nested member",
1706
+ )
1707
+ p_base.add_argument("--feature", required=True, help="Feature name")
1708
+ p_base.add_argument("--specs-dir", default="./specs", help="Specs directory")
1709
+ p_base.add_argument("--config", default="./forge.config.json", help="forge.config.json path")
1710
+ p_base.add_argument("--epic", default=None, help="Epic name for a nested member")
1711
+ p_base.add_argument("--json", action="store_true", dest="json_output")
1712
+
1590
1713
  p_exit = sub.add_parser(
1591
1714
  "stage-exit", help="Emit the Scripted Stage Exit directives + NEXT-STEPS block"
1592
1715
  )
@@ -1667,6 +1790,16 @@ def main() -> int:
1667
1790
  _print_reconcile(payload)
1668
1791
  return 0
1669
1792
 
1793
+ if args.cmd == "check-epic-base":
1794
+ payload = check_epic_base(
1795
+ args.feature, Path(args.specs_dir), Path(args.config), args.epic
1796
+ )
1797
+ if args.json_output:
1798
+ print(json.dumps(payload, indent=2, ensure_ascii=False))
1799
+ else:
1800
+ _print_check_epic_base(payload)
1801
+ return 0
1802
+
1670
1803
  if args.cmd == "stage-exit":
1671
1804
  payload = stage_exit(
1672
1805
  args.feature,