forgedock 1.51.0 → 1.52.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.
@@ -11,6 +11,7 @@ import { fileURLToPath } from "node:url";
11
11
  import { homedir, hostname, cpus } from "node:os";
12
12
  import { localLaneCap } from "./lean/admission.mjs";
13
13
  import { memAvailableMb } from "./lean/heavy.mjs";
14
+ import { liveOverload, formatOverload, formatHostLoad } from "./lean/hostload.mjs";
14
15
  import { join, resolve as resolvePath } from "node:path";
15
16
  import { runIssue, DEFAULT_MAX_ATTEMPTS, sanitizeLeaseHost } from "./engine.mjs";
16
17
  import { makeProjector } from "./engine/projector.mjs";
@@ -363,7 +364,9 @@ export function readAdmission(cwd = process.cwd()) {
363
364
  return { ...(en === "false" ? { enabled: false } : {}),
364
365
  min_free_mem_mb: num(e.min_free_mem_mb ?? e.admission_min_free_mem_mb), min_free_tmp_mb: num(e.min_free_tmp_mb ?? e.admission_min_free_tmp_mb),
365
366
  max_load_per_core: num(e.max_load_per_core ?? e.admission_max_load_per_core),
366
- lane_cpu_reservation: pos(e.lane_cpu_reservation ?? e.admission_lane_cpu_reservation), lane_mem_mb: pos(e.lane_mem_mb ?? e.admission_lane_mem_mb) };
367
+ lane_cpu_reservation: pos(e.lane_cpu_reservation ?? e.admission_lane_cpu_reservation), lane_mem_mb: pos(e.lane_mem_mb ?? e.admission_lane_mem_mb),
368
+ overload_load_per_core: num(e.overload_load_per_core ?? e.admission_overload_load_per_core) }; // #5174: hostload.mjs overload hold
369
+
367
370
  } catch { return {}; }
368
371
  }
369
372
  /**
@@ -1858,6 +1861,7 @@ export async function runBatch({ argv, cwd: callerCwd = process.cwd(), env: call
1858
1861
  const maint = deps.maintenance !== undefined ? deps.maintenance : readMaintenance(cwd);
1859
1862
  const schedMod = await import("./lean/sched.mjs");
1860
1863
  const registry = deps.sched !== undefined ? deps.sched : schedMod.openSched(schedMod.schedDir());
1864
+ const overload = deps.overload !== undefined ? deps.overload : registry ? liveOverload(readAdmission(cwd)) : null; // #5174
1861
1865
  const labelNames = async (n) => {
1862
1866
  if (!labelsOf.has(n)) labelsOf.set(n, (JSON.parse(await leanIo.gh(["issue", "view", String(n), "-R", repo, "--json", "labels"])).labels ?? []).map((x) => x.name));
1863
1867
  return labelsOf.get(n);
@@ -1982,6 +1986,8 @@ export async function runBatch({ argv, cwd: callerCwd = process.cwd(), env: call
1982
1986
  issues, parallel, prefilter, resolveLane: laneOf, store: batch.store, getParallel: batch.readParallel, getAdded: batch.readAdded, getRequeued: batch.readRequeued, getCancelled: batch.readCancel, getHeld: batch.readHeld, getGates: batch.readGates, baseWait: baseWaits.size ? baseWaitOf(baseWaits, { io, leanIo, cwd }) : null, ...lanes,
1983
1987
  breaker: orch.breaker, maxDeferrals: orch.maxDeferrals, ...(Number.isInteger(orch.transientRetries) ? { transientRetries: orch.transientRetries } : {}), ...(deps.pollMs ? { pollMs: deps.pollMs } : {}), ...budget, limits, identity, rotator, batchId: batch.id, drift, lifecycle, integration,
1984
1988
  ...(registry ? { sched: { registry, batch: batch.id, repo, cap: liveLaneCap(orch.globalParallel ?? null, { cfg: readAdmission(cwd) }), exclusive: true }, priorityOf: async (n) => schedMod.priorityFromLabels(await labelNames(n)) } : {}),
1989
+ // #5174: hold new local admissions while loadavg/cores is above engine.overload_load_per_core (host-wide batches only)
1990
+ ...(overload ? { overload } : {}),
1985
1991
  ...(remote ? { remote } : {}),
1986
1992
  // #4267: mechanical needs-human outcomes are recovered in the batch; every runner decision is a FORGE:DECISION.
1987
1993
  ...(recoveryOn ? { recovery: orch.recovery } : {}),
@@ -2249,6 +2255,7 @@ export async function scheddFromCli(argv, deps = {}) {
2249
2255
  const pend = b.pendingAdds?.length ? `, pending adds: ${b.pendingAdds.map((n) => `#${n}`).join(" ")}` : "";
2250
2256
  console.log(` ${b.id}${b.running ? "" : " (not hosted)"}: ${age}${pend}`);
2251
2257
  }
2258
+ if (st.host) { const h = formatOverload(st.host) ?? formatHostLoad(st.host); if (h) console.log(`schedd: ${st.host.overloaded ? h : `host ${h}`}`); } // #5174
2252
2259
  for (const u of st.unhosted ?? []) console.log(`schedd: batch ${u.id} is not hosted but has ${u.pending.length} pending: ${u.pending.map((n) => `#${n}`).join(" ")} (forgedock orchestrate --resume ${u.id})`);
2253
2260
  return { running: true, ...st };
2254
2261
  }
package/bin/forgedock.mjs CHANGED
@@ -990,6 +990,15 @@ async function batchHealthSection(c, batchId) {
990
990
  }
991
991
 
992
992
  /** Compact status screen for configured/managed directories. */
993
+ /** #5174: the status `host` row: the host_overloaded line, else `load X.X/core ...`; null (rendered `unknown`) on any failure. */
994
+ async function hostLoadRow(cwd) {
995
+ try {
996
+ const [{ readAdmission }, { liveOverload, formatOverload, formatHostLoad }] = await Promise.all([import("./engine-cli.mjs"), import("./lean/hostload.mjs")]);
997
+ const snap = liveOverload(readAdmission(cwd))();
998
+ return formatOverload(snap) ?? formatHostLoad(snap);
999
+ } catch { return null; }
1000
+ }
1001
+
993
1002
  async function statusScreen(c) {
994
1003
  const state = resolveState(c.cwd);
995
1004
  const mark = renderMark("compact", c.mode);
@@ -1016,6 +1025,7 @@ async function statusScreen(c) {
1016
1025
  c.stdout.write(
1017
1026
  ` engine ${data.engine === null ? dim("unknown") : (data.engine.total === 0 ? "none in-flight" : `${data.engine.inFlight} in-flight, ${data.engine.stalled} stalled`)}\n`,
1018
1027
  );
1028
+ c.stdout.write(` host ${await hostLoadRow(c.cwd) ?? dim("unknown")}\n`); // #5174
1019
1029
  c.stdout.write(` bot token ${dim("not available — see docs/CONFIG.md (GitHub App Install)")}\n`);
1020
1030
  c.stdout.write(
1021
1031
  ` last run ${data.lastRun === null ? dim("none") : `#${data.lastRun.issue} — ${data.lastRun.terminal ? (data.lastRun.terminalReason || "done") : "in progress"}`}\n`,
@@ -299,7 +299,10 @@ const MOCKED_RE = new RegExp(String.raw`\b${MOCKED_TERM}\b`, "i");
299
299
  // #5116: a negated mock ("do not mock", "no stubs") or a fake clock is not a substitute for the e2e check.
300
300
  const NEG_MOCK_RE = /\b(?:do(?:es)? not|don't|never|no|not|without)\s+(?:use\s+|any\s+)?(?:mock\w*|stub\w*|fake\w*)/gi;
301
301
  // #5130: a negated weakener ("do not skip the e2e suite", "e2e tests are not replaced") keeps the e2e check.
302
- const NEG_DROP_RE = /\b(?:do(?:es)? not|don't|never|not)\s+(?:be\s+|been\s+|being\s+)?(?:skip|drop|replac|swap|downgrad)\w*/gi;
302
+ const NEG_LEAD = String.raw`(?:be\s+|been\s+|being\s+|(?:going|planning|intending|about|trying)\s+to\s+|intend\w*\s+to\s+)?`;
303
+ const NEG_DROP_RE = new RegExp(String.raw`\b(?:do(?:es)? not|don't|won't|never|not)\s+${NEG_LEAD}(?:skip|drop|replac|swap|downgrad)\w*`, "gi");
304
+ // A negated omission ("will not forget to add the e2e test") is a double negative: the e2e check stays.
305
+ const NEG_OMIT_RE = new RegExp(String.raw`\b(?:do(?:es)? not|don't|won't|never|not)\s+${NEG_LEAD}(?:forget|fail|omit|neglect)\w*`, "gi");
303
306
  const FAKE_CLOCK_RE = /\bfake[- ](?:timers?|clocks?)\b/gi;
304
307
  // A weakener governs the e2e term only within a few words and the same clause (no . or ; between them).
305
308
  const GAP = String.raw`(?:[\s,]+\w+){0,5}?[\s,]+`;
@@ -323,7 +326,7 @@ export function weakenedE2eDecisions(c) {
323
326
  return decisions.filter((k) => {
324
327
  const choice = String(k?.choice ?? "");
325
328
  if (!E2E_WORD_RE.test(choice)) return false;
326
- const mocked = choice.replace(NEG_MOCK_RE, " ").replace(FAKE_CLOCK_RE, " ").replace(NEG_DROP_RE, " ");
329
+ const mocked = choice.replace(NEG_MOCK_RE, " ").replace(FAKE_CLOCK_RE, " ").replace(NEG_DROP_RE, " ").replace(NEG_OMIT_RE, " ");
327
330
  if (!MOCKED_RE.test(mocked) || !(DROP_BEFORE_RE.test(mocked) || DROP_AFTER_RE.test(mocked) || INSTEAD_OF_RE.test(mocked))) return false;
328
331
  const own = `${choice} ${k?.justification ?? ""}`;
329
332
  return !((PROBE_RE.test(own) && !NEG_PROBE_RE.test(own)) || /forge-probe/i.test(elsewhere(k?.id)));
@@ -1262,7 +1265,7 @@ export function formatShadowSummary(rows) {
1262
1265
  }
1263
1266
 
1264
1267
  /** #4664: follow-up classes, one issue each per parent (scripts/file-deferred-followups.sh); post-deploy is one rollup per release lane (#4724), external one aggregate per batch and host a `host-task` (#5078). */
1265
- export const FOLLOWUP_CLASSES = ["engineering", "post-deploy", "external", "ops", "host"];
1268
+ export const FOLLOWUP_CLASSES = ["engineering", "post-deploy", "external", "ops", "host", "backlog"];
1266
1269
  /** #4724: the bucket every deferred row gets at contract time. `date:<YYYY-MM-DD>` and `owner:<action>` carry a value. */
1267
1270
  export const BUCKETS = Object.freeze(["post-deploy", "verify-now", "date", "owner", "new-issue", "host"]);
1268
1271
  const DATE_BUCKET_RE = /^date:(\d{4})-(\d{2})-(\d{2})$/;
@@ -1288,7 +1291,7 @@ export function bucketProblems(r) {
1288
1291
  const POST_PROMOTION_RE = /(?:after|post)[- ]?(?:promotion|release|deploy)|in production after|production[- ]verif|promot(?:e|ion)|rollout|purge|deploy[- ]time/i;
1289
1292
  export const READONLY_PROD_RE = /\bssh\s+[\w.-]*-monitor\b|\bobs-psql\b|\bprod(?:uction)?[ _-]monitor\b|\bread[- ]only\b[^.]{0,40}\bprod(?:uction)?\b|\bprod(?:uction)?\b[^.]{0,30}\b(?:query|queries|capture|telemetry|logs?)\b/i;
1290
1293
  /** An item that truly needs the outside world (or a write to production) stays external even when it also reads production. */
1291
- export const EXTERNAL_NEED_RE = /credential|secret|api[- ]?key|token|password|passphrase|ssh[- ]?keys?\b|private[- ]key|\blogin\b|\bsudo\b|spend|budget|billing|purchase|payment|account|third[- ]party|vendor|customer|contract sign|legal|\b(?:delete|drop|truncate|wipe|destroy|modify|migrate|write|update|restart|rotate|remove|grant|alter)\b/i;
1294
+ export const EXTERNAL_NEED_RE = /credential|secret|api[- ]?key|token|password|passphrase|ssh[- ]?keys?\b|private[- ]key|\blogin\b|\bsudo\b|spend|budget|purchase|payment|account|third[- ]party|vendor|customer|contract sign|legal|\b(?:delete|drop|truncate|wipe|destroy|modify|migrate|write|update|restart|rotate|remove|grant|alter)\b/i;
1292
1295
  /**
1293
1296
  * #5078: where an owner deferral goes. `owner:orchestrator`, `owner:promote:*` or post-promotion text -> post-deploy (the
1294
1297
  * rollup); read-only production data or capture (with no credential/spend/account/third-party/customer need) -> host; else external (credentials, spend, an account, a third party or a customer).
@@ -1301,12 +1304,18 @@ export function ownerRoute(r) {
1301
1304
  if (POST_PROMOTION_RE.test(text) && !EXTERNAL_NEED_RE.test(text)) return "post-deploy";
1302
1305
  return READONLY_PROD_RE.test(text) && !EXTERNAL_NEED_RE.test(text) ? "host" : "external";
1303
1306
  }
1304
- /** The follow-up class of a requirement: owner -> ownerRoute (ops kept), host -> host, new-issue -> engineering, other buckets post-deploy; else its `class`, else post-deploy for that disposition, else engineering. */
1307
+ const PRE_PROMOTION_RE = /(?:before|pre)[- ]?(?:promotion|release|deploy)/i;
1308
+ /** #5186: an explicit host deferral that is post-promotion text (and needs nothing external) joins the release rollup; work needed before promotion stays host. Mirrored in scripts/file-deferred-followups.sh host_route. */
1309
+ function hostRoute(r) {
1310
+ const text = `${r?.bucket ?? ""} ${r?.why ?? ""}`;
1311
+ return POST_PROMOTION_RE.test(text) && !PRE_PROMOTION_RE.test(text) && !EXTERNAL_NEED_RE.test(text) ? "post-deploy" : "host";
1312
+ }
1313
+ /** The follow-up class of a requirement: owner -> ownerRoute (ops kept), host -> host, new-issue -> backlog (one issue per batch, #5188), other buckets post-deploy; else its `class`, else post-deploy for that disposition, else engineering. */
1305
1314
  export function followupClass(r) {
1306
1315
  const k = bucketKind(r?.bucket);
1307
1316
  if (k === "owner") return r?.class === "ops" ? "ops" : ownerRoute(r);
1308
- if (k === "host") return "host";
1309
- if (k === "new-issue") return r?.class && r.class !== "post-deploy" && FOLLOWUP_CLASSES.includes(r.class) ? r.class : "engineering";
1317
+ if (k === "host") return hostRoute(r);
1318
+ if (k === "new-issue") return r?.class && !["post-deploy", "engineering"].includes(r.class) && FOLLOWUP_CLASSES.includes(r.class) ? r.class : "backlog"; // #5188: the per-batch backlog issue
1310
1319
  if (k) return "post-deploy";
1311
1320
  return FOLLOWUP_CLASSES.includes(r?.class) ? r.class : r?.disposition === "post-deploy" ? "post-deploy" : "engineering";
1312
1321
  }
@@ -998,7 +998,7 @@ describe("post-deploy check ids (#4626)", () => {
998
998
  assert.equal(cls({ disposition: "post-deploy", check: "x" }), "post-deploy");
999
999
  assert.equal(cls({ disposition: "defer", class: "external" }), "external");
1000
1000
  assert.equal(cls({ disposition: "defer", class: "bogus" }), "engineering");
1001
- assert.deepEqual(FOLLOWUP_CLASSES, ["engineering", "post-deploy", "external", "ops", "host"]);
1001
+ assert.deepEqual(FOLLOWUP_CLASSES, ["engineering", "post-deploy", "external", "ops", "host", "backlog"]);
1002
1002
  assert.equal(followupClass({ disposition: "post-deploy" }), "post-deploy"); assert.equal(followupClass({ class: "ops" }), "ops");
1003
1003
  const v = validateContract({ requirements: [{ id: "R1", quote: Q1, disposition: "defer", why: "w", class: "bogus" }], deliverables: [], preserve: [], validate: [{ id: "V1", command: "true" }] }, Q1);
1004
1004
  assert.ok(v.problems.some((x) => /R1: class must be one of/.test(x)), v.problems.join(";"));
@@ -1025,7 +1025,8 @@ describe("post-deploy check ids (#4626)", () => {
1025
1025
  assert.equal(followupClass({ disposition: "defer", bucket: "owner:spend" }), "external");
1026
1026
  assert.equal(followupClass({ disposition: "defer", bucket: "owner:spend", class: "ops" }), "ops");
1027
1027
  assert.equal(followupClass({ disposition: "defer", bucket: "owner:x", class: "post-deploy" }), "external");
1028
- assert.equal(followupClass({ disposition: "defer", bucket: "new-issue", class: "post-deploy" }), "engineering");
1028
+ assert.equal(followupClass({ disposition: "defer", bucket: "new-issue", class: "post-deploy" }), "backlog");
1029
+ assert.equal(followupClass({ disposition: "defer", bucket: "new-issue" }), "backlog"); assert.equal(followupClass({ disposition: "defer", bucket: "new-issue", class: "ops" }), "ops"); // #5188
1029
1030
  for (const bucket of ["post-deploy", "verify-now", "date:2026-12-01"]) assert.equal(followupClass({ disposition: "defer", bucket }), "post-deploy");
1030
1031
  assert.equal(one({ bucket: "owner:rotate the key" }).why, "owner: rotate the key. [bucket:owner] w");
1031
1032
  assert.equal(one({ bucket: "verify-now" }).why, "post-deploy: [bucket:verify-now] w");
@@ -1047,6 +1048,13 @@ describe("post-deploy check ids (#4626)", () => {
1047
1048
  assert.equal(followupClass(d("owner:ops", "needs a customer account to read production data")), "external");
1048
1049
  assert.equal(followupClass({ ...d("owner:obs-psql", "read prod data"), class: "ops" }), "ops");
1049
1050
  assert.equal(followupClass(d("host")), "host");
1051
+ // #5186: host + post-promotion text -> rollup; pre-promotion or external need stays host
1052
+ assert.equal(followupClass(d("host", "≥95% success over 7 days by the canary after promotion")), "post-deploy");
1053
+ assert.equal(followupClass(d("host", "billed margin from billing rows in production after promotion")), "post-deploy");
1054
+ assert.equal(followupClass(d("owner:ops", "read billing rows after promotion")), "post-deploy");
1055
+ assert.equal(followupClass(d("host", "capture the page in a browser on the host before promotion")), "host");
1056
+ assert.equal(followupClass(d("host", "capture the page in a browser on the host")), "host");
1057
+ assert.equal(followupClass(d("host", "update the rows after promotion")), "host");
1050
1058
  assert.deepEqual(bucketProblems(d("host")), []);
1051
1059
  assert.match(bucketProblems({ disposition: "post-deploy", check: "a", bucket: "host" }).join(";"), /never post-deploy/);
1052
1060
  assert.match(bucketProblems(d("owner:obs-psql", "capture production query counts")).join(";"), /use bucket host/);
@@ -1405,6 +1413,12 @@ describe("#5087 a plan decision may not weaken an e2e/integration criterion to m
1405
1413
  }
1406
1414
  assert.deepEqual(weakenedE2eDecisions({ ...C, decisions: [{ id: "K1", choice: "Keep playwright e2e coverage; add unit tests (no new fixtures needed for e2e)", source: "doc" }] }), []);
1407
1415
  });
1416
+ it("#5184 a negated omission verb keeps e2e and is not flagged", () => {
1417
+ for (const choice of ["Mocked the gateway with stubs; will not forget to add the e2e test", "Mocked the gateway with stubs; not going to forget to add the e2e test", "Mocked the gateway with stubs; never intending to skip the e2e test", "Stubs for the API; will not fail to run e2e", "Mocks used; never omit the e2e test"]) {
1418
+ assert.deepEqual(weakenedE2eDecisions({ ...C, decisions: [{ id: "K1", choice, source: "doc" }] }), [], choice);
1419
+ }
1420
+ assert.deepEqual(weakenedE2eDecisions({ ...C, decisions: [{ id: "K1", choice: "We do not need to run e2e; mocked route tests cover it", source: "doc" }] }), ["K1"]);
1421
+ });
1408
1422
  it("leaves unrelated decisions and contracts without decisions alone", () => {
1409
1423
  assert.deepEqual(weakenedE2eDecisions(C), []);
1410
1424
  assert.deepEqual(weakenedE2eDecisions({ ...C, decisions: [{ id: "K1", choice: "Run the Playwright e2e suite against the live stack", source: "doc" }, { id: "K3", choice: "Use unit tests with mocks for the parser", source: "spec" }] }), []);
@@ -119,6 +119,9 @@ const namesSymbol = (text, symbols) => symbols.some((s) => new RegExp(`(?:^|[^\\
119
119
 
120
120
  const STOPWORDS = new Set(("about after again also always another because before being between both cannot could does doing during each every from have having into issue issues just make makes more most must never only other over same should some such than that their them then there these they this those through under until very what when where which while will with within without would your " +
121
121
  "fix fixes fixed bug bugs feat chore docs test tests file files when wrong error errors fail fails failed failing add adds remove update use uses").split(" "));
122
+ /** #5110: status/label-like tokens that match a large share of any repo's history; a code or word made only of them is not a subject. */
123
+ const GENERIC_TERMS = new Set("blocked generic broad base status state failure failures result results page pages response default common general detection handling".split(" "));
124
+ const isGeneric = (t) => String(t).toLowerCase().split(/[._-]+/).filter(Boolean).every((x) => GENERIC_TERMS.has(x) || STOPWORDS.has(x));
122
125
  const FILE_EXT = /\.(?:m?[jt]sx?|cjs|md|sh|json|ya?ml|py|go|rs|rb|css|html|txt|toml|lock|sql)$/i;
123
126
  /** #5085: subject terms split by kind: codes and symbols (exact, quoted searches) and distinctive title words. */
124
127
  function subjectParts({ title = "", body = "" } = {}) {
@@ -131,8 +134,9 @@ function subjectParts({ title = "", body = "" } = {}) {
131
134
  for (const s of issueSymbols(body)) if (!codes.some((c) => c.toLowerCase().endsWith(`.${s.toLowerCase()}`))) add(s);
132
135
  const head = stripComments(title).replace(/^\s*\w+(?:\([^)]*\))?!?:\s*/, "");
133
136
  const words = [];
134
- for (const w of head.toLowerCase().match(/[a-z][a-z0-9-]{3,}/g) ?? []) if (!STOPWORDS.has(w) && !words.includes(w) && !codes.some((c) => c.toLowerCase() === w)) words.push(w);
135
- return { codes: codes.slice(0, 3), words: words.slice(0, 3) };
137
+ const tokens = [...(head.match(/\b[A-Z][A-Z0-9]{2}\b/g) ?? []), ...(head.toLowerCase().match(/[a-z][a-z0-9-]{3,}/g) ?? [])];
138
+ for (const raw of tokens) { const w = raw.toLowerCase(); if (!isGeneric(w) && !words.includes(w) && !codes.some((c) => c.toLowerCase() === w)) words.push(w); }
139
+ return { codes: codes.filter((c) => !isGeneric(c)).slice(0, 3), words: words.slice(0, 3) };
136
140
  }
137
141
  /** #5085: the issue's subject terms, codes and symbols first, then title words; deterministic, deduped, at most 6. */
138
142
  export function subjectTerms({ title = "", body = "" } = {}) {
@@ -228,7 +232,7 @@ async function readComments(gh, repo, n) {
228
232
 
229
233
  /**
230
234
  * #5085: closed issues and merged PRs on the same subject, found by term rather than by issue number or file: up to
231
- * MAX_SUBJECT_QUERIES GitHub searches (each code/symbol quoted, then the title words together) and one `git log --grep`
235
+ * MAX_SUBJECT_QUERIES GitHub searches (each non-generic code/symbol quoted, then the title words, #5110: generic codes are never searched) and one `git log --grep`
232
236
  * over the whole history of `base`. `exclude` (self, linked issues) is dropped; rows are ranked by the number of
233
237
  * matched terms, then newest first, and capped. A failed query lands in `errors`; the rest still count.
234
238
  * @returns {Promise<{terms:string[], rows:{number:number, kind:string, status:string, title:string, matched:string[]}[], errors:string[]}>}
@@ -245,7 +249,9 @@ export async function subjectHistory({ io, repo, issue = null, title = "", body
245
249
  hits.set(n, row);
246
250
  };
247
251
  if (!terms.length) return { terms, rows: [], errors };
248
- const queries = [...codes.slice(0, words.length ? MAX_SUBJECT_QUERIES - 1 : MAX_SUBJECT_QUERIES).map((c) => [c]), ...(words.length ? [words] : [])].slice(0, MAX_SUBJECT_QUERIES);
252
+ // #5110: words are searched whatever the codes are; three words run as overlapping pairs so an earlier attempt that names only two of them still matches (full matches rank first)
253
+ const groups = words.length > 2 ? [words.slice(0, 2), words.slice(1)] : words.length ? [words] : [];
254
+ const queries = [...codes.slice(0, MAX_SUBJECT_QUERIES - groups.length).map((c) => [c]), ...groups].slice(0, MAX_SUBJECT_QUERIES);
249
255
  for (const q of queries) {
250
256
  const text = q.length === 1 && codes.includes(q[0]) ? `"${q[0]}"` : q.join(" ");
251
257
  try {
@@ -258,19 +264,23 @@ export async function subjectHistory({ io, repo, issue = null, title = "", body
258
264
  } catch (e) { errors.push(`attempts: subject search ${oneLine(e?.message ?? e, 80)}`); }
259
265
  }
260
266
  if (base && io.git) {
261
- try {
262
- const greps = codes.length ? ["-E", `--grep=${codes.map(reEscape).join("|")}`] : ["--all-match", ...words.map((w) => `--grep=${reEscape(w)}`)];
263
- const out = String(await io.git(["log", "-i", ...greps, "-n", "20", "--format=%x1e%H%x1f%s%x1f%b", base]));
264
- for (const rec of out.split("\x1e").filter((x) => x.trim())) {
265
- const [, subject = "", msg = ""] = rec.split("\x1f");
266
- const pr = Number(/Merge pull request #(\d+)/.exec(subject)?.[1] ?? /\(#(\d+)\)\s*$/.exec(subject.trim())?.[1]) || null;
267
- const hay = `${subject}\n${msg}`.toLowerCase();
268
- const matched = (codes.length ? codes : words).filter((t) => hay.includes(t.toLowerCase()));
269
- if (!pr || !matched.length || (!codes.length && matched.length < words.length)) continue;
270
- const named = /^Merge pull request/.test(subject) ? msg.split("\n").map((l) => l.trim()).find(Boolean) ?? subject : subject;
271
- hit(pr, { src: "git", kind: "PR", status: "merged", title: oneLine(named, 120) }, matched);
272
- }
273
- } catch (e) { errors.push(`attempts: subject git log ${oneLine(e?.message ?? e, 80)}`); }
267
+ // one repo-wide log per kind: codes (any), words (all of a group)
268
+ const runs = [...(codes.length ? [{ greps: ["-E", `--grep=${codes.map(reEscape).join("|")}`], groups: codes.map((c) => [c]) }] : []),
269
+ ...(words.length ? [{ greps: ["--all-match", ...words.map((w) => `--grep=${reEscape(w)}`)], groups: [words] }] : [])];
270
+ for (const run of runs) {
271
+ try {
272
+ const out = String(await io.git(["log", "-i", ...run.greps, "-n", "20", "--format=%x1e%H%x1f%s%x1f%b", base]));
273
+ for (const rec of out.split("\x1e").filter((x) => x.trim())) {
274
+ const [, subject = "", msg = ""] = rec.split("\x1f");
275
+ const pr = Number(/Merge pull request #(\d+)/.exec(subject)?.[1] ?? /\(#(\d+)\)\s*$/.exec(subject.trim())?.[1]) || null;
276
+ const hay = `${subject}\n${msg}`.toLowerCase();
277
+ const matched = run.groups.filter((g) => g.every((t) => hay.includes(t.toLowerCase()))).flat();
278
+ if (!pr || !matched.length) continue;
279
+ const named = /^Merge pull request/.test(subject) ? msg.split("\n").map((l) => l.trim()).find(Boolean) ?? subject : subject;
280
+ hit(pr, { src: "git", kind: "PR", status: "merged", title: oneLine(named, 120) }, matched);
281
+ }
282
+ } catch (e) { errors.push(`attempts: subject git log ${oneLine(e?.message ?? e, 80)}`); }
283
+ }
274
284
  }
275
285
  const rows = [...hits.values()].sort((a, b) => b.matched.length - a.matched.length || b.number - a.number)
276
286
  .slice(0, max);
@@ -530,6 +530,21 @@ describe("#5085: subject history and recall status", () => {
530
530
  assert.ok(kinds.indexOf("subject") > kinds.lastIndexOf("salvage"), kinds.join(","));
531
531
  });
532
532
 
533
+ it("#5110: generic quoted codes do not replace the subject words", async () => {
534
+ const corpus = [item(34683, "Classify dead origins: TLS cert verify failures"), item(35204, "classify dead origins failures"), item(39485, "deploy reverts hotfixes blocked.generic broad-base"), item(32764, "release safety blocked.generic generic broad-base")].map((j) => JSON.parse(j));
535
+ const search = (q) => { const terms = q.replace(/^q=repo:\S+ is:closed /, "").replace(/"/g, "").toLowerCase().split(" "); return corpus.filter((c) => terms.every((t) => c.title.toLowerCase().includes(t))).map((c) => JSON.stringify(c)).join("\n"); };
536
+ const title = "fix(detection): ~85% of broad-base 'blocked.generic' are dead origins (cert-invalid, parked, TLS-refused) that run the full ladder";
537
+ const body = "Most `blocked.generic` rows on the `broad-base` crawl are dead origins.";
538
+ assert.ok(!subjectTerms({ title, body }).some((t) => /generic|broad/.test(t)), subjectTerms({ title, body }).join(","));
539
+ const f = fakes({ search });
540
+ const r = await subjectHistory({ io: f.io, repo: REPO, issue: 50, title, body, base: "origin/staging" });
541
+ assert.deepEqual(r.rows.map((x) => x.number).sort(), [34683, 35204]);
542
+ assert.ok(!f.calls.some((c) => c.some((x) => /generic|broad-base/.test(String(x)) && String(x).startsWith("q="))), "no search on a generic code");
543
+ assert.ok(r.rows[0].number === 34683 || r.rows[0].matched.length >= r.rows[1].matched.length);
544
+ const only = await subjectHistory({ io: fakes({ search }).io, repo: REPO, issue: 50, title: "fix(x): 'blocked.generic' on broad-base", body: "`blocked.generic`" });
545
+ assert.deepEqual(only, { terms: [], rows: [], errors: [] });
546
+ });
547
+
533
548
  it("ranks rows by matched-term count, then newest number", async () => {
534
549
  const search = (q) => (q.includes('"a.code"') ? [item(901, "x"), item(950, "y")] : q.includes('"b.code"') ? [item(901, "x")] : []).join("\n");
535
550
  const r = await subjectHistory({ io: fakes({ search }).io, repo: REPO, issue: 50, title: "", body: "`a.code` and `b.code`" });
@@ -406,9 +406,9 @@ export function makeLeanIo({ repo, subagentModel = readSubagentModel() }) {
406
406
  pitfalls: makePitfallStore(),
407
407
  /** forge#4275: the context pack's facts for one issue (bin/lean/context.mjs), from gh and git only; sources fail independently. */
408
408
  contextFacts: (args) => gatherContextFacts({ ...args, io: { gh: run("gh"), git: run("git"), exists: async (p) => existsSync(p) } }),
409
- /** forge#4195: scripts/hotspots.sh facts for `paths` in cwd (growth since base when given); null on any failure. */
410
- async hotspots({ cwd, base = null, paths = [] }) {
411
- const args = [script("hotspots.sh"), ...(base ? ["--base", base] : []), "--", ...paths];
409
+ /** forge#4195: scripts/hotspots.sh facts for `paths` in cwd (growth since base when given; config = the host forge.yaml, #5163); null on any failure. */
410
+ async hotspots({ cwd, base = null, paths = [], config = null }) {
411
+ const args = [script("hotspots.sh"), ...(config ? ["--config", config] : []), ...(base ? ["--base", base] : []), "--", ...paths];
412
412
  try { return JSON.parse((await pexec("bash", args, { cwd, timeout: 30000, maxBuffer: 16 * 1024 * 1024 })).stdout); } catch { return null; }
413
413
  },
414
414
  /** #4322: tests enumerating the members of the given paths, and new members those tests miss (bin/lean/enumerating.mjs); [] on failure. */
@@ -26,6 +26,7 @@ import { writeAtomic } from "./batch.mjs";
26
26
  import { schedDir, pidAlive, DEFAULT_PRIORITY } from "./sched.mjs";
27
27
  import { which } from "./toolchain.mjs";
28
28
  import { hostParallelism } from "./admission.mjs";
29
+ import { lowerPriority } from "./hostload.mjs";
29
30
 
30
31
  export const HEAVY_DEFAULTS = Object.freeze({ enabled: true, max: null, step_mem_mb: 2048, reserve_mb: 1024, ramp_s: 60, max_wait_s: 1800 });
31
32
  export const HEAVY_POLL_MS = 2000;
@@ -388,13 +389,15 @@ export async function runWrapped(argv, { env: env0 = process.env, open = openHea
388
389
  let cores = 1; try { cores = hostP.cores() || 1; } catch { /* 1 */ }
389
390
  const childEnv = { ...env, FORGE_HEAVY_HELD: "1",
390
391
  ...(env.FORGE_HEAVY_PARALLELISM_PINNED === "1" ? {} : { FORGE_HOST_PARALLELISM: String(hostParallelism({ cores, lanes: g.holders })) }) };
391
- try { return await run(cmd, args, childEnv); } finally { g.release(); }
392
+ // #5174: a gated step runs at nice 10 / ionice idle so local test runners and installs do not starve the schedd event loop.
393
+ try { return await run(cmd, args, childEnv, (child) => lowerPriority(child?.pid)); } finally { g.release(); }
392
394
  }
393
395
 
394
- /** Spawn with inherited stdio; resolves {code, signal}; forwards termination signals to the child. */
395
- export function spawnInherit(cmd, args, env) {
396
+ /** Spawn with inherited stdio; resolves {code, signal}; forwards termination signals to the child. `onSpawn(child)` runs once it has a pid. */
397
+ export function spawnInherit(cmd, args, env, onSpawn = null) {
396
398
  return new Promise((done) => {
397
399
  const child = spawn(cmd, args, { stdio: "inherit", env });
400
+ if (onSpawn && child.pid) { try { onSpawn(child); } catch { /* best effort */ } }
398
401
  const fwd = (sig) => { try { child.kill(sig); } catch { /* gone */ } };
399
402
  const sigs = ["SIGTERM", "SIGINT", "SIGHUP"];
400
403
  for (const s of sigs) process.on(s, fwd);
@@ -0,0 +1,78 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ /**
4
+ * Host overload signal (#5174). Remote lanes already run every heavy step inside their sandbox (sandbox-remote.mjs runs
5
+ * `forgedock run-issue` there). What loads a small dispatcher are the lanes that run on it: local placements and fallbacks.
6
+ * - `hostOverload` is the snapshot: overloaded when the 1-min load average divided by cores is above
7
+ * `engine.overload_load_per_core` (default 2; 0 disables; env FORGEDOCK_OVERLOAD_LOAD_PER_CORE overrides). An unreadable probe never counts as overloaded.
8
+ * - orchestrate `grant()` holds new local admissions while it is overloaded (remote placements are never held).
9
+ * - `forgedock status` and `forgedock schedd status` print `formatOverload`.
10
+ * - `lowerPriority` runs a local heavy step at nice 10 (plus `ionice -c3` on Linux when available), so test runners and
11
+ * installs do not starve the schedd event loop. Best effort, never throws.
12
+ */
13
+ import { spawn } from "node:child_process";
14
+ import { cpus, loadavg, setPriority as osSetPriority } from "node:os";
15
+ import { which } from "./toolchain.mjs";
16
+
17
+ export const OVERLOAD_DEFAULTS = Object.freeze({ load_per_core: 2 });
18
+ export const HEAVY_NICE = 10;
19
+
20
+ /** Threshold (load per core) from cfg.overload_load_per_core: > 0 sets it, 0 disables (null), unset or invalid is the default. */
21
+ export function overloadThreshold(cfg = {}) {
22
+ const v = cfg?.overload_load_per_core;
23
+ if (v === undefined || v === null || String(v).trim() === "") return OVERLOAD_DEFAULTS.load_per_core;
24
+ const n = Number(v);
25
+ if (!Number.isFinite(n) || n < 0) return OVERLOAD_DEFAULTS.load_per_core;
26
+ return n === 0 ? null : n;
27
+ }
28
+
29
+ /** Snapshot {overloaded, load1, cores, perCore, threshold}; threshold null (disabled) or an unreadable probe is never overloaded. */
30
+ export function hostOverload({ threshold = OVERLOAD_DEFAULTS.load_per_core, host = { loadAvg1: () => loadavg()[0], cores: () => cpus().length || 1 } } = {}) {
31
+ const probe = (f) => { try { const v = f?.(); return Number.isFinite(v) ? v : null; } catch { return null; } };
32
+ const load1 = probe(host?.loadAvg1), cores = probe(host?.cores);
33
+ const perCore = load1 !== null && cores ? load1 / cores : null;
34
+ const t = Number.isFinite(threshold) && threshold > 0 ? threshold : null;
35
+ return { overloaded: perCore !== null && t !== null && perCore > t, load1, cores, perCore, threshold: t };
36
+ }
37
+
38
+ /**
39
+ * A `() => snapshot` probe with the threshold read from an admission cfg (engine-cli `readAdmission`). The env
40
+ * `FORGEDOCK_OVERLOAD_LOAD_PER_CORE` (same values; 0 disables) overrides forge.yaml host-wide; the test helper sets it to 0.
41
+ */
42
+ export function liveOverload(cfg = {}, { host, env = process.env } = {}) {
43
+ const e = env?.FORGEDOCK_OVERLOAD_LOAD_PER_CORE;
44
+ const threshold = overloadThreshold(e !== undefined && String(e).trim() !== "" ? { overload_load_per_core: e } : cfg);
45
+ return () => hostOverload({ threshold, ...(host ? { host } : {}) });
46
+ }
47
+
48
+ /** `host_overloaded (load X.X/core > T): new local admissions held`, or null when not overloaded. */
49
+ export function formatOverload(snap) {
50
+ if (!snap?.overloaded) return null;
51
+ return `host_overloaded (load ${Number(snap.perCore).toFixed(1)}/core > ${snap.threshold}): new local admissions held`;
52
+ }
53
+
54
+ /** One-line host summary: the overload line, else `load X.X/core (threshold T)`, else null when load is unknown. */
55
+ export function formatHostLoad(snap) {
56
+ const o = formatOverload(snap);
57
+ if (o) return o;
58
+ if (!Number.isFinite(snap?.perCore)) return null;
59
+ return `load ${snap.perCore.toFixed(1)}/core${snap.threshold ? ` (threshold ${snap.threshold})` : " (overload hold off)"}`;
60
+ }
61
+
62
+ /** Default `spawnIonice`: `ionice -c3 -p <pid>` detached and unref'd when ionice is on PATH; returns whether it was started. */
63
+ export function spawnIoniceIdle(pid, { find = (n) => which(n, process.env.PATH ?? ""), run = spawn } = {}) {
64
+ const ionice = find("ionice");
65
+ if (!ionice) return false;
66
+ const c = run(ionice, ["-c3", "-p", String(pid)], { stdio: "ignore", detached: true, windowsHide: true });
67
+ c?.on?.("error", () => {}); c?.unref?.();
68
+ return true;
69
+ }
70
+
71
+ /** Lower a heavy step's CPU (nice 10) and, on Linux, IO (ionice idle class) priority; returns whether nice was applied. Never throws. */
72
+ export function lowerPriority(pid, { setPriority = osSetPriority, spawnIonice = spawnIoniceIdle, platform = process.platform, level = HEAVY_NICE } = {}) {
73
+ if (!Number.isInteger(pid) || pid <= 0) return false;
74
+ let ok = false;
75
+ try { setPriority(pid, level); ok = true; } catch { ok = false; }
76
+ if (platform === "linux") { try { spawnIonice(pid); } catch { /* best effort */ } }
77
+ return ok;
78
+ }
@@ -0,0 +1,117 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ // #5174: host overload hold (orchestrate grant), status host line, heavy-step niceness.
4
+ import { describe, it } from "node:test";
5
+ import assert from "node:assert/strict";
6
+ import { getPriority } from "node:os";
7
+ import { OVERLOAD_DEFAULTS, HEAVY_NICE, overloadThreshold, hostOverload, liveOverload, formatOverload, formatHostLoad, lowerPriority, spawnIoniceIdle } from "./hostload.mjs";
8
+ import { orchestrate } from "./orchestrate.mjs";
9
+ import { spawnInherit, runWrapped } from "./heavy.mjs";
10
+
11
+ const host = (load1, cores) => ({ loadAvg1: () => load1, cores: () => cores });
12
+ const sleep = (ms) => new Promise((r) => setTimeout(r, Math.min(ms ?? 1, 5)));
13
+
14
+ describe("#5174 hostload", () => {
15
+ it("overloadThreshold: default 2, > 0 sets, 0 disables, invalid is the default", () => {
16
+ assert.equal(OVERLOAD_DEFAULTS.load_per_core, 2);
17
+ assert.equal(overloadThreshold({}), 2);
18
+ assert.equal(overloadThreshold(), 2);
19
+ assert.equal(overloadThreshold({ overload_load_per_core: 3.5 }), 3.5);
20
+ assert.equal(overloadThreshold({ overload_load_per_core: 0 }), null);
21
+ assert.equal(overloadThreshold({ overload_load_per_core: -1 }), 2);
22
+ assert.equal(overloadThreshold({ overload_load_per_core: "x" }), 2);
23
+ });
24
+
25
+ it("hostOverload: overloaded only when load1/cores > threshold; unreadable probes and a disabled threshold never are", () => {
26
+ assert.deepEqual(hostOverload({ threshold: 2, host: host(18, 4) }), { overloaded: true, load1: 18, cores: 4, perCore: 4.5, threshold: 2 });
27
+ assert.equal(hostOverload({ threshold: 2, host: host(8, 4) }).overloaded, false, "exactly at the threshold is not over it");
28
+ assert.equal(hostOverload({ threshold: 2, host: host(4, 4) }).overloaded, false);
29
+ assert.equal(hostOverload({ threshold: null, host: host(18, 4) }).overloaded, false);
30
+ assert.equal(hostOverload({ threshold: 2, host: { loadAvg1: () => { throw new Error("no /proc"); }, cores: () => 4 } }).overloaded, false);
31
+ assert.equal(hostOverload({ threshold: 2, host: host(NaN, 4) }).overloaded, false);
32
+ assert.equal(hostOverload({ threshold: 2, host: host(18, 0) }).overloaded, false);
33
+ assert.equal(liveOverload({ overload_load_per_core: 1 }, { host: host(18, 4), env: {} })().overloaded, true);
34
+ assert.equal(liveOverload({ overload_load_per_core: 0 }, { host: host(18, 4), env: {} })().overloaded, false);
35
+ assert.equal(liveOverload({ overload_load_per_core: 1 }, { host: host(18, 4), env: { FORGEDOCK_OVERLOAD_LOAD_PER_CORE: "0" } })().overloaded, false, "env 0 disables");
36
+ assert.equal(liveOverload({}, { host: host(6, 4), env: { FORGEDOCK_OVERLOAD_LOAD_PER_CORE: "1" } })().threshold, 1, "env overrides forge.yaml");
37
+ assert.equal(liveOverload({}, { host: host(6, 4), env: {} })().threshold, 2);
38
+ const live = liveOverload({})();
39
+ assert.equal(typeof live.overloaded, "boolean");
40
+ });
41
+
42
+ it("formatOverload / formatHostLoad render the status lines", () => {
43
+ const over = hostOverload({ threshold: 2, host: host(18, 4) });
44
+ assert.equal(formatOverload(over), "host_overloaded (load 4.5/core > 2): new local admissions held");
45
+ assert.equal(formatHostLoad(over), "host_overloaded (load 4.5/core > 2): new local admissions held");
46
+ const ok = hostOverload({ threshold: 2, host: host(2, 4) });
47
+ assert.equal(formatOverload(ok), null);
48
+ assert.equal(formatHostLoad(ok), "load 0.5/core (threshold 2)");
49
+ assert.equal(formatHostLoad(hostOverload({ threshold: null, host: host(2, 4) })), "load 0.5/core (overload hold off)");
50
+ assert.equal(formatHostLoad(null), null);
51
+ assert.equal(formatOverload(undefined), null);
52
+ });
53
+
54
+ it("lowerPriority: nice 10, ionice idle on Linux only, never throws", () => {
55
+ const calls = [];
56
+ assert.equal(lowerPriority(123, { setPriority: (p, l) => calls.push(["nice", p, l]), spawnIonice: (p) => calls.push(["ionice", p]), platform: "linux" }), true);
57
+ assert.deepEqual(calls, [["nice", 123, HEAVY_NICE], ["ionice", 123]]);
58
+ calls.length = 0;
59
+ assert.equal(lowerPriority(123, { setPriority: (p, l) => calls.push(["nice", p, l]), spawnIonice: (p) => calls.push(["ionice", p]), platform: "darwin" }), true);
60
+ assert.deepEqual(calls, [["nice", 123, 10]]);
61
+ assert.equal(lowerPriority(123, { setPriority: () => { throw new Error("EPERM"); }, spawnIonice: () => { throw new Error("x"); }, platform: "linux" }), false);
62
+ assert.equal(lowerPriority(0), false);
63
+ assert.equal(lowerPriority(undefined), false);
64
+ const spawned = [];
65
+ assert.equal(spawnIoniceIdle(42, { find: () => "/usr/bin/ionice", run: (c, a, o) => { spawned.push([c, a, o.detached, o.windowsHide]); return { on() {}, unref() {} }; } }), true);
66
+ assert.deepEqual(spawned, [["/usr/bin/ionice", ["-c3", "-p", "42"], true, true]]);
67
+ assert.equal(spawnIoniceIdle(42, { find: () => null, run: () => assert.fail("no ionice") }), false);
68
+ });
69
+
70
+ it("spawnInherit runs onSpawn with the child; a real heavy child ends up at nice 10 and its exit code propagates", async () => {
71
+ let pid = null, nice = null;
72
+ const r = await spawnInherit(process.execPath, ["-e", "setTimeout(() => process.exit(4), 300)"], process.env, (c) => {
73
+ pid = c.pid; lowerPriority(c.pid); try { nice = getPriority(c.pid); } catch { nice = null; }
74
+ });
75
+ assert.deepEqual(r, { code: 4, signal: null });
76
+ assert.ok(Number.isInteger(pid));
77
+ assert.equal(nice, Math.max(HEAVY_NICE, getPriority()), "the heavy child runs at nice 10 (or the parent's, if already lower)");
78
+ });
79
+
80
+ it("runWrapped passes the priority hook on the gated path only (llm and nested steps pass through)", async () => {
81
+ const seen = [];
82
+ const run = async (cmd, args, env, onSpawn) => { seen.push(typeof onSpawn); return { code: 0, signal: null }; };
83
+ const open = () => ({ stats: () => ({ holders: 0 }) });
84
+ const host2 = { memAvailableMb: () => 64000, cores: () => 8 };
85
+ await runWrapped(["run", "--name", "x", "--", "/r/x"], { env: { FORGE_HEAVY_HELD: "1" }, run, host: host2, open });
86
+ await runWrapped(["run", "--name", "claude", "--", "/r/claude"], { env: { FORGE_HEAVY_DISABLED: "1" }, run, host: host2, open });
87
+ assert.deepEqual(seen, ["undefined", "undefined"]);
88
+ });
89
+
90
+ it("orchestrate holds new local admissions while overloaded, one host-overloaded row per episode, then admits", async () => {
91
+ let over = true, probes = 0;
92
+ const snap = () => { probes++; return hostOverload({ threshold: 2, host: host(over ? 18 : 2, 4) }); };
93
+ const rows = [], started = [];
94
+ const runOne = async (n) => { started.push(n); return { terminalReason: "merged", pr: n }; };
95
+ const done = orchestrate({ issues: [1, 2], parallel: 2, runOne, readBody: async () => "", overload: snap, onUpdate: (r) => rows.push(r), pollMs: 1, sleep });
96
+ for (let i = 0; i < 200 && probes < 5; i++) await new Promise((r) => setTimeout(r, 5));
97
+ assert.deepEqual(started, [], "nothing admitted while overloaded");
98
+ over = false;
99
+ const out = await done;
100
+ assert.deepEqual(out.map((r) => r.outcome).sort(), ["merged", "merged"]);
101
+ const held = rows.filter((r) => r.outcome === "host-overloaded");
102
+ assert.equal(held.length, 1, "one row per episode");
103
+ assert.equal(held[0].detail, "host_overloaded (load 4.5/core > 2): new local admissions held");
104
+ });
105
+
106
+ it("a throwing probe is not overloaded; remote placements are never held", async () => {
107
+ const started = [];
108
+ const runOne = async (n) => { started.push(n); return { terminalReason: "merged", pr: n }; };
109
+ await orchestrate({ issues: [1], parallel: 1, runOne, readBody: async () => "", overload: () => { throw new Error("x"); }, pollMs: 1, sleep });
110
+ assert.deepEqual(started, [1]);
111
+ let probes = 0;
112
+ const out = await orchestrate({ issues: [2], parallel: 1, runOne, readBody: async () => "", pollMs: 1, sleep,
113
+ overload: () => { probes++; return { overloaded: true }; }, remote: { max: 1, isRemote: () => true } });
114
+ assert.deepEqual(out.map((r) => r.outcome), ["merged"]);
115
+ assert.equal(probes, 0, "the remote placement never consults the overload gate");
116
+ });
117
+ });
@@ -0,0 +1,71 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ // Remote lanes use the batch-pinned config for hotspot facts (#5193, deferred from #5163). No mocks: the pinned forge.yaml is
4
+ // materialised by the real pool/image/entrypoint.sh snippet, then the real io.hotspots runs the real scripts/hotspots.sh in a
5
+ // real git repo. Skipped when yq (which hotspots.sh needs to read forge.yaml) or jq is missing.
6
+ import { describe, it } from "node:test";
7
+ import assert from "node:assert/strict";
8
+ import { execFileSync } from "node:child_process";
9
+ import { readFileSync, writeFileSync, mkdirSync } from "node:fs";
10
+ import { join } from "node:path";
11
+ import { fileURLToPath } from "node:url";
12
+ import { tmpDir } from "../tests/_tmp.mjs";
13
+ import { makeLeanIo } from "./effects.mjs";
14
+
15
+ const has = (bin) => { try { execFileSync(bin, ["--version"], { stdio: "ignore", timeout: 10000 }); return true; } catch { return false; } };
16
+ const skip = !has("yq") ? "yq unavailable" : !has("jq") ? "jq unavailable" : false;
17
+ const ENTRYPOINT = fileURLToPath(new URL("../../pool/image/entrypoint.sh", import.meta.url));
18
+ const PINNED = "maintenance:\n hotspot:\n exclude_globs:\n - \"web/public/openapi.json\"\n generated_paths:\n - \"gen/*.json\"\n";
19
+
20
+ const git = (cwd, ...a) => execFileSync("git", ["-c", "user.email=t@example.com", "-c", "user.name=t", "-c", "commit.gpgsign=false", ...a], { cwd, stdio: "pipe" }).toString();
21
+ const lines = (n) => Array.from({ length: n }, (_, i) => `l${i}`).join("\n") + "\n";
22
+
23
+ /** the real entrypoint block that writes the batch-pinned config into the lane checkout (pool/image/entrypoint.sh) */
24
+ function pinnedBlock() {
25
+ const m = readFileSync(ENTRYPOINT, "utf8").match(/if \[ -n "\$\{CS_FORGE_YAML_B64:-\}" \]; then\n[\s\S]*?\nfi\n/);
26
+ assert.ok(m, "entrypoint.sh no longer writes CS_FORGE_YAML_B64 to forge.yaml");
27
+ return m[0];
28
+ }
29
+
30
+ function lane(root) {
31
+ mkdirSync(join(root, "web/public"), { recursive: true });
32
+ mkdirSync(join(root, "gen"), { recursive: true });
33
+ git(root, "init", "-q", "-b", "main");
34
+ writeFileSync(join(root, "web/public/openapi.json"), lines(2100));
35
+ writeFileSync(join(root, "gen/api.json"), lines(2100));
36
+ writeFileSync(join(root, ".gitignore"), "forge.yaml\n"); // the supported layout: forge.yaml is untracked
37
+ git(root, "add", "-A"); git(root, "commit", "-qm", "base");
38
+ git(root, "checkout", "-qb", "lane");
39
+ writeFileSync(join(root, "web/public/openapi.json"), lines(2446));
40
+ writeFileSync(join(root, "gen/api.json"), lines(2446));
41
+ git(root, "add", "-A"); git(root, "commit", "-qm", "grow");
42
+ }
43
+
44
+ describe("remote lane hotspot facts use the pinned config (#5193)", { skip }, () => {
45
+ const io = makeLeanIo({ repo: "o/r" });
46
+ const paths = ["web/public/openapi.json", "gen/api.json"];
47
+
48
+ it("honours exclude_globs and generated_paths from the pinned forge.yaml the entrypoint writes", async () => {
49
+ const root = tmpDir("hotspots-remote-");
50
+ lane(root);
51
+ execFileSync("bash", ["-c", pinnedBlock()], { cwd: root, env: { ...process.env, CS_FORGE_YAML_B64: Buffer.from(PINNED).toString("base64") } });
52
+ assert.equal(readFileSync(join(root, "forge.yaml"), "utf8"), PINNED);
53
+ const h = await io.hotspots({ cwd: root, base: "main", paths });
54
+ assert.ok(h, "io.hotspots returned null");
55
+ assert.deepEqual(h.generated_paths, ["gen/*.json"]);
56
+ const by = Object.fromEntries(h.files.map((f) => [f.path, f]));
57
+ assert.equal(by["web/public/openapi.json"].growth, 346);
58
+ assert.equal(by["web/public/openapi.json"].excluded, true);
59
+ assert.equal(by["gen/api.json"].generated, true);
60
+ assert.equal(by["gen/api.json"].excluded, true);
61
+ });
62
+
63
+ it("control: without the pinned config the same files are not excluded (the defect this guards)", async () => {
64
+ const root = tmpDir("hotspots-remote-ctl-");
65
+ lane(root);
66
+ const h = await io.hotspots({ cwd: root, base: "main", paths });
67
+ const by = Object.fromEntries(h.files.map((f) => [f.path, f]));
68
+ assert.equal(by["web/public/openapi.json"].excluded, false);
69
+ assert.equal(by["gen/api.json"].excluded, false);
70
+ });
71
+ });
package/bin/lean/lean.mjs CHANGED
@@ -1309,10 +1309,14 @@ export async function runCore(o) {
1309
1309
  try { return selfCheckState(JSON.parse(await io.fs.read(`${wt}/${SELF_CHECK_FILE}`)), await worktreeFingerprint({ git, base })); } catch { return "skipped"; }
1310
1310
  };
1311
1311
  /** forge#4195: scripts/hotspots.sh facts in the worktree, or null (no io.hotspots, script failure): never fails a run. */
1312
+ let hotCfgNoted = false;
1312
1313
  const hotspotsOf = async (args) => {
1313
1314
  if (!io.hotspots) return null;
1314
- const h = await io.hotspots({ cwd: wt, ...args }).catch(() => null);
1315
- return h && typeof h === "object" && Array.isArray(h.files) ? h : null;
1315
+ const config = existsSync(join(cwd, "forge.yaml")) ? join(cwd, "forge.yaml") : null; // #5163: forge.yaml is often gitignored, so the worktree has none
1316
+ const h = await io.hotspots({ cwd: wt, config, ...args }).catch(() => null);
1317
+ if (!(h && typeof h === "object" && Array.isArray(h.files))) return null;
1318
+ if (h.config_source === null && !hotCfgNoted) { hotCfgNoted = true; T.anomalies.push("hotspot_config_missing: no forge.yaml readable for the hotspot gate (exclude_globs and generated_paths not applied; defaults used)"); }
1319
+ return h;
1316
1320
  };
1317
1321
  /** #4271: a bug lane with lean.repro_test on; refactor:split lanes never set it (no plan call, no repro_test). */
1318
1322
  const reproOn = () => reproTest !== "off" && isBugIssue(iss?.labels);
@@ -1995,7 +1995,7 @@ describe("hotspot prevention (forge#4195): plan facts, build rule, unexempted gr
1995
1995
  assert.ok(!builders(w)[0][4].includes("src/bar.js: 300 lines"), "under-threshold files get no line");
1996
1996
  assert.match(builders(w)[1][4], /Don't grow a file over 2000 lines by more than 150 lines\. Put new code next to it\./);
1997
1997
  assert.equal(w.hotCalls[0].cwd, "/wt/lean-7"); assert.ok(Array.isArray(w.hotCalls[0].paths)); assert.equal(w.hotCalls[0].base, undefined);
1998
- assert.deepEqual(w.hotCalls[1], { cwd: "/wt/lean-7", base: "origin/staging", paths: ["src/foo.js", "test/foo.test.js"] });
1998
+ assert.deepEqual(w.hotCalls[1], { cwd: "/wt/lean-7", config: null, base: "origin/staging", paths: ["src/foo.js", "test/foo.test.js"] });
1999
1999
  const plain = world(); await run(plain);
2000
2000
  assert.equal(plain.calls.filter((c) => c[0] === "runner").length, w.calls.filter((c) => c[0] === "runner").length, "no extra LLM calls");
2001
2001
  });
@@ -2024,6 +2024,18 @@ describe("hotspot prevention (forge#4195): plan facts, build rule, unexempted gr
2024
2024
  assert.equal(builders(wn)[0][4], builders(plain)[0][4], "no plan note"); assert.equal(builders(wn)[1][4], builders(plain)[1][4], "no build rule");
2025
2025
  }
2026
2026
  });
2027
+
2028
+ it("#5163: io.hotspots gets the host forge.yaml; a null config_source records one hotspot_config_missing anomaly", async () => {
2029
+ const w = hworld({ enabled: true, file_lines: 2000, growth_lines: 150, generated_paths: [], config_source: null, files: [] }, [{ enabled: true, file_lines: 2000, growth_lines: 150, generated_paths: [], config_source: null, files: [] }]);
2030
+ assert.equal((await run(w)).terminalReason, "merged");
2031
+ assert.ok(w.hotCalls.length >= 2);
2032
+ assert.ok(w.hotCalls.every((c) => c.config === null || /forge\.yaml$/.test(c.config)));
2033
+ assert.equal(w.comments.join("\n").split("hotspot_config_missing").length - 1, 1);
2034
+ const host = tmpDir("host-"); writeFileSync(join(host, "forge.yaml"), "maintenance: {}\n");
2035
+ const ok = hworld({ enabled: true, files: [], config_source: join(host, "forge.yaml") }, [{ enabled: true, files: [], config_source: join(host, "forge.yaml") }]);
2036
+ await run(ok, { cwd: host }); assert.ok(!ok.comments.join("\n").includes("hotspot_config_missing"));
2037
+ assert.ok(ok.hotCalls.length >= 2 && ok.hotCalls.every((c) => c.config === join(host, "forge.yaml") && c.cwd === "/wt/lean-7"), "the host checkout's forge.yaml, run in the worktree");
2038
+ });
2027
2039
  });
2028
2040
 
2029
2041
  describe("bug lanes freeze a red-green repro_test (#4271)", () => {
@@ -87,6 +87,8 @@
87
87
  * With `remote.fallbackLocal`, a lane placed remote runs on the host path instead of waiting when `max` remote lanes run,
88
88
  * and instead of stopping when the budget refuses. The final `{where, reason}` is kept on the run record and the row as
89
89
  * `placement` and passed to `runOne` as `ctx.placement` (the lane records it in its FORGE:STATE).
90
+ * #5174: `overload() -> {overloaded, ...}` (hostload.mjs `liveOverload`) holds every new non-remote admission while the
91
+ * host is overloaded (retry after `pollMs`), with one `host-overloaded` row per episode; remote placements are never held.
90
92
  *
91
93
  * In-batch recovery (#4267), on by default: this module recovers only when `recovery: {maxAttempts}` is passed, and the
92
94
  * CLI always passes it (forge.yaml `orchestration.recovery.max_attempts`, default 1; 0 disables): a row `classifyNeedsHuman` calls
@@ -127,6 +129,7 @@ import { makeCapWait } from "./capwait.mjs";
127
129
  import { mapLimit } from "./pmap.mjs";
128
130
  import { quotaRequeue } from "./rotator.mjs";
129
131
  import { joinsDecomposed, addsEpicChildren, selectChildren, edgeText, DEFAULT_POLL_S } from "./autochildren.mjs";
132
+ import { formatOverload } from "./hostload.mjs";
130
133
 
131
134
  // A dependency that finished like this no longer blocks its dependents.
132
135
  const SATISFIED = new Set(["merged", "invalid"]);
@@ -301,7 +304,7 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
301
304
  classify = null, maintenance = null, limits = null, identity = () => "default", batchId = null, drift = null, integration = null, sched = null, priorityOf = null, remote = null, beforeAdmit = null, preflight = null,
302
305
  recovery = null, decide = () => {}, conflicting = null, relabelNeedsHuman = null, onExit = null, issueLabels = null, issueState = null, getCancelled = null, getHeld = null, getBlocked = null, trusted = null, getGates = null, stopLane = null,
303
306
  estimate = null, starveMs = DEFAULT_STARVE_MS, setupConcurrency = DEFAULT_SETUP_CONCURRENCY, signal = null, dispatchCheck = null, syncParked = null, syncEveryMs = DEFAULT_SYNC_EVERY_MS, lifecycle = null,
304
- getChildren = null, autoChildren = null, baseWait = null, rotator = null, transientRetries = DEFAULT_TRANSIENT_RETRIES }) {
307
+ getChildren = null, autoChildren = null, baseWait = null, rotator = null, transientRetries = DEFAULT_TRANSIENT_RETRIES, overload = null }) {
305
308
  const saved = store?.load?.() ?? null;
306
309
  const order = saved ? [...saved.order] : [];
307
310
  const set = new Set(order);
@@ -594,6 +597,7 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
594
597
  };
595
598
  // A host slot for `n` (a lane-refused issue runs nothing and needs none); refused: `n` stays queued in the registry.
596
599
  // true: start it; false: no capacity now; "busy" (#4481): another batch runs `n`, try the next issue.
600
+ let overloadNoted = false; // #5174: one host-overloaded row per overload episode
597
601
  const grant = (n, wanted) => {
598
602
  if (lanes.get(n)?.ok === false) return true;
599
603
  let p = placeOf(n);
@@ -653,6 +657,16 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
653
657
  p = { where: "local", reason: `fallback to local: execution budget: ${adm.reason}` };
654
658
  }
655
659
  }
660
+ if (p?.where !== "remote" && overload) {
661
+ let snap = null;
662
+ try { snap = overload(); } catch { snap = null; }
663
+ if (snap?.overloaded) {
664
+ if (!overloadNoted) { overloadNoted = true; update({ issue: null, outcome: "host-overloaded", detail: formatOverload(snap) }); }
665
+ notBefore.set(n, now() + Math.max(pollMs, 1));
666
+ return false;
667
+ }
668
+ overloadNoted = false;
669
+ }
656
670
  if (!reg) { if (p) placed.set(n, p); return true; }
657
671
  const r = reg.tryAcquire(keyOf(n), entryOf(n), liveCap());
658
672
  if (!r?.ok && r?.conflict != null) return busy(n, r.conflict, wanted);
@@ -21,7 +21,9 @@
21
21
  * {type:"ok", cancelled:false, finished:true}, nothing written
22
22
  * {op:"hold"|"release", id, issues} → {type:"ok", changed, hosted} (#4592): merges into / removes from the batch's `hold` file; a hosted
23
23
  * runner admits no held issue from its next pass (running lanes are not stopped)
24
- * {op:"status"} → {type:"status", pid, lastTick, batches:[{id, running, lastProgressAt, lastProgressAgeSec, pendingAdds}]} (#4775: also an unhosted batch with pending adds)
24
+ * {op:"status"} → {type:"status", pid, lastTick, batches:[{id, running, lastProgressAt, lastProgressAgeSec, pendingAdds}], unhosted, host} (#4775: also an unhosted batch with pending adds;
25
+ * #5174: host = hostload.mjs snapshot {overloaded, load1, cores, perCore, threshold} from the
26
+ * `hostLoad` probe, null when it throws)
25
27
  * Failures answer {type:"error", message}. A client closing its connection never cancels a batch (only `cancel` stops one), and stopping the daemon
26
28
  * never stops a lane (lanes are detached sessions). On start the daemon resumes every daemon-hosted batch without a
27
29
  * report, so live lanes are re-adopted through the batch runner's `adopt`. It exits after `idleMs` with no batch and no client.
@@ -44,6 +46,7 @@ import { schedDir, pidAlive } from "./sched.mjs";
44
46
  import { HEARTBEAT_MS, writeHeartbeat, clearHeartbeat } from "./schedd-health.mjs";
45
47
  import { batchRoot, listBatches, openBatch, SECRET_ENV } from "./batch.mjs";
46
48
  import { applySetExecution } from "./live-execution.mjs";
49
+ import { liveOverload } from "./hostload.mjs";
47
50
 
48
51
  export const IDLE_MS = 10 * 60 * 1000;
49
52
  export const STOP_MS = 10 * 1000;
@@ -144,7 +147,8 @@ function takeLock(lock, pid, alive) {
144
147
  */
145
148
  export async function startDaemon({ dir = schedDir(), runBatch, idleMs = Number(process.env.FORGEDOCK_SCHEDD_IDLE_MS) || IDLE_MS,
146
149
  root = batchRoot(), log = (m) => console.log(m), pid = process.pid, alive = pidAlive, resumeOnStart = true, stopMs = STOP_MS,
147
- lockCheckMs = LOCK_CHECK_MS, admitMs = Number(process.env.FORGEDOCK_SCHEDD_ADMIT_MS) || ADMIT_MS, lagMs = LAG_MS, due = null, dueMs = Number(process.env.FORGEDOCK_SCHEDD_DUE_MS) || DUE_MS, preflight = null } = {}) {
150
+ lockCheckMs = LOCK_CHECK_MS, admitMs = Number(process.env.FORGEDOCK_SCHEDD_ADMIT_MS) || ADMIT_MS, lagMs = LAG_MS, due = null, dueMs = Number(process.env.FORGEDOCK_SCHEDD_DUE_MS) || DUE_MS, preflight = null,
151
+ hostLoad = liveOverload() } = {}) {
148
152
  const p = scheddPaths(dir);
149
153
  mkdirSync(dir, { recursive: true });
150
154
  const lock = takeLock(p.lock, pid, alive);
@@ -244,7 +248,8 @@ export async function startDaemon({ dir = schedDir(), runBatch, idleMs = Number(
244
248
  if (hosted.has(id) || starting.has(id)) continue;
245
249
  try { const pending = openBatch(root, id).pendingIssues(); if (pending.length) unhosted.push({ id, pending }); } catch { /* advisory */ }
246
250
  }
247
- return send({ type: "status", pid, lastTick, batches: statusBatches(), unhosted }, true);
251
+ let host = null; try { host = hostLoad?.() ?? null; } catch { host = null; } // #5174
252
+ return send({ type: "status", pid, lastTick, batches: statusBatches(), unhosted, host }, true);
248
253
  }
249
254
  if (req.op === "set-parallel") {
250
255
  const b = openBatch(root, req.id);
@@ -818,6 +818,27 @@ describe("schedd under load and restart (#4775)", () => {
818
818
  } finally { await d.close(); }
819
819
  });
820
820
 
821
+ it("#5174: status carries the host load snapshot (null when the probe throws) and `schedd status` prints host_overloaded", async () => {
822
+ const root = tmpDir("schedd-host-b-"), dir = tmpDir("schedd-host-");
823
+ const snap = { overloaded: true, load1: 18, cores: 4, perCore: 4.5, threshold: 2 };
824
+ let probe = () => snap;
825
+ const d = await startDaemon({ dir, root, runBatch: async () => ({}), resumeOnStart: false, log: () => {}, hostLoad: () => probe() });
826
+ try {
827
+ const st = await request(await connectDaemon({ dir, spawnDaemon: null }), { op: "status" });
828
+ assert.deepEqual(st.host, snap);
829
+ assert.ok("pid" in st && "lastTick" in st && Array.isArray(st.batches) && Array.isArray(st.unhosted), "existing fields unchanged");
830
+ const lines = []; const l = console.log; console.log = (x) => lines.push(String(x));
831
+ try { await scheddFromCli(["status"], { scheddDir: dir }); } finally { console.log = l; }
832
+ assert.ok(lines.includes("schedd: host_overloaded (load 4.5/core > 2): new local admissions held"), lines.join("\n"));
833
+ probe = () => ({ ...snap, overloaded: false, load1: 2, perCore: 0.5 });
834
+ lines.length = 0; console.log = (x) => lines.push(String(x));
835
+ try { await scheddFromCli(["status"], { scheddDir: dir }); } finally { console.log = l; }
836
+ assert.ok(lines.includes("schedd: host load 0.5/core (threshold 2)"), lines.join("\n"));
837
+ probe = () => { throw new Error("no /proc"); };
838
+ assert.equal((await request(await connectDaemon({ dir, spawnDaemon: null }), { op: "status" })).host, null);
839
+ } finally { await d.close(); }
840
+ });
841
+
821
842
  it("a batch whose start stalls does not block another batch's request, and the stalled request answers an error", async () => {
822
843
  const root = tmpDir("schedd-stall-b-"), dir = tmpDir("schedd-stall-");
823
844
  for (const id of ["b-hung", "b-ok"]) { mkdirSync(join(root, id), { recursive: true }); writeFileSync(join(root, id, "plan.json"), JSON.stringify({ daemon: true })); writeFileSync(join(root, id, "state.json"), JSON.stringify({ order: [1] })); }
@@ -242,6 +242,7 @@ export function createRouter(cfg, { fetchFn = globalThis.fetch, now = () => Date
242
242
  const q = (s) => `'${String(s).replace(/'/g, "''")}'`;
243
243
  const int = (k) => { const v = Number(url?.searchParams.get(k)); return Number.isInteger(v) && v > 0 ? v : 0; };
244
244
  const sizing = `${int("cpus") ? ` -AllowCpus ${int("cpus")}` : ""}${int("mem") ? ` -AllowMemGb ${int("mem")}` : ""}`;
245
+ const net = ["nat", "mirrored"].includes(url?.searchParams.get("net")) ? ` -Networking ${url.searchParams.get("net")}` : "";
245
246
  return [
246
247
  "$ErrorActionPreference = 'Stop'",
247
248
  `$RouterUrl = ${q(cfg.public_url)}`,
@@ -251,7 +252,7 @@ export function createRouter(cfg, { fetchFn = globalThis.fetch, now = () => Date
251
252
  "New-Item -ItemType Directory -Path $tmp | Out-Null",
252
253
  "Invoke-WebRequest -UseBasicParsing \"$RouterUrl/bootstrap/bundle.tar.gz?token=$EnrollToken\" -OutFile (Join-Path $tmp 'bundle.tar.gz')",
253
254
  "tar.exe -xzf (Join-Path $tmp 'bundle.tar.gz') -C $tmp",
254
- `& (Join-Path $tmp 'pool\\install\\install-agent.ps1') -RouterUrl $RouterUrl -EnrollToken $EnrollToken -BundlePath (Join-Path $tmp 'bundle.tar.gz')${sizing}`,
255
+ `& (Join-Path $tmp 'pool\\install\\install-agent.ps1') -RouterUrl $RouterUrl -EnrollToken $EnrollToken -BundlePath (Join-Path $tmp 'bundle.tar.gz')${sizing}${net}`,
255
256
  "",
256
257
  ].join("\r\n");
257
258
  }
package/docs/CONFIG.md CHANGED
@@ -643,7 +643,7 @@ engine:
643
643
  | `cli_max_minutes` | number | No | Absolute ceiling for a core builder session (code `cli.timeout`), replacing the fixed 60-minute kill. A session that keeps making progress is never idle-killed. Default 180. On either kill, uncommitted work is committed as `wip(forge): checkpoint after <reason>` and the lane branch is pushed (with the push retry), the builder retries once from the checkpoint, and a second kill ends `deferred`; a rerun resumes from the branch. |
644
644
  | `turn_budget_s` / `turn_budget_m` / `turn_budget_l` | number | No | Core implement turn budget per lane size (#4392). Size comes from a `size:S|M|L` issue label, else the frozen contract's distinct deliverable paths (S ≤ 2, M ≤ 5, else L). The build call and its context/timeout restarts share the budget; at the limit the session is stopped, checkpointed, and one fresh wrap-up session of max(5, budget/5) turns either finishes or writes `status: budget-exceeded` with a digest. A stop or overrun ends with the non-human `budget-exceeded` reason and code `budget.exceeded` (no `needs-human` label, forge#4505), which `forgedock orchestrate` recovers once (continue from the checkpoint or split); a batch that does not recover it labels it `needs-human` once. Lane results carry `turns: {size, budget, build, total, exceeded}`, and the batch report prints `turns by size`. Defaults 25 / 60 / 100; 0 disables that size. An L lane's budget scales with the contract: +10 turns per distinct deliverable path above 5 (capped at +2x `turn_budget_l`), and a `budget.exceeded` recovery of an L lane gets a further +50% of `turn_budget_l` (#4587). |
645
645
  | `lane_limits` | map | No | Cap each core lane's whole process tree (#4115, #4690), under `pipeline:` or `engine:`: `tasks_max` (default `1024`; `0`/`off` disables), `memory_max` (for example `3G`) and `cpu_quota` (for example `150%`). Where `systemd-run --user --scope` works (probed once) every lane's builder CLI is spawned as `systemd-run --user --scope -q --unit=forgedock-lane-... -p TasksMax=... -p MemoryMax=... -p CPUQuota=... -- claude ...` by default. `memory_max` has no default: lanes get no `MemoryMax` unless it is set (`off` also disables; #4740). A lane that hits `TasksMax` or `MemoryMax` is stopped and ends `needs-human` with `env.lane_limit` (not an engine-error, so the breaker ignores it). Where scopes are unavailable the run logs one line saying lanes are uncapped and the limits are ignored. Write it nested or flat (`lane_limits_tasks_max`, `lane_limits_memory_max`, `lane_limits_cpu_quota`). While a builder runs the engine polls host load and memory every 15 s against the `admission` thresholds: over them it SIGSTOPs the lane's process group, under them SIGCONT, and never pauses longer than 10 minutes. |
646
- | `admission` | map | No | Host-resource admission for the core work-on (#4105), checked before the lease, worktree or any GitHub call. When a check fails the run ends `deferred` (code `host.busy`, exit 75) with a last line such as `issue #N → deferred (host busy: mem 1.2G < 2G; retry in 60s)`; no lease is taken and nothing is posted. Keys: `enabled` (default `true`; `false` disables admission), `min_free_mem_mb` (default 2048; `MemAvailable` from `/proc/meminfo`, else `os.freemem()`), `min_free_tmp_mb` (default 1024; free space of the run TMPDIR filesystem, `~/.forge/tmp`, and of `/tmp`, via `statfs`), `max_load_per_core` (default 4; 1-minute load average divided by cores), `lane_cpu_reservation` (default 1) and `lane_mem_mb` (default 2048). The last two feed the live local lane cap (#4777), on by default: `min(--parallel / global_parallel, max(1, min(floor(cores / lane_cpu_reservation), floor((MemAvailable - min_free_mem_mb) / lane_mem_mb))))`, re-probed at every admission attempt, so `--parallel 12` on a 4-core / 8 GB host runs fewer concurrent local lanes. Remote sandbox lanes are exempt; `enabled: false` removes the cap. The cap reads the `forge.yaml` of the batch's repo, also when the batch runs under the schedd daemon. Write it nested (`engine:` then `admission:` with the keys indented) or flat as `admission_enabled`, `admission_min_free_mem_mb`, `admission_min_free_tmp_mb`, `admission_max_load_per_core`, `admission_lane_cpu_reservation`, `admission_lane_mem_mb`; the parser reads one nested level into `engine`. `/orchestrate` requeues a host-busy lane and lowers K by 1 for 5 minutes. |
646
+ | `admission` | map | No | Host-resource admission for the core work-on (#4105), checked before the lease, worktree or any GitHub call. When a check fails the run ends `deferred` (code `host.busy`, exit 75) with a last line such as `issue #N → deferred (host busy: mem 1.2G < 2G; retry in 60s)`; no lease is taken and nothing is posted. Keys: `enabled` (default `true`; `false` disables admission), `min_free_mem_mb` (default 2048; `MemAvailable` from `/proc/meminfo`, else `os.freemem()`), `min_free_tmp_mb` (default 1024; free space of the run TMPDIR filesystem, `~/.forge/tmp`, and of `/tmp`, via `statfs`), `max_load_per_core` (default 4; 1-minute load average divided by cores), `lane_cpu_reservation` (default 1) and `lane_mem_mb` (default 2048). The last two feed the live local lane cap (#4777), on by default: `min(--parallel / global_parallel, max(1, min(floor(cores / lane_cpu_reservation), floor((MemAvailable - min_free_mem_mb) / lane_mem_mb))))`, re-probed at every admission attempt, so `--parallel 12` on a 4-core / 8 GB host runs fewer concurrent local lanes. Remote sandbox lanes are exempt; `enabled: false` removes the cap. The cap reads the `forge.yaml` of the batch's repo, also when the batch runs under the schedd daemon. Write it nested (`engine:` then `admission:` with the keys indented) or flat as `admission_enabled`, `admission_min_free_mem_mb`, `admission_min_free_tmp_mb`, `admission_max_load_per_core`, `admission_lane_cpu_reservation`, `admission_lane_mem_mb`; the parser reads one nested level into `engine`. `/orchestrate` requeues a host-busy lane and lowers K by 1 for 5 minutes. Host overload hold (#5174): `overload_load_per_core` (flat `admission_overload_load_per_core`; default 2, `0` disables) holds every new local lane admission of a host-wide batch while the 1-minute load average divided by cores is above it; the issue stays queued and is retried on the next poll, and remote sandbox placements are never held. While it holds, the batch log has one `host-overloaded` row per episode, and `forgedock status` (`host` row) and `forgedock schedd status` print `host_overloaded (load X.X/core > T): new local admissions held` (otherwise `load X.X/core (threshold T)`). Unlike `max_load_per_core` it never defers a running lane. The env `FORGEDOCK_OVERLOAD_LOAD_PER_CORE` (same values) overrides it for every batch on the host. Local heavy steps (the heavy-shim semaphore path) run at nice 10 and, on Linux with `ionice` on PATH, in the idle IO class, so test runners and installs do not starve the schedd daemon. |
647
647
  | `merge_wait` | string | No | Core work-on merge gate. `required` (default): wait only for the status checks the base branch requires: the union of classic branch protection (`gh api repos/{o}/{r}/branches/{base}/protection/required_status_checks`, contexts and checks) and repository rulesets (`gh api repos/{o}/{r}/rules/branches/{base}`, `required_status_checks` rules); with neither (404 or empty) merge right after review PASS. A merge rejected by base branch policy (PR `MERGEABLE` but `BLOCKED`) is waited on and retried within the CI budget, then left `ci-pending`; it is never base-synced and never `base.conflict`. A failing required check is `needs-human`; a pending one is polled with backoff and never `needs-human`. `all`: wait for every check (`scripts/wait-ci-green.sh`). `none`: merge right after review. Always `--match-head-commit` at the reviewed head. The policy used is recorded in the `FORGE:WORK-ON` comment. |
648
648
  | `context_pack` | string | No | Context pack (#4275). Before the plan call the core compiles the issue's GitHub/git neighbourhood into a small, budgeted pack: linked issues and PRs (parent, `Depends on`, body links, same-repo cross-references, siblings), prior attempts, merged PRs on the issue's files that were reverted or whose decisions/findings name a symbol from the issue, structured `FORGE:FACTS` records of earlier lanes on the issue's files (rejected approaches with why, hot spots, decisions, conventions, baselines; #4401), and repo-fact file pointers (found in the lane worktree or, for untracked caches, the main checkout; #4400). `shadow` (default): the pack is compiled, posted on the issue as a collapsed `FORGE:CONTEXT` comment and logged as a `CONTEXT_PACK` event; the builder prompt is unchanged. `on`: it is also appended to the plan prompt as hints. `off`: nothing is gathered, posted or logged. `ab` (#4444): the A/B experiment. Each issue gets a stable arm, `on` or `shadow`, from a hash of `repo#issue`, logged as that mode with `context_ab: true`; the default stays `shadow`. The pack never enters the text contract quotes are checked against. Values read from linked issues' `FORGE:STATE` are kept only when they are outcome codes. Compare with `forgedock stats --context-ab` (per lane type and mode: first-pass yield, turns and cache-read per merge, rework rate, and recovery lanes' implement attempt against the first run on the same issue). Unless `off`, a resumed or recovery lane also gets a bounded resume digest of its last run in the builder prompt (end reason, validate results per command, deliver requirements, files changed; logged as `RESUME_DIGEST`; #4400), whatever the mode. |
649
649
  | `context_pack_sources` | string | No | Comma list of the pack sources to use: `graph`, `attempts`, `pitfalls`, `ledger`, `facts` (earlier lanes' `FORGE:FACTS` on the issue's files plus repo-fact file pointers). Default: all five. |
@@ -777,6 +777,7 @@ Deferred follow-ups (`scripts/file-deferred-followups.sh`) are routed by kind (#
777
777
  | Post-promotion, production-verify, rollout-promote (`post-deploy`, `owner:orchestrator`, `owner:promote:<flag>`, or an owner why such as "after release", "rollout", "purge") | A checklist line in the repo's ONE open post-deploy rollup (`FORGE:POSTDEPLOY_ROLLUP`, else the lowest open issue labelled `followups.rollup_issue_label`). Never a new issue when one is open. |
778
778
  | Read-only production data or capture (bucket `host`, or an owner why naming obs-psql, a `*-monitor` or a read-only prod query) | Class `host`: added to the parent's engineering follow-up of the same run, else one per-parent follow-up. Labels `followup:host` and `host-task`, never `needs-human`. |
779
779
  | Truly external (credentials, spend, an account, a third party, a customer) | ONE issue per batch (`FORGE:EXTERNAL_BATCH: <batch id>`) holding every item under a `### #<parent>` heading, labelled `followup:external`, `external-prerequisite` and `needs-human`. |
780
+ | Deferred engineering work (bucket `new-issue`) | ONE issue per batch (`FORGE:BACKLOG_BATCH: <batch id>`) holding every item under a `### #<parent>` heading (deduplicated), labelled `followup:engineering` and `followup:backlog`. |
780
781
  | Engineering | The parent's open follow-up when one exists, else one issue per parent with all its items together. `ops` and `verify-now` also keep one issue per parent. |
781
782
 
782
783
  Each issue carries the label `followup:<class>` and inherits the parent's milestone. A requirement may set an optional `class` in the contract. Otherwise `post-deploy` items are `post-deploy` and the rest `engineering`. A parent milestone that has shipped (closed) is replaced by the next open milestone by due date, else `followups.default_milestone`. The batch report lists `follow-ups appended: #N (<class>: k item(s) from #a,#b)` per issue, not "issues filed".
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "forgedock",
3
- "version": "1.51.0",
3
+ "version": "1.52.0",
4
4
  "description": "Autonomous development pipeline for coding agents. GitHub as institutional memory, with native Claude Code and OpenCode entrypoints.",
5
5
  "bin": {
6
6
  "forgedock": "bin/forgedock.mjs"
@@ -17,6 +17,7 @@ param(
17
17
  [int] $AllowCpus = 0, # 0 = logical CPUs minus 4 (min 2)
18
18
  [int] $AllowMemGb = 0, # 0 = half of physical RAM (min 4)
19
19
  [string] $Distro = 'computeshare',
20
+ [ValidateSet('auto', 'mirrored', 'nat')] [string] $Networking = 'auto', # nat: for PCs where mirrored mode fails (e.g. WSL error 0x8007054f)
20
21
  [switch] $Force # kept for compatibility; the install never prompts
21
22
  )
22
23
  $ErrorActionPreference = 'Stop'
@@ -106,7 +107,7 @@ if ($needReboot) {
106
107
  }
107
108
 
108
109
  $build = [int](Get-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion').CurrentBuildNumber
109
- $mirrored = $build -ge 22621
110
+ $mirrored = switch ($Networking) { 'nat' { $false } 'mirrored' { $true } default { $build -ge 22621 } }
110
111
  Say ("Networking: " + ($(if ($mirrored) { 'mirrored (agent listens on the Tailscale IP directly)' } else { 'NAT + portproxy (Windows 10 / older 11)' })))
111
112
 
112
113
  # .wslconfig is per Windows user and applies to every distro: merge our keys, keep everything else.
@@ -116,6 +117,7 @@ $want = [ordered]@{ processors = "$AllowCpus"; memory = "${vmMemGb}GB"; vmIdleTi
116
117
  if ($mirrored) { $want['networkingMode'] = 'mirrored' }
117
118
  $out = New-Object System.Collections.Generic.List[string]; $inWsl2 = $false; $seen = @{}
118
119
  foreach ($l in $lines) {
120
+ if (-not $mirrored -and $l -match '^\s*networkingMode\s*=\s*mirrored\s*$') { $out.Add("# $l # disabled by computeshare: -Networking nat"); continue }
119
121
  if ($l -match '^\s*\[(.+)\]\s*$') {
120
122
  if ($inWsl2) { foreach ($k in $want.Keys) { if (-not $seen[$k]) { $out.Add("$k=$($want[$k])"); $seen[$k] = $true } } }
121
123
  $inWsl2 = ($Matches[1].Trim().ToLower() -eq 'wsl2')
@@ -211,7 +213,9 @@ $taskArgs = "-NoProfile -WindowStyle Hidden -ExecutionPolicy Bypass -File `"$kee
211
213
  $action = New-ScheduledTaskAction -Execute 'powershell.exe' -Argument $taskArgs
212
214
  $trigger = New-ScheduledTaskTrigger -AtLogOn -User "$env:USERDOMAIN\$env:USERNAME"
213
215
  $settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -ExecutionTimeLimit ([TimeSpan]::Zero) -RestartCount 999 -RestartInterval (New-TimeSpan -Minutes 1)
214
- Register-ScheduledTask -TaskName 'computeshare-keepalive' -Action $action -Trigger $trigger -Settings $settings -Description 'computeshare agent keep-alive' -Force | Out-Null
216
+ # Highest: on NAT networking the task maintains a netsh portproxy, which needs an elevated token.
217
+ $principal = New-ScheduledTaskPrincipal -UserId "$env:USERDOMAIN\$env:USERNAME" -LogonType Interactive -RunLevel Highest
218
+ Register-ScheduledTask -TaskName 'computeshare-keepalive' -Action $action -Trigger $trigger -Settings $settings -Principal $principal -Description 'computeshare agent keep-alive' -Force | Out-Null
215
219
  Start-ScheduledTask -TaskName 'computeshare-keepalive'
216
220
 
217
221
  Start-Sleep -Seconds 5
@@ -23,7 +23,8 @@
23
23
  # the parent's engineering follow-up when the run has one. External items go to ONE aggregate per batch, found by
24
24
  # `<!-- FORGE:EXTERNAL_BATCH: <FORGE_BATCH_ID or adhoc> -->` (an older per-parent external follow-up is still appended to).
25
25
  # The rollup may also be the lowest open trusted issue labelled FORGE_ROLLUP_LABEL (forge.yaml followups.rollup_issue_label).
26
- # `new-issue` engineering, `verify-now` (the parent is already on the default branch) its own per-parent follow-up class
26
+ # `new-issue` engineering deferrals (class backlog, #5188) go to ONE issue per batch found by `<!-- FORGE:BACKLOG_BATCH: <batch> -->`
27
+ # (labels `followup:engineering` + `followup:backlog`, sections per parent, deduplicated like the rollup); `verify-now` (the parent is already on the default branch) its own per-parent follow-up class
27
28
  # `verify-now` that the gate releases at once, and `post-deploy`/`date` go to the ONE open rollup of the release lane.
28
29
  # The rollup (class post-deploy) is found by `<!-- FORGE:POSTDEPLOY_ROLLUP: <lane> -->`, not by parent: every lane appends
29
30
  # its items under a `### #<root parent>` heading (a follow-up of a follow-up is filed under the root parent), deduplicated
@@ -62,20 +63,27 @@ if [ "$ITEMS" = "-" ]; then cat > "$TMP/items.raw"; else cat "$ITEMS" > "$TMP/it
62
63
  # Internal file uses a non-whitespace separator (US, \x1f): a tab IFS collapses an empty `why` and drops the known-flaw flag.
63
64
  # Fields: identity, why, flag, path (`-` when none), class.
64
65
  SEP=$(printf '\037')
65
- CLASSES="engineering post-deploy external ops verify-now host"
66
+ CLASSES="engineering post-deploy external ops verify-now host backlog"
66
67
  # #5078: an owner item is external only when it needs credentials, spend, an account, a third party or a customer. A
67
68
  # post-promotion action (owner:orchestrator, owner:promote:*, after promotion/release, rollout, purge) joins the rollup and
68
69
  # read-only production data or capture (obs-psql, *-monitor, a read-only prod query) is a host task. Mirrors
69
70
  # bin/lean/conformance.mjs ownerRoute; word boundaries spelled (^|[^[:alnum:]_]) / ([^[:alnum:]_]|$), no \b, for BSD grep (bash 3.2 hosts).
70
71
  POSTPROM_ERE='(after|post)[- ]?(promotion|release|deploy)|in production after|production[- ]verif|promot(e|ion)|rollout|purge|deploy[- ]time'
71
72
  ROPROD_ERE='ssh[[:space:]]+[[:alnum:]_.-]*-monitor([^[:alnum:]_]|$)|(^|[^[:alnum:]_])obs-psql([^[:alnum:]_]|$)|(^|[^[:alnum:]_])prod(uction)?[ _-]monitor([^[:alnum:]_]|$)|(^|[^[:alnum:]_])read[- ]only[^[:alnum:]_.]([^.]{0,38}[^[:alnum:]_.])?prod(uction)?([^[:alnum:]_]|$)|(^|[^[:alnum:]_])prod(uction)?[^[:alnum:]_.]([^.]{0,28}[^[:alnum:]_.])?(query|queries|capture|telemetry|logs?)([^[:alnum:]_]|$)'
72
- EXTNEED_ERE='credential|secret|api[- ]?key|token|password|passphrase|ssh[- ]?keys?([^[:alnum:]_]|$)|private[- ]key|(^|[^[:alnum:]_])login([^[:alnum:]_]|$)|(^|[^[:alnum:]_])sudo([^[:alnum:]_]|$)|spend|budget|billing|purchase|payment|account|third[- ]party|vendor|customer|contract sign|legal|(^|[^[:alnum:]_])(delete|drop|truncate|wipe|destroy|modify|migrate|write|update|restart|rotate|remove|grant|alter)([^[:alnum:]_]|$)'
73
+ EXTNEED_ERE='credential|secret|api[- ]?key|token|password|passphrase|ssh[- ]?keys?([^[:alnum:]_]|$)|private[- ]key|(^|[^[:alnum:]_])login([^[:alnum:]_]|$)|(^|[^[:alnum:]_])sudo([^[:alnum:]_]|$)|spend|budget|purchase|payment|account|third[- ]party|vendor|customer|contract sign|legal|(^|[^[:alnum:]_])(delete|drop|truncate|wipe|destroy|modify|migrate|write|update|restart|rotate|remove|grant|alter)([^[:alnum:]_]|$)'
73
74
  owner_route() { # why -> post-deploy | host | external
74
75
  case "$1" in "owner: orchestrator"*|"owner: promote"*) echo "post-deploy"; return 0 ;; esac
75
76
  if printf '%s' "$1" | grep -qiE "$POSTPROM_ERE" && ! printf '%s' "$1" | grep -qiE "$EXTNEED_ERE"; then echo "post-deploy"
76
77
  elif printf '%s' "$1" | grep -qiE "$ROPROD_ERE" && ! printf '%s' "$1" | grep -qiE "$EXTNEED_ERE"; then echo "host"
77
78
  else echo "external"; fi
78
79
  }
80
+ # #5186: an explicit host item is post-promotion (the release rollup) when its text says so and needs nothing external; work
81
+ # needed before promotion ("before promotion", "pre-release") stays a host task. Mirrors bin/lean/conformance.mjs hostRoute.
82
+ PREPROM_ERE='(before|pre)[- ]?(promotion|release|deploy)'
83
+ host_route() { # why -> post-deploy | host
84
+ if printf '%s' "$1" | grep -qiE "$POSTPROM_ERE" && ! printf '%s' "$1" | grep -qiE "$PREPROM_ERE" && ! printf '%s' "$1" | grep -qiE "$EXTNEED_ERE"; then echo "post-deploy"
85
+ else echo "host"; fi
86
+ }
79
87
  : > "$TMP/items"
80
88
  BAD=0; ROW=0
81
89
  bad_row() { BAD=$((BAD+1)); echo "file-deferred-followups: row $ROW: $1" >&2; }
@@ -106,12 +114,12 @@ while IFS= read -r line || [ -n "$line" ]; do
106
114
  if [ -z "$c" ]; then
107
115
  case "$w" in post-deploy:*) c="post-deploy" ;; external:*) c="external" ;; ops:*) c="ops" ;; host:*) c="host" ;; *) c="engineering" ;; esac
108
116
  fi
109
- case " $CLASSES " in *" $c "*) ;; *) bad_row "unknown class \`$c\` (engineering|post-deploy|external|ops|host)"; continue ;; esac
117
+ case " $CLASSES " in *" $c "*) ;; *) bad_row "unknown class \`$c\` (engineering|post-deploy|external|ops|host|backlog)"; continue ;; esac
110
118
  # #4724: the bucket token decides the class: owner actions never join the post-deploy rollup, verify-now needs no release.
111
119
  case "$w" in
112
120
  *"[bucket:owner]"*) [ "$c" = "ops" ] || c=$(owner_route "$w") ;;
113
- *"[bucket:host]"*) c="host" ;;
114
- *"[bucket:new-issue]"*) [ "$c" = "post-deploy" ] && c="engineering" ;;
121
+ *"[bucket:host]"*) c=$(host_route "$w") ;;
122
+ *"[bucket:new-issue]"*) [ "$c" = "post-deploy" ] && c="engineering"; [ "$c" = "engineering" ] && c="backlog" ;; # #5188: one per-batch issue
115
123
  *"[bucket:verify-now]"*) [ "$c" = "post-deploy" ] && c="verify-now" ;;
116
124
  esac
117
125
  if cut -d "$SEP" -f1 "$TMP/items" | grep -qxF -- "$id"; then continue; fi
@@ -213,7 +221,8 @@ ROLLUP_MARKER="<!-- FORGE:POSTDEPLOY_ROLLUP: ${RELEASE_LANE} -->"
213
221
  BATCH="${FORGE_BATCH_ID:-adhoc}"
214
222
  EXTERNAL_MARKER="<!-- FORGE:EXTERNAL_BATCH: ${BATCH} -->"
215
223
  ROLLUP_LABEL="${FORGE_ROLLUP_LABEL:-}"
216
- agg_marker() { if [ "$1" = "post-deploy" ]; then printf '%s' "$ROLLUP_MARKER"; else printf '%s' "$EXTERNAL_MARKER"; fi; }
224
+ BACKLOG_MARKER="<!-- FORGE:BACKLOG_BATCH: ${BATCH} -->"
225
+ agg_marker() { case "$1" in post-deploy) printf '%s' "$ROLLUP_MARKER" ;; backlog) printf '%s' "$BACKLOG_MARKER" ;; *) printf '%s' "$EXTERNAL_MARKER" ;; esac; }
217
226
  verify_rollup() { # number [marker] -> `number<TAB>open` when a trusted, open, non-PR issue carries the marker
218
227
  local out rc m="${2:-$ROLLUP_MARKER}"
219
228
  out=$(gh api "repos/${REPO}/issues/$1" 2>"$TMP/verr"); rc=$?
@@ -230,7 +239,7 @@ verify_labelled() { # number -> `number<TAB>open` when a trusted, open, non-PR i
230
239
  select(.pull_request == null) | select(trusted) | select(.state == "open") | select(any(.labels[]?; (.name // .) == $l))
231
240
  | "\(.number)\t\(.state)"' 2>/dev/null
232
241
  }
233
- find_aggregate() { # kind (post-deploy|external) ; sets CANON/CSTATE to the lowest open one; non-zero only when a lookup failed
242
+ find_aggregate() { # kind (post-deploy|external|backlog) ; sets CANON/CSTATE to the lowest open one; non-zero only when a lookup failed
234
243
  local kind="$1" m q cands n r
235
244
  CANON=""; CSTATE=""
236
245
  m=$(agg_marker "$kind"); q="${m#<!-- }"; q="${q% -->}"
@@ -299,6 +308,8 @@ file_rollup() { # items in $ITEMS_F, class $CLS (post-deploy: the release-lane r
299
308
  m=$(agg_marker "$CLS")
300
309
  if [ "$CLS" = "post-deploy" ]; then
301
310
  title="post-deploy: release checklist (${RELEASE_LANE})"; what="post-deploy rollup ${RELEASE_LANE}"; lbls="followup:post-deploy"
311
+ elif [ "$CLS" = "backlog" ]; then
312
+ title="follow-up: deferred work of batch ${BATCH}"; what="backlog aggregate of batch ${BATCH}"; lbls="followup:engineering followup:backlog"
302
313
  else
303
314
  title="external: prerequisites of batch ${BATCH}"; what="external aggregate of batch ${BATCH}"; lbls="followup:external external-prerequisite needs-human"
304
315
  fi
@@ -306,6 +317,8 @@ file_rollup() { # items in $ITEMS_F, class $CLS (post-deploy: the release-lane r
306
317
  {
307
318
  if [ "$CLS" = "post-deploy" ]; then
308
319
  printf '## Problem\n\nPost-deploy checklist of release lane `%s`%s. Every merged lane appends its post-deploy items under a `### #<parent>` heading (deduplicated), so one read-only verification works through this one issue per release.\n\n' "$RELEASE_LANE" "${FORGE_RELEASE_SHA:+ (deploy target at $FORGE_RELEASE_SHA)}"
320
+ elif [ "$CLS" = "backlog" ]; then
321
+ printf '## Problem\n\nDeferred engineering work of batch `%s`: items declared out of scope (`new-issue`) by the lanes of this batch. Every lane appends its items under a `### #<parent>` heading (deduplicated), so the batch has ONE backlog issue.\n\n' "$BATCH"
309
322
  else
310
323
  printf '## Problem\n\nExternal prerequisites of batch `%s`: every item below waits on something outside the repo (credentials, spend, an account, a third party or a customer). Every lane of the batch appends its items under a `### #<parent>` heading (deduplicated), so the batch has ONE external issue.' "$BATCH"
311
324
  [ -n "${FORGE_EXTERNAL_PREREQ:-}" ] && printf ' Linked prerequisite: #%s.' "${FORGE_EXTERNAL_PREREQ#\#}"
@@ -364,6 +377,7 @@ lookup_class() {
364
377
  CKIND="agg"
365
378
  case "$CLS" in
366
379
  post-deploy) find_aggregate post-deploy ;;
380
+ backlog) find_aggregate backlog ;;
367
381
  external)
368
382
  find_aggregate external || return 1
369
383
  [ -n "$CANON" ] && return 0
@@ -529,7 +543,7 @@ INTO=""; FILED=0
529
543
  for CLS in $CLS_LIST; do
530
544
  ITEMS_F="$TMP/items.$CLS"
531
545
  case "$CLS:$(cut -f3 "$TMP/canon.$CLS")" in
532
- post-deploy:*|external:agg) file_rollup ;;
546
+ post-deploy:*|external:agg|backlog:agg) file_rollup ;;
533
547
  *) file_class ;;
534
548
  esac
535
549
  case " $INTO " in *" $FILED_N "*) ;; *) INTO="${INTO:+$INTO }$FILED_N" ;; esac
@@ -363,9 +363,23 @@ OUT=$(bash "$S" --parent 10 --repo o/r --items "$T/host.tsv"); RC=$?
363
363
  check "routing: read-only prod owner item -> one host follow-up labelled host-task" "[ $RC -eq 0 ] && [ \$(grep -c '^issue create' '$GH_LOG') -eq 1 ] && grep '^issue create' '$GH_LOG' | grep -q -- '--label followup:host' && grep '^issue create' '$GH_LOG' | grep -q -- '--label host-task' && grep -q 'FORGE:DEFERRED_CLASS: host' '$T/created.901.body'"
364
364
  check "routing: host follow-up carries no needs-human or external-prerequisite" "! grep '^issue create' '$GH_LOG' | grep -qE 'needs-human|external-prerequisite'"
365
365
  reset
366
- printf -- '-\t[bucket:host] host: run the obs-psql report\t\t\tR6: report rows\n-\tdefer: [bucket:new-issue] wire it\t\t\tR7: wire the report\n' > "$T/join.tsv"
366
+ printf -- '-\t[bucket:host] host: run the obs-psql report\t\t\tR6: report rows\n-\tdefer: wire it\t\t\tR7: wire the report\n' > "$T/join.tsv"
367
367
  OUT=$(bash "$S" --parent 10 --repo o/r --items "$T/join.tsv"); RC=$?
368
368
  check "routing: host items join the engineering follow-up of the same run" "[ $RC -eq 0 ] && [ \$(grep -c '^issue create' '$GH_LOG') -eq 1 ] && grep -q 'report rows' '$T/created.901.body' && grep -q 'wire the report' '$T/created.901.body' && grep '^issue create' '$GH_LOG' | grep -q -- '--label followup:engineering' && grep '^issue create' '$GH_LOG' | grep -q -- '--label host-task' && ! grep '^issue create' '$GH_LOG' | grep -q needs-human"
369
+ # #5186: host + post-promotion text joins the rollup; the same text from two parents is listed once; pre-promotion stays host
370
+ reset
371
+ printf '{"number":902,"state":"open","author_association":"OWNER","user":{"type":"User"},"body":"<!-- FORGE:POSTDEPLOY_ROLLUP: default -->"}\n' > "$T/issue.902.json"
372
+ echo '{"items":[{"number":902}]}' > "$SEARCH_JSON"; printf '<!-- FORGE:POSTDEPLOY_ROLLUP: default -->\n' > "$ISSUE_BODY"
373
+ printf -- '-\thost: [bucket:host] billed margin from billing rows in production after promotion\t\t\tR1: billed margin check\n' > "$T/hp.tsv"
374
+ OUT=$(bash "$S" --parent 10 --repo o/r --items "$T/hp.tsv"); RC=$?
375
+ check "routing: host post-promotion item appends to the rollup, no issue create" "[ $RC -eq 0 ] && ! grep -q '^issue create' '$GH_LOG' && grep -q '^issue edit 902' '$GH_LOG' && grep -q 'billed margin check' '$ISSUE_BODY.edited' && printf '%s' \"\$OUT\" | grep -q 'classes=post-deploy '"
376
+ cp "$ISSUE_BODY.edited" "$ISSUE_BODY"; : > "$GH_LOG"
377
+ OUT=$(bash "$S" --parent 11 --repo o/r --items "$T/hp.tsv"); RC=$?
378
+ check "routing: the same host item from a second parent is listed once" "[ $RC -eq 0 ] && ! grep -q '^issue create' '$GH_LOG' && [ \$(grep -c 'billed margin check' '$ISSUE_BODY') -eq 1 ] && { [ ! -f '$ISSUE_BODY.edited' ] || [ \$(grep -c 'billed margin check' '$ISSUE_BODY.edited') -eq 1 ]; }"
379
+ reset
380
+ printf -- '-\thost: [bucket:host] capture the page in a browser on the host before promotion\t\t\tR2: browser capture\n' > "$T/hb.tsv"
381
+ OUT=$(bash "$S" --parent 10 --repo o/r --items "$T/hb.tsv"); RC=$?
382
+ check "routing: pre-promotion host item still files follow-up (host)" "[ $RC -eq 0 ] && [ \$(grep -c '^issue create' '$GH_LOG') -eq 1 ] && grep '^issue create' '$GH_LOG' | grep -q -- '--label followup:host'"
369
383
  # N external deferrals in one batch -> ONE aggregated issue carrying needs-human
370
384
  reset
371
385
  export FORGE_BATCH_ID=b42
@@ -387,5 +401,24 @@ printf -- '-\tdefer: parser first\t\t\tR1: add the parser\n-\tdefer: needs the p
387
401
  OUT=$(bash "$S" --parent 10 --repo o/r --items "$T/eng.tsv"); RC=$?
388
402
  check "engineering: dependent items of one parent in one issue" "[ $RC -eq 0 ] && [ \$(grep -c '^issue create' '$GH_LOG') -eq 1 ] && grep -q 'add the parser' '$T/created.901.body' && grep -q 'use the parser' '$T/created.901.body'"
389
403
 
404
+
405
+ # 25. #5188: new-issue deferrals of one batch -> ONE backlog issue per batch; sections per parent; duplicates once
406
+ reset
407
+ printf -- '-\tdefer: [bucket:new-issue] wire the report\t\t\tR1: wire the report\n-\tdefer: [bucket:new-issue] add the cache\t\t\tR2: add the cache\n' > "$T/bl1.tsv"
408
+ OUT=$(FORGE_BATCH_ID=b1 bash "$S" --parent 10 --repo o/r --items "$T/bl1.tsv"); RC=$?
409
+ check "backlog: lane 1 creates ONE batch issue holding both items" "[ $RC -eq 0 ] && [ \$(grep -c '^issue create' '$GH_LOG') -eq 1 ] && grep -q 'FORGE:BACKLOG_BATCH: b1' '$T/created.901.body' && grep -q 'wire the report' '$T/created.901.body' && grep -q 'add the cache' '$T/created.901.body' && grep -q '^### #10\$' '$T/created.901.body'"
410
+ check "backlog: labelled followup:engineering and followup:backlog, never needs-human" "grep '^issue create' '$GH_LOG' | grep -q -- '--label followup:engineering' && grep '^issue create' '$GH_LOG' | grep -q -- '--label followup:backlog' && ! grep '^issue create' '$GH_LOG' | grep -q needs-human && printf '%s' \"\$OUT\" | grep -q 'classes=backlog '"
411
+ cp "$T/created.901.body" "$ISSUE_BODY"; : > "$GH_LOG"
412
+ echo '{"items":[{"number":901}]}' > "$SEARCH_JSON"
413
+ printf '{"number":901,"state":"open","author_association":"OWNER","user":{"type":"User"},"body":"<!-- FORGE:BACKLOG_BATCH: b1 -->"}\n' > "$T/issue.901.json"
414
+ printf -- '-\tdefer: [bucket:new-issue] wire the report\t\t\tR9: Wire the report!\n-\tdefer: [bucket:new-issue] other\t\t\tR3: another thing\n' > "$T/bl2.tsv"
415
+ OUT=$(FORGE_BATCH_ID=b1 bash "$S" --parent 11 --repo o/r --items "$T/bl2.tsv"); RC=$?
416
+ check "backlog: lane 2 of the batch appends to #901, creates nothing" "[ $RC -eq 0 ] && ! grep -q '^issue create' '$GH_LOG' && grep -q '^issue edit 901' '$GH_LOG' && grep -q '^### #11\$' '$ISSUE_BODY.edited' && grep -q 'another thing' '$ISSUE_BODY.edited'"
417
+ check "backlog: duplicate text from another parent stored once" "[ \$(grep -ci 'wire the report' '$ISSUE_BODY.edited') -eq 1 ] && printf '%s\n' \"\$OUT\" | grep -q '^R9: Wire the report!.901'"
418
+ # another batch does not join it
419
+ : > "$GH_LOG"; echo '{"items":[]}' > "$SEARCH_JSON"
420
+ OUT=$(FORGE_BATCH_ID=b2 bash "$S" --parent 12 --repo o/r --items "$T/bl2.tsv"); RC=$?
421
+ check "backlog: a different batch files its own issue" "[ $RC -eq 0 ] && [ \$(grep -c '^issue create' '$GH_LOG') -eq 1 ] && grep -q 'FORGE:BACKLOG_BATCH: b2' '$T/created.902.body'"
422
+
390
423
  echo "passed=$PASS failed=$FAIL"
391
424
  [ "$FAIL" -eq 0 ]
@@ -5,12 +5,14 @@
5
5
  # hotspots.sh — deterministic size and churn facts for named files (forge#4195). No LLM, no network: git + wc + jq,
6
6
  # yq (optional) only to read forge.yaml. Run from the repo root.
7
7
  #
8
- # Usage: hotspots.sh [--base <ref>] [--] <path>...
8
+ # Usage: hotspots.sh [--base <ref>] [--config <forge.yaml>] [--] <path>...
9
+ # Config file (#5163, forge.yaml is often gitignored so a lane worktree has none): --config, then $FORGE_CONFIG, then ./forge.yaml;
10
+ # output config_source is the file read, or null (defaults used).
9
11
  # Config: forge.yaml maintenance.hotspot {enabled, file_lines, growth_lines, exclude_globs}; defaults true/2000/150/[] (lockfiles are always excluded)
10
12
  # (also when forge.yaml or yq is missing); maintenance.generated_paths (forge#4519): shell globs of generated,
11
13
  # bot-owned files, default [].
12
14
  # Output (stdout, one JSON object):
13
- # {"enabled","file_lines","growth_lines","generated_paths",
15
+ # {"enabled","file_lines","growth_lines","generated_paths","config_source",
14
16
  # "files":[{path,lines,commits_90d,hotspot,over,generated,excluded,base_lines,growth}]}
15
17
  # lines = `wc -l` of the working-tree file (0 when missing); commits_90d = `git rev-list --count --since=90.days HEAD`;
16
18
  # hotspot = lines × commits_90d; over = lines > file_lines; generated = linguist-generated set by .gitattributes, a
@@ -23,10 +25,11 @@ set -uo pipefail
23
25
 
24
26
  die() { echo "hotspots: $*" >&2; exit 2; }
25
27
  command -v jq >/dev/null 2>&1 || die "jq is required"
26
- BASE=""
28
+ BASE=""; CONFIG_ARG=""
27
29
  while [ $# -gt 0 ]; do
28
30
  case "$1" in
29
31
  --base) [ $# -ge 2 ] && [ -n "$2" ] || die "usage: hotspots.sh [--base <ref>] [--] <path>..."; BASE="$2"; shift 2 ;;
32
+ --config) [ $# -ge 2 ] && [ -n "$2" ] || die "usage: hotspots.sh [--base <ref>] [--config <forge.yaml>] [--] <path>..."; CONFIG_ARG="$2"; shift 2 ;;
30
33
  --) shift; break ;;
31
34
  -*) die "unknown option: $1" ;;
32
35
  *) break ;;
@@ -34,11 +37,12 @@ while [ $# -gt 0 ]; do
34
37
  done
35
38
 
36
39
  # ---- config: maintenance.hotspot as JSON, {} when unreadable ----
37
- CFG='{}'; GEN_CFG='[]'
38
- if [ -f forge.yaml ] && command -v yq >/dev/null 2>&1; then
39
- c=$(yq -o=json '.maintenance.hotspot // {}' forge.yaml 2>/dev/null) || c=""
40
+ CFG='{}'; GEN_CFG='[]'; CONFIG_FILE="${CONFIG_ARG:-${FORGE_CONFIG:-forge.yaml}}"; CONFIG_SRC=""
41
+ if [ -f "$CONFIG_FILE" ] && command -v yq >/dev/null 2>&1; then
42
+ CONFIG_SRC="$CONFIG_FILE"
43
+ c=$(yq -o=json '.maintenance.hotspot // {}' "$CONFIG_FILE" 2>/dev/null) || c=""
40
44
  printf '%s' "$c" | jq -e 'type == "object"' >/dev/null 2>&1 && CFG="$c"
41
- g=$(yq -o=json '.maintenance.generated_paths // []' forge.yaml 2>/dev/null) || g=""
45
+ g=$(yq -o=json '.maintenance.generated_paths // []' "$CONFIG_FILE" 2>/dev/null) || g=""
42
46
  printf '%s' "$g" | jq -e 'type == "array"' >/dev/null 2>&1 && GEN_CFG="$g"
43
47
  fi
44
48
  GEN_CFG=$(printf '%s' "$GEN_CFG" | jq -c '[.[] | strings | select(length > 0)]')
@@ -48,7 +52,7 @@ CFG=$(printf '%s' "$CFG" | jq -c '
48
52
  exclude_globs: ([(.exclude_globs // [])[]? | strings]) }')
49
53
  ENABLED=$(printf '%s' "$CFG" | jq -r '.enabled')
50
54
  FILE_LINES=$(printf '%s' "$CFG" | jq -r '.file_lines')
51
- head_json() { printf '%s' "$CFG" | jq -c --argjson files "$1" --argjson gen "$GEN_CFG" '{enabled, file_lines, growth_lines, generated_paths: $gen, files: $files}'; }
55
+ head_json() { printf '%s' "$CFG" | jq -c --argjson files "$1" --argjson gen "$GEN_CFG" --arg src "$CONFIG_SRC" '{enabled, file_lines, growth_lines, generated_paths: $gen, config_source: (if $src == "" then null else $src end), files: $files}'; }
52
56
  [ "$ENABLED" = true ] || { head_json '[]'; exit 0; }
53
57
 
54
58
  MB=""
@@ -125,5 +125,27 @@ OUT="$(bash "$S" --base main -- web/package-lock.json app.py)"
125
125
  eq "lockfile excluded" "$(q '.files[0] | [.excluded,.growth]')" '[true,900]'
126
126
  eq "ordinary file not excluded" "$(q '.files[1].excluded')" 'false'
127
127
 
128
+ # ---- #5163: gitignored forge.yaml: the config comes from --config / FORGE_CONFIG, not the worktree ----
129
+ if [ "$HAVE_YQ" = 1 ]; then
130
+ new_repo
131
+ lines gen.json 10; lines app.py 10; commit base
132
+ git checkout -q -b feat3; lines more 300; cat more >> gen.json; cat more >> app.py; commit grow
133
+ HOSTCFG="$TMP/host.yaml"; printf 'maintenance:\n generated_paths: ["gen.json"]\n hotspot:\n exclude_globs: ["app.py"]\n' > "$HOSTCFG"
134
+ OUT="$(bash "$S" --base main --config "$HOSTCFG" -- gen.json app.py)"
135
+ eq "--config: generated_paths" "$(q '.files[0] | [.generated,.excluded]')" '[true,true]'
136
+ eq "--config: exclude_globs" "$(q '.files[1].excluded')" 'true'
137
+ eq "--config: source" "$(q '.config_source')" "\"$HOSTCFG\""
138
+ OUT="$(FORGE_CONFIG="$HOSTCFG" bash "$S" -- app.py)"; eq "FORGE_CONFIG honoured" "$(q '.files[0].excluded')" 'true'
139
+ printf 'maintenance:\n hotspot:\n enabled: false\n' > forge.yaml
140
+ OUT="$(bash "$S" --config "$HOSTCFG" -- app.py)"; eq "--config beats ./forge.yaml" "$(q '.enabled')" 'true'
141
+ OUT="$(FORGE_CONFIG="$HOSTCFG" bash "$S" --config "$TMP/none.yaml" -- app.py)"; eq "--config beats env" "$(q '.config_source')" 'null'
142
+ rm -f forge.yaml
143
+ fi
144
+ new_repo; lines a.py 5; commit base
145
+ OUT="$(bash "$S" -- a.py)"; eq "no config: config_source null" "$(q '.config_source')" 'null'
146
+ eq "no config: key present" "$(q 'has("config_source")')" 'true'
147
+ OUT="$(bash "$S" --config "$TMP/none.yaml" -- a.py)"; eq "bad --config: not exit 2, source null" "$(q '[has("config_source"),.config_source]')" '[true,null]'
148
+ eq "no config: defaults" "$(q '[.enabled,.file_lines]')" '[true,2000]'
149
+
128
150
  echo "hotspots.test.sh: $PASS passed, $FAILN failed"
129
151
  [ "$FAILN" -eq 0 ]
@@ -22,7 +22,7 @@ describe("#5085: prior-attempts.mjs", () => {
22
22
  assert.ok(t.includes("| #34935 won't fix (issue, not_planned) | ? | no | ? |"), t);
23
23
  assert.ok(t.includes("| #34683 TLS bypass counted as block (issue, completed) | ? | closed | ? |"), t);
24
24
  assert.ok(t.includes("| #34735 Classify tls.bypass_misclassified as success (PR, merged) | ? | yes | ? |"), t);
25
- assert.ok(t.includes("Search terms: tls.bypass_misclassified, bypass, misclassified"), t);
25
+ assert.ok(t.includes("Search terms: tls.bypass_misclassified, tls, bypass, misclassified"), t);
26
26
  assert.ok(queries.every((q) => q.startsWith("q=repo:o/r is:closed ")) && !queries.some((q) => q.includes("src/a.ts")));
27
27
  });
28
28