forgedock 1.54.1 → 1.55.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (115) hide show
  1. package/bin/config-schema.mjs +12 -0
  2. package/bin/engine/events.mjs +1 -0
  3. package/bin/engine/events.test.mjs +5 -1
  4. package/bin/engine/outcome-codes.mjs +3 -0
  5. package/bin/engine-cli.mjs +126 -34
  6. package/bin/forge-utils.mjs +37 -5
  7. package/bin/forgedock.mjs +54 -2
  8. package/bin/gc-schedule.mjs +83 -0
  9. package/bin/gc.mjs +66 -10
  10. package/bin/help-text.mjs +1 -1
  11. package/bin/hooks/pre-tool-use.mjs +1 -0
  12. package/bin/init-detect.mjs +73 -2
  13. package/bin/labels.json +5 -0
  14. package/bin/lean/admission.mjs +21 -1
  15. package/bin/lean/baselines.mjs +43 -0
  16. package/bin/lean/baselines.test.mjs +33 -0
  17. package/bin/lean/batch-health.mjs +43 -6
  18. package/bin/lean/batch-health.test.mjs +41 -1
  19. package/bin/lean/batch.mjs +41 -4
  20. package/bin/lean/batch.test.mjs +106 -3
  21. package/bin/lean/conformance.mjs +131 -12
  22. package/bin/lean/conformance.test.mjs +172 -3
  23. package/bin/lean/depcache.mjs +23 -2
  24. package/bin/lean/depcache.test.mjs +22 -0
  25. package/bin/lean/docsgate.mjs +137 -0
  26. package/bin/lean/docsgate.test.mjs +78 -0
  27. package/bin/lean/effects.mjs +31 -2
  28. package/bin/lean/enumerating.mjs +39 -13
  29. package/bin/lean/enumerating.test.mjs +20 -0
  30. package/bin/lean/execution.test.mjs +3 -3
  31. package/bin/lean/fastforward.mjs +93 -0
  32. package/bin/lean/fastforward.test.mjs +73 -0
  33. package/bin/lean/guardgate.mjs +38 -7
  34. package/bin/lean/guardgate.test.mjs +39 -0
  35. package/bin/lean/issuewatch-install.mjs +92 -0
  36. package/bin/lean/issuewatch-install.test.mjs +31 -0
  37. package/bin/lean/issuewatch-parity.mjs +33 -3
  38. package/bin/lean/issuewatch-parity.test.mjs +30 -5
  39. package/bin/lean/issuewatch-reconcile.mjs +123 -0
  40. package/bin/lean/issuewatch-reconcile.test.mjs +30 -0
  41. package/bin/lean/issuewatch-verify.mjs +51 -9
  42. package/bin/lean/issuewatch.mjs +153 -33
  43. package/bin/lean/issuewatch.test.mjs +243 -22
  44. package/bin/lean/lean.mjs +381 -75
  45. package/bin/lean/lean.test.mjs +437 -20
  46. package/bin/lean/light.mjs +11 -3
  47. package/bin/lean/light.test.mjs +27 -0
  48. package/bin/lean/lightlane.mjs +8 -3
  49. package/bin/lean/lightlane.test.mjs +20 -0
  50. package/bin/lean/mechfix.mjs +21 -2
  51. package/bin/lean/mechfix.test.mjs +28 -1
  52. package/bin/lean/orchestrate-children.test.mjs +10 -0
  53. package/bin/lean/orchestrate-owned.test.mjs +73 -0
  54. package/bin/lean/orchestrate.mjs +28 -4
  55. package/bin/lean/overlap.mjs +20 -0
  56. package/bin/lean/overlap.test.mjs +49 -0
  57. package/bin/lean/pagegate.mjs +152 -0
  58. package/bin/lean/pagegate.test.mjs +77 -0
  59. package/bin/lean/parked-relabel.mjs +32 -0
  60. package/bin/lean/parked-relabel.test.mjs +45 -0
  61. package/bin/lean/phaseledger.mjs +17 -2
  62. package/bin/lean/postdeploy-check.mjs +27 -0
  63. package/bin/lean/postdeploy-check.test.mjs +13 -1
  64. package/bin/lean/postrun.mjs +32 -0
  65. package/bin/lean/postrun.test.mjs +41 -0
  66. package/bin/lean/preflight.mjs +46 -0
  67. package/bin/lean/preflight.test.mjs +30 -1
  68. package/bin/lean/prompts.mjs +36 -6
  69. package/bin/lean/recovery.test.mjs +16 -0
  70. package/bin/lean/release-review.mjs +12 -1
  71. package/bin/lean/release-review.test.mjs +14 -0
  72. package/bin/lean/release.mjs +23 -2
  73. package/bin/lean/release.test.mjs +28 -1
  74. package/bin/lean/render.mjs +17 -6
  75. package/bin/lean/reproquality.mjs +116 -0
  76. package/bin/lean/reproquality.test.mjs +85 -0
  77. package/bin/lean/review-trigger.mjs +8 -3
  78. package/bin/lean/sandbox-budget.test.mjs +27 -0
  79. package/bin/lean/schedd.mjs +40 -11
  80. package/bin/lean/schedd.test.mjs +12 -1
  81. package/bin/lean/testadequacy.mjs +97 -0
  82. package/bin/lean/testadequacy.test.mjs +92 -0
  83. package/bin/lean/testsandbox.mjs +202 -0
  84. package/bin/lean/testsandbox.test.mjs +157 -0
  85. package/bin/lean/toolplace.mjs +5 -2
  86. package/bin/lean/toolplace.test.mjs +6 -0
  87. package/bin/lean/verify.mjs +6 -1
  88. package/bin/lean/verify.test.mjs +18 -2
  89. package/bin/lean/warmtree.mjs +77 -0
  90. package/bin/lean/warmtree.test.mjs +81 -0
  91. package/bin/review-staging.mjs +51 -9
  92. package/bin/stats/conformance-outcomes.mjs +12 -2
  93. package/bin/stats/depth.mjs +24 -1
  94. package/bin/stats/depth.test.mjs +21 -1
  95. package/bin/stats/index.mjs +5 -2
  96. package/bin/stats/query.mjs +2 -1
  97. package/commands/cleanup.md +18 -0
  98. package/commands/fd-introspect.md +19 -0
  99. package/commands/milestone.md +5 -1
  100. package/commands/pipeline-health/phase-2-metrics.md +4 -0
  101. package/commands/recover-orphans.md +31 -1
  102. package/commands/review-pr-staging.md +9 -0
  103. package/commands/review-pr.md +2 -0
  104. package/docs/CONFIG.md +26 -1
  105. package/docs/EVENTS.md +1 -0
  106. package/docs/ISSUE-WATCH.md +12 -3
  107. package/docs/eval/adversarial-bench.md +1 -1
  108. package/docs/eval/published/adversarial-2026-11-11.md +58 -0
  109. package/package.json +1 -1
  110. package/scripts/bench-lightlane.mjs +3 -2
  111. package/scripts/hotspots.sh +7 -4
  112. package/scripts/hotspots.test.sh +12 -0
  113. package/scripts/recover-orphans-stateless.test.sh +79 -0
  114. package/scripts/transition-label.sh +2 -0
  115. package/templates/workflows/forgedock-reopen-clean.yml +33 -0
@@ -174,8 +174,9 @@ ${HOST_RULES}${toolchainRule(toolchain)}${sparseRule(sparse)}${factsRule(facts)}
174
174
  ### History (introducing commit, prior fixes)
175
175
  ### Recommendation
176
176
  ### Related Issues
177
+ ### Test plan (bug issues: per deliver requirement, see the contract test_plan)
177
178
 
178
- If the issue is already fixed or invalid, write ${RESULT_FILE} {"status":"already-fixed|invalid","summary":"one line","evidence":["file:line ..."]} and stop. If it is blocked, write {"status":"blocked","summary":"",...} with a typed "block" (rules below) and stop.
179
+ If the issue is already fixed or invalid, write ${RESULT_FILE} {"status":"already-fixed|invalid","summary":"one line","evidence":["file:line ..."]} and stop. A feature already reachable (another name, or a stdlib or wrapped dependency function) is a duplicate: INVALID, naming the equivalent and its path; its deprecation counts against an alias. If it is blocked, write {"status":"blocked","summary":"",...} with a typed "block" (rules below) and stop.
179
180
 
180
181
  2. Otherwise write ${CONTRACT_FILE}, the frozen hand-off: a developer who never saw the issue must be able to implement and verify from this file alone.
181
182
  {"requirements":[{"id":"R1","quote":"<verbatim sentence or checklist item from the issue>","disposition":"deliver|defer|post-deploy|not-applicable","why":"<defer, post-deploy>","bucket":"<defer, post-deploy: post-deploy|verify-now|date:YYYY-MM-DD|owner:<action>|host>","check":"<post-deploy: id in .forge/post-deploy-checks.json>","evidence":"<file:line, required for not-applicable>","verify":"<optional: in_lane|out_of_band>"}],
@@ -192,6 +193,8 @@ A validate or repro command must not read a $TMPDIR file it did not create: each
192
193
  Scope is enforced by the engine: it checks the changed files against the deliverables plus typed amendments itself, so do not write a file-allowlist or denylist validate (git diff --name-only | grep); the engine drops such a validate at freeze.
193
194
  A new dependency between workspace packages (a workspace package added to a package.json dependencies, devDependencies or peerDependencies) must be a deliverable on that package.json whose change names the package and gives the reason, citing the architecture doc where there is one; "the lint allows it" or "there is a precedent" is not a reason on its own. Record each non-obvious choice in "decisions" with where its justification comes from (doc, lint, precedent or spec); omit the field when none. Then stop. Finish your reply with "Build reads:", the files (with line ranges) and searches the build needs; the build opens by issuing them all in one turn.
194
195
 
196
+ Blast radius: list neighbours (callers, shared modules, sibling configs) from the code graph; add \`"regression":[{"id":"G1","command":"","covers":""}]\` (engine runs it as validate). A post-deploy row needs a registered \`check\` and \`local_infeasible_why\`; developing or fixing the signal is never post-deploy.
197
+
195
198
  An added route needs its production ingress rule, and a touched topology.prod_parity surface its check or parity entry, cited in ${INVESTIGATION_FILE}. No decision may swap e2e for mocked tests without a forge-probe.
196
199
 
197
200
  ${BLOCK_RULES}`;
@@ -254,7 +257,7 @@ ${REVIEW_RUBRIC}
254
257
 
255
258
  Finally write ${RESULT_FILE}: {"status":"fixed","summary":"one line","requirements":[{"id":"R1","status":"implemented|partial|missing","evidence":"file:line","instrumented":"<true if out_of_band bench+job committed>"}],"validation":[{"id":"V1","command":"","exit":0}],"tests":[{"command":"","result":"pass|fail: ...","fails_without_fix":true|false|"unknown"}],"self_review":[{"question":"1","answer":"yes|no","evidence":""}],"amendments":[]}
256
259
  Optional "facts":{"decisions":[],"rejected":[{"approach":"","why":""}],"hotspots":[{"at":"file:line","why":""}],"conventions":[]}; rejected: approaches you dropped, with why.
257
- Docker: start containers with docker run --rm; pass --label for each entry of $FORGE_DOCKER_LABELS on every docker run, volume create, network create and build (compose: on services, volumes, networks); tear down via trap/finally.
260
+ Docker: start containers with docker run --rm; pass --label for each entry of $FORGE_DOCKER_LABELS on every docker run, volume create, network create and build (compose: override file labels on services, volumes, networks; keep $COMPOSE_PROJECT_NAME); tear down via trap/finally.
258
261
  If you started Docker containers or volumes that are still there, list their names in ${RESULT_FILE} as "resources":{"containers":[],"volumes":[]} so the engine removes them when the lane ends.
259
262
  If you find you are blocked, write "status":"blocked" with a typed "block" instead.`;
260
263
  }
@@ -287,9 +290,25 @@ export function unrunnableValidateNote(testRunners = null) {
287
290
  return `\n\nValidate and repro commands must pass bash -n (no prose notes), select tests that exist, and run from the right cwd (never combine \`poetry -C <dir>\` or \`uv run --project <dir>\` with repo-root-relative paths: use \`cd <dir> && poetry run pytest <dir-relative paths>\`)${map ? ` (forge.yaml verification.test_runners: ${map})` : ""}. An unrunnable validate (missing tool, wrong cwd, no tests selected) is never a block or "human" product-decision: run an equivalent through the repo's toolchain and record {"kind":"substitute-validate","validate":"V#","command":"<runnable equivalent>","why":""} in ${RESULT_FILE} amendments. A post-deploy requirement needs a registered check id; one that is a manual or production-credential action with no runnable check is disposition "defer" with bucket "owner:<action>" only when it needs credentials, spend, an account, a third party or a customer; read-only prod data is "host". forge.yaml validate.recipes rewrite matching commands at freeze.`;
288
291
  }
289
292
 
293
+ /** #5419: the R-docs rule for the planner; "" when forge.yaml docs.required_for is unset. */
294
+ export function docsPlanNote(cfg) {
295
+ if (!cfg?.required_for?.length) return "";
296
+ const where = cfg.paths?.length ? ` under ${cfg.paths.join(", ")}` : "";
297
+ const reg = cfg.registries?.length ? ` and their registration (${cfg.registries.join(", ")})` : "";
298
+ return `\n\nThis repo requires user docs for user-facing surfaces (${cfg.required_for.join(", ")}). When the issue adds or changes one (a public API endpoint, MCP tool, dashboard page or feature, CLI command or SDK method), ${CONTRACT_FILE} must carry a requirement R-docs and a deliverable for each docs page${where} to create or update${reg}. A \`/docs/...\` link the change adds must resolve to a page. If no docs apply, say why in the result file as docs: [{"surface":"<kind>","justification":"<why>"}].`;
299
+ }
300
+
301
+ /** #5428: the page_gate rule for the planner; "" when forge.yaml pages is off. */
302
+ export function pagePlanNote(cfg) {
303
+ if (!cfg?.require?.length) return "";
304
+ return `\n\nThis repo gates public pages (forge.yaml pages.require: ${cfg.require.join(", ")}). When the issue adds or changes a public page, ${CONTRACT_FILE} must carry "page_gate":{"design_spec":"<approved FORGE:DESIGN_SPEC ref, from /design>","seo":{"intent":"<target query>","icp":"<named ICP${cfg.icp_doc ? ` from ${cfg.icp_doc}` : ""}>","title":"","h1":"","meta":"","structured_data":"<schema.org type>","links_in":[],"links_out":[],"gsc_baseline":"","measure_by":"YYYY-MM-DD"},"geo":{"surfaces":["llms.txt","llms-full","markdown mirror","ai-catalog","MCP tool description"],"agent_question":"<natural-language question that must resolve to the page>"}}, plus a sitemap entry, metadata, canonical and structured data in the page, and the result file must list page_gate.screenshots (390 and 1440 wide). Never render raw JSON first or null samples on a public page.`;
305
+ }
306
+
290
307
  export function reproPlanNote(on) {
291
308
  if (!on) return "";
292
- return `\n\nThis issue is a bug. When it is testable, ${CONTRACT_FILE} must also carry "repro_test":{"path":"<test file>","id":"<test name>","command":"<exact command that runs only that test>"}: a test that fails on the base and passes after the fix. The command's environment must come from the repo's own lockfile or toolchain (its project runner, a lockfile export fed to uv run --with-requirements, or a forge.yaml validate.recipes entry); never a hand-picked --with package list with --offline, which cannot import the module under test (env.repro_unrunnable). The engine proves it with scripts/acceptance-red-green.sh (head's changed test files are overlaid on the base) and fails the run if it is not red on base and green on head. When it is not testable (specs, docs, workflows, environment), write "repro_test":"none","repro_test_reason":"<one line why>" instead.`;
309
+ return `\n\nThis issue is a bug. When it is testable, ${CONTRACT_FILE} must also carry "repro_test":{"path":"<test file>","id":"<test name>","command":"<exact command that runs only that test>"}: a test that fails on the base and passes after the fix. The command's environment must come from the repo's own lockfile or toolchain (its project runner, a lockfile export fed to uv run --with-requirements, or a forge.yaml validate.recipes entry); never a hand-picked --with package list with --offline, which cannot import the module under test (env.repro_unrunnable). The engine proves it with scripts/acceptance-red-green.sh (head's changed test files are overlaid on the base) and fails the run if it is not red on base and green on head. When it is not testable (specs, docs, workflows, environment), write "repro_test":"none","repro_test_reason":"<one line why>" instead.
310
+
311
+ Also write a \`### Test plan\` section in ${INVESTIGATION_FILE} and "test_plan":[{"requirement":"R1","proof":"<the root-cause observable that was wrong and must now hold, e.g. 'www.reddit.com/*.json returns 200 JSON', never 'the URL is rewritten'>","level":"unit|integration|e2e|live","level_reason":"<why this is the cheapest level that observes the cause>","repro":"<test id, red on base and green on head> or no-repro","reason":"<no-repro only>","regression":["<neighbouring behaviours that must stay green>"],"env":["<services, fixtures, packages>"],"command":"<exact command>"}] in ${CONTRACT_FILE}, one row per deliver requirement. A proof that restates a deliverable is rejected; never mock the component the bug lives in.`;
293
312
  }
294
313
 
295
314
  /** forge#4519: the repo's generated, bot-owned globs (forge.yaml maintenance.generated_paths via hotspots.sh); "" when none. */
@@ -468,6 +487,7 @@ You receive the GitHub issue with its comments, the frozen contract (requirement
468
487
  - requirements: one row per contract requirement id: implemented|partial|missing|deferred|post-deploy|not-applicable, with evidence as a backtick-quoted repo-relative path:line copied verbatim from the changed files, including (group), [slug] and [...slug] folders (e.g. \`apps/web/app/(console)/layout.tsx:12\`, not route.ts:12) and the validate id or test that proves it (validated_by). For a defer or post-deploy requirement add deferral_ok: true only if it is genuinely separate work or only checkable after a deploy, false if it belongs in this change, including an outcome criterion (a metric, rate or log expectation) this change could ship as a test, metric or alert, or a read-only production check possible now (bucket verify-now). For a verify out_of_band row (measured by the named job, not in this lane) set instrumented: true only when its budget test or bench is committed and that job is configured, with that path:line as evidence; false otherwise. Do not judge the measured result.
469
488
  - post-deploy requirements: deferral_ok is false when the requirement has no \`check\` id, or its check is neither in .forge/post-deploy-checks.json on the default branch nor added by this change (the commands run from that file only).
470
489
  - scope: one row per changed file, pre-filled with the engine's authorization: the deliverable id that authorizes it (deliverables may be directories or globs), "test", "incidental" (changelog, lockfile), or "none" with what it changes. Change it only if the diff shows the file does something its deliverable does not cover.
490
+ - test_adequacy (optional, on a requirement row): {"verdict":"adequate|weak","reason":""}; weak only when the test would still pass with the bug present (it asserts the patch or routing, not the root cause).
471
491
  - preserve: one row per preserve id: intact|violated|unverified, with path:line. The skeleton starts each at "unverified"; set intact only after checking it.
472
492
  - regressions: concrete breakages only, each with path:line.
473
493
 
@@ -523,6 +543,9 @@ export function decisionNote(comments = []) {
523
543
 
524
544
  /** #5099: one check line per review domain (domains from review-trigger.mjs pathDomains); mirrors the /review-pr personas. */
525
545
  export const DOMAIN_CHECKS = Object.freeze({
546
+ design: "A public page diff with no approved FORGE:DESIGN_SPEC, or a rendering that ignores it (raw JSON as main content, null samples, dead-end empty states, no 390/1440 check), is a regression.",
547
+ "seo-geo": "A public page diff with no target intent/ICP, title/H1/meta, canonical, structured data, sitemap entry or internal links, or no GEO surface (llms.txt, markdown mirror, ai-catalog, MCP description) an agent question resolves to, is a regression.",
548
+ docs: "A user-facing diff (public API endpoint, MCP tool, dashboard page, CLI command, SDK method) with no matching docs change, or docs that contradict the code (endpoint paths, fields, scopes), is a regression.",
526
549
  frontend: "Dynamic API in a static/ISR tree: a headers(), cookies(), connection() or searchParams read in a layout, a not-found/error boundary or a module they import, when the route tree is static or ISR (revalidate, generateStaticParams, dynamic = 'force-static'), opts the route out of static rendering or throws at render and turns pages into HTTP 500.",
527
550
  });
528
551
 
@@ -534,12 +557,19 @@ export function domainChecksBlock(domains = []) {
534
557
  return `\n<domain_checks>\nThis diff touches these review domains. Report every finding below as a regressions row with path:line (it blocks the merge).\n${lines.join("\n")}\n</domain_checks>`;
535
558
  }
536
559
 
537
- export function reviewerPrompt({ issue, comments = [], contract, result, files = [], diff, stat = "", base = "", structure = "", ignore = [`${LEAN_DIR}/`], skeleton = null, investigationVerdict = null, domains = [], relaxations = [] }) {
560
+ /** #5446: the engine flagged the repro_test (patch_echo, mutation_survivor); the reviewer must accept or reject it explicitly. "" otherwise. */
561
+ export function reproFlagNote(flag) {
562
+ if (flag !== "patch_echo" && flag !== "mutation_survivor") return "";
563
+ const why = flag === "patch_echo" ? "its assertions only compare against literals this diff introduced (no behaviour or output is asserted)" : "it still passes when the fix's changed lines are mutated";
564
+ return `\n<repro_quality>${flag}: the repro_test ${why}. Accept or reject it explicitly in a row (a rejection is a failing row naming the behaviour the test must exercise).</repro_quality>`;
565
+ }
566
+
567
+ export function reviewerPrompt({ issue, comments = [], contract, result, files = [], diff, stat = "", base = "", structure = "", ignore = [`${LEAN_DIR}/`], skeleton = null, investigationVerdict = null, domains = [], relaxations = [], reproFlag = null }) {
538
568
  const notes = comments.map((c) => String(c?.body ?? "")).filter((b) => !/^<!-- FORGE:/.test(b.trim()));
539
569
  const decisions = comments.filter((c) => isDecision(c?.body) && isTrustedIssueComment(c)).map((c) => String(c.body)); // #4901: operator decisions bind the review; other FORGE: records stay out
540
570
  notes.push(...decisions);
541
571
  const sk = JSON.stringify(skeleton ?? reviewSkeleton(contract ?? {}, files, ignore), null, 1);
542
- return `Issue #${issue.number}: ${issue.title}\n\n<issue_body>\n${cap(issue.body ?? "", 20000)}\n</issue_body>\n\n<issue_comments>\n${cap(notes.join("\n---\n"), 8000)}\n</issue_comments>\n\n<contract>\n${cap(JSON.stringify(contract ?? {}, null, 1), 12000)}\n</contract>\n\n<builder_result>\n${cap(JSON.stringify(result ?? {}, null, 1), 6000)}\n</builder_result>\n\n${investigationVerdict ? `<investigation_verdict>${investigationVerdict}</investigation_verdict>\n${VERDICT_RULE}\n\n` : ""}<changed_files>\n${files.join("\n")}\n</changed_files>\n\n<rubric>\n${REVIEW_RUBRIC}\n</rubric>\n\n<row_skeleton>\n${cap(sk, 30000)}\n</row_skeleton>\n\n<diff>\n${boundDiff(diff, { stat, base })}\n</diff>${structure ? `\n<structure>${String(structure).replace(/[\r\n]+/g, " ")}</structure>` : ""}${domainChecksBlock(domains)}${relaxationBlock(relaxations)}`;
572
+ return `Issue #${issue.number}: ${issue.title}\n\n<issue_body>\n${cap(issue.body ?? "", 20000)}\n</issue_body>\n\n<issue_comments>\n${cap(notes.join("\n---\n"), 8000)}\n</issue_comments>\n\n<contract>\n${cap(JSON.stringify(contract ?? {}, null, 1), 12000)}\n</contract>\n\n<builder_result>\n${cap(JSON.stringify(result ?? {}, null, 1), 6000)}\n</builder_result>\n\n${investigationVerdict ? `<investigation_verdict>${investigationVerdict}</investigation_verdict>\n${VERDICT_RULE}\n\n` : ""}<changed_files>\n${files.join("\n")}\n</changed_files>\n\n<rubric>\n${REVIEW_RUBRIC}\n</rubric>\n\n<row_skeleton>\n${cap(sk, 30000)}\n</row_skeleton>\n\n<diff>\n${boundDiff(diff, { stat, base })}\n</diff>${structure ? `\n<structure>${String(structure).replace(/[\r\n]+/g, " ")}</structure>` : ""}${domainChecksBlock(domains)}${relaxationBlock(relaxations)}${reproFlagNote(reproFlag)}`;
543
573
  }
544
574
 
545
575
  /**
@@ -555,7 +585,7 @@ export function reviewerRepairPrompt({ missing = [], problems = [], rows = null,
555
585
  /** Pre-filter (#4123): one read-only, single-turn check of an issue a cheap signal flagged as possibly already fixed. */
556
586
  export const PREFILTER_SYSTEM = `You check whether one GitHub issue is still open work. Read-only: use Read, Grep and Glob on the repository when needed. Answer in a single turn.
557
587
 
558
- Signals from the engine (a merged PR that mentions the issue, or code paths the issue names that no longer exist) are hints, not proof. Answer ALREADY-FIXED only when the code you can see shows the described problem is gone or the requested change is present, and cite file:line. Answer INVALID only when the issue cannot apply to this code at all. Otherwise answer CONFIRMED.
588
+ Signals from the engine (a merged PR that mentions the issue, or code paths the issue names that no longer exist) are hints, not proof. Answer ALREADY-FIXED only when the code you can see shows the described problem is gone or the requested change is present, and cite file:line. Answer INVALID only when the issue cannot apply to this code at all. A feature request whose behaviour is already reachable under another name, or from the stdlib or a dependency the project wraps, is a duplicate: answer INVALID and name the equivalent and its path; a deprecation of it counts against a new alias. Otherwise answer CONFIRMED.
559
589
 
560
590
  Output ONLY a JSON object in a json code fence:
561
591
  {"verdict":"CONFIRMED|ALREADY-FIXED|INVALID","summary":"<one line>","evidence":["<file:line or PR/commit reference showing it>"]}
@@ -559,3 +559,19 @@ describe("#4318: the batch-exit relabel survives a throw and a signal; relabel r
559
559
  });
560
560
  });
561
561
  });
562
+
563
+ describe("#5423 env.tool_missing recovery placement", () => {
564
+ const run = async (maxAttempts) => {
565
+ const calls = [];
566
+ await orchestrate({ issues: [5], parallel: 2, recovery: { maxAttempts, mechanicalMaxAttempts: maxAttempts }, readBody: async () => "",
567
+ remote: { max: 2, isRemote: () => true, place: () => ({ where: "remote", reason: "mode remote" }), admit: () => ({ ok: true }), onBudget: "stop", costPerMinute: 0 },
568
+ runOne: async (n, _l, ctx = {}) => {
569
+ calls.push(ctx.placement?.where);
570
+ return calls.length <= maxAttempts ? { terminalReason: "needs-human", code: "env.tool_missing", detail: `vitest ${calls.length}`, placement: { where: ctx.placement?.where } } : { terminalReason: "merged", pr: 9 };
571
+ } });
572
+ return calls;
573
+ };
574
+ it("the first recovery of a remote run retries remotely, a repeat goes to the host", async () => {
575
+ assert.deepEqual(await run(2), ["remote", "remote", "local"]);
576
+ });
577
+ });
@@ -126,7 +126,7 @@ async function runReview({ seam, pr, def, delta = null }) {
126
126
  if ((st.notes ?? []).length) await seam.addNotes(pr, st.notes);
127
127
  const sum = await seam.summary({ pr, filed });
128
128
  if (!sum.data) return blocked(`the gate summary was not posted (exit ${sum.code}): ${(sum.lines ?? []).slice(-1).join("").slice(0, 200)}`);
129
- return { pr, head: st.head, verdict: sum.data.verdict, marker: sum.data.marker, ciFailing: sum.data.ciFailing, filed, blocking, delta: st.delta?.from ?? null };
129
+ return { pr, head: st.head, verdict: sum.data.verdict, marker: sum.data.marker, ciFailing: sum.data.ciFailing, ciCancelOnly: Boolean(sum.data.ciCancelOnly), filed, blocking, delta: st.delta?.from ?? null };
130
130
  }
131
131
 
132
132
  /** Review step. @returns {{pr, head, verdict, marker, filed, blocking}|{blocked: true, reason: string}} */
@@ -143,6 +143,17 @@ export async function fixStep(ctx) {
143
143
  const seam = seamOf(ctx);
144
144
  for (let round = 0; r.marker !== "FORGE:GATE_PASS"; round++) {
145
145
  if (round >= MAX_FIX_ROUNDS) return blocked(`still ${r.verdict} after ${MAX_FIX_ROUNDS} fix round(s)`);
146
+ // Only cancelled duplicate runs are red (#5502): nothing to fix. The summary reruns them once; re-summarise without spending the round.
147
+ if (!r.blocking?.length && r.ciFailing > 0 && r.ciCancelOnly) {
148
+ const sum = await seam.summary({ pr: r.pr, filed: r.filed ?? [] });
149
+ if (!sum.data) return blocked(`the gate summary was not posted (exit ${sum.code}) after rerunning the cancelled checks of #${r.pr}`);
150
+ r = { ...r, verdict: sum.data.verdict, marker: sum.data.marker, ciFailing: sum.data.ciFailing, ciCancelOnly: Boolean(sum.data.ciCancelOnly) };
151
+ ctx.state.steps.review = { ...ctx.state.steps.review, result: r };
152
+ ctx.save();
153
+ if (r.marker === "FORGE:GATE_PASS") break;
154
+ if (r.ciCancelOnly) return blocked(`required checks of #${r.pr} still cancelled after a rerun, with no failure to fix`);
155
+ round--; continue;
156
+ }
146
157
  // Blocking findings are already filed issues; red CI has none, so it gets one issue naming the failing checks.
147
158
  const issues = [...(r.blocking ?? [])];
148
159
  if (r.ciFailing > 0) {
@@ -192,6 +192,20 @@ describe("fixStep", () => {
192
192
  assert.deepEqual(s.log.filter((e) => e[0] === "lane").map((e) => e[1]), [101, 100]);
193
193
  });
194
194
 
195
+ it("only cancelled CI: no CI issue, no lane, no round spent; re-summarises and goes on", async () => {
196
+ const pass = { code: 0, data: { verdict: "APPROVE FOR DEPLOY", marker: "FORGE:GATE_PASS", ciFailing: 0 }, lines: [] };
197
+ const s = fakeSeam({ summary: pass });
198
+ const r = await fixStep(ctx(s, { review: { result: { ...failed, blocking: [], filed: [], ciFailing: 2, ciCancelOnly: true } } }));
199
+ assert.deepEqual(s.log, [["summary", []]]);
200
+ assert.equal(r.blocked, undefined);
201
+ assert.equal(r.verdict, "APPROVE FOR DEPLOY");
202
+ const still = { code: 0, data: { verdict: "BLOCK DEPLOY", marker: "FORGE:GATE_FAILURE", ciFailing: 1, ciCancelOnly: true }, lines: [] };
203
+ const s2 = fakeSeam({ summary: still });
204
+ const r2 = await fixStep(ctx(s2, { review: { result: { ...failed, blocking: [], filed: [], ciFailing: 1, ciCancelOnly: true } } }));
205
+ assert.match(r2.reason, /still cancelled/);
206
+ assert.ok(!s2.log.some((e) => e[0] === "ci-issue" || e[0] === "lane"));
207
+ });
208
+
195
209
  it("blocks when the verdict is not a pass but there is nothing to fix", async () => {
196
210
  assert.match((await fixStep(ctx(fakeSeam(), { review: { result: { ...failed, blocking: [], ciFailing: 0 } } }))).reason, /nothing to fix|neither/);
197
211
  });
@@ -162,6 +162,26 @@ export async function gateState({ io, repo, pr, head }) {
162
162
  return { marker, deployGate: gate?.conclusion ?? null };
163
163
  }
164
164
 
165
+ const GATE_POLLS = 12, GATE_POLL_MS = 10_000;
166
+
167
+ /** Re-run the newest gate-marker-check run on `head`: the bot's GATE_PASS comment never triggers it, so the status would stay pending. */
168
+ async function retriggerGate({ io, repo, head }) {
169
+ try {
170
+ const runs = json(await io.gh(["run", "list", "--repo", repo, "--workflow", "gate-marker-check.yml", "--commit", head, "--json", "databaseId", "--limit", "1"])) ?? [];
171
+ if (runs[0]?.databaseId) await io.gh(["run", "rerun", String(runs[0].databaseId), "--repo", repo]);
172
+ } catch { /* a run still in progress cannot be rerun, and it re-reads the markers anyway: just wait */ }
173
+ }
174
+
175
+ /** Re-trigger the gate, then poll (bounded) until `forge/deploy-gate` is success or failure; @returns the last gateState. */
176
+ async function awaitGate({ io, repo, pr, head, gate }) {
177
+ await retriggerGate({ io, repo, head });
178
+ for (let i = 0; i < GATE_POLLS && gate.deployGate !== "success" && gate.deployGate !== "failure"; i++) {
179
+ await io.sleep(GATE_POLL_MS);
180
+ gate = await gateState({ io, repo, pr, head });
181
+ }
182
+ return gate;
183
+ }
184
+
165
185
  async function promotionStep(ctx) {
166
186
  const { io, repo, state, opts } = ctx;
167
187
  const { pr } = state.steps["release-pr"].result;
@@ -174,11 +194,12 @@ async function promotionStep(ctx) {
174
194
  const chain = checkChain({ git: io.git, record: state.release, sha: head, staging: ctx.staging, exact: true });
175
195
  if (!chain.ok) return { stopped: true, why: `release head ${head} is not snapshot + recorded cherry-picks: ${chain.why}`, head };
176
196
  }
177
- const gate = await gateState({ io, repo, pr, head });
197
+ let gate = await gateState({ io, repo, pr, head });
178
198
  if (gate.marker !== "pass") return { stopped: true, why: `no FORGE:GATE_PASS on #${pr} (last marker: ${gate.marker ?? "none"})`, head };
199
+ if (gate.deployGate !== "success" && gate.deployGate !== "failure") gate = await awaitGate({ io, repo, pr, head, gate });
179
200
  const cmd = `gh pr merge ${pr} --repo ${repo} --merge --match-head-commit ${head}`;
180
201
  if (!opts.merge && !ctx.config.autoMerge) { io.print(`GATE_PASS on #${pr}. Merge when ready:\n ${cmd}`); return { stopped: true, why: "GATE_PASS; promotion is opt-in (--merge or release.auto_merge)", cmd, head, gate }; }
181
- if (gate.deployGate !== "success") return { stopped: true, why: `forge/deploy-gate is ${gate.deployGate ?? "absent"}, not success`, head, gate };
202
+ if (gate.deployGate !== "success") return { stopped: true, why: `forge/deploy-gate is ${gate.deployGate ?? "absent"}, not success${gate.deployGate === "failure" ? "" : ` after ${GATE_POLLS} polls`}`, head, gate };
182
203
  await io.gh(["pr", "merge", String(pr), "--repo", repo, "--merge", "--match-head-commit", head]);
183
204
  return { merged: true, head, gate };
184
205
  }
@@ -34,9 +34,11 @@ function fakeIo(world = {}) {
34
34
  if (a[0] === "pr" && a[1] === "view" && j.includes("--json state,mergeCommit,headRefOid")) return JSON.stringify({ state: w.prState ?? "OPEN", mergeCommit: w.prState === "MERGED" ? { oid: "m".repeat(40) } : null, headRefOid: HEAD });
35
35
  if (j.includes("--json headRefOid")) return JSON.stringify({ headRefOid: HEAD });
36
36
  if (j.includes("--json comments")) return JSON.stringify({ comments: w.comments });
37
- if (a[0] === "api" && /\/commits\/[^/]+\/status$/.test(a[1])) return JSON.stringify(w.statusGate ? [{ name: "forge/deploy-gate", conclusion: w.statusGate }] : []);
37
+ if (a[0] === "api" && /\/commits\/[^/]+\/status$/.test(a[1])) return JSON.stringify(io.reran && w.afterRerun ? [{ name: "forge/deploy-gate", conclusion: w.afterRerun }] : w.statusGate ? [{ name: "forge/deploy-gate", conclusion: w.statusGate }] : []);
38
38
  if (a[0] === "api") return JSON.stringify(w.gate ? [{ name: "forge/deploy-gate", conclusion: w.gate }] : []);
39
39
  if (a[0] === "pr" && a[1] === "merge") return "";
40
+ if (a[0] === "run" && a[1] === "list") return JSON.stringify(w.noRun ? [] : [{ databaseId: 42 }]);
41
+ if (a[0] === "run" && a[1] === "rerun") { if (w.rerunFails) throw new Error("run in progress"); io.reran = (io.reran ?? 0) + 1; return ""; }
40
42
  throw new Error(`unexpected gh ${j}`);
41
43
  },
42
44
  };
@@ -84,6 +86,31 @@ describe("release job (#5211)", () => {
84
86
  assert.equal(pend.out.status, "stopped");
85
87
  });
86
88
 
89
+ it("#5417: a pending gate is re-run on the head, awaited, and --merge then merges", async () => {
90
+ const r = await promote({ gate: null, statusGate: "pending", afterRerun: "success" }, { opts: { merge: true } });
91
+ assert.equal(r.out.status, "done");
92
+ assert.equal(r.io.reran, 1);
93
+ assert.ok(r.io.calls.some((a) => a[0] === "run" && a.includes("--commit") && a.includes(HEAD)));
94
+ assert.ok(r.io.calls.some((a) => a[1] === "merge"));
95
+ assert.equal(r.io.sleeps.length, 1);
96
+ });
97
+
98
+ it("#5417: without --merge the wait still happens, then the merge command is printed", async () => {
99
+ const r = await promote({ gate: null, statusGate: "pending", afterRerun: "success" });
100
+ assert.equal(r.io.reran, 1);
101
+ assert.ok(r.io.printed.some((l) => l.includes("gh pr merge 7")));
102
+ });
103
+
104
+ it("#5417: a gate that stays pending stops after the bounded polls; a failing rerun does not throw", async () => {
105
+ const r = await promote({ gate: null, statusGate: "pending", rerunFails: true }, { opts: { merge: true } });
106
+ assert.equal(r.out.status, "stopped");
107
+ assert.equal(r.io.sleeps.length, 12);
108
+ assert.ok(!r.io.calls.some((a) => a[1] === "merge"));
109
+ const f = await promote({ gate: "failure" }, { opts: { merge: true } });
110
+ assert.equal(f.io.sleeps.length, 0);
111
+ assert.equal(f.io.reran, undefined);
112
+ });
113
+
87
114
  it("#5266: a release PR merged by hand moves to post-merge with the merge sha, without the opt-in stop", async () => {
88
115
  const io = fakeIo({ prState: "MERGED" }), root = tmp(), id = newReleaseId();
89
116
  const mod = await import("./release.mjs");
@@ -130,7 +130,9 @@ export function renderContract(c, hash, { compact = false, scope = null } = {})
130
130
  const del = (c.deliverables ?? []).map((d) => `| ${esc(d.id)} | \`${esc(d.path)}\` | ${esc(d.change)} | ${esc((d.requirements ?? []).join(", "))} |`).join("\n");
131
131
  const dec = Array.isArray(c.decisions) && c.decisions.length // forge#4165: decision provenance
132
132
  ? `\n\n### Decisions\n| Id | Choice | Justification | Source |\n| --- | --- | --- | --- |\n${c.decisions.map((k) => `| ${esc(k?.id)} | ${esc(k?.choice)} | ${esc(k?.justification)} | ${esc(k?.source)} |`).join("\n")}` : "";
133
- return `## Builder Contract (frozen \`${hash}\`)\n\n### Requirements\n| Id | From the issue | Disposition |\n| --- | --- | --- |\n${req}\n\n### Deliverables\n${del ? `| Id | Path | Change | Requirements |\n| --- | --- | --- | --- |\n${del}` : "None."}\n\n### Preserve\n${(c.preserve ?? []).map((p) => `- ${escl(p.id)}: ${escl(p.what)}`).join("\n") || "None."}\n\n### Validate\n${(c.validate ?? []).map((v) => `- ${escl(v.id)}: \`${escl(v.command).replace(/`/g, "'")}\``).join("\n") || NR}${dec}\n\n${json}`;
133
+ const tp = Array.isArray(c.test_plan) && c.test_plan.length // #5445: the frozen test plan
134
+ ? `\n\n### Test plan\n| Requirement | Proof | Level | Repro | Regression | Env | Command |\n| --- | --- | --- | --- | --- | --- | --- |\n${c.test_plan.map((t) => `| ${esc(t?.requirement)} | ${esc(t?.proof)} | ${esc(t?.level)} | ${esc(/^no-repro$/i.test(String(t?.repro ?? "").trim()) ? `no-repro: ${t?.reason ?? ""}` : t?.repro)} | ${esc(Array.isArray(t?.regression) ? t.regression.join("; ") : t?.regression)} | ${esc(Array.isArray(t?.env) ? t.env.join("; ") : t?.env)} | \`${esc(t?.command).replace(/`/g, "'")}\` |`).join("\n")}` : "";
135
+ return `## Builder Contract (frozen \`${hash}\`)\n\n### Requirements\n| Id | From the issue | Disposition |\n| --- | --- | --- |\n${req}\n\n### Deliverables\n${del ? `| Id | Path | Change | Requirements |\n| --- | --- | --- | --- |\n${del}` : "None."}\n\n### Preserve\n${(c.preserve ?? []).map((p) => `- ${escl(p.id)}: ${escl(p.what)}`).join("\n") || "None."}\n\n### Validate\n${(c.validate ?? []).map((v) => `- ${escl(v.id)}: \`${escl(v.command).replace(/`/g, "'")}\``).join("\n") || NR}${tp}${dec}\n\n${json}`;
134
136
  }
135
137
  /** {contract, hash, scope, text} from a FORGE:CONTRACT comment body (scope null for a pre-#4265 comment), or null. */
136
138
  export function parseContractComment(body) {
@@ -153,20 +155,27 @@ export function parseAmendmentsComment(body) {
153
155
  }
154
156
 
155
157
  /** FORGE:REVIEW for a conforming change: the engine-computed verdict and the reviewer's rows. */
156
- export function renderReview(rv, contract) {
158
+ /** #5449: the Test adequacy table (rows from testadequacy.mjs), or "" without rows. */
159
+ export function renderTestAdequacy(rows) {
160
+ if (!rows?.length) return "";
161
+ const body = rows.map((r) => `| ${esc(r.id)} | ${esc(r.planned)} | ${esc(r.test)} | ${esc(r.level)} | ${esc(r.redgreen)} | ${esc(r.mutation)} | ${esc(r.regression)} | ${esc(r.verdict === "weak" ? `weak (${r.reason})` : r.verdict)} |`).join("\n");
162
+ return `\n\n**Test adequacy**\n| Requirement | Planned proof | Test written | Level | Red→green | Mutation | Regression set | Verdict |\n| --- | --- | --- | --- | --- | --- | --- | --- |\n${body}`;
163
+ }
164
+
165
+ export function renderReview(rv, contract, adequacy = null) {
157
166
  const rows = contract.requirements.map((r) => {
158
167
  const x = (rv.requirements ?? []).find((y) => y.id === r.id) ?? {};
159
168
  const oob = r.verify === "out_of_band" ? ` (out of band${r.evidence ? `: ${r.evidence}` : ""})` : "";
160
169
  return `| ${esc(r.id)} | ${oob ? esc(`${x.status ?? ""}${oob}`) : esc(x.status)}${r.tracked ? ` (tracked ${r.tracked})` : ""} | ${esc(x.evidence)} | ${esc(x.validated_by)} |`;
161
170
  }).join("\n");
162
171
  const cov = rv.issue_coverage ?? [];
163
- return `## Conformance Review\n**Verdict:** CONFORMS (computed by the engine from the rows below)\n\n| Requirement | Status | Evidence | Validated by |\n| --- | --- | --- | --- |\n${rows}\n\n**Issue coverage:** ${cov.filter((c) => c.status === "covered").length}/${cov.length} issue requirement(s) covered by the contract\n**Scope:** ${(rv.scope ?? []).map((s) => `\`${escl(s.file)}\` ← ${escl(s.authorized_by)}`).join(", ") || NR}\n**Preserve:** ${(rv.preserve ?? []).map((p) => `${escl(p.id)} ${escl(p.status)}`).join(", ") || "none"}\n**Regressions:** none\n\n**Notes:** ${escl(rv.summary)}`;
172
+ return `## Conformance Review\n**Verdict:** CONFORMS (computed by the engine from the rows below)\n\n| Requirement | Status | Evidence | Validated by |\n| --- | --- | --- | --- |\n${rows}\n\n**Issue coverage:** ${cov.filter((c) => c.status === "covered").length}/${cov.length} issue requirement(s) covered by the contract\n**Scope:** ${(rv.scope ?? []).map((s) => `\`${escl(s.file)}\` ← ${escl(s.authorized_by)}`).join(", ") || NR}\n**Preserve:** ${(rv.preserve ?? []).map((p) => `${escl(p.id)} ${escl(p.status)}`).join(", ") || "none"}\n**Regressions:** none${renderTestAdequacy(adequacy)}\n\n**Notes:** ${escl(rv.summary)}`;
164
173
  }
165
174
 
166
175
  /** FORGE:REVIEW in shadow mode: what the enforced gate would have done, without enforcing it. */
167
- export function renderShadowReview({ would, failures = [], review, contract, degraded = null }) {
176
+ export function renderShadowReview({ would, failures = [], review, contract, degraded = null, adequacy = null }) {
168
177
  const head = would === "conforms" ? "would PASS" : `would BLOCK (${escl(would)})`;
169
- const rows = review ? `\n\n${renderReview(review, contract).split("\n").slice(2).join("\n")}` : "";
178
+ const rows = review ? `\n\n${renderReview(review, contract, adequacy).split("\n").slice(2).join("\n")}` : "";
170
179
  const fl = failures.length ? `\n\n**What the enforced gate would have flagged:**\n${failures.slice(0, 30).map((f) => `- \`${escl(f.code)}\`: ${escl(f.detail)}`).join("\n")}` : "";
171
180
  const dg = degraded ? `\n\n**Review degraded:** the review stayed incomplete after the targeted re-ask; merged with label \`review-degraded\`, follow-up ${escl(degraded)}.` : "";
172
181
  return `## Conformance Review (shadow mode: not enforced)\n**Gate verdict:** ${head}. In shadow mode a requirement not implemented (found by the review or the precheck), a regression, or a review without complete rows blocks; accepted deferrals are filed as follow-ups.${fl}${dg}${rows}`;
@@ -204,8 +213,10 @@ export function renderStructure(s) {
204
213
  ];
205
214
  return `**Structure**\n| Delta | Value |\n| --- | --- |\n${rows.map(([k, v]) => `| ${k} | ${esc(v)} |`).join("\n")}\n\n`;
206
215
  }
216
+ /** #5447: `N declared, N ran, N red→green, N skipped(reason)`. */
217
+ const testsCell = (t) => `${t.declared} declared, ${t.ran} ran, ${t.redGreen} red→green, ${t.skipped?.length ?? 0} skipped${t.skipped?.length ? `(${[...new Set(t.skipped.map((s) => s.reason))].join(", ")})` : ""}`;
207
218
  export function renderTrajectory(T) {
208
- const rows = [["Validate", T.validate], ["Plan", T.plan], ["Implement", T.implement], ...(T.verify ? [["Verify", T.verify]] : []), ["Review", T.review], ["PR", T.pr], ["Base Sync", T.baseSync ?? "not needed"], ["Merge", T.merge], ["Close", T.close]];
219
+ const rows = [["Validate", T.validate], ["Plan", T.plan], ["Implement", T.implement], ...(T.verify ? [["Verify", T.verify]] : []), ...(T.tests ? [["Tests", testsCell(T.tests)]] : []), ["Review", T.review], ["PR", T.pr], ["Base Sync", T.baseSync ?? "not needed"], ["Merge", T.merge], ["Close", T.close]];
209
220
  const cellPair = (v) => {
210
221
  const [res, notes] = Array.isArray(v) ? v : [v, ""];
211
222
  return `${cell(res ?? "not reached")} | ${notes ? cell(notes) : "-"}`;
@@ -0,0 +1,116 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ /**
4
+ * Repro quality (#5446): a repro_test that is red on base and green on head can still prove nothing about the bug. Two cheap,
5
+ * deterministic checks (0 LLM calls): a patch-echo heuristic (assertions only compare literals the same diff introduced) and
6
+ * a targeted mutation of the fix's added lines (the repro must fail on at least one). Result: behavioural | patch_echo |
7
+ * mutation_survivor | none.
8
+ */
9
+ import { isTestPath } from "./conformance.mjs";
10
+
11
+ export const REPRO_QUALITY = ["behavioural", "patch_echo", "mutation_survivor", "none"];
12
+ const SRC_EXT = /\.(?:m?[jt]sx?|cjs|py|go)$/i;
13
+ const ASSERT_RE = /\b(?:assert\w*|expect|should|self\.assert\w*|t\.(?:Error|Fatal)f?)\b/;
14
+ const LIT_RE = /"(?:[^"\\]|\\.)+"|'(?:[^'\\]|\\.)+'|`(?:[^`\\]|\\.)+`|\b\d+(?:\.\d+)?\b/g;
15
+
16
+ /** Added lines per file of a unified diff: [{file, line (new-file number), text}]. */
17
+ export function addedLines(diff) {
18
+ const out = [];
19
+ let file = null, n = 0;
20
+ for (const l of String(diff ?? "").split("\n")) {
21
+ if (l.startsWith("+++ ")) { file = l.slice(4).replace(/^b\//, ""); if (file === "/dev/null") file = null; continue; }
22
+ const h = /^@@ -\d+(?:,\d+)? \+(\d+)/.exec(l);
23
+ if (h) { n = Number(h[1]); continue; }
24
+ if (!file || l.startsWith("---")) continue;
25
+ if (l.startsWith("+")) { out.push({ file, line: n, text: l.slice(1) }); n++; }
26
+ else if (!l.startsWith("-") && !l.startsWith("\\")) n++;
27
+ }
28
+ return out;
29
+ }
30
+
31
+ const literals = (s) => (String(s).match(LIT_RE) ?? []).filter((x) => x.length > 2 || /^\d/.test(x));
32
+
33
+ /**
34
+ * True when the added test assertions only compare against literals that the non-test diff introduced and no assertion
35
+ * calls anything or reads an output (no call on the asserted subject beyond property access).
36
+ */
37
+ export function patchEcho({ testDiff = "", srcDiff = "" } = {}) {
38
+ const asserts = addedLines(testDiff).filter((a) => isTestPath(a.file) && ASSERT_RE.test(a.text));
39
+ if (!asserts.length) return false;
40
+ const srcLits = new Set(addedLines(srcDiff).filter((a) => !isTestPath(a.file)).flatMap((a) => literals(a.text)));
41
+ if (!srcLits.size) return false;
42
+ return asserts.every((a) => {
43
+ const lits = literals(a.text);
44
+ if (!lits.length || !lits.every((x) => srcLits.has(x))) return false;
45
+ const body = a.text.replace(LIT_RE, "").replace(/\b(?:self\.)?(?:assert\w*|expect|should)(?:\.\w+)*\s*\(/, "(");
46
+ return !/\w\s*\(/.test(body); // a call left on the asserted subject is behaviour (output of a function)
47
+ });
48
+ }
49
+
50
+ /** Up to `max` mutations of added non-test lines: negate a condition, return early, drop a call statement. */
51
+ export function mutationsOf(srcDiff, max = 3) {
52
+ const cands = addedLines(srcDiff).filter((a) => !isTestPath(a.file) && SRC_EXT.test(a.file) && a.text.trim() && !/^\s*(?:\/\/|#|\*|\/\*)/.test(a.text));
53
+ const out = [];
54
+ const py = (f) => /\.py$/i.test(f);
55
+ for (const a of cands) {
56
+ if (out.length >= max) break;
57
+ const ind = /^\s*/.exec(a.text)[0];
58
+ let m = /^(\s*(?:\}\s*else\s+)?(?:if|while))\s*\((.*)\)\s*(\{?)\s*$/.exec(a.text);
59
+ if (m) { out.push({ ...a, kind: "flip", to: `${m[1]} (!(${m[2]})) ${m[3]}`.trimEnd() }); continue; }
60
+ m = /^(\s*(?:elif|if|while))\s+(.*):\s*$/.exec(a.text);
61
+ if (m && py(a.file)) { out.push({ ...a, kind: "flip", to: `${m[1]} not (${m[2]}):` }); continue; }
62
+ if (/^\s*(?:[\w.$]+\s*\(.*\)|await\s+[\w.$]+\s*\(.*\))\s*;?\s*$/.test(a.text)) { out.push({ ...a, kind: "drop", to: py(a.file) ? `${ind}pass` : `${ind}/* dropped */;` }); continue; }
63
+ }
64
+ for (const a of cands) { // early return as the last resort, on a statement line
65
+ if (out.length >= max) break;
66
+ if (out.some((o) => o.file === a.file && o.line === a.line)) continue;
67
+ if (/^\s*(?:return\b.*|[\w.$]+\s*=.*)$/.test(a.text) && !/[{(,]\s*$/.test(a.text)) {
68
+ const ind = /^\s*/.exec(a.text)[0];
69
+ out.push({ ...a, kind: "return", to: py(a.file) ? `${ind}return None` : `${ind}return;` });
70
+ }
71
+ }
72
+ return out.slice(0, max);
73
+ }
74
+
75
+ /**
76
+ * Run the repro once per mutation on a clean tree; restore with reset --hard + clean in a finally (fail closed when the tree
77
+ * is still dirty). Each result: {kind, file, line, status: killed|survived|skipped}.
78
+ */
79
+ export async function runReproMutations({ mutations = [], command, git, runCommand, cwd, env, readFile, writeFile, capMs = 120000, now = Date.now } = {}) {
80
+ const results = [], t0 = now();
81
+ if (!mutations.length) return { results, skipped: "no mutable line" };
82
+ if (String(await git(["status", "--porcelain"]).catch(() => "x")).trim()) return { results, skipped: "working tree not clean" };
83
+ const files = [...new Set(mutations.map((m) => m.file))];
84
+ try {
85
+ for (const m of mutations) {
86
+ const left = capMs - (now() - t0);
87
+ if (left <= 0) { results.push({ ...m, status: "skipped" }); continue; }
88
+ try {
89
+ const lines = String(await readFile(`${cwd}/${m.file}`)).split("\n");
90
+ if (lines[m.line - 1] !== m.text) { results.push({ ...m, status: "skipped" }); continue; }
91
+ lines[m.line - 1] = m.to;
92
+ await writeFile(`${cwd}/${m.file}`, lines.join("\n"));
93
+ let r;
94
+ try { r = await runCommand({ command, cwd, timeoutMs: left, env }); } catch { r = { rc: 127 }; }
95
+ r = r?.r ?? r;
96
+ const rc = Number.isInteger(r?.rc) ? r.rc : 1;
97
+ results.push({ ...m, status: rc === 124 || rc === 127 ? "skipped" : rc === 0 ? "survived" : "killed" });
98
+ } finally {
99
+ await git(["checkout", "-q", "HEAD", "--", m.file]).catch(() => {});
100
+ }
101
+ }
102
+ } finally {
103
+ const dirty = String(await git(["status", "--porcelain", "--", ...files]).catch(() => "unreadable")).trim();
104
+ if (dirty) throw new Error(`repro mutation left the tree dirty: ${dirty.slice(0, 200)}`);
105
+ }
106
+ return { results, skipped: "" };
107
+ }
108
+
109
+ /** repro_quality for a frozen repro_test: none (no repro), patch_echo, mutation_survivor (every run mutation survived), else behavioural. */
110
+ export function classifyRepro({ repro_test, echo = false, mutations = [] } = {}) {
111
+ if (!repro_test || typeof repro_test !== "object") return "none";
112
+ if (echo) return "patch_echo";
113
+ const ran = mutations.filter((m) => m.status !== "skipped");
114
+ if (ran.length && ran.every((m) => m.status === "survived")) return "mutation_survivor";
115
+ return "behavioural";
116
+ }
@@ -0,0 +1,85 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ import { test } from "node:test";
4
+ import assert from "node:assert/strict";
5
+ import { patchEcho, mutationsOf, runReproMutations, classifyRepro, addedLines } from "./reproquality.mjs";
6
+
7
+ const srcDiff = `--- a/src/strat.js
8
+ +++ b/src/strat.js
9
+ @@ -1,2 +1,5 @@
10
+ const a = 1;
11
+ +function pick(url) {
12
+ + if (url.includes("reddit.com")) {
13
+ + return "https://old.reddit.com/x";
14
+ + }
15
+ }
16
+ `;
17
+ const echoTest = `--- /dev/null
18
+ +++ b/test/strat.test.js
19
+ @@ -0,0 +1,2 @@
20
+ +test("rewrite", () => {
21
+ + assert.equal(strategy.rewrite_url, "https://old.reddit.com/x");
22
+ `;
23
+ const behaviourTest = `--- /dev/null
24
+ +++ b/test/strat.test.js
25
+ @@ -0,0 +1,2 @@
26
+ +test("rewrite", () => {
27
+ + assert.equal(pick("https://www.reddit.com/r/a"), "https://old.reddit.com/x");
28
+ `;
29
+
30
+ test("patch-echo test is flagged", () => assert.equal(patchEcho({ testDiff: echoTest, srcDiff }), true));
31
+ test("behavioural test is not flagged", () => assert.equal(patchEcho({ testDiff: behaviourTest, srcDiff }), false));
32
+ test("addedLines tracks new-file line numbers", () => assert.equal(addedLines(srcDiff)[0].line, 2));
33
+ test("mutationsOf flips conditions and caps at 3", () => {
34
+ const ms = mutationsOf(srcDiff);
35
+ assert.ok(ms.length >= 1 && ms.length <= 3);
36
+ assert.match(ms[0].to, /if \(!\(url\.includes\("reddit\.com"\)\)\) \{/);
37
+ assert.equal(mutationsOf(echoTest).length, 0);
38
+ });
39
+
40
+ const fakeEnv = (rcs, { dirty = false } = {}) => {
41
+ const files = { "/w/src/strat.js": "const a = 1;\nfunction pick(url) {\n if (url.includes(\"reddit.com\")) {\n return 1;\n }\n}" };
42
+ const orig = { ...files };
43
+ let i = 0;
44
+ return {
45
+ files,
46
+ opts: {
47
+ cwd: "/w", command: "t", mutations: [{ file: "src/strat.js", line: 3, text: files["/w/src/strat.js"].split("\n")[2], to: " if (!(x)) {" }],
48
+ git: async (a) => { if (a[0] === "checkout") { files["/w/src/strat.js"] = orig["/w/src/strat.js"]; return ""; } if (a[0] === "status") return dirty ? " M x" : ""; return ""; },
49
+ runCommand: async () => ({ rc: rcs[i++] }),
50
+ readFile: async (p) => files[p], writeFile: async (p, c) => { files[p] = c; },
51
+ },
52
+ };
53
+ };
54
+ test("mutation survivor is flagged, tree restored", async () => {
55
+ const e = fakeEnv([0]);
56
+ const r = await runReproMutations(e.opts);
57
+ assert.equal(r.results[0].status, "survived");
58
+ assert.match(e.files["/w/src/strat.js"], /reddit\.com/);
59
+ assert.equal(classifyRepro({ repro_test: { path: "t" }, mutations: r.results }), "mutation_survivor");
60
+ });
61
+ test("killed mutation is behavioural; dirty tree and timeout skip", async () => {
62
+ const r = await runReproMutations(fakeEnv([1]).opts);
63
+ assert.equal(classifyRepro({ repro_test: {}, mutations: r.results }), "behavioural");
64
+ assert.equal((await runReproMutations(fakeEnv([0], { dirty: true }).opts)).skipped, "working tree not clean");
65
+ assert.equal((await runReproMutations(fakeEnv([124]).opts)).results[0].status, "skipped");
66
+ });
67
+ test("classify: none and patch_echo", () => {
68
+ assert.equal(classifyRepro({ repro_test: "none" }), "none");
69
+ assert.equal(classifyRepro({ repro_test: {}, echo: true }), "patch_echo");
70
+ });
71
+
72
+ import { reproQualityFailures } from "./conformance.mjs";
73
+ import { reproFlagNote } from "./prompts.mjs";
74
+ test("enforce blocks a mutation survivor; shadow and patch_echo do not", () => {
75
+ assert.equal(reproQualityFailures({ quality: "mutation_survivor", enforce: true })[0].kind, "repro_mutation_survivor");
76
+ assert.equal(reproQualityFailures({ quality: "mutation_survivor", enforce: false }).length, 0);
77
+ assert.equal(reproQualityFailures({ quality: "patch_echo", enforce: true }).length, 0);
78
+ assert.equal(reproQualityFailures({}).length, 0);
79
+ });
80
+ test("reviewer prompt note appears only for flagged repros", () => {
81
+ assert.match(reproFlagNote("patch_echo"), /Accept or reject it explicitly/);
82
+ assert.match(reproFlagNote("mutation_survivor"), /mutated/);
83
+ assert.equal(reproFlagNote("behavioural"), "");
84
+ assert.equal(reproFlagNote(null), "");
85
+ });
@@ -8,6 +8,8 @@
8
8
  * Run directly, it reports per repo how many would-skip lanes the reviewer flagged as nonconforming.
9
9
  */
10
10
  import { execFileSync } from "node:child_process";
11
+ import { userFacingSurfaces } from "./docsgate.mjs";
12
+ import { pageFiles } from "./pagegate.mjs";
11
13
  import { existsSync, readdirSync, readFileSync } from "node:fs";
12
14
  import { homedir } from "node:os";
13
15
  import { join } from "node:path";
@@ -45,7 +47,7 @@ export function parseRiskPaths(v) {
45
47
  }
46
48
 
47
49
  /** #5099: the review domains a lane can touch, from scripts/review-roster.sh path triggers. */
48
- export const DOMAINS = Object.freeze(["api", "auth", "database", "frontend", "infra"]);
50
+ export const DOMAINS = Object.freeze(["api", "auth", "database", "design", "docs", "frontend", "infra", "seo-geo"]);
49
51
  const DOMAIN_OF_TRIGGER = Object.freeze({ "frontend-path": "frontend", "auth-path": "auth", "infra-path": "infra", "route-handler": "infra", "migration-path": "database", "sdk-path": "api" });
50
52
  const ROSTER = fileURLToPath(new URL("../../scripts/review-roster.sh", import.meta.url));
51
53
 
@@ -58,14 +60,17 @@ export function parseEnforceDomains(v) {
58
60
  * #5099: the domains the changed files touch, by the path triggers of the bundled scripts/review-roster.sh (the one
59
61
  * source of the domain path rules). Sorted, unique; [] without files; null when the script fails (the caller logs it).
60
62
  */
61
- export function pathDomains(files = [], { script = ROSTER } = {}) {
63
+ export function pathDomains(files = [], { script = ROSTER, docs = null, pages = null } = {}) {
62
64
  const list = [...new Set((files ?? []).map(String).filter(Boolean))];
63
65
  if (!list.length) return [];
64
66
  let out;
65
67
  try { out = execFileSync("bash", [script, "--files-file", "-", "--changed-lines", "1"], { input: `${list.join("\n")}\n`, encoding: "utf8", timeout: 15000, stdio: ["pipe", "pipe", "ignore"] }); } catch { return null; }
66
68
  const m = /^REASON=.*?triggers:([^\n]*)$/m.exec(String(out));
67
69
  if (!/^SELECTED_AGENTS=/m.test(String(out))) return null;
68
- return [...new Set((m ? m[1].trim().split(/\s+/) : []).map((t) => DOMAIN_OF_TRIGGER[t]).filter(Boolean))].sort();
70
+ const found = (m ? m[1].trim().split(/\s+/) : []).map((t) => DOMAIN_OF_TRIGGER[t]).filter(Boolean);
71
+ if (docs && Object.keys(userFacingSurfaces(list, docs)).length) found.push("docs"); // #5419
72
+ if (pages && pageFiles(list, pages).length) found.push("design", "seo-geo"); // #5428
73
+ return [...new Set(found)].sort();
69
74
  }
70
75
 
71
76
  /**
@@ -0,0 +1,27 @@
1
+ import { test } from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { readFileSync } from "node:fs";
4
+ import { createLedger, sandboxStartBudget, SANDBOX_START_P50_BUDGET_MS } from "./phaseledger.mjs";
5
+
6
+ const lane = (ms, steps = {}) => { let t = 0; const l = createLedger(() => t); for (const [k, v] of Object.entries(steps)) l.addStep("sandbox_start", k, v); t = ms; l.enter("plan"); return l.snapshot(); };
7
+
8
+ test("sandbox_start p50 budget is 3 s and judges the median, not the max", () => {
9
+ assert.equal(SANDBOX_START_P50_BUDGET_MS, 3000);
10
+ assert.equal(sandboxStartBudget([lane(1000), lane(2000), lane(20000)]).ok, true);
11
+ const r = sandboxStartBudget([lane(4000), lane(5000), lane(900)]);
12
+ assert.equal(r.ok, false); assert.equal(r.p50, 4000);
13
+ assert.equal(sandboxStartBudget([]).ok, true);
14
+ });
15
+
16
+ test("sandbox_start sub-timings (sparse_plan, git_worktree_add, sparse_checkout) ride the ledger snapshot", () => {
17
+ const s = lane(2500, { sparse_plan: 300, git_worktree_add: 1500, sparse_checkout: 400 });
18
+ assert.deepEqual(s.sandbox_start.steps, { sparse_plan: 300, git_worktree_add: 1500, sparse_checkout: 400 });
19
+ });
20
+
21
+ // Bench corpus gate: FORGE_BENCH_LOG=<log.jsonl of a bench run>. Without it only the unit checks above run.
22
+ test("bench corpus: sandbox_start p50 <= 3 s", { skip: !process.env.FORGE_BENCH_LOG }, () => {
23
+ const rows = readFileSync(process.env.FORGE_BENCH_LOG, "utf8").split("\n").filter(Boolean).map((l) => { try { return JSON.parse(l); } catch { return null; } });
24
+ const r = sandboxStartBudget(rows.map((x) => x?.phases).filter(Boolean));
25
+ assert.ok(r.n > 0, "no ledger rows in the bench log");
26
+ assert.ok(r.ok, `sandbox_start p50 ${r.p50} ms > ${r.budgetMs} ms`);
27
+ });