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
@@ -2,7 +2,8 @@
2
2
  // SPDX-License-Identifier: AGPL-3.0-or-later
3
3
  import { describe, it } from "node:test";
4
4
  import assert from "node:assert/strict";
5
- import { readSelfReview, compareSelfReview } from "./selfreview.mjs";
5
+ import { readSelfReview, compareSelfReview, selfReviewFindings, selfCheckFailures, firstReviewRecord, sectionOfKind, FINDING_PITFALLS } from "./selfreview.mjs";
6
+ import { selfCheck, selfCheckState, formatCheckTable } from "./precheck.mjs";
6
7
 
7
8
  const item = (question, answer = "yes", evidence = "src/a.py:3") => ({ question, answer, evidence });
8
9
 
@@ -49,3 +50,59 @@ describe("compareSelfReview (#4374)", () => {
49
50
  assert.equal(compareSelfReview(yes, null), null);
50
51
  });
51
52
  });
53
+
54
+ describe("selfReviewFindings (#5345)", () => {
55
+ const contract = { requirements: [{ id: "R1", quote: "q", disposition: "deliver" }], deliverables: [{ id: "D1", path: "src/a.js" }], preserve: [{ id: "P1", what: "src/keep.js behaviour unchanged" }], validate: [] };
56
+ it("catches scope creep and a preserved path touched without authorization", () => {
57
+ const f = selfReviewFindings({ contract, result: {}, changedFiles: ["src/a.js", "src/keep.js", "src/b.js"] });
58
+ assert.ok(f.some((x) => x.code === "conformance.scope_creep" && x.section === "deliverables"));
59
+ assert.ok(f.some((x) => x.code === "conformance.preserve_violated" && /P1: src\/keep\.js/.test(x.detail)));
60
+ });
61
+ it("selfReviewFindings applies add-deliverable amendments", () => {
62
+ const files = ["src/a.js", "src/b.js"];
63
+ const amendments = [{ kind: "add-deliverable", path: "src/b.js", why: "needed helper" }];
64
+ assert.ok(selfReviewFindings({ contract, result: { amendments }, changedFiles: files }).length === 0);
65
+ assert.ok(selfReviewFindings({ contract, result: { amendments: [] }, changedFiles: files }).some((x) => x.code === "conformance.scope_creep"));
66
+ assert.ok(!selfReviewFindings({ contract, changedFiles: files }).some((x) => x.code === "conformance.scope_creep"), "no result.json yet: scope_creep not judged");
67
+ const keep = selfReviewFindings({ contract, result: { amendments: [{ kind: "add-deliverable", path: "src/keep.js", why: "w" }] }, changedFiles: ["src/a.js", "src/keep.js"] });
68
+ assert.deepEqual(keep, []);
69
+ });
70
+ it("catches an unimplemented requirement only once the builder reported statuses", () => {
71
+ assert.deepEqual(selfReviewFindings({ contract, changedFiles: ["src/a.js"] }), []);
72
+ const f = selfReviewFindings({ contract, result: { requirements: [{ id: "R1", status: "missing" }] }, changedFiles: ["src/a.js"] });
73
+ assert.ok(f.some((x) => x.code === "conformance.unimplemented" && x.section === "requirements"));
74
+ });
75
+ it("a red review section makes the check fail and the record red, so the lane is fixed before review", async () => {
76
+ const review = selfReviewFindings({ contract, result: {}, changedFiles: ["src/b.js"] });
77
+ const r = await selfCheck({ review, contract, plan: { commands: [], budgetMs: 0, perCommandMs: 1 }, run: async () => ({ rc: 0 }) });
78
+ assert.equal(r.ok, false);
79
+ assert.match(formatCheckTable(r), /FAIL review {2}conformance\.scope_creep/);
80
+ const rec = { fingerprint: "x", ok: r.ok, review: r.review.map((f) => ({ code: f.code, detail: f.detail })) };
81
+ assert.equal(selfCheckState(rec, "x"), "red");
82
+ assert.deepEqual(selfCheckFailures(rec).map((f) => f.code), review.map((f) => f.code));
83
+ assert.equal((await selfCheck({ contract, plan: { commands: [], budgetMs: 0, perCommandMs: 1 }, run: async () => ({ rc: 0 }) })).ok, true);
84
+ });
85
+ it("pitfalls cover the recurring kinds and map to sections", () => {
86
+ assert.deepEqual(Object.keys(FINDING_PITFALLS).sort(), ["conformance.omission", "conformance.preserve_violated", "conformance.scope_creep"]);
87
+ assert.equal(sectionOfKind("conformance.preserve_violated"), "preserve");
88
+ });
89
+ });
90
+
91
+ describe("firstReviewRecord (#5345)", () => {
92
+ it("null without a round; otherwise the first judgement, rounds, type and surfaces", () => {
93
+ assert.equal(firstReviewRecord({}), null);
94
+ const r = firstReviewRecord({ rounds: [{ state: "fails", failures: ["conformance.scope_creep"] }, { state: "conforms", failures: [] }], labels: [{ name: "bug" }], files: ["src/a.js"] });
95
+ assert.deepEqual([r.state, r.kinds, r.rounds, r.clean, r.type], ["fails", ["conformance.scope_creep"], 2, false, "bug"]);
96
+ assert.equal(firstReviewRecord({ rounds: [{ state: "review.incomplete", failures: [] }] }).incomplete, true);
97
+ });
98
+ });
99
+
100
+ describe("planner tightening (#5345 R5)", () => {
101
+ it("every contract section first-round findings map to has a planner rule, rendered in the plan prompt", async () => {
102
+ const { PLANNER_TIGHTENING, KIND_SECTION } = await import("./selfreview.mjs");
103
+ const { builderPlanPrompt } = await import("./prompts.mjs");
104
+ for (const s of new Set(Object.values(KIND_SECTION).filter((x) => ["requirements", "deliverables", "preserve"].includes(x)))) assert.ok(PLANNER_TIGHTENING[s], s);
105
+ const p = builderPlanPrompt(1);
106
+ for (const x of Object.values(PLANNER_TIGHTENING)) assert.ok(p.includes(x));
107
+ });
108
+ });
@@ -44,3 +44,25 @@ export async function readMarkerComments(gh, repo, pr) {
44
44
  export async function postMarker(gh, repo, pr, m) {
45
45
  await gh(["pr", "comment", String(pr), "-R", repo, "--body", `${buildMarker(m)}\nLive selftest: ${m.result}${m.step ? ` (step ${m.step})` : ""}`]);
46
46
  }
47
+
48
+ // FORGE:JOURNEY marker (#5305): the new-user journey result, posted next to GATE_PASS. Informational: the release gate
49
+ // above never reads it, and it is a separate marker so it cannot replace the FORGE:SELFTEST result.
50
+ const JOURNEY_RE = /^\s*<!--\s*FORGE:JOURNEY\s+([^>]*?)\s*-->/;
51
+
52
+ /** @param {{result:"pass"|"fail", sha:string, step?:string|null, ttfm?:number|null}} m ttfm: seconds to the first merged PR */
53
+ export function buildJourneyMarker({ result, sha, step, ttfm }) {
54
+ return `<!-- FORGE:JOURNEY result=${result} sha=${sha} step=${step || "none"} ttfm=${ttfm ?? "na"} -->`;
55
+ }
56
+
57
+ /** @returns {{result:string, sha:string, step:string, ttfm:number|null}|null} */
58
+ export function parseJourneyMarker(body) {
59
+ const m = JOURNEY_RE.exec(String(body ?? ""));
60
+ if (!m) return null;
61
+ const kv = Object.fromEntries(m[1].split(/\s+/).map((p) => p.split("=")).filter((p) => p.length === 2));
62
+ if (!/^(pass|fail)$/.test(kv.result ?? "") || !/^[0-9a-f]{40}$/.test(kv.sha ?? "")) return null;
63
+ return { result: kv.result, sha: kv.sha, step: kv.step ?? "none", ttfm: /^\d+$/.test(kv.ttfm ?? "") ? Number(kv.ttfm) : null };
64
+ }
65
+
66
+ export async function postJourneyMarker(gh, repo, pr, m) {
67
+ await gh(["pr", "comment", String(pr), "-R", repo, "--body", `${buildJourneyMarker(m)}\nNew-user journey: ${m.result}${m.step ? ` (step ${m.step})` : ""}${m.ttfm != null ? `, first merged PR in ${m.ttfm}s` : ""}`]);
68
+ }
@@ -2,7 +2,7 @@
2
2
  // SPDX-License-Identifier: AGPL-3.0-or-later
3
3
  import { describe, it } from "node:test";
4
4
  import assert from "node:assert/strict";
5
- import { buildMarker, parseMarker, selftestGate, readMarkerComments, postMarker } from "./selftest-gate.mjs";
5
+ import { buildJourneyMarker, parseJourneyMarker, postJourneyMarker, buildMarker, parseMarker, selftestGate, readMarkerComments, postMarker } from "./selftest-gate.mjs";
6
6
 
7
7
  const H = "a".repeat(40), O = "b".repeat(40);
8
8
  describe("FORGE:SELFTEST gate (#4865)", () => {
@@ -38,3 +38,20 @@ describe("FORGE:SELFTEST gate (#4865)", () => {
38
38
  });
39
39
  });
40
40
 
41
+
42
+ describe("FORGE:JOURNEY marker (#5305)", () => {
43
+ it("round-trips and never counts as a FORGE:SELFTEST result", () => {
44
+ const m = buildJourneyMarker({ result: "pass", sha: H, ttfm: 312 });
45
+ assert.deepEqual(parseJourneyMarker(m), { result: "pass", sha: H, step: "none", ttfm: 312 });
46
+ assert.equal(parseMarker(m), null);
47
+ assert.equal(selftestGate([m], H).ok, false);
48
+ assert.equal(parseJourneyMarker(buildMarker({ result: "pass", sha: H })), null);
49
+ assert.equal(parseJourneyMarker(`quote ${m}`), null);
50
+ assert.equal(parseJourneyMarker(buildJourneyMarker({ result: "fail", sha: H, step: "doctor" })).ttfm, null);
51
+ });
52
+ it("posts through gh", async () => {
53
+ const calls = [];
54
+ await postJourneyMarker(async (a) => { calls.push(a); return ""; }, "o/r", 5, { result: "fail", sha: H, step: "banner" });
55
+ assert.match(calls[0].at(-1), /^<!-- FORGE:JOURNEY result=fail sha=a{40} step=banner ttfm=na -->/);
56
+ });
57
+ });
@@ -0,0 +1,234 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ // `forgedock selftest --journey [--repo <owner/sandbox>] [--pr N] [--update-snapshots]` (#5305): the scripted new-user
4
+ // journey. Stage 1 runs the packed tarball in a clean environment (only node and git) and checks the not-ready output,
5
+ // the files written and the doctor output against committed snapshots. Stage 2 (needs gh auth, claude, a sandbox repo)
6
+ // takes a fresh checkout through setup, doctor and demo --run to a merged PR and records time to first merge and the
7
+ // prompts shown. Run on the host before a release, never in Actions. All process access goes through `io`.
8
+ import { readFileSync, writeFileSync, mkdirSync, existsSync, mkdtempSync, symlinkSync, rmSync } from "node:fs";
9
+ import { join, dirname } from "node:path";
10
+ import { tmpdir } from "node:os";
11
+ import { fileURLToPath } from "node:url";
12
+ import { spawnSync } from "node:child_process";
13
+ import { StepError } from "./selftest-live.mjs";
14
+ import { parseForgeYaml } from "../forge-utils.mjs";
15
+
16
+ const HERE = dirname(fileURLToPath(import.meta.url));
17
+ export const SNAPSHOT_DIR = join(HERE, "..", "tests", "fixtures", "journey-snapshots");
18
+ const fail = (step, msg) => { throw new StepError(step, msg); };
19
+
20
+ /** The user-visible outputs captured in the clean environment; `file` is the snapshot name. */
21
+ export const CASES = [
22
+ { name: "banner", args: [], file: "banner.txt" },
23
+ { name: "help", args: ["help"], file: "help.txt" },
24
+ { name: "doctor", args: ["doctor"], file: "doctor.txt" },
25
+ { name: "errors", args: ["nosuchcommand"], file: "errors.txt" },
26
+ ];
27
+
28
+ // Success wording that must not appear while node/git are all a clean machine has (the false banner of 2026-11-10).
29
+ const FALSE_SUCCESS = /(all checks passed|you'?re all set|setup complete|✔\s+(Claude Code|gh\b|GitHub CLI)\b)/i;
30
+ const JARGON = /\b(ENOENT|EACCES|ERR_[A-Z_]+|TypeError|ReferenceError|SyntaxError|undefined|\[object Object\])\b|\n\s+at \S+ \(/;
31
+ // A placeholder VALUE in a config file the CLI wrote; `# TODO` comments are the CLI's deliberate "verify this" flags.
32
+ const PLACEHOLDER = /<owner>|<repo>|<your[^>]*>|\byour-[\w-]+|\bCHANGEME\b|\bexample\.com\b|:\s*["']?TODO\b/i;
33
+ const CONFIG_FILE = /(^|\/)forge\.yaml$/;
34
+ const uncomment = (t) => String(t).split("\n").filter((l) => !/^\s*#/.test(l)).map((l) => l.replace(/\s#.*$/, "")).join("\n");
35
+ const PROMPT = /(\[y\/n\]|\(y\/n\)|\[Y\/n\]|\[y\/N\]|\?\s*$)/i;
36
+
37
+ /** Output with ANSI, absolute paths, versions, durations and trailing blanks removed, so a snapshot only moves on wording. */
38
+ export function scrub(text) {
39
+ return String(text ?? "")
40
+ .replace(/\u001b\[[0-9;?]*[A-Za-z]/g, "")
41
+ .replace(/(?:\/(?:tmp|var|root|home|Users|usr|opt|work|pkg)\b|[A-Za-z]:\\)[^\s'"`)]*/g, "<path>")
42
+ .replace(/\bv?\d+\.\d+\.\d+(?:[-+][\w.]+)?\b/g, "<ver>")
43
+ .replace(/\b\d+(?:\.\d+)?\s?(?:ms|s|sec|seconds|min)\b/g, "<time>")
44
+ .split("\n").map((l) => l.replace(/\s+$/, "")).join("\n").replace(/\n{3,}/g, "\n\n").trim() + "\n";
45
+ }
46
+
47
+ /** Regression assertions on the stage 1 results: the classes of defect the 2026-11-10 clean-room run found. */
48
+ export function assertStage1(results) {
49
+ const bad = [];
50
+ for (const [name, r] of Object.entries(results.cases)) {
51
+ if (r.code === 126 || r.code === 127) bad.push([name, `the packed CLI did not start (exit ${r.code}): ${scrub(r.output).slice(0, 120).trim()}`]);
52
+ if (FALSE_SUCCESS.test(r.output)) bad.push(["banner", `${name}: success wording on a machine without gh or Claude Code`]);
53
+ if (JARGON.test(r.output)) bad.push(["errors", `${name}: raw runtime error text shown to the user`]);
54
+ }
55
+ const doctor = results.cases.doctor;
56
+ if (doctor && doctor.code === 0) bad.push(["doctor", "doctor exits 0 on a machine without gh and Claude Code"]);
57
+ if (doctor && !/claude/i.test(doctor.output)) bad.push(["doctor", "doctor output never names Claude Code"]);
58
+ if (doctor && !/\bgh\b|github cli/i.test(doctor.output)) bad.push(["doctor", "doctor output never names the gh CLI"]);
59
+ const errs = results.cases.errors;
60
+ if (errs && errs.code === 0) bad.push(["errors", "an unknown command exits 0"]);
61
+ for (const [path, content] of Object.entries(results.files)) {
62
+ if (CONFIG_FILE.test(path) && PLACEHOLDER.test(uncomment(content))) bad.push(["files", `${path} holds placeholder config`]);
63
+ }
64
+ return bad;
65
+ }
66
+
67
+ // Installed copies under ~/.forge and ~/.claude vary by version: collapse them to their directory.
68
+ const filesSummary = (files) => [...new Set(Object.keys(files).map((p) => { const seg = p.split("/"); return seg.length > 3 ? `${seg.slice(0, 3).join("/")}/` : p; }))].sort().join("\n") + "\n";
69
+
70
+ /** Compare (or with `update` write) the scrubbed outputs against the committed snapshots; returns the notes. */
71
+ export function compareSnapshots(results, { dir = SNAPSHOT_DIR, update = false } = {}) {
72
+ const want = { ...Object.fromEntries(CASES.map((c) => [c.file, scrub(results.cases[c.name]?.output)])), "not-ready.txt": scrub(`exit codes: ${CASES.map((c) => `${c.name}=${results.cases[c.name]?.code}`).join(" ")}\nfiles written:\n${filesSummary(results.files)}`) };
73
+ const notes = [];
74
+ for (const [file, text] of Object.entries(want)) {
75
+ const path = join(dir, file);
76
+ if (update) { mkdirSync(dir, { recursive: true }); writeFileSync(path, text); notes.push(`journey: wrote snapshot ${file}`); continue; }
77
+ if (!existsSync(path)) fail("snapshot", `no snapshot ${file}; run \`forgedock selftest --journey --update-snapshots\` and review the diff`);
78
+ const have = readFileSync(path, "utf8");
79
+ if (have !== text) {
80
+ const a = have.split("\n"), b = text.split("\n"), i = a.findIndex((l, k) => l !== b[k]);
81
+ fail("snapshot", `${file} changed at line ${i < 0 ? a.length + 1 : i + 1}: was ${JSON.stringify(a[i] ?? "")}, now ${JSON.stringify(b[i] ?? "")}; review it and re-run with --update-snapshots`);
82
+ }
83
+ }
84
+ return notes;
85
+ }
86
+
87
+ /** Stage 1: pack, run every case in the clean environment, assert, snapshot. */
88
+ export async function stage1(ctx) {
89
+ const { io } = ctx;
90
+ const tgz = await io.pack().catch((e) => fail("pack", `npm pack failed: ${String(e.message ?? e).slice(0, 200)}`));
91
+ const results = { cases: {}, files: {} };
92
+ for (const c of CASES) {
93
+ const r = await io.clean(tgz, c.args).catch((e) => fail(c.name, `clean-environment run failed: ${String(e.message ?? e).slice(0, 200)}`));
94
+ results.cases[c.name] = r;
95
+ Object.assign(results.files, r.files ?? {});
96
+ }
97
+ const bad = assertStage1(results);
98
+ if (bad.length) fail(bad[0][0], bad.map((b) => b[1]).join("; "));
99
+ ctx.notes.push(...compareSnapshots(results, { dir: ctx.snapshotDir, update: ctx.update }));
100
+ }
101
+
102
+ /** Stage 2: setup, doctor green and the first merged PR on the sandbox repo; time to first merge and prompts recorded. */
103
+ export async function stage2(ctx) {
104
+ const { io, repo } = ctx;
105
+ if (!(await io.ghAuthed())) { ctx.notes.push("journey stage 2: skipped (gh is not authenticated)"); return; }
106
+ if (!(await io.claudeAvailable())) { ctx.notes.push("journey stage 2: skipped (Claude Code is not available)"); return; }
107
+ const start = io.now();
108
+ const dir = ctx.dir = await io.mkdir();
109
+ const run = async (step, args, opts) => {
110
+ const r = await io.cli(args, { cwd: dir, ...opts });
111
+ ctx.prompts.push(...String(r.stdout).split("\n").filter((l) => PROMPT.test(l)).map((l) => l.trim()));
112
+ if (r.code !== 0) fail(step, `forgedock ${args.join(" ")} exited ${r.code}: ${scrub(r.stderr || r.stdout).slice(0, 200)}`);
113
+ return r;
114
+ };
115
+ await run("setup", ["demo", dir, "--repo", repo]);
116
+ await run("doctor", ["doctor"]);
117
+ await run("first-merge", ["demo", dir, "--repo", repo, "--run"]);
118
+ const prs = JSON.parse(await io.gh(["pr", "list", "-R", repo, "--state", "merged", "--json", "number,mergedAt", "--limit", "20"]));
119
+ const merged = prs.map((p) => Date.parse(p.mergedAt)).filter((t) => t >= start).sort((a, b) => a - b)[0];
120
+ if (!merged) fail("first-merge", `no PR merged on ${repo} after the journey started`);
121
+ ctx.ttfmMs = merged - start;
122
+ }
123
+
124
+ async function cleanup2(ctx, errors) {
125
+ const { io, repo } = ctx;
126
+ if (ctx.dir) try { await io.rm(ctx.dir); } catch (e) { errors.push(`remove ${ctx.dir}: ${String(e.message ?? e).slice(0, 120)}`); }
127
+ if (ctx.startedStage2) {
128
+ try {
129
+ const open = JSON.parse(await io.gh(["issue", "list", "-R", repo, "--state", "open", "--json", "number,createdAt", "--limit", "50"]));
130
+ for (const i of open.filter((x) => Date.parse(x.createdAt) >= ctx.startedStage2)) await io.gh(["issue", "close", String(i.number), "-R", repo]);
131
+ } catch (e) { errors.push(`close journey issues: ${String(e.message ?? e).slice(0, 120)}`); }
132
+ }
133
+ }
134
+
135
+ /** Run both stages; the first failure stops them, cleanup always runs. */
136
+ export async function runNewUserJourney({ repo, io, snapshotDir = SNAPSHOT_DIR, update = false }) {
137
+ const ctx = { io, repo, snapshotDir, update, notes: [], prompts: [], ttfmMs: null, dir: null, startedStage2: null };
138
+ let out = { ok: true, step: null, message: null };
139
+ try {
140
+ await stage1(ctx);
141
+ ctx.startedStage2 = io.now();
142
+ await stage2(ctx);
143
+ } catch (e) { out = { ok: false, step: e.step ?? "journey", message: String(e.message ?? e) }; }
144
+ const cleanupErrors = [];
145
+ await cleanup2(ctx, cleanupErrors);
146
+ return { ...out, notes: ctx.notes, cleanupErrors, ttfmMs: ctx.ttfmMs, prompts: [...new Set(ctx.prompts)] };
147
+ }
148
+
149
+ // ── real io ──────────────────────────────────────────────────────────────────────────────────────────────────
150
+ const q = (s) => `'${String(s).replace(/'/g, `'\\''`)}'`;
151
+ const which = (bin) => { const r = spawnSync("sh", ["-c", `command -v ${bin}`], { encoding: "utf8" }); return r.status === 0 ? r.stdout.trim() : null; };
152
+ const TOOLS = ["node", "npm", "npx", "git", "sh", "env", "find", "head", "mkdir", "mktemp", "cat", "dirname", "uname", "sort", "rm", "tr", "sed", "printf"];
153
+
154
+ // Runs in the clean environment: npx the tarball with `args`, then report the exit code and every file written.
155
+ const script = (tgz, args) => `W=$(mktemp -d); H=$(mktemp -d); export HOME=$H; cd "$W"; npx --yes --package ${q(tgz)} forgedock ${args.map(q).join(" ")} 2>&1 </dev/null; rc=$?
156
+ printf '\\n@@RC %s\\n' "$rc"
157
+ for r in "$W" "$H"; do find "$r" \\( -name .npm -o -name node_modules -o -name _cacache \\) -prune -o -type f -print | while read -r f; do printf '@@FILE %s\\n' "$(printf %s "$f" | sed "s#^$W#.#;s#^$H#~#")"; head -c 4000 "$f"; printf '\\n@@END\\n'; done; done`;
158
+
159
+ export function parseCleanOutput(raw) {
160
+ const text = String(raw), at = text.indexOf("\n@@RC ");
161
+ if (at < 0) throw new Error("clean run produced no exit marker");
162
+ const [rcLine, ...rest] = text.slice(at + 1).split("\n");
163
+ const files = {};
164
+ for (const m of rest.join("\n").matchAll(/@@FILE (.*)\n([\s\S]*?)\n@@END/g)) files[m[1]] = m[2];
165
+ return { code: Number(rcLine.slice(5)), output: text.slice(0, at), files };
166
+ }
167
+
168
+ export function realJourneyIo(env = process.env, { docker } = {}) {
169
+ const root = join(HERE, "..", "..");
170
+ const useDocker = docker ?? (which("docker") && spawnSync("docker", ["info"], { stdio: "ignore" }).status === 0);
171
+ const scratch = mkdtempSync(join(env.TMPDIR || tmpdir(), "journey-"));
172
+ const sh = (cmd, args, o = {}) => spawnSync(cmd, args, { encoding: "utf8", maxBuffer: 64 * 1024 * 1024, ...o });
173
+ const cliPath = join(root, "bin", "forgedock.mjs");
174
+ return {
175
+ now: () => Date.now(),
176
+ pack: async () => {
177
+ const r = sh("npm", ["pack", "--silent", "--pack-destination", scratch], { cwd: root });
178
+ if (r.status !== 0) throw new Error(r.stderr.trim() || `npm pack exited ${r.status}`);
179
+ return join(scratch, r.stdout.trim().split("\n").at(-1));
180
+ },
181
+ clean: async (tgz, args) => {
182
+ if (useDocker) {
183
+ const labels = String(env.FORGE_DOCKER_LABELS ?? "").split(/[\s,]+/).filter(Boolean).flatMap((l) => ["--label", l]);
184
+ const r = sh("docker", ["run", "--rm", ...labels, "-v", `${dirname(tgz)}:/pkg:ro`, env.FORGE_JOURNEY_IMAGE || "node:22", "sh", "-c", script(`/pkg/${tgz.split("/").at(-1)}`, args)]);
185
+ return parseCleanOutput(r.stdout);
186
+ }
187
+ // Host fallback: a PATH holding only node and git (and the shell basics), a throwaway HOME.
188
+ const bin = join(scratch, "bin"); mkdirSync(bin, { recursive: true });
189
+ for (const t of TOOLS) { const p = which(t); if (p?.startsWith("/") && !existsSync(join(bin, t))) try { symlinkSync(p, join(bin, t)); } catch { /* already linked */ } }
190
+ const r = sh(join(bin, "sh"), ["-c", script(tgz, args)], { env: { PATH: bin, LANG: "C", TMPDIR: scratch, NO_COLOR: "1", CI: "1" } });
191
+ return parseCleanOutput(r.stdout);
192
+ },
193
+ ghAuthed: async () => sh("gh", ["auth", "status"]).status === 0,
194
+ claudeAvailable: async () => sh("claude", ["--version"]).status === 0,
195
+ gh: async (args) => { const r = sh("gh", args); if (r.status !== 0) throw new Error(r.stderr.trim() || `gh exited ${r.status}`); return r.stdout; },
196
+ mkdir: async () => mkdtempSync(join(scratch, "demo-")),
197
+ rm: async (d) => rmSync(d, { recursive: true, force: true }),
198
+ cli: async (args, { cwd } = {}) => { const r = sh(process.execPath, [cliPath, ...args], { cwd, env, timeout: 45 * 60 * 1000, input: "" }); return { code: r.status ?? 1, stdout: r.stdout ?? "", stderr: r.stderr ?? "" }; },
199
+ dispose: () => rmSync(scratch, { recursive: true, force: true }),
200
+ };
201
+ }
202
+
203
+ // ── CLI ──────────────────────────────────────────────────────────────────────────────────────────────────────
204
+ const REPO_RE = /^[\w.-]+\/[\w.-]+$/;
205
+ const val = (argv, f) => { const i = argv.indexOf(f), v = argv[i + 1]; if (i < 0) return null; if (v == null || String(v).startsWith("--")) throw new Error(`${f} needs a value`); return v; };
206
+
207
+ /** `forgedock selftest --journey [--repo o/sandbox] [--pr N] [--release-repo o/r] [--update-snapshots]`. */
208
+ export async function journeyFromCli(argv, deps = {}) {
209
+ const cwd = deps.cwd ?? process.cwd(), env = deps.env ?? process.env, print = deps.print ?? ((l) => console.log(l));
210
+ let cfg = {}; try { cfg = parseForgeYaml(readFileSync(join(cwd, "forge.yaml"), "utf8")) ?? {}; } catch { /* none */ }
211
+ const repo = [val(argv, "--repo"), cfg.selftest?.sandbox_repo].map((v) => String(v ?? "").trim()).find((v) => REPO_RE.test(v));
212
+ if (!repo) throw new Error("no sandbox repo: pass --repo owner/sandbox or set selftest.sandbox_repo in forge.yaml\nusage: forgedock selftest --journey [--repo <owner/sandbox>] [--pr <N>] [--update-snapshots]");
213
+ const project = cfg.project?.owner && cfg.project?.repo ? `${cfg.project.owner}/${cfg.project.repo}` : null;
214
+ if (project && project.toLowerCase() === repo.toLowerCase()) throw new Error(`refusing to run in ${repo}: it is this project's repo (forge.yaml project); use a disposable sandbox repo`);
215
+ const io = deps.io ?? realJourneyIo(env);
216
+ const pr = val(argv, "--pr");
217
+ let releaseRepo = null, head = null;
218
+ if (pr) {
219
+ releaseRepo = val(argv, "--release-repo") ?? JSON.parse(String(await io.gh(["repo", "view", "--json", "nameWithOwner"]))).nameWithOwner;
220
+ if (releaseRepo.toLowerCase() === repo.toLowerCase()) throw new Error(`refusing to run in ${repo}: it is the release repo`);
221
+ head = String(await io.gh(["pr", "view", String(pr), "-R", releaseRepo, "--json", "headRefOid", "--jq", ".headRefOid"])).trim();
222
+ }
223
+ let r;
224
+ try { r = await runNewUserJourney({ repo, io, update: argv.includes("--update-snapshots"), ...(deps.snapshotDir ? { snapshotDir: deps.snapshotDir } : {}) }); } finally { io.dispose?.(); }
225
+ for (const n of r.notes) print(n);
226
+ for (const e of r.cleanupErrors) print(`cleanup: ${e}`);
227
+ if (r.ttfmMs != null) print(`journey: time to first merged PR ${Math.round(r.ttfmMs / 1000)}s; prompts shown: ${r.prompts.length ? r.prompts.join(" | ") : "none"}`);
228
+ print(r.ok ? `selftest --journey: all stages passed on ${repo}` : `selftest --journey FAILED at step ${r.step}: ${r.message}`);
229
+ if (pr) {
230
+ const { postJourneyMarker } = await import("./selftest-gate.mjs");
231
+ await postJourneyMarker((a) => io.gh(a), releaseRepo, pr, { result: r.ok ? "pass" : "fail", sha: head, step: r.step, ttfm: r.ttfmMs == null ? null : Math.round(r.ttfmMs / 1000) });
232
+ }
233
+ return { ok: r.ok, step: r.step, message: r.message };
234
+ }
@@ -0,0 +1,130 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ import { describe, it } from "node:test";
4
+ import assert from "node:assert/strict";
5
+ import { readFileSync } from "node:fs";
6
+ import { join } from "node:path";
7
+ import { scrub, assertStage1, compareSnapshots, runNewUserJourney, parseCleanOutput, journeyFromCli, CASES } from "./selftest-journey.mjs";
8
+ import { selftestFromCli } from "./selftest-live.mjs";
9
+ import { tmpDir } from "../tests/_tmp.mjs";
10
+
11
+ const GOOD = {
12
+ banner: { code: 0, output: "ForgeDock v1.2.3\n ✖ Claude Code not found\n" },
13
+ help: { code: 0, output: "Usage: forgedock <command>\n" },
14
+ doctor: { code: 1, output: " ✗ gh CLI\n ✗ Claude Code settings\n" },
15
+ errors: { code: 1, output: "Unknown command: nosuchcommand\n" },
16
+ };
17
+ const stage1Io = (over = {}, files = { "./forge.yaml": 'owner: "acme"\n' }) => ({
18
+ pack: async () => "/x/f.tgz",
19
+ clean: async (_t, args) => { const c = CASES.find((k) => k.args.join(" ") === args.join(" ")); return { ...(over[c.name] ?? GOOD[c.name]), files: c.name === "banner" ? files : {} }; },
20
+ });
21
+ const now = (() => { let t = 1000; return () => (t += 10); })();
22
+ const io2 = (over = {}) => ({
23
+ now, ghAuthed: async () => true, claudeAvailable: async () => true, mkdir: async () => "/d", rm: async () => {},
24
+ cli: async (args) => ({ code: 0, stdout: args.includes("--run") ? "Proceed? [y/N]\nmerged\n" : "ok\n", stderr: "" }),
25
+ gh: async (a) => (a[0] === "pr" ? JSON.stringify([{ number: 1, mergedAt: new Date(5000).toISOString() }]) : "[]"),
26
+ ...over,
27
+ });
28
+ const run = (io, o = {}) => { const dir = tmpDir("jt-"); return runNewUserJourney({ repo: "o/sandbox", io, snapshotDir: dir, update: true, ...o }).then(() => runNewUserJourney({ repo: "o/sandbox", io, snapshotDir: dir, ...o, update: false })); };
29
+
30
+ describe("journey scrub", () => {
31
+ it("removes paths, versions, ansi and timings", () => {
32
+ assert.equal(scrub("\u001b[31mv1.2.3\u001b[0m at /tmp/x/y took 12ms \n\n\n\nend"), "<ver> at <path> took <time>\n\nend\n");
33
+ });
34
+ });
35
+
36
+ describe("assertStage1 (the 2026-11-10 regression classes)", () => {
37
+ const ok = { cases: GOOD, files: { "./forge.yaml": 'owner: "acme" # TODO(forgedock:owner) verify\n' } };
38
+ it("passes the expected not-ready run, including deliberate # TODO flags", () => assert.deepEqual(assertStage1(ok), []));
39
+ it("fails a false success banner", () => {
40
+ const r = assertStage1({ ...ok, cases: { ...GOOD, banner: { code: 0, output: "✔ Claude Code ready\n" } } });
41
+ assert.match(r[0][1], /success wording/);
42
+ });
43
+ it("fails a doctor that exits 0, or never names the missing tools", () => {
44
+ assert.ok(assertStage1({ ...ok, cases: { ...GOOD, doctor: { code: 0, output: "all good" } } }).length >= 2);
45
+ });
46
+ it("fails jargon errors and a CLI that did not start", () => {
47
+ assert.match(assertStage1({ ...ok, cases: { ...GOOD, errors: { code: 1, output: "Error: ENOENT: no such file" } } })[0][1], /raw runtime/);
48
+ assert.match(assertStage1({ ...ok, cases: { ...GOOD, help: { code: 126, output: "Permission denied" } } })[0][1], /did not start/);
49
+ });
50
+ it("fails placeholder config values but not installed copies", () => {
51
+ assert.match(assertStage1({ ...ok, files: { "./forge.yaml": 'owner: "your-github-org"\n' } })[0][1], /placeholder/);
52
+ assert.deepEqual(assertStage1({ ...ok, files: { "~/.forge/commands/x.md": "TODO your-org" } }), []);
53
+ });
54
+ });
55
+
56
+ describe("snapshots", () => {
57
+ it("a missing snapshot fails naming the update flag; a changed one names the line", () => {
58
+ const dir = tmpDir("jt-");
59
+ const res = { cases: GOOD, files: {} };
60
+ assert.throws(() => compareSnapshots(res, { dir }), /--update-snapshots/);
61
+ compareSnapshots(res, { dir, update: true });
62
+ assert.equal(readFileSync(join(dir, "help.txt"), "utf8"), "Usage: forgedock <command>\n");
63
+ assert.doesNotThrow(() => compareSnapshots(res, { dir }));
64
+ assert.throws(() => compareSnapshots({ cases: { ...GOOD, help: { code: 0, output: "Usage: forgedock <cmd>\n" } }, files: {} }, { dir }), /help\.txt changed at line 1/);
65
+ });
66
+ });
67
+
68
+ describe("runNewUserJourney", () => {
69
+ it("passes both stages and records time to first merge and the prompts", async () => {
70
+ const r = await run({ ...stage1Io(), ...io2() });
71
+ assert.equal(r.ok, true, r.message);
72
+ assert.equal(r.prompts[0], "Proceed? [y/N]");
73
+ assert.ok(r.ttfmMs > 0);
74
+ });
75
+ it("fails stage 1 on a wording regression against the snapshot", async () => {
76
+ const dir = tmpDir("jt-");
77
+ await runNewUserJourney({ repo: "o/s", io: { ...stage1Io(), ...io2() }, snapshotDir: dir, update: true });
78
+ const r = await runNewUserJourney({ repo: "o/s", io: { ...stage1Io({ help: { code: 0, output: "Usage: forgedock <thing>\n" } }), ...io2() }, snapshotDir: dir });
79
+ assert.equal(r.ok, false);
80
+ assert.match(r.message, /help\.txt changed/);
81
+ assert.equal(r.step, "snapshot");
82
+ });
83
+ it("fails on a false success banner before stage 2 starts", async () => {
84
+ let cli = 0;
85
+ const r = await run({ ...stage1Io({ banner: { code: 0, output: "setup complete\n" } }), ...io2({ cli: async () => { cli++; return { code: 0, stdout: "", stderr: "" }; } }) });
86
+ assert.equal(r.step, "banner");
87
+ assert.equal(cli, 0);
88
+ });
89
+ it("skips stage 2 with a note when gh is unauthenticated", async () => {
90
+ const r = await run({ ...stage1Io(), ...io2({ ghAuthed: async () => false }) });
91
+ assert.equal(r.ok, true);
92
+ assert.match(r.notes.join("\n"), /stage 2: skipped \(gh/);
93
+ });
94
+ it("names the step when doctor is not green, and still cleans up", async () => {
95
+ const removed = [], closed = [];
96
+ const r = await run({ ...stage1Io(), ...io2({
97
+ rm: async (d) => removed.push(d),
98
+ cli: async (args) => (args[0] === "doctor" ? { code: 1, stdout: "", stderr: "gh missing" } : { code: 0, stdout: "", stderr: "" }),
99
+ gh: async (a) => { if (a[1] === "close" || a[0] === "issue" && a[1] === "close") closed.push(a[2]); return a[0] === "issue" && a[1] === "list" ? JSON.stringify([{ number: 7, createdAt: new Date(9e12).toISOString() }]) : "[]"; },
100
+ }) });
101
+ assert.equal(r.step, "doctor");
102
+ assert.ok(removed.length > 0 && removed.every((d) => d === "/d"));
103
+ assert.ok(closed.length > 0 && closed.every((n) => n === "7"));
104
+ });
105
+ it("fails when no PR merged after the journey started", async () => {
106
+ const r = await run({ ...stage1Io(), ...io2({ gh: async () => "[]" }) });
107
+ assert.equal(r.step, "first-merge");
108
+ });
109
+ });
110
+
111
+ describe("clean output parsing and the CLI", () => {
112
+ it("parses the exit code and files", () => {
113
+ const p = parseCleanOutput("hello\n\n@@RC 3\n@@FILE ./a\nx\ny\n@@END\n");
114
+ assert.deepEqual(p, { code: 3, output: "hello\n", files: { "./a": "x\ny" } });
115
+ assert.throws(() => parseCleanOutput("nothing"), /no exit marker/);
116
+ });
117
+ it("selftest --journey routes here, refuses the project repo and posts the marker", async () => {
118
+ await assert.rejects(selftestFromCli(["--journey"], { cwd: "/nonexistent", print: () => {}, io: {} }), /no sandbox repo/);
119
+ const calls = [], out = [], head = "c".repeat(40), dir = tmpDir("jt-");
120
+ const gh = async (a) => { calls.push(a); return a[0] === "pr" && a[1] === "view" ? head : a[0] === "pr" ? JSON.stringify([]) : "[]"; };
121
+ const io = { ...stage1Io(), ...io2({ gh }) };
122
+ await runNewUserJourney({ repo: "o/s", io, snapshotDir: dir, update: true });
123
+ const r = await journeyFromCli(["--journey", "--repo", "o/sandbox", "--pr", "9", "--release-repo", "o/rel"], { cwd: "/nonexistent", print: (l) => out.push(l), io, snapshotDir: dir });
124
+ assert.equal(r.ok, false);
125
+ assert.equal(r.step, "first-merge");
126
+ assert.match(calls.at(-1).at(-1), new RegExp(`^<!-- FORGE:JOURNEY result=fail sha=${head} step=first-merge ttfm=na -->`));
127
+ assert.match(out.join("\n"), /FAILED at step first-merge/);
128
+ await assert.rejects(journeyFromCli(["--journey", "--repo", "o/rel", "--pr", "9", "--release-repo", "o/rel"], { cwd: "/nonexistent", print: () => {}, io }), /release repo/);
129
+ });
130
+ });
@@ -229,7 +229,8 @@ const repoOrNull = (v) => (REPO_RE.test(String(v ?? "").trim()) ? String(v).trim
229
229
  /** `forgedock selftest [--static] | --live --repo <o/sandbox> [--lang node|python] [--pr N]`; non-zero exit names the failed step. */
230
230
  export async function selftestFromCli(argv, deps = {}) {
231
231
  const cwd = deps.cwd ?? process.cwd(), env = deps.env ?? process.env, print = deps.print ?? ((l) => console.log(l));
232
- const usage = "usage: forgedock selftest [--static] | --live [--repo <owner/sandbox>] [--lang node|python] [--pr <staging->main PR>] (sandbox repo from --repo or forge.yaml selftest.sandbox_repo)";
232
+ const usage = "usage: forgedock selftest [--static] | --live [--repo <owner/sandbox>] [--lang node|python] [--pr <staging->main PR>] | --journey [--repo <owner/sandbox>] [--pr <N>] [--update-snapshots] (sandbox repo from --repo or forge.yaml selftest.sandbox_repo)";
233
+ if (argv.includes("--journey")) return (await import("./selftest-journey.mjs")).journeyFromCli(argv, deps); // #5305
233
234
  if (!argv.includes("--live") && !argv.includes("--static")) throw new Error(usage);
234
235
  const nightlyRepo = argv.includes("--nightly-report") ? flag(argv, "--nightly-report") : null;
235
236
  if (nightlyRepo) {
@@ -27,7 +27,7 @@ const RESERVE_TTL_MS = 24 * 3600 * 1000;
27
27
  * `acquire({repo, lane, dirs, issue, maxWaitS})` takes every dir's lease in sorted order (no lock-order deadlock).
28
28
  * @returns {{acquire: (e:object) => Promise<{waitMs:number, timedOut:boolean, release:Function}>}}
29
29
  */
30
- export function makeSequenceLeaseIo({ dir = join(schedDir(), "seq-lease"), pickDir = join(schedDir(), "seq-pick"), open = openHeavy, acquire = acquireHeavy, pollMs, alive = pidAlive, now = () => Date.now() } = {}) {
30
+ export function makeSequenceLeaseIo({ dir = join(schedDir(), "seq-lease"), pickDir = join(schedDir(), "seq-pick"), declDir = join(schedDir(), "surface-declared"), open = openHeavy, acquire = acquireHeavy, pollMs, alive = pidAlive, now = () => Date.now() } = {}) {
31
31
  const reservedDirs = new Map(); // `${repo}\0${lane}\0${issue}` -> dirs reserved in, for unreserve
32
32
  /** Run `fn(entries) => entries'` on one key's reservations under its pick lock; returns what `fn` set as `out`. */
33
33
  const locked = async ({ repo, lane, dir: d }, fn) => {
@@ -46,7 +46,41 @@ export function makeSequenceLeaseIo({ dir = join(schedDir(), "seq-lease"), pickD
46
46
  return r.out;
47
47
  } finally { try { g.release(); } catch { /* fail-open */ } }
48
48
  };
49
+ /** #5340: run `fn(entries) => entries'` on one repo's surface declarations under their own lock; entries of dead pids or older than 24h are dropped first. */
50
+ const lockedDecl = async (repo, fn) => {
51
+ const kd = join(declDir, createHash("sha1").update(String(repo)).digest("hex").slice(0, 16)), file = join(kd, "declared.json");
52
+ const h = open(kd, { cfg: { max: 1, max_wait_s: 60 }, env: {}, host: NO_MEM });
53
+ const g = await acquire(h, { phase: "surface-declare" }, ...(pollMs ? [{ pollMs }] : []));
54
+ try {
55
+ let entries = [];
56
+ try { const o = JSON.parse(readFileSync(file, "utf8")); if (Array.isArray(o?.entries)) entries = o.entries; } catch { /* none yet */ }
57
+ const t = now();
58
+ entries = entries.filter((e) => Array.isArray(e?.surfaces) && alive(e.pid) && t - Number(e.at ?? 0) < RESERVE_TTL_MS);
59
+ const r = fn(entries);
60
+ mkdirSync(kd, { recursive: true });
61
+ writeFileSync(`${file}.tmp`, `${JSON.stringify({ entries: r.entries }, null, 2)}\n`);
62
+ renameSync(`${file}.tmp`, file);
63
+ return r.out;
64
+ } finally { try { g.release(); } catch { /* fail-open */ } }
65
+ };
66
+ const declared = new Set(); // `${repo}\0${issue}` declared by this process, for undeclare
49
67
  return {
68
+ /** #5340: record what `issue` will add on shared surfaces, for sibling context packs. Fail-open (never throws). */
69
+ async declare({ repo, issue = null, surfaces = [], paths = [], pid = process.pid } = {}) {
70
+ try {
71
+ declared.add(`${repo}\0${issue}`);
72
+ await lockedDecl(repo, (entries) => ({ entries: [...entries.filter((e) => String(e.issue) !== String(issue)), { issue, pid, surfaces, paths: paths.slice(0, 40), at: now() }] }));
73
+ } catch { /* fail-open */ }
74
+ },
75
+ /** #5340: drop `issue`'s declaration (run end). Never throws. */
76
+ async undeclare({ repo, issue = null } = {}) {
77
+ if (!declared.delete(`${repo}\0${issue}`)) return;
78
+ try { await lockedDecl(repo, (entries) => ({ entries: entries.filter((e) => String(e.issue) !== String(issue)) })); } catch { /* fail-open */ }
79
+ },
80
+ /** #5340: live declarations of in-flight lanes in `repo`, other than `except`: [{issue, surfaces, paths}]; [] on error. */
81
+ async declared({ repo, except = null } = {}) {
82
+ try { return await lockedDecl(repo, (entries) => ({ entries, out: entries.filter((e) => String(e.issue) !== String(except)).map(({ issue, surfaces, paths }) => ({ issue, surfaces, paths })) })); } catch { return []; }
83
+ },
50
84
  /**
51
85
  * #4526: `count` consecutive numbers above max(floor, every other issue's live reservation) in (repo, lane, dir),
52
86
  * recorded for `issue` (its earlier entries there replaced). @returns {Promise<{numbers:number[]}|null>} null on error.
@@ -55,6 +55,21 @@ describe("sequence lease (#4386)", () => {
55
55
  });
56
56
  });
57
57
 
58
+ describe("#5340 surface declarations", () => {
59
+ it("declare/declared/undeclare per repo, dead holders dropped, never throws", async () => {
60
+ const dead = new Set();
61
+ const io = makeSequenceLeaseIo({ dir: tmpDir("seqlease-"), declDir: tmpDir("decl-"), pollMs: 20, alive: (pid) => !dead.has(pid) });
62
+ await io.declare({ repo: "o/r", issue: 1, surfaces: ["api"], paths: ["api/a.ts"], pid: 11 });
63
+ await io.declare({ repo: "o/r", issue: 2, surfaces: ["api"], paths: ["api/b.ts"], pid: 12 });
64
+ await io.declare({ repo: "o/x", issue: 3, surfaces: ["api"], pid: 13 });
65
+ assert.deepEqual((await io.declared({ repo: "o/r", except: 2 })).map((d) => d.issue), [1]);
66
+ dead.add(11);
67
+ assert.deepEqual((await io.declared({ repo: "o/r" })).map((d) => d.issue), [2]);
68
+ await io.undeclare({ repo: "o/r", issue: 2 });
69
+ assert.deepEqual(await io.declared({ repo: "o/r" }), []);
70
+ });
71
+ });
72
+
58
73
  const env = { ...process.env, GIT_AUTHOR_NAME: "t", GIT_AUTHOR_EMAIL: "t@t", GIT_COMMITTER_NAME: "t", GIT_COMMITTER_EMAIL: "t@t" };
59
74
  const sh = (cwd, ...a) => execFileSync("git", a, { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], env });
60
75
  const gitIn = (cwd) => async (a) => sh(cwd, ...a);