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/lean/phaseledger.mjs
CHANGED
|
@@ -93,6 +93,12 @@ export const laneSum = (phases) => Object.entries(phases ?? {}).reduce((s, [id,
|
|
|
93
93
|
/** True when the lane phases sum to within `tol` of `wallMs`. */
|
|
94
94
|
export const withinWall = (phases, wallMs, tol = 0.05) => isNum(wallMs) && wallMs >= 0 && Math.abs(laneSum(phases) - wallMs) <= Math.max(1, wallMs * tol);
|
|
95
95
|
|
|
96
|
+
/** Fixed overhead = lane wall time not spent in a model call (never negative); model_share = model time / wall (0 when wall <= 0). */
|
|
97
|
+
export function overheadStats(_phases, wallMs, modelMs) {
|
|
98
|
+
const wall = isNum(wallMs) ? wallMs : 0, model = isNum(modelMs) ? modelMs : 0;
|
|
99
|
+
return { fixed_overhead_ms: Math.max(0, wall - model), model_share: wall > 0 ? Math.round((model / wall) * 1000) / 1000 : 0 };
|
|
100
|
+
}
|
|
101
|
+
|
|
96
102
|
export function flattenPhases(phases) {
|
|
97
103
|
const out = {};
|
|
98
104
|
for (const [id, v] of Object.entries(phases ?? {})) {
|
|
@@ -7,7 +7,7 @@ import { tmpDir } from "../tests/_tmp.mjs";
|
|
|
7
7
|
import { join } from "node:path";
|
|
8
8
|
import { phasesOf } from "./orchestrate.mjs";
|
|
9
9
|
import { aggregate } from "../stats/aggregate.mjs";
|
|
10
|
-
import { LANE_PHASES, createLedger, laneSum, withinWall, flattenPhases, unflattenPhases, summarizePhases, formatLedgerSummary, WAIT_CAUSES, summarizeWaits, comparePhases, formatPhaseComparison, readBaselineRows } from "./phaseledger.mjs";
|
|
10
|
+
import { LANE_PHASES, createLedger, laneSum, withinWall, flattenPhases, unflattenPhases, overheadStats, summarizePhases, formatLedgerSummary, WAIT_CAUSES, summarizeWaits, comparePhases, formatPhaseComparison, readBaselineRows } from "./phaseledger.mjs";
|
|
11
11
|
|
|
12
12
|
const clock = () => { let t = 1000; const f = () => t; f.tick = (ms) => { t += ms; }; return f; };
|
|
13
13
|
|
|
@@ -167,3 +167,15 @@ describe("phase comparison vs previous 7 days (#5649)", () => {
|
|
|
167
167
|
assert.equal(readBaselineRows({ root: join(root, "missing"), now }), null);
|
|
168
168
|
});
|
|
169
169
|
});
|
|
170
|
+
|
|
171
|
+
describe("overheadStats", () => {
|
|
172
|
+
it("splits wall into model share and fixed overhead", () => {
|
|
173
|
+
assert.deepEqual(overheadStats({}, 1000, 320), { fixed_overhead_ms: 680, model_share: 0.32 });
|
|
174
|
+
});
|
|
175
|
+
it("zero wall gives zero share", () => {
|
|
176
|
+
assert.deepEqual(overheadStats({}, 0, 50), { fixed_overhead_ms: 0, model_share: 0 });
|
|
177
|
+
});
|
|
178
|
+
it("model > wall clamps overhead to 0", () => {
|
|
179
|
+
assert.equal(overheadStats({}, 100, 150).fixed_overhead_ms, 0);
|
|
180
|
+
});
|
|
181
|
+
});
|
|
@@ -94,7 +94,7 @@ describe("post-deploy named checks (#4626)", () => {
|
|
|
94
94
|
assert.equal(r.state, "recorded-fail"); assert.deepEqual(w.spawned, []);
|
|
95
95
|
});
|
|
96
96
|
|
|
97
|
-
it("contract: post-deploy needs a check id; amendment too;
|
|
97
|
+
it("contract: post-deploy needs a check id; amendment too; followup item names it", () => {
|
|
98
98
|
const Q = "The deploy-time health row must exist after promotion.";
|
|
99
99
|
const c = { requirements: [{ id: "R1", quote: Q, disposition: "post-deploy", why: "w" }], deliverables: [], preserve: [], validate: [{ id: "V1", command: "true" }] };
|
|
100
100
|
assert.ok(validateContract(c, Q).problems.some((p) => /needs a check id/.test(p)));
|
|
@@ -105,8 +105,6 @@ describe("post-deploy named checks (#4626)", () => {
|
|
|
105
105
|
assert.equal(deferred.contract.requirements[0].disposition, "defer");
|
|
106
106
|
const ok = applyAmendments(frozen, [{ kind: "post-deploy", requirement: "R1", why: "w", check: "smoke" }], Q);
|
|
107
107
|
assert.equal(ok.contract.requirements[0].check, "smoke");
|
|
108
|
-
const pc = precheck({ contract: { ...c, requirements: [{ ...c.requirements[0], check: "ghost" }] }, result: { requirements: [] }, changedFiles: [], checkIds: new Set(["smoke"]) });
|
|
109
|
-
assert.ok(pc.failures.some((f) => f.kind === "check_unknown"));
|
|
110
108
|
assert.match(followupItems([{ ...c.requirements[0], check: "smoke" }])[0].why, /^post-deploy: \[check:smoke\] w/);
|
|
111
109
|
});
|
|
112
110
|
});
|
package/bin/lean/precheck.mjs
CHANGED
|
@@ -234,6 +234,26 @@ export function quietFailure(output, { lines = QUIET_TAIL_LINES, maxChars = Infi
|
|
|
234
234
|
return out.join("\n");
|
|
235
235
|
}
|
|
236
236
|
|
|
237
|
+
/** #6107: masks credential-looking text before a check's output reaches a needs-human comment or the run log. Generic patterns only. */
|
|
238
|
+
export function redactSecrets(text) {
|
|
239
|
+
return String(text ?? "")
|
|
240
|
+
.replace(/-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?(?:-----END [A-Z ]*PRIVATE KEY-----|$)/g, "[redacted private key]")
|
|
241
|
+
.replace(/\b(?:sk|pk|rk)-[A-Za-z0-9_-]{8,}/g, "[redacted]")
|
|
242
|
+
.replace(/\b(?:ghp|gho|ghu|ghs|ghr|github_pat|glpat|xox[abprs]|npm|AKIA|ASIA)[_-]?[A-Za-z0-9_-]{12,}/g, "[redacted]")
|
|
243
|
+
.replace(/\b(Bearer|Basic)\s+[A-Za-z0-9._~+\/=-]{8,}/gi, "$1 [redacted]")
|
|
244
|
+
.replace(/\b([A-Za-z0-9_.-]*(?:token|secret|password|passwd|api[_-]?key|private[_-]?key|credential|authorization)[A-Za-z0-9_.-]*)(["']?\s*[:=]\s*["']?)[^\s"',}]{4,}/gi, "$1$2[redacted]")
|
|
245
|
+
.replace(/\b([a-z][a-z0-9+.-]*:\/\/[^\s:@\/]+:)[^\s@\/]+@/gi, "$1[redacted]@");
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/**
|
|
249
|
+
* #6107: one failed check as park/run-log text: its name (a CI job name, else the command) and the last `lines` lines of
|
|
250
|
+
* its output, secrets redacted, within `maxChars`.
|
|
251
|
+
*/
|
|
252
|
+
export function checkFailureTail(f, { name = null, lines = QUIET_TAIL_LINES, maxChars = 4000 } = {}) {
|
|
253
|
+
const label = name ? `${name} (\`${f.command}\`)` : `\`${f.command}\``;
|
|
254
|
+
return `\n\nFailing check ${label}, exit ${f.rc}, last ${lines} lines of its output:\n${redactSecrets(quietFailure(f.output, { lines, maxChars }))}`;
|
|
255
|
+
}
|
|
256
|
+
|
|
237
257
|
/** #4364: the compact pass/fail table `forgedock check` prints; #4390: each failure quiet (`quietFailure`), within `cap` chars. */
|
|
238
258
|
export function formatCheckTable(r, cap = LOG_CAP) {
|
|
239
259
|
const word = (x) => (x.status === "ci" ? "CI" : x.status ? "DEFERRED" : x.rc === 0 ? "PASS" : `FAIL exit ${x.rc}`);
|
package/bin/lean/preflight.mjs
CHANGED
|
@@ -11,7 +11,7 @@
|
|
|
11
11
|
*/
|
|
12
12
|
import { builtinModules } from "node:module";
|
|
13
13
|
import { existsSync } from "node:fs";
|
|
14
|
-
import { join, dirname, delimiter,
|
|
14
|
+
import { join, dirname, delimiter, posix } from "node:path";
|
|
15
15
|
import { missingTool } from "./conformance.mjs";
|
|
16
16
|
|
|
17
17
|
export const PREFLIGHT_CAP = 20;
|
|
@@ -159,12 +159,32 @@ export function testRunnerProblems(contract, runners) {
|
|
|
159
159
|
return out;
|
|
160
160
|
}
|
|
161
161
|
|
|
162
|
+
/**
|
|
163
|
+
* #5749: validate/repro commands that cannot run in a lane sandbox whatever is installed: a host-only wrapper or path
|
|
164
|
+
* (`legion-run`, `ssh <host>`, `/home/<user>/...`) or an unbounded CPU busy loop (`while :`/`while true` with no sleep or
|
|
165
|
+
* read, `yes > /dev/null`, `seq $(nproc)` fan-out). One problem per command id. Pure.
|
|
166
|
+
*/
|
|
167
|
+
export function hostOnlyProblems(contract) {
|
|
168
|
+
const out = [];
|
|
169
|
+
for (const v of contractCommands(contract)) {
|
|
170
|
+
const cmd = v.command, why = [];
|
|
171
|
+
const exes = shellSegments(cmd).map((seg) => { let i = 0; while (i < seg.length && (/^[A-Za-z_]\w*=/.test(seg[i]) || ["!", "time", "exec", "command", "env"].includes(seg[i]))) i++; return seg[i]; });
|
|
172
|
+
if (cmd.split(/[\s'"`(;&|]+/).includes("legion-run") || exes.includes("legion-run")) why.push("the host-only wrapper `legion-run`");
|
|
173
|
+
if (exes.includes("ssh")) why.push("`ssh <host>`");
|
|
174
|
+
if (/(^|[\s='"`:(])\/home\/[\w.-]+\//.test(cmd)) why.push("an absolute `/home/<user>/` path");
|
|
175
|
+
if (/\bwhile\s+(:|true)\s*;\s*do\s*(:\s*;\s*)?done\b/.test(cmd) || /\byes\b[^|;&]*>\s*\/dev\/null/.test(cmd) || /\bseq\s+\$\(\s*nproc\s*\)/.test(cmd)) why.push("an unbounded CPU busy loop");
|
|
176
|
+
if (why.length) out.push(`${v.id}: uses ${why.join(" and ")}, which no lane sandbox provides or tolerates, so the command cannot run as written; use a bounded check through the repo's own toolchain, not a host wrapper, host path or CPU stress loop`);
|
|
177
|
+
}
|
|
178
|
+
return out;
|
|
179
|
+
}
|
|
180
|
+
|
|
162
181
|
const FIX_HOW = "run the check through the repo's own toolchain (its virtualenv, lockfile-pinned runner or package scripts) or use a check that does not need it, never a global install";
|
|
163
182
|
/** One contract problem per miss: names the validate ids and the tool (or path, or env var), and how to fix the plan (never a global install). */
|
|
164
183
|
export function preflightProblems(misses) {
|
|
165
184
|
return (misses ?? []).map((m) => {
|
|
166
185
|
const ids = m.ids.join(", ");
|
|
167
186
|
if (m.kind === "env-var") return `${ids}: uses $${m.tool}, which is unset or empty in the lane environment, so the validate command cannot run as written; set it inside the command or ${FIX_HOW}`;
|
|
187
|
+
if (m.source === "collect") return `${ids}: importing its test modules on the base worktree (pytest --collect-only) failed: needs Python module '${m.tool}'${m.line ? ` (\`${m.line}\`)` : ""}, so the command does not run in the environment that has the test's dependencies; run it the way the repo's CI runs that test path (its working-directory and poetry run / uv run) or ${FIX_HOW}`; // #5753
|
|
168
188
|
if (m.source === "run") return `${ids}: running it on the base worktree stopped before any test ran: needs ${KIND_NAME[m.kind] ?? m.kind} '${m.tool}'${m.line ? ` (\`${m.line}\`)` : ""}, so the validate command cannot run here; ${m.kind === "path" ? "point it at a path the repo or a deliverable has, or " : ""}${FIX_HOW}`;
|
|
169
189
|
return `${ids}: needs ${KIND_NAME[m.kind] ?? m.kind} '${m.tool}'${m.interp ? ` (for ${m.interp})` : ""}, which this host lacks, so the validate command cannot run here; ${FIX_HOW}`;
|
|
170
190
|
});
|
|
@@ -326,12 +346,81 @@ export function testRunSummary({ contract, failures = [], repro = null } = {}) {
|
|
|
326
346
|
return { declared: ids.length, ran: ids.length - skipped.length, redGreen, skipped };
|
|
327
347
|
}
|
|
328
348
|
|
|
329
|
-
/**
|
|
330
|
-
|
|
349
|
+
/**
|
|
350
|
+
* #5447: tool names the contract's test plan declares in `env` (per row of the #5445 `test_plan` array, or `test_plan.env`);
|
|
351
|
+
* strings, comma lists or {tool}; [] when absent. #5753: a directory the repo tracks (`files`: tracked paths, e.g. `shared`)
|
|
352
|
+
* is never a host tool. Pure.
|
|
353
|
+
*/
|
|
354
|
+
export function declaredEnv(contract, files = []) {
|
|
331
355
|
const plan = contract?.test_plan;
|
|
332
356
|
const raw = Array.isArray(plan) ? plan.map((r) => r?.env) : [plan?.env];
|
|
333
357
|
const names = raw.flatMap((e) => (Array.isArray(e) ? e : typeof e === "string" ? e.split(",") : [])).map((e) => String(typeof e === "string" ? e : e?.tool ?? "").trim());
|
|
334
|
-
|
|
358
|
+
const dirs = trackedDirs(files);
|
|
359
|
+
return [...new Set(names.filter((t) => /^[\w.+-]+$/.test(t) && isExecutableName(t) && !dirs.has(t)))];
|
|
360
|
+
}
|
|
361
|
+
/** #5753: every directory name a tracked path runs through (`shared/detection/x.py` -> shared, detection). */
|
|
362
|
+
function trackedDirs(files) {
|
|
363
|
+
const out = new Set();
|
|
364
|
+
for (const f of Array.isArray(files) ? files : []) for (const seg of String(f).split("/").slice(0, -1)) if (seg) out.add(seg);
|
|
365
|
+
return out;
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
/** The prefix of one command segment up to its pytest invocation (bare, path/.venv, `python[3[.x]] -m pytest`, after
|
|
369
|
+
* `poetry|uv [flags] run [flags]` and env assignments), or null. A linear token scan: no backtracking (CodeQL js/redos). */
|
|
370
|
+
function pytestPrefix(segment) {
|
|
371
|
+
const toks = [...String(segment).matchAll(/\S+/g)].map((m) => ({ t: m[0], end: m.index + m[0].length }));
|
|
372
|
+
let i = 0;
|
|
373
|
+
while (i < toks.length && /^[A-Za-z_]\w*=/.test(toks[i].t)) i++;
|
|
374
|
+
const base = (t) => t.split("/").pop();
|
|
375
|
+
const isPy = (t) => /^python3?(?:\.\d+)?$/.test(base(t));
|
|
376
|
+
const isPytest = (t) => base(t) === "pytest";
|
|
377
|
+
if (i < toks.length && (toks[i].t === "poetry" || toks[i].t === "uv")) {
|
|
378
|
+
i++;
|
|
379
|
+
while (i < toks.length && toks[i].t.startsWith("-")) i++;
|
|
380
|
+
if (toks[i]?.t !== "run") return null;
|
|
381
|
+
i++;
|
|
382
|
+
while (i < toks.length && toks[i].t.startsWith("-")) {
|
|
383
|
+
const flag = toks[i].t; i++;
|
|
384
|
+
const next = toks[i]?.t;
|
|
385
|
+
if (!flag.includes("=") && next && !next.startsWith("-") && !isPy(next) && !isPytest(next) && toks[i + 1]) i++;
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
const t = toks[i]?.t;
|
|
389
|
+
if (!t) return null;
|
|
390
|
+
if (isPytest(t)) return segment.slice(0, toks[i].end);
|
|
391
|
+
if (isPy(t) && toks[i + 1]?.t === "-m" && toks[i + 2]?.t === "pytest") return segment.slice(0, toks[i + 2].end);
|
|
392
|
+
return null;
|
|
393
|
+
}
|
|
394
|
+
/**
|
|
395
|
+
* #5753: the contract command with `--collect-only -q` after its first pytest invocation (bare, `.venv/bin/python -m`,
|
|
396
|
+
* `poetry run`, `uv run`): one cheap run imports the test modules, so an import error shows at freeze, not in the builder.
|
|
397
|
+
* null when the command runs no pytest. Pure.
|
|
398
|
+
*/
|
|
399
|
+
export function collectOnlyCommand(command) {
|
|
400
|
+
const parts = String(command ?? "").split(/(&&|\|\||;|\||\n)/);
|
|
401
|
+
for (let i = 0; i < parts.length; i += 2) {
|
|
402
|
+
const pre = pytestPrefix(parts[i]);
|
|
403
|
+
if (pre === null) continue;
|
|
404
|
+
if (/(?:^|\s)--collect-only\b/.test(parts[i])) return null;
|
|
405
|
+
parts[i] = `${pre} --collect-only -q${parts[i].slice(pre.length)}`;
|
|
406
|
+
return parts.slice(0, i + 1).join(""); // later segments (`| tail`, `&& echo`) would hide the collect exit
|
|
407
|
+
}
|
|
408
|
+
return null;
|
|
409
|
+
}
|
|
410
|
+
const COLLECT_IMPORT_RE = /(?:ModuleNotFoundError|ImportError): No module named '?([\w.]+)'?/;
|
|
411
|
+
/**
|
|
412
|
+
* #5753: why a collect-only run (collectOnlyCommand) shows the test module cannot import on this host: a module the repo does
|
|
413
|
+
* not track (`repoHas`) is {tool, kind: "python-module", line}. A passing or empty collection, a timeout, an import of a name
|
|
414
|
+
* the change adds (`cannot import name`) and a repo-owned module are no miss (RED on base is expected). Pure.
|
|
415
|
+
*/
|
|
416
|
+
export function collectImportMiss(r, { repoHas = () => false } = {}) {
|
|
417
|
+
const rc = r?.rc, out = String(r?.output ?? "");
|
|
418
|
+
if (!Number.isInteger(rc) || rc === 0 || rc === 5 || rc === TIMEOUT_RC) return null;
|
|
419
|
+
const m = COLLECT_IMPORT_RE.exec(out);
|
|
420
|
+
if (!m) return null;
|
|
421
|
+
const tool = m[1].split(".")[0];
|
|
422
|
+
if (!tool || repoHas(tool) || repoHas(m[1])) return null;
|
|
423
|
+
return { tool, kind: "python-module", line: (out.split("\n").find((l) => l.includes(m[0])) ?? "").trim().slice(0, 160) };
|
|
335
424
|
}
|
|
336
425
|
|
|
337
426
|
/** #5590: pytest's built-in fixtures, never host executables. */
|
|
@@ -390,15 +479,15 @@ export function manifestDepOwner(name, files = [], readFile = () => "") {
|
|
|
390
479
|
const parts = String(f).split("/"), base = parts[parts.length - 1];
|
|
391
480
|
if (parts.includes("node_modules") || !(base === "package.json" || base === "pyproject.toml" || /^requirements[\w.-]*\.txt$/.test(base))) continue;
|
|
392
481
|
let text = ""; try { text = String(readFile(f) ?? ""); } catch { continue; }
|
|
393
|
-
if (manifestDeclares(base.startsWith("requirements") ? "requirements.txt" : base, text, name)) return dirname(f);
|
|
482
|
+
if (manifestDeclares(base.startsWith("requirements") ? "requirements.txt" : base, text, name)) return posix.dirname(f);
|
|
394
483
|
}
|
|
395
484
|
return null;
|
|
396
485
|
}
|
|
397
486
|
|
|
398
487
|
/** nearest ancestor dir (of `dir`, up to the root ".") holding a tracked Python manifest, or null. */
|
|
399
488
|
function nearestPyProject(dir, files) {
|
|
400
|
-
const have = new Set(files.filter((f) => PY_MANIFESTS.has(String(f).split("/").pop()) || /(^|\/)requirements[\w.-]*\.txt$/.test(f)).map((f) => dirname(f)));
|
|
401
|
-
for (let d = dir; ; d = dirname(d)) { if (have.has(d)) return d; if (d === "." || d === "/") return null; }
|
|
489
|
+
const have = new Set(files.filter((f) => PY_MANIFESTS.has(String(f).split("/").pop()) || /(^|\/)requirements[\w.-]*\.txt$/.test(f)).map((f) => posix.dirname(f)));
|
|
490
|
+
for (let d = dir; ; d = posix.dirname(d)) { if (have.has(d)) return d; if (d === "." || d === "/") return null; }
|
|
402
491
|
}
|
|
403
492
|
const PYTEST_SEG = /^(\s*(?:[A-Za-z_]\w*=\S*\s+)*)(?:python3?(?:\.\d+)?\s+-m\s+pytest|pytest)\b/;
|
|
404
493
|
/**
|
|
@@ -412,17 +501,17 @@ export function venvPythonRewrite(command, files = [], exists = () => false) {
|
|
|
412
501
|
const out = parts.map((seg, i) => {
|
|
413
502
|
if (i % 2) return seg;
|
|
414
503
|
const cd = /^\s*cd\s+(?:"([^"]+)"|'([^']+)'|(\S+))\s*$/.exec(seg);
|
|
415
|
-
if (cd) { const t = (cd[1] ?? cd[2] ?? cd[3]).replace(/^\.\//, "").replace(/\/+$/, ""); cwd = t.startsWith("/") || t.startsWith("$") || t.startsWith("..") ? "?" : join(cwd === "?" ? "." : cwd, t) || "."; return seg; }
|
|
504
|
+
if (cd) { const t = (cd[1] ?? cd[2] ?? cd[3]).replace(/^\.\//, "").replace(/\/+$/, ""); cwd = t.startsWith("/") || t.startsWith("$") || t.startsWith("..") ? "?" : posix.join(cwd === "?" ? "." : cwd, t) || "."; return seg; }
|
|
416
505
|
const m = PYTEST_SEG.exec(seg);
|
|
417
506
|
if (!m || cwd === "?") return seg;
|
|
418
507
|
const rest = seg.slice(m[0].length);
|
|
419
508
|
const tp = rest.split(/\s+/).map((x) => x.replace(/::.*$/, "").replace(/^\.\//, "")).find((x) => x && !x.startsWith("-") && /[\w-]\/|\.py$/.test(x) && !x.startsWith("/"));
|
|
420
|
-
const origin = cwd !== "." ? cwd : tp ? dirname(tp) : ".";
|
|
509
|
+
const origin = cwd !== "." ? cwd : tp ? posix.dirname(tp) : ".";
|
|
421
510
|
const proj = nearestPyProject(origin, files);
|
|
422
511
|
if (proj === null) return seg;
|
|
423
|
-
const venv = join(proj, ".venv/bin/python");
|
|
512
|
+
const venv = posix.join(proj, ".venv/bin/python");
|
|
424
513
|
if (!exists(venv)) return seg;
|
|
425
|
-
const rel = cwd === "." ? venv : relative(cwd, venv);
|
|
514
|
+
const rel = cwd === "." ? venv : posix.relative(cwd, venv);
|
|
426
515
|
changed = true;
|
|
427
516
|
return `${m[1]}${rel} -m pytest${rest}`;
|
|
428
517
|
});
|
|
@@ -3,8 +3,8 @@
|
|
|
3
3
|
import { describe, it } from "node:test";
|
|
4
4
|
import assert from "node:assert/strict";
|
|
5
5
|
import { mkdirSync, writeFileSync } from "node:fs";
|
|
6
|
-
import { join } from "node:path";
|
|
7
|
-
import { manifestDepOwner, venvPythonRewrite, testRunnerProblems, shellSegments, pythonImports, nodeImports, preflightProbes, preflightProblems, runProbeMiss, unsetEnvVars, runPreflight, knownToContract, contractCommands, depInstallFailures, toolMissingInstalls, testRunSummary, projectBinDirs, withLocalBins } from "./preflight.mjs";
|
|
6
|
+
import { join, delimiter } from "node:path";
|
|
7
|
+
import { manifestDepOwner, venvPythonRewrite, testRunnerProblems, shellSegments, pythonImports, nodeImports, preflightProbes, preflightProblems, runProbeMiss, unsetEnvVars, runPreflight, knownToContract, contractCommands, depInstallFailures, toolMissingInstalls, testRunSummary, projectBinDirs, withLocalBins, collectOnlyCommand, collectImportMiss, declaredEnv } from "./preflight.mjs";
|
|
8
8
|
import { runCheckCommand } from "./effects.mjs";
|
|
9
9
|
import { repoTracks } from "./conformance.mjs";
|
|
10
10
|
import { tmpDir } from "../tests/_tmp.mjs";
|
|
@@ -54,7 +54,7 @@ describe("#4328 validate preflight: what a command needs", () => {
|
|
|
54
54
|
assert.equal(rc["command:node"], 0); assert.equal(rc["node-module:here"], 0, "found in an ancestor node_modules");
|
|
55
55
|
assert.notEqual(rc["node-module:absent-pkg-4328"], 0);
|
|
56
56
|
const py = preflightProbes(C(`python3 -c "import json, no_such_mod_4328"`)).probes.filter((p) => p.kind === "python-module");
|
|
57
|
-
if ((await runCheckCommand({ command: "
|
|
57
|
+
if ((await runCheckCommand({ command: "python3 -c pass", cwd: dir })).rc === 0) { // #5753: a Windows Store python3 stub is on PATH but runs nothing
|
|
58
58
|
assert.deepEqual(await Promise.all(py.map(async (p) => (await runCheckCommand({ command: p.probe, cwd: dir })).rc !== 0)), [false, true]);
|
|
59
59
|
}
|
|
60
60
|
});
|
|
@@ -209,7 +209,7 @@ describe("project-local executables (#5592 3d/9)", () => {
|
|
|
209
209
|
assert.equal((await runCheckCommand({ command: probes[0].probe, cwd: wt, env: { PATH: withLocalBins(base, local) } })).rc, 0);
|
|
210
210
|
});
|
|
211
211
|
it("local bins go after the lane PATH, never ahead, and are not duplicated", () => {
|
|
212
|
-
assert.equal(withLocalBins("/a
|
|
212
|
+
assert.equal(withLocalBins(["/a", "/b"].join(delimiter), ["/c", "/a"]), ["/a", "/b", "/c"].join(delimiter)); // #5753: the host PATH delimiter (; on Windows)
|
|
213
213
|
});
|
|
214
214
|
});
|
|
215
215
|
|
|
@@ -241,3 +241,43 @@ describe("#5683 sub-project manifest deps and venv python", () => {
|
|
|
241
241
|
assert.equal(venvPythonRewrite("cd web && pytest", files, exists), "cd web && pytest");
|
|
242
242
|
});
|
|
243
243
|
});
|
|
244
|
+
|
|
245
|
+
describe("#5749 host-only and busy-loop validates", () => {
|
|
246
|
+
const V = (...commands) => ({ deliverables: [], validate: commands.map((command, i) => ({ id: `V${i + 1}`, command })) });
|
|
247
|
+
it("#5749 hostOnlyProblems rejects host-only and busy-loop validates", async () => {
|
|
248
|
+
const { hostOnlyProblems } = await import("./preflight.mjs");
|
|
249
|
+
const bad = [`legion-run bash -lc 'for i in $(seq $(nproc)); do (timeout 300 sh -c "while :; do :; done") & done; npx vitest run'`, "ssh build-host make test", "bash /home/u/x/check.sh", "yes > /dev/null & npx vitest run"];
|
|
250
|
+
for (const c of bad) assert.equal(hostOnlyProblems(V(c)).length, 1, c);
|
|
251
|
+
assert.match(hostOnlyProblems(V(bad[0]))[0], /^V1: /);
|
|
252
|
+
assert.deepEqual(hostOnlyProblems(V("npx vitest run", "python -m pytest tests/x.py", "while read l; do echo $l; done < f", "git diff origin/staging...HEAD --stat")), []);
|
|
253
|
+
assert.equal(hostOnlyProblems({ ...V("npx vitest run"), repro_test: { path: "t.py", id: "t", command: "ssh h pytest t.py" } }).length, 1);
|
|
254
|
+
});
|
|
255
|
+
it("#5749 repro_test python -m pytest is probed at freeze", () => {
|
|
256
|
+
const c = { ...V("npx vitest run"), repro_test: { path: "tests/x.py", id: "t", command: "python -m pytest tests/x.py::t" } };
|
|
257
|
+
const got = preflightProbes(c).probes.map((p) => [p.kind, p.tool, p.ids.join(",")]);
|
|
258
|
+
assert.deepEqual(got.filter((x) => x[2] === "repro_test"), [["command", "python", "repro_test"], ["python-module", "pytest", "repro_test"]]);
|
|
259
|
+
});
|
|
260
|
+
});
|
|
261
|
+
|
|
262
|
+
describe("#5753 collect-only import preflight and tracked-dir env names", () => {
|
|
263
|
+
it("collectOnlyCommand adds --collect-only -q after the pytest invocation, dropping later segments", () => {
|
|
264
|
+
assert.equal(collectOnlyCommand("cd services/worker && poetry run pytest ../../shared/t.py -x"), "cd services/worker && poetry run pytest --collect-only -q ../../shared/t.py -x");
|
|
265
|
+
assert.equal(collectOnlyCommand("python3 -m pytest -q tests/t.py | tail -5"), "python3 -m pytest --collect-only -q -q tests/t.py ");
|
|
266
|
+
assert.equal(collectOnlyCommand(".venv/bin/python -m pytest t.py"), ".venv/bin/python -m pytest --collect-only -q t.py");
|
|
267
|
+
assert.equal(collectOnlyCommand("uv run --frozen pytest"), "uv run --frozen pytest --collect-only -q");
|
|
268
|
+
assert.equal(collectOnlyCommand("node --test x.test.mjs"), null);
|
|
269
|
+
});
|
|
270
|
+
it("a collect-only ModuleNotFoundError of a module the repo does not track is a miss; RED-on-base shapes are not", () => {
|
|
271
|
+
const out = "ImportError while importing test module '/w/shared/detection/test_x.py'.\nE ModuleNotFoundError: No module named 'html2text'\n";
|
|
272
|
+
assert.deepEqual(collectImportMiss({ rc: 2, output: out }), { tool: "html2text", kind: "python-module", line: "E ModuleNotFoundError: No module named 'html2text'" });
|
|
273
|
+
assert.equal(collectImportMiss({ rc: 2, output: out }, { repoHas: (n) => n === "html2text" }), null, "a repo-owned module is the change's");
|
|
274
|
+
assert.equal(collectImportMiss({ rc: 2, output: "ImportError: cannot import name 'new_fn' from 'shared.x'" }), null, "a name the change adds");
|
|
275
|
+
assert.equal(collectImportMiss({ rc: 0, output: out }), null);
|
|
276
|
+
assert.equal(collectImportMiss({ rc: 5, output: "no tests ran" }), null);
|
|
277
|
+
});
|
|
278
|
+
it("a tracked repo directory name (shared) in declared env is never a host tool", () => {
|
|
279
|
+
const c = { test_plan: [{ requirement: "R1", env: ["shared", "pytest"] }] };
|
|
280
|
+
assert.deepEqual(declaredEnv(c, ["shared/detection/test_x.py", "services/worker/pyproject.toml"]), ["pytest"]);
|
|
281
|
+
assert.deepEqual(declaredEnv(c), ["shared", "pytest"], "without tracked paths the name is unchanged");
|
|
282
|
+
});
|
|
283
|
+
});
|
package/bin/lean/prompts.mjs
CHANGED
|
@@ -10,6 +10,7 @@ import { capText, FIX_CAPS, FIX_PROMPT_MAX, NARROW_CAPS, NARROW_PROMPT_MAX } fro
|
|
|
10
10
|
import { SPLIT_MIN_FILES, SPLIT_MIN_LINES } from "./decompose.mjs";
|
|
11
11
|
import { relaxationBlock } from "./relaxation.mjs";
|
|
12
12
|
import { visualReviewCheck } from "./ui-quality.mjs";
|
|
13
|
+
import { amendmentPromptLines, AMEND_KINDS } from "./amendment-schema.mjs"; // #5979
|
|
13
14
|
import { stampRule } from "./stagestamp.mjs";
|
|
14
15
|
import { FINDING_PITFALLS, PLANNER_TIGHTENING } from "./selfreview.mjs";
|
|
15
16
|
import { isTrustedIssueComment } from "./prefilter.mjs"; // call-time use only: prefilter.mjs imports this module
|
|
@@ -262,12 +263,7 @@ export function builderImplementPrompt(mode = "local", { toolchain = null, spars
|
|
|
262
263
|
${HOST_RULES}${toolchainRule(toolchain)}${sparseRule(sparse)}${factsRule(facts)}${stampRule(stamp)}${remote ? `\n\n${VERIFY_RULES[mode]}` : ""}
|
|
263
264
|
|
|
264
265
|
The contract changes only through typed amendments in ${RESULT_FILE}, each with a why:
|
|
265
|
-
|
|
266
|
-
- {"kind":"add-requirement","requirement":{"id":"R9","quote":"<verbatim from the issue>","disposition":"deliver|defer|post-deploy"},"why":""}: a missed requirement.
|
|
267
|
-
- {"kind":"defer|post-deploy","requirement":"R#","why":"","check":"<id>"}: separate work or a post-deploy check, filed as a follow-up. Not "type"; unknown kinds are rejected. One requirement id per row. An impossible deliverable is a defer, not a new kind.
|
|
268
|
-
- {"kind":"amend-requirement","requirement":"R#","text":"<revised wording>","why":""}: reworded.
|
|
269
|
-
- {"kind":"supersedes","guard":"#N","why":""}: overrides a guard_broken failure; {"kind":"supersedes","mechanism":"<name>","why":""} retires every guard whose test this lane deletes.
|
|
270
|
-
- {"kind":"decision","decision":{"choice":"","anchors":["<base path>"],"supersedes":"<id>"},"why":""}: supersedes changes an H-row.
|
|
266
|
+
${amendmentPromptLines()}
|
|
271
267
|
New keys: translate, never copy English; status entries in place.
|
|
272
268
|
Never report a deliver requirement as "deferred" or "follow-up" without an amendment.
|
|
273
269
|
Never name or number migration files by hand; use the generator.
|
|
@@ -276,7 +272,7 @@ A [type:e2e] requirement needs a validate that runs a real e2e check (repo e2e s
|
|
|
276
272
|
A new keyword/regex classifier ships negative examples (inputs it must not match).
|
|
277
273
|
A forge.yaml outcome_evidence area change needs result outcome_evidence [{area,metric,corpus,before,after,better}] measured on recorded real inputs; its post-deploy checks get a numeric baseline.
|
|
278
274
|
A new workspace-package dependency in a package.json no deliverable names is blocked by the engine: add it through add-deliverable with a why naming the package, or do not add it.
|
|
279
|
-
If scripts/check-devdocs-freshness.sh exists, a behaviour change under its paths
|
|
275
|
+
If scripts/check-devdocs-freshness.sh exists, a behaviour change under its paths adds a new devdocs/decisions/<issue>-<slug>.md in the same change (a new file never conflicts with parallel lanes); run it against the base first.
|
|
280
276
|
|
|
281
277
|
Before writing ${RESULT_FILE}, after your last edit, run \`node ${FORGEDOCK_CLI} check\` in the worktree and fix until it passes; if it cannot pass, report the problem as blocked.
|
|
282
278
|
A \`FAIL review\` line from check is a finding the reviewer would raise; fix it. Also:
|
|
@@ -326,15 +322,7 @@ export function buildOpeningNote({ paths = [], tests = [], packFiles = [] } = {}
|
|
|
326
322
|
/** #4857: validate-command rules for the plan prompt (the implement session resumes it), kept out of the shared templates (their token caps are guarded). */
|
|
327
323
|
export function unrunnableValidateNote(testRunners = null) {
|
|
328
324
|
const map = testRunners && typeof testRunners === "object" ? Object.entries(testRunners).map(([k, v]) => `${k}/ -> ${v}`).join("; ") : "";
|
|
329
|
-
return `\n\nValidate and repro commands must pass bash -n (no prose notes), select tests that exist, and run from the right cwd (never combine \`poetry -C <dir>\` or \`uv run --project <dir>\` with repo-root-relative paths: use \`cd <dir> && poetry run pytest <dir-relative paths>\`)${map ? ` (forge.yaml verification.test_runners: ${map})` : ""}. An unrunnable validate (missing tool, wrong cwd, no tests selected) is never a block or "human" product-decision: run an equivalent through the repo's toolchain and
|
|
330
|
-
}
|
|
331
|
-
|
|
332
|
-
/** #5419: the R-docs rule for the planner; "" when forge.yaml docs.required_for is unset. */
|
|
333
|
-
export function docsPlanNote(cfg) {
|
|
334
|
-
if (!cfg?.required_for?.length) return "";
|
|
335
|
-
const where = cfg.paths?.length ? ` under ${cfg.paths.join(", ")}` : "";
|
|
336
|
-
const reg = cfg.registries?.length ? ` and their registration (${cfg.registries.join(", ")})` : "";
|
|
337
|
-
return `\n\nThis repo requires user docs for user-facing surfaces (${cfg.required_for.join(", ")}). When the issue adds or changes one (a public API endpoint, MCP tool, dashboard page or feature, CLI command or SDK method), ${CONTRACT_FILE} must carry a requirement R-docs and a deliverable for each docs page${where} to create or update${reg}. A \`/docs/...\` link the change adds must resolve to a page. If no docs apply, say why in the result file as docs: [{"surface":"<kind>","justification":"<why>"}].`;
|
|
325
|
+
return `\n\nValidate and repro commands must pass bash -n (no prose notes), select tests that exist, and run from the right cwd (never combine \`poetry -C <dir>\` or \`uv run --project <dir>\` with repo-root-relative paths: use \`cd <dir> && poetry run pytest <dir-relative paths>\`)${map ? ` (forge.yaml verification.test_runners: ${map})` : ""}. An unrunnable validate (missing tool, wrong cwd, no tests selected) is never a block or "human" product-decision: run an equivalent through the repo's toolchain and report its real result in ${RESULT_FILE}. A post-deploy requirement needs a registered check id; one that is a manual or production-credential action with no runnable check is disposition "defer" with bucket "owner:<action>" only when it needs credentials, spend, an account, a third party or a customer; read-only prod data is "host". forge.yaml validate.recipes rewrite matching commands at freeze, and the engine rewrites an unrunnable command from the repo's CI-derived command catalogue: prefer the repo's own CI test commands over free-form paths. A criterion only time or production can show (a 14-day metric, a corpus re-run, a published scorecard) is post-deploy or defer with a bucket: never narrow it into something the lane can observe.`;
|
|
338
326
|
}
|
|
339
327
|
|
|
340
328
|
/** #5428: the page_gate rule for the planner; "" when forge.yaml pages is off. */
|
|
@@ -430,17 +418,18 @@ export function contractCorrectionPrompt(problems) {
|
|
|
430
418
|
return `Your ${CONTRACT_FILE} is not valid:\n${problems.slice(0, 20).map((p) => `- ${p}`).join("\n")}\n\nFix the contract (planning only, no code, no commit) and stop. Do not push or touch GitHub.`;
|
|
431
419
|
}
|
|
432
420
|
|
|
433
|
-
/** #5089: the builder's amendments name an unknown kind or miss a field; one correction before the conformance gate. */
|
|
434
|
-
export function amendmentCorrectionPrompt(problems) {
|
|
435
|
-
return `The amendments in ${RESULT_FILE} are not valid:\n${problems.slice(0, 20).map((p) => `- ${p}`).join("\n")}\n\nRewrite them with a valid kind: add-deliverable, add-requirement, defer, post-deploy, amend-requirement, supersedes, decision, substitute-validate or out-of-band. A deliverable that is impossible on this platform is {"kind":"defer","requirement":"R#","why":""}, not a changed deliverable. Edit only ${RESULT_FILE} (commit nothing else) and stop. Do not push or touch GitHub.`;
|
|
436
|
-
}
|
|
437
|
-
|
|
438
421
|
/** The one bounded correction round, in the builder's own session. */
|
|
439
422
|
export function conformanceResumePrompt(failures, mode = "local", lane = "") {
|
|
440
423
|
const baseMoved = lane && failures.some((f) => f?.kind === "validate_failed")
|
|
441
424
|
? `\n\nIf a validate command fails only because origin/${lane} moved on after this branch started (the change itself is fine), bring the branch up to date with \`git merge --no-edit origin/${lane}\` (already fetched; never rebase or force), resolve any conflicts, then re-run every validate command and record the results.`
|
|
442
425
|
: "";
|
|
443
|
-
|
|
426
|
+
// #6058: a requirement with no status row was skipped, not failed: name each id with its quote and ask for the work and a row
|
|
427
|
+
const skipped = failures.filter((f) => f?.kind === "requirement_no_status" && f.reqId);
|
|
428
|
+
const rest = skipped.length ? failures.filter((f) => !skipped.includes(f)) : failures;
|
|
429
|
+
const targeted = skipped.length
|
|
430
|
+
? `You skipped ${skipped.length === 1 ? "a requirement" : `${skipped.length} requirements`}: ${RESULT_FILE} has no status row for ${skipped.map((f) => f.reqId).join(", ")}, so ${skipped.length === 1 ? "it was" : "they were"} not addressed at all:\n${skipped.map((f) => `- ${f.reqId}: "${String(f.quote ?? "").slice(0, 400)}"`).join("\n")}\n\nFor each one, implement it now (a file it needs that no deliverable names is an \`add-deliverable\` amendment), then add its row {"id","status","evidence"} to the requirements array of ${RESULT_FILE}, keeping the rows already there.${rest.length ? "\n\nAlso:\n" : ""}`
|
|
431
|
+
: "The change does not conform to the frozen contract and the issue:\n";
|
|
432
|
+
return `${targeted}${rest.slice(0, 30).map((f) => `- ${f.code}: ${String(f.detail).slice(0, 900)}`).join("\n")}${baseMoved}\n\nFix each item in the code, or record a typed amendment with a why in ${RESULT_FILE}. ${rerun(mode)}, commit, and update ${IMPLEMENTATION_FILE} and ${RESULT_FILE}. Do not push or touch GitHub.`;
|
|
444
433
|
}
|
|
445
434
|
|
|
446
435
|
/** forge#4159: the one resume for package.json edges between workspace packages the contract does not name. */
|
|
@@ -448,11 +437,6 @@ export function structurePrompt(edges, mode = "local") {
|
|
|
448
437
|
return `This change adds dependencies between workspace packages that the frozen contract does not name:\n${edges.slice(0, 30).map((e) => `- ${e.from} -> ${e.to} (${e.kind}, ${e.manifest})`).join("\n")}\n\nFor each one, add it to the contract with a reason, or remove it: either record {"kind":"add-deliverable","path":"<that package.json>","why":"<names the package and why this dependency is right>"} in ${RESULT_FILE}, or drop the dependency from the package.json and the code that needs it. ${rerun(mode)}, commit, and update ${IMPLEMENTATION_FILE} and ${RESULT_FILE}. Do not push or touch GitHub.`;
|
|
449
438
|
}
|
|
450
439
|
|
|
451
|
-
/** The repo's devdocs freshness rule failed on the committed change: update the named dossier(s) and commit. */
|
|
452
|
-
export function docsPrompt(output, mode = "local") {
|
|
453
|
-
return `The repository's docs freshness check (scripts/check-devdocs-freshness.sh) fails on this change:\n${String(output ?? "").slice(0, 4000)}\n\nUpdate the module dossier it names (devdocs/modules/*.md; devdocs/index.yaml maps files to dossiers) to describe the behaviour you changed, in the dossier's existing style and in a few lines. ${rerun(mode)}, commit, and update ${IMPLEMENTATION_FILE} and ${RESULT_FILE}. Do not push or touch GitHub.`;
|
|
454
|
-
}
|
|
455
|
-
|
|
456
440
|
/**
|
|
457
441
|
* #4363: a fix round in a fresh session (no transcript). It carries the site's task prompt (which holds the capped
|
|
458
442
|
* failure output), the lane diff, the frozen contract and the issue title and summary, each capped; under FIX_PROMPT_MAX.
|
|
@@ -524,6 +508,7 @@ You receive the GitHub issue with its comments, the frozen contract (requirement
|
|
|
524
508
|
- issue_coverage: one row per requirement or acceptance criterion in the issue, quoted verbatim, saying whether the contract covers it, narrows it, or misses it. The skeleton lists the contract's quotes; add a row for any issue requirement the contract does not quote.
|
|
525
509
|
- guidance: a guidance requirement (pre-filled covered / not-applicable) is a proposed change, non-binding: judge whether the outcome rows are met, never whether the proposal was followed. Set misclassified: true on its issue_coverage row only when the quote is really a symptom or success criterion. A deliver row with derived_outcome is judged against derived_outcome, like amendment.text.
|
|
526
510
|
- amendment: a requirement with an \`amendment\` is judged against amendment.text and its why, not the quote; its issue_coverage row is covered when the amendment follows from its why. A requirement with \`amended_from\` was contracted defer or post-deploy and flipped to deliver: compare amended_from.quote and amended_from.why with amendment.text side by side, and mark the row partial when the rewording drops the original work or only trivially restates it. If it does not hold, mark the row partial with note "amendment: <what to change>".
|
|
511
|
+
- frozen defer/post-deploy rows: a requirement the contract froze as defer or post-deploy is a tracked follow-up, never an omission; do not mark its issue_coverage row narrowed or missing for that. An amendment that cites a frozen decision id (D#/K#) is judged against that decision's choice and justification.
|
|
527
512
|
- requirements: one row per contract requirement id: implemented|partial|missing|deferred|post-deploy|not-applicable, with evidence as a backtick-quoted repo-relative path:line copied verbatim from the changed files, including (group), [slug] and [...slug] folders (e.g. \`apps/web/app/(console)/layout.tsx:12\`, not route.ts:12) and the validate id or test that proves it (validated_by). For a defer or post-deploy requirement add deferral_ok: true only if it is genuinely separate work or only checkable after a deploy, false if it belongs in this change, including an outcome criterion (a metric, rate or log expectation) this change could ship as a test, metric or alert, or a read-only production check possible now (bucket verify-now). For a verify out_of_band row (measured by the named job, not in this lane) set instrumented: true only when its budget test or bench is committed and that job is configured, with that path:line as evidence; false otherwise. Do not judge the measured result.
|
|
528
513
|
- post-deploy requirements: deferral_ok is false when the requirement has no \`check\` id, or its check is neither in .forge/post-deploy-checks.json on the default branch nor added by this change (the commands run from that file only).
|
|
529
514
|
- scope: one row per changed file, pre-filled with the engine's authorization: the deliverable id that authorizes it (deliverables may be directories or globs), "test", "incidental" (changelog, lockfile), or "none" with what it changes. Change it only if the diff shows the file does something its deliverable does not cover.
|
|
@@ -606,7 +591,7 @@ export function reproFlagNote(flag) {
|
|
|
606
591
|
|
|
607
592
|
export function reviewerPrompt({ issue, comments = [], contract, result, files = [], diff, stat = "", base = "", structure = "", ignore = [`${LEAN_DIR}/`], skeleton = null, investigationVerdict = null, domains = [], relaxations = [], reproFlag = null }) {
|
|
608
593
|
const notes = comments.map((c) => String(c?.body ?? "")).filter((b) => !/^<!-- FORGE:/.test(b.trim()));
|
|
609
|
-
const decisions = comments.filter((c) => isDecision(c?.body) && isTrustedIssueComment(c)).map((c) => String(c.body)); // #4901: operator decisions bind the review; other FORGE: records stay out
|
|
594
|
+
const decisions = comments.filter((c) => isDecision(c?.body) && isTrustedIssueComment(c)).map((c) => `Binding operator decision (trusted; judge the rows against it, as the builder was told):\n${String(c.body)}`); // #4901/#6051: operator decisions bind the review and the builder alike; other FORGE: records stay out
|
|
610
595
|
notes.push(...decisions);
|
|
611
596
|
const sk = JSON.stringify(skeleton ?? reviewSkeleton(contract ?? {}, files, ignore), null, 1);
|
|
612
597
|
return `Issue #${issue.number}: ${issue.title}\n\n<issue_body>\n${cap(issue.body ?? "", 20000)}\n</issue_body>\n\n<issue_comments>\n${cap(notes.join("\n---\n"), 8000)}\n</issue_comments>\n\n<contract>\n${cap(JSON.stringify(contract ?? {}, null, 1), 12000)}\n</contract>\n\n<builder_result>\n${cap(JSON.stringify(result ?? {}, null, 1), 6000)}\n</builder_result>\n\n${investigationVerdict ? `<investigation_verdict>${investigationVerdict}</investigation_verdict>\n${VERDICT_RULE}\n\n` : ""}<changed_files>\n${files.join("\n")}\n</changed_files>\n\n<rubric>\n${REVIEW_RUBRIC}\n</rubric>\n\n<row_skeleton>\n${cap(sk, 30000)}\n</row_skeleton>\n\n<diff>\n${boundDiff(diff, { stat, base })}\n</diff>${structure ? `\n<structure>${String(structure).replace(/[\r\n]+/g, " ")}</structure>` : ""}${domainChecksBlock(domains)}${relaxationBlock(relaxations)}${reproFlagNote(reproFlag)}`;
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
|
+
// #5978: standing orders. A batch started with `--select <query>` keeps owning every open issue the selector matches:
|
|
4
|
+
// matching issues join, closed or moved ones leave, and an issue that ended deferred / held / engine-error / conformance-failed is
|
|
5
|
+
// re-admitted by policy instead of by an operator. Pure helpers; the runner (orchestrate.mjs) feeds the results through its
|
|
6
|
+
// existing add/requeue seams (the query is issue-watch's `search` selector, handed to gh unchanged, K2; no import, so batch.mjs can use this module), so the DAG, priority and lane rules are the ones a `--add` already gets (K1).
|
|
7
|
+
|
|
8
|
+
/** How often the runner re-reads the selector ("every few minutes"). */
|
|
9
|
+
export const RECONCILE_MS = 3 * 60 * 1000;
|
|
10
|
+
/** Deferred issues retry with exponential backoff from this base, capped at DEFER_CAP_MS. */
|
|
11
|
+
export const DEFER_BASE_MS = 5 * 60 * 1000;
|
|
12
|
+
export const DEFER_CAP_MS = 2 * 60 * 60 * 1000;
|
|
13
|
+
/** A held / engine-error issue is a fresh attempt after this cooldown even if no version moved. */
|
|
14
|
+
export const HELD_COOLDOWN_MS = 6 * 60 * 60 * 1000;
|
|
15
|
+
/** The breaker auto-resets after this cooldown when its failures were environmental. */
|
|
16
|
+
export const BREAKER_COOLDOWN_MS = 15 * 60 * 1000;
|
|
17
|
+
|
|
18
|
+
/** gh args listing the open issues `select` matches (a GitHub search query: `no:milestone`, `milestone:X`, `label:Y`). */
|
|
19
|
+
export const selectArgs = (repo, select) => ["issue", "list", "-R", repo, "--state", "open", "--search", String(select), "--limit", "500", "--json", "number,labels,milestone,title"];
|
|
20
|
+
|
|
21
|
+
/** Open issue numbers (and labels) from the `gh issue list --json` output; null when it cannot be read (nobody leaves on a failed read). */
|
|
22
|
+
export function parseSelected(text) {
|
|
23
|
+
let v;
|
|
24
|
+
try { v = JSON.parse(text); } catch { return null; }
|
|
25
|
+
if (!Array.isArray(v)) return null;
|
|
26
|
+
return v.filter((x) => Number.isSafeInteger(x?.number) && x.number > 0).map((x) => ({ number: x.number, labels: (x.labels ?? []).map((l) => (typeof l === "string" ? l : l?.name)).filter(Boolean) }));
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Diff the selector result against batch membership.
|
|
31
|
+
* @returns {{join:number[], leave:number[]}} join: open matches not in the batch; leave: pending members (not running, no result row) no longer open/matching
|
|
32
|
+
*/
|
|
33
|
+
export function diffSelection({ open, members, pending, running, results, matched = null }) {
|
|
34
|
+
const have = new Set(members), now = new Set(open.map((o) => o.number));
|
|
35
|
+
const join = [...now].filter((n) => !have.has(n)).sort((a, b) => a - b);
|
|
36
|
+
// #6022: only an issue the selector matched can leave it; env.* issues, children, --add and argv members never did
|
|
37
|
+
const leave = pending.filter((n) => (!matched || matched.has(n)) && !now.has(n) && !running.has(n) && !results.has(n));
|
|
38
|
+
return { join, leave };
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Human codes (credentials, spend, customer, promotion, product decision): the only reasons an issue may stay unscheduled. */
|
|
42
|
+
const HUMAN = /\b(credentials?|secrets?\b.*\b(needed|missing|required)|api[ -]?keys?|spend|billing|payment|budget approval|customers?|promotion|promote|product decision|needs?[- ]decision|human[- ]code)\b/i;
|
|
43
|
+
export const HUMAN_LABEL = /^(human[:/-].+|needs?-(credentials|spend|customer|promotion|product-decision))$/i;
|
|
44
|
+
export const humanCode = (row, labels = []) => labels.some((l) => HUMAN_LABEL.test(l)) || (row?.outcome === "needs-human" && !row?.conformance && HUMAN.test(String(row?.detail ?? "")));
|
|
45
|
+
|
|
46
|
+
/** Failure details that are environmental (VM restart, mirror, network): a breaker tripped by them may close itself (#5947 classes). */
|
|
47
|
+
export const environmentalDetail = (detail) => /\b(vm (restart|reboot)|restart(ed|ing)|mirror|network|dns|econn(reset|refused)|etimedout|connection (reset|refused|timed out)|net\.transient|sandbox\.lost|unreachable)\b/i.test(String(detail ?? ""));
|
|
48
|
+
|
|
49
|
+
/** @returns {number} ms to wait before deferred attempt number `n` (0-based) is retried */
|
|
50
|
+
export const backoffMs = (n) => Math.min(DEFER_CAP_MS, DEFER_BASE_MS * 2 ** Math.max(0, Math.min(n, 16)));
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Re-admission policy for rows that ended without success. `state` is `Map<issue, {n, since, version, base, conformanceTried}>`
|
|
54
|
+
* (kept in batch state); it is updated in place. Returns the issues to requeue with the reason, and the parked "needs decision" list.
|
|
55
|
+
* @param {{results:Map<number,object>, state:Map<number,object>, now:number, version:string|null, base:string|null, labels?:(n:number)=>string[]}} p
|
|
56
|
+
*/
|
|
57
|
+
export function readmitDue({ results, state, now, version = null, base = null, labels = () => [] }) {
|
|
58
|
+
const requeue = [], parked = [];
|
|
59
|
+
for (const [n, row] of results) {
|
|
60
|
+
const o = row?.outcome;
|
|
61
|
+
const isConf = Boolean(row?.conformance) && o === "needs-human";
|
|
62
|
+
if (!["deferred", "held", "engine-error"].includes(o) && !isConf) { state.delete(n); continue; }
|
|
63
|
+
if (humanCode(row, labels(n))) continue;
|
|
64
|
+
let s = state.get(n);
|
|
65
|
+
if (!s || s.outcome !== o) { s = { n: s?.n ?? 0, since: now, version, base, outcome: o, conformanceTried: s?.conformanceTried ?? 0 }; state.set(n, s); }
|
|
66
|
+
if (o === "deferred") {
|
|
67
|
+
if (now - s.since >= backoffMs(s.n)) { requeue.push({ issue: n, reason: `deferred: retry ${s.n + 1} after backoff (cap ${DEFER_CAP_MS / 3600000} h)` }); state.set(n, { ...s, n: s.n + 1, since: now, outcome: null }); }
|
|
68
|
+
} else if (isConf) {
|
|
69
|
+
if (s.conformanceTried >= 1) { parked.push({ issue: n, why: "conformance failed after one retry on a moved base" }); continue; }
|
|
70
|
+
if (base && s.base && base !== s.base) { requeue.push({ issue: n, reason: "conformance: one more attempt, the base moved" }); state.set(n, { ...s, conformanceTried: s.conformanceTried + 1, since: now, outcome: null, base }); }
|
|
71
|
+
else if (!s.base && base) state.set(n, { ...s, base });
|
|
72
|
+
} else {
|
|
73
|
+
const moved = version && s.version && version !== s.version;
|
|
74
|
+
if (moved || now - s.since >= HELD_COOLDOWN_MS) { requeue.push({ issue: n, reason: moved ? `${o}: agent/lane-image version changed` : `${o}: cooldown elapsed, fresh attempt` }); state.set(n, { ...s, since: now, version, outcome: null }); }
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
return { requeue, parked };
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* The breaker may close itself: an environmental failure signature, the cooldown elapsed and the pool healthy again.
|
|
82
|
+
* (Lives in clear-breaker.mjs as `decideAutoReset`; re-exported here for the policy tests.)
|
|
83
|
+
*/
|
|
84
|
+
export { decideAutoReset } from "./clear-breaker.mjs";
|
|
85
|
+
|
|
86
|
+
/** One "needs decision" digest for the parked issues: a single decision body, empty string when nothing is parked. */
|
|
87
|
+
export const needsDecisionDigest = (parked) => (parked.length ? `needs decision (${parked.length}): ${parked.map((p) => `#${p.issue} (${p.why})`).join("; ")}` : "");
|
|
88
|
+
|
|
89
|
+
/** Whether a merge into `lane` leaves the issue open on GitHub (`Closes` only fires on the default branch): staging / milestone lanes. */
|
|
90
|
+
export const closesManually = (lane, defaultBranch = "main") => Boolean(lane) && lane !== defaultBranch && /^(staging|milestone\/|release\/|lane\/)/.test(String(lane));
|