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
@@ -0,0 +1,663 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { readFileSync } from "node:fs";
3
+ import { isAbsolute, join } from "node:path";
4
+ import { PhaseRef, buildPhasePrompt, isSoftOutcome, phaseConfigFor, renderTemplate, resolveTemplatedNumber, runLedgeredPhase, validateShellCommand, OPENINFERENCE_CHAIN, OPENINFERENCE_SPAN_KIND, } from "lastlight-workflow-engine";
5
+ import { withAgentSession } from "../../engine/agent-executor.js";
6
+ import { safeSpanAttributes, withSpan } from "../../telemetry/index.js";
7
+ import { OI, SpanKind, splitProviderModel } from "../../telemetry/openinference.js";
8
+ import { logger } from "../../logging/logger.js";
9
+ const log = logger("fanout");
10
+ /**
11
+ * How many agent sessions a backend may have in flight against ONE provisioned
12
+ * workspace.
13
+ *
14
+ * This is the safety valve, and the asymmetry in it is the whole point.
15
+ *
16
+ * - **`none`** runs agentic-pi in the harness process. `InProcessSandbox.runAgent`
17
+ * holds no per-call mutable state — every per-run value (`githubAuthEnv`,
18
+ * `authFile`, `sandboxEnv`, `cwd`, `allowedHttpHosts`) travels as an explicit
19
+ * argument, and issue #215 made that true *precisely because* concurrent
20
+ * in-process runs share `process.env`. So N concurrent turns are safe, and
21
+ * this is the backend the eval harness uses.
22
+ * - **`docker`** is N `docker exec`s into the one container the phase already
23
+ * provisioned.
24
+ * - **`gondolin`** boots a QEMU micro-VM per agent session, inside the harness
25
+ * process. That is WP5's D7 exactly, and the nearform host has no swap, a
26
+ * hard agent memory cap, and has wedged under memory pressure before.
27
+ * - **`smol` / `kubernetes`** are simply unverified for concurrent turns.
28
+ *
29
+ * The last three clamp to 1, which runs the branches sequentially — byte-identical
30
+ * to the chained phases this replaced. That costs nothing today: the review
31
+ * evidence pipeline cannot run in production at all until `lastlight-facts` is
32
+ * in the sandbox image (WP2), and until then the only thing that fans out is the
33
+ * eval harness on `none`.
34
+ */
35
+ const BACKEND_MAX_CONCURRENT = {
36
+ none: 6,
37
+ docker: 6,
38
+ gondolin: 1,
39
+ smol: 1,
40
+ kubernetes: 1,
41
+ };
42
+ /** Absent `on_branch_soft_failure` ⇒ no retry, and one soft branch never fails the phase. */
43
+ const DEFAULT_BRANCH_SOFT_POLICY = { retries: 0, then: "complete" };
44
+ /**
45
+ * The heading the appended {@link FanoutBranch.context_file} is filed under. A
46
+ * constant rather than a literal at the call site because two tests and one
47
+ * prompt-authoring convention all name it.
48
+ */
49
+ export const BRANCH_CONTEXT_HEADING = "## Attached: the file this pass was seeded with";
50
+ /**
51
+ * Backends whose workspace the HARNESS can read.
52
+ *
53
+ * Every backend but one hands out a `hostAgentCwd` that exists on this machine —
54
+ * docker and smol as the host end of a bind mount, the two in-process backends
55
+ * because the agent IS this process. **`kubernetes` does not**: its paths are
56
+ * in-pod, which is the same caveat `hostWorkspaceDir` already carries there
57
+ * (`deliverAgentContext` routes around it through a sink for exactly this
58
+ * reason).
59
+ *
60
+ * So a `context_file` read is not even ATTEMPTED there, and the branch is given
61
+ * the path to open itself — today's behaviour, unchanged. Attempting it would
62
+ * ENOENT every time and turn "the harness cannot see this workspace" into "the
63
+ * seeding step failed", which is a worse lie than the one this key removes.
64
+ */
65
+ const HOST_READABLE_WORKSPACE = {
66
+ none: true,
67
+ docker: true,
68
+ gondolin: true,
69
+ smol: true,
70
+ kubernetes: false,
71
+ };
72
+ /**
73
+ * What a branch is told when the harness cannot read its workspace at all.
74
+ *
75
+ * The path goes back in the prompt, because on that backend it is the only
76
+ * channel there is — but it goes in with the trap named. 27 of 133 measured
77
+ * reads went to the workspace root; the model has no way to know that is wrong
78
+ * unless it is told, and a bare path in a fenced block is what it was told
79
+ * before.
80
+ */
81
+ function branchContextPointer(relPath) {
82
+ return [
83
+ BRANCH_CONTEXT_HEADING,
84
+ "",
85
+ `This backend's workspace is not readable from the harness, so the file could not be`,
86
+ "attached. Open it yourself, **relative to your working directory**:",
87
+ "",
88
+ "```",
89
+ relPath,
90
+ "```",
91
+ "",
92
+ "Read it RELATIVE, exactly as written. Do not build an absolute path from the",
93
+ "directory your skills came from — the skill bundle is a sibling of your working",
94
+ "directory, one level up, and joining this path onto it resolves to a file that does",
95
+ "not exist. If the read fails, that is a path error and not a clean family: say so,",
96
+ "and do not report an absence you were never in a position to observe.",
97
+ "",
98
+ ].join("\n");
99
+ }
100
+ /**
101
+ * Read a branch's `context_file` and return the text to APPEND to its prompt.
102
+ *
103
+ * **Why the harness reads it instead of the model.** See
104
+ * `FanoutBranchSchema.context_file` for the measurement. In one sentence: the
105
+ * model is handed absolute skill paths rooted at the workspace ROOT and a
106
+ * relative artifact path rooted at the CHECKOUT, and on ~22% of branches it
107
+ * resolved the second against the first and got ENOENT. Neither path is wrong;
108
+ * having two bases is. Reading it here collapses them to one — the same
109
+ * `hostAgentCwd` a `type: bash` phase's shell ran in, so the phase that WROTE
110
+ * the file and the branch that CONSUMES it cannot disagree about where it is.
111
+ *
112
+ * **Two outcomes, and they are never confused.** Bytes, or a loud notice naming
113
+ * the path and saying in words that nothing was read. `null` (nobody looked)
114
+ * must never render as `[]` (looked, found none) — that is this package's
115
+ * founding invariant, and a branch that silently falls back to free-styling off
116
+ * the diff is precisely that invariant broken.
117
+ */
118
+ function branchContextSection(hostAgentCwd, relPath) {
119
+ // Workspace-relative only. An absolute path or a `..` escape would resolve
120
+ // against something the workflow author did not name, which is the failure
121
+ // this key exists to remove rather than relocate.
122
+ const unsafe = isAbsolute(relPath) || relPath.split(/[\\/]/).includes("..");
123
+ const abs = unsafe ? "" : join(hostAgentCwd, relPath);
124
+ let body;
125
+ let reason;
126
+ if (unsafe) {
127
+ reason = `\`${relPath}\` is not a workspace-relative path`;
128
+ }
129
+ else {
130
+ try {
131
+ body = readFileSync(abs, "utf8");
132
+ }
133
+ catch (err) {
134
+ reason = err instanceof Error ? err.message : String(err);
135
+ }
136
+ }
137
+ if (body !== undefined && body.trim().length > 0) {
138
+ return {
139
+ ok: true,
140
+ text: [
141
+ BRANCH_CONTEXT_HEADING,
142
+ "",
143
+ `The contents of \`${relPath}\` are reproduced below **verbatim**. It has`,
144
+ "already been read for you — do not open it, and do not construct a path to it.",
145
+ "",
146
+ body.trimEnd(),
147
+ "",
148
+ ].join("\n"),
149
+ };
150
+ }
151
+ // The empty-file case is folded in with the unreadable one on purpose: a
152
+ // zero-byte artifact is not a measurement either, and the seeder never writes
153
+ // one (`renderFamilyBlock` always emits a block, including a NOT MEASURED one).
154
+ return {
155
+ ok: false,
156
+ reason: reason ?? "the file was empty",
157
+ text: [
158
+ BRANCH_CONTEXT_HEADING,
159
+ "",
160
+ `**NOT AVAILABLE.** \`${relPath}\` could not be read by the harness` +
161
+ (reason ? ` (${reason})` : "") +
162
+ ".",
163
+ "",
164
+ "This is a HARNESS failure, not a finding. The deterministic layer is supposed to",
165
+ "write this file before this pass runs, and it always writes one — including when it",
166
+ "has nothing to say, in which case the file says so in those words. So its absence",
167
+ "means the seeding step did not run or did not survive, NOT that there is nothing to",
168
+ "check on this axis.",
169
+ "",
170
+ "Record that fact FIRST, as the first line of your output file:",
171
+ "",
172
+ ' {"status": "NOT_SEEDED", "claim": "the obligations file was not delivered to this pass"}',
173
+ "",
174
+ "`NOT_SEEDED` and `NOT_MEASURED` are DIFFERENT facts and must not be swapped: the",
175
+ "second says the deterministic layer looked and could not measure this axis, the first",
176
+ "says its answer never reached you. Then work the diff for this family's question",
177
+ "directly, and say in your summary that you did so unseeded. Nothing downstream may",
178
+ "read this pass as evidence that this family is clean.",
179
+ "",
180
+ ].join("\n"),
181
+ };
182
+ }
183
+ /**
184
+ * Bounded, order-preserving concurrent map. Results land at their input index
185
+ * however the pool interleaves, so `branches[i]` always pairs with `out[i]` —
186
+ * a fan-out that reported its families in completion order would make two runs
187
+ * of the same case diff against each other for no reason.
188
+ */
189
+ async function mapPool(items, limit, fn) {
190
+ const out = new Array(items.length);
191
+ let next = 0;
192
+ const worker = async () => {
193
+ for (;;) {
194
+ const i = next++;
195
+ if (i >= items.length)
196
+ return;
197
+ out[i] = await fn(items[i], i);
198
+ }
199
+ };
200
+ await Promise.all(Array.from({ length: Math.max(1, Math.min(limit, items.length)) }, worker));
201
+ return out;
202
+ }
203
+ /**
204
+ * The `type: fanout` phase — N agent sessions run CONCURRENTLY inside ONE
205
+ * provisioned workspace, as a single DAG node.
206
+ *
207
+ * **Why this exists rather than parallel phases.** Real DAG concurrency is
208
+ * parked (`docs/plans/deterministic-pr-levers.md` §WP5) behind
209
+ * four hard blockers and seven design changes, and that document says why in one
210
+ * sentence: *"Every hard blocker below — B1, D1, D2, D7 — exists because each
211
+ * phase provisions its own sandbox against a shared workspace. A fan-out inside
212
+ * one agent has none of them."* One node means one workspace (B1), one
213
+ * `current_phase` (B4), one terminal transition (D5), one provisioning pass so
214
+ * no `ensureBaseAvailable` git-lock contention (D1/D2), one artifact
215
+ * stage/harvest (D3), and one `outputs` writer (D4). B2 — a sibling's success
216
+ * overwriting a `paused` run and orphaning its approval row, the item that doc
217
+ * calls the worst in the list — is refused at the schema instead: a fanout phase
218
+ * may not declare an approval gate.
219
+ *
220
+ * **What it gives up, and buys back.** A DAG node per branch is genuinely lost:
221
+ * six survey families are one node now, retried as one. What is NOT lost is the
222
+ * per-branch `executions` row — each branch goes through the same
223
+ * {@link runLedgeredPhase} every other phase does, keyed
224
+ * `<phase>_branch_<name>`, so resume, dedup, cost attribution and the
225
+ * dashboard's longest-prefix grouping all keep working. WP5
226
+ * (`docs/plans/deterministic-pr-levers.md` §"Parked: parallel phases (WP5)")
227
+ * listed exactly those as the price of an in-agent fan-out; the ledger key is
228
+ * how it goes unpaid.
229
+ */
230
+ export class FanoutHandler {
231
+ run;
232
+ reporter;
233
+ constructor(run, reporter) {
234
+ this.run = run;
235
+ this.reporter = reporter;
236
+ }
237
+ async execute(phase, _node, outputs) {
238
+ const phaseName = phase.name;
239
+ const branches = phase.branches ?? [];
240
+ await this.reporter.onStart(phaseName);
241
+ await this.reporter.step(phaseName, "running", phase.messages?.on_start);
242
+ const concurrency = this.resolveConcurrency(phase, branches.length);
243
+ const policy = phase.on_branch_soft_failure ?? DEFAULT_BRANCH_SOFT_POLICY;
244
+ let outcomes;
245
+ try {
246
+ outcomes = await withAgentSession(this.phaseConfig(phase), {
247
+ taskId: this.run.taskId,
248
+ githubAccess: this.run.githubAccess,
249
+ sandboxFactory: this.run.sandboxFactory,
250
+ }, async (session) => {
251
+ const ran = await mapPool(branches, concurrency, (branch) => this.runBranch(session, phase, branch, outputs, policy));
252
+ // Gates run AFTER the join, and SEQUENTIALLY. `InProcessSandbox.runCommand`
253
+ // is a `spawnSync` — it blocks the event loop — so interleaving a gate
254
+ // with the agent turns would serialise the whole fan-out on the very
255
+ // backend (`none`) the fan-out exists to speed up.
256
+ for (const outcome of ran) {
257
+ if (outcome.deduped)
258
+ continue;
259
+ await this.runBranchGate(session, phase, outcome);
260
+ }
261
+ return ran;
262
+ });
263
+ }
264
+ catch (err) {
265
+ // A provisioning failure, or a mint that could not happen. One error for
266
+ // the whole fan-out, because there was one workspace to fail.
267
+ this.run.observeError(err);
268
+ }
269
+ return this.report(phase, outcomes, policy);
270
+ }
271
+ // ── Branches ───────────────────────────────────────────────────────────────
272
+ /**
273
+ * Run one branch, with the one-shot soft retry `on_branch_soft_failure`
274
+ * describes. A HARD failure (terminated / fatal / tool error / non-zero exit)
275
+ * is never retried — that is `isSoftOutcome`'s split, shared with the reviewer
276
+ * and generic loops so all three stay in lockstep.
277
+ */
278
+ async runBranch(session, phase, branch, outputs, policy) {
279
+ const label = PhaseRef.branch(phase.name, branch.name).format();
280
+ // A branch opens and closes its OWN phase window, exactly as
281
+ // `PhaseExecutor.runStandard` does for a phase. Both hooks are pass-throughs
282
+ // to the caller's `onPhaseStart`/`onPhaseEnd` (`runner.ts`), no-ops when a
283
+ // caller supplies none — so this is inert in production and is the only
284
+ // signal an external consumer has that a branch ran at all. Without it the
285
+ // evals harness measured the parent window, found no row to hang it on, and
286
+ // silently dropped 61% of a case's cost on the floor.
287
+ //
288
+ // `finally`, because a window this side opened must not be left open by a
289
+ // throw: the consumer's rule for an unclosed window is indistinguishable
290
+ // from "never started".
291
+ await this.reporter.onStart(label);
292
+ let outcome;
293
+ try {
294
+ outcome = await this.runBranchAttempts(session, phase, branch, label, outputs, policy);
295
+ return outcome;
296
+ }
297
+ finally {
298
+ await this.reporter.onEnd(label, outcome
299
+ ? {
300
+ phase: label,
301
+ success: outcome.result.success,
302
+ output: outcome.result.output ?? "",
303
+ error: outcome.result.success ? undefined : outcome.result.error,
304
+ }
305
+ : { phase: label, success: false, output: "", error: "fan-out branch threw" });
306
+ }
307
+ }
308
+ /** The attempt loop — one branch's agent turn plus its one-shot soft retry. */
309
+ async runBranchAttempts(session, phase, branch, label, outputs, policy) {
310
+ const rendered = buildPhasePrompt(this.branchPhase(phase, branch, label), this.run.ctx, this.run.assets, {
311
+ phaseOutputs: outputs,
312
+ });
313
+ const prompt = this.withBranchContext(session, phase, branch, rendered);
314
+ let attempt = 0;
315
+ for (;;) {
316
+ const attemptLabel = attempt === 0 ? label : PhaseRef.branchRetry(phase.name, branch.name).format();
317
+ const pr = await this.runBranchOnce(session, phase, branch, attemptLabel, prompt);
318
+ if (pr.skipped) {
319
+ // `running` (another instance owns this row) and `done` (resume) both
320
+ // mean "not ours to do". A fan-out cannot abort the run the way a
321
+ // standard phase does — its five siblings are mid-flight — so both are
322
+ // reported as a non-failing no-op and the phase carries on.
323
+ return {
324
+ branch,
325
+ label,
326
+ deduped: true,
327
+ result: { success: true, output: "", turns: 0, durationMs: 0 },
328
+ };
329
+ }
330
+ const result = this.run.observeResult(pr.result);
331
+ const soft = !result.success && isSoftOutcome(result);
332
+ if (!soft || attempt >= policy.retries)
333
+ return { branch, label, result, deduped: false };
334
+ log.info("fan-out branch came back soft — retrying once", {
335
+ phase: phase.name,
336
+ branch: branch.name,
337
+ stopReason: result.stopReason,
338
+ });
339
+ attempt += 1;
340
+ }
341
+ }
342
+ /**
343
+ * Append the branch's `context_file` to its rendered prompt, if it declares
344
+ * one.
345
+ *
346
+ * **LAST in the prompt, and that is §D4's ordering rather than convenience.**
347
+ * Provider-side prompt caching is keyed on the request PREFIX, so the shared
348
+ * head (skills, AGENTS.md, the diff summary) has to stay byte-identical across
349
+ * the six branches and everything family-specific has to come after it. The
350
+ * attached file is the most family-specific thing there is.
351
+ *
352
+ * Whether the read succeeded is LOGGED either way. A lost seed used to be
353
+ * invisible from outside the transcript — it is now one grep on the harness
354
+ * log, which is what turned a 22%-of-branches defect into something anybody
355
+ * could have found in a minute.
356
+ */
357
+ withBranchContext(session, phase, branch, prompt) {
358
+ const relPath = branch.context_file?.trim();
359
+ if (!relPath)
360
+ return prompt;
361
+ if (!HOST_READABLE_WORKSPACE[this.run.backend]) {
362
+ log.info("backend has no host-readable workspace — the branch is given the path instead", {
363
+ phase: phase.name,
364
+ branch: branch.name,
365
+ backend: this.run.backend,
366
+ path: relPath,
367
+ });
368
+ return `${prompt.trimEnd()}\n\n${branchContextPointer(relPath)}`;
369
+ }
370
+ const section = branchContextSection(session.hostAgentCwd, relPath);
371
+ if (section.ok) {
372
+ log.debug("attached a fan-out branch's context file", {
373
+ phase: phase.name,
374
+ branch: branch.name,
375
+ path: relPath,
376
+ });
377
+ }
378
+ else {
379
+ // `warn`, not `info`: on every workflow that declares `context_file` this
380
+ // is a deterministic phase's artifact failing to reach the pass that was
381
+ // built to consume it, and the pass will still run.
382
+ log.warn("fan-out branch context file could not be read — the pass runs UNSEEDED", {
383
+ phase: phase.name,
384
+ branch: branch.name,
385
+ path: relPath,
386
+ hostAgentCwd: session.hostAgentCwd,
387
+ reason: section.reason,
388
+ });
389
+ }
390
+ return `${prompt.trimEnd()}\n\n${section.text}`;
391
+ }
392
+ /** One ledgered agent turn for a branch, under its own AGENT span. */
393
+ async runBranchOnce(session, phase, branch, label, prompt) {
394
+ const { workflowName, taskId, triggerId, githubAccess, workflowId, backend } = this.run;
395
+ const config = this.branchConfig(phase, branch, label);
396
+ const model = config.model;
397
+ const attrs = {
398
+ "workflow.name": workflowName,
399
+ "phase.name": label,
400
+ "workflow.run_id": workflowId,
401
+ "trigger.id": triggerId,
402
+ "task.id": taskId,
403
+ repo: githubAccess.owner ? `${githubAccess.owner}/${githubAccess.repo}` : githubAccess.repo,
404
+ "sandbox.backend": backend,
405
+ "fanout.parent": phase.name,
406
+ "fanout.branch": branch.name,
407
+ model,
408
+ [OPENINFERENCE_SPAN_KIND]: OPENINFERENCE_CHAIN,
409
+ };
410
+ return runLedgeredPhase(attrs, {
411
+ dedupKey: `${workflowName}:${label}`,
412
+ phaseName: label,
413
+ taskId,
414
+ triggerId,
415
+ repo: githubAccess.repo,
416
+ owner: githubAccess.owner,
417
+ workflowRunId: workflowId,
418
+ }, { ...this.run.ledger, store: this.run.store }, (onSessionId) => {
419
+ const { system, modelName } = splitProviderModel(model ?? "");
420
+ const spanAttrs = safeSpanAttributes({
421
+ "agent.runtime": "agentic-pi",
422
+ "sandbox.backend": backend,
423
+ "task.id": taskId,
424
+ repo: githubAccess.repo,
425
+ "github.profile": githubAccess.profile,
426
+ model,
427
+ variant: config.variant,
428
+ "fanout.parent": phase.name,
429
+ "fanout.branch": branch.name,
430
+ "workflow.name": workflowName,
431
+ "phase.name": label,
432
+ [OI.SPAN_KIND]: SpanKind.AGENT,
433
+ ...(modelName ? { [OI.LLM_MODEL_NAME]: modelName } : {}),
434
+ ...(system ? { [OI.LLM_SYSTEM]: system } : {}),
435
+ });
436
+ // The AGENT span is opened per branch and nests under the phase span
437
+ // `runLedgeredPhase` just opened. `withSpan` runs on the OTel
438
+ // AsyncLocalStorage context manager and `AgentSpanTree` snapshots its
439
+ // parent in the constructor, so concurrent branches do not mis-parent
440
+ // each other's turn/tool spans.
441
+ return withSpan("lastlight.agent.execute", spanAttrs, (span) => session.runAgent(prompt, config, { onSessionId, span }));
442
+ });
443
+ }
444
+ /**
445
+ * A branch's `until_bash`, recorded as its own `<phase>_branch_<name>_check`
446
+ * row.
447
+ *
448
+ * Observational, and that is not a weakening — it is what the six chained
449
+ * survey phases already did. Each declared `generic_loop: { max_iterations: 1,
450
+ * until_bash: … }`, and with one iteration the gate can never cause a re-run:
451
+ * it runs once, records `condition_met` / `condition_not_met`, and the loop
452
+ * ends either way. Reproducing that exactly is what makes this a speed change
453
+ * rather than a behaviour change.
454
+ *
455
+ * Like the generic loop's check row it bypasses the dedup ledger: a condition
456
+ * must be re-evaluated every time it is asked, and `success` records whether
457
+ * the check RAN, not what it said.
458
+ */
459
+ async runBranchGate(session, phase, outcome) {
460
+ const command = outcome.branch.until_bash?.trim();
461
+ if (!command)
462
+ return;
463
+ const { workflowName, triggerId, githubAccess, workflowId, store: db } = this.run;
464
+ const label = PhaseRef.branchCheck(phase.name, outcome.branch.name).format();
465
+ const startedAt = Date.now();
466
+ const executionId = db ? randomUUID() : undefined;
467
+ if (db && executionId) {
468
+ try {
469
+ await db.executions.recordStart({
470
+ id: executionId,
471
+ triggerType: "webhook",
472
+ triggerId,
473
+ skill: `${workflowName}:${label}`,
474
+ owner: githubAccess.owner,
475
+ repo: githubAccess.repo,
476
+ startedAt: new Date(startedAt).toISOString(),
477
+ workflowRunId: workflowId,
478
+ });
479
+ }
480
+ catch (err) {
481
+ log.warn("Failed to record fan-out branch check row", { label, err });
482
+ }
483
+ }
484
+ let met = false;
485
+ let error;
486
+ try {
487
+ validateShellCommand(command);
488
+ const res = await session.runCommand({ kind: "bash", command }, this.branchConfig(phase, outcome.branch, label), { timeoutSeconds: this.gateTimeoutSeconds(phase, outcome.branch), writeSession: false });
489
+ met = res.success;
490
+ }
491
+ catch (err) {
492
+ error = err instanceof Error ? err.message : String(err);
493
+ }
494
+ if (!met) {
495
+ log.info("fan-out branch gate did not close", {
496
+ phase: phase.name,
497
+ branch: outcome.branch.name,
498
+ error,
499
+ });
500
+ }
501
+ if (db && executionId) {
502
+ try {
503
+ await db.executions.recordFinish(executionId, {
504
+ success: error === undefined,
505
+ error,
506
+ turns: 0,
507
+ durationMs: Date.now() - startedAt,
508
+ stopReason: error !== undefined ? "error_fatal" : met ? "condition_met" : "condition_not_met",
509
+ });
510
+ }
511
+ catch (err) {
512
+ log.warn("Failed to finish fan-out branch check row", { label, err });
513
+ }
514
+ }
515
+ }
516
+ // ── Reporting ──────────────────────────────────────────────────────────────
517
+ /**
518
+ * Fold the branches into one node outcome.
519
+ *
520
+ * `then: "complete"` (the default) is what makes a fan-out a fan-out: it
521
+ * gathers independent evidence, so one branch coming back empty must not
522
+ * discard the other five. The six survey phases already had this — a chained
523
+ * phase with `on_soft_failure: { retries: 1, then: complete }` — and it was
524
+ * worth having: without it a single degenerate turn hard-failed the run, which
525
+ * records no `assessedHeadShaByWorkflow` and hands `cron-review.yaml` something
526
+ * to re-dispatch every thirty minutes forever.
527
+ *
528
+ * A HARD branch failure still fails the phase. That is not the soft policy's
529
+ * business, and a fan-out where every branch crashed is not a success.
530
+ */
531
+ async report(phase, outcomes, policy) {
532
+ const results = outcomes.map((o) => ({
533
+ phase: o.label,
534
+ success: o.result.success || (isSoftOutcome(o.result) && policy.then === "complete"),
535
+ output: o.result.output ?? "",
536
+ error: o.result.success ? undefined : o.result.error,
537
+ }));
538
+ const failed = results.filter((r) => !r.success);
539
+ const succeeded = results.length - failed.length;
540
+ const summary = `${succeeded}/${results.length} branches` +
541
+ (failed.length ? ` (failed: ${failed.map((r) => r.phase).join(", ")})` : "");
542
+ // Every branch's output is addressable downstream under its own label, and
543
+ // the phase's own key carries the joined text so `{{phaseOutputs.<phase>}}`
544
+ // and an `output_var` keep meaning something.
545
+ const outputVars = {};
546
+ for (const o of outcomes)
547
+ outputVars[o.label] = o.result.output ?? "";
548
+ const joined = outcomes.map((o) => o.result.output ?? "").join("\n\n");
549
+ outputVars[phase.name] = joined;
550
+ if (phase.output_var)
551
+ outputVars[phase.output_var] = joined;
552
+ if (failed.length === results.length && results.length > 0) {
553
+ const error = `every fan-out branch failed: ${failed.map((r) => r.error ?? r.phase).join("; ")}`;
554
+ await this.reporter.onEnd(phase.name, { phase: phase.name, success: false, output: "", error });
555
+ await this.reporter.step(phase.name, "failed", phase.messages?.on_failure);
556
+ return { results, status: "failed", outputVars };
557
+ }
558
+ await this.reporter.persistPhase(phase.name, summary);
559
+ await this.reporter.onEnd(phase.name, { phase: phase.name, success: true, output: joined });
560
+ await this.reporter.step(phase.name, "done", phase.messages?.on_success);
561
+ return { results, status: "succeeded", outputVars };
562
+ }
563
+ // ── Resolution helpers ─────────────────────────────────────────────────────
564
+ /**
565
+ * `min(declared, backend ceiling)`, logged when the host has the last word so
566
+ * an operator who set `max_concurrent: 6` and saw sequential timings can find
567
+ * out why from the log rather than from this file.
568
+ */
569
+ resolveConcurrency(phase, branchCount) {
570
+ const declared = resolveTemplatedNumber(phase.max_concurrent, this.run.ctx, `${phase.name}.max_concurrent`, this.run.ledger.logger);
571
+ const wanted = Math.max(1, declared ?? branchCount);
572
+ const ceiling = BACKEND_MAX_CONCURRENT[this.run.backend] ?? 1;
573
+ const effective = Math.min(wanted, ceiling, Math.max(1, branchCount));
574
+ if (effective < wanted) {
575
+ log.info("clamping fan-out concurrency for this backend", {
576
+ phase: phase.name,
577
+ backend: this.run.backend,
578
+ requested: wanted,
579
+ effective,
580
+ reason: this.run.backend === "gondolin"
581
+ ? "gondolin boots a QEMU micro-VM per agent session in the harness process"
582
+ : "concurrent agent turns are unverified on this backend",
583
+ });
584
+ }
585
+ return effective;
586
+ }
587
+ /** The phase-level config — what opens the shared session. */
588
+ phaseConfig(phase) {
589
+ const { model, variant } = this.resolveModelVariant(phase.model, phase.variant, phase.name);
590
+ const base = phaseConfigFor(this.run.config, phase, this.run.assets);
591
+ return {
592
+ ...base,
593
+ ...(model ? { model } : {}),
594
+ ...(variant ? { variant } : {}),
595
+ telemetry: {
596
+ workflowName: this.run.workflowName,
597
+ phaseName: phase.name,
598
+ triggerId: this.run.triggerId,
599
+ workflowRunId: this.run.workflowId,
600
+ },
601
+ };
602
+ }
603
+ /**
604
+ * The per-branch config. Two things vary and both matter:
605
+ * `telemetry.phaseName` (which is `skillBundleKey`, so each branch stages into
606
+ * its OWN `.lastlight-skills/<label>/` and concurrent branches cannot clobber
607
+ * each other's catalogue) and `skillPaths` when the branch overrides skills.
608
+ */
609
+ branchConfig(phase, branch, label) {
610
+ const { model, variant } = this.resolveModelVariant(branch.model ?? phase.model, branch.variant ?? phase.variant, label, phase.name);
611
+ const base = phaseConfigFor(this.run.config, this.branchPhase(phase, branch, label), this.run.assets);
612
+ return {
613
+ ...base,
614
+ ...(model ? { model } : {}),
615
+ ...(variant ? { variant } : {}),
616
+ telemetry: {
617
+ workflowName: this.run.workflowName,
618
+ phaseName: label,
619
+ triggerId: this.run.triggerId,
620
+ workflowRunId: this.run.workflowId,
621
+ },
622
+ };
623
+ }
624
+ /**
625
+ * The branch as a phase-shaped object, for the two engine helpers that take
626
+ * one (`buildPhasePrompt`, `phaseConfigFor`).
627
+ *
628
+ * Built by hand rather than by spreading the branch over the phase: a spread
629
+ * would carry `until_bash` and `branches` into something that looks like a
630
+ * PhaseDefinition, and the prompt-cache ordering (§D4 — shared prefix first,
631
+ * the family's obligations last) depends on this going through exactly the
632
+ * same `buildPhasePrompt` path the six chained phases used.
633
+ */
634
+ branchPhase(phase, branch, label) {
635
+ return {
636
+ name: label,
637
+ type: "agent",
638
+ prompt: branch.prompt ?? phase.prompt,
639
+ skill: branch.skills ? undefined : (branch.skill ?? (branch.skills ? undefined : phase.skill)),
640
+ skills: branch.skills ?? (branch.skill ? undefined : phase.skills),
641
+ unrestricted_egress: phase.unrestricted_egress,
642
+ web_search: phase.web_search,
643
+ sandbox_image: phase.sandbox_image,
644
+ };
645
+ }
646
+ /** Mirrors `PhaseExecutor.resolveModelVariant` — YAML template first, then the resolver. */
647
+ resolveModelVariant(template, variantTemplate, taskName, fallbackTask) {
648
+ const render = (t) => t ? renderTemplate(t, this.run.ctx) : undefined;
649
+ const model = render(template) || this.run.resolver.modelFor(taskName) ||
650
+ (fallbackTask ? this.run.resolver.modelFor(fallbackTask) : undefined);
651
+ const variant = render(variantTemplate) || this.run.resolver.variantFor(taskName) ||
652
+ (fallbackTask ? this.run.resolver.variantFor(fallbackTask) : undefined);
653
+ return { model, variant };
654
+ }
655
+ gateTimeoutSeconds(phase, branch) {
656
+ return (resolveTemplatedNumber(branch.timeout_seconds ?? phase.timeout_seconds, this.run.ctx, `${phase.name}.${branch.name}.timeout_seconds`, this.run.ledger.logger) ?? 30);
657
+ }
658
+ }
659
+ /** Build the app-registered `fanout` phase-type handler for a run. */
660
+ export function makeFanoutHandler(run, reporter) {
661
+ return new FanoutHandler(run, reporter);
662
+ }
663
+ //# sourceMappingURL=fanout.js.map