forgedock 1.66.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 +96 -17
- 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 +3 -0
- package/bin/lean/batch-health.test.mjs +16 -0
- package/bin/lean/batch.mjs +45 -0
- package/bin/lean/batch.test.mjs +54 -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/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 +123 -24
- package/bin/lean/lean.test.mjs +137 -46
- 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-pause.test.mjs +23 -0
- package/bin/lean/orchestrate-reconcile.test.mjs +147 -0
- package/bin/lean/orchestrate.mjs +170 -26
- 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 +4 -4
- package/bin/lean/schedd-health.test.mjs +8 -4
- package/bin/lean/schedd.mjs +34 -2
- package/bin/lean/schedd.test.mjs +55 -2
- 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 +2 -2
- package/bin/pool/cli.mjs +16 -1
- package/bin/pool/lane-tools.mjs +21 -0
- 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/OUTCOME-CODES.md +1 -0
- package/package.json +1 -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> --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";
|
|
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). */
|
|
@@ -1579,6 +1628,9 @@ async function pauseBatch({ op, id, root, viaDaemon = null, meta = null, print =
|
|
|
1579
1628
|
*/
|
|
1580
1629
|
async function holdBatch({ op, id, tokens, root, viaDaemon = null, takeover = null, meta = null, print = (l) => console.log(l) }) {
|
|
1581
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
|
+
}
|
|
1582
1634
|
if (!id || String(id).startsWith("--") || !issues.length) throw new Error(ORCH_USAGE);
|
|
1583
1635
|
let res = viaDaemon ? await viaDaemon(op, issues, meta) : null;
|
|
1584
1636
|
if (!res) {
|
|
@@ -1737,6 +1789,7 @@ async function orchestrateClient(argv, deps = {}) {
|
|
|
1737
1789
|
const i = argv.indexOf("--requeue"), id = argv[i + 1];
|
|
1738
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) });
|
|
1739
1791
|
}
|
|
1792
|
+
if (argv.includes("--status")) return statusBatch({ id: flag(argv, "--status"), root: await batchRootOf(), io: deps.io ?? makeIo() });
|
|
1740
1793
|
if (argv.includes("--gc-orphans")) return gcOrphans({ root: await batchRootOf(), viaDaemon: async () => {
|
|
1741
1794
|
let sock = null;
|
|
1742
1795
|
try { sock = await schedd.connectDaemon({ dir, spawnDaemon: null }); } catch { sock = null; }
|
|
@@ -1766,7 +1819,7 @@ async function orchestrateClient(argv, deps = {}) {
|
|
|
1766
1819
|
let msg;
|
|
1767
1820
|
if (resumeId) msg = { op: "attach", id: resumeId, resume: true };
|
|
1768
1821
|
else {
|
|
1769
|
-
if (!issuesOf(argv).length) throw new Error(ORCH_USAGE);
|
|
1822
|
+
if (!issuesOf(argv).length && !flag(argv, "--select")) throw new Error(ORCH_USAGE);
|
|
1770
1823
|
parallelOf(argv);
|
|
1771
1824
|
let sub = [...argv];
|
|
1772
1825
|
if (!flag(sub, "--repo")) {
|
|
@@ -1869,6 +1922,7 @@ export async function runBatch({ argv, cwd: callerCwd = process.cwd(), env: call
|
|
|
1869
1922
|
const i = argv.indexOf("--requeue");
|
|
1870
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) });
|
|
1871
1924
|
}
|
|
1925
|
+
if (argv.includes("--status")) return statusBatch({ id: flag(argv, "--status"), root, io: deps.io ?? makeIo(), print: (l) => sink.line(l) });
|
|
1872
1926
|
if (argv.includes("--gc-orphans")) return gcOrphans({ root, print: (l) => sink.line(l) });
|
|
1873
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`
|
|
1874
1928
|
return pauseBatch({ op, id: flag(argv, flagName), root, meta: op === "pause" ? holdMetaAll(argv) : null, print: (l) => sink.line(l) });
|
|
@@ -1901,7 +1955,8 @@ export async function runBatch({ argv, cwd: callerCwd = process.cwd(), env: call
|
|
|
1901
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"));
|
|
1902
1956
|
}
|
|
1903
1957
|
let issues = issuesOf(argv);
|
|
1904
|
-
|
|
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);
|
|
1905
1960
|
const parallel = parallelOf(argv);
|
|
1906
1961
|
// The lanes' env: a resumed daemon batch uses the env its plan kept, over the daemon's own.
|
|
1907
1962
|
// A pre-#4192 batch resumed by the daemon kept no env: its lanes use the daemon's.
|
|
@@ -2044,6 +2099,7 @@ export async function runBatch({ argv, cwd: callerCwd = process.cwd(), env: call
|
|
|
2044
2099
|
const needsOf = new Map(); // issue -> host-only capabilities its body names (#4542), filled by readBody
|
|
2045
2100
|
const prefetchOf = new Map(); // issue -> the frozen contract's relayable read-only commands (#4778), filled by readBody
|
|
2046
2101
|
let execForNeeds = null;
|
|
2102
|
+
let poolUsage = []; // #5985: pool usage-history rows (cpu_avg per repo), refreshed in the background; classify lanes light/heavy
|
|
2047
2103
|
let lanes, remote = null, execBudget = null, execConf = null, hybrid = false;
|
|
2048
2104
|
const execMode = () => (deps.execution !== undefined ? deps.execution : readExecution(cwd))?.mode ?? "local";
|
|
2049
2105
|
if (deps.leanModule) {
|
|
@@ -2051,6 +2107,7 @@ export async function runBatch({ argv, cwd: callerCwd = process.cwd(), env: call
|
|
|
2051
2107
|
const emitTelemetry = deps.emitTelemetry ?? makeEmitTelemetry({ repo });
|
|
2052
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
|
|
2053
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
|
|
2054
2111
|
...(rotatorKind({ execution: readExecution(cwd), env }) ? { accountRotator: rotatorKind({ execution: readExecution(cwd), env }) } : {}), // #5094, #5205: detected
|
|
2055
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)) } : {}) }) };
|
|
2056
2113
|
} else {
|
|
@@ -2094,7 +2151,7 @@ export async function runBatch({ argv, cwd: callerCwd = process.cwd(), env: call
|
|
|
2094
2151
|
const ledgerFor = deps.sandboxLedger ?? ((n) => makeLedger({ batch: batch.id, lane: `sandbox-${n}`, owner: `orch_${process.pid}`, issue: n }));
|
|
2095
2152
|
const bud = exec.budget ?? {};
|
|
2096
2153
|
const holdId = execMod.remoteHoldId(provider); // #5095: the pool account's usage-limit hold key
|
|
2097
|
-
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,
|
|
2098
2155
|
...(Number.isFinite(exec.unreachableWindowMin) ? { unreachableWindowMs: exec.unreachableWindowMin * 60000 } : {}),
|
|
2099
2156
|
...(deps.now ? { now: deps.now } : {}), ...(deps.pollMs ? { pollMs: deps.pollMs } : {}),
|
|
2100
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
|
|
@@ -2126,21 +2183,22 @@ export async function runBatch({ argv, cwd: callerCwd = process.cwd(), env: call
|
|
|
2126
2183
|
if (batch.readExecution()?.provider !== true) batch.setExecution({ provider: true });
|
|
2127
2184
|
// #4540: provider free slots, refreshed in the background (admission is sync); unknown (null) never blocks.
|
|
2128
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
|
|
2129
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; }, () => {}); }
|
|
2130
2189
|
if (capFailed) throw new Error("capacity probe failed"); // #5048: until the next successful sample, so every caller sees it (release review CONC-1)
|
|
2131
2190
|
const t = deps.now ? deps.now() : Date.now();
|
|
2132
2191
|
if (typeof provider.capacity === "function" && t - capLast >= (deps.pollMs ?? 5000)) {
|
|
2133
2192
|
capLast = t;
|
|
2134
|
-
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++; });
|
|
2135
2194
|
}
|
|
2136
|
-
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 };
|
|
2137
2196
|
};
|
|
2138
2197
|
remote = liveExec.liveRemote({
|
|
2139
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,
|
|
2140
2199
|
admit: (u) => execBudget.admit(u),
|
|
2141
2200
|
onUsage: (n, sb, rec) => {
|
|
2142
|
-
|
|
2143
|
-
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 */ }
|
|
2144
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(() => {});
|
|
2145
2203
|
},
|
|
2146
2204
|
}, { exec, readOverride: batch.readExecution, place, onChange: (e) => sink.line(`execution: live placement ${e.mode}, max_remote ${e.maxRemote}`) });
|
|
@@ -2154,7 +2212,9 @@ export async function runBatch({ argv, cwd: callerCwd = process.cwd(), env: call
|
|
|
2154
2212
|
const stopLane = deps.stopLane ?? ((n, rec) => (rec?.remote || rec?.handle ? remoteStop?.(n, rec) ?? false : rec?.pid ? killLedgerPid(rec.pid, batch.resultFile(n)) : false));
|
|
2155
2213
|
// #5241: a cancelled lane that ended gives its issue lease back, unless a live lane of another batch runs the issue.
|
|
2156
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);
|
|
2157
|
-
|
|
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 };
|
|
2158
2218
|
}
|
|
2159
2219
|
const orch = deps.orchestration ?? readOrchestration(cwd);
|
|
2160
2220
|
const train = orch.mergeTrain === "on" ? (deps.train ?? (await import("./lean/mergetrain.mjs")).createMergeTrain({ gh: (a) => leanIo.gh(a), repo, batchSize: orch.mergeTrainBatch ?? 4,
|
|
@@ -2288,6 +2348,19 @@ export async function runBatch({ argv, cwd: callerCwd = process.cwd(), env: call
|
|
|
2288
2348
|
const hostIo = await laneCheck.hostLaneIo({ env });
|
|
2289
2349
|
preflight = async () => (await laneCheck.runLaneChecks({ exec: execForNeeds, env, io: hostIo })).filter((c) => !c.ok);
|
|
2290
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
|
+
}
|
|
2291
2364
|
const { hostMissingTools } = await import("./lean/toolplace.mjs");
|
|
2292
2365
|
const envHold = deps.envHold !== undefined ? deps.envHold : testDeps ? null : {
|
|
2293
2366
|
version: () => scheddMod.readInstalledVersion() ?? ENGINE_VERSION,
|
|
@@ -2342,16 +2415,18 @@ export async function runBatch({ argv, cwd: callerCwd = process.cwd(), env: call
|
|
|
2342
2415
|
...(estimate ? { estimate } : {}),
|
|
2343
2416
|
beforeAdmit,
|
|
2344
2417
|
...(preflight ? { preflight } : {}),
|
|
2418
|
+
...(baseProbe ? { baseProbe } : {}),
|
|
2345
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
|
|
2346
2420
|
trusted: (n) => trustedOf.get(n) === true,
|
|
2347
2421
|
autoChildren,
|
|
2348
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 }) }) } : {}),
|
|
2423
|
+
...(select ? { select, reconcile: await makeReconcile({ select, repo, leanIo, orch, lane, argv }) } : {}),
|
|
2349
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,
|
|
2350
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,
|
|
2351
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)) } : {}),
|
|
2352
2427
|
// #5174: hold new local admissions while loadavg/cores is above engine.overload_load_per_core (host-wide batches only)
|
|
2353
2428
|
...(overload ? { overload } : {}),
|
|
2354
|
-
...(remote ? { remote } : {}),
|
|
2429
|
+
...(remote ? { remote, usageRows: () => poolUsage, repoSlug: repo } : {}),
|
|
2355
2430
|
// #4267: mechanical needs-human outcomes are recovered in the batch; every runner decision is a FORGE:DECISION.
|
|
2356
2431
|
...(recoveryOn ? { recovery: orch.recovery } : {}),
|
|
2357
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
|
|
@@ -2377,6 +2452,8 @@ export async function runBatch({ argv, cwd: callerCwd = process.cwd(), env: call
|
|
|
2377
2452
|
onInterrupted: deps.onInterrupted ?? (async (n) => leanIo.gh(["issue", "edit", String(n), "-R", repo, "--remove-label", "workflow:building"]).catch(() => {})),
|
|
2378
2453
|
// #4387: an out-of-set dependency labelled needs-human is not pulled into the batch
|
|
2379
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 } }) } : {}),
|
|
2380
2457
|
// #4725: a closed (completed) dependency is satisfied even when it still carries a stale needs-human label
|
|
2381
2458
|
// #5152: a NOT_PLANNED close labelled workflow:merged, or a decomposition whose sub-issues all closed, is delivered: CLOSED
|
|
2382
2459
|
issueState: async (n) => {
|
|
@@ -2435,6 +2512,7 @@ export async function runBatch({ argv, cwd: callerCwd = process.cwd(), env: call
|
|
|
2435
2512
|
const { batchEfficiency, formatEfficiencyLines } = await import("./stats/efficiency.mjs");
|
|
2436
2513
|
report.push(...formatEfficiencyLines(await (deps.efficiency ?? batchEfficiency)({ batchDir: batch.dir, runsDir: dir, repo, gh: (a) => leanIo.gh(a), rows })));
|
|
2437
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 */ }
|
|
2438
2516
|
report.push(await budgetReportLine({ cwd, repo, gh: (a) => leanIo.gh(a) })); // #5278: month usage, projection and any auto switch to local-first
|
|
2439
2517
|
const adequacyLine = formatTestAdequacySummary(rows); // #5449
|
|
2440
2518
|
if (adequacyLine) report.push(adequacyLine);
|
|
@@ -2739,12 +2817,12 @@ export async function scheddFromCli(argv, deps = {}) {
|
|
|
2739
2817
|
const start = () => { if (schedd.unitState() === null) schedd.defaultSpawn({ dir }); else schedd.startUnit(); };
|
|
2740
2818
|
const unit = deps.unitState ?? schedd.unitState; // #5966: active unit but no daemon is alerted and the unit restarted
|
|
2741
2819
|
const batchVerdicts = () => schedd.batchVerdicts(bm.batchRoot());
|
|
2742
|
-
return (deps.watchdog ?? health.watchdog)({ dir, ...(sec > 0 ? { stallMs: sec * 1000 } : {}), unfinished, start, batchVerdicts, unit });
|
|
2820
|
+
return (deps.watchdog ?? health.watchdog)({ dir, ...(sec > 0 ? { stallMs: sec * 1000 } : {}), unfinished, start, restart: () => schedd.restartUnit(), batchVerdicts, unit });
|
|
2743
2821
|
}
|
|
2744
2822
|
if (argv.length) throw new Error("usage: forgedock schedd [status | watchdog [--stall-sec N]]");
|
|
2745
2823
|
(deps.renice ?? (await import("./lean/schedd-health.mjs")).bestEffortRenice)(); // #4780: lanes must not starve the scheduler
|
|
2746
2824
|
process.title = "forgedock-schedd"; // distinctive name for OOM-killer avoid lists and ps (#4673)
|
|
2747
|
-
const d = await 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 }),
|
|
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 }),
|
|
2748
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); } }) });
|
|
2749
2827
|
if (!d.running) {
|
|
2750
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
|
|
@@ -2938,6 +3016,7 @@ export async function schedFromCli(argv, deps = {}) {
|
|
|
2938
3016
|
const batchMod = await import("./lean/batch.mjs");
|
|
2939
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; };
|
|
2940
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
|
|
2941
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
|
|
2942
3021
|
return st;
|
|
2943
3022
|
}
|
|
@@ -2990,7 +3069,7 @@ export function readOrchestration(cwd = process.cwd()) {
|
|
|
2990
3069
|
const errors = int(o.breaker_errors ?? o.errors, 3), windowMin = int(o.breaker_window_min ?? o.window_min, 30);
|
|
2991
3070
|
const gp = int(o.global_parallel, null);
|
|
2992
3071
|
const recoveryMax = int(o.recovery_max_attempts ?? o.max_attempts, 1);
|
|
2993
|
-
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,
|
|
2994
3073
|
stacking: normalizeStacking(o.stacking), // #5831
|
|
2995
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
|
|
2996
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
|
+
}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
|
+
import { describe, it } from "node:test";
|
|
4
|
+
import assert from "node:assert/strict";
|
|
5
|
+
import * as fs from "node:fs";
|
|
6
|
+
import { join } from "node:path";
|
|
7
|
+
import { tmpDir } from "./tests/_tmp.mjs";
|
|
8
|
+
import { runIntrospect, installIntrospectSchedule, renderIntrospectCron, renderIntrospectSystemd, introspectUnitName } from "./introspect-schedule.mjs";
|
|
9
|
+
|
|
10
|
+
describe("#5987 introspect schedule", () => {
|
|
11
|
+
it("renders a daily systemd unit and a tagged cron line that run stats --file-issues", () => {
|
|
12
|
+
const s = renderIntrospectSystemd({ cwd: "/work/r", node: "/n", bin: "/b/forgedock.mjs" });
|
|
13
|
+
assert.match(s.service, /ExecStart="\/n" ".*introspect-schedule.mjs" --run/);
|
|
14
|
+
assert.match(s.timer, /OnCalendar=daily/);
|
|
15
|
+
assert.match(renderIntrospectCron({ cwd: "/work/r", node: "/n", bin: "/b/f.mjs" }), /^17 4 \* \* \* cd "\/work\/r" .*introspect-schedule.mjs" --run .*# forgedock-introspect \/work\/r$/);
|
|
16
|
+
});
|
|
17
|
+
|
|
18
|
+
it("systemd: installs once (rewrite, no duplicate), removes when disabled", async () => {
|
|
19
|
+
const home = tmpDir("isch-"), calls = [];
|
|
20
|
+
const exec = async (c, a) => { calls.push([c, ...a].join(" ")); return ""; };
|
|
21
|
+
const o = { cwd: "/work/r", home, platform: "linux", exec, node: "/n", bin: "/b" };
|
|
22
|
+
assert.equal((await installIntrospectSchedule(o)).status, "installed");
|
|
23
|
+
assert.equal((await installIntrospectSchedule(o)).status, "installed");
|
|
24
|
+
const name = introspectUnitName("/work/r"), dir = join(home, ".config", "systemd", "user");
|
|
25
|
+
assert.deepEqual(fs.readdirSync(dir).sort(), [`${name}.service`, `${name}.timer`]);
|
|
26
|
+
assert.equal((await installIntrospectSchedule({ ...o, enabled: false })).status, "removed");
|
|
27
|
+
assert.equal(fs.existsSync(join(dir, `${name}.timer`)), false);
|
|
28
|
+
assert.equal((await installIntrospectSchedule({ ...o, enabled: false })).status, "off");
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
it("cron fallback replaces only its own line and dedupes", async () => {
|
|
32
|
+
let tab = "0 1 * * * other\n17 4 * * * x # forgedock-introspect /work/r2\n";
|
|
33
|
+
const exec = async (c, a, input) => { if (c === "systemctl") throw new Error("no systemd"); if (a[0] === "-l") return tab; tab = input; return ""; };
|
|
34
|
+
const o = { cwd: "/work/r", platform: "linux", exec, node: "/n", bin: "/b" };
|
|
35
|
+
await installIntrospectSchedule(o); await installIntrospectSchedule(o);
|
|
36
|
+
const lines = tab.trim().split("\n");
|
|
37
|
+
assert.equal(lines.filter((l) => l.endsWith("# forgedock-introspect /work/r")).length, 1);
|
|
38
|
+
assert.equal(lines.length, 3, "other lines kept");
|
|
39
|
+
assert.equal((await installIntrospectSchedule({ ...o, enabled: false })).status, "removed");
|
|
40
|
+
assert.equal(tab.trim().split("\n").length, 2);
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
it("never throws", async () => {
|
|
44
|
+
const r = await installIntrospectSchedule({ cwd: "/w", platform: "darwin", exec: async () => { throw new Error("boom"); } });
|
|
45
|
+
assert.ok(["off", "failed", "removed"].includes(r.status) || r.status === "installed");
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
it("runIntrospect files the report once, dedupes an unchanged report, adopts an open issue, and honors file_issues: false", async () => {
|
|
49
|
+
const home = tmpDir("isch-run-"), cwd = tmpDir("isch-cwd-"), calls = [];
|
|
50
|
+
const gh = async (a) => { calls.push(a); return a[1] === "list" ? "[]" : a[1] === "create" ? "https://x/issues/9\n" : ""; };
|
|
51
|
+
const run = async () => "adequate 80%";
|
|
52
|
+
fs.writeFileSync(join(cwd, "forge.yaml"), "orchestrate:\n slo:\n file_issues: false\n");
|
|
53
|
+
assert.equal((await runIntrospect({ cwd, home, run, gh })).action, "disabled");
|
|
54
|
+
assert.equal(calls.length, 0);
|
|
55
|
+
fs.rmSync(join(cwd, "forge.yaml"));
|
|
56
|
+
assert.equal((await runIntrospect({ cwd, home, run, gh })).action, "disabled", "no forge.yaml: default does not file");
|
|
57
|
+
assert.equal(calls.length, 0);
|
|
58
|
+
fs.writeFileSync(join(cwd, "forge.yaml"), "orchestrate:\n slo:\n file_issues: true\n");
|
|
59
|
+
const a = await runIntrospect({ cwd, home, run, gh });
|
|
60
|
+
assert.equal(a.action, "create"); assert.equal(a.issue, 9);
|
|
61
|
+
assert.equal((await runIntrospect({ cwd, home, run, gh })).action, "unchanged", "prior report: nothing filed");
|
|
62
|
+
const c = await runIntrospect({ cwd, home, run: async () => "adequate 70%", gh });
|
|
63
|
+
assert.equal(c.action, "comment"); assert.equal(c.issue, 9);
|
|
64
|
+
assert.equal(calls.filter((x) => x[1] === "create").length, 1);
|
|
65
|
+
assert.doesNotMatch(calls.at(-1).at(-1), /report: |\.forge\/introspect|\/introspect\//, "no local path posted");
|
|
66
|
+
});
|
|
67
|
+
});
|