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