forgedock 1.66.0 → 1.68.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/config-schema.mjs +3 -0
- package/bin/engine/outcome-codes.mjs +2 -0
- package/bin/engine-cli.mjs +193 -27
- package/bin/engine.mjs +10 -0
- package/bin/forgedock.mjs +24 -1
- package/bin/help-text.mjs +4 -3
- package/bin/introspect-schedule.mjs +98 -0
- package/bin/introspect-schedule.test.mjs +67 -0
- package/bin/lean/admission.mjs +21 -0
- package/bin/lean/admission.test.mjs +30 -0
- package/bin/lean/advisory.test.mjs +64 -0
- package/bin/lean/amendment-schema.mjs +30 -0
- package/bin/lean/attempts.mjs +162 -0
- package/bin/lean/attempts.test.mjs +141 -0
- package/bin/lean/basered.mjs +81 -0
- package/bin/lean/basered.test.mjs +68 -1
- package/bin/lean/batch-health.mjs +20 -12
- package/bin/lean/batch-health.test.mjs +55 -11
- package/bin/lean/batch.mjs +45 -0
- package/bin/lean/batch.test.mjs +105 -5
- package/bin/lean/capwait.mjs +14 -3
- package/bin/lean/capwait.test.mjs +20 -0
- package/bin/lean/ci-gate.mjs +2 -90
- package/bin/lean/ci-gate.test.mjs +1 -127
- package/bin/lean/ci-precheck.mjs +25 -8
- package/bin/lean/ci-precheck.test.mjs +24 -0
- package/bin/lean/clear-breaker.mjs +14 -0
- package/bin/lean/clear-breaker.test.mjs +4 -3
- package/bin/lean/commentstate.mjs +46 -0
- package/bin/lean/commentstate.test.mjs +43 -0
- package/bin/lean/concurrency.mjs +89 -0
- package/bin/lean/concurrency.test.mjs +113 -0
- package/bin/lean/conformance.e2e.test.mjs +13 -8
- package/bin/lean/conformance.mjs +73 -181
- package/bin/lean/conformance.test.mjs +61 -345
- package/bin/lean/depcache.mjs +100 -10
- package/bin/lean/depcache.test.mjs +105 -0
- package/bin/lean/docsgate.mjs +0 -32
- package/bin/lean/docsgate.test.mjs +2 -23
- package/bin/lean/effects-cap.test.mjs +9 -1
- package/bin/lean/effects-killtree.test.mjs +35 -0
- package/bin/lean/effects.mjs +42 -24
- package/bin/lean/efficiency.mjs +162 -0
- package/bin/lean/efficiency.test.mjs +79 -0
- package/bin/lean/engine-readmit.test.mjs +35 -0
- package/bin/lean/envgap.mjs +93 -0
- package/bin/lean/envgap.test.mjs +53 -0
- package/bin/lean/execution.mjs +41 -17
- package/bin/lean/execution.test.mjs +58 -0
- package/bin/lean/failure-census.mjs +170 -0
- package/bin/lean/failure-census.test.mjs +59 -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/guardgate.test.mjs +2 -3
- package/bin/lean/heavy.mjs +33 -4
- package/bin/lean/heavy.test.mjs +38 -6
- package/bin/lean/hotarea.mjs +0 -36
- package/bin/lean/hotarea.test.mjs +1 -22
- package/bin/lean/issuewatch-verify.mjs +19 -4
- package/bin/lean/issuewatch.mjs +21 -4
- package/bin/lean/issuewatch.test.mjs +48 -1
- package/bin/lean/lane-audit-gap.mjs +66 -0
- package/bin/lean/lane-audit-gap.test.mjs +59 -0
- package/bin/lean/lane-audit-llm.mjs +5 -0
- package/bin/lean/lane-audit-query.mjs +47 -0
- package/bin/lean/lane-audit-query.test.mjs +44 -0
- package/bin/lean/lane-audit-signatures.mjs +33 -0
- package/bin/lean/lane-audit.mjs +110 -0
- package/bin/lean/lane-audit.test.mjs +97 -0
- package/bin/lean/lane-recovery.test.mjs +33 -0
- package/bin/lean/lanecheck.mjs +5 -3
- package/bin/lean/lanecheck.test.mjs +6 -0
- package/bin/lean/lean.mjs +311 -154
- package/bin/lean/lean.test.mjs +530 -223
- package/bin/lean/limits.mjs +17 -0
- package/bin/lean/limits.test.mjs +15 -1
- package/bin/lean/live-execution.mjs +21 -2
- package/bin/lean/live-execution.test.mjs +39 -0
- package/bin/lean/liveness.mjs +37 -0
- package/bin/lean/liveness.test.mjs +33 -0
- package/bin/lean/orchestrate-attempts.test.mjs +82 -0
- package/bin/lean/orchestrate-envhold.test.mjs +47 -0
- package/bin/lean/orchestrate-heldroot.test.mjs +72 -0
- package/bin/lean/orchestrate-hostfallback.test.mjs +59 -1
- package/bin/lean/orchestrate-overload-recovery.test.mjs +37 -0
- package/bin/lean/orchestrate-pause.test.mjs +76 -1
- package/bin/lean/orchestrate-reconcile.test.mjs +164 -0
- package/bin/lean/orchestrate-relaunch-gates.test.mjs +57 -0
- package/bin/lean/orchestrate-stacking.test.mjs +10 -0
- package/bin/lean/orchestrate.mjs +344 -45
- package/bin/lean/phaseledger.mjs +6 -0
- package/bin/lean/phaseledger.test.mjs +13 -1
- package/bin/lean/postdeploy-check.test.mjs +1 -3
- package/bin/lean/precheck.mjs +20 -0
- package/bin/lean/preflight.mjs +100 -11
- package/bin/lean/preflight.test.mjs +44 -4
- package/bin/lean/prompts.mjs +13 -28
- package/bin/lean/reconcile.mjs +90 -0
- package/bin/lean/recurrence.mjs +6 -112
- package/bin/lean/recurrence.test.mjs +11 -92
- package/bin/lean/release-flakes.mjs +14 -2
- package/bin/lean/release-flakes.test.mjs +17 -1
- package/bin/lean/release-ledger.mjs +19 -1
- package/bin/lean/release-ledger.test.mjs +23 -0
- package/bin/lean/release-preflight.mjs +28 -0
- package/bin/lean/release-preflight.test.mjs +42 -1
- package/bin/lean/release-review.mjs +40 -5
- package/bin/lean/release-review.test.mjs +43 -2
- package/bin/lean/release.mjs +43 -14
- package/bin/lean/release.test.mjs +32 -0
- package/bin/lean/retry.mjs +1 -1
- package/bin/lean/retry.test.mjs +6 -1
- package/bin/lean/rotator.mjs +9 -0
- package/bin/lean/rotator.test.mjs +11 -1
- package/bin/lean/sandbox-remote.mjs +49 -11
- 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 +45 -8
- package/bin/lean/schedd.test.mjs +120 -7
- package/bin/lean/selfreview.mjs +1 -1
- package/bin/lean/slo.mjs +126 -0
- package/bin/lean/slo.test.mjs +112 -0
- package/bin/lean/statuscomment.mjs +40 -0
- package/bin/lean/statuscomment.test.mjs +48 -1
- package/bin/lean/validate-catalog.mjs +108 -0
- package/bin/lean/validate-catalog.test.mjs +46 -1
- package/bin/lean/verify.mjs +3 -2
- package/bin/pool/affinity.test.mjs +91 -0
- package/bin/pool/agent.mjs +144 -10
- package/bin/pool/cache-sweep.mjs +31 -10
- package/bin/pool/ci-autoscale.mjs +160 -0
- package/bin/pool/cli.mjs +53 -9
- package/bin/pool/docker.mjs +3 -0
- package/bin/pool/engine-placement.test.mjs +94 -0
- package/bin/pool/lane-target.mjs +41 -0
- package/bin/pool/lane-tools.mjs +26 -0
- package/bin/pool/lane-tools.test.mjs +9 -0
- package/bin/pool/mirror-seed.mjs +15 -11
- package/bin/pool/router.mjs +88 -32
- package/bin/pool/version.mjs +29 -2
- package/bin/review-staging.mjs +11 -3
- package/bin/runner.mjs +59 -11
- 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/bin/stats/release.mjs +7 -0
- package/bin/stats/release.test.mjs +20 -0
- package/bin/stats/scorecard.mjs +187 -0
- package/bin/stats/scorecard.test.mjs +89 -0
- package/commands/orchestrate.md +21 -18
- package/docs/CONFIG.md +41 -0
- package/docs/OUTCOME-CODES.md +2 -0
- package/docs/STATS.md +17 -0
- package/package.json +1 -1
- package/pool/image/Dockerfile +14 -2
- package/pool/image/manifest.json +25 -0
- package/pool/image/mirror.sh +11 -2
- package/pool/install/install-agent.ps1 +11 -4
- package/scripts/check-devdocs-freshness.sh +1 -1
- package/scripts/ci-local/adapters/github-actions.mjs +8 -0
- package/scripts/ci-local/cli.mjs +1 -1
- package/scripts/ci-local/plan.mjs +3 -2
- package/scripts/ci-local.test.sh +11 -0
- package/scripts/failure-census.mjs +67 -0
- package/scripts/review-finalize.sh +5 -5
- package/scripts/review-finalize.test.sh +8 -1
- package/scripts/verify-phase-trail.sh +11 -0
- package/scripts/verify-phase-trail.test.sh +9 -0
package/bin/config-schema.mjs
CHANGED
|
@@ -43,8 +43,11 @@ export const TYPES = {
|
|
|
43
43
|
"verification.ci_local.extra_commands": "list",
|
|
44
44
|
"verification.ci_local.budget_minutes": "number",
|
|
45
45
|
"verification.ci_local.max_parallel": "number",
|
|
46
|
+
"review.max_parallel": "posint", // #6098: release-review reviewers in flight at once (default max(2, cores/2))
|
|
46
47
|
"orchestration.merge_train": { enum: ["off", "on"] }, // #5836: lanes end pr-ready and the batch merge train merges (default off)
|
|
47
48
|
"orchestration.merge_train_batch": "posint", // #5837: up to N green PRs of one base validated together on a candidate ref (default 4)
|
|
49
|
+
"orchestration.max_attempts_per_issue": "posint", // #5986: lifetime lanes per issue before one FORGE:ESCALATION (default 4)
|
|
50
|
+
"orchestration.max_identical_signature": "posint", // #5986: identical failure signatures tolerated per issue (default 2)
|
|
48
51
|
"env.snapshots.enabled": "bool",
|
|
49
52
|
"env.snapshots.store": { enum: ["local", "oci"] },
|
|
50
53
|
"env.snapshots.keep": "number",
|
|
@@ -61,6 +61,7 @@ export const OUTCOME_CODES = Object.freeze({
|
|
|
61
61
|
ENV_REPRO_UNRUNNABLE: "env.repro_unrunnable", // forge#4334: the repro harness could not run the repro test on head; an environment error, not a conformance failure
|
|
62
62
|
ENV_LANE_LIMIT: "env.lane_limit", // forge#4690: the lane hit its own scope limit (TasksMax or MemoryMax) and was stopped; an environment error, never an engine-error, so the breaker ignores it
|
|
63
63
|
ENV_CAPABILITY_REMOTE: "env.capability_remote", // forge#4542: a remote sandbox lane blocked only on a host-only capability (SOPS key, ops credentials, prod monitor SSH) the dispatching host has; recovered locally
|
|
64
|
+
ENV_ENGINE_SKEW: "env.engine_skew", // forge#5931: the sandbox ran a different engine version than the host; an environment error (gates fixed in the host version still fire), never conformance
|
|
64
65
|
SANDBOX_START_FAILED: "sandbox.start_failed", // forge#4254: a lane sandbox could not start (a non-auth 4xx/config error or a non-HTTP start failure); needs-human, not relaunched
|
|
65
66
|
BASE_RED: "base.red", // forge#5239: a verify.invariants guard fails on the base too; the lane is deferred behind the introducing issue, never needs-human
|
|
66
67
|
SANDBOX_CAPACITY: "sandbox.capacity", // forge#4254: the sandbox provider had no capacity; deferred with backoff
|
|
@@ -101,6 +102,7 @@ export const OUTCOME_CODES = Object.freeze({
|
|
|
101
102
|
CONFORMANCE_UNIMPLEMENTED: "conformance.unimplemented",
|
|
102
103
|
CONFORMANCE_E2E_UNVERIFIED: "conformance.e2e_unverified",
|
|
103
104
|
CONFORMANCE_SCOPE_CREEP: "conformance.scope_creep",
|
|
105
|
+
FAILURE_REPEATED: "failure.repeated", // #5979: the same failure twice; parked, never recovered (kept out of RECOVERABLE_CODES)
|
|
104
106
|
CONFORMANCE_UNTRACKED_DEFERRAL: "conformance.untracked_deferral",
|
|
105
107
|
CONFORMANCE_UNJUSTIFIED_DEFERRAL: "conformance.unjustified_deferral",
|
|
106
108
|
CONFORMANCE_PRESERVE_VIOLATED: "conformance.preserve_violated",
|
package/bin/engine-cli.mjs
CHANGED
|
@@ -23,7 +23,8 @@ import { localLaneCap, ADMISSION_DEFAULTS } from "./lean/admission.mjs";
|
|
|
23
23
|
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
|
-
import { runIssue, DEFAULT_MAX_ATTEMPTS, sanitizeLeaseHost, ENGINE_VERSION } from "./engine.mjs";
|
|
26
|
+
import { holdResumePlan, holdTtlRefusal, 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,8 @@ 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";
|
|
57
|
+
import { cmpVersion } from "./pool/version.mjs";
|
|
55
58
|
import * as _autoChildren from "./lean/autochildren.mjs";
|
|
56
59
|
|
|
57
60
|
/**
|
|
@@ -497,10 +500,11 @@ export function readVerify(cwd = process.cwd()) {
|
|
|
497
500
|
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
501
|
} catch { return undefined; }
|
|
499
502
|
}
|
|
500
|
-
/** #4542: forge.yaml `execution.host_capabilities` (+ patterns) for a lane's remote-block mapping
|
|
503
|
+
/** #4542: forge.yaml `execution.host_capabilities` (+ patterns) for a lane's remote-block mapping, plus `offload_wrappers`; undefined when none are declared. */
|
|
501
504
|
export function readHostCaps(cwd = process.cwd()) {
|
|
502
505
|
const e = readExecution(cwd);
|
|
503
|
-
|
|
506
|
+
if (!e?.hostCapabilities?.length && !e?.offloadWrappers?.length) return undefined;
|
|
507
|
+
return { hostCapabilities: e.hostCapabilities ?? [], ...(e.hostCapabilityPatterns ? { hostCapabilityPatterns: e.hostCapabilityPatterns } : {}), ...(e.offloadWrappers ? { offloadWrappers: e.offloadWrappers } : {}) };
|
|
504
508
|
}
|
|
505
509
|
/** #4778: the capabilities the dispatching host relays to this sandbox lane (`CS_RELAY_CAPS`, set by the remote provider); `{}` when none. */
|
|
506
510
|
export function readRelayCaps(env = process.env) {
|
|
@@ -518,7 +522,8 @@ export function readRelayCaps(env = process.env) {
|
|
|
518
522
|
export function readHostFallback(cwd = process.cwd()) {
|
|
519
523
|
let hostRole = null;
|
|
520
524
|
try { hostRole = parseForgeYaml(readFileSync(join(cwd, "forge.yaml"), "utf8"))?.host?.role ?? null; } catch { /* unreadable: role unset */ }
|
|
521
|
-
|
|
525
|
+
const exec = readExecution(cwd);
|
|
526
|
+
return hostFallbackAllowed({ hostFallback: exec?.hostFallback ?? null, hostRole, mode: exec?.mode ?? null });
|
|
522
527
|
}
|
|
523
528
|
export function readExecution(cwd = process.cwd()) {
|
|
524
529
|
try {
|
|
@@ -526,6 +531,10 @@ export function readExecution(cwd = process.cwd()) {
|
|
|
526
531
|
return sec && typeof sec === "object" ? parseExecution(sec) : undefined;
|
|
527
532
|
} catch { return undefined; }
|
|
528
533
|
}
|
|
534
|
+
/** R2: forge.yaml `execution.min_lane_engine` (a version string such as 1.67); undefined when unset or unreadable. */
|
|
535
|
+
export function readMinLaneEngine(cwd = process.cwd()) {
|
|
536
|
+
try { const v = String(parseForgeYaml(readFileSync(join(cwd, "forge.yaml"), "utf8"))?.execution?.min_lane_engine ?? "").trim(); return /^v?\d+(\.\d+)*$/.test(v) ? v.replace(/^v/, "") : undefined; } catch { return undefined; }
|
|
537
|
+
}
|
|
529
538
|
/** #5748: forge.yaml sets a valid `execution.mode` (even `local`): the explicit opt-out from the public-repo default. */
|
|
530
539
|
export function executionModeExplicit(cwd = process.cwd()) {
|
|
531
540
|
try { return ["local", "remote", "hybrid"].includes(String(parseForgeYaml(readFileSync(join(cwd, "forge.yaml"), "utf8"))?.execution?.mode ?? "").trim()); } catch { return false; }
|
|
@@ -652,7 +661,7 @@ export function readEnvConfig(cwd = process.cwd()) {
|
|
|
652
661
|
let appPages = false; // #5428: default-on trigger: the repo tracks Next app/**/page.* files
|
|
653
662
|
try { appPages = String(execFileSync("git", ["ls-files", "--", "*page.*"], { cwd, encoding: "utf8", timeout: 10000, stdio: ["ignore", "pipe", "ignore"] })).split("\n").some((f) => PAGE_RE.test(f)); } catch { /* not a git checkout: off */ }
|
|
654
663
|
const pg = parsePagesConfig(y?.pages, { hasAppPages: appPages }); // #5428: forge.yaml pages: (off for repos without pages)
|
|
655
|
-
const rc = y?.recurrence && typeof y.recurrence === "object" ? parseRecurrenceConfig({ ...y.recurrence, hot_areas: readYamlMap(cwd, "recurrence", "hot_areas")
|
|
664
|
+
const rc = y?.recurrence && typeof y.recurrence === "object" ? parseRecurrenceConfig({ ...y.recurrence, hot_areas: readYamlMap(cwd, "recurrence", "hot_areas") }) : null; // #5751: forge.yaml recurrence: (absent: the engine defaults)
|
|
656
665
|
const dg = parseDesignConfig(y?.design); // #5330: forge.yaml design: (system always read; routes/gate opt in the design gate)
|
|
657
666
|
const kb = typeof e.sparse_max_kb === "string" && /^\d+$/.test(e.sparse_max_kb.trim()) ? Number(e.sparse_max_kb) : e.sparse_max_kb;
|
|
658
667
|
return { ...(s(e.toolchain) ? { toolchainOverride: s(e.toolchain) } : {}), ...(s(e.setup) ? { envSetup: s(e.setup) } : {}),
|
|
@@ -1124,7 +1133,12 @@ export async function runFromCli(argv, deps = {}) {
|
|
|
1124
1133
|
if (interrupted) return;
|
|
1125
1134
|
interrupted = true;
|
|
1126
1135
|
let r = null;
|
|
1127
|
-
|
|
1136
|
+
// #6081: a teardown that hangs (a builder child that ignores SIGTERM, a blocked git call) must not leave the lane alive after the operator stop:
|
|
1137
|
+
// bounded, then the lane reports and exits anyway.
|
|
1138
|
+
const bound = Number(deps.teardownMs ?? process.env.FORGEDOCK_TEARDOWN_MS) > 0 ? Number(deps.teardownMs ?? process.env.FORGEDOCK_TEARDOWN_MS) : 30000;
|
|
1139
|
+
let timer;
|
|
1140
|
+
try { r = teardown ? await Promise.race([teardown(sig), new Promise((res) => { timer = setTimeout(() => res(null), bound); })]) : null; } catch { r = null; }
|
|
1141
|
+
clearTimeout(timer);
|
|
1128
1142
|
try { report({ ...(r ?? {}), terminalReason: "deferred", code: OUTCOME_CODES.RUN_INTERRUPTED, detail: r?.detail ?? `interrupted by ${sig}` }); } catch { /* exit anyway */ }
|
|
1129
1143
|
console.log(`issue #${issue} → deferred (interrupted by ${sig})`);
|
|
1130
1144
|
exit(128 + SIGNO[sig]);
|
|
@@ -1132,10 +1146,12 @@ export async function runFromCli(argv, deps = {}) {
|
|
|
1132
1146
|
for (const [sig, f] of Object.entries(handlers)) on(sig, f);
|
|
1133
1147
|
const env = deps.env ?? process.env;
|
|
1134
1148
|
let lres;
|
|
1149
|
+
// #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
|
|
1150
|
+
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
1151
|
try {
|
|
1136
1152
|
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
1153
|
...(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 } : {}),
|
|
1154
|
+
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
1155
|
emitTelemetry: deps.emitTelemetry ?? composeEmit(makeEmitTelemetry({ repo: leanRepo }), makeEventEmitter({ repo: leanRepo, config: readEvents() }).emit),
|
|
1140
1156
|
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
1157
|
} catch (e) { if (!interrupted) report({ terminalReason: "engine-error", detail: String(e?.message ?? e).slice(0, 500) }); throw e; }
|
|
@@ -1396,8 +1412,8 @@ async function envBatch({ argv, root, print = (l) => console.log(l) }) {
|
|
|
1396
1412
|
return { ok: true, batch: id };
|
|
1397
1413
|
}
|
|
1398
1414
|
|
|
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"];
|
|
1415
|
+
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";
|
|
1416
|
+
const ORCH_VALUED = ["--parallel", "--lane", "--repo", "--model", "--prefilter-model", "--reason", "--force", "--auto-children", "--epic", "--for", "--ttl", "--select"];
|
|
1401
1417
|
const issuesOf = (argv) => {
|
|
1402
1418
|
const issues = [];
|
|
1403
1419
|
for (let i = 0; i < argv.length; i++) {
|
|
@@ -1406,6 +1422,50 @@ const issuesOf = (argv) => {
|
|
|
1406
1422
|
}
|
|
1407
1423
|
return issues;
|
|
1408
1424
|
};
|
|
1425
|
+
/**
|
|
1426
|
+
* #5978: `--status <id>`: the coverage of a selector batch: running + queued + backing-off + waiting on deps + human-blocked = the open
|
|
1427
|
+
* issues its selector matches; `unscheduled` is 0 when the order is healthy. A batch without a selector reports its own counts.
|
|
1428
|
+
*/
|
|
1429
|
+
/** #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. */
|
|
1430
|
+
const suspendMarker = (projector, batchId) => async (n, on, reason) => {
|
|
1431
|
+
const cur = (await projector.readState(n)) ?? {};
|
|
1432
|
+
if (on) await projector.writeState(n, { ...cur, suspend: { reason, batch: batchId, at: new Date().toISOString() } });
|
|
1433
|
+
else if (cur.suspend) { const { suspend: _s, ...rest } = cur; await projector.writeState(n, rest); }
|
|
1434
|
+
};
|
|
1435
|
+
async function statusBatch({ id, root, io, print = (l) => console.log(l) }) {
|
|
1436
|
+
const batchMod = await import("./lean/batch.mjs"), { selectArgs, parseSelected } = await import("./lean/reconcile.mjs");
|
|
1437
|
+
if (!id || String(id).startsWith("--")) throw new Error(ORCH_USAGE);
|
|
1438
|
+
const b = batchMod.openBatch(root, id), plan = b.readPlan(), st = b.store.load();
|
|
1439
|
+
if (!plan || !st) throw new Error(`no batch ${id} in ${root}`);
|
|
1440
|
+
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
|
|
1441
|
+
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(", ")}`); };
|
|
1442
|
+
showKept();
|
|
1443
|
+
const select = flag(plan.argv ?? [], "--select");
|
|
1444
|
+
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: [] }; }
|
|
1445
|
+
const open = parseSelected(await io.gh(selectArgs(plan.repo, select)));
|
|
1446
|
+
if (!open) throw new Error(`cannot read the issues matching '${select}'`);
|
|
1447
|
+
const c = batchMod.coverage({ state: st, open });
|
|
1448
|
+
const n = (k) => c[k].length;
|
|
1449
|
+
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`);
|
|
1450
|
+
if (c.humanBlocked.length) print(`human-blocked: ${c.humanBlocked.map((x) => `#${x}`).join(", ")}`);
|
|
1451
|
+
print(c.unscheduled.length ? `UNSCHEDULED (${c.unscheduled.length}): ${c.unscheduled.map((x) => `#${x}`).join(", ")}` : "unscheduled: 0 (healthy)");
|
|
1452
|
+
return { ok: true, batch: id, coverage: c, unscheduled: c.unscheduled, kept };
|
|
1453
|
+
}
|
|
1454
|
+
/** #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. */
|
|
1455
|
+
async function makeReconcile({ select, repo, leanIo, orch, lane, argv }) {
|
|
1456
|
+
const { selectArgs, parseSelected, RECONCILE_MS } = await import("./lean/reconcile.mjs");
|
|
1457
|
+
const rollup = Number.parseInt(process.env.FORGE_POSTDEPLOY_ROLLUP ?? "", 10) > 0 ? Number.parseInt(process.env.FORGE_POSTDEPLOY_ROLLUP, 10) : null;
|
|
1458
|
+
return {
|
|
1459
|
+
everyMs: RECONCILE_MS,
|
|
1460
|
+
list: async () => parseSelected(await leanIo.gh(selectArgs(repo, select))),
|
|
1461
|
+
version: () => `${ENGINE_VERSION}|${process.env.FORGE_LANE_IMAGE ?? ""}`,
|
|
1462
|
+
base: async () => { try { return String(await leanIo.gh(["api", `repos/${repo}/commits/${lane || flag(argv, "--lane") || "staging"}`, "--jq", ".sha"])).trim() || null; } catch { return null; } },
|
|
1463
|
+
closeIssue: async (n, { lane: l }) => {
|
|
1464
|
+
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).`]);
|
|
1465
|
+
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.`]);
|
|
1466
|
+
},
|
|
1467
|
+
};
|
|
1468
|
+
}
|
|
1409
1469
|
/** #5471: the reason of `--force <reason>` (null when absent or valueless): lifts the cross-batch ownership skip. */
|
|
1410
1470
|
const forceOf = (argv) => { const v = flag(argv, "--force"); return v && !String(v).startsWith("--") ? v : null; };
|
|
1411
1471
|
/** #4469: the operands among `tokens` (`--add`/`--resume` extras): no flags, and no value of a valued flag (`--parallel 5` is not issue #5). */
|
|
@@ -1530,7 +1590,7 @@ function parseHoldFor(v) {
|
|
|
1530
1590
|
}
|
|
1531
1591
|
/** #5469: the hold's owner (the operator session: the CLI's parent pid on this host), expiry (`--for`) and `--reason`. */
|
|
1532
1592
|
function holdMeta(argv) {
|
|
1533
|
-
const forLabel = flag(argv, "--for"), reason = flag(argv, "--reason");
|
|
1593
|
+
const forLabel = flag(argv, "--for") ?? flag(argv, "--ttl"), reason = flag(argv, "--reason");
|
|
1534
1594
|
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
1595
|
}
|
|
1536
1596
|
|
|
@@ -1579,7 +1639,12 @@ async function pauseBatch({ op, id, root, viaDaemon = null, meta = null, print =
|
|
|
1579
1639
|
*/
|
|
1580
1640
|
async function holdBatch({ op, id, tokens, root, viaDaemon = null, takeover = null, meta = null, print = (l) => console.log(l) }) {
|
|
1581
1641
|
const issues = tokens.filter((t) => /^#?\d+$/.test(String(t))).map((t) => parseInt(String(t).replace("#", ""), 10));
|
|
1642
|
+
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
|
|
1643
|
+
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 */ }
|
|
1644
|
+
}
|
|
1582
1645
|
if (!id || String(id).startsWith("--") || !issues.length) throw new Error(ORCH_USAGE);
|
|
1646
|
+
const refusal = op === "hold" ? holdTtlRefusal(issues, meta?.forMs) : null; // #5988
|
|
1647
|
+
if (refusal) throw new Error(refusal);
|
|
1583
1648
|
let res = viaDaemon ? await viaDaemon(op, issues, meta) : null;
|
|
1584
1649
|
if (!res) {
|
|
1585
1650
|
const b = (await import("./lean/batch.mjs")).openBatch(root, id);
|
|
@@ -1600,6 +1665,7 @@ async function holdBatch({ op, id, tokens, root, viaDaemon = null, takeover = nu
|
|
|
1600
1665
|
const list = (res.changed ?? []).map((n) => `#${n}`).join(" ") || "(none)";
|
|
1601
1666
|
print(op === "hold" ? `batch ${id}: held ${list}${meta?.forMs ? ` for ${meta.forLabel}` : ""}; forgedock orchestrate --release ${id} <issue...> (or --resume ${id} <issue...>) re-admits them`
|
|
1602
1667
|
: `batch ${id}: released ${list}`);
|
|
1668
|
+
if (op === "hold" && issues.length > 1) print(holdResumePlan(res.changed?.length ? res.changed : issues, meta?.forLabel)); // #5988
|
|
1603
1669
|
return { ok: true, batch: id, changed: res.changed ?? [] };
|
|
1604
1670
|
}
|
|
1605
1671
|
|
|
@@ -1737,6 +1803,7 @@ async function orchestrateClient(argv, deps = {}) {
|
|
|
1737
1803
|
const i = argv.indexOf("--requeue"), id = argv[i + 1];
|
|
1738
1804
|
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
1805
|
}
|
|
1806
|
+
if (argv.includes("--status")) return statusBatch({ id: flag(argv, "--status"), root: await batchRootOf(), io: deps.io ?? makeIo() });
|
|
1740
1807
|
if (argv.includes("--gc-orphans")) return gcOrphans({ root: await batchRootOf(), viaDaemon: async () => {
|
|
1741
1808
|
let sock = null;
|
|
1742
1809
|
try { sock = await schedd.connectDaemon({ dir, spawnDaemon: null }); } catch { sock = null; }
|
|
@@ -1766,7 +1833,7 @@ async function orchestrateClient(argv, deps = {}) {
|
|
|
1766
1833
|
let msg;
|
|
1767
1834
|
if (resumeId) msg = { op: "attach", id: resumeId, resume: true };
|
|
1768
1835
|
else {
|
|
1769
|
-
if (!issuesOf(argv).length) throw new Error(ORCH_USAGE);
|
|
1836
|
+
if (!issuesOf(argv).length && !flag(argv, "--select")) throw new Error(ORCH_USAGE);
|
|
1770
1837
|
parallelOf(argv);
|
|
1771
1838
|
let sub = [...argv];
|
|
1772
1839
|
if (!flag(sub, "--repo")) {
|
|
@@ -1869,6 +1936,7 @@ export async function runBatch({ argv, cwd: callerCwd = process.cwd(), env: call
|
|
|
1869
1936
|
const i = argv.indexOf("--requeue");
|
|
1870
1937
|
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
1938
|
}
|
|
1939
|
+
if (argv.includes("--status")) return statusBatch({ id: flag(argv, "--status"), root, io: deps.io ?? makeIo(), print: (l) => sink.line(l) });
|
|
1872
1940
|
if (argv.includes("--gc-orphans")) return gcOrphans({ root, print: (l) => sink.line(l) });
|
|
1873
1941
|
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
1942
|
return pauseBatch({ op, id: flag(argv, flagName), root, meta: op === "pause" ? holdMetaAll(argv) : null, print: (l) => sink.line(l) });
|
|
@@ -1901,7 +1969,8 @@ export async function runBatch({ argv, cwd: callerCwd = process.cwd(), env: call
|
|
|
1901
1969
|
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
1970
|
}
|
|
1903
1971
|
let issues = issuesOf(argv);
|
|
1904
|
-
|
|
1972
|
+
const select = flag(argv, "--select"); // #5978: a standing order: the selector is kept in plan.argv and in the batch state
|
|
1973
|
+
if (!issues.length && !select) throw new Error(ORCH_USAGE);
|
|
1905
1974
|
const parallel = parallelOf(argv);
|
|
1906
1975
|
// The lanes' env: a resumed daemon batch uses the env its plan kept, over the daemon's own.
|
|
1907
1976
|
// A pre-#4192 batch resumed by the daemon kept no env: its lanes use the daemon's.
|
|
@@ -2044,6 +2113,8 @@ export async function runBatch({ argv, cwd: callerCwd = process.cwd(), env: call
|
|
|
2044
2113
|
const needsOf = new Map(); // issue -> host-only capabilities its body names (#4542), filled by readBody
|
|
2045
2114
|
const prefetchOf = new Map(); // issue -> the frozen contract's relayable read-only commands (#4778), filled by readBody
|
|
2046
2115
|
let execForNeeds = null;
|
|
2116
|
+
let poolUsage = []; // #5985: pool usage-history rows (cpu_avg per repo), refreshed in the background; classify lanes light/heavy
|
|
2117
|
+
let agentEngine = null;
|
|
2047
2118
|
let lanes, remote = null, execBudget = null, execConf = null, hybrid = false;
|
|
2048
2119
|
const execMode = () => (deps.execution !== undefined ? deps.execution : readExecution(cwd))?.mode ?? "local";
|
|
2049
2120
|
if (deps.leanModule) {
|
|
@@ -2051,6 +2122,7 @@ export async function runBatch({ argv, cwd: callerCwd = process.cwd(), env: call
|
|
|
2051
2122
|
const emitTelemetry = deps.emitTelemetry ?? makeEmitTelemetry({ repo });
|
|
2052
2123
|
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
2124
|
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,
|
|
2125
|
+
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
2126
|
...(rotatorKind({ execution: readExecution(cwd), env }) ? { accountRotator: rotatorKind({ execution: readExecution(cwd), env }) } : {}), // #5094, #5205: detected
|
|
2055
2127
|
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
2128
|
} else {
|
|
@@ -2081,7 +2153,9 @@ export async function runBatch({ argv, cwd: callerCwd = process.cwd(), env: call
|
|
|
2081
2153
|
return l.runOne(n, ln, ctx);
|
|
2082
2154
|
}, adopt: l.adopt });
|
|
2083
2155
|
const execMod = await import("./lean/execution.mjs");
|
|
2084
|
-
const
|
|
2156
|
+
const exec0 = deps.execution !== undefined ? deps.execution : await withPublicDefault(readExecution(cwd), { cwd, repo, gh: (a) => leanIo.gh(a, { cwd }), deps }); // #5748
|
|
2157
|
+
const minLane = readMinLaneEngine(cwd); // R2: execution.min_lane_engine, unset = lower-engine agents are a fallback
|
|
2158
|
+
const exec = exec0 && minLane && exec0.minLaneEngine === undefined ? { ...exec0, minLaneEngine: minLane } : exec0;
|
|
2085
2159
|
execForNeeds = exec ?? null;
|
|
2086
2160
|
hybrid = exec?.mode === "hybrid" && Number.isInteger(exec.maxRemote) && exec.maxRemote >= 1;
|
|
2087
2161
|
let remoteStop = null; // #4612: the sandbox provider's checkpoint stop, used only when the cancel asks for it
|
|
@@ -2094,11 +2168,15 @@ export async function runBatch({ argv, cwd: callerCwd = process.cwd(), env: call
|
|
|
2094
2168
|
const ledgerFor = deps.sandboxLedger ?? ((n) => makeLedger({ batch: batch.id, lane: `sandbox-${n}`, owner: `orch_${process.pid}`, issue: n }));
|
|
2095
2169
|
const bud = exec.budget ?? {};
|
|
2096
2170
|
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,
|
|
2171
|
+
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
2172
|
...(Number.isFinite(exec.unreachableWindowMin) ? { unreachableWindowMs: exec.unreachableWindowMin * 60000 } : {}),
|
|
2099
2173
|
...(deps.now ? { now: deps.now } : {}), ...(deps.pollMs ? { pollMs: deps.pollMs } : {}),
|
|
2100
2174
|
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
|
|
2101
2175
|
remoteStop = remoteLanes.stopLane;
|
|
2176
|
+
agentEngine = async () => { // R6: the lane engine of the agent that would run a lane (the best placeable one)
|
|
2177
|
+
const best = ((await provider.capacity?.())?.agents ?? []).filter((a) => a.ok && !a.paused).map((a) => a.engine_version).sort((a, b) => cmpVersion(b, a) ?? 0)[0];
|
|
2178
|
+
return best ?? null;
|
|
2179
|
+
};
|
|
2102
2180
|
lanes = withPlacement(remoteLanes);
|
|
2103
2181
|
{
|
|
2104
2182
|
// #4255: once the budget refuses a remote lane, the rest run as detached host lanes. #4256: hybrid mixes both.
|
|
@@ -2126,24 +2204,28 @@ export async function runBatch({ argv, cwd: callerCwd = process.cwd(), env: call
|
|
|
2126
2204
|
if (batch.readExecution()?.provider !== true) batch.setExecution({ provider: true });
|
|
2127
2205
|
// #4540: provider free slots, refreshed in the background (admission is sync); unknown (null) never blocks.
|
|
2128
2206
|
let capSample = null, onlineSample = null, capAt = 0, capLast = -Infinity, capFailed = false; // #5048: capFailed = last probe rejected // #4547: online = agents alive, null unknown
|
|
2207
|
+
let liveSample = {}, usageLast = -Infinity; // #5985: the pool's live load/memory ride the capacity sample
|
|
2129
2208
|
const capacity = () => {
|
|
2209
|
+
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
2210
|
if (capFailed) throw new Error("capacity probe failed"); // #5048: until the next successful sample, so every caller sees it (release review CONC-1)
|
|
2131
2211
|
const t = deps.now ? deps.now() : Date.now();
|
|
2132
2212
|
if (typeof provider.capacity === "function" && t - capLast >= (deps.pollMs ?? 5000)) {
|
|
2133
2213
|
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++; });
|
|
2214
|
+
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
2215
|
}
|
|
2136
|
-
return capSample === null && onlineSample === null ? null : { free: capSample, online: onlineSample, at: capAt };
|
|
2216
|
+
return capSample === null && onlineSample === null ? null : { free: capSample, online: onlineSample, ...liveSample, at: capAt };
|
|
2137
2217
|
};
|
|
2138
2218
|
remote = liveExec.liveRemote({
|
|
2139
2219
|
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
2220
|
admit: (u) => execBudget.admit(u),
|
|
2141
2221
|
onUsage: (n, sb, rec) => {
|
|
2142
|
-
|
|
2143
|
-
try { execBudget.record(`${batch.id}#${sb.id ?? n}#${startedAt}`, sb); } catch { /* the batch total still counts it */ }
|
|
2222
|
+
try { execBudget.record(sandboxBudgetKey(batch.id, sb.id ?? n, rec?.handle?.startedAt ?? rec?.startedAt ?? null), sb); } catch { /* the batch total still counts it */ }
|
|
2144
2223
|
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
2224
|
},
|
|
2146
|
-
}, { exec, readOverride: batch.readExecution, place, onChange: (e) => sink.line(`execution: live placement ${e.mode}, max_remote ${e.maxRemote}`)
|
|
2225
|
+
}, { exec, readOverride: batch.readExecution, place, onChange: (e) => sink.line(`execution: live placement ${e.mode}, max_remote ${e.maxRemote}`),
|
|
2226
|
+
// #5746: a live max_remote left below the pinned value is announced once after FORGEDOCK_MAX_REMOTE_WARN_HOURS (default 6)
|
|
2227
|
+
belowPinnedHours: Number(process.env.FORGEDOCK_MAX_REMOTE_WARN_HOURS) || undefined,
|
|
2228
|
+
onBelowPinned: (w) => sink.line(`WARNING: execution: live max_remote ${w.maxRemote} has been below the pinned ${w.pinned} for over ${w.hours}h (forgedock orchestrate --set-max-remote ${batch.id} ${w.pinned} restores it)`) });
|
|
2147
2229
|
sink.line(`execution: ${hybrid ? "hybrid" : "remote"} via ${provider.name}, max_remote ${exec.maxRemote}`);
|
|
2148
2230
|
} else {
|
|
2149
2231
|
lanes = withPlacement(batchMod.detachedLanes({ batch, cwd, env: laneEnv, script: laneScript, bin: deps.laneBin, pollMs: deps.pollMs, laneArgs, spawnFn: laneSpawn }));
|
|
@@ -2154,7 +2236,9 @@ export async function runBatch({ argv, cwd: callerCwd = process.cwd(), env: call
|
|
|
2154
2236
|
const stopLane = deps.stopLane ?? ((n, rec) => (rec?.remote || rec?.handle ? remoteStop?.(n, rec) ?? false : rec?.pid ? killLedgerPid(rec.pid, batch.resultFile(n)) : false));
|
|
2155
2237
|
// #5241: a cancelled lane that ended gives its issue lease back, unless a live lane of another batch runs the issue.
|
|
2156
2238
|
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
|
-
|
|
2239
|
+
// #6008: hold/pause/keep reach a kept sandbox through the `suspend` marker on the issue's FORGE:STATE (the sandbox cannot read batch files)
|
|
2240
|
+
const suspendLane = deps.suspendLane ?? (leanIo?.projector ? suspendMarker(leanIo.projector, batch.id) : null);
|
|
2241
|
+
lanes = { ...lanes, stopLane, releaseLease, suspendLane };
|
|
2158
2242
|
}
|
|
2159
2243
|
const orch = deps.orchestration ?? readOrchestration(cwd);
|
|
2160
2244
|
const train = orch.mergeTrain === "on" ? (deps.train ?? (await import("./lean/mergetrain.mjs")).createMergeTrain({ gh: (a) => leanIo.gh(a), repo, batchSize: orch.mergeTrainBatch ?? 4,
|
|
@@ -2179,8 +2263,8 @@ export async function runBatch({ argv, cwd: callerCwd = process.cwd(), env: call
|
|
|
2179
2263
|
const schedMod = await import("./lean/sched.mjs");
|
|
2180
2264
|
const registry = deps.sched !== undefined ? deps.sched : schedMod.openSched(schedMod.schedDir());
|
|
2181
2265
|
const overload = deps.overload !== undefined ? deps.overload : registry ? liveOverload(readAdmission(cwd)) : null; // #5174
|
|
2182
|
-
const labelNames = async (n) => {
|
|
2183
|
-
if (!labelsOf.has(n)) labelsOf.set(n, (JSON.parse(await leanIo.gh(["issue", "view", String(n), "-R", repo, "--json", "labels"])).labels ?? []).map((x) => x.name));
|
|
2266
|
+
const labelNames = async (n, { fresh = false } = {}) => { // #5893: `fresh` re-reads (the readmit decision); the cache serves placement
|
|
2267
|
+
if (fresh || !labelsOf.has(n)) labelsOf.set(n, (JSON.parse(await leanIo.gh(["issue", "view", String(n), "-R", repo, "--json", "labels"])).labels ?? []).map((x) => x.name));
|
|
2184
2268
|
return labelsOf.get(n);
|
|
2185
2269
|
};
|
|
2186
2270
|
let budget = {};
|
|
@@ -2288,10 +2372,25 @@ export async function runBatch({ argv, cwd: callerCwd = process.cwd(), env: call
|
|
|
2288
2372
|
const hostIo = await laneCheck.hostLaneIo({ env });
|
|
2289
2373
|
preflight = async () => (await laneCheck.runLaneChecks({ exec: execForNeeds, env, io: hostIo })).filter((c) => !c.ok);
|
|
2290
2374
|
}
|
|
2375
|
+
// #5992: the base is probed once per (repo, base sha) on the dispatcher, before any sandbox launch; a red verdict holds admissions.
|
|
2376
|
+
let baseProbe = deps.baseProbe === undefined ? null : deps.baseProbe;
|
|
2377
|
+
const guardCmds = readInvariants(cwd) ?? [];
|
|
2378
|
+
if (deps.baseProbe === undefined && !testDeps && guardCmds.length) {
|
|
2379
|
+
const { probeBase } = await import("./lean/basered.mjs"), { runCheckCommand } = await import("./lean/effects.mjs");
|
|
2380
|
+
const baseRef = readBranches(cwd).staging ?? readBranches(cwd).default ?? "main", vcfg = readVerify(cwd) ?? {};
|
|
2381
|
+
const gitIn = (a) => leanIo.git(a, { cwd });
|
|
2382
|
+
const readSha = async () => {
|
|
2383
|
+
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 */ }
|
|
2384
|
+
return gitIn(["rev-parse", `origin/${baseRef}`]);
|
|
2385
|
+
};
|
|
2386
|
+
baseProbe = () => probeBase({ repo, base: baseRef, commands: guardCmds, readSha, git: gitIn, runCommand: runCheckCommand, cwd, env, timeoutMs: (vcfg.precheckTimeoutSeconds ?? 300) * 1000 });
|
|
2387
|
+
}
|
|
2291
2388
|
const { hostMissingTools } = await import("./lean/toolplace.mjs");
|
|
2292
2389
|
const envHold = deps.envHold !== undefined ? deps.envHold : testDeps ? null : {
|
|
2293
2390
|
version: () => scheddMod.readInstalledVersion() ?? ENGINE_VERSION,
|
|
2294
2391
|
envFingerprint: () => batchMod.envFingerprint(batch.readPlan()?.env),
|
|
2392
|
+
envValues: () => batch.readPlan()?.env ?? null, // #5931
|
|
2393
|
+
agentVersion: async () => (agentEngine ? agentEngine() : null), // R6: re-admission of a remote lane checks the agent that will run it
|
|
2295
2394
|
missingTools: async (tools) => { const p = batch.readPlan()?.env, e = p ? scheddMod.mergeEnv(process.env, p) : env; return hostMissingTools(tools, { path: e.PATH ?? e.Path ?? "" }); },
|
|
2296
2395
|
};
|
|
2297
2396
|
// #4785: decisions and the frozen contract's validate commands too. #5824: one view per issue; the plan pass's view is
|
|
@@ -2321,6 +2420,12 @@ export async function runBatch({ argv, cwd: callerCwd = process.cwd(), env: call
|
|
|
2321
2420
|
batch.writePlan({ ...batch.readPlan(), dag: { edges: dag.edges, overlaps: dag.overlaps } });
|
|
2322
2421
|
} catch (e) { sink.line(`plan: n/a (${String(e?.message ?? e).split("\n")[0].slice(0, 160)})`); }
|
|
2323
2422
|
}
|
|
2423
|
+
// #5988: the cheap login probe (`claude auth status`, no model call) on the account the rotator names; ok on exit 0.
|
|
2424
|
+
const authProbeOf = () => async ({ configDir = null } = {}) => {
|
|
2425
|
+
const { spawnSync } = await import("node:child_process");
|
|
2426
|
+
const r = spawnSync("claude", ["auth", "status"], { timeout: 15000, stdio: "ignore", env: { ...process.env, ...(configDir ? { CLAUDE_CONFIG_DIR: configDir } : {}) } });
|
|
2427
|
+
return { ok: !r.error && r.status === 0 };
|
|
2428
|
+
};
|
|
2324
2429
|
let rows, childFields = null; // #4965: the host gh's accepted `issue list --json` fields, read once from its help
|
|
2325
2430
|
const healthCheck = (checkpoint) => batchHealth.runCheck({ batch, checkpoint, config: healthConf, repo, now: healthNow,
|
|
2326
2431
|
resolve: (cands) => batchHealth.resolvedOnGithub(cands, (a) => leanIo.gh(a), repo),
|
|
@@ -2342,16 +2447,24 @@ export async function runBatch({ argv, cwd: callerCwd = process.cwd(), env: call
|
|
|
2342
2447
|
...(estimate ? { estimate } : {}),
|
|
2343
2448
|
beforeAdmit,
|
|
2344
2449
|
...(preflight ? { preflight } : {}),
|
|
2450
|
+
...(baseProbe ? { baseProbe } : {}),
|
|
2345
2451
|
...(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
2452
|
trusted: (n) => trustedOf.get(n) === true,
|
|
2347
2453
|
autoChildren,
|
|
2348
2454
|
...(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 }) }) } : {}),
|
|
2349
|
-
|
|
2455
|
+
...(select ? { select, reconcile: await makeReconcile({ select, repo, leanIo, orch, lane, argv }) } : {}),
|
|
2456
|
+
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, authProbe: authProbeOf(), onEscalate: async ({ detail, issues: affected }) => { // #5988: the 30 min backend.auth escalation: notify + one issue comment
|
|
2457
|
+
const text = `BATCH AUTH OUTAGE ${batch.id}\n ${detail}\n recovery: forgedock orchestrate --resume ${batch.id}`;
|
|
2458
|
+
await batchHealth.deliverAlert({ text, batchId: batch.id, health: null, sink, gh: (a) => leanIo.gh(a), repo, config: { ...healthConf, issue: null }, epics: [], ...(deps.notify ? { notify: deps.notify } : {}) });
|
|
2459
|
+
const n = [...affected].sort((x, y) => x - y)[0];
|
|
2460
|
+
if (Number.isInteger(n) && repo) { try { await leanIo.gh(["issue", "comment", String(n), "-R", repo, "--body", `<!-- FORGE:AUTH-OUTAGE batch=${batch.id} -->\n${text}`]); } catch { /* best effort */ } }
|
|
2461
|
+
},
|
|
2462
|
+
...(typeof remote?.quarantineAgent === "function" ? { quarantineAgent: (q) => remote.quarantineAgent(q) } : {}), ...(typeof remote?.reseedCache === "function" ? { reseedCache: (q) => remote.reseedCache(q) } : {}), getGates: batch.readGates, baseWait: baseWaits.size ? baseWaitOf(baseWaits, { io, leanIo, cwd }) : null, ...lanes,
|
|
2350
2463
|
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
2464
|
...(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
2465
|
// #5174: hold new local admissions while loadavg/cores is above engine.overload_load_per_core (host-wide batches only)
|
|
2353
2466
|
...(overload ? { overload } : {}),
|
|
2354
|
-
...(remote ? { remote } : {}),
|
|
2467
|
+
...(remote ? { remote, usageRows: () => poolUsage, repoSlug: repo } : {}),
|
|
2355
2468
|
// #4267: mechanical needs-human outcomes are recovered in the batch; every runner decision is a FORGE:DECISION.
|
|
2356
2469
|
...(recoveryOn ? { recovery: orch.recovery } : {}),
|
|
2357
2470
|
...(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 +2490,19 @@ export async function runBatch({ argv, cwd: callerCwd = process.cwd(), env: call
|
|
|
2377
2490
|
onInterrupted: deps.onInterrupted ?? (async (n) => leanIo.gh(["issue", "edit", String(n), "-R", repo, "--remove-label", "workflow:building"]).catch(() => {})),
|
|
2378
2491
|
// #4387: an out-of-set dependency labelled needs-human is not pulled into the batch
|
|
2379
2492
|
issueLabels: labelNames,
|
|
2493
|
+
// #5893: a held needs-human root is released only when the label's removal event post-dates the newest FORGE:NEEDS_HUMAN comment
|
|
2494
|
+
heldFacts: deps.heldFacts ?? (async (n) => {
|
|
2495
|
+
// #6102: one timestamp per line, so empty pages add nothing (joined per-page arrays broke on an empty page)
|
|
2496
|
+
const ev = String(await leanIo.gh(["api", `repos/${repo}/issues/${n}/events`, "--paginate", "--jq", ".[] | select(.event==\"unlabeled\" and .label.name==\"needs-human\") | .created_at"])).split("\n").map((l) => l.trim()).filter(Boolean);
|
|
2497
|
+
const cs = JSON.parse(await leanIo.gh(["issue", "view", String(n), "-R", repo, "--json", "comments"])).comments ?? [];
|
|
2498
|
+
const blk = cs.filter((c) => String(c.body ?? "").includes("<!-- FORGE:NEEDS_HUMAN"));
|
|
2499
|
+
const last = blk[blk.length - 1];
|
|
2500
|
+
const ask = cs.filter((c) => /FORGE:ASK key=/.test(String(c.body ?? ""))).pop();
|
|
2501
|
+
const t = (x) => Date.parse(x);
|
|
2502
|
+
return { removedAt: Math.max(...ev.map(t), -Infinity), blockedAt: last ? t(last.createdAt) : NaN, askKey: ask ? (/FORGE:ASK key=([^\s>]+)/.exec(String(ask.body))?.[1] ?? "") : "" };
|
|
2503
|
+
}),
|
|
2504
|
+
// #5986: per-issue attempts ledger and input-hash admission (off under the test seams)
|
|
2505
|
+
...((deps.attempts !== undefined ? deps.attempts : testDeps ? null : true) ? { attempts: deps.attempts !== undefined ? deps.attempts : makeAttemptsSeam({ gh: (a) => leanIo.gh(a), repo, engineVersion: ENGINE_VERSION, hostVersion: scheddMod.readInstalledVersion?.() ?? null, sandboxVersion: deps.sandboxVersion ?? null, cfg: { maxAttempts: orch.maxAttemptsPerIssue, maxIdentical: orch.maxIdenticalSignature } }) } : {}),
|
|
2380
2506
|
// #4725: a closed (completed) dependency is satisfied even when it still carries a stale needs-human label
|
|
2381
2507
|
// #5152: a NOT_PLANNED close labelled workflow:merged, or a decomposition whose sub-issues all closed, is delivered: CLOSED
|
|
2382
2508
|
issueState: async (n) => {
|
|
@@ -2435,6 +2561,7 @@ export async function runBatch({ argv, cwd: callerCwd = process.cwd(), env: call
|
|
|
2435
2561
|
const { batchEfficiency, formatEfficiencyLines } = await import("./stats/efficiency.mjs");
|
|
2436
2562
|
report.push(...formatEfficiencyLines(await (deps.efficiency ?? batchEfficiency)({ batchDir: batch.dir, runsDir: dir, repo, gh: (a) => leanIo.gh(a), rows })));
|
|
2437
2563
|
} catch (e) { report.push(`efficiency: n/a (${String(e?.message ?? e).split("\n")[0].slice(0, 160)})`); }
|
|
2564
|
+
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
2565
|
report.push(await budgetReportLine({ cwd, repo, gh: (a) => leanIo.gh(a) })); // #5278: month usage, projection and any auto switch to local-first
|
|
2439
2566
|
const adequacyLine = formatTestAdequacySummary(rows); // #5449
|
|
2440
2567
|
if (adequacyLine) report.push(adequacyLine);
|
|
@@ -2739,12 +2866,12 @@ export async function scheddFromCli(argv, deps = {}) {
|
|
|
2739
2866
|
const start = () => { if (schedd.unitState() === null) schedd.defaultSpawn({ dir }); else schedd.startUnit(); };
|
|
2740
2867
|
const unit = deps.unitState ?? schedd.unitState; // #5966: active unit but no daemon is alerted and the unit restarted
|
|
2741
2868
|
const batchVerdicts = () => schedd.batchVerdicts(bm.batchRoot());
|
|
2742
|
-
return (deps.watchdog ?? health.watchdog)({ dir, ...(sec > 0 ? { stallMs: sec * 1000 } : {}), unfinished, start, batchVerdicts, unit });
|
|
2869
|
+
return (deps.watchdog ?? health.watchdog)({ dir, ...(sec > 0 ? { stallMs: sec * 1000 } : {}), unfinished, start, restart: () => schedd.restartUnit(), batchVerdicts, unit });
|
|
2743
2870
|
}
|
|
2744
2871
|
if (argv.length) throw new Error("usage: forgedock schedd [status | watchdog [--stall-sec N]]");
|
|
2745
2872
|
(deps.renice ?? (await import("./lean/schedd-health.mjs")).bestEffortRenice)(); // #4780: lanes must not starve the scheduler
|
|
2746
2873
|
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 }),
|
|
2874
|
+
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
2875
|
...(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
2876
|
if (!d.running) {
|
|
2750
2877
|
// #4775: under systemd, exiting here (code 0) makes `Restart=always` loop while another daemon holds the lock: stand by, take over when it dies
|
|
@@ -2841,6 +2968,44 @@ export async function decisionsFromCli(argv, deps = {}) {
|
|
|
2841
2968
|
return { rows };
|
|
2842
2969
|
}
|
|
2843
2970
|
|
|
2971
|
+
/**
|
|
2972
|
+
* `forgedock audits [--repo OWNER/NAME] [--version X | --since-version X] [--signature S] [--class C] [--active] [--json]` (#6077):
|
|
2973
|
+
* queries the repo's FORGE:LANE_AUDIT comments (trusted authors only). `--active` = active, not fixed_in_later, current version
|
|
2974
|
+
* (highest engine_version seen, or --version), grouped per signature with count and lanes. Read-only.
|
|
2975
|
+
*/
|
|
2976
|
+
export async function auditsFromCli(argv, deps = {}) {
|
|
2977
|
+
const q = await import("./lean/lane-audit-query.mjs");
|
|
2978
|
+
const { parseAudit, LANE_AUDIT_MARKER } = await import("./lean/lane-audit.mjs");
|
|
2979
|
+
const usage = "usage: forgedock audits [--repo OWNER/NAME] [--version X | --since-version X] [--signature S] [--class C] [--active] [--json]";
|
|
2980
|
+
const valued = new Set(["--repo", "--version", "--since-version", "--signature", "--class"]);
|
|
2981
|
+
const opts = {};
|
|
2982
|
+
for (let i = 0; i < argv.length; i++) {
|
|
2983
|
+
const a = argv[i];
|
|
2984
|
+
if (valued.has(a)) { if (argv[i + 1] == null || argv[i + 1].startsWith("--")) throw new Error(usage); opts[a] = argv[++i]; }
|
|
2985
|
+
else if (a === "--active" || a === "--json") opts[a] = true;
|
|
2986
|
+
else throw new Error(usage);
|
|
2987
|
+
}
|
|
2988
|
+
const run = deps.exec ?? (async (cmd, args) => String((await pexec(cmd, args, { maxBuffer: 64 * 1024 * 1024, timeout: 60000 })).stdout));
|
|
2989
|
+
const repo = opts["--repo"] ?? String(await run("gh", ["repo", "view", "--json", "nameWithOwner", "--jq", ".nameWithOwner"])).trim();
|
|
2990
|
+
const jq = `.[] | select(.body | contains("<!-- ${LANE_AUDIT_MARKER}")) | {body, user, author_association, issue_url} | tojson`;
|
|
2991
|
+
const lines = String(await run("gh", ["api", "--paginate", `repos/${repo}/issues/comments?per_page=100`, "--jq", jq])).split("\n").filter(Boolean);
|
|
2992
|
+
const { isTrustedIssueComment } = await import("./lean/prefilter.mjs");
|
|
2993
|
+
const audits = [];
|
|
2994
|
+
for (const l of lines) {
|
|
2995
|
+
try {
|
|
2996
|
+
const c = JSON.parse(l);
|
|
2997
|
+
if (!isTrustedIssueComment(c)) continue;
|
|
2998
|
+
const a = parseAudit(c.body);
|
|
2999
|
+
if (!a) continue;
|
|
3000
|
+
audits.push({ ...a, issue: Number(/(\d+)$/.exec(c.issue_url ?? "")?.[1]) || a.issue || null });
|
|
3001
|
+
} catch { /* skip a malformed comment */ }
|
|
3002
|
+
}
|
|
3003
|
+
const rows = q.filterAudits(audits, { version: opts["--version"], sinceVersion: opts["--since-version"], signature: opts["--signature"], class: opts["--class"] });
|
|
3004
|
+
const out = opts["--active"] ? q.summarizeActive(rows, { currentVersion: opts["--version"] ?? q.highestVersion(audits) }) : rows;
|
|
3005
|
+
console.log(opts["--json"] ? JSON.stringify(out, null, 2) : q.formatAudits(out, { active: Boolean(opts["--active"]) }));
|
|
3006
|
+
return { rows: out };
|
|
3007
|
+
}
|
|
3008
|
+
|
|
2844
3009
|
/**
|
|
2845
3010
|
* `forgedock check [--repo DIR] [--base REF] [--json]` (#4364): runs in the lane worktree what the engine runs after the
|
|
2846
3011
|
* builder: the frozen validate commands (.forge-lean/contract.json) and the change-scoped pre-PR checks, with the plan
|
|
@@ -2938,6 +3103,7 @@ export async function schedFromCli(argv, deps = {}) {
|
|
|
2938
3103
|
const batchMod = await import("./lean/batch.mjs");
|
|
2939
3104
|
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
3105
|
for (const l of schedMod.remoteLines(st, { agentOf })) console.log(l); // #4964
|
|
3106
|
+
for (const l of schedMod.concurrencyLines(st, { eventsOf: (b) => batchMod.openBatch(batchMod.batchRoot(), b).store.readLog() })) console.log(l); // #5985
|
|
2941
3107
|
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
3108
|
return st;
|
|
2943
3109
|
}
|
|
@@ -2990,7 +3156,7 @@ export function readOrchestration(cwd = process.cwd()) {
|
|
|
2990
3156
|
const errors = int(o.breaker_errors ?? o.errors, 3), windowMin = int(o.breaker_window_min ?? o.window_min, 30);
|
|
2991
3157
|
const gp = int(o.global_parallel, null);
|
|
2992
3158
|
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,
|
|
3159
|
+
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
3160
|
stacking: normalizeStacking(o.stacking), // #5831
|
|
2995
3161
|
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
3162
|
// #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/engine.mjs
CHANGED
|
@@ -26,6 +26,16 @@ import { OUTCOME_CODES, UNCLASSIFIED, normalizeCode, codeForRunnerError, codeFor
|
|
|
26
26
|
// Exported (forge#2175) so bin/engine-cli.mjs can render "failed N/M attempts"
|
|
27
27
|
// diagnostics without duplicating the retry budget constant.
|
|
28
28
|
export const DEFAULT_MAX_ATTEMPTS = 3;
|
|
29
|
+
/** #5988: an operator hold on more issues than this needs an explicit `--for`/`--ttl`: an open-ended hold idles them for as long as it is forgotten. */
|
|
30
|
+
export const HOLD_TTL_REQUIRED_ABOVE = 10;
|
|
31
|
+
/** #5988: `--hold` on many issues without a TTL is refused; the message names the flag. @returns {string|null} the refusal, or null when allowed */
|
|
32
|
+
export function holdTtlRefusal(issues, forMs) {
|
|
33
|
+
return issues.length > HOLD_TTL_REQUIRED_ABOVE && !(Number(forMs) > 0) ? `holding ${issues.length} issues (more than ${HOLD_TTL_REQUIRED_ABOVE}) requires an explicit --ttl <4h|30m|1d> (or --for)` : null;
|
|
34
|
+
}
|
|
35
|
+
/** #5988: the plan printed with a hold: when it expires, an alert at T-30 min, and that expiry re-admits at the concurrency controller's pace. */
|
|
36
|
+
export function holdResumePlan(issues, forLabel) {
|
|
37
|
+
return `resume plan: ${issues.length} issue${issues.length === 1 ? "" : "s"} held${forLabel ? ` for ${forLabel}` : " until released"}; an alert posts 30 min before expiry; on expiry they re-admit through the concurrency controller, not all at once`;
|
|
38
|
+
}
|
|
29
39
|
|
|
30
40
|
// forge#2239: lease TTL and renewal-interval defaults. Exported/overridable
|
|
31
41
|
// (mirrors DEFAULT_MAX_ATTEMPTS) so tests can exercise "phase outlives the
|