forgedock 1.61.1 → 1.62.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 (134) hide show
  1. package/bin/config-schema.mjs +10 -1
  2. package/bin/engine/outcome-codes.mjs +4 -0
  3. package/bin/engine-cli.mjs +160 -18
  4. package/bin/env/env.mjs +6 -4
  5. package/bin/forge-home-check.mjs +91 -0
  6. package/bin/forgedock.mjs +50 -7
  7. package/bin/gc.mjs +2 -0
  8. package/bin/hooks/pre-tool-use.mjs +4 -0
  9. package/bin/journey.mjs +55 -5
  10. package/bin/lean/admission.mjs +16 -5
  11. package/bin/lean/batch-health.mjs +55 -16
  12. package/bin/lean/batch-health.test.mjs +67 -1
  13. package/bin/lean/batch.mjs +8 -0
  14. package/bin/lean/batch.test.mjs +5 -0
  15. package/bin/lean/ceiling.mjs +20 -0
  16. package/bin/lean/ceiling.test.mjs +33 -2
  17. package/bin/lean/ci-gate.mjs +240 -0
  18. package/bin/lean/ci-gate.test.mjs +227 -0
  19. package/bin/lean/ci-precheck.mjs +178 -0
  20. package/bin/lean/ci-precheck.test.mjs +149 -0
  21. package/bin/lean/conformance.mjs +118 -20
  22. package/bin/lean/conformance.test.mjs +193 -3
  23. package/bin/lean/context.test.mjs +7 -6
  24. package/bin/lean/dag.mjs +128 -0
  25. package/bin/lean/dag.test.mjs +131 -0
  26. package/bin/lean/decisions.mjs +5 -4
  27. package/bin/lean/decisions.test.mjs +11 -0
  28. package/bin/lean/delguard.mjs +84 -0
  29. package/bin/lean/delguard.test.mjs +104 -0
  30. package/bin/lean/depcache.mjs +125 -17
  31. package/bin/lean/depcache.test.mjs +111 -0
  32. package/bin/lean/design-gate.mjs +5 -5
  33. package/bin/lean/design-gate.test.mjs +14 -0
  34. package/bin/lean/effects.mjs +81 -7
  35. package/bin/lean/execution.mjs +81 -15
  36. package/bin/lean/execution.test.mjs +156 -3
  37. package/bin/lean/forgedock-lane-workflow.test.mjs +35 -0
  38. package/bin/lean/guardgate.mjs +30 -7
  39. package/bin/lean/guardgate.test.mjs +44 -1
  40. package/bin/lean/guards.test.mjs +1 -1
  41. package/bin/lean/heavy.test.mjs +87 -0
  42. package/bin/lean/hotarea.mjs +73 -0
  43. package/bin/lean/hotarea.test.mjs +73 -0
  44. package/bin/lean/issuewatch-reconcile.mjs +20 -1
  45. package/bin/lean/issuewatch-reconcile.test.mjs +30 -0
  46. package/bin/lean/lanecheck.mjs +27 -3
  47. package/bin/lean/lanecheck.test.mjs +47 -5
  48. package/bin/lean/laneconfine.mjs +83 -0
  49. package/bin/lean/laneconfine.test.mjs +113 -0
  50. package/bin/lean/lean.mjs +398 -91
  51. package/bin/lean/lean.test.mjs +792 -26
  52. package/bin/lean/live-reconcile.mjs +169 -0
  53. package/bin/lean/live-reconcile.test.mjs +176 -0
  54. package/bin/lean/orchestrate-envhold.test.mjs +245 -0
  55. package/bin/lean/orchestrate-hostfallback.test.mjs +39 -0
  56. package/bin/lean/orchestrate.mjs +207 -17
  57. package/bin/lean/outcomeevidence.mjs +104 -0
  58. package/bin/lean/outcomeevidence.test.mjs +78 -0
  59. package/bin/lean/page-capture.mjs +68 -0
  60. package/bin/lean/page-capture.test.mjs +44 -0
  61. package/bin/lean/pagegate.mjs +46 -7
  62. package/bin/lean/pagegate.test.mjs +66 -1
  63. package/bin/lean/postdeploy-check.mjs +18 -4
  64. package/bin/lean/postdeploy-check.test.mjs +32 -1
  65. package/bin/lean/prefilter.mjs +36 -4
  66. package/bin/lean/prefilter.test.mjs +31 -1
  67. package/bin/lean/preflight.mjs +22 -0
  68. package/bin/lean/preflight.test.mjs +19 -1
  69. package/bin/lean/probe.mjs +18 -0
  70. package/bin/lean/probe.test.mjs +40 -0
  71. package/bin/lean/prompts.mjs +41 -4
  72. package/bin/lean/recovery.test.mjs +20 -0
  73. package/bin/lean/recurrence.mjs +133 -0
  74. package/bin/lean/recurrence.test.mjs +99 -0
  75. package/bin/lean/release-config.mjs +2 -1
  76. package/bin/lean/release-config.test.mjs +18 -0
  77. package/bin/lean/release-control.mjs +4 -2
  78. package/bin/lean/release-control.test.mjs +15 -0
  79. package/bin/lean/release-merge-hold.mjs +65 -0
  80. package/bin/lean/release-merge-hold.test.mjs +69 -0
  81. package/bin/lean/release-review.mjs +26 -9
  82. package/bin/lean/release-review.test.mjs +53 -0
  83. package/bin/lean/release-status.mjs +3 -1
  84. package/bin/lean/release-status.test.mjs +11 -0
  85. package/bin/lean/release.test.mjs +26 -1
  86. package/bin/lean/render.mjs +8 -7
  87. package/bin/lean/repro-output.test.mjs +45 -0
  88. package/bin/lean/routing.mjs +49 -0
  89. package/bin/lean/routing.test.mjs +54 -1
  90. package/bin/lean/run-issue-placement.test.mjs +30 -1
  91. package/bin/lean/sandbox-actions.mjs +121 -0
  92. package/bin/lean/sandbox-actions.test.mjs +94 -0
  93. package/bin/lean/sandbox-provider.contract.test.mjs +22 -1
  94. package/bin/lean/sandbox-remote.mjs +3 -1
  95. package/bin/lean/schedd-health.mjs +14 -2
  96. package/bin/lean/schedd-health.test.mjs +13 -0
  97. package/bin/lean/schedd.mjs +43 -17
  98. package/bin/lean/schedd.test.mjs +61 -1
  99. package/bin/lean/toolchain.mjs +16 -6
  100. package/bin/lean/toolplace.mjs +12 -0
  101. package/bin/lean/weakguard.mjs +105 -0
  102. package/bin/lean/weakguard.test.mjs +59 -0
  103. package/bin/lean/winspawn.mjs +61 -0
  104. package/bin/lean/winspawn.test.mjs +45 -0
  105. package/bin/lean/worktree.mjs +3 -1
  106. package/bin/lean/worktree.test.mjs +11 -0
  107. package/bin/pool/agent.mjs +215 -15
  108. package/bin/pool/cache-sweep.mjs +74 -0
  109. package/bin/pool/cli.mjs +11 -3
  110. package/bin/pool/docker.mjs +33 -2
  111. package/bin/pool/health.mjs +38 -0
  112. package/bin/pool/lane-tools.mjs +23 -4
  113. package/bin/pool/lane-tools.test.mjs +12 -1
  114. package/bin/pool/router.mjs +21 -3
  115. package/bin/runner.mjs +37 -0
  116. package/bin/splash-scene.mjs +356 -0
  117. package/bin/win-hide-children.mjs +114 -0
  118. package/commands/orchestrate.md +18 -27
  119. package/commands/review-pr-agents/infra.md +1 -0
  120. package/commands/review-pr-staging.md +2 -2
  121. package/docs/CONFIG.md +60 -3
  122. package/docs/OUTCOME-CODES.md +3 -0
  123. package/package.json +1 -1
  124. package/plugins/forgedock-splash/.claude-plugin/plugin.json +1 -1
  125. package/plugins/forgedock-splash/README.md +1 -1
  126. package/plugins/forgedock-splash/hooks/scene.ts +142 -8
  127. package/pool/README.md +6 -0
  128. package/pool/image/entrypoint.sh +1 -0
  129. package/scripts/acceptance-red-green.sh +8 -3
  130. package/scripts/acceptance-red-green.test.sh +8 -0
  131. package/scripts/check-spec-size.sh +3 -1
  132. package/scripts/gen-splash-scene.mjs +24 -0
  133. package/scripts/review-staging-pre.sh +8 -3
  134. package/scripts/review-staging-pre.test.sh +2 -0
@@ -47,6 +47,8 @@
47
47
  * (`placementText`); a remote lane whose frozen validate commands name a declared one ends before building (`contractHostNeeds`).
48
48
  * #4776: the body is read without its quoted material (comments, code, quotes, evidence sections) and the frozen
49
49
  * `repro_test` command counts like a validate command, so a quoted evidence query no longer pins a lane to the host.
50
+ * #5725: body prose pins only on a command signal (`sops -d`, an age key path, `needs: sops`); a bare mention of sops or
51
+ * credentials.yaml counts only in decisions, contract commands and block summaries (`placementNeeds`).
50
52
  */
51
53
  import { execFile } from "node:child_process";
52
54
  import { existsSync, mkdirSync, readFileSync, rmSync } from "node:fs";
@@ -62,6 +64,7 @@ import { OUTCOME_CODES } from "../engine/outcome-codes.mjs";
62
64
  import { validateLaneTools } from "../pool/lane-tools.mjs";
63
65
  import { resolveCredential, memoKeychain, defaultKeychain } from "./credentials.mjs";
64
66
  import { httpTransport, isActionsEndpoint, remoteProvider } from "./sandbox-remote.mjs";
67
+ import { actionsProvider, laneCap } from "./sandbox-actions.mjs";
65
68
  import { ADMISSION_DEFAULTS } from "./admission.mjs";
66
69
  import { classifyStep, heavyConfig, memAvailableMb } from "./heavy.mjs";
67
70
  import { detectPins } from "./toolchain.mjs";
@@ -70,7 +73,7 @@ import { parseRelayCommands } from "./relay.mjs";
70
73
  import { detectUsageLimit, parseSessionLimitResetEpochMs } from "../runner.mjs";
71
74
 
72
75
  export const EXECUTION_MODES = Object.freeze(["local", "remote", "hybrid"]);
73
- export const SANDBOX_PROVIDERS = Object.freeze(["local", "container", "remote", "pool"]);
76
+ export const SANDBOX_PROVIDERS = Object.freeze(["local", "container", "remote", "pool", "actions"]);
74
77
  const NAME_RE = /^[a-z][a-z0-9-]*$/;
75
78
  const CAPABILITY_RE = /^[a-z][a-z0-9_-]*$/;
76
79
  const safeRegExp = (src) => { try { return new RegExp(src, "i"); } catch { return null; } };
@@ -144,7 +147,13 @@ export function parseExecution(sec = {}) {
144
147
  // #5094: rotator.mjs reads its per-account quota state; #5205: off/none/false disables auto-detection, anything else is unset (auto)
145
148
  const rot = str(s.account_rotator).toLowerCase(), accountRotator = rot === "tokenbaton" ? "tokenbaton" : ["off", "none", "false"].includes(rot) ? "off" : null;
146
149
  const unreachableWindowMin = str(s.unreachable_window_min) !== "" && Number.isFinite(uw) && uw >= 0 ? uw : null; // unset: providerLanes defaults to 5
147
- return { mode, maxRemote, provider, image, secrets, budget, ...(hostFallback !== null ? { hostFallback } : {}), ...(hostCapabilities.length ? { hostCapabilities } : {}), ...(hostCapabilityPatterns.length ? { hostCapabilityPatterns } : {}), ...(endpoint ? { endpoint } : {}), ...(tokenEnv ? { tokenEnv } : {}), ...(tokenFile ? { tokenFile } : {}), ...(cacheStore ? { cacheStore } : {}), ...(allowActions ? { allowActions } : {}), ...(fallbackLocal ? { fallbackLocal } : {}), ...(capacityFallbackAfter !== null ? { capacityFallbackAfter } : {}), ...(heavy !== null ? { heavy } : {}), ...(unreachableWindowMin !== null ? { unreachableWindowMin } : {}), ...(Object.keys(relay).length ? { relay } : {}), ...(warmSandboxes ? { warmSandboxes } : {}), ...(accountRotator ? { accountRotator } : {}), ...(lt.tools.length ? { laneTools: lt.tools } : {}), ...(lt.errors.length ? { laneToolsErrors: lt.errors } : {}) };
150
+ // #5748: the `actions` provider's plan (concurrent-job limit), explicit job_limit, CI reserve and dispatcher identity
151
+ const jl = Number(str(s.job_limit)), cr = Number(str(s.ci_reserve));
152
+ const jobLimit = str(s.job_limit) !== "" && Number.isInteger(jl) && jl > 0 ? jl : null;
153
+ const ciReserve = str(s.ci_reserve) !== "" && Number.isInteger(cr) && cr >= 0 ? cr : null;
154
+ const plan = ["free", "pro", "team", "enterprise"].includes(str(s.plan).toLowerCase()) ? str(s.plan).toLowerCase() : null;
155
+ const dispatcher = /^[A-Za-z0-9][A-Za-z0-9-]*(\[bot\])?$/.test(str(s.dispatcher)) ? str(s.dispatcher) : null;
156
+ return { mode, maxRemote, provider, image, secrets, budget, ...(jobLimit ? { jobLimit } : {}), ...(ciReserve !== null ? { ciReserve } : {}), ...(plan ? { plan } : {}), ...(dispatcher ? { dispatcher } : {}), ...(hostFallback !== null ? { hostFallback } : {}), ...(hostCapabilities.length ? { hostCapabilities } : {}), ...(hostCapabilityPatterns.length ? { hostCapabilityPatterns } : {}), ...(endpoint ? { endpoint } : {}), ...(tokenEnv ? { tokenEnv } : {}), ...(tokenFile ? { tokenFile } : {}), ...(cacheStore ? { cacheStore } : {}), ...(allowActions ? { allowActions } : {}), ...(fallbackLocal ? { fallbackLocal } : {}), ...(capacityFallbackAfter !== null ? { capacityFallbackAfter } : {}), ...(heavy !== null ? { heavy } : {}), ...(unreachableWindowMin !== null ? { unreachableWindowMin } : {}), ...(Object.keys(relay).length ? { relay } : {}), ...(warmSandboxes ? { warmSandboxes } : {}), ...(accountRotator ? { accountRotator } : {}), ...(lt.tools.length ? { laneTools: lt.tools } : {}), ...(lt.errors.length ? { laneToolsErrors: lt.errors } : {}) };
148
157
  }
149
158
 
150
159
  const round1 = (x) => Math.round(x * 10) / 10;
@@ -213,27 +222,61 @@ export function openExecutionBudget({ budget = {}, file = executionBudgetFile(),
213
222
  };
214
223
  }
215
224
 
225
+ /**
226
+ * #5748: the product default. An `execution.mode` that forge.yaml does not set (`exec.modeExplicit` unset) on a public repo
227
+ * places lanes on GitHub-hosted runners (`provider: actions`, free minutes), capped at the plan's job limit minus a CI reserve.
228
+ * A private repo, an unknown visibility (`isPublic` not true: fails closed) and any explicit mode, `local` included, keep
229
+ * `exec` as is.
230
+ */
231
+ export function resolveDefaultExecution(exec, { isPublic = false } = {}) {
232
+ if (exec?.modeExplicit || isPublic !== true) return exec;
233
+ const base = exec ?? parseExecution({});
234
+ const cap = laneCap({ jobLimit: base.jobLimit ?? null, plan: base.plan ?? null, ciReserve: base.ciReserve });
235
+ return { ...base, mode: "remote", provider: "actions", maxRemote: cap, defaultedActions: true };
236
+ }
237
+
238
+ /** #5748: whether `repo` is public, from `gh api repos/<repo>`; any failure is false (private: today's default). */
239
+ export async function repoIsPublic({ repo, gh }) {
240
+ if (!repo || typeof gh !== "function") return false;
241
+ try { return JSON.parse(await gh(["api", `repos/${repo}`]))?.private === false; } catch { return false; }
242
+ }
243
+
216
244
  /** Where a `mode: remote` lane runs: remote only with `max_remote >= 1`. Hybrid is placed per lane by `placeLane` (#4256). */
217
245
  export function placement(exec) {
218
246
  return exec?.mode === "remote" && Number.isInteger(exec.maxRemote) && exec.maxRemote >= 1 ? "remote" : "local";
219
247
  }
220
248
 
221
- /** Host-only capabilities and the issue-text signals that mean a lane needs them (#4542). */
249
+ /** An explicit need written in prose (#5725): `needs: sops`, `needs sops`, `host capability: sops`. */
250
+ const DECLARE = String.raw`\b(?:needs?|host[ _-]capabilit(?:y|ies))\s*:?\s+`;
251
+
252
+ /**
253
+ * Host-only capabilities and the issue-text signals that mean a lane needs them (#4542). #5725: `command` is a signal that
254
+ * the lane itself uses the capability and counts everywhere, issue prose included; `mention` (only sops and ops_credentials)
255
+ * merely names it and counts only outside body prose (FORGE:DECISION comments, frozen contract commands, block summaries).
256
+ */
222
257
  const CAPABILITY_SIGNALS = Object.freeze({
223
- sops: /\.secrets\/[^\s`'")]*\.enc\.ya?ml|\bsops\b|\bage key\b|\.age\//i,
224
- prod_monitor: /\bssh\s+[\w.-]*-monitor\b|\b(?:ovh|netcup)-monitor\b|\bobs-psql\b|\bprod(?:uction)?[ _-]monitor|\bread[- ]only (?:prod(?:uction)? )?(?:prod(?:uction)? )?telemetry\b/i,
225
- ops_credentials: /\bcredentials\.yaml\b|\bops[ _-]credentials\b/i,
258
+ sops: {
259
+ command: new RegExp(String.raw`\bsops\s+(?:-d|--decrypt|-e|--encrypt|edit|exec-env|exec-file|updatekeys|-i|--in-place|rotate)\b|\.age\/[\w.-]+\.key\b|\.secrets\/[^\s\x60'")]*\.enc\.ya?ml|${DECLARE}sops\b`, "i"),
260
+ mention: /\.secrets\/[^\s`'")]*\.enc\.ya?ml|\bsops\b|\bage key\b|\.age\//i,
261
+ },
262
+ prod_monitor: { command: /\bssh\s+[\w.-]*-monitor\b|\b(?:ovh|netcup)-monitor\b|\bobs-psql\b|\bprod(?:uction)?[ _-]monitor|\bread[- ]only (?:prod(?:uction)? )?(?:prod(?:uction)? )?telemetry\b/i },
263
+ ops_credentials: {
264
+ command: /\b(?:cat|less|head|yq|jq|source|grep|sed)\s+\S*credentials\.yaml\b|\bops[ _-]credentials\b/i,
265
+ mention: /\bcredentials\.yaml\b|\bops[ _-]credentials\b/i,
266
+ },
226
267
  });
227
268
 
228
269
  /**
229
270
  * Host-only capabilities named by `text` (issue body, contract or a builder summary), zero LLM, sorted by name: the
230
271
  * built-in signals above, a declared name written out (`prod_monitor`, `prod monitor`) and `exec.hostCapabilityPatterns`.
272
+ * #5725: `prose: true` (issue body prose) counts only command signals, and a declared name only in declaration form
273
+ * (`needs: <name>`, `host capability: <name>`), so prose that merely names SOPS no longer pins a lane to the host.
231
274
  */
232
- export function detectNeeds(text, exec = null) {
275
+ export function detectNeeds(text, exec = null, { prose = false } = {}) {
233
276
  const t = String(text ?? "");
234
277
  const found = new Set();
235
- for (const [name, re] of Object.entries(CAPABILITY_SIGNALS)) if (re.test(t)) found.add(name);
236
- for (const name of exec?.hostCapabilities ?? []) if (new RegExp(`\\b${name.replace(/[_-]/g, "[ _-]")}\\b`, "i").test(t)) found.add(name);
278
+ for (const [name, { command, mention }] of Object.entries(CAPABILITY_SIGNALS)) if (command.test(t) || (!prose && mention?.test(t))) found.add(name);
279
+ for (const name of exec?.hostCapabilities ?? []) if (new RegExp(`${prose ? DECLARE : "\\b"}${name.replace(/[_-]/g, "[ _-]")}\\b`, "i").test(t)) found.add(name);
237
280
  for (const { name, pattern } of exec?.hostCapabilityPatterns ?? []) { const re = safeRegExp(pattern); if (re?.test(t)) found.add(name); }
238
281
  return [...found].sort();
239
282
  }
@@ -292,6 +335,11 @@ function contractCommands(contract) {
292
335
  * `<!-- FORGE:CONTRACT -->` comment. `comments` are gh comment objects (`{body}`) or strings; anything else is ignored.
293
336
  */
294
337
  export function placementText({ body = "", comments = [] } = {}) {
338
+ return [proseOf(body), ...commentSources(comments)].join("\n");
339
+ }
340
+
341
+ /** Every `<!-- FORGE:DECISION` comment body and the last frozen contract's validate and repro_test commands (#4785, #4776). */
342
+ function commentSources(comments) {
295
343
  const bodies = (Array.isArray(comments) ? comments : []).map((c) => String((typeof c === "string" ? c : c?.body) ?? "").trimStart());
296
344
  let validate = [];
297
345
  for (const b of bodies) {
@@ -299,7 +347,17 @@ export function placementText({ body = "", comments = [] } = {}) {
299
347
  const c = parseContractComment(b)?.contract;
300
348
  if (c && typeof c === "object") validate = contractCommands(c);
301
349
  }
302
- return [proseOf(body), ...bodies.filter((b) => b.startsWith("<!-- FORGE:DECISION")), ...validate].join("\n");
350
+ return [...bodies.filter((b) => b.startsWith("<!-- FORGE:DECISION")), ...validate];
351
+ }
352
+
353
+ /**
354
+ * Host-only capabilities an issue needs for placement (#5725), pure, sorted: body prose (`proseOf`) counts only command
355
+ * signals (`detectNeeds` `prose: true`), while FORGE:DECISION comments and the frozen contract's commands also count mentions.
356
+ */
357
+ export function placementNeeds({ body = "", comments = [] } = {}, exec = null) {
358
+ const found = new Set(detectNeeds(proseOf(body), exec, { prose: true }));
359
+ for (const n of detectNeeds(commentSources(comments).join("\n"), exec)) found.add(n);
360
+ return [...found].sort();
303
361
  }
304
362
 
305
363
  /** Declared host capabilities a contract's validate and repro_test commands name (#4785, #4776): `{caps, ids}`, both empty when none. */
@@ -407,7 +465,8 @@ export function hostHeadroom({ cfg = {}, heavyCfg = {}, host = { memAvailableMb,
407
465
  if (c.enabled === false) return { ok: true, detail: "" };
408
466
  const reasons = [];
409
467
  const need = c.min_free_mem_mb + h.step_mem_mb, mem = probe(host?.memAvailableMb);
410
- if (mem !== null && mem < need) reasons.push(`mem ${mem} MB < ${need} MB`);
468
+ const ramping = mem === null ? 0 : Math.max(0, probe(() => host?.rampingMb?.(c.ramp_s)) ?? 0); // #5845: lanes admitted within the ramp window have not grown yet
469
+ if (mem !== null && mem - ramping < need) reasons.push(ramping > 0 ? `mem ${mem} MB − ramping ${ramping} MB < ${need} MB` : `mem ${mem} MB < ${need} MB`);
411
470
  const maxLoad = typeof c.max_load_per_core === "number" && Number.isFinite(c.max_load_per_core) ? c.max_load_per_core : null;
412
471
  if (maxLoad !== null) {
413
472
  const load = probe(host?.loadAvg1), cores = probe(host?.cores);
@@ -570,6 +629,7 @@ export function poolRouterConfig({ env = process.env, path = env.COMPUTESHARE_CO
570
629
  export function providerByName(name, opts) {
571
630
  if (name === "local") return localProvider(opts);
572
631
  if (name === "container") return containerProvider(opts);
632
+ if (name === "actions") return actionsProvider({ batch: opts.batch, repo: opts.repo, settings: opts.exec ?? {}, env: opts?.env ?? process.env, ...(opts?.transport ? { transport: opts.transport } : {}), ...(opts?.actionsApi ? { api: opts.actionsApi } : {}), ...(opts?.now ? { now: opts.now } : {}) });
573
633
  if (name === "remote" || name === "pool") {
574
634
  const env = opts?.env ?? process.env;
575
635
  const exec = opts?.exec ?? {};
@@ -650,6 +710,13 @@ export function providerLanes({ provider, laneArgs, ledgerFor, env = process.env
650
710
  if (ok) { try { led?.release("sandbox", h.id); led?.remove(); } catch { /* the reaper retries */ } }
651
711
  return ok;
652
712
  };
713
+ // #5808: the result is handed back at once; the teardown starts now and the dispatcher's postRun hook waits for it (the batch
714
+ // never ends before it, the ledger still holds the sandbox until it is released), so it is off the slot's path.
715
+ const tearAfter = (led, h, r) => {
716
+ const torn = tear(led, h), prev = r && typeof r === "object" && typeof r.postRun === "function" ? r.postRun : null;
717
+ const postRun = async () => { await torn; if (prev) await prev(); };
718
+ return (r && typeof r === "object") ? { ...r, postRun } : r;
719
+ };
653
720
  // #4672: a transport failure (router restart, refused/reset connection, 502/503/504) is retried with backoff until the lane has
654
721
  // waited `unreachableWindowMs` in a row without one successful poll; then it ends sandbox.unreachable with the sandbox kept.
655
722
  const guard = (st) => async (fn) => {
@@ -742,8 +809,8 @@ export function providerLanes({ provider, laneArgs, ledgerFor, env = process.env
742
809
  if (started && e?.unreachable) return withUsage(unreachable(h, e), h); // #4672: no tear, the ledger keeps it
743
810
  r = started ? settleClone({ terminalReason: "engine-error", detail: `sandbox ${base.id}: ${errText(e)}` }, base.id) : startFailed(base.id, e);
744
811
  }
745
- await tear(led, h); // every path, after the result is in (tear never throws)
746
- return started ? withUsage(r, h) : r; // a sandbox that never started used nothing
812
+ const torn = tearAfter(led, h, r); // every path, after the result is in (tear never throws); #5808: not awaited here
813
+ return started ? withUsage(torn, h) : torn; // a sandbox that never started used nothing
747
814
  },
748
815
  adopt: (n, rec, ctx = {}) => adoptSaved(n, rec, ctx),
749
816
  };
@@ -771,8 +838,7 @@ export function providerLanes({ provider, laneArgs, ledgerFor, env = process.env
771
838
  if (e?.unreachable) return withUsage(unreachable(h, e), h); // #4672: same tolerance; no tear, left for the next adopt
772
839
  r = { terminalReason: "engine-error", detail: `sandbox ${h.id}: ${errText(e)}` };
773
840
  }
774
- await tear(led, h);
775
- return withUsage(r, h);
841
+ return withUsage(tearAfter(led, h, r), h); // #5808: teardown runs after the result is handed back
776
842
  }
777
843
  // A leftover ledger entry of this lane's sandbox: its result if it can still be had, else null (torn down by the caller).
778
844
  async function adoptLeft(n, left, ctx) {
@@ -7,7 +7,8 @@ import { mkdirSync, writeFileSync, existsSync, readFileSync } from "node:fs";
7
7
  import { join } from "node:path";
8
8
  import { tmpDir } from "../tests/_tmp.mjs";
9
9
  import { renderContract } from "./render.mjs";
10
- import { parseExecution, hostFallbackAllowed, SANDBOX_PROVIDERS, detectNeeds, hostCapabilityBlock, placementText, contractHostNeeds, placement, placeLane, validationWeight, hostHeadroom, scopedEnv, providerLanes, remoteHoldId, usageLimitInTail, isTransportError, isCloneFailure, containerProvider, providerByName, openExecutionBudget, poolCredential, remoteTransportFor } from "./execution.mjs";
10
+ import { parseExecution, hostFallbackAllowed, SANDBOX_PROVIDERS, detectNeeds, hostCapabilityBlock, placementText, contractHostNeeds, placement, placeLane, validationWeight, hostHeadroom, scopedEnv, providerLanes, remoteHoldId, usageLimitInTail, isTransportError, isCloneFailure, containerProvider, providerByName, openExecutionBudget, poolCredential, remoteTransportFor, resolveDefaultExecution, repoIsPublic } from "./execution.mjs";
11
+ import * as executionModule from "./execution.mjs";
11
12
  import { remoteProvider } from "./sandbox-remote.mjs";
12
13
  import { makeLedger, countLiveLanes } from "./ledger.mjs";
13
14
  import { openBatch } from "./batch.mjs";
@@ -160,6 +161,49 @@ describe("providerLanes: an unreachable provider is retried, then deferred witho
160
161
  });
161
162
  });
162
163
 
164
+ describe("providerLanes: runOne returns the result before sandbox teardown (#5808)", () => {
165
+ const setup = (usage) => {
166
+ const root = tmpDir("exec-5808-");
167
+ const ledgerFor = ledgerIn(root);
168
+ const prov = fakeProvider({ finish: () => ({ terminalReason: "merged", pr: 9 }), ...(usage ? { usage } : {}) });
169
+ let release;
170
+ const gate = new Promise((res) => { release = res; });
171
+ const origTeardown = prov.teardown;
172
+ prov.teardown = async (h) => { await gate; return origTeardown(h); };
173
+ const lanes = providerLanes({ provider: prov, laneArgs: () => [], ledgerFor, pollMs: 1, now: () => 1000 });
174
+ return { prov, lanes, release, led: ledgerFor(7) };
175
+ };
176
+ it("runOne resolves while teardown is pending; postRun finishes it and releases the ledger", async () => {
177
+ const { prov, lanes, release, led } = setup();
178
+ const r = await lanes.runOne(7, "staging"); // resolves although provider.teardown is still gated
179
+ assert.equal(r.terminalReason, "merged");
180
+ assert.equal(typeof r.postRun, "function");
181
+ assert.deepEqual(led.entries("sandbox").map((e) => e.value), ["fake-7"]); // still listed until torn down
182
+ release();
183
+ await r.postRun();
184
+ assert.ok(prov.calls.some((c) => c[0] === "teardown" && c[1] === "fake-7"));
185
+ assert.equal(led.read(), null);
186
+ });
187
+ it("a failed teardown keeps the entry for the reaper after postRun", async () => {
188
+ const root = tmpDir("exec-5808b-");
189
+ const ledgerFor = ledgerIn(root);
190
+ const prov = fakeProvider({ finish: () => ({ terminalReason: "merged" }), teardownOk: false });
191
+ const r = await providerLanes({ provider: prov, laneArgs: () => [], ledgerFor, pollMs: 1 }).runOne(7, null);
192
+ await r.postRun();
193
+ assert.deepEqual(ledgerFor(7).entries("sandbox").map((e) => e.value), ["fake-7"]);
194
+ });
195
+ it("an unreachable provider still ends without a teardown", async () => {
196
+ const root = tmpDir("exec-5808c-");
197
+ const ledgerFor = ledgerIn(root);
198
+ const prov = fakeProvider();
199
+ prov.fetchResult = async () => { throw Object.assign(new Error("ECONNRESET"), { code: "ECONNRESET" }); };
200
+ prov.status = async () => { throw Object.assign(new Error("ECONNRESET"), { code: "ECONNRESET" }); };
201
+ const r = await providerLanes({ provider: prov, laneArgs: () => [], ledgerFor, pollMs: 1, unreachableWindowMs: 0, sleep: async () => {} }).runOne(7, null);
202
+ assert.equal(prov.calls.some((c) => c[0] === "teardown"), false);
203
+ assert.equal(r.postRun, undefined);
204
+ });
205
+ });
206
+
163
207
  describe("providerLanes: sandbox ledger and teardown on every exit path (#4253)", () => {
164
208
  const run = async ({ finish, startThrows, teardownOk, pollMs = 1 } = {}) => {
165
209
  const root = tmpDir("exec-ledger-");
@@ -170,7 +214,8 @@ describe("providerLanes: sandbox ledger and teardown on every exit path (#4253)"
170
214
  sleep: async () => { if (++ticks === 2 && !finish) { prov.results[7] = { terminalReason: "merged", pr: 9 }; prov.live.delete(7); } } });
171
215
  const started = [];
172
216
  const r = await lanes.runOne(7, "staging", { onStart: (i) => started.push(i) });
173
- return { r, prov, started, led: ledgerFor(7) };
217
+ await r.postRun?.(); // #5808: the teardown runs after the result is handed back
218
+ return { r: Object.fromEntries(Object.entries(r).filter(([k]) => k !== "postRun")), prov, started, led: ledgerFor(7) };
174
219
  };
175
220
 
176
221
  it("success: registered before start, result reaches the batch, torn down and released", async () => {
@@ -225,7 +270,8 @@ describe("providerLanes: sandbox ledger and teardown on every exit path (#4253)"
225
270
  const prov = fakeProvider();
226
271
  prov.live.add(7);
227
272
  const lanes = providerLanes({ provider: prov, laneArgs: () => [], ledgerFor, pollMs: 1, sleep: async () => { prov.results[7] = { terminalReason: "merged", pr: 3 }; prov.live.delete(7); } });
228
- const r = await lanes.adopt(7, { pid: undefined, remote: true, handle: { provider: "fake", id: "fake-7", issue: 7 } });
273
+ const { postRun, ...r } = await lanes.adopt(7, { pid: undefined, remote: true, handle: { provider: "fake", id: "fake-7", issue: 7 } });
274
+ await postRun(); // #5808
229
275
  assert.deepEqual(r, { terminalReason: "merged", pr: 3, sandbox: { provider: "fake", id: "fake-7", minutes: 0, cost_usd: 0 } });
230
276
  assert.ok(prov.calls.some((c) => c[0] === "teardown"));
231
277
  assert.equal(ledgerFor(7).read(), null);
@@ -894,6 +940,62 @@ describe("host capabilities in placement (#4542)", () => {
894
940
  assert.deepEqual(detectNeeds(t, exec), ["promtool"]);
895
941
  });
896
942
 
943
+ // Namespace lookup (#5725): the file still loads on a base without this export, so the repro fails as an assertion, not a link error.
944
+ const placementNeeds = (...a) => executionModule.placementNeeds(...a);
945
+ const declSops = () => parseExecution({ mode: "remote", max_remote: 2, host_capabilities: "sops" });
946
+ const frozen = (cmd) => "<!-- FORGE:CONTRACT -->\n<!-- FORGE:PLAN -->\n" + renderContract({ requirements: [], deliverables: [], validate: [{ id: "V1", command: cmd }] }, "abcdef123456");
947
+
948
+ it("#5725 T1: prose that only names the secrets tool does not pin", () => {
949
+ for (const body of ["add X to SOPS per devdocs/SOPS.md", "the key lives in SOPS", "rotate the age key"]) {
950
+ for (const exec of [null, declSops()]) {
951
+ assert.deepEqual(placementNeeds({ body }, exec), [], body);
952
+ assert.deepEqual(detectNeeds(body, exec, { prose: true }), [], body);
953
+ }
954
+ assert.deepEqual(detectNeeds(placementText({ body }), declSops()), ["sops"], `${body}: pinned before #5725`);
955
+ }
956
+ });
957
+
958
+ it("#5725 T2: commands, key paths and declarations in prose still pin", () => {
959
+ for (const body of ["run sops -d .secrets/prod.enc.yaml first", "sops exec-env .secrets/x.enc.yaml ./run", "load ~/.age/prod.key",
960
+ "needs: sops", "host capability: sops", "Edit .secrets/prod.enc.yaml"]) {
961
+ assert.deepEqual(placementNeeds({ body }), ["sops"], body);
962
+ assert.deepEqual(placementNeeds({ body }, declSops()), ["sops"], body);
963
+ }
964
+ });
965
+
966
+ it("#5725 T3: decisions and frozen contract commands still pin on a bare mention", () => {
967
+ assert.deepEqual(placementNeeds({ body: "x", comments: [{ body: "<!-- FORGE:DECISION -->\nthe owner keeps this in sops" }] }), ["sops"]);
968
+ assert.deepEqual(placementNeeds({ body: "x", comments: [{ body: frozen("sops -d x.enc.yaml") }] }), ["sops"]);
969
+ assert.deepEqual(placementNeeds({ body: "the key lives in SOPS", comments: [{ body: "just chatter about sops" }] }), []);
970
+ assert.deepEqual(contractHostNeeds({ validate: [{ id: "V1", command: "sops -d x.enc.yaml" }] }, { hostCapabilities: ["sops"] }), { caps: ["sops"], ids: ["V1"] });
971
+ });
972
+
973
+ it("#5725 T4: credentials.yaml named in prose does not pin", () => {
974
+ assert.deepEqual(placementNeeds({ body: "the owner adds the token to credentials.yaml" }), []);
975
+ assert.deepEqual(placementNeeds({ body: "cat ~/ops/credentials.yaml" }), ["ops_credentials"]);
976
+ assert.deepEqual(placementNeeds({ body: "needs ops_credentials" }), ["ops_credentials"]);
977
+ assert.deepEqual(placementNeeds({ body: "x", comments: [{ body: "<!-- FORGE:DECISION -->\nread the token from credentials.yaml" }] }), ["ops_credentials"]);
978
+ });
979
+
980
+ it("#5725 T5: AlterLab#40984 body places remote under mode remote", () => {
981
+ const body = ["## Problem", "The DataImpulse balance is never estimated and the poller is dormant.", "",
982
+ "The login is read from `.secrets/prod.enc.yaml` at deploy time.", "", "## Fix", "Wire a balance estimate and alert when the poller stays dormant.", "",
983
+ "## Owner steps", "- add `proxy.dataimpulse_api_login` to SOPS per `devdocs/SOPS.md`", "",
984
+ "<!-- FORGE:STATE\n{\"placement\":{\"where\":\"local\",\"reason\":\"host capability: sops\"}}\n-->"].join("\n");
985
+ const exec = declSops(), view = { body, comments: [] };
986
+ assert.deepEqual(detectNeeds(placementText(view), exec), ["sops"]); // pinned before #5725
987
+ const needs = placementNeeds(view, exec);
988
+ assert.deepEqual(needs, []);
989
+ assert.equal(placeLane({ exec, needs }).where, "remote");
990
+ assert.equal(placeLane({ exec, needs: ["sops"] }).where, "local");
991
+ });
992
+
993
+ it("#5725 T6: block-summary recovery and prod monitor signal unchanged", () => {
994
+ assert.deepEqual(hostCapabilityBlock("this lane has no sops key", { hostCapabilities: ["sops"] }), ["sops"]);
995
+ assert.deepEqual(placementNeeds({ body: "needs the prod monitor" }), ["prod_monitor"]);
996
+ assert.deepEqual(placementNeeds({ body: "run ssh ovh-monitor obs-psql for counts" }), ["prod_monitor"]);
997
+ });
998
+
897
999
  it("#4785/#5423 orchestrate: a remote lane that ends env.tool_missing is retried remotely once (sandbox provisioned), see recovery.test.mjs for the host fallback", async () => {
898
1000
  const calls = [];
899
1001
  const rows = await orchestrate({ issues: [5], parallel: 2, recovery: { maxAttempts: 1 }, readBody: async () => "",
@@ -907,6 +1009,21 @@ describe("host capabilities in placement (#4542)", () => {
907
1009
  assert.equal(rows.find((r) => r.issue === 5).outcome, "merged");
908
1010
  });
909
1011
 
1012
+ it("#5727 placeOf does not retry a recipe-less tool miss remotely", async () => {
1013
+ for (const toolNoRecipe of [true, false]) {
1014
+ const calls = [];
1015
+ await orchestrate({ issues: [5], parallel: 2, recovery: { maxAttempts: 1 }, readBody: async () => "",
1016
+ remote: { max: 2, isRemote: () => true, place: () => ({ where: "remote", reason: "mode remote" }), admit: () => ({ ok: true }), onBudget: "stop", costPerMinute: 0 },
1017
+ runOne: async (n, _l, ctx = {}) => {
1018
+ calls.push({ placement: ctx.placement?.where, reason: ctx.placement?.reason });
1019
+ return ctx.recover ? { terminalReason: "merged", pr: 9 } : { terminalReason: "needs-human", code: "env.tool_missing", detail: "Remote sandbox lacks forgedock, and no lane_tools recipe exists for it.", placement: { where: "remote" }, ...(toolNoRecipe ? { toolNoRecipe } : {}) };
1020
+ } });
1021
+ assert.equal(calls.length, 2);
1022
+ if (toolNoRecipe) { assert.equal(calls[1].placement, "local"); assert.notEqual(calls[1].reason, "retry remotely after sandbox provisioning"); }
1023
+ else assert.equal(calls[1].reason, "retry remotely after sandbox provisioning");
1024
+ }
1025
+ });
1026
+
910
1027
  it("#5371 orchestrate: a remote env.validate_placement or mechanical failure is requeued on a different placement", async () => {
911
1028
  for (const code of ["env.validate_placement", "env.repro_unrunnable"]) {
912
1029
  const calls = [];
@@ -1204,3 +1321,39 @@ describe("providerLanes: a halted batch keeps its sandbox for adopt (#5669)", ()
1204
1321
  assert.equal(r.terminalReason, "merged");
1205
1322
  });
1206
1323
  });
1324
+
1325
+ describe("public-repo default placement (#5748)", () => {
1326
+ it("actions is a known provider; plan, job_limit, ci_reserve and dispatcher parse", () => {
1327
+ assert.ok(SANDBOX_PROVIDERS.includes("actions"));
1328
+ assert.equal(providerByName("actions", { batch: { id: "b" }, repo: "o/r", exec: {}, actionsApi: async () => null }).name, "actions");
1329
+ const e = parseExecution({ plan: "Team", job_limit: "30", ci_reserve: "4", dispatcher: "forgedock[bot]" });
1330
+ assert.deepEqual([e.plan, e.jobLimit, e.ciReserve, e.dispatcher], ["team", 30, 4, "forgedock[bot]"]);
1331
+ for (const k of ["jobLimit", "ciReserve", "plan", "dispatcher"]) assert.ok(!(k in parseExecution({ plan: "x", job_limit: "0", ci_reserve: "-1", dispatcher: "a b" })));
1332
+ });
1333
+ it("public + mode unset -> actions, capped at job limit minus reserve; private or unknown visibility unchanged", () => {
1334
+ const d = resolveDefaultExecution(undefined, { isPublic: true });
1335
+ assert.equal(d.provider, "actions"); assert.equal(placement(d), "remote"); assert.equal(d.maxRemote, 15);
1336
+ assert.equal(placeLane({ exec: d }).where, "remote");
1337
+ assert.equal(resolveDefaultExecution(parseExecution({ plan: "team", ci_reserve: "10" }), { isPublic: true }).maxRemote, 50);
1338
+ const base = parseExecution({ image: "i:1" });
1339
+ assert.equal(resolveDefaultExecution(base, { isPublic: false }), base);
1340
+ assert.equal(resolveDefaultExecution(base, {}), base);
1341
+ assert.equal(resolveDefaultExecution(undefined, { isPublic: false }), undefined);
1342
+ });
1343
+ it("an explicit mode always wins, local included", () => {
1344
+ for (const mode of ["local", "remote", "hybrid"]) {
1345
+ const e = { ...parseExecution({ mode, max_remote: "2", provider: "pool" }), modeExplicit: true };
1346
+ assert.equal(resolveDefaultExecution(e, { isPublic: true }), e);
1347
+ }
1348
+ });
1349
+ it("a defaulted lane that needs a host capability still places local", () => {
1350
+ assert.equal(placeLane({ exec: resolveDefaultExecution(undefined, { isPublic: true }), needs: ["sops"] }).where, "local");
1351
+ });
1352
+ it("repoIsPublic reads private:false and fails closed", async () => {
1353
+ assert.equal(await repoIsPublic({ repo: "o/r", gh: async () => JSON.stringify({ private: false }) }), true);
1354
+ assert.equal(await repoIsPublic({ repo: "o/r", gh: async () => JSON.stringify({ private: true }) }), false);
1355
+ assert.equal(await repoIsPublic({ repo: "o/r", gh: async () => { throw new Error("timeout"); } }), false);
1356
+ assert.equal(await repoIsPublic({ repo: "o/r", gh: async () => "not json" }), false);
1357
+ assert.equal(await repoIsPublic({ repo: null, gh: async () => "{}" }), false);
1358
+ });
1359
+ });
@@ -0,0 +1,35 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ // #5748: the lane workflow's security shape, checked as text (zero LLM).
4
+ import { describe, it } from "node:test";
5
+ import assert from "node:assert/strict";
6
+ import { readFileSync } from "node:fs";
7
+ import { fileURLToPath } from "node:url";
8
+
9
+ const text = readFileSync(fileURLToPath(new URL("../../.github/workflows/forgedock-lane.yml", import.meta.url)), "utf8");
10
+ const code = text.split("\n").filter((l) => !l.trim().startsWith("#")).join("\n");
11
+
12
+ describe("forgedock-lane.yml (#5748)", () => {
13
+ it("triggers on workflow_dispatch only, never pull_request or pull_request_target", () => {
14
+ const on = /^on:\n((?:[ ]+.*\n|\n)+)/m.exec(code)[1];
15
+ assert.deepEqual([...on.matchAll(/^ ([a-z_]+):/gm)].map((m) => m[1]), ["workflow_dispatch"]);
16
+ assert.doesNotMatch(code, /pull_request/);
17
+ });
18
+ it("has least-privilege permissions, an environment holding the credential, and a job limit under 6 h", () => {
19
+ assert.match(code, /^permissions:\n contents: write\n issues: write\n pull-requests: write\n/m);
20
+ assert.doesNotMatch(code, /permissions:[\s\S]*(actions|packages|id-token|security-events): write/);
21
+ assert.match(code, /environment: forgedock-lane/);
22
+ assert.match(code, /secrets\.CLAUDE_CODE_OAUTH_TOKEN/);
23
+ const m = /timeout-minutes: (\d+)/.exec(code); assert.ok(m && Number(m[1]) < 360);
24
+ assert.match(code, /timeout 345m forgedock run-issue/);
25
+ assert.doesNotMatch(code, /run-issue[^\n]*\|\| true/); // the cap must not be swallowed: rc 124 posts the retryable deferral
26
+ assert.match(code, /\[ "\$rc" = 124 \][\s\S]*sandbox\.actions_timeout/);
27
+ });
28
+ it("keeps inputs out of shell text, pushes to feat/* only and never echoes env or secrets", () => {
29
+ assert.doesNotMatch(code, /run:[^\n]*\$\{\{ *inputs\./);
30
+ assert.match(code, /refs\/heads\/feat\/\*/);
31
+ assert.doesNotMatch(code, /\b(printenv|set -x)\b|\benv\s*(\||$)|echo[^\n]*(secrets\.|TOKEN)/m);
32
+ assert.match(code, /run-issue[^\n]*> \/dev\/null 2>&1/);
33
+ assert.match(code, /run-name: forgedock-lane \$\{\{ inputs\.lane_id \}\}/);
34
+ });
35
+ });
@@ -13,6 +13,7 @@ import { dirname, extname, join } from "node:path";
13
13
  import { OUTCOME_CODES } from "../engine/outcome-codes.mjs";
14
14
  import { collectGuards, guardsIndexPath, readIndex, writeIndex } from "./guards.mjs";
15
15
  import { isTestPath } from "./enumerating.mjs";
16
+ import { isWeakGuardTest } from "./weakguard.mjs";
16
17
 
17
18
  export const GUARD_CAP_MS = 120000;
18
19
  export const INDEX_MAX_AGE_MS = 6 * 3600000;
@@ -178,6 +179,7 @@ export async function runGuards({ selected, mergeBase, contract, guardCommand, g
178
179
  const materialize = async (j) => {
179
180
  let body;
180
181
  try { body = await git(["show", `${mergeBase}:${j.path}`]); } catch { skipped.push(`#${j.guard.issue} ${j.path}: not on base`); return false; }
182
+ j.weak = isWeakGuardTest(body, j.path); // #5752: only asserts literals exist in file text: a review note, never a park
181
183
  const abs = join(cwd, j.copy);
182
184
  try { fs.mkdirSync(dirname(abs), { recursive: true }); fs.writeFileSync(abs, body); made.push(abs); return true; } catch (e) { skipped.push(`#${j.guard.issue} ${j.path}: ${String(e?.message ?? e).slice(0, 80)}`); return false; }
183
185
  };
@@ -203,7 +205,7 @@ export async function runGuards({ selected, mergeBase, contract, guardCommand, g
203
205
  try { r = await runCommand({ command, cwd, timeoutMs: capMs - (now() - t0), env }); } catch (e) { r = { rc: 127, output: String(e?.message ?? e) }; }
204
206
  if (r?.rc !== 0) return;
205
207
  batches++;
206
- for (const j of ready) { settled.add(j); runs.push({ issue: j.guard.issue, why: j.guard.why, test: j.path, command, rc: 0, output: String(r?.output ?? ""), failed: null }); }
208
+ for (const j of ready) { settled.add(j); runs.push({ issue: j.guard.issue, why: j.guard.why, test: j.path, command, rc: 0, output: String(r?.output ?? ""), failed: null, weak: Boolean(j.weak) }); }
207
209
  }));
208
210
  return settled;
209
211
  };
@@ -226,7 +228,7 @@ export async function runGuards({ selected, mergeBase, contract, guardCommand, g
226
228
  if (v.skip) { skipped.push(`guard #${j.guard.issue} ${j.path}: ${v.skip}`); continue; }
227
229
  if (v.fresh) failed = v.fresh;
228
230
  }
229
- runs.push({ issue: j.guard.issue, why: j.guard.why, test: j.path, command: j.command, rc, output, failed });
231
+ runs.push({ issue: j.guard.issue, why: j.guard.why, test: j.path, command: j.command, rc, output, failed, weak: Boolean(j.weak) });
230
232
  }
231
233
  };
232
234
  await Promise.all(Array.from({ length: Math.max(1, Math.min(parallelism, queue.length)) }, work));
@@ -245,19 +247,40 @@ export async function runGuards({ selected, mergeBase, contract, guardCommand, g
245
247
  /** The only override of a guard_broken failure, named for the builder (#4883); leads the detail so the resume prompt's truncation keeps it. */
246
248
  const supersedesHint = (guard) => `If this change intentionally changes the guarded behaviour (e.g. adding a code to an enum an exhaustiveness test enumerates), add {"kind":"supersedes","guard":"${guard}","why":"..."} to the amendments in the result file; the reviewer judges it.`;
247
249
 
248
- /** conformance.guard_broken rows (one per failing guard test): the guard's issue, its one-line why, the failing test and its output tail. */
250
+ /** conformance.guard_broken rows (one per failing strong guard test): the guard's issue, its one-line why, the failing test and its output tail. #5752: weak runs are notes (weakGuardNotes). */
249
251
  export function guardFailures(runs) {
250
- return (runs ?? []).filter((r) => r.rc !== 0).map((r) => ({
252
+ return (runs ?? []).filter((r) => r.rc !== 0 && !r.weak).map((r) => ({
251
253
  code: OUTCOME_CODES.CONFORMANCE_GUARD_BROKEN, kind: "guard_broken", guard: `#${r.issue}`, test: r.test,
252
254
  detail: `${supersedesHint(`#${r.issue}`)} guard #${r.issue} broken (${String(r.why ?? "").slice(0, 200)}): base test ${r.test} fails against your tree (\`${r.command}\`, exit ${r.rc})${r.failed?.length ? `; failing tests: ${r.failed.slice(0, 20).join(" | ")}` : ""}:\n${tailOf(r.output)}`,
253
255
  }));
254
256
  }
255
257
 
258
+ /** #5752: review notes for failing weak guards (tests that only assert a literal exists in file text): recorded for the reviewer, never a precheck failure. */
259
+ export function weakGuardNotes(runs) {
260
+ return (runs ?? []).filter((r) => r.rc !== 0 && r.weak).map((r) => ({
261
+ guard: `#${r.issue}`, test: r.test,
262
+ note: `Weak guard #${r.issue} broken (review note, not a park): base test ${r.test} only asserts that literal text exists in a file (${String(r.why ?? "").slice(0, 160)}); confirm the removed text is intentional`,
263
+ }));
264
+ }
265
+
256
266
  /** The comment the engine posts on a guarded issue once its guard is superseded. */
257
267
  export const supersessionComment = ({ guard, pr, why }) => `The fix guard from ${guard} was superseded by PR #${pr}: ${String(why ?? "").trim()}\n\nThe lane's contract carried a \`supersedes\` amendment the reviewer accepted; this guard's test no longer describes current behaviour.`;
258
268
 
259
- /** Guard ids the effective contract's accepted supersedes amendments retire, limited to guards the gate selected. */
260
- export function supersededIds(contract, selected) {
269
+ /**
270
+ * Guard ids the effective contract's accepted supersedes amendments retire, limited to guards the gate selected.
271
+ * #5752: with a mechanism amendment (contract.mechanisms), also each selected guard whose test files the lane deleted (`removedPaths`).
272
+ */
273
+ export function supersededIds(contract, selected, removedPaths = []) {
261
274
  const sel = new Set((selected ?? []).map((s) => `#${s.guard.issue}`));
262
- return (contract?.supersedes ?? []).filter((s) => sel.has(s.guard));
275
+ const out = (contract?.supersedes ?? []).filter((s) => sel.has(s.guard));
276
+ const mech = contract?.mechanisms ?? [];
277
+ if (!mech.length || !removedPaths?.length) return out;
278
+ const gone = new Set(removedPaths.map(norm)), seen = new Set(out.map((s) => s.guard));
279
+ const why = mech.map((m) => `mechanism ${m.mechanism} removed: ${m.why}`).join("; ");
280
+ for (const { guard } of selected ?? []) {
281
+ const id = `#${guard.issue}`, tests = (guard.tests ?? []).map((t) => norm(t.path));
282
+ if (seen.has(id) || !tests.length || !tests.every((t) => gone.has(t))) continue;
283
+ seen.add(id); out.push({ guard: id, why, mechanism: mech.map((m) => m.mechanism).join(", ") });
284
+ }
285
+ return out;
263
286
  }
@@ -6,7 +6,7 @@ import * as nodeFs from "node:fs";
6
6
  import { execFileSync, spawnSync } from "node:child_process";
7
7
  import { existsSync, mkdirSync, readdirSync, writeFileSync } from "node:fs";
8
8
  import { join } from "node:path";
9
- import { oldRanges, selectGuards, runGuards, commandFor, basePathOf, failingNames, guardFailures, supersessionComment, supersededIds, loadGuards } from "./guardgate.mjs";
9
+ import { oldRanges, selectGuards, runGuards, commandFor, basePathOf, failingNames, guardFailures, supersessionComment, supersededIds, loadGuards, weakGuardNotes } from "./guardgate.mjs";
10
10
  import { applyAmendments, precheck } from "./conformance.mjs";
11
11
  import { builderImplementPrompt, conformanceResumePrompt } from "./prompts.mjs";
12
12
  import { tmpDir } from "../tests/_tmp.mjs";
@@ -334,3 +334,46 @@ test("a template that repeats the path is never batched", async () => {
334
334
  await runGuards({ selected: [{ guard: guard(1, "a.test.mjs"), reason: "r" }, { guard: guard(2, "b.test.mjs"), reason: "r" }], mergeBase: "b", contract: {}, guardCommand: { ".mjs": "run {path} {path}" }, git: async () => "x", fs, cwd: "/w", env: {}, runCommand: async (a) => { calls.push(a.command); return { rc: 0, output: "" }; } });
335
335
  assert.ok(calls.every((c) => !c.includes("a.test__guardbase.mjs") || !c.includes("b.test__guardbase.mjs")), "no single invocation spans both files");
336
336
  });
337
+
338
+ const WEAK_SRC = `import test from "node:test";\nimport assert from "node:assert/strict";\nimport { readFileSync } from "node:fs";\nconst src = readFileSync("src/a.mjs", "utf8");\ntest("price literal", () => assert.match(src, /return 2;/));\n`;
339
+
340
+ test("#5752: a broken weak guard (literal-presence test) is a review note, never guard_broken", async () => {
341
+ const { d, guard } = fixture(WEAK_SRC);
342
+ put(d, "src/a.mjs", "export function price() {\n return 3;\n}\n");
343
+ commit(d, "change");
344
+ const { r } = await gate(d, guard);
345
+ assert.equal(r.runs.length, 1, JSON.stringify(r.skipped));
346
+ assert.equal(r.runs[0].weak, true);
347
+ assert.notEqual(r.runs[0].rc, 0);
348
+ assert.deepEqual(r.failures, [], "weak guards never park");
349
+ const notes = weakGuardNotes(r.runs);
350
+ assert.deepEqual(notes.map((n) => [n.guard, n.test]), [["#7", "src/a.test.mjs"]]);
351
+ assert.match(notes[0].note, /review note, not a park/);
352
+ const pc = precheck({ contract: { requirements: [], deliverables: [{ id: "D1", path: "src/a.mjs" }], validate: [] }, result: {}, changedFiles: ["src/a.mjs"], guardFailures: r.failures });
353
+ assert.equal(pc.ok, true, JSON.stringify(pc.failures));
354
+ });
355
+
356
+ test("#5752: a broken behavioural guard stays strong: guard_broken and no weak note", async () => {
357
+ const { d, guard } = fixture();
358
+ put(d, "src/a.mjs", "export function price() {\n return 3;\n}\n");
359
+ commit(d, "change");
360
+ const { r } = await gate(d, guard);
361
+ assert.equal(r.runs[0].weak, false);
362
+ assert.deepEqual(r.failures.map((f) => f.kind), ["guard_broken"]);
363
+ assert.deepEqual(weakGuardNotes(r.runs), []);
364
+ assert.deepEqual(guardFailures([{ issue: 1, test: "t", rc: 1, weak: true, output: "" }]), [], "guardFailures excludes weak runs");
365
+ });
366
+
367
+ test("#5752: a mechanism amendment reaches supersededIds only for guards whose test files the lane deleted", () => {
368
+ const sel = [
369
+ { guard: { issue: 7, tests: [{ path: "src/a.test.mjs" }] } },
370
+ { guard: { issue: 8, tests: [{ path: "src/b.test.mjs" }, { path: "src/c.test.mjs" }] } },
371
+ { guard: { issue: 9, tests: [{ path: "src/d.test.mjs" }] } },
372
+ ];
373
+ const contract = { mechanisms: [{ mechanism: "keyword triage", why: "replaced by the scorer" }], supersedes: [{ guard: "#9", why: "own" }] };
374
+ const ids = supersededIds(contract, sel, ["src/a.test.mjs", "src/b.test.mjs", "src/d.test.mjs"]);
375
+ assert.deepEqual(ids.map((s) => s.guard), ["#9", "#7"], "#8 keeps a surviving test; #9 is listed once");
376
+ assert.match(ids[1].why, /mechanism keyword triage removed: replaced by the scorer/);
377
+ assert.deepEqual(supersededIds({ supersedes: [] }, sel, ["src/a.test.mjs"]), [], "no mechanism: deleted tests retire nothing");
378
+ assert.deepEqual(supersededIds(contract, sel).map((s) => s.guard), ["#9"], "no removed paths: per-guard rows only");
379
+ });
@@ -153,7 +153,7 @@ test("guardAfterMerge fetches the bare branch (not origin/<lane>) and the merge
153
153
  gh: async (a) => a[0] === "issue" ? JSON.stringify({ number: 9, title: "t", comments: [{ body }] }) : a[0] === "pr" ? JSON.stringify({ number: 3, mergeCommit: { oid: "abc123" } }) : "",
154
154
  git: async (a) => { calls.push(a.join(" ")); if (a[0] === "diff") { if (!have) throw new Error("bad object"); return DIFF; } if (a.join(" ") === "fetch origin abc123") have = true; return ""; },
155
155
  };
156
- const r = await guardAfterMerge({ io, repo: "o/r", issue: 9, pr: 3, cwd: "/x", base: "origin/staging" });
156
+ const r = await guardAfterMerge({ io, repo: "o/r", issue: 9, pr: 3, cwd: "/x", base: "origin/staging", root: tmpDir("guards-fetch-") });
157
157
  assert.ok(calls.includes("fetch origin staging"));
158
158
  assert.ok(!calls.some((c) => c.includes("origin/staging")));
159
159
  assert.ok(r.posted, JSON.stringify(r));