lastlight-core 0.16.1

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 (345) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +10 -0
  3. package/agent-context/rules.md +80 -0
  4. package/agent-context/security.md +69 -0
  5. package/agent-context/soul.md +21 -0
  6. package/config/default.yaml +119 -0
  7. package/deploy/.env.production.example +100 -0
  8. package/deploy/entrypoint.sh +82 -0
  9. package/deploy/native/README.md +160 -0
  10. package/deploy/native/install.sh +110 -0
  11. package/deploy/native/lastlight.env.example +95 -0
  12. package/deploy/native/lastlight.service +50 -0
  13. package/deploy/sandbox-entrypoint.sh +93 -0
  14. package/deploy/slack/README.md +92 -0
  15. package/deploy/slack/slack-manifest.json +55 -0
  16. package/dist/admin/auth.d.ts +51 -0
  17. package/dist/admin/auth.js +121 -0
  18. package/dist/admin/auth.js.map +1 -0
  19. package/dist/admin/chat-session-reader.d.ts +39 -0
  20. package/dist/admin/chat-session-reader.js +84 -0
  21. package/dist/admin/chat-session-reader.js.map +1 -0
  22. package/dist/admin/docker.d.ts +61 -0
  23. package/dist/admin/docker.js +187 -0
  24. package/dist/admin/docker.js.map +1 -0
  25. package/dist/admin/index.d.ts +9 -0
  26. package/dist/admin/index.js +59 -0
  27. package/dist/admin/index.js.map +1 -0
  28. package/dist/admin/routes.d.ts +81 -0
  29. package/dist/admin/routes.js +1381 -0
  30. package/dist/admin/routes.js.map +1 -0
  31. package/dist/admin/sessions.d.ts +89 -0
  32. package/dist/admin/sessions.js +204 -0
  33. package/dist/admin/sessions.js.map +1 -0
  34. package/dist/admin/tail.d.ts +12 -0
  35. package/dist/admin/tail.js +145 -0
  36. package/dist/admin/tail.js.map +1 -0
  37. package/dist/admin/version.d.ts +22 -0
  38. package/dist/admin/version.js +92 -0
  39. package/dist/admin/version.js.map +1 -0
  40. package/dist/config/config-resolve.d.ts +28 -0
  41. package/dist/config/config-resolve.js +47 -0
  42. package/dist/config/config-resolve.js.map +1 -0
  43. package/dist/config/config.d.ts +140 -0
  44. package/dist/config/config.js +581 -0
  45. package/dist/config/config.js.map +1 -0
  46. package/dist/connectors/github-webhook.d.ts +45 -0
  47. package/dist/connectors/github-webhook.js +321 -0
  48. package/dist/connectors/github-webhook.js.map +1 -0
  49. package/dist/connectors/index.d.ts +18 -0
  50. package/dist/connectors/index.js +41 -0
  51. package/dist/connectors/index.js.map +1 -0
  52. package/dist/connectors/messaging/base.d.ts +42 -0
  53. package/dist/connectors/messaging/base.js +139 -0
  54. package/dist/connectors/messaging/base.js.map +1 -0
  55. package/dist/connectors/messaging/delivery.d.ts +14 -0
  56. package/dist/connectors/messaging/delivery.js +38 -0
  57. package/dist/connectors/messaging/delivery.js.map +1 -0
  58. package/dist/connectors/messaging/index.d.ts +4 -0
  59. package/dist/connectors/messaging/index.js +4 -0
  60. package/dist/connectors/messaging/index.js.map +1 -0
  61. package/dist/connectors/messaging/session-manager.d.ts +53 -0
  62. package/dist/connectors/messaging/session-manager.js +255 -0
  63. package/dist/connectors/messaging/session-manager.js.map +1 -0
  64. package/dist/connectors/messaging/types.d.ts +58 -0
  65. package/dist/connectors/messaging/types.js +7 -0
  66. package/dist/connectors/messaging/types.js.map +1 -0
  67. package/dist/connectors/slack/connector.d.ts +142 -0
  68. package/dist/connectors/slack/connector.js +494 -0
  69. package/dist/connectors/slack/connector.js.map +1 -0
  70. package/dist/connectors/slack/index.d.ts +2 -0
  71. package/dist/connectors/slack/index.js +3 -0
  72. package/dist/connectors/slack/index.js.map +1 -0
  73. package/dist/connectors/slack/mrkdwn.d.ts +19 -0
  74. package/dist/connectors/slack/mrkdwn.js +240 -0
  75. package/dist/connectors/slack/mrkdwn.js.map +1 -0
  76. package/dist/connectors/types.d.ts +61 -0
  77. package/dist/connectors/types.js +2 -0
  78. package/dist/connectors/types.js.map +1 -0
  79. package/dist/cron/fanout.d.ts +33 -0
  80. package/dist/cron/fanout.js +55 -0
  81. package/dist/cron/fanout.js.map +1 -0
  82. package/dist/cron/jobs.d.ts +18 -0
  83. package/dist/cron/jobs.js +37 -0
  84. package/dist/cron/jobs.js.map +1 -0
  85. package/dist/cron/scheduler.d.ts +45 -0
  86. package/dist/cron/scheduler.js +105 -0
  87. package/dist/cron/scheduler.js.map +1 -0
  88. package/dist/engine/agent-executor.d.ts +34 -0
  89. package/dist/engine/agent-executor.js +246 -0
  90. package/dist/engine/agent-executor.js.map +1 -0
  91. package/dist/engine/chat/chat-runner.d.ts +132 -0
  92. package/dist/engine/chat/chat-runner.js +424 -0
  93. package/dist/engine/chat/chat-runner.js.map +1 -0
  94. package/dist/engine/chat/chat-skills.d.ts +45 -0
  95. package/dist/engine/chat/chat-skills.js +184 -0
  96. package/dist/engine/chat/chat-skills.js.map +1 -0
  97. package/dist/engine/chat/chat.d.ts +54 -0
  98. package/dist/engine/chat/chat.js +316 -0
  99. package/dist/engine/chat/chat.js.map +1 -0
  100. package/dist/engine/chat/message-batcher.d.ts +32 -0
  101. package/dist/engine/chat/message-batcher.js +109 -0
  102. package/dist/engine/chat/message-batcher.js.map +1 -0
  103. package/dist/engine/dispatcher.d.ts +73 -0
  104. package/dist/engine/dispatcher.js +663 -0
  105. package/dist/engine/dispatcher.js.map +1 -0
  106. package/dist/engine/event-shim.d.ts +117 -0
  107. package/dist/engine/event-shim.js +435 -0
  108. package/dist/engine/event-shim.js.map +1 -0
  109. package/dist/engine/executors/orchestrator.d.ts +74 -0
  110. package/dist/engine/executors/orchestrator.js +365 -0
  111. package/dist/engine/executors/orchestrator.js.map +1 -0
  112. package/dist/engine/executors/shared.d.ts +189 -0
  113. package/dist/engine/executors/shared.js +616 -0
  114. package/dist/engine/executors/shared.js.map +1 -0
  115. package/dist/engine/github/git-auth.d.ts +62 -0
  116. package/dist/engine/github/git-auth.js +161 -0
  117. package/dist/engine/github/git-auth.js.map +1 -0
  118. package/dist/engine/github/github-app-client.d.ts +23 -0
  119. package/dist/engine/github/github-app-client.js +33 -0
  120. package/dist/engine/github/github-app-client.js.map +1 -0
  121. package/dist/engine/github/github-tools.d.ts +18 -0
  122. package/dist/engine/github/github-tools.js +263 -0
  123. package/dist/engine/github/github-tools.js.map +1 -0
  124. package/dist/engine/github/github.d.ts +1193 -0
  125. package/dist/engine/github/github.js +357 -0
  126. package/dist/engine/github/github.js.map +1 -0
  127. package/dist/engine/github/profiles.d.ts +11 -0
  128. package/dist/engine/github/profiles.js +42 -0
  129. package/dist/engine/github/profiles.js.map +1 -0
  130. package/dist/engine/github/review-poster.d.ts +98 -0
  131. package/dist/engine/github/review-poster.js +177 -0
  132. package/dist/engine/github/review-poster.js.map +1 -0
  133. package/dist/engine/llm.d.ts +79 -0
  134. package/dist/engine/llm.js +269 -0
  135. package/dist/engine/llm.js.map +1 -0
  136. package/dist/engine/oauth.d.ts +8 -0
  137. package/dist/engine/oauth.js +9 -0
  138. package/dist/engine/oauth.js.map +1 -0
  139. package/dist/engine/router.d.ts +29 -0
  140. package/dist/engine/router.js +680 -0
  141. package/dist/engine/router.js.map +1 -0
  142. package/dist/engine/screen/classifier.d.ts +93 -0
  143. package/dist/engine/screen/classifier.js +215 -0
  144. package/dist/engine/screen/classifier.js.map +1 -0
  145. package/dist/engine/screen/screen.d.ts +41 -0
  146. package/dist/engine/screen/screen.js +93 -0
  147. package/dist/engine/screen/screen.js.map +1 -0
  148. package/dist/evals-api.d.ts +24 -0
  149. package/dist/evals-api.js +22 -0
  150. package/dist/evals-api.js.map +1 -0
  151. package/dist/index.d.ts +1 -0
  152. package/dist/index.js +940 -0
  153. package/dist/index.js.map +1 -0
  154. package/dist/managed-repos.d.ts +30 -0
  155. package/dist/managed-repos.js +72 -0
  156. package/dist/managed-repos.js.map +1 -0
  157. package/dist/notify/blocks.d.ts +23 -0
  158. package/dist/notify/blocks.js +118 -0
  159. package/dist/notify/blocks.js.map +1 -0
  160. package/dist/notify/index.d.ts +17 -0
  161. package/dist/notify/index.js +7 -0
  162. package/dist/notify/index.js.map +1 -0
  163. package/dist/notify/model.d.ts +57 -0
  164. package/dist/notify/model.js +89 -0
  165. package/dist/notify/model.js.map +1 -0
  166. package/dist/notify/notifier.d.ts +18 -0
  167. package/dist/notify/notifier.js +100 -0
  168. package/dist/notify/notifier.js.map +1 -0
  169. package/dist/notify/render.d.ts +21 -0
  170. package/dist/notify/render.js +59 -0
  171. package/dist/notify/render.js.map +1 -0
  172. package/dist/notify/transports/github.d.ts +26 -0
  173. package/dist/notify/transports/github.js +27 -0
  174. package/dist/notify/transports/github.js.map +1 -0
  175. package/dist/notify/transports/slack.d.ts +27 -0
  176. package/dist/notify/transports/slack.js +37 -0
  177. package/dist/notify/transports/slack.js.map +1 -0
  178. package/dist/notify/types.d.ts +111 -0
  179. package/dist/notify/types.js +16 -0
  180. package/dist/notify/types.js.map +1 -0
  181. package/dist/sandbox/docker.d.ts +180 -0
  182. package/dist/sandbox/docker.js +517 -0
  183. package/dist/sandbox/docker.js.map +1 -0
  184. package/dist/sandbox/egress-allowlist.d.ts +74 -0
  185. package/dist/sandbox/egress-allowlist.js +164 -0
  186. package/dist/sandbox/egress-allowlist.js.map +1 -0
  187. package/dist/sandbox/egress-firewall-config.d.ts +127 -0
  188. package/dist/sandbox/egress-firewall-config.js +434 -0
  189. package/dist/sandbox/egress-firewall-config.js.map +1 -0
  190. package/dist/sandbox/images.d.ts +23 -0
  191. package/dist/sandbox/images.js +55 -0
  192. package/dist/sandbox/images.js.map +1 -0
  193. package/dist/sandbox/index.d.ts +112 -0
  194. package/dist/sandbox/index.js +332 -0
  195. package/dist/sandbox/index.js.map +1 -0
  196. package/dist/sandbox/sandbox.d.ts +214 -0
  197. package/dist/sandbox/sandbox.js +453 -0
  198. package/dist/sandbox/sandbox.js.map +1 -0
  199. package/dist/sandbox/smol.d.ts +162 -0
  200. package/dist/sandbox/smol.js +485 -0
  201. package/dist/sandbox/smol.js.map +1 -0
  202. package/dist/session-log.d.ts +63 -0
  203. package/dist/session-log.js +290 -0
  204. package/dist/session-log.js.map +1 -0
  205. package/dist/state/approval-store.d.ts +88 -0
  206. package/dist/state/approval-store.js +149 -0
  207. package/dist/state/approval-store.js.map +1 -0
  208. package/dist/state/build-assets.d.ts +50 -0
  209. package/dist/state/build-assets.js +154 -0
  210. package/dist/state/build-assets.js.map +1 -0
  211. package/dist/state/db.d.ts +81 -0
  212. package/dist/state/db.js +155 -0
  213. package/dist/state/db.js.map +1 -0
  214. package/dist/state/execution-store.d.ts +257 -0
  215. package/dist/state/execution-store.js +527 -0
  216. package/dist/state/execution-store.js.map +1 -0
  217. package/dist/state/migrate.d.ts +15 -0
  218. package/dist/state/migrate.js +175 -0
  219. package/dist/state/migrate.js.map +1 -0
  220. package/dist/state/workflow-run-store.d.ts +216 -0
  221. package/dist/state/workflow-run-store.js +403 -0
  222. package/dist/state/workflow-run-store.js.map +1 -0
  223. package/dist/telemetry/index.d.ts +38 -0
  224. package/dist/telemetry/index.js +253 -0
  225. package/dist/telemetry/index.js.map +1 -0
  226. package/dist/telemetry/pi-events.d.ts +12 -0
  227. package/dist/telemetry/pi-events.js +134 -0
  228. package/dist/telemetry/pi-events.js.map +1 -0
  229. package/dist/workflows/dag.d.ts +1 -0
  230. package/dist/workflows/dag.js +2 -0
  231. package/dist/workflows/dag.js.map +1 -0
  232. package/dist/workflows/handlers/post-review.d.ts +45 -0
  233. package/dist/workflows/handlers/post-review.js +220 -0
  234. package/dist/workflows/handlers/post-review.js.map +1 -0
  235. package/dist/workflows/handlers/verdict-reader.d.ts +14 -0
  236. package/dist/workflows/handlers/verdict-reader.js +55 -0
  237. package/dist/workflows/handlers/verdict-reader.js.map +1 -0
  238. package/dist/workflows/loader.d.ts +9 -0
  239. package/dist/workflows/loader.js +10 -0
  240. package/dist/workflows/loader.js.map +1 -0
  241. package/dist/workflows/loop-eval.d.ts +1 -0
  242. package/dist/workflows/loop-eval.js +2 -0
  243. package/dist/workflows/loop-eval.js.map +1 -0
  244. package/dist/workflows/phase-executor.d.ts +1 -0
  245. package/dist/workflows/phase-executor.js +6 -0
  246. package/dist/workflows/phase-executor.js.map +1 -0
  247. package/dist/workflows/phase-ref.d.ts +1 -0
  248. package/dist/workflows/phase-ref.js +2 -0
  249. package/dist/workflows/phase-ref.js.map +1 -0
  250. package/dist/workflows/resume.d.ts +58 -0
  251. package/dist/workflows/resume.js +313 -0
  252. package/dist/workflows/resume.js.map +1 -0
  253. package/dist/workflows/runner.d.ts +47 -0
  254. package/dist/workflows/runner.js +278 -0
  255. package/dist/workflows/runner.js.map +1 -0
  256. package/dist/workflows/schema.d.ts +1 -0
  257. package/dist/workflows/schema.js +2 -0
  258. package/dist/workflows/schema.js.map +1 -0
  259. package/dist/workflows/simple.d.ts +90 -0
  260. package/dist/workflows/simple.js +393 -0
  261. package/dist/workflows/simple.js.map +1 -0
  262. package/dist/workflows/target-policy.d.ts +74 -0
  263. package/dist/workflows/target-policy.js +80 -0
  264. package/dist/workflows/target-policy.js.map +1 -0
  265. package/dist/workflows/templates.d.ts +1 -0
  266. package/dist/workflows/templates.js +2 -0
  267. package/dist/workflows/templates.js.map +1 -0
  268. package/dist/workflows/triggers.d.ts +21 -0
  269. package/dist/workflows/triggers.js +45 -0
  270. package/dist/workflows/triggers.js.map +1 -0
  271. package/dist/workflows/verdict.d.ts +1 -0
  272. package/dist/workflows/verdict.js +2 -0
  273. package/dist/workflows/verdict.js.map +1 -0
  274. package/dist/worktree/manager.d.ts +43 -0
  275. package/dist/worktree/manager.js +127 -0
  276. package/dist/worktree/manager.js.map +1 -0
  277. package/docker-compose.yml +280 -0
  278. package/package.json +93 -0
  279. package/sandbox.Dockerfile +68 -0
  280. package/skills/README.md +42 -0
  281. package/skills/browser-qa/SKILL.md +208 -0
  282. package/skills/browser-qa/scripts/agent-browser.mjs +531 -0
  283. package/skills/building/SKILL.md +95 -0
  284. package/skills/chat/SKILL.md +36 -0
  285. package/skills/code-review/SKILL.md +82 -0
  286. package/skills/debug-production/SKILL.md +108 -0
  287. package/skills/demo/SKILL.md +228 -0
  288. package/skills/demo/scripts/compose-demo.sh +243 -0
  289. package/skills/issue-answer/SKILL.md +91 -0
  290. package/skills/issue-comment/SKILL.md +49 -0
  291. package/skills/issue-triage/SKILL.md +149 -0
  292. package/skills/issue-triage/references/AGENT-BRIEF.md +65 -0
  293. package/skills/pr-comment/SKILL.md +64 -0
  294. package/skills/pr-review/SKILL.md +148 -0
  295. package/skills/pr-review/references/findings-schema.md +89 -0
  296. package/skills/qa-test/SKILL.md +97 -0
  297. package/skills/repo-health/SKILL.md +67 -0
  298. package/skills/security-feedback/SKILL.md +173 -0
  299. package/skills/security-feedback/references/templates.md +77 -0
  300. package/skills/security-review/SKILL.md +215 -0
  301. package/skills/security-review/references/issue-format.md +302 -0
  302. package/skills/verify/SKILL.md +118 -0
  303. package/workflows/answer.yaml +44 -0
  304. package/workflows/build.yaml +129 -0
  305. package/workflows/cron-health.yaml +6 -0
  306. package/workflows/cron-review.yaml +8 -0
  307. package/workflows/cron-security.yaml +6 -0
  308. package/workflows/cron-triage.yaml +8 -0
  309. package/workflows/demo.yaml +62 -0
  310. package/workflows/examples/bash-smoke.yaml +41 -0
  311. package/workflows/examples/parallel-review.yaml +36 -0
  312. package/workflows/examples/tdd-loop.yaml +17 -0
  313. package/workflows/explore.yaml +80 -0
  314. package/workflows/issue-comment.yaml +15 -0
  315. package/workflows/issue-triage.yaml +22 -0
  316. package/workflows/pr-comment.yaml +16 -0
  317. package/workflows/pr-fix.yaml +17 -0
  318. package/workflows/pr-review.yaml +50 -0
  319. package/workflows/prompts/answer.md +68 -0
  320. package/workflows/prompts/architect.md +44 -0
  321. package/workflows/prompts/classifier.md +60 -0
  322. package/workflows/prompts/classify-adds-info.md +17 -0
  323. package/workflows/prompts/demo.md +125 -0
  324. package/workflows/prompts/executor.md +42 -0
  325. package/workflows/prompts/explore-ask.md +99 -0
  326. package/workflows/prompts/explore-publish.md +31 -0
  327. package/workflows/prompts/explore-read.md +120 -0
  328. package/workflows/prompts/explore-synthesize.md +88 -0
  329. package/workflows/prompts/fix.md +18 -0
  330. package/workflows/prompts/guardrails.md +96 -0
  331. package/workflows/prompts/pr-fix.md +26 -0
  332. package/workflows/prompts/pr.md +39 -0
  333. package/workflows/prompts/qa-browser.md +95 -0
  334. package/workflows/prompts/qa-synth.md +44 -0
  335. package/workflows/prompts/qa-test.md +60 -0
  336. package/workflows/prompts/re-reviewer.md +33 -0
  337. package/workflows/prompts/reviewer.md +60 -0
  338. package/workflows/prompts/verify-browser.md +93 -0
  339. package/workflows/prompts/verify-synth.md +44 -0
  340. package/workflows/prompts/verify.md +63 -0
  341. package/workflows/qa-test.yaml +94 -0
  342. package/workflows/repo-health.yaml +15 -0
  343. package/workflows/security-feedback.yaml +25 -0
  344. package/workflows/security-review.yaml +37 -0
  345. package/workflows/verify.yaml +93 -0
@@ -0,0 +1,313 @@
1
+ import { runWorkflow } from "./runner.js";
2
+ import { getWorkflow } from "./loader.js";
3
+ import { workflowScopedTaskId } from "./simple.js";
4
+ import { slugify } from "./templates.js";
5
+ import { ProgressNotifier, GitHubTransport, buildProgressModel, runDashboardUrl, } from "../notify/index.js";
6
+ /**
7
+ * Parse `cliftonc/drizby#18` (or `cliftonc/drizby::workflow-name`) into
8
+ * its components. Returns null for Slack/chat-originated trigger ids —
9
+ * those runs resume via the messaging connector, not GitHub refetch.
10
+ */
11
+ export function parseTriggerId(triggerId) {
12
+ if (triggerId.startsWith("slack:"))
13
+ return null;
14
+ const slashIdx = triggerId.indexOf("/");
15
+ if (slashIdx < 0)
16
+ return null;
17
+ const hashIdx = triggerId.indexOf("#");
18
+ const colonIdx = triggerId.indexOf("::");
19
+ const end = hashIdx >= 0 ? hashIdx : colonIdx >= 0 ? colonIdx : triggerId.length;
20
+ const owner = triggerId.slice(0, slashIdx);
21
+ const repo = triggerId.slice(slashIdx + 1, end);
22
+ if (!owner || !repo)
23
+ return null;
24
+ return { owner, repo };
25
+ }
26
+ /**
27
+ * Parse a Slack trigger id of the form `slack:{teamId}:{channel}:{thread}`.
28
+ * Returns null for anything else. Used by the runner bridge to reconstruct
29
+ * channel/thread coordinates when resuming a Slack-initiated explore run.
30
+ */
31
+ export function parseSlackTriggerId(triggerId) {
32
+ if (!triggerId.startsWith("slack:"))
33
+ return null;
34
+ const parts = triggerId.slice("slack:".length).split(":");
35
+ if (parts.length !== 3)
36
+ return null;
37
+ const [teamId, channelId, threadTs] = parts;
38
+ if (!teamId || !channelId || !threadTs)
39
+ return null;
40
+ return { teamId, channelId, threadTs };
41
+ }
42
+ /**
43
+ * Refetch the issue title/body/labels from GitHub so the resumed workflow
44
+ * has fresh context (the user may have edited the issue while the harness
45
+ * was down). Falls back to placeholder values if the fetch fails or no
46
+ * GitHub client is available.
47
+ */
48
+ async function refetchIssue(github, owner, repo, issueNumber) {
49
+ const fallback = {
50
+ title: `Issue #${issueNumber}`,
51
+ body: "",
52
+ labels: [],
53
+ };
54
+ if (!github)
55
+ return fallback;
56
+ try {
57
+ const issue = await github.getIssue(owner, repo, issueNumber);
58
+ return {
59
+ title: issue.title || fallback.title,
60
+ body: issue.body || "",
61
+ labels: (issue.labels || []).map((l) => typeof l === "string" ? l : l.name ?? "").filter(Boolean),
62
+ };
63
+ }
64
+ catch (err) {
65
+ const msg = err instanceof Error ? err.message : String(err);
66
+ console.warn(`[resume] Could not refetch ${owner}/${repo}#${issueNumber}: ${msg}`);
67
+ return fallback;
68
+ }
69
+ }
70
+ /**
71
+ * Build the standard postComment callback for a resumed workflow. Comments
72
+ * land on the originating GitHub issue so the maintainer sees the resume
73
+ * progress alongside the original run.
74
+ */
75
+ function makeCallbacks(github, owner, repo, issueNumber, workflowName) {
76
+ return {
77
+ postComment: github && issueNumber
78
+ ? async (msg) => {
79
+ try {
80
+ await github.postComment(owner, repo, issueNumber, msg);
81
+ }
82
+ catch (err) {
83
+ const m = err instanceof Error ? err.message : String(err);
84
+ console.warn(`[resume] Failed to post comment: ${m}`);
85
+ }
86
+ }
87
+ : undefined,
88
+ onPhaseStart: async (phase) => console.log(`[resume] ▶ ${workflowName}/${phase}`),
89
+ onPhaseEnd: async (phase, result) => console.log(`[resume] ◀ ${workflowName}/${phase}: ${result.success ? "OK" : "FAILED"}`),
90
+ };
91
+ }
92
+ /**
93
+ * Resume a workflow run by calling runWorkflow directly with the existing
94
+ * workflowId. We bypass runSimpleWorkflow because that wrapper always creates a
95
+ * fresh workflow_runs row — we want to keep the existing one and let the
96
+ * runner's per-phase dedup (`shouldRunPhase`) handle "what's already done".
97
+ *
98
+ * Two callers, same machinery:
99
+ * - `resumeOrphanedWorkflows` — boot recovery of `running` runs after a crash.
100
+ * - the admin/CLI **retry** path (`config.retryWorkflow` in `src/index.ts`) —
101
+ * a user retrying a `failed` run. The failed phase's ledger row is
102
+ * `success=0`, so it re-runs while already-succeeded phases skip; context is
103
+ * reconstructed here from the stored `run.context` + `run.scratch`, which is
104
+ * why retry works for Slack-thread-scoped runs the lossy `resumeWorkflow`
105
+ * (owner/repo/issueNumber) path can't handle.
106
+ *
107
+ * The caller MUST have already flipped the row to `running` (`setRunning` /
108
+ * `restartRun`) — this function does not change the pre-run status, only the
109
+ * terminal `finishRun` at the end.
110
+ */
111
+ export async function resumeSimpleRun(run, opts) {
112
+ const stored = (run.context || {});
113
+ // Derive owner/repo: GitHub trigger ids encode it as owner/repo#N;
114
+ // Slack-originated runs store owner in context and repo on the row.
115
+ const parsed = parseTriggerId(run.triggerId);
116
+ const owner = parsed?.owner ?? stored.owner ?? "";
117
+ const repo = parsed?.repo ?? run.repo ?? "";
118
+ const issueNumber = run.issueNumber;
119
+ const isSlack = run.triggerId.startsWith("slack:");
120
+ if (!owner && !repo && !isSlack) {
121
+ console.warn(`[resume] Skipping ${run.id}: cannot derive owner/repo from triggerId ${run.triggerId}`);
122
+ return;
123
+ }
124
+ let definition;
125
+ try {
126
+ definition = getWorkflow(run.workflowName);
127
+ }
128
+ catch (err) {
129
+ const msg = err instanceof Error ? err.message : String(err);
130
+ console.warn(`[resume] Skipping ${run.id}: workflow definition "${run.workflowName}" not found: ${msg}`);
131
+ opts.db.runs.finishRun(run.id, "failed", { error: `harness restarted; workflow definition not found` });
132
+ return;
133
+ }
134
+ const issue = issueNumber && owner && repo
135
+ ? await refetchIssue(opts.github, owner, repo, issueNumber)
136
+ : { title: "", body: "", labels: [] };
137
+ // Reconstruct the template context using the bits we stored on creation +
138
+ // refreshed issue data. taskId/branch/issueDir were saved on the original
139
+ // row, fall back to deterministic defaults if the row is older.
140
+ const taskId = stored.taskId ??
141
+ workflowScopedTaskId(repo, issueNumber, run.workflowName, run.id);
142
+ const branch = stored.branch ??
143
+ (issueNumber
144
+ ? `lastlight/${issueNumber}-${slugify(issue.title || `issue-${issueNumber}`)}`
145
+ : `lastlight/${run.workflowName}`);
146
+ const issueDir = stored.issueDir
147
+ ?? (issueNumber ? `.lastlight/issue-${issueNumber}` : `.lastlight/${run.workflowName}`);
148
+ const ctx = {
149
+ owner,
150
+ repo,
151
+ issueNumber: issueNumber ?? 0,
152
+ issueTitle: issue.title,
153
+ issueBody: issue.body,
154
+ issueLabels: issue.labels,
155
+ commentBody: "",
156
+ sender: "system:resume",
157
+ branch,
158
+ taskId,
159
+ issueDir,
160
+ // Mirror the fresh-dispatch context so a resumed server-mode run keeps
161
+ // externalizing (and linking docs to the dashboard) instead of silently
162
+ // reverting to committing them on the branch.
163
+ externalizeArtifacts: opts.config.buildAssets === "server",
164
+ publicUrl: opts.publicUrl,
165
+ bootstrapLabel: opts.bootstrapLabel || "lastlight:bootstrap",
166
+ contextSnapshot: "",
167
+ // Preserve the original prePopulateBranch so a resumed run still
168
+ // gets its workspace pre-cloned (matters for pr-fix re-entry after
169
+ // an approval gate, where the branch was resolved at first dispatch).
170
+ prePopulateBranch: typeof stored.prePopulateBranch === "string"
171
+ ? stored.prePopulateBranch
172
+ : undefined,
173
+ models: opts.models,
174
+ triggerIdOverride: isSlack ? run.triggerId : undefined,
175
+ };
176
+ console.log(`[resume] Re-dispatching ${run.workflowName} for ${run.triggerId} (was on phase=${run.currentPhase})`);
177
+ // For Slack-originated runs, post progress to the Slack thread instead
178
+ // of GitHub. The channelId/threadId were stored in context by the
179
+ // original dispatch.
180
+ let slackCallbacks = null;
181
+ if (isSlack && opts.slackPoster) {
182
+ const ch = stored.channelId;
183
+ const th = stored.threadId;
184
+ if (ch && th) {
185
+ const poster = opts.slackPoster;
186
+ slackCallbacks = {
187
+ postComment: async (msg) => {
188
+ try {
189
+ await poster(ch, th, msg);
190
+ }
191
+ catch (err) {
192
+ const m = err instanceof Error ? err.message : String(err);
193
+ console.warn(`[resume] Failed to post to Slack thread: ${m}`);
194
+ }
195
+ },
196
+ onPhaseStart: async (phase) => console.log(`[resume] ▶ ${run.workflowName}/${phase}`),
197
+ onPhaseEnd: async (phase, result) => console.log(`[resume] ◀ ${run.workflowName}/${phase}: ${result.success ? "OK" : "FAILED"}`),
198
+ };
199
+ }
200
+ }
201
+ let callbacks = slackCallbacks || makeCallbacks(opts.github, owner, repo, issueNumber, run.workflowName);
202
+ // Re-attach the in-place checklist on GitHub boot-recovery so a run that was
203
+ // mid-flight when the harness died keeps editing its original status comment
204
+ // instead of posting a fresh one. The stored comment id lives in
205
+ // scratch.notifier; completed phases are re-seeded from phase_history.
206
+ // (The Slack boot-recovery path only has a post function here — no
207
+ // chat.update — so it stays on legacy comments.)
208
+ if (!slackCallbacks && definition.status_checklist && opts.github && issueNumber) {
209
+ try {
210
+ const saved = ((run.scratch?.notifier) ?? {});
211
+ const github = opts.github;
212
+ const persist = (patch) => {
213
+ const cur = ((opts.db.runs.getRun(run.id)?.scratch?.notifier) ?? {});
214
+ opts.db.runs.mergeScratch(run.id, { notifier: { ...cur, ...patch } });
215
+ };
216
+ const transport = new GitHubTransport({
217
+ github,
218
+ owner,
219
+ repo,
220
+ issueNumber,
221
+ commentId: saved.githubCommentId,
222
+ save: (id) => persist({ githubCommentId: id }),
223
+ });
224
+ const notifier = new ProgressNotifier([transport]);
225
+ const completed = new Set(run.phaseHistory.map((h) => h.phase));
226
+ await notifier.start(buildProgressModel(definition, {
227
+ workflowName: run.workflowName,
228
+ number: issueNumber,
229
+ issueTitle: issue.title,
230
+ owner,
231
+ repo,
232
+ branch,
233
+ completed,
234
+ runUrl: runDashboardUrl(opts.publicUrl, run.id, run.workflowName),
235
+ }));
236
+ callbacks = { ...callbacks, reporter: notifier };
237
+ }
238
+ catch (err) {
239
+ const m = err instanceof Error ? err.message : String(err);
240
+ console.warn(`[resume] notifier setup failed: ${m}`);
241
+ }
242
+ }
243
+ // Server mode: tag the config with this run's artifact identity so the
244
+ // executor's stage-in/harvest seam targets the same store path the original
245
+ // dispatch used (issueKey = issueDir minus the `.lastlight/` prefix).
246
+ const runConfig = opts.config.buildAssets === "server"
247
+ ? { ...opts.config, buildAssetsKey: { owner, repo, issueKey: issueDir.replace(/^\.lastlight\//, "") } }
248
+ : opts.config;
249
+ try {
250
+ const result = await runWorkflow(definition, ctx, runConfig, callbacks, opts.db, opts.models, opts.approvalConfig, run.id, // <-- key bit: reuse the existing workflow run id
251
+ opts.variants);
252
+ if (result.success) {
253
+ opts.db.runs.finishRun(run.id, "succeeded");
254
+ }
255
+ else if (!result.paused) {
256
+ opts.db.runs.finishRun(run.id, "failed", {
257
+ error: result.phases.find((p) => !p.success)?.error || "workflow failed during resume",
258
+ });
259
+ }
260
+ }
261
+ catch (err) {
262
+ const msg = err instanceof Error ? err.message : String(err);
263
+ console.error(`[resume] ${run.workflowName} resume for ${run.id} threw: ${msg}`);
264
+ opts.db.runs.finishRun(run.id, "failed", { error: `resume threw: ${msg}` });
265
+ }
266
+ }
267
+ /**
268
+ * Boot-time sweep: find every workflow run that was 'running' when the
269
+ * harness last shut down, mark its in-flight execution rows as stale (the
270
+ * Docker containers were already killed by cleanupOrphanedSandboxes), then
271
+ * re-dispatch each run so the runner can pick up where it left off.
272
+ *
273
+ * 'paused' runs are intentionally left alone — they're waiting for human
274
+ * approval and the dashboard / GitHub comment flow will resume them.
275
+ */
276
+ /**
277
+ * Maximum number of times a single workflow run can be resumed after a
278
+ * harness restart. Past this we mark the run failed and stop re-dispatching
279
+ * it, on the theory that a run that crashes the host three times in a row
280
+ * (agent OOM, infinite loop, etc.) needs a human, not another attempt.
281
+ */
282
+ const MAX_RESTART_RESUMES = 3;
283
+ export async function resumeOrphanedWorkflows(opts) {
284
+ const active = opts.db.runs.listActive();
285
+ const orphans = active.filter((r) => r.status === "running");
286
+ if (orphans.length === 0) {
287
+ console.log("[resume] No orphaned workflow runs to recover");
288
+ return;
289
+ }
290
+ console.log(`[resume] Found ${orphans.length} orphaned workflow run(s) — recovering`);
291
+ for (const run of orphans) {
292
+ // Clear any "still running" execution rows so dedup works on resume.
293
+ const cleared = opts.db.executions.markAllStaleForTrigger(run.triggerId, "stale: harness restarted");
294
+ if (cleared > 0) {
295
+ console.log(`[resume] Cleared ${cleared} stale execution(s) for ${run.triggerId}`);
296
+ }
297
+ // Circuit breaker: bump the per-run restart counter, and if we've now
298
+ // resumed it more than MAX_RESTART_RESUMES times, mark it failed and
299
+ // move on. This is what stops an OOM-on-restart loop from churning
300
+ // forever.
301
+ const attempts = opts.db.runs.incrementRestartCount(run.id);
302
+ if (attempts > MAX_RESTART_RESUMES) {
303
+ const msg = `harness restarted ${attempts - 1}x while this run was active — giving up after ${MAX_RESTART_RESUMES} resume attempts`;
304
+ console.warn(`[resume] ${run.workflowName} run ${run.id}: ${msg}`);
305
+ opts.db.runs.finishRun(run.id, "failed", { error: msg });
306
+ continue;
307
+ }
308
+ // Dispatch in the background — we don't want one slow resume to block
309
+ // the others (or the rest of the boot sequence).
310
+ resumeSimpleRun(run, opts).catch((err) => console.error(`[resume] ${run.workflowName} run ${run.id} crashed:`, err));
311
+ }
312
+ }
313
+ //# sourceMappingURL=resume.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"resume.js","sourceRoot":"","sources":["../../src/workflows/resume.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,WAAW,EAAiD,MAAM,aAAa,CAAC;AACzF,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAC1C,OAAO,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,GAAG,qBAAqB,QAAQ,GAAG,CAAC,iDAAiD,mBAAmB,kBAAkB,CAAC;YACpI,OAAO,CAAC,IAAI,CAAC,YAAY,GAAG,CAAC,YAAY,QAAQ,GAAG,CAAC,EAAE,KAAK,GAAG,EAAE,CAAC,CAAC;YACnE,IAAI,CAAC,EAAE,CAAC,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,EAAE,EAAE,QAAQ,EAAE,EAAE,KAAK,EAAE,GAAG,EAAE,CAAC,CAAC;YACzD,SAAS;QACX,CAAC;QAED,sEAAsE;QACtE,iDAAiD;QACjD,eAAe,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC,KAAK,CAAC,CAAC,GAAG,EAAE,EAAE,CACvC,OAAO,CAAC,KAAK,CAAC,YAAY,GAAG,CAAC,YAAY,QAAQ,GAAG,CAAC,EAAE,WAAW,EAAE,GAAG,CAAC,CAC1E,CAAC;IACJ,CAAC;AACH,CAAC"}
@@ -0,0 +1,47 @@
1
+ import type { ExecutorConfig, GitAccessProfile, GitSandboxAccess } from "../engine/github/profiles.js";
2
+ import type { StateDb } from "../state/db.js";
3
+ import type { ModelConfig, VariantConfig } from "../config/config.js";
4
+ import type { AgentWorkflowDefinition } from "./schema.js";
5
+ import { type TemplateContext } from "./templates.js";
6
+ import { isTerminated } from "./phase-executor.js";
7
+ import type { PhaseResult, WorkflowResult } from "lastlight-workflow-engine";
8
+ import type { ProgressReporter } from "../notify/types.js";
9
+ export { isTerminated };
10
+ export type { PhaseResult, WorkflowResult };
11
+ /**
12
+ * Map of approval gate name → enabled. Gate names are arbitrary strings
13
+ * declared in YAML (`phase.approval_gate`, `phase.loop.approval_gate`); a
14
+ * gate pauses only if the corresponding key is `true` here.
15
+ */
16
+ export type ApprovalGateConfig = Record<string, boolean>;
17
+ export interface RunnerCallbacks {
18
+ onPhaseStart?: (phase: string) => Promise<void>;
19
+ onPhaseEnd?: (phase: string, result: PhaseResult) => Promise<void>;
20
+ postComment?: (body: string) => Promise<void>;
21
+ /**
22
+ * In-place "task list" progress surface. When set (workflows that opt in via
23
+ * `status_checklist: true`), the runner drives this instead of posting a new
24
+ * comment per phase. When unset, the runner falls back to `postComment`.
25
+ */
26
+ reporter?: ProgressReporter;
27
+ /**
28
+ * Fires once the workflow_runs row is known. Used by the Slack dispatch path
29
+ * to post the "Starting <skill>" reply with a deep link to the run.
30
+ */
31
+ onRunStart?: (runId: string) => Promise<void>;
32
+ /**
33
+ * Public base URL of the admin dashboard (`config.publicUrl`). When set, the
34
+ * progress checklist embeds a live-run deep link in its meta. Undefined when
35
+ * no public URL is configured (the link is simply omitted).
36
+ */
37
+ publicUrl?: string;
38
+ }
39
+ export declare function gitAccessProfileForWorkflow(workflowName: string): GitAccessProfile;
40
+ export declare function gitSandboxAccessForWorkflow(workflowName: string, owner: string, repo: string, prePopulateBranch?: string, runId?: string): GitSandboxAccess;
41
+ /**
42
+ * Run an agent workflow defined by a YAML definition. This is the frozen
43
+ * `lastlight/evals` surface — the 9-arg signature is byte-stable. It builds the
44
+ * default engine ports, the reporter/resolver collaborators, and the run-scoped
45
+ * {@link PhaseRunContext}, then delegates the DAG walk to `runWorkflowCore`.
46
+ */
47
+ export declare function runWorkflow(definition: AgentWorkflowDefinition, ctx: TemplateContext, config: ExecutorConfig, callbacks: RunnerCallbacks, db?: StateDb, models?: ModelConfig, approvalConfig?: ApprovalGateConfig, workflowId?: string, variants?: VariantConfig): Promise<WorkflowResult>;
@@ -0,0 +1,278 @@
1
+ import { resolveModel, resolveVariant, getBotName } from "../config/config.js";
2
+ import { loadPromptTemplate, resolveSkillPaths } from "./loader.js";
3
+ import { renderTemplate } from "./templates.js";
4
+ import { PER_TARGET_RECREATE_WORKFLOWS } from "./target-policy.js";
5
+ import { qaImageAvailable, SANDBOX_IMAGE_QA } from "../sandbox/images.js";
6
+ import { executeAgent, executeCommand } from "../engine/agent-executor.js";
7
+ import { listRunningContainers } from "../admin/docker.js";
8
+ import { withSpan, recordExecutionMetrics, recordError } from "../telemetry/index.js";
9
+ import { isTerminated } from "./phase-executor.js";
10
+ import { runWorkflowCore } from "lastlight-workflow-engine";
11
+ import { makePostReviewHandler } from "./handlers/post-review.js";
12
+ import { fileVerdictReader } from "./handlers/verdict-reader.js";
13
+ import { collapseDetail } from "../notify/render.js";
14
+ // `isTerminated` used to live here; re-exported for API stability.
15
+ export { isTerminated };
16
+ export function gitAccessProfileForWorkflow(workflowName) {
17
+ switch (workflowName) {
18
+ case "build":
19
+ case "pr-fix":
20
+ return "repo-write";
21
+ case "pr-review":
22
+ return "review-write";
23
+ case "issue-triage":
24
+ case "issue-comment":
25
+ case "pr-comment":
26
+ case "explore":
27
+ case "answer":
28
+ case "security-review":
29
+ // verify / qa-test / demo read the repo and post a findings/demo comment —
30
+ // they never push code, so issues-write (contents:read + issues:write) is
31
+ // enough.
32
+ case "verify":
33
+ case "qa-test":
34
+ case "demo":
35
+ return "issues-write";
36
+ case "security-feedback":
37
+ return "repo-write";
38
+ default:
39
+ return "read";
40
+ }
41
+ }
42
+ export function gitSandboxAccessForWorkflow(workflowName, owner, repo, prePopulateBranch, runId) {
43
+ const profile = gitAccessProfileForWorkflow(workflowName);
44
+ return {
45
+ owner,
46
+ repo,
47
+ profile,
48
+ // Never forward the App PEM into sandboxes. The harness already mints a
49
+ // profile-scoped token and forwards it as GITHUB_TOKEN, so the agent gets
50
+ // github tools in static-token mode without the App private key ever
51
+ // entering the sandbox.
52
+ allowMcpAppAuth: false,
53
+ prePopulateBranch,
54
+ runId,
55
+ // Read-only workflows never need git history — clone at --depth 1. Only
56
+ // the code-pushing profiles (build / pr-fix / security-feedback) keep the
57
+ // deeper clone for rebase/amend headroom.
58
+ shallow: profile !== "repo-write",
59
+ // `build` recreates its workspace from the default branch on a fresh run
60
+ // (issue #153) rather than refreshing a possibly-stale feature branch.
61
+ recreateFromBase: PER_TARGET_RECREATE_WORKFLOWS.has(workflowName),
62
+ };
63
+ }
64
+ // ── Default engine ports (app adapters) ──────────────────────────────────────
65
+ //
66
+ // Thin delegations to the real app functions; injected into the engine so the
67
+ // core stays domain-agnostic. Built once at module load (they hold no run
68
+ // state) except the post-review handler, which is per-run.
69
+ const defaultAgentPort = {
70
+ runAgent: (prompt, config, opts) => executeAgent(prompt, config, opts),
71
+ runCommand: (spec, config, opts) => executeCommand(spec, config, opts),
72
+ };
73
+ const defaultAssetLoader = {
74
+ loadPromptTemplate: (relativePath) => loadPromptTemplate(relativePath),
75
+ resolveSkillPaths: (names) => resolveSkillPaths(names),
76
+ };
77
+ const dockerLivenessPort = {
78
+ isPhaseContainerAlive: async (taskId) => {
79
+ const containers = await listRunningContainers();
80
+ return containers.some((c) => c.taskId === taskId);
81
+ },
82
+ };
83
+ // The engine types the span opaquely (EngineSpan: addEvent/setAttributes) so it
84
+ // never pulls in @opentelemetry; the real OTEL `Span` satisfies that shape at
85
+ // runtime — the cast bridges the structural-vs-nominal gap while preserving T.
86
+ function obsWithSpan(name, attrs, fn) {
87
+ return withSpan(name, attrs, fn);
88
+ }
89
+ const telemetryObservability = {
90
+ withSpan: obsWithSpan,
91
+ recordExecutionMetrics: (surface, attrs) => recordExecutionMetrics(surface, attrs),
92
+ recordError: (surface, error, attrs) => recordError(surface, error, attrs),
93
+ };
94
+ // ── Unified workflow scheduler (composition root) ────────────────────────────
95
+ /**
96
+ * Run an agent workflow defined by a YAML definition. This is the frozen
97
+ * `lastlight/evals` surface — the 9-arg signature is byte-stable. It builds the
98
+ * default engine ports, the reporter/resolver collaborators, and the run-scoped
99
+ * {@link PhaseRunContext}, then delegates the DAG walk to `runWorkflowCore`.
100
+ */
101
+ export async function runWorkflow(definition, ctx, config, callbacks, db, models, approvalConfig, workflowId, variants) {
102
+ const outputs = {};
103
+ const { taskId } = ctx;
104
+ // Slack-originated runs carry an explicit `slack:` trigger id — everything
105
+ // else (GitHub webhook, CLI) uses the legacy owner/repo#N shape.
106
+ const triggerId = ctx.triggerIdOverride
107
+ || `${ctx.owner}/${ctx.repo}#${ctx.issueNumber}`;
108
+ // Load scratch state from the workflow run so generic loops can resume
109
+ // iteration at the right index and templates can read {{scratch.*}}.
110
+ const scratch = ctx.scratch
111
+ ? { ...ctx.scratch }
112
+ : (db && workflowId ? { ...(db.runs.getRun(workflowId)?.scratch ?? {}) } : {});
113
+ ctx.scratch = scratch;
114
+ const prePopulateBranch = typeof ctx.prePopulateBranch === "string"
115
+ ? ctx.prePopulateBranch
116
+ : undefined;
117
+ const githubAccess = gitSandboxAccessForWorkflow(definition.name, ctx.owner, ctx.repo, prePopulateBranch, workflowId);
118
+ const notify = callbacks.postComment || (async () => { });
119
+ const reporter = callbacks.reporter;
120
+ const onStart = callbacks.onPhaseStart || (async () => { });
121
+ const onEnd = callbacks.onPhaseEnd || (async () => { });
122
+ // Terminal step key — dynamic loop steps (re-review / fix cycles) are
123
+ // inserted just above it so the checklist reads top-to-bottom in run order.
124
+ const lastPhaseKey = [...definition.phases]
125
+ .reverse()
126
+ .find((p) => (p.type ?? "agent") !== "context")?.name;
127
+ const modelFor = (taskType) => models ? resolveModel(models, taskType) : undefined;
128
+ const variantFor = (taskType) => variants ? resolveVariant(variants, taskType) : undefined;
129
+ /** Render a prompt template with current context + outputs. */
130
+ const renderPrompt = (promptPath, extraCtx) => {
131
+ const template = loadPromptTemplate(promptPath);
132
+ return renderTemplate(template, { ...ctx, phaseOutputs: outputs, ...(extraCtx || {}) });
133
+ };
134
+ /**
135
+ * Render a YAML message template and post it as a *standalone* message.
136
+ * Routes through `reporter.note()` when the in-place checklist is active,
137
+ * else the legacy `postComment`.
138
+ */
139
+ const notifyMessage = async (template, extraCtx) => {
140
+ if (!template)
141
+ return;
142
+ const rendered = renderTemplate(template, { ...ctx, phaseOutputs: outputs, ...(extraCtx || {}) });
143
+ if (!rendered.trim())
144
+ return;
145
+ if (reporter)
146
+ await reporter.note(rendered);
147
+ else
148
+ await notify(rendered);
149
+ };
150
+ /** Post a pre-rendered standalone message (already-built string). */
151
+ const postNote = async (text) => {
152
+ if (!text.trim())
153
+ return;
154
+ if (reporter)
155
+ await reporter.note(text);
156
+ else
157
+ await notify(text);
158
+ };
159
+ /**
160
+ * Render a YAML message template and post it as an interactive approval
161
+ * prompt — Approve/Reject buttons on rich surfaces (Slack), plain text on the
162
+ * legacy `notify` path or a surface without buttons (GitHub).
163
+ */
164
+ const approvalNote = async (template, extraCtx, meta) => {
165
+ if (!template)
166
+ return;
167
+ const rendered = renderTemplate(template, { ...ctx, phaseOutputs: outputs, ...(extraCtx || {}) });
168
+ if (!rendered.trim())
169
+ return;
170
+ if (reporter)
171
+ await reporter.noteApproval(rendered, meta);
172
+ else
173
+ await notify(rendered);
174
+ };
175
+ /** Transition a checklist step (and optionally render a YAML message detail). */
176
+ const reportStep = async (key, status, template, extraCtx, opts) => {
177
+ const rendered = template
178
+ ? renderTemplate(template, { ...ctx, phaseOutputs: outputs, ...(extraCtx || {}) }).trim()
179
+ : "";
180
+ if (reporter) {
181
+ const detail = collapseDetail(rendered);
182
+ if (opts?.insert) {
183
+ const step = { key, label: opts.label ?? key, status, detail };
184
+ await reporter.insertStep(step, opts.insertBefore ?? lastPhaseKey);
185
+ }
186
+ else {
187
+ await reporter.step(key, status, detail);
188
+ }
189
+ if (opts?.alsoNote && rendered)
190
+ await reporter.note(rendered);
191
+ }
192
+ else if (rendered) {
193
+ await notify(rendered);
194
+ }
195
+ };
196
+ /** Persist a phase transition to the DB workflow run. */
197
+ const persistPhase = (phase, summary) => {
198
+ if (db && workflowId) {
199
+ const entry = {
200
+ phase,
201
+ timestamp: new Date().toISOString(),
202
+ success: true,
203
+ summary,
204
+ };
205
+ db.runs.appendPhase(workflowId, phase, entry);
206
+ }
207
+ };
208
+ /** Mark the workflow run as failed. */
209
+ const failWorkflow = (errorMsg) => {
210
+ if (db && workflowId) {
211
+ db.runs.finishRun(workflowId, "failed", { error: errorMsg });
212
+ }
213
+ };
214
+ /** Should an approval gate with this name actually pause the workflow? */
215
+ const gateEnabled = (gateName) => !!gateName && approvalConfig?.[gateName] === true;
216
+ /** Fold a workflow's final synthesized result into the checklist footer. */
217
+ const footer = async (markdown) => {
218
+ if (reporter)
219
+ await reporter.footer(markdown);
220
+ else
221
+ await notify(markdown);
222
+ };
223
+ /** Post the run's completion ping — terminal-ping surfaces (Slack) only. */
224
+ const noteTerminal = async (markdown) => {
225
+ if (reporter)
226
+ await reporter.noteTerminal(markdown);
227
+ };
228
+ // ── Collaborators ───────────────────────────────────────────────────────────
229
+ const runScope = {
230
+ definition,
231
+ ctx,
232
+ config,
233
+ taskId,
234
+ triggerId,
235
+ githubAccess,
236
+ scratch,
237
+ store: db,
238
+ workflowId,
239
+ botName: getBotName(),
240
+ };
241
+ const phaseReporter = {
242
+ onStart,
243
+ onEnd,
244
+ step: reportStep,
245
+ message: notifyMessage,
246
+ approvalNote,
247
+ postNote,
248
+ persistPhase,
249
+ failWorkflow,
250
+ footer,
251
+ noteTerminal,
252
+ };
253
+ const phaseResolver = {
254
+ modelFor,
255
+ variantFor,
256
+ renderPrompt,
257
+ gateEnabled,
258
+ };
259
+ const ports = {
260
+ agent: defaultAgentPort,
261
+ assets: defaultAssetLoader,
262
+ liveness: dockerLivenessPort,
263
+ observability: telemetryObservability,
264
+ verdictReader: fileVerdictReader,
265
+ handlers: new Map([
266
+ ["post-review", makePostReviewHandler({ ctx, config, taskId, store: db, workflowId }, phaseReporter)],
267
+ ]),
268
+ };
269
+ return runWorkflowCore(runScope, {
270
+ reporter: phaseReporter,
271
+ resolver: phaseResolver,
272
+ ports,
273
+ store: db,
274
+ reporterActive: !!reporter,
275
+ capabilities: { qaImageAvailable, qaImageName: SANDBOX_IMAGE_QA },
276
+ }, outputs);
277
+ }
278
+ //# sourceMappingURL=runner.js.map