forgedock 1.53.0 → 1.54.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/.claude-plugin/marketplace.json +51 -0
- package/README.md +8 -2
- package/bin/auth/app-manifest.mjs +89 -0
- package/bin/auth/app-manifest.test.mjs +75 -0
- package/bin/auth/app-token.mjs +256 -0
- package/bin/auth/app-token.test.mjs +232 -0
- package/bin/brand.mjs +7 -0
- package/bin/config-history.mjs +151 -0
- package/bin/config-schema.mjs +115 -0
- package/bin/demo.mjs +65 -11
- package/bin/engine/outcome-codes.mjs +6 -3
- package/bin/engine/telemetry-seam.mjs +8 -2
- package/bin/engine/telemetry-seam.test.mjs +17 -0
- package/bin/engine-cli.mjs +57 -20
- package/bin/first-run.mjs +122 -0
- package/bin/forgedock.mjs +128 -146
- package/bin/help-text.mjs +144 -0
- package/bin/hooks/pre-tool-use.mjs +7 -0
- package/bin/journey.mjs +82 -83
- package/bin/lean/acceptance.mjs +313 -0
- package/bin/lean/acceptance.test.mjs +215 -0
- package/bin/lean/activation.mjs +18 -0
- package/bin/lean/activation.test.mjs +23 -1
- package/bin/lean/batch-health.mjs +74 -1
- package/bin/lean/batch-health.test.mjs +54 -1
- package/bin/lean/batch.test.mjs +11 -9
- package/bin/lean/branchlock.mjs +54 -0
- package/bin/lean/branchlock.test.mjs +49 -0
- package/bin/lean/ceiling.mjs +72 -0
- package/bin/lean/ceiling.test.mjs +54 -0
- package/bin/lean/ci-budget.mjs +366 -0
- package/bin/lean/ci-budget.test.mjs +167 -0
- package/bin/lean/conformance.e2e.test.mjs +7 -0
- package/bin/lean/conformance.mjs +77 -19
- package/bin/lean/conformance.test.mjs +129 -3
- package/bin/lean/context.mjs +35 -6
- package/bin/lean/context.test.mjs +27 -1
- package/bin/lean/depcache.mjs +25 -1
- package/bin/lean/depcache.test.mjs +26 -0
- package/bin/lean/e2e.mjs +18 -2
- package/bin/lean/e2e.test.mjs +26 -1
- package/bin/lean/effects.mjs +40 -11
- package/bin/lean/execution.test.mjs +24 -0
- package/bin/lean/facts.mjs +3 -3
- package/bin/lean/facts.test.mjs +5 -0
- package/bin/lean/fixround.mjs +14 -0
- package/bin/lean/fixround.test.mjs +25 -2
- package/bin/lean/gh-assoc.test.mjs +2 -1
- package/bin/lean/integration.mjs +100 -9
- package/bin/lean/integration.test.mjs +98 -0
- package/bin/lean/issuewatch-parity.mjs +64 -0
- package/bin/lean/issuewatch-parity.test.mjs +127 -0
- package/bin/lean/issuewatch-release.test.mjs +1 -1
- package/bin/lean/issuewatch.mjs +34 -5
- package/bin/lean/issuewatch.test.mjs +3 -2
- package/bin/lean/lean.mjs +316 -74
- package/bin/lean/lean.test.mjs +397 -24
- package/bin/lean/mechfix.mjs +124 -0
- package/bin/lean/mechfix.test.mjs +75 -0
- package/bin/lean/orchestrate.mjs +20 -2
- package/bin/lean/phaseledger.mjs +47 -5
- package/bin/lean/phaseledger.test.mjs +30 -1
- package/bin/lean/precheck.mjs +23 -4
- package/bin/lean/precheck.test.mjs +14 -1
- package/bin/lean/prereq.mjs +28 -0
- package/bin/lean/prereq.test.mjs +20 -0
- package/bin/lean/probe.mjs +4 -2
- package/bin/lean/prodparity.mjs +52 -0
- package/bin/lean/prodparity.test.mjs +67 -0
- package/bin/lean/prompts.mjs +69 -12
- package/bin/lean/recovery.test.mjs +1 -1
- package/bin/lean/release-io.test.mjs +42 -0
- package/bin/lean/release-postmerge.mjs +6 -0
- package/bin/lean/release-preflight.mjs +58 -0
- package/bin/lean/release-preflight.test.mjs +114 -0
- package/bin/lean/release-rehearsal.mjs +8 -7
- package/bin/lean/release-review.mjs +67 -11
- package/bin/lean/release-review.test.mjs +128 -1
- package/bin/lean/release-snapshot.mjs +188 -0
- package/bin/lean/release-snapshot.test.mjs +190 -0
- package/bin/lean/release.mjs +80 -12
- package/bin/lean/release.test.mjs +95 -0
- package/bin/lean/render.mjs +1 -1
- package/bin/lean/replan.mjs +184 -0
- package/bin/lean/replan.test.mjs +110 -0
- package/bin/lean/resume.mjs +9 -7
- package/bin/lean/resume.test.mjs +16 -0
- package/bin/lean/schedd.mjs +34 -1
- package/bin/lean/schedd.test.mjs +21 -1
- package/bin/lean/selfreview.mjs +94 -0
- package/bin/lean/selfreview.test.mjs +58 -1
- package/bin/lean/selftest-gate.mjs +22 -0
- package/bin/lean/selftest-gate.test.mjs +18 -1
- package/bin/lean/selftest-journey.mjs +234 -0
- package/bin/lean/selftest-journey.test.mjs +130 -0
- package/bin/lean/selftest-live.mjs +2 -1
- package/bin/lean/seqlease.mjs +35 -1
- package/bin/lean/seqlease.test.mjs +15 -0
- package/bin/lean/seqreserve.e2e.test.mjs +135 -0
- package/bin/lean/seqreserve.mjs +73 -0
- package/bin/lean/seqreserve.test.mjs +134 -0
- package/bin/lean/sequence.mjs +35 -6
- package/bin/lean/seqversioned.mjs +147 -0
- package/bin/lean/stagestamp.mjs +28 -0
- package/bin/lean/stagestamp.test.mjs +32 -0
- package/bin/lean/surfaces.mjs +75 -0
- package/bin/lean/surfaces.test.mjs +59 -0
- package/bin/lean/toolplace.mjs +28 -0
- package/bin/lean/toolplace.test.mjs +24 -0
- package/bin/lean/toolstats.mjs +3 -1
- package/bin/lean/toolstats.test.mjs +11 -0
- package/bin/lean/validatebest.mjs +28 -0
- package/bin/lean/validatebest.test.mjs +27 -0
- package/bin/pool/agent.mjs +9 -0
- package/bin/pool/docker.mjs +5 -0
- package/bin/pool/router.mjs +8 -4
- package/bin/prereqs.mjs +111 -0
- package/bin/replay-timelapse.mjs +149 -0
- package/bin/review-staging.mjs +100 -16
- package/bin/review-staging.test.mjs +18 -0
- package/bin/runner.mjs +43 -6
- package/bin/splash-install.mjs +157 -0
- package/bin/stats/aggregate.mjs +8 -1
- package/bin/stats/conformance-outcomes.mjs +100 -19
- package/bin/stats/conformance-outcomes.test.mjs +87 -1
- package/bin/stats/depth.mjs +88 -31
- package/bin/stats/depth.test.mjs +63 -38
- package/bin/stats/efficiency.mjs +26 -5
- package/bin/stats/efficiency.test.mjs +45 -1
- package/bin/stats/first-review.mjs +77 -0
- package/bin/stats/first-review.test.mjs +36 -0
- package/bin/stats/firstmerge.mjs +40 -0
- package/bin/stats/firstmerge.test.mjs +41 -0
- package/bin/stats/github-source.mjs +51 -13
- package/bin/stats/index.mjs +91 -15
- package/bin/stats/local-source.mjs +1 -0
- package/bin/stats/origin.mjs +80 -0
- package/bin/stats/origin.test.mjs +58 -0
- package/bin/stats/render.mjs +3 -1
- package/bin/stats/scoreboard.mjs +137 -0
- package/bin/stats/scoreboard.test.mjs +87 -0
- package/bin/stats/stats.test.mjs +80 -0
- package/bin/tui.mjs +3 -2
- package/commands/bootstrap.md +15 -14
- package/commands/deploy-pr.md +18 -3
- package/commands/forge-stats.md +1 -1
- package/commands/forgedock-ci-setup.md +28 -0
- package/commands/forgedock-init.md +4 -5
- package/commands/issue.md +2 -0
- package/commands/milestone.md +9 -1
- package/commands/replay.md +2 -0
- package/commands/review-pr-staging.md +4 -1
- package/commands/work-on/close.md +8 -0
- package/docs/CONFIG.md +105 -10
- package/docs/ISSUE-WATCH.md +23 -0
- package/docs/OUTCOME-CODES.md +1 -0
- package/docs/REPLAY.md +9 -0
- package/docs/SELFTEST.md +11 -0
- package/docs/STATS.md +19 -2
- package/docs/eval/README.md +6 -0
- package/docs/eval/adversarial-bench.md +68 -0
- package/docs/eval/corpus/adversarial-v1.json +285 -0
- package/docs/eval/feature-bench.md +42 -0
- package/docs/eval/feature-specs/crud-auth/journeys/notes-crud-isolated.mjs +21 -0
- package/docs/eval/feature-specs/crud-auth/journeys/register-login.mjs +12 -0
- package/docs/eval/feature-specs/crud-auth/spec.md +15 -0
- package/docs/site/start-a-new-project.md +2 -1
- package/package.json +5 -2
- package/plugins/forgedock-splash/.claude-plugin/plugin.json +10 -0
- package/plugins/forgedock-splash/README.md +27 -0
- package/plugins/forgedock-splash/hooks/hooks.json +1 -0
- package/plugins/forgedock-splash/hooks/register.tsx +74 -0
- package/plugins/forgedock-splash/hooks/scene.ts +222 -0
- package/plugins/forgedock-splash/types/index.d.ts +10 -0
- package/scripts/bench-adversarial.mjs +216 -0
- package/scripts/bench-feature.mjs +170 -0
- package/scripts/bench-lightlane.mjs +2 -2
- package/scripts/bootstrap-create.mjs +2 -2
- package/scripts/bootstrap-validate.mjs +35 -2
- package/scripts/check-spec-size.sh +4 -3
- package/scripts/check-spec-size.test.sh +3 -0
- package/scripts/plan-validate-live.mjs +40 -6
- package/scripts/review-pr-staging-scope.test.sh +1 -1
- package/scripts/review-staging-post.sh +23 -0
- package/scripts/review-staging-post.test.sh +8 -0
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
|
+
// Re-plan loop (#5342): a `design-invalidated` block files one spike-amendment issue, holds the affected open siblings
|
|
4
|
+
// behind it with the existing `**Depends on**` edge, and `replan apply` re-evaluates each child once the amendment merged.
|
|
5
|
+
// Pure and deterministic: no LLM call. The amendment lane writes the per-child dispositions; the engine only applies them.
|
|
6
|
+
import { parentOf } from "./context.mjs";
|
|
7
|
+
import { selectChildren, readChildList } from "./autochildren.mjs";
|
|
8
|
+
|
|
9
|
+
export const REPLAN_MARKER = "FORGE:REPLAN";
|
|
10
|
+
export const CHILD_DISPOSITIONS = Object.freeze(["unchanged", "re-scoped", "dropped"]);
|
|
11
|
+
export const DISPOSITIONS_TAG = "forge-replan-dispositions";
|
|
12
|
+
const TEXT_MAX = 600;
|
|
13
|
+
|
|
14
|
+
const text = (v, max = TEXT_MAX) => (typeof v === "string" ? v.replace(/\s+/g, " ").trim().slice(0, max) : "");
|
|
15
|
+
const issueNo = (v) => { const n = Number(String(v ?? "").replace(/^#/, "")); return Number.isSafeInteger(n) && n > 0 ? n : null; };
|
|
16
|
+
const strList = (v) => [...new Set((Array.isArray(v) ? v : []).filter((x) => typeof x === "string").map((x) => x.trim().replace(/^\.?\/+/, "")).filter(Boolean))];
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* The typed `design-invalidated` block: {decision, why} required; `epic` (the epic or tracker to amend), `supersedes` (a
|
|
20
|
+
* decision-register id), `paths` (files of the invalidated interface) optional. Null when decision or why is missing.
|
|
21
|
+
*/
|
|
22
|
+
export function normaliseInvalidation(block, issue = null) {
|
|
23
|
+
const decision = text(block?.decision), why = text(block?.why);
|
|
24
|
+
if (!decision || !why) return null;
|
|
25
|
+
const epic = issueNo(block?.epic);
|
|
26
|
+
return { decision, why, epic: epic && epic !== Number(issue) ? epic : null, supersedes: text(block?.supersedes, 60) || null, paths: strList(block?.paths ?? block?.anchors) };
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** The epic of `issue`: the block's own `epic`, else the `**Parent**: #N` line of the issue body. */
|
|
30
|
+
export const epicOf = (inv, body) => inv?.epic ?? parentOf(body ?? "");
|
|
31
|
+
|
|
32
|
+
/** Hidden record on the amendment issue body, read back to find it again (idempotent filing) and to reach its epic. */
|
|
33
|
+
const recordOf = (body) => {
|
|
34
|
+
const m = new RegExp(`<!--\\s*${REPLAN_MARKER}\\s*(\\{[\\s\\S]*?\\})\\s*-->`).exec(String(body ?? ""));
|
|
35
|
+
if (!m) return null;
|
|
36
|
+
try { const j = JSON.parse(m[1]); return issueNo(j?.epic) ? { epic: issueNo(j.epic), from: issueNo(j.from) } : null; } catch { return null; }
|
|
37
|
+
};
|
|
38
|
+
export const amendmentEpic = (body) => recordOf(body)?.epic ?? null;
|
|
39
|
+
|
|
40
|
+
/** Open amendment issue of `epic` in one open-issue list, or null (a second invalidation joins it, never files another). */
|
|
41
|
+
export function findAmendment(list, epic) {
|
|
42
|
+
const hit = (list ?? []).find((it) => recordOf(it?.body)?.epic === epic);
|
|
43
|
+
return hit ? hit.number : null;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** Open children of `epic` an invalidation touches: every open child, or only those naming one of `paths` when given. `self` is excluded. */
|
|
47
|
+
export function affectedChildren({ list, epic, self = null, paths = [] }) {
|
|
48
|
+
const kids = selectChildren({ list, roots: [epic], skip: self ? [self] : [] });
|
|
49
|
+
if (!paths.length) return kids;
|
|
50
|
+
const by = new Map((list ?? []).map((it) => [it.number, it]));
|
|
51
|
+
return kids.filter((n) => paths.some((p) => String(by.get(n)?.body ?? "").includes(p)));
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export const amendmentTitle = (inv, epic) => `spike amendment: ${inv.decision.slice(0, 80)} no longer holds (epic #${epic})`;
|
|
55
|
+
|
|
56
|
+
/** Body of the amendment issue: the invalidated decision, why, the held children and the disposition block it must produce. */
|
|
57
|
+
export function amendmentBody({ inv, epic, from, children }) {
|
|
58
|
+
const rec = JSON.stringify({ epic, from });
|
|
59
|
+
return [`<!-- ${REPLAN_MARKER} ${rec} -->`, `**Parent**: #${epic}`, "",
|
|
60
|
+
"## Spike amendment", `Invalidated by #${from}: **${inv.decision}**`, "", `Why: ${inv.why}`, ...(inv.supersedes ? ["", `Supersedes decision ${inv.supersedes}.`] : []), "",
|
|
61
|
+
"Update the spike and the epic so the design holds again, and record the replacement decision (`supersedes`). Then give every held child a disposition in one fenced block:", "",
|
|
62
|
+
`\`\`\`${DISPOSITIONS_TAG}`, JSON.stringify({ children: Object.fromEntries(children.map((n) => [n, { disposition: "unchanged" }])) }, null, 2), "```", "",
|
|
63
|
+
`\`${CHILD_DISPOSITIONS.join("`, `")}`.concat("` (a re-scoped child carries `body`, regenerated from the amended design; a dropped child is closed as superseded)."), "",
|
|
64
|
+
"A re-scoped child that is user-visible (a page or UI) must say in its body to run `/design` before build, so the rendered page is judged before the lanes merge (#5330).", "",
|
|
65
|
+
`Held until this merges: ${children.length ? children.map((n) => `#${n}`).join(", ") : "none"}.`].join("\n");
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
const dependsLine = (n) => `**Depends on**: #${n}`;
|
|
69
|
+
const holdRe = (n) => new RegExp(`^[ \\t]*\\*\\*Depends on\\*\\*: #${n}[ \\t]*$\\n?`, "gim");
|
|
70
|
+
|
|
71
|
+
/** `body` with the hold edge on `amendment` added (once). */
|
|
72
|
+
export function holdEdge(body, amendment) {
|
|
73
|
+
const b = String(body ?? "");
|
|
74
|
+
return holdRe(amendment).test(b) ? b : `${b.replace(/\s+$/, "")}\n\n${dependsLine(amendment)}\n`;
|
|
75
|
+
}
|
|
76
|
+
/** `body` without the hold edge on `amendment`. */
|
|
77
|
+
export const releaseEdge = (body, amendment) => String(body ?? "").replace(holdRe(amendment), "").replace(/\s+$/, "") + "\n";
|
|
78
|
+
|
|
79
|
+
/** The last disposition block in the texts (issue body first, then comments): `{children:{N:{disposition, body?}}}` or null. */
|
|
80
|
+
export function parseDispositions(texts) {
|
|
81
|
+
const re = new RegExp(`\`\`\`${DISPOSITIONS_TAG}\\s*\\n([\\s\\S]*?)\`\`\``, "g");
|
|
82
|
+
let last = null;
|
|
83
|
+
for (const t of texts ?? []) for (const m of String(t ?? "").matchAll(re)) { try { last = JSON.parse(m[1]); } catch { /* an unparsable block is skipped */ } }
|
|
84
|
+
return last && typeof last.children === "object" && last.children ? last : null;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Fail closed: every affected child needs one known disposition; a re-scoped child needs its regenerated body.
|
|
89
|
+
* @returns {{ok:boolean, problem?:string, rows?:{n:number, disposition:string, body?:string}[]}}
|
|
90
|
+
*/
|
|
91
|
+
export function validateDispositions(d, affected) {
|
|
92
|
+
const rows = [];
|
|
93
|
+
for (const n of affected) {
|
|
94
|
+
const e = d?.children?.[n] ?? d?.children?.[`#${n}`];
|
|
95
|
+
if (!e || !CHILD_DISPOSITIONS.includes(e.disposition)) return { ok: false, problem: `open child #${n} has no valid disposition (${CHILD_DISPOSITIONS.join(", ")})` };
|
|
96
|
+
if (e.disposition === "re-scoped" && !text(e.body, 100000)) return { ok: false, problem: `re-scoped child #${n} carries no regenerated body` };
|
|
97
|
+
rows.push({ n, disposition: e.disposition, ...(e.disposition === "re-scoped" ? { body: String(e.body) } : {}) });
|
|
98
|
+
}
|
|
99
|
+
return { ok: true, rows };
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** The epic body with each child's checklist line marked once: dropped is checked and struck, re-scoped is annotated. */
|
|
103
|
+
export function renderEpicChecklist(epicBody, rows, amendment) {
|
|
104
|
+
let out = String(epicBody ?? "");
|
|
105
|
+
for (const r of rows) {
|
|
106
|
+
if (r.disposition === "unchanged") continue;
|
|
107
|
+
const re = new RegExp(`^([ \\t]*[-*+][ \\t]+)\\[[ xX]\\]([ \\t]+)(.*#${r.n}\\b.*)$`, "gm");
|
|
108
|
+
out = out.replace(re, (_m, pre, sp, rest) => {
|
|
109
|
+
if (/superseded by #|re-scoped by #/.test(rest)) return `${pre}[${r.disposition === "dropped" ? "x" : " "}]${sp}${rest}`;
|
|
110
|
+
return r.disposition === "dropped" ? `${pre}[x]${sp}~~${rest}~~ (dropped, superseded by #${amendment})` : `${pre}[ ]${sp}${rest} (re-scoped by #${amendment})`;
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
return out;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* Files (or joins) the one amendment issue of `epic` and holds every affected open child, and `self`, behind it.
|
|
118
|
+
* @param {{gh:Function, create:Function, repo:string, issue:number, inv:object, epic:number, milestone?:string|null}} p
|
|
119
|
+
* gh: read, create: write (retried) `gh` runners returning stdout.
|
|
120
|
+
* @returns {Promise<{amendment:number, created:boolean, held:number[]}>}
|
|
121
|
+
*/
|
|
122
|
+
export async function fileAmendment({ gh, create, repo, issue, inv, epic, milestone = null }) {
|
|
123
|
+
const list = await readChildList({ gh, repo });
|
|
124
|
+
const children = affectedChildren({ list, epic, self: issue, paths: inv.paths });
|
|
125
|
+
let amendment = findAmendment(list, epic), created = false;
|
|
126
|
+
if (!amendment) {
|
|
127
|
+
const out = String(await create(["issue", "create", "-R", repo, "--title", amendmentTitle(inv, epic), "--body", amendmentBody({ inv, epic, from: issue, children }), ...(milestone ? ["--milestone", milestone] : [])]));
|
|
128
|
+
amendment = issueNo(/\/issues\/(\d+)/.exec(out)?.[1]);
|
|
129
|
+
if (!amendment) throw new Error(`cannot parse the amendment issue number from: ${out.slice(0, 200)}`);
|
|
130
|
+
created = true;
|
|
131
|
+
}
|
|
132
|
+
const held = [];
|
|
133
|
+
for (const n of [...children, issue]) {
|
|
134
|
+
if (n === amendment) continue;
|
|
135
|
+
const rec = JSON.parse(String(await gh(["issue", "view", String(n), "-R", repo, "--json", "body"])) || "{}");
|
|
136
|
+
const next = holdEdge(rec.body, amendment);
|
|
137
|
+
if (next !== String(rec.body ?? "")) await create(["issue", "edit", String(n), "-R", repo, "--body", next]);
|
|
138
|
+
held.push(n);
|
|
139
|
+
}
|
|
140
|
+
return { amendment, created, held };
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* After the amendment merged: re-evaluate every held open child from the dispositions the amendment lane wrote, release
|
|
145
|
+
* the hold, and rewrite the epic checklist. Nothing is changed unless every affected child has a valid disposition.
|
|
146
|
+
* @returns {Promise<{ok:boolean, problem?:string, rows?:object[]}>}
|
|
147
|
+
*/
|
|
148
|
+
export async function applyReplan({ gh, create, repo, amendment }) {
|
|
149
|
+
const view = JSON.parse(String(await gh(["issue", "view", String(amendment), "-R", repo, "--json", "body,comments"])) || "{}");
|
|
150
|
+
const epic = amendmentEpic(view.body);
|
|
151
|
+
if (!epic) return { ok: false, problem: `#${amendment} is not a spike amendment (no ${REPLAN_MARKER} record)` };
|
|
152
|
+
const d = parseDispositions([view.body, ...(view.comments ?? []).map((c) => c?.body)]);
|
|
153
|
+
if (!d) return { ok: false, problem: `#${amendment} carries no \`${DISPOSITIONS_TAG}\` block` };
|
|
154
|
+
const list = await readChildList({ gh, repo });
|
|
155
|
+
const held = selectChildren({ list, roots: [epic] }).filter((n) => String(list.find((it) => it.number === n)?.body ?? "").includes(dependsLine(amendment)));
|
|
156
|
+
const v = validateDispositions(d, held);
|
|
157
|
+
if (!v.ok) return v;
|
|
158
|
+
for (const r of v.rows) {
|
|
159
|
+
const cur = String(list.find((it) => it.number === r.n)?.body ?? "");
|
|
160
|
+
if (r.disposition === "dropped") {
|
|
161
|
+
await create(["issue", "close", String(r.n), "-R", repo, "--reason", "not planned", "--comment", `Dropped: superseded by the design amendment in #${amendment}.`]);
|
|
162
|
+
continue;
|
|
163
|
+
}
|
|
164
|
+
const base = r.disposition === "re-scoped" ? (parentOf(r.body) ? r.body : `${r.body.replace(/\s+$/, "")}\n\n**Parent**: #${epic}\n`) : cur;
|
|
165
|
+
await create(["issue", "edit", String(r.n), "-R", repo, "--body", releaseEdge(base, amendment)]);
|
|
166
|
+
}
|
|
167
|
+
const ep = JSON.parse(String(await gh(["issue", "view", String(epic), "-R", repo, "--json", "body"])) || "{}");
|
|
168
|
+
const next = renderEpicChecklist(ep.body, v.rows, amendment);
|
|
169
|
+
if (next !== String(ep.body ?? "")) await create(["issue", "edit", String(epic), "-R", repo, "--body", next]);
|
|
170
|
+
return { ok: true, rows: v.rows };
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/** `forgedock replan apply --amendment N --repo owner/repo`. */
|
|
174
|
+
export async function replanFromCli(argv, deps = {}) {
|
|
175
|
+
const arg = (k) => { const i = argv.indexOf(k); return i >= 0 ? argv[i + 1] : null; };
|
|
176
|
+
const usage = "usage: forgedock replan apply --amendment N --repo owner/repo";
|
|
177
|
+
const amendment = issueNo(arg("--amendment")), repo = arg("--repo") ?? deps.repo;
|
|
178
|
+
if (argv[0] !== "apply" || !amendment || !repo) throw new Error(usage);
|
|
179
|
+
const io = deps.io ?? (await import("./effects.mjs")).makeLeanIo({ repo });
|
|
180
|
+
const r = await applyReplan({ gh: (a) => io.gh(a), create: (a) => io.gh(a), repo, amendment });
|
|
181
|
+
if (!r.ok) { process.stderr.write(`replan: ${r.problem}\n`); return 1; }
|
|
182
|
+
for (const x of r.rows) process.stdout.write(`#${x.n}: ${x.disposition}\n`);
|
|
183
|
+
return 0;
|
|
184
|
+
}
|
|
@@ -0,0 +1,110 @@
|
|
|
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 { normaliseInvalidation, epicOf, findAmendment, affectedChildren, amendmentBody, holdEdge, releaseEdge, parseDispositions, validateDispositions, renderEpicChecklist, fileAmendment, applyReplan, DISPOSITIONS_TAG } from "./replan.mjs";
|
|
6
|
+
|
|
7
|
+
const kid = (n, body = "**Parent**: #5\n") => ({ number: n, body, labels: [], author: { login: "o" }, authorAssociation: "OWNER" });
|
|
8
|
+
const inv = normaliseInvalidation({ decision: "replay_store is optional", why: "core loop needs it", epic: 5 }, 7);
|
|
9
|
+
|
|
10
|
+
// A fake gh over an in-memory repo: issue list/view/create/edit/close and the REST association list.
|
|
11
|
+
const repoWorld = (issues) => {
|
|
12
|
+
const w = { issues: new Map(issues.map((i) => [i.number, { ...i }])), calls: [], next: 100 };
|
|
13
|
+
w.gh = async (a) => {
|
|
14
|
+
w.calls.push(a);
|
|
15
|
+
if (a[0] === "issue" && a[1] === "list" && a.includes("--help")) return "JSON FIELDS\n author, body, labels, number\n";
|
|
16
|
+
if (a[0] === "issue" && a[1] === "list") return JSON.stringify([...w.issues.values()].filter((i) => i.state !== "closed").map(({ number, body, labels, author }) => ({ number, body, labels: labels ?? [], author: author ?? { login: "o" } })));
|
|
17
|
+
if (a[0] === "api") return [...w.issues.values()].map((i) => `${i.number}\tOWNER`).join("\n");
|
|
18
|
+
if (a[1] === "view") { const i = w.issues.get(Number(a[2])); return JSON.stringify({ body: i.body, comments: i.comments ?? [] }); }
|
|
19
|
+
if (a[1] === "create") { const n = ++w.next; w.issues.set(n, { number: n, body: a[a.indexOf("--body") + 1], title: a[a.indexOf("--title") + 1] }); return `https://github.com/o/r/issues/${n}\n`; }
|
|
20
|
+
if (a[1] === "edit") { w.issues.get(Number(a[2])).body = a[a.indexOf("--body") + 1]; return ""; }
|
|
21
|
+
if (a[1] === "close") { w.issues.get(Number(a[2])).state = "closed"; return ""; }
|
|
22
|
+
throw new Error(`unexpected gh ${a.join(" ")}`);
|
|
23
|
+
};
|
|
24
|
+
return w;
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
describe("re-plan loop (#5342)", () => {
|
|
28
|
+
it("normaliseInvalidation needs a decision and a why; epic never equals the lane issue", () => {
|
|
29
|
+
assert.equal(normaliseInvalidation({ decision: "x" }, 7), null);
|
|
30
|
+
assert.equal(normaliseInvalidation({ why: "y" }, 7), null);
|
|
31
|
+
assert.equal(normaliseInvalidation({ decision: "x", why: "y", epic: 7 }, 7).epic, null);
|
|
32
|
+
assert.equal(epicOf(normaliseInvalidation({ decision: "x", why: "y" }, 7), "**Parent**: #12\n"), 12);
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
it("hold edge is added once and released cleanly", () => {
|
|
36
|
+
const held = holdEdge("body\n", 100);
|
|
37
|
+
assert.equal(holdEdge(held, 100), held);
|
|
38
|
+
assert.match(held, /^\*\*Depends on\*\*: #100$/m);
|
|
39
|
+
assert.doesNotMatch(releaseEdge(held, 100), /Depends on/);
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
it("affectedChildren: open children of the epic, narrowed by declared paths, never the lane itself", () => {
|
|
43
|
+
const list = [kid(7), kid(8, "**Parent**: #5\nedits src/a.ts"), kid(9, "**Parent**: #5\nedits src/b.ts"), kid(10, "**Parent**: #6\n")];
|
|
44
|
+
assert.deepEqual(affectedChildren({ list, epic: 5, self: 7 }), [8, 9]);
|
|
45
|
+
assert.deepEqual(affectedChildren({ list, epic: 5, self: 7, paths: ["src/a.ts"] }), [8]);
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
it("fileAmendment files one amendment, holds siblings and the lane; a second invalidation joins it", async () => {
|
|
49
|
+
const w = repoWorld([{ number: 7, body: "**Parent**: #5\n" }, { number: 8, body: "**Parent**: #5\n" }, { number: 9, body: "**Parent**: #5\n" }]);
|
|
50
|
+
const f = await fileAmendment({ gh: w.gh, create: w.gh, repo: "o/r", issue: 7, inv, epic: 5 });
|
|
51
|
+
assert.deepEqual([f.created, f.held.sort()], [true, [7, 8, 9]]);
|
|
52
|
+
for (const n of [7, 8, 9]) assert.match(w.issues.get(n).body, new RegExp(`^\\*\\*Depends on\\*\\*: #${f.amendment}$`, "m"));
|
|
53
|
+
assert.equal(findAmendment([...w.issues.values()], 5), f.amendment);
|
|
54
|
+
const again = await fileAmendment({ gh: w.gh, create: w.gh, repo: "o/r", issue: 8, inv, epic: 5 });
|
|
55
|
+
assert.deepEqual([again.created, again.amendment], [false, f.amendment]);
|
|
56
|
+
assert.equal([...w.issues.values()].filter((i) => /spike amendment/.test(i.title ?? "")).length, 1);
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
it("parseDispositions takes the last block; validateDispositions fails closed on a missing or bad one", () => {
|
|
60
|
+
const blk = (o) => `\`\`\`${DISPOSITIONS_TAG}\n${JSON.stringify(o)}\n\`\`\``;
|
|
61
|
+
const d = parseDispositions([blk({ children: { 8: { disposition: "dropped" } } }), blk({ children: { 8: { disposition: "unchanged" } } })]);
|
|
62
|
+
assert.equal(d.children[8].disposition, "unchanged");
|
|
63
|
+
assert.equal(validateDispositions(d, [8, 9]).ok, false);
|
|
64
|
+
assert.equal(validateDispositions({ children: { 8: { disposition: "re-scoped" } } }, [8]).ok, false);
|
|
65
|
+
assert.equal(validateDispositions({ children: { 8: { disposition: "bogus" } } }, [8]).ok, false);
|
|
66
|
+
assert.equal(validateDispositions(d, [8]).ok, true);
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
it("renderEpicChecklist strikes dropped children and annotates re-scoped ones once", () => {
|
|
70
|
+
const rows = [{ n: 8, disposition: "dropped" }, { n: 9, disposition: "re-scoped" }, { n: 10, disposition: "unchanged" }];
|
|
71
|
+
const once = renderEpicChecklist("- [ ] #8 a\n- [ ] #9 b\n- [ ] #10 c\n", rows, 100);
|
|
72
|
+
assert.equal(once, "- [x] ~~#8 a~~ (dropped, superseded by #100)\n- [ ] #9 b (re-scoped by #100)\n- [ ] #10 c\n");
|
|
73
|
+
assert.equal(renderEpicChecklist(once, rows, 100), once);
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
it("applyReplan marks each open child unchanged, re-scoped or dropped, releases the hold and updates the epic", async () => {
|
|
77
|
+
const w = repoWorld([{ number: 5, body: "- [ ] #8 a\n- [ ] #9 b\n- [ ] #10 c\n" }, { number: 8, body: "**Parent**: #5\n" }, { number: 9, body: "**Parent**: #5\n" }, { number: 10, body: "**Parent**: #5\n" }, { number: 99, body: "**Parent**: #5\n" }]);
|
|
78
|
+
w.issues.get(5).labels = [{ name: "epic" }];
|
|
79
|
+
// 5 is the epic; the children sit under it. Hold 8, 9, 10 as fileAmendment would.
|
|
80
|
+
const f = await fileAmendment({ gh: w.gh, create: w.gh, repo: "o/r", issue: 99, inv, epic: 5 });
|
|
81
|
+
w.issues.get(f.amendment).comments = [{ body: `\`\`\`${DISPOSITIONS_TAG}\n${JSON.stringify({ children: { 8: { disposition: "dropped" }, 9: { disposition: "re-scoped", body: "new design for 9" }, 10: { disposition: "unchanged" }, 99: { disposition: "unchanged" } } })}\n\`\`\`` }];
|
|
82
|
+
const r = await applyReplan({ gh: w.gh, create: w.gh, repo: "o/r", amendment: f.amendment });
|
|
83
|
+
assert.equal(r.ok, true);
|
|
84
|
+
assert.equal(w.issues.get(8).state, "closed");
|
|
85
|
+
assert.match(w.issues.get(9).body, /^new design for 9/);
|
|
86
|
+
assert.match(w.issues.get(9).body, /^\*\*Parent\*\*: #5$/m);
|
|
87
|
+
for (const n of [9, 10]) assert.doesNotMatch(w.issues.get(n).body, /Depends on/);
|
|
88
|
+
assert.match(w.issues.get(5).body, /~~#8 a~~ \(dropped, superseded by #/);
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
it("applyReplan changes nothing when a held child has no disposition", async () => {
|
|
92
|
+
const w = repoWorld([{ number: 8, body: "**Parent**: #5\n" }, { number: 9, body: "**Parent**: #5\n" }, { number: 99, body: "**Parent**: #5\n" }]);
|
|
93
|
+
const f = await fileAmendment({ gh: w.gh, create: w.gh, repo: "o/r", issue: 99, inv, epic: 5 });
|
|
94
|
+
w.issues.get(f.amendment).comments = [{ body: `\`\`\`${DISPOSITIONS_TAG}\n${JSON.stringify({ children: { 8: { disposition: "dropped" } } })}\n\`\`\`` }];
|
|
95
|
+
const r = await applyReplan({ gh: w.gh, create: w.gh, repo: "o/r", amendment: f.amendment });
|
|
96
|
+
assert.equal(r.ok, false);
|
|
97
|
+
assert.match(r.problem, /#9/);
|
|
98
|
+
assert.notEqual(w.issues.get(8).state, "closed");
|
|
99
|
+
});
|
|
100
|
+
|
|
101
|
+
it("applyReplan refuses an issue that is not an amendment", async () => {
|
|
102
|
+
const w = repoWorld([{ number: 3, body: "plain" }]);
|
|
103
|
+
assert.equal((await applyReplan({ gh: w.gh, create: w.gh, repo: "o/r", amendment: 3 })).ok, false);
|
|
104
|
+
assert.match(amendmentBody({ inv, epic: 5, from: 7, children: [8] }), /FORGE:REPLAN/);
|
|
105
|
+
});
|
|
106
|
+
|
|
107
|
+
it("amendmentBody routes re-scoped user-visible children to /design before build (#5330)", () => {
|
|
108
|
+
assert.match(amendmentBody({ inv, epic: 5, from: 7, children: [8] }), /user-visible[\s\S]*`\/design`[\s\S]*before build/);
|
|
109
|
+
});
|
|
110
|
+
});
|
package/bin/lean/resume.mjs
CHANGED
|
@@ -11,6 +11,7 @@
|
|
|
11
11
|
import { noComments } from "./render.mjs";
|
|
12
12
|
import { parseFactsComment } from "./facts.mjs";
|
|
13
13
|
import { isTrustedIssueComment as trusted } from "./prefilter.mjs";
|
|
14
|
+
import { bestResults, passedOnHead } from "./validatebest.mjs";
|
|
14
15
|
|
|
15
16
|
export const RESUME_DIGEST_BYTES = 2048;
|
|
16
17
|
const LINE_MAX = 200;
|
|
@@ -33,10 +34,9 @@ const recordLine = (body) => one(noComments(String(body ?? "")).split("\n").map(
|
|
|
33
34
|
* branch's changed files, `lane` the base branch. The text never exceeds `maxBytes` (UTF-8): whole lines are dropped from
|
|
34
35
|
* the end, so the end reason and validate results (first) survive longest.
|
|
35
36
|
*/
|
|
36
|
-
export function buildResumeDigest({ state = null, comments = [], contract = null, files = [], lane = "", maxBytes = RESUME_DIGEST_BYTES } = {}) {
|
|
37
|
+
export function buildResumeDigest({ state = null, comments = [], contract = null, files = [], lane = "", head: laneHead = "", maxBytes = RESUME_DIGEST_BYTES } = {}) {
|
|
37
38
|
try {
|
|
38
39
|
const tc = (Array.isArray(comments) ? comments : []).filter(trusted);
|
|
39
|
-
const facts = [...tc].reverse().map((c) => parseFactsComment(c?.body)).find(Boolean) ?? null;
|
|
40
40
|
const last = [...tc].reverse().find((c) => ["NEEDS_HUMAN", "FIX_CI"].includes(markerOf(c?.body)));
|
|
41
41
|
const validate = Array.isArray(contract?.validate) ? contract.validate : [];
|
|
42
42
|
const idOf = (cmd) => validate.find((v) => one(v?.command) === cmd)?.id ?? null;
|
|
@@ -46,13 +46,15 @@ export function buildResumeDigest({ state = null, comments = [], contract = null
|
|
|
46
46
|
const fails = Array.isArray(state?.failureClasses) ? [...new Set(state.failureClasses.map(code).filter(Boolean))].sort().slice(0, 5) : [];
|
|
47
47
|
const why = last ? `FORGE:${markerOf(last.body)}: ${recordLine(last.body)}` : "";
|
|
48
48
|
if (reason || why) sections.push(["How the last run ended:", ...(reason ? [`- ${reason}${tcode && tcode !== "unclassified" ? ` (${tcode})` : ""}${fails.length ? `; failures ${fails.join(", ")}` : ""}`] : []), ...(why ? [`- ${why}`] : [])]);
|
|
49
|
-
|
|
50
|
-
|
|
49
|
+
// #5331: the best result per validate id over every trusted record, not the newest record alone; a tool-missing row never replaces a pass
|
|
50
|
+
const rows = [...tc].map((c) => parseFactsComment(c?.body)).filter(Boolean).flatMap((f) => f.baselines.map((b) => ({ id: idOf(b.command), command: b.command, exit: b.exit, head: b.head })));
|
|
51
|
+
const base = bestResults(rows);
|
|
52
|
+
if (base.length) sections.push(["Validate results of the last run (command: exit):", ...base.map((b) => `- ${b.id ? `${one(b.id, 20)} ` : ""}\`${b.command.replace(/`/g, "'")}\`: exit ${b.exit}${b.exit === 0 ? (passedOnHead(b, laneHead) ? " (already passed: do not re-run unless you changed what it covers)" : "") : " (failing)"}`)]);
|
|
51
53
|
const reqs = (Array.isArray(contract?.requirements) ? contract.requirements : []).filter((r) => r?.disposition === "deliver");
|
|
52
54
|
if (reqs.length) sections.push(["Requirements to deliver (frozen contract); verify each against the branch and finish what is missing:", ...reqs.map((r) => `- ${one(r.id, 20)}: ${one(r.quote, 160)}`)]);
|
|
53
55
|
const changed = (Array.isArray(files) ? files : []).map((f) => one(f)).filter(Boolean);
|
|
54
56
|
if (changed.length) sections.push([`Files changed on the branch (vs ${one(lane) || "base"}):`, ...changed.slice(0, LIST_MAX).map((f) => `- ${f}`), ...(changed.length > LIST_MAX ? [`- … ${changed.length - LIST_MAX} more`] : [])]);
|
|
55
|
-
const none = { text: "", files: 0, validates: 0, reason: null };
|
|
57
|
+
const none = { text: "", files: 0, validates: 0, reason: null, passes: [] };
|
|
56
58
|
if (!sections.length) return none;
|
|
57
59
|
|
|
58
60
|
const head = "\n\nResume digest of the last run on this branch (engine facts, not issue text):";
|
|
@@ -62,6 +64,6 @@ export function buildResumeDigest({ state = null, comments = [], contract = null
|
|
|
62
64
|
while (lines.length && size(lines) > maxBytes) lines.pop();
|
|
63
65
|
while (lines.length && lines[lines.length - 1] === "") lines.pop();
|
|
64
66
|
if (!lines.length || size(lines) > maxBytes) return none;
|
|
65
|
-
return { text: [head, ...lines, tail].join("\n"), files: changed.length, validates: base.length, reason };
|
|
66
|
-
} catch { return { text: "", files: 0, validates: 0, reason: null }; }
|
|
67
|
+
return { text: [head, ...lines, tail].join("\n"), files: changed.length, validates: base.length, reason, passes: base.filter((b) => b.id && passedOnHead(b, laneHead)).map((b) => ({ id: b.id, command: b.command, head: b.head })) };
|
|
68
|
+
} catch { return { text: "", files: 0, validates: 0, reason: null, passes: [] }; }
|
|
67
69
|
}
|
package/bin/lean/resume.test.mjs
CHANGED
|
@@ -81,4 +81,20 @@ describe("#4467: App comments in gh issue view shape", () => {
|
|
|
81
81
|
assert.ok(buildResumeDigest({ state, comments: [ghShape("rapiercraft-forgedock")] }).text.includes("- FORGE:NEEDS_HUMAN: CI red on lint"));
|
|
82
82
|
assert.ok(!buildResumeDigest({ state, comments: [ghShape("someone")] }).text.includes("FORGE:NEEDS_HUMAN"));
|
|
83
83
|
});
|
|
84
|
+
it("keeps the best result per validate id: a later tool-missing row never replaces a pass (#5331)", () => {
|
|
85
|
+
const hf = (validation) => `<!-- ${FACTS_MARKER} -->\n${renderFactsRecord(normaliseFacts({ validation }, { files: ["src/a.ts"], head: "abc1234" }))}`;
|
|
86
|
+
const comments = [
|
|
87
|
+
{ body: hf([{ command: "npm run lint", exit: 0 }]), ...BOT },
|
|
88
|
+
{ body: hf([{ command: "npm run lint", exit: 127 }, { command: "npm test -- a.test.ts", exit: 1 }]), ...BOT },
|
|
89
|
+
];
|
|
90
|
+
const d = buildResumeDigest({ comments, contract: CONTRACT, head: "abc1234" });
|
|
91
|
+
assert.match(d.text, /V2 `npm run lint`: exit 0 \(already passed/);
|
|
92
|
+
assert.doesNotMatch(d.text, /exit 127/);
|
|
93
|
+
assert.match(d.text, /V1 `npm test -- a.test.ts`: exit 1 \(failing\)/);
|
|
94
|
+
assert.deepEqual(d.passes, [{ id: "V2", command: "npm run lint", head: "abc1234" }]);
|
|
95
|
+
// a different head, or a record with no head, is not "the same head": nothing is claimed or carried
|
|
96
|
+
assert.deepEqual(buildResumeDigest({ comments, contract: CONTRACT, head: "fff0000" }).passes, []);
|
|
97
|
+
assert.deepEqual(buildResumeDigest({ comments: COMMENTS, contract: CONTRACT, head: "abc1234" }).passes, []);
|
|
98
|
+
assert.doesNotMatch(buildResumeDigest({ comments: COMMENTS, contract: CONTRACT, head: "abc1234" }).text, /already passed/);
|
|
99
|
+
});
|
|
84
100
|
});
|
package/bin/lean/schedd.mjs
CHANGED
|
@@ -49,6 +49,7 @@ import { createHash } from "node:crypto";
|
|
|
49
49
|
import { join, resolve } from "node:path";
|
|
50
50
|
import { fileURLToPath } from "node:url";
|
|
51
51
|
import { schedDir, pidAlive } from "./sched.mjs";
|
|
52
|
+
import { DEFAULT_STALL_MIN, FIRST_HOUR_FILE, FIRST_HOUR_MIN, evaluateDispatchStall, firstHourReport, recordStallAlert, writeFirstHour } from "./batch-health.mjs";
|
|
52
53
|
import { HEARTBEAT_MS, writeHeartbeat, clearHeartbeat } from "./schedd-health.mjs";
|
|
53
54
|
import { batchRoot, listBatches, openBatch, SECRET_ENV } from "./batch.mjs";
|
|
54
55
|
import { applySetExecution } from "./live-execution.mjs";
|
|
@@ -153,7 +154,7 @@ function takeLock(lock, pid, alive) {
|
|
|
153
154
|
*/
|
|
154
155
|
export async function startDaemon({ dir = schedDir(), runBatch, idleMs = Number(process.env.FORGEDOCK_SCHEDD_IDLE_MS) || IDLE_MS,
|
|
155
156
|
root = batchRoot(), log = (m) => console.log(m), pid = process.pid, alive = pidAlive, resumeOnStart = true, stopMs = STOP_MS,
|
|
156
|
-
lockCheckMs = LOCK_CHECK_MS, admitMs = Number(process.env.FORGEDOCK_SCHEDD_ADMIT_MS) || ADMIT_MS, lagMs = LAG_MS, due = null, dueMs = Number(process.env.FORGEDOCK_SCHEDD_DUE_MS) || DUE_MS, preflight = null,
|
|
157
|
+
lockCheckMs = LOCK_CHECK_MS, admitMs = Number(process.env.FORGEDOCK_SCHEDD_ADMIT_MS) || ADMIT_MS, lagMs = LAG_MS, stallCheckMs = Number(process.env.FORGEDOCK_SCHEDD_STALL_CHECK_MS) || 60_000, stallMin = Number(process.env.FORGEDOCK_SCHEDD_STALL_MIN) || DEFAULT_STALL_MIN, due = null, dueMs = Number(process.env.FORGEDOCK_SCHEDD_DUE_MS) || DUE_MS, preflight = null,
|
|
157
158
|
hostLoad = liveOverload(), installedVersion = readInstalledVersion, respawn = undefined } = {}) {
|
|
158
159
|
const p = scheddPaths(dir);
|
|
159
160
|
// #5204: default handover target: a new daemon from the (new) install unless systemd restarts the unit itself
|
|
@@ -390,6 +391,7 @@ export async function startDaemon({ dir = schedDir(), runBatch, idleMs = Number(
|
|
|
390
391
|
clearInterval(idleTimer);
|
|
391
392
|
clearInterval(lockTimer);
|
|
392
393
|
clearInterval(lagTimer);
|
|
394
|
+
clearInterval(stallTimer);
|
|
393
395
|
clearInterval(beatTimer);
|
|
394
396
|
for (const t of rehostTimers) clearTimeout(t);
|
|
395
397
|
if (dueTimer) clearInterval(dueTimer);
|
|
@@ -440,6 +442,37 @@ export async function startDaemon({ dir = schedDir(), runBatch, idleMs = Number(
|
|
|
440
442
|
if (lag >= lagMs && now - lagLogged >= 60_000) { lagLogged = now; log(`schedd: event loop stalled ${Math.round(lag / 1000)}s (host overloaded?)`); }
|
|
441
443
|
}, 1000);
|
|
442
444
|
lagTimer.unref?.();
|
|
445
|
+
// #5314: a batch with ready issues, free lanes and no dispatch for `stallMin` is re-hosted once per ready set, else one needs-you
|
|
446
|
+
// alert is recorded (health.json, status, sched show); every batch also gets its first-hour report once, without operator action.
|
|
447
|
+
const rehostedStall = new Map();
|
|
448
|
+
const watchBatches = () => {
|
|
449
|
+
if (closing) return;
|
|
450
|
+
const now = Date.now();
|
|
451
|
+
for (const id of listBatches(root)) {
|
|
452
|
+
try {
|
|
453
|
+
const b = openBatch(root, id), plan = b.readPlan();
|
|
454
|
+
if (!plan?.daemon) continue;
|
|
455
|
+
const reported = !!b.readReport(), cancelled = !!b.readCancel(), state = b.store.load(), created = Date.parse(plan.created ?? "");
|
|
456
|
+
const isHosted = hosted.has(id) || starting.has(id);
|
|
457
|
+
const stall = evaluateDispatchStall(state, { held: b.readHeld(), parallel: b.readParallel(), hosted: isHosted, lastProgressMs: b.lastProgressMs(), now, windowMin: stallMin, cancelled, reported });
|
|
458
|
+
if (Number.isFinite(created) && (reported || now - created >= FIRST_HOUR_MIN * 60_000) && !existsSync(join(b.dir, FIRST_HOUR_FILE)) && now - created < 24 * 3600_000) {
|
|
459
|
+
if (writeFirstHour(b, firstHourReport(state, { batchId: id, now, held: b.readHeld(), stall }))) log(`schedd: first-hour report written for batch ${id}`);
|
|
460
|
+
}
|
|
461
|
+
if (!stall) continue;
|
|
462
|
+
const sig = stall.ready.join(",");
|
|
463
|
+
if (!isHosted && rehostedStall.get(id) !== sig) {
|
|
464
|
+
rehostedStall.set(id, sig);
|
|
465
|
+
log(`schedd: re-hosting batch ${id} (${stall.detail})`);
|
|
466
|
+
const started = host({ argv: ["--resume", id], cwd: process.cwd(), env: {}, keepBreaker: true });
|
|
467
|
+
starting.set(id, started);
|
|
468
|
+
started.catch((e) => { log(`schedd: re-host ${id} failed: ${e?.message ?? e}`); recordStallAlert(b, stall); }).finally(() => starting.delete(id));
|
|
469
|
+
} else if (recordStallAlert(b, stall)) log(`schedd: batch ${id} needs you: ${stall.detail}`);
|
|
470
|
+
} catch { /* advisory: one unreadable batch never stops the watchdog */ }
|
|
471
|
+
}
|
|
472
|
+
};
|
|
473
|
+
const stallTimer = setInterval(watchBatches, stallCheckMs);
|
|
474
|
+
stallTimer.unref?.();
|
|
475
|
+
|
|
443
476
|
// #4627: windowed post-deploy checks. One run at a time; a failure is logged and never stops the daemon.
|
|
444
477
|
let dueRunning = false;
|
|
445
478
|
const dueTimer = due ? setInterval(async () => {
|
package/bin/lean/schedd.test.mjs
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
import { describe, it } from "node:test";
|
|
4
4
|
import assert from "node:assert/strict";
|
|
5
5
|
import { spawn } from "node:child_process";
|
|
6
|
-
import { closeSync, existsSync, mkdirSync, openSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
6
|
+
import { closeSync, existsSync, mkdirSync, openSync, readFileSync, rmSync, utimesSync, writeFileSync } from "node:fs";
|
|
7
7
|
import { homedir, tmpdir } from "node:os";
|
|
8
8
|
import { join } from "node:path";
|
|
9
9
|
import { tmpDir } from "../tests/_tmp.mjs";
|
|
@@ -464,6 +464,26 @@ await orchestrateFromCli(["1", "2", "--parallel", "2", "--repo", "o/r", "--no-pr
|
|
|
464
464
|
}
|
|
465
465
|
});
|
|
466
466
|
|
|
467
|
+
it("#5314: a batch whose runner is gone with ready issues pending is re-hosted by the watchdog; a runner that dispatches nothing raises one alert", async () => {
|
|
468
|
+
const dir = tmpDir("schedd-stall-"), root = join(dir, "batches"), id = "b20261104-052317-5314";
|
|
469
|
+
const calls = [];
|
|
470
|
+
const b = openBatch(root, id);
|
|
471
|
+
b.writePlan({ daemon: true, repo: "o/r", created: new Date(Date.now() - 90 * 60000).toISOString() });
|
|
472
|
+
b.store.save({ v: 1, order: [1], results: {}, running: {}, pending: [1], parallel: 2 });
|
|
473
|
+
const old = new Date(Date.now() - 30 * 60000);
|
|
474
|
+
utimesSync(join(b.dir, "state.json"), old, old);
|
|
475
|
+
const runBatch = async ({ argv, sink }) => { calls.push(argv); sink.batch({ id, dir: b.dir }); return await new Promise(() => {}); }; // a wedged runner
|
|
476
|
+
const d = await startDaemon({ dir, root, runBatch, log: () => {}, resumeOnStart: false, stallCheckMs: 50, stallMin: 10 });
|
|
477
|
+
try {
|
|
478
|
+
await until(() => calls.length === 1, 8000);
|
|
479
|
+
assert.deepEqual(calls[0], ["--resume", id], "re-hosted without operator action");
|
|
480
|
+
await until(() => existsSync(join(b.dir, "first-hour.json")), 8000);
|
|
481
|
+
utimesSync(join(b.dir, "state.json"), old, old); // the wedged runner still dispatched nothing
|
|
482
|
+
await until(() => existsSync(join(b.dir, "health.json")) && readFileSync(join(b.dir, "health.json"), "utf8").includes("dispatch-stalled"), 8000);
|
|
483
|
+
assert.equal(calls.length, 1, "a hosted runner is not re-hosted again");
|
|
484
|
+
} finally { await d.close(); }
|
|
485
|
+
});
|
|
486
|
+
|
|
467
487
|
it("#4917: a resume that leaves the waiting issue unadmitted (breaker tripped, retry-at passed) is not re-hosted again", async () => {
|
|
468
488
|
const dir = tmpDir("schedd-rehost-loop-"), root = join(dir, "batches"), id = "b20261031-000000-4918";
|
|
469
489
|
const calls = [];
|
package/bin/lean/selfreview.mjs
CHANGED
|
@@ -7,6 +7,9 @@
|
|
|
7
7
|
* SELF_REVIEW_DISAGREED). Never a failure, never a runner call. Pure: no I/O.
|
|
8
8
|
*/
|
|
9
9
|
|
|
10
|
+
import { precheck, authorizationOf, applyAmendments } from "./conformance.mjs";
|
|
11
|
+
import { pathDomains, riskClassOf } from "./review-trigger.mjs";
|
|
12
|
+
|
|
10
13
|
const text = (v) => (v === null || v === undefined ? "" : String(v)).trim();
|
|
11
14
|
|
|
12
15
|
/**
|
|
@@ -35,3 +38,94 @@ export function compareSelfReview(self, decision) {
|
|
|
35
38
|
const allYes = self.no.length === 0;
|
|
36
39
|
return { agreed: allYes === (reviewer === "conforms"), reviewer, self_no: self.no };
|
|
37
40
|
}
|
|
41
|
+
|
|
42
|
+
// ---- #5345 clean-first-review: the reviewer's deterministic checks, run by the builder before it finishes ----
|
|
43
|
+
/** (selfReviewFindings, firstReviewRecord, sectionOfKind, FINDING_PITFALLS: precheck() subset + preserve-touch; the first-round record riding on RUN_TERMINAL) */
|
|
44
|
+
/** The contract section a finding kind traces to (measures which section of the plan first-round findings map to). */
|
|
45
|
+
export const KIND_SECTION = Object.freeze({
|
|
46
|
+
"conformance.omission": "requirements",
|
|
47
|
+
"conformance.unimplemented": "requirements",
|
|
48
|
+
"conformance.untracked_deferral": "requirements",
|
|
49
|
+
"conformance.unjustified_deferral": "requirements",
|
|
50
|
+
"conformance.scope_creep": "deliverables",
|
|
51
|
+
"conformance.preserve_violated": "preserve",
|
|
52
|
+
"conformance.regression": "validate",
|
|
53
|
+
"review.incomplete": "reviewer",
|
|
54
|
+
});
|
|
55
|
+
export const sectionOfKind = (code) => KIND_SECTION[code] ?? "other";
|
|
56
|
+
|
|
57
|
+
/** Builder pitfall per recurring finding kind (the three that are 80% of first-round findings). */
|
|
58
|
+
export const FINDING_PITFALLS = Object.freeze({
|
|
59
|
+
"conformance.omission": "Map every issue requirement to the diff line that delivers it; omission is the top finding.",
|
|
60
|
+
"conformance.scope_creep": "Edit only contract-listed files (tests aside); amend a needed extra file in first.",
|
|
61
|
+
"conformance.preserve_violated": "Re-check each preserve path is unchanged; an edited one needs a covering deliverable.",
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
/** R5: the planner rule per contract section the first-round findings trace to (rendered into the plan prompt). */
|
|
65
|
+
export const PLANNER_TIGHTENING = Object.freeze({
|
|
66
|
+
requirements: "One requirement per sentence or clause, each with a deliverable and a validate (omission is the top finding).",
|
|
67
|
+
deliverables: "List every changed file, tests included (scope_creep flags unnamed ones).",
|
|
68
|
+
preserve: "Give each preserve row a file path; it cannot be checked without one.",
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
const PATH_RE = /[\w@.-]+(?:\/[\w@.*-]+)+\.\w+|[\w@.-]+\/[\w@.*-]+\/?/g;
|
|
72
|
+
const NEEDS_RESULT = new Set(["requirement_unimplemented", "untracked_deferral"]);
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* The deterministic conformance findings of the current tree: [{code, kind, detail, section}]. Validate commands are not
|
|
76
|
+
* judged here (`forgedock check` runs them); requirement statuses are judged only when the builder reported any.
|
|
77
|
+
*/
|
|
78
|
+
export function selfReviewFindings({ contract: frozen, result = null, changedFiles = [], ignore = [".forge-lean/"], hotspots = null }) {
|
|
79
|
+
if (!frozen || typeof frozen !== "object") return [];
|
|
80
|
+
// the builder's typed amendments (add-deliverable, ...) are part of the contract the gate judges; problems are the engine's to report
|
|
81
|
+
const contract = Array.isArray(result?.amendments) && result.amendments.length ? applyAmendments(frozen, result.amendments).contract : frozen;
|
|
82
|
+
const reported = Array.isArray(result?.requirements);
|
|
83
|
+
const pc = precheck({ contract: { ...contract, validate: [] }, result: reported ? result : null, changedFiles, ignore, hotspots, ciVerified: true });
|
|
84
|
+
// no result.json yet: the builder cannot have amended an extra file in, so scope_creep is not judged until one exists
|
|
85
|
+
const out = pc.failures.filter((f) => (reported || !NEEDS_RESULT.has(f.kind)) && (result || f.code !== "conformance.scope_creep")).map((f) => ({ code: f.code, kind: f.kind ?? null, detail: f.detail, section: sectionOfKind(f.code) }));
|
|
86
|
+
out.push(...preserveTouched(contract, changedFiles, ignore));
|
|
87
|
+
return out;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** A preserve item names a path the diff changed that no deliverable authorizes: the touch can only be a violation. */
|
|
91
|
+
export function preserveTouched(contract, changedFiles = [], ignore = []) {
|
|
92
|
+
const out = [];
|
|
93
|
+
for (const p of contract?.preserve ?? []) {
|
|
94
|
+
const named = [...String(p?.what ?? "").matchAll(PATH_RE)].map((m) => m[0].replace(/[.,;:)]+$/, ""));
|
|
95
|
+
for (const f of changedFiles) {
|
|
96
|
+
if (ignore.some((x) => f.startsWith(x)) || authorizationOf(contract, f)) continue;
|
|
97
|
+
if (named.some((n) => n === f || (n.endsWith("/") && f.startsWith(n)))) out.push({ code: "conformance.preserve_violated", kind: "preserve_touched", detail: `${p.id}: ${f} is preserved and no deliverable authorizes changing it`, section: "preserve" });
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
return out;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** The change type of a lane from its issue labels: bug|feature|chore|docs|other. */
|
|
104
|
+
export function changeTypeOf(labels = []) {
|
|
105
|
+
const names = (Array.isArray(labels) ? labels : []).map((l) => String(l?.name ?? l).toLowerCase());
|
|
106
|
+
for (const t of ["bug", "feature", "chore", "docs"]) if (names.some((n) => n === t || n === `type:${t}`)) return t;
|
|
107
|
+
return "other";
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** `domain:<d>` / `risk:<class>` surfaces a lane's files touch (the same names `stats --conformance-outcomes` uses). */
|
|
111
|
+
export function surfacesOf(files = []) {
|
|
112
|
+
const domains = pathDomains(files) ?? [];
|
|
113
|
+
return [...new Set([...domains.map((d) => `domain:${d}`), ...files.map(riskClassOf).filter(Boolean).map((c) => `risk:${c}`)])].sort();
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* The first-round record riding on RUN_TERMINAL: the first gate judgement (`rounds[0]`: {state, failures: [code]}), its
|
|
118
|
+
* failure kinds, how many gate rounds the lane took, and whether the reviewer's own first reply (`firstReply`, a decide()
|
|
119
|
+
* state) was incomplete. null when no review ran.
|
|
120
|
+
*/
|
|
121
|
+
export function firstReviewRecord({ rounds = [], firstReply = null, labels = [], files = [] } = {}) {
|
|
122
|
+
if (!rounds.length) return null;
|
|
123
|
+
const first = rounds[0];
|
|
124
|
+
const kinds = [...new Set((first.failures ?? []).filter(Boolean))].sort();
|
|
125
|
+
return { state: first.state, kinds, rounds: rounds.length, clean: first.state === "conforms", incomplete: firstReply === "review.incomplete" || first.state === "review.incomplete", type: changeTypeOf(labels), surfaces: surfacesOf(files) };
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** The failures a builder's own red `forgedock check` record holds (the review section), as resume failures; [] when none. */
|
|
129
|
+
export function selfCheckFailures(record) {
|
|
130
|
+
return (Array.isArray(record?.review) ? record.review : []).filter((f) => f?.code && f?.detail).map((f) => ({ code: f.code, detail: String(f.detail) }));
|
|
131
|
+
}
|