forgedock 1.71.0 → 1.72.1
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 +1 -1
- package/bin/engine/outcome-codes.mjs +5 -4
- package/bin/init-detect.mjs +35 -2
- package/bin/lean/admit.mjs +152 -0
- package/bin/lean/admit.test.mjs +120 -0
- package/bin/lean/attempts.mjs +1 -1
- package/bin/lean/batch.mjs +8 -0
- package/bin/lean/batch.test.mjs +17 -0
- package/bin/lean/concurrency.mjs +7 -2
- package/bin/lean/concurrency.test.mjs +16 -3
- package/bin/lean/conformance.mjs +2 -0
- package/bin/lean/conformance.test.mjs +9 -0
- package/bin/lean/effects.mjs +22 -0
- package/bin/lean/failure-census.mjs +1 -1
- package/bin/lean/heavy.mjs +20 -6
- package/bin/lean/heavy.test.mjs +24 -3
- package/bin/lean/lean.mjs +97 -5
- package/bin/lean/lean.test.mjs +38 -0
- package/bin/lean/orchestrate-envhold.test.mjs +14 -0
- package/bin/lean/orchestrate-heldroot.test.mjs +32 -0
- package/bin/lean/orchestrate.mjs +33 -11
- package/bin/lean/queuecause.mjs +42 -0
- package/bin/lean/release-cigreen.mjs +18 -4
- package/bin/lean/release-cigreen.test.mjs +23 -0
- package/bin/lean/release-review.mjs +24 -10
- package/bin/lean/release-review.test.mjs +65 -0
- package/bin/lean/release.mjs +1 -1
- package/bin/lean/release.test.mjs +19 -0
- package/bin/lean/schedd.mjs +24 -1
- package/bin/lean/schedd.test.mjs +38 -0
- package/bin/pool/agent.mjs +61 -18
- package/bin/pool/docker-dns.mjs +39 -0
- package/bin/pool/docker.mjs +7 -3
- package/bin/pool/engine-placement.test.mjs +2 -2
- package/bin/pool/image-manifest.test.mjs +13 -0
- package/bin/pool/lane-image.mjs +56 -15
- package/bin/pool/lane-tools.mjs +26 -12
- package/bin/pool/lane-tools.test.mjs +63 -1
- package/bin/pool/project-layer.mjs +2 -2
- package/bin/pool/router.mjs +2 -1
- package/bin/review-staging.mjs +14 -11
- package/bin/review-staging.test.mjs +20 -1
- package/bin/stats/escapes.mjs +124 -0
- package/bin/stats/index.mjs +5 -1
- package/bin/stats/quality-ledger.mjs +49 -0
- package/bin/stats/quality-ledger.test.mjs +84 -0
- package/bin/stats/weekly.mjs +230 -0
- package/docs/OUTCOME-CODES.md +2 -1
- package/package.json +1 -1
- package/pool/README.md +2 -0
- package/pool/image/Dockerfile +4 -1
- package/pool/image/lane-tools-sets.json +6 -0
- package/scripts/lane-variants.mjs +51 -0
package/bin/config-schema.mjs
CHANGED
|
@@ -47,7 +47,7 @@ export const TYPES = {
|
|
|
47
47
|
"orchestration.merge_train": { enum: ["off", "on"] }, // #5836: lanes end pr-ready and the batch merge train merges (default off)
|
|
48
48
|
"orchestration.merge_train_batch": "posint", // #5837: up to N green PRs of one base validated together on a candidate ref (default 4)
|
|
49
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
|
|
50
|
+
"orchestration.max_identical_signature": "posint", // #5986: identical failure signatures at which an issue breaches (default 2: the 2nd breaches)
|
|
51
51
|
"env.snapshots.enabled": "bool",
|
|
52
52
|
"env.snapshots.store": { enum: ["local", "oci"] },
|
|
53
53
|
"env.snapshots.keep": "number",
|
|
@@ -60,6 +60,7 @@ export const OUTCOME_CODES = Object.freeze({
|
|
|
60
60
|
ENV_TOOL_MISSING: "env.tool_missing", // forge#4323: a validate command could not run because a host tool or module is missing; an environment error, not a conformance failure
|
|
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
|
+
ENV_CAPABILITY_DOCKER: "env.capability_docker", // forge#6196: a validate command needs a Docker daemon or image the sandbox lacks (no daemon, no local image, no docker binary); the host has one, so the lane is re-placed there or the validate is deferred to CI
|
|
63
64
|
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
65
|
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
|
|
65
66
|
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
|
|
@@ -220,13 +221,13 @@ export const ENV_VALIDATE_PLACEMENT = "env.validate_placement";
|
|
|
220
221
|
* Batch recovery classes of a lane result (forge#4267). The batch runner recovers `recoverable` rows once
|
|
221
222
|
* (`orchestration.recovery.max_attempts`) and re-queues them; only `human` rows are escalations.
|
|
222
223
|
*/
|
|
223
|
-
export const RECOVERABLE_CODES = Object.freeze([OUTCOME_CODES.CI_RED, OUTCOME_CODES.BASE_CONFLICT, OUTCOME_CODES.BUILDER_BLOCK_UNTYPED, OUTCOME_CODES.CONTRACT_INVALID, OUTCOME_CODES.CONTRACT_INVALID_COMMAND, OUTCOME_CODES.ENV_TOOL_MISSING, OUTCOME_CODES.ENV_REPRO_UNRUNNABLE, ENV_VALIDATE_TIMEOUT, ENV_VALIDATE_PLACEMENT, OUTCOME_CODES.ENV_CAPABILITY_REMOTE, OUTCOME_CODES.BUDGET_EXCEEDED, OUTCOME_CODES.CONFORMANCE_UNIMPLEMENTED, OUTCOME_CODES.CONFORMANCE_OMISSION, OUTCOME_CODES.CONFORMANCE_UNJUSTIFIED_DEFERRAL, OUTCOME_CODES.CONFORMANCE_REGRESSION, OUTCOME_CODES.CONFORMANCE_SCOPE_CREEP]); // #5644: regression and scope creep are builder-fixable
|
|
224
|
+
export const RECOVERABLE_CODES = Object.freeze([OUTCOME_CODES.CI_RED, OUTCOME_CODES.BASE_CONFLICT, OUTCOME_CODES.BUILDER_BLOCK_UNTYPED, OUTCOME_CODES.CONTRACT_INVALID, OUTCOME_CODES.CONTRACT_INVALID_COMMAND, OUTCOME_CODES.ENV_TOOL_MISSING, OUTCOME_CODES.ENV_REPRO_UNRUNNABLE, ENV_VALIDATE_TIMEOUT, ENV_VALIDATE_PLACEMENT, OUTCOME_CODES.ENV_CAPABILITY_REMOTE, OUTCOME_CODES.ENV_CAPABILITY_DOCKER, OUTCOME_CODES.BUDGET_EXCEEDED, OUTCOME_CODES.CONFORMANCE_UNIMPLEMENTED, OUTCOME_CODES.CONFORMANCE_OMISSION, OUTCOME_CODES.CONFORMANCE_UNJUSTIFIED_DEFERRAL, OUTCOME_CODES.CONFORMANCE_REGRESSION, OUTCOME_CODES.CONFORMANCE_SCOPE_CREEP]); // #5644: regression and scope creep are builder-fixable
|
|
224
225
|
/** `builder.blocked` is only reached by a typed human block: credentials, spend, promotion, customer, product-decision. */
|
|
225
226
|
export const HUMAN_CODES = Object.freeze([OUTCOME_CODES.BUILDER_BLOCKED]);
|
|
226
227
|
|
|
227
228
|
/**
|
|
228
229
|
* `recoverable` | `human` | `terminal` for a lane result row ({outcome|terminalReason, code, issueEdited?, conflicting?}).
|
|
229
|
-
* Recoverable: needs-human `ci.red`, `base.conflict`, `builder.block_untyped`, `env.tool_missing`, `env.repro_unrunnable`, `env.validate_timeout`, `env.capability_remote`, `budget.exceeded`, `conformance.unimplemented` / `conformance.omission` / `conformance.unjustified_deferral` (#5035), `conformance.regression` / `conformance.scope_creep` (#5644; guard_broken and e2e_unverified stay terminal), `contract.invalid` after a mid-run issue
|
|
230
|
+
* Recoverable: needs-human `ci.red`, `base.conflict`, `builder.block_untyped`, `env.tool_missing`, `env.repro_unrunnable`, `env.validate_timeout`, `env.capability_remote`, `env.capability_docker` (#6196), `budget.exceeded`, `conformance.unimplemented` / `conformance.omission` / `conformance.unjustified_deferral` (#5035), `conformance.regression` / `conformance.scope_creep` (#5644; guard_broken and e2e_unverified stay terminal), `contract.invalid` after a mid-run issue
|
|
230
231
|
* edit (`issueEdited`) or when every problem was an unmatched quote (`quoteMismatch`), `ci-pending` on a conflicting PR (`conflicting`), and the non-human `budget-exceeded` turn-overrun end (forge#4505). Human: `builder.blocked`. Anything else
|
|
231
232
|
* (another code, or not a needs-human/ci-pending row) is terminal. Pure, never throws.
|
|
232
233
|
*/
|
|
@@ -252,10 +253,10 @@ function classifyNeedsHumanBase(row) {
|
|
|
252
253
|
}
|
|
253
254
|
|
|
254
255
|
/** forge#4725: mechanical/environment codes recover on their own budget (`recovery.mechanicalMaxAttempts`), apart from conformance failures. */
|
|
255
|
-
export const MECHANICAL_CODES = Object.freeze([OUTCOME_CODES.BASE_CONFLICT, OUTCOME_CODES.CONTRACT_INVALID_COMMAND, OUTCOME_CODES.ENV_TOOL_MISSING, OUTCOME_CODES.ENV_REPRO_UNRUNNABLE, ENV_VALIDATE_TIMEOUT, ENV_VALIDATE_PLACEMENT, OUTCOME_CODES.ENV_CAPABILITY_REMOTE]);
|
|
256
|
+
export const MECHANICAL_CODES = Object.freeze([OUTCOME_CODES.BASE_CONFLICT, OUTCOME_CODES.CONTRACT_INVALID_COMMAND, OUTCOME_CODES.ENV_TOOL_MISSING, OUTCOME_CODES.ENV_REPRO_UNRUNNABLE, ENV_VALIDATE_TIMEOUT, ENV_VALIDATE_PLACEMENT, OUTCOME_CODES.ENV_CAPABILITY_REMOTE, OUTCOME_CODES.ENV_CAPABILITY_DOCKER]);
|
|
256
257
|
|
|
257
258
|
/** #5423: environment gaps the engine recovers itself: a first lane ending on one never labels the issue needs-human. */
|
|
258
|
-
export const ENV_ENGINE_OWNED_CODES = Object.freeze([OUTCOME_CODES.ENV_TOOL_MISSING, ENV_VALIDATE_PLACEMENT, ENV_VALIDATE_TIMEOUT, OUTCOME_CODES.ENV_CAPABILITY_REMOTE, OUTCOME_CODES.ENV_REPRO_UNRUNNABLE]);
|
|
259
|
+
export const ENV_ENGINE_OWNED_CODES = Object.freeze([OUTCOME_CODES.ENV_TOOL_MISSING, ENV_VALIDATE_PLACEMENT, ENV_VALIDATE_TIMEOUT, OUTCOME_CODES.ENV_CAPABILITY_REMOTE, OUTCOME_CODES.ENV_REPRO_UNRUNNABLE, OUTCOME_CODES.ENV_CAPABILITY_DOCKER]);
|
|
259
260
|
|
|
260
261
|
/** `mechanical` | `conformance`: the recovery budget class of a lane result row (a conflicting `ci-pending` is a base conflict). */
|
|
261
262
|
export function recoveryClassOf(row) {
|
package/bin/init-detect.mjs
CHANGED
|
@@ -529,14 +529,47 @@ export function detectSandboxes(cwd, fs = { existsSync, readFileSync }) {
|
|
|
529
529
|
}
|
|
530
530
|
if (hasMigrations && !out.postgres && (hasTests || compose)) out.postgres = '{ image: postgres:16, init: "<your migrate command> $SANDBOX_URL" }';
|
|
531
531
|
else if (hasMigrations && out.postgres && !out.postgres.includes("init:")) out.postgres = out.postgres.replace(/ }$/, ', init: "<your migrate command> $SANDBOX_URL" }');
|
|
532
|
+
if (detectDocker(cwd, fs, compose)) Object.defineProperty(out, "poolDocker", { value: true, enumerable: false }); // #6196: carried to the proposal without becoming a sandbox entry
|
|
532
533
|
return out;
|
|
533
534
|
}
|
|
534
535
|
|
|
536
|
+
// #6196: docker/testcontainers/postgres-image references in test files or compose files => propose the pool repo entry `docker: true`
|
|
537
|
+
const DOCKER_REF_RE = /testcontainers|\bdocker(?:-compose)?\s+(?:run|compose|exec)\b|\bpostgres:\d|pgvector\/pgvector|image present locally/i;
|
|
538
|
+
const DOCKER_SKIP_DIRS = new Set(["node_modules", ".git", "dist", "build", "vendor", ".venv", "venv", "__pycache__", "target"]);
|
|
539
|
+
const DOCKER_TEST_DIR_RE = /^(?:tests?|__tests__|specs?|e2e|integration|scripts)$/i;
|
|
540
|
+
const DOCKER_TEST_FILE_RE = /(?:\.(?:test|spec)\.[cm]?[jt]sx?|(?:^|\/)test_[^/]*\.py|(?:^|\/)conftest\.py|_test\.(?:py|go|rb)|Tests?\.java|\.sh)$/;
|
|
541
|
+
/** True when a compose file or a (bounded scan of the repo's) test file references docker, testcontainers or a postgres image. Pure over `fs`; readdirSync is optional. */
|
|
542
|
+
export function detectDocker(cwd, fs = { existsSync, readFileSync, readdirSync }, compose = COMPOSE_FILES.find((f) => fs.existsSync(join(cwd, f)))) {
|
|
543
|
+
const read = (f) => { try { return String(fs.readFileSync(f, "utf8")); } catch { return ""; } };
|
|
544
|
+
if (compose && DOCKER_REF_RE.test(read(join(cwd, compose)))) return true;
|
|
545
|
+
if (typeof fs.readdirSync !== "function") return false;
|
|
546
|
+
let budget = 500; // files read
|
|
547
|
+
const walk = (dir, depth, inTests) => {
|
|
548
|
+
let ents = [];
|
|
549
|
+
try { ents = fs.readdirSync(dir, { withFileTypes: true }); } catch { return false; }
|
|
550
|
+
for (const e of ents) {
|
|
551
|
+
if (budget <= 0) return false;
|
|
552
|
+
const full = join(dir, e.name);
|
|
553
|
+
if (e.isDirectory()) { if (depth < 6 && !DOCKER_SKIP_DIRS.has(e.name) && walk(full, depth + 1, inTests || DOCKER_TEST_DIR_RE.test(e.name))) return true; }
|
|
554
|
+
else if ((DOCKER_TEST_FILE_RE.test(e.name) || (inTests && /\.(?:[cm]?[jt]sx?|py|go|rb|sh)$/.test(e.name))) && budget-- > 0 && DOCKER_REF_RE.test(read(full))) return true;
|
|
555
|
+
}
|
|
556
|
+
return false;
|
|
557
|
+
};
|
|
558
|
+
return walk(cwd, 0, false);
|
|
559
|
+
}
|
|
560
|
+
|
|
535
561
|
/** The commented forge.yaml block for a detected proposal; "" when there is none. */
|
|
536
562
|
export function sandboxesProposalYaml(sandboxes) {
|
|
537
563
|
const names = Object.keys(sandboxes ?? {});
|
|
538
|
-
|
|
539
|
-
|
|
564
|
+
const dockerPool = sandboxes?.poolDocker === true
|
|
565
|
+
? `
|
|
566
|
+
# POOL DOCKER (proposed by init): tests reference docker/testcontainers/postgres images. A remote pool lane has no Docker
|
|
567
|
+
# daemon unless the pool repo entry enables the dind sidecar (operator-owned pool config, per repo):
|
|
568
|
+
# docker: true
|
|
569
|
+
`
|
|
570
|
+
: "";
|
|
571
|
+
if (!names.length) return dockerPool;
|
|
572
|
+
return dockerPool + `
|
|
540
573
|
# =============================================================================
|
|
541
574
|
# TEST SANDBOXES (proposed by init, uncomment to enable; see docs/CONFIG.md verify.sandboxes)
|
|
542
575
|
# =============================================================================
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
|
+
/**
|
|
4
|
+
* #6206: the admit probe. Before the first builder or plan session a lane asks four cheap deterministic questions, so no builder
|
|
5
|
+
* spend goes to a lane the base or the environment already dooms:
|
|
6
|
+
* 1. base health: the base head's required checks (red on something this issue does not touch -> `base.red`, deferred);
|
|
7
|
+
* 2. environment: the claude login answers (`backend.auth`, deferred);
|
|
8
|
+
* 3. contract dry-run: the frozen validates run once on the base tree (existing runPreflight); Docker-only gaps become
|
|
9
|
+
* deferred-to-CI with a FORGE:DECISION, other missing tools end `env.tool_missing` before the build;
|
|
10
|
+
* 4. failure fingerprint: an issue parked with fingerprint F on (base head B, input I) is not re-admitted until B or I changed.
|
|
11
|
+
* Every outcome is one typed `ADMIT_PROBE` telemetry event with `builder_spend_usd: 0`. Everything here is pure or takes seams; no LLM.
|
|
12
|
+
*/
|
|
13
|
+
import { OUTCOME_CODES, ENV_ENGINE_OWNED_CODES } from "../engine/outcome-codes.mjs";
|
|
14
|
+
import { baseRedPaths } from "./basered.mjs";
|
|
15
|
+
import { computeInputHash, frozenContractHash } from "./attempts.mjs";
|
|
16
|
+
import { isResetDecision } from "./failure-stop.mjs";
|
|
17
|
+
|
|
18
|
+
export const ADMIT_EVENT = "ADMIT_PROBE";
|
|
19
|
+
export const ADMIT_MARKER = "FORGE:ADMIT_PROBE";
|
|
20
|
+
const RED = new Set(["failure", "timed_out", "startup_failure", "error"]);
|
|
21
|
+
const sha12 = (s) => String(s ?? "").trim().slice(0, 12);
|
|
22
|
+
|
|
23
|
+
/** Failing required checks of the base head. `checks`: [{name, conclusion|state, url, completed_at, summary}] (check runs and commit statuses); latest per name wins. */
|
|
24
|
+
export function failingRequired({ checks = [], required = [] } = {}) {
|
|
25
|
+
const want = new Set((required ?? []).map(String));
|
|
26
|
+
if (!want.size) return []; // no known required set: no evidence, fail open
|
|
27
|
+
const latest = new Map();
|
|
28
|
+
for (const c of checks ?? []) {
|
|
29
|
+
const name = String(c?.name ?? "");
|
|
30
|
+
if (!want.has(name)) continue;
|
|
31
|
+
const prev = latest.get(name);
|
|
32
|
+
if (!prev || String(c.completed_at ?? "") >= String(prev.completed_at ?? "")) latest.set(name, c);
|
|
33
|
+
}
|
|
34
|
+
return [...latest.values()].filter((c) => RED.has(String(c.conclusion ?? c.state ?? "").toLowerCase()))
|
|
35
|
+
.map((c) => ({ name: String(c.name), conclusion: String(c.conclusion ?? c.state), url: c.url ?? c.html_url ?? "", summary: String(c.summary ?? "").slice(0, 600) }));
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
const esc = (x) => String(x).replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
39
|
+
/** #6232: `needle` as a whole token of `text` (not inside a longer word, name or path): `test` does not match `latest` or `tests/foo`. Both lowercased by the caller. */
|
|
40
|
+
export const hasToken = (text, needle) => Boolean(needle) && new RegExp(`(?<![a-z0-9_./-])${esc(needle)}(?![a-z0-9_-]|\\.[a-z0-9])`).test(text);
|
|
41
|
+
const BASE_RED_LABEL = /^(base[-. _]?red|fix(es)?[-: ]base[-. _]?red)$/i;
|
|
42
|
+
const dirOf = (p) => (p.includes("/") ? p.slice(0, p.lastIndexOf("/")) : "");
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* True when the issue is the fix for (or about) the failing check, not a bystander. `issue`: a string (title and body) or
|
|
46
|
+
* {text, contractText, labels, linkedBaseRed}. It is the fix when any of:
|
|
47
|
+
* - its text names the failing check as a whole token (substrings do not count: `test` is not in `latest`),
|
|
48
|
+
* - its text, frozen contract or deliverables name a file (or sit in the directory of a file) the check's output names,
|
|
49
|
+
* - it is labelled base-red, or linked as the base-red cause (a trusted FORGE:BASE_RED comment).
|
|
50
|
+
*/
|
|
51
|
+
export function touchedByIssue(fail, issue) {
|
|
52
|
+
const o = typeof issue === "string" || issue == null ? { text: issue } : issue;
|
|
53
|
+
if ((o.labels ?? []).some((l) => BASE_RED_LABEL.test(String(l?.name ?? l)))) return true;
|
|
54
|
+
if (o.linkedBaseRed) return true;
|
|
55
|
+
const text = String(o.text ?? "").toLowerCase(), contract = String(o.contractText ?? "").toLowerCase();
|
|
56
|
+
if (!text && !contract) return false;
|
|
57
|
+
if (hasToken(text, String(fail.name).toLowerCase())) return true;
|
|
58
|
+
const { src, tests } = baseRedPaths([{ command: "", output: fail.summary }]);
|
|
59
|
+
return [...src, ...tests].map((p) => p.toLowerCase()).some((p) => {
|
|
60
|
+
if (hasToken(text, p) || hasToken(contract, p)) return true;
|
|
61
|
+
const d = dirOf(p); // the check's scope: a contract file in the same directory is the fix's territory
|
|
62
|
+
return d.includes("/") && (text.includes(`${d}/`) || contract.includes(`${d}/`));
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** Base health verdict: red only for a failing required check this issue does not touch. */
|
|
67
|
+
export function baseHealth({ checks, required, issueText, issue } = {}) {
|
|
68
|
+
const failing = failingRequired({ checks, required });
|
|
69
|
+
const who = issue ?? issueText;
|
|
70
|
+
const foreign = failing.filter((f) => !touchedByIssue(f, who));
|
|
71
|
+
return { red: foreign.length > 0, failing: foreign, touched: failing.filter((f) => !foreign.includes(f)) };
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** Reads check runs and commit statuses of `sha` through `gh` (a function of argv, string out). Throws on an unreadable base; the caller fails open. */
|
|
75
|
+
export async function fetchBaseChecks({ gh, repo, sha }) {
|
|
76
|
+
const runs = String(await gh(["api", "--paginate", `repos/${repo}/commits/${sha}/check-runs`, "--jq", ".check_runs[] | {name, conclusion, url: .html_url, completed_at, summary: (.output.summary // .output.title // \"\")}"]));
|
|
77
|
+
let statuses = "";
|
|
78
|
+
try { statuses = String(await gh(["api", `repos/${repo}/commits/${sha}/status`, "--jq", ".statuses[] | {name: .context, conclusion: .state, url: .target_url, completed_at: .updated_at, summary: (.description // \"\")}"])); } catch { /* classic statuses are optional */ }
|
|
79
|
+
const rows = [];
|
|
80
|
+
for (const l of `${runs}\n${statuses}`.split("\n")) { try { if (l.trim()) rows.push(JSON.parse(l)); } catch { /* skip */ } }
|
|
81
|
+
return rows;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** Evidence comment for a red base: the checks with links. Keyed by the base sha so a requeue loop posts it once. */
|
|
85
|
+
export function baseRedComment({ base, sha, failing }) {
|
|
86
|
+
const rows = failing.map((f) => `- \`${f.name}\` (${f.conclusion})${f.url ? ` ${f.url}` : ""}${f.summary ? `\n ${f.summary.split("\n")[0].slice(0, 200)}` : ""}`).join("\n");
|
|
87
|
+
return `<!-- ${ADMIT_MARKER} base.red ${base}@${sha12(sha)} -->\n## Admit probe: base is red\nRequired check(s) fail on \`${base}\` at \`${sha12(sha)}\`, and this issue does not touch them:\n${rows}\n\nNo builder session was started (spend $0). The lane is deferred and re-admitted when the base head moves.`;
|
|
88
|
+
}
|
|
89
|
+
export const hasAdmitComment = (comments, key) => (comments ?? []).some((c) => String(c?.body ?? "").includes(`<!-- ${ADMIT_MARKER} ${key} -->`));
|
|
90
|
+
|
|
91
|
+
/** What the dry-run's misses mean: Docker-only gaps are deferred to CI, other tools (not owned by the repo's manifests) end the lane before the build. */
|
|
92
|
+
export function classifyDryRun({ misses = [], owned = () => false } = {}) {
|
|
93
|
+
const isDocker = (m) => /^docker(?: daemon)?$/i.test(String(m?.tool ?? "")) || /Cannot connect to the Docker daemon|docker\.sock/i.test(String(m?.line ?? ""));
|
|
94
|
+
const docker = new Set(), tools = new Set(), toolIds = new Set();
|
|
95
|
+
for (const m of misses ?? []) {
|
|
96
|
+
if (!m || !m.tool) continue;
|
|
97
|
+
if (isDocker(m)) { for (const id of m.ids ?? []) docker.add(String(id)); continue; }
|
|
98
|
+
if (m.kind !== "command" || owned(m.tool)) continue; // paths, modules, env vars stay the builder's to fix: the existing contract correction handles them
|
|
99
|
+
tools.add(String(m.tool)); for (const id of m.ids ?? []) toolIds.add(String(id));
|
|
100
|
+
}
|
|
101
|
+
return { docker: [...docker].sort(), tools: [...tools].sort(), ids: [...toolIds].sort() };
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** The park stamp a NEEDS_HUMAN/PARKED comment carries: the base head and the input hash it ran on, and the code. */
|
|
105
|
+
export const STAMP_RE = /\bbase=([0-9a-f]{12})\s+in=([0-9a-f]{16})\s+code=([\w.:-]+)/;
|
|
106
|
+
export const renderStamp = ({ base, input, code }) => (sha12(base) && input && code ? `base=${sha12(base)} in=${input} code=${code}` : "");
|
|
107
|
+
|
|
108
|
+
/** Hash of what a person can change on the issue: title, body, trusted FORGE:DECISIONs, the frozen contract, the engine major.minor (labels are state, not input). */
|
|
109
|
+
export function inputOf({ iss, comments = [], trusted = () => true, engineVersion = null }) {
|
|
110
|
+
const decisions = (comments ?? []).filter((c) => /^\s*<!--\s*FORGE:DECISION\b/.test(String(c?.body ?? "")) && trusted(c)).map((c) => c.body);
|
|
111
|
+
return computeInputHash({ title: iss?.title ?? "", body: iss?.body ?? "", labels: [], decisions, engineVersion, contractHash: frozenContractHash(comments, trusted) });
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* #6231: codes a repeat cannot help or that are transient/infrastructure: the engine's own environment recovery, a human block, a deferral,
|
|
116
|
+
* the engine, the sandbox, the backend login, the network and gh. A park of these is never stamped and never stops admission or counts as a
|
|
117
|
+
* repeat: after the operator fixes the cause a rerun must be admitted. The ONE list, used by the stamp writer, the stop reader and lean.mjs.
|
|
118
|
+
*/
|
|
119
|
+
export const NON_STOPPABLE_CODES = Object.freeze(new Set([
|
|
120
|
+
...ENV_ENGINE_OWNED_CODES, OUTCOME_CODES.BUILDER_BLOCKED, OUTCOME_CODES.FAILURE_REPEATED, OUTCOME_CODES.BASE_RED, OUTCOME_CODES.BASE_CONFLICT,
|
|
121
|
+
OUTCOME_CODES.ENGINE_ERROR, OUTCOME_CODES.ENV_SETUP_FAILED, OUTCOME_CODES.ENV_LANE_LIMIT, OUTCOME_CODES.ENV_ENGINE_SKEW,
|
|
122
|
+
OUTCOME_CODES.BACKEND_AUTH, OUTCOME_CODES.BACKEND_CLI_FAILED, OUTCOME_CODES.QUOTA_EXHAUSTED, OUTCOME_CODES.RATE_LIMITED, OUTCOME_CODES.HOST_BUSY,
|
|
123
|
+
OUTCOME_CODES.GH_UNAVAILABLE, OUTCOME_CODES.GH_AUTH, OUTCOME_CODES.NET_TRANSIENT, OUTCOME_CODES.MERGE_TRANSIENT, OUTCOME_CODES.PUSH_TRANSIENT,
|
|
124
|
+
OUTCOME_CODES.RUN_INTERRUPTED, OUTCOME_CODES.LEASE_HELD, OUTCOME_CODES.CLI_IDLE, OUTCOME_CODES.CLI_TIMEOUT, OUTCOME_CODES.CLI_HOST_KILLED,
|
|
125
|
+
OUTCOME_CODES.PATH_SWITCH_CONFLICT,
|
|
126
|
+
]));
|
|
127
|
+
/** Families that are transient or infrastructure by prefix: sandbox.*, lane.*, engine.*, infra.*, backend.*, net.*, gh.*, and deferred/dependency holds. */
|
|
128
|
+
const NON_STOPPABLE_PREFIX = /^(sandbox|lane|engine|infra|backend|net|gh|dependency|pool|deferred)[.:_]/;
|
|
129
|
+
export const isNonStoppable = (code) => NON_STOPPABLE_CODES.has(code) || NON_STOPPABLE_PREFIX.test(String(code ?? ""));
|
|
130
|
+
export const stampable = (code) => Boolean(code) && !isNonStoppable(code);
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* The failure-fingerprint stop: the newest trusted NEEDS_HUMAN/PARKED comment (after the last trusted FORGE:DECISION) carries a stamp whose base head and
|
|
134
|
+
* input hash equal the current ones. Returns {sig, code, base, input} or null (a missing stamp, a changed base or input, an engine-owned code admit).
|
|
135
|
+
*/
|
|
136
|
+
export function fingerprintStop({ comments = [], base, input, trusted = () => true } = {}) {
|
|
137
|
+
let last = null;
|
|
138
|
+
for (const c of comments ?? []) {
|
|
139
|
+
const body = String(c?.body ?? "");
|
|
140
|
+
if (isResetDecision(body) && trusted(c)) { last = null; continue; }
|
|
141
|
+
if (!/<!--\s*FORGE:(NEEDS_HUMAN|PARKED)(?![A-Za-z0-9_])/.test(body) || !trusted(c)) continue;
|
|
142
|
+
const m = STAMP_RE.exec(body);
|
|
143
|
+
if (m) last = { base: m[1], input: m[2], code: m[3], sig: /\bsig=([0-9a-f]{12})\b/.exec(body)?.[1] ?? "" }; // an unstamped park (older, or an engine-owned code) leaves the last stamp standing
|
|
144
|
+
}
|
|
145
|
+
if (!last || !stampable(last.code) || !base || !input) return null;
|
|
146
|
+
return last.base === sha12(base) && last.input === input ? last : null;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
export const stopReason = (s) => `parked before with fingerprint ${s.sig || "(unsigned)"} (${s.code}) on this base head and this issue input; nothing changed since, so no builder session is spent. Change the issue, add a FORGE:DECISION, or wait for the base to move, then rerun`;
|
|
150
|
+
|
|
151
|
+
/** The one telemetry record of a probe, always zero builder spend. */
|
|
152
|
+
export const admitEvent = ({ outcome, code = null, detail = "", checks = [], ms = 0 } = {}) => ({ event: ADMIT_EVENT, outcome, code, detail: String(detail).slice(0, 300), checks, builder_spend_usd: 0, ms });
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
|
+
import { test } from "node:test";
|
|
4
|
+
import assert from "node:assert/strict";
|
|
5
|
+
import { failingRequired, baseHealth, baseRedComment, hasAdmitComment, classifyDryRun, renderStamp, stampable, isNonStoppable, NON_STOPPABLE_CODES, inputOf, fingerprintStop, admitEvent, fetchBaseChecks } from "./admit.mjs";
|
|
6
|
+
import { OUTCOME_CODES } from "../engine/outcome-codes.mjs";
|
|
7
|
+
|
|
8
|
+
const run = (name, conclusion, extra = {}) => ({ name, conclusion, url: `https://x/${name}`, completed_at: "2026-11-28T10:00:00Z", ...extra });
|
|
9
|
+
|
|
10
|
+
test("failingRequired: only required, latest per name, red conclusions", () => {
|
|
11
|
+
const rows = [run("lint", "failure"), run("lint", "success", { completed_at: "2026-11-28T11:00:00Z" }), run("e2e", "failure"), run("docs", "failure"), run("unit", "success")];
|
|
12
|
+
assert.deepEqual(failingRequired({ checks: rows, required: ["lint", "e2e", "unit"] }).map((f) => f.name), ["e2e"]);
|
|
13
|
+
assert.deepEqual(failingRequired({ checks: rows, required: [] }), []); // no known required set: fail open
|
|
14
|
+
assert.deepEqual(failingRequired({ checks: [run("e2e", "cancelled"), run("e2e2", "in_progress")], required: ["e2e", "e2e2"] }), []);
|
|
15
|
+
});
|
|
16
|
+
|
|
17
|
+
test("baseHealth: a failure the issue names is not a foreign red", () => {
|
|
18
|
+
const rows = [run("e2e", "failure", { summary: "FAIL test/api/users.test.mjs" })];
|
|
19
|
+
assert.equal(baseHealth({ checks: rows, required: ["e2e"], issueText: "Fix a typo in the README" }).red, true);
|
|
20
|
+
assert.equal(baseHealth({ checks: rows, required: ["e2e"], issueText: "users.test.mjs is flaky: test/api/users.test.mjs" }).red, false);
|
|
21
|
+
assert.equal(baseHealth({ checks: rows, required: ["e2e"], issueText: "the e2e check is red" }).red, false);
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
test("baseRedComment carries the links and a key the probe dedupes on", () => {
|
|
25
|
+
const f = [{ name: "e2e", conclusion: "failure", url: "https://x/e2e", summary: "boom" }];
|
|
26
|
+
const body = baseRedComment({ base: "origin/staging", sha: "abcdef1234567890", failing: f });
|
|
27
|
+
assert.match(body, /https:\/\/x\/e2e/);
|
|
28
|
+
assert.ok(hasAdmitComment([{ body }], "base.red origin/staging@abcdef123456"));
|
|
29
|
+
assert.ok(!hasAdmitComment([{ body }], "base.red origin/staging@000000000000"));
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
test("fetchBaseChecks parses check runs and tolerates missing statuses", async () => {
|
|
33
|
+
const gh = async (a) => { if (a.includes("--paginate")) return `${JSON.stringify(run("e2e", "failure"))}\n`; throw new Error("404"); };
|
|
34
|
+
assert.equal((await fetchBaseChecks({ gh, repo: "o/r", sha: "abc" })).length, 1);
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
test("classifyDryRun: docker deferred to CI, owned tools ignored, other tools stop the lane", () => {
|
|
38
|
+
const misses = [{ ids: ["V1"], tool: "docker", kind: "command" }, { ids: ["V2"], tool: "ffmpeg", kind: "command" }, { ids: ["V3"], tool: "pytest", kind: "command" }, { ids: ["V4"], tool: "x", kind: "python-module" }];
|
|
39
|
+
const r = classifyDryRun({ misses, owned: (t) => t === "pytest" });
|
|
40
|
+
assert.deepEqual(r, { docker: ["V1"], tools: ["ffmpeg"], ids: ["V2"] });
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
const stamped = (code, base, input, extra = "") => ({ body: `<!-- FORGE:NEEDS_HUMAN -->\n## Needs human\nx\n\nsig=0123456789ab ${renderStamp({ base, input, code })}${extra}`, __mine: true });
|
|
44
|
+
|
|
45
|
+
test("fingerprintStop: same base head and input stops; a moved base or changed input admits", () => {
|
|
46
|
+
const input = "a".repeat(16), base = "b".repeat(40);
|
|
47
|
+
const c = [stamped("ci.red", base, input)];
|
|
48
|
+
assert.equal(fingerprintStop({ comments: c, base, input })?.code, "ci.red");
|
|
49
|
+
assert.equal(fingerprintStop({ comments: c, base: "c".repeat(40), input }), null);
|
|
50
|
+
assert.equal(fingerprintStop({ comments: c, base, input: "d".repeat(16) }), null);
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
test("fingerprintStop: engine-owned env codes, a FORGE:DECISION and unstamped parks never stop", () => {
|
|
54
|
+
const input = "a".repeat(16), base = "b".repeat(40);
|
|
55
|
+
assert.equal(fingerprintStop({ comments: [stamped(OUTCOME_CODES.ENV_TOOL_MISSING, base, input)], base, input }), null);
|
|
56
|
+
assert.ok(!stampable(OUTCOME_CODES.ENV_TOOL_MISSING) && !stampable(OUTCOME_CODES.BASE_RED) && stampable("ci.red"));
|
|
57
|
+
const decision = { body: "<!-- FORGE:DECISION -->\nretry with the e2e deferred", __mine: true };
|
|
58
|
+
assert.equal(fingerprintStop({ comments: [stamped("ci.red", base, input), decision], base, input }), null);
|
|
59
|
+
const unstamped = { body: "<!-- FORGE:NEEDS_HUMAN -->\nold\n\nsig=0123456789ab", __mine: true };
|
|
60
|
+
assert.equal(fingerprintStop({ comments: [stamped("ci.red", base, input), unstamped], base, input })?.code, "ci.red"); // a later unstamped park leaves the stamp standing
|
|
61
|
+
assert.equal(fingerprintStop({ comments: [unstamped], base, input }), null);
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
test("fingerprintStop honours trust", () => {
|
|
65
|
+
const input = "a".repeat(16), base = "b".repeat(40);
|
|
66
|
+
assert.equal(fingerprintStop({ comments: [stamped("ci.red", base, input)], base, input, trusted: () => false }), null);
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
test("inputOf ignores labels, follows title/body/decisions/contract", () => {
|
|
70
|
+
const a = inputOf({ iss: { title: "t", body: "b" }, comments: [] });
|
|
71
|
+
assert.equal(a, inputOf({ iss: { title: "t", body: "b", labels: ["x"] }, comments: [] }));
|
|
72
|
+
assert.notEqual(a, inputOf({ iss: { title: "t", body: "b2" }, comments: [] }));
|
|
73
|
+
assert.notEqual(a, inputOf({ iss: { title: "t", body: "b" }, comments: [{ body: "<!-- FORGE:DECISION -->\nd" }] }));
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
test("admitEvent always records zero builder spend", () => {
|
|
77
|
+
assert.equal(admitEvent({ outcome: "base_red", code: "base.red" }).builder_spend_usd, 0);
|
|
78
|
+
});
|
|
79
|
+
|
|
80
|
+
// #6231: one non-stoppable list for the stamp writer, the stop reader and lean.mjs.
|
|
81
|
+
test("transient and infrastructure codes are never stamped and never stop admission (#6231)", () => {
|
|
82
|
+
const input = "a".repeat(16), base = "b".repeat(40);
|
|
83
|
+
for (const code of ["engine.error", "sandbox.transient", "sandbox.lost", "sandbox.auth", "backend.auth", "env.setup_failed", "gh.unavailable", "net.transient", "lane.mismatch", "lease.held", "rate_limited", "base.red"]) {
|
|
84
|
+
assert.ok(isNonStoppable(code), code);
|
|
85
|
+
assert.ok(!stampable(code), code);
|
|
86
|
+
assert.equal(fingerprintStop({ comments: [stamped(code, base, input)], base, input }), null, code); // an old stamp of such a code (written by an earlier engine) never stops either
|
|
87
|
+
}
|
|
88
|
+
assert.ok(NON_STOPPABLE_CODES.has("engine.error"));
|
|
89
|
+
for (const code of ["ci.red", "review.failed", "build.acceptance_failed"]) assert.ok(stampable(code) && !isNonStoppable(code), code);
|
|
90
|
+
});
|
|
91
|
+
|
|
92
|
+
// #6232: whole-token check names, contract/deliverable files, label or link.
|
|
93
|
+
const redRow = [{ name: "test", conclusion: "failure", summary: "FAIL bin/lean/foo.test.mjs\n at bin/lean/foo.mjs:3" }];
|
|
94
|
+
const req = ["test"];
|
|
95
|
+
test("base.red: a check name matches as a whole token, not a substring (#6232)", () => {
|
|
96
|
+
assert.equal(baseHealth({ checks: redRow, required: req, issueText: "handle the latest contest of attestation" }).red, true);
|
|
97
|
+
assert.equal(baseHealth({ checks: redRow, required: req, issueText: "the test check is red" }).red, false);
|
|
98
|
+
});
|
|
99
|
+
test("base.red: an issue whose frozen contract touches the failing files, or is labelled or linked as the fix, is admitted (#6232)", () => {
|
|
100
|
+
const issue = (x) => ({ text: "refactor the planner", ...x });
|
|
101
|
+
assert.equal(baseHealth({ checks: redRow, required: req, issue: issue({}) }).red, true); // a bystander is still deferred
|
|
102
|
+
assert.equal(baseHealth({ checks: redRow, required: req, issue: issue({ contractText: JSON.stringify({ deliverables: ["bin/lean/foo.mjs"] }) }) }).red, false);
|
|
103
|
+
assert.equal(baseHealth({ checks: redRow, required: req, issue: issue({ contractText: JSON.stringify({ files: ["bin/lean/other.mjs"] }) }) }).red, false); // same directory: the check's scope
|
|
104
|
+
assert.equal(baseHealth({ checks: redRow, required: req, issue: issue({ contractText: JSON.stringify({ files: ["docs/readme.md"] }) }) }).red, true);
|
|
105
|
+
assert.equal(baseHealth({ checks: redRow, required: req, issue: issue({ labels: [{ name: "base-red" }] }) }).red, false);
|
|
106
|
+
assert.equal(baseHealth({ checks: redRow, required: req, issue: issue({ linkedBaseRed: true }) }).red, false);
|
|
107
|
+
});
|
|
108
|
+
|
|
109
|
+
// #6233: only the documented logged-out signal is a login failure; anything else unknown fails open with a warning.
|
|
110
|
+
import { classifyAuthStatus } from "./effects.mjs";
|
|
111
|
+
test("classifyAuthStatus: logged-out is ok:false, success ok:true, other non-zero or no run is unknown (#6233)", () => {
|
|
112
|
+
assert.equal(classifyAuthStatus({ status: 0, out: '{"loggedIn": true}' }).ok, true);
|
|
113
|
+
assert.equal(classifyAuthStatus({ status: 1, out: '{"loggedIn": false}' }).ok, false);
|
|
114
|
+
assert.equal(classifyAuthStatus({ status: 1, out: "Not logged in. Run claude login" }).ok, false);
|
|
115
|
+
const other = classifyAuthStatus({ status: 2, out: "unexpected flag" });
|
|
116
|
+
assert.equal(other.ok, null); assert.match(other.warning, /exited 2/);
|
|
117
|
+
assert.equal(classifyAuthStatus({ status: 1, out: "ECONNREFUSED proxy" }).ok, null); // a non-logged-out failure is not backend.auth
|
|
118
|
+
assert.equal(classifyAuthStatus({ error: Object.assign(new Error("x"), { code: "ENOENT" }), status: null }).ok, null);
|
|
119
|
+
assert.equal(classifyAuthStatus({ status: null }).ok, null);
|
|
120
|
+
});
|
package/bin/lean/attempts.mjs
CHANGED
|
@@ -54,7 +54,7 @@ export function recordFailure(ledger, { signature, hash = null, spend = 0, run =
|
|
|
54
54
|
return { ...rest, ...(pin ? { hostPin: true } : {}), ...(escalated && !changed ? { escalated } : {}), attempts: l.attempts + 1, signatures: [...l.signatures, { sig: String(signature ?? ""), ...(hash ? { hash } : {}), ...(run ? { run } : {}), ...(blocker ? { blocker } : {}) }], lastInputHash: hash ?? l.lastInputHash, spend: Math.round((l.spend + (Number(spend) || 0)) * 1e6) / 1e6 };
|
|
55
55
|
}
|
|
56
56
|
|
|
57
|
-
/** The breach of the lifetime budget, or null: attempts reached the cap, or one signature
|
|
57
|
+
/** The breach of the lifetime budget, or null: attempts reached the cap, or one signature reached `maxIdentical` failures. */
|
|
58
58
|
export function breach(ledger, cfg) {
|
|
59
59
|
const l = normalizeLedger(ledger), { maxAttempts, maxIdentical } = budgets(cfg);
|
|
60
60
|
const counts = new Map();
|
package/bin/lean/batch.mjs
CHANGED
|
@@ -409,6 +409,14 @@ export function openBatch(root, id) {
|
|
|
409
409
|
clearCancel: () => rmSync(f("cancel"), { force: true }),
|
|
410
410
|
/** Added issues the batch never took into its `order` (a finished or unhosted batch with pending adds). */
|
|
411
411
|
unrunAdds: () => { const order = new Set(readJsonCached(f("state.json"))?.order ?? []); return readAdded(f("add")).filter((n) => !order.has(n)); },
|
|
412
|
+
/** #6197: age (ms) of the oldest unconsumed add/requeue entry (the add/requeue file's mtime while `unrunAdds()`/`unrunRequeues()` is non-empty), else null. */
|
|
413
|
+
unrunInputAgeMs: (now = Date.now()) => {
|
|
414
|
+
let oldest = null;
|
|
415
|
+
for (const [name, open] of [["add", () => self.unrunAdds().length], ["requeue", () => self.unrunRequeues().length]]) {
|
|
416
|
+
try { if (!open()) continue; const m = statSync(f(name)).mtimeMs; if (oldest === null || m < oldest) oldest = m; } catch { /* absent */ }
|
|
417
|
+
}
|
|
418
|
+
return oldest === null ? null : Math.max(0, now - oldest);
|
|
419
|
+
},
|
|
412
420
|
/** #5531: a `report.json` or `cancel` file exists (two stats, no parse): the batch needs no scanning. */
|
|
413
421
|
isTerminal: () => existsSync(f("report.json")) || existsSync(f("cancel")),
|
|
414
422
|
/** #4775: epoch ms of the batch's last progress (newest mtime of `state.json` / `log.jsonl`), or null when neither exists. */
|
package/bin/lean/batch.test.mjs
CHANGED
|
@@ -1251,6 +1251,23 @@ describe("#4540: remote admissions are capped to the provider's free capacity",
|
|
|
1251
1251
|
});
|
|
1252
1252
|
});
|
|
1253
1253
|
|
|
1254
|
+
describe("#6204: a capacity-gated refusal is a wait, not a deferral row", () => {
|
|
1255
|
+
it("a sandbox.capacity bounce while the pool reports slots writes no deferred row and the issue still runs", async () => {
|
|
1256
|
+
const c = { t: 1_000_000 };
|
|
1257
|
+
const sleep = async (ms) => { await new Promise((r) => setImmediate(r)); c.t += ms; };
|
|
1258
|
+
const updates = [], events = [];
|
|
1259
|
+
let tries = 0, at = 0;
|
|
1260
|
+
const rows = await orchestrate({ issues: [1], parallel: 1, now: () => c.t, sleep, pollMs: 1, readBody: async () => "", onUpdate: (r) => updates.push(r),
|
|
1261
|
+
store: { log: (e) => events.push(e), save() {}, load: () => null },
|
|
1262
|
+
remote: { max: 1, isRemote: () => true, capacity: () => ({ free: 1, online: 1, at: ++at }) },
|
|
1263
|
+
runOne: async (n) => (++tries === 1 ? { terminalReason: "deferred", code: "sandbox.capacity", retryInSeconds: 60, detail: "sandbox launch: HTTP 503" } : { terminalReason: "merged", pr: 100 + n }) });
|
|
1264
|
+
assert.deepEqual(rows.map((r) => r.outcome), ["merged"]);
|
|
1265
|
+
assert.equal(updates.filter((r) => r.outcome === "deferred").length, 0, "no deferred row");
|
|
1266
|
+
assert.equal(events.filter((e) => e.event === "capacity.wait").length, 1, "one wait event");
|
|
1267
|
+
assert.equal(tries, 2);
|
|
1268
|
+
});
|
|
1269
|
+
});
|
|
1270
|
+
|
|
1254
1271
|
describe("#4547: opt-in local fallback in mode remote when no pool agent is online", () => {
|
|
1255
1272
|
const run = async (remoteExtra, online) => {
|
|
1256
1273
|
const c = { t: 1_000_000 };
|
package/bin/lean/concurrency.mjs
CHANGED
|
@@ -12,6 +12,7 @@ export const LOAD_HALVE = 1.5;
|
|
|
12
12
|
export const LOAD_GREEN = 1.0;
|
|
13
13
|
export const MEM_FLOOR_GB = 4;
|
|
14
14
|
export const MEM_HEADROOM_GB = 2;
|
|
15
|
+
export const RECOVER_HOLDS = 3;
|
|
15
16
|
|
|
16
17
|
const fin = (v) => typeof v === "number" && Number.isFinite(v);
|
|
17
18
|
/** `host_load` from a refusal reason/code (`pool.host_load` or `host_load`); "" when it is not a pool reason. */
|
|
@@ -35,7 +36,7 @@ export function makeController({ ceiling, heavyCap = null, now = Date.now, memFl
|
|
|
35
36
|
let top = Math.max(1, Number.isInteger(ceiling) ? ceiling : 1);
|
|
36
37
|
let k = Math.min(top, Math.max(1, Number.isInteger(start) ? start : top)); // no signal yet: run at the ceiling, as before
|
|
37
38
|
let factor = "ceiling";
|
|
38
|
-
let lastRefusal = -Infinity;
|
|
39
|
+
let lastRefusal = -Infinity, lastGrow = -Infinity;
|
|
39
40
|
const held = new Map(); // issue -> { at, reason }
|
|
40
41
|
const hcap = () => Math.max(1, Math.min(top, Number.isInteger(heavyCap) ? heavyCap : Math.ceil(top / 3)));
|
|
41
42
|
const ev = (change, inputs) => ({ event: "concurrency", change, k, ceiling: top, factor, inputs });
|
|
@@ -65,7 +66,11 @@ export function makeController({ ceiling, heavyCap = null, now = Date.now, memFl
|
|
|
65
66
|
observe(cap) {
|
|
66
67
|
if (!cap || !fin(cap.load_per_core) || !fin(cap.mem_available_gb)) return null; // unknown pool: K applies unchanged
|
|
67
68
|
if (k >= top) { factor = "ceiling"; return null; }
|
|
68
|
-
|
|
69
|
+
// #6204: recover to the ceiling after pressure clears: green load grows after holdMs; a load between green and the halve line (never
|
|
70
|
+
// a halving cause) grows after RECOVER_HOLDS holds of quiet, so a host that sits at 1.0-1.5/core no longer pins K at its low point for hours.
|
|
71
|
+
const quiet = now() - lastRefusal, calm = cap.load_per_core < LOAD_GREEN ? quiet >= holdMs : cap.load_per_core < LOAD_HALVE && quiet >= holdMs * RECOVER_HOLDS;
|
|
72
|
+
if (cap.mem_available_gb > memFloorGb + MEM_HEADROOM_GB && calm && (cap.load_per_core < LOAD_GREEN || now() - lastGrow >= holdMs / RECOVER_HOLDS)) {
|
|
73
|
+
lastGrow = now();
|
|
69
74
|
const before = k; k += 1;
|
|
70
75
|
if (k >= top) factor = "ceiling";
|
|
71
76
|
return ev("increase", { from: before, load_per_core: cap.load_per_core, mem_available_gb: cap.mem_available_gb });
|
|
@@ -35,12 +35,25 @@ describe("controller (#5985)", () => {
|
|
|
35
35
|
assert.equal(ctl.operating(), 4);
|
|
36
36
|
assert.equal(ctl.limiting(), "host_load");
|
|
37
37
|
});
|
|
38
|
-
it("a red pool (low memory or load >= 1) does not increase", () => {
|
|
38
|
+
it("a red pool (low memory or load >= 1.5) does not increase", () => {
|
|
39
39
|
const { c, ctl } = mk();
|
|
40
|
-
ctl.refused({ code: "pool.host_load" }); c.t += REFUSAL_HOLD_MS;
|
|
41
|
-
assert.equal(ctl.observe({ load_per_core: 1.
|
|
40
|
+
ctl.refused({ code: "pool.host_load" }); c.t += REFUSAL_HOLD_MS * 4;
|
|
41
|
+
assert.equal(ctl.observe({ load_per_core: 1.8, mem_available_gb: 12 }), null);
|
|
42
42
|
assert.equal(ctl.observe({ load_per_core: 0.3, mem_available_gb: 5 }), null);
|
|
43
43
|
});
|
|
44
|
+
it("#6204: a host sitting at 1.0-1.5/core recovers toward the ceiling slowly after quiet, and never within the first hold", () => {
|
|
45
|
+
const { c, ctl } = mk();
|
|
46
|
+
ctl.refused({ code: "pool.host_load" }); // 8 -> 4
|
|
47
|
+
const mid = { load_per_core: 1.2, mem_available_gb: 12 };
|
|
48
|
+
c.t += REFUSAL_HOLD_MS;
|
|
49
|
+
assert.equal(ctl.observe(mid), null, "one hold of quiet is not enough at moderate load");
|
|
50
|
+
c.t += REFUSAL_HOLD_MS * 2;
|
|
51
|
+
assert.equal(ctl.observe(mid).change, "increase");
|
|
52
|
+
assert.equal(ctl.observe(mid), null, "grows are paced");
|
|
53
|
+
for (let i = 0; i < 4; i++) { c.t += REFUSAL_HOLD_MS; ctl.observe(mid); }
|
|
54
|
+
assert.equal(ctl.operating(), 8);
|
|
55
|
+
assert.equal(ctl.limiting(), "ceiling");
|
|
56
|
+
});
|
|
44
57
|
it("classifies heavy repos from usage-history cpu_avg > 1.5 and caps heavy lanes below light", () => {
|
|
45
58
|
const rows = [{ repo: "a/h", cpu_avg: 3 }, { repo: "a/h", cpu_avg: 2 }, { repo: "a/l", cpu_avg: 0.4 }];
|
|
46
59
|
assert.equal(classifyRepo(rows, "a/h"), "heavy");
|
package/bin/lean/conformance.mjs
CHANGED
|
@@ -832,6 +832,8 @@ const CMD_NOT_FOUND_RE = /([^\s:'"`]+): command not found/, SH_NOT_FOUND_RE = /(
|
|
|
832
832
|
// no Playwright browser, no network for npm), never a failing assertion of the change
|
|
833
833
|
const ENV_SIGNATURES = [
|
|
834
834
|
[/Cannot connect to the Docker daemon|docker\.sock|error during connect|Is the docker daemon running/i, "Docker daemon"],
|
|
835
|
+
// #6196: no Docker where the step runs: a script's own "no ... image present locally", a failed pull, no docker binary, testcontainers without a daemon
|
|
836
|
+
[/\bno\b[^\n]{0,60}\bimage\b[^\n]{0,30}present locally|Unable to find image [^\n]*locally[\s\S]{0,300}?(?:pull access denied|failed to pull|error pulling|Error response from daemon|dial tcp|no such host)|\bdocker: (?:command )?not found|Could not find a valid Docker environment/i, "Docker daemon"],
|
|
835
837
|
[/invalid mount config for type "bind"|bind source path does not exist|error while creating mount source path|mounts denied/i, "Docker bind-mount source"],
|
|
836
838
|
[/Executable doesn't exist at|npx playwright install|browserType\.launch: Executable/i, "Playwright browser"],
|
|
837
839
|
[/\bENOTFOUND\b|\bEAI_AGAIN\b|npm (?:ERR!|error) network|getaddrinfo (?:ENOTFOUND|EAI_AGAIN)/i, "network access for npm"],
|
|
@@ -178,6 +178,15 @@ describe("precheck (deterministic, no reviewer)", () => {
|
|
|
178
178
|
const local = precheck({ contract: C, result: failed, changedFiles: files, repoHas: repoTracks(["src/leak/__init__.py"]), validateRuns: { V1: { rc: 1, output: "ModuleNotFoundError: No module named 'leak.core'" } } });
|
|
179
179
|
assert.deepEqual(codes(local), ["conformance.unimplemented"], "a repo module the change did not create is a code defect");
|
|
180
180
|
});
|
|
181
|
+
it("6196: docker image/daemon-less messages are env failures with a docker tool; assertion output mentioning docker is not", () => {
|
|
182
|
+
const msgs = ["no scratch Postgres image present locally (tried postgres:15-alpine, pgvector/pgvector:pg15)",
|
|
183
|
+
"Unable to find image 'postgres:15' locally\ndocker: Error response from daemon: pull access denied for postgres, repository does not exist",
|
|
184
|
+
"Could not find a valid Docker environment. Please see logs and check configuration"];
|
|
185
|
+
for (const o of msgs) { assert.equal(isEnvValidateFailure(o), true, o); assert.equal(missingTool({ rc: 1, output: o })?.tool, "Docker daemon", o); }
|
|
186
|
+
assert.equal(missingTool({ rc: 127, output: "bash: docker: command not found" })?.tool, "docker");
|
|
187
|
+
for (const o of ["AssertionError: expected docker image tag to equal 'latest'\nno image present locally was reported", "FAILED tests/test_docker.py::test_build - assert 'docker' == 'podman'"]) assert.equal(isEnvValidateFailure(o), false, o);
|
|
188
|
+
});
|
|
189
|
+
|
|
181
190
|
it("5730: isEnvValidateFailure matches sandbox-only signatures, never assertion or stale-artifact output", () => {
|
|
182
191
|
for (const o of ["sh: 1: foo: command not found", "connect ECONNREFUSED 127.0.0.1:5432", "dial tcp: lookup db: no such host", "Connection refused", "services/api/.venv/bin/python: No such file or directory", "cannot open display :0", "Cannot connect to the Docker daemon"]) assert.equal(isEnvValidateFailure(o), true, o);
|
|
183
192
|
for (const o of ["AssertionError: 1 != 2", "x.md: missing or out of date (run --render-agent-md)", "ECONNREFUSED\nAssertionError: expected 1 to equal 2", "", undefined]) assert.equal(isEnvValidateFailure(o), false, String(o));
|
package/bin/lean/effects.mjs
CHANGED
|
@@ -526,6 +526,15 @@ export function makeGhCache({ root = null, tmp = tmpdir() } = {}) {
|
|
|
526
526
|
};
|
|
527
527
|
}
|
|
528
528
|
|
|
529
|
+
/** #6233: classify a `claude auth status` result. Only the documented logged-out signal is `ok:false`; everything else that is not success is unknown. */
|
|
530
|
+
export function classifyAuthStatus({ error = null, status = null, out = "" } = {}) {
|
|
531
|
+
if (error || status === null) return { ok: null, warning: `claude auth status did not run (${String(error?.code ?? error?.message ?? "timeout or signal").slice(0, 80)})` };
|
|
532
|
+
const text = String(out ?? "");
|
|
533
|
+
if (/"loggedIn"\s*:\s*false/i.test(text) || (status === 1 && /\bnot logged in\b/i.test(text))) return { ok: false };
|
|
534
|
+
if (status === 0) return { ok: true };
|
|
535
|
+
return { ok: null, warning: `claude auth status exited ${status} without the logged-out signal; treated as unknown, not as a login failure: ${text.trim().split("\n")[0].slice(0, 120)}` };
|
|
536
|
+
}
|
|
537
|
+
|
|
529
538
|
export function makeLeanIo({ repo, subagentModel = readSubagentModel() }) {
|
|
530
539
|
const base = makeIo();
|
|
531
540
|
const seqLeaseIo = makeSequenceLeaseIo(); // #5340: one instance: sequence leases, surface leases and declarations
|
|
@@ -543,6 +552,19 @@ export function makeLeanIo({ repo, subagentModel = readSubagentModel() }) {
|
|
|
543
552
|
gh: run("gh"), git: run("git"), docker: run("docker"), killGroup: async (pid, marker) => killLedgerPid(pid, marker), ledger: (opts) => makeLedger(opts), runTmp: makeRunTmp(), host: makeHostProbe(), heavy: guardHeavyDisk(makeHeavyIo({ host: makeHostProbe() }), { host: makeHostProbe(), minFreeGb: async () => (await import("../gc.mjs")).readHygiene(process.cwd()).min_free_gb, gc: async () => { const g = await import("../gc.mjs"); return g.runOwnedGc({ probes: g.makeGcProbes({ cwd: process.cwd() }), hygiene: g.readHygiene(process.cwd()), budgetMs: 60000 }); } }), projector: makeProjector({ gh: base.gh }, { repo }), runner: makeLeanRunner({ subagentModel }), waitCiGreen: base.waitCiGreen,
|
|
544
553
|
/** Shared dependency cache (#4220): the repo's own package manager, argv only, bounded by the cache's timeout. */
|
|
545
554
|
deps: makeDepCache({ exec: async (cmd, args, { cwd, env, timeoutMs } = {}) => String((await pexec(cmd, args, { cwd, env: { ...process.env, ...(env ?? {}) }, timeout: timeoutMs ?? 0, maxBuffer: 100 * 1024 * 1024 })).stdout) }),
|
|
555
|
+
/**
|
|
556
|
+
* #6206/#6233: the cheap login probe (`claude auth status`, no model call) the admit probe runs before any builder session. It runs with the
|
|
557
|
+
* lane's own env (`env`: CLAUDE_CONFIG_DIR, API-key vars), so a pinned-profile or API-key lane is probed as itself. `ok` false only for the
|
|
558
|
+
* documented logged-out signal (exit 1 with "Not logged in" or loggedIn:false); any other non-zero exit, a missing binary or a timeout is unknown
|
|
559
|
+
* (`ok` null, `warning` set): the caller fails open and records the warning.
|
|
560
|
+
*/
|
|
561
|
+
async claudeAuthProbe({ env = null } = {}) {
|
|
562
|
+
const { spawnSync } = await import("node:child_process");
|
|
563
|
+
const r = spawnSync("claude", ["auth", "status"], { timeout: 15000, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], env: { ...process.env, ...(env ?? {}) } });
|
|
564
|
+
return classifyAuthStatus({ error: r.error, status: r.status, out: `${r.stdout ?? ""}\n${r.stderr ?? ""}` });
|
|
565
|
+
},
|
|
566
|
+
/** #6206: the admit probe's own read of the required checks (a separate seam, so the precheck's and the merge policy's reads are unchanged). */
|
|
567
|
+
async baseRequiredChecks(lane) { return requiredChecksFor({ gh: run("gh"), repo, lane }); },
|
|
546
568
|
/** Names of the checks the base branch requires: classic protection plus rulesets (#4158). [] when neither has any. */
|
|
547
569
|
async requiredChecks(lane) { return requiredChecksFor({ gh: run("gh"), repo, lane }); },
|
|
548
570
|
/**
|
|
@@ -25,7 +25,7 @@ export const PARK_BUCKETS = Object.freeze([
|
|
|
25
25
|
["scope_creep", /scope_creep|outside the contract's deliverables/],
|
|
26
26
|
["validate_failed", /validate [A-Z]?\d+ .*failed|frozen command runs and fails|Declared check command\(s\) failing/],
|
|
27
27
|
["ci_red", /Required check\(s\) failed|ci\.red|CI verification failed/],
|
|
28
|
-
["env_setup", /Environment error|env\.(setup_failed|tool_missing|validate_timeout|validate_placement|repro_unrunnable|capability_remote)/],
|
|
28
|
+
["env_setup", /Environment error|env\.(setup_failed|tool_missing|validate_timeout|validate_placement|repro_unrunnable|capability_remote|capability_docker)/],
|
|
29
29
|
["builder_blocked", /Builder is blocked|builder\.(blocked|no_commit)|Builder made no commit/],
|
|
30
30
|
["review_incomplete", /review\.(incomplete|failed|unparseable)|Review FAIL/],
|
|
31
31
|
["e2e_unverified", /e2e_unverified|e2e_placement/],
|