forgedock 1.50.0 → 1.52.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/engine/outcome-codes.mjs +2 -0
- package/bin/engine-cli.mjs +98 -10
- package/bin/forgedock.mjs +40 -2
- package/bin/lean/batch-health.mjs +219 -0
- package/bin/lean/batch-health.test.mjs +156 -0
- package/bin/lean/batch.mjs +3 -3
- package/bin/lean/batch.test.mjs +236 -8
- package/bin/lean/conformance.mjs +66 -12
- package/bin/lean/conformance.test.mjs +55 -3
- package/bin/lean/context.mjs +35 -19
- package/bin/lean/context.test.mjs +26 -1
- package/bin/lean/credentials.mjs +18 -0
- package/bin/lean/effects.mjs +3 -3
- package/bin/lean/execution.mjs +11 -6
- package/bin/lean/execution.test.mjs +28 -0
- package/bin/lean/fixclosereasons.mjs +52 -0
- package/bin/lean/fixclosereasons.test.mjs +64 -0
- package/bin/lean/heavy.mjs +6 -3
- package/bin/lean/hostload.mjs +78 -0
- package/bin/lean/hostload.test.mjs +117 -0
- package/bin/lean/hotspots-remote.e2e.test.mjs +71 -0
- package/bin/lean/lean.mjs +34 -19
- package/bin/lean/lean.test.mjs +87 -14
- package/bin/lean/orchestrate-blocked.test.mjs +47 -0
- package/bin/lean/orchestrate.mjs +138 -12
- package/bin/lean/prefilter.mjs +4 -3
- package/bin/lean/prefilter.test.mjs +5 -4
- package/bin/lean/prompts.mjs +4 -2
- package/bin/lean/recovery.test.mjs +5 -5
- package/bin/lean/sandbox-provider.contract.test.mjs +15 -1
- package/bin/lean/schedd.mjs +8 -3
- package/bin/lean/schedd.test.mjs +21 -0
- package/bin/pool/agent.mjs +3 -1
- package/bin/pool/router.mjs +74 -8
- package/bin/review-staging.mjs +2 -0
- package/bin/runner.mjs +24 -0
- package/commands/review-pr-staging.md +2 -2
- package/docs/CONFIG.md +41 -2
- package/docs/OUTCOME-CODES.md +2 -1
- package/package.json +1 -1
- package/pool/README.md +2 -0
- package/pool/image/cs-cred +8 -1
- package/pool/install/install-agent.ps1 +6 -2
- package/scripts/file-deferred-followups.sh +23 -9
- package/scripts/file-deferred-followups.test.sh +34 -1
- package/scripts/hotspots.sh +12 -8
- package/scripts/hotspots.test.sh +22 -0
- package/scripts/prior-attempts.test.mjs +1 -1
- package/scripts/review-staging-post.sh +70 -25
- package/scripts/review-staging-post.test.sh +40 -8
package/bin/lean/conformance.mjs
CHANGED
|
@@ -73,6 +73,32 @@ export function inIssue(quote, issueText) {
|
|
|
73
73
|
if (q.length < 3) return false;
|
|
74
74
|
return String(issueText ?? "").split("\n").some((l) => norm(l.replace(ITEM_PREFIX_RE, "")) === q);
|
|
75
75
|
}
|
|
76
|
+
/** #5164: the issue's list or checklist item lines (item marker stripped), or every non-empty line when it has none. */
|
|
77
|
+
export function criterionLines(issueText) {
|
|
78
|
+
const lines = String(noComments(String(issueText ?? ""))).split("\n");
|
|
79
|
+
const items = lines.filter((l) => /^\s*(?:[-*+]\s+|\d+[.)]\s+)/.test(l)).map((l) => l.replace(ITEM_PREFIX_RE, "").trim()).filter((l) => norm(l));
|
|
80
|
+
return items.length ? items : lines.map((l) => l.trim()).filter((l) => norm(l));
|
|
81
|
+
}
|
|
82
|
+
/** #5164: norm() plus what a reviewer retyping a criterion slips on: `#N` reference digits, trailing punctuation, a plural `s`. */
|
|
83
|
+
const loose = (s) => norm(String(s ?? "").replace(/#\d+/g, "#")).replace(/[\s.,;:!?)\]]+$/, "").replace(/\b([a-z]{3,})s\b/g, "$1");
|
|
84
|
+
const MATCH_MIN = 0.8;
|
|
85
|
+
/**
|
|
86
|
+
* #5164: the issue's exact criterion line a near-verbatim quote stands for, or null. After loose normalisation the quote is a
|
|
87
|
+
* prefix covering at least 80% of exactly one line, or else at least 80% of its words are in exactly one line (no ties).
|
|
88
|
+
*/
|
|
89
|
+
export function matchCriterion(quote, issueText) {
|
|
90
|
+
const q = loose(quote);
|
|
91
|
+
if (q.length < MIN_QUOTE_CHARS) return null;
|
|
92
|
+
const lines = criterionLines(issueText).map((raw) => ({ raw, l: loose(raw) }));
|
|
93
|
+
const prefix = lines.filter(({ l }) => l.startsWith(q) && q.length >= MATCH_MIN * l.length);
|
|
94
|
+
if (prefix.length === 1) return prefix[0].raw;
|
|
95
|
+
if (prefix.length > 1) return null;
|
|
96
|
+
const qw = [...new Set(q.match(WORD_RE) ?? [])];
|
|
97
|
+
if (qw.length < 3) return null;
|
|
98
|
+
const hits = lines.filter(({ l }) => { const lw = new Set(l.match(WORD_RE) ?? []); return qw.filter((w) => lw.has(w)).length / qw.length >= MATCH_MIN; });
|
|
99
|
+
return hits.length === 1 ? hits[0].raw : null;
|
|
100
|
+
}
|
|
101
|
+
const MISQUOTE_PREFIX = "issue_coverage quote is not verbatim from the issue";
|
|
76
102
|
// Scan-based (not a one-pass regex), so nested or unclosed markers cannot survive into the scope hash.
|
|
77
103
|
const stripHtmlComments = (s) => noComments(s).replace(/\r\n/g, "\n").trim();
|
|
78
104
|
/**
|
|
@@ -273,13 +299,17 @@ const MOCKED_RE = new RegExp(String.raw`\b${MOCKED_TERM}\b`, "i");
|
|
|
273
299
|
// #5116: a negated mock ("do not mock", "no stubs") or a fake clock is not a substitute for the e2e check.
|
|
274
300
|
const NEG_MOCK_RE = /\b(?:do(?:es)? not|don't|never|no|not|without)\s+(?:use\s+|any\s+)?(?:mock\w*|stub\w*|fake\w*)/gi;
|
|
275
301
|
// #5130: a negated weakener ("do not skip the e2e suite", "e2e tests are not replaced") keeps the e2e check.
|
|
276
|
-
const
|
|
302
|
+
const NEG_LEAD = String.raw`(?:be\s+|been\s+|being\s+|(?:going|planning|intending|about|trying)\s+to\s+|intend\w*\s+to\s+)?`;
|
|
303
|
+
const NEG_DROP_RE = new RegExp(String.raw`\b(?:do(?:es)? not|don't|won't|never|not)\s+${NEG_LEAD}(?:skip|drop|replac|swap|downgrad)\w*`, "gi");
|
|
304
|
+
// A negated omission ("will not forget to add the e2e test") is a double negative: the e2e check stays.
|
|
305
|
+
const NEG_OMIT_RE = new RegExp(String.raw`\b(?:do(?:es)? not|don't|won't|never|not)\s+${NEG_LEAD}(?:forget|fail|omit|neglect)\w*`, "gi");
|
|
277
306
|
const FAKE_CLOCK_RE = /\bfake[- ](?:timers?|clocks?)\b/gi;
|
|
278
307
|
// A weakener governs the e2e term only within a few words and the same clause (no . or ; between them).
|
|
279
308
|
const GAP = String.raw`(?:[\s,]+\w+){0,5}?[\s,]+`;
|
|
280
|
-
// #5145:
|
|
281
|
-
|
|
282
|
-
const
|
|
309
|
+
// #5145/#5157: only the determiner "no" ("no new fixtures needed for e2e") stops at a preposition, since it negates a noun. not/without/never
|
|
310
|
+
// negate the verb that governs e2e ("not need to run e2e", "not with e2e") and "no need/reason/point/requirement" negates the action; all keep the wide GAP.
|
|
311
|
+
const NEG_GAP = String.raw`(?:[\s,]+(?!(?:for|of|in|on|at|by|with|from|via)\b)\w+){0,5}?[\s,]+`;
|
|
312
|
+
const DROP_BEFORE_RE = new RegExp(String.raw`\b(?:no${NEG_GAP}|(?:not|without|never|no\s+(?:need|reason|point|requirement)|drop(?:ped|s|ping)?|skip(?:ped|s|ping)?|replac\w+|downgrad\w+|swap\w*)${GAP})${E2E_TERM}\b`, "i");
|
|
283
313
|
const DROP_AFTER_RE = new RegExp(String.raw`\b${E2E_TERM}${GAP}(?:replaced|dropped|skipped|swapped|downgraded|unnecessary|(?:not|no longer)\s+(?:needed|required|necessary|run\w*|used|executed))\b`, "i");
|
|
284
314
|
const INSTEAD_OF_RE = new RegExp(String.raw`\b${MOCKED_TERM}[^.;]{0,60}?\b(?:instead of|rather than|in lieu of)\b${GAP}${E2E_TERM}\b`, "i");
|
|
285
315
|
const PROBE_RE = /forge-probe|acceptance[- ]probe/i;
|
|
@@ -296,7 +326,7 @@ export function weakenedE2eDecisions(c) {
|
|
|
296
326
|
return decisions.filter((k) => {
|
|
297
327
|
const choice = String(k?.choice ?? "");
|
|
298
328
|
if (!E2E_WORD_RE.test(choice)) return false;
|
|
299
|
-
const mocked = choice.replace(NEG_MOCK_RE, " ").replace(FAKE_CLOCK_RE, " ").replace(NEG_DROP_RE, " ");
|
|
329
|
+
const mocked = choice.replace(NEG_MOCK_RE, " ").replace(FAKE_CLOCK_RE, " ").replace(NEG_DROP_RE, " ").replace(NEG_OMIT_RE, " ");
|
|
300
330
|
if (!MOCKED_RE.test(mocked) || !(DROP_BEFORE_RE.test(mocked) || DROP_AFTER_RE.test(mocked) || INSTEAD_OF_RE.test(mocked))) return false;
|
|
301
331
|
const own = `${choice} ${k?.justification ?? ""}`;
|
|
302
332
|
return !((PROBE_RE.test(own) && !NEG_PROBE_RE.test(own)) || /forge-probe/i.test(elsewhere(k?.id)));
|
|
@@ -1002,6 +1032,13 @@ const MISSING_PATH_RE = /^[^:]+: evidence path .+ does not exist$/;
|
|
|
1002
1032
|
export function evidencePathOnly(problems = []) {
|
|
1003
1033
|
return problems.length > 0 && problems.every((p) => MISSING_PATH_RE.test(String(p)));
|
|
1004
1034
|
}
|
|
1035
|
+
/**
|
|
1036
|
+
* #5164: true when every problem of an incomplete review is a reviewer slip a targeted re-ask can fix: an evidence path that
|
|
1037
|
+
* did not resolve (#4327) or an issue_coverage misquote. A real coverage gap is never one, so it keeps the two-run limit.
|
|
1038
|
+
*/
|
|
1039
|
+
export function reaskable(problems = []) {
|
|
1040
|
+
return problems.length > 0 && problems.every((p) => MISSING_PATH_RE.test(String(p)) || String(p).startsWith(MISQUOTE_PREFIX));
|
|
1041
|
+
}
|
|
1005
1042
|
const reviewedFiles = (changedFiles, ignore) => changedFiles.filter((x) => !ignore.some((pre) => x.startsWith(pre)));
|
|
1006
1043
|
|
|
1007
1044
|
/**
|
|
@@ -1009,7 +1046,7 @@ const reviewedFiles = (changedFiles, ignore) => changedFiles.filter((x) => !igno
|
|
|
1009
1046
|
* contract's own authorization ("none" when unauthorized, still scope creep), a preserve row per id as "unverified"
|
|
1010
1047
|
* (still preserve_violated), and implemented evidence rewritten to `path:line` with the repo path. Returns a new object.
|
|
1011
1048
|
*/
|
|
1012
|
-
export function fillEngineRows(rv, { contract, changedFiles = [], repoFiles = [], ignore = [] }) {
|
|
1049
|
+
export function fillEngineRows(rv, { contract, changedFiles = [], repoFiles = [], ignore = [], issueText = null }) {
|
|
1013
1050
|
if (!rv || typeof rv !== "object") return rv;
|
|
1014
1051
|
const out = { ...rv };
|
|
1015
1052
|
const scope = Array.isArray(rv.scope) ? [...rv.scope] : [];
|
|
@@ -1018,6 +1055,14 @@ export function fillEngineRows(rv, { contract, changedFiles = [], repoFiles = []
|
|
|
1018
1055
|
const pres = Array.isArray(rv.preserve) ? [...rv.preserve] : [];
|
|
1019
1056
|
for (const c of contract.preserve ?? []) if (!pres.some((x) => x?.id === c.id)) pres.push({ id: c.id, status: "unverified", note: "no row from the reviewer", filled: true });
|
|
1020
1057
|
out.preserve = pres;
|
|
1058
|
+
// #5164: a near-verbatim coverage quote is replaced by the issue's exact criterion line; the original stays as `requoted`
|
|
1059
|
+
if (Array.isArray(rv.issue_coverage) && issueText != null) {
|
|
1060
|
+
out.issue_coverage = rv.issue_coverage.map((c) => {
|
|
1061
|
+
if (!c || typeof c !== "object" || typeof c.quote !== "string" || inIssue(c.quote, issueText)) return c;
|
|
1062
|
+
const line = matchCriterion(c.quote, issueText);
|
|
1063
|
+
return line ? { ...c, quote: line, requoted: c.quote } : c;
|
|
1064
|
+
});
|
|
1065
|
+
}
|
|
1021
1066
|
if (Array.isArray(rv.requirements)) {
|
|
1022
1067
|
out.requirements = rv.requirements.map((r) => {
|
|
1023
1068
|
if (r?.status !== "implemented" && r?.instrumented !== true) return r;
|
|
@@ -1038,7 +1083,10 @@ export function checkCompleteness(rv, { contract, changedFiles, issueText, pathE
|
|
|
1038
1083
|
if (!cov?.length) miss("issue_coverage", "issue_coverage is missing or empty");
|
|
1039
1084
|
for (const c of cov ?? []) {
|
|
1040
1085
|
if (!COVER_STATUS.includes(c?.status)) miss("issue_coverage", `issue_coverage status invalid: ${c?.status}`);
|
|
1041
|
-
if (!inIssue(c?.quote, issueText))
|
|
1086
|
+
if (!inIssue(c?.quote, issueText)) {
|
|
1087
|
+
const near = nearestSpan(c?.quote, criterionLines(issueText).join("\n"));
|
|
1088
|
+
miss("issue_coverage", `${MISQUOTE_PREFIX}: "${String(c?.quote ?? "").slice(0, 60)}"${near ? `; nearest criterion line: "${near}"` : ""}`);
|
|
1089
|
+
}
|
|
1042
1090
|
}
|
|
1043
1091
|
const reqs = arr("requirements");
|
|
1044
1092
|
if (!reqs) p.push("requirements rows are missing");
|
|
@@ -1217,7 +1265,7 @@ export function formatShadowSummary(rows) {
|
|
|
1217
1265
|
}
|
|
1218
1266
|
|
|
1219
1267
|
/** #4664: follow-up classes, one issue each per parent (scripts/file-deferred-followups.sh); post-deploy is one rollup per release lane (#4724), external one aggregate per batch and host a `host-task` (#5078). */
|
|
1220
|
-
export const FOLLOWUP_CLASSES = ["engineering", "post-deploy", "external", "ops", "host"];
|
|
1268
|
+
export const FOLLOWUP_CLASSES = ["engineering", "post-deploy", "external", "ops", "host", "backlog"];
|
|
1221
1269
|
/** #4724: the bucket every deferred row gets at contract time. `date:<YYYY-MM-DD>` and `owner:<action>` carry a value. */
|
|
1222
1270
|
export const BUCKETS = Object.freeze(["post-deploy", "verify-now", "date", "owner", "new-issue", "host"]);
|
|
1223
1271
|
const DATE_BUCKET_RE = /^date:(\d{4})-(\d{2})-(\d{2})$/;
|
|
@@ -1243,7 +1291,7 @@ export function bucketProblems(r) {
|
|
|
1243
1291
|
const POST_PROMOTION_RE = /(?:after|post)[- ]?(?:promotion|release|deploy)|in production after|production[- ]verif|promot(?:e|ion)|rollout|purge|deploy[- ]time/i;
|
|
1244
1292
|
export const READONLY_PROD_RE = /\bssh\s+[\w.-]*-monitor\b|\bobs-psql\b|\bprod(?:uction)?[ _-]monitor\b|\bread[- ]only\b[^.]{0,40}\bprod(?:uction)?\b|\bprod(?:uction)?\b[^.]{0,30}\b(?:query|queries|capture|telemetry|logs?)\b/i;
|
|
1245
1293
|
/** An item that truly needs the outside world (or a write to production) stays external even when it also reads production. */
|
|
1246
|
-
export const EXTERNAL_NEED_RE = /credential|secret|api[- ]?key|token|password|passphrase|ssh[- ]?keys?\b|private[- ]key|\blogin\b|\bsudo\b|spend|budget|
|
|
1294
|
+
export const EXTERNAL_NEED_RE = /credential|secret|api[- ]?key|token|password|passphrase|ssh[- ]?keys?\b|private[- ]key|\blogin\b|\bsudo\b|spend|budget|purchase|payment|account|third[- ]party|vendor|customer|contract sign|legal|\b(?:delete|drop|truncate|wipe|destroy|modify|migrate|write|update|restart|rotate|remove|grant|alter)\b/i;
|
|
1247
1295
|
/**
|
|
1248
1296
|
* #5078: where an owner deferral goes. `owner:orchestrator`, `owner:promote:*` or post-promotion text -> post-deploy (the
|
|
1249
1297
|
* rollup); read-only production data or capture (with no credential/spend/account/third-party/customer need) -> host; else external (credentials, spend, an account, a third party or a customer).
|
|
@@ -1256,12 +1304,18 @@ export function ownerRoute(r) {
|
|
|
1256
1304
|
if (POST_PROMOTION_RE.test(text) && !EXTERNAL_NEED_RE.test(text)) return "post-deploy";
|
|
1257
1305
|
return READONLY_PROD_RE.test(text) && !EXTERNAL_NEED_RE.test(text) ? "host" : "external";
|
|
1258
1306
|
}
|
|
1259
|
-
|
|
1307
|
+
const PRE_PROMOTION_RE = /(?:before|pre)[- ]?(?:promotion|release|deploy)/i;
|
|
1308
|
+
/** #5186: an explicit host deferral that is post-promotion text (and needs nothing external) joins the release rollup; work needed before promotion stays host. Mirrored in scripts/file-deferred-followups.sh host_route. */
|
|
1309
|
+
function hostRoute(r) {
|
|
1310
|
+
const text = `${r?.bucket ?? ""} ${r?.why ?? ""}`;
|
|
1311
|
+
return POST_PROMOTION_RE.test(text) && !PRE_PROMOTION_RE.test(text) && !EXTERNAL_NEED_RE.test(text) ? "post-deploy" : "host";
|
|
1312
|
+
}
|
|
1313
|
+
/** The follow-up class of a requirement: owner -> ownerRoute (ops kept), host -> host, new-issue -> backlog (one issue per batch, #5188), other buckets post-deploy; else its `class`, else post-deploy for that disposition, else engineering. */
|
|
1260
1314
|
export function followupClass(r) {
|
|
1261
1315
|
const k = bucketKind(r?.bucket);
|
|
1262
1316
|
if (k === "owner") return r?.class === "ops" ? "ops" : ownerRoute(r);
|
|
1263
|
-
if (k === "host") return
|
|
1264
|
-
if (k === "new-issue") return r?.class &&
|
|
1317
|
+
if (k === "host") return hostRoute(r);
|
|
1318
|
+
if (k === "new-issue") return r?.class && !["post-deploy", "engineering"].includes(r.class) && FOLLOWUP_CLASSES.includes(r.class) ? r.class : "backlog"; // #5188: the per-batch backlog issue
|
|
1265
1319
|
if (k) return "post-deploy";
|
|
1266
1320
|
return FOLLOWUP_CLASSES.includes(r?.class) ? r.class : r?.disposition === "post-deploy" ? "post-deploy" : "engineering";
|
|
1267
1321
|
}
|
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
import { readFileSync } from "node:fs";
|
|
4
4
|
import { describe, it } from "node:test";
|
|
5
5
|
import assert from "node:assert/strict";
|
|
6
|
-
import { removedNamedPaths, removedPathsOf, shellSyntaxError, unrunnableValidate, noopCommand, substituteVerdict, describesUnrunnableCommand, vitestQuietFlag, normalizeRunnerCommand, cliUsageError, validateContract, applyAmendments, amendmentKindProblems, precheck, hotspotGrowth, reproFailures, isBugIssue, parseReview, checkCompleteness, decide, closePlan, isInvestigation, formatShadowSummary, followupItems, inIssue, isTestPath, normalizeEvidencePath, mergeReviewRows, reviewSkeleton, missingIds, resolveEvidencePath, movingBaseDiff, scopeText, evidencePathLine, evidencePathOnly, explainFailures, resolveForgedockPaths, missingTool, repoTracks, tmpdirInputs, isScopeCheck, isPureScopeCheck, dropScopeValidates, tagOutOfBand, outOfBandRequirements, isOutOfBand, followupMap, renderPendingFollowups, VERIFY_MODES, OUT_OF_BAND_RE, FOLLOWUP_CLASSES, followupClass, BUCKETS, bucketKind, bucketProblems, bucketTally, isE2eCommand, e2eVerified, impliedDocDeliverables, applyValidateRecipes, deferChecklessPostDeploy, substituteShellProblem, reproEnvMiss, ORCHESTRATOR_BUCKET, ownerRoute, weakenedE2eDecisions } from "./conformance.mjs";
|
|
6
|
+
import { removedNamedPaths, removedPathsOf, shellSyntaxError, unrunnableValidate, noopCommand, substituteVerdict, describesUnrunnableCommand, vitestQuietFlag, normalizeRunnerCommand, cliUsageError, validateContract, applyAmendments, amendmentKindProblems, precheck, hotspotGrowth, reproFailures, isBugIssue, parseReview, checkCompleteness, decide, closePlan, isInvestigation, formatShadowSummary, followupItems, inIssue, isTestPath, normalizeEvidencePath, mergeReviewRows, reviewSkeleton, missingIds, resolveEvidencePath, movingBaseDiff, scopeText, evidencePathLine, evidencePathOnly, reaskable, matchCriterion, criterionLines, fillEngineRows, explainFailures, resolveForgedockPaths, missingTool, repoTracks, tmpdirInputs, isScopeCheck, isPureScopeCheck, dropScopeValidates, tagOutOfBand, outOfBandRequirements, isOutOfBand, followupMap, renderPendingFollowups, VERIFY_MODES, OUT_OF_BAND_RE, FOLLOWUP_CLASSES, followupClass, BUCKETS, bucketKind, bucketProblems, bucketTally, isE2eCommand, e2eVerified, impliedDocDeliverables, applyValidateRecipes, deferChecklessPostDeploy, substituteShellProblem, reproEnvMiss, ORCHESTRATOR_BUCKET, ownerRoute, weakenedE2eDecisions } from "./conformance.mjs";
|
|
7
7
|
|
|
8
8
|
const ISSUE = "## Requirements\n1. The scrape route must release the spend reservation on 429.\n2. The search route must release the spend reservation on 429.\n\n- [ ] Billing pricing is unchanged.";
|
|
9
9
|
const Q1 = "The scrape route must release the spend reservation on 429.";
|
|
@@ -494,6 +494,38 @@ describe("conformance review: the engine computes the verdict from complete rows
|
|
|
494
494
|
it("incomplete: a coverage quote paraphrased instead of verbatim", () => {
|
|
495
495
|
assert.equal(decide({ ...good, issue_coverage: [{ quote: "scrape should release money on rate limits", status: "covered" }] }, ctx).state, "review.incomplete");
|
|
496
496
|
});
|
|
497
|
+
it("#5164 a near-verbatim coverage misquote is requoted to the criterion line and the review completes", () => {
|
|
498
|
+
const issue = "## Acceptance Criteria\n- [ ] Every manifest step kind from #38826 compiles to engine nodes, with a test per kind.\n- [ ] The scrape route must release the spend reservation on 429.";
|
|
499
|
+
const k = { ...C, requirements: [{ id: "R1", quote: "The scrape route must release the spend reservation on 429.", disposition: "deliver" }, { id: "R2", quote: Q2, disposition: "deliver" }] };
|
|
500
|
+
const quote = "Every manifest step kind from #38829 compiles to engine node";
|
|
501
|
+
const rv = { ...good, issue_coverage: [{ quote, contract_ids: ["R1"], status: "covered" }, { quote: "The scrape route must release the spend reservation on 429.", status: "covered" }] };
|
|
502
|
+
const d = decide(rv, { ...ctx, contract: k, issueText: `${issue}\n${ISSUE}` });
|
|
503
|
+
assert.equal(d.state, "conforms");
|
|
504
|
+
assert.equal(d.review.issue_coverage[0].quote, "Every manifest step kind from #38826 compiles to engine nodes, with a test per kind.");
|
|
505
|
+
assert.equal(d.review.issue_coverage[0].requoted, quote, "the substitution is recorded in the review");
|
|
506
|
+
});
|
|
507
|
+
it("#5164 matchCriterion: loose prefix or a unique token match; a paraphrase, an ambiguous or a short quote matches nothing", () => {
|
|
508
|
+
const t = "- [ ] Every manifest step kind from #38826 compiles to engine nodes, with a test per kind.\n- The scrape route must release the spend reservation on 429.\n- The search route must release the spend reservation on 429.";
|
|
509
|
+
assert.deepEqual(criterionLines(t)[0], "Every manifest step kind from #38826 compiles to engine nodes, with a test per kind.");
|
|
510
|
+
assert.equal(matchCriterion("every manifest step kind from #1 compiles to engine node with a test per kinds", t), criterionLines(t)[0], "prefix tier");
|
|
511
|
+
assert.equal(matchCriterion("The scrape route must release the spend reservations on 429", t), "The scrape route must release the spend reservation on 429.");
|
|
512
|
+
assert.equal(matchCriterion("route must release the spend reservation", t), null, "two lines tie");
|
|
513
|
+
assert.equal(matchCriterion("scrape should release money on rate limits", t), null);
|
|
514
|
+
assert.equal(matchCriterion("engine node", t), null);
|
|
515
|
+
});
|
|
516
|
+
it("#5164 a quote that matches no criterion still fails as incomplete, naming the nearest criterion line; it is re-askable, a real gap is not", () => {
|
|
517
|
+
const d = decide({ ...good, issue_coverage: [{ quote: "scrape should release money on rate limits", status: "covered" }] }, ctx);
|
|
518
|
+
assert.equal(d.state, "review.incomplete");
|
|
519
|
+
assert.equal(d.review.issue_coverage[0].requoted, undefined);
|
|
520
|
+
const problems = d.failures.map((f) => f.detail);
|
|
521
|
+
assert.match(problems[0], /nearest criterion line: "The scrape route must release/);
|
|
522
|
+
assert.ok(reaskable(problems));
|
|
523
|
+
assert.ok(reaskable(["R1: evidence path /layout.tsx does not exist"]), "#4327 evidence paths stay re-askable");
|
|
524
|
+
assert.ok(!reaskable([...problems, "requirement R1 needs exactly one row (has 0)"]));
|
|
525
|
+
assert.ok(!reaskable(["issue_coverage is missing or empty"]));
|
|
526
|
+
assert.ok(!reaskable([]));
|
|
527
|
+
assert.deepEqual(fillEngineRows(good, ctx).issue_coverage, good.issue_coverage, "verbatim rows are untouched");
|
|
528
|
+
});
|
|
497
529
|
it("omission: an issue requirement missing from or narrowed by the contract", () => {
|
|
498
530
|
const d = decide({ ...good, issue_coverage: [...good.issue_coverage.slice(0, 2), { quote: "Billing pricing is unchanged.", status: "missing" }] }, ctx);
|
|
499
531
|
assert.deepEqual(codes(d), ["conformance.omission"]);
|
|
@@ -966,7 +998,7 @@ describe("post-deploy check ids (#4626)", () => {
|
|
|
966
998
|
assert.equal(cls({ disposition: "post-deploy", check: "x" }), "post-deploy");
|
|
967
999
|
assert.equal(cls({ disposition: "defer", class: "external" }), "external");
|
|
968
1000
|
assert.equal(cls({ disposition: "defer", class: "bogus" }), "engineering");
|
|
969
|
-
assert.deepEqual(FOLLOWUP_CLASSES, ["engineering", "post-deploy", "external", "ops", "host"]);
|
|
1001
|
+
assert.deepEqual(FOLLOWUP_CLASSES, ["engineering", "post-deploy", "external", "ops", "host", "backlog"]);
|
|
970
1002
|
assert.equal(followupClass({ disposition: "post-deploy" }), "post-deploy"); assert.equal(followupClass({ class: "ops" }), "ops");
|
|
971
1003
|
const v = validateContract({ requirements: [{ id: "R1", quote: Q1, disposition: "defer", why: "w", class: "bogus" }], deliverables: [], preserve: [], validate: [{ id: "V1", command: "true" }] }, Q1);
|
|
972
1004
|
assert.ok(v.problems.some((x) => /R1: class must be one of/.test(x)), v.problems.join(";"));
|
|
@@ -993,7 +1025,8 @@ describe("post-deploy check ids (#4626)", () => {
|
|
|
993
1025
|
assert.equal(followupClass({ disposition: "defer", bucket: "owner:spend" }), "external");
|
|
994
1026
|
assert.equal(followupClass({ disposition: "defer", bucket: "owner:spend", class: "ops" }), "ops");
|
|
995
1027
|
assert.equal(followupClass({ disposition: "defer", bucket: "owner:x", class: "post-deploy" }), "external");
|
|
996
|
-
assert.equal(followupClass({ disposition: "defer", bucket: "new-issue", class: "post-deploy" }), "
|
|
1028
|
+
assert.equal(followupClass({ disposition: "defer", bucket: "new-issue", class: "post-deploy" }), "backlog");
|
|
1029
|
+
assert.equal(followupClass({ disposition: "defer", bucket: "new-issue" }), "backlog"); assert.equal(followupClass({ disposition: "defer", bucket: "new-issue", class: "ops" }), "ops"); // #5188
|
|
997
1030
|
for (const bucket of ["post-deploy", "verify-now", "date:2026-12-01"]) assert.equal(followupClass({ disposition: "defer", bucket }), "post-deploy");
|
|
998
1031
|
assert.equal(one({ bucket: "owner:rotate the key" }).why, "owner: rotate the key. [bucket:owner] w");
|
|
999
1032
|
assert.equal(one({ bucket: "verify-now" }).why, "post-deploy: [bucket:verify-now] w");
|
|
@@ -1015,6 +1048,13 @@ describe("post-deploy check ids (#4626)", () => {
|
|
|
1015
1048
|
assert.equal(followupClass(d("owner:ops", "needs a customer account to read production data")), "external");
|
|
1016
1049
|
assert.equal(followupClass({ ...d("owner:obs-psql", "read prod data"), class: "ops" }), "ops");
|
|
1017
1050
|
assert.equal(followupClass(d("host")), "host");
|
|
1051
|
+
// #5186: host + post-promotion text -> rollup; pre-promotion or external need stays host
|
|
1052
|
+
assert.equal(followupClass(d("host", "≥95% success over 7 days by the canary after promotion")), "post-deploy");
|
|
1053
|
+
assert.equal(followupClass(d("host", "billed margin from billing rows in production after promotion")), "post-deploy");
|
|
1054
|
+
assert.equal(followupClass(d("owner:ops", "read billing rows after promotion")), "post-deploy");
|
|
1055
|
+
assert.equal(followupClass(d("host", "capture the page in a browser on the host before promotion")), "host");
|
|
1056
|
+
assert.equal(followupClass(d("host", "capture the page in a browser on the host")), "host");
|
|
1057
|
+
assert.equal(followupClass(d("host", "update the rows after promotion")), "host");
|
|
1018
1058
|
assert.deepEqual(bucketProblems(d("host")), []);
|
|
1019
1059
|
assert.match(bucketProblems({ disposition: "post-deploy", check: "a", bucket: "host" }).join(";"), /never post-deploy/);
|
|
1020
1060
|
assert.match(bucketProblems(d("owner:obs-psql", "capture production query counts")).join(";"), /use bucket host/);
|
|
@@ -1367,6 +1407,18 @@ describe("#5087 a plan decision may not weaken an e2e/integration criterion to m
|
|
|
1367
1407
|
assert.deepEqual(weakenedE2eDecisions({ ...C, decisions: [{ id: "K1", choice, source: "doc" }] }), [], choice);
|
|
1368
1408
|
}
|
|
1369
1409
|
});
|
|
1410
|
+
it("#5157 negated verbs and bare negators before a preposition still weaken e2e", () => {
|
|
1411
|
+
for (const choice of ["We do not need to run e2e; mocked route tests cover it", "will not rely on e2e, mock the API", "not with e2e: unit tests used", "not for e2e, unit tests used", "no need to run e2e; mocks cover it", "no need for e2e, mocks cover it"]) {
|
|
1412
|
+
assert.deepEqual(weakenedE2eDecisions({ ...C, decisions: [{ id: "K1", choice, source: "doc" }] }), ["K1"], choice);
|
|
1413
|
+
}
|
|
1414
|
+
assert.deepEqual(weakenedE2eDecisions({ ...C, decisions: [{ id: "K1", choice: "Keep playwright e2e coverage; add unit tests (no new fixtures needed for e2e)", source: "doc" }] }), []);
|
|
1415
|
+
});
|
|
1416
|
+
it("#5184 a negated omission verb keeps e2e and is not flagged", () => {
|
|
1417
|
+
for (const choice of ["Mocked the gateway with stubs; will not forget to add the e2e test", "Mocked the gateway with stubs; not going to forget to add the e2e test", "Mocked the gateway with stubs; never intending to skip the e2e test", "Stubs for the API; will not fail to run e2e", "Mocks used; never omit the e2e test"]) {
|
|
1418
|
+
assert.deepEqual(weakenedE2eDecisions({ ...C, decisions: [{ id: "K1", choice, source: "doc" }] }), [], choice);
|
|
1419
|
+
}
|
|
1420
|
+
assert.deepEqual(weakenedE2eDecisions({ ...C, decisions: [{ id: "K1", choice: "We do not need to run e2e; mocked route tests cover it", source: "doc" }] }), ["K1"]);
|
|
1421
|
+
});
|
|
1370
1422
|
it("leaves unrelated decisions and contracts without decisions alone", () => {
|
|
1371
1423
|
assert.deepEqual(weakenedE2eDecisions(C), []);
|
|
1372
1424
|
assert.deepEqual(weakenedE2eDecisions({ ...C, decisions: [{ id: "K1", choice: "Run the Playwright e2e suite against the live stack", source: "doc" }, { id: "K3", choice: "Use unit tests with mocks for the parser", source: "spec" }] }), []);
|
package/bin/lean/context.mjs
CHANGED
|
@@ -119,6 +119,9 @@ const namesSymbol = (text, symbols) => symbols.some((s) => new RegExp(`(?:^|[^\\
|
|
|
119
119
|
|
|
120
120
|
const STOPWORDS = new Set(("about after again also always another because before being between both cannot could does doing during each every from have having into issue issues just make makes more most must never only other over same should some such than that their them then there these they this those through under until very what when where which while will with within without would your " +
|
|
121
121
|
"fix fixes fixed bug bugs feat chore docs test tests file files when wrong error errors fail fails failed failing add adds remove update use uses").split(" "));
|
|
122
|
+
/** #5110: status/label-like tokens that match a large share of any repo's history; a code or word made only of them is not a subject. */
|
|
123
|
+
const GENERIC_TERMS = new Set("blocked generic broad base status state failure failures result results page pages response default common general detection handling".split(" "));
|
|
124
|
+
const isGeneric = (t) => String(t).toLowerCase().split(/[._-]+/).filter(Boolean).every((x) => GENERIC_TERMS.has(x) || STOPWORDS.has(x));
|
|
122
125
|
const FILE_EXT = /\.(?:m?[jt]sx?|cjs|md|sh|json|ya?ml|py|go|rs|rb|css|html|txt|toml|lock|sql)$/i;
|
|
123
126
|
/** #5085: subject terms split by kind: codes and symbols (exact, quoted searches) and distinctive title words. */
|
|
124
127
|
function subjectParts({ title = "", body = "" } = {}) {
|
|
@@ -131,8 +134,9 @@ function subjectParts({ title = "", body = "" } = {}) {
|
|
|
131
134
|
for (const s of issueSymbols(body)) if (!codes.some((c) => c.toLowerCase().endsWith(`.${s.toLowerCase()}`))) add(s);
|
|
132
135
|
const head = stripComments(title).replace(/^\s*\w+(?:\([^)]*\))?!?:\s*/, "");
|
|
133
136
|
const words = [];
|
|
134
|
-
|
|
135
|
-
|
|
137
|
+
const tokens = [...(head.match(/\b[A-Z][A-Z0-9]{2}\b/g) ?? []), ...(head.toLowerCase().match(/[a-z][a-z0-9-]{3,}/g) ?? [])];
|
|
138
|
+
for (const raw of tokens) { const w = raw.toLowerCase(); if (!isGeneric(w) && !words.includes(w) && !codes.some((c) => c.toLowerCase() === w)) words.push(w); }
|
|
139
|
+
return { codes: codes.filter((c) => !isGeneric(c)).slice(0, 3), words: words.slice(0, 3) };
|
|
136
140
|
}
|
|
137
141
|
/** #5085: the issue's subject terms, codes and symbols first, then title words; deterministic, deduped, at most 6. */
|
|
138
142
|
export function subjectTerms({ title = "", body = "" } = {}) {
|
|
@@ -212,9 +216,15 @@ const failuresOf = (st) => (Array.isArray(st?.failureClasses) ? [...new Set(st.f
|
|
|
212
216
|
const recordLine = (body) => oneLine(noComments(body).split("\n").map((l) => l.trim()).find((l) => l && !/^#+\s/.test(l)) ?? "");
|
|
213
217
|
const markerOf = (body) => /^\s*<!--\s*FORGE:([A-Z_]+)\s*-->/.exec(String(body ?? ""))?.[1] ?? null;
|
|
214
218
|
|
|
219
|
+
/**
|
|
220
|
+
* #5152: a closed record's result for the builder context. Delivered (`workflow:merged`) or moved (`workflow:decomposed`)
|
|
221
|
+
* scope reads `completed` whatever its `stateReason`, so a legacy NOT_PLANNED close of delivered work never reads as dropped.
|
|
222
|
+
*/
|
|
223
|
+
export const closedResult = (rec) => (["workflow:merged", "workflow:decomposed"].some((l) => (rec?.labels ?? []).includes(l)) ? "completed" : rec?.stateReason ?? "closed");
|
|
215
224
|
async function readIssue(gh, repo, n) {
|
|
216
225
|
const j = JSON.parse(String(await gh(["api", `repos/${repo}/issues/${n}`])));
|
|
217
|
-
return { number: Number(j.number ?? n), title: oneLine(j.title, 120), state: String(j.state ?? "").toUpperCase() || null, stateReason: j.state_reason ?? null, body: String(j.body ?? ""), pr: Boolean(j.pull_request)
|
|
226
|
+
return { number: Number(j.number ?? n), title: oneLine(j.title, 120), state: String(j.state ?? "").toUpperCase() || null, stateReason: j.state_reason ?? null, body: String(j.body ?? ""), pr: Boolean(j.pull_request),
|
|
227
|
+
labels: (Array.isArray(j.labels) ? j.labels : []).map((l) => String(l?.name ?? l)) };
|
|
218
228
|
}
|
|
219
229
|
async function readComments(gh, repo, n) {
|
|
220
230
|
return parseLines(await gh(["api", "--paginate", `repos/${repo}/issues/${n}/comments`, "--jq", ".[] | {id, body, author_association, user: {type: .user.type, login: .user.login}} | @json"]));
|
|
@@ -222,7 +232,7 @@ async function readComments(gh, repo, n) {
|
|
|
222
232
|
|
|
223
233
|
/**
|
|
224
234
|
* #5085: closed issues and merged PRs on the same subject, found by term rather than by issue number or file: up to
|
|
225
|
-
* MAX_SUBJECT_QUERIES GitHub searches (each code/symbol quoted, then the title words
|
|
235
|
+
* MAX_SUBJECT_QUERIES GitHub searches (each non-generic code/symbol quoted, then the title words, #5110: generic codes are never searched) and one `git log --grep`
|
|
226
236
|
* over the whole history of `base`. `exclude` (self, linked issues) is dropped; rows are ranked by the number of
|
|
227
237
|
* matched terms, then newest first, and capped. A failed query lands in `errors`; the rest still count.
|
|
228
238
|
* @returns {Promise<{terms:string[], rows:{number:number, kind:string, status:string, title:string, matched:string[]}[], errors:string[]}>}
|
|
@@ -239,7 +249,9 @@ export async function subjectHistory({ io, repo, issue = null, title = "", body
|
|
|
239
249
|
hits.set(n, row);
|
|
240
250
|
};
|
|
241
251
|
if (!terms.length) return { terms, rows: [], errors };
|
|
242
|
-
|
|
252
|
+
// #5110: words are searched whatever the codes are; three words run as overlapping pairs so an earlier attempt that names only two of them still matches (full matches rank first)
|
|
253
|
+
const groups = words.length > 2 ? [words.slice(0, 2), words.slice(1)] : words.length ? [words] : [];
|
|
254
|
+
const queries = [...codes.slice(0, MAX_SUBJECT_QUERIES - groups.length).map((c) => [c]), ...groups].slice(0, MAX_SUBJECT_QUERIES);
|
|
243
255
|
for (const q of queries) {
|
|
244
256
|
const text = q.length === 1 && codes.includes(q[0]) ? `"${q[0]}"` : q.join(" ");
|
|
245
257
|
try {
|
|
@@ -252,19 +264,23 @@ export async function subjectHistory({ io, repo, issue = null, title = "", body
|
|
|
252
264
|
} catch (e) { errors.push(`attempts: subject search ${oneLine(e?.message ?? e, 80)}`); }
|
|
253
265
|
}
|
|
254
266
|
if (base && io.git) {
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
const
|
|
261
|
-
const
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
267
|
+
// one repo-wide log per kind: codes (any), words (all of a group)
|
|
268
|
+
const runs = [...(codes.length ? [{ greps: ["-E", `--grep=${codes.map(reEscape).join("|")}`], groups: codes.map((c) => [c]) }] : []),
|
|
269
|
+
...(words.length ? [{ greps: ["--all-match", ...words.map((w) => `--grep=${reEscape(w)}`)], groups: [words] }] : [])];
|
|
270
|
+
for (const run of runs) {
|
|
271
|
+
try {
|
|
272
|
+
const out = String(await io.git(["log", "-i", ...run.greps, "-n", "20", "--format=%x1e%H%x1f%s%x1f%b", base]));
|
|
273
|
+
for (const rec of out.split("\x1e").filter((x) => x.trim())) {
|
|
274
|
+
const [, subject = "", msg = ""] = rec.split("\x1f");
|
|
275
|
+
const pr = Number(/Merge pull request #(\d+)/.exec(subject)?.[1] ?? /\(#(\d+)\)\s*$/.exec(subject.trim())?.[1]) || null;
|
|
276
|
+
const hay = `${subject}\n${msg}`.toLowerCase();
|
|
277
|
+
const matched = run.groups.filter((g) => g.every((t) => hay.includes(t.toLowerCase()))).flat();
|
|
278
|
+
if (!pr || !matched.length) continue;
|
|
279
|
+
const named = /^Merge pull request/.test(subject) ? msg.split("\n").map((l) => l.trim()).find(Boolean) ?? subject : subject;
|
|
280
|
+
hit(pr, { src: "git", kind: "PR", status: "merged", title: oneLine(named, 120) }, matched);
|
|
281
|
+
}
|
|
282
|
+
} catch (e) { errors.push(`attempts: subject git log ${oneLine(e?.message ?? e, 80)}`); }
|
|
283
|
+
}
|
|
268
284
|
}
|
|
269
285
|
const rows = [...hits.values()].sort((a, b) => b.matched.length - a.matched.length || b.number - a.number)
|
|
270
286
|
.slice(0, max);
|
|
@@ -324,7 +340,7 @@ export async function gatherContextFacts({ io, repo, issue, iss, comments = [],
|
|
|
324
340
|
const st = stateOf(rec.body);
|
|
325
341
|
const reason = codeOf(st?.terminalReason), fails = failuresOf(st);
|
|
326
342
|
facts.links.push({ number: n, rel: r, kind: rec.pr ? "pr" : "issue", title: rec.title, state: rec.state, code: outcomeOf(st),
|
|
327
|
-
result: reason ?? (rec.state === "CLOSED" ? rec
|
|
343
|
+
result: reason ?? (rec.state === "CLOSED" ? closedResult(rec) : null), ...(fails.length ? { failures: fails } : {}), ...(r === "parent" || r === "depends-on" ? { body: stripComments(rec.body) } : {}) });
|
|
328
344
|
}
|
|
329
345
|
});
|
|
330
346
|
|
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
import { describe, it } from "node:test";
|
|
4
4
|
import assert from "node:assert/strict";
|
|
5
5
|
import { normaliseFacts, renderFactsRecord, FACTS_MARKER } from "./facts.mjs";
|
|
6
|
-
import { gatherContextFacts, compileContextPack, contextPackFor, contextArm, contextPackCacheKey, linkStateStamp, LINK_STAMP_MAX, parseContextPackConfig, laneType, priorAttempts, issueSymbols, bodyLinks, parentOf, renderContextRecord, DEFAULT_CONTEXT_BYTES, noComments, subjectTerms, subjectHistory, MAX_SUBJECT_ITEMS, MAX_SUBJECT_QUERIES } from "./context.mjs";
|
|
6
|
+
import { closedResult, gatherContextFacts, compileContextPack, contextPackFor, contextArm, contextPackCacheKey, linkStateStamp, LINK_STAMP_MAX, parseContextPackConfig, laneType, priorAttempts, issueSymbols, bodyLinks, parentOf, renderContextRecord, DEFAULT_CONTEXT_BYTES, noComments, subjectTerms, subjectHistory, MAX_SUBJECT_ITEMS, MAX_SUBJECT_QUERIES } from "./context.mjs";
|
|
7
7
|
|
|
8
8
|
const REPO = "o/r";
|
|
9
9
|
const BOT = { author_association: "NONE", user: { type: "Bot", login: "forge[bot]" } };
|
|
@@ -530,6 +530,21 @@ describe("#5085: subject history and recall status", () => {
|
|
|
530
530
|
assert.ok(kinds.indexOf("subject") > kinds.lastIndexOf("salvage"), kinds.join(","));
|
|
531
531
|
});
|
|
532
532
|
|
|
533
|
+
it("#5110: generic quoted codes do not replace the subject words", async () => {
|
|
534
|
+
const corpus = [item(34683, "Classify dead origins: TLS cert verify failures"), item(35204, "classify dead origins failures"), item(39485, "deploy reverts hotfixes blocked.generic broad-base"), item(32764, "release safety blocked.generic generic broad-base")].map((j) => JSON.parse(j));
|
|
535
|
+
const search = (q) => { const terms = q.replace(/^q=repo:\S+ is:closed /, "").replace(/"/g, "").toLowerCase().split(" "); return corpus.filter((c) => terms.every((t) => c.title.toLowerCase().includes(t))).map((c) => JSON.stringify(c)).join("\n"); };
|
|
536
|
+
const title = "fix(detection): ~85% of broad-base 'blocked.generic' are dead origins (cert-invalid, parked, TLS-refused) that run the full ladder";
|
|
537
|
+
const body = "Most `blocked.generic` rows on the `broad-base` crawl are dead origins.";
|
|
538
|
+
assert.ok(!subjectTerms({ title, body }).some((t) => /generic|broad/.test(t)), subjectTerms({ title, body }).join(","));
|
|
539
|
+
const f = fakes({ search });
|
|
540
|
+
const r = await subjectHistory({ io: f.io, repo: REPO, issue: 50, title, body, base: "origin/staging" });
|
|
541
|
+
assert.deepEqual(r.rows.map((x) => x.number).sort(), [34683, 35204]);
|
|
542
|
+
assert.ok(!f.calls.some((c) => c.some((x) => /generic|broad-base/.test(String(x)) && String(x).startsWith("q="))), "no search on a generic code");
|
|
543
|
+
assert.ok(r.rows[0].number === 34683 || r.rows[0].matched.length >= r.rows[1].matched.length);
|
|
544
|
+
const only = await subjectHistory({ io: fakes({ search }).io, repo: REPO, issue: 50, title: "fix(x): 'blocked.generic' on broad-base", body: "`blocked.generic`" });
|
|
545
|
+
assert.deepEqual(only, { terms: [], rows: [], errors: [] });
|
|
546
|
+
});
|
|
547
|
+
|
|
533
548
|
it("ranks rows by matched-term count, then newest number", async () => {
|
|
534
549
|
const search = (q) => (q.includes('"a.code"') ? [item(901, "x"), item(950, "y")] : q.includes('"b.code"') ? [item(901, "x")] : []).join("\n");
|
|
535
550
|
const r = await subjectHistory({ io: fakes({ search }).io, repo: REPO, issue: 50, title: "", body: "`a.code` and `b.code`" });
|
|
@@ -570,3 +585,13 @@ describe("#5085: subject history and recall status", () => {
|
|
|
570
585
|
assert.equal(compileContextPack({ issue: 1, links: [], attempts: [], ledger: [], facts: [], recall: absent.recall }).recall.present, false, "the empty pack carries it too");
|
|
571
586
|
});
|
|
572
587
|
});
|
|
588
|
+
|
|
589
|
+
describe("#5152 builder context: delivered or moved scope never reads as dropped", () => {
|
|
590
|
+
it("a closed workflow:merged or workflow:decomposed dependency is completed whatever its stateReason (legacy not_planned too)", () => {
|
|
591
|
+
assert.equal(closedResult({ stateReason: "not_planned", labels: ["workflow:merged"] }), "completed");
|
|
592
|
+
assert.equal(closedResult({ stateReason: "not_planned", labels: ["bug", "workflow:decomposed"] }), "completed");
|
|
593
|
+
assert.equal(closedResult({ stateReason: "not_planned", labels: ["workflow:invalid"] }), "not_planned", "dropped scope keeps its reason");
|
|
594
|
+
assert.equal(closedResult({ stateReason: "completed", labels: [] }), "completed");
|
|
595
|
+
assert.equal(closedResult({ stateReason: null }), "closed");
|
|
596
|
+
});
|
|
597
|
+
});
|
package/bin/lean/credentials.mjs
CHANGED
|
@@ -27,3 +27,21 @@ export function resolveCredential(name, { env = process.env, keychain = defaultK
|
|
|
27
27
|
if (v !== undefined && v !== null && String(v) !== "") return String(v);
|
|
28
28
|
try { const k = keychain(String(name), platform); return k === undefined || k === null || String(k) === "" ? null : String(k); } catch { return null; }
|
|
29
29
|
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* #5159: a keychain lookup memoised per name for `ttlMs` (a miss or a failure is cached as null too), so a resolver run
|
|
33
|
+
* on every request (#5144) spawns `secret-tool`/`security` at most once per TTL instead of on every HTTP call.
|
|
34
|
+
*/
|
|
35
|
+
export function memoKeychain({ keychain = defaultKeychain, ttlMs = 60000, now = Date.now } = {}) {
|
|
36
|
+
const cache = new Map();
|
|
37
|
+
return (name, platform) => {
|
|
38
|
+
const key = `${platform ?? ""}\u0000${name}`;
|
|
39
|
+
const hit = cache.get(key);
|
|
40
|
+
const t = now();
|
|
41
|
+
if (hit && t - hit.at < ttlMs) return hit.value;
|
|
42
|
+
let value = null;
|
|
43
|
+
try { const k = keychain(name, platform); value = k === undefined || k === null || String(k) === "" ? null : String(k); } catch { value = null; }
|
|
44
|
+
cache.set(key, { at: t, value });
|
|
45
|
+
return value;
|
|
46
|
+
};
|
|
47
|
+
}
|
package/bin/lean/effects.mjs
CHANGED
|
@@ -406,9 +406,9 @@ export function makeLeanIo({ repo, subagentModel = readSubagentModel() }) {
|
|
|
406
406
|
pitfalls: makePitfallStore(),
|
|
407
407
|
/** forge#4275: the context pack's facts for one issue (bin/lean/context.mjs), from gh and git only; sources fail independently. */
|
|
408
408
|
contextFacts: (args) => gatherContextFacts({ ...args, io: { gh: run("gh"), git: run("git"), exists: async (p) => existsSync(p) } }),
|
|
409
|
-
/** forge#4195: scripts/hotspots.sh facts for `paths` in cwd (growth since base when given); null on any failure. */
|
|
410
|
-
async hotspots({ cwd, base = null, paths = [] }) {
|
|
411
|
-
const args = [script("hotspots.sh"), ...(base ? ["--base", base] : []), "--", ...paths];
|
|
409
|
+
/** forge#4195: scripts/hotspots.sh facts for `paths` in cwd (growth since base when given; config = the host forge.yaml, #5163); null on any failure. */
|
|
410
|
+
async hotspots({ cwd, base = null, paths = [], config = null }) {
|
|
411
|
+
const args = [script("hotspots.sh"), ...(config ? ["--config", config] : []), ...(base ? ["--base", base] : []), "--", ...paths];
|
|
412
412
|
try { return JSON.parse((await pexec("bash", args, { cwd, timeout: 30000, maxBuffer: 16 * 1024 * 1024 })).stdout); } catch { return null; }
|
|
413
413
|
},
|
|
414
414
|
/** #4322: tests enumerating the members of the given paths, and new members those tests miss (bin/lean/enumerating.mjs); [] on failure. */
|
package/bin/lean/execution.mjs
CHANGED
|
@@ -58,7 +58,7 @@ import { isLaneAlive, launchLane, writeAtomic } from "./batch.mjs";
|
|
|
58
58
|
import { schedDir } from "./sched.mjs";
|
|
59
59
|
import { dockerLabels, safeSegment } from "./ledger.mjs";
|
|
60
60
|
import { OUTCOME_CODES } from "../engine/outcome-codes.mjs";
|
|
61
|
-
import { resolveCredential } from "./credentials.mjs";
|
|
61
|
+
import { resolveCredential, memoKeychain, defaultKeychain } from "./credentials.mjs";
|
|
62
62
|
import { httpTransport, isActionsEndpoint, remoteProvider } from "./sandbox-remote.mjs";
|
|
63
63
|
import { ADMISSION_DEFAULTS } from "./admission.mjs";
|
|
64
64
|
import { classifyStep, heavyConfig, memAvailableMb } from "./heavy.mjs";
|
|
@@ -515,10 +515,11 @@ export function poolCredential(exec = {}, { env = process.env, router = null, ke
|
|
|
515
515
|
/**
|
|
516
516
|
* The remote transport for forge.yaml `execution` settings: `opts.transport` when injected, else `httpTransport` on
|
|
517
517
|
* `exec.endpoint` with the credential `exec.tokenEnv` from `credentials`, or by default poolCredential (#5131: env,
|
|
518
|
-
* keychain, `token_file`, the matching local router's token
|
|
518
|
+
* keychain, `token_file`, the matching local router's token; #5159: the keychain lookup is memoised per transport, `keychain`
|
|
519
|
+
* is its seam). `fetchFn` is a test seam. Throws `execution.provider.misconfigured`
|
|
519
520
|
* without an endpoint, `execution.provider.actions_refused` for a GitHub Actions endpoint without `allow_actions`.
|
|
520
521
|
*/
|
|
521
|
-
export function remoteTransportFor(exec = {}, { transport = null, env = process.env, credentials = null, router, fetchFn } = {}) {
|
|
522
|
+
export function remoteTransportFor(exec = {}, { transport = null, env = process.env, credentials = null, router, fetchFn, keychain } = {}) {
|
|
522
523
|
if (transport) return transport;
|
|
523
524
|
if (!exec?.endpoint) throw typedError("execution.provider.misconfigured", "execution.provider remote needs execution.endpoint");
|
|
524
525
|
if (isActionsEndpoint(exec.endpoint) && exec.allowActions !== true) {
|
|
@@ -526,8 +527,10 @@ export function remoteTransportFor(exec = {}, { transport = null, env = process.
|
|
|
526
527
|
}
|
|
527
528
|
// #5144: a getter, so the bearer is resolved on every request (a token fixed or rotated mid-batch is picked up), not once here.
|
|
528
529
|
const rt = credentials ? null : (router !== undefined ? router : poolRouterConfig({ env }));
|
|
530
|
+
// #5159: the env and token files are re-read per request; the sync keychain lookup is memoised (misses too) for its TTL.
|
|
531
|
+
const kc = credentials ? null : memoKeychain({ keychain: keychain ?? defaultKeychain });
|
|
529
532
|
const token = credentials ? () => (exec.tokenEnv ? credentials(exec.tokenEnv) : null)
|
|
530
|
-
: () => poolCredential({ provider: "remote", ...exec }, { env, router: rt }).token;
|
|
533
|
+
: () => poolCredential({ provider: "remote", ...exec }, { env, router: rt, keychain: kc }).token;
|
|
531
534
|
return httpTransport({ endpoint: exec.endpoint, token, ...(fetchFn ? { fetchFn } : {}) });
|
|
532
535
|
}
|
|
533
536
|
|
|
@@ -565,13 +568,15 @@ export function providerByName(name, opts) {
|
|
|
565
568
|
const c = poolRouterConfig({ env, ...(opts?.poolConfigPath ? { path: opts.poolConfigPath } : {}) });
|
|
566
569
|
return c ? { endpoint: router?.endpoint ?? c.endpoint, token: c.token } : router;
|
|
567
570
|
};
|
|
568
|
-
|
|
571
|
+
// #5159: one memoised keychain per provider, so a `token_env` absent from the env does not spawn the keychain per request.
|
|
572
|
+
const keychain = memoKeychain({ keychain: opts?.keychain ?? defaultKeychain });
|
|
573
|
+
const resolve = () => poolCredential({ ...exec, provider: name, ...(endpoint ? { endpoint } : {}) }, { env, router: routerNow(), keychain });
|
|
569
574
|
// A token read from a file is resolved under a fixed name so remoteProvider redacts it like any `token_env` credential.
|
|
570
575
|
// #5144: set even when no token exists yet, so one that appears later is still resolved per call (and redacted).
|
|
571
576
|
const fixed = pool ? "FORGEDOCK_POOL_TOKEN" : "FORGEDOCK_REMOTE_TOKEN";
|
|
572
577
|
const tokenEnv = exec.tokenEnv ?? fixed;
|
|
573
578
|
// #4685/#5131: an empty env/keychain lookup of `token_env` falls back to `token_file`, then the (matching) router's token file.
|
|
574
|
-
const credentials = (n) => (n === tokenEnv ? resolve().token : resolveCredential(n, { env })); // per call,
|
|
579
|
+
const credentials = (n) => (n === tokenEnv ? resolve().token : resolveCredential(n, { env, keychain })); // per call, keychain memoised (#5159)
|
|
575
580
|
const settings = { ...exec, ...(endpoint ? { endpoint } : {}), ...(tokenEnv ? { tokenEnv } : {}), ...(forgeYaml ? { forgeYaml } : {}),
|
|
576
581
|
...(typeof opts?.prefetch === "function" ? { prefetch: opts.prefetch } : {}) }; // #4778: dispatch-time relay pre-fetch
|
|
577
582
|
return remoteProvider({ batch: opts.batch, repo: opts.repo, settings, ...(pool ? { name: "pool" } : {}), env, credentials,
|
|
@@ -1025,6 +1025,34 @@ describe("remote/pool credential resolver (#5131)", () => {
|
|
|
1025
1025
|
assert.equal(hit.seen.at(-1).auth, "Bearer env-late-2");
|
|
1026
1026
|
});
|
|
1027
1027
|
|
|
1028
|
+
it("5159: a token_env absent from the env runs the keychain once, not on every request; the token_file bearer and a later env token still apply", async () => {
|
|
1029
|
+
const dir = tmpDir("kc-5159-");
|
|
1030
|
+
const file = join(dir, "explicit.token");
|
|
1031
|
+
writeFileSync(file, "file-tok\n");
|
|
1032
|
+
const hit = recorder();
|
|
1033
|
+
let calls = 0;
|
|
1034
|
+
const keychain = () => { calls++; return null; };
|
|
1035
|
+
const env = {};
|
|
1036
|
+
const p = providerByName("remote", { batch: { id: "b5159" }, repo: "o/r", exec: parseExecution({ mode: "remote", max_remote: "1", provider: "remote", endpoint: "https://runner.example.com", token_env: "COMPUTESHARE_TOKEN", token_file: file }),
|
|
1037
|
+
env, poolConfigPath: join(dir, "none.json"), fetchFn: hit.fetchFn, keychain });
|
|
1038
|
+
for (let i = 0; i < 4; i++) await p.capacity();
|
|
1039
|
+
assert.ok(hit.seen.length >= 4);
|
|
1040
|
+
assert.ok(hit.seen.every((x) => x.auth === "Bearer file-tok"), "every request carries the token_file bearer");
|
|
1041
|
+
assert.ok(calls <= 1, `keychain ran ${calls} times`);
|
|
1042
|
+
env.COMPUTESHARE_TOKEN = "env-late";
|
|
1043
|
+
await p.capacity();
|
|
1044
|
+
assert.equal(hit.seen.at(-1).auth, "Bearer env-late");
|
|
1045
|
+
let tcalls = 0;
|
|
1046
|
+
const tenv = {};
|
|
1047
|
+
const t = remoteTransportFor({ endpoint: "https://runner.example.com", tokenEnv: "COMPUTESHARE_TOKEN", tokenFile: file }, { env: tenv, router: null, fetchFn: hit.fetchFn, keychain: () => { tcalls++; return null; } });
|
|
1048
|
+
for (let i = 0; i < 4; i++) await t.capacity();
|
|
1049
|
+
assert.equal(hit.seen.at(-1).auth, "Bearer file-tok");
|
|
1050
|
+
assert.equal(tcalls, 1, "remoteTransportFor: one keychain lookup across requests");
|
|
1051
|
+
tenv.COMPUTESHARE_TOKEN = "env-late-2";
|
|
1052
|
+
await t.capacity();
|
|
1053
|
+
assert.equal(hit.seen.at(-1).auth, "Bearer env-late-2");
|
|
1054
|
+
});
|
|
1055
|
+
|
|
1028
1056
|
it("5131: remoteTransportFor's default credentials (gc) fall back to the matching router token", async () => {
|
|
1029
1057
|
const hit = recorder();
|
|
1030
1058
|
const t = remoteTransportFor({ endpoint: "http://127.0.0.1:7710" }, { env: {}, router: { endpoint: "http://127.0.0.1:7710", token: "router-tok" }, fetchFn: hit.fetchFn });
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
|
+
/**
|
|
4
|
+
* `forgedock fix-close-reasons <owner/repo> [--milestone <m>] [--apply]` (#5177, deferred from #5152). No LLM.
|
|
5
|
+
* Migration helper: an issue closed `not planned` that carries `workflow:merged` or `workflow:decomposed` was delivered
|
|
6
|
+
* (or moved to sub-issues), not dropped. It is re-closed as `completed` with a comment. One PATCH changes the reason in place
|
|
7
|
+
* (no reopen window). A `workflow:invalid` issue is a real drop and is never touched. Dry-run unless `--apply`.
|
|
8
|
+
*/
|
|
9
|
+
const DELIVERED = ["workflow:merged", "workflow:decomposed"];
|
|
10
|
+
const isNotPlanned = (r) => String(r ?? "").toUpperCase().replace(/\s/g, "_") === "NOT_PLANNED";
|
|
11
|
+
|
|
12
|
+
const commentFor = (label) => label === "workflow:decomposed"
|
|
13
|
+
? "Close reason corrected to `completed`: this issue was decomposed and its scope moved to its sub-issues, it was not dropped (`workflow:decomposed`). Re-closed by `forgedock fix-close-reasons` (#5177)."
|
|
14
|
+
: "Close reason corrected to `completed`: the work was delivered and merged, it was not dropped (`workflow:merged`). Re-closed by `forgedock fix-close-reasons` (#5177).";
|
|
15
|
+
|
|
16
|
+
/** Closed `not planned` issues that were delivered: [{number, label}], by issue number, once each. */
|
|
17
|
+
export async function findMisclosed({ gh, repo, milestone }) {
|
|
18
|
+
const found = new Map();
|
|
19
|
+
for (const label of DELIVERED) {
|
|
20
|
+
const out = await gh(["issue", "list", "-R", repo, "--state", "closed", "--label", label, ...(milestone ? ["--milestone", milestone] : []), "--limit", "1000", "--json", "number,stateReason,labels"]);
|
|
21
|
+
for (const i of JSON.parse(String(out || "[]"))) {
|
|
22
|
+
const names = (i.labels ?? []).map((l) => (typeof l === "string" ? l : l.name));
|
|
23
|
+
if (!isNotPlanned(i.stateReason) || names.includes("workflow:invalid") || found.has(i.number)) continue;
|
|
24
|
+
found.set(i.number, { number: i.number, label });
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
return [...found.values()].sort((a, b) => a.number - b.number);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export async function runFixCloseReasonsCli(argv, deps = {}) {
|
|
31
|
+
const val = (n) => { const i = argv.indexOf(n); return i >= 0 ? argv[i + 1] : null; };
|
|
32
|
+
const repo = argv[0] && !argv[0].startsWith("--") ? argv[0] : (val("--repo") ?? deps.repo ?? null);
|
|
33
|
+
if (!repo || !/^[^/\s]+\/[^/\s]+$/.test(repo)) throw new Error("usage: forgedock fix-close-reasons <owner/repo> [--milestone <title|number>] [--apply]");
|
|
34
|
+
const milestone = val("--milestone");
|
|
35
|
+
if (argv.includes("--milestone") && (!milestone || milestone.startsWith("--"))) throw new Error("--milestone requires a milestone title or number");
|
|
36
|
+
const apply = argv.includes("--apply");
|
|
37
|
+
const gh = deps.gh ?? (await import("./effects.mjs")).makeLeanIo({ repo }).gh;
|
|
38
|
+
const print = deps.print ?? ((t) => console.log(t));
|
|
39
|
+
const items = await findMisclosed({ gh, repo, milestone });
|
|
40
|
+
let changed = 0, failed = 0;
|
|
41
|
+
for (const { number, label } of items) {
|
|
42
|
+
if (!apply) { print(`would re-close #${number} as completed (${label})`); continue; }
|
|
43
|
+
try {
|
|
44
|
+
await gh(["api", "-X", "PATCH", `repos/${repo}/issues/${number}`, "-f", "state=closed", "-f", "state_reason=completed"]);
|
|
45
|
+
await gh(["issue", "comment", String(number), "-R", repo, "--body", commentFor(label)]);
|
|
46
|
+
changed++;
|
|
47
|
+
print(`re-closed #${number} as completed (${label})`);
|
|
48
|
+
} catch (e) { failed++; print(`#${number}: failed: ${String(e?.message ?? e).slice(0, 160)}`); }
|
|
49
|
+
}
|
|
50
|
+
print(`fix-close-reasons: ${items.length} found, ${changed} changed, ${failed} failed${apply ? "" : " (dry run, pass --apply to write)"}`);
|
|
51
|
+
return failed ? 1 : 0;
|
|
52
|
+
}
|