forgedock 1.59.2 → 1.60.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 (94) hide show
  1. package/bin/engine/outcome-codes.mjs +3 -3
  2. package/bin/engine-cli.mjs +50 -10
  3. package/bin/labels.json +5 -0
  4. package/bin/lean/batch.mjs +21 -2
  5. package/bin/lean/batch.test.mjs +116 -1
  6. package/bin/lean/conformance.mjs +12 -5
  7. package/bin/lean/conformance.test.mjs +30 -2
  8. package/bin/lean/depcache.mjs +34 -15
  9. package/bin/lean/depcache.test.mjs +100 -1
  10. package/bin/lean/design-gate.mjs +15 -10
  11. package/bin/lean/design-gate.test.mjs +21 -0
  12. package/bin/lean/effects.mjs +18 -2
  13. package/bin/lean/execution.mjs +23 -5
  14. package/bin/lean/execution.test.mjs +81 -1
  15. package/bin/lean/gatewatch.test.mjs +5 -5
  16. package/bin/lean/issuewatch-triage.mjs +68 -0
  17. package/bin/lean/issuewatch-triage.test.mjs +98 -0
  18. package/bin/lean/issuewatch.mjs +34 -6
  19. package/bin/lean/issuewatch.test.mjs +11 -0
  20. package/bin/lean/lanelock.mjs +5 -4
  21. package/bin/lean/lean.mjs +123 -17
  22. package/bin/lean/lean.test.mjs +154 -6
  23. package/bin/lean/orchestrate-cancel.test.mjs +33 -0
  24. package/bin/lean/orchestrate-hostfallback.test.mjs +41 -0
  25. package/bin/lean/orchestrate-recovering.test.mjs +42 -0
  26. package/bin/lean/orchestrate.mjs +23 -10
  27. package/bin/lean/pagegate.mjs +50 -12
  28. package/bin/lean/pagegate.test.mjs +38 -1
  29. package/bin/lean/phaseledger.mjs +65 -2
  30. package/bin/lean/phaseledger.test.mjs +70 -2
  31. package/bin/lean/preflight.mjs +5 -2
  32. package/bin/lean/preflight.test.mjs +7 -0
  33. package/bin/lean/prompts.mjs +2 -1
  34. package/bin/lean/recovery.test.mjs +11 -6
  35. package/bin/lean/release-classify.mjs +143 -0
  36. package/bin/lean/release-classify.test.mjs +130 -0
  37. package/bin/lean/release-conductor.mjs +163 -0
  38. package/bin/lean/release-conductor.test.mjs +194 -0
  39. package/bin/lean/release-config.mjs +60 -8
  40. package/bin/lean/release-config.test.mjs +43 -1
  41. package/bin/lean/release-control.mjs +22 -5
  42. package/bin/lean/release-control.test.mjs +22 -0
  43. package/bin/lean/release-credentials.mjs +40 -0
  44. package/bin/lean/release-credentials.test.mjs +42 -0
  45. package/bin/lean/release-deploy.mjs +3 -3
  46. package/bin/lean/release-deploy.test.mjs +8 -0
  47. package/bin/lean/release-docs.test.mjs +93 -0
  48. package/bin/lean/release-fence.mjs +2 -0
  49. package/bin/lean/release-gate.mjs +88 -0
  50. package/bin/lean/release-gate.test.mjs +116 -0
  51. package/bin/lean/release-gates.mjs +5 -1
  52. package/bin/lean/release-ledger.mjs +47 -1
  53. package/bin/lean/release-ledger.test.mjs +33 -1
  54. package/bin/lean/release-mergeback.mjs +148 -0
  55. package/bin/lean/release-mergeback.test.mjs +129 -0
  56. package/bin/lean/release-p0.mjs +193 -0
  57. package/bin/lean/release-p0.test.mjs +127 -0
  58. package/bin/lean/release-plan.mjs +267 -0
  59. package/bin/lean/release-plan.test.mjs +202 -0
  60. package/bin/lean/release-preflight.mjs +16 -0
  61. package/bin/lean/release-regate.mjs +141 -0
  62. package/bin/lean/release-regate.test.mjs +149 -0
  63. package/bin/lean/release-review.mjs +5 -3
  64. package/bin/lean/release-rollback.mjs +277 -0
  65. package/bin/lean/release-rollback.test.mjs +245 -0
  66. package/bin/lean/release-snapshot.mjs +48 -9
  67. package/bin/lean/release-snapshot.test.mjs +43 -1
  68. package/bin/lean/release-start.mjs +164 -0
  69. package/bin/lean/release-start.test.mjs +171 -0
  70. package/bin/lean/release-status.mjs +6 -2
  71. package/bin/lean/release-train.mjs +159 -0
  72. package/bin/lean/release-train.test.mjs +139 -0
  73. package/bin/lean/release.mjs +127 -5
  74. package/bin/lean/release.test.mjs +80 -0
  75. package/bin/lean/sandbox-remote.mjs +2 -0
  76. package/bin/lean/schedd-load.test.mjs +82 -0
  77. package/bin/lean/schedd.mjs +67 -31
  78. package/bin/lean/schedd.test.mjs +80 -1
  79. package/bin/lean/validate-catalog.mjs +94 -0
  80. package/bin/lean/validate-catalog.test.mjs +42 -0
  81. package/bin/pool/agent.mjs +4 -1
  82. package/bin/pool/lane-tools.mjs +115 -0
  83. package/bin/pool/lane-tools.test.mjs +26 -0
  84. package/bin/pool/warm.mjs +1 -1
  85. package/docs/CONFIG.md +225 -1
  86. package/docs/ISSUE-WATCH.md +1 -0
  87. package/docs/design/visual-gate.md +10 -0
  88. package/docs/eval/adversarial-bench.md +1 -0
  89. package/package.json +1 -1
  90. package/pool/README.md +2 -0
  91. package/scripts/bench-adversarial.mjs +4 -0
  92. package/scripts/bench-lightlane.mjs +2 -1
  93. package/templates/github-actions/forge-conductor.scopes.json +7 -0
  94. package/templates/github-actions/forge-conductor.yml +57 -0
@@ -0,0 +1,41 @@
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 { orchestrate } from "./orchestrate.mjs";
6
+ import { hostFallbackAllowed } from "./execution.mjs";
7
+
8
+ // #5652: host re-placement of a remote lane's env.tool_missing / env.capability_remote end follows host.role / execution.host_fallback.
9
+ const go = async (code, cfg) => {
10
+ const calls = [];
11
+ const rows = await orchestrate({ issues: [5], parallel: 2, recovery: { maxAttempts: 1 }, readBody: async () => "",
12
+ remote: { max: 2, isRemote: () => true, hostFallback: hostFallbackAllowed(cfg), place: () => ({ where: "remote", reason: "mode remote" }), admit: () => ({ ok: true }), onBudget: "stop", costPerMinute: 0 },
13
+ runOne: async (n, _l, ctx = {}) => {
14
+ calls.push({ placement: ctx.placement?.where, recover: ctx.recover?.code ?? null });
15
+ return ctx.recover ? { terminalReason: "merged", pr: 9 } : { terminalReason: "needs-human", code, detail: "no tool", placement: { where: "remote" } };
16
+ } });
17
+ return { rows, calls };
18
+ };
19
+
20
+ describe("#5652 host fallback placement", () => {
21
+ for (const code of ["env.capability_remote", "env.tool_missing"]) {
22
+ it(`${code}: host.role unset keeps the host re-placement`, async () => {
23
+ const r = await go(code, {});
24
+ assert.equal(r.calls.length, 2);
25
+ });
26
+ it(`${code}: host.role orchestrator ends the lane without a host re-placement`, async () => {
27
+ const r = await go(code, { hostRole: "orchestrator" });
28
+ assert.equal(r.calls.length, 1);
29
+ assert.equal(r.rows.find((x) => x.issue === 5).outcome, "needs-human");
30
+ });
31
+ it(`${code}: explicit host_fallback: true overrides host.role orchestrator`, async () => {
32
+ const r = await go(code, { hostRole: "orchestrator", hostFallback: true });
33
+ assert.equal(r.calls.length, 2);
34
+ assert.equal(r.calls[1].placement === "local" || r.calls[1].placement === "remote", true);
35
+ });
36
+ }
37
+ it("regression: a non-host code (ci.red-like) recovery is unaffected by host.role", async () => {
38
+ const r = await go("env.repro_unrunnable", { hostRole: "orchestrator" });
39
+ assert.ok(r.calls.length >= 1);
40
+ });
41
+ });
@@ -0,0 +1,42 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ // #5647: while a recovery lane is queued or running the issue shows workflow:recovering, not needs-human.
4
+ import { describe, it } from "node:test";
5
+ import assert from "node:assert/strict";
6
+ import { tmpDir } from "../tests/_tmp.mjs";
7
+ import { orchestrate } from "./orchestrate.mjs";
8
+
9
+ process.env.FORGEDOCK_SCHED_DIR = tmpDir("recovering-sched-");
10
+ const NH = (code) => ({ terminalReason: "needs-human", code, detail: `ended ${code}` });
11
+ const run = (script, extra = {}) => {
12
+ const marks = [], relabels = [], rows = [];
13
+ let k = 0;
14
+ return orchestrate({ issues: [1], parallel: 1, recovery: { maxAttempts: 1 }, readBody: async () => "", onUpdate: (r) => rows.push(r.outcome),
15
+ runOne: async () => script[Math.min(k++, script.length - 1)],
16
+ markRecovering: async (x) => { marks.push(x); }, relabelNeedsHuman: async (x) => { relabels.push(x); }, ...extra })
17
+ .then((res) => ({ res, marks, relabels, rows }));
18
+ };
19
+
20
+ describe("workflow:recovering during recovery (#5647)", () => {
21
+ it("a recoverable needs-human row calls markRecovering once with attempt/max and the row goes recovering", async () => {
22
+ const r = await run([NH("base.conflict"), { terminalReason: "merged" }]);
23
+ assert.deepEqual(r.marks, [{ issue: 1, code: "base.conflict", attempt: 1, max: 1 }]);
24
+ assert.ok(r.rows.includes("recovering"));
25
+ assert.equal(r.res[0].outcome, "merged");
26
+ assert.deepEqual(r.relabels, []);
27
+ });
28
+ it("a throwing markRecovering does not block the recovery lane", async () => {
29
+ const r = await run([NH("base.conflict"), { terminalReason: "merged" }], { markRecovering: async () => { throw new Error("gh down"); } });
30
+ assert.equal(r.res[0].outcome, "merged");
31
+ });
32
+ it("an exhausted recovery ends needs-human through relabelNeedsHuman, after the single mark", async () => {
33
+ const r = await run([NH("base.conflict"), NH("base.conflict")]);
34
+ assert.equal(r.marks.length, 1);
35
+ assert.equal(r.res[0].outcome, "needs-human");
36
+ assert.equal(r.relabels.length, 1);
37
+ });
38
+ it("a human-owned code is never marked recovering", async () => {
39
+ const r = await run([NH("builder.blocked")]);
40
+ assert.deepEqual(r.marks, []);
41
+ });
42
+ });
@@ -249,6 +249,7 @@ export function deferPolicy(r, { now, deferrals = 0, maxDeferrals = DEFAULT_MAX_
249
249
  const k = deferrals + 1;
250
250
  if (k > maxDeferrals) return { capped: true };
251
251
  if (posNum(r?.retryInSeconds)) return { delayMs: r.retryInSeconds * 1000 };
252
+ if (code === "run.interrupted") return { delayMs: 0 }; // #5654: its lease was released, so there is nothing to wait out
252
253
  // lease-held: "leased by X until <ISO>"
253
254
  const until = /\buntil (\d{4}-\d\d-\d\dT[\d:.]+Z)/.exec(String(r?.detail ?? ""))?.[1];
254
255
  const at = until ? Date.parse(until) : NaN;
@@ -311,7 +312,7 @@ const toMap = (o) => new Map(Object.entries(o ?? {}).map(([k, v]) => [Number(k),
311
312
  export async function orchestrate({ issues, parallel = 3, runOne, readBody, prefilter = null, resolveLane = null, now = () => Date.now(), blockedRefreshMs = 60000, onUpdate = () => {}, onCrossLane = () => {},
312
313
  store = null, adopt = null, getParallel = null, getAdded = null, getRequeued = null, breaker = null, maxDeferrals = DEFAULT_MAX_DEFERRALS, sleep = cancellableSleep, pollMs = 5000,
313
314
  classify = null, maintenance = null, limits = null, identity = () => "default", batchId = null, drift = null, integration = null, sched = null, priorityOf = null, remote = null, beforeAdmit = null, preflight = null,
314
- recovery = null, decide = () => {}, conflicting = null, relabelNeedsHuman = null, onExit = null, issueLabels = null, issueState = null, getCancelled = null, getHeld = null, expireHolds = null, getHoldInfo = null, getBlocked = null, trusted = null, getGates = null, stopLane = null, releaseLease = null, stopRetryMs = STOP_RETRY_MS, stopTimeoutMs = STOP_TIMEOUT_MS,
315
+ recovery = null, decide = () => {}, conflicting = null, relabelNeedsHuman = null, markRecovering = null, onExit = null, issueLabels = null, issueState = null, getCancelled = null, getHeld = null, expireHolds = null, getHoldInfo = null, getBlocked = null, trusted = null, getGates = null, stopLane = null, releaseLease = null, stopRetryMs = STOP_RETRY_MS, stopTimeoutMs = STOP_TIMEOUT_MS,
315
316
  estimate = null, starveMs = DEFAULT_STARVE_MS, setupConcurrency = DEFAULT_SETUP_CONCURRENCY, signal = null, dispatchCheck = null, syncParked = null, syncEveryMs = DEFAULT_SYNC_EVERY_MS, lifecycle = null,
316
317
  getChildren = null, autoChildren = null, baseWait = null, rotator = null, transientRetries = DEFAULT_TRANSIENT_RETRIES, overload = null, version = null, onInterrupted = null }) {
317
318
  const saved = store?.load?.() ?? null;
@@ -382,6 +383,7 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
382
383
  const remoteRun = new Set(); // remote lanes running now (#4253): admitted against remoteMax, never the host cap
383
384
  let budgetLocal = false; // the execution budget refused a remote lane under on_budget local: the rest run on the host
384
385
  // #4256: where a lane goes before capacity: `remote.place` (hybrid) or `remote.isRemote` (remote mode).
386
+ const hostFallbackOn = () => remote?.hostFallback !== false; // #5652: unset keeps the host re-placement
385
387
  const placeOf = (n) => {
386
388
  if (!remote) return null;
387
389
  // #4542: a lane recovering from a remote capability block runs on the host, which has the capability.
@@ -389,7 +391,8 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
389
391
  // #5423: the lane now provisions the sandbox before ending tool_missing, so the first tool-missing recovery of a remote run retries remotely (not parked behind host load); a repeat goes to the host
390
392
  const rec = recovering.get(n);
391
393
  if (rec?.code === OUTCOME_CODES.ENV_TOOL_MISSING && rec.where === "remote" && (rec.attempt ?? 1) <= 1 && !budgetLocal) return { where: "remote", reason: "retry remotely after sandbox provisioning" };
392
- if ([OUTCOME_CODES.ENV_CAPABILITY_REMOTE, OUTCOME_CODES.ENV_TOOL_MISSING].includes(recovering.get(n)?.code)) return { where: "local", reason: `host capability: recovering ${recovering.get(n).code}` };
394
+ // #5652: with host fallback off (execution.host_fallback / host.role: orchestrator) the host is orchestrator-only: no re-placement here
395
+ if (hostFallbackOn() && [OUTCOME_CODES.ENV_CAPABILITY_REMOTE, OUTCOME_CODES.ENV_TOOL_MISSING].includes(recovering.get(n)?.code)) return { where: "local", reason: `host capability: recovering ${recovering.get(n).code}` };
393
396
  // #5371: a mechanical recovery never repeats the placement of the run that failed (a remote sandbox env defect recurs there), and a remote validate failure is rerun on the host
394
397
  if (recovering.get(n)?.code === ENV_VALIDATE_PLACEMENT || (MECHANICAL_CODES.includes(recovering.get(n)?.code) && recovering.get(n)?.where === "remote")) return { where: "local", reason: `different placement: recovering ${recovering.get(n).code} off the remote run` };
395
398
  { // #5331: a frozen contract naming a tool the sandbox is known to lack runs on the host (`remote.lacks`, `remote.contractOf(n)`; both optional)
@@ -744,7 +747,8 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
744
747
  // Apply one lane's result: requeue it (deferred, dependency-open, engine-error) or record its final row.
745
748
  const settleLane = async (n, r, rec, pf) => {
746
749
  if (halted) return; // #4454: a resume adopts the lane and settles it
747
- if (cancelled && releaseLease) { try { await releaseLease(n, rec); } catch { /* best effort: the lease expires */ } } // #5241: the lane ended: its lease goes with it
750
+ // #5241: the lane ended: its lease goes with it. #5654: also an interrupted or engine-error end, which is requeued at once
751
+ if (releaseLease && (cancelled || (r?.terminalReason ?? "engine-error") === "engine-error" || (r?.terminalReason === "deferred" && r?.code === "run.interrupted"))) { try { await releaseLease(n, rec); } catch { /* best effort: the lease expires */ } }
748
752
  // #4304: the pre-filter runs once per issue; a recovery pass's row adds the earlier attempt's cost, which already holds it.
749
753
  const pfCost = recovering.has(n) ? 0 : (pf?.cost_usd ?? 0);
750
754
  const row = { issue: n, outcome: r?.terminalReason ?? "engine-error", pr: r?.pr ?? null, cost_usd: (r?.cost_usd ?? 0) + pfCost, minutes: Math.round((now() - rec.startedAt) / 6000) / 10, detail: r?.detail, ...(r?.code ? { code: r.code } : {}), ...(pf ? { prefilter: pf } : {}),
@@ -943,13 +947,18 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
943
947
  row.detail = `Environment defect: the recovery attempt failed with the same \`${row.code}\` as the run before it, so no further rebuild is spent; run the command below on the host with the project's real dependencies.\n${String(row.detail ?? "")}`;
944
948
  decided({ issue: n, what: `no further recovery for ${row.code}: the same failure repeated`, why: firstLine(row.detail), alternative: "requeue another recovery lane that rebuilds against the same frozen command" });
945
949
  }
946
- if (!repeatEnv && !sameHostReplay && classifyNeedsHuman(facts) === "recoverable" && used < max) {
950
+ // #5652: a remote lane's tool/capability end is not recovered on the host when host fallback is off; the lane message names the fix
951
+ const noHostRecovery = !hostFallbackOn() && row.placement?.where === "remote" && [OUTCOME_CODES.ENV_CAPABILITY_REMOTE, OUTCOME_CODES.ENV_TOOL_MISSING].includes(row.code);
952
+ if (noHostRecovery) decided({ issue: n, what: `no host re-placement for ${row.code}: host fallback is off (execution.host_fallback / host.role: orchestrator)`, why: firstLine(row.detail), alternative: "re-place the lane on the host" });
953
+ if (!repeatEnv && !noHostRecovery && !sameHostReplay && classifyNeedsHuman(facts) === "recoverable" && used < max) {
947
954
  const code = recoveryCodeOf(facts), attempt = used + 1;
948
955
  classUsed.set(`${n}:${cls}`, attempt);
949
956
  // #4315: the full lane detail is kept (never firstLine) for the relabel when the batch stops before this attempt
950
957
  recoveries.set(n, (recoveries.get(n) ?? 0) + 1); recovering.set(n, { code, attempt, max, cost_usd: Number(row.cost_usd) || 0, minutes: Number(row.minutes) || 0,
951
958
  detail: String(row.detail ?? ""), outcome: row.outcome, ...(row.placement?.where ? { where: row.placement.where } : {}), ...(row.code ? { result_code: row.code } : {}), prev_attempt: prior?.attempt ?? 0 });
952
959
  requeue(n, 0); done(); save();
960
+ // #5647: the first lane labelled needs-human before the batch chose to recover; swap it for workflow:recovering while the recovery runs
961
+ if (typeof markRecovering === "function") { try { await markRecovering({ issue: n, code, attempt, max }); } catch { /* best effort: needs-human stays */ } }
953
962
  decided({ issue: n, what: `recovery lane for ${code} (attempt ${attempt}/${max}); dependents stay queued`, why: firstLine(row.detail) || code,
954
963
  alternative: "leave needs-human for the operator and skip the dependents" });
955
964
  update({ ...row, outcome: "recovering", detail: `recovering (${code}), attempt ${attempt}/${max}: ${firstLine(row.detail)}` });
@@ -1039,7 +1048,7 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
1039
1048
  else if (pf?.parked) r = { terminalReason: pf.kind, cost_usd: 0, detail: `pre-filter: ${pf.detail}` };
1040
1049
  else {
1041
1050
  try {
1042
- r = await runOne(n, lane, { remote: !!rec.remote, ...(rec.placement ? { placement: rec.placement } : {}), ...(recovering.has(n) ? { recover: { code: recovering.get(n).code, attempt: recovering.get(n).attempt, final: recovering.get(n).attempt >= (recovering.get(n).max ?? recoveryMax) } } : {}), onStart: (info) => {
1051
+ r = await runOne(n, lane, { ...(signal ? { signal } : {}), remote: !!rec.remote, ...(rec.placement ? { placement: rec.placement } : {}), ...(recovering.has(n) ? { recover: { code: recovering.get(n).code, attempt: recovering.get(n).attempt, final: recovering.get(n).attempt >= (recovering.get(n).max ?? recoveryMax) } } : {}), onStart: (info) => {
1043
1052
  Object.assign(rec, info ?? {}); save();
1044
1053
  if (rec.remote && remoteRun.has(n)) noteRemote(n, rec.handle);
1045
1054
  if (cancelled) stop(n, rec); // #4376: launched while the cancel arrived
@@ -1058,9 +1067,13 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
1058
1067
  // #5204: a requeue is never silent: one `deferred`/`run.interrupted` row names the cause (an upgrade or a plain restart)
1059
1068
  // and `onInterrupted` reconciles the issue's labels. It consumes no deferral, engine-error or recovery attempt.
1060
1069
  const interruptCause = saved?.engineVersion && version && saved.engineVersion !== version ? `upgrade v${saved.engineVersion}→v${version}` : "dispatcher restart";
1061
- const requeueLost = (n, why) => {
1070
+ const requeueLost = async (n, why) => {
1071
+ const rec = runRecs.get(n);
1062
1072
  runRecs.delete(n);
1063
1073
  if (pending.includes(n) || results.has(n)) return;
1074
+ // #5654: the lost lane's own lease would defer the requeue as lease.held for its whole TTL
1075
+ if (releaseLease) { try { await releaseLease(n, rec); } catch { /* best effort: the lease expires */ } }
1076
+ if (pending.includes(n) || results.has(n)) return;
1064
1077
  pending.unshift(n); enqueued.set(n, now());
1065
1078
  update({ issue: n, outcome: "deferred", code: "run.interrupted", pr: null, cost_usd: 0, minutes: 0, detail: `interrupted: ${interruptCause}; ${why}; requeued` });
1066
1079
  decided({ issue: n, what: "requeued (interrupted)", why, alternative: "leave it pending silently" });
@@ -1072,7 +1085,7 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
1072
1085
  if (!adopt || !(rec?.pid || rec?.handle || rec?.remote)) return { n, rec, live: false, p: Promise.resolve(null) };
1073
1086
  let onLive;
1074
1087
  const isLive = new Promise((r) => { onLive = () => r(true); });
1075
- const p = Promise.resolve().then(() => adopt(n, rec, { onLive })).catch((e) => { adoptErrors.set(n, `adopt failed: ${firstLine(e?.message ?? e)}`); return null; });
1088
+ const p = Promise.resolve().then(() => adopt(n, rec, { onLive, ...(signal ? { signal } : {}) })).catch((e) => { adoptErrors.set(n, `adopt failed: ${firstLine(e?.message ?? e)}`); return null; });
1076
1089
  return { n, rec, p, first: Promise.race([p.then(() => false), isLive]) };
1077
1090
  });
1078
1091
  for (const a of adopting) a.live = a.first ? await a.first : false;
@@ -1080,17 +1093,17 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
1080
1093
  if (live) {
1081
1094
  if (rec.remote) { remoteRun.add(n); noteRemote(n, rec.handle); }
1082
1095
  else if (reg) { reg.adoptSlot(keyOf(n), { ...entryOf(n), lanePid: rec.pid }); slotted.add(n); }
1083
- track(n, p.then((r) => {
1096
+ track(n, p.then(async (r) => {
1084
1097
  if (r) return settle(n, r, rec, checked.get(n) ?? null);
1085
1098
  if (halted) return; // #4454: kept for the next resume
1086
- running.delete(n); releaseSlot(n); endRemote(n); requeueLost(n, "the adopted lane ended without a result"); save(); // ended without a result after all
1099
+ running.delete(n); releaseSlot(n); endRemote(n); await requeueLost(n, "the adopted lane ended without a result"); save(); // ended without a result after all
1087
1100
  }));
1088
1101
  continue;
1089
1102
  }
1090
1103
  const r = await p;
1091
1104
  if (!r) {
1092
1105
  const why = adoptErrors.get(n) ?? (!adopt || !(rec?.pid || rec?.handle || rec?.remote) ? "no adoptable pid or handle" : "the lane ended without a result");
1093
- requeueLost(n, why); continue;
1106
+ await requeueLost(n, why); continue;
1094
1107
  }
1095
1108
  if (rec.remote) { remoteRun.add(n); noteRemote(n, rec.handle); }
1096
1109
  else if (reg) { reg.adoptSlot(keyOf(n), { ...entryOf(n), lanePid: rec.pid }); slotted.add(n); } // released by the settle
@@ -37,7 +37,7 @@ export function parsePagesConfig(raw, { hasAppPages = false } = {}) {
37
37
  const req = list(obj.require).map((k) => k.toLowerCase()).filter((k) => PAGE_REQUIRE.includes(k));
38
38
  const pick = (v, d) => { const l = list(v); return l.length ? l : d; };
39
39
  return {
40
- routes, exclude: list(obj.exclude).map(norm), design_only: list(obj.design_only).map(norm), icp_doc: typeof obj.icp_doc === "string" && obj.icp_doc.trim() ? obj.icp_doc.trim() : null,
40
+ routes, exclude: list(obj.exclude).map(norm), design_only: list(obj.design_only).map(norm), generated: list(obj.generated).map(norm), rewrite_threshold: Number(obj.rewrite_threshold) > 0 && Number(obj.rewrite_threshold) <= 1 ? Number(obj.rewrite_threshold) : 0.6, icp_doc: typeof obj.icp_doc === "string" && obj.icp_doc.trim() ? obj.icp_doc.trim() : null,
41
41
  require: raw && obj.require !== undefined && req.length ? [...new Set(req)] : [...PAGE_REQUIRE],
42
42
  sitemap: pick(obj.sitemap, DEFAULTS.sitemap).map(norm), metadata_patterns: pick(obj.metadata_patterns, DEFAULTS.metadata),
43
43
  canonical_patterns: pick(obj.canonical_patterns, DEFAULTS.canonical), structured_data_patterns: pick(obj.structured_data_patterns, DEFAULTS.structured),
@@ -68,12 +68,47 @@ export function designOnlyFiles(files, cfg) {
68
68
  return [...new Set((files ?? []).map(norm).filter((f) => f && !TEST_RE.test(f) && anyGlob(cfg.design_only, f) && !anyGlob(cfg.exclude ?? [], f)))];
69
69
  }
70
70
 
71
+ const GENERATED_RE = /(?:^|\/)(?:__generated__|generated)(?:\/|$)/;
72
+ const MARKUP_RE = /<\/?[A-Za-z][\w.]*|\/>|\b(?:className|style|class)\s*=|^\s*(?:import|export)\b/;
73
+ /** Added and removed lines per file from a unified diff. */
74
+ function changedByFile(diff) {
75
+ const out = {}; let cur = null;
76
+ for (const line of String(diff ?? "").split("\n")) {
77
+ if (line.startsWith("+++ ")) { cur = line.replace(/^\+\+\+ (?:b\/)?/, "").trim(); if (cur === "/dev/null") cur = null; continue; }
78
+ if (line.startsWith("--- ")) continue;
79
+ if (cur && (line.startsWith("+") || line.startsWith("-"))) (out[cur] ??= []).push(line.slice(1));
80
+ }
81
+ return out;
82
+ }
83
+
84
+ /**
85
+ * #5648: how a diff touches a page file: "generated" (exempt: a generated/ path, a `pages.generated` glob or an @generated header),
86
+ * "new" (added, or unknown: no `added` list or no diff for the file fails closed), "rewrite" (a markup/style/import change, or churn at
87
+ * or over `threshold` of the file) or "copy" (only text or data lines changed: takes the visual-check path, no design spec).
88
+ */
89
+ export function pageChange(file, { added = null, diff = "", threshold = 0.6, generated = [], readFile = null } = {}) {
90
+ const f = norm(file);
91
+ if (GENERATED_RE.test(f) || anyGlob(generated ?? [], f)) return "generated";
92
+ let src = "";
93
+ try { src = typeof readFile === "function" ? String(readFile(f) ?? "") : ""; } catch { /* unreadable: no header, no churn */ }
94
+ if (/@generated|auto-?generated/i.test(src.split("\n").slice(0, 5).join("\n"))) return "generated";
95
+ if (!Array.isArray(added) || added.map(norm).includes(f)) return "new";
96
+ const lines = changedByFile(diff)[f];
97
+ if (!lines?.length) return "new";
98
+ if (lines.some((l) => MARKUP_RE.test(l))) return "rewrite";
99
+ const total = src ? src.split("\n").length : 0;
100
+ return total && lines.length / total >= threshold ? "rewrite" : "copy";
101
+ }
102
+
71
103
  const present = (o, ks) => ks.filter((k) => blank(o?.[k]));
72
104
 
73
105
  /** Contract-time problems: a deliverable that is a page needs `page_gate` {design_spec, seo, geo} per `pages.require`. [] when off or no page deliverable. */
74
- export function contractBriefProblems(contract, cfg, { readFile = null } = {}) {
106
+ export function contractBriefProblems(contract, cfg, { readFile = null, baseFiles = null } = {}) {
75
107
  const paths = (contract?.deliverables ?? []).map((d) => d?.path);
76
- const pages = pageFiles(paths, cfg, { readFile }), dOnly = designOnlyFiles(paths, cfg);
108
+ // #5648: a page already on the base is modified, not new: pageFailures judges rewrite vs copy from the diff; generated pages are exempt
109
+ const onBase = new Set(Array.isArray(baseFiles) ? baseFiles.map(norm) : []);
110
+ const gen = (f) => GENERATED_RE.test(f) || anyGlob(cfg?.generated ?? [], f);
111
+ const pages = pageFiles(paths, cfg, { readFile }).filter((f) => !onBase.has(f) && !gen(f)), dOnly = designOnlyFiles(paths, cfg).filter((f) => !onBase.has(f) && !gen(f));
77
112
  if (!pages.length && !dOnly.length) return [];
78
113
  if (!pages.length) {
79
114
  const g = contract?.page_gate;
@@ -129,38 +164,41 @@ const LINK_RE = /href\s*=\s*\{?\s*["'`](\/[^"'`#?\s{}$]*)/g;
129
164
  * Blocking failures (conformance.unimplemented) for the pages a diff adds or changes. `readFile(path)` returns worktree content or "";
130
165
  * `tracked` the repo's files; `designApproved` true/false/null (unknown skips); `run({command})` -> {rc, output} for `pages.lint`.
131
166
  */
132
- export async function pageFailures({ cfg, files = [], diff = "", result = null, readFile = () => "", tracked = null, designApproved = null, run = null }) {
133
- const pages = pageFiles(files, cfg, { readFile }), dOnly = designOnlyFiles(files, cfg), uiFiles = [...pages, ...dOnly];
167
+ export async function pageFailures({ cfg, files = [], diff = "", result = null, readFile = () => "", tracked = null, designApproved = null, run = null, added = null }) {
168
+ // #5648: generated pages are exempt; a modified copy-only page takes the visual-check path (no spec, no new-page briefs)
169
+ const kind = (f) => pageChange(f, { added, diff, threshold: cfg?.rewrite_threshold, generated: cfg?.generated, readFile });
170
+ const pages = pageFiles(files, cfg, { readFile }).filter((f) => kind(f) !== "generated"), dOnly = designOnlyFiles(files, cfg).filter((f) => kind(f) !== "generated"), uiFiles = [...pages, ...dOnly];
134
171
  if (!cfg || !uiFiles.length) return [];
172
+ const specFiles = uiFiles.filter((f) => kind(f) !== "copy"), briefPages = pages.filter((f) => kind(f) !== "copy");
135
173
  const C = OUTCOME_CODES.CONFORMANCE_UNIMPLEMENTED, out = [], j = result?.page_gate ?? {};
136
174
  const row = (kind, detail) => out.push({ code: C, kind, detail });
137
175
  if (cfg.require.includes("design")) {
138
- if (designApproved === false) row("page_design_missing", `${uiFiles.slice(0, 3).join(", ")} is a public page but the issue has no approved FORGE:DESIGN_SPEC: run /design before building`);
176
+ if (designApproved === false && specFiles.length) row("page_design_missing", `${specFiles.slice(0, 3).join(", ")} is a public page but the issue has no approved FORGE:DESIGN_SPEC: run /design before building`);
139
177
  const shots = list(j.screenshots).join(" ");
140
178
  if (!/390/.test(shots) || !/1440/.test(shots)) row("page_visual_missing", `${uiFiles.slice(0, 3).join(", ")}: the result's page_gate.screenshots must name a 390px and a 1440px visual check attached to the PR`);
141
179
  }
142
180
  const all = [...new Set([...(tracked ?? []), ...files].map(norm))];
143
- if (pages.length && cfg.require.includes("seo_intent")) {
181
+ if (briefPages.length && cfg.require.includes("seo_intent")) {
144
182
  const meta = regexes(cfg.metadata_patterns), canon = regexes(cfg.canonical_patterns), sd = regexes(cfg.structured_data_patterns);
145
- for (const f of pages) {
183
+ for (const f of briefPages) {
146
184
  const dir = f.split("/").slice(0, -1);
147
185
  const ctx = [f, ...all.filter((p) => /(?:^|\/)layout\.[cm]?[jt]sx?$/.test(p) && (p.split("/").slice(0, -1).join("/") === "" || dir.join("/").startsWith(p.split("/").slice(0, -1).join("/"))))].map((p) => String(readFile(p) ?? "")).join("\n");
148
186
  if (!meta.some((r) => r.test(ctx))) row("page_metadata_missing", `${f} has no title/description metadata (forge.yaml pages.metadata_patterns)`);
149
187
  if (!canon.some((r) => r.test(ctx))) row("page_canonical_missing", `${f} declares no canonical URL (pages.canonical_patterns)`);
150
188
  if (!sd.some((r) => r.test(ctx))) row("page_structured_data_missing", `${f} emits no structured data / JSON-LD (pages.structured_data_patterns)`);
151
189
  }
152
- if (!files.map(norm).some((f) => anyGlob(cfg.sitemap, f)) && blank(j.sitemap_justification)) row("page_sitemap_missing", `${pages.slice(0, 3).join(", ")} needs a sitemap entry (a change under ${cfg.sitemap.join(", ")}) or page_gate.sitemap_justification in the result (a generated sitemap)`);
190
+ if (!files.map(norm).some((f) => anyGlob(cfg.sitemap, f)) && blank(j.sitemap_justification)) row("page_sitemap_missing", `${briefPages.slice(0, 3).join(", ")} needs a sitemap entry (a change under ${cfg.sitemap.join(", ")}) or page_gate.sitemap_justification in the result (a generated sitemap)`);
153
191
  }
154
- const added = addedByFile(diff), forbid = regexes(cfg.forbid_patterns);
192
+ const addedLines = addedByFile(diff), forbid = regexes(cfg.forbid_patterns);
155
193
  for (const f of pages) {
156
- const lines = added[f] ?? [];
194
+ const lines = addedLines[f] ?? [];
157
195
  const hit = forbid.find((r) => lines.some((l) => r.test(l)));
158
196
  if (hit) row("page_forbidden_pattern", `${f} adds content matching /${hit.source}/ (null sample, raw JSON or dead-end state on a public page; forge.yaml pages.forbid_patterns)`);
159
197
  }
160
198
  if (tracked) {
161
199
  const routes = all.map(pageRouteOf).concat(all.map(routePathOf)).filter(Boolean).map(routeRe);
162
200
  const bad = new Set();
163
- for (const f of pages) for (const l of added[f] ?? []) for (const m of l.matchAll(LINK_RE)) {
201
+ for (const f of pages) for (const l of addedLines[f] ?? []) for (const m of l.matchAll(LINK_RE)) {
164
202
  const p = m[1].replace(/\/+$/, "") || "/";
165
203
  if (!routes.some((r) => r.test(p)) && !all.includes(`public${p}`) && !all.some((a) => a.endsWith(`/public${p}`))) bad.add(p);
166
204
  }
@@ -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 { parsePagesConfig, pageFiles, designOnlyFiles, contractBriefProblems, pageFailures, designSpecApproved, designHold, designLabelApproved } from "./pagegate.mjs";
5
+ import { parsePagesConfig, pageChange, pageFiles, designOnlyFiles, contractBriefProblems, pageFailures, designSpecApproved, designHold, designLabelApproved } from "./pagegate.mjs";
6
6
  import { pagePlanNote, domainChecksBlock } from "./prompts.mjs";
7
7
  import { pathDomains } from "./review-trigger.mjs";
8
8
  import { validateContract, precheck } from "./conformance.mjs";
@@ -113,3 +113,40 @@ describe("page gate exclusions (#5585)", () => {
113
113
  assert.deepEqual(f.map((x) => x.kind).sort(), ["page_design_missing", "page_visual_missing"]);
114
114
  });
115
115
  });
116
+
117
+ describe("copy-only edits to existing pages (#5648)", () => {
118
+ const docs = "web/src/app/(site)/docs/api/search/page.tsx", mig = "docs/migrations/search-to-serp/page.tsx", gen = "docs/api/generated/search/page.tsx";
119
+ const copyDiff = (f) => `+++ b/${f}\n- Searches Google and Bing.\n+ Searches the web.\n`;
120
+ const body = (f) => (f === docs || f === mig ? Array.from({ length: 40 }, (_, i) => `line ${i}`).join("\n") : "");
121
+ const files = [docs, mig, gen], diff = files.map(copyDiff).join("");
122
+ const kinds = (f) => f.map((x) => x.kind).sort();
123
+ it("pageChange: new, copy, rewrite, generated; unknown fails closed", () => {
124
+ const o = { added: [], diff, readFile: body };
125
+ assert.equal(pageChange(docs, o), "copy");
126
+ assert.equal(pageChange(gen, o), "generated");
127
+ assert.equal(pageChange(docs, { ...o, added: [docs] }), "new");
128
+ assert.equal(pageChange(docs, { ...o, added: null }), "new");
129
+ assert.equal(pageChange(docs, { ...o, diff: "" }), "new");
130
+ assert.equal(pageChange(docs, { ...o, diff: `+++ b/${docs}\n+<div className="x">hi</div>\n` }), "rewrite");
131
+ assert.equal(pageChange(docs, { ...o, threshold: 0.01 }), "rewrite");
132
+ });
133
+ it("copy-only modified pages need a visual check, not a design spec; generated pages need nothing", async () => {
134
+ const f = await pageFailures({ cfg, files, diff, readFile: body, tracked: files, added: [], designApproved: false });
135
+ assert.deepEqual(kinds(f), ["page_visual_missing"]);
136
+ assert.ok(!f.some((x) => x.detail.includes("generated")));
137
+ const shots = { page_gate: { screenshots: ["a-390.png", "a-1440.png"] } };
138
+ assert.deepEqual(await pageFailures({ cfg, files, diff, readFile: body, tracked: files, added: [], designApproved: false, result: shots }), []);
139
+ });
140
+ it("a new page, a markup rewrite, or unknown change info still needs the design spec", async () => {
141
+ assert.ok(kinds(await pageFailures({ cfg, files: [docs], diff, readFile: body, tracked: [docs], added: [docs], designApproved: false })).includes("page_design_missing"));
142
+ assert.ok(kinds(await pageFailures({ cfg, files: [docs], diff, readFile: body, tracked: [docs], designApproved: false })).includes("page_design_missing"));
143
+ const md = `+++ b/${docs}\n+<section className="grid">x</section>\n`;
144
+ assert.ok(kinds(await pageFailures({ cfg, files: [docs], diff: md, readFile: body, tracked: [docs], added: [], designApproved: false })).includes("page_design_missing"));
145
+ });
146
+ it("contract: on-base page deliverables skip the new-page briefs, generated ones too", () => {
147
+ const c = { deliverables: files.map((path) => ({ path })) };
148
+ assert.equal(contractBriefProblems(c, cfg).length, 1);
149
+ assert.deepEqual(contractBriefProblems(c, cfg, { baseFiles: [docs, mig, gen] }), []);
150
+ assert.deepEqual(contractBriefProblems({ deliverables: [{ path: gen }] }, cfg), []);
151
+ });
152
+ });
@@ -9,9 +9,14 @@
9
9
  * `phase_<id>_ms|_model_ms|_usd|_wait_<cause>_ms` keys for it and `unflattenPhases` reads them back.
10
10
  * #5349: `wait` is the phase's non-model time by cause (WAIT_CAUSES); what no typed wait explains is `command` (`sandbox` in
11
11
  * sandbox_start), so model_ms + the wait causes close to ms.
12
+ * #5649: `contract` (contract authoring and corrections) and `fix` (review/CI fix rounds) are their own phases; the batch summary
13
+ * compares each phase's median/p75 with the previous 7 days of batches (`comparePhases`, `readBaselineRows`).
12
14
  */
15
+ import { readdirSync, readFileSync, statSync } from "node:fs";
16
+ import { join } from "node:path";
17
+ import { homedir } from "node:os";
13
18
 
14
- export const LANE_PHASES = Object.freeze(["queue_wait", "sandbox_start", "deps_install", "validate", "plan", "implement", "precheck", "review", "ci_wait", "base_sync", "merge"]);
19
+ export const LANE_PHASES = Object.freeze(["queue_wait", "sandbox_start", "deps_install", "validate", "plan", "contract", "implement", "precheck", "review", "fix", "ci_wait", "base_sync", "merge"]);
15
20
  /** Why a lane was not in a model call: queued for a heavy slot, paused for host load, rate-limited, sandbox start, or running a command. */
16
21
  export const WAIT_CAUSES = Object.freeze(["heavy_queue", "host_load", "rate_limit", "sandbox", "command"]);
17
22
  const isNum = (x) => typeof x === "number" && Number.isFinite(x);
@@ -125,7 +130,7 @@ export function summarizePhases(list) {
125
130
  if (!by[id]) continue;
126
131
  const sum = by[id].reduce((a, b) => a + b, 0);
127
132
  total += sum;
128
- phases[id] = { n: by[id].length, p50: pct(by[id], 50), p90: pct(by[id], 90), sum };
133
+ phases[id] = { n: by[id].length, p50: pct(by[id], 50), p75: pct(by[id], 75), p90: pct(by[id], 90), sum };
129
134
  }
130
135
  let largest = null;
131
136
  for (const [id, v] of Object.entries(phases)) if (!largest || v.sum > phases[largest].sum) largest = id;
@@ -163,6 +168,64 @@ export function formatLedgerSummary(rows) {
163
168
  } catch { return "phases (wall time): n/a"; }
164
169
  }
165
170
 
171
+ const DAY_MS = 86400000, GROWTH = 0.25;
172
+ const merged = (r) => r?.outcome === "merged";
173
+
174
+ /**
175
+ * #5649: per phase the current median/p75 and the baseline's, with the median delta (ratio - 1, null without a baseline), plus
176
+ * the lane wall time (merged rows' `minutes`) the same way. `prevRows` null/empty (no prior batches) gives `prev: null` everywhere.
177
+ * Pure; rows without a ledger are skipped; a phase on one side only keeps the other side null.
178
+ */
179
+ export function comparePhases(curRows, prevRows) {
180
+ const side = (rows) => ({ s: summarizePhases((rows ?? []).map((r) => r?.phases)), wall: (rows ?? []).filter(merged).map((r) => r.minutes).filter(isNum).map((m) => m * 60000) });
181
+ const c = side(curRows), p = side(prevRows);
182
+ const stat = (v) => (v ? { median: v.p50, p75: v.p75, n: v.n } : null);
183
+ const delta = (cur, prev) => (cur && prev && prev.median > 0 ? cur.median / prev.median - 1 : null);
184
+ const phases = {};
185
+ for (const id of LANE_PHASES) {
186
+ const cur = stat(c.s.phases[id]), prev = stat(p.s.phases[id]);
187
+ if (cur || prev) phases[id] = { cur, prev, delta: delta(cur, prev) };
188
+ }
189
+ const w = (a) => (a.length ? { median: pct(a, 50), p75: pct(a, 75), n: a.length } : null);
190
+ const wall = { cur: w(c.wall), prev: w(p.wall) };
191
+ wall.delta = delta(wall.cur, wall.prev);
192
+ return { phases, wall, baseline: Boolean(p.s.n || p.wall.length) };
193
+ }
194
+
195
+ /**
196
+ * #5649: the lane rows of the batches under `root` (default `~/.forge/batches`) whose last progress is within the previous
197
+ * `days` days, excluding batch `excludeId`; the last row per issue of each batch. Read-only; null when it cannot be read.
198
+ */
199
+ export function readBaselineRows({ root = process.env.FORGEDOCK_BATCH_DIR || join(homedir(), ".forge", "batches"), excludeId = null, now = Date.now(), days = 7 } = {}) {
200
+ try {
201
+ const out = [];
202
+ for (const id of readdirSync(root)) {
203
+ if (id === excludeId) continue;
204
+ try {
205
+ const f = join(root, id, "log.jsonl");
206
+ if (now - statSync(f).mtimeMs > days * DAY_MS) continue;
207
+ const last = new Map();
208
+ for (const l of readFileSync(f, "utf8").split("\n")) { try { const r = l && JSON.parse(l); if (r && r.issue != null) last.set(r.issue, r); } catch { /* skip */ } }
209
+ out.push(...last.values());
210
+ } catch { /* a batch without a log */ }
211
+ }
212
+ return out;
213
+ } catch { return null; }
214
+ }
215
+
216
+ /** #5649: one line per phase, `<phase> median Xm (prev7d Ym) p75 Xm (prev7d Ym)`, `!` after a median that grew over 25%; then lane wall. */
217
+ export function formatPhaseComparison(curRows, prevRows) {
218
+ try {
219
+ const c = comparePhases(curRows, prevRows);
220
+ const m = (v, k) => (v ? min(v[k]) : "n/a");
221
+ const wm = (v, k) => (v ? `${v[k].toFixed(1)}m` : "n/a");
222
+ const line = (id, v, f) => `${id} median ${f(v.cur, "median")} (prev7d ${f(v.prev, "median")}) p75 ${f(v.cur, "p75")} (prev7d ${f(v.prev, "p75")})${v.delta != null && v.delta > GROWTH ? ` ! median +${Math.round(v.delta * 100)}%` : ""}`;
223
+ const lines = Object.entries(c.phases).map(([id, v]) => line(id, v, m));
224
+ if (c.wall.cur || c.wall.prev) lines.push(line("lane wall (merged)", { ...c.wall, cur: c.wall.cur && { median: c.wall.cur.median / 60000, p75: c.wall.cur.p75 / 60000 }, prev: c.wall.prev && { median: c.wall.prev.median / 60000, p75: c.wall.prev.p75 / 60000 } }, wm));
225
+ return lines.length ? lines : ["phases vs prev7d: n/a"];
226
+ } catch { return ["phases vs prev7d: n/a"]; }
227
+ }
228
+
166
229
  /** #5435: the local `sandbox_start` budget (issue: p50 <= 3 s on the bench corpus). */
167
230
  export const SANDBOX_START_P50_BUDGET_MS = 3000;
168
231
 
@@ -2,9 +2,12 @@
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 { mkdirSync, writeFileSync, utimesSync } from "node:fs";
6
+ import { tmpDir } from "../tests/_tmp.mjs";
7
+ import { join } from "node:path";
5
8
  import { phasesOf } from "./orchestrate.mjs";
6
9
  import { aggregate } from "../stats/aggregate.mjs";
7
- import { LANE_PHASES, createLedger, laneSum, withinWall, flattenPhases, unflattenPhases, summarizePhases, formatLedgerSummary, WAIT_CAUSES, summarizeWaits } from "./phaseledger.mjs";
10
+ import { LANE_PHASES, createLedger, laneSum, withinWall, flattenPhases, unflattenPhases, summarizePhases, formatLedgerSummary, WAIT_CAUSES, summarizeWaits, comparePhases, formatPhaseComparison, readBaselineRows } from "./phaseledger.mjs";
8
11
 
9
12
  const clock = () => { let t = 1000; const f = () => t; f.tick = (ms) => { t += ms; }; return f; };
10
13
 
@@ -53,7 +56,7 @@ describe("phase ledger (#4908)", () => {
53
56
  assert.match(line, /largest: implement/);
54
57
  assert.equal(formatLedgerSummary([{ issue: 1 }]), "phases (wall time): n/a");
55
58
  assert.equal(formatLedgerSummary(null), "phases (wall time): n/a");
56
- assert.equal(LANE_PHASES.length, 11);
59
+ assert.equal(LANE_PHASES.length, 13);
57
60
  });
58
61
 
59
62
  it("the batch row adds queue_wait to the lane ledger and stays null without one (#4908)", () => {
@@ -99,3 +102,68 @@ describe("phase ledger (#4908)", () => {
99
102
  assert.deepEqual(q.phases.plan.pct.heavy_queue, { p50: 2500, p90: 4000 });
100
103
  });
101
104
  });
105
+
106
+ describe("phase comparison vs previous 7 days (#5649)", () => {
107
+ const row = (phases, minutes, outcome = "merged", issue = 1) => ({ issue, outcome, minutes, phases });
108
+ const M = 60000;
109
+
110
+ it("contract and fix are ledger phases that keep the lane sum, rows without them still summarise", async () => {
111
+ const now = clock(), t0 = now(), L = createLedger(now);
112
+ now.tick(1000); L.enter("plan"); now.tick(2000);
113
+ await L.during("contract", async () => { now.tick(3000); });
114
+ now.tick(4000); L.enter("review"); now.tick(5000);
115
+ await L.during("fix", async () => { now.tick(6000); });
116
+ now.tick(7000); L.enter("merge"); now.tick(1000);
117
+ const p = L.snapshot();
118
+ assert.deepEqual(Object.keys(p), ["sandbox_start", "plan", "contract", "review", "fix", "merge"]);
119
+ assert.equal(p.contract.ms, 3000); assert.equal(p.fix.ms, 6000);
120
+ assert.ok(withinWall(p, now() - t0));
121
+ assert.equal(unflattenPhases(flattenPhases(p)).fix.ms, 6000);
122
+ const s = summarizePhases([p, { plan: { ms: 10 } }]);
123
+ assert.equal(s.n, 2); assert.equal(s.phases.plan.n, 2); assert.equal(s.phases.fix.n, 1);
124
+ });
125
+
126
+ it("summarizePhases carries p75", () => {
127
+ const s = summarizePhases([1, 2, 3, 4].map((x) => ({ plan: { ms: x * 1000 } })));
128
+ assert.equal(s.phases.plan.p75, 3000);
129
+ });
130
+
131
+ it("comparePhases: no prior batches, rows without ledgers, one-sided phases", () => {
132
+ const cur = [row({ plan: { ms: 4 * M }, fix: { ms: M } }, 20), row(undefined, 30, "merged", 2)];
133
+ const none = comparePhases(cur, null);
134
+ assert.equal(none.baseline, false);
135
+ assert.equal(none.phases.plan.prev, null); assert.equal(none.phases.plan.delta, null);
136
+ assert.deepEqual([none.wall.cur.median, none.wall.cur.p75], [25 * M, 30 * M]);
137
+ const c = comparePhases(cur, [row({ plan: { ms: 2 * M }, merge: { ms: M } }, 10), row({}, 0, "failed")]);
138
+ assert.equal(c.baseline, true);
139
+ assert.equal(c.phases.plan.delta, 1);
140
+ assert.equal(c.phases.fix.prev, null); assert.equal(c.phases.merge.cur, null);
141
+ assert.equal(c.wall.prev.median, 10 * M);
142
+ assert.doesNotThrow(() => comparePhases(undefined, undefined));
143
+ });
144
+
145
+ it("formatPhaseComparison prints the line form, marks >25% growth and the lane wall", () => {
146
+ const out = formatPhaseComparison([row({ plan: { ms: 3 * M }, merge: { ms: M } }, 20)], [row({ plan: { ms: 2 * M }, merge: { ms: M } }, 10)]);
147
+ assert.equal(out[0], "plan median 3.0m (prev7d 2.0m) p75 3.0m (prev7d 2.0m) ! median +50%");
148
+ assert.equal(out[1], "merge median 1.0m (prev7d 1.0m) p75 1.0m (prev7d 1.0m)");
149
+ assert.equal(out[2], "lane wall (merged) median 20.0m (prev7d 10.0m) p75 20.0m (prev7d 10.0m) ! median +100%");
150
+ assert.match(formatPhaseComparison([row({ plan: { ms: M } }, 5)], null)[0], /^plan median 1\.0m \(prev7d n\/a\)/);
151
+ assert.deepEqual(formatPhaseComparison([], []), ["phases vs prev7d: n/a"]);
152
+ });
153
+
154
+ it("readBaselineRows reads recent batches except the current one, last row per issue; null when unreadable", () => {
155
+ const root = tmpDir("bl-"), now = Date.now();
156
+ const mk = (id, rows, ageDays) => {
157
+ mkdirSync(join(root, id)); const f = join(root, id, "log.jsonl");
158
+ writeFileSync(f, rows.map((r) => JSON.stringify(r)).join("\n") + "\nnot json\n");
159
+ const t = (now - ageDays * 86400000) / 1000; utimesSync(f, t, t);
160
+ };
161
+ mk("a", [{ issue: 1, minutes: 1 }, { issue: 1, minutes: 2 }, { issue: 2, minutes: 3 }], 1);
162
+ mk("old", [{ issue: 9, minutes: 9 }], 10);
163
+ mk("cur", [{ issue: 5, minutes: 5 }], 0);
164
+ mkdirSync(join(root, "nolog"));
165
+ const rows = readBaselineRows({ root, excludeId: "cur", now });
166
+ assert.deepEqual(rows.map((r) => r.minutes).sort(), [2, 3]);
167
+ assert.equal(readBaselineRows({ root: join(root, "missing"), now }), null);
168
+ });
169
+ });
@@ -280,6 +280,7 @@ export function depInstallFailures({ results = [], changedFiles = [] } = {}) {
280
280
  if (r?.status !== "failed") continue;
281
281
  const label = `${r.eco ?? "dependencies"}${r.dir && r.dir !== "." ? ` in ${r.dir}` : ""}: ${r.reason ?? "install failed"}`;
282
282
  const rx = SRC_BY_ECO(r.eco);
283
+ if (r.code === "env.tool_missing") { block.push({ code: "env.tool_missing", kind: "dep_install", tool: r.eco ?? "python", detail: `dependency install stopped (${label}) (environment, not the change)` }); continue; } // #5651
283
284
  const hit = r.eco ? changedFiles.find((f) => rx.test(f) && underDir(r.dir, f) && (r.dir && r.dir !== "." ? true : !dirs.some((d) => underDir(d, f)))) : null;
284
285
  if (hit) block.push({ code: "env.tool_missing", kind: "dep_install", tool: r.eco, detail: `dependency install failed (${label}) for a package the changed file ${hit} imports (environment, not the change)` });
285
286
  else logged.push(`Dependency install failed, unrelated to the changed files: ${label}`);
@@ -313,9 +314,11 @@ export function declaredEnv(contract) {
313
314
 
314
315
  /** #5590: pytest's built-in fixtures, never host executables. */
315
316
  const PYTEST_FIXTURES = new Set(["caplog", "capsys", "capfd", "capsysbinary", "capfdbinary", "monkeypatch", "tmp_path", "tmp_path_factory", "tmpdir", "tmpdir_factory", "request", "recwarn", "pytestconfig", "mocker", "doctest_namespace", "cache", "testdir"]);
316
- /** #5590: `env` lists executables only; CamelCase (a class such as FakeRedis), snake_case and pytest-fixture names are libraries/fixtures that come from the lockfile. Pure. */
317
+ /** A file name (`depcache.test.mjs`, `conftest.py`) in `env` is a test file, not a host tool; versioned executables (`python3.12`) still pass. */
318
+ const SOURCE_FILE_RE = /\.(?:[cm]?[jt]sx?|py|rb|go|rs|java|kt|sh|bash|json|ya?ml|toml|md|txt|lock|cfg|ini)$/;
319
+ /** #5590: `env` lists executables only; CamelCase (a class such as FakeRedis), snake_case, pytest-fixture and source-file names are libraries/fixtures/tests, not host tools. Pure. */
317
320
  export function isExecutableName(t) {
318
- return !/[A-Z]/.test(t) && !t.includes("_") && !PYTEST_FIXTURES.has(t);
321
+ return !/[A-Z]/.test(t) && !t.includes("_") && !PYTEST_FIXTURES.has(t) && !SOURCE_FILE_RE.test(t);
319
322
  }
320
323
 
321
324
  /**
@@ -146,6 +146,11 @@ describe("#5447 unrunnable tests: install classification and the Tests summary",
146
146
  assert.deepEqual(depInstallFailures({ results, changedFiles: ["svc/a.py"] }).block, []);
147
147
  assert.equal(depInstallFailures({ results, changedFiles: ["top.py"] }).block.length, 1);
148
148
  });
149
+ it("#5651 a row coded env.tool_missing blocks without a changed-file match", () => {
150
+ const r = depInstallFailures({ results: [{ status: "failed", eco: "poetry", dir: ".", code: "env.tool_missing", reason: "no python satisfying the declared range" }], changedFiles: ["README.md"] });
151
+ assert.equal(r.block.length, 1);
152
+ assert.equal(r.block[0].code, "env.tool_missing");
153
+ });
149
154
  it("testRunSummary counts declared, ran, red->green and skipped(reason)", () => {
150
155
  const c = { validate: [{ id: "V1", command: "a" }, { id: "V2", command: "b" }], repro_test: { command: "c" } };
151
156
  const t = testRunSummary({ contract: c, failures: [{ kind: "validate_env", detail: "validate V2 (`b`) could not run" }], repro: { base: "FAILED", head: "RAN" } });
@@ -161,6 +166,8 @@ describe("#5447 declaredEnv", () => {
161
166
  assert.deepEqual(declaredEnv({}), []);
162
167
  // #5590: fixtures and libraries are not executables
163
168
  assert.deepEqual(declaredEnv({ test_plan: { env: ["pytest", "caplog", "FakeRedis", "tmp_path", "node", "psql"] } }), ["pytest", "node", "psql"]);
169
+ // a test file named in env is not a host tool (#5651 parked env.tool_missing on depcache.test.mjs)
170
+ assert.deepEqual(declaredEnv({ test_plan: [{ requirement: "R1", env: ["depcache.test.mjs", "conftest.py", "node", "python3.12"] }] }), ["node", "python3.12"]);
164
171
  });
165
172
  });
166
173