forgedock 1.53.0 → 1.54.0

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 (185) hide show
  1. package/.claude-plugin/marketplace.json +51 -0
  2. package/README.md +8 -2
  3. package/bin/auth/app-manifest.mjs +89 -0
  4. package/bin/auth/app-manifest.test.mjs +75 -0
  5. package/bin/auth/app-token.mjs +256 -0
  6. package/bin/auth/app-token.test.mjs +232 -0
  7. package/bin/brand.mjs +7 -0
  8. package/bin/config-history.mjs +151 -0
  9. package/bin/config-schema.mjs +115 -0
  10. package/bin/demo.mjs +65 -11
  11. package/bin/engine/outcome-codes.mjs +6 -3
  12. package/bin/engine/telemetry-seam.mjs +8 -2
  13. package/bin/engine/telemetry-seam.test.mjs +17 -0
  14. package/bin/engine-cli.mjs +57 -20
  15. package/bin/first-run.mjs +122 -0
  16. package/bin/forgedock.mjs +128 -146
  17. package/bin/help-text.mjs +144 -0
  18. package/bin/hooks/pre-tool-use.mjs +7 -0
  19. package/bin/journey.mjs +82 -83
  20. package/bin/lean/acceptance.mjs +313 -0
  21. package/bin/lean/acceptance.test.mjs +215 -0
  22. package/bin/lean/activation.mjs +18 -0
  23. package/bin/lean/activation.test.mjs +23 -1
  24. package/bin/lean/batch-health.mjs +74 -1
  25. package/bin/lean/batch-health.test.mjs +54 -1
  26. package/bin/lean/batch.test.mjs +11 -9
  27. package/bin/lean/branchlock.mjs +54 -0
  28. package/bin/lean/branchlock.test.mjs +49 -0
  29. package/bin/lean/ceiling.mjs +72 -0
  30. package/bin/lean/ceiling.test.mjs +54 -0
  31. package/bin/lean/ci-budget.mjs +366 -0
  32. package/bin/lean/ci-budget.test.mjs +167 -0
  33. package/bin/lean/conformance.e2e.test.mjs +7 -0
  34. package/bin/lean/conformance.mjs +77 -19
  35. package/bin/lean/conformance.test.mjs +129 -3
  36. package/bin/lean/context.mjs +35 -6
  37. package/bin/lean/context.test.mjs +27 -1
  38. package/bin/lean/depcache.mjs +25 -1
  39. package/bin/lean/depcache.test.mjs +26 -0
  40. package/bin/lean/e2e.mjs +18 -2
  41. package/bin/lean/e2e.test.mjs +26 -1
  42. package/bin/lean/effects.mjs +40 -11
  43. package/bin/lean/execution.test.mjs +24 -0
  44. package/bin/lean/facts.mjs +3 -3
  45. package/bin/lean/facts.test.mjs +5 -0
  46. package/bin/lean/fixround.mjs +14 -0
  47. package/bin/lean/fixround.test.mjs +25 -2
  48. package/bin/lean/gh-assoc.test.mjs +2 -1
  49. package/bin/lean/integration.mjs +100 -9
  50. package/bin/lean/integration.test.mjs +98 -0
  51. package/bin/lean/issuewatch-parity.mjs +64 -0
  52. package/bin/lean/issuewatch-parity.test.mjs +127 -0
  53. package/bin/lean/issuewatch-release.test.mjs +1 -1
  54. package/bin/lean/issuewatch.mjs +34 -5
  55. package/bin/lean/issuewatch.test.mjs +3 -2
  56. package/bin/lean/lean.mjs +316 -74
  57. package/bin/lean/lean.test.mjs +397 -24
  58. package/bin/lean/mechfix.mjs +124 -0
  59. package/bin/lean/mechfix.test.mjs +75 -0
  60. package/bin/lean/orchestrate.mjs +20 -2
  61. package/bin/lean/phaseledger.mjs +47 -5
  62. package/bin/lean/phaseledger.test.mjs +30 -1
  63. package/bin/lean/precheck.mjs +23 -4
  64. package/bin/lean/precheck.test.mjs +14 -1
  65. package/bin/lean/prereq.mjs +28 -0
  66. package/bin/lean/prereq.test.mjs +20 -0
  67. package/bin/lean/probe.mjs +4 -2
  68. package/bin/lean/prodparity.mjs +52 -0
  69. package/bin/lean/prodparity.test.mjs +67 -0
  70. package/bin/lean/prompts.mjs +69 -12
  71. package/bin/lean/recovery.test.mjs +1 -1
  72. package/bin/lean/release-io.test.mjs +42 -0
  73. package/bin/lean/release-postmerge.mjs +6 -0
  74. package/bin/lean/release-preflight.mjs +58 -0
  75. package/bin/lean/release-preflight.test.mjs +114 -0
  76. package/bin/lean/release-rehearsal.mjs +8 -7
  77. package/bin/lean/release-review.mjs +67 -11
  78. package/bin/lean/release-review.test.mjs +128 -1
  79. package/bin/lean/release-snapshot.mjs +188 -0
  80. package/bin/lean/release-snapshot.test.mjs +190 -0
  81. package/bin/lean/release.mjs +80 -12
  82. package/bin/lean/release.test.mjs +95 -0
  83. package/bin/lean/render.mjs +1 -1
  84. package/bin/lean/replan.mjs +184 -0
  85. package/bin/lean/replan.test.mjs +110 -0
  86. package/bin/lean/resume.mjs +9 -7
  87. package/bin/lean/resume.test.mjs +16 -0
  88. package/bin/lean/schedd.mjs +34 -1
  89. package/bin/lean/schedd.test.mjs +21 -1
  90. package/bin/lean/selfreview.mjs +94 -0
  91. package/bin/lean/selfreview.test.mjs +58 -1
  92. package/bin/lean/selftest-gate.mjs +22 -0
  93. package/bin/lean/selftest-gate.test.mjs +18 -1
  94. package/bin/lean/selftest-journey.mjs +234 -0
  95. package/bin/lean/selftest-journey.test.mjs +130 -0
  96. package/bin/lean/selftest-live.mjs +2 -1
  97. package/bin/lean/seqlease.mjs +35 -1
  98. package/bin/lean/seqlease.test.mjs +15 -0
  99. package/bin/lean/seqreserve.e2e.test.mjs +135 -0
  100. package/bin/lean/seqreserve.mjs +73 -0
  101. package/bin/lean/seqreserve.test.mjs +134 -0
  102. package/bin/lean/sequence.mjs +35 -6
  103. package/bin/lean/seqversioned.mjs +147 -0
  104. package/bin/lean/stagestamp.mjs +28 -0
  105. package/bin/lean/stagestamp.test.mjs +32 -0
  106. package/bin/lean/surfaces.mjs +75 -0
  107. package/bin/lean/surfaces.test.mjs +59 -0
  108. package/bin/lean/toolplace.mjs +28 -0
  109. package/bin/lean/toolplace.test.mjs +24 -0
  110. package/bin/lean/toolstats.mjs +3 -1
  111. package/bin/lean/toolstats.test.mjs +11 -0
  112. package/bin/lean/validatebest.mjs +28 -0
  113. package/bin/lean/validatebest.test.mjs +27 -0
  114. package/bin/pool/agent.mjs +9 -0
  115. package/bin/pool/docker.mjs +5 -0
  116. package/bin/pool/router.mjs +8 -4
  117. package/bin/prereqs.mjs +111 -0
  118. package/bin/replay-timelapse.mjs +149 -0
  119. package/bin/review-staging.mjs +100 -16
  120. package/bin/review-staging.test.mjs +18 -0
  121. package/bin/runner.mjs +43 -6
  122. package/bin/splash-install.mjs +157 -0
  123. package/bin/stats/aggregate.mjs +8 -1
  124. package/bin/stats/conformance-outcomes.mjs +100 -19
  125. package/bin/stats/conformance-outcomes.test.mjs +87 -1
  126. package/bin/stats/depth.mjs +88 -31
  127. package/bin/stats/depth.test.mjs +63 -38
  128. package/bin/stats/efficiency.mjs +26 -5
  129. package/bin/stats/efficiency.test.mjs +45 -1
  130. package/bin/stats/first-review.mjs +77 -0
  131. package/bin/stats/first-review.test.mjs +36 -0
  132. package/bin/stats/firstmerge.mjs +40 -0
  133. package/bin/stats/firstmerge.test.mjs +41 -0
  134. package/bin/stats/github-source.mjs +51 -13
  135. package/bin/stats/index.mjs +91 -15
  136. package/bin/stats/local-source.mjs +1 -0
  137. package/bin/stats/origin.mjs +80 -0
  138. package/bin/stats/origin.test.mjs +58 -0
  139. package/bin/stats/render.mjs +3 -1
  140. package/bin/stats/scoreboard.mjs +137 -0
  141. package/bin/stats/scoreboard.test.mjs +87 -0
  142. package/bin/stats/stats.test.mjs +80 -0
  143. package/bin/tui.mjs +3 -2
  144. package/commands/bootstrap.md +15 -14
  145. package/commands/deploy-pr.md +18 -3
  146. package/commands/forge-stats.md +1 -1
  147. package/commands/forgedock-ci-setup.md +28 -0
  148. package/commands/forgedock-init.md +4 -5
  149. package/commands/issue.md +2 -0
  150. package/commands/milestone.md +9 -1
  151. package/commands/replay.md +2 -0
  152. package/commands/review-pr-staging.md +4 -1
  153. package/commands/work-on/close.md +8 -0
  154. package/docs/CONFIG.md +105 -10
  155. package/docs/ISSUE-WATCH.md +23 -0
  156. package/docs/OUTCOME-CODES.md +1 -0
  157. package/docs/REPLAY.md +9 -0
  158. package/docs/SELFTEST.md +11 -0
  159. package/docs/STATS.md +19 -2
  160. package/docs/eval/README.md +6 -0
  161. package/docs/eval/adversarial-bench.md +68 -0
  162. package/docs/eval/corpus/adversarial-v1.json +285 -0
  163. package/docs/eval/feature-bench.md +42 -0
  164. package/docs/eval/feature-specs/crud-auth/journeys/notes-crud-isolated.mjs +21 -0
  165. package/docs/eval/feature-specs/crud-auth/journeys/register-login.mjs +12 -0
  166. package/docs/eval/feature-specs/crud-auth/spec.md +15 -0
  167. package/docs/site/start-a-new-project.md +2 -1
  168. package/package.json +5 -2
  169. package/plugins/forgedock-splash/.claude-plugin/plugin.json +10 -0
  170. package/plugins/forgedock-splash/README.md +27 -0
  171. package/plugins/forgedock-splash/hooks/hooks.json +1 -0
  172. package/plugins/forgedock-splash/hooks/register.tsx +74 -0
  173. package/plugins/forgedock-splash/hooks/scene.ts +222 -0
  174. package/plugins/forgedock-splash/types/index.d.ts +10 -0
  175. package/scripts/bench-adversarial.mjs +216 -0
  176. package/scripts/bench-feature.mjs +170 -0
  177. package/scripts/bench-lightlane.mjs +2 -2
  178. package/scripts/bootstrap-create.mjs +2 -2
  179. package/scripts/bootstrap-validate.mjs +35 -2
  180. package/scripts/check-spec-size.sh +4 -3
  181. package/scripts/check-spec-size.test.sh +3 -0
  182. package/scripts/plan-validate-live.mjs +40 -6
  183. package/scripts/review-pr-staging-scope.test.sh +1 -1
  184. package/scripts/review-staging-post.sh +23 -0
  185. package/scripts/review-staging-post.test.sh +8 -0
@@ -1479,6 +1479,13 @@ function checkMainCheckoutMutation(command) {
1479
1479
  }
1480
1480
  for (const hit of mutatingGitHits(tokens)) {
1481
1481
  const targetDir = hit.dir === null ? baseDir : resolvePath(baseDir, hit.dir);
1482
+ // #5333: refs/stash is shared by every worktree of the repo; a lane builder (FORGE_LANE_WORKTREE, set by the engine) must not touch it.
1483
+ if (hit.name === "git stash" && process.env.FORGE_LANE_WORKTREE === "1") {
1484
+ return (
1485
+ "BLOCKED: `git stash` in a lane worktree: the stash stack is shared by every lane of this repo, so a pop can apply another lane's files.\n" +
1486
+ "Use a WIP commit instead (`git add -A && git commit -m wip`); `git stash list` and `git stash show` stay allowed.\n"
1487
+ );
1488
+ }
1482
1489
  if (!isMainCheckout(targetDir)) continue;
1483
1490
  if (hit.branches) {
1484
1491
  // Ref-only verb: only the checked-out branch matters; unresolvable (detached HEAD, error) = allow.
package/bin/journey.mjs CHANGED
@@ -12,6 +12,7 @@
12
12
 
13
13
  import { existsSync, lstatSync, readFileSync, writeFileSync, renameSync, unlinkSync } from "fs";
14
14
  import { join, basename } from "path";
15
+ import { backupToHistory } from "./config-history.mjs";
15
16
 
16
17
  // ---------------------------------------------------------------------------
17
18
  // forge.yaml generation (Task 4)
@@ -505,6 +506,14 @@ export function backupExisting(outputPath) {
505
506
  return { backupName: basename(baseBak) };
506
507
  }
507
508
 
509
+ /**
510
+ * Setup/agent edit of forge.yaml (#5315): record the current file as a config-history version (~/.forge/config-history/<repo>/)
511
+ * and move it away, instead of leaving a forge.yaml.bak in the repo. Same return shape as backupExisting.
512
+ */
513
+ export function backupForgeYaml(outputPath, reason = "setup") {
514
+ return backupToHistory(outputPath, reason);
515
+ }
516
+
508
517
  /**
509
518
  * Lightweight forge.yaml presence/shape check for the install receipt
510
519
  * (Issue #1946) — no YAML parser dependency, mirrors the regex-based
@@ -623,6 +632,7 @@ import {
623
632
  colorMode, motionEnabled, CHROME_STOPS, HERO_MARK, COMPACT_MARK, sleep,
624
633
  } from "./cinema.mjs";
625
634
  import { detectEnvironment, wslPathToWindows } from "./env-detect.mjs";
635
+ import { checkPrereqs, formatNotReady, offerInstall } from "./prereqs.mjs";
626
636
 
627
637
  // ---------------------------------------------------------------------------
628
638
  // URL opener (default openFn implementation — injectable for tests)
@@ -712,7 +722,7 @@ const dimLine = (ctx, s) => (ctx.mode === "none" ? s : `\x1b[2m${s}\x1b[22m`);
712
722
  * and the journey continues — advisory, never fatal. Includes informational
713
723
  * Platform/WSL/Shell rows (via env-detect.mjs) after the pass/fail checks —
714
724
  * those three always report `ok: true`, they surface state rather than gate it.
715
- * @returns {Promise<{ checks: Array<{name, ok, detail, fix?}>, ghReady: boolean }>}
725
+ * @returns {Promise<{ checks: Array<{name, ok, detail, fix?, blocking?}>, ghReady: boolean, blocking: Array }>}
716
726
  */
717
727
  export async function preflight(ctx) {
718
728
  const { stdout: w } = ctx;
@@ -721,61 +731,16 @@ export async function preflight(ctx) {
721
731
  w.write("\n " + ember("F O R G E D O C K", ctx.mode) + "\n");
722
732
  w.write(" " + dimLine(ctx, `──── ${getLogoTagline("install")} ────────────────────`) + "\n\n");
723
733
 
724
- const rows = [
725
- {
726
- label: "Node",
727
- run: async () => {
728
- const major = Number(ctx.nodeVersion.split(".")[0]);
729
- return major >= 18
730
- ? { ok: true, detail: `v${ctx.nodeVersion}` }
731
- : { ok: false, detail: `v${ctx.nodeVersion} — need ≥18`, fix: ["Upgrade Node: https://nodejs.org/"] };
732
- },
733
- },
734
- {
735
- label: "git",
736
- run: async () => {
737
- try {
738
- const v = ctx.exec("git", ["--version"]);
739
- return { ok: true, detail: v.replace(/^git version\s*/, "") };
740
- } catch {
741
- return { ok: false, detail: "not found", fix: ["Install git: https://git-scm.com/downloads"] };
742
- }
743
- },
744
- },
745
- {
746
- label: "Claude Code",
747
- run: async () => {
748
- const claudeDir = claudeDirOf(ctx);
749
- return existsSync(claudeDir)
750
- ? { ok: true, detail: `${claudeDir} found` }
751
- : { ok: false, detail: `${claudeDir} not found`, fix: ["Install Claude Code: https://claude.com/claude-code"] };
752
- },
753
- },
754
- {
755
- label: "GitHub CLI",
756
- run: async () => {
757
- try {
758
- ctx.exec("gh", ["--version"]);
759
- } catch {
760
- return {
761
- ok: false,
762
- detail: "not found",
763
- fix: ["Install gh: https://cli.github.com/", "Windows: winget install GitHub.cli"],
764
- };
765
- }
766
- try {
767
- ctx.exec("gh", ["auth", "status"]);
768
- return { ok: true, detail: "authenticated" };
769
- } catch {
770
- return { ok: false, detail: "not authenticated", fix: ["Run: gh auth login"] };
771
- }
772
- },
773
- },
774
- ];
734
+ // One list shared with `doctor` (prereqs.mjs, #5302). Probed once, shown as rows.
735
+ const prereqs = checkPrereqs({ exec: ctx.exec, nodeVersion: ctx.nodeVersion, claudeDir: claudeDirOf(ctx), platform: ctx.platform });
736
+ const rows = prereqs.map((p) => ({
737
+ label: p.label,
738
+ run: async () => (p.ok ? { ok: true, detail: p.detail } : { ok: false, detail: p.detail, fix: p.fix }),
739
+ }));
775
740
 
776
741
  // Environment reveal rows (platform/WSL/shell) — informational only, never
777
742
  // fail the preflight. Appended after the existing 4 checks so `named[3]`
778
- // (GitHub CLI, used for `ghReady` below) keeps its index.
743
+ // (GitHub CLI, used for `ghReady` below) keeps its index; yq follows it.
779
744
  const envInfo = detectEnvironment({ platform: ctx.platform, env: ctx.env, release: ctx.release });
780
745
  rows.push(
781
746
  {
@@ -799,8 +764,8 @@ export async function preflight(ctx) {
799
764
  );
800
765
 
801
766
  const results = await revealRows(rows, { mode: ctx.mode, motion: ctx.motion, writer: w });
802
- const named = rows.map((r, i) => ({ name: r.label, ...results[i] }));
803
- return { checks: named, ghReady: named[3].ok };
767
+ const named = rows.map((r, i) => ({ name: r.label, ...results[i], ...(prereqs[i] ? { label: prereqs[i].label, blocking: prereqs[i].blocking, auto: prereqs[i].auto, id: prereqs[i].id } : {}) }));
768
+ return { checks: named, ghReady: named[3].ok, blocking: named.filter((c) => c.blocking) };
804
769
  }
805
770
 
806
771
  // ---------------------------------------------------------------------------
@@ -2486,6 +2451,7 @@ export async function forge(ctx) {
2486
2451
  import { detectConfig } from "./init-detect.mjs";
2487
2452
  import { enrich, resolveEnrichBackend } from "./init-enrich.mjs";
2488
2453
  import { isClaudeCliAvailable } from "./runner.mjs";
2454
+ import { installSplash } from "./splash-install.mjs";
2489
2455
  import { annotatedReviewScreen, box, confirm, getLogoTagline, input, select } from "./tui.mjs";
2490
2456
  import {
2491
2457
  defaultExec as repoExec, listOwners, listAppInstallations, ownerCoverageWarning,
@@ -2748,20 +2714,15 @@ export async function review(ctx, draft, description) {
2748
2714
  extraFields,
2749
2715
  });
2750
2716
 
2751
- // Hard-fail on unresolved identity placeholders when OVERWRITING an
2752
- // existing config (forge#1850 spec item 4): never destroy a working
2753
- // forge.yaml in favor of one that can't address a repo. A brand-new
2754
- // (non-existing) config is allowed to write placeholders — that's the
2755
- // existing, already-flagged (# TODO comments) greenfield-setup path, and
2756
- // there's nothing valuable to lose. Checked AFTER the review screen so an
2757
- // interactive edit that fixes the field still passes.
2758
- if (hasExisting && (accepted.owner === "your-github-org" || accepted.repo === "your-repo-name")) {
2759
- w.write("\n Could not determine the GitHub owner/repo for this project.\n");
2760
- w.write(" " + dimLine(ctx, "Run this inside the target git repository, or edit those fields before accepting.") + "\n");
2717
+ // Never write placeholder identity (#5302; overwrite case: forge#1850 item 4): a config that can't address
2718
+ // a repo is worse than none. Checked AFTER the review screen so an interactive edit that fixes the field passes.
2719
+ if (accepted.owner === "your-github-org" || accepted.repo === "your-repo-name") {
2720
+ w.write("\n Could not determine the GitHub owner/repo for this project" + (hasExisting ? "." : " — forge.yaml not written.") + "\n");
2721
+ w.write(" " + dimLine(ctx, "Run this inside a git repository with a GitHub origin, then run: npx forgedock init") + "\n");
2761
2722
  return { written: false, todoCount: 0, backupName: null, aborted: true };
2762
2723
  }
2763
2724
 
2764
- const backup = backupExisting(outputPath);
2725
+ const backup = backupForgeYaml(outputPath, "setup review");
2765
2726
  if (backup) w.write(` Backed up: forge.yaml → ${backup.backupName}\n`);
2766
2727
 
2767
2728
  const { todoCount } = writeForgeYaml(accepted, accepted.lowConfidenceKeys, outputPath);
@@ -2772,6 +2733,20 @@ export async function review(ctx, draft, description) {
2772
2733
  // Act V — Forged (Task 8)
2773
2734
  // ---------------------------------------------------------------------------
2774
2735
 
2736
+ /**
2737
+ * The single recommended command after a green setup (#5304). Order: install
2738
+ * the App (#5295), merge a first PR on the user's own repo (#5290), then the
2739
+ * demo. The first two flows are not shipped yet, so flip their availability
2740
+ * here when they land.
2741
+ * @param {{appFlow?: boolean, firstPrFlow?: boolean}} [avail]
2742
+ * @returns {{command: string, why: string}}
2743
+ */
2744
+ export function pickNextStep({ appFlow = false, firstPrFlow = false } = {}) {
2745
+ if (appFlow) return { command: "npx forgedock install-app", why: "give ForgeDock its own bot identity and rate limit" };
2746
+ if (firstPrFlow) return { command: "npx forgedock first-pr", why: "merge your first PR on your own repo" };
2747
+ return { command: "npx forgedock demo --run", why: "watch a PR merge on a risk-free demo repo (uses your Claude Code login)" };
2748
+ }
2749
+
2775
2750
  /**
2776
2751
  * Act V: quench flash on the compact mark, receipt with real elapsed time,
2777
2752
  * next-steps box.
@@ -2803,21 +2778,8 @@ export function celebrate(ctx, summary) {
2803
2778
  if (summary.isMinimal) {
2804
2779
  w.write(" " + dimLine(ctx, "see docs/CONFIG.md for optional sections") + "\n");
2805
2780
  }
2806
- w.write(
2807
- box(
2808
- [
2809
- ` 1. install GitHub App — github.com/apps/rapiercraft-forgedock`,
2810
- ` 2. run npx forgedock labels setup — bootstrap GitHub labels`,
2811
- ` 3. run npx forgedock doctor — verify the install is green`,
2812
- ` 4. open claude in this repo`,
2813
- ` 5. run /issue <title> then /work-on <number>`,
2814
- ` 6. run npx forgedock run-issue <N> — drive an issue via the durable engine`,
2815
- ` 7. run npx forgedock watch — monitor pipeline state`,
2816
- ` 8. run npx forgedock guide — how the workflow fits together`,
2817
- ],
2818
- { title: "what's next" },
2819
- ),
2820
- );
2781
+ const next = pickNextStep();
2782
+ w.write(box([` ${next.command}`, ` ${next.why}`], { title: "next step" }));
2821
2783
  w.write(" " + dimLine(ctx, "not for you? npx forgedock uninstall removes everything · full command list: npx forgedock help") + "\n");
2822
2784
  w.write(" " + dimLine(ctx, "docs: github.com/RapierCraftStudios/ForgeDock · ⭐ a star is the whole marketing budget") + "\n\n");
2823
2785
  }
@@ -3056,6 +3018,27 @@ export async function maybeOfferDemo(ctx) {
3056
3018
  }
3057
3019
  }
3058
3020
 
3021
+ /**
3022
+ * #5290: offer the guided first run (propose small issues on this repo, run one to a PR). Default no; skipped
3023
+ * without a TTY or with --fast. Best-effort: never fails the install.
3024
+ */
3025
+ export async function maybeOfferFirstRun(ctx) {
3026
+ const isTTY = ctx.isTTY ?? process.stdin.isTTY === true;
3027
+ if (!isTTY || ctx.argv.includes("--fast")) return { offered: false };
3028
+ try {
3029
+ if (!(await ctx.confirmFn("Find 3 small issues in this repo and run one to a PR now?", false))) {
3030
+ ctx.stdout.write(" " + dimLine(ctx, "Skipped, try it anytime: npx forgedock first-run") + "\n");
3031
+ return { offered: true, ran: false };
3032
+ }
3033
+ const runFirstRunFn = ctx.runFirstRunFn ?? (async (o) => (await import("./first-run.mjs")).runFirstRun(o));
3034
+ const { runFromCli } = await import("./engine-cli.mjs");
3035
+ await runFirstRunFn({ cwd: ctx.cwd, exec: ctx.exec, confirmFn: ctx.confirmFn, runIssueFn: (n) => runFromCli([String(n)]), startedMs: ctx.startedAt });
3036
+ return { offered: true, ran: true };
3037
+ } catch {
3038
+ return { offered: true, ran: false };
3039
+ }
3040
+ }
3041
+
3059
3042
  // ---------------------------------------------------------------------------
3060
3043
  // The full journey (Task 8)
3061
3044
  // ---------------------------------------------------------------------------
@@ -3083,25 +3066,41 @@ export async function runJourney(ctx) {
3083
3066
  };
3084
3067
  process.on("SIGINT", onSigint);
3085
3068
  try {
3086
- await preflight(ctx);
3069
+ const pre = await preflight(ctx);
3070
+ // #5302: a missing blocking prerequisite ends setup here: nothing is installed or written, no success banner.
3071
+ let missing = pre.blocking;
3072
+ if (missing.length > 0) {
3073
+ const installed = await offerInstall(missing, { confirmFn: ctx.confirmFn, write: (t) => ctx.stdout.write(t) });
3074
+ if (installed.length > 0) {
3075
+ missing = checkPrereqs({ exec: ctx.exec, nodeVersion: ctx.nodeVersion, claudeDir: claudeDirOf(ctx), platform: ctx.platform }).filter((p) => p.blocking);
3076
+ }
3077
+ }
3078
+ if (missing.length > 0) {
3079
+ ctx.stdout.write(formatNotReady(missing) + "\n");
3080
+ return 1;
3081
+ }
3087
3082
  // Persist the toolset into ~/.forge/ before linking anything (#1943): when
3088
3083
  // not skipped (git-clone installs are exempt), reassign ctx.forgeHome so
3089
3084
  // every symlink/hook path forge() creates below originates from the
3090
3085
  // stable copy, not the ephemeral npm/npx/git source. Stashed on ctx so
3091
3086
  // forge()'s reporting block can surface the outcome (see isEphemeralCachePath
3092
3087
  // advisory extension above).
3088
+ const splashPkgRoot = ctx.forgeHome;
3093
3089
  const persistResult = await persistHome(ctx);
3094
3090
  ctx.persistHomeResult = persistResult;
3095
3091
  if (!persistResult.skipped) {
3096
3092
  ctx.forgeHome = persistResult.forgeHome;
3097
3093
  }
3098
3094
  const forged = await forge(ctx);
3095
+ const splash = installSplash({ pkgRoot: splashPkgRoot, home: ctx.home, env: ctx.env, argv: ctx.argv, exec: ctx.splashExec });
3096
+ if (splash.line) ctx.stdout.write(` ${splash.status === "installed" || splash.status === "already-installed" ? "✔" : "!"} ${splash.line}\n\n`);
3099
3097
  const { draft, description } = await setupAfterRead(ctx, await read(ctx));
3100
3098
  const reviewed = await review(ctx, draft, description);
3101
3099
  const connected = await connect(ctx);
3102
- celebrate(ctx, { ...reviewed, ...connected, total: forged.total, hookStatus: forged.hookStatus, scriptsResult: forged.scriptsResult });
3100
+ if (!reviewed.aborted) celebrate(ctx, { ...reviewed, ...connected, total: forged.total, hookStatus: forged.hookStatus, scriptsResult: forged.scriptsResult });
3103
3101
  await writeInstallReceipt(ctx, { forged });
3104
3102
  if (!reviewed.aborted) await maybeOfferDemo(ctx);
3103
+ if (!reviewed.aborted) await maybeOfferFirstRun(ctx);
3105
3104
  return reviewed.aborted ? 1 : 0;
3106
3105
  } finally {
3107
3106
  process.removeListener("SIGINT", onSigint);
@@ -0,0 +1,313 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ /**
4
+ * Feature-level acceptance (#5336): an epic declares user journeys, each a probe-format command that runs against the
5
+ * assembled milestone branch; a milestone with an epic cannot ship or close, and its release review cannot pass, while a
6
+ * journey is red, has never run on the branch head, or (at close) a post-deploy journey has not yet passed in production.
7
+ * Deterministic: no model call. Same trust rule as probes (`isProbeDeclarer`, fail closed).
8
+ *
9
+ * Declaration, a top-level fenced block in the epic body or a declarer's comment (the latest wins):
10
+ * ```forge-acceptance
11
+ * journey: create a session-backed task and get a result
12
+ * run: ./scripts/journey-task.sh
13
+ * pass: exit 0 # or /regex/flags against stdout
14
+ * timeout: 300
15
+ * when: milestone # default; `post-deploy` journeys run after release and hold the epic open
16
+ * ```
17
+ * Each run is posted on the epic as a `FORGE:ACCEPTANCE` comment: {head, at, site, results}.
18
+ * `forgedock acceptance check --body-file F | run --milestone T [--site post-deploy] | gate --milestone T|--branch B [--stage ship|close]`.
19
+ */
20
+ import { readFileSync } from "node:fs";
21
+ import { isTrustedComment } from "../engine/phases.mjs";
22
+ import { noComments } from "./render.mjs";
23
+ import { fencedBlocks, isProbeDeclarer, runProbe, probeEnv, readProbeConfig, MAX_TIMEOUT_S } from "./probe.mjs";
24
+ import { listMilestones, milestoneSlug, readBranches, DEFAULT_FEATURE_PATTERN } from "./lane.mjs";
25
+
26
+ export const ACCEPTANCE_MARKER = "FORGE:ACCEPTANCE";
27
+ export const ACCEPTANCE_TAG = "forge-acceptance";
28
+ export const AWAITING_LABEL = "awaiting-measurement";
29
+ export const WHEN = ["milestone", "post-deploy"];
30
+ export const TRANSFER_MARKER = "FORGE:TRANSFERRED";
31
+
32
+ const isForgeMarker = (body) => /^\s*<!--\s*FORGE:/.test(String(body ?? ""));
33
+ const sameSha = (a, b) => !!a && !!b && (a.startsWith(b) || b.startsWith(a));
34
+ const actorOf = (o) => ({ association: o?.author_association, type: o?.user?.type, login: o?.user?.login });
35
+
36
+ function journeyOf(f) {
37
+ const bad = (why) => ({ error: `journey "${f.journey ?? "?"}": ${why}` });
38
+ if (!f.journey) return { error: "a journey section has no name" };
39
+ if (!f.run) return bad("no `run:` command");
40
+ let pass = { kind: "exit" };
41
+ const p = (f.pass ?? "").replace(/\s+#.*$/, "");
42
+ if (p && !/^exit\s+0$/i.test(p)) {
43
+ const r = /^\/(.+)\/([a-z]*)$/.exec(p);
44
+ try { if (!r) return bad("`pass:` must be `exit 0` or /regex/flags"); new RegExp(r[1], r[2]); } catch { return bad("`pass:` regex does not compile"); }
45
+ pass = { kind: "regex", re: r[1], flags: r[2] };
46
+ }
47
+ let timeoutS = null;
48
+ if (f.timeout) {
49
+ const t = parseInt(f.timeout, 10);
50
+ if (!Number.isFinite(t) || t <= 0) return bad("`timeout:` must be a positive number of seconds");
51
+ timeoutS = Math.min(t, MAX_TIMEOUT_S);
52
+ }
53
+ const when = (f.when ?? "milestone").toLowerCase();
54
+ if (!WHEN.includes(when)) return bad("`when:` must be milestone or post-deploy");
55
+ return { journey: { name: f.journey, run: f.run, pass, timeoutS, when } };
56
+ }
57
+
58
+ /** The last top-level forge-acceptance block of `text`: {journeys, errors}; journeys is empty when no block exists. */
59
+ export function parseAcceptance(text) {
60
+ const blocks = fencedBlocks(noComments(String(text ?? ""), " ").replace(/\r\n?/g, "\n"), ACCEPTANCE_TAG);
61
+ const out = { journeys: [], errors: [] };
62
+ if (!blocks.length) return out;
63
+ const sections = [];
64
+ for (const line of blocks[blocks.length - 1].split("\n")) {
65
+ const m = /^\s*(journey|run|pass|timeout|when)\s*:\s*(.*?)\s*$/i.exec(line);
66
+ if (!m) continue;
67
+ const k = m[1].toLowerCase();
68
+ if (k === "journey") sections.push({ journey: m[2] });
69
+ else if (sections.length && !(k in sections.at(-1))) sections.at(-1)[k] = m[2];
70
+ }
71
+ for (const s of sections) { const j = journeyOf(s); if (j.error) out.errors.push(j.error); else out.journeys.push(j.journey); }
72
+ return out;
73
+ }
74
+
75
+ /** Creation gate: {ok, journeys, errors}. An epic body needs at least one valid journey and no malformed one. */
76
+ export function validateEpic(body) {
77
+ const { journeys, errors } = parseAcceptance(body);
78
+ const all = journeys.length ? errors : ["no `forge-acceptance` block with at least one journey (journey/run/pass)", ...errors];
79
+ return { ok: !all.length, journeys, errors: all };
80
+ }
81
+
82
+ /** The epic's declared journeys: the latest declarer comment, else the body when its author is a declarer. {journeys, errors, source} | {untrusted:true} | null. */
83
+ export function declaredAcceptance(iss) {
84
+ let untrusted = false;
85
+ for (const c of [...(iss?.comments ?? [])].reverse()) {
86
+ if (isForgeMarker(c?.body)) continue;
87
+ const a = parseAcceptance(c?.body);
88
+ if (!a.journeys.length && !a.errors.length) continue;
89
+ if (isProbeDeclarer(actorOf(c))) return { ...a, source: "comment" };
90
+ untrusted = true;
91
+ }
92
+ const a = parseAcceptance(iss?.body);
93
+ if (a.journeys.length || a.errors.length) {
94
+ if (isProbeDeclarer(actorOf(iss))) return { ...a, source: "body" };
95
+ untrusted = true;
96
+ }
97
+ return untrusted ? { untrusted: true } : null;
98
+ }
99
+
100
+ /** The FORGE:ACCEPTANCE comment: pass/fail, when, and on which head. */
101
+ export function renderAcceptanceComment({ head, at, site, branch, rows }) {
102
+ const pass = rows.length > 0 && rows.every((r) => r.result === "pass");
103
+ const rec = { head, at, site, branch, result: pass ? "pass" : "fail", results: Object.fromEntries(rows.map((r) => [r.name, { result: r.result, exit: r.exit, ms: r.ms }])) };
104
+ const table = rows.map((r) => `| ${r.name.replace(/\|/g, "/")} | ${r.result} | ${r.exit ?? "timeout"} |`);
105
+ const tails = rows.filter((r) => r.result === "fail").map((r) => `<details><summary>${r.name.replace(/[<>]/g, "")}</summary>\n\n\`\`\`\`\n${String(r.output ?? "").trim() || "(no output)"}\n\`\`\`\`\n</details>`);
106
+ return [`<!-- ${ACCEPTANCE_MARKER} -->`, `## Feature acceptance (${site}): ${rec.result}`, JSON.stringify(rec), "",
107
+ `Ran on \`${String(head).slice(0, 12)}\`${branch ? ` of \`${branch}\`` : ""} at ${at}.`, "", "| Journey | Result | Exit |", "|---|---|---|", ...table, "", ...tails].join("\n");
108
+ }
109
+
110
+ /** {head, at, site, result, results} of a FORGE:ACCEPTANCE comment body, or null. */
111
+ export function acceptanceResultOf(body) {
112
+ const s = String(body ?? "");
113
+ if (!s.trimStart().startsWith(`<!-- ${ACCEPTANCE_MARKER} -->`)) return null;
114
+ const line = s.split("\n").find((l) => /^\{.*"results"/.test(l.trim()));
115
+ try { const j = line && JSON.parse(line.trim()); return j && typeof j.head === "string" && j.results && typeof j.results === "object" ? j : null; } catch { return null; }
116
+ }
117
+
118
+ /** Run `journeys` (those of `site`) in `cwd`; rows {name, when, result, exit, ms, output}. */
119
+ export async function runJourneys({ journeys, site = "milestone", cwd, config = readProbeConfig(cwd), env = process.env, spawn }) {
120
+ const rows = [];
121
+ for (const j of journeys.filter((x) => x.when === site)) {
122
+ const r = await runProbe(j, { cwd, env: probeEnv(config.env, env), mask: config.env.map((k) => env[k]), timeoutS: config.timeoutS, ...(spawn ? { spawn } : {}) });
123
+ rows.push({ name: j.name, when: j.when, ...r });
124
+ }
125
+ return rows;
126
+ }
127
+
128
+ /** #5339: the name a journey must carry to settle a requirement transferred from `issue`'s `req`. */
129
+ export const transferName = (issue, req) => `#${issue} ${req}`;
130
+
131
+ /** #5339: {issue, req, quote} of a FORGE:TRANSFERRED comment body (posted by the engine; it declares no command), or null. */
132
+ export function transferOf(body) {
133
+ const s = String(body ?? "");
134
+ if (!s.trimStart().startsWith(`<!-- ${TRANSFER_MARKER} -->`)) return null;
135
+ const line = s.split("\n").find((l) => /^\{.*"req"/.test(l.trim()));
136
+ try { const j = line && JSON.parse(line.trim()); return j && Number.isInteger(j.issue) && typeof j.req === "string" ? j : null; } catch { return null; }
137
+ }
138
+
139
+ /**
140
+ * The gate for one milestone's epics. `epics`: [{number, declared, comments}]. `stage`: "ship" needs every milestone journey
141
+ * green on `head`; "close" also needs every post-deploy journey to have passed (any head, site post-deploy).
142
+ * Returns {ok, reasons}. A milestone with no epics is not gated.
143
+ */
144
+ export function gateMilestone({ epics, head, stage = "ship" }) {
145
+ const reasons = [];
146
+ for (const e of epics) {
147
+ const tag = `epic #${e.number}`;
148
+ const d = e.declared;
149
+ if (!d || d.untrusted || !d.journeys?.length) { reasons.push(`${tag}: no runnable journey declared${d?.untrusted ? " (only by untrusted authors)" : ""}`); continue; }
150
+ if (d.errors?.length) reasons.push(`${tag}: ${d.errors.join("; ")}`);
151
+ const recs = (e.comments ?? []).filter((c) => isTrustedComment(c)).map((c) => acceptanceResultOf(c.body)).filter(Boolean);
152
+ // close after ship: the branch is deleted (head null), so the last milestone-site run is the shipped head's record
153
+ const onHead = recs.filter((r) => r.site !== "post-deploy" && (head == null || sameSha(r.head, head))).at(-1);
154
+ for (const j of d.journeys.filter((x) => x.when === "milestone")) {
155
+ const got = onHead?.results?.[j.name]?.result;
156
+ if (got === "pass") continue;
157
+ reasons.push(`${tag}: journey "${j.name}" ${got ? "is red" : recs.length ? `has not run on ${String(head).slice(0, 7)}` : "has never run"}`);
158
+ }
159
+ if (stage === "close") {
160
+ // #5339: a requirement transferred from a lane is open until a post-deploy journey named `#<issue> <req>` passes
161
+ for (const t of (e.comments ?? []).filter((c) => isTrustedComment(c)).map((c) => transferOf(c.body)).filter(Boolean)) {
162
+ if (!recs.some((r) => r.site === "post-deploy" && r.results?.[transferName(t.issue, t.req)]?.result === "pass")) reasons.push(`${tag}: requirement ${t.req} transferred from #${t.issue} has not been run (post-deploy journey "${transferName(t.issue, t.req)}" must pass; epic stays open, ${AWAITING_LABEL})`);
163
+ }
164
+ for (const j of d.journeys.filter((x) => x.when === "post-deploy")) {
165
+ if (!recs.some((r) => r.site === "post-deploy" && r.results?.[j.name]?.result === "pass")) reasons.push(`${tag}: post-deploy journey "${j.name}" has not passed in production (epic stays open, ${AWAITING_LABEL})`);
166
+ }
167
+ }
168
+ }
169
+ return { ok: !reasons.length, reasons };
170
+ }
171
+
172
+ const branchOf = (pattern, title) => { const slug = milestoneSlug(title); return slug ? String(pattern || DEFAULT_FEATURE_PATTERN).replace("{slug}", slug) : null; };
173
+
174
+ /** The open milestone whose branch is `branch` (or titled `title`): {number, title, branch}, or null. */
175
+ export async function findMilestone({ io, repo, title = null, branch = null, pattern = DEFAULT_FEATURE_PATTERN }) {
176
+ for (const m of await listMilestones({ gh: io.gh, repo, state: "all" })) {
177
+ const b = branchOf(pattern, m.title);
178
+ if ((title && m.title === title) || (branch && b === branch)) return { number: m.number, title: m.title, branch: b };
179
+ }
180
+ return null;
181
+ }
182
+
183
+ /** The milestone's epic issues, each with comments and declared journeys. */
184
+ export async function readEpics({ io, repo, milestone }) {
185
+ const list = JSON.parse(String(await io.gh(["api", `repos/${repo}/issues?milestone=${milestone.number}&labels=epic&state=all&per_page=100`, "--jq", "[.[] | select(.pull_request == null)]"])) || "[]");
186
+ const out = [];
187
+ for (const iss of list) {
188
+ const raw = String(await io.gh(["api", `repos/${repo}/issues/${iss.number}/comments`, "--paginate", "--jq", ".[]"]));
189
+ const comments = raw.split("\n").filter((l) => l.trim()).map((l) => JSON.parse(l));
190
+ out.push({ number: iss.number, state: iss.state, declared: declaredAcceptance({ ...iss, comments }), comments });
191
+ }
192
+ return out;
193
+ }
194
+
195
+ /** Gate by milestone title or branch. Fails closed: a milestone with epics whose head cannot be read is blocked. Not gated: no milestone or no epic. */
196
+ export async function gateByRef({ io, repo, title = null, branch = null, head = null, stage = "ship", pattern = DEFAULT_FEATURE_PATTERN }) {
197
+ const ms = await findMilestone({ io, repo, title, branch, pattern });
198
+ if (!ms) return { gated: false, ok: true, reasons: [] };
199
+ const epics = await readEpics({ io, repo, milestone: ms });
200
+ if (!epics.length) return { gated: false, ok: true, reasons: [], milestone: ms };
201
+ let h = head;
202
+ if (!h && ms.branch) { try { h = String(await io.gh(["api", `repos/${repo}/branches/${encodeURIComponent(ms.branch)}`, "--jq", ".commit.sha"])).trim(); } catch { h = null; } }
203
+ if (!h && stage !== "close") return { gated: true, ok: false, reasons: [`milestone ${ms.title}: head of ${ms.branch} unreadable (fail closed)`], milestone: ms };
204
+ return { gated: true, ...gateMilestone({ epics, head: h, stage }), milestone: ms, epics, head: h };
205
+ }
206
+
207
+ /**
208
+ * #5339: record each requirement of `issue` that cannot run in the lane on the milestone's epic (a FORGE:TRANSFERRED comment,
209
+ * idempotent per issue+req), so `gate --stage close` holds the epic open until it runs. Returns the epic number, or null
210
+ * (no milestone or no epic: the requirement stays open on the issue, which closes partial).
211
+ */
212
+ export async function transferToEpic({ io, repo, milestoneTitle, issue, reqs, now = () => new Date().toISOString(), pattern = DEFAULT_FEATURE_PATTERN }) {
213
+ if (!milestoneTitle || !reqs?.length) return null;
214
+ const ms = await findMilestone({ io, repo, title: milestoneTitle, pattern });
215
+ if (!ms) return null;
216
+ const epics = await readEpics({ io, repo, milestone: ms });
217
+ const epic = epics.find((e) => e.state === "open") ?? epics[0];
218
+ if (!epic) return null;
219
+ const have = new Set(epic.comments.map((c) => transferOf(c.body)).filter(Boolean).map((t) => transferName(t.issue, t.req)));
220
+ for (const r of reqs) {
221
+ if (have.has(transferName(issue, r.id))) continue;
222
+ const rec = { issue, req: r.id, quote: String(r.quote ?? "").slice(0, 300), at: now() };
223
+ await io.gh(["issue", "comment", String(epic.number), "-R", repo, "--body", [`<!-- ${TRANSFER_MARKER} -->`, `## Requirement transferred from #${issue} (${r.id}): not met, open`, JSON.stringify(rec), "",
224
+ `The lane could not run this end to end. Declare a post-deploy journey named \`${transferName(issue, r.id)}\` in the epic's \`forge-acceptance\` block; the epic cannot close until it passes.`].join("\n")]);
225
+ }
226
+ return epic.number;
227
+ }
228
+
229
+ /** Run a milestone's journeys in `cwd` (checked out at its branch head) and post the result on each epic. Resolves [{epic, result, rows}]. */
230
+ export async function runMilestoneJourneys({ io, repo, milestone, cwd, head, site = "milestone", now = () => new Date().toISOString(), config, env, spawn, dryRun = false }) {
231
+ const out = [];
232
+ for (const e of await readEpics({ io, repo, milestone })) {
233
+ if (!e.declared?.journeys?.length || e.declared.untrusted) { out.push({ epic: e.number, result: "no-journey", rows: [] }); continue; }
234
+ const rows = await runJourneys({ journeys: e.declared.journeys, site, cwd, ...(config ? { config } : {}), ...(env ? { env } : {}), ...(spawn ? { spawn } : {}) });
235
+ if (!rows.length) { out.push({ epic: e.number, result: "no-journey", rows }); continue; }
236
+ const body = renderAcceptanceComment({ head, at: now(), site, branch: milestone.branch, rows });
237
+ if (!dryRun) {
238
+ await io.gh(["issue", "comment", String(e.number), "-R", repo, "--body", body]);
239
+ if (site === "milestone" && rows.some((r) => r.result === "fail")) { try { await io.gh(["issue", "edit", String(e.number), "-R", repo, "--add-label", "integration-red"]); } catch { /* label is advisory */ } }
240
+ }
241
+ out.push({ epic: e.number, result: rows.every((r) => r.result === "pass") ? "pass" : "fail", rows });
242
+ }
243
+ return out;
244
+ }
245
+
246
+ /** `forgedock acceptance check|run|gate`. Resolves the exit code (1: invalid, red or blocked). */
247
+ export async function acceptanceFromCli(argv, deps = {}) {
248
+ const val = (n) => { const i = argv.indexOf(n); return i >= 0 ? argv[i + 1] : null; };
249
+ const print = deps.print ?? ((t) => console.log(t));
250
+ const cwd = deps.cwd ?? process.cwd();
251
+ const usage = "usage: forgedock acceptance check --body-file F | run --milestone T [--site milestone|post-deploy] [--repo o/r] | gate (--milestone T | --branch B) [--stage ship|close] [--repo o/r]";
252
+ if (argv[0] === "check") {
253
+ const f = val("--body-file");
254
+ if (!f) throw new Error(usage);
255
+ const v = validateEpic(deps.readFile ? deps.readFile(f) : readFileSync(f, "utf8"));
256
+ if (v.ok) print(`acceptance: ${v.journeys.length} journey(s): ${v.journeys.map((j) => `${j.name} [${j.when}]`).join("; ")}`);
257
+ else for (const e of v.errors) print(`acceptance: ${e}`);
258
+ return v.ok ? 0 : 1;
259
+ }
260
+ if (argv[0] !== "run" && argv[0] !== "gate") throw new Error(usage);
261
+ const repo = val("--repo") ?? deps.repo;
262
+ if (!repo) throw new Error("acceptance needs the repo: pass --repo owner/repo");
263
+ const io = deps.io ?? (await import("./effects.mjs")).makeLeanIo({ repo });
264
+ const pattern = deps.pattern ?? readBranches(cwd).featurePattern ?? DEFAULT_FEATURE_PATTERN;
265
+ if (argv[0] === "gate") {
266
+ const stage = val("--stage") ?? "ship";
267
+ if (stage !== "ship" && stage !== "close") throw new Error(usage);
268
+ if (!val("--milestone") && !val("--branch")) throw new Error(usage);
269
+ const g = await gateByRef({ io, repo, title: val("--milestone"), branch: val("--branch"), stage, pattern });
270
+ if (!g.gated) print("acceptance: milestone has no epic; not gated");
271
+ else if (g.ok) print(`acceptance: pass (${g.milestone.title} @ ${g.head ? String(g.head).slice(0, 7) : "branch deleted"}, ${stage})`);
272
+ else for (const r of g.reasons) print(`acceptance: BLOCKED: ${r}`);
273
+ return g.ok ? 0 : 1;
274
+ }
275
+ const title = val("--milestone");
276
+ const site = val("--site") ?? "milestone";
277
+ if (!title || !WHEN.includes(site)) throw new Error(usage);
278
+ const ms = await findMilestone({ io, repo, title, pattern });
279
+ if (!ms) throw new Error(`no milestone titled ${title}`);
280
+ const head = String(await (deps.git ?? io.git)(["rev-parse", "HEAD"], { cwd })).trim();
281
+ const res = await runMilestoneJourneys({ io, repo, milestone: ms, cwd, head, site, dryRun: argv.includes("--dry-run"), ...(deps.spawn ? { spawn: deps.spawn } : {}) });
282
+ for (const r of res) print(`acceptance: epic #${r.epic}: ${r.result}`);
283
+ return res.some((r) => r.result === "fail") ? 1 : 0;
284
+ }
285
+
286
+ /**
287
+ * The orchestrate seam's `journeys({title, branch, number})`: fetch the milestone branch, check it out detached in a
288
+ * throwaway worktree, run the epics' milestone journeys there and post the results. Milestones with no epic or journey are a no-op (a string);
289
+ * a run resolves {summary, red, ran, head} (#5337).
290
+ */
291
+ export function makeJourneyRunner({ repo, io, cwd = process.cwd(), tmpRoot }) {
292
+ return async ({ title, branch, number }) => {
293
+ if (!branch) return "no branch";
294
+ const git = (a, o = {}) => io.git(a, { cwd, ...o });
295
+ const epics = await readEpics({ io, repo, milestone: { number } });
296
+ if (!epics.some((e) => e.declared?.journeys?.some((j) => j.when === "milestone"))) return "no journey declared";
297
+ await git(["fetch", "origin", branch]);
298
+ const { mkdtempSync, rmSync } = await import("node:fs");
299
+ const { tmpdir } = await import("node:os");
300
+ const { join } = await import("node:path");
301
+ const dir = join(mkdtempSync(join(tmpRoot ?? tmpdir(), "forge-journey-")), "wt");
302
+ try {
303
+ await git(["worktree", "add", "--detach", dir, `origin/${branch}`]);
304
+ const head = String(await git(["rev-parse", "HEAD"], { cwd: dir })).trim();
305
+ const res = await runMilestoneJourneys({ io, repo, milestone: { number, title, branch }, cwd: dir, head });
306
+ // #5337: structured so the integration seam can file the red issue and hold admission; it still reads as its `summary`.
307
+ return { summary: res.map((r) => `#${r.epic} ${r.result}`).join(", ") || "no journey declared", red: res.some((r) => r.result === "fail"), ran: res.some((r) => r.result === "pass" || r.result === "fail"), head };
308
+ } finally {
309
+ try { await git(["worktree", "remove", "--force", dir]); } catch { /* pruned below */ }
310
+ try { rmSync(join(dir, ".."), { recursive: true, force: true }); await git(["worktree", "prune"]); } catch { /* best effort */ }
311
+ }
312
+ };
313
+ }