lastlight-core 0.23.7 → 0.24.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 (131) hide show
  1. package/deploy/.env.production.example +3 -1
  2. package/deploy/k8s/harness-deployment.yaml +1 -0
  3. package/deploy/native/lastlight.env.example +3 -1
  4. package/dist/admin/routes.js +54 -24
  5. package/dist/admin/routes.js.map +1 -1
  6. package/dist/admin/tail.js +3 -1
  7. package/dist/admin/tail.js.map +1 -1
  8. package/dist/config/config.d.ts +11 -2
  9. package/dist/config/config.js +17 -10
  10. package/dist/config/config.js.map +1 -1
  11. package/dist/config/repo-config.js +6 -4
  12. package/dist/config/repo-config.js.map +1 -1
  13. package/dist/connectors/github-webhook.d.ts +12 -0
  14. package/dist/connectors/github-webhook.js +59 -17
  15. package/dist/connectors/github-webhook.js.map +1 -1
  16. package/dist/connectors/index.js +5 -3
  17. package/dist/connectors/index.js.map +1 -1
  18. package/dist/connectors/messaging/base.js +7 -1
  19. package/dist/connectors/messaging/base.js.map +1 -1
  20. package/dist/connectors/messaging/delivery.d.ts +0 -4
  21. package/dist/connectors/messaging/delivery.js +5 -3
  22. package/dist/connectors/messaging/delivery.js.map +1 -1
  23. package/dist/connectors/messaging/session-manager.js +3 -1
  24. package/dist/connectors/messaging/session-manager.js.map +1 -1
  25. package/dist/connectors/slack/connector.js +24 -15
  26. package/dist/connectors/slack/connector.js.map +1 -1
  27. package/dist/cron/fanout.js +14 -4
  28. package/dist/cron/fanout.js.map +1 -1
  29. package/dist/cron/jobs.js +6 -2
  30. package/dist/cron/jobs.js.map +1 -1
  31. package/dist/cron/repo-crons.js +7 -2
  32. package/dist/cron/repo-crons.js.map +1 -1
  33. package/dist/cron/sandbox-sweep.js +3 -1
  34. package/dist/cron/sandbox-sweep.js.map +1 -1
  35. package/dist/cron/scheduler.js +11 -9
  36. package/dist/cron/scheduler.js.map +1 -1
  37. package/dist/engine/agent-executor.js +85 -36
  38. package/dist/engine/agent-executor.js.map +1 -1
  39. package/dist/engine/chat/chat-runner.js +9 -3
  40. package/dist/engine/chat/chat-runner.js.map +1 -1
  41. package/dist/engine/chat/chat.js +12 -5
  42. package/dist/engine/chat/chat.js.map +1 -1
  43. package/dist/engine/chat/message-batcher.js +3 -1
  44. package/dist/engine/chat/message-batcher.js.map +1 -1
  45. package/dist/engine/dispatcher.js +35 -26
  46. package/dist/engine/dispatcher.js.map +1 -1
  47. package/dist/engine/event-shim.js +3 -2
  48. package/dist/engine/event-shim.js.map +1 -1
  49. package/dist/engine/executors/orchestrator.js +5 -5
  50. package/dist/engine/executors/orchestrator.js.map +1 -1
  51. package/dist/engine/executors/shared.js +16 -14
  52. package/dist/engine/executors/shared.js.map +1 -1
  53. package/dist/engine/fix-harvest.js +3 -2
  54. package/dist/engine/fix-harvest.js.map +1 -1
  55. package/dist/engine/github/app-jwt.d.ts +12 -0
  56. package/dist/engine/github/app-jwt.js +25 -0
  57. package/dist/engine/github/app-jwt.js.map +1 -0
  58. package/dist/engine/github/git-auth.js +14 -19
  59. package/dist/engine/github/git-auth.js.map +1 -1
  60. package/dist/engine/github/github-app-client.js +14 -5
  61. package/dist/engine/github/github-app-client.js.map +1 -1
  62. package/dist/engine/github/github-tools.d.ts +16 -4
  63. package/dist/engine/github/github-tools.js +58 -3
  64. package/dist/engine/github/github-tools.js.map +1 -1
  65. package/dist/engine/github/github.d.ts +68 -9
  66. package/dist/engine/github/github.js +167 -42
  67. package/dist/engine/github/github.js.map +1 -1
  68. package/dist/engine/github/installations.d.ts +129 -0
  69. package/dist/engine/github/installations.js +264 -0
  70. package/dist/engine/github/installations.js.map +1 -0
  71. package/dist/engine/pr-escalation.js +42 -22
  72. package/dist/engine/pr-escalation.js.map +1 -1
  73. package/dist/engine/pr-state.js +4 -2
  74. package/dist/engine/pr-state.js.map +1 -1
  75. package/dist/engine/review-check.js +21 -16
  76. package/dist/engine/review-check.js.map +1 -1
  77. package/dist/engine/router.js +38 -15
  78. package/dist/engine/router.js.map +1 -1
  79. package/dist/engine/screen/classifier.js +7 -6
  80. package/dist/engine/screen/classifier.js.map +1 -1
  81. package/dist/engine/screen/screen.js +3 -2
  82. package/dist/engine/screen/screen.js.map +1 -1
  83. package/dist/index.js +218 -115
  84. package/dist/index.js.map +1 -1
  85. package/dist/logging/logger.d.ts +7 -0
  86. package/dist/logging/logger.js +55 -0
  87. package/dist/logging/logger.js.map +1 -0
  88. package/dist/managed-repos.d.ts +14 -7
  89. package/dist/managed-repos.js +48 -22
  90. package/dist/managed-repos.js.map +1 -1
  91. package/dist/notify/notifier.js +5 -6
  92. package/dist/notify/notifier.js.map +1 -1
  93. package/dist/sandbox/docker.js +7 -5
  94. package/dist/sandbox/docker.js.map +1 -1
  95. package/dist/sandbox/index.js +65 -32
  96. package/dist/sandbox/index.js.map +1 -1
  97. package/dist/sandbox/k8s/artifact-upload-route.js +3 -1
  98. package/dist/sandbox/k8s/artifact-upload-route.js.map +1 -1
  99. package/dist/sandbox/k8s/egress-ensurer.js +4 -3
  100. package/dist/sandbox/k8s/egress-ensurer.js.map +1 -1
  101. package/dist/sandbox/k8s/pod-lifecycle.js +4 -2
  102. package/dist/sandbox/k8s/pod-lifecycle.js.map +1 -1
  103. package/dist/sandbox/k8s/reclaim.js +14 -5
  104. package/dist/sandbox/k8s/reclaim.js.map +1 -1
  105. package/dist/sandbox/k8s/sweep.js +3 -2
  106. package/dist/sandbox/k8s/sweep.js.map +1 -1
  107. package/dist/sandbox/reap.js +5 -4
  108. package/dist/sandbox/reap.js.map +1 -1
  109. package/dist/sandbox/sandbox.js +2 -1
  110. package/dist/sandbox/sandbox.js.map +1 -1
  111. package/dist/sandbox/smol.js +12 -9
  112. package/dist/sandbox/smol.js.map +1 -1
  113. package/dist/state/workflow-run-store.js +3 -2
  114. package/dist/state/workflow-run-store.js.map +1 -1
  115. package/dist/telemetry/index.js +7 -7
  116. package/dist/telemetry/index.js.map +1 -1
  117. package/dist/workflows/admission.js +6 -8
  118. package/dist/workflows/admission.js.map +1 -1
  119. package/dist/workflows/handlers/post-review.js +5 -4
  120. package/dist/workflows/handlers/post-review.js.map +1 -1
  121. package/dist/workflows/pr-scope.js +8 -6
  122. package/dist/workflows/pr-scope.js.map +1 -1
  123. package/dist/workflows/resume.js +27 -28
  124. package/dist/workflows/resume.js.map +1 -1
  125. package/dist/workflows/runner.js +9 -8
  126. package/dist/workflows/runner.js.map +1 -1
  127. package/dist/workflows/simple.js +28 -16
  128. package/dist/workflows/simple.js.map +1 -1
  129. package/dist/worktree/manager.js +6 -4
  130. package/dist/worktree/manager.js.map +1 -1
  131. package/package.json +7 -3
package/dist/index.js CHANGED
@@ -12,6 +12,7 @@ import { configureWorkflowAssets, validateAssets, getWorkflow } from "./workflow
12
12
  import { ChatRunner } from "./engine/chat/chat-runner.js";
13
13
  import { buildReadSkillTool, loadChatSkillCatalogue } from "./engine/chat/chat-skills.js";
14
14
  import { configureGitAuth } from "./engine/github/git-auth.js";
15
+ import { getInstallationDirectory, initInstallationDirectory, } from "./engine/github/installations.js";
15
16
  import { StateDb, isTriggerActorType } from "./state/db.js";
16
17
  import { CronScheduler } from "./cron/scheduler.js";
17
18
  import { getJobs } from "./cron/jobs.js";
@@ -45,6 +46,7 @@ import { harvestFixMarkers } from "./engine/fix-harvest.js";
45
46
  import { resumeOrphanedWorkflows, resumeSimpleRun } from "./workflows/resume.js";
46
47
  import { createAdmissionController } from "./workflows/admission.js";
47
48
  import { ProgressNotifier, GitHubTransport, SlackTransport, } from "./notify/index.js";
49
+ import { logger } from "./logging/logger.js";
48
50
  /**
49
51
  /**
50
52
  * The `review.trigger` ROUTE this dispatch arrived on, off the context key the
@@ -65,15 +67,20 @@ function reviewRouteFromContext(context) {
65
67
  * Docker's restart policy doesn't loop forever on a misconfigured container.
66
68
  */
67
69
  function validateConfig(config) {
68
- const fatal = (msg) => {
69
- console.error(`\n[startup] FATAL: ${msg}`);
70
- console.error("[startup] Fix your .env and restart.\n");
70
+ const log = logger("startup");
71
+ const fatal = (msg, fields) => {
72
+ log.fatal(msg, fields);
73
+ log.fatal("Fix your .env and restart.");
71
74
  process.exit(78); // EX_CONFIG — sysexits.h convention
72
75
  };
73
76
  if (config.githubApp) {
74
- const { appId, privateKeyPath, installationId } = config.githubApp;
75
- if (!appId || !installationId) {
76
- fatal("GITHUB_APP_ID and GITHUB_APP_INSTALLATION_ID are required when the GitHub App is configured.");
77
+ const { appId, privateKeyPath } = config.githubApp;
78
+ // No installation-id check: installations are DISCOVERED from the App JWT
79
+ // and resolved per repo owner, because an App installed on several accounts
80
+ // has one id per account. `GITHUB_APP_INSTALLATION_ID` is honoured as a
81
+ // legacy fallback when set, and is no longer required.
82
+ if (!appId) {
83
+ fatal("GITHUB_APP_ID is required when the GitHub App is configured.");
77
84
  }
78
85
  if (!existsSync(resolve(privateKeyPath))) {
79
86
  fatal(`GITHUB_APP_PRIVATE_KEY_PATH points to "${privateKeyPath}" which does not exist.`);
@@ -85,16 +92,17 @@ function validateConfig(config) {
85
92
  }
86
93
  }
87
94
  catch (err) {
88
- fatal(`Cannot read GITHUB_APP_PRIVATE_KEY_PATH ("${privateKeyPath}"): ${err.message}`);
95
+ fatal(`Cannot read GITHUB_APP_PRIVATE_KEY_PATH ("${privateKeyPath}")`, { err });
89
96
  }
90
97
  }
91
98
  if (!config.webhookSecret && config.githubApp) {
92
- console.warn("[startup] WEBHOOK_SECRET is not set — webhook signature verification is disabled.");
99
+ log.warn("WEBHOOK_SECRET is not set — webhook signature verification is disabled.");
93
100
  }
94
101
  }
95
102
  async function main() {
96
- console.log(`Last Light v${readPackageVersion() ?? "unknown"} — Agent SDK Harness`);
97
- console.log("====================================");
103
+ const startupLog = logger("startup");
104
+ startupLog.info(`Last Light v${readPackageVersion() ?? "unknown"} — Agent SDK Harness`);
105
+ startupLog.info("====================================");
98
106
  // Load and validate config + overlay assets before starting anything. These
99
107
  // throw on a broken/empty overlay, a cron targeting a missing workflow, or a
100
108
  // phase whose prompt/skill can't resolve — all unfixable by a restart, so we
@@ -107,24 +115,31 @@ async function main() {
107
115
  overlayRoot: config.overlayDir,
108
116
  disabled: config.disabled,
109
117
  });
110
- validateAssets(config.routes);
118
+ validateAssets(config.routes, logger("workflows"));
111
119
  }
112
120
  catch (err) {
113
- console.error(`\n[startup] FATAL: ${err.message}`);
114
- console.error("[startup] Fix your config/overlay and restart.\n");
121
+ startupLog.fatal(err.message, { err });
122
+ startupLog.fatal("Fix your config/overlay and restart.");
115
123
  process.exit(78); // EX_CONFIG — sysexits.h convention
116
124
  }
117
125
  validateConfig(config);
118
126
  const packageJson = JSON.parse(readFileSync(resolve("package.json"), "utf8"));
119
127
  await initTelemetry(config.otel, { packageVersion: packageJson.version });
120
128
  let telemetryShutdownStarted = false;
121
- console.log(config.otel.enabled
122
- ? `[otel] enabled service=${config.otel.serviceName} forwardToSandbox=${config.otel.forwardToSandbox} includeContent=${config.otel.includeContent}`
123
- : "[otel] disabled");
124
- console.log(`[config] Port: ${config.port}, Model: ${config.model}`);
129
+ const configLog = logger("config");
130
+ configLog.info(config.otel.enabled ? "otel enabled" : "otel disabled", config.otel.enabled
131
+ ? {
132
+ service: config.otel.serviceName,
133
+ forwardToSandbox: config.otel.forwardToSandbox,
134
+ includeContent: config.otel.includeContent,
135
+ }
136
+ : undefined);
137
+ configLog.info("Port and model", { port: config.port, model: config.model });
125
138
  const modelOverrides = Object.entries(config.models).filter(([k]) => k !== "default");
126
139
  if (modelOverrides.length > 0) {
127
- console.log(`[config] Model overrides: ${modelOverrides.map(([k, v]) => `${k}=${v}`).join(", ")}`);
140
+ configLog.info("Model overrides", {
141
+ overrides: Object.fromEntries(modelOverrides),
142
+ });
128
143
  }
129
144
  // Clean up any sandbox containers left over from a previous run
130
145
  cleanupOrphanedSandboxes();
@@ -132,9 +147,8 @@ async function main() {
132
147
  for (const sub of ["sessions", "logs", "sandboxes"]) {
133
148
  mkdirSync(resolve(config.stateDir, sub), { recursive: true });
134
149
  }
135
- console.log(`[state] State dir: ${config.stateDir}`);
136
- console.log(`[state] Sessions dir: ${config.sessionsDir}`);
137
- console.log(`[config] Sandbox backend: ${config.sandbox}`);
150
+ configLog.info("State dirs", { stateDir: config.stateDir, sessionsDir: config.sessionsDir });
151
+ configLog.info("Sandbox backend", { backend: config.sandbox });
138
152
  // Regenerate egress firewall configs (nginx ssl_preread + coredns) from
139
153
  // the allowlist source of truth. Only meaningful for the docker backend;
140
154
  // cheap enough to do unconditionally so a backend switch doesn't leave
@@ -143,7 +157,7 @@ async function main() {
143
157
  // SNI allowlist no longer needs collector hosts — that hop happens on
144
158
  // the collector's trusted outbound leg, not through the firewall.
145
159
  const proxyDir = writeEgressFirewallConfigs(config.stateDir);
146
- console.log(`[state] Egress firewall configs: ${proxyDir}`);
160
+ configLog.info("Egress firewall configs", { dir: proxyDir });
147
161
  // Generate the in-network OTEL collector config (docker backend). Derived
148
162
  // from the harness's OTEL_* backend env so the collector re-exports to the
149
163
  // same backend the harness uses — with auth headers that stay host-side.
@@ -153,11 +167,14 @@ async function main() {
153
167
  const collectorConfigPath = writeOtelCollectorConfig(config.stateDir, {
154
168
  active: config.otel.enabled && config.otel.forwardToSandbox,
155
169
  });
156
- console.log(`[state] OTEL collector config: ${collectorConfigPath} (forwarding ${config.otel.enabled && config.otel.forwardToSandbox ? "active" : "disabled"})`);
170
+ configLog.info("OTEL collector config", {
171
+ path: collectorConfigPath,
172
+ forwarding: config.otel.enabled && config.otel.forwardToSandbox ? "active" : "disabled",
173
+ });
157
174
  // Initialize state database first — ChatRunner needs SessionManager
158
175
  // (DB-backed) at construction time.
159
176
  const db = new StateDb(config.dbPath);
160
- console.log(`[state] Database: ${config.dbPath}`);
177
+ configLog.info("Database", { path: config.dbPath });
161
178
  // Session manager for messaging connectors (shared across Slack, Discord, etc.)
162
179
  const sessionManager = new SessionManager(db.database);
163
180
  // In-process chat runner backs the messaging chat skill. One pi-ai
@@ -191,27 +208,23 @@ async function main() {
191
208
  ? { tools: [readSkill.tool], execute: readSkill.execute }
192
209
  : undefined,
193
210
  }, sessionManager);
211
+ const chatLog = logger("chat");
194
212
  if (chatSkills.skills.length > 0) {
195
- console.log(`[chat] Loaded ${chatSkills.skills.length} skill(s): ${chatSkills.skills.map((s) => s.name).join(", ")}`);
213
+ chatLog.info("Loaded skills", { names: chatSkills.skills.map((s) => s.name) });
196
214
  }
197
215
  else {
198
- console.warn("[chat] No skills loaded — frontmatter missing or no matching SKILL.md found");
216
+ chatLog.warn("No skills loaded — frontmatter missing or no matching SKILL.md found");
199
217
  }
200
- // Configure git with GitHub App credentials — agents can git clone/push natively.
201
- // Non-fatal: the token is refreshed before each agent execution anyway, so a
202
- // transient failure here (DNS, rate limit) doesn't block startup.
218
+ // The App may be installed on several ACCOUNTS, each with its own installation
219
+ // id — and a token minted against the wrong one is rejected. The directory is
220
+ // the single owner→installation authority every mint and every App-authed
221
+ // Octokit resolves through, so it has to exist before either.
203
222
  if (config.githubApp) {
204
- try {
205
- await configureGitAuth({
206
- appId: config.githubApp.appId,
207
- privateKeyPath: config.githubApp.privateKeyPath,
208
- installationId: config.githubApp.installationId,
209
- botLogin: config.botLogin,
210
- });
211
- }
212
- catch (err) {
213
- console.warn(`[git-auth] Initial token mint failed (will retry per-execution): ${err.message}`);
214
- }
223
+ initInstallationDirectory({
224
+ appId: config.githubApp.appId,
225
+ privateKeyPath: config.githubApp.privateKeyPath,
226
+ fallbackInstallationId: config.githubApp.installationId,
227
+ });
215
228
  }
216
229
  // GitHub API client for harness-level operations (posting comments, fetching
217
230
  // issues). App auth when configured; otherwise a PAT (read-only unless the
@@ -231,20 +244,60 @@ async function main() {
231
244
  botLogin: config.botLogin,
232
245
  botMention: `@${config.botName}`,
233
246
  });
234
- // Discover the repos the App installation can access and seed the managed-repo
235
- // list. When the overlay's `managedRepos` is empty this becomes the effective
236
- // allowlist (getManagedRepos falls back to it); a configured list still wins.
237
- // Kept live afterwards by installation webhooks (github-webhook.ts). Non-fatal:
238
- // on failure we fall back to whatever `managedRepos` config provides. Runs
239
- // before the HTTP listener opens, so the list is warm before the first event.
247
+ // Discover the repos the App can access — across EVERY installation — and seed
248
+ // the managed-repo list. When the overlay's `managedRepos` is empty this
249
+ // becomes the effective allowlist (getManagedRepos falls back to the union); a
250
+ // configured list still wins. Kept live afterwards by installation webhooks
251
+ // (github-webhook.ts). Non-fatal: on failure we fall back to whatever
252
+ // `managedRepos` config provides. Runs before the HTTP listener opens, so the
253
+ // list is warm before the first event.
240
254
  if (github && config.githubApp) {
255
+ const githubLog = logger("github");
241
256
  try {
242
- const repos = await github.listInstallationRepos();
243
- setInstallationRepos(repos);
244
- console.log(`[github] Discovered ${repos.length} installation repos`);
257
+ const grants = await github.listAllInstallationRepos();
258
+ for (const grant of grants) {
259
+ if (grant.error) {
260
+ githubLog.warn("Installation repo discovery failed for one account", {
261
+ account: grant.account,
262
+ installationId: grant.installationId,
263
+ error: grant.error,
264
+ });
265
+ continue;
266
+ }
267
+ setInstallationRepos(grant.installationId, grant.repos);
268
+ }
269
+ githubLog.info("Discovered App installations", {
270
+ installations: grants.length,
271
+ accounts: grants.map((g) => `${g.account}=${g.installationId}(${g.repos.length})`).join(","),
272
+ });
273
+ if (grants.length === 0) {
274
+ githubLog.warn("The GitHub App has no installations — install it on an account before it can act");
275
+ }
245
276
  }
246
277
  catch (err) {
247
- console.warn(`[github] Installation repo discovery failed: ${err.message}`);
278
+ githubLog.warn("Installation discovery failed", { err });
279
+ }
280
+ }
281
+ // Configure git with a GitHub App token — only meaningful when the operator
282
+ // opted into a global `~/.gitconfig` write (LASTLIGHT_WRITE_GLOBAL_GIT=1) and
283
+ // only defensible with a single installation, since a global credential can
284
+ // name exactly one. Every agent run mints its own owner-scoped token
285
+ // regardless, so this is non-fatal and skipped when ambiguous.
286
+ if (config.githubApp) {
287
+ const gitAuthLog = logger("git-auth");
288
+ try {
289
+ const soleInstallation = await getInstallationDirectory()?.soleInstallationId();
290
+ if (soleInstallation) {
291
+ await configureGitAuth({
292
+ appId: config.githubApp.appId,
293
+ privateKeyPath: config.githubApp.privateKeyPath,
294
+ installationId: soleInstallation,
295
+ botLogin: config.botLogin,
296
+ });
297
+ }
298
+ }
299
+ catch (err) {
300
+ gitAuthLog.warn("Initial token mint failed (will retry per-execution)", { err });
248
301
  }
249
302
  }
250
303
  // Late-bound: constructed after resumeOpts (below) because it closes over
@@ -261,6 +314,7 @@ async function main() {
261
314
  * agent skills they're 1:1 with workflow names.
262
315
  */
263
316
  const dispatchWorkflow = async (workflowName, context, onRunStart) => {
317
+ const log = logger("dispatch");
264
318
  // Slack-initiated workflows (explore, /explore) carry a
265
319
  // `slack:{team}:{channel}:{thread}` triggerId and don't require a
266
320
  // managed `repo` — their postComment goes back to the Slack thread.
@@ -270,7 +324,7 @@ async function main() {
270
324
  const repoStr = context.repo;
271
325
  if (!repoStr && !slackTriggerId) {
272
326
  const msg = `dispatchWorkflow(${workflowName}): missing 'repo' in context`;
273
- console.error(`[dispatch] ${msg}`);
327
+ log.error(msg, { workflowName });
274
328
  return { success: false, error: msg };
275
329
  }
276
330
  const [owner, repo] = repoStr && repoStr.includes("/")
@@ -280,7 +334,7 @@ async function main() {
280
334
  : ["", ""];
281
335
  if (repoStr && (!owner || !repo)) {
282
336
  const msg = `dispatchWorkflow(${workflowName}): invalid repo format '${repoStr}'`;
283
- console.error(`[dispatch] ${msg}`);
337
+ log.error(msg, { workflowName, repoStr });
284
338
  return { success: false, error: msg };
285
339
  }
286
340
  // Choke-point managedRepos guard: every trigger path (webhook, router,
@@ -292,7 +346,7 @@ async function main() {
292
346
  const unmanaged = unmanagedReposInContext(context);
293
347
  if (unmanaged.length > 0) {
294
348
  const msg = `dispatchWorkflow(${workflowName}): refusing unmanaged repo(s): ${unmanaged.join(", ")}`;
295
- console.warn(`[dispatch] ${msg}`);
349
+ log.warn(msg, { workflowName, unmanaged });
296
350
  return { success: false, error: msg };
297
351
  }
298
352
  // Per-repository config layer (issue #180). Resolved at the SAME choke
@@ -307,7 +361,7 @@ async function main() {
307
361
  // The repo opting itself out via `disabled.workflows`. Same refusal shape
308
362
  // as the unmanaged-repo guard, so every caller already handles it.
309
363
  const msg = `dispatchWorkflow(${workflowName}): refusing repo-disabled workflow: ${refusal}`;
310
- console.warn(`[dispatch] ${msg}`);
364
+ log.warn(msg, { workflowName, refusal });
311
365
  return { success: false, error: msg };
312
366
  }
313
367
  // ── The PR state machine (09-state-machine.md → S3) ────────────────────
@@ -502,8 +556,12 @@ async function main() {
502
556
  (PR_FIX_SHAPED_WORKFLOWS.has(workflowName) ||
503
557
  PR_HEADREF_PREPOPULATE_WORKFLOWS.has(workflowName))) {
504
558
  prePopulateBranch = prState.headRef;
505
- console.log(`[dispatch] ${workflowName}: pre-populating workspace at ${owner}/${repo}@${prePopulateBranch} ` +
506
- `(base ${prState.baseRef || "?"})`);
559
+ log.info("Pre-populating workspace", {
560
+ workflowName,
561
+ repo: `${owner}/${repo}`,
562
+ branch: prePopulateBranch,
563
+ base: prState.baseRef || "?",
564
+ });
507
565
  }
508
566
  if (!prePopulateBranch && typeof ctxBranch === "string" && ctxBranch && PR_FIX_SHAPED_WORKFLOWS.has(workflowName)) {
509
567
  prePopulateBranch = ctxBranch;
@@ -530,13 +588,18 @@ async function main() {
530
588
  // head ref, so `origin/<base>` isn't present until the agent fetches it).
531
589
  if (pr.base?.ref)
532
590
  extra.baseBranch = pr.base.ref;
533
- console.log(`[dispatch] ${workflowName}: pre-populating workspace at ${owner}/${repo}@${prePopulateBranch} ` +
534
- `(base ${pr.base?.ref ?? "?"})`);
591
+ log.info("Pre-populating workspace", {
592
+ workflowName,
593
+ repo: `${owner}/${repo}`,
594
+ headRef: prePopulateBranch,
595
+ baseRef: pr.base?.ref ?? "?",
596
+ });
535
597
  }
536
598
  catch (err) {
537
- const msg = err instanceof Error ? err.message : String(err);
538
- console.warn(`[dispatch] ${workflowName}: could not resolve PR head ref (${msg}); ` +
539
- `agent will need to clone via MCP`);
599
+ log.warn("Could not resolve PR head ref; agent will need to clone via MCP", {
600
+ workflowName,
601
+ err,
602
+ });
540
603
  }
541
604
  }
542
605
  // Base branch for scoping. PR-triggered runs set it from the PR's base ref
@@ -551,9 +614,11 @@ async function main() {
551
614
  extra.baseBranch = await github.getDefaultBranch(owner, repo);
552
615
  }
553
616
  catch (err) {
554
- const msg = err instanceof Error ? err.message : String(err);
555
- console.warn(`[dispatch] ${workflowName}: could not resolve default branch for ${owner}/${repo} ` +
556
- `(${msg}); assuming main`);
617
+ log.warn("Could not resolve default branch; assuming main", {
618
+ workflowName,
619
+ repo: `${owner}/${repo}`,
620
+ err,
621
+ });
557
622
  extra.baseBranch = "main";
558
623
  }
559
624
  }
@@ -620,13 +685,16 @@ async function main() {
620
685
  // exclusively (avoids double-rendering the body).
621
686
  request.issueBody = "";
622
687
  if (screen.flagged) {
623
- console.warn(`[dispatch] Screener flagged combined issue context for ${owner}/${repo}#${request.issueNumber}: ${screen.reason || "no reason"}`);
688
+ log.warn("Screener flagged combined issue context", {
689
+ repo: `${owner}/${repo}`,
690
+ issueNumber: request.issueNumber,
691
+ reason: screen.reason || "no reason",
692
+ });
624
693
  }
625
694
  }
626
695
  }
627
696
  catch (err) {
628
- const m = err instanceof Error ? err.message : String(err);
629
- console.warn(`[dispatch] Failed to fetch/screen issue context: ${m}`);
697
+ log.warn("Failed to fetch/screen issue context", { err });
630
698
  // Non-fatal — workflow proceeds with whatever context the envelope had.
631
699
  }
632
700
  }
@@ -636,8 +704,7 @@ async function main() {
636
704
  await slackConnector.sendMessage(channelId, threadId, msg);
637
705
  }
638
706
  catch (err) {
639
- const m = err instanceof Error ? err.message : String(err);
640
- console.warn(`[dispatch] Failed to post to Slack thread: ${m}`);
707
+ log.warn("Failed to post to Slack thread", { err });
641
708
  }
642
709
  }
643
710
  : undefined;
@@ -715,8 +782,7 @@ async function main() {
715
782
  notifier = new ProgressNotifier(transports);
716
783
  }
717
784
  catch (err) {
718
- const m = err instanceof Error ? err.message : String(err);
719
- console.warn(`[dispatch] notifier setup failed: ${m}`);
785
+ log.warn("Notifier setup failed", { err });
720
786
  }
721
787
  }
722
788
  : undefined;
@@ -732,13 +798,12 @@ async function main() {
732
798
  return await github.postComment(owner, repo, issueNumber, msg);
733
799
  }
734
800
  catch (err) {
735
- const m = err instanceof Error ? err.message : String(err);
736
- console.warn(`[dispatch] Failed to post comment: ${m}`);
801
+ log.warn("Failed to post comment", { err });
737
802
  }
738
803
  }
739
804
  : undefined),
740
805
  onPhaseStart: async (phase) => {
741
- console.log(`[dispatch] ▶ ${workflowName}/${phase}`);
806
+ log.info("Phase start", { workflowName, phase });
742
807
  // Refresh the Slack thinking indicator so long-running phases
743
808
  // don't leave the thread looking dead. threadId doubles as both
744
809
  // the message anchor and the thread root for DM threads.
@@ -747,7 +812,7 @@ async function main() {
747
812
  }
748
813
  },
749
814
  onPhaseEnd: async (phase, result) => {
750
- console.log(`[dispatch] ◀ ${workflowName}/${phase}: ${result.success ? "OK" : "FAILED"}`);
815
+ log.info("Phase end", { workflowName, phase, success: result.success });
751
816
  // The marker harvest (09 → S1). This is the ONLY moment the two marker
752
817
  // lines exist in memory — `{{phaseOutputs}}` is empty across a run
753
818
  // boundary and the shared per-PR workspace is `reset --hard`-ed between
@@ -790,7 +855,7 @@ async function main() {
790
855
  }, callbacks, db, config.models, config.approval, config.bootstrapLabel, config.variants, config.concurrency);
791
856
  const summary = result.phases.map((p) => `${p.phase}=${p.success ? "ok" : "fail"}`).join(", ");
792
857
  if (result.queued) {
793
- console.log(`[dispatch] ${workflowName} queued (concurrency cap reached)`);
858
+ log.info("Queued (concurrency cap reached)", { workflowName });
794
859
  // A queued run never reaches `onRunStart` — `runSimpleWorkflow` returns
795
860
  // the moment it writes the `queued` row — so bind the check here instead
796
861
  // of leaving the run's only PR-visible artifact unowned. The row is
@@ -801,19 +866,19 @@ async function main() {
801
866
  await bindReviewCheckForQueuedRun();
802
867
  }
803
868
  else if (result.paused) {
804
- console.log(`[dispatch] ${workflowName} paused (${summary})`);
869
+ log.info("Paused", { workflowName, summary });
805
870
  }
806
871
  else if (result.success) {
807
- console.log(`[dispatch] ${workflowName} completed (${summary})`);
872
+ log.info("Completed", { workflowName, summary });
808
873
  }
809
874
  else {
810
- console.warn(`[dispatch] ${workflowName} failed (${summary})`);
875
+ log.warn("Failed", { workflowName, summary });
811
876
  }
812
877
  return { success: result.success, paused: result.paused, queued: result.queued };
813
878
  }
814
879
  catch (err) {
815
880
  const msg = err instanceof Error ? err.message : String(err);
816
- console.error(`[dispatch] ${workflowName} threw: ${msg}`);
881
+ log.error("Threw", { workflowName, err });
817
882
  return { success: false, error: msg };
818
883
  }
819
884
  finally {
@@ -824,8 +889,7 @@ async function main() {
824
889
  // retry.
825
890
  if (!result?.backpressure) {
826
891
  admissionController?.admitNext().catch((err) => {
827
- const msg = err instanceof Error ? err.message : String(err);
828
- console.warn(`[admission] admitNext error: ${msg}`);
892
+ logger("admission").warn("admitNext error", { err });
829
893
  });
830
894
  }
831
895
  }
@@ -870,6 +934,9 @@ async function main() {
870
934
  // and a repo that opts itself into `after-checks` under an `eager`
871
935
  // operator is covered by the 30-minute `check-prs-awaiting-review` sweep.
872
936
  reviewTrigger: () => config.review.trigger,
937
+ // The harness client memoizes an Octokit per installation; drop it when
938
+ // the App is uninstalled so a re-install can't be served by a dead one.
939
+ onInstallationRemoved: (installationId) => github?.forgetInstallation(installationId),
873
940
  });
874
941
  registry.register(githubConnector);
875
942
  }
@@ -929,6 +996,7 @@ async function main() {
929
996
  // `dispatchWorkflow`, which is defined earlier in this file. Named (not inline)
930
997
  // so the admin `triggerCron` callback can reuse it to fire a cron on demand.
931
998
  const cronRunner = async (workflowName, context) => {
999
+ const log = logger("cron");
932
1000
  let dispatched;
933
1001
  let failures;
934
1002
  // A cron whose context sets `discover: <key>` fans out one bounded single-PR
@@ -964,14 +1032,27 @@ async function main() {
964
1032
  })).repos
965
1033
  : candidates;
966
1034
  if (repos.length !== candidates.length) {
967
- console.log(`[cron] ${cronName}: ${repos.length}/${candidates.length} repo(s) participate in this cron`);
1035
+ log.info("Repo(s) participate in this cron", {
1036
+ cronName,
1037
+ participating: repos.length,
1038
+ candidates: candidates.length,
1039
+ });
968
1040
  }
969
1041
  // Every repo opted out (or a globally-off cron nobody opted into) — no
970
1042
  // discovery calls, no dispatches, no failure. A cheap no-op tick.
1043
+ // The discoverer's `log` callback only carries per-repo/per-candidate
1044
+ // diagnostics (a skipped malformed repo, a failed listing/fetch) — one
1045
+ // of these can fire per managed repo on every tick, so it's `.debug`,
1046
+ // not `.info`. The once-per-tick summary below stays `.info`.
971
1047
  const prs = github && repos.length
972
- ? await discoverer(repos, github, { log: (m) => console.log(m) })
1048
+ ? await discoverer(repos, github, { log: (m) => log.debug(m) })
973
1049
  : [];
974
- console.log(`[cron] ${workflowName}: ${prs.length} ${discoverKey} across ${repos.length} repo(s)`);
1050
+ log.info("Discovered PRs", {
1051
+ workflowName,
1052
+ discoverKey,
1053
+ count: prs.length,
1054
+ repoCount: repos.length,
1055
+ });
975
1056
  const contexts = prs.map((pr) => ({
976
1057
  _triggerType: "cron",
977
1058
  repo: pr.repo,
@@ -996,7 +1077,7 @@ async function main() {
996
1077
  ({ dispatched, failures } = await dispatchCronWorkflow(workflowName, context, dispatchWorkflow));
997
1078
  }
998
1079
  if (failures > 0) {
999
- console.warn(`[cron] ${workflowName}: ${failures}/${dispatched} dispatches failed`);
1080
+ log.warn("Dispatches failed", { workflowName, failures, dispatched });
1000
1081
  }
1001
1082
  };
1002
1083
  const cron = new CronScheduler(db, cronRunner);
@@ -1039,6 +1120,7 @@ async function main() {
1039
1120
  });
1040
1121
  // Mount admin dashboard on the shared HTTP server (always available).
1041
1122
  {
1123
+ const adminLog = logger("admin");
1042
1124
  mountAdmin(app, db, {
1043
1125
  cronScheduler: cron,
1044
1126
  triggerCron: cronRunner,
@@ -1073,7 +1155,7 @@ async function main() {
1073
1155
  githubAllowedOrg: process.env.GITHUB_ALLOWED_ORG,
1074
1156
  resumeWorkflow: async (workflowRun, sender) => {
1075
1157
  if (!github) {
1076
- console.warn(`[admin] Cannot resume workflow ${workflowRun.id}: GitHub App not configured`);
1158
+ adminLog.warn("Cannot resume workflow: GitHub App not configured", { runId: workflowRun.id });
1077
1159
  return;
1078
1160
  }
1079
1161
  // Derive owner/repo for the resume dispatch. Prefer the triggerId
@@ -1091,11 +1173,16 @@ async function main() {
1091
1173
  }
1092
1174
  const issueNumber = workflowRun.issueNumber;
1093
1175
  if (!owner || !repo || !issueNumber) {
1094
- console.warn(`[admin] Cannot resume workflow ${workflowRun.id}: missing owner/repo/issueNumber`);
1176
+ adminLog.warn("Cannot resume workflow: missing owner/repo/issueNumber", { runId: workflowRun.id });
1095
1177
  return;
1096
1178
  }
1097
1179
  db.runs.setRunning(workflowRun.id);
1098
- console.log(`[admin] Resuming ${workflowRun.workflowName} for ${owner}/${repo}#${issueNumber} after dashboard approval by ${sender}`);
1180
+ adminLog.info("Resuming after dashboard approval", {
1181
+ workflowName: workflowRun.workflowName,
1182
+ repo: `${owner}/${repo}`,
1183
+ issueNumber,
1184
+ sender,
1185
+ });
1099
1186
  dispatchWorkflow(workflowRun.workflowName, {
1100
1187
  repo: `${owner}/${repo}`,
1101
1188
  issueNumber,
@@ -1103,7 +1190,7 @@ async function main() {
1103
1190
  body: "",
1104
1191
  sender,
1105
1192
  _triggerType: "admin",
1106
- }).catch((err) => console.error(`[admin] Resume failed:`, err));
1193
+ }).catch((err) => adminLog.error("Resume failed", { err }));
1107
1194
  },
1108
1195
  // Retry a FAILED or CANCELLED run, resuming from where it stopped with the
1109
1196
  // same context. Unlike `resumeWorkflow` (approval-gate resume, which
@@ -1116,7 +1203,10 @@ async function main() {
1116
1203
  // phases and starts clean.
1117
1204
  retryWorkflow: async (workflowRun, sender) => {
1118
1205
  if (workflowRun.status !== "failed" && workflowRun.status !== "cancelled") {
1119
- console.warn(`[admin] Cannot retry ${workflowRun.id}: status is '${workflowRun.status}', not 'failed' or 'cancelled'`);
1206
+ adminLog.warn("Cannot retry: not in a retryable status", {
1207
+ runId: workflowRun.id,
1208
+ status: workflowRun.status,
1209
+ });
1120
1210
  return;
1121
1211
  }
1122
1212
  // Compare-and-set: flip failed/cancelled→running and clear the terminal
@@ -1124,17 +1214,24 @@ async function main() {
1124
1214
  // dispatch.
1125
1215
  const changed = db.runs.restartRun(workflowRun.id);
1126
1216
  if (changed !== 1) {
1127
- console.warn(`[admin] Retry ${workflowRun.id}: run is no longer retryable (raced) — skipping dispatch`);
1217
+ adminLog.warn("Retry: run is no longer retryable (raced) — skipping dispatch", {
1218
+ runId: workflowRun.id,
1219
+ });
1128
1220
  return;
1129
1221
  }
1130
1222
  const fresh = db.runs.getRun(workflowRun.id);
1131
1223
  if (!fresh)
1132
1224
  return;
1133
- console.log(`[admin] Retrying ${fresh.workflowName} run ${fresh.id} (was on phase=${workflowRun.currentPhase}) by ${sender}`);
1134
- resumeSimpleRun(fresh, resumeOpts).catch((err) => console.error(`[admin] Retry ${fresh.id} failed:`, err));
1225
+ adminLog.info("Retrying", {
1226
+ workflowName: fresh.workflowName,
1227
+ runId: fresh.id,
1228
+ previousPhase: workflowRun.currentPhase,
1229
+ sender,
1230
+ });
1231
+ resumeSimpleRun(fresh, resumeOpts).catch((err) => adminLog.error("Retry failed", { runId: fresh.id, err }));
1135
1232
  },
1136
1233
  });
1137
- console.log(`[admin] Dashboard mounted at /admin`);
1234
+ adminLog.info("Dashboard mounted at /admin");
1138
1235
  }
1139
1236
  // Protect API endpoints with auth when any login method is configured
1140
1237
  // (password OR OAuth) — same gate as the dashboard, via the shared helper.
@@ -1148,9 +1245,10 @@ async function main() {
1148
1245
  githubOAuthClientSecret: process.env.GITHUB_OAUTH_CLIENT_SECRET,
1149
1246
  githubAllowedOrg: process.env.GITHUB_ALLOWED_ORG,
1150
1247
  });
1248
+ const apiLog = logger("api");
1151
1249
  if (apiAuthEnabled) {
1152
1250
  app.use("/api/*", authMiddleware(apiAuthEnabled, adminSecret));
1153
- console.log(`[api] API endpoints protected with auth`);
1251
+ apiLog.info("API endpoints protected with auth");
1154
1252
  }
1155
1253
  // API endpoint for CLI triggers
1156
1254
  app.post("/api/run", async (c) => {
@@ -1170,7 +1268,7 @@ async function main() {
1170
1268
  if (unmanaged.length > 0) {
1171
1269
  return c.json({ error: `Repo not managed: ${unmanaged.join(", ")}` }, 403);
1172
1270
  }
1173
- console.log(`[api] CLI triggered: workflow=${workflowName}`);
1271
+ apiLog.info("CLI triggered", { workflowName });
1174
1272
  // Run asynchronously — return immediately with a stable id the caller
1175
1273
  // can correlate with workflow_runs in the dashboard.
1176
1274
  const executionId = randomUUID();
@@ -1183,8 +1281,7 @@ async function main() {
1183
1281
  ...(apiActor ? { triggeredBy: apiActor } : {}),
1184
1282
  _triggerType: "api",
1185
1283
  }).catch((err) => {
1186
- const msg = err instanceof Error ? err.message : String(err);
1187
- console.error(`[api] workflow ${workflowName} failed: ${msg}`);
1284
+ apiLog.error("Workflow failed", { workflowName, err });
1188
1285
  });
1189
1286
  return c.json({ accepted: true, executionId, workflow: workflowName }, 202);
1190
1287
  });
@@ -1198,7 +1295,7 @@ async function main() {
1198
1295
  if (!isManagedRepo(`${owner}/${repo}`)) {
1199
1296
  return c.json({ error: `Repo not managed: ${owner}/${repo}` }, 403);
1200
1297
  }
1201
- console.log(`[api] CLI build triggered: ${owner}/${repo}#${issueNumber}`);
1298
+ apiLog.info("CLI build triggered", { repo: `${owner}/${repo}`, issueNumber });
1202
1299
  // If labels weren't supplied, fetch them so the orchestrator can detect
1203
1300
  // bootstrap tasks (lastlight:bootstrap label) and skip the BLOCKED gate.
1204
1301
  let resolvedLabels = issueLabels;
@@ -1222,7 +1319,7 @@ async function main() {
1222
1319
  ...(actorFromContext(c) ? { triggeredBy: actorFromContext(c) } : {}),
1223
1320
  _triggerType: "api",
1224
1321
  }).catch((err) => {
1225
- console.error(`[api] Build failed:`, err);
1322
+ apiLog.error("Build failed", { err });
1226
1323
  });
1227
1324
  return c.json({ accepted: true, owner, repo, issueNumber }, 202);
1228
1325
  });
@@ -1305,20 +1402,25 @@ async function main() {
1305
1402
  });
1306
1403
  return c.json({ text: reply, thread: threadId ?? session.id, sessionId: session.id, outcome: outcome.kind });
1307
1404
  });
1405
+ const eventLog = logger("event");
1308
1406
  const handleEnvelope = async (envelope) => {
1309
- console.log(`[event] ${envelope.source}:${envelope.type} from ${envelope.sender}${envelope.repo ? ` on ${envelope.repo}` : ""}`);
1407
+ eventLog.info("Received", {
1408
+ source: envelope.source,
1409
+ type: envelope.type,
1410
+ sender: envelope.sender,
1411
+ repo: envelope.repo,
1412
+ });
1310
1413
  try {
1311
1414
  const outcome = await dispatch(envelope, dispatchDeps);
1312
1415
  if (outcome.kind === "ignored") {
1313
- console.log(`[event] Ignored: ${outcome.reason}`);
1416
+ eventLog.info("Ignored", { reason: outcome.reason });
1314
1417
  }
1315
1418
  else if (outcome.kind === "skipped") {
1316
- console.log(`[event] Skipped: ${outcome.reason}`);
1419
+ eventLog.info("Skipped", { reason: outcome.reason });
1317
1420
  }
1318
1421
  }
1319
1422
  catch (err) {
1320
- const msg = err instanceof Error ? err.message : String(err);
1321
- console.error(`[event] dispatch threw: ${msg}`);
1423
+ eventLog.error("Dispatch threw", { err });
1322
1424
  }
1323
1425
  };
1324
1426
  // Batch bursty messaging input per session BEFORE routing: a rapid Slack
@@ -1352,11 +1454,11 @@ async function main() {
1352
1454
  cron.register(job);
1353
1455
  }
1354
1456
  if (webhooksEnabled) {
1355
- console.log("[cron] Webhooks enabled — skipping issue/PR polling crons");
1457
+ logger("cron").info("Webhooks enabled — skipping issue/PR polling crons");
1356
1458
  }
1357
1459
  }
1358
1460
  else {
1359
- console.log("[cron] No GitHub client — skipping all cron jobs (chat-only mode)");
1461
+ logger("cron").info("No GitHub client — skipping all cron jobs (chat-only mode)");
1360
1462
  }
1361
1463
  // Sandbox-workspace reaping backstop (issue #106) — a DIRECT (non-sandboxed)
1362
1464
  // job, registered regardless of `github` so it runs in chat-only mode too.
@@ -1394,15 +1496,16 @@ async function main() {
1394
1496
  });
1395
1497
  }
1396
1498
  // Start everything
1499
+ const mainLog = logger("main");
1397
1500
  await registry.startAll();
1398
- console.log("[main] All connectors started");
1399
- console.log("[main] Cron jobs registered");
1501
+ mainLog.info("All connectors started");
1502
+ mainLog.info("Cron jobs registered");
1400
1503
  // Open the shared HTTP listener. All routes (admin, /api/*, /health,
1401
1504
  // /webhooks/github, /webhooks/slack) are registered synchronously above, so
1402
1505
  // the port is ready the moment it opens. Always boots — chat-only, PAT, and
1403
1506
  // full GitHub App modes alike.
1404
1507
  const server = serve({ fetch: app.fetch, port: config.port, hostname: "0.0.0.0" });
1405
- console.log(`[http] Listening on port ${config.port}`);
1508
+ logger("http").info("Listening", { port: config.port });
1406
1509
  // Chat runs in-process via pi-ai — no long-lived server to boot.
1407
1510
  // Boot-time recovery: any workflow_runs left in 'running' state from a
1408
1511
  // previous harness lifetime have already had their sandbox containers
@@ -1410,15 +1513,15 @@ async function main() {
1410
1513
  // failed and re-dispatch each run so the runner can pick up after the last
1411
1514
  // completed phase. Skips 'paused' runs — those intentionally wait for a
1412
1515
  // human approval and are resumed via the dashboard / GitHub comment flow.
1413
- resumeOrphanedWorkflows(resumeOpts).catch((err) => console.error("[main] Resume sweep failed:", err));
1516
+ resumeOrphanedWorkflows(resumeOpts).catch((err) => mainLog.error("Resume sweep failed", { err }));
1414
1517
  // Start the periodic admission sweeper. Also admits any queued runs that
1415
1518
  // were persisted before the harness restarted (e.g. a queued run survived
1416
1519
  // a crash; the sweeper picks it up on the first tick).
1417
1520
  admissionController.start();
1418
- console.log("[main] Ready to receive events");
1521
+ mainLog.info("Ready to receive events");
1419
1522
  // Graceful shutdown
1420
1523
  const shutdown = async () => {
1421
- console.log("\n[main] Shutting down...");
1524
+ mainLog.info("Shutting down");
1422
1525
  cron.stopAll();
1423
1526
  admissionController.stop();
1424
1527
  await registry.stopAll();
@@ -1436,7 +1539,7 @@ async function main() {
1436
1539
  process.on("SIGTERM", shutdown);
1437
1540
  }
1438
1541
  main().catch((err) => {
1439
- console.error("[main] Fatal error:", err);
1542
+ logger("main").fatal("Fatal error", { err });
1440
1543
  // Exit 78 (EX_CONFIG) to signal Docker restart policy that looping won't help.
1441
1544
  // Common causes: bad PEM, wrong App ID, missing env vars.
1442
1545
  const msg = err?.message || "";