forgedock 1.63.0 → 1.65.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.
- package/bin/config-schema.mjs +3 -0
- package/bin/engine/outcome-codes.mjs +5 -0
- package/bin/engine-cli.mjs +88 -12
- package/bin/env/cli.mjs +18 -1
- package/bin/lean/basered.mjs +56 -11
- package/bin/lean/basered.test.mjs +58 -5
- package/bin/lean/batch-health.mjs +46 -4
- package/bin/lean/batch-health.test.mjs +55 -1
- package/bin/lean/batch.mjs +8 -1
- package/bin/lean/batch.test.mjs +71 -6
- package/bin/lean/ceiling.mjs +47 -3
- package/bin/lean/ceiling.test.mjs +32 -1
- package/bin/lean/clear-breaker.mjs +15 -0
- package/bin/lean/clear-breaker.test.mjs +100 -0
- package/bin/lean/conformance.e2e.test.mjs +32 -6
- package/bin/lean/conformance.mjs +57 -13
- package/bin/lean/conformance.test.mjs +93 -1
- package/bin/lean/execution.mjs +18 -8
- package/bin/lean/execution.test.mjs +44 -3
- package/bin/lean/issuewatch-reconcile.mjs +2 -0
- package/bin/lean/issuewatch-reconcile.test.mjs +25 -0
- package/bin/lean/issuewatch.mjs +3 -0
- package/bin/lean/lanecheck.test.mjs +13 -1
- package/bin/lean/lean.mjs +157 -28
- package/bin/lean/lean.test.mjs +289 -21
- package/bin/lean/live-execution.mjs +25 -0
- package/bin/lean/live-execution.test.mjs +35 -1
- package/bin/lean/merged-park.mjs +76 -0
- package/bin/lean/merged-park.test.mjs +64 -0
- package/bin/lean/mergetrain.mjs +357 -0
- package/bin/lean/mergetrain.test.mjs +348 -0
- package/bin/lean/mirror-bundle.mjs +84 -0
- package/bin/lean/orchestrate-envhold.test.mjs +62 -0
- package/bin/lean/orchestrate-stacking.test.mjs +23 -1
- package/bin/lean/orchestrate-train.test.mjs +130 -0
- package/bin/lean/orchestrate-transient-git.test.mjs +53 -0
- package/bin/lean/orchestrate.mjs +170 -13
- package/bin/lean/prompts.mjs +4 -3
- package/bin/lean/release-review.mjs +8 -1
- package/bin/lean/release-review.test.mjs +42 -2
- package/bin/lean/release-status.test.mjs +53 -1
- package/bin/lean/release.mjs +6 -3
- package/bin/lean/render.mjs +6 -1
- package/bin/lean/sandbox-provider.contract.test.mjs +6 -0
- package/bin/lean/sandbox-remote.mjs +43 -3
- package/bin/lean/sched.mjs +19 -2
- package/bin/lean/sched.test.mjs +33 -1
- package/bin/lean/schedd-health.mjs +2 -1
- package/bin/lean/schedd-health.test.mjs +7 -0
- package/bin/lean/schedd.mjs +58 -7
- package/bin/lean/schedd.test.mjs +78 -1
- package/bin/lean/stacking.mjs +45 -0
- package/bin/lean/stacking.test.mjs +25 -1
- package/bin/lean/statuscomment.mjs +14 -8
- package/bin/lean/statuscomment.test.mjs +18 -1
- package/bin/lean/validate-catalog.mjs +1 -1
- package/bin/lean/validate-catalog.test.mjs +3 -0
- package/bin/lean/worktree.mjs +8 -3
- package/bin/lean/worktree.test.mjs +18 -0
- package/bin/pool/agent.mjs +309 -33
- package/bin/pool/cache-sweep.mjs +4 -2
- package/bin/pool/cli.mjs +125 -6
- package/bin/pool/disk.mjs +43 -0
- package/bin/pool/docker.mjs +11 -0
- package/bin/pool/health.mjs +95 -0
- package/bin/pool/mirror-seed.mjs +103 -0
- package/bin/pool/router.mjs +301 -27
- package/bin/runner.mjs +3 -1
- package/bin/stats/chains.mjs +101 -0
- package/bin/stats/chains.test.mjs +53 -0
- package/bin/stats/efficiency.mjs +7 -6
- package/bin/stats/efficiency.test.mjs +48 -7
- package/bin/stats/index.mjs +11 -3
- package/bin/stats/stats.test.mjs +9 -0
- package/docs/CONFIG.md +8 -1
- package/docs/OUTCOME-CODES.md +4 -0
- package/package.json +1 -1
- package/pool/README.md +10 -0
- package/pool/image/Dockerfile +2 -1
- package/pool/image/entrypoint.sh +25 -6
- package/pool/image/mirror.sh +71 -0
- package/pool/install/install-agent-linux.sh +57 -5
- package/pool/install/install-agent-macos.sh +148 -0
- package/pool/install/install-agent.ps1 +11 -0
- package/pool/install/install-agent.sh +59 -7
- package/pool/install/uninstall-agent-linux.sh +75 -0
- package/pool/install/uninstall-agent-macos.sh +60 -0
- package/pool/install/uninstall-agent.ps1 +1 -0
- package/scripts/transition-label.sh +11 -0
package/bin/lean/prompts.mjs
CHANGED
|
@@ -136,7 +136,7 @@ export function routeDigestPrompt({ contract = null, read = [], buildReads = "",
|
|
|
136
136
|
const rows = (x) => (Array.isArray(x) ? x.filter((v) => v && typeof v === "object") : []);
|
|
137
137
|
const deliverables = rows(c.deliverables).map((d) => `${d.path ?? "?"}${d.change ? `: ${one(d.change, 160)}` : ""}`);
|
|
138
138
|
const decisions = rows(c.decisions).map((k) => `${k.id ?? "K?"} ${one(k.choice, 200)}${k.justification ? ` (${one(k.justification, 160)})` : ""}`);
|
|
139
|
-
const open = rows(c.requirements).filter((r) => r.disposition && r.disposition !== "deliver").map((r) => `${r.id ?? "R?"} ${r.disposition}: ${one(r.quote, 160)}`);
|
|
139
|
+
const open = rows(c.requirements).filter((r) => r.disposition && r.disposition !== "deliver").map((r) => (r.disposition === "guidance" ? `${r.id ?? "R?"} guidance (non-binding, not open work; ${one(r.why, 80)}): ${one(r.quote, 120)}` : `${r.id ?? "R?"} ${r.disposition}: ${one(r.quote, 160)}`));
|
|
140
140
|
const reads = [...new Set((Array.isArray(read) ? read : []).filter((p) => typeof p === "string" && p))];
|
|
141
141
|
const budget = Math.max(2048, Number(maxBytes) || 0);
|
|
142
142
|
const st = String(stat ?? "").trim(), br = String(buildReads ?? "").trim().slice(0, 3000), ck = String(check ?? "").trim().slice(0, 2000);
|
|
@@ -215,12 +215,12 @@ A trusted comment recording a prod failure after the merged fix overrides ancest
|
|
|
215
215
|
If the issue is already fixed or invalid, write ${RESULT_FILE} {"status":"already-fixed|invalid","summary":"one line","evidence":["file:line ..."]} and stop. A feature already reachable (another name, or a stdlib or wrapped dependency function) is a duplicate: INVALID, naming the equivalent and its path; its deprecation counts against an alias. If it is blocked, write {"status":"blocked","summary":"",...} with a typed "block" (rules below) and stop.
|
|
216
216
|
|
|
217
217
|
2. Otherwise write ${CONTRACT_FILE}, the frozen hand-off: a developer who never saw the issue must be able to implement and verify from this file alone.
|
|
218
|
-
{"requirements":[{"id":"R1","quote":"<verbatim sentence or checklist item from the issue>","disposition":"deliver|defer|post-deploy|not-applicable","why":"<defer, post-deploy>","bucket":"<defer, post-deploy: post-deploy|verify-now|date:YYYY-MM-DD|owner:<action>|host>","check":"<post-deploy: id in .forge/post-deploy-checks.json>","evidence":"<file:line, required for not-applicable>","verify":"<optional: in_lane|out_of_band>"}],
|
|
218
|
+
{"requirements":[{"id":"R1","quote":"<verbatim sentence or checklist item from the issue>","disposition":"deliver|defer|post-deploy|not-applicable|guidance","why":"<defer, post-deploy, guidance>","bucket":"<defer, post-deploy: post-deploy|verify-now|date:YYYY-MM-DD|owner:<action>|host>","check":"<post-deploy: id in .forge/post-deploy-checks.json>","evidence":"<file:line, required for not-applicable>","verify":"<optional: in_lane|out_of_band>"}],
|
|
219
219
|
"deliverables":[{"id":"D1","path":"<file to change>","change":"<what>","requirements":["R1"]}],
|
|
220
220
|
"preserve":[{"id":"P1","what":"<caller, contract or behaviour that must not change, with its path>"}],
|
|
221
221
|
"validate":[{"id":"V1","command":"<exact command: the new regression test plus the existing tests that reference the files you change; a git diff compares against the merge base (origin/<lane>...HEAD), never the moving origin/<lane> tip>"}],
|
|
222
222
|
"decisions":[{"id":"K1","choice":"<a non-obvious choice: a new dependency, a copied pattern, a boundary relied on>","justification":"<why, with file:line>","source":"doc|lint|precedent|spec"}]}
|
|
223
|
-
Every requirement and acceptance criterion in the issue and its maintainers' comments is one requirement, quoted verbatim (others' comments are context, not requirements). Never drop or narrow one silently: "defer" (separate work) and "post-deploy" (only checkable after a deploy) are judged by the reviewer and, if accepted, filed by the engine into an aggregate. Every defer or post-deploy row has one "bucket": post-deploy (needs a release), verify-now (parent already on the default branch), date:YYYY-MM-DD (absolute, never a relative wait), owner:<action> (only credentials, spend, an account, a third party, a customer; defer, never post-deploy) or host (read-only prod data: obs-psql, *-monitor). In-repo work: deliver or block split-required. A post-promotion check without a check id is post-deploy. One sentence is one row. An outcome criterion this change can ship as a test, metric or alert is "deliver". A deliver requirement whose result is only measured outside the lane (Lighthouse, field perf, a nightly or report-only suite) is "verify":"out_of_band" with "evidence" naming the job or workflow that measures it (delivered by its instrumentation). The engine tags such quotes itself; set "verify":"in_lane" when this change can check it. List every file you will change as a deliverable; tests are always allowed.
|
|
223
|
+
Every requirement and acceptance criterion in the issue and its maintainers' comments is one requirement, quoted verbatim (others' comments are context, not requirements). Outcome rows (symptom, success statement) bind; a proposed fix is "guidance" (why = follow|adapt|reject: reason). Prescription-only issue: deliver row with "derived_outcome", or block needs-human. Never drop or narrow one silently: "defer" (separate work) and "post-deploy" (only checkable after a deploy) are judged by the reviewer and, if accepted, filed by the engine into an aggregate. Every defer or post-deploy row has one "bucket": post-deploy (needs a release), verify-now (parent already on the default branch), date:YYYY-MM-DD (absolute, never a relative wait), owner:<action> (only credentials, spend, an account, a third party, a customer; defer, never post-deploy) or host (read-only prod data: obs-psql, *-monitor). In-repo work: deliver or block split-required. A post-promotion check without a check id is post-deploy. One sentence is one row. An outcome criterion this change can ship as a test, metric or alert is "deliver". A deliver requirement whose result is only measured outside the lane (Lighthouse, field perf, a nightly or report-only suite) is "verify":"out_of_band" with "evidence" naming the job or workflow that measures it (delivered by its instrumentation). The engine tags such quotes itself; set "verify":"in_lane" when this change can check it. List every file you will change as a deliverable; tests are always allowed.
|
|
224
224
|
First reviews most often find defects in:
|
|
225
225
|
${Object.entries(PLANNER_TIGHTENING).map(([k, x]) => `- ${k}: ${x}`).join("\n")}
|
|
226
226
|
A new default-off flag or rollout key needs an activation row: defer, bucket \`owner:promote:<flag>\`, why = first cohort, guard metrics, shadow evidence (an AC naming shadow/cohort/treated fails if it ships off).
|
|
@@ -522,6 +522,7 @@ export const REVIEWER_SYSTEM = `You are an independent conformance reviewer of o
|
|
|
522
522
|
|
|
523
523
|
You receive the GitHub issue with its comments, the frozen contract (requirements quoted from the issue, deliverables, preserve constraints, validate commands) with typed amendments, the builder's result with validation output, the changed files, the diff, and a row skeleton with one row per contract id and changed file. The engine computes the verdict from your rows; a reply without rows is rejected, so fill the skeleton rather than composing rows: fill EVERY row (set each empty status, evidence and validated_by, and each null deferral_ok; keep the ids and files as given):
|
|
524
524
|
- issue_coverage: one row per requirement or acceptance criterion in the issue, quoted verbatim, saying whether the contract covers it, narrows it, or misses it. The skeleton lists the contract's quotes; add a row for any issue requirement the contract does not quote.
|
|
525
|
+
- guidance: a guidance requirement (pre-filled covered / not-applicable) is a proposed change, non-binding: judge whether the outcome rows are met, never whether the proposal was followed. Set misclassified: true on its issue_coverage row only when the quote is really a symptom or success criterion. A deliver row with derived_outcome is judged against derived_outcome, like amendment.text.
|
|
525
526
|
- amendment: a requirement with an \`amendment\` is judged against amendment.text and its why, not the quote; its issue_coverage row is covered when the amendment follows from its why. A requirement with \`amended_from\` was contracted defer or post-deploy and flipped to deliver: compare amended_from.quote and amended_from.why with amendment.text side by side, and mark the row partial when the rewording drops the original work or only trivially restates it. If it does not hold, mark the row partial with note "amendment: <what to change>".
|
|
526
527
|
- requirements: one row per contract requirement id: implemented|partial|missing|deferred|post-deploy|not-applicable, with evidence as a backtick-quoted repo-relative path:line copied verbatim from the changed files, including (group), [slug] and [...slug] folders (e.g. \`apps/web/app/(console)/layout.tsx:12\`, not route.ts:12) and the validate id or test that proves it (validated_by). For a defer or post-deploy requirement add deferral_ok: true only if it is genuinely separate work or only checkable after a deploy, false if it belongs in this change, including an outcome criterion (a metric, rate or log expectation) this change could ship as a test, metric or alert, or a read-only production check possible now (bucket verify-now). For a verify out_of_band row (measured by the named job, not in this lane) set instrumented: true only when its budget test or bench is committed and that job is configured, with that path:line as evidence; false otherwise. Do not judge the measured result.
|
|
527
528
|
- post-deploy requirements: deferral_ok is false when the requirement has no \`check\` id, or its check is neither in .forge/post-deploy-checks.json on the default branch nor added by this change (the commands run from that file only).
|
|
@@ -234,6 +234,13 @@ export async function fixStep(ctx) {
|
|
|
234
234
|
if (!r?.pr) return blocked("no review result recorded by the review step");
|
|
235
235
|
const seam = seamOf(ctx);
|
|
236
236
|
const cfg = parseFixConfig(ctx.config?.fix);
|
|
237
|
+
// #5912: a resume reads the result saved while CI was still running. A CI-only failure at an unmoved head is re-summarised once, so CI
|
|
238
|
+
// that finished green since posts GATE_PASS instead of the stale "still pending" block.
|
|
239
|
+
if (r.marker !== "FORGE:GATE_PASS" && !r.blocking?.length && !r.guards?.length && (r.ciPendingOnly || !(r.ciFailing > 0)) && (await seam.headOf(r.pr)) === r.head) {
|
|
240
|
+
const s = await resummarise(ctx, seam, r);
|
|
241
|
+
if (s.err) return blocked(s.err);
|
|
242
|
+
r = s.r;
|
|
243
|
+
}
|
|
237
244
|
while (r.marker !== "FORGE:GATE_PASS") {
|
|
238
245
|
// Only cancelled duplicate runs are red (#5502): nothing to fix. The summary reruns them once; re-summarise without spending the round.
|
|
239
246
|
if (!r.blocking?.length && r.ciFailing > 0 && r.ciCancelOnly) {
|
|
@@ -257,7 +264,7 @@ export async function fixStep(ctx) {
|
|
|
257
264
|
const rec = collectFindings({ head: r.head, jobs, findings: r.items ?? [], guards: r.guards ?? [] });
|
|
258
265
|
const b = blockingOf(rec);
|
|
259
266
|
if (!b.ci.length && !b.review.length && !b.guards.length && !r.blocking?.length && jobs.pending?.length) return blocked(`required checks of #${r.pr} still running (${jobs.pending.join(", ")}), with no failure to fix yet; re-run the release once CI finishes`);
|
|
260
|
-
if (!b.ci.length && !b.review.length && !b.guards.length && !r.blocking?.length && !(r.ciFailing > 0)) return blocked(`${r.verdict} with neither a blocking finding nor red CI to fix`);
|
|
267
|
+
if (!b.ci.length && !b.review.length && !b.guards.length && !r.blocking?.length && !(r.ciFailing > 0)) return blocked(`${r.verdict} (${r.marker}) on #${r.pr} at ${String(r.head).slice(0, 7)} with neither a blocking finding nor red CI to fix: nothing is pending or failing, so the gate summary names the actual blocker; read it and re-run the release`);
|
|
261
268
|
const hashesNow = Object.fromEntries(rec.ci.map((j) => [j.name, j.inputHash ?? inputHash(j.name, r.head)]));
|
|
262
269
|
const brief = compileBrief(rec, { commands: ctx.config?.preflight ? [ctx.config.preflight.command] : [], rerunChecks: jobsToRerun(hashesNow, ctx.state.fixloop?.hashes ?? {}) });
|
|
263
270
|
// Non-blocking and out-of-wave findings become next-plan issues, once per head; they are never part of the fix and never merged after READY (I16).
|
|
@@ -5,7 +5,7 @@ import assert from "node:assert/strict";
|
|
|
5
5
|
import { reviewStep, fixStep, missingReviewers, SPEC_PANEL, MAX_DELTA_PASSES, realSeam, withIntegrityMarker, TEST_GATE_SKIP_NO_TESTS, testGatePrompt, integrationTestCount, resolveSkillName } from "./release-review.mjs";
|
|
6
6
|
import { readFileSync } from "node:fs";
|
|
7
7
|
import { EventEmitter } from "node:events";
|
|
8
|
-
import { reviewStagingJson } from "../review-staging.mjs";
|
|
8
|
+
import { reviewStagingJson, classifyChecks, cancelOnlyChecks } from "../review-staging.mjs";
|
|
9
9
|
|
|
10
10
|
const H1 = "a".repeat(40), H2 = "b".repeat(40);
|
|
11
11
|
const manifest = (head, delta = null) => ({ pr: 7, headSha: head, bundle: [1, 2], scopeMode: "full", contextFile: "/sd/review-ctx-7.json", launchedFile: "/sd/7_launched", briefs: [{ domain: "security", path: "/sd/brief-security.md" }], delta });
|
|
@@ -266,6 +266,7 @@ describe("fixStep", () => {
|
|
|
266
266
|
|
|
267
267
|
it("only pending CI (#5519): blocks without a CI issue or lane; a real failure alongside still files", async () => {
|
|
268
268
|
const s = fakeSeam();
|
|
269
|
+
s.summary = async () => ({ code: 0, data: { verdict: "BLOCK DEPLOY", marker: "FORGE:GATE_FAILURE", ciFailing: 1, ciPendingOnly: true }, lines: [] });
|
|
269
270
|
const r = await fixStep(ctx(s, { review: { result: { ...failed, blocking: [], filed: [], ciFailing: 1, ciPendingOnly: true } } }));
|
|
270
271
|
assert.match(r.reason, /still pending/);
|
|
271
272
|
assert.deepEqual(s.log, []);
|
|
@@ -274,8 +275,47 @@ describe("fixStep", () => {
|
|
|
274
275
|
assert.ok(s2.log.some((e) => e[0] === "fix-issue"));
|
|
275
276
|
});
|
|
276
277
|
|
|
278
|
+
it("#5912: a stale pending-only GATE_FAILURE is re-summarised on resume and passes once CI is green", async () => {
|
|
279
|
+
const s = fakeSeam();
|
|
280
|
+
const r = await fixStep(ctx(s, { review: { result: { ...failed, blocking: [], filed: [], ciFailing: 3, ciPendingOnly: true } } }));
|
|
281
|
+
assert.equal(r.verdict, "APPROVE FOR DEPLOY");
|
|
282
|
+
assert.deepEqual(s.log, [["summary", []]]);
|
|
283
|
+
});
|
|
284
|
+
|
|
285
|
+
it("#5912: a GATE_FAILURE with a blocking finding is not re-summarised away", async () => {
|
|
286
|
+
const s = fakeSeam();
|
|
287
|
+
await fixStep(ctx(s, { review: { result: { ...failed, ciFailing: 0, ciPendingOnly: false } } }));
|
|
288
|
+
assert.ok(s.log.some((e) => e[0] === "fix-issue"));
|
|
289
|
+
});
|
|
290
|
+
|
|
291
|
+
it("#5912: a moved head is not re-summarised on resume", async () => {
|
|
292
|
+
const s = fakeSeam({ heads: [H2] });
|
|
293
|
+
await fixStep(ctx(s, { review: { result: { ...failed, blocking: [], filed: [], ciFailing: 3, ciPendingOnly: true } } }));
|
|
294
|
+
assert.ok(!s.log.some((e) => e[0] === "summary"));
|
|
295
|
+
});
|
|
296
|
+
|
|
297
|
+
it("#5912: still pending after the re-summarise blocks with the pending reason", async () => {
|
|
298
|
+
const s = fakeSeam({ summary: { code: 0, data: { verdict: "BLOCK DEPLOY", marker: "FORGE:GATE_FAILURE", ciFailing: 2, ciPendingOnly: true }, lines: [] } });
|
|
299
|
+
const r = await fixStep(ctx(s, { review: { result: { ...failed, blocking: [], filed: [], ciFailing: 3, ciPendingOnly: true } } }));
|
|
300
|
+
assert.match(r.reason, /still pending/);
|
|
301
|
+
assert.equal(s.log.filter((e) => e[0] === "summary").length, 1);
|
|
302
|
+
});
|
|
303
|
+
|
|
304
|
+
it("#5912: nothing pending and nothing failed names the verdict and never says still pending", async () => {
|
|
305
|
+
const s = fakeSeam({ summary: { code: 0, data: { verdict: "BLOCK DEPLOY", marker: "FORGE:GATE_FAILURE", ciFailing: 0 }, lines: [] } });
|
|
306
|
+
const r = await fixStep(ctx(s, { review: { result: { ...failed, blocking: [], filed: [], ciFailing: 0 } } }));
|
|
307
|
+
assert.match(r.reason, /BLOCK DEPLOY \(FORGE:GATE_FAILURE\).*neither/);
|
|
308
|
+
assert.doesNotMatch(r.reason, /still pending/);
|
|
309
|
+
});
|
|
310
|
+
|
|
311
|
+
it("#5912: only forge/deploy-gate and the gate marker non-green gives zero blocking checks", () => {
|
|
312
|
+
const checks = [{ name: "build", bucket: "pass" }, { name: "forge/deploy-gate", bucket: "fail" }, { name: "Check for FORGE gate markers", bucket: "pending" }];
|
|
313
|
+
assert.equal(classifyChecks(checks, ["build"]).blocking, 0);
|
|
314
|
+
assert.deepEqual(cancelOnlyChecks(checks, ["build"]), []);
|
|
315
|
+
});
|
|
316
|
+
|
|
277
317
|
it("blocks when the verdict is not a pass but there is nothing to fix", async () => {
|
|
278
|
-
assert.match((await fixStep(ctx(fakeSeam(), { review: { result: { ...failed, blocking: [], ciFailing: 0 } } }))).reason, /nothing to fix|neither/);
|
|
318
|
+
assert.match((await fixStep(ctx(Object.assign(fakeSeam(), { summary: async () => ({ code: 0, data: { verdict: "BLOCK DEPLOY", marker: "FORGE:GATE_FAILURE", ciFailing: 0 }, lines: [] }) }), { review: { result: { ...failed, blocking: [], ciFailing: 0 } } }))).reason, /nothing to fix|neither/);
|
|
279
319
|
});
|
|
280
320
|
});
|
|
281
321
|
|
|
@@ -5,7 +5,7 @@ import { writeFileSync } from "node:fs";
|
|
|
5
5
|
import { tmpDir } from "../tests/_tmp.mjs";
|
|
6
6
|
import { join } from "node:path";
|
|
7
7
|
import assert from "node:assert/strict";
|
|
8
|
-
import { releaseFromCli, gateState } from "./release.mjs";
|
|
8
|
+
import { releaseFromCli, withStubs, gateState } from "./release.mjs";
|
|
9
9
|
import { controlFromCli, VERBS } from "./release-control.mjs";
|
|
10
10
|
import { CONTROL_VERBS, collectStatus, renderReleaseStatus, watchStatus, explainIssue, explainPr, renderExplain, parseNextAction, policyFromYaml, registerPlannerRule, PLANNER_RULES } from "./release-status.mjs";
|
|
11
11
|
|
|
@@ -228,4 +228,56 @@ describe("release status / explain (#5554)", () => {
|
|
|
228
228
|
await assert.rejects(run(["status", "--watch", "--interval", "0", "--repo", REPO]), /positive number/);
|
|
229
229
|
await assert.rejects(releaseFromCli(["status", "--bogus"], { io: fakeIo() }), /unknown option --bogus/);
|
|
230
230
|
});
|
|
231
|
+
|
|
232
|
+
it("#5848: `release --merge --watch` without a valid release.yaml prints the reason and check-config hint, exits 1, shows no older record", async () => {
|
|
233
|
+
const io = fakeIo({ state: { ...STATE, status: "refused" } });
|
|
234
|
+
const code = await releaseFromCli(["--merge", "--watch", "--repo", REPO], { io, cwd: managedDir, env: { FORGEDOCK_RELEASE_DIR: join(managedDir, "rel") }, deps: {} });
|
|
235
|
+
const out = io.printed.join("\n");
|
|
236
|
+
assert.equal(code, 1);
|
|
237
|
+
assert.match(out, /refused: no valid \.forge\/release\.yaml.*check-config/);
|
|
238
|
+
assert.ok(!out.includes(ID), out);
|
|
239
|
+
});
|
|
240
|
+
it("#5848: plain `release --merge` without a valid release.yaml also refuses with the check-config hint and exits 1", async () => {
|
|
241
|
+
const io = fakeIo({ state: { ...STATE, status: "refused" } });
|
|
242
|
+
const code = await releaseFromCli(["--merge", "--repo", REPO], { io, cwd: managedDir, env: { FORGEDOCK_RELEASE_DIR: join(managedDir, "rel") }, deps: {} });
|
|
243
|
+
const out = io.printed.join("\n");
|
|
244
|
+
assert.equal(code, 1);
|
|
245
|
+
assert.match(out, /check-config/);
|
|
246
|
+
assert.ok(!out.includes(ID), out);
|
|
247
|
+
});
|
|
248
|
+
|
|
249
|
+
it("#5848: `release --merge --watch` with a valid release.yaml prints only the record this start created", async () => {
|
|
250
|
+
const io = fakeIo({ state: { ...STATE, status: "refused" }, active: { lease: null, holds: [] } });
|
|
251
|
+
const policy = "schema: 1\nbranches: {default: main, integration: staging}\nunits:\n api: {paths: [\"services/api/**\"], criticality: high}\nlanes:\n release: {pipeline: full, ci_tier: T3, base: integration}\ndeploy:\n pipelines:\n full: {workflow: deploy.yml, trigger: push, wait: true}\nci:\n tiers: {T3: {jobs: [e2e]}}\n";
|
|
252
|
+
io.git = (a) => { if (String(a[1]).endsWith(".forge/release.yaml")) return policy; throw new Error("git"); };
|
|
253
|
+
io.now = () => Date.UTC(2026, 10, 20, 1, 2, 3);
|
|
254
|
+
io.runningLanes = async () => [];
|
|
255
|
+
const refs = {}, commits = {}, trees = {}; // an in-memory git ledger: what this start writes is what the watch reads
|
|
256
|
+
const miss = () => Object.assign(new Error("HTTP 404"), { status: 404 });
|
|
257
|
+
io.api = async (m, p, body) => {
|
|
258
|
+
const n = Object.keys(commits).length + 1;
|
|
259
|
+
if (m === "POST" && p.endsWith("/git/trees")) { trees[`t${n}`] = { ...(body.base_tree ? trees[body.base_tree] : {}), ...Object.fromEntries(body.tree.map((f) => [f.path, f.content])) }; return { sha: `t${n}` }; }
|
|
260
|
+
if (m === "POST" && p.endsWith("/git/commits")) { commits[`c${n}`] = body.tree; return { sha: `c${n}` }; }
|
|
261
|
+
if (m === "POST" && p.endsWith("/git/refs")) { const br = body.ref.replace("refs/heads/", ""); if (refs[br]) throw Object.assign(new Error("HTTP 422"), { status: 422 }); refs[br] = body.sha; return {}; }
|
|
262
|
+
if (m === "PATCH") { refs[/git\/refs\/heads\/(.+)$/.exec(p)[1]] = body.sha; return {}; }
|
|
263
|
+
if (m !== "GET") return {};
|
|
264
|
+
let r;
|
|
265
|
+
if ((r = /git\/commits\/(.+)$/.exec(p))) return { tree: { sha: commits[r[1]] } };
|
|
266
|
+
if ((r = /git\/ref\/heads\/(.+)$/.exec(p))) { if (!refs[r[1]]) throw miss(); return { object: { sha: refs[r[1]] } }; }
|
|
267
|
+
if ((r = /git\/matching-refs\/heads\/(.*)$/.exec(p))) return Object.keys(refs).filter((b) => b.startsWith(r[1])).map((b) => ({ ref: `refs/heads/${b}` }));
|
|
268
|
+
if ((r = /contents\/([^?]+)\?ref=(.+)$/.exec(p))) { const f = trees[commits[refs[decodeURIComponent(r[2])]]]?.[r[1]]; if (f === undefined) throw miss(); return { content: Buffer.from(f).toString("base64") }; }
|
|
269
|
+
throw miss();
|
|
270
|
+
};
|
|
271
|
+
const steps = { preflight: async () => ({ stopped: true, why: "stub stop" }) }; // the start ends non-terminal, so the watch begins
|
|
272
|
+
let polls = 0; io.sleep = async () => { if (++polls > 2) throw new Error("watch-ended"); }; // a stopped release never turns terminal: end the loop after a few polls
|
|
273
|
+
await assert.rejects(releaseFromCli(["--merge", "--watch", "--repo", REPO], { io, cwd: managedDir, env: { FORGEDOCK_RELEASE_DIR: join(managedDir, "rel2") }, steps: withStubs(steps) }), /watch-ended/);
|
|
274
|
+
const out = io.printed.join("\n");
|
|
275
|
+
const created = /release (r[\w-]+): stopped at preflight/.exec(out)?.[1];
|
|
276
|
+
assert.ok(created && created !== ID, out);
|
|
277
|
+
assert.ok(Object.keys(refs).includes(`forge-ledger/${created}`), "the start wrote its ledger");
|
|
278
|
+
const watched = io.printed.filter((l) => l.startsWith("status=") || /status=/.test(l)).map((l) => /\b(r\d{8}-[\w-]+)/.exec(l)?.[1]).filter(Boolean);
|
|
279
|
+
assert.ok(watched.length && watched.every((w) => w === created), out); // the watch shows the created release only
|
|
280
|
+
assert.ok(!out.includes(ID), out);
|
|
281
|
+
assert.doesNotMatch(out, /no valid \.forge\/release\.yaml/);
|
|
282
|
+
});
|
|
231
283
|
});
|
package/bin/lean/release.mjs
CHANGED
|
@@ -633,7 +633,7 @@ export async function releaseFromCli(argv, deps = {}) {
|
|
|
633
633
|
if (argv[0] === "control") throw new Error(`unknown control verb ${argv[1] ?? ""}; ${RELEASE_USAGE}`);
|
|
634
634
|
const unknown = argv.filter((a, i) => a.startsWith("--") && !["--repo", "--merge", "--watch", "--resume", "--lane", "--interval"].includes(a) && !(argv[i - 1] === "--resume" || argv[i - 1] === "--repo" || argv[i - 1] === "--lane" || argv[i - 1] === "--interval"));
|
|
635
635
|
if (unknown.length) throw new Error(`unknown option ${unknown[0]}; ${RELEASE_USAGE}`);
|
|
636
|
-
if (argv.includes("--watch")) { // the bare flag delegates to the status loop (#5554)
|
|
636
|
+
if (argv.includes("--watch") && !argv.includes("--merge")) { // the bare flag delegates to the status loop (#5554); `--merge` is a start (#5848)
|
|
637
637
|
const pick = (f) => (flag(argv, f) ? [f, flag(argv, f)] : []);
|
|
638
638
|
return statusCli(["status", ...(flag(argv, "--resume") ? [flag(argv, "--resume")] : []), "--watch", ...pick("--repo"), ...pick("--interval")], { io, cwd, env, deps });
|
|
639
639
|
}
|
|
@@ -656,6 +656,7 @@ export async function releaseFromCli(argv, deps = {}) {
|
|
|
656
656
|
const { conductorGuard } = await import("./release-conductor.mjs"); // #5564: a configured conductor must exist on the default branch
|
|
657
657
|
const noConductor = conductorGuard({ io, policy: pol, def: readBranches(cwd).default || "main" });
|
|
658
658
|
if (noConductor) { io.print(`release: refused: ${noConductor}`); return 1; }
|
|
659
|
+
if (!pol && !resume) { io.print("release: refused: no valid .forge/release.yaml on the default branch (run release check-config)"); return 1; } // #5848: same reason as `release plan`
|
|
659
660
|
config.policy = pol; config.fix = parseFixConfig(pol?.ci?.fix); // #5567: ci.fix.max_rounds / co_start / full_run_workflow
|
|
660
661
|
config.deployPipeline = pol?.lanes?.[flag(argv, "--lane")]?.pipeline ?? "full"; // service/hotfix lanes dispatch with unit inputs
|
|
661
662
|
if (pol?.verify) { // #5562: verification layers; risk class picks the soak minutes
|
|
@@ -674,11 +675,13 @@ export async function releaseFromCli(argv, deps = {}) {
|
|
|
674
675
|
try { io.print(await budgetReportLine({ cwd, repo, gh: (a) => io.gh(a), now: io.now(), release: since ? await releaseRuns({ gh: (a) => io.gh(a), repo, sinceMs: since }) : null })); } catch { /* best effort */ }
|
|
675
676
|
};
|
|
676
677
|
await budget(null);
|
|
677
|
-
const r = await runRelease({ io, repo, opts: { merge: argv.includes("--merge"), lane: flag(argv, "--lane") }, config, branches: readBranches(cwd), root, id, mounts: deps.mounts });
|
|
678
|
+
const r = await runRelease({ io, repo, opts: { merge: argv.includes("--merge"), lane: flag(argv, "--lane") }, config, branches: readBranches(cwd), root, id, mounts: deps.mounts, steps: deps.steps });
|
|
678
679
|
const line = r.status === "done" ? `release ${id}: done` : `release ${id}: ${r.status} at ${r.step}: ${r.reason} (resume: forgedock release --resume ${id})`;
|
|
679
680
|
io.print(line);
|
|
680
681
|
try { await budget(Date.parse(openRelease(root, id).load()?.startedAt) || null); } catch { /* best effort */ }
|
|
681
|
-
|
|
682
|
+
const code = r.status === "refused" ? 1 : r.status === "blocked" ? BLOCKED_EXIT : 0;
|
|
683
|
+
if (argv.includes("--watch") && code === 0 && r.status !== "done") return statusCli(["status", id, "--watch", "--repo", repo, ...(flag(argv, "--interval") ? ["--interval", flag(argv, "--interval")] : [])], { io, cwd, env, deps }); // #5848: watch the record this start created
|
|
684
|
+
return code;
|
|
682
685
|
}
|
|
683
686
|
|
|
684
687
|
/** `forgedock release verify <sha> [--repo R]`: exit 0 when the release head is the snapshot plus its recorded cherry-picks of staging commits, else 1. */
|
package/bin/lean/render.mjs
CHANGED
|
@@ -168,10 +168,15 @@ export function renderTestAdequacy(rows) {
|
|
|
168
168
|
export function renderReview(rv, contract, adequacy = null) {
|
|
169
169
|
const rows = contract.requirements.map((r) => {
|
|
170
170
|
const x = (rv.requirements ?? []).find((y) => y.id === r.id) ?? {};
|
|
171
|
+
if (r.disposition === "guidance") return `| ${esc(r.id)} | ${esc(`guidance (non-binding): ${r.why ?? ""}`)} | ${esc(x.note || x.evidence)} | |`; // #5750: stance and reason
|
|
171
172
|
const oob = r.verify === "out_of_band" ? ` (out of band${r.evidence ? `: ${r.evidence}` : ""})` : "";
|
|
172
173
|
return `| ${esc(r.id)} | ${oob ? esc(`${x.status ?? ""}${oob}`) : esc(x.status)}${r.tracked ? ` (tracked ${r.tracked})` : ""} | ${esc(x.evidence)} | ${esc(x.validated_by)} |`;
|
|
173
174
|
}).join("\n");
|
|
174
|
-
const
|
|
175
|
+
const guidance = contract.requirements.filter((r) => r.disposition === "guidance");
|
|
176
|
+
const guide = new Set(guidance.map((r) => r.id)), guideQuotes = new Set(guidance.map((r) => r.quote));
|
|
177
|
+
// #5750: guidance rows are non-binding, so they are not counted as covered issue requirements (matched by contract_ids, else by quote)
|
|
178
|
+
const isGuide = (c) => c.guidance === true || (Array.isArray(c.contract_ids) && c.contract_ids.length ? c.contract_ids.every((id) => guide.has(id)) : guideQuotes.has(c.quote));
|
|
179
|
+
const cov = (rv.issue_coverage ?? []).filter((c) => !isGuide(c));
|
|
175
180
|
return `## Conformance Review\n**Verdict:** CONFORMS (computed by the engine from the rows below)\n\n| Requirement | Status | Evidence | Validated by |\n| --- | --- | --- | --- |\n${rows}\n\n**Issue coverage:** ${cov.filter((c) => c.status === "covered").length}/${cov.length} issue requirement(s) covered by the contract\n**Scope:** ${(rv.scope ?? []).map((s) => `\`${escl(s.file)}\` ← ${escl(s.authorized_by)}`).join(", ") || NR}\n**Preserve:** ${(rv.preserve ?? []).map((p) => `${escl(p.id)} ${escl(p.status)}`).join(", ") || "none"}\n**Regressions:** none${renderTestAdequacy(adequacy)}\n\n**Notes:** ${escl(rv.summary)}`;
|
|
176
181
|
}
|
|
177
182
|
|
|
@@ -219,6 +219,12 @@ describe("remote adapter (#4254)", () => {
|
|
|
219
219
|
await assert.rejects(t504.launch({ id: "x" }), (e) => e.status === 504 && e.transient === true && e.retryable !== true && e.retryInSeconds === undefined);
|
|
220
220
|
});
|
|
221
221
|
|
|
222
|
+
it("#5957 httpTransport: a disk-paused sandbox (#5891) is still running, never exited", async () => {
|
|
223
|
+
const t = (state) => httpTransport({ endpoint: "https://pool.example", token: TOKEN, fetchFn: async () => ({ status: 200, ok: true, text: async () => JSON.stringify({ state }), headers: { get: () => null } }) });
|
|
224
|
+
assert.equal(await t("paused").status("x"), "running");
|
|
225
|
+
assert.equal(await t("exited").status("x"), "exited");
|
|
226
|
+
});
|
|
227
|
+
|
|
222
228
|
it("#5053 httpTransport: a 401 on status is transient and names its hop; a launch 401 is not transient", async () => {
|
|
223
229
|
const reply = (status, body) => ({ status, ok: status < 300, text: async () => JSON.stringify(body), headers: { get: () => null } });
|
|
224
230
|
const t = httpTransport({ endpoint: "https://pool.example", token: TOKEN, fetchFn: async () => reply(401, { error: "unauthorized", hop: "agent", agent: "a1", reason: "agent auth: router token rejected by agent" }) });
|
|
@@ -25,8 +25,11 @@ import { scopedEnv } from "./execution.mjs";
|
|
|
25
25
|
import { OUTCOME_CODES } from "../engine/outcome-codes.mjs";
|
|
26
26
|
import { laneEnvFor, readEnvSnapshots } from "../env/env.mjs";
|
|
27
27
|
import { resolveCredential } from "./credentials.mjs";
|
|
28
|
+
import { seedMirror } from "./mirror-bundle.mjs";
|
|
28
29
|
import { relayCommandNames, runRelayed, servicePending } from "./relay.mjs";
|
|
29
30
|
|
|
31
|
+
/** #5949: one log line for a launch's seed stats: bytes sent, and the time saved against shipping the whole repo at the same rate. */
|
|
32
|
+
const seedLine = (s) => (s.fallback ? `fell back to GitHub (${s.reason})` : s.upToDate ? "mirror already up to date, nothing sent" : `${s.full ? "full" : "incremental"} bundle, ${s.bytes} bytes in ${s.chunks} chunks, ${s.ms} ms${Number.isFinite(s.saved_ms) ? `, about ${Math.round(s.saved_ms / 1000)} s saved` : ""}`);
|
|
30
33
|
const REDACTED = "[redacted]";
|
|
31
34
|
const PREFETCH_MAX_B64 = 96 * 1024; // one env string stays under Linux MAX_ARG_STRLEN (128 KB)
|
|
32
35
|
/** Replace every value of `secrets` (4+ chars, longest first) in `text`. */
|
|
@@ -92,10 +95,10 @@ export function httpTransport({ endpoint, token = null, fetchFn = globalThis.fet
|
|
|
92
95
|
if (r.status === 404) return "gone";
|
|
93
96
|
if (!r.ok) throw Object.assign(fail("status", r), r.status === 401 ? { transient: true } : {}); // #5053: the sandbox launched, so a 401 is retried like an unreachable pool
|
|
94
97
|
const s = String(r.data?.state ?? "");
|
|
95
|
-
return s === "running" || s === "pending" || s === "starting" ? "running" : s === "gone" ? "gone" : "exited";
|
|
98
|
+
return s === "running" || s === "pending" || s === "starting" || s === "paused" ? "running" : s === "gone" ? "gone" : "exited";
|
|
96
99
|
},
|
|
97
100
|
async logs(id, cursor = 0) { const r = await call("GET", `${p(id)}/logs?cursor=${encodeURIComponent(cursor)}`); return r.ok ? { text: String(r.data?.text ?? ""), cursor: r.data?.cursor ?? cursor } : { text: "", cursor }; },
|
|
98
|
-
async result(id) { const r = await call("GET", `${p(id)}/result`); if (r.status === 401) throw Object.assign(fail("result", r), { transient: true }); if (r.ok && r.data?.drained === true) return { terminalReason: "deferred", code: OUTCOME_CODES.SANDBOX_CAPACITY, retryInSeconds: 60, cost_usd: 0, detail: `sandbox ${id} was drained to free capacity for reserved work (${String(r.data.reason ?? "").slice(0, 120)}); rescheduled` }; /* #5856 */ return r.ok && r.data && typeof r.data === "object" ? r.data : null; },
|
|
101
|
+
async result(id) { const r = await call("GET", `${p(id)}/result`); if (r.status === 401) throw Object.assign(fail("result", r), { transient: true }); if (r.ok && r.data?.disk_pressure === true) return { terminalReason: "deferred", code: OUTCOME_CODES.SANDBOX_DISK_PRESSURE, retryInSeconds: 120, cost_usd: 0, detail: `sandbox ${id} was stopped to save the host drive (disk pressure); worktree and volume kept, requeued to resume` }; /* #5891 */ if (r.ok && r.data?.drained === true) return { terminalReason: "deferred", code: OUTCOME_CODES.SANDBOX_CAPACITY, retryInSeconds: 60, cost_usd: 0, detail: `sandbox ${id} was drained to free capacity for reserved work (${String(r.data.reason ?? "").slice(0, 120)}); rescheduled` }; /* #5856 */ return r.ok && r.data && typeof r.data === "object" ? r.data : null; },
|
|
99
102
|
async usage(id) { const r = await call("GET", `${p(id)}/usage`); return r.ok && Number.isFinite(Number(r.data?.minutes)) ? { minutes: Number(r.data.minutes), ...(typeof r.data.agent === "string" && r.data.agent ? { agent: r.data.agent } : {}) } : null; }, // agent: #4549, optional
|
|
100
103
|
async stop(id) { const r = await call("POST", `${p(id)}/stop`); if (r.ok) return true; if (r.status === 404 || r.status === 405) return false; throw fail("stop", r); },
|
|
101
104
|
async destroy(id) { const r = await call("DELETE", p(id)); if (r.ok || r.status === 404) return true; throw fail("destroy", r); },
|
|
@@ -114,6 +117,30 @@ export function httpTransport({ endpoint, token = null, fetchFn = globalThis.fet
|
|
|
114
117
|
if (!Array.isArray(r.data?.agents)) throw new Error("agent disk: malformed router answer");
|
|
115
118
|
return r.data.agents.map((a) => ({ name: String(a?.name ?? "?"), disk_free_gb: Number.isFinite(a?.disk_free_gb) ? a.disk_free_gb : null }));
|
|
116
119
|
},
|
|
120
|
+
/** #5949: the agent mirror's ref tips for a repo ({mirrors: {slug: {ref: sha} | "absent"}, upload_offset?}); 404/405 = an older router/agent (unsupported). */
|
|
121
|
+
async mirrors(id, q) {
|
|
122
|
+
const r = await call("GET", `${p(id)}/mirrors?${new URLSearchParams(Object.entries(q).filter(([, v]) => v !== null && v !== undefined).map(([k, v]) => [k, String(v)]))}`);
|
|
123
|
+
if (r.status === 404 || r.status === 405) throw Object.assign(fail("mirrors", r), { unsupported: true });
|
|
124
|
+
if (!r.ok) throw fail("mirrors", r);
|
|
125
|
+
return r.data ?? {};
|
|
126
|
+
},
|
|
127
|
+
/** #5949: one bundle chunk or the finish call; a 409 carries the agent's resume offset. */
|
|
128
|
+
async seed(id, body) {
|
|
129
|
+
const r = await call("POST", `${p(id)}/seed`, body);
|
|
130
|
+
if (r.status === 404 || r.status === 405) throw Object.assign(fail("seed", r), { unsupported: true });
|
|
131
|
+
if (!r.ok) throw Object.assign(fail("seed", r), Number.isInteger(r.data?.offset) ? { offset: r.data.offset } : {});
|
|
132
|
+
return r.data ?? {};
|
|
133
|
+
},
|
|
134
|
+
/** #5735: lane sandboxes per pool agent (`GET /agents` -> `agents[].lanes {used, ceiling}`) and across all batches (`remote_lanes`; else the `fdrsbx-` keys of `sandboxes`). A bad answer throws. */
|
|
135
|
+
async agentLanes() {
|
|
136
|
+
const r = await call("GET", "/agents");
|
|
137
|
+
if (!r.ok) throw fail("agent lanes", r);
|
|
138
|
+
if (!Array.isArray(r.data?.agents)) throw new Error("agent lanes: malformed router answer");
|
|
139
|
+
const int = (v) => (Number.isInteger(v) && v >= 0 ? v : null);
|
|
140
|
+
const agents = r.data.agents.map((a) => ({ name: String(a?.name ?? "?"), used: int(a?.lanes?.used) ?? 0, ceiling: int(a?.lanes?.ceiling) }));
|
|
141
|
+
const sb = r.data.sandboxes && typeof r.data.sandboxes === "object" ? Object.keys(r.data.sandboxes) : [];
|
|
142
|
+
return { agents, total: int(r.data.remote_lanes) ?? sb.filter((id) => id.startsWith("fdrsbx-")).length };
|
|
143
|
+
},
|
|
117
144
|
async relayPending(id) { const r = await call("GET", `${p(id)}/relay`); return r.ok && Array.isArray(r.data?.requests) ? r.data.requests : []; },
|
|
118
145
|
async relayAnswer(id, rid, out) { const r = await call("POST", `${p(id)}/relay/${encodeURIComponent(rid)}`, out); if (!r.ok) throw fail("relay answer", r); return true; },
|
|
119
146
|
async capacity() {
|
|
@@ -243,8 +270,21 @@ export function remoteProvider({ batch, repo, settings = {}, name = "remote", tr
|
|
|
243
270
|
// #4912: a ready warm sandbox first; none, an error or a transport without claim is the cold start.
|
|
244
271
|
let claimed = null;
|
|
245
272
|
if (warm && typeof transport.claim === "function") { try { claimed = await transport.claim(spec); } catch { claimed = null; } }
|
|
273
|
+
// #5949: seed the pool agent's mirror from this host first (repo_source dispatcher|github|auto); failure falls back to GitHub, or fails under `dispatcher`.
|
|
274
|
+
let seed = null;
|
|
275
|
+
const source = ["dispatcher", "github"].includes(settings.repoSource) ? settings.repoSource : "auto";
|
|
276
|
+
if (!claimed && repo && settings.repoDir && source !== "github" && typeof transport.seed === "function") {
|
|
277
|
+
try { seed = await seedMirror({ transport, id, slug: repo, cacheKey: spec.cache?.key ?? repo, repoDir: settings.repoDir, now }); }
|
|
278
|
+
catch (e) {
|
|
279
|
+
if (source === "dispatcher") throw Object.assign(new Error(`repo seeding failed (repo_source=dispatcher): ${redact(e?.message ?? e, [...known]).slice(0, 200)}`), { code: "pool.seed_failed", transient: e?.transient === true });
|
|
280
|
+
seed = { sent: false, fallback: true, reason: redact(e?.message ?? e, [...known]).slice(0, 160) };
|
|
281
|
+
}
|
|
282
|
+
}
|
|
246
283
|
if (!claimed) await transport.launch(spec);
|
|
247
|
-
|
|
284
|
+
if (seed) {
|
|
285
|
+
try { const f = batch.logFile(issue); mkdirSync(dirname(f), { recursive: true }); appendFileSync(f, `[seed] ${seedLine(seed)}\n`); } catch { /* logging only */ }
|
|
286
|
+
}
|
|
287
|
+
return { provider: name, id, issue, startedAt, minutes: 0, ...(seed ? { seed } : {}) };
|
|
248
288
|
},
|
|
249
289
|
async status(h) {
|
|
250
290
|
let s;
|
package/bin/lean/sched.mjs
CHANGED
|
@@ -251,9 +251,26 @@ export function openSched(dir = schedDir(), { now = () => Date.now(), pid = proc
|
|
|
251
251
|
}
|
|
252
252
|
|
|
253
253
|
/** #4964: `sched show` lines for remote (pool) lanes and an unreachable pool; empty when there are none. */
|
|
254
|
-
export function remoteLines(st) {
|
|
255
|
-
|
|
254
|
+
export function remoteLines(st, { agentOf = null } = {}) {
|
|
255
|
+
// #5938: the registry entry can predate placement; the batch run record's placement names the agent once the sandbox is placed
|
|
256
|
+
const agent = (e) => { if (e.agent) return e.agent; try { return agentOf?.(e) ?? "-"; } catch { return "-"; } };
|
|
257
|
+
const out = (st?.remote ?? []).map((e) => ` remote #${e.issue} ${e.repo ?? "-"} batch ${e.batch ?? "-"} sandbox ${e.sandbox ?? "-"} agent ${agent(e)} dispatcher ${e.pid}`);
|
|
256
258
|
const down = st?.pool ?? [];
|
|
257
259
|
if (down.length) out.push(`pool: unreachable (${down.map((e) => `batch ${e.batch}${e.reason ? `: ${e.reason}` : ""}`).join("; ")})`);
|
|
258
260
|
return out;
|
|
259
261
|
}
|
|
262
|
+
|
|
263
|
+
/** #5847: batch-start report of the effective concurrency K, the host cap and which source set it; pure and read-only. */
|
|
264
|
+
export function describeConcurrency({ parallel, parallelFrom = "default", registryCap = null, globalParallel = null, derivedCap = null, yamlFound = true, cwd = "." } = {}) {
|
|
265
|
+
const pos = (n) => (Number.isInteger(n) && n > 0 ? n : null);
|
|
266
|
+
const [reg, glob, derived] = [pos(registryCap), pos(globalParallel), pos(derivedCap)];
|
|
267
|
+
let cap = null, source = "none";
|
|
268
|
+
if (reg !== null) { cap = reg; source = "forgedock sched cap"; }
|
|
269
|
+
else if (glob !== null && (derived === null || glob <= derived)) { cap = glob; source = "forge.yaml orchestration.global_parallel"; }
|
|
270
|
+
else if (derived !== null) { cap = derived; source = "host-derived limit"; }
|
|
271
|
+
const line = `concurrency: K=${parallel} (host cap ${cap ?? "none"} from ${source}) [K from ${parallelFrom}]`;
|
|
272
|
+
const warnings = [];
|
|
273
|
+
if (cap !== null && Number(parallel) > cap) warnings.push(`warning: K=${parallel} exceeds the host cap ${cap} (${source}); lanes beyond ${cap} queue. Raise it with: forgedock sched cap ${parallel}`);
|
|
274
|
+
if (!yamlFound) warnings.push(`warning: no forge.yaml in ${cwd}; defaults apply (global_parallel unset, host-derived admission limits)`);
|
|
275
|
+
return { line, warnings };
|
|
276
|
+
}
|
package/bin/lean/sched.test.mjs
CHANGED
|
@@ -5,7 +5,7 @@ import assert from "node:assert/strict";
|
|
|
5
5
|
import { writeFileSync } from "node:fs";
|
|
6
6
|
import { join } from "node:path";
|
|
7
7
|
import { tmpDir } from "../tests/_tmp.mjs";
|
|
8
|
-
import { grantOrder, openSched, priorityFromLabels, remoteLines } from "./sched.mjs";
|
|
8
|
+
import { describeConcurrency, grantOrder, openSched, priorityFromLabels, remoteLines } from "./sched.mjs";
|
|
9
9
|
import { orchestrate, estimateLaneMinutes, laneHistory, formatEstimateSummary, EST_DEFAULT_MIN, POST_DEPLOY_EST_MIN } from "./orchestrate.mjs";
|
|
10
10
|
import { schedFromCli } from "../engine-cli.mjs";
|
|
11
11
|
|
|
@@ -555,6 +555,13 @@ describe("sched show lists remote (pool) lanes (#4964)", () => {
|
|
|
555
555
|
assert.deepEqual(remoteLines({}), []);
|
|
556
556
|
});
|
|
557
557
|
|
|
558
|
+
it("#5938: a placed remote lane shows its agent name, from the registry or the batch run record; `-` only when neither knows it", () => {
|
|
559
|
+
const e = { issue: 7, repo: "o/r", batch: "B", sandbox: "sb1", pid: 9 };
|
|
560
|
+
assert.match(remoteLines({ remote: [{ ...e, agent: "legion" }] })[0], /agent legion /);
|
|
561
|
+
assert.match(remoteLines({ remote: [e] }, { agentOf: () => "atlas" })[0], /agent atlas /);
|
|
562
|
+
assert.match(remoteLines({ remote: [e] }, { agentOf: () => { throw new Error("no batch"); } })[0], /agent - /);
|
|
563
|
+
});
|
|
564
|
+
|
|
558
565
|
it("orchestrate publishes a remote lane while it runs, drops it after, and never acquires a slot", async () => {
|
|
559
566
|
const { handle } = world();
|
|
560
567
|
const reg = handle(531);
|
|
@@ -569,3 +576,28 @@ describe("sched show lists remote (pool) lanes (#4964)", () => {
|
|
|
569
576
|
assert.equal(reg.list().remote.length, 0);
|
|
570
577
|
});
|
|
571
578
|
});
|
|
579
|
+
|
|
580
|
+
describe("describeConcurrency", () => {
|
|
581
|
+
it("describeConcurrency line format", () => {
|
|
582
|
+
const r = describeConcurrency({ parallel: 6, parallelFrom: "--parallel", registryCap: 2 });
|
|
583
|
+
assert.equal(r.line, "concurrency: K=6 (host cap 2 from forgedock sched cap) [K from --parallel]");
|
|
584
|
+
});
|
|
585
|
+
it("describeConcurrency reports K, cap and source", () => {
|
|
586
|
+
assert.match(describeConcurrency({ parallel: 2, globalParallel: 3 }).line, /host cap 3 from forge\.yaml orchestration\.global_parallel/);
|
|
587
|
+
assert.match(describeConcurrency({ parallel: 2, globalParallel: 5, derivedCap: 4 }).line, /host cap 4 from host-derived limit/);
|
|
588
|
+
const none = describeConcurrency({ parallel: 2 });
|
|
589
|
+
assert.match(none.line, /host cap none from none/);
|
|
590
|
+
assert.deepEqual(none.warnings, []);
|
|
591
|
+
});
|
|
592
|
+
it("describeConcurrency warns when K exceeds cap", () => {
|
|
593
|
+
const r = describeConcurrency({ parallel: 6, registryCap: 2 });
|
|
594
|
+
assert.equal(r.warnings.length, 1);
|
|
595
|
+
assert.match(r.warnings[0], /forgedock sched cap 6/);
|
|
596
|
+
assert.deepEqual(describeConcurrency({ parallel: 2, registryCap: 2 }).warnings, []);
|
|
597
|
+
});
|
|
598
|
+
it("describeConcurrency warns when forge.yaml is missing", () => {
|
|
599
|
+
const r = describeConcurrency({ parallel: 1, yamlFound: false, cwd: "/x" });
|
|
600
|
+
assert.match(r.warnings[0], /no forge\.yaml in \/x; defaults apply/);
|
|
601
|
+
assert.deepEqual(describeConcurrency({ parallel: 1 }).warnings, []);
|
|
602
|
+
});
|
|
603
|
+
});
|
|
@@ -55,8 +55,9 @@ export function tickText(c) {
|
|
|
55
55
|
* @returns the check, plus `killed` (and `started` when it started one)
|
|
56
56
|
*/
|
|
57
57
|
export async function watchdog({ dir = schedDir(), stallMs = STALL_MS, now = () => Date.now(), alive = pidAlive, kill = (p, s) => process.kill(p, s),
|
|
58
|
-
sleep = (ms) => new Promise((r) => setTimeout(r, ms)), graceMs = KILL_GRACE_MS, log = (m) => console.log(m), unfinished = () => [], start = null } = {}) {
|
|
58
|
+
sleep = (ms) => new Promise((r) => setTimeout(r, ms)), graceMs = KILL_GRACE_MS, log = (m) => console.log(m), unfinished = () => [], start = null, batchVerdicts = null } = {}) {
|
|
59
59
|
const c = stallCheck({ dir, stallMs, now, alive });
|
|
60
|
+
if (batchVerdicts) { try { for (const l of batchVerdicts() ?? []) log(`schedd watchdog: ${l}`); } catch { /* advisory */ } } // #5938: one verdict line per batch
|
|
60
61
|
if (c.status === "down" && start) {
|
|
61
62
|
let ids = [];
|
|
62
63
|
try { ids = unfinished() ?? []; } catch { ids = []; }
|
|
@@ -57,6 +57,13 @@ describe("schedd heartbeat and watchdog (#4780)", () => {
|
|
|
57
57
|
assert.match(lines.at(-1), /start failed: no unit/);
|
|
58
58
|
});
|
|
59
59
|
|
|
60
|
+
it("#5938: the watchdog logs one verdict line per batch and leaves the heartbeat behaviour alone", async () => {
|
|
61
|
+
const dir = tmpDir("hb-verdict-"), lines = [];
|
|
62
|
+
const r = await watchdog({ dir, now: () => 0, alive: () => false, log: (m) => lines.push(m), batchVerdicts: () => ["batch b1: healthy", "batch b2: stalled -> no action, needs you (x)"] });
|
|
63
|
+
assert.equal(r.status, "down");
|
|
64
|
+
assert.deepEqual(lines, ["schedd watchdog: batch b1: healthy", "schedd watchdog: batch b2: stalled -> no action, needs you (x)"]);
|
|
65
|
+
});
|
|
66
|
+
|
|
60
67
|
it("bestEffortRenice never throws", () => {
|
|
61
68
|
assert.equal(bestEffortRenice(() => { throw new Error("EACCES"); }), false);
|
|
62
69
|
assert.equal(bestEffortRenice(() => {}), true);
|
package/bin/lean/schedd.mjs
CHANGED
|
@@ -11,6 +11,7 @@
|
|
|
11
11
|
* {op:"attach", id, resume?} → (`resume` also clears a pending cancel, #4592) log.jsonl rows replayed, then live rows/lines and done; a finished batch replays report.json
|
|
12
12
|
* ({type:"done", replay:true}) unless it has unrun added issues; a batch nobody hosts is resumed here
|
|
13
13
|
* {op:"set-parallel", id, k} → {type:"ok", parallel}
|
|
14
|
+
* {op:"clear-breaker", id} → {type:"ok", cleared, acknowledged, hosted} (#5947): a hosted runner resets its in-memory breaker (request file + ack, #5964: the request is never dropped; no ack within waitMs → pending:true); otherwise state.json is rewritten
|
|
14
15
|
* {op:"set-execution", id, maxRemote?, mode?} → {type:"ok", execution} (#5138): live max_remote / placement (remote|hybrid|local); remote/hybrid refused for a batch with no provider
|
|
15
16
|
* {op:"requeue", id, issues, reason, by} → {type:"ok", requeued, refused, hosted, reopened} (#4550): see batch.requeue; a finished batch is hosted again
|
|
16
17
|
* {op:"add", id, issues} → {type:"ok", added, skipped, hosted} (#4408): merged into the batch's `add` file, which a
|
|
@@ -41,7 +42,7 @@
|
|
|
41
42
|
* `interrupted: upgrade vX→vY` row (orchestrate.mjs).
|
|
42
43
|
* `runBatch({argv, cwd, env, sink, keepBreaker, signal})` is injected (engine-cli `runBatch`); `sink` gets `batch(b)`, `row(r)`, `line(text)`.
|
|
43
44
|
*/
|
|
44
|
-
import { closeSync, existsSync, mkdirSync, openSync, readFileSync, rmSync, writeSync } from "node:fs";
|
|
45
|
+
import { closeSync, existsSync, mkdirSync, openSync, readFileSync, rmSync, statSync, writeSync } from "node:fs";
|
|
45
46
|
import { createConnection, createServer } from "node:net";
|
|
46
47
|
import { execFileSync, spawn } from "node:child_process";
|
|
47
48
|
import { homedir, tmpdir } from "node:os";
|
|
@@ -49,7 +50,7 @@ import { createHash } from "node:crypto";
|
|
|
49
50
|
import { delimiter, join, resolve } from "node:path";
|
|
50
51
|
import { fileURLToPath } from "node:url";
|
|
51
52
|
import { schedDir, pidAlive } from "./sched.mjs";
|
|
52
|
-
import { DEFAULT_STALL_MIN, FIRST_HOUR_FILE, FIRST_HOUR_MIN, decideStallAction, evaluateDispatchStall, firstHourReport, readHealth, recordStallAlert, recordStallRecovery, writeFirstHour } from "./batch-health.mjs";
|
|
53
|
+
import { DEFAULT_STALL_MIN, FIRST_HOUR_FILE, FIRST_HOUR_MIN, batchVerdict, clearStaleStall, decideStallAction, evaluateDispatchStall, firstHourReport, readHealth, recordStallAlert, recordStallRecovery, runningSplit, writeFirstHour } from "./batch-health.mjs";
|
|
53
54
|
import { probeBatchEnv } from "./lanecheck.mjs";
|
|
54
55
|
import { HEARTBEAT_MS, writeHeartbeat, clearHeartbeat } from "./schedd-health.mjs";
|
|
55
56
|
import { batchRoot, listBatches, openBatch, SECRET_ENV } from "./batch.mjs";
|
|
@@ -57,6 +58,28 @@ import { killTrackedChildren } from "./effects.mjs";
|
|
|
57
58
|
import { applySetExecution } from "./live-execution.mjs";
|
|
58
59
|
import { liveOverload } from "./hostload.mjs";
|
|
59
60
|
|
|
61
|
+
/** #5938: epoch ms of the newest lane log of a running issue (a lane heartbeat), or null. */
|
|
62
|
+
export function lanesAlive(b, state) {
|
|
63
|
+
let best = null;
|
|
64
|
+
for (const n of Object.keys(state?.running ?? {})) { try { const m = statSync(b.logFile(n)).mtimeMs; if (best === null || m > best) best = m; } catch { /* no lane log yet */ } }
|
|
65
|
+
return best;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** #5938: one verdict line per unfinished daemon batch (offline, from saved state): healthy, stalled -> action, or stalled -> no action. */
|
|
69
|
+
export function batchVerdicts(root, { now = Date.now(), windowMin = DEFAULT_STALL_MIN } = {}) {
|
|
70
|
+
const out = [];
|
|
71
|
+
for (const id of listBatches(root)) {
|
|
72
|
+
try {
|
|
73
|
+
const b = openBatch(root, id);
|
|
74
|
+
if (!b.readPlan()?.daemon || b.isTerminal()) continue;
|
|
75
|
+
const state = b.store.peek(), stall = evaluateDispatchStall(state, { held: b.readHeld(), parallel: b.readParallel(), hosted: false, lastProgressMs: b.lastProgressMs(), now, windowMin, lanesAliveMs: lanesAlive(b, state) });
|
|
76
|
+
const decision = stall ? decideStallAction(stall, { recovery: readHealth(b.dir)?.stallRecovery ?? null, hosted: false }) : null;
|
|
77
|
+
out.push(batchVerdict(id, stall, decision));
|
|
78
|
+
} catch { /* one unreadable batch has no verdict */ }
|
|
79
|
+
}
|
|
80
|
+
return out;
|
|
81
|
+
}
|
|
82
|
+
|
|
60
83
|
/** #5471: `schedd status` warning lines for issues pending in two or more hosted batches. */
|
|
61
84
|
export function sharedPendingLines(batches) {
|
|
62
85
|
const shared = new Map();
|
|
@@ -310,10 +333,14 @@ export async function startDaemon({ dir = schedDir(), runBatch, idleMs = Number(
|
|
|
310
333
|
for (const id of [...ids].sort()) {
|
|
311
334
|
await yieldLoop();
|
|
312
335
|
const isHosted = hosted.has(id) || starting.has(id);
|
|
313
|
-
let last = null, pending = [], pend = [];
|
|
314
|
-
try {
|
|
336
|
+
let last = null, pending = [], pend = [], split = null, alive = null;
|
|
337
|
+
try {
|
|
338
|
+
const b = openBatch(root, id); last = b.lastProgressMs(); pending = b.unrunAdds(); pend = b.pendingIssues();
|
|
339
|
+
const st = b.store.peek(); split = runningSplit(st, b.readParallel());
|
|
340
|
+
alive = lanesAlive(b, st); // #5938: lane output is a heartbeat
|
|
341
|
+
} catch { /* a half-written batch */ }
|
|
315
342
|
if (!isHosted && !pending.length) continue;
|
|
316
|
-
out.push({ id, running: isHosted, lastProgressAt: last === null ? null : new Date(last).toISOString(), lastProgressAgeSec: last === null ? null : Math.max(0, Math.round((now - last) / 1000)), pendingAdds: pending, pending: pend });
|
|
343
|
+
out.push({ id, running: isHosted, lastProgressAt: last === null ? null : new Date(last).toISOString(), lastProgressAgeSec: last === null ? null : Math.max(0, Math.round((now - last) / 1000)), ...(split ? { lanes: { running: split.running, k: split.k, local: split.local, remote: split.remote } } : {}), lanesAliveAgeSec: alive === null ? null : Math.max(0, Math.round((now - alive) / 1000)), pendingAdds: pending, pending: pend });
|
|
317
344
|
}
|
|
318
345
|
return out;
|
|
319
346
|
};
|
|
@@ -335,6 +362,30 @@ export async function startDaemon({ dir = schedDir(), runBatch, idleMs = Number(
|
|
|
335
362
|
b.setParallel(Number(req.k));
|
|
336
363
|
return send({ type: "ok", parallel: Number(req.k) }, true);
|
|
337
364
|
}
|
|
365
|
+
if (req.op === "clear-breaker") {
|
|
366
|
+
// #5947: a hosted runner holds the breaker in memory; it consumes the request file and acks. An unhosted (or silent) batch gets the state.json rewrite.
|
|
367
|
+
const b = openBatch(root, req.id);
|
|
368
|
+
if (!b.exists()) throw new Error(`no batch ${req.id} in ${root}`);
|
|
369
|
+
const isHosted = hosted.has(req.id);
|
|
370
|
+
let acknowledged = false, cleared = false;
|
|
371
|
+
if (isHosted) {
|
|
372
|
+
const at = b.requestClearBreaker();
|
|
373
|
+
// #5964: never drop the request: the runner consumes it on its next pass (time-scoped against the trip)
|
|
374
|
+
const budget = Math.min(Number.isFinite(req.waitMs) && req.waitMs > 0 ? req.waitMs : 7000, 60000);
|
|
375
|
+
for (let i = 0, n = Math.ceil(budget / 50); i < n && !acknowledged; i++) {
|
|
376
|
+
const a = b.readClearBreakerAck();
|
|
377
|
+
if (a && a.at >= at) { acknowledged = true; cleared = Boolean(a.cleared); } else await new Promise((r) => setTimeout(r, 50));
|
|
378
|
+
}
|
|
379
|
+
if (!acknowledged) return send({ type: "ok", cleared: false, acknowledged: false, pending: true, hosted: true }, true);
|
|
380
|
+
}
|
|
381
|
+
if (!acknowledged) {
|
|
382
|
+
b.readClearBreaker(); // drop an unconsumed request so it cannot clear a later trip
|
|
383
|
+
const st = b.store.load();
|
|
384
|
+
cleared = Boolean(st?.breaker);
|
|
385
|
+
if (st) b.store.save({ ...st, breaker: null, errorTimes: [] });
|
|
386
|
+
}
|
|
387
|
+
return send({ type: "ok", cleared, acknowledged, hosted: isHosted }, true);
|
|
388
|
+
}
|
|
338
389
|
if (req.op === "set-execution") {
|
|
339
390
|
// #5138: live max_remote / placement mode; the hosted runner re-reads the batch's `execution` file on every admission.
|
|
340
391
|
const b = openBatch(root, req.id);
|
|
@@ -520,7 +571,7 @@ export async function startDaemon({ dir = schedDir(), runBatch, idleMs = Number(
|
|
|
520
571
|
const created = Date.parse(plan.created ?? "");
|
|
521
572
|
if (b.isTerminal() && (!Number.isFinite(created) || now - created >= 24 * 3600_000)) continue; // nothing left to report or re-host
|
|
522
573
|
const reported = !!b.readReport(), cancelled = !!b.readCancel(), state = b.store.peek(), isHosted = hosted.has(id) || starting.has(id);
|
|
523
|
-
const stallOpts = { held: b.readHeld(), parallel: b.readParallel(), hosted: isHosted, lastProgressMs: b.lastProgressMs(), now, windowMin: stallMin, cancelled, reported };
|
|
574
|
+
const stallOpts = { held: b.readHeld(), parallel: b.readParallel(), hosted: isHosted, lastProgressMs: b.lastProgressMs(), now, windowMin: stallMin, cancelled, reported, lanesAliveMs: lanesAlive(b, state) };
|
|
524
575
|
let stall = evaluateDispatchStall(state, stallOpts);
|
|
525
576
|
if (stall && preflight) { // #5745: name the preflight gate holding admission (advisory; dispatch decisions are unchanged)
|
|
526
577
|
let gates = [];
|
|
@@ -538,7 +589,7 @@ export async function startDaemon({ dir = schedDir(), runBatch, idleMs = Number(
|
|
|
538
589
|
log(`schedd: batch ${id} abandoned (not hosted, ${state.pending.length} pending, no progress for ${Math.round((now - last) / 86400_000)} days)`);
|
|
539
590
|
continue;
|
|
540
591
|
}
|
|
541
|
-
if (!stall) continue;
|
|
592
|
+
if (!stall) { if (clearStaleStall(b, { now })) log(`schedd: batch ${id} STALL CLEARED`); continue; } // #5938: re-evaluated every tick; a stored stall that no longer holds is cleared
|
|
542
593
|
// #5806: the batch env is probed first (a PATH without gh/git/node stalls every resume the same way); the first stall of a
|
|
543
594
|
// ready set is recovered once (health.json stallRecovery survives a daemon restart), a repeat alerts with the probed cause.
|
|
544
595
|
let probe = null;
|