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/forgedock.mjs
CHANGED
|
@@ -1107,6 +1107,13 @@ async function installHygieneSchedule(cwd, write = () => {}) {
|
|
|
1107
1107
|
const { installGcSchedule } = await import("./gc-schedule.mjs");
|
|
1108
1108
|
const r = await installGcSchedule({ schedule: h.schedule, enabled: h.auto_gc, cwd });
|
|
1109
1109
|
if (r.status !== "off") write(` Hygiene schedule: ${r.status} (${r.kind}) ${r.detail}\n`);
|
|
1110
|
+
try { // #5987: daily introspect, filed only on an explicit orchestrate.slo.file_issues: true (the installer removes the entry otherwise)
|
|
1111
|
+
const [{ installIntrospectSchedule }, { parseSloConfig }, { parseForgeYaml }] = await Promise.all([import("./introspect-schedule.mjs"), import("./lean/slo.mjs"), import("./forge-utils.mjs")]);
|
|
1112
|
+
let fileIssues = false;
|
|
1113
|
+
try { fileIssues = parseSloConfig(parseForgeYaml(readFileSync(join(cwd, "forge.yaml"), "utf8"))).fileIssues; } catch { fileIssues = false; }
|
|
1114
|
+
const i = await installIntrospectSchedule({ enabled: fileIssues, cwd });
|
|
1115
|
+
if (i.status !== "off") write(` Introspect schedule: ${i.status} (${i.kind}) ${i.detail}\n`);
|
|
1116
|
+
} catch { /* advisory */ }
|
|
1110
1117
|
return r;
|
|
1111
1118
|
} catch { return null; }
|
|
1112
1119
|
}
|
|
@@ -4014,7 +4021,7 @@ async function watch() {
|
|
|
4014
4021
|
const SPLASH_COMMANDS = new Set(["run", "bootstrap", "run-issue", "orchestrate", "triage", "probe", "gc", "resume-stalled", "demo", "first-run", "doctor", "watch", "help", "--help", "-h"]);
|
|
4015
4022
|
const KNOWN_COMMANDS = new Set([
|
|
4016
4023
|
"install", "init", "enable", "disable", "status", "uninstall", "update",
|
|
4017
|
-
"run", "bootstrap", "backend-check", "run-issue", "orchestrate", "milestone", "milestone-sync", "fix-close-reasons", "guards", "triage", "probe", "close", "acceptance", "interfaces", "docs", "review-staging", "release", "intake", "gc", "env", "sandbox", "resume-stalled", "demo", "first-run", "doctor", "auth", "watch", "issue-watch", "prod-watch", "selftest", "labels", "config", "stats", "limits", "decisions", "sched", "schedd", "pool", "check", "guide", "help", "--help", "-h",
|
|
4024
|
+
"run", "bootstrap", "backend-check", "run-issue", "orchestrate", "milestone", "milestone-sync", "fix-close-reasons", "guards", "triage", "probe", "close", "acceptance", "interfaces", "docs", "review-staging", "release", "intake", "gc", "env", "sandbox", "resume-stalled", "demo", "first-run", "doctor", "auth", "watch", "issue-watch", "prod-watch", "selftest", "labels", "config", "stats", "scorecard", "limits", "decisions", "audits", "sched", "schedd", "pool", "check", "guide", "help", "--help", "-h",
|
|
4018
4025
|
"ci-step", "ci-hook", "tests",
|
|
4019
4026
|
"version", "--version", "-v",
|
|
4020
4027
|
]);
|
|
@@ -4275,6 +4282,17 @@ switch (command) {
|
|
|
4275
4282
|
}
|
|
4276
4283
|
break;
|
|
4277
4284
|
}
|
|
4285
|
+
case "audits": {
|
|
4286
|
+
// #6077: query FORGE:LANE_AUDIT comments
|
|
4287
|
+
const { auditsFromCli } = await import("./engine-cli.mjs");
|
|
4288
|
+
try {
|
|
4289
|
+
await auditsFromCli(restArgs);
|
|
4290
|
+
} catch (err) {
|
|
4291
|
+
process.stderr.write(`${RED}${err.message}${RESET}\n`);
|
|
4292
|
+
exitCode = 1;
|
|
4293
|
+
}
|
|
4294
|
+
break;
|
|
4295
|
+
}
|
|
4278
4296
|
case "decisions": {
|
|
4279
4297
|
// #4695: anchored decisions of the local index
|
|
4280
4298
|
const { decisionsFromCli } = await import("./engine-cli.mjs");
|
|
@@ -4617,6 +4635,11 @@ switch (command) {
|
|
|
4617
4635
|
exitCode = await runStats(restArgs);
|
|
4618
4636
|
break;
|
|
4619
4637
|
}
|
|
4638
|
+
case "scorecard": {
|
|
4639
|
+
const { runScorecard } = await import("./stats/scorecard.mjs");
|
|
4640
|
+
exitCode = await runScorecard(restArgs);
|
|
4641
|
+
break;
|
|
4642
|
+
}
|
|
4620
4643
|
case "watch":
|
|
4621
4644
|
await watch();
|
|
4622
4645
|
break;
|
package/bin/help-text.mjs
CHANGED
|
@@ -12,7 +12,7 @@ import { wrap } from "./guide.mjs";
|
|
|
12
12
|
export const EVERYDAY_COMMANDS = [
|
|
13
13
|
["setup", "Guided setup: install ForgeDock and configure this repo"],
|
|
14
14
|
["run-issue <issue>", "Turn one GitHub issue into a reviewed, merged pull request"],
|
|
15
|
-
["orchestrate <issue...>", "Work on several issues at once, in dependency order"],
|
|
15
|
+
["orchestrate <issue...> | --select <query>", "Work on several issues at once, in dependency order; --select keeps a standing order over every open issue a query matches"],
|
|
16
16
|
["watch", "Live view of what each agent is doing"],
|
|
17
17
|
["status", "Show ForgeDock state for this directory"],
|
|
18
18
|
["release", "Promote staging to your main branch as one reviewed release"],
|
|
@@ -66,8 +66,8 @@ export const FULL_COMMAND_GROUPS = [
|
|
|
66
66
|
["npx forgedock bootstrap <idea|docs> [--dry-run] [--spike <path>] | --plan <plan.json> [--dry-run]", "Headless /bootstrap: idea to orchestrate-ready backlog (--dry-run previews milestones, titles, DAG and estimated agent cost without GitHub writes); --plan validates and creates (or previews) a plan, and re-running resumes from GitHub"],
|
|
67
67
|
["npx forgedock run-issue <issue> [--lane <lane>] [--lane-override] [--path core|full] [--retry] [--wait-lease] [--local]", "Work one issue from claim to merge (the lane comes from the issue: its milestone, else staging; --lane only asserts it). Follows forge.yaml execution: like orchestrate (remote or hybrid places the lane on the pool, with fallback_local); --local forces this host and the placement is printed. --retry reopens a failed run, or one needing a human once the label is cleared; --wait-lease waits for another holder of the issue; exit status 75 means deferred, nothing was lost"],
|
|
68
68
|
["npx forgedock plan validate --live [--repo owner/repo] [--json]", "Re-run the bootstrap dependency-order rules on live GitHub state: each cross-milestone Depends-on edge is ok, held or invalid (fails on invalid)"],
|
|
69
|
-
["npx forgedock orchestrate <issue...> [--parallel K] [--lane L]", "Work on several issues with bounded concurrency and Depends-on ordering; each issue on its own lane, cross-lane dependencies reported"],
|
|
70
|
-
["npx forgedock orchestrate --resume <id> [N...] | --set-parallel <id> K | --set-max-remote <id> N | --set-placement <id> remote|hybrid|local | --add <id> N... | --requeue <id> N... [--reason \"...\"] | --cancel <id> | --hold <id> N... [--for 4h] [--reason \"...\"] | --adopt <issue> | --gc-orphans | --release <id> N... | --show-env <id> | --set-env <id> KEY=VAL | --unset-env <id> KEY", "Reattach to a running or finished batch (a finished one replays its report, an interrupted one resumes), change its concurrency or placement live, add, requeue, hold (with an owner and an optional expiry, --for) or release single issues, adopt an open hand-built PR, cancel orphaned batches (--gc-orphans), stop one batch without stopping the background scheduler, or print, set or unset the batch environment (secrets redacted; applies to newly started lanes)"],
|
|
69
|
+
["npx forgedock orchestrate <issue...> | --select <query> [--parallel K] [--lane L]", "Work on several issues with bounded concurrency and Depends-on ordering; each issue on its own lane, cross-lane dependencies reported"],
|
|
70
|
+
["npx forgedock orchestrate --resume <id> [N...] | --set-parallel <id> K | --set-max-remote <id> N | --set-placement <id> remote|hybrid|local | --status <id> | --add <id> N... | --requeue <id> N... [--reason \"...\"] | --cancel <id> | --hold <id> N... [--for 4h] [--reason \"...\"] | --adopt <issue> | --gc-orphans | --release <id> N... | --show-env <id> | --set-env <id> KEY=VAL | --unset-env <id> KEY", "Reattach to a running or finished batch (a finished one replays its report, an interrupted one resumes), change its concurrency or placement live, add, requeue, hold (with an owner and an optional expiry, --for) or release single issues, adopt an open hand-built PR, cancel orphaned batches (--gc-orphans), stop one batch without stopping the background scheduler, or print, set or unset the batch environment (secrets redacted; applies to newly started lanes)"],
|
|
71
71
|
["npx forgedock triage <issue...> [--lane L] [--dry-run]", "Already-fixed pre-filter: close issues a merged PR or green CI already resolved; print the rest"],
|
|
72
72
|
["npx forgedock probe [issue...] [--dry-run]", "Run declared acceptance probes for closed issues whose fix is on the default branch; a fail reopens the issue"],
|
|
73
73
|
["npx forgedock interfaces check|register|contract", "Interface contracts: require an Interfaces section on a spike/epic with 2+ slices, register its rows in the decision register, generate seam contract tests"],
|
|
@@ -86,6 +86,7 @@ export const FULL_COMMAND_GROUPS = [
|
|
|
86
86
|
["npx forgedock guards list [--path p] [--json] | backfill --since <date> [--dry-run]", "Fix guards: list the records (test files + protected hunks of merged fixes) covering a path, or build them for already-merged runs"],
|
|
87
87
|
["npx forgedock limits show | clear <id>|--all", "Show or clear per-account usage-limit holds shared by orchestrate batches"],
|
|
88
88
|
["npx forgedock decisions list [--stale] [--refresh]", "List anchored decisions (FORGE:DECISION); --stale shows those with an anchor missing on the base"],
|
|
89
|
+
["npx forgedock audits [--repo R] [--version X | --since-version X] [--signature S] [--class C] [--active] [--json]", "Query lane audits (FORGE:LANE_AUDIT) by engine version, signature and class; --active lists current-version findings per signature with counts and lanes"],
|
|
89
90
|
["npx forgedock watch [--repo owner/repo]", "Live per-agent orchestration view (Ctrl+C to exit)"],
|
|
90
91
|
["npx forgedock report [--days 30] [--md] [--json]", "30-day pipeline impact receipts for your repo"],
|
|
91
92
|
["npx forgedock stats [--since <ver|date>] [--repo owner/repo] [--json] [--refresh]", "Version-over-version cost/time/flow/review/gate report from GitHub telemetry (no model)"],
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
|
+
/**
|
|
4
|
+
* Daily `fd-introspect --file-issues` (#5987): the lean-lane test-quality trend (`forgedock stats --conformance-outcomes`) run on a
|
|
5
|
+
* systemd user timer, with a tagged cron entry as the fallback, modelled on gc-schedule.mjs. Installed by `doctor --fix` and
|
|
6
|
+
* `forgedock init`. Findings are filed (deduped against open issues and prior reports) only when `orchestrate.slo.file_issues: true`
|
|
7
|
+
* is set (opt-in); `enabled` false removes the entry. All I/O is injected (`exec`, `fs`). Never throws.
|
|
8
|
+
*/
|
|
9
|
+
import * as nodeFs from "node:fs";
|
|
10
|
+
import { createHash } from "node:crypto";
|
|
11
|
+
import { execFile } from "node:child_process";
|
|
12
|
+
import { promisify } from "node:util";
|
|
13
|
+
import { homedir } from "node:os";
|
|
14
|
+
import { dirname, join, resolve } from "node:path";
|
|
15
|
+
import { fileURLToPath } from "node:url";
|
|
16
|
+
|
|
17
|
+
const pexec = promisify(execFile);
|
|
18
|
+
const CRON_TAG = "# forgedock-introspect";
|
|
19
|
+
const ARGS = "--run"; // this file is the entry: runs the introspect report and files it (see runIntrospect)
|
|
20
|
+
|
|
21
|
+
export const introspectUnitName = (cwd) => `forgedock-introspect-${createHash("sha1").update(resolve(cwd)).digest("hex").slice(0, 8)}`;
|
|
22
|
+
/** Where today's report for `cwd` is saved; the SLO rolling issue links it (#5987). */
|
|
23
|
+
export const introspectReportPath = (cwd, home = homedir(), now = Date.now()) => join(home, ".forge", "introspect", `${new Date(now).toISOString().slice(0, 10)}-${introspectUnitName(cwd).slice(-8)}.txt`);
|
|
24
|
+
const q = (s) => `"${String(s).replace(/(["\\$`])/g, "\\$1")}"`;
|
|
25
|
+
const SELF = fileURLToPath(import.meta.url);
|
|
26
|
+
const forgedockBin = () => join(dirname(SELF), "forgedock.mjs");
|
|
27
|
+
|
|
28
|
+
export function renderIntrospectSystemd({ cwd, node = process.execPath, bin = forgedockBin() }) {
|
|
29
|
+
return {
|
|
30
|
+
service: `[Unit]\nDescription=ForgeDock introspect, files findings (${resolve(cwd)})\n\n[Service]\nType=oneshot\nWorkingDirectory=${resolve(cwd)}\nExecStart=${q(node)} ${q(SELF)} ${ARGS}\n`,
|
|
31
|
+
timer: `[Unit]\nDescription=ForgeDock introspect daily\n\n[Timer]\nOnCalendar=daily\nRandomizedDelaySec=30min\nPersistent=true\n\n[Install]\nWantedBy=timers.target\n`,
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function renderIntrospectCron({ cwd, node = process.execPath, bin = forgedockBin() }) {
|
|
36
|
+
return `17 4 * * * cd ${q(resolve(cwd))} && ${q(node)} ${q(SELF)} ${ARGS} >/dev/null 2>&1 ${CRON_TAG} ${resolve(cwd)}`;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Install (or remove) the daily run. @returns {status: installed|removed|off|failed, kind, detail} */
|
|
40
|
+
export async function installIntrospectSchedule({ enabled = true, cwd = process.cwd(), home = homedir(), platform = process.platform, fs = nodeFs, exec = async (cmd, args, input) => { const p = pexec(cmd, args, { timeout: 30000 }); if (input != null) p.child.stdin.end(input); return (await p).stdout; }, node, bin } = {}) {
|
|
41
|
+
const name = introspectUnitName(cwd), dir = join(home, ".config", "systemd", "user");
|
|
42
|
+
const opts = { cwd, ...(node ? { node } : {}), ...(bin ? { bin } : {}) };
|
|
43
|
+
try {
|
|
44
|
+
if (platform === "linux") {
|
|
45
|
+
let hasSystemd = false;
|
|
46
|
+
try { await exec("systemctl", ["--user", "show-environment"]); hasSystemd = true; } catch { hasSystemd = false; }
|
|
47
|
+
if (hasSystemd) {
|
|
48
|
+
if (!enabled) {
|
|
49
|
+
if (!fs.existsSync(join(dir, `${name}.timer`))) return { status: "off", kind: "systemd", detail: "not enabled" };
|
|
50
|
+
try { await exec("systemctl", ["--user", "disable", "--now", `${name}.timer`]); } catch { /* already gone */ }
|
|
51
|
+
for (const f of [`${name}.timer`, `${name}.service`]) fs.rmSync(join(dir, f), { force: true });
|
|
52
|
+
return { status: "removed", kind: "systemd", detail: `removed ${name}.timer` };
|
|
53
|
+
}
|
|
54
|
+
const { service, timer } = renderIntrospectSystemd(opts);
|
|
55
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
56
|
+
fs.writeFileSync(join(dir, `${name}.service`), service);
|
|
57
|
+
fs.writeFileSync(join(dir, `${name}.timer`), timer);
|
|
58
|
+
await exec("systemctl", ["--user", "daemon-reload"]);
|
|
59
|
+
await exec("systemctl", ["--user", "enable", "--now", `${name}.timer`]);
|
|
60
|
+
return { status: "installed", kind: "systemd", detail: `${name}.timer daily` };
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
let cur = "";
|
|
64
|
+
try { cur = String(await exec("crontab", ["-l"])); } catch { cur = ""; }
|
|
65
|
+
const mine = (l) => l.trimEnd().endsWith(`${CRON_TAG} ${resolve(cwd)}`);
|
|
66
|
+
const all = cur.split("\n").filter((l) => l.trim()), rest = all.filter((l) => !mine(l));
|
|
67
|
+
if (!enabled && rest.length === all.length) return { status: "off", kind: "cron", detail: "not enabled" };
|
|
68
|
+
await exec("crontab", ["-"], [...rest, ...(enabled ? [renderIntrospectCron(opts)] : [])].join("\n") + "\n");
|
|
69
|
+
return enabled ? { status: "installed", kind: "cron", detail: "crontab entry daily" } : { status: "removed", kind: "cron", detail: "removed crontab entry" };
|
|
70
|
+
} catch (e) {
|
|
71
|
+
return { status: "failed", kind: "unknown", detail: String(e?.message ?? e).slice(0, 200) };
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* One introspect run: `forgedock stats --conformance-outcomes`, its report saved under `<home>/.forge/introspect/`, then filed
|
|
77
|
+
* (deduped, see slo.fileIntrospect) when `orchestrate.slo.file_issues: true` (opt-in, default off); the local report path is never posted. State `filed.json` holds the last filed report hash.
|
|
78
|
+
*/
|
|
79
|
+
export async function runIntrospect({ cwd = process.cwd(), home = homedir(), fs = nodeFs, run = async () => String((await pexec(process.execPath, [forgedockBin(), "stats", "--conformance-outcomes"], { cwd, timeout: 300000, maxBuffer: 8 << 20 })).stdout), gh = async (a) => String((await pexec("gh", a, { timeout: 30000 })).stdout), now = Date.now() } = {}) {
|
|
80
|
+
try {
|
|
81
|
+
const [{ parseSloConfig, fileIntrospect }, { parseForgeYaml }] = await Promise.all([import("./lean/slo.mjs"), import("./forge-utils.mjs")]);
|
|
82
|
+
let cfg; try { cfg = parseSloConfig(parseForgeYaml(fs.readFileSync(join(cwd, "forge.yaml"), "utf8"))); } catch { cfg = parseSloConfig({}); }
|
|
83
|
+
const report = await run(), dir = join(home, ".forge", "introspect"), scope = introspectUnitName(cwd).slice(-8);
|
|
84
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
85
|
+
const reportPath = introspectReportPath(cwd, home, now);
|
|
86
|
+
fs.writeFileSync(reportPath, report);
|
|
87
|
+
if (!cfg.fileIssues) return { action: "disabled", reportPath };
|
|
88
|
+
const stateFile = join(dir, `filed-${scope}.json`);
|
|
89
|
+
let prior = null; try { prior = JSON.parse(fs.readFileSync(stateFile, "utf8")); } catch { prior = null; }
|
|
90
|
+
const r = await fileIntrospect({ report, scope, gh, cfg, prior });
|
|
91
|
+
if (r.hash && ["create", "comment"].includes(r.action)) fs.writeFileSync(stateFile, JSON.stringify({ hash: r.hash, issue: r.issue }));
|
|
92
|
+
return { ...r, reportPath };
|
|
93
|
+
} catch (e) { return { action: "failed", detail: String(e?.message ?? e).slice(0, 200) }; }
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
if (process.argv[1] && resolve(process.argv[1]) === SELF && process.argv.includes("--run")) {
|
|
97
|
+
runIntrospect().then((r) => { console.log(`introspect: ${r.action}${r.reportPath ? ` ${r.reportPath}` : ""}`); });
|
|
98
|
+
}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
|
+
import { describe, it } from "node:test";
|
|
4
|
+
import assert from "node:assert/strict";
|
|
5
|
+
import * as fs from "node:fs";
|
|
6
|
+
import { join } from "node:path";
|
|
7
|
+
import { tmpDir } from "./tests/_tmp.mjs";
|
|
8
|
+
import { runIntrospect, installIntrospectSchedule, renderIntrospectCron, renderIntrospectSystemd, introspectUnitName } from "./introspect-schedule.mjs";
|
|
9
|
+
|
|
10
|
+
describe("#5987 introspect schedule", () => {
|
|
11
|
+
it("renders a daily systemd unit and a tagged cron line that run stats --file-issues", () => {
|
|
12
|
+
const s = renderIntrospectSystemd({ cwd: "/work/r", node: "/n", bin: "/b/forgedock.mjs" });
|
|
13
|
+
assert.match(s.service, /ExecStart="\/n" ".*introspect-schedule.mjs" --run/);
|
|
14
|
+
assert.match(s.timer, /OnCalendar=daily/);
|
|
15
|
+
assert.match(renderIntrospectCron({ cwd: "/work/r", node: "/n", bin: "/b/f.mjs" }), /^17 4 \* \* \* cd "\/work\/r" .*introspect-schedule.mjs" --run .*# forgedock-introspect \/work\/r$/);
|
|
16
|
+
});
|
|
17
|
+
|
|
18
|
+
it("systemd: installs once (rewrite, no duplicate), removes when disabled", async () => {
|
|
19
|
+
const home = tmpDir("isch-"), calls = [];
|
|
20
|
+
const exec = async (c, a) => { calls.push([c, ...a].join(" ")); return ""; };
|
|
21
|
+
const o = { cwd: "/work/r", home, platform: "linux", exec, node: "/n", bin: "/b" };
|
|
22
|
+
assert.equal((await installIntrospectSchedule(o)).status, "installed");
|
|
23
|
+
assert.equal((await installIntrospectSchedule(o)).status, "installed");
|
|
24
|
+
const name = introspectUnitName("/work/r"), dir = join(home, ".config", "systemd", "user");
|
|
25
|
+
assert.deepEqual(fs.readdirSync(dir).sort(), [`${name}.service`, `${name}.timer`]);
|
|
26
|
+
assert.equal((await installIntrospectSchedule({ ...o, enabled: false })).status, "removed");
|
|
27
|
+
assert.equal(fs.existsSync(join(dir, `${name}.timer`)), false);
|
|
28
|
+
assert.equal((await installIntrospectSchedule({ ...o, enabled: false })).status, "off");
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
it("cron fallback replaces only its own line and dedupes", async () => {
|
|
32
|
+
let tab = "0 1 * * * other\n17 4 * * * x # forgedock-introspect /work/r2\n";
|
|
33
|
+
const exec = async (c, a, input) => { if (c === "systemctl") throw new Error("no systemd"); if (a[0] === "-l") return tab; tab = input; return ""; };
|
|
34
|
+
const o = { cwd: "/work/r", platform: "linux", exec, node: "/n", bin: "/b" };
|
|
35
|
+
await installIntrospectSchedule(o); await installIntrospectSchedule(o);
|
|
36
|
+
const lines = tab.trim().split("\n");
|
|
37
|
+
assert.equal(lines.filter((l) => l.endsWith("# forgedock-introspect /work/r")).length, 1);
|
|
38
|
+
assert.equal(lines.length, 3, "other lines kept");
|
|
39
|
+
assert.equal((await installIntrospectSchedule({ ...o, enabled: false })).status, "removed");
|
|
40
|
+
assert.equal(tab.trim().split("\n").length, 2);
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
it("never throws", async () => {
|
|
44
|
+
const r = await installIntrospectSchedule({ cwd: "/w", platform: "darwin", exec: async () => { throw new Error("boom"); } });
|
|
45
|
+
assert.ok(["off", "failed", "removed"].includes(r.status) || r.status === "installed");
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
it("runIntrospect files the report once, dedupes an unchanged report, adopts an open issue, and honors file_issues: false", async () => {
|
|
49
|
+
const home = tmpDir("isch-run-"), cwd = tmpDir("isch-cwd-"), calls = [];
|
|
50
|
+
const gh = async (a) => { calls.push(a); return a[1] === "list" ? "[]" : a[1] === "create" ? "https://x/issues/9\n" : ""; };
|
|
51
|
+
const run = async () => "adequate 80%";
|
|
52
|
+
fs.writeFileSync(join(cwd, "forge.yaml"), "orchestrate:\n slo:\n file_issues: false\n");
|
|
53
|
+
assert.equal((await runIntrospect({ cwd, home, run, gh })).action, "disabled");
|
|
54
|
+
assert.equal(calls.length, 0);
|
|
55
|
+
fs.rmSync(join(cwd, "forge.yaml"));
|
|
56
|
+
assert.equal((await runIntrospect({ cwd, home, run, gh })).action, "disabled", "no forge.yaml: default does not file");
|
|
57
|
+
assert.equal(calls.length, 0);
|
|
58
|
+
fs.writeFileSync(join(cwd, "forge.yaml"), "orchestrate:\n slo:\n file_issues: true\n");
|
|
59
|
+
const a = await runIntrospect({ cwd, home, run, gh });
|
|
60
|
+
assert.equal(a.action, "create"); assert.equal(a.issue, 9);
|
|
61
|
+
assert.equal((await runIntrospect({ cwd, home, run, gh })).action, "unchanged", "prior report: nothing filed");
|
|
62
|
+
const c = await runIntrospect({ cwd, home, run: async () => "adequate 70%", gh });
|
|
63
|
+
assert.equal(c.action, "comment"); assert.equal(c.issue, 9);
|
|
64
|
+
assert.equal(calls.filter((x) => x[1] === "create").length, 1);
|
|
65
|
+
assert.doesNotMatch(calls.at(-1).at(-1), /report: |\.forge\/introspect|\/introspect\//, "no local path posted");
|
|
66
|
+
});
|
|
67
|
+
});
|
package/bin/lean/admission.mjs
CHANGED
|
@@ -10,6 +10,27 @@ export const ADMISSION_DEFAULTS = Object.freeze({ enabled: true, min_free_mem_mb
|
|
|
10
10
|
// #5845: lanes admitted within `ramp_s` have not grown yet; `host.rampingMb/rampingLanes/laneFootprintMb` (effects.mjs) expose them. null `max_new_per_ramp` = no rate limit.
|
|
11
11
|
export const ADMISSION_RETRY_SECONDS = 60;
|
|
12
12
|
|
|
13
|
+
/**
|
|
14
|
+
* #6047: usable cores = min(VM cores, the container's cgroup CPU quota). `read(path)` returns file text or throws; v2 `cpu.max`
|
|
15
|
+
* ("<quota> <period>" or "max <period>"), v1 `cpu.cfs_quota_us` (-1 = unlimited) / `cpu.cfs_period_us`. `CS_CPU_QUOTA` (set by
|
|
16
|
+
* the pool when the cgroup files are hidden from the lane) is the fallback. Unlimited or unreadable gives the VM cores.
|
|
17
|
+
*/
|
|
18
|
+
export function quotaCores({ cores, read, env = {} } = {}) {
|
|
19
|
+
const vm = Number.isFinite(cores) && cores > 0 ? cores : 1;
|
|
20
|
+
const num = (f) => { try { const v = Number(String(read?.(f) ?? "").trim()); return Number.isFinite(v) ? v : null; } catch { return null; } };
|
|
21
|
+
let q = null;
|
|
22
|
+
try {
|
|
23
|
+
const [quota, period] = String(read?.("/sys/fs/cgroup/cpu.max") ?? "").trim().split(/\s+/);
|
|
24
|
+
if (quota && quota !== "max" && Number(quota) > 0 && Number(period) > 0) q = Number(quota) / Number(period);
|
|
25
|
+
} catch { /* not cgroup v2 */ }
|
|
26
|
+
if (q === null) {
|
|
27
|
+
const quota = num("/sys/fs/cgroup/cpu/cpu.cfs_quota_us"), period = num("/sys/fs/cgroup/cpu/cpu.cfs_period_us");
|
|
28
|
+
if (quota > 0 && period > 0) q = quota / period;
|
|
29
|
+
}
|
|
30
|
+
if (q === null) { const e = Number(env?.CS_CPU_QUOTA); if (Number.isFinite(e) && e > 0) q = e; }
|
|
31
|
+
return q === null ? vm : Math.max(1, Math.min(vm, Math.floor(q)));
|
|
32
|
+
}
|
|
33
|
+
|
|
13
34
|
/** Workers one verification step may use (#4182): max(1, floor(cores / lanes)); bad inputs count as 1. Heavy shims pass live heavy holders (#4169). */
|
|
14
35
|
export function hostParallelism({ cores, lanes } = {}) {
|
|
15
36
|
const c = Number.isFinite(cores) && cores > 0 ? cores : 1, l = Number.isFinite(lanes) && lanes > 0 ? lanes : 1;
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
|
+
import { describe, it } from "node:test";
|
|
4
|
+
import assert from "node:assert/strict";
|
|
5
|
+
import { quotaCores, hostParallelism } from "./admission.mjs";
|
|
6
|
+
|
|
7
|
+
const files = (m) => (f) => { if (!(f in m)) throw new Error("ENOENT"); return m[f]; };
|
|
8
|
+
|
|
9
|
+
describe("quotaCores (#6047)", () => {
|
|
10
|
+
it("cgroup v2 cpu.max `400000 100000` on 20 VM cores gives 4; `max 100000` gives 20", () => {
|
|
11
|
+
assert.equal(quotaCores({ cores: 20, read: files({ "/sys/fs/cgroup/cpu.max": "400000 100000\n" }) }), 4);
|
|
12
|
+
assert.equal(quotaCores({ cores: 20, read: files({ "/sys/fs/cgroup/cpu.max": "max 100000\n" }) }), 20);
|
|
13
|
+
});
|
|
14
|
+
it("cgroup v1 quota/period; -1 is unlimited", () => {
|
|
15
|
+
const v1 = (q) => files({ "/sys/fs/cgroup/cpu/cpu.cfs_quota_us": q, "/sys/fs/cgroup/cpu/cpu.cfs_period_us": "100000" });
|
|
16
|
+
assert.equal(quotaCores({ cores: 20, read: v1("200000") }), 2);
|
|
17
|
+
assert.equal(quotaCores({ cores: 20, read: v1("-1") }), 20);
|
|
18
|
+
});
|
|
19
|
+
it("unreadable files give the VM cores; CS_CPU_QUOTA is the fallback; a quota above the VM is capped", () => {
|
|
20
|
+
assert.equal(quotaCores({ cores: 20, read: files({}) }), 20);
|
|
21
|
+
assert.equal(quotaCores({ cores: 20, read: files({}), env: { CS_CPU_QUOTA: "4" } }), 4);
|
|
22
|
+
assert.equal(quotaCores({ cores: 2, read: files({ "/sys/fs/cgroup/cpu.max": "800000 100000" }) }), 2);
|
|
23
|
+
assert.equal(quotaCores({ cores: 20, read: files({}), env: { CS_CPU_QUOTA: "junk" } }), 20);
|
|
24
|
+
});
|
|
25
|
+
it("hostParallelism with the quota divides the container's cores, not the VM's", () => {
|
|
26
|
+
const cores = quotaCores({ cores: 20, read: files({ "/sys/fs/cgroup/cpu.max": "400000 100000" }) });
|
|
27
|
+
assert.equal(hostParallelism({ cores, lanes: 2 }), 2);
|
|
28
|
+
assert.equal(hostParallelism({ cores: 20, lanes: 2 }), 10);
|
|
29
|
+
});
|
|
30
|
+
});
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
|
+
import { describe, it } from "node:test";
|
|
4
|
+
import assert from "node:assert/strict";
|
|
5
|
+
import { splitAdvisory, ADVISORY_KINDS, ADVISORY_CODES } from "./conformance.mjs";
|
|
6
|
+
import { OUTCOME_CODES as C } from "../engine/outcome-codes.mjs";
|
|
7
|
+
import { genericInstallCommands } from "../pool/lane-tools.mjs";
|
|
8
|
+
|
|
9
|
+
describe("advisory gates (unclog)", () => {
|
|
10
|
+
it("shape, environment and opinion rules are advisory; failing checks, regressions and omissions block (#6083)", () => {
|
|
11
|
+
const rows = [
|
|
12
|
+
{ code: C.CONFORMANCE_SCOPE_CREEP, kind: "scope_creep", detail: "x" },
|
|
13
|
+
{ code: C.CONFORMANCE_SCOPE_CREEP, detail: "review-side creep has no kind" },
|
|
14
|
+
{ code: C.CONFORMANCE_E2E_UNVERIFIED, kind: "e2e_row", detail: "e2e" },
|
|
15
|
+
{ code: C.CONFORMANCE_UNTRACKED_DEFERRAL, kind: "untracked_deferral", detail: "deferral" },
|
|
16
|
+
{ code: C.CONFORMANCE_UNIMPLEMENTED, kind: "review_unimplemented", detail: "reviewer opinion" },
|
|
17
|
+
{ code: C.CONFORMANCE_UNIMPLEMENTED, kind: "validate_missing", detail: "V1 no result" },
|
|
18
|
+
{ code: C.ENV_TOOL_MISSING, kind: "validate_env", detail: "tool" },
|
|
19
|
+
{ code: C.CONFORMANCE_GUARD_BROKEN, kind: "guard_broken", detail: "G1" },
|
|
20
|
+
{ code: C.CONFORMANCE_UNIMPLEMENTED, kind: "page_metadata_missing", detail: "page" },
|
|
21
|
+
{ code: C.CONFORMANCE_UNIMPLEMENTED, kind: "prod_parity_unjustified", detail: "parity" },
|
|
22
|
+
{ code: C.CONFORMANCE_UNIMPLEMENTED, kind: "validate_failed", detail: "V1 failed" },
|
|
23
|
+
{ code: C.CONFORMANCE_UNIMPLEMENTED, kind: "requirement_unimplemented", detail: "R1 reported not done" },
|
|
24
|
+
{ code: C.CONFORMANCE_UNIMPLEMENTED, kind: "repro_red_green", detail: "repro" },
|
|
25
|
+
{ code: C.CONFORMANCE_UNIMPLEMENTED, kind: "source_deliverable_untouched", detail: "tests only" },
|
|
26
|
+
{ code: C.CONFORMANCE_REGRESSION, detail: "a.test.mjs: fails" },
|
|
27
|
+
{ code: C.CONFORMANCE_OMISSION, detail: "narrowed" },
|
|
28
|
+
];
|
|
29
|
+
const { block, advisory } = splitAdvisory(rows);
|
|
30
|
+
assert.deepEqual(block.map((f) => f.kind ?? f.code), ["validate_failed", "requirement_unimplemented", "repro_red_green", "source_deliverable_untouched", C.CONFORMANCE_REGRESSION, C.CONFORMANCE_OMISSION]);
|
|
31
|
+
assert.equal(advisory.length, 10);
|
|
32
|
+
});
|
|
33
|
+
it("never lists a kind that proves the change wrong", () => {
|
|
34
|
+
for (const k of ["validate_failed", "requirement_unimplemented", "repro_red_green", "source_deliverable_untouched", "test_missing", "test_weak"]) assert.ok(!ADVISORY_KINDS.includes(k), k);
|
|
35
|
+
assert.ok(!ADVISORY_CODES.includes(C.CONFORMANCE_REGRESSION) && !ADVISORY_CODES.includes(C.CONFORMANCE_OMISSION));
|
|
36
|
+
});
|
|
37
|
+
it("a kind the repo enforces by code stays blocking", () => {
|
|
38
|
+
const { block } = splitAdvisory([{ code: C.CONFORMANCE_GUARD_BROKEN, kind: "guard_broken", detail: "G1" }], { enforce: [C.CONFORMANCE_GUARD_BROKEN] });
|
|
39
|
+
assert.equal(block.length, 1);
|
|
40
|
+
});
|
|
41
|
+
it("a code the repo explicitly enforces stays blocking", () => {
|
|
42
|
+
const { block, advisory } = splitAdvisory([{ code: C.CONFORMANCE_SCOPE_CREEP, kind: "scope_creep", detail: "x" }], { enforce: [C.CONFORMANCE_SCOPE_CREEP] });
|
|
43
|
+
assert.equal(block.length, 1); assert.equal(advisory.length, 0);
|
|
44
|
+
});
|
|
45
|
+
it("empty and missing input", () => {
|
|
46
|
+
assert.deepEqual(splitAdvisory(undefined), { block: [], advisory: [] });
|
|
47
|
+
});
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
describe("generic sandbox install (unclog)", () => {
|
|
51
|
+
it("installs by miss kind, mapping import names to packages", () => {
|
|
52
|
+
assert.match(genericInstallCommands({ kind: "python-module", tool: "yaml" })[0], /pip install --user --quiet PyYAML/);
|
|
53
|
+
assert.match(genericInstallCommands({ kind: "python-module", tool: "requests" })[0], /pip install --user --quiet requests/);
|
|
54
|
+
const y = genericInstallCommands({ kind: "python-module", tool: "yaml" })[0];
|
|
55
|
+
assert.match(y, /\|\| \(apt-get update -qq && apt-get install -y --no-install-recommends python3-yaml && rm -rf \/var\/lib\/apt\/lists\/\*\)$/, "apt fallback grouped so it runs only when pip fails");
|
|
56
|
+
assert.match(genericInstallCommands({ kind: "node-module", tool: "@adobe/css-tools" })[0], /^npm install --no-save .* @adobe\/css-tools$/);
|
|
57
|
+
assert.match(genericInstallCommands({ kind: "command", tool: "shellcheck" })[0], /apt-get install -y --no-install-recommends shellcheck/);
|
|
58
|
+
assert.match(genericInstallCommands({ kind: "command", tool: "shellcheck" }, { root: false })[0], /^sudo sh -c /);
|
|
59
|
+
});
|
|
60
|
+
it("refuses unsafe names and kinds nothing can install", () => {
|
|
61
|
+
for (const m of [{ kind: "command", tool: "a;rm -rf /" }, { kind: "command", tool: "$(x)" }, { kind: "command", tool: "../x" }, { kind: "command", tool: "bin/x" }, { kind: "environment", tool: "db" }, { kind: "forgedock-path", tool: "forgedock" }, {}])
|
|
62
|
+
assert.deepEqual(genericInstallCommands(m), [], JSON.stringify(m));
|
|
63
|
+
});
|
|
64
|
+
});
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
|
+
/**
|
|
4
|
+
* #5979: the amendment shapes the builder may write to result.json, as data. The builder prompt, the correction prompt and the
|
|
5
|
+
* tests render from this one list, so the prompt never documents a shape the validator (conformance.mjs) rejects, nor omits one it accepts.
|
|
6
|
+
* Pure: no imports.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
/** kind -> {shape, doc, example}. `supersedes` takes only a "#N" guard issue or a mechanism, never a validate-row id (G2). */
|
|
10
|
+
export const AMENDMENT_SHAPES = Object.freeze({
|
|
11
|
+
"add-deliverable": { shape: `{"kind":"add-deliverable","path":"<file>"}`, doc: "a file not listed.", example: { kind: "add-deliverable", path: "bin/x.mjs", why: "needed" } },
|
|
12
|
+
"add-requirement": { shape: `{"kind":"add-requirement","requirement":{"id":"R9","quote":"<verbatim from the issue>","disposition":"deliver|defer|post-deploy"}}`, doc: "a missed requirement.", example: { kind: "add-requirement", requirement: { id: "R9", quote: "q", disposition: "deliver" }, why: "missed" } },
|
|
13
|
+
defer: { shape: `{"kind":"defer|post-deploy","requirement":"R#","why":"","check":"<id>"}`, doc: `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.`, example: { kind: "defer", requirement: "R1", why: "separate work", check: "c1" } },
|
|
14
|
+
"post-deploy": { example: { kind: "post-deploy", requirement: "R1", why: "measured after release", check: "c1" } },
|
|
15
|
+
"amend-requirement": { shape: `{"kind":"amend-requirement","requirement":"R#","text":"<revised wording>"}`, doc: "reworded.", example: { kind: "amend-requirement", requirement: "R1", text: "revised", why: "reworded" } },
|
|
16
|
+
supersedes: { shape: `{"kind":"supersedes","guard":"#N"}`, doc: `overrides a guard_broken failure; {"kind":"supersedes","mechanism":"<name>"} retires every guard whose test this lane deletes. A validate-row id is never a supersedes guard.`, example: { kind: "supersedes", guard: "#123", why: "obsolete" } },
|
|
17
|
+
"out-of-band": { shape: `{"kind":"out-of-band","requirement":"R#","evidence":"<job that measures it>"}`, doc: "measured by a job.", example: { kind: "out-of-band", requirement: "R1", evidence: ".github/workflows/bench.yml", why: "measured by the bench job" } },
|
|
18
|
+
decision: { shape: `{"kind":"decision","decision":{"choice":"","anchors":["<base path>"],"supersedes":"<id>"}}`, doc: "supersedes changes an H-row.", example: { kind: "decision", decision: { choice: "c", anchors: ["bin/x.mjs"] }, why: "w" } },
|
|
19
|
+
});
|
|
20
|
+
|
|
21
|
+
export const AMEND_KINDS = Object.freeze(["add-deliverable", "add-requirement", "defer", "post-deploy", "amend-requirement", "supersedes", "decision", "out-of-band"]);
|
|
22
|
+
|
|
23
|
+
/** One valid example per kind (supersedes only with #N). */
|
|
24
|
+
export const AMENDMENT_EXAMPLES = Object.freeze(AMEND_KINDS.map((k) => AMENDMENT_SHAPES[k].example));
|
|
25
|
+
|
|
26
|
+
/** The builder-prompt bullet list, in the order the prompt documents them. */
|
|
27
|
+
export function amendmentPromptLines() {
|
|
28
|
+
return ["add-deliverable", "add-requirement", "defer", "amend-requirement", "supersedes", "out-of-band", "decision"]
|
|
29
|
+
.map((k) => `- ${AMENDMENT_SHAPES[k].shape}: ${AMENDMENT_SHAPES[k].doc}`).join("\n");
|
|
30
|
+
}
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
|
+
/**
|
|
4
|
+
* #5986: the per-issue attempts ledger `{attempts, signatures[], lastInputHash, spend}`. It lives in the batch state.json (cache) and is
|
|
5
|
+
* mirrored as one hidden `FORGE:ATTEMPTS` comment (the register). Readmission needs a new input hash; the same hash after a failure is
|
|
6
|
+
* refused (`loop.no_new_input`); a lifetime budget breach escalates once (`FORGE:ESCALATION`, needs-human) until the hash changes.
|
|
7
|
+
* Nothing here clears the ledger: releaseHeld, --requeue and --set-env leave it alone. A missing ledger always admits.
|
|
8
|
+
*/
|
|
9
|
+
import { createHash } from "node:crypto";
|
|
10
|
+
import { parseContractComment } from "./render.mjs";
|
|
11
|
+
import { postUpsert, findLeading, engineCommentCount } from "./statuscomment.mjs";
|
|
12
|
+
|
|
13
|
+
export const ATTEMPTS_MARKER = "FORGE:ATTEMPTS";
|
|
14
|
+
export const ESCALATION_MARKER = "FORGE:ESCALATION";
|
|
15
|
+
export const NO_NEW_INPUT = "loop.no_new_input";
|
|
16
|
+
export const DEFAULT_ISSUE_ATTEMPTS = 4;
|
|
17
|
+
export const DEFAULT_MAX_IDENTICAL = 2;
|
|
18
|
+
|
|
19
|
+
const sha = (s) => createHash("sha256").update(String(s)).digest("hex").slice(0, 16);
|
|
20
|
+
const majorMinor = (v) => (/^v?(\d+)\.(\d+)/.exec(String(v ?? "")) ?? []).slice(1, 3).join(".");
|
|
21
|
+
const labelName = (l) => (typeof l === "string" ? l : l?.name);
|
|
22
|
+
|
|
23
|
+
/** Hash of what a person can change: title+body, labels (not needs-human), operator FORGE:DECISION comments, engine and sandbox engine major.minor, contract hash. */
|
|
24
|
+
export function computeInputHash({ title = "", body = "", labels = [], decisions = [], engineVersion = null, sandboxVersion = null, contractHash = null } = {}) {
|
|
25
|
+
const ls = (labels ?? []).map(labelName).filter((n) => n && n !== "needs-human" && !String(n).startsWith("needs-human:")).sort();
|
|
26
|
+
return sha(JSON.stringify([String(title), String(body), ls, (decisions ?? []).map(String), majorMinor(engineVersion), majorMinor(sandboxVersion), contractHash ?? null]));
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export const emptyLedger = () => ({ attempts: 0, signatures: [], lastInputHash: null, spend: 0 });
|
|
30
|
+
export function normalizeLedger(x) {
|
|
31
|
+
if (!x || typeof x !== "object") return emptyLedger();
|
|
32
|
+
return { attempts: Number.isInteger(x.attempts) && x.attempts > 0 ? x.attempts : 0, signatures: Array.isArray(x.signatures) ? x.signatures.map((s) => ({ ...s, sig: String(s?.sig ?? "") })) : [],
|
|
33
|
+
lastInputHash: typeof x.lastInputHash === "string" ? x.lastInputHash : null, spend: Number(x.spend) > 0 ? Number(x.spend) : 0, ...(Number.isInteger(x.comments) && x.comments >= 0 ? { comments: x.comments } : {}), ...(x.escalated ? { escalated: x.escalated } : {}), ...(x.hostPin ? { hostPin: true } : {}) };
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** `{maxAttempts, maxIdentical}` from the orchestration config (posint, else the defaults 4 and 2). */
|
|
37
|
+
export const budgets = (cfg) => ({ maxAttempts: Number(cfg?.maxAttempts) >= 1 ? Math.floor(cfg.maxAttempts) : DEFAULT_ISSUE_ATTEMPTS, maxIdentical: Number(cfg?.maxIdentical) >= 1 ? Math.floor(cfg.maxIdentical) : DEFAULT_MAX_IDENTICAL });
|
|
38
|
+
|
|
39
|
+
/** The ledger after one failed lane (a new object): attempts+1, the signature with its run link, the hash it ran under, spend added. */
|
|
40
|
+
const normDetail = (d) => String(d ?? "").replace(/https?:\/\/\S+/g, "").replace(/\b[0-9a-f]{7,40}\b/g, "").replace(/\d+/g, "#").replace(/\s+/g, " ").trim().slice(0, 200);
|
|
41
|
+
/** #5931: what blocked a lane: code, normalized detail, contract hash, the engine version the lane ran, placement, and the env keys the detail names. */
|
|
42
|
+
export function blockerSignature({ code = null, detail = "", contractHash = null, engineVersion = null, placement = null, env = null } = {}) {
|
|
43
|
+
const envKeys = [...new Set(String(detail ?? "").match(/\b[A-Z][A-Z0-9]*_[A-Z0-9_]+\b/g) ?? [])].sort();
|
|
44
|
+
return { code: code ?? null, detail: normDetail(detail), contractHash: contractHash ?? null, engineVersion: engineVersion ? majorMinor(engineVersion) || String(engineVersion) : null, placement: placement ?? null, ...(envKeys.length ? { envKeys, env: Object.fromEntries(envKeys.map((k) => [k, env?.[k] == null ? null : sha(env[k])])) } : {}) };
|
|
45
|
+
}
|
|
46
|
+
/** A credentials block naming ops_credentials is pinned to the host on readmit. */
|
|
47
|
+
export const isCredentialsBlock = (detail) => /ops_credentials/i.test(String(detail ?? "")) && /credential/i.test(String(detail ?? ""));
|
|
48
|
+
|
|
49
|
+
export function recordFailure(ledger, { signature, hash = null, spend = 0, run = null, blocker = null }) {
|
|
50
|
+
const l = normalizeLedger(ledger);
|
|
51
|
+
const changed = hash && l.lastInputHash && hash !== l.lastInputHash; // a new input starts a new escalation window, the lifetime counters stay
|
|
52
|
+
const { escalated, ...rest } = l;
|
|
53
|
+
const pin = l.hostPin || (blocker && isCredentialsBlock(blocker.detail)); // `comments` (the engine comment count seen at the last mirror) rides along
|
|
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
|
+
}
|
|
56
|
+
|
|
57
|
+
/** The breach of the lifetime budget, or null: attempts reached the cap, or one signature exceeded `maxIdentical` failures. */
|
|
58
|
+
export function breach(ledger, cfg) {
|
|
59
|
+
const l = normalizeLedger(ledger), { maxAttempts, maxIdentical } = budgets(cfg);
|
|
60
|
+
const counts = new Map();
|
|
61
|
+
for (const s of l.signatures) counts.set(s.sig, (counts.get(s.sig) ?? 0) + 1);
|
|
62
|
+
const worst = [...counts].sort((a, b) => b[1] - a[1])[0];
|
|
63
|
+
if (worst && worst[1] >= maxIdentical) return { kind: "identical", detail: `failure signature \`${worst[0]}\` repeated ${worst[1]} times (max_identical_signature ${maxIdentical})` };
|
|
64
|
+
if (l.attempts >= maxAttempts) return { kind: "attempts", detail: `${l.attempts} lanes ran (max_attempts_per_issue ${maxAttempts})` };
|
|
65
|
+
return null;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Admission of a re-run. `hash` null (unreadable input) fails open. Returns {ok:true} or {ok:false, code, reason}: `escalate` (a budget
|
|
70
|
+
* breach not yet escalated), or `loop.no_new_input` (the same input after a failure).
|
|
71
|
+
*/
|
|
72
|
+
export function admitInput(ledger, hash, cfg, cur = null) {
|
|
73
|
+
const l = normalizeLedger(ledger);
|
|
74
|
+
if (!hash || !l.attempts || !l.lastInputHash || hash !== l.lastInputHash) return { ok: true };
|
|
75
|
+
const why = changedSince(l.signatures[l.signatures.length - 1]?.blocker, cur); // #5931: the hash omits placement and env values
|
|
76
|
+
if (why) return { ok: true, reason: why };
|
|
77
|
+
const b = breach(l, cfg);
|
|
78
|
+
if (b && !l.escalated) return { ok: false, code: "escalate", reason: b.detail };
|
|
79
|
+
const last = l.signatures[l.signatures.length - 1]?.sig;
|
|
80
|
+
return { ok: false, code: NO_NEW_INPUT, reason: `input unchanged since the last failure${last ? ` (\`${last}\`)` : ""}${b ? `; ${b.detail}` : ""}` };
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** What relevant thing changed since the blocker (engine version, placement, contract hash, a referenced env key), or null. */
|
|
84
|
+
export function changedSince(b, cur) {
|
|
85
|
+
if (!b || !cur) return null;
|
|
86
|
+
const diff = (a, c) => a != null && c != null && String(a) !== String(c);
|
|
87
|
+
if (diff(b.engineVersion, cur.engineVersion ? majorMinor(cur.engineVersion) || cur.engineVersion : null)) return `engine version changed ${b.engineVersion} -> ${cur.engineVersion}`;
|
|
88
|
+
if (diff(b.placement, cur.placement)) return `placement changed ${b.placement} -> ${cur.placement}`;
|
|
89
|
+
if (diff(b.contractHash, cur.contractHash)) return "contract hash changed";
|
|
90
|
+
const keys = (b.envKeys ?? []).filter((k) => cur.env && cur.env[k] !== undefined && (b.env?.[k] ?? null) !== (cur.env[k] == null ? null : sha(cur.env[k])));
|
|
91
|
+
return keys.length ? `env key changed: ${keys.join(", ")}` : null;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export const markEscalated = (ledger, at) => ({ ...normalizeLedger(ledger), escalated: at ?? true });
|
|
95
|
+
|
|
96
|
+
/** The one consolidated FORGE:ESCALATION body: signatures with run links, spend, what unblocks it. */
|
|
97
|
+
export function renderEscalation(ledger, reason) {
|
|
98
|
+
const l = normalizeLedger(ledger);
|
|
99
|
+
const rows = l.signatures.map((s, i) => `${i + 1}. \`${s.sig}\`${s.run ? ` (${s.run})` : ""}`);
|
|
100
|
+
return [`Escalated to a person after ${l.attempts} attempt${l.attempts === 1 ? "" : "s"}: ${reason}.`, "", ...rows, "", `Spend: $${l.spend.toFixed(2)}`,
|
|
101
|
+
"No further lanes run until the issue's input changes (edit the issue, add a FORGE:DECISION, or upgrade the engine); removing needs-human alone does not readmit it."].join("\n");
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** Hidden FORGE:ATTEMPTS comment body and its parse (null when absent or malformed). */
|
|
105
|
+
export const renderAttempts = (ledger) => `<!-- ${ATTEMPTS_MARKER} ${JSON.stringify(normalizeLedger(ledger))} -->`;
|
|
106
|
+
export function parseAttempts(body) {
|
|
107
|
+
const m = new RegExp(`^\\s*<!--\\s*${ATTEMPTS_MARKER}\\s+(\\{.*\\})\\s*-->`, "s").exec(String(body ?? ""));
|
|
108
|
+
if (!m) return null;
|
|
109
|
+
try { return normalizeLedger(JSON.parse(m[1])); } catch { return null; }
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** Hash of the last trusted, parseable FORGE:CONTRACT comment (the frozen contract), or null. */
|
|
113
|
+
export function frozenContractHash(comments, trusted) {
|
|
114
|
+
let h = null;
|
|
115
|
+
for (const c of comments ?? []) {
|
|
116
|
+
const b = String(c?.body ?? "");
|
|
117
|
+
if (!b.startsWith("<!-- FORGE:CONTRACT -->") || !trusted(c)) continue;
|
|
118
|
+
const fc = parseContractComment(b);
|
|
119
|
+
if (fc?.hash) h = fc.hash;
|
|
120
|
+
}
|
|
121
|
+
return h;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* The orchestrate seam, bound to GitHub: `hash(n)` reads the issue and computes the input hash (null on any read failure: fail open),
|
|
126
|
+
* `load(n)` reads the FORGE:ATTEMPTS comment, `mirror(n, ledger)` upserts it, `notify(...)` posts the one escalation or the no-new-input note.
|
|
127
|
+
*/
|
|
128
|
+
export function makeAttemptsSeam({ gh, repo, engineVersion = null, hostVersion = null, sandboxVersion = null, cfg = {}, trusted = null, contractHash = null }) {
|
|
129
|
+
const view = async (n) => JSON.parse(String(await gh(["issue", "view", String(n), "-R", repo, "--json", "title,body,labels,comments"])));
|
|
130
|
+
const isTrusted = async () => trusted ?? (await import("./prefilter.mjs")).isTrustedIssueComment;
|
|
131
|
+
let seenSandbox = sandboxVersion;
|
|
132
|
+
return {
|
|
133
|
+
noteSandboxVersion(v) { if (v) seenSandbox = v; },
|
|
134
|
+
cfg,
|
|
135
|
+
async hash(n) {
|
|
136
|
+
try {
|
|
137
|
+
const v = await view(n), t = await isTrusted();
|
|
138
|
+
const decisions = (v.comments ?? []).filter((c) => /^\s*<!--\s*FORGE:DECISION\b/.test(c?.body ?? "") && t(c)).map((c) => c.body);
|
|
139
|
+
return computeInputHash({ title: v.title, body: v.body, labels: v.labels, decisions, engineVersion, sandboxVersion: seenSandbox ?? hostVersion, // the version the lane ran; the host's only when none is known
|
|
140
|
+
contractHash: contractHash ? await contractHash(n) : frozenContractHash(v.comments, t) });
|
|
141
|
+
} catch { return null; }
|
|
142
|
+
},
|
|
143
|
+
async load(n) {
|
|
144
|
+
try { const c = findLeading((await view(n)).comments, ATTEMPTS_MARKER, await isTrusted()); return c ? parseAttempts(c.body) : null; } catch { return null; }
|
|
145
|
+
},
|
|
146
|
+
/** Upserts the ledger comment; returns the issue's engine comment count (for stats). */
|
|
147
|
+
async mirror(n, ledger) {
|
|
148
|
+
const t = await isTrusted();
|
|
149
|
+
await postUpsert({ gh, repo, issue: n, markers: ATTEMPTS_MARKER, body: "", trusted: t, attrs: JSON.stringify(normalizeLedger(ledger)) });
|
|
150
|
+
try { return engineCommentCount((await view(n)).comments, t); } catch { return null; }
|
|
151
|
+
},
|
|
152
|
+
async notify({ issue, code, ledger, reason, relabel = false }) {
|
|
153
|
+
if (code === "escalate") {
|
|
154
|
+
await postUpsert({ gh, repo, issue, markers: ESCALATION_MARKER, body: renderEscalation(ledger, reason), trusted: await isTrusted() });
|
|
155
|
+
await gh(["issue", "edit", String(issue), "-R", repo, "--add-label", "needs-human"]);
|
|
156
|
+
} else {
|
|
157
|
+
await postUpsert({ gh, repo, issue, markers: "FORGE:NO_NEW_INPUT", body: `${NO_NEW_INPUT}: ${reason}. Not readmitted; the existing label stays.`, trusted: await isTrusted() });
|
|
158
|
+
if (relabel) await gh(["issue", "edit", String(issue), "-R", repo, "--add-label", "needs-human"]).catch(() => {}); // the label stays: a removal without new input does not readmit
|
|
159
|
+
}
|
|
160
|
+
},
|
|
161
|
+
};
|
|
162
|
+
}
|