lastlight-core 0.34.1 → 0.35.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 (70) hide show
  1. package/config/default.yaml +100 -138
  2. package/dist/config/config.d.ts +11 -0
  3. package/dist/config/config.js +93 -30
  4. package/dist/config/config.js.map +1 -1
  5. package/dist/engine/github/github.d.ts +42 -0
  6. package/dist/engine/github/github.js +41 -0
  7. package/dist/engine/github/github.js.map +1 -1
  8. package/dist/engine/github/review-poster.d.ts +16 -3
  9. package/dist/engine/github/review-poster.js +3 -3
  10. package/dist/engine/github/review-poster.js.map +1 -1
  11. package/dist/engine/github/review-summary.d.ts +2 -2
  12. package/dist/engine/github/review-summary.js +1 -1
  13. package/dist/engine/github/review-summary.js.map +1 -1
  14. package/dist/engine/pr-decisions.d.ts +7 -0
  15. package/dist/engine/pr-decisions.js +84 -97
  16. package/dist/engine/pr-decisions.js.map +1 -1
  17. package/dist/engine/pr-discussion.d.ts +23 -0
  18. package/dist/engine/pr-discussion.js +55 -0
  19. package/dist/engine/pr-discussion.js.map +1 -0
  20. package/dist/engine/pr-intent.d.ts +32 -0
  21. package/dist/engine/pr-intent.js +55 -0
  22. package/dist/engine/pr-intent.js.map +1 -0
  23. package/dist/engine/pr-state.d.ts +10 -2
  24. package/dist/engine/pr-state.js +14 -2
  25. package/dist/engine/pr-state.js.map +1 -1
  26. package/dist/engine/review-spec.d.ts +2 -87
  27. package/dist/engine/review-spec.js +2 -445
  28. package/dist/engine/review-spec.js.map +1 -1
  29. package/dist/engine/review-triage.d.ts +27 -9
  30. package/dist/engine/review-triage.js +20 -7
  31. package/dist/engine/review-triage.js.map +1 -1
  32. package/dist/evals-api.d.ts +7 -0
  33. package/dist/evals-api.js +21 -0
  34. package/dist/evals-api.js.map +1 -1
  35. package/dist/sandbox/sandbox.d.ts +25 -0
  36. package/dist/sandbox/sandbox.js +97 -14
  37. package/dist/sandbox/sandbox.js.map +1 -1
  38. package/dist/workflows/handlers/fanout.d.ts +17 -4
  39. package/dist/workflows/handlers/fanout.js +68 -31
  40. package/dist/workflows/handlers/fanout.js.map +1 -1
  41. package/dist/workflows/handlers/host-repo-dir.d.ts +38 -0
  42. package/dist/workflows/handlers/host-repo-dir.js +55 -0
  43. package/dist/workflows/handlers/host-repo-dir.js.map +1 -0
  44. package/dist/workflows/handlers/post-review.d.ts +9 -1
  45. package/dist/workflows/handlers/post-review.js +39 -16
  46. package/dist/workflows/handlers/post-review.js.map +1 -1
  47. package/dist/workflows/handlers/survey-units.d.ts +323 -0
  48. package/dist/workflows/handlers/survey-units.js +1211 -0
  49. package/dist/workflows/handlers/survey-units.js.map +1 -0
  50. package/dist/workflows/runner.js +42 -15
  51. package/dist/workflows/runner.js.map +1 -1
  52. package/package.json +9 -9
  53. package/skills/code-review/SKILL.md +2 -3
  54. package/skills/pr-review/references/findings-schema.md +4 -4
  55. package/workflows/pr-review.yaml +491 -271
  56. package/workflows/prompts/review-falsify.md +17 -9
  57. package/workflows/prompts/review-select.md +113 -0
  58. package/workflows/prompts/review-site-summary.md +48 -0
  59. package/workflows/prompts/review-site.md +305 -0
  60. package/workflows/prompts/review.md +0 -60
  61. package/workflows/prompts/survey-unit.md +60 -0
  62. package/skills/adjudicate-pass/SKILL.md +0 -149
  63. package/skills/survey-pass/SKILL.md +0 -139
  64. package/workflows/prompts/review-adjudicate.md +0 -498
  65. package/workflows/prompts/survey-contract.md +0 -121
  66. package/workflows/prompts/survey-enforcement.md +0 -105
  67. package/workflows/prompts/survey-security.md +0 -162
  68. package/workflows/prompts/survey-spec.md +0 -131
  69. package/workflows/prompts/survey-state.md +0 -152
  70. package/workflows/prompts/survey-tests.md +0 -99
@@ -0,0 +1,1211 @@
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import { mkdirSync, readFileSync, renameSync, rmSync, unlinkSync, writeFileSync } from "node:fs";
3
+ import { dirname, join, resolve } from "node:path";
4
+ import { completeSimple } from "@earendil-works/pi-ai/compat";
5
+ import { OPENINFERENCE_CHAIN, OPENINFERENCE_SPAN_KIND, renderTemplate, resolveTemplatedNumber, runLedgeredPhase, } from "lastlight-workflow-engine";
6
+ import { defaultReviewPolicy } from "lastlight-shared/config-types";
7
+ import { completeWithRetry, endpointApiKey, resolveModel } from "../../engine/chat/chat-runner.js";
8
+ import { AgenticShim } from "../../engine/event-shim.js";
9
+ import { resolveSessionsDir } from "../../engine/executors/shared.js";
10
+ import { OAUTH_ONLY_PROVIDERS, oauthProviderIdForModel, resolveOAuthApiKey } from "../../engine/oauth.js";
11
+ import { logger } from "../../logging/logger.js";
12
+ import { CHAT_PROJECT_SLUG, projectSlugForCwd } from "../../session-log.js";
13
+ import { HOST_READABLE_WORKSPACE, resolveHostRepoDir } from "./host-repo-dir.js";
14
+ const log = logger("survey-units");
15
+ /**
16
+ * The `type: survey-units` phase — the model half of the per-unit survey
17
+ * (`docs/plans/pr-review-units-sites.md`).
18
+ *
19
+ * `lastlight-facts units` (a bash phase, in the sandbox) has already cut the PR
20
+ * into units and rendered each one's COMPLETE request. This handler does only
21
+ * model I/O: one bounded, non-agentic call per unit, the phase's prompt as the
22
+ * system prompt and `unit.request` verbatim as the user message, then one
23
+ * `units/responses/<unitId>.json` per unit for `lastlight-facts units-ingest`
24
+ * to validate and turn into `hypotheses/<family>.jsonl`. Core does not depend
25
+ * on `lastlight-code-facts` and must not start to — the package drags tsgo and
26
+ * ast-grep natives into the agent image — so the FILE CONTRACT is the whole
27
+ * interface.
28
+ *
29
+ * **Why in-process rather than an agent phase.** A unit is a single request
30
+ * with no tools. An agent session would spend its turns re-deriving, with bash,
31
+ * the context the request already carries — which is the cost this engine
32
+ * exists to remove.
33
+ *
34
+ * **Only host-checkout backends.** The handler reads and writes the workspace
35
+ * from the harness. `kubernetes` has no host checkout (its paths are in-pod;
36
+ * see {@link HOST_READABLE_WORKSPACE}), so `loadConfig` refuses
37
+ * `review.analysis.enabled` there at startup; the run-time check below is a guard
38
+ * that degrades, never the primary refusal.
39
+ *
40
+ * **Degrade, don't fail.** Every path INSIDE the phase — no `units.json`, an
41
+ * empty or unreadable one, every call failing, the phase deadline, a cancel —
42
+ * ends in a SUCCEEDED phase with a loud summary and a warn log. A red phase
43
+ * here would post nothing and re-arm the review sweep, while `units-ingest`
44
+ * (which runs either way) already records every obligation no unit answered.
45
+ *
46
+ * **Visible like any other phase.** One virtual session transcript through
47
+ * {@link AgenticShim} (one `survey_unit` tool call per model call, so a retry
48
+ * or a cache hit is its own pair), and one `executions` row through
49
+ * {@link runLedgeredPhase} carrying that session id and the summed cost. The
50
+ * dashboard finds a phase's transcript ONLY via `executions.session_id`, stats
51
+ * cost only off that row, and the evals harness costs a phase off the
52
+ * transcript's `result` line — so all three are load-bearing.
53
+ */
54
+ /** Relative to the checkout — the same root every deterministic phase wrote in. */
55
+ const PR_REVIEW_DIR = join(".lastlight", "pr-review");
56
+ const UNITS_FILE = "units.json";
57
+ const RESPONSES_DIR = join("units", "responses");
58
+ const INGEST_FILE = join("units", "ingest.json");
59
+ /** The tool name the transcript records each unit call under. */
60
+ export const SURVEY_UNIT_TOOL = "survey_unit";
61
+ /** A unit id is also a filename, so it is held to the session-id alphabet. */
62
+ const SAFE_UNIT_ID = /^[A-Za-z0-9_-]+$/;
63
+ const ZERO_USAGE = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, costUsd: 0 };
64
+ /** pi-ai's `reasoning` excludes `off` — its default IS no reasoning (chat-runner's rule). */
65
+ function thinkingLevel(variant) {
66
+ if (!variant || variant === "off")
67
+ return undefined;
68
+ return variant;
69
+ }
70
+ /**
71
+ * The production {@link UnitModelCall}: pi-ai's `completeSimple`, resolved and
72
+ * credentialed exactly as the in-process chat path does it (`chat-runner.ts`) —
73
+ * a deployment's endpoint override, a named key env var, an OAuth subscription
74
+ * token. Transient provider faults (429 / 5xx / network) are retried with
75
+ * backoff by `completeWithRetry` INSIDE one attempt; the handler's own single
76
+ * retry is for a reply that came back without a usable object for the unit.
77
+ *
78
+ * No explicit `maxTokens`: pi-ai sends the model's own output cap
79
+ * (`options.maxTokens ?? model.maxTokens`), the most generous value there is,
80
+ * and a reply that still hits it comes back `stopReason: "length"`.
81
+ *
82
+ * **Prompt caching.** The handler moves code-facts' byte-identical
83
+ * `sharedPrefix` (the unit-independent questions, evidence record and rules)
84
+ * OUT of the user message and onto the end of the system prompt, so every call
85
+ * of a phase opens with the same system text. `cacheRetention: "short"` is
86
+ * pi-ai's default, spelled out so a `PI_CACHE_RETENTION=long` in the harness
87
+ * env cannot silently double the write price of a phase that re-asks within
88
+ * minutes, not hours. What each provider does with it differs:
89
+ * - Anthropic caches only at explicit breakpoints. pi-ai folds
90
+ * `Context.systemPrompt` into a leading system message and emits it as
91
+ * `system: [{ type: "text", text, cache_control: { type: "ephemeral" } }]`
92
+ * (plus a second breakpoint on the last user block), so the system text —
93
+ * prompt AND shared prefix — is the cross-unit cache hit. It is cached only
94
+ * above the model's minimum cacheable length.
95
+ * - OpenAI-family prefix caching is automatic over any identical prefix
96
+ * (≥1024 tokens); `cacheKey` goes out as `prompt_cache_key` to keep
97
+ * concurrent calls on one cache.
98
+ */
99
+ export const completeUnitCall = async ({ model, variant, systemPrompt, request, timeoutMs, cacheKey, signal, }) => {
100
+ const resolved = resolveModel(model);
101
+ let apiKey;
102
+ const oauthId = oauthProviderIdForModel(model);
103
+ if (oauthId) {
104
+ const res = await resolveOAuthApiKey(oauthId);
105
+ if (res)
106
+ apiKey = res.apiKey;
107
+ else if (OAUTH_ONLY_PROVIDERS.has(oauthId)) {
108
+ throw new Error(`model '${model}' requires an OAuth login — run: lastlight oauth login ${oauthId}`);
109
+ }
110
+ }
111
+ const key = apiKey ?? endpointApiKey(resolved.provider);
112
+ const context = {
113
+ systemPrompt,
114
+ messages: [{ role: "user", content: request, timestamp: Date.now() }],
115
+ };
116
+ const reasoning = thinkingLevel(variant);
117
+ const assistant = await completeWithRetry(completeSimple, resolved, context, {
118
+ timeoutMs,
119
+ cacheRetention: "short",
120
+ sessionId: cacheKey,
121
+ ...(resolved.api === "anthropic-messages" ? { onPayload: systemOnlyCacheBreakpoint } : {}),
122
+ ...(signal ? { signal } : {}),
123
+ ...(reasoning ? { reasoning } : {}),
124
+ ...(key ? { apiKey: key } : {}),
125
+ });
126
+ const text = assistant.content
127
+ .filter((c) => c.type === "text" && typeof c.text === "string")
128
+ .map((c) => c.text)
129
+ .join("");
130
+ const failed = assistant.stopReason === "error" || assistant.stopReason === "aborted";
131
+ return {
132
+ text,
133
+ stopReason: assistant.stopReason,
134
+ usage: {
135
+ input: assistant.usage.input,
136
+ output: assistant.usage.output,
137
+ cacheRead: assistant.usage.cacheRead,
138
+ cacheWrite: assistant.usage.cacheWrite,
139
+ costUsd: assistant.usage.cost.total,
140
+ },
141
+ ...(failed ? { error: assistant.errorMessage ?? assistant.stopReason } : {}),
142
+ };
143
+ };
144
+ /**
145
+ * Keep Anthropic's cache breakpoint on the SYSTEM prompt only.
146
+ *
147
+ * pi-ai also marks the last user block `cache_control`, which is right for a
148
+ * conversation and wrong here: a unit's user message is that unit's own
149
+ * request, never sent twice, so the breakpoint bought a 1.25x cache WRITE on
150
+ * every unit's unique input and no read. Measured on 1587-r2 (Haiku 4.5, v7,
151
+ * 74 calls): 358k tokens written, 26k read — about 55% of the case's $0.81.
152
+ * The system prompt (role + the shared prefix) is identical on every call and
153
+ * keeps its breakpoint, which is the part worth caching.
154
+ */
155
+ export function systemOnlyCacheBreakpoint(payload) {
156
+ const p = payload;
157
+ if (!p || !Array.isArray(p.messages))
158
+ return undefined;
159
+ for (const m of p.messages) {
160
+ if (!Array.isArray(m.content))
161
+ continue;
162
+ for (const block of m.content) {
163
+ if (block && typeof block === "object")
164
+ delete block.cache_control;
165
+ }
166
+ }
167
+ return p;
168
+ }
169
+ /**
170
+ * What identifies the ENDPOINT a model string resolves to — provider, request
171
+ * family, model id and base URL, after this deployment's `providers:`
172
+ * overrides. Part of the reply cache key: the same `{{models.review-survey}}`
173
+ * spelling pointed at a different gateway is a different model as far as a
174
+ * cached reading is concerned. An unresolvable spec keys on itself (its call
175
+ * fails anyway, and a failure is never cached).
176
+ */
177
+ export function unitEndpointIdentity(model) {
178
+ try {
179
+ const m = resolveModel(model);
180
+ return [m.provider, m.api, m.id, m.baseUrl].join("|");
181
+ }
182
+ catch {
183
+ return `unresolved|${model}`;
184
+ }
185
+ }
186
+ function sha256(text) {
187
+ return createHash("sha256").update(text).digest("hex");
188
+ }
189
+ /**
190
+ * Read and shape-check `units.json`. Throws with a message fit for the loud
191
+ * summary: the `units` phase ALWAYS writes a document (its shell fallback
192
+ * included), so a missing or malformed one is a broken contract, never an
193
+ * empty survey — the caller degrades on it rather than failing the phase.
194
+ */
195
+ export function readUnitsDocument(path) {
196
+ let parsed;
197
+ try {
198
+ parsed = JSON.parse(readFileSync(path, "utf8"));
199
+ }
200
+ catch (err) {
201
+ const reason = err instanceof Error ? err.message : String(err);
202
+ throw new Error(`survey-units: could not read ${path} (${reason}) — the \`units\` phase always writes this document, ` +
203
+ `so its absence means that phase did not run or did not survive; no unit was surveyed`);
204
+ }
205
+ const doc = parsed;
206
+ if (!doc || typeof doc !== "object" || !Array.isArray(doc.units)) {
207
+ throw new Error(`survey-units: ${path} has no \`units\` array — not a units document`);
208
+ }
209
+ const seen = new Set();
210
+ for (const [i, u] of doc.units.entries()) {
211
+ if (!u || typeof u !== "object" || typeof u.id !== "string" || typeof u.request !== "string") {
212
+ throw new Error(`survey-units: ${path} units[${i}] has no string \`id\` and \`request\``);
213
+ }
214
+ if (!SAFE_UNIT_ID.test(u.id)) {
215
+ throw new Error(`survey-units: ${path} units[${i}] id ${JSON.stringify(u.id)} is not a safe filename`);
216
+ }
217
+ if (seen.has(u.id))
218
+ throw new Error(`survey-units: ${path} repeats unit id ${u.id}`);
219
+ seen.add(u.id);
220
+ }
221
+ return doc;
222
+ }
223
+ // ── The ONE reply rule ───────────────────────────────────────────────────────
224
+ //
225
+ // A COPY of the canonical `findUnitObject` / `isUsableUnitReply` in
226
+ // `packages/code-facts/src/unit-response.ts`, which `units-ingest` judges every
227
+ // reply by. Core may not import code-facts (see the module header), and the
228
+ // handler's retry and cache decisions must be the SAME decision ingest makes —
229
+ // a reply this accepts and ingest rejects was cached forever as an answer
230
+ // ingest would never use. Change the two together:
231
+ // `tests/workflows/survey-units.test.ts` carries a VERBATIM copy of the case
232
+ // tables in `packages/code-facts/tests/unit-reply.test.ts`.
233
+ /** Index just past the `{…}` opening at `start` (string-aware), or -1 if the text ends first. */
234
+ function objectEnd(text, start) {
235
+ let depth = 0;
236
+ let inString = false;
237
+ for (let i = start; i < text.length; i += 1) {
238
+ const ch = text[i];
239
+ if (inString) {
240
+ if (ch === "\\")
241
+ i += 1;
242
+ else if (ch === '"')
243
+ inString = false;
244
+ }
245
+ else if (ch === '"')
246
+ inString = true;
247
+ else if (ch === "{")
248
+ depth += 1;
249
+ else if (ch === "}") {
250
+ depth -= 1;
251
+ if (depth === 0)
252
+ return i + 1;
253
+ }
254
+ }
255
+ return -1;
256
+ }
257
+ function isPlainObject(v) {
258
+ return v !== null && typeof v === "object" && !Array.isArray(v);
259
+ }
260
+ /**
261
+ * `JSON.parse` plus one repair — a `"line"` number with leading zeros, copied
262
+ * from the request's `L0142` tag. Mirrors code-facts' `parseReplyJson`.
263
+ */
264
+ function parseReplyJson(text) {
265
+ try {
266
+ return JSON.parse(text);
267
+ }
268
+ catch (err) {
269
+ const repaired = text.replace(/("line"\s*:\s*)0+(\d)/g, "$1$2");
270
+ if (repaired === text)
271
+ throw err;
272
+ return JSON.parse(repaired);
273
+ }
274
+ }
275
+ /**
276
+ * Every balanced top-level `{…}` span in `text` that parses as a JSON object,
277
+ * in order. An UNCLOSED `{` (a stray brace in prose, a truncated reply) is
278
+ * skipped and the scan CONTINUES from the next character — never abandoned —
279
+ * and so is a balanced span that is not JSON.
280
+ */
281
+ function objectSpans(text) {
282
+ const out = [];
283
+ let pos = 0;
284
+ while (pos < text.length) {
285
+ const start = text.indexOf("{", pos);
286
+ if (start === -1)
287
+ break;
288
+ const end = objectEnd(text, start);
289
+ if (end !== -1) {
290
+ try {
291
+ const value = parseReplyJson(text.slice(start, end));
292
+ if (isPlainObject(value)) {
293
+ out.push(value);
294
+ pos = end;
295
+ continue;
296
+ }
297
+ }
298
+ catch {
299
+ /* balanced but not JSON — try the next brace */
300
+ }
301
+ }
302
+ pos = start + 1;
303
+ }
304
+ return out;
305
+ }
306
+ /** The bodies of the ``` fences in `text`, in order — scanned on their own too, so a quote in prose cannot hide one. */
307
+ function fencedBodies(text) {
308
+ const out = [];
309
+ for (const m of text.matchAll(/```[^\n`]*\n([\s\S]*?)```/g))
310
+ out.push(m[1]);
311
+ return out;
312
+ }
313
+ /**
314
+ * The reply object for `unitId` in a model's raw text, or `null` — the
315
+ * canonical rule, step for step:
316
+ *
317
+ * 1. Candidates are every balanced top-level `{…}` span that parses as a JSON
318
+ * object — first across the whole of `raw`, then inside each ``` fence
319
+ * body — in that order (see `objectSpans`).
320
+ * 2. The FIRST candidate whose `unitId` is exactly `unitId` is the reply.
321
+ * 3. Otherwise ONE level of nesting: per candidate, a property value that is
322
+ * an object with that `unitId`, or such an object element of a property
323
+ * value that is an array (`{"result": {…}}`, `{"units": [{…}]}`).
324
+ * 4. Otherwise `null`. An object naming ANOTHER unit is never this unit's.
325
+ */
326
+ export function findUnitObject(raw, unitId) {
327
+ const candidates = [raw, ...fencedBodies(raw)].flatMap(objectSpans);
328
+ const direct = candidates.find((c) => c.unitId === unitId);
329
+ if (direct)
330
+ return direct;
331
+ for (const c of candidates) {
332
+ for (const v of Object.values(c)) {
333
+ const inner = Array.isArray(v) ? v : [v];
334
+ const hit = inner.find((e) => isPlainObject(e) && e.unitId === unitId);
335
+ if (hit)
336
+ return hit;
337
+ }
338
+ }
339
+ return null;
340
+ }
341
+ /**
342
+ * Whether a found object is a reply `units-ingest` can use: an object naming
343
+ * this unit, with `answers` and `defects` both arrays (possibly empty). The
344
+ * entries are not inspected — a malformed entry is ingest's to record, never a
345
+ * reason to re-ask.
346
+ */
347
+ export function isUsableUnitReply(obj, unitId) {
348
+ return isPlainObject(obj) && obj.unitId === unitId && Array.isArray(obj.answers) && Array.isArray(obj.defects);
349
+ }
350
+ /** The handler's one decision about a reply: {@link findUnitObject} then {@link isUsableUnitReply}. */
351
+ export function usableUnitReply(raw, unitId) {
352
+ return isUsableUnitReply(findUnitObject(raw, unitId), unitId);
353
+ }
354
+ /** Write a file whole or not at all — a concurrent reader never sees half of it. */
355
+ function writeAtomic(path, body) {
356
+ mkdirSync(dirname(path), { recursive: true });
357
+ const tmp = `${path}.${process.pid}.${randomUUID().slice(0, 8)}.tmp`;
358
+ writeFileSync(tmp, body);
359
+ renameSync(tmp, path);
360
+ }
361
+ // ── The response cache ───────────────────────────────────────────────────────
362
+ /**
363
+ * Readings cached OUTSIDE the per-run workspace, so a re-review of the same
364
+ * repo reuses every unit whose request did not change — the other half of the
365
+ * perch shape. Keyed on everything that determines the reply: the RESOLVED
366
+ * endpoint ({@link unitEndpointIdentity} — provider, api, model id, base URL),
367
+ * the thinking level, and the hashes of the system text and the user message
368
+ * actually sent (which together carry the prompt, the shared prefix, the
369
+ * unit's code, its obligations and code-facts' `promptVersion`).
370
+ *
371
+ * Only replies that pass the ONE reply rule ({@link usableUnitReply}) are
372
+ * stored, and a hit is re-checked against it — so an entry written under a
373
+ * looser rule is ignored rather than replayed. An entry `units-ingest` later
374
+ * judged `invalid` / `partial` is EVICTED at the start of the next run (see
375
+ * `previousBadRequests`). Scoped by `<owner>/<repo>` so one repository's cache
376
+ * cannot answer for another's, even on an identical request.
377
+ */
378
+ export function unitCacheDir(stateDir, owner, repo) {
379
+ const safe = (s) => (s.replace(/[^A-Za-z0-9._-]/g, "_").replace(/^\.+/, "_") || "_");
380
+ return join(stateDir, "unit-survey-cache", safe(owner), safe(repo));
381
+ }
382
+ /** Version-tagged, so a change to what the key covers never replays an old entry. */
383
+ function cacheKey(k) {
384
+ return sha256(["unit-cache-v2", k.endpoint, k.variant ?? "", k.systemSha256, k.userSha256].join("\n"));
385
+ }
386
+ function readCached(dir, key, unitId) {
387
+ try {
388
+ const rec = JSON.parse(readFileSync(join(dir, `${key}.json`), "utf8"));
389
+ return rec && rec.ok === true && typeof rec.raw === "string" && usableUnitReply(rec.raw, unitId) ? rec : undefined;
390
+ }
391
+ catch {
392
+ return undefined;
393
+ }
394
+ }
395
+ /** Remove one cache entry; true when there was one. Never throws. */
396
+ function evictCached(dir, key) {
397
+ try {
398
+ unlinkSync(join(dir, `${key}.json`));
399
+ return true;
400
+ }
401
+ catch {
402
+ return false;
403
+ }
404
+ }
405
+ /** `units-ingest` statuses that mean a reply the handler accepted was not an answer. */
406
+ const EVICT_STATUSES = new Set(["invalid", "partial"]);
407
+ /**
408
+ * The requests whose cached reply the LAST run's `units-ingest` rejected, read
409
+ * from the previous `units/ingest.json` + `units/responses/<id>.json` BEFORE
410
+ * this run clears them. Ingest's report carries the unit id and status but not
411
+ * the request, so the response record left beside it supplies the
412
+ * `requestSha256`; the caller evicts the cache entry that request would hit.
413
+ *
414
+ * Best-effort and logged: any unreadable piece means nothing to evict, which
415
+ * costs at worst one replay of a reply ingest will record as unanswered again.
416
+ */
417
+ function previousBadRequests(prDir, phase) {
418
+ const out = new Set();
419
+ let report;
420
+ try {
421
+ report = JSON.parse(readFileSync(join(prDir, INGEST_FILE), "utf8"));
422
+ }
423
+ catch {
424
+ return out; // no previous ingest — the normal first run
425
+ }
426
+ const units = isPlainObject(report) && Array.isArray(report.units) ? report.units : [];
427
+ for (const u of units) {
428
+ if (!isPlainObject(u) || typeof u.unitId !== "string" || !EVICT_STATUSES.has(String(u.status)))
429
+ continue;
430
+ if (!SAFE_UNIT_ID.test(u.unitId))
431
+ continue;
432
+ try {
433
+ const rec = JSON.parse(readFileSync(join(prDir, RESPONSES_DIR, `${u.unitId}.json`), "utf8"));
434
+ if (isPlainObject(rec) && typeof rec.requestSha256 === "string")
435
+ out.add(rec.requestSha256);
436
+ }
437
+ catch (err) {
438
+ log.warn("unit survey: ingest rejected a reply whose response record is unreadable — cannot evict it", {
439
+ phase,
440
+ unitId: u.unitId,
441
+ status: u.status,
442
+ err,
443
+ });
444
+ }
445
+ }
446
+ if (out.size)
447
+ log.info("unit survey: evicting replies the last ingest rejected", { phase, requests: out.size });
448
+ return out;
449
+ }
450
+ // ── The transcript ───────────────────────────────────────────────────────────
451
+ /**
452
+ * ONE virtual session per phase, fed through {@link AgenticShim} the way
453
+ * `writeChatShim` (`engine/chat/chat.ts`) replays a chat turn: the shim already
454
+ * turns `message_end` / `tool_execution_end` into the envelope lines the
455
+ * dashboard's SessionReader and `lastlight session log` render.
456
+ *
457
+ * Events are fed as calls COMPLETE, and each call's pair is fed in one
458
+ * synchronous block — `feed` is synchronous and the shim serialises its own
459
+ * appends on one promise chain — so concurrent units never interleave a
460
+ * `tool_use` with another unit's `tool_result`. Every `tool_execution_end`
461
+ * follows its own `message_end`: the shim DROPS a result whose call id it never
462
+ * saw.
463
+ */
464
+ class UnitSurveyTranscript {
465
+ shim;
466
+ sessionId = randomUUID();
467
+ opened = false;
468
+ constructor(opts) {
469
+ this.shim = new AgenticShim({
470
+ homeDir: opts.sessionsDir,
471
+ projectSlug: opts.projectSlug,
472
+ model: opts.model,
473
+ initialPrompt: opts.initialPrompt,
474
+ phase: opts.phase,
475
+ });
476
+ }
477
+ open() {
478
+ this.feed({ type: "session", id: this.sessionId, timestamp: Date.now() });
479
+ this.opened = true;
480
+ }
481
+ /** One call (or cache hit): the assistant's tool call with its usage, then the result. */
482
+ call(toolCallId, text, args, usage, result, isError) {
483
+ const ts = Date.now();
484
+ this.feed({
485
+ type: "message_end",
486
+ sessionId: this.sessionId,
487
+ timestamp: ts,
488
+ message: {
489
+ role: "assistant",
490
+ content: [
491
+ { type: "text", text },
492
+ { type: "toolCall", id: toolCallId, name: SURVEY_UNIT_TOOL, arguments: args },
493
+ ],
494
+ usage: { input: usage.input, output: usage.output, cacheRead: usage.cacheRead, cacheWrite: usage.cacheWrite },
495
+ },
496
+ });
497
+ this.feed({
498
+ type: "tool_execution_end",
499
+ sessionId: this.sessionId,
500
+ timestamp: ts,
501
+ toolCallId,
502
+ toolName: SURVEY_UNIT_TOOL,
503
+ result,
504
+ isError,
505
+ });
506
+ }
507
+ say(text) {
508
+ this.feed({
509
+ type: "message_end",
510
+ sessionId: this.sessionId,
511
+ timestamp: Date.now(),
512
+ message: { role: "assistant", content: [{ type: "text", text }] },
513
+ });
514
+ }
515
+ async close(totals) {
516
+ this.shim.finalize({
517
+ finalText: totals.text,
518
+ turns: totals.turns,
519
+ costUsd: totals.usage.costUsd,
520
+ inputTokens: totals.usage.input,
521
+ outputTokens: totals.usage.output,
522
+ cacheReadInputTokens: totals.usage.cacheRead,
523
+ cacheCreationInputTokens: totals.usage.cacheWrite,
524
+ stopReason: totals.stopReason,
525
+ durationMs: totals.durationMs,
526
+ });
527
+ await this.shim.flush();
528
+ }
529
+ feed(record) {
530
+ this.shim.feed(record);
531
+ }
532
+ }
533
+ function addUsage(a, b) {
534
+ return {
535
+ input: a.input + b.input,
536
+ output: a.output + b.output,
537
+ cacheRead: a.cacheRead + b.cacheRead,
538
+ cacheWrite: a.cacheWrite + b.cacheWrite,
539
+ costUsd: a.costUsd + b.costUsd,
540
+ };
541
+ }
542
+ function unitLabel(u) {
543
+ const where = u.file ? `${u.file}${u.lines ? `:${u.lines[0]}-${u.lines[1]}` : ""}` : "the whole PR";
544
+ return `${u.id} · ${u.symbol ?? u.kind ?? "unit"} (${where})`;
545
+ }
546
+ /**
547
+ * A unit's request as the TRANSCRIPT records it: verbatim, except that the
548
+ * document's `sharedPrefix` — identical in every request, and shown once in the
549
+ * opening prompt — is replaced by a one-line marker. The model always gets the
550
+ * full request; this only keeps a hundred-unit transcript from carrying a
551
+ * hundred copies of the same few thousand characters.
552
+ */
553
+ function transcriptRequest(request, sharedPrefix) {
554
+ if (!sharedPrefix || !request.startsWith(sharedPrefix))
555
+ return request;
556
+ return `[shared request prefix — ${sharedPrefix.length} chars, shown once in the opening prompt]\n${request.slice(sharedPrefix.length)}`;
557
+ }
558
+ /** The unit list the transcript opens with, after the system prompt. */
559
+ function manifest(units, doc, prefixInSystem) {
560
+ const head = [
561
+ "---",
562
+ "",
563
+ `## Units to survey (${units.length})`,
564
+ "",
565
+ `coverage: ${doc.coverage ?? "unknown"} · promptVersion: ${doc.promptVersion ?? "unknown"}`,
566
+ "",
567
+ prefixInSystem
568
+ ? "The prompt above, followed by the shared request prefix below, is the SYSTEM prompt of every call; each call's user message is the rest of its unit's `request`."
569
+ : "The prompt above is the SYSTEM prompt of every call below; each call's user message is its unit's `request`, verbatim.",
570
+ "",
571
+ ];
572
+ if (units.length === 0)
573
+ return [...head, "(none — `units.json` lists no units)"].join("\n");
574
+ const rows = units.map((u) => {
575
+ const families = u.families?.length ? ` · families ${u.families.join(", ")}` : "";
576
+ const obligations = u.obligationIds?.length ? ` · obligations ${u.obligationIds.join(", ")}` : "";
577
+ return `- ${unitLabel(u)}${families}${obligations}${u.truncated ? " · TRUNCATED" : ""}`;
578
+ });
579
+ const shared = doc.sharedPrefix
580
+ ? [
581
+ "",
582
+ "## Shared request prefix",
583
+ "",
584
+ prefixInSystem
585
+ ? "Every request opens with these bytes. They were sent ONCE per call as the end of the system prompt (the cache breakpoint), not in the user message; the calls record them as a one-line marker."
586
+ : "Every request below opens with these bytes; the calls record it as a one-line marker.",
587
+ "",
588
+ doc.sharedPrefix,
589
+ ]
590
+ : [];
591
+ return [...head, ...rows, ...shared].join("\n");
592
+ }
593
+ /**
594
+ * The SYSTEM text every call of a survey sends, and how it was decided.
595
+ *
596
+ * The shared prefix goes to the SYSTEM prompt — where pi-ai puts Anthropic's
597
+ * cache breakpoint — only when every request really opens with it and keeps
598
+ * something after it. Otherwise every request is sent verbatim.
599
+ */
600
+ export function unitSurveySystemText(systemPrompt, doc) {
601
+ const units = doc.units;
602
+ const sharedPrefix = typeof doc.sharedPrefix === "string" && doc.sharedPrefix.length > 0 ? doc.sharedPrefix : undefined;
603
+ const splitPrefix = sharedPrefix && units.length > 0 && units.every((u) => u.request.startsWith(sharedPrefix) && u.request.length > sharedPrefix.length)
604
+ ? sharedPrefix
605
+ : undefined;
606
+ const systemText = splitPrefix ? `${systemPrompt}\n\n${splitPrefix}` : systemPrompt;
607
+ return { systemText, systemSha256: sha256(systemText), sharedPrefix, splitPrefix };
608
+ }
609
+ /**
610
+ * The model half of the unit survey, with no run, ledger or transcript of its
611
+ * own: one bounded call per unit (a cache hit, or up to two calls — see
612
+ * `surveyUnit`), `concurrency` at a time, one `<unitId>.json` per unit under
613
+ * `responsesDir`. Every unit settles — a throw anywhere in one unit (a
614
+ * response file that cannot be written, a bug) becomes THAT unit's failure, so
615
+ * the pool always drains. The phase handler wraps this; the evals replay calls
616
+ * it directly, with no cache, so every replay pays and measures.
617
+ */
618
+ export async function runUnitSurvey(opts) {
619
+ const { systemText, systemSha256, sharedPrefix, splitPrefix } = unitSurveySystemText(opts.systemPrompt, opts.doc);
620
+ const plan = {
621
+ model: opts.model,
622
+ variant: opts.variant,
623
+ endpoint: unitEndpointIdentity(opts.model),
624
+ systemText,
625
+ systemSha256,
626
+ splitPrefix,
627
+ sharedPrefix,
628
+ deadlineAt: opts.deadlineAt,
629
+ signal: opts.signal,
630
+ cacheDir: opts.cacheDir,
631
+ call: opts.call ?? completeUnitCall,
632
+ // Stable for everything the phase's calls share — the system text.
633
+ // Clamped well inside OpenAI's 64-char key.
634
+ promptCacheKey: `lastlight-units-${systemSha256.slice(0, 24)}`,
635
+ evict: opts.evict ?? new Set(),
636
+ ...(opts.transcript ? { transcript: opts.transcript } : {}),
637
+ };
638
+ let usage = { ...ZERO_USAGE };
639
+ let calls = 0;
640
+ const surveyOne = async (unit) => {
641
+ let o;
642
+ try {
643
+ o = await surveyUnit(unit, plan);
644
+ }
645
+ catch (err) {
646
+ const error = `the unit's survey threw: ${err instanceof Error ? err.message : String(err)}`;
647
+ log.error("unit survey threw", { unitId: unit.id, err });
648
+ o = { record: failedRecord(unit, plan, error, 0), calls: 0 };
649
+ }
650
+ try {
651
+ writeAtomic(join(opts.responsesDir, `${unit.id}.json`), `${JSON.stringify(o.record, null, 2)}\n`);
652
+ }
653
+ catch (err) {
654
+ const error = `could not write the response file: ${err instanceof Error ? err.message : String(err)}`;
655
+ log.error("unit survey: response file not written", { unitId: unit.id, err });
656
+ o = { ...o, record: { ...o.record, ok: false, error } };
657
+ }
658
+ usage = addUsage(usage, o.record.usage);
659
+ calls += o.calls;
660
+ opts.onSettled?.(o);
661
+ return o;
662
+ };
663
+ // WARM the prompt cache: one unit alone first, then the rest in parallel.
664
+ // Fired together, every call starts before any cache entry exists, so all of
665
+ // them WRITE the shared system prompt and none reads it (Haiku 4.5, v7:
666
+ // 358k written / 26k read on a 74-call case). One call's latency buys every
667
+ // other call a cache read of the ~11k-char system text.
668
+ const units = opts.doc.units;
669
+ const limit = Math.max(1, Math.floor(opts.concurrency));
670
+ const outcomes = units.length > 1 && limit > 1
671
+ ? [await surveyOne(units[0]), ...(await mapPool(units.slice(1), limit, surveyOne))]
672
+ : await mapPool(units, limit, surveyOne);
673
+ return { outcomes, usage, calls, systemSha256, prefixInSystem: !!splitPrefix };
674
+ }
675
+ /** One unit: a cache hit, or up to two calls. Never throws on a model failure. */
676
+ async function surveyUnit(unit, c) {
677
+ const startedAt = Date.now();
678
+ const requestSha256 = sha256(unit.request);
679
+ if (unit.requestSha256 && unit.requestSha256 !== requestSha256) {
680
+ log.warn("units.json requestSha256 does not match its request — caching on the request as sent", {
681
+ unitId: unit.id,
682
+ });
683
+ }
684
+ const contractSha = unit.requestSha256 ?? requestSha256;
685
+ const userText = c.splitPrefix ? unit.request.slice(c.splitPrefix.length) : unit.request;
686
+ const key = cacheKey({ endpoint: c.endpoint, variant: c.variant, systemSha256: c.systemSha256, userSha256: sha256(userText) });
687
+ const args = {
688
+ unitId: unit.id,
689
+ symbol: unit.symbol,
690
+ file: unit.file,
691
+ lines: unit.lines,
692
+ model: c.model,
693
+ request: transcriptRequest(unit.request, c.sharedPrefix),
694
+ };
695
+ // No cache dir ⇒ no cache at all: nothing read, evicted or written (the
696
+ // evals replay runs this way, so every run pays and measures).
697
+ if (c.cacheDir === undefined) {
698
+ /* uncached */
699
+ }
700
+ else if (c.evict.has(contractSha) || c.evict.has(requestSha256)) {
701
+ if (evictCached(c.cacheDir, key)) {
702
+ log.info("unit survey: evicted a cached reply the last ingest rejected", { unitId: unit.id });
703
+ }
704
+ }
705
+ else {
706
+ const hit = readCached(c.cacheDir, key, unit.id);
707
+ if (hit) {
708
+ const record = {
709
+ ...hit,
710
+ unitId: unit.id,
711
+ model: c.model,
712
+ systemPromptSha256: c.systemSha256,
713
+ requestSha256: contractSha,
714
+ cached: true,
715
+ usage: { ...ZERO_USAGE },
716
+ durationMs: Date.now() - startedAt,
717
+ };
718
+ c.transcript?.call(`${unit.id}-cache`, `${unitLabel(unit)} — cache hit (an identical request was answered before); no model call.`, { ...args, cached: true }, ZERO_USAGE, `[cached response]\n${hit.raw}`, false);
719
+ log.debug("unit survey cache hit", { unitId: unit.id });
720
+ return { record, calls: 0 };
721
+ }
722
+ }
723
+ let usage = { ...ZERO_USAGE };
724
+ let raw = "";
725
+ let error = null;
726
+ let ok = false;
727
+ let attempts = 0;
728
+ // At most TWO calls: the retry is for a reply without a usable object for
729
+ // the unit (or a call that failed outright). Never after the phase was
730
+ // aborted, and never after a reply cut at the output cap — the identical
731
+ // request would stop there again. Transient provider faults are already
732
+ // retried inside one call by `completeWithRetry`.
733
+ while (attempts < 2 && !ok) {
734
+ if (c.signal.aborted)
735
+ break;
736
+ attempts += 1;
737
+ const intro = attempts === 1
738
+ ? `Surveying ${unitLabel(unit)}.`
739
+ : `Retrying ${unit.id} once — the first attempt failed: ${error ?? "unknown"}`;
740
+ const callStarted = Date.now();
741
+ let callUsage = { ...ZERO_USAGE };
742
+ let callError;
743
+ let stopReason;
744
+ let text = "";
745
+ try {
746
+ const res = await c.call({
747
+ model: c.model,
748
+ ...(c.variant ? { variant: c.variant } : {}),
749
+ systemPrompt: c.systemText,
750
+ request: userText,
751
+ timeoutMs: Math.max(1000, c.deadlineAt - Date.now()),
752
+ cacheKey: c.promptCacheKey,
753
+ signal: c.signal,
754
+ });
755
+ text = res.text ?? "";
756
+ callUsage = { ...ZERO_USAGE, ...res.usage };
757
+ callError = res.error;
758
+ stopReason = res.stopReason;
759
+ }
760
+ catch (err) {
761
+ callError = err instanceof Error ? err.message : String(err);
762
+ }
763
+ // An abort during the call is recorded as the phase's reason, whatever
764
+ // shape the provider gave it.
765
+ if (c.signal.aborted)
766
+ callError = String(c.signal.reason);
767
+ usage = addUsage(usage, callUsage);
768
+ raw = text;
769
+ ok = callError === undefined && usableUnitReply(text, unit.id);
770
+ const truncated = !ok && callError === undefined && stopReason === "length";
771
+ error = ok
772
+ ? null
773
+ : (callError ??
774
+ (truncated
775
+ ? "the reply stopped at the output-token cap (stopReason: length) before holding a usable object — not retried, the identical request would stop there again"
776
+ : `the response holds no usable JSON object for unitId "${unit.id}" (it must name the unit and carry \`answers\` and \`defects\` arrays)`));
777
+ c.transcript?.call(`${unit.id}-a${attempts}`, intro, attempts === 1 ? args : { ...args, attempt: attempts }, callUsage, callError !== undefined ? callError : text || "(empty response)", !ok);
778
+ log.debug("unit survey call", {
779
+ unitId: unit.id,
780
+ attempt: attempts,
781
+ ok,
782
+ stopReason,
783
+ durationMs: Date.now() - callStarted,
784
+ costUsd: callUsage.costUsd,
785
+ });
786
+ if (truncated || c.signal.aborted)
787
+ break;
788
+ }
789
+ if (attempts === 0) {
790
+ // Aborted before this unit's first call: it is still RECORDED — in the
791
+ // transcript and as a response — never silently missing.
792
+ const reason = String(c.signal.reason ?? PHASE_DEADLINE);
793
+ c.transcript?.call(`${unit.id}-stopped`, `${unitLabel(unit)} — not surveyed: ${reason}.`, args, ZERO_USAGE, reason, true);
794
+ log.warn("unit survey unit not started", { unitId: unit.id, reason });
795
+ return { record: failedRecord(unit, c, reason, 0, Date.now() - startedAt), calls: 0 };
796
+ }
797
+ const record = {
798
+ unitId: unit.id,
799
+ model: c.model,
800
+ systemPromptSha256: c.systemSha256,
801
+ requestSha256: contractSha,
802
+ ok,
803
+ cached: false,
804
+ attempts,
805
+ raw,
806
+ error,
807
+ usage,
808
+ durationMs: Date.now() - startedAt,
809
+ };
810
+ if (ok && c.cacheDir !== undefined) {
811
+ try {
812
+ writeAtomic(join(c.cacheDir, `${key}.json`), `${JSON.stringify(record)}\n`);
813
+ }
814
+ catch (err) {
815
+ // A cache that cannot be written costs the next re-review a call; it
816
+ // must never cost this one its answer.
817
+ log.warn("could not write the unit survey cache", { unitId: unit.id, err });
818
+ }
819
+ }
820
+ else if (!ok) {
821
+ log.warn("unit survey unit failed", { unitId: unit.id, attempts, error });
822
+ }
823
+ return { record, calls: attempts };
824
+ }
825
+ function failedRecord(unit, c, error, attempts, durationMs = 0) {
826
+ return {
827
+ unitId: unit.id,
828
+ model: c.model,
829
+ systemPromptSha256: c.systemSha256,
830
+ requestSha256: unit.requestSha256 ?? sha256(unit.request),
831
+ ok: false,
832
+ cached: false,
833
+ attempts,
834
+ raw: "",
835
+ error,
836
+ usage: { ...ZERO_USAGE },
837
+ durationMs,
838
+ };
839
+ }
840
+ /** The reasons a phase's AbortController fires with — also each unfinished unit's recorded error. */
841
+ const PHASE_DEADLINE = "phase deadline";
842
+ const RUN_CANCELLED = "run cancelled";
843
+ export class SurveyUnitsHandler {
844
+ run;
845
+ reporter;
846
+ constructor(run, reporter) {
847
+ this.run = run;
848
+ this.reporter = reporter;
849
+ }
850
+ async execute(phase, _node, _outputs) {
851
+ const phaseName = phase.name;
852
+ await this.reporter.onStart(phaseName);
853
+ await this.reporter.step(phaseName, "running", phase.messages?.on_start);
854
+ const { workflowName, taskId, triggerId, githubAccess, workflowId, backend } = this.run;
855
+ const model = this.resolveModel(phase);
856
+ const attrs = {
857
+ "workflow.name": workflowName,
858
+ "phase.name": phaseName,
859
+ "workflow.run_id": workflowId,
860
+ "trigger.id": triggerId,
861
+ "task.id": taskId,
862
+ repo: githubAccess.owner ? `${githubAccess.owner}/${githubAccess.repo}` : githubAccess.repo,
863
+ "sandbox.backend": backend,
864
+ model,
865
+ [OPENINFERENCE_SPAN_KIND]: OPENINFERENCE_CHAIN,
866
+ };
867
+ let pr;
868
+ try {
869
+ pr = await runLedgeredPhase(attrs, {
870
+ dedupKey: `${workflowName}:${phaseName}`,
871
+ phaseName,
872
+ taskId,
873
+ triggerId,
874
+ repo: githubAccess.repo,
875
+ owner: githubAccess.owner,
876
+ workflowRunId: workflowId,
877
+ }, { ...this.run.ledger, store: this.run.store }, (onSessionId) => this.survey(phase, model, onSessionId));
878
+ }
879
+ catch (err) {
880
+ // Only the LEDGER itself can land here — `survey` degrades every failure
881
+ // of its own. A store that cannot record the phase is not a survey
882
+ // outcome, so it stays red.
883
+ return this.fail(phase, err instanceof Error ? err.message : String(err));
884
+ }
885
+ if (pr.skipped) {
886
+ // The same two readings `runStandard` gives a dedup hit: another instance
887
+ // owns the row (stop, not a failure), or resume found it done.
888
+ if (pr.reason === "running") {
889
+ await this.reporter.message(phase.messages?.on_skipped_done);
890
+ return { results: [], status: "failed", aborted: true };
891
+ }
892
+ const result = { phase: phaseName, success: true, output: "Already completed" };
893
+ await this.reporter.persistPhase(phaseName, "Already completed (deduplicated)");
894
+ await this.reporter.onEnd(phaseName, result);
895
+ await this.reporter.step(phaseName, "done", phase.messages?.on_skipped_done);
896
+ return { results: [result], status: "succeeded" };
897
+ }
898
+ if (!pr.result.success)
899
+ return this.fail(phase, pr.result.error ?? "survey-units failed");
900
+ const output = pr.result.output ?? "";
901
+ const result = { phase: phaseName, success: true, output };
902
+ await this.reporter.persistPhase(phaseName, output.split("\n")[0]);
903
+ await this.reporter.onEnd(phaseName, result);
904
+ await this.reporter.step(phaseName, "done", phase.messages?.on_success);
905
+ const outputVars = { [phaseName]: output };
906
+ if (phase.output_var)
907
+ outputVars[phase.output_var] = output;
908
+ return { results: [result], status: "succeeded", outputVars };
909
+ }
910
+ /**
911
+ * The ledgered body — everything that spends, and the transcript that shows
912
+ * it. Returns an {@link ExecutionResult} whose cost and tokens are the sum of
913
+ * every call, which `runLedgeredPhase` copies onto the `executions` row.
914
+ *
915
+ * SUCCEEDS on every path (see the module header): a degraded survey is a
916
+ * loud summary on a green phase, never a red one.
917
+ */
918
+ async survey(phase, model, onSessionId) {
919
+ const startedAt = Date.now();
920
+ const repo = String(this.run.ctx.repo ?? this.run.githubAccess.repo);
921
+ const owner = String(this.run.ctx.owner ?? this.run.githubAccess.owner ?? "");
922
+ const hostRepoDir = resolveHostRepoDir(this.run.config, this.run.taskId, repo);
923
+ const prDir = join(hostRepoDir, PR_REVIEW_DIR);
924
+ let totals = { ...ZERO_USAGE };
925
+ let turns = 0;
926
+ let transcript;
927
+ /** Nothing (more) was surveyed: say why, loudly, and SUCCEED. */
928
+ const degrade = async (reason, opening = "") => {
929
+ const text = `SURVEY DEGRADED — ${reason}\n` +
930
+ "No survey reading exists for any unit not answered above. `units-ingest` records every obligation " +
931
+ "those units owned as unanswered (routed to a probe), so nothing here may be read as \"no findings\".";
932
+ log.warn("unit survey degraded", { phase: phase.name, reason });
933
+ if (!transcript) {
934
+ transcript = this.transcript(phase, model ?? "", hostRepoDir, (opening || reason).trim());
935
+ transcript.open();
936
+ onSessionId(transcript.sessionId);
937
+ }
938
+ transcript.say(text);
939
+ await transcript.close({ text, turns, usage: totals, durationMs: Date.now() - startedAt, stopReason: "success" });
940
+ return this.executionResult(text, turns, totals, startedAt, transcript.sessionId);
941
+ };
942
+ // A backend with no host checkout is refused at config load
943
+ // (`assertReviewAnalysisSupported`); this is the belt to that. It comes
944
+ // FIRST and touches nothing on disk: on kubernetes a `units.json` may even
945
+ // be readable (the artifact upload unpacks `.lastlight/` host-side), but a
946
+ // response written here would never reach the pod `units-ingest` runs in.
947
+ if (!HOST_READABLE_WORKSPACE[this.run.backend]) {
948
+ return degrade(`the ${this.run.backend} backend has no host checkout, so the harness cannot read units.json or write ` +
949
+ "the responses. `review.analysis.enabled` should have been refused at startup on this backend.");
950
+ }
951
+ let evict = new Set();
952
+ try {
953
+ // Read what the LAST run's ingest rejected before its evidence is
954
+ // cleared, then clear: a reused per-target workspace still holds the
955
+ // last head's responses, and any unit id this document no longer lists
956
+ // would be ingested as if it had been asked. Cleared on EVERY path below,
957
+ // degraded ones included — a stale response is worse than none.
958
+ evict = previousBadRequests(prDir, phase.name);
959
+ const responsesDir = join(prDir, RESPONSES_DIR);
960
+ rmSync(responsesDir, { recursive: true, force: true });
961
+ mkdirSync(responsesDir, { recursive: true });
962
+ }
963
+ catch (err) {
964
+ return degrade(`could not prepare ${join(prDir, RESPONSES_DIR)}: ${err instanceof Error ? err.message : String(err)}`);
965
+ }
966
+ if (!model) {
967
+ return degrade(`no model resolved for phase \`${phase.name}\` — set \`models.review-survey\` (or the phase's \`model:\`)`);
968
+ }
969
+ if (!phase.prompt)
970
+ return degrade(`phase \`${phase.name}\` has no \`prompt:\``);
971
+ let systemPrompt;
972
+ let doc;
973
+ let deadlineSeconds;
974
+ try {
975
+ systemPrompt = renderTemplate(this.run.assets.loadPromptTemplate(phase.prompt), this.run.ctx);
976
+ deadlineSeconds = this.deadlineSeconds(phase);
977
+ }
978
+ catch (err) {
979
+ return degrade(err instanceof Error ? err.message : String(err));
980
+ }
981
+ try {
982
+ doc = readUnitsDocument(join(prDir, UNITS_FILE));
983
+ }
984
+ catch (err) {
985
+ return degrade(err instanceof Error ? err.message : String(err), systemPrompt);
986
+ }
987
+ const units = doc.units;
988
+ const { sharedPrefix, splitPrefix } = unitSurveySystemText(systemPrompt, doc);
989
+ if (sharedPrefix && units.length > 0 && !splitPrefix) {
990
+ log.warn("units.json sharedPrefix is not the head of every request — sending each request verbatim", {
991
+ phase: phase.name,
992
+ });
993
+ }
994
+ transcript = this.transcript(phase, model, hostRepoDir, `${systemPrompt.trimEnd()}\n\n${manifest(units, doc, !!splitPrefix)}`);
995
+ transcript.open();
996
+ onSessionId(transcript.sessionId);
997
+ if (units.length === 0) {
998
+ const reasons = (doc.degraded ?? []).map((d) => d.reason).filter((r) => typeof r === "string" && r.length > 0);
999
+ if (doc.coverage === "none" || reasons.length > 0) {
1000
+ // The shell fallback's shape: `units` could not cut the PR at all. NOT
1001
+ // "there was nothing to survey".
1002
+ return degrade(`No units to survey — \`units.json\` lists none and its coverage is "${doc.coverage ?? "unknown"}"` +
1003
+ (reasons.length ? `: ${reasons.join("; ")}` : "") +
1004
+ ". No model call was made.");
1005
+ }
1006
+ const text = `No units to survey — \`units.json\` lists none (coverage: ${doc.coverage ?? "unknown"}). ` +
1007
+ "No model call was made; `units-ingest` reports what that means for each family.";
1008
+ transcript.say(text);
1009
+ await transcript.close({ text, turns: 0, usage: totals, durationMs: Date.now() - startedAt, stopReason: "success" });
1010
+ log.info("unit survey: nothing to survey", { phase: phase.name, coverage: doc.coverage });
1011
+ return this.executionResult(text, 0, totals, startedAt, transcript.sessionId);
1012
+ }
1013
+ // One controller over every call of the phase: the deadline, and a run
1014
+ // cancel noticed by polling the run row (the handler scope carries no
1015
+ // signal of its own; the scheduler checks the same row between phases).
1016
+ const controller = new AbortController();
1017
+ const deadlineAt = Date.now() + deadlineSeconds * 1000;
1018
+ const deadline = setTimeout(() => controller.abort(PHASE_DEADLINE), deadlineSeconds * 1000);
1019
+ deadline.unref?.();
1020
+ const stopCancelPoll = this.pollForCancel(controller);
1021
+ const t = transcript;
1022
+ try {
1023
+ const concurrency = this.concurrency();
1024
+ // Every unit settles inside the runner, so the pool always drains before
1025
+ // the transcript is finalized and nothing writes a line after the
1026
+ // `result`. Totals accumulate as units settle, so a degrade below still
1027
+ // reports what was spent.
1028
+ const { outcomes } = await runUnitSurvey({
1029
+ doc,
1030
+ systemPrompt,
1031
+ model,
1032
+ variant: this.resolveVariant(phase),
1033
+ concurrency,
1034
+ deadlineAt,
1035
+ signal: controller.signal,
1036
+ responsesDir: join(prDir, RESPONSES_DIR),
1037
+ cacheDir: unitCacheDir(this.run.config.stateDir || resolve("data"), owner, repo),
1038
+ evict,
1039
+ call: this.run.callUnit ?? completeUnitCall,
1040
+ transcript: t,
1041
+ onSettled: (o) => {
1042
+ totals = addUsage(totals, o.record.usage);
1043
+ turns += o.calls;
1044
+ },
1045
+ });
1046
+ const ok = outcomes.filter((o) => o.record.ok).length;
1047
+ const cached = outcomes.filter((o) => o.record.cached).length;
1048
+ const failedUnits = outcomes.filter((o) => !o.record.ok);
1049
+ const stopped = controller.signal.aborted ? String(controller.signal.reason) : undefined;
1050
+ const head = `Surveyed ${units.length} unit(s): ${ok} ok, ${failedUnits.length} failed, ${cached} from cache — ` +
1051
+ `${turns} model call(s), $${totals.costUsd.toFixed(4)}.`;
1052
+ const failures = failedUnits.length
1053
+ ? `\nFailed: ${failedUnits.map((o) => `${o.record.unitId} (${o.record.error ?? "unknown"})`).join(", ")}. ` +
1054
+ "`units-ingest` records every obligation those units owned as unanswered — never dropped."
1055
+ : "";
1056
+ const summary = ok === 0
1057
+ ? `SURVEY DEGRADED — EVERY one of ${units.length} unit(s) failed (first error: ${failedUnits[0]?.record.error ?? "unknown"}). ` +
1058
+ "This looks like a bad key, an unknown model or a provider outage, not a thin survey.\n" +
1059
+ head +
1060
+ failures
1061
+ : `${stopped ? `SURVEY STOPPED EARLY (${stopped}). ` : ""}${head}${failures}`;
1062
+ transcript.say(summary);
1063
+ await transcript.close({ text: summary, turns, usage: totals, durationMs: Date.now() - startedAt, stopReason: "success" });
1064
+ const fields = {
1065
+ phase: phase.name,
1066
+ units: units.length,
1067
+ ok,
1068
+ failed: failedUnits.length,
1069
+ cached,
1070
+ calls: turns,
1071
+ costUsd: totals.costUsd,
1072
+ concurrency,
1073
+ stopped,
1074
+ durationMs: Date.now() - startedAt,
1075
+ };
1076
+ if (ok === 0 || stopped)
1077
+ log.warn("unit survey finished degraded", fields);
1078
+ else
1079
+ log.info("unit survey finished", fields);
1080
+ return this.executionResult(summary, turns, totals, startedAt, transcript.sessionId);
1081
+ }
1082
+ catch (err) {
1083
+ return degrade(err instanceof Error ? err.message : String(err));
1084
+ }
1085
+ finally {
1086
+ clearTimeout(deadline);
1087
+ stopCancelPoll();
1088
+ }
1089
+ }
1090
+ // ── Helpers ────────────────────────────────────────────────────────────────
1091
+ /**
1092
+ * Abort `controller` when the run row turns `cancelled`. The admin cancel
1093
+ * only flips the row (and kills sandbox containers — this phase has none),
1094
+ * so polling it is the only way an in-process phase hears of it. Returns
1095
+ * the stopper. Best-effort: a store error stops nothing.
1096
+ */
1097
+ pollForCancel(controller) {
1098
+ const { store, workflowId } = this.run;
1099
+ if (!store || !workflowId)
1100
+ return () => { };
1101
+ const timer = setInterval(() => {
1102
+ void store.runs
1103
+ .getRun(workflowId)
1104
+ .then((run) => {
1105
+ if (run?.status === "cancelled" && !controller.signal.aborted)
1106
+ controller.abort(RUN_CANCELLED);
1107
+ })
1108
+ .catch((err) => log.debug("unit survey: cancel poll failed", { err }));
1109
+ }, this.run.cancelPollMs ?? 5000);
1110
+ timer.unref?.();
1111
+ return () => clearInterval(timer);
1112
+ }
1113
+ transcript(phase, model, hostRepoDir, initialPrompt) {
1114
+ // The checkout's own slug, as the phase's bash siblings use on `none`.
1115
+ // Never the chat slug: SessionReader's sandbox scope excludes it outright.
1116
+ const slug = projectSlugForCwd(hostRepoDir);
1117
+ return new UnitSurveyTranscript({
1118
+ sessionsDir: resolveSessionsDir(this.run.config),
1119
+ projectSlug: slug === CHAT_PROJECT_SLUG ? `${slug}-survey-units` : slug,
1120
+ model,
1121
+ phase: phase.name,
1122
+ initialPrompt,
1123
+ });
1124
+ }
1125
+ /** Always a SUCCESS — every outcome of the survey itself degrades, never fails. */
1126
+ executionResult(output, turns, usage, startedAt, sessionId) {
1127
+ return {
1128
+ success: true,
1129
+ output,
1130
+ turns,
1131
+ durationMs: Date.now() - startedAt,
1132
+ sessionId,
1133
+ costUsd: usage.costUsd,
1134
+ inputTokens: usage.input,
1135
+ outputTokens: usage.output,
1136
+ cacheReadInputTokens: usage.cacheRead,
1137
+ cacheCreationInputTokens: usage.cacheWrite,
1138
+ stopReason: "success",
1139
+ };
1140
+ }
1141
+ /** YAML template first, then the resolver — `fanout.ts`'s precedence. */
1142
+ resolveModel(phase) {
1143
+ const rendered = phase.model ? renderTemplate(phase.model, this.run.ctx) : "";
1144
+ return rendered || this.run.resolver.modelFor(phase.name) || undefined;
1145
+ }
1146
+ /** The thinking level, resolved exactly as an agent phase's `variant:` is. */
1147
+ resolveVariant(phase) {
1148
+ const rendered = phase.variant ? renderTemplate(phase.variant, this.run.ctx).trim() : "";
1149
+ return rendered || this.run.resolver.variantFor(phase.name) || undefined;
1150
+ }
1151
+ /**
1152
+ * The WHOLE-PHASE deadline, in seconds: the phase's `timeout_seconds`
1153
+ * (`{ from: surveyUnitsTimeoutSeconds }` in the packaged YAML), else the
1154
+ * run's agent limit (`timeouts.agentSeconds`) — a config key, never a
1155
+ * literal (issue #385).
1156
+ */
1157
+ deadlineSeconds(phase) {
1158
+ const seconds = resolveTemplatedNumber(phase.timeout_seconds ?? { from: "timeouts.agentSeconds" }, this.run.ctx, `${phase.name}.timeout_seconds (the whole-phase deadline)`, this.run.ledger.logger);
1159
+ if (seconds === undefined)
1160
+ throw new Error(`${phase.name}: the phase deadline did not resolve`);
1161
+ return seconds;
1162
+ }
1163
+ /** `surveyUnitConcurrency` off the run context, else the shipped default. */
1164
+ concurrency() {
1165
+ const raw = Number(this.run.ctx.surveyUnitConcurrency);
1166
+ const n = Number.isFinite(raw) && raw > 0 ? Math.floor(raw) : defaultReviewPolicy().analysis.surveyUnitConcurrency;
1167
+ return Math.max(1, n);
1168
+ }
1169
+ async fail(phase, error) {
1170
+ const result = { phase: phase.name, success: false, output: "", error };
1171
+ await this.reporter.onEnd(phase.name, result);
1172
+ await this.reporter.step(phase.name, "failed", phase.messages?.on_failure);
1173
+ // A failed entry so the dashboard pipeline renders this node red —
1174
+ // `persistPhase` only writes success entries (post-review's reasoning).
1175
+ if (this.run.store && this.run.workflowId) {
1176
+ await this.run.store.runs.appendPhase(this.run.workflowId, phase.name, {
1177
+ phase: phase.name,
1178
+ timestamp: new Date().toISOString(),
1179
+ success: false,
1180
+ summary: error,
1181
+ });
1182
+ }
1183
+ return { results: [result], status: "failed" };
1184
+ }
1185
+ }
1186
+ /**
1187
+ * Bounded, order-preserving concurrent map — results land at their input
1188
+ * index however the pool interleaves. `fn` must not throw (the caller settles
1189
+ * each unit itself), so every worker runs to the end of the list and the pool
1190
+ * resolves only once every item has. (`fanout.ts` has the same helper; each
1191
+ * handler keeps its own so neither imports the other's module.)
1192
+ */
1193
+ async function mapPool(items, limit, fn) {
1194
+ const out = new Array(items.length);
1195
+ let next = 0;
1196
+ const worker = async () => {
1197
+ for (;;) {
1198
+ const i = next++;
1199
+ if (i >= items.length)
1200
+ return;
1201
+ out[i] = await fn(items[i], i);
1202
+ }
1203
+ };
1204
+ await Promise.all(Array.from({ length: Math.max(1, Math.min(limit, items.length)) }, worker));
1205
+ return out;
1206
+ }
1207
+ /** Build the app-registered `survey-units` phase-type handler for a run. */
1208
+ export function makeSurveyUnitsHandler(run, reporter) {
1209
+ return new SurveyUnitsHandler(run, reporter);
1210
+ }
1211
+ //# sourceMappingURL=survey-units.js.map