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
@@ -17,62 +17,299 @@
17
17
  */
18
18
  const FENCE = "```";
19
19
  /**
20
- * Map a unified diff to `path -> Set<"SIDE:line">`. Added/`+` and context lines
21
- * are `RIGHT:<newLine>`; removed/`-` and context lines are `LEFT:<oldLine>` —
22
- * mirroring GitHub's three-dot PR diff anchoring. A finding may be commented
23
- * inline only when its `side:line` appears in this set.
20
+ * Parse a unified diff into per-file hunks, **keeping the line text**.
21
+ *
22
+ * `parseDiff` used to be the only parser and threw the text away, which made
23
+ * the WP6a anchor cascade structurally impossible: you cannot match an excerpt
24
+ * against a corpus of line numbers. This is the same single pass, retaining
25
+ * what it already read.
26
+ *
27
+ * A `+++ /dev/null` (a deletion) yields no file — there is no new-side path to
28
+ * anchor against — matching the old parser exactly.
24
29
  */
25
- export function parseDiff(diff) {
26
- const map = new Map();
27
- let path = null;
30
+ export function parseDiffFiles(diff) {
31
+ const files = [];
32
+ const byPath = new Map();
33
+ let file = null;
34
+ let hunk = null;
28
35
  let right = 0;
29
36
  let left = 0;
30
- let inHunk = false;
31
37
  for (const line of diff.split("\n")) {
32
38
  if (line.startsWith("+++ ")) {
33
39
  const p = line.slice(4).replace(/^b\//, "");
34
- path = p === "/dev/null" ? null : p;
35
- if (path && !map.has(path))
36
- map.set(path, new Set());
37
- inHunk = false;
40
+ if (p === "/dev/null") {
41
+ file = null;
42
+ }
43
+ else {
44
+ file = byPath.get(p) ?? { path: p, hunks: [] };
45
+ if (!byPath.has(p)) {
46
+ byPath.set(p, file);
47
+ files.push(file);
48
+ }
49
+ }
50
+ hunk = null;
38
51
  }
39
52
  else if (line.startsWith("@@")) {
40
53
  const m = /@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/.exec(line);
41
54
  if (m) {
42
55
  left = parseInt(m[1], 10);
43
56
  right = parseInt(m[2], 10);
44
- inHunk = true;
57
+ hunk = { lines: [] };
58
+ if (file)
59
+ file.hunks.push(hunk);
45
60
  }
46
61
  }
47
- else if (inHunk && path) {
48
- const set = map.get(path);
62
+ else if (hunk && file) {
49
63
  if (line.startsWith("+")) {
50
- set.add("RIGHT:" + right);
51
- right++;
64
+ hunk.lines.push({
65
+ prefix: "+",
66
+ text: line.slice(1),
67
+ left: null,
68
+ right: right++,
69
+ });
52
70
  }
53
71
  else if (line.startsWith("-")) {
54
- set.add("LEFT:" + left);
55
- left++;
72
+ hunk.lines.push({
73
+ prefix: "-",
74
+ text: line.slice(1),
75
+ left: left++,
76
+ right: null,
77
+ });
56
78
  }
57
79
  else if (line.startsWith(" ")) {
58
- set.add("RIGHT:" + right);
59
- set.add("LEFT:" + left);
60
- right++;
61
- left++;
80
+ hunk.lines.push({
81
+ prefix: " ",
82
+ text: line.slice(1),
83
+ left: left++,
84
+ right: right++,
85
+ });
62
86
  }
63
87
  else if (line.startsWith("\\")) {
64
88
  /* "" */
65
89
  }
66
90
  else {
67
- inHunk = false;
91
+ hunk = null;
92
+ }
93
+ }
94
+ }
95
+ return files;
96
+ }
97
+ /**
98
+ * The commentable set: `path -> Set<"SIDE:line">`. Added/`+` and context lines
99
+ * are `RIGHT:<newLine>`; removed/`-` and context lines are `LEFT:<oldLine>` —
100
+ * mirroring GitHub's three-dot PR diff anchoring. A finding may be commented
101
+ * inline only when its `side:line` appears in this set.
102
+ */
103
+ export function commentableOf(files) {
104
+ const map = new Map();
105
+ for (const file of files) {
106
+ const set = map.get(file.path) ?? new Set();
107
+ map.set(file.path, set);
108
+ for (const hunk of file.hunks) {
109
+ for (const l of hunk.lines) {
110
+ if (l.right !== null)
111
+ set.add("RIGHT:" + l.right);
112
+ if (l.left !== null)
113
+ set.add("LEFT:" + l.left);
68
114
  }
69
115
  }
70
116
  }
71
117
  return map;
72
118
  }
119
+ /** Map a unified diff straight to its commentable set. */
120
+ export function parseDiff(diff) {
121
+ return commentableOf(parseDiffFiles(diff));
122
+ }
123
+ /** Normalise one line for matching: leading/trailing whitespace is not evidence. */
124
+ function norm(s) {
125
+ return s.trim();
126
+ }
127
+ /** Split an excerpt into the normalised line sequence to look for. Empty ⇒ no match possible. */
128
+ function needleOf(excerpt) {
129
+ if (!excerpt)
130
+ return [];
131
+ const lines = excerpt.split("\n").map(norm);
132
+ while (lines.length && lines[0] === "")
133
+ lines.shift();
134
+ while (lines.length && lines[lines.length - 1] === "")
135
+ lines.pop();
136
+ return lines;
137
+ }
138
+ /**
139
+ * Every consecutive run in `hay` matching `needle`. `hay` must be contiguous —
140
+ * hence one haystack per HUNK rather than per file, so a match can never span
141
+ * the gap between two hunks and claim lines that are not adjacent.
142
+ */
143
+ function findRuns(hay, needle) {
144
+ const out = [];
145
+ if (needle.length === 0 || hay.length < needle.length)
146
+ return out;
147
+ for (let i = 0; i + needle.length <= hay.length; i++) {
148
+ let ok = true;
149
+ for (let j = 0; j < needle.length; j++) {
150
+ if (norm(hay[i + j].text) !== needle[j]) {
151
+ ok = false;
152
+ break;
153
+ }
154
+ }
155
+ if (ok)
156
+ out.push({ start: hay[i].line, end: hay[i + needle.length - 1].line });
157
+ }
158
+ return out;
159
+ }
160
+ /** The new-side (context + added) view of a hunk, in new-file line numbers. */
161
+ function newSide(hunk) {
162
+ return hunk.lines
163
+ .filter((l) => l.right !== null)
164
+ .map((l) => ({ text: l.text, line: l.right }));
165
+ }
166
+ /** The old-side (context + removed) view of a hunk, in old-file line numbers. */
167
+ function oldSide(hunk) {
168
+ return hunk.lines
169
+ .filter((l) => l.left !== null)
170
+ .map((l) => ({ text: l.text, line: l.left }));
171
+ }
172
+ /**
173
+ * Pick one run when several matched. Within the finding's OWN file the model's
174
+ * advisory line is a legitimate tie-breaker — it is usually close and only ever
175
+ * wrong by a little, which is the whole premise of this cascade. Across files
176
+ * there is no such signal, which is why step 3 requires uniqueness instead.
177
+ */
178
+ function nearest(runs, advisory) {
179
+ if (runs.length <= 1 || advisory === undefined)
180
+ return runs[0];
181
+ return runs.reduce((best, r) => Math.abs(r.start - advisory) < Math.abs(best.start - advisory) ? r : best);
182
+ }
183
+ function resolutionOf(path, side, run, via) {
184
+ const res = { path, line: run.end, side, via };
185
+ if (run.end !== run.start)
186
+ res.start_line = run.start;
187
+ return res;
188
+ }
189
+ /**
190
+ * Derive a finding's anchor from its verbatim `existingCode`, instead of
191
+ * trusting the line number the model counted.
192
+ *
193
+ * | # | Step | Model? |
194
+ * |---|---|---|
195
+ * | 1 | Match the excerpt against the file's own hunks — new side, then old side | no |
196
+ * | 2 | Scan the full head-side file content | no |
197
+ * | 3 | Relocate across files: a **unique** hit anywhere in the diff re-files the finding | no |
198
+ * | 4 | Ask a model to regenerate the excerpt and retry step 1 | yes |
199
+ * | 5 | Still unlocated — demote to the body, exactly as today | — |
200
+ *
201
+ * **Step 4 is deliberately NOT built**, and the reason is the same one that
202
+ * makes step 3 mandatory. `post-review` is a deterministic phase-type handler
203
+ * with no model binding, so step 4 is new machinery; and Open Code Review's
204
+ * source records what that machinery does when it fires — handed the *wrong
205
+ * file's* diff and a prompt demanding a code block back, the model answers with
206
+ * whatever token in that diff looks closest, overwriting the one piece of
207
+ * evidence that pointed at the real code. The comment then ends up **looking
208
+ * located while pointing at unrelated code**, which is strictly worse than the
209
+ * demotion it was trying to avoid. A declaration/implementation split is the
210
+ * normal shape of a finding from a contract delta, so that is not an exotic
211
+ * case for us. Step 3 covers it without a model; step 5 is the honest floor.
212
+ *
213
+ * Returns `null` when nothing resolved — the caller then leaves the model's own
214
+ * `line` alone and lets {@link splitFindings} demote it if it is off-diff.
215
+ */
216
+ export function resolveAnchor(f, files, readHeadFile) {
217
+ const needle = needleOf(f.existingCode);
218
+ if (needle.length === 0)
219
+ return null;
220
+ const own = files.find((x) => x.path === f.path);
221
+ // Step 1 — the finding's own file, new side first. An excerpt that is present
222
+ // on both sides is the same text either way; preferring RIGHT keeps the
223
+ // comment on the author's code rather than on what they deleted.
224
+ if (own) {
225
+ for (const [side, view] of [
226
+ ["RIGHT", newSide],
227
+ ["LEFT", oldSide],
228
+ ]) {
229
+ const runs = own.hunks.flatMap((h) => findRuns(view(h), needle));
230
+ const run = nearest(runs, f.line);
231
+ if (run)
232
+ return resolutionOf(f.path, side, run, "hunk");
233
+ }
234
+ }
235
+ // Step 2 — the whole head-side file. Covers an excerpt that sits outside any
236
+ // hunk; the result is very likely off-diff and demoted, but a body entry that
237
+ // cites the right line beats one that cites a wrong one.
238
+ const content = readHeadFile?.(f.path);
239
+ if (content) {
240
+ const hay = content.split("\n").map((text, i) => ({ text, line: i + 1 }));
241
+ const run = nearest(findRuns(hay, needle), f.line);
242
+ if (run)
243
+ return resolutionOf(f.path, "RIGHT", run, "file");
244
+ }
245
+ // Step 3 — relocate across files. UNIQUE hit only: zero hits and multiple
246
+ // hits both decline, because guessing which file a repeated excerpt came from
247
+ // is exactly the corruption step 4 would commit, done deterministically.
248
+ const hits = [];
249
+ for (const file of files) {
250
+ if (file.path === f.path)
251
+ continue;
252
+ for (const h of file.hunks) {
253
+ for (const run of findRuns(newSide(h), needle))
254
+ hits.push({ path: file.path, run });
255
+ }
256
+ }
257
+ if (hits.length === 1) {
258
+ const hit = hits[0];
259
+ return resolutionOf(hit.path, "RIGHT", hit.run, "relocated");
260
+ }
261
+ return null;
262
+ }
263
+ /**
264
+ * Run the cascade over every finding, returning NEW finding objects with the
265
+ * derived anchor written on. Pure: the only I/O is the injected `readHeadFile`.
266
+ *
267
+ * The anchor must be written back onto the finding before {@link splitFindings}
268
+ * sees it — that function partitions on `f.line`, so a resolution that is not
269
+ * persisted is a resolution that demotes anyway.
270
+ */
271
+ export function anchorFindings(findings, files, readHeadFile) {
272
+ const stats = {
273
+ hunk: 0,
274
+ file: 0,
275
+ relocated: 0,
276
+ unresolved: 0,
277
+ noExcerpt: 0,
278
+ };
279
+ const out = findings.map((f) => {
280
+ if (!f || !f.path)
281
+ return f;
282
+ if (!needleOf(f.existingCode).length) {
283
+ stats.noExcerpt++;
284
+ return f;
285
+ }
286
+ const res = resolveAnchor(f, files, readHeadFile);
287
+ if (!res) {
288
+ stats.unresolved++;
289
+ return f;
290
+ }
291
+ if (res.via === "hunk")
292
+ stats.hunk++;
293
+ else if (res.via === "file")
294
+ stats.file++;
295
+ else
296
+ stats.relocated++;
297
+ // start_line is REPLACED, never merged: a stale multi-line range paired
298
+ // with a freshly derived end line is a comment GitHub 422s on.
299
+ const { start_line: _drop, ...rest } = f;
300
+ return {
301
+ ...rest,
302
+ path: res.path,
303
+ line: res.line,
304
+ side: res.side,
305
+ ...(res.start_line ? { start_line: res.start_line } : {}),
306
+ };
307
+ });
308
+ return { findings: out, stats };
309
+ }
73
310
  /** True when a finding anchors onto a line that appears in the diff. */
74
311
  export function isAnchored(f, commentable) {
75
- if (!commentable)
312
+ if (!commentable || !f.line)
76
313
  return false;
77
314
  const side = f.side === "LEFT" ? "LEFT" : "RIGHT";
78
315
  const set = commentable.get(f.path);
@@ -99,35 +336,292 @@ export function splitFindings(findings, commentable) {
99
336
  }
100
337
  return { inline, demoted };
101
338
  }
339
+ const SEVERITY_WEIGHT = {
340
+ critical: 3,
341
+ important: 2,
342
+ minor: 1,
343
+ };
344
+ /**
345
+ * Rank for the inline budget: confidence × severity.
346
+ *
347
+ * **An absent `confidence` ranks as 1.0, not as 0.** Nothing the shipped
348
+ * reviewer writes carries the field, so treating absence as low confidence
349
+ * would push every one of today's findings below every hypothesis-derived one —
350
+ * a silent re-ranking of the reviewer that ships, caused by a field it does not
351
+ * know about. With 1.0 the ranking degenerates to severity order, which is what
352
+ * a document with no confidences should get.
353
+ *
354
+ * **An UNRECOGNISED severity is warned about, not just defaulted.** Absence is a
355
+ * known state and ranks Important on purpose (above). A string nobody defined —
356
+ * `Blocker`, `High`, `p1` — is a different thing: it means some prompt is
357
+ * emitting a vocabulary this code does not share, and the `?? 2` below turns
358
+ * that into an ordinary-looking Important. See {@link unknownSeverity}.
359
+ */
360
+ function rankOf(f) {
361
+ const sev = SEVERITY_WEIGHT[(f.severity || "important").toLowerCase()] ?? 2;
362
+ return (f.confidence ?? 1) * sev;
363
+ }
364
+ /**
365
+ * A severity string no {@link SEVERITY_WEIGHT} entry matches — see `rankOf`.
366
+ *
367
+ * A PREDICATE, not a warning, because this module does no I/O: every function
368
+ * here is a pure transform, which is what lets the anchoring and tiering rules
369
+ * be exercised directly rather than through an eval. `post-review.ts` owns the
370
+ * logger and calls this.
371
+ *
372
+ * **Absence is deliberately NOT unknown.** The shipped reviewer writes no
373
+ * severity at all, and ranking that Important is the documented default above,
374
+ * not a drift. What this catches is a spelling from some other vocabulary —
375
+ * severity is written by prompts, in more than one schema, and nothing between
376
+ * them normalises it.
377
+ */
378
+ export function unknownSeverity(f) {
379
+ const raw = f.severity?.trim();
380
+ return (raw !== undefined &&
381
+ raw !== "" &&
382
+ SEVERITY_WEIGHT[raw.toLowerCase()] === undefined);
383
+ }
384
+ /**
385
+ * Is every hypothesis behind this finding a CLEAN DISCHARGE — i.e. is the
386
+ * finding an anti-finding?
387
+ *
388
+ * Two absences are deliberately NOT clean, and both are the same rule read
389
+ * twice: **absence of provenance is not evidence of innocence.**
390
+ *
391
+ * - **No `hypotheses[]` at all.** Measured on the three `1587-r2` repeats of
392
+ * 2026-08-23: 0, 1 and 1 findings carried none. Those are either the shipped
393
+ * reviewer's own or generated downstream of the surveys; nothing about them
394
+ * is knowable from a set of ids that does not exist, so they take the
395
+ * confidence path unchanged.
396
+ * - **An id that resolves to no row.** It falls out of `every` for free —
397
+ * `clean` holds only ids that resolved AND were clean — which is the correct
398
+ * direction: a citation naming provenance that does not exist is exactly the
399
+ * case where the boundary must not act on the citation.
400
+ */
401
+ function allHypothesesClean(f, clean) {
402
+ if (!clean || clean.size === 0)
403
+ return false;
404
+ const ids = f.hypotheses;
405
+ if (!Array.isArray(ids) || ids.length === 0)
406
+ return false;
407
+ return ids.every((id) => typeof id === "string" && clean.has(id));
408
+ }
409
+ /**
410
+ * Split findings across the three destinations.
411
+ *
412
+ * Order matters and each step is a different question: does this SAY anything
413
+ * (the clean-discharge rule) · is it worth a human's attention at all (the
414
+ * floor) · can it even be anchored (GitHub's constraint) · is it confident
415
+ * enough for an inline comment (the family threshold) · is there room (the
416
+ * budget) · and, last, may the body still grow (the body budget,
417
+ * {@link AttentionBoundary.maxBodyComments} — the one step that moves a
418
+ * finding OUT of the posted review, to `internal` with reason `body-budget`).
419
+ *
420
+ * **A missing `confidence` never demotes and never suppresses.** Both bars are
421
+ * `confidence !== undefined && confidence < bar`, so a finding that declines to
422
+ * self-score is treated as passing — the alternative silently deletes every
423
+ * finding from any prompt that has not been taught the field.
424
+ *
425
+ * ## The clean-discharge rule, and why it is not a confidence rule
426
+ *
427
+ * A survey discharges each obligation with QUOTE / ABSENT / PARTIAL / PROBE,
428
+ * and the row shape's own contract is *"on a clean QUOTE write
429
+ * `failureScenario: null`"*. So a row that is a `QUOTE` with an explicit null
430
+ * scenario is the pass saying **"I looked, I quote the line, and it is fine"**.
431
+ * A finding built ENTIRELY out of such rows is an anti-finding: it cannot match
432
+ * a gold defect by construction, and posting it spends a maintainer's attention
433
+ * on a report that nothing is wrong.
434
+ *
435
+ * **Measured on `prreview__skillspro-1587-r2`, three identical repeats**: of the
436
+ * 45 / 48 / 46 hypotheses, **23 / 25 / 23** are clean discharges under the rule
437
+ * this file implements — `QUOTE` with `failureScenario` PRESENT and explicitly
438
+ * `null` — and 17 / 14 / 7 findings trace entirely to them.
439
+ *
440
+ * The looser reading that counts a merely ABSENT key scores 23 / 25 / 30, and
441
+ * the seven-row gap is the whole reason the strict form is the one here. Under
442
+ * the pre-2026-08-23 obligation contract the field did not exist at all, and the
443
+ * `spec` pass's row shape has nowhere to record one, so 37 rows across the
444
+ * preserved minimal-contract runs are `QUOTE` with no key — silence that carries
445
+ * no information. Reading it as "clean" would demote 28 findings across 4 of 16
446
+ * of those instances on the strength of a field nobody asked for. Strictly, the
447
+ * count there is **0 of 16** and this rule is a verified no-op, which is what
448
+ * keeps the control arm single-variable. On the first repeat **all 17 were posted**
449
+ * — "Type contract: consolidateData correctly accepts…", "GOOGLE_CLIENT_ID
450
+ * constant imported and passed correctly". The confidence bars cannot catch
451
+ * them: confidence on those rows is uniformly ≥ 0.7 (median 0.95–1.00, minimum
452
+ * 0.75 across the whole document), so `internalFloor` and every family
453
+ * threshold pass them. That is the point — **an anti-finding is not an
454
+ * unconfident finding, it is a confident report of nothing**, and only its
455
+ * provenance says so.
456
+ *
457
+ * It is checked BEFORE the floor because it is the more specific answer to
458
+ * "why was this withheld?", not because the two disagree about the tier — they
459
+ * cannot; both are `internal`.
460
+ *
461
+ * `clean` is supplied by the caller (`post-review` reads the sibling
462
+ * `hypotheses/*.jsonl`), never read here: this module does no I/O. Absent or
463
+ * empty ⇒ the rule cannot fire, which is the inertness guarantee for every
464
+ * deployment and every arm that runs no evidence pipeline.
465
+ */
466
+ export function tierFindings(findings, commentable, boundary, clean) {
467
+ const internal = [];
468
+ const body = [];
469
+ const candidates = [];
470
+ for (const f of findings) {
471
+ if (!f)
472
+ continue;
473
+ // An explicit `internal` is obeyed unconditionally and FIRST. The
474
+ // conservation floor writes unaccounted-for hypotheses at this tier with no
475
+ // `confidence` at all, and a confidence-only rule would have posted every
476
+ // one of them — turning "we recorded what we could not adjudicate" into
477
+ // "we published what we could not adjudicate".
478
+ if (f.tier === "internal") {
479
+ internal.push({ finding: f, reason: "adjudicated" });
480
+ continue;
481
+ }
482
+ if (allHypothesesClean(f, clean)) {
483
+ internal.push({ finding: f, reason: "clean-discharge" });
484
+ continue;
485
+ }
486
+ if (f.confidence !== undefined && f.confidence < boundary.internalFloor) {
487
+ internal.push({ finding: f, reason: "below-floor" });
488
+ continue;
489
+ }
490
+ if (!f.path || !f.line || !isAnchored(f, commentable)) {
491
+ body.push({ finding: f, reason: "off-diff" });
492
+ continue;
493
+ }
494
+ // An explicit `body` is a demotion, and a demotion is always safe to obey.
495
+ if (f.tier === "body") {
496
+ body.push({ finding: f, reason: "adjudicated" });
497
+ continue;
498
+ }
499
+ const bar = f.family ? boundary.thresholds[f.family] : undefined;
500
+ if (bar !== undefined && f.confidence !== undefined && f.confidence < bar) {
501
+ body.push({ finding: f, reason: "below-threshold" });
502
+ continue;
503
+ }
504
+ candidates.push(f);
505
+ }
506
+ // Stable within equal rank: `sort` is stable in V8, so the model's own
507
+ // ordering breaks ties rather than something arbitrary.
508
+ candidates.sort((a, b) => rankOf(b) - rankOf(a));
509
+ const inline = candidates.slice(0, Math.max(0, boundary.maxInlineComments));
510
+ for (const f of candidates.slice(Math.max(0, boundary.maxInlineComments))) {
511
+ body.push({ finding: f, reason: "overflow" });
512
+ }
513
+ // The body budget — LAST, over the FINAL body list, so the inline overflow
514
+ // has already landed there and competes for body slots like everything else
515
+ // (under a cap of 0 the inline excess therefore goes `internal`, not to a
516
+ // body the cap just closed). Ranked by the same severity × confidence rank
517
+ // the inline budget spends — {@link rankOf}, absent confidence = 1.0 — and
518
+ // the sort is over a COPY: the survivors keep their document order, so the
519
+ // grouped rendering and the disposition rows read as before. Ties across
520
+ // the cut fall to document order (stable sort), the same tie-break the
521
+ // inline budget uses. `null`/absent = unlimited, the legacy funnel.
522
+ const cap = boundary.maxBodyComments;
523
+ if (cap === null || cap === undefined || body.length <= Math.max(0, cap)) {
524
+ return { inline, body, internal };
525
+ }
526
+ const keep = new Set([...body]
527
+ .sort((a, b) => rankOf(b.finding) - rankOf(a.finding))
528
+ .slice(0, Math.max(0, cap)));
529
+ const kept = [];
530
+ for (const e of body) {
531
+ if (keep.has(e))
532
+ kept.push(e);
533
+ else
534
+ internal.push({ finding: e.finding, reason: "body-budget" });
535
+ }
536
+ return { inline, body: kept, internal };
537
+ }
102
538
  function commentBody(f) {
103
- let b = "**[" + (f.severity || "Important") + "] " + (f.title || "") + "**\n\n" + (f.body || "");
539
+ let b = "**[" +
540
+ (f.severity || "Important") +
541
+ "] " +
542
+ (f.title || "") +
543
+ "**\n\n" +
544
+ (f.body || "");
104
545
  if (f.suggestion)
105
546
  b += "\n\n" + FENCE + "suggestion\n" + f.suggestion + "\n" + FENCE;
106
547
  return b;
107
548
  }
108
- /** The "Additional findings" section appended to the body for demoted findings. */
549
+ /** The bullet list itself — shared by the flat and the grouped renderings. */
550
+ function renderDemotedItems(list) {
551
+ return list
552
+ .map((f) => "- **[" +
553
+ (f.severity || "Important") +
554
+ "] " +
555
+ (f.title || "") +
556
+ "** (" +
557
+ f.path +
558
+ // A finding the cascade could not place has no line, and `path:undefined`
559
+ // reads as a bug in the reviewer rather than as an honest "somewhere in
560
+ // this file". WP6a made `line` optional; this is where that surfaces.
561
+ (f.line ? ":" + f.line : "") +
562
+ ") — " +
563
+ (f.body || ""))
564
+ .join("\n");
565
+ }
566
+ /**
567
+ * The flat "Additional findings" section — no reasons, one heading. Still the
568
+ * whole story when there is no attention boundary configured, and the shape the
569
+ * body-only retry uses (there every finding is demoted for the same reason).
570
+ */
109
571
  export function renderDemoted(list) {
110
572
  if (!list.length)
111
573
  return "";
112
- return ("\n\n### Additional findings\n" +
113
- list
114
- .map((f) => "- **[" +
115
- (f.severity || "Important") +
116
- "] " +
117
- (f.title || "") +
118
- "** (" +
119
- f.path +
120
- ":" +
121
- f.line +
122
- ") — " +
123
- (f.body || ""))
124
- .join("\n"));
574
+ return "\n\n### Additional findings\n" + renderDemotedItems(list);
575
+ }
576
+ /**
577
+ * The reason lead-ins for the grouped body section. Three causes under one
578
+ * heading is a worse review to read, so each group says what it is — and the
579
+ * wording matters: none of these mean "we were not sure", they mean "this did
580
+ * not earn an inline comment", which is a different claim.
581
+ */
582
+ const DEMOTION_LEAD = {
583
+ "off-diff": "_Outside this PR's diff — GitHub cannot anchor a comment here._",
584
+ "below-threshold": "_Below the reporting confidence bar for their family._",
585
+ overflow: "_Beyond the inline comment budget, ranked by severity and confidence._",
586
+ adjudicated: "_Reported here rather than inline by the adjudicating pass._",
587
+ };
588
+ const DEMOTION_ORDER = [
589
+ "off-diff",
590
+ "below-threshold",
591
+ "adjudicated",
592
+ "overflow",
593
+ ];
594
+ /**
595
+ * The "Additional findings" section, grouped by why each finding is here.
596
+ *
597
+ * Everything in it is still POSTED and still visible — demotion is not
598
+ * suppression. What it is not is an inline comment at the defect site, and the
599
+ * evidence says that difference is large ("Does AI Code Review Lead to Code
600
+ * Changes?", 22k+ real comments: concise, hunk-level, actionable findings are
601
+ * substantially likelier to cause a change).
602
+ */
603
+ export function renderDemotedGrouped(entries) {
604
+ if (!entries.length)
605
+ return "";
606
+ const out = ["\n\n### Additional findings"];
607
+ for (const reason of DEMOTION_ORDER) {
608
+ const group = entries.filter((e) => e.reason === reason);
609
+ if (!group.length)
610
+ continue;
611
+ out.push("", DEMOTION_LEAD[reason], renderDemotedItems(group.map((e) => e.finding)));
612
+ }
613
+ return out.join("\n");
125
614
  }
126
615
  /** Build the inline-comment objects GitHub's create-review API expects. */
127
616
  export function toInlineComments(list) {
128
617
  return list.map((f) => {
129
618
  const side = f.side === "LEFT" ? "LEFT" : "RIGHT";
130
- const c = { path: f.path, line: f.line, side, body: commentBody(f) };
619
+ const c = {
620
+ path: f.path,
621
+ line: f.line,
622
+ side,
623
+ body: commentBody(f),
624
+ };
131
625
  if (f.start_line) {
132
626
  c.start_line = f.start_line;
133
627
  c.start_side = side;
@@ -135,43 +629,116 @@ export function toInlineComments(list) {
135
629
  return c;
136
630
  });
137
631
  }
632
+ /**
633
+ * The worse of the two axes, or `undefined` when neither was recorded.
634
+ *
635
+ * Ordering is `fail` > `unknown` > `pass`, and only `fail` is load-bearing —
636
+ * see {@link SplitVerdict} for why `unknown` must not block.
637
+ */
638
+ export function worstAxis(verdict) {
639
+ if (!verdict)
640
+ return undefined;
641
+ const axes = [verdict.spec, verdict.standards].filter((v) => v === "pass" || v === "fail" || v === "unknown");
642
+ if (axes.length === 0)
643
+ return undefined;
644
+ if (axes.includes("fail"))
645
+ return "fail";
646
+ if (axes.includes("unknown"))
647
+ return "unknown";
648
+ return "pass";
649
+ }
138
650
  /**
139
651
  * Resolve the review event. An explicit `doc.event` wins; otherwise an empty
140
652
  * findings set is an `APPROVE` and anything else is a `COMMENT` (never an
141
653
  * automatic `REQUEST_CHANGES` — that stays an explicit, deliberate call).
654
+ *
655
+ * ## The split verdict's one effect
656
+ *
657
+ * A `fail` on EITHER axis stops the review being an `APPROVE`; it becomes a
658
+ * `COMMENT`. Nothing else changes: the event is never escalated to
659
+ * `REQUEST_CHANGES`, and among the non-APPROVE events an explicit `doc.event`
660
+ * still wins, so a fork choosing `REQUEST_CHANGES` over `COMMENT` keeps its
661
+ * choice.
662
+ *
663
+ * **Why the downgrade also applies to an EXPLICIT `APPROVE`**, which is the one
664
+ * judgement call in this function. The retired WP6 doc (git history; condensed
665
+ * in `docs/plans/deterministic-pr-levers.md` §"Adjudication and the attention
666
+ * boundary (WP6)") says `resolveEvent` "takes
667
+ * the worse of the two axes" while `event` "remains explicit-wins". Read
668
+ * strictly, those contradict: today's skill makes `event` a REQUIRED field, so
669
+ * an always-present explicit event would make the split verdict inert by
670
+ * construction — the passing axis would go on hiding the failing one, which is
671
+ * the entire defect #271 filed. So "explicit-wins" is read as governing the
672
+ * CHOICE OF EVENT, and the axis verdict as a FLOOR under it, exactly like the
673
+ * skill's existing "never APPROVE over an open human CHANGES_REQUESTED" rule.
674
+ * An agent that writes `event: APPROVE` beside `verdict.spec: "fail"` has
675
+ * contradicted itself, and the safe reading of a self-contradiction is the one
676
+ * that does not silently approve a change that does not do what was asked.
142
677
  */
143
678
  export function resolveEvent(doc) {
144
679
  const findings = Array.isArray(doc.findings) ? doc.findings : [];
145
- return doc.event || (findings.length === 0 ? "APPROVE" : "COMMENT");
680
+ const event = doc.event || (findings.length === 0 ? "APPROVE" : "COMMENT");
681
+ if (event === "APPROVE" && worstAxis(doc.verdict) === "fail")
682
+ return "COMMENT";
683
+ return event;
146
684
  }
147
685
  /**
148
686
  * Compose the full review payload. Pass `commentable = null` to force every
149
687
  * finding into the body (the diff-unavailable fallback).
150
688
  */
151
- export function buildReview(doc, commentable) {
689
+ export function buildReview(doc, commentable, boundary, clean) {
152
690
  const findings = Array.isArray(doc.findings) ? doc.findings : [];
153
- const { inline, demoted } = splitFindings(findings, commentable);
691
+ if (!boundary) {
692
+ // No attention boundary — anchorability is the only question, exactly as
693
+ // before WP6b. This branch is what makes the feature inert on a deployment
694
+ // that has not enabled the evidence pipeline.
695
+ const { inline, demoted } = splitFindings(findings, commentable);
696
+ return {
697
+ event: resolveEvent(doc),
698
+ body: (doc.summary || "") + renderDemoted(demoted),
699
+ comments: toInlineComments(inline),
700
+ inlineCount: inline.length,
701
+ demotedCount: demoted.length,
702
+ internalCount: 0,
703
+ };
704
+ }
705
+ const tiered = tierFindings(findings, commentable, boundary, clean);
154
706
  return {
155
707
  event: resolveEvent(doc),
156
- body: (doc.summary || "") + renderDemoted(demoted),
157
- comments: toInlineComments(inline),
158
- inlineCount: inline.length,
159
- demotedCount: demoted.length,
708
+ body: (doc.summary || "") + renderDemotedGrouped(tiered.body),
709
+ comments: toInlineComments(tiered.inline),
710
+ inlineCount: tiered.inline.length,
711
+ demotedCount: tiered.body.length,
712
+ internalCount: tiered.internal.length,
713
+ tiered,
160
714
  };
161
715
  }
162
716
  /**
163
717
  * The body-only fallback: when the inline POST is rejected (e.g. a stale diff
164
- * yields a 422 on a comment line), re-render with ALL findings in the body so
165
- * the review still lands. Same event as the inline attempt.
718
+ * yields a 422 on a comment line), re-render with every POSTABLE finding in the
719
+ * body so the review still lands. Same event as the inline attempt.
720
+ *
721
+ * **Pass `tiered` whenever the boundary produced one.** Without it this
722
+ * re-reads `doc.findings` wholesale, which republishes the `internal` tier —
723
+ * the conservation floor's repaired hypotheses and the anti-findings alike — so
724
+ * "recorded, never posted" would hold on the happy path and quietly stop
725
+ * holding on the retry. That is a dark drop's mirror image: a publication
726
+ * nobody decided on, reached by a failure in an unrelated request. Omitted ⇒
727
+ * today's behaviour exactly, which is what every no-boundary caller gets.
166
728
  */
167
- export function buildBodyOnlyReview(doc) {
168
- const findings = Array.isArray(doc.findings) ? doc.findings : [];
729
+ export function buildBodyOnlyReview(doc, tiered) {
730
+ const findings = tiered
731
+ ? [...tiered.inline, ...tiered.body.map((d) => d.finding)]
732
+ : Array.isArray(doc.findings)
733
+ ? doc.findings
734
+ : [];
169
735
  return {
170
736
  event: resolveEvent(doc),
171
737
  body: (doc.summary || "") + renderDemoted(findings),
172
738
  comments: [],
173
739
  inlineCount: 0,
174
740
  demotedCount: findings.length,
741
+ internalCount: 0,
175
742
  };
176
743
  }
177
744
  //# sourceMappingURL=review-poster.js.map