forgedock 1.65.0 → 1.67.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 +2 -0
- package/bin/engine/outcome-codes.mjs +1 -0
- package/bin/engine-cli.mjs +143 -19
- package/bin/forgedock.mjs +7 -0
- package/bin/help-text.mjs +3 -3
- package/bin/introspect-schedule.mjs +98 -0
- package/bin/introspect-schedule.test.mjs +67 -0
- package/bin/lean/advisory.test.mjs +49 -0
- package/bin/lean/amendment-schema.mjs +31 -0
- package/bin/lean/attempts.mjs +159 -0
- package/bin/lean/attempts.test.mjs +127 -0
- package/bin/lean/basered.mjs +55 -0
- package/bin/lean/basered.test.mjs +68 -1
- package/bin/lean/batch-health.mjs +13 -5
- package/bin/lean/batch-health.test.mjs +16 -0
- package/bin/lean/batch.mjs +62 -0
- package/bin/lean/batch.test.mjs +119 -3
- package/bin/lean/capwait.mjs +14 -3
- package/bin/lean/capwait.test.mjs +20 -0
- package/bin/lean/clear-breaker.mjs +14 -0
- package/bin/lean/commentstate.mjs +41 -0
- package/bin/lean/commentstate.test.mjs +32 -0
- package/bin/lean/concurrency.mjs +89 -0
- package/bin/lean/concurrency.test.mjs +113 -0
- package/bin/lean/conformance.e2e.test.mjs +4 -2
- package/bin/lean/conformance.mjs +35 -3
- package/bin/lean/conformance.test.mjs +52 -0
- package/bin/lean/depcache.mjs +9 -0
- package/bin/lean/efficiency.mjs +162 -0
- package/bin/lean/efficiency.test.mjs +79 -0
- package/bin/lean/execution.mjs +31 -13
- package/bin/lean/execution.test.mjs +46 -0
- package/bin/lean/failure-stop.mjs +46 -0
- package/bin/lean/failure-stop.test.mjs +45 -0
- package/bin/lean/fixtures/capacity-storm.json +609 -0
- package/bin/lean/lean.mjs +130 -30
- package/bin/lean/lean.test.mjs +138 -47
- package/bin/lean/liveness.mjs +37 -0
- package/bin/lean/liveness.test.mjs +33 -0
- package/bin/lean/orchestrate-attempts.test.mjs +74 -0
- package/bin/lean/orchestrate-envhold.test.mjs +17 -0
- package/bin/lean/orchestrate-pause.test.mjs +84 -0
- package/bin/lean/orchestrate-reconcile.test.mjs +147 -0
- package/bin/lean/orchestrate.mjs +202 -28
- package/bin/lean/phaseledger.mjs +6 -0
- package/bin/lean/phaseledger.test.mjs +13 -1
- package/bin/lean/prompts.mjs +6 -10
- package/bin/lean/reconcile.mjs +90 -0
- package/bin/lean/recurrence.mjs +38 -2
- package/bin/lean/recurrence.test.mjs +56 -1
- package/bin/lean/sandbox-remote.mjs +33 -2
- package/bin/lean/sched.mjs +19 -0
- package/bin/lean/sched.test.mjs +11 -1
- package/bin/lean/schedd-health.mjs +8 -1
- package/bin/lean/schedd-health.test.mjs +19 -0
- package/bin/lean/schedd.mjs +97 -10
- package/bin/lean/schedd.test.mjs +138 -1
- package/bin/lean/slo.mjs +126 -0
- package/bin/lean/slo.test.mjs +112 -0
- package/bin/lean/statuscomment.mjs +37 -0
- package/bin/lean/statuscomment.test.mjs +48 -1
- package/bin/lean/verify.mjs +2 -1
- package/bin/pool/agent.mjs +46 -8
- package/bin/pool/cache-sweep.mjs +41 -4
- package/bin/pool/cli.mjs +28 -1
- package/bin/pool/health.mjs +18 -0
- package/bin/pool/lane-tools.mjs +21 -0
- package/bin/pool/mirror-seed.mjs +21 -2
- package/bin/pool/router.mjs +6 -2
- package/bin/stats/attempts.mjs +54 -0
- package/bin/stats/attempts.test.mjs +30 -0
- package/bin/stats/churn.mjs +49 -0
- package/bin/stats/churn.test.mjs +31 -0
- package/bin/stats/index.mjs +11 -3
- package/commands/orchestrate.md +21 -18
- package/docs/CONFIG.md +1 -0
- package/docs/OUTCOME-CODES.md +1 -0
- package/package.json +1 -1
- package/pool/image/entrypoint.sh +2 -1
- package/scripts/check-devdocs-freshness.sh +1 -1
package/bin/config-schema.mjs
CHANGED
|
@@ -45,6 +45,8 @@ export const TYPES = {
|
|
|
45
45
|
"verification.ci_local.max_parallel": "number",
|
|
46
46
|
"orchestration.merge_train": { enum: ["off", "on"] }, // #5836: lanes end pr-ready and the batch merge train merges (default off)
|
|
47
47
|
"orchestration.merge_train_batch": "posint", // #5837: up to N green PRs of one base validated together on a candidate ref (default 4)
|
|
48
|
+
"orchestration.max_attempts_per_issue": "posint", // #5986: lifetime lanes per issue before one FORGE:ESCALATION (default 4)
|
|
49
|
+
"orchestration.max_identical_signature": "posint", // #5986: identical failure signatures tolerated per issue (default 2)
|
|
48
50
|
"env.snapshots.enabled": "bool",
|
|
49
51
|
"env.snapshots.store": { enum: ["local", "oci"] },
|
|
50
52
|
"env.snapshots.keep": "number",
|
|
@@ -101,6 +101,7 @@ export const OUTCOME_CODES = Object.freeze({
|
|
|
101
101
|
CONFORMANCE_UNIMPLEMENTED: "conformance.unimplemented",
|
|
102
102
|
CONFORMANCE_E2E_UNVERIFIED: "conformance.e2e_unverified",
|
|
103
103
|
CONFORMANCE_SCOPE_CREEP: "conformance.scope_creep",
|
|
104
|
+
FAILURE_REPEATED: "failure.repeated", // #5979: the same failure twice; parked, never recovered (kept out of RECOVERABLE_CODES)
|
|
104
105
|
CONFORMANCE_UNTRACKED_DEFERRAL: "conformance.untracked_deferral",
|
|
105
106
|
CONFORMANCE_UNJUSTIFIED_DEFERRAL: "conformance.unjustified_deferral",
|
|
106
107
|
CONFORMANCE_PRESERVE_VIOLATED: "conformance.preserve_violated",
|
package/bin/engine-cli.mjs
CHANGED
|
@@ -24,6 +24,7 @@ import { memAvailableMb } from "./lean/heavy.mjs";
|
|
|
24
24
|
import { liveOverload, formatOverload, formatHostLoad } from "./lean/hostload.mjs";
|
|
25
25
|
import { join, resolve as resolvePath } from "node:path";
|
|
26
26
|
import { runIssue, DEFAULT_MAX_ATTEMPTS, sanitizeLeaseHost, ENGINE_VERSION } from "./engine.mjs";
|
|
27
|
+
import { sandboxBudgetKey } from "./lean/liveness.mjs";
|
|
27
28
|
import { makeProjector } from "./engine/projector.mjs";
|
|
28
29
|
import { decomposedSubissues, isDecomposedRecord, isTrustedActor, parseDependsOn } from "./engine/phases.mjs";
|
|
29
30
|
import { readLog, readLogFile, deriveState, runLogPath, migrateRunLogs, attachRunLog } from "./engine/runlog.mjs";
|
|
@@ -52,6 +53,7 @@ import { parseCiPrecheckConfig } from "./lean/ci-precheck.mjs";
|
|
|
52
53
|
import { OUTCOME_CODES } from "./engine/outcome-codes.mjs";
|
|
53
54
|
import { USER_ERRORS } from "./help-text.mjs";
|
|
54
55
|
import * as batchHealth from "./lean/batch-health.mjs";
|
|
56
|
+
import { makeAttemptsSeam } from "./lean/attempts.mjs";
|
|
55
57
|
import * as _autoChildren from "./lean/autochildren.mjs";
|
|
56
58
|
|
|
57
59
|
/**
|
|
@@ -497,10 +499,11 @@ export function readVerify(cwd = process.cwd()) {
|
|
|
497
499
|
return coerceCiVerify(parseVerify({ ...sec, ...(invariants ? { invariants } : {}), ...(flaky ? { flaky } : {}), ...(guard_command ? { guard_command } : {}), ...(baselines ? { baselines } : {}), ...(sandboxes ? { sandboxes } : {}) }), { cwd }); // #5278: local-first never pushes for paid CI before review
|
|
498
500
|
} catch { return undefined; }
|
|
499
501
|
}
|
|
500
|
-
/** #4542: forge.yaml `execution.host_capabilities` (+ patterns) for a lane's remote-block mapping
|
|
502
|
+
/** #4542: forge.yaml `execution.host_capabilities` (+ patterns) for a lane's remote-block mapping, plus `offload_wrappers`; undefined when none are declared. */
|
|
501
503
|
export function readHostCaps(cwd = process.cwd()) {
|
|
502
504
|
const e = readExecution(cwd);
|
|
503
|
-
|
|
505
|
+
if (!e?.hostCapabilities?.length && !e?.offloadWrappers?.length) return undefined;
|
|
506
|
+
return { hostCapabilities: e.hostCapabilities ?? [], ...(e.hostCapabilityPatterns ? { hostCapabilityPatterns: e.hostCapabilityPatterns } : {}), ...(e.offloadWrappers ? { offloadWrappers: e.offloadWrappers } : {}) };
|
|
504
507
|
}
|
|
505
508
|
/** #4778: the capabilities the dispatching host relays to this sandbox lane (`CS_RELAY_CAPS`, set by the remote provider); `{}` when none. */
|
|
506
509
|
export function readRelayCaps(env = process.env) {
|
|
@@ -1132,10 +1135,12 @@ export async function runFromCli(argv, deps = {}) {
|
|
|
1132
1135
|
for (const [sig, f] of Object.entries(handlers)) on(sig, f);
|
|
1133
1136
|
const env = deps.env ?? process.env;
|
|
1134
1137
|
let lres;
|
|
1138
|
+
// #5991: on the batch's own host a lease of another batch that no longer owns the issue is taken over at once; a sandbox has no batch dir, so it is unknown there
|
|
1139
|
+
const liveBatches = env.FORGEDOCK_BATCH_ID ? await import("./lean/batch.mjs").then((bm) => { const root = bm.batchRoot(env); return (n) => (bm.listBatches(root).includes(env.FORGEDOCK_BATCH_ID) ? bm.batchesOwning(root, leanRepo, n, { exceptId: env.FORGEDOCK_BATCH_ID }).filter((b) => !b.cancelled).map((b) => b.id) : null); }).catch(() => null) : null;
|
|
1135
1140
|
try {
|
|
1136
1141
|
lres = await runCore({ issue, repo: leanRepo, deferPostRun: true, ...(adopt ? { adopt: true } : {}), ...(lane ? { lane } : {}), laneOverride, branches: readBranches(), cwd: process.cwd(), dir, io: leanIo, path: enginePath, onProgress,
|
|
1137
1142
|
...(rotatorKind({ execution: readExecution(process.cwd()), env }) ? { accountRotator: rotatorKind({ execution: readExecution(process.cwd()), env }) } : {}), // #5094, #5205: detected
|
|
1138
|
-
onTeardown: (fn) => { teardown = fn; }, ...(env.FORGEDOCK_BATCH_ID ? { batchId: env.FORGEDOCK_BATCH_ID } : {}), ...(placement ? { placement } : {}), ...(recover ? { recover } : {}), ...(plan ? { plan: true } : {}), ...(planned ? { planned } : {}), ...(stackedOn ? { stackedOn } : {}), ...(stackedOn ? { stackedOn } : {}),
|
|
1143
|
+
onTeardown: (fn) => { teardown = fn; }, ...(env.FORGEDOCK_BATCH_ID ? { batchId: env.FORGEDOCK_BATCH_ID } : {}), ...(liveBatches ? { liveBatches } : {}), ...(placement ? { placement } : {}), ...(recover ? { recover } : {}), ...(plan ? { plan: true } : {}), ...(planned ? { planned } : {}), ...(stackedOn ? { stackedOn } : {}), ...(stackedOn ? { stackedOn } : {}),
|
|
1139
1144
|
emitTelemetry: deps.emitTelemetry ?? composeEmit(makeEmitTelemetry({ repo: leanRepo }), makeEventEmitter({ repo: leanRepo, config: readEvents() }).emit),
|
|
1140
1145
|
admission: readAdmission(), heavy: readHeavy(), ...readCoreLimits(), ...readEnvConfig(), ...(readMergeWait() ? { mergeWait: readMergeWait() } : {}), ...(readConformanceMode() ? { conformance: readConformanceMode() } : {}), ...(readConformanceKinds() ? { conformanceKinds: readConformanceKinds() } : {}), ...(readConformanceMutation() ? { conformanceMutation: "report" } : {}), ...(readContextPack() ? { contextPack: readContextPack() } : {}), ...(readSequenceVersioned() ? { sequenceVersioned: readSequenceVersioned() } : {}), ...(readSharedSurfaces() ? { sharedSurfaces: readSharedSurfaces() } : {}), ...(readReviewIncomplete() ? { reviewIncomplete: readReviewIncomplete() } : {}), ...(readLaneInstructions() ? { laneInstructions: readLaneInstructions() } : {}), ...(readReproTest() ? { reproTest: readReproTest() } : {}), ...(readReproQuality() ? { reproQuality: readReproQuality() } : {}), ...(readExplore() ? { explore: readExplore() } : {}), ...(readExperiment() ? { experiment: readExperiment() } : {}), light: readLight(), ...(readCloseParent() ? { closeParent: true } : {}), ...(readOrchestration().mergeTrain === "on" ? { mergeTrain: "on" } : {}), ...(readReviewTrigger() ? { reviewTrigger: readReviewTrigger() } : {}), ...(readVerify() ? { verify: readVerify() } : {}), ...readPrecheckOptions(), ...(model ? { builderModel: model } : {}), ...(readLeanSetting("reviewer_model") ? { reviewerModel: readLeanSetting("reviewer_model") } : {}), ...(readFixModel() ? { fixModel: readFixModel() } : {}), ...(readBuilderRouting() ? { builderRouting: readBuilderRouting() } : {}), ...(readVerifier() ? { verifier: readVerifier() } : {}), ...(readHostCaps() ? { hostCaps: readHostCaps() } : {}), hostFallback: readHostFallback(), ...readRelayCaps(), ...(readSequenceRegenerate() ? { sequenceRegenerate: readSequenceRegenerate() } : {}), ...(readBaseMerge() ? { baseMerge: readBaseMerge() } : {}), ...(readFollowupsDefaultMilestone() ? { followupsDefaultMilestone: readFollowupsDefaultMilestone() } : {}), ...(readFollowupsRollupLabel() ? { followupsRollupLabel: readFollowupsRollupLabel() } : {}), ...(readCiFailFast() ? { ci: { fail_fast: readCiFailFast() } } : {}), ...(Number.isInteger(Number(readLeanSetting("contract_max_corrections"))) && Number(readLeanSetting("contract_max_corrections")) >= 1 ? { contractMaxCorrections: Number(readLeanSetting("contract_max_corrections")) } : {}), ...(Number.isInteger(Number(readLeanSetting("review_max_resumes"))) && Number(readLeanSetting("review_max_resumes")) >= 1 ? { reviewMaxResumes: Number(readLeanSetting("review_max_resumes")) } : {}) });
|
|
1141
1146
|
} catch (e) { if (!interrupted) report({ terminalReason: "engine-error", detail: String(e?.message ?? e).slice(0, 500) }); throw e; }
|
|
@@ -1396,8 +1401,8 @@ async function envBatch({ argv, root, print = (l) => console.log(l) }) {
|
|
|
1396
1401
|
return { ok: true, batch: id };
|
|
1397
1402
|
}
|
|
1398
1403
|
|
|
1399
|
-
const ORCH_USAGE = "usage: forgedock orchestrate <issue...> [--parallel K] [--lane L] [--lane-override] [--force <reason>] [--repo owner/repo] [--auto-children off|decomposed|epic|all] [--epic N] | --resume <id> [issue...] | --set-parallel <id> <K> | --set-max-remote <id> <N> | --set-placement <id> remote|hybrid|local | --clear-breaker <id> | --add <id> <issue...> | --requeue <id> <issue...> [--reason <text>] | --cancel <id> [--stop-remote] | --hold <id> <issue...> [--for <4h|30m|1d>] [--reason <text>] | --gc-orphans | --adopt <issue> [--repo owner/repo] [--lane L] | --release <id> <issue...> | --show-env <id> | --set-env <id> KEY=VAL | --unset-env <id> KEY";
|
|
1400
|
-
const ORCH_VALUED = ["--parallel", "--lane", "--repo", "--model", "--prefilter-model", "--reason", "--force", "--auto-children", "--epic", "--for"];
|
|
1404
|
+
const ORCH_USAGE = "usage: forgedock orchestrate <issue...> | --select <query> [--parallel K] [--lane L] [--lane-override] [--force <reason>] [--repo owner/repo] [--auto-children off|decomposed|epic|all] [--epic N] | --resume <id> [issue...] | --set-parallel <id> <K> | --set-max-remote <id> <N> | --set-placement <id> remote|hybrid|local | --clear-breaker <id> | --status <id> | --add <id> <issue...> | --requeue <id> <issue...> [--reason <text>] | --cancel <id> [--stop-remote] | --hold <id> --all [--for 2h] [--reason T] (sugar for --pause) | --hold <id> <issue...> [--for <4h|30m|1d>] [--reason <text>] | --pause <id> [--for <4h|30m|1d>] --reason <text> | --unpause <id> | --gc-orphans | --adopt <issue> [--repo owner/repo] [--lane L] | --release <id> <issue...> | --show-env <id> | --set-env <id> KEY=VAL | --unset-env <id> KEY";
|
|
1405
|
+
const ORCH_VALUED = ["--parallel", "--lane", "--repo", "--model", "--prefilter-model", "--reason", "--force", "--auto-children", "--epic", "--for", "--select"];
|
|
1401
1406
|
const issuesOf = (argv) => {
|
|
1402
1407
|
const issues = [];
|
|
1403
1408
|
for (let i = 0; i < argv.length; i++) {
|
|
@@ -1406,6 +1411,50 @@ const issuesOf = (argv) => {
|
|
|
1406
1411
|
}
|
|
1407
1412
|
return issues;
|
|
1408
1413
|
};
|
|
1414
|
+
/**
|
|
1415
|
+
* #5978: `--status <id>`: the coverage of a selector batch: running + queued + backing-off + waiting on deps + human-blocked = the open
|
|
1416
|
+
* issues its selector matches; `unscheduled` is 0 when the order is healthy. A batch without a selector reports its own counts.
|
|
1417
|
+
*/
|
|
1418
|
+
/** #6008: writes/clears the `suspend` marker on an issue's FORGE:STATE: the lane re-reads it before push and merge and stops renewing under it. */
|
|
1419
|
+
const suspendMarker = (projector, batchId) => async (n, on, reason) => {
|
|
1420
|
+
const cur = (await projector.readState(n)) ?? {};
|
|
1421
|
+
if (on) await projector.writeState(n, { ...cur, suspend: { reason, batch: batchId, at: new Date().toISOString() } });
|
|
1422
|
+
else if (cur.suspend) { const { suspend: _s, ...rest } = cur; await projector.writeState(n, rest); }
|
|
1423
|
+
};
|
|
1424
|
+
async function statusBatch({ id, root, io, print = (l) => console.log(l) }) {
|
|
1425
|
+
const batchMod = await import("./lean/batch.mjs"), { selectArgs, parseSelected } = await import("./lean/reconcile.mjs");
|
|
1426
|
+
if (!id || String(id).startsWith("--")) throw new Error(ORCH_USAGE);
|
|
1427
|
+
const b = batchMod.openBatch(root, id), plan = b.readPlan(), st = b.store.load();
|
|
1428
|
+
if (!plan || !st) throw new Error(`no batch ${id} in ${root}`);
|
|
1429
|
+
const kept = b.keptSandboxes(!b.readReport() && b.lastProgressMs() !== null && Date.now() - b.lastProgressMs() <= 10 * 60000); // #6008: a batch with no progress for 10 min has no dispatcher
|
|
1430
|
+
const showKept = () => { if (kept.length) print(`kept sandboxes (${kept.length}): ${kept.map((k) => `#${k.issue} age ${Math.round((k.ageMs ?? 0) / 60000)}m phase ${k.phase ?? "?"}`).join(", ")}`); };
|
|
1431
|
+
showKept();
|
|
1432
|
+
const select = flag(plan.argv ?? [], "--select");
|
|
1433
|
+
if (!select) { print(`batch ${id}: no selector (a fixed list); ${(st.pending ?? []).length} pending, ${Object.keys(st.running ?? {}).length} running`); return { ok: true, batch: id, unscheduled: [] }; }
|
|
1434
|
+
const open = parseSelected(await io.gh(selectArgs(plan.repo, select)));
|
|
1435
|
+
if (!open) throw new Error(`cannot read the issues matching '${select}'`);
|
|
1436
|
+
const c = batchMod.coverage({ state: st, open });
|
|
1437
|
+
const n = (k) => c[k].length;
|
|
1438
|
+
print(`batch ${id} selector '${select}': ${open.length} matching open = ${n("running")} running + ${n("queued")} queued + ${n("backingOff")} backing-off + ${n("waitingDeps")} waiting on deps + ${n("humanBlocked")} human-blocked + ${n("unscheduled")} unscheduled`);
|
|
1439
|
+
if (c.humanBlocked.length) print(`human-blocked: ${c.humanBlocked.map((x) => `#${x}`).join(", ")}`);
|
|
1440
|
+
print(c.unscheduled.length ? `UNSCHEDULED (${c.unscheduled.length}): ${c.unscheduled.map((x) => `#${x}`).join(", ")}` : "unscheduled: 0 (healthy)");
|
|
1441
|
+
return { ok: true, batch: id, coverage: c, unscheduled: c.unscheduled, kept };
|
|
1442
|
+
}
|
|
1443
|
+
/** #5978: the runner's reconcile seam for a `--select` batch: the gh search, the agent/lane-image version, the base sha, close-on-lane-merge. */
|
|
1444
|
+
async function makeReconcile({ select, repo, leanIo, orch, lane, argv }) {
|
|
1445
|
+
const { selectArgs, parseSelected, RECONCILE_MS } = await import("./lean/reconcile.mjs");
|
|
1446
|
+
const rollup = Number.parseInt(process.env.FORGE_POSTDEPLOY_ROLLUP ?? "", 10) > 0 ? Number.parseInt(process.env.FORGE_POSTDEPLOY_ROLLUP, 10) : null;
|
|
1447
|
+
return {
|
|
1448
|
+
everyMs: RECONCILE_MS,
|
|
1449
|
+
list: async () => parseSelected(await leanIo.gh(selectArgs(repo, select))),
|
|
1450
|
+
version: () => `${ENGINE_VERSION}|${process.env.FORGE_LANE_IMAGE ?? ""}`,
|
|
1451
|
+
base: async () => { try { return String(await leanIo.gh(["api", `repos/${repo}/commits/${lane || flag(argv, "--lane") || "staging"}`, "--jq", ".sha"])).trim() || null; } catch { return null; } },
|
|
1452
|
+
closeIssue: async (n, { lane: l }) => {
|
|
1453
|
+
await leanIo.gh(["issue", "close", String(n), "-R", repo, "--comment", `Merged into \`${l}\`; closed by the batch (\`Closes\` does not fire on a lane branch).`]);
|
|
1454
|
+
if (rollup) await leanIo.gh(["issue", "comment", String(rollup), "-R", repo, "--body", `#${n} merged into \`${l}\`: its post-deploy checks are folded into this release checklist.`]);
|
|
1455
|
+
},
|
|
1456
|
+
};
|
|
1457
|
+
}
|
|
1409
1458
|
/** #5471: the reason of `--force <reason>` (null when absent or valueless): lifts the cross-batch ownership skip. */
|
|
1410
1459
|
const forceOf = (argv) => { const v = flag(argv, "--force"); return v && !String(v).startsWith("--") ? v : null; };
|
|
1411
1460
|
/** #4469: the operands among `tokens` (`--add`/`--resume` extras): no flags, and no value of a valued flag (`--parallel 5` is not issue #5). */
|
|
@@ -1534,6 +1583,12 @@ function holdMeta(argv) {
|
|
|
1534
1583
|
return { owner: process.env.FORGE_HOLD_OWNER || `${process.env.USER || process.env.USERNAME || "operator"}@${hostname()}`, ownerPid: process.ppid, ownerHost: hostname(), forMs: parseHoldFor(forLabel), forLabel, reason: reason && !reason.startsWith("--") ? reason : null };
|
|
1535
1584
|
}
|
|
1536
1585
|
|
|
1586
|
+
/** #5975: `--hold --all` pauses the batch without a `--reason`: the reason defaults to the flag that asked. */
|
|
1587
|
+
function holdMetaAll(argv) {
|
|
1588
|
+
const m = holdMeta(argv);
|
|
1589
|
+
return argv.includes("--hold") && !m.reason ? { ...m, reason: "--hold --all" } : m;
|
|
1590
|
+
}
|
|
1591
|
+
|
|
1537
1592
|
/** #5469: `--gc-orphans`: cancel every orphaned batch (unhosted, pending issues, idle for a week) through the daemon or the batch files. */
|
|
1538
1593
|
async function gcOrphans({ root, viaDaemon = null, print = (l) => console.log(l) }) {
|
|
1539
1594
|
let res = viaDaemon ? await viaDaemon() : null;
|
|
@@ -1547,6 +1602,25 @@ async function gcOrphans({ root, viaDaemon = null, print = (l) => console.log(l)
|
|
|
1547
1602
|
return { ok: true, cancelled: res.cancelled ?? [] };
|
|
1548
1603
|
}
|
|
1549
1604
|
|
|
1605
|
+
/**
|
|
1606
|
+
* `--pause <id> [--for 2h] --reason T` / `--unpause <id>` (#5975): the batch's `pause` file, through the daemon (`viaDaemon(op, meta)`,
|
|
1607
|
+
* null when none runs) or directly. Admission stops for every issue, later re-admissions, requeues and adds included; running lanes
|
|
1608
|
+
* are untouched. @returns {{ok, batch, pause}}
|
|
1609
|
+
*/
|
|
1610
|
+
async function pauseBatch({ op, id, root, viaDaemon = null, meta = null, print = (l) => console.log(l) }) {
|
|
1611
|
+
if (!id || String(id).startsWith("--")) throw new Error(ORCH_USAGE);
|
|
1612
|
+
if (op === "pause" && !meta?.reason) throw new Error("--pause needs --reason <text>");
|
|
1613
|
+
let res = viaDaemon ? await viaDaemon(op, meta) : null;
|
|
1614
|
+
if (!res) {
|
|
1615
|
+
const b = (await import("./lean/batch.mjs")).openBatch(root, id);
|
|
1616
|
+
if (!b.exists()) throw new Error(`no batch ${id} in ${root}`);
|
|
1617
|
+
res = op === "pause" ? { pause: b.setPause(meta) } : { changed: b.clearPause() };
|
|
1618
|
+
}
|
|
1619
|
+
print(op === "pause" ? `batch ${id}: paused (${meta.reason}, until ${res.pause?.expiresAt ?? "unpause"}); running lanes continue; forgedock orchestrate --unpause ${id} re-admits`
|
|
1620
|
+
: res.changed === false ? `batch ${id}: not paused` : `batch ${id}: unpaused`);
|
|
1621
|
+
return { ok: true, batch: id, pause: res.pause ?? null };
|
|
1622
|
+
}
|
|
1623
|
+
|
|
1550
1624
|
/**
|
|
1551
1625
|
* `--hold <id> N...` / `--release <id> N...` (#4592): the batch's `hold` file, through the daemon (`viaDaemon(op, issues)`, null
|
|
1552
1626
|
* when none runs) or directly. A held issue is not admitted (a running lane is not stopped); `--release` (or a `--resume` that
|
|
@@ -1554,6 +1628,9 @@ async function gcOrphans({ root, viaDaemon = null, print = (l) => console.log(l)
|
|
|
1554
1628
|
*/
|
|
1555
1629
|
async function holdBatch({ op, id, tokens, root, viaDaemon = null, takeover = null, meta = null, print = (l) => console.log(l) }) {
|
|
1556
1630
|
const issues = tokens.filter((t) => /^#?\d+$/.test(String(t))).map((t) => parseInt(String(t).replace("#", ""), 10));
|
|
1631
|
+
if (op === "hold" && tokens.includes("pending") && id) { // #6008: every issue not running: queued, deferred (notBefore, capacity backoff) and retry-timer ones, not only the ones in `pending` right now
|
|
1632
|
+
try { const st = (await import("./lean/batch.mjs")).openBatch(root, id).store.load(); for (const n of st?.pending ?? []) if (!issues.includes(n)) issues.push(n); for (const n of Object.keys(st?.notBefore ?? {})) if (!issues.includes(Number(n))) issues.push(Number(n)); } catch { /* unreadable: the explicit list stands */ }
|
|
1633
|
+
}
|
|
1557
1634
|
if (!id || String(id).startsWith("--") || !issues.length) throw new Error(ORCH_USAGE);
|
|
1558
1635
|
let res = viaDaemon ? await viaDaemon(op, issues, meta) : null;
|
|
1559
1636
|
if (!res) {
|
|
@@ -1692,6 +1769,11 @@ async function orchestrateClient(argv, deps = {}) {
|
|
|
1692
1769
|
try { sock = await schedd.connectDaemon({ dir, spawnDaemon: null }); } catch { sock = null; }
|
|
1693
1770
|
return sock ? schedd.request(sock, { op, id, issues, ...(meta ? { meta } : {}) }, undefined, { timeoutMs: schedd.REQUEST_MS }) : null;
|
|
1694
1771
|
};
|
|
1772
|
+
const viaPause = async (id, op, meta) => {
|
|
1773
|
+
let sock = null;
|
|
1774
|
+
try { sock = await schedd.connectDaemon({ dir, spawnDaemon: null }); } catch { sock = null; }
|
|
1775
|
+
return sock ? schedd.request(sock, { op, id, ...(meta ? { meta } : {}) }, undefined, { timeoutMs: schedd.REQUEST_MS }) : null;
|
|
1776
|
+
};
|
|
1695
1777
|
const batchRootOf = async () => (await import("./lean/batch.mjs")).batchRoot();
|
|
1696
1778
|
if (["--show-env", "--set-env", "--unset-env"].some((f) => argv.includes(f))) return envBatch({ argv, root: await batchRootOf() });
|
|
1697
1779
|
if (argv.includes("--clear-breaker")) return runBatch({ argv, deps, sink: consoleSink() });
|
|
@@ -1707,11 +1789,16 @@ async function orchestrateClient(argv, deps = {}) {
|
|
|
1707
1789
|
const i = argv.indexOf("--requeue"), id = argv[i + 1];
|
|
1708
1790
|
return requeueBatch({ id, tokens: operandsOf(argv.slice(i + 2)), reason: flag(argv, "--reason"), root: await batchRootOf(), io: deps.io ?? makeIo(), viaDaemon: requeueVia(id), requireHost: true, force: forceOf(argv) });
|
|
1709
1791
|
}
|
|
1792
|
+
if (argv.includes("--status")) return statusBatch({ id: flag(argv, "--status"), root: await batchRootOf(), io: deps.io ?? makeIo() });
|
|
1710
1793
|
if (argv.includes("--gc-orphans")) return gcOrphans({ root: await batchRootOf(), viaDaemon: async () => {
|
|
1711
1794
|
let sock = null;
|
|
1712
1795
|
try { sock = await schedd.connectDaemon({ dir, spawnDaemon: null }); } catch { sock = null; }
|
|
1713
1796
|
return sock ? schedd.request(sock, { op: "gc-orphans" }, undefined, { timeoutMs: schedd.REQUEST_MS }) : null;
|
|
1714
1797
|
} });
|
|
1798
|
+
for (const [flagName, op] of [["--pause", "pause"], ["--unpause", "unpause"], ["--hold", "pause"]]) if (argv.includes(flagName) && (flagName !== "--hold" || argv.includes("--all"))) { // #5975: `--hold <id> --all` is sugar for `--pause`
|
|
1799
|
+
const id = flag(argv, flagName), pv = (_o, meta) => viaPause(id, op, meta);
|
|
1800
|
+
return pauseBatch({ op, id, root: await batchRootOf(), viaDaemon: pv, meta: op === "pause" ? holdMetaAll(argv) : null });
|
|
1801
|
+
}
|
|
1715
1802
|
for (const op of ["hold", "release"]) if (argv.includes(`--${op}`)) {
|
|
1716
1803
|
const id = flag(argv, `--${op}`);
|
|
1717
1804
|
const root = await batchRootOf(), io = deps.io ?? makeIo();
|
|
@@ -1732,7 +1819,7 @@ async function orchestrateClient(argv, deps = {}) {
|
|
|
1732
1819
|
let msg;
|
|
1733
1820
|
if (resumeId) msg = { op: "attach", id: resumeId, resume: true };
|
|
1734
1821
|
else {
|
|
1735
|
-
if (!issuesOf(argv).length) throw new Error(ORCH_USAGE);
|
|
1822
|
+
if (!issuesOf(argv).length && !flag(argv, "--select")) throw new Error(ORCH_USAGE);
|
|
1736
1823
|
parallelOf(argv);
|
|
1737
1824
|
let sub = [...argv];
|
|
1738
1825
|
if (!flag(sub, "--repo")) {
|
|
@@ -1835,7 +1922,11 @@ export async function runBatch({ argv, cwd: callerCwd = process.cwd(), env: call
|
|
|
1835
1922
|
const i = argv.indexOf("--requeue");
|
|
1836
1923
|
return requeueBatch({ id: argv[i + 1], tokens: operandsOf(argv.slice(i + 2)), reason: flag(argv, "--reason"), root, io: deps.io ?? makeIo(), requireHost: true, force: forceOf(argv), print: (l) => sink.line(l) });
|
|
1837
1924
|
}
|
|
1925
|
+
if (argv.includes("--status")) return statusBatch({ id: flag(argv, "--status"), root, io: deps.io ?? makeIo(), print: (l) => sink.line(l) });
|
|
1838
1926
|
if (argv.includes("--gc-orphans")) return gcOrphans({ root, print: (l) => sink.line(l) });
|
|
1927
|
+
for (const [flagName, op] of [["--pause", "pause"], ["--unpause", "unpause"], ["--hold", "pause"]]) if (argv.includes(flagName) && (flagName !== "--hold" || argv.includes("--all"))) { // #5975: `--hold <id> --all` is sugar for `--pause`
|
|
1928
|
+
return pauseBatch({ op, id: flag(argv, flagName), root, meta: op === "pause" ? holdMetaAll(argv) : null, print: (l) => sink.line(l) });
|
|
1929
|
+
}
|
|
1839
1930
|
for (const op of ["hold", "release"]) if (argv.includes(`--${op}`)) {
|
|
1840
1931
|
const hid = flag(argv, `--${op}`);
|
|
1841
1932
|
return holdBatch({ op, id: hid, tokens: operandsOf(argv.slice(argv.indexOf(`--${op}`) + 2)), root, meta: op === "hold" ? holdMeta(argv) : null, print: (l) => sink.line(l),
|
|
@@ -1864,7 +1955,8 @@ export async function runBatch({ argv, cwd: callerCwd = process.cwd(), env: call
|
|
|
1864
1955
|
for (const [n, l] of Object.entries(plan.baseWaits ?? {})) if (Array.isArray(l) && l.length) baseWaits.set(Number(n), l.filter((w) => w && typeof w.sha === "string" && typeof w.base === "string"));
|
|
1865
1956
|
}
|
|
1866
1957
|
let issues = issuesOf(argv);
|
|
1867
|
-
|
|
1958
|
+
const select = flag(argv, "--select"); // #5978: a standing order: the selector is kept in plan.argv and in the batch state
|
|
1959
|
+
if (!issues.length && !select) throw new Error(ORCH_USAGE);
|
|
1868
1960
|
const parallel = parallelOf(argv);
|
|
1869
1961
|
// The lanes' env: a resumed daemon batch uses the env its plan kept, over the daemon's own.
|
|
1870
1962
|
// A pre-#4192 batch resumed by the daemon kept no env: its lanes use the daemon's.
|
|
@@ -2007,6 +2099,7 @@ export async function runBatch({ argv, cwd: callerCwd = process.cwd(), env: call
|
|
|
2007
2099
|
const needsOf = new Map(); // issue -> host-only capabilities its body names (#4542), filled by readBody
|
|
2008
2100
|
const prefetchOf = new Map(); // issue -> the frozen contract's relayable read-only commands (#4778), filled by readBody
|
|
2009
2101
|
let execForNeeds = null;
|
|
2102
|
+
let poolUsage = []; // #5985: pool usage-history rows (cpu_avg per repo), refreshed in the background; classify lanes light/heavy
|
|
2010
2103
|
let lanes, remote = null, execBudget = null, execConf = null, hybrid = false;
|
|
2011
2104
|
const execMode = () => (deps.execution !== undefined ? deps.execution : readExecution(cwd))?.mode ?? "local";
|
|
2012
2105
|
if (deps.leanModule) {
|
|
@@ -2014,6 +2107,7 @@ export async function runBatch({ argv, cwd: callerCwd = process.cwd(), env: call
|
|
|
2014
2107
|
const emitTelemetry = deps.emitTelemetry ?? makeEmitTelemetry({ repo });
|
|
2015
2108
|
lanes = { adopt: null, runOne: (n, ln, ctx = {}) => runCore({ issue: n, repo, lane: ln, deferPostRun: true, // #5437: orchestrate runs result.postRun once the slot is free
|
|
2016
2109
|
laneOverride, ...(ctx.placement ? { placement: { ...ctx.placement, mode: execMode() } } : {}), ...(ctx.recover ? { recover: ctx.recover } : {}), ...(ctx.plan ? { plan: true } : {}), ...(ctx.planned ? { planned: ctx.planned } : {}), ...(ctx.stackedOn ? { stackedOn: ctx.stackedOn } : {}), branches, cwd, dir, io: leanIo, agentId: `orch_${process.pid}_${n}`, emitTelemetry, batchId: batch.id,
|
|
2110
|
+
liveBatches: (issue) => batchMod.batchesOwning(root, repo, issue, { exceptId: batch.id }).filter((b) => !b.cancelled).map((b) => b.id), // #5991: a lease of any other batch is taken over at once
|
|
2017
2111
|
...(rotatorKind({ execution: readExecution(cwd), env }) ? { accountRotator: rotatorKind({ execution: readExecution(cwd), env }) } : {}), // #5094, #5205: detected
|
|
2018
2112
|
admission: readAdmission(cwd), heavy: readHeavy(cwd), ...readCoreLimits(cwd), ...readEnvConfig(cwd), ...(readMergeWait(cwd) ? { mergeWait: readMergeWait(cwd) } : {}), ...(readConformanceMode(cwd) ? { conformance: readConformanceMode(cwd) } : {}), ...(readConformanceKinds(cwd) ? { conformanceKinds: readConformanceKinds(cwd) } : {}), ...(readConformanceMutation(cwd) ? { conformanceMutation: "report" } : {}), ...(readContextPack(cwd) ? { contextPack: readContextPack(cwd) } : {}), ...(readSequenceVersioned(cwd) ? { sequenceVersioned: readSequenceVersioned(cwd) } : {}), ...(readSharedSurfaces(cwd) ? { sharedSurfaces: readSharedSurfaces(cwd) } : {}), ...(readReviewIncomplete(cwd) ? { reviewIncomplete: readReviewIncomplete(cwd) } : {}), ...(readLaneInstructions(cwd) ? { laneInstructions: readLaneInstructions(cwd) } : {}), ...(readReproTest(cwd) ? { reproTest: readReproTest(cwd) } : {}), ...(readReproQuality(cwd) ? { reproQuality: readReproQuality(cwd) } : {}), ...(readExplore(cwd) ? { explore: readExplore(cwd) } : {}), ...(readExperiment(cwd) ? { experiment: readExperiment(cwd) } : {}), light: readLight(cwd), ...(readCloseParent(cwd) ? { closeParent: true } : {}), ...(readOrchestration(cwd).mergeTrain === "on" ? { mergeTrain: "on" } : {}), ...(readReviewTrigger(cwd) ? { reviewTrigger: readReviewTrigger(cwd) } : {}), ...(readVerify(cwd) ? { verify: readVerify(cwd) } : {}), ...readPrecheckOptions(cwd), ...(model ? { builderModel: model } : {}), ...(readLeanSetting("reviewer_model", cwd) ? { reviewerModel: readLeanSetting("reviewer_model", cwd) } : {}), ...(readFixModel(cwd) ? { fixModel: readFixModel(cwd) } : {}), ...(readBuilderRouting(cwd) ? { builderRouting: readBuilderRouting(cwd) } : {}), ...(readVerifier(cwd) ? { verifier: readVerifier(cwd) } : {}), ...(readHostCaps(cwd) ? { hostCaps: readHostCaps(cwd) } : {}), hostFallback: readHostFallback(cwd), ...readRelayCaps(), ...(readSequenceRegenerate(cwd) ? { sequenceRegenerate: readSequenceRegenerate(cwd) } : {}), ...(readBaseMerge(cwd) ? { baseMerge: readBaseMerge(cwd) } : {}), ...(readFollowupsDefaultMilestone(cwd) ? { followupsDefaultMilestone: readFollowupsDefaultMilestone(cwd) } : {}), ...(readFollowupsRollupLabel(cwd) ? { followupsRollupLabel: readFollowupsRollupLabel(cwd) } : {}), ...(readCiFailFast(cwd) ? { ci: { fail_fast: readCiFailFast(cwd) } } : {}), ...(Number.isInteger(Number(readLeanSetting("contract_max_corrections", cwd))) && Number(readLeanSetting("contract_max_corrections", cwd)) >= 1 ? { contractMaxCorrections: Number(readLeanSetting("contract_max_corrections", cwd)) } : {}), ...(Number.isInteger(Number(readLeanSetting("review_max_resumes", cwd))) && Number(readLeanSetting("review_max_resumes", cwd)) >= 1 ? { reviewMaxResumes: Number(readLeanSetting("review_max_resumes", cwd)) } : {}) }) };
|
|
2019
2113
|
} else {
|
|
@@ -2057,7 +2151,7 @@ export async function runBatch({ argv, cwd: callerCwd = process.cwd(), env: call
|
|
|
2057
2151
|
const ledgerFor = deps.sandboxLedger ?? ((n) => makeLedger({ batch: batch.id, lane: `sandbox-${n}`, owner: `orch_${process.pid}`, issue: n }));
|
|
2058
2152
|
const bud = exec.budget ?? {};
|
|
2059
2153
|
const holdId = execMod.remoteHoldId(provider); // #5095: the pool account's usage-limit hold key
|
|
2060
|
-
const remoteLanes = execMod.providerLanes({ provider, laneArgs, ledgerFor, env, secrets: exec.secrets, costPerMinute: bud.costPerMinute ?? 0, holdId,
|
|
2154
|
+
const remoteLanes = execMod.providerLanes({ provider, laneArgs, ...(leanIo?.projector ? { suspendKept: (n) => suspendMarker(leanIo.projector, batch.id)(n, true, "kept for adopt"), resumeKept: (n) => suspendMarker(leanIo.projector, batch.id)(n, false, "adopted") } : {}), ...(typeof provider.agentOnline === "function" ? { agentOnline: (h) => provider.agentOnline(h) } : {}), ledgerFor, env, secrets: exec.secrets, costPerMinute: bud.costPerMinute ?? 0, holdId,
|
|
2061
2155
|
...(Number.isFinite(exec.unreachableWindowMin) ? { unreachableWindowMs: exec.unreachableWindowMin * 60000 } : {}),
|
|
2062
2156
|
...(deps.now ? { now: deps.now } : {}), ...(deps.pollMs ? { pollMs: deps.pollMs } : {}),
|
|
2063
2157
|
logTail: (h) => { try { return readFileSync(batch.logFile(h.issue), "utf8").slice(-4000); } catch { return ""; } } }); // #4866: a clone failure in the lane log types sandbox.clone
|
|
@@ -2089,21 +2183,22 @@ export async function runBatch({ argv, cwd: callerCwd = process.cwd(), env: call
|
|
|
2089
2183
|
if (batch.readExecution()?.provider !== true) batch.setExecution({ provider: true });
|
|
2090
2184
|
// #4540: provider free slots, refreshed in the background (admission is sync); unknown (null) never blocks.
|
|
2091
2185
|
let capSample = null, onlineSample = null, capAt = 0, capLast = -Infinity, capFailed = false; // #5048: capFailed = last probe rejected // #4547: online = agents alive, null unknown
|
|
2186
|
+
let liveSample = {}, usageLast = -Infinity; // #5985: the pool's live load/memory ride the capacity sample
|
|
2092
2187
|
const capacity = () => {
|
|
2188
|
+
if (typeof provider.usageHistory === "function" && (deps.now ? deps.now() : Date.now()) - usageLast >= 600000) { usageLast = deps.now ? deps.now() : Date.now(); Promise.resolve().then(() => provider.usageHistory()).then((rows) => { if (Array.isArray(rows)) poolUsage = rows; }, () => {}); }
|
|
2093
2189
|
if (capFailed) throw new Error("capacity probe failed"); // #5048: until the next successful sample, so every caller sees it (release review CONC-1)
|
|
2094
2190
|
const t = deps.now ? deps.now() : Date.now();
|
|
2095
2191
|
if (typeof provider.capacity === "function" && t - capLast >= (deps.pollMs ?? 5000)) {
|
|
2096
2192
|
capLast = t;
|
|
2097
|
-
Promise.resolve().then(() => provider.capacity()).then((c) => { capFailed = false; capSample = c && Number.isInteger(c.free) ? c.free : null; onlineSample = c && Number.isInteger(c.online) ? c.online : null; capAt++; }, () => { capSample = null; onlineSample = null; capFailed = true; capAt++; });
|
|
2193
|
+
Promise.resolve().then(() => provider.capacity()).then((c) => { capFailed = false; capSample = c && Number.isInteger(c.free) ? c.free : null; onlineSample = c && Number.isInteger(c.online) ? c.online : null; liveSample = { ...(Number.isFinite(c?.load_per_core) ? { load_per_core: c.load_per_core } : {}), ...(Number.isFinite(c?.mem_available_gb) ? { mem_available_gb: c.mem_available_gb } : {}) }; capAt++; }, () => { capSample = null; onlineSample = null; capFailed = true; capAt++; });
|
|
2098
2194
|
}
|
|
2099
|
-
return capSample === null && onlineSample === null ? null : { free: capSample, online: onlineSample, at: capAt };
|
|
2195
|
+
return capSample === null && onlineSample === null ? null : { free: capSample, online: onlineSample, ...liveSample, at: capAt };
|
|
2100
2196
|
};
|
|
2101
2197
|
remote = liveExec.liveRemote({
|
|
2102
2198
|
hostFallback: readHostFallback(), capacity, isRemote: () => true, identity: () => holdId, ...(exec.fallbackLocal ? { offlineFallback: true, headroom: hostHeadroom, ...(exec.capacityFallbackAfter ? { capacityFallbackAfter: exec.capacityFallbackAfter } : {}) } : {}), onBudget: bud.onBudget ?? "stop", costPerMinute: bud.costPerMinute ?? 0,
|
|
2103
2199
|
admit: (u) => execBudget.admit(u),
|
|
2104
2200
|
onUsage: (n, sb, rec) => {
|
|
2105
|
-
|
|
2106
|
-
try { execBudget.record(`${batch.id}#${sb.id ?? n}#${startedAt}`, sb); } catch { /* the batch total still counts it */ }
|
|
2201
|
+
try { execBudget.record(sandboxBudgetKey(batch.id, sb.id ?? n, rec?.handle?.startedAt ?? rec?.startedAt ?? null), sb); } catch { /* the batch total still counts it */ }
|
|
2107
2202
|
Promise.resolve(emitSbx({ event: "SANDBOX_USAGE", issue: n, provider: sb.provider, sandbox_id: sb.id, minutes: sb.minutes, cost_usd: sb.cost_usd, batch: batch.id })).catch(() => {});
|
|
2108
2203
|
},
|
|
2109
2204
|
}, { exec, readOverride: batch.readExecution, place, onChange: (e) => sink.line(`execution: live placement ${e.mode}, max_remote ${e.maxRemote}`) });
|
|
@@ -2117,7 +2212,9 @@ export async function runBatch({ argv, cwd: callerCwd = process.cwd(), env: call
|
|
|
2117
2212
|
const stopLane = deps.stopLane ?? ((n, rec) => (rec?.remote || rec?.handle ? remoteStop?.(n, rec) ?? false : rec?.pid ? killLedgerPid(rec.pid, batch.resultFile(n)) : false));
|
|
2118
2213
|
// #5241: a cancelled lane that ended gives its issue lease back, unless a live lane of another batch runs the issue.
|
|
2119
2214
|
const releaseLease = deps.releaseLease ?? (leanIo?.projector ? async (n) => { await clearLease({ projector: leanIo.projector, issue: n, shouldClear: () => !batchMod.batchesOwning(root, repo, n, { exceptId: batch.id }).some((o) => !o.cancelled && o.running) }); } : null);
|
|
2120
|
-
|
|
2215
|
+
// #6008: hold/pause/keep reach a kept sandbox through the `suspend` marker on the issue's FORGE:STATE (the sandbox cannot read batch files)
|
|
2216
|
+
const suspendLane = deps.suspendLane ?? (leanIo?.projector ? suspendMarker(leanIo.projector, batch.id) : null);
|
|
2217
|
+
lanes = { ...lanes, stopLane, releaseLease, suspendLane };
|
|
2121
2218
|
}
|
|
2122
2219
|
const orch = deps.orchestration ?? readOrchestration(cwd);
|
|
2123
2220
|
const train = orch.mergeTrain === "on" ? (deps.train ?? (await import("./lean/mergetrain.mjs")).createMergeTrain({ gh: (a) => leanIo.gh(a), repo, batchSize: orch.mergeTrainBatch ?? 4,
|
|
@@ -2251,6 +2348,19 @@ export async function runBatch({ argv, cwd: callerCwd = process.cwd(), env: call
|
|
|
2251
2348
|
const hostIo = await laneCheck.hostLaneIo({ env });
|
|
2252
2349
|
preflight = async () => (await laneCheck.runLaneChecks({ exec: execForNeeds, env, io: hostIo })).filter((c) => !c.ok);
|
|
2253
2350
|
}
|
|
2351
|
+
// #5992: the base is probed once per (repo, base sha) on the dispatcher, before any sandbox launch; a red verdict holds admissions.
|
|
2352
|
+
let baseProbe = deps.baseProbe === undefined ? null : deps.baseProbe;
|
|
2353
|
+
const guardCmds = readInvariants(cwd) ?? [];
|
|
2354
|
+
if (deps.baseProbe === undefined && !testDeps && guardCmds.length) {
|
|
2355
|
+
const { probeBase } = await import("./lean/basered.mjs"), { runCheckCommand } = await import("./lean/effects.mjs");
|
|
2356
|
+
const baseRef = readBranches(cwd).staging ?? readBranches(cwd).default ?? "main", vcfg = readVerify(cwd) ?? {};
|
|
2357
|
+
const gitIn = (a) => leanIo.git(a, { cwd });
|
|
2358
|
+
const readSha = async () => {
|
|
2359
|
+
try { const m = String(await gitIn(["ls-remote", "origin", `refs/heads/${baseRef}`])).trim().split(/\s+/)[0]; if (/^[0-9a-f]{40}$/.test(m)) { await gitIn(["fetch", "origin", baseRef]).catch(() => ""); return m; } } catch { /* offline: the local ref */ }
|
|
2360
|
+
return gitIn(["rev-parse", `origin/${baseRef}`]);
|
|
2361
|
+
};
|
|
2362
|
+
baseProbe = () => probeBase({ repo, base: baseRef, commands: guardCmds, readSha, git: gitIn, runCommand: runCheckCommand, cwd, env, timeoutMs: (vcfg.precheckTimeoutSeconds ?? 300) * 1000 });
|
|
2363
|
+
}
|
|
2254
2364
|
const { hostMissingTools } = await import("./lean/toolplace.mjs");
|
|
2255
2365
|
const envHold = deps.envHold !== undefined ? deps.envHold : testDeps ? null : {
|
|
2256
2366
|
version: () => scheddMod.readInstalledVersion() ?? ENGINE_VERSION,
|
|
@@ -2305,16 +2415,18 @@ export async function runBatch({ argv, cwd: callerCwd = process.cwd(), env: call
|
|
|
2305
2415
|
...(estimate ? { estimate } : {}),
|
|
2306
2416
|
beforeAdmit,
|
|
2307
2417
|
...(preflight ? { preflight } : {}),
|
|
2418
|
+
...(baseProbe ? { baseProbe } : {}),
|
|
2308
2419
|
...(orch.blockedLabel ? { getBlocked: async () => JSON.parse(await leanIo.gh(["issue", "list", "-R", repo, "--label", orch.blockedLabel, "--state", "open", "--limit", "200", "--json", "number"])).map((x) => x.number) } : {}), // #4773
|
|
2309
2420
|
trusted: (n) => trustedOf.get(n) === true,
|
|
2310
2421
|
autoChildren,
|
|
2311
2422
|
...(autoMod.addsEpicChildren(autoChildren.mode) ? { getChildren: async () => ({ list: await autoMod.readChildList({ gh: (a) => leanIo.gh(a), repo, fields: childFields ??= await autoMod.hostListFields((a) => leanIo.gh(a)) }), elsewhere: autoMod.liveElsewhere({ batchMod, root, self: batch.id, repo }) }) } : {}),
|
|
2312
|
-
|
|
2423
|
+
...(select ? { select, reconcile: await makeReconcile({ select, repo, leanIo, orch, lane, argv }) } : {}),
|
|
2424
|
+
issues, parallel, prefilter, resolveLane: laneOf, store: batch.store, getParallel: batch.readParallel, getClearBreaker: batch.peekClearBreaker, consumeClearBreaker: batch.readClearBreaker, ackClearBreaker: batch.ackClearBreaker, getAdded: batch.readAdded, getRequeued: batch.readRequeued, getCancelled: batch.readCancel, getHeld: batch.readHeld, expireHolds: batch.expireHolds, getPause: batch.readPause, expirePause: batch.expirePause, getHoldInfo: batch.readHoldInfo, getGates: batch.readGates, baseWait: baseWaits.size ? baseWaitOf(baseWaits, { io, leanIo, cwd }) : null, ...lanes,
|
|
2313
2425
|
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,
|
|
2314
2426
|
...(registry ? { sched: { registry, batch: batch.id, repo, cap: liveLaneCap(orch.globalParallel ?? null, { cfg: readAdmission(cwd), host: { cores: () => cpus().length, memAvailableMb, rampingMb: rampProbe.rampingMb } }), exclusive: true }, priorityOf: async (n) => schedMod.priorityFromLabels(await labelNames(n)) } : {}),
|
|
2315
2427
|
// #5174: hold new local admissions while loadavg/cores is above engine.overload_load_per_core (host-wide batches only)
|
|
2316
2428
|
...(overload ? { overload } : {}),
|
|
2317
|
-
...(remote ? { remote } : {}),
|
|
2429
|
+
...(remote ? { remote, usageRows: () => poolUsage, repoSlug: repo } : {}),
|
|
2318
2430
|
// #4267: mechanical needs-human outcomes are recovered in the batch; every runner decision is a FORGE:DECISION.
|
|
2319
2431
|
...(recoveryOn ? { recovery: orch.recovery } : {}),
|
|
2320
2432
|
...(stackingOn ? { stacking: orch.stacking, ...(orch.stacking === "full" ? { readPrReady: async (n) => (await makeProjector(io, { repo }).readState(n))?.prReady ?? null } : {}) } : {}), // #5831, #5832: PR-ready is read from the dependency lane's FORGE:STATE
|
|
@@ -2340,6 +2452,8 @@ export async function runBatch({ argv, cwd: callerCwd = process.cwd(), env: call
|
|
|
2340
2452
|
onInterrupted: deps.onInterrupted ?? (async (n) => leanIo.gh(["issue", "edit", String(n), "-R", repo, "--remove-label", "workflow:building"]).catch(() => {})),
|
|
2341
2453
|
// #4387: an out-of-set dependency labelled needs-human is not pulled into the batch
|
|
2342
2454
|
issueLabels: labelNames,
|
|
2455
|
+
// #5986: per-issue attempts ledger and input-hash admission (off under the test seams)
|
|
2456
|
+
...((deps.attempts !== undefined ? deps.attempts : testDeps ? null : true) ? { attempts: deps.attempts !== undefined ? deps.attempts : makeAttemptsSeam({ gh: (a) => leanIo.gh(a), repo, engineVersion: ENGINE_VERSION, sandboxVersion: scheddMod.readInstalledVersion?.() ?? null, cfg: { maxAttempts: orch.maxAttemptsPerIssue, maxIdentical: orch.maxIdenticalSignature } }) } : {}),
|
|
2343
2457
|
// #4725: a closed (completed) dependency is satisfied even when it still carries a stale needs-human label
|
|
2344
2458
|
// #5152: a NOT_PLANNED close labelled workflow:merged, or a decomposition whose sub-issues all closed, is delivered: CLOSED
|
|
2345
2459
|
issueState: async (n) => {
|
|
@@ -2398,6 +2512,7 @@ export async function runBatch({ argv, cwd: callerCwd = process.cwd(), env: call
|
|
|
2398
2512
|
const { batchEfficiency, formatEfficiencyLines } = await import("./stats/efficiency.mjs");
|
|
2399
2513
|
report.push(...formatEfficiencyLines(await (deps.efficiency ?? batchEfficiency)({ batchDir: batch.dir, runsDir: dir, repo, gh: (a) => leanIo.gh(a), rows })));
|
|
2400
2514
|
} catch (e) { report.push(`efficiency: n/a (${String(e?.message ?? e).split("\n")[0].slice(0, 160)})`); }
|
|
2515
|
+
try { report.push(...await (await import("./stats/churn.mjs")).readChurn({ gh: (a) => leanIo.gh(a), repo, issues: rows.map((r) => r.issue).filter(Number.isInteger) })); } catch { /* #5979: churn lines never fail a batch */ }
|
|
2401
2516
|
report.push(await budgetReportLine({ cwd, repo, gh: (a) => leanIo.gh(a) })); // #5278: month usage, projection and any auto switch to local-first
|
|
2402
2517
|
const adequacyLine = formatTestAdequacySummary(rows); // #5449
|
|
2403
2518
|
if (adequacyLine) report.push(adequacyLine);
|
|
@@ -2700,13 +2815,14 @@ export async function scheddFromCli(argv, deps = {}) {
|
|
|
2700
2815
|
const bm = await import("./lean/batch.mjs");
|
|
2701
2816
|
const unfinished = () => { const root = bm.batchRoot(); return bm.listBatches(root).filter((id) => { try { const b = bm.openBatch(root, id); const br = b.store.peek()?.breaker; return !!b.readPlan()?.daemon && !b.isTerminal() && b.pendingIssues().length > 0 && !(br && !br.transport); } catch { return false; } }); };
|
|
2702
2817
|
const start = () => { if (schedd.unitState() === null) schedd.defaultSpawn({ dir }); else schedd.startUnit(); };
|
|
2818
|
+
const unit = deps.unitState ?? schedd.unitState; // #5966: active unit but no daemon is alerted and the unit restarted
|
|
2703
2819
|
const batchVerdicts = () => schedd.batchVerdicts(bm.batchRoot());
|
|
2704
|
-
return (deps.watchdog ?? health.watchdog)({ dir, ...(sec > 0 ? { stallMs: sec * 1000 } : {}), unfinished, start, batchVerdicts });
|
|
2820
|
+
return (deps.watchdog ?? health.watchdog)({ dir, ...(sec > 0 ? { stallMs: sec * 1000 } : {}), unfinished, start, restart: () => schedd.restartUnit(), batchVerdicts, unit });
|
|
2705
2821
|
}
|
|
2706
2822
|
if (argv.length) throw new Error("usage: forgedock schedd [status | watchdog [--stall-sec N]]");
|
|
2707
2823
|
(deps.renice ?? (await import("./lean/schedd-health.mjs")).bestEffortRenice)(); // #4780: lanes must not starve the scheduler
|
|
2708
2824
|
process.title = "forgedock-schedd"; // distinctive name for OOM-killer avoid lists and ps (#4673)
|
|
2709
|
-
const d = await schedd.startDaemon({ dir, runBatch: (a) => runBatch({ ...a, daemon: true, deps: deps.batchDeps ?? {} }), ...(deps.due !== undefined ? { due: deps.due } : { due: scheddDue }),
|
|
2825
|
+
const d = await (deps.startDaemon ?? schedd.startDaemon)({ dir, runBatch: (a) => runBatch({ ...a, daemon: true, deps: deps.batchDeps ?? {} }), exit: deps.exit ?? ((c) => process.exit(c)), ...(deps.due !== undefined ? { due: deps.due } : { due: scheddDue }),
|
|
2710
2826
|
...(deps.daemonPreflight !== undefined ? { preflight: deps.daemonPreflight } : deps.batchDeps ? {} : { preflight: async () => { const lc = await import("./lean/lanecheck.mjs"); return (await lc.runLaneChecks({ exec: readExecution(process.cwd()), io: await lc.hostLaneIo() })).filter((c) => !c.ok); } }) });
|
|
2711
2827
|
if (!d.running) {
|
|
2712
2828
|
// #4775: under systemd, exiting here (code 0) makes `Restart=always` loop while another daemon holds the lock: stand by, take over when it dies
|
|
@@ -2718,7 +2834,14 @@ export async function scheddFromCli(argv, deps = {}) {
|
|
|
2718
2834
|
// #4454: a signal stops the hosted batch loops, then releases the lock and socket, then exits 128+signo
|
|
2719
2835
|
schedd.exitOnSignals(d, { ...(deps.processOn ? { on: deps.processOn } : {}), ...(deps.exit ? { exit: deps.exit } : {}) });
|
|
2720
2836
|
await d.closed;
|
|
2721
|
-
|
|
2837
|
+
await d.settled?.(); // #5984: a self-stop keeps spawning/probing the successor after `closed`; exiting now would leave no daemon
|
|
2838
|
+
// #5966 R1: a handover whose successor never listened re-hosted the batches in a new daemon; follow it to its end
|
|
2839
|
+
let cur = d;
|
|
2840
|
+
while (cur.rehosted?.()) { cur = cur.rehosted(); await cur.closed; await cur.settled?.(); }
|
|
2841
|
+
// #5966: a self-initiated stop (handover, stall recovery, lost socket) exits non-zero so systemd restarts the unit instead of leaving a zombie
|
|
2842
|
+
const code = cur.stopCode?.();
|
|
2843
|
+
if (code) (deps.exit ?? ((c) => process.exit(c)))(code);
|
|
2844
|
+
return { running: false, ...(code ? { exitCode: code } : {}) };
|
|
2722
2845
|
}
|
|
2723
2846
|
|
|
2724
2847
|
/**
|
|
@@ -2893,6 +3016,7 @@ export async function schedFromCli(argv, deps = {}) {
|
|
|
2893
3016
|
const batchMod = await import("./lean/batch.mjs");
|
|
2894
3017
|
const agentOf = (e) => { const bm = batchMod; const r = bm.openBatch(bm.batchRoot(), e.batch).store.peek()?.running?.[e.issue]; return r?.placement?.agent ?? r?.agent ?? null; };
|
|
2895
3018
|
for (const l of schedMod.remoteLines(st, { agentOf })) console.log(l); // #4964
|
|
3019
|
+
for (const l of schedMod.concurrencyLines(st, { eventsOf: (b) => batchMod.openBatch(batchMod.batchRoot(), b).store.readLog() })) console.log(l); // #5985
|
|
2896
3020
|
try { for (const l of (await import("./lean/batch-health.mjs")).summaryLines((await import("./lean/batch.mjs")).batchRoot())) console.log(l); } catch { /* advisory */ } // #5314
|
|
2897
3021
|
return st;
|
|
2898
3022
|
}
|
|
@@ -2945,7 +3069,7 @@ export function readOrchestration(cwd = process.cwd()) {
|
|
|
2945
3069
|
const errors = int(o.breaker_errors ?? o.errors, 3), windowMin = int(o.breaker_window_min ?? o.window_min, 30);
|
|
2946
3070
|
const gp = int(o.global_parallel, null);
|
|
2947
3071
|
const recoveryMax = int(o.recovery_max_attempts ?? o.max_attempts, 1);
|
|
2948
|
-
return { mergeTrain: String(o.merge_train ?? "off").trim().toLowerCase() === "on" ? "on" : "off", /* #5836 */ mergeTrainBatch: int(o.merge_train_batch, 4) >= 1 ? int(o.merge_train_batch, 4) : 4, /* #5837 */ breaker: errors > 0 && windowMin > 0 ? { errors, window_min: windowMin } : null, maxDeferrals: int(o.max_deferrals, 3), transientRetries: int(o.transient_retries, 4), blockedLabel: String(o.blocked_label ?? "blocked").trim(), globalParallel: gp >= 1 ? gp : null,
|
|
3072
|
+
return { maxAttemptsPerIssue: int(o.max_attempts_per_issue, 4) >= 1 ? int(o.max_attempts_per_issue, 4) : 4, maxIdenticalSignature: int(o.max_identical_signature, 2) >= 1 ? int(o.max_identical_signature, 2) : 2, /* #5986 */ mergeTrain: String(o.merge_train ?? "off").trim().toLowerCase() === "on" ? "on" : "off", /* #5836 */ mergeTrainBatch: int(o.merge_train_batch, 4) >= 1 ? int(o.merge_train_batch, 4) : 4, /* #5837 */ breaker: errors > 0 && windowMin > 0 ? { errors, window_min: windowMin } : null, maxDeferrals: int(o.max_deferrals, 3), transientRetries: int(o.transient_retries, 4), blockedLabel: String(o.blocked_label ?? "blocked").trim(), globalParallel: gp >= 1 ? gp : null,
|
|
2949
3073
|
stacking: normalizeStacking(o.stacking), // #5831
|
|
2950
3074
|
recovery: { maxAttempts: recoveryMax, mechanicalMaxAttempts: Math.max(int(o.recovery_mechanical_max_attempts ?? o.mechanical_max_attempts, 2), recoveryMax) }, // #4725: env/base/sequence codes have their own budget
|
|
2951
3075
|
// #4525: parked-PR base sync. The parser flattens one level, so `base_sync.enabled|union_globs` arrive as `enabled|union_globs` (or flat `base_sync_*`).
|
package/bin/forgedock.mjs
CHANGED
|
@@ -1107,6 +1107,13 @@ async function installHygieneSchedule(cwd, write = () => {}) {
|
|
|
1107
1107
|
const { installGcSchedule } = await import("./gc-schedule.mjs");
|
|
1108
1108
|
const r = await installGcSchedule({ schedule: h.schedule, enabled: h.auto_gc, cwd });
|
|
1109
1109
|
if (r.status !== "off") write(` Hygiene schedule: ${r.status} (${r.kind}) ${r.detail}\n`);
|
|
1110
|
+
try { // #5987: daily introspect, filed only on an explicit orchestrate.slo.file_issues: true (the installer removes the entry otherwise)
|
|
1111
|
+
const [{ installIntrospectSchedule }, { parseSloConfig }, { parseForgeYaml }] = await Promise.all([import("./introspect-schedule.mjs"), import("./lean/slo.mjs"), import("./forge-utils.mjs")]);
|
|
1112
|
+
let fileIssues = false;
|
|
1113
|
+
try { fileIssues = parseSloConfig(parseForgeYaml(readFileSync(join(cwd, "forge.yaml"), "utf8"))).fileIssues; } catch { fileIssues = false; }
|
|
1114
|
+
const i = await installIntrospectSchedule({ enabled: fileIssues, cwd });
|
|
1115
|
+
if (i.status !== "off") write(` Introspect schedule: ${i.status} (${i.kind}) ${i.detail}\n`);
|
|
1116
|
+
} catch { /* advisory */ }
|
|
1110
1117
|
return r;
|
|
1111
1118
|
} catch { return null; }
|
|
1112
1119
|
}
|
package/bin/help-text.mjs
CHANGED
|
@@ -12,7 +12,7 @@ import { wrap } from "./guide.mjs";
|
|
|
12
12
|
export const EVERYDAY_COMMANDS = [
|
|
13
13
|
["setup", "Guided setup: install ForgeDock and configure this repo"],
|
|
14
14
|
["run-issue <issue>", "Turn one GitHub issue into a reviewed, merged pull request"],
|
|
15
|
-
["orchestrate <issue...>", "Work on several issues at once, in dependency order"],
|
|
15
|
+
["orchestrate <issue...> | --select <query>", "Work on several issues at once, in dependency order; --select keeps a standing order over every open issue a query matches"],
|
|
16
16
|
["watch", "Live view of what each agent is doing"],
|
|
17
17
|
["status", "Show ForgeDock state for this directory"],
|
|
18
18
|
["release", "Promote staging to your main branch as one reviewed release"],
|
|
@@ -66,8 +66,8 @@ export const FULL_COMMAND_GROUPS = [
|
|
|
66
66
|
["npx forgedock bootstrap <idea|docs> [--dry-run] [--spike <path>] | --plan <plan.json> [--dry-run]", "Headless /bootstrap: idea to orchestrate-ready backlog (--dry-run previews milestones, titles, DAG and estimated agent cost without GitHub writes); --plan validates and creates (or previews) a plan, and re-running resumes from GitHub"],
|
|
67
67
|
["npx forgedock run-issue <issue> [--lane <lane>] [--lane-override] [--path core|full] [--retry] [--wait-lease] [--local]", "Work one issue from claim to merge (the lane comes from the issue: its milestone, else staging; --lane only asserts it). Follows forge.yaml execution: like orchestrate (remote or hybrid places the lane on the pool, with fallback_local); --local forces this host and the placement is printed. --retry reopens a failed run, or one needing a human once the label is cleared; --wait-lease waits for another holder of the issue; exit status 75 means deferred, nothing was lost"],
|
|
68
68
|
["npx forgedock plan validate --live [--repo owner/repo] [--json]", "Re-run the bootstrap dependency-order rules on live GitHub state: each cross-milestone Depends-on edge is ok, held or invalid (fails on invalid)"],
|
|
69
|
-
["npx forgedock orchestrate <issue...> [--parallel K] [--lane L]", "Work on several issues with bounded concurrency and Depends-on ordering; each issue on its own lane, cross-lane dependencies reported"],
|
|
70
|
-
["npx forgedock orchestrate --resume <id> [N...] | --set-parallel <id> K | --set-max-remote <id> N | --set-placement <id> remote|hybrid|local | --add <id> N... | --requeue <id> N... [--reason \"...\"] | --cancel <id> | --hold <id> N... [--for 4h] [--reason \"...\"] | --adopt <issue> | --gc-orphans | --release <id> N... | --show-env <id> | --set-env <id> KEY=VAL | --unset-env <id> KEY", "Reattach to a running or finished batch (a finished one replays its report, an interrupted one resumes), change its concurrency or placement live, add, requeue, hold (with an owner and an optional expiry, --for) or release single issues, adopt an open hand-built PR, cancel orphaned batches (--gc-orphans), stop one batch without stopping the background scheduler, or print, set or unset the batch environment (secrets redacted; applies to newly started lanes)"],
|
|
69
|
+
["npx forgedock orchestrate <issue...> | --select <query> [--parallel K] [--lane L]", "Work on several issues with bounded concurrency and Depends-on ordering; each issue on its own lane, cross-lane dependencies reported"],
|
|
70
|
+
["npx forgedock orchestrate --resume <id> [N...] | --set-parallel <id> K | --set-max-remote <id> N | --set-placement <id> remote|hybrid|local | --status <id> | --add <id> N... | --requeue <id> N... [--reason \"...\"] | --cancel <id> | --hold <id> N... [--for 4h] [--reason \"...\"] | --adopt <issue> | --gc-orphans | --release <id> N... | --show-env <id> | --set-env <id> KEY=VAL | --unset-env <id> KEY", "Reattach to a running or finished batch (a finished one replays its report, an interrupted one resumes), change its concurrency or placement live, add, requeue, hold (with an owner and an optional expiry, --for) or release single issues, adopt an open hand-built PR, cancel orphaned batches (--gc-orphans), stop one batch without stopping the background scheduler, or print, set or unset the batch environment (secrets redacted; applies to newly started lanes)"],
|
|
71
71
|
["npx forgedock triage <issue...> [--lane L] [--dry-run]", "Already-fixed pre-filter: close issues a merged PR or green CI already resolved; print the rest"],
|
|
72
72
|
["npx forgedock probe [issue...] [--dry-run]", "Run declared acceptance probes for closed issues whose fix is on the default branch; a fail reopens the issue"],
|
|
73
73
|
["npx forgedock interfaces check|register|contract", "Interface contracts: require an Interfaces section on a spike/epic with 2+ slices, register its rows in the decision register, generate seam contract tests"],
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
|
+
/**
|
|
4
|
+
* Daily `fd-introspect --file-issues` (#5987): the lean-lane test-quality trend (`forgedock stats --conformance-outcomes`) run on a
|
|
5
|
+
* systemd user timer, with a tagged cron entry as the fallback, modelled on gc-schedule.mjs. Installed by `doctor --fix` and
|
|
6
|
+
* `forgedock init`. Findings are filed (deduped against open issues and prior reports) only when `orchestrate.slo.file_issues: true`
|
|
7
|
+
* is set (opt-in); `enabled` false removes the entry. All I/O is injected (`exec`, `fs`). Never throws.
|
|
8
|
+
*/
|
|
9
|
+
import * as nodeFs from "node:fs";
|
|
10
|
+
import { createHash } from "node:crypto";
|
|
11
|
+
import { execFile } from "node:child_process";
|
|
12
|
+
import { promisify } from "node:util";
|
|
13
|
+
import { homedir } from "node:os";
|
|
14
|
+
import { dirname, join, resolve } from "node:path";
|
|
15
|
+
import { fileURLToPath } from "node:url";
|
|
16
|
+
|
|
17
|
+
const pexec = promisify(execFile);
|
|
18
|
+
const CRON_TAG = "# forgedock-introspect";
|
|
19
|
+
const ARGS = "--run"; // this file is the entry: runs the introspect report and files it (see runIntrospect)
|
|
20
|
+
|
|
21
|
+
export const introspectUnitName = (cwd) => `forgedock-introspect-${createHash("sha1").update(resolve(cwd)).digest("hex").slice(0, 8)}`;
|
|
22
|
+
/** Where today's report for `cwd` is saved; the SLO rolling issue links it (#5987). */
|
|
23
|
+
export const introspectReportPath = (cwd, home = homedir(), now = Date.now()) => join(home, ".forge", "introspect", `${new Date(now).toISOString().slice(0, 10)}-${introspectUnitName(cwd).slice(-8)}.txt`);
|
|
24
|
+
const q = (s) => `"${String(s).replace(/(["\\$`])/g, "\\$1")}"`;
|
|
25
|
+
const SELF = fileURLToPath(import.meta.url);
|
|
26
|
+
const forgedockBin = () => join(dirname(SELF), "forgedock.mjs");
|
|
27
|
+
|
|
28
|
+
export function renderIntrospectSystemd({ cwd, node = process.execPath, bin = forgedockBin() }) {
|
|
29
|
+
return {
|
|
30
|
+
service: `[Unit]\nDescription=ForgeDock introspect, files findings (${resolve(cwd)})\n\n[Service]\nType=oneshot\nWorkingDirectory=${resolve(cwd)}\nExecStart=${q(node)} ${q(SELF)} ${ARGS}\n`,
|
|
31
|
+
timer: `[Unit]\nDescription=ForgeDock introspect daily\n\n[Timer]\nOnCalendar=daily\nRandomizedDelaySec=30min\nPersistent=true\n\n[Install]\nWantedBy=timers.target\n`,
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function renderIntrospectCron({ cwd, node = process.execPath, bin = forgedockBin() }) {
|
|
36
|
+
return `17 4 * * * cd ${q(resolve(cwd))} && ${q(node)} ${q(SELF)} ${ARGS} >/dev/null 2>&1 ${CRON_TAG} ${resolve(cwd)}`;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Install (or remove) the daily run. @returns {status: installed|removed|off|failed, kind, detail} */
|
|
40
|
+
export async function installIntrospectSchedule({ enabled = true, cwd = process.cwd(), home = homedir(), platform = process.platform, fs = nodeFs, exec = async (cmd, args, input) => { const p = pexec(cmd, args, { timeout: 30000 }); if (input != null) p.child.stdin.end(input); return (await p).stdout; }, node, bin } = {}) {
|
|
41
|
+
const name = introspectUnitName(cwd), dir = join(home, ".config", "systemd", "user");
|
|
42
|
+
const opts = { cwd, ...(node ? { node } : {}), ...(bin ? { bin } : {}) };
|
|
43
|
+
try {
|
|
44
|
+
if (platform === "linux") {
|
|
45
|
+
let hasSystemd = false;
|
|
46
|
+
try { await exec("systemctl", ["--user", "show-environment"]); hasSystemd = true; } catch { hasSystemd = false; }
|
|
47
|
+
if (hasSystemd) {
|
|
48
|
+
if (!enabled) {
|
|
49
|
+
if (!fs.existsSync(join(dir, `${name}.timer`))) return { status: "off", kind: "systemd", detail: "not enabled" };
|
|
50
|
+
try { await exec("systemctl", ["--user", "disable", "--now", `${name}.timer`]); } catch { /* already gone */ }
|
|
51
|
+
for (const f of [`${name}.timer`, `${name}.service`]) fs.rmSync(join(dir, f), { force: true });
|
|
52
|
+
return { status: "removed", kind: "systemd", detail: `removed ${name}.timer` };
|
|
53
|
+
}
|
|
54
|
+
const { service, timer } = renderIntrospectSystemd(opts);
|
|
55
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
56
|
+
fs.writeFileSync(join(dir, `${name}.service`), service);
|
|
57
|
+
fs.writeFileSync(join(dir, `${name}.timer`), timer);
|
|
58
|
+
await exec("systemctl", ["--user", "daemon-reload"]);
|
|
59
|
+
await exec("systemctl", ["--user", "enable", "--now", `${name}.timer`]);
|
|
60
|
+
return { status: "installed", kind: "systemd", detail: `${name}.timer daily` };
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
let cur = "";
|
|
64
|
+
try { cur = String(await exec("crontab", ["-l"])); } catch { cur = ""; }
|
|
65
|
+
const mine = (l) => l.trimEnd().endsWith(`${CRON_TAG} ${resolve(cwd)}`);
|
|
66
|
+
const all = cur.split("\n").filter((l) => l.trim()), rest = all.filter((l) => !mine(l));
|
|
67
|
+
if (!enabled && rest.length === all.length) return { status: "off", kind: "cron", detail: "not enabled" };
|
|
68
|
+
await exec("crontab", ["-"], [...rest, ...(enabled ? [renderIntrospectCron(opts)] : [])].join("\n") + "\n");
|
|
69
|
+
return enabled ? { status: "installed", kind: "cron", detail: "crontab entry daily" } : { status: "removed", kind: "cron", detail: "removed crontab entry" };
|
|
70
|
+
} catch (e) {
|
|
71
|
+
return { status: "failed", kind: "unknown", detail: String(e?.message ?? e).slice(0, 200) };
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* One introspect run: `forgedock stats --conformance-outcomes`, its report saved under `<home>/.forge/introspect/`, then filed
|
|
77
|
+
* (deduped, see slo.fileIntrospect) when `orchestrate.slo.file_issues: true` (opt-in, default off); the local report path is never posted. State `filed.json` holds the last filed report hash.
|
|
78
|
+
*/
|
|
79
|
+
export async function runIntrospect({ cwd = process.cwd(), home = homedir(), fs = nodeFs, run = async () => String((await pexec(process.execPath, [forgedockBin(), "stats", "--conformance-outcomes"], { cwd, timeout: 300000, maxBuffer: 8 << 20 })).stdout), gh = async (a) => String((await pexec("gh", a, { timeout: 30000 })).stdout), now = Date.now() } = {}) {
|
|
80
|
+
try {
|
|
81
|
+
const [{ parseSloConfig, fileIntrospect }, { parseForgeYaml }] = await Promise.all([import("./lean/slo.mjs"), import("./forge-utils.mjs")]);
|
|
82
|
+
let cfg; try { cfg = parseSloConfig(parseForgeYaml(fs.readFileSync(join(cwd, "forge.yaml"), "utf8"))); } catch { cfg = parseSloConfig({}); }
|
|
83
|
+
const report = await run(), dir = join(home, ".forge", "introspect"), scope = introspectUnitName(cwd).slice(-8);
|
|
84
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
85
|
+
const reportPath = introspectReportPath(cwd, home, now);
|
|
86
|
+
fs.writeFileSync(reportPath, report);
|
|
87
|
+
if (!cfg.fileIssues) return { action: "disabled", reportPath };
|
|
88
|
+
const stateFile = join(dir, `filed-${scope}.json`);
|
|
89
|
+
let prior = null; try { prior = JSON.parse(fs.readFileSync(stateFile, "utf8")); } catch { prior = null; }
|
|
90
|
+
const r = await fileIntrospect({ report, scope, gh, cfg, prior });
|
|
91
|
+
if (r.hash && ["create", "comment"].includes(r.action)) fs.writeFileSync(stateFile, JSON.stringify({ hash: r.hash, issue: r.issue }));
|
|
92
|
+
return { ...r, reportPath };
|
|
93
|
+
} catch (e) { return { action: "failed", detail: String(e?.message ?? e).slice(0, 200) }; }
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
if (process.argv[1] && resolve(process.argv[1]) === SELF && process.argv.includes("--run")) {
|
|
97
|
+
runIntrospect().then((r) => { console.log(`introspect: ${r.action}${r.reportPath ? ` ${r.reportPath}` : ""}`); });
|
|
98
|
+
}
|