lastlight-core 0.26.0 → 0.28.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.
Files changed (127) hide show
  1. package/config/default.yaml +302 -5
  2. package/dist/admin/docker.js.map +1 -1
  3. package/dist/admin/sessions.js.map +1 -1
  4. package/dist/admin/tail.js.map +1 -1
  5. package/dist/config/config.d.ts +18 -4
  6. package/dist/config/config.js +122 -9
  7. package/dist/config/config.js.map +1 -1
  8. package/dist/config/repo-config.js.map +1 -1
  9. package/dist/connectors/messaging/session-manager.js.map +1 -1
  10. package/dist/connectors/slack/connector.js.map +1 -1
  11. package/dist/cron/dependabot-discovery.js.map +1 -1
  12. package/dist/cron/review-discovery.js.map +1 -1
  13. package/dist/engine/agent-executor.d.ts +25 -1
  14. package/dist/engine/agent-executor.js +41 -1
  15. package/dist/engine/agent-executor.js.map +1 -1
  16. package/dist/engine/chat/chat-prompt.js.map +1 -1
  17. package/dist/engine/chat/chat-runner.js.map +1 -1
  18. package/dist/engine/dispatcher.js +17 -0
  19. package/dist/engine/dispatcher.js.map +1 -1
  20. package/dist/engine/event-shim.d.ts +18 -0
  21. package/dist/engine/event-shim.js +2 -0
  22. package/dist/engine/event-shim.js.map +1 -1
  23. package/dist/engine/executors/orchestrator.d.ts +92 -1
  24. package/dist/engine/executors/orchestrator.js +144 -46
  25. package/dist/engine/executors/orchestrator.js.map +1 -1
  26. package/dist/engine/executors/shared.js.map +1 -1
  27. package/dist/engine/fix-harvest.js.map +1 -1
  28. package/dist/engine/github/github.d.ts +59 -0
  29. package/dist/engine/github/github.js +72 -0
  30. package/dist/engine/github/github.js.map +1 -1
  31. package/dist/engine/github/installations.js.map +1 -1
  32. package/dist/engine/github/review-poster.d.ts +403 -9
  33. package/dist/engine/github/review-poster.js +619 -52
  34. package/dist/engine/github/review-poster.js.map +1 -1
  35. package/dist/engine/github/team-visibility.js.map +1 -1
  36. package/dist/engine/llm.js.map +1 -1
  37. package/dist/engine/pr-decisions.d.ts +85 -5
  38. package/dist/engine/pr-decisions.js +331 -5
  39. package/dist/engine/pr-decisions.js.map +1 -1
  40. package/dist/engine/pr-state.d.ts +82 -0
  41. package/dist/engine/pr-state.js +71 -1
  42. package/dist/engine/pr-state.js.map +1 -1
  43. package/dist/engine/review-spec.d.ts +264 -0
  44. package/dist/engine/review-spec.js +723 -0
  45. package/dist/engine/review-spec.js.map +1 -0
  46. package/dist/engine/router.js.map +1 -1
  47. package/dist/engine/screen/classifier.js.map +1 -1
  48. package/dist/engine/screen/screen.js.map +1 -1
  49. package/dist/evals-api.d.ts +3 -0
  50. package/dist/evals-api.js +20 -0
  51. package/dist/evals-api.js.map +1 -1
  52. package/dist/index.js +76 -11
  53. package/dist/index.js.map +1 -1
  54. package/dist/notify/digest-blocks.js.map +1 -1
  55. package/dist/notify/model.js.map +1 -1
  56. package/dist/notify/transports/github.js.map +1 -1
  57. package/dist/notify/transports/slack.js.map +1 -1
  58. package/dist/sandbox/artifact-backend.js.map +1 -1
  59. package/dist/sandbox/artifact-store.js.map +1 -1
  60. package/dist/sandbox/docker.d.ts +23 -4
  61. package/dist/sandbox/docker.js +1 -1
  62. package/dist/sandbox/docker.js.map +1 -1
  63. package/dist/sandbox/egress-allowlist.js.map +1 -1
  64. package/dist/sandbox/k8s/agent-context-registry.js.map +1 -1
  65. package/dist/sandbox/k8s/client.js.map +1 -1
  66. package/dist/sandbox/k8s/kubernetes-sandbox.js.map +1 -1
  67. package/dist/sandbox/k8s/resource-name.js.map +1 -1
  68. package/dist/sandbox/k8s/run-id.js.map +1 -1
  69. package/dist/sandbox/k8s/run-secrets.js.map +1 -1
  70. package/dist/sandbox/k8s/skill-bundle.js.map +1 -1
  71. package/dist/sandbox/k8s/workspace-provisioner.js +10 -2
  72. package/dist/sandbox/k8s/workspace-provisioner.js.map +1 -1
  73. package/dist/sandbox/sandbox.d.ts +20 -0
  74. package/dist/sandbox/sandbox.js +27 -6
  75. package/dist/sandbox/sandbox.js.map +1 -1
  76. package/dist/session-log.js.map +1 -1
  77. package/dist/state/approval-store.js.map +1 -1
  78. package/dist/state/build-assets.js.map +1 -1
  79. package/dist/state/cron-run-store.js.map +1 -1
  80. package/dist/state/data-migrate.d.ts +135 -0
  81. package/dist/state/data-migrate.js +309 -0
  82. package/dist/state/data-migrate.js.map +1 -0
  83. package/dist/state/db.d.ts +24 -3
  84. package/dist/state/db.js +41 -11
  85. package/dist/state/db.js.map +1 -1
  86. package/dist/state/execution-store.js.map +1 -1
  87. package/dist/state/feedback-store.js.map +1 -1
  88. package/dist/state/pg-client.d.ts +44 -0
  89. package/dist/state/pg-client.js +81 -0
  90. package/dist/state/pg-client.js.map +1 -0
  91. package/dist/state/schema/pg.d.ts +15 -15
  92. package/dist/state/schema/sqlite.d.ts +15 -15
  93. package/dist/state/state-cli.d.ts +8 -0
  94. package/dist/state/state-cli.js +247 -0
  95. package/dist/state/state-cli.js.map +1 -0
  96. package/dist/state/team-store.js.map +1 -1
  97. package/dist/state/user-store.js.map +1 -1
  98. package/dist/state/workflow-run-store.js.map +1 -1
  99. package/dist/telemetry/index.js.map +1 -1
  100. package/dist/workflows/handlers/fanout.d.ts +157 -0
  101. package/dist/workflows/handlers/fanout.js +663 -0
  102. package/dist/workflows/handlers/fanout.js.map +1 -0
  103. package/dist/workflows/handlers/post-review.d.ts +111 -10
  104. package/dist/workflows/handlers/post-review.js +531 -39
  105. package/dist/workflows/handlers/post-review.js.map +1 -1
  106. package/dist/workflows/runner.js +33 -0
  107. package/dist/workflows/runner.js.map +1 -1
  108. package/dist/workflows/simple.js.map +1 -1
  109. package/docker-compose.yml +50 -0
  110. package/package.json +22 -12
  111. package/sandbox.Dockerfile +54 -0
  112. package/skills/adjudicate-pass/SKILL.md +117 -0
  113. package/skills/code-review/SKILL.md +114 -15
  114. package/skills/pr-review/SKILL.md +113 -24
  115. package/skills/pr-review/references/findings-schema.md +38 -7
  116. package/skills/survey-pass/SKILL.md +148 -0
  117. package/workflows/pr-review.yaml +626 -0
  118. package/workflows/prompts/dependabot-pr-merge.md +22 -2
  119. package/workflows/prompts/review-adjudicate.md +340 -0
  120. package/workflows/prompts/review-falsify.md +167 -0
  121. package/workflows/prompts/review.md +80 -0
  122. package/workflows/prompts/survey-contract.md +121 -0
  123. package/workflows/prompts/survey-enforcement.md +137 -0
  124. package/workflows/prompts/survey-security.md +165 -0
  125. package/workflows/prompts/survey-spec.md +116 -0
  126. package/workflows/prompts/survey-state.md +151 -0
  127. package/workflows/prompts/survey-tests.md +99 -0
@@ -1,10 +1,11 @@
1
1
  import { execFileSync } from "node:child_process";
2
- import { existsSync, readFileSync } from "node:fs";
3
- import { join, resolve } from "node:path";
2
+ import { existsSync, readdirSync, readFileSync, statSync, writeFileSync, } from "node:fs";
3
+ import { basename, join, resolve, sep } from "node:path";
4
4
  import { GitHubClient } from "../../engine/github/github.js";
5
- import { buildReview, buildBodyOnlyReview, parseDiff, } from "../../engine/github/review-poster.js";
5
+ import { anchorFindings, buildReview, buildBodyOnlyReview, commentableOf, parseDiffFiles, unknownSeverity, worstAxis, } from "../../engine/github/review-poster.js";
6
6
  import { getRuntimeConfig } from "../../config/config.js";
7
- import { hasMaterialChange } from "../../engine/pr-decisions.js";
7
+ import { defaultReviewConfig } from "lastlight-shared/config-types";
8
+ import { hasMaterialChange, resolveReviewPost, } from "../../engine/pr-decisions.js";
8
9
  import { logger } from "../../logging/logger.js";
9
10
  const log = logger("post-review");
10
11
  /**
@@ -40,6 +41,189 @@ export function resolveReviewGitHubClient(runConfig) {
40
41
  privateKeyPath: process.env.GITHUB_APP_PRIVATE_KEY_PATH || "",
41
42
  });
42
43
  }
44
+ /**
45
+ * Is this hypothesis row a CLEAN DISCHARGE — the pass saying *"I looked, I
46
+ * quote the line, and it is fine"*?
47
+ *
48
+ * Two conditions, and each one is defensive about a shape that was actually
49
+ * measured on disk:
50
+ *
51
+ * 1. **`discharge` OR `status`, case-insensitively**, mirroring `codeOf` in
52
+ * `code-facts`' `discharge.ts` so the gate and the boundary can never
53
+ * disagree about whether a row was discharged. Rows are heterogeneous: some
54
+ * carry neither (the `spec` pass's invented `{verdict, rationale, path,
55
+ * line, obligation}` shape), and a dead family writes `{status:
56
+ * "notMeasured"}`. Neither is a QUOTE, so neither is clean.
57
+ * 2. **`failureScenario` PRESENT and explicitly `null`**, not merely absent —
58
+ * and this is the load-bearing half. The rule being read is the row shape's
59
+ * own contract, *"on a clean QUOTE write `failureScenario: null`"*, so it is
60
+ * a SELF-REPORT: a row that never wrote the key made no report at all.
61
+ *
62
+ * Measured, and it decides the `--contract minimal` question. Across the two
63
+ * preserved 2026-08-22 runs (the pre-`full` contract, which never asked for
64
+ * the field) **37 rows are `QUOTE` with no `failureScenario` key, and every
65
+ * single one is from `spec.jsonl`'s invented `{claim, status, path, line,
66
+ * evidence}` shape** — a shape with nowhere to record a scenario, so its
67
+ * silence carries no information. Under the `full` contract of 2026-08-23,
68
+ * 71 of 78 clean rows write the key explicitly. Requiring it therefore costs
69
+ * **zero findings** on the full-contract runs (17 / 14 / 7 demoted either
70
+ * way) and makes the rule a **true no-op** on every minimal-contract run,
71
+ * where the loose reading would have silently demoted 28 findings on the
72
+ * strength of a field nobody asked for.
73
+ */
74
+ function isCleanDischarge(row) {
75
+ if (!row || typeof row !== "object" || Array.isArray(row))
76
+ return false;
77
+ const r = row;
78
+ const raw = r.discharge ?? r.status;
79
+ if (typeof raw !== "string" || raw.trim().toUpperCase() !== "QUOTE")
80
+ return false;
81
+ return "failureScenario" in r && r.failureScenario === null;
82
+ }
83
+ /**
84
+ * Which hypothesis ids in `<dir>/hypotheses/*.jsonl` are clean discharges.
85
+ *
86
+ * **`undefined` means there is no `hypotheses/` directory at all** — the
87
+ * shipped two-phase reviewer, and every arm that runs no evidence pipeline. The
88
+ * caller passes it straight through, so no pipeline ⇒ byte-identical output.
89
+ * (An empty set behaves identically by construction: `every` over a non-empty
90
+ * id list against an empty set is false. The distinction is kept for the log.)
91
+ *
92
+ * Identity is assigned exactly as `code-facts`' `readHypothesisSet` assigns it,
93
+ * because the ids in `findings[].hypotheses[]` came out of that reader's own
94
+ * `--ledger`: canonical **`<family>-NNN`**, family from the FILENAME (the
95
+ * survey branch owns its file, so the name is authoritative in a way a
96
+ * self-reported field is not), ordinal from position in an append-only file.
97
+ * A model-declared `id` is honoured as an **alias** only when exactly one row
98
+ * claims it and it shadows no canonical id — an ambiguous alias resolves to
99
+ * nothing, which leaves the finding on the confidence path rather than crediting
100
+ * whichever file sorted first.
101
+ *
102
+ * Parsing is defensive throughout: a torn final line on a killed run is normal
103
+ * and must not throw. Note that a line that parses to a non-object still
104
+ * consumes its ordinal, because `readHypothesisSet` counts it — an ordinal that
105
+ * drifted from the ledger's would mis-resolve every later citation in the file.
106
+ */
107
+ export function readCleanDischarges(dir) {
108
+ let files;
109
+ try {
110
+ files = readdirSync(join(dir, "hypotheses"))
111
+ .filter((f) => f.endsWith(".jsonl"))
112
+ .sort();
113
+ }
114
+ catch {
115
+ // No `hypotheses/` directory — the surveys never ran. Not an empty set:
116
+ // "nobody looked" and "looked, found none clean" are different facts.
117
+ return undefined;
118
+ }
119
+ const cleanCanonical = new Set();
120
+ const canonical = new Set();
121
+ /** A model-declared id → every canonical id claiming it. */
122
+ const claims = new Map();
123
+ for (const file of files) {
124
+ const family = basename(file, ".jsonl");
125
+ let rows;
126
+ try {
127
+ rows = readFileSync(join(dir, "hypotheses", file), "utf8")
128
+ .split("\n")
129
+ .map((line) => line.trim())
130
+ .filter((line) => line.length > 0)
131
+ .flatMap((line) => {
132
+ try {
133
+ return [JSON.parse(line)];
134
+ }
135
+ catch {
136
+ return []; // a torn final line on a killed run is normal
137
+ }
138
+ });
139
+ }
140
+ catch {
141
+ continue; // unreadable file — the other families still count
142
+ }
143
+ rows.forEach((row, index) => {
144
+ const id = `${family}-${String(index + 1).padStart(3, "0")}`;
145
+ canonical.add(id);
146
+ if (isCleanDischarge(row))
147
+ cleanCanonical.add(id);
148
+ const declared = row?.id;
149
+ if (typeof declared === "string" &&
150
+ declared.length > 0 &&
151
+ declared !== id) {
152
+ claims.set(declared, [...(claims.get(declared) ?? []), id]);
153
+ }
154
+ });
155
+ }
156
+ const clean = new Set(cleanCanonical);
157
+ for (const [declared, claimedBy] of claims) {
158
+ // Canonical always wins, and an id two rows claim credits neither.
159
+ if (canonical.has(declared) || claimedBy.length !== 1)
160
+ continue;
161
+ if (cleanCanonical.has(claimedBy[0]))
162
+ clean.add(declared);
163
+ }
164
+ return clean;
165
+ }
166
+ /**
167
+ * The review that stood on the head SHA when this run was DISPATCHED, off the
168
+ * persisted `context.prState` — `resolveReviewPost`'s discriminator between a
169
+ * prior review and this run's own.
170
+ *
171
+ * Read defensively rather than through the `PrState` type: the context is JSON
172
+ * that outlives the build that wrote it, and a run dispatched before
173
+ * `submittedAt` was recorded has the same shape minus that field. `null` — no
174
+ * snapshot at all, which is every eval-harness run — degrades to "treat
175
+ * anything at the head as ours", i.e. exactly the unconditional guard this
176
+ * replaced.
177
+ */
178
+ function dispatchReview(ctx) {
179
+ const state = ctx.prState;
180
+ if (!state || typeof state !== "object")
181
+ return null;
182
+ const review = state.botReviewAtHead;
183
+ if (!review || typeof review !== "object")
184
+ return null;
185
+ const { state: reviewState, submittedAt } = review;
186
+ if (typeof reviewState !== "string")
187
+ return null;
188
+ return {
189
+ state: reviewState,
190
+ submittedAt: typeof submittedAt === "string" ? submittedAt : null,
191
+ };
192
+ }
193
+ /**
194
+ * Parse one context-projected boundary number back off its string form.
195
+ * The projection is `specContext`'s (`pr-decisions.ts`); garbage degrades to
196
+ * the caller's default — the direction `config.ts` coerces the same keys.
197
+ */
198
+ function toBudget(v, fallback) {
199
+ const n = Number(v);
200
+ return Number.isFinite(n) && n >= 0 ? Math.floor(n) : fallback;
201
+ }
202
+ /** Like {@link toBudget} but fractional — `internalFloor` is a 0..1 bar. */
203
+ function toFloor(v, fallback) {
204
+ const n = Number(v);
205
+ return Number.isFinite(n) && n >= 0 ? n : fallback;
206
+ }
207
+ /** The one JSON-valued context key; an unparseable value means "no bars". */
208
+ function parseThresholds(v) {
209
+ if (typeof v !== "string" || v === "")
210
+ return {};
211
+ try {
212
+ const parsed = JSON.parse(v);
213
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed))
214
+ return {};
215
+ const out = {};
216
+ for (const [k, val] of Object.entries(parsed)) {
217
+ const n = Number(val);
218
+ if (Number.isFinite(n))
219
+ out[k] = n;
220
+ }
221
+ return out;
222
+ }
223
+ catch {
224
+ return {};
225
+ }
226
+ }
43
227
  /**
44
228
  * The `type: post-review` phase — the one workflow body genuinely coupled to
45
229
  * GitHub, lifted out of the engine into an app-registered {@link PhaseTypeHandler}.
@@ -53,8 +237,10 @@ export function resolveReviewGitHubClient(runConfig) {
53
237
  *
54
238
  * A genuine failure — missing findings after a real review, or a GitHub error
55
239
  * that survives the body-only retry — FAILS the phase visibly; only a
56
- * legitimate `skip` succeeds without posting. Idempotent on resume: it no-ops
57
- * when a bot review already exists on the current head SHA.
240
+ * legitimate `skip` succeeds without posting. Idempotent on resume: a review
241
+ * this run already posted on the head SHA is never posted twice — see
242
+ * {@link resolveReviewPost}, which is also what keeps that idempotency from
243
+ * swallowing a maintainer's deliberate re-review of an unchanged head.
58
244
  */
59
245
  export class GitHubPostReviewHandler {
60
246
  run;
@@ -68,14 +254,23 @@ export class GitHubPostReviewHandler {
68
254
  await this.reporter.onStart(phaseName);
69
255
  await this.reporter.step(phaseName, "running", phase.messages?.on_start);
70
256
  const succeed = async (summary) => {
71
- const result = { phase: phaseName, success: true, output: summary };
257
+ const result = {
258
+ phase: phaseName,
259
+ success: true,
260
+ output: summary,
261
+ };
72
262
  await this.reporter.persistPhase(phaseName, summary);
73
263
  await this.reporter.onEnd(phaseName, result);
74
264
  await this.reporter.step(phaseName, "done", phase.messages?.on_success);
75
265
  return { results: [result], status: "succeeded" };
76
266
  };
77
267
  const fail = async (error) => {
78
- const result = { phase: phaseName, success: false, output: "", error };
268
+ const result = {
269
+ phase: phaseName,
270
+ success: false,
271
+ output: "",
272
+ error,
273
+ };
79
274
  await this.reporter.onEnd(phaseName, result);
80
275
  await this.reporter.step(phaseName, "failed", phase.messages?.on_failure);
81
276
  // Record a failed phase_history entry so the dashboard pipeline renders
@@ -98,9 +293,17 @@ export class GitHubPostReviewHandler {
98
293
  const owner = String(ctx.owner);
99
294
  const repo = String(ctx.repo);
100
295
  const prNumber = (typeof ctx.prNumber === "number" ? ctx.prNumber : undefined) ??
101
- (typeof ctx.issueNumber === "number" && ctx.issueNumber > 0 ? ctx.issueNumber : undefined);
296
+ (typeof ctx.issueNumber === "number" && ctx.issueNumber > 0
297
+ ? ctx.issueNumber
298
+ : undefined);
102
299
  if (!prNumber)
103
300
  return fail("post-review: no PR number in run context; cannot post review");
301
+ // A human asked for THIS run by name — projected onto the run context at
302
+ // the dispatch choke point (`src/index.ts`), so every route carries it
303
+ // identically and a resume of this run still carries the request that
304
+ // started it. Absent (an eval-harness run, a context written before the
305
+ // field existed) reads as `false`, which is the pre-existing behaviour.
306
+ const explicitRequest = ctx.explicitRequest === true;
104
307
  // Read the agent's findings from the host checkout. The review phase writes
105
308
  // it at `.lastlight/pr-review/findings.json` relative to the repo cwd; the
106
309
  // workspace persists on the host between phases (see sandbox/index.ts).
@@ -116,12 +319,32 @@ export class GitHubPostReviewHandler {
116
319
  // phase didn't honour its contract — surface it, don't post silently.
117
320
  return fail(`post-review: could not read findings (${findingsPath}): ${msg}`);
118
321
  }
322
+ // The split verdict (#271 fix 7) only exists when the evidence pipeline is
323
+ // on. Dropping it here rather than trusting nothing to write it is what
324
+ // makes locked decision 8 STRUCTURAL: with `review.analysis.enabled: false`
325
+ // a findings file that carries a `verdict` — a forked prompt, an overlay
326
+ // that got ahead of its config, a model improvising the field — cannot
327
+ // change the event this deployment would have posted yesterday.
328
+ //
329
+ // Operator-layer config on purpose, matching `staleAgainstCurrentHead`
330
+ // below: this runs in-process against a run whose repo-clamped block is not
331
+ // threaded here, and `review.analysis` is operator-only anyway, so the two
332
+ // cannot disagree.
333
+ if (!this.analysisEnabled() && doc.verdict) {
334
+ log.info("Ignoring a split verdict: review.analysis is disabled", {
335
+ repo: `${owner}/${repo}`,
336
+ prNumber,
337
+ });
338
+ doc = { ...doc, verdict: undefined };
339
+ }
119
340
  if (doc.skip) {
120
341
  return succeed(`skipped: ${doc.summary || "agent skipped review"}`);
121
342
  }
122
343
  const github = this.buildReviewClient();
123
344
  // Head SHA + base ref come from the checkout / run context, never the agent.
124
- const baseRef = typeof ctx.baseBranch === "string" && ctx.baseBranch ? ctx.baseBranch : undefined;
345
+ const baseRef = typeof ctx.baseBranch === "string" && ctx.baseBranch
346
+ ? ctx.baseBranch
347
+ : undefined;
125
348
  // `git rev-parse HEAD` doubles as the "is there a local checkout?" probe: it
126
349
  // returns a SHA on host-checkout backends (docker/none/gondolin) and
127
350
  // undefined on k8s, where the workspace lives in a sandbox PVC and only the
@@ -132,21 +355,42 @@ export class GitHubPostReviewHandler {
132
355
  // both work.
133
356
  let headSha = localHeadSha;
134
357
  if (!headSha)
135
- headSha = await github.getPullRequestHeadSha(owner, repo, prNumber).catch(() => undefined);
358
+ headSha = await github
359
+ .getPullRequestHeadSha(owner, repo, prNumber)
360
+ .catch(() => undefined);
136
361
  // One pass over our review history answers both questions asked below: is
137
362
  // there already a review on THIS head (idempotency), and what did we last
138
363
  // actually say (the duplicate guard). Both used to be their own paginated
139
364
  // `listReviews`.
140
- let history = { atHead: null, latest: null };
365
+ let history = {
366
+ atHead: null,
367
+ latest: null,
368
+ };
141
369
  if (headSha) {
142
370
  // Best-effort: a failed read leaves both null, which posts.
143
371
  history = await github
144
372
  .getBotReviewHistory(owner, repo, prNumber, headSha, getRuntimeConfig()?.botLogin)
145
373
  .catch(() => ({ atHead: null, latest: null }));
146
- // Idempotency: skip if a bot review already exists on this head SHA
147
- // (guards resume / re-entry from double-posting).
148
- if (history.atHead) {
149
- return succeed(`already reviewed head ${headSha.slice(0, 7)} (${history.atHead.state})`);
374
+ // "We already reviewed this head" — decided ONCE, by the same module the
375
+ // dispatch gate asks. Two things are being told apart here and they used
376
+ // to be one: a resume/re-entry finding the review this run itself posted
377
+ // (never post again) versus a maintainer's deliberate `@bot review` on a
378
+ // head we reviewed yesterday (post — that is the whole ask). The
379
+ // discriminator is the dispatch snapshot, which is why `atDispatch` comes
380
+ // off the persisted run context rather than a fresh read.
381
+ const post = resolveReviewPost({
382
+ atHead: history.atHead,
383
+ atDispatch: dispatchReview(ctx),
384
+ explicitRequest,
385
+ });
386
+ if (post.decision === "skip") {
387
+ log.info("Not posting a review", {
388
+ repo: `${owner}/${repo}`,
389
+ prNumber,
390
+ reason: post.reason,
391
+ inputs: post.inputs,
392
+ });
393
+ return succeed(`${post.reason} — ${headSha.slice(0, 7)}`);
150
394
  }
151
395
  const stale = await this.staleAgainstCurrentHead(github, owner, repo, prNumber, headSha);
152
396
  if (stale)
@@ -158,16 +402,76 @@ export class GitHubPostReviewHandler {
158
402
  // harness) runs a guaranteed-to-fail `git diff` that dumps a usage block and
159
403
  // a FALSE "demoting all findings to the body" on every run — before the API
160
404
  // fallback silently rescues the findings.
161
- let commentable = localHeadSha && baseRef ? this.gitCommentableDiff(hostRepoDir, baseRef) : null;
405
+ let files = localHeadSha && baseRef ? this.gitDiffFiles(hostRepoDir, baseRef) : null;
162
406
  // No local checkout (or no base ref) — fall back to GitHub's own PR diff
163
407
  // (the same merge-base diff) so findings still anchor inline on k8s instead
164
408
  // of demoting to the body.
165
- if (!commentable)
166
- commentable = await this.apiCommentableDiff(github, owner, repo, prNumber);
167
- const review = buildReview(doc, commentable);
168
- const repeat = this.repeatOfLastReview(history.latest, review);
409
+ if (!files)
410
+ files = await this.apiDiffFiles(github, owner, repo, prNumber);
411
+ const commentable = files ? commentableOf(files) : null;
412
+ // WP6a — derive each finding's anchor from its verbatim `existingCode`
413
+ // before anything partitions on `line`. A finding whose analysis is right
414
+ // and whose arithmetic is off by two is otherwise demoted to the body, which
415
+ // is the full price of a wrong answer for a counting slip. Inert on a
416
+ // findings.json whose entries carry no excerpt: `anchorFindings` returns
417
+ // them untouched, so this cannot move a deployment that has not opted in.
418
+ if (files) {
419
+ const anchored = anchorFindings(Array.isArray(doc.findings) ? doc.findings : [], files, localHeadSha ? (p) => this.readHeadFile(hostRepoDir, p) : undefined);
420
+ if (anchored.stats.hunk ||
421
+ anchored.stats.file ||
422
+ anchored.stats.relocated) {
423
+ log.info("Anchored findings from their code excerpts", {
424
+ repo: `${owner}/${repo}`,
425
+ prNumber,
426
+ ...anchored.stats,
427
+ });
428
+ }
429
+ doc = { ...doc, findings: anchored.findings };
430
+ }
431
+ // Warn, never fail: the finding is real and still posts — it just ranks as
432
+ // Important, which is the wrong slot if it meant to be Critical. Nothing
433
+ // else a run writes records that this happened.
434
+ const strange = (Array.isArray(doc.findings) ? doc.findings : []).filter(unknownSeverity);
435
+ if (strange.length > 0) {
436
+ log.warn("findings carry a severity the ranker does not know — ranked as Important", {
437
+ repo: `${owner}/${repo}`,
438
+ prNumber,
439
+ count: strange.length,
440
+ severities: [...new Set(strange.map((f) => f.severity))],
441
+ });
442
+ }
443
+ // WP6b — the attention boundary, and it exists ONLY when the evidence
444
+ // pipeline is on. `undefined` here is not a default, it is the whole
445
+ // inertness guarantee: `buildReview` takes its pre-WP6b branch and a
446
+ // deployment that never opted in gets no cap, no thresholds and no
447
+ // `internal` tier, whatever a findings.json happens to carry.
448
+ const boundary = this.attentionBoundary();
449
+ // The anti-finding rule (below). Read ONLY when a boundary exists, so a
450
+ // deployment that never opted in does not even stat the directory — the
451
+ // same inertness discipline the boundary itself keeps.
452
+ const clean = boundary
453
+ ? readCleanDischarges(join(hostRepoDir, ".lastlight", "pr-review"))
454
+ : undefined;
455
+ const review = buildReview(doc, commentable, boundary, clean);
456
+ if (boundary && review.tiered) {
457
+ const antiFindings = review.tiered.internal.filter((r) => r.reason === "clean-discharge").length;
458
+ if (clean?.size || antiFindings) {
459
+ log.info("Withheld findings whose evidence is entirely clean discharges", {
460
+ repo: `${owner}/${repo}`,
461
+ prNumber,
462
+ cleanHypotheses: clean?.size ?? 0,
463
+ antiFindings,
464
+ });
465
+ }
466
+ this.recordDisposition(hostRepoDir, boundary, review.tiered);
467
+ }
468
+ const repeat = this.repeatOfLastReview(history.latest, review, explicitRequest);
169
469
  if (repeat) {
170
- log.info("Skipping a duplicate review post", { repo: `${owner}/${repo}`, prNumber, summary: repeat });
470
+ log.info("Skipping a duplicate review post", {
471
+ repo: `${owner}/${repo}`,
472
+ prNumber,
473
+ summary: repeat,
474
+ });
171
475
  return succeed(repeat);
172
476
  }
173
477
  try {
@@ -177,14 +481,31 @@ export class GitHubPostReviewHandler {
177
481
  comments: review.comments,
178
482
  commitId: headSha,
179
483
  });
180
- return succeed(`posted review: ${review.inlineCount} inline, ${review.demotedCount} in body, event=${review.event}`);
484
+ // Name the downgrade in the ledger row when the split verdict caused one.
485
+ // Without it "event=COMMENT" on a doc whose `event` says APPROVE reads as
486
+ // a bug rather than as the axis floor doing its job.
487
+ const downgraded = doc.event === "APPROVE" &&
488
+ review.event !== "APPROVE" &&
489
+ worstAxis(doc.verdict) === "fail"
490
+ ? `, downgraded from APPROVE by verdict spec=${doc.verdict?.spec ?? "-"}/standards=${doc.verdict?.standards ?? "-"}`
491
+ : "";
492
+ // The `internal` count is reported even when it is zero, and only when a
493
+ // boundary applied: "recorded, not posted" is a number nobody can read off
494
+ // the review itself, and leaving it out of the one line the ledger keeps
495
+ // is how a dark drop would look exactly like a quiet review.
496
+ const withheld = review.tiered
497
+ ? `, ${review.internalCount} recorded-only`
498
+ : "";
499
+ return succeed(`posted review: ${review.inlineCount} inline, ${review.demotedCount} in body${withheld}, event=${review.event}${downgraded}`);
181
500
  }
182
501
  catch (err) {
183
502
  const msg = err instanceof Error ? err.message : String(err);
184
503
  log.warn("Inline review POST failed; retrying body-only", { err });
185
504
  // Off-diff anchors (e.g. a stale diff) 422 — retry with everything in the
186
505
  // body so the review still lands.
187
- const bodyOnly = buildBodyOnlyReview(doc);
506
+ // The tiering, when there was one: the retry must not republish what the
507
+ // boundary recorded-and-withheld just because GitHub rejected an anchor.
508
+ const bodyOnly = buildBodyOnlyReview(doc, review.tiered);
188
509
  try {
189
510
  await github.createPullRequestReview(owner, repo, prNumber, {
190
511
  body: bodyOnly.body,
@@ -225,8 +546,19 @@ export class GitHubPostReviewHandler {
225
546
  * suppressing a duplicate APPROVE changes nothing; suppressing a duplicate
226
547
  * CHANGES_REQUESTED would turn a `failure` check into a passing one and open
227
548
  * a merge gate the review deliberately closed.
549
+ *
550
+ * Off for an EXPLICIT request, and that is not a courtesy — it is the same
551
+ * rule `resolveReviewPost` applies one guard above. The shape this catches is
552
+ * an unprompted re-review of a push that changed nothing a reviewer can read;
553
+ * a maintainer who typed `@bot review` on an unchanged head is asking for
554
+ * precisely the review this would suppress, and would get eight minutes of
555
+ * pipeline and silence. Suppressing a duplicate APPROVE is safe (the check
556
+ * concludes `neutral`, which passes) — but so is posting one, and only one of
557
+ * the two answers the question.
228
558
  */
229
- repeatOfLastReview(last, review) {
559
+ repeatOfLastReview(last, review, explicitRequest) {
560
+ if (explicitRequest)
561
+ return null;
230
562
  if (review.event !== "APPROVE" || review.comments.length > 0)
231
563
  return null;
232
564
  if (!last || last.state !== "APPROVED" || last.body !== review.body)
@@ -263,7 +595,9 @@ export class GitHubPostReviewHandler {
263
595
  const review = getRuntimeConfig()?.review;
264
596
  if (!review || review.trigger === "on-request")
265
597
  return null;
266
- const currentSha = await github.getPullRequestHeadSha(owner, repo, prNumber).catch(() => undefined);
598
+ const currentSha = await github
599
+ .getPullRequestHeadSha(owner, repo, prNumber)
600
+ .catch(() => undefined);
267
601
  if (!currentSha || currentSha === reviewedSha)
268
602
  return null;
269
603
  const changed = await github
@@ -278,7 +612,11 @@ export class GitHubPostReviewHandler {
278
612
  return null;
279
613
  const summary = `stale: reviewed ${reviewedSha.slice(0, 7)} but the head is now ${currentSha.slice(0, 7)}; ` +
280
614
  `a review of the new head will be dispatched instead`;
281
- log.info("Skipping a stale review post", { repo: `${owner}/${repo}`, prNumber, summary });
615
+ log.info("Skipping a stale review post", {
616
+ repo: `${owner}/${repo}`,
617
+ prNumber,
618
+ summary,
619
+ });
282
620
  return summary;
283
621
  }
284
622
  /** Host path of the run's repo checkout — mirrors sandbox/index.ts layout. */
@@ -296,6 +634,157 @@ export class GitHubPostReviewHandler {
296
634
  return workDir;
297
635
  return repoDir;
298
636
  }
637
+ /**
638
+ * The attention budget, or `undefined` when the evidence pipeline is off.
639
+ *
640
+ * Operator-layer config, matching the `verdict` strip and
641
+ * `staleAgainstCurrentHead` — `review.analysis` is operator-only anyway, so
642
+ * the repo-clamped block cannot disagree with it.
643
+ */
644
+ attentionBoundary() {
645
+ if (!this.analysisEnabled())
646
+ return undefined;
647
+ // The RUN CONTEXT is the first authority, for the same reason
648
+ // `analysisEnabled()` reads it: the eval harness threads the arm's
649
+ // `review:` policy through the context and never populates the
650
+ // process-global runtime config, so a boundary read only off
651
+ // `getRuntimeConfig()` silently applies the packaged defaults to every
652
+ // eval arm — found on this pipeline's own PR after three repeats of an
653
+ // arm that pinned `maxBodyComments: null` each recorded 5–14
654
+ // `body-budget` demotions. `specContext` projects all four fields
655
+ // together, so their presence is atomic; production projects them from
656
+ // the same runtime config this fallback reads, so the two authorities
657
+ // cannot disagree there.
658
+ const ctx = this.run.ctx;
659
+ if (typeof ctx.maxInlineComments === "string") {
660
+ return {
661
+ maxInlineComments: toBudget(ctx.maxInlineComments, defaultReviewConfig().analysis.maxInlineComments),
662
+ thresholds: parseThresholds(ctx.boundaryThresholds),
663
+ internalFloor: toFloor(ctx.internalFloor, defaultReviewConfig().analysis.internalFloor),
664
+ // `"null"` is the literal the projection writes for the documented
665
+ // "unlimited body overflow" value; anything else degrades to the
666
+ // shipped default, the same direction `config.ts` coerces garbage —
667
+ // and read from the same authority, so the two cannot drift apart when
668
+ // the default moves.
669
+ maxBodyComments: ctx.maxBodyComments === "null"
670
+ ? null
671
+ : toBudget(ctx.maxBodyComments, defaultReviewConfig().analysis.maxBodyComments ?? 0),
672
+ };
673
+ }
674
+ const analysis = getRuntimeConfig()?.review?.analysis ?? defaultReviewConfig().analysis;
675
+ return {
676
+ maxInlineComments: analysis.maxInlineComments,
677
+ thresholds: analysis.thresholds ?? {},
678
+ internalFloor: analysis.internalFloor,
679
+ // Nullable on purpose — `null` is the documented "unlimited body
680
+ // overflow" value, so it must survive this projection rather than be
681
+ // defaulted away. `??` here would erase the operator's explicit choice.
682
+ maxBodyComments: analysis.maxBodyComments,
683
+ };
684
+ }
685
+ /**
686
+ * Is the review evidence pipeline on FOR THIS RUN?
687
+ *
688
+ * Two authorities, and the second one is why this is a method rather than a
689
+ * `getRuntimeConfig()` read at each site. The process-global runtime config is
690
+ * the production authority. But `analysisEnabled` on the run CONTEXT is what
691
+ * every gated phase in `pr-review.yaml` actually keys off — `specContext`
692
+ * projects it, and only when the run's own effective review config had
693
+ * `analysis.enabled`. So the context is the run-scoped truth, and reading only
694
+ * the global one makes this handler disagree with the twelve phases upstream
695
+ * of it about whether the pipeline ran.
696
+ *
697
+ * **Measured 2026-08-22, and it silently cost a whole arm.** The eval harness
698
+ * threads the arm's `review:` policy through `prContextPatch` and never
699
+ * populates the runtime config, so a pipeline-ON eval run had all twelve
700
+ * analysis phases fire and then hit a `post-review` that believed the pipeline
701
+ * was off: the attention boundary was inert (every `internal`-tier finding
702
+ * POSTED, no inline cap, no family thresholds) and the split verdict was
703
+ * stripped. Twenty findings posted where the shipped configuration would have
704
+ * posted eleven — a precision number describing a deployment that does not
705
+ * exist.
706
+ *
707
+ * The inertness guarantee is unchanged: `specContext` returns `{}` when
708
+ * analysis is off, so `analysisEnabled` is ABSENT — not `false` — on every
709
+ * deployment that has not opted in, and neither authority can be satisfied.
710
+ */
711
+ analysisEnabled() {
712
+ if (getRuntimeConfig()?.review?.analysis?.enabled)
713
+ return true;
714
+ return this.run.ctx.analysisEnabled === "true";
715
+ }
716
+ /**
717
+ * Write what happened to each finding — its tier, and why.
718
+ *
719
+ * [WP6](../../../../../docs/plans/deterministic-pr-levers.md#adjudication-and-the-attention-boundary-wp6)'s
720
+ * AC1b asks for this in a `review_findings` table, and that table is
721
+ * [WP7](../../../../../docs/plans/deterministic-pr-levers.md#review-memory-wp7)'s
722
+ * — which depends on WP6, so it does not exist yet. **Decided deliberately
723
+ * (2026-08-22): scope the record to the run's own workspace for now** rather
724
+ * than pull a schema change forward for a consumer that has not been written,
725
+ * on a table whose shape would be a guess.
726
+ *
727
+ * What it buys today is the thing that separates an attention boundary from
728
+ * v2's suppressor: *"what did we know and not say?"* is answerable. Without a
729
+ * record the `internal` tier is a dark drop, and a dark drop is the defect
730
+ * this whole work package exists to avoid re-introducing.
731
+ *
732
+ * Best-effort — a failure here must never stop a review posting.
733
+ */
734
+ recordDisposition(repoDir, boundary, tiered) {
735
+ try {
736
+ const rows = [
737
+ ...tiered.inline.map((f) => ({
738
+ tier: "inline",
739
+ reason: null,
740
+ finding: f,
741
+ })),
742
+ ...tiered.body.map((d) => ({
743
+ tier: "body",
744
+ reason: d.reason,
745
+ finding: d.finding,
746
+ })),
747
+ // `reason` is the same machine token the body tier carries, not prose:
748
+ // the sibling eval harness reads this file, and "below the internal
749
+ // floor" as a sentence made the three causes of a withheld finding
750
+ // indistinguishable to anything but a human.
751
+ ...tiered.internal.map((r) => ({
752
+ tier: "internal",
753
+ reason: r.reason,
754
+ finding: r.finding,
755
+ })),
756
+ ];
757
+ writeFileSync(join(repoDir, ".lastlight", "pr-review", "disposition.json"), JSON.stringify({ generatedAt: new Date().toISOString(), boundary, findings: rows }, null, 2));
758
+ }
759
+ catch (err) {
760
+ log.warn("Could not record the finding disposition", { err });
761
+ }
762
+ }
763
+ /**
764
+ * Read a head-side file for the anchor cascade's step 2. Best-effort by
765
+ * design: a miss just means the excerpt is not found there and the cascade
766
+ * moves on to relocation.
767
+ *
768
+ * **The path comes from a model**, so it is confined to the checkout the same
769
+ * way every other path in this handler is — `resolve` then a prefix check, not
770
+ * a `..` denylist. Size-capped because the excerpt scan is O(file) and a
771
+ * findings.json naming a vendored bundle should cost nothing.
772
+ */
773
+ readHeadFile(repoDir, relPath) {
774
+ try {
775
+ const root = resolve(repoDir);
776
+ const full = resolve(root, relPath);
777
+ if (full !== root && !full.startsWith(root + sep))
778
+ return null;
779
+ const st = statSync(full);
780
+ if (!st.isFile() || st.size > 2 * 1024 * 1024)
781
+ return null;
782
+ return readFileSync(full, "utf8");
783
+ }
784
+ catch {
785
+ return null;
786
+ }
787
+ }
299
788
  /** Build the GitHub client for the post: token+baseUrl in evals, App auth in prod. */
300
789
  buildReviewClient() {
301
790
  return resolveReviewGitHubClient(this.run.config);
@@ -314,9 +803,12 @@ export class GitHubPostReviewHandler {
314
803
  return undefined;
315
804
  }
316
805
  }
317
- /** Compute the base…head diff locally and parse it into a commentable set. */
318
- gitCommentableDiff(repoDir, baseRef) {
319
- const git = (...args) => execFileSync("git", ["-C", repoDir, ...args], { encoding: "utf8", maxBuffer: 64 * 1024 * 1024 });
806
+ /** Compute the base…head diff locally and parse it into per-file hunks. */
807
+ gitDiffFiles(repoDir, baseRef) {
808
+ const git = (...args) => execFileSync("git", ["-C", repoDir, ...args], {
809
+ encoding: "utf8",
810
+ maxBuffer: 64 * 1024 * 1024,
811
+ });
320
812
  const tryGit = (...args) => {
321
813
  try {
322
814
  execFileSync("git", ["-C", repoDir, ...args], { stdio: "ignore" });
@@ -328,14 +820,14 @@ export class GitHubPostReviewHandler {
328
820
  // The three-dot (merge-base…head) diff mirrors GitHub's own PR diff exactly,
329
821
  // so it's the ideal anchor set — but it needs the merge-base present locally,
330
822
  // which a shallow `--depth 1 --single-branch` pr-review clone doesn't have.
331
- const threeDot = () => parseDiff(git("diff", `origin/${baseRef}...HEAD`));
823
+ const threeDot = () => parseDiffFiles(git("diff", `origin/${baseRef}...HEAD`));
332
824
  // Two-dot compares the two end trees directly — no history walk — so it works
333
825
  // on ANY clone depth (down to depth 1). It's a *superset* of the three-dot
334
826
  // diff (it also shows changes the base picked up since the PR forked), which
335
827
  // is a safe over-approximation for anchoring: the agent's findings sit on the
336
828
  // PR's own changed lines (⊆ three-dot ⊆ two-dot), and any stray off-diff
337
829
  // anchor is caught by the body-only POST retry.
338
- const twoDot = () => parseDiff(git("diff", `origin/${baseRef}`, "HEAD"));
830
+ const twoDot = () => parseDiffFiles(git("diff", `origin/${baseRef}`, "HEAD"));
339
831
  // Materialize origin/<base> as a real remote-tracking ref (a single-branch
340
832
  // clone's refspec only covers the PR branch, so a bare `fetch origin <base>`
341
833
  // updates FETCH_HEAD but may not create origin/<base>).
@@ -385,14 +877,14 @@ export class GitHubPostReviewHandler {
385
877
  log.warn("Could not compute commentable diff; demoting all findings to the body", { reason: msg });
386
878
  return null;
387
879
  }
388
- /** Fetch the PR's diff from the GitHub API and parse it into a commentable
389
- * set — the fallback when there's no local checkout (k8s). GitHub's PR diff
390
- * is the same merge-base…head diff the local three-dot path targets, so the
391
- * anchor set is identical. Best-effort: any failure returns null and every
392
- * finding demotes to the body (the review still posts). */
393
- async apiCommentableDiff(github, owner, repo, prNumber) {
880
+ /** Fetch the PR's diff from the GitHub API and parse it into per-file hunks —
881
+ * the fallback when there's no local checkout (k8s). GitHub's PR diff is the
882
+ * same merge-base…head diff the local three-dot path targets, so the anchor
883
+ * set is identical. Best-effort: any failure returns null and every finding
884
+ * demotes to the body (the review still posts). */
885
+ async apiDiffFiles(github, owner, repo, prNumber) {
394
886
  try {
395
- return parseDiff(await github.getPullRequestDiff(owner, repo, prNumber));
887
+ return parseDiffFiles(await github.getPullRequestDiff(owner, repo, prNumber));
396
888
  }
397
889
  catch (err) {
398
890
  return this.diffFailed(err instanceof Error ? err.message : String(err));