@codyswann/lisa 4.106.0 → 4.106.2

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 (153) hide show
  1. package/dist/core/lisa.d.ts +21 -0
  2. package/dist/core/lisa.d.ts.map +1 -1
  3. package/dist/core/lisa.js +48 -0
  4. package/dist/core/lisa.js.map +1 -1
  5. package/dist/core/nightly-e2e-guard-behavior-certificate.js +2 -2
  6. package/dist/core/upstream-evidence-manifest.d.ts.map +1 -1
  7. package/dist/core/upstream-evidence-manifest.js +36 -11
  8. package/dist/core/upstream-evidence-manifest.js.map +1 -1
  9. package/dist/sonar/sonar-shim-fs.d.ts +32 -0
  10. package/dist/sonar/sonar-shim-fs.d.ts.map +1 -0
  11. package/dist/sonar/sonar-shim-fs.js +70 -0
  12. package/dist/sonar/sonar-shim-fs.js.map +1 -0
  13. package/dist/sonar/sonar-shim-repoint.d.ts +71 -0
  14. package/dist/sonar/sonar-shim-repoint.d.ts.map +1 -0
  15. package/dist/sonar/sonar-shim-repoint.js +221 -0
  16. package/dist/sonar/sonar-shim-repoint.js.map +1 -0
  17. package/package.json +4 -4
  18. package/plugins/lisa/.claude-plugin/plugin.json +1 -1
  19. package/plugins/lisa/.codex-plugin/plugin.json +1 -1
  20. package/plugins/lisa/.codex-plugin/skills/lisa-session-manager/SKILL.md +9 -3
  21. package/plugins/lisa/.codex-plugin/skills/lisa-session-manager/scripts/cli-cycle.mjs +5 -0
  22. package/plugins/lisa/.codex-plugin/skills/lisa-session-manager/scripts/cli-usage.mjs +18 -5
  23. package/plugins/lisa/.codex-plugin/skills/lisa-session-manager/scripts/cli-workers.mjs +67 -3
  24. package/plugins/lisa/.codex-plugin/skills/lisa-session-manager/scripts/first-prompt.mjs +221 -0
  25. package/plugins/lisa/.codex-plugin/skills/lisa-session-manager/scripts/ledger.mjs +25 -3
  26. package/plugins/lisa/.codex-plugin/skills/lisa-session-manager/scripts/session-manager.mjs +4 -1
  27. package/plugins/lisa/.codex-plugin/skills/lisa-session-manager/scripts/worker-launch.mjs +91 -0
  28. package/plugins/lisa/.codex-plugin/skills/lisa-session-manager/scripts/workers.mjs +10 -5
  29. package/plugins/lisa/skills/lisa-session-manager/SKILL.md +9 -3
  30. package/plugins/lisa/skills/lisa-session-manager/scripts/cli-cycle.mjs +5 -0
  31. package/plugins/lisa/skills/lisa-session-manager/scripts/cli-usage.mjs +18 -5
  32. package/plugins/lisa/skills/lisa-session-manager/scripts/cli-workers.mjs +67 -3
  33. package/plugins/lisa/skills/lisa-session-manager/scripts/first-prompt.mjs +221 -0
  34. package/plugins/lisa/skills/lisa-session-manager/scripts/ledger.mjs +25 -3
  35. package/plugins/lisa/skills/lisa-session-manager/scripts/session-manager.mjs +4 -1
  36. package/plugins/lisa/skills/lisa-session-manager/scripts/worker-launch.mjs +91 -0
  37. package/plugins/lisa/skills/lisa-session-manager/scripts/workers.mjs +10 -5
  38. package/plugins/lisa-agy/plugin.json +1 -1
  39. package/plugins/lisa-agy/skills/lisa-session-manager/SKILL.md +9 -3
  40. package/plugins/lisa-agy/skills/lisa-session-manager/scripts/cli-cycle.mjs +5 -0
  41. package/plugins/lisa-agy/skills/lisa-session-manager/scripts/cli-usage.mjs +18 -5
  42. package/plugins/lisa-agy/skills/lisa-session-manager/scripts/cli-workers.mjs +67 -3
  43. package/plugins/lisa-agy/skills/lisa-session-manager/scripts/first-prompt.mjs +221 -0
  44. package/plugins/lisa-agy/skills/lisa-session-manager/scripts/ledger.mjs +25 -3
  45. package/plugins/lisa-agy/skills/lisa-session-manager/scripts/session-manager.mjs +4 -1
  46. package/plugins/lisa-agy/skills/lisa-session-manager/scripts/worker-launch.mjs +91 -0
  47. package/plugins/lisa-agy/skills/lisa-session-manager/scripts/workers.mjs +10 -5
  48. package/plugins/lisa-cdk/.claude-plugin/plugin.json +1 -1
  49. package/plugins/lisa-cdk/.codex-plugin/plugin.json +1 -1
  50. package/plugins/lisa-cdk-agy/plugin.json +1 -1
  51. package/plugins/lisa-cdk-copilot/.claude-plugin/plugin.json +1 -1
  52. package/plugins/lisa-cdk-cursor/.claude-plugin/plugin.json +1 -1
  53. package/plugins/lisa-cdk-devin/.claude-plugin/plugin.json +1 -1
  54. package/plugins/lisa-cdk-devin/.devin-plugin/plugin.json +1 -1
  55. package/plugins/lisa-copilot/.claude-plugin/plugin.json +1 -1
  56. package/plugins/lisa-copilot/skills/lisa-session-manager/SKILL.md +9 -3
  57. package/plugins/lisa-copilot/skills/lisa-session-manager/scripts/cli-cycle.mjs +5 -0
  58. package/plugins/lisa-copilot/skills/lisa-session-manager/scripts/cli-usage.mjs +18 -5
  59. package/plugins/lisa-copilot/skills/lisa-session-manager/scripts/cli-workers.mjs +67 -3
  60. package/plugins/lisa-copilot/skills/lisa-session-manager/scripts/first-prompt.mjs +221 -0
  61. package/plugins/lisa-copilot/skills/lisa-session-manager/scripts/ledger.mjs +25 -3
  62. package/plugins/lisa-copilot/skills/lisa-session-manager/scripts/session-manager.mjs +4 -1
  63. package/plugins/lisa-copilot/skills/lisa-session-manager/scripts/worker-launch.mjs +91 -0
  64. package/plugins/lisa-copilot/skills/lisa-session-manager/scripts/workers.mjs +10 -5
  65. package/plugins/lisa-cursor/.claude-plugin/plugin.json +1 -1
  66. package/plugins/lisa-cursor/skills/lisa-session-manager/SKILL.md +9 -3
  67. package/plugins/lisa-cursor/skills/lisa-session-manager/scripts/cli-cycle.mjs +5 -0
  68. package/plugins/lisa-cursor/skills/lisa-session-manager/scripts/cli-usage.mjs +18 -5
  69. package/plugins/lisa-cursor/skills/lisa-session-manager/scripts/cli-workers.mjs +67 -3
  70. package/plugins/lisa-cursor/skills/lisa-session-manager/scripts/first-prompt.mjs +221 -0
  71. package/plugins/lisa-cursor/skills/lisa-session-manager/scripts/ledger.mjs +25 -3
  72. package/plugins/lisa-cursor/skills/lisa-session-manager/scripts/session-manager.mjs +4 -1
  73. package/plugins/lisa-cursor/skills/lisa-session-manager/scripts/worker-launch.mjs +91 -0
  74. package/plugins/lisa-cursor/skills/lisa-session-manager/scripts/workers.mjs +10 -5
  75. package/plugins/lisa-devin/.claude-plugin/plugin.json +1 -1
  76. package/plugins/lisa-devin/.devin-plugin/plugin.json +1 -1
  77. package/plugins/lisa-devin/skills/lisa-session-manager/SKILL.md +9 -3
  78. package/plugins/lisa-devin/skills/lisa-session-manager/scripts/cli-cycle.mjs +5 -0
  79. package/plugins/lisa-devin/skills/lisa-session-manager/scripts/cli-usage.mjs +18 -5
  80. package/plugins/lisa-devin/skills/lisa-session-manager/scripts/cli-workers.mjs +67 -3
  81. package/plugins/lisa-devin/skills/lisa-session-manager/scripts/first-prompt.mjs +221 -0
  82. package/plugins/lisa-devin/skills/lisa-session-manager/scripts/ledger.mjs +25 -3
  83. package/plugins/lisa-devin/skills/lisa-session-manager/scripts/session-manager.mjs +4 -1
  84. package/plugins/lisa-devin/skills/lisa-session-manager/scripts/worker-launch.mjs +91 -0
  85. package/plugins/lisa-devin/skills/lisa-session-manager/scripts/workers.mjs +10 -5
  86. package/plugins/lisa-expo/.claude-plugin/plugin.json +1 -1
  87. package/plugins/lisa-expo/.codex-plugin/plugin.json +1 -1
  88. package/plugins/lisa-expo-agy/plugin.json +1 -1
  89. package/plugins/lisa-expo-copilot/.claude-plugin/plugin.json +1 -1
  90. package/plugins/lisa-expo-cursor/.claude-plugin/plugin.json +1 -1
  91. package/plugins/lisa-expo-devin/.claude-plugin/plugin.json +1 -1
  92. package/plugins/lisa-expo-devin/.devin-plugin/plugin.json +1 -1
  93. package/plugins/lisa-harper-fabric/.claude-plugin/plugin.json +1 -1
  94. package/plugins/lisa-harper-fabric/.codex-plugin/plugin.json +1 -1
  95. package/plugins/lisa-harper-fabric-agy/plugin.json +1 -1
  96. package/plugins/lisa-harper-fabric-copilot/.claude-plugin/plugin.json +1 -1
  97. package/plugins/lisa-harper-fabric-cursor/.claude-plugin/plugin.json +1 -1
  98. package/plugins/lisa-harper-fabric-devin/.claude-plugin/plugin.json +1 -1
  99. package/plugins/lisa-harper-fabric-devin/.devin-plugin/plugin.json +1 -1
  100. package/plugins/lisa-nestjs/.claude-plugin/plugin.json +1 -1
  101. package/plugins/lisa-nestjs/.codex-plugin/plugin.json +1 -1
  102. package/plugins/lisa-nestjs-agy/plugin.json +1 -1
  103. package/plugins/lisa-nestjs-copilot/.claude-plugin/plugin.json +1 -1
  104. package/plugins/lisa-nestjs-cursor/.claude-plugin/plugin.json +1 -1
  105. package/plugins/lisa-nestjs-devin/.claude-plugin/plugin.json +1 -1
  106. package/plugins/lisa-nestjs-devin/.devin-plugin/plugin.json +1 -1
  107. package/plugins/lisa-openclaw/.claude-plugin/plugin.json +1 -1
  108. package/plugins/lisa-openclaw/.codex-plugin/plugin.json +1 -1
  109. package/plugins/lisa-openclaw-agy/plugin.json +1 -1
  110. package/plugins/lisa-openclaw-copilot/.claude-plugin/plugin.json +1 -1
  111. package/plugins/lisa-openclaw-cursor/.claude-plugin/plugin.json +1 -1
  112. package/plugins/lisa-openclaw-devin/.claude-plugin/plugin.json +1 -1
  113. package/plugins/lisa-openclaw-devin/.devin-plugin/plugin.json +1 -1
  114. package/plugins/lisa-phaser/.claude-plugin/plugin.json +1 -1
  115. package/plugins/lisa-phaser/.codex-plugin/plugin.json +1 -1
  116. package/plugins/lisa-phaser-agy/plugin.json +1 -1
  117. package/plugins/lisa-phaser-copilot/.claude-plugin/plugin.json +1 -1
  118. package/plugins/lisa-phaser-cursor/.claude-plugin/plugin.json +1 -1
  119. package/plugins/lisa-phaser-devin/.claude-plugin/plugin.json +1 -1
  120. package/plugins/lisa-phaser-devin/.devin-plugin/plugin.json +1 -1
  121. package/plugins/lisa-rails/.claude-plugin/plugin.json +1 -1
  122. package/plugins/lisa-rails/.codex-plugin/plugin.json +1 -1
  123. package/plugins/lisa-rails-agy/plugin.json +1 -1
  124. package/plugins/lisa-rails-copilot/.claude-plugin/plugin.json +1 -1
  125. package/plugins/lisa-rails-cursor/.claude-plugin/plugin.json +1 -1
  126. package/plugins/lisa-rails-devin/.claude-plugin/plugin.json +1 -1
  127. package/plugins/lisa-rails-devin/.devin-plugin/plugin.json +1 -1
  128. package/plugins/lisa-typescript/.claude-plugin/plugin.json +1 -1
  129. package/plugins/lisa-typescript/.codex-plugin/plugin.json +1 -1
  130. package/plugins/lisa-typescript-agy/plugin.json +1 -1
  131. package/plugins/lisa-typescript-copilot/.claude-plugin/plugin.json +1 -1
  132. package/plugins/lisa-typescript-cursor/.claude-plugin/plugin.json +1 -1
  133. package/plugins/lisa-typescript-devin/.claude-plugin/plugin.json +1 -1
  134. package/plugins/lisa-typescript-devin/.devin-plugin/plugin.json +1 -1
  135. package/plugins/lisa-wiki/.claude-plugin/plugin.json +1 -1
  136. package/plugins/lisa-wiki/.codex-plugin/plugin.json +1 -1
  137. package/plugins/lisa-wiki-agy/plugin.json +1 -1
  138. package/plugins/lisa-wiki-copilot/.claude-plugin/plugin.json +1 -1
  139. package/plugins/lisa-wiki-cursor/.claude-plugin/plugin.json +1 -1
  140. package/plugins/lisa-wiki-devin/.claude-plugin/plugin.json +1 -1
  141. package/plugins/lisa-wiki-devin/.devin-plugin/plugin.json +1 -1
  142. package/plugins/src/base/skills/lisa-session-manager/SKILL.md +9 -3
  143. package/plugins/src/base/skills/lisa-session-manager/scripts/cli-cycle.mjs +5 -0
  144. package/plugins/src/base/skills/lisa-session-manager/scripts/cli-usage.mjs +18 -5
  145. package/plugins/src/base/skills/lisa-session-manager/scripts/cli-workers.mjs +67 -3
  146. package/plugins/src/base/skills/lisa-session-manager/scripts/first-prompt.mjs +221 -0
  147. package/plugins/src/base/skills/lisa-session-manager/scripts/ledger.mjs +25 -3
  148. package/plugins/src/base/skills/lisa-session-manager/scripts/session-manager.mjs +4 -1
  149. package/plugins/src/base/skills/lisa-session-manager/scripts/worker-launch.mjs +91 -0
  150. package/plugins/src/base/skills/lisa-session-manager/scripts/workers.mjs +10 -5
  151. package/scripts/check-shell-guard-refusal-coverage.mjs +9 -3
  152. package/scripts/lib/shell-guard-shard-runner.mjs +40 -35
  153. package/scripts/lib/shell-guard-shards.mjs +176 -11
@@ -8,7 +8,12 @@
8
8
  * worker may already hold the ref (4). Only then does it run
9
9
  * `claude --bg`, with the cwd set to the routed repo and every `TELEGRAM_*`
10
10
  * variable removed from the worker's environment. A repo whose workspace
11
- * trust was never accepted is exit 2 too (see worker-launch.mjs).
11
+ * trust was never accepted is exit 2 too (see worker-launch.mjs). So is a
12
+ * worker whose first prompt never ran — `/lisa:implement` unknown in that
13
+ * repo, or refused by a `UserPromptSubmit` hook: `spawn` reads the new
14
+ * session's transcript briefly, stops that worker and records nothing
15
+ * (lisa#4503). `classify` reads the same transcript every cycle and reports
16
+ * such a worker as `setup-gap` instead of `working` until the stall timer.
12
17
  * @module session-manager/cli-workers
13
18
  */
14
19
  import { createHash } from "node:crypto";
@@ -47,7 +52,12 @@ import {
47
52
  findLiveWorker,
48
53
  parseSessionId,
49
54
  } from "./workers.mjs";
50
- import { resolveFullSessionId, runWorkerSession } from "./worker-launch.mjs";
55
+ import { claudeConfigDir, readFirstPrompt } from "./first-prompt.mjs";
56
+ import {
57
+ confirmFirstPrompt,
58
+ resolveFullSessionId,
59
+ runWorkerSession,
60
+ } from "./worker-launch.mjs";
51
61
 
52
62
  /**
53
63
  * Compute the capacity report for this machine and these agents.
@@ -165,6 +175,13 @@ export async function spawn(ctx) {
165
175
  `claude --bg printed no session id; find ${name} in claude agents --json.`
166
176
  );
167
177
  }
178
+ // Before anything is recorded: a first prompt that never ran is a setup
179
+ // gap (exit 2), not an attempt. With no session id there is no transcript
180
+ // to find, so waiting would only delay the spawn.
181
+ const firstPrompt =
182
+ sessionId === null
183
+ ? "unconfirmed"
184
+ : await confirmFirstPrompt(ctx, { name, sessionId, repoDir });
168
185
  const repo = key ?? ".";
169
186
  await recordSpawn(ctx.root, { ref, worker: name, sessionId, repo });
170
187
  await appendSessionEvent(ctx.root, {
@@ -175,7 +192,7 @@ export async function spawn(ctx) {
175
192
  repo,
176
193
  cwd: repoDir,
177
194
  });
178
- return { json: { ref, name, sessionId, repo, cwd: repoDir } };
195
+ return { json: { ref, name, sessionId, repo, cwd: repoDir, firstPrompt } };
179
196
  }
180
197
 
181
198
  /**
@@ -270,6 +287,50 @@ function logsHash(ctx, name) {
270
287
  return createHash("sha256").update(result.stdout).digest("hex");
271
288
  }
272
289
 
290
+ /**
291
+ * The repo dir a ledger item's worker started in, or null when it cannot be
292
+ * resolved (no config for a child repo key, or a key the config lost).
293
+ * @param {object} ctx - CLI context
294
+ * @param {object | null} config - Resolved `sessionManager` block, if any
295
+ * @param {{repo?: string|null}} entry - Ledger item
296
+ * @returns {string | null} Absolute dir
297
+ */
298
+ function workerDir(ctx, config, entry) {
299
+ if (!entry.repo || entry.repo === ".") return ctx.root;
300
+ try {
301
+ return config ? resolveRepoDir(config, entry.repo, ctx.root) : null;
302
+ } catch {
303
+ return null;
304
+ }
305
+ }
306
+
307
+ /**
308
+ * The first-prompt failure the item's worker transcript records, if any.
309
+ *
310
+ * probe-direction: fail-open — an unreadable or missing transcript yields
311
+ * null, which leaves classification exactly as it was before this check.
312
+ * A finished item (DONE or FAILED) classifies `finished` whatever its
313
+ * transcript says, so its transcript is never read.
314
+ * @param {object} ctx - CLI context
315
+ * @param {object | null} config - Resolved `sessionManager` block, if any
316
+ * @param {{worker?: string|null, sessionId?: string|null, repo?: string|null,
317
+ * status?: string}} entry - Ledger item
318
+ * @returns {{kind: string, detail: string} | null} Failure
319
+ */
320
+ function transcriptFailure(ctx, config, entry) {
321
+ if (entry.status === "DONE" || entry.status === "FAILED") return null;
322
+ const cwd =
323
+ entry.worker && entry.sessionId ? workerDir(ctx, config, entry) : null;
324
+ if (cwd === null) return null;
325
+ return (
326
+ readFirstPrompt({
327
+ configDir: claudeConfigDir(ctx.env, ctx.homedir),
328
+ cwd,
329
+ sessionId: entry.sessionId,
330
+ })?.failure ?? null
331
+ );
332
+ }
333
+
273
334
  /**
274
335
  * `classify [<ref>]`: classify one ledger item, or every one, for this cycle,
275
336
  * and record each logs hash as progress.
@@ -293,12 +354,14 @@ export async function classify(ctx) {
293
354
  : [];
294
355
  const agent = named.find(row => row.active) ?? named[0] ?? null;
295
356
  const hash = agent ? logsHash(ctx, entry.worker) : null;
357
+ const setupGap = transcriptFailure(ctx, config, entry);
296
358
  const classification = classifyWorker({
297
359
  agent,
298
360
  entry,
299
361
  logsHash: hash,
300
362
  now: ctx.now(),
301
363
  stall,
364
+ firstPromptFailure: setupGap,
302
365
  });
303
366
  if (hash !== null) await recordProgress(ctx.root, { ref, logsHash: hash });
304
367
  rows.push({
@@ -310,6 +373,7 @@ export async function classify(ctx) {
310
373
  attempts: entry.attempts ?? 0,
311
374
  agentStatus: agent?.status ?? agent?.state ?? null,
312
375
  pendingQuestion: entry.pendingQuestion ?? null,
376
+ setupGap: classification === "setup-gap" ? setupGap : null,
313
377
  });
314
378
  }
315
379
  return { json: rows };
@@ -0,0 +1,221 @@
1
+ /**
2
+ * Did a worker's first prompt run? Read from the session's transcript.
3
+ *
4
+ * A worker is started with one prompt, `/lisa:implement <REF> managedBy=…`.
5
+ * Two machine setup gaps stop that prompt from ever running, and both leave
6
+ * the session idle with zero assistant turns while `claude agents --json`
7
+ * shows nothing wrong (lisa#4503):
8
+ *
9
+ * - **unknown-command**: Claude Code in that repo does not know the command
10
+ * (Lisa's plugin is not visible there, e.g. a fresh clone whose
11
+ * dependencies were never installed). Claude Code 2.1.319 writes a `system`
12
+ * entry `Unknown command: /lisa:implement`.
13
+ * - **prompt-blocked**: a `UserPromptSubmit` hook refused the prompt. The
14
+ * `system` entry reads `UserPromptSubmit operation blocked by hook: …` and
15
+ * carries `promptSubmitEnding.ending.kind: "blocked_by_hook"` with the
16
+ * hook's reason.
17
+ *
18
+ * Retrying the item can never fix either one, so the manager must see them as
19
+ * setup gaps, not as a worker that is still working. The transcript lives at
20
+ * `<config dir>/projects/<cwd, every non-alphanumeric character as "-">/
21
+ * <full session id>.jsonl`; Claude Code files a symlinked cwd under its real
22
+ * path. Only `system` entries count as the failure, so text a user or the
23
+ * model typed can never trip it, and any assistant turn proves the worker is
24
+ * alive. A missing transcript gives no verdict — never a failure.
25
+ * @module session-manager/first-prompt
26
+ */
27
+ import { readFileSync, readdirSync, realpathSync } from "node:fs";
28
+ import path from "node:path";
29
+
30
+ /** `Unknown command: /<name>` as Claude Code words it. */
31
+ const UNKNOWN_COMMAND = /^Unknown command: (\/\S+)/;
32
+
33
+ /** The hook refusal's message text, for a transcript without the ending. */
34
+ const PROMPT_BLOCKED =
35
+ /^UserPromptSubmit operation blocked by hook:\s*\n?([^\n]*)/;
36
+
37
+ /** Default wait for the first prompt to resolve after `claude --bg`. */
38
+ export const FIRST_PROMPT_WINDOW_MS = 30_000;
39
+
40
+ /** How often the transcript is re-read while waiting. */
41
+ export const FIRST_PROMPT_INTERVAL_MS = 1_000;
42
+
43
+ /**
44
+ * Parse transcript JSONL, skipping blank lines and a half-written last line.
45
+ * @param {string} text - File contents
46
+ * @returns {object[]} Entries
47
+ */
48
+ export function parseTranscript(text) {
49
+ return String(text)
50
+ .split("\n")
51
+ .filter(line => line.trim() !== "")
52
+ .flatMap(line => {
53
+ try {
54
+ const entry = JSON.parse(line);
55
+ return entry !== null && typeof entry === "object" ? [entry] : [];
56
+ } catch {
57
+ return [];
58
+ }
59
+ });
60
+ }
61
+
62
+ /**
63
+ * The first-prompt failure one `system` entry records, if any.
64
+ * @param {object} entry - Transcript entry
65
+ * @returns {{kind: "unknown-command"|"prompt-blocked", detail: string} | null}
66
+ * Failure
67
+ */
68
+ function entryFailure(entry) {
69
+ if (entry.type !== "system") return null;
70
+ const content = typeof entry.content === "string" ? entry.content : "";
71
+ const unknown = UNKNOWN_COMMAND.exec(content);
72
+ if (unknown) return { kind: "unknown-command", detail: unknown[1] };
73
+ const ending = entry.promptSubmitEnding?.ending;
74
+ if (ending?.kind === "blocked_by_hook") {
75
+ return { kind: "prompt-blocked", detail: String(ending.reason ?? "") };
76
+ }
77
+ const blocked = PROMPT_BLOCKED.exec(content);
78
+ return blocked ? { kind: "prompt-blocked", detail: blocked[1].trim() } : null;
79
+ }
80
+
81
+ /**
82
+ * Judge a transcript: alive once any assistant turn exists; failed when,
83
+ * with no assistant turn, a `system` entry records a first-prompt failure;
84
+ * neither while the first prompt has not resolved yet.
85
+ * @param {object[]} entries - Parsed transcript
86
+ * @returns {{alive: boolean, failure: {kind: string, detail: string} | null}}
87
+ * Verdict
88
+ */
89
+ export function firstPromptVerdict(entries) {
90
+ // One pass that stops at the first assistant turn: a long, healthy
91
+ // transcript is read only up to the worker's first reply.
92
+ let failure = null;
93
+ for (const entry of entries) {
94
+ if (entry.type === "assistant") return { alive: true, failure: null };
95
+ failure ??= entryFailure(entry);
96
+ }
97
+ return { alive: false, failure };
98
+ }
99
+
100
+ /**
101
+ * The first-prompt failure a transcript records, or null (including for any
102
+ * transcript with an assistant turn).
103
+ * @param {object[]} entries - Parsed transcript
104
+ * @returns {{kind: "unknown-command"|"prompt-blocked", detail: string} | null}
105
+ * Failure
106
+ */
107
+ export function detectFirstPromptFailure(entries) {
108
+ return firstPromptVerdict(entries).failure;
109
+ }
110
+
111
+ /**
112
+ * Claude Code's config dir: `CLAUDE_CONFIG_DIR`, else `<home>/.claude`.
113
+ * @param {Record<string, string | undefined>} env - Environment
114
+ * @param {string} homedir - Home directory
115
+ * @returns {string} Absolute path
116
+ */
117
+ export function claudeConfigDir(env, homedir) {
118
+ return env.CLAUDE_CONFIG_DIR || path.join(homedir, ".claude");
119
+ }
120
+
121
+ /**
122
+ * The `projects/` subdirectory name Claude Code uses for a cwd.
123
+ * @param {string} cwd - Session cwd
124
+ * @returns {string} Encoded name
125
+ */
126
+ export function encodeProjectDir(cwd) {
127
+ return cwd.replace(/[^A-Za-z0-9]/g, "-");
128
+ }
129
+
130
+ /**
131
+ * The cwd and, when different, its real path.
132
+ * @param {string} cwd - Session cwd
133
+ * @returns {string[]} Candidates
134
+ */
135
+ function cwdCandidates(cwd) {
136
+ try {
137
+ const real = realpathSync(cwd);
138
+ return real === cwd ? [cwd] : [cwd, real];
139
+ } catch {
140
+ return [cwd];
141
+ }
142
+ }
143
+
144
+ /**
145
+ * Transcript files in one project dir whose name matches the session id.
146
+ * @param {string} dir - Project dir
147
+ * @param {string} id - Full or short (8-hex) session id, lowercase
148
+ * @returns {string[]} Matching paths
149
+ */
150
+ function matchesIn(dir, id) {
151
+ try {
152
+ return readdirSync(dir)
153
+ .filter(
154
+ name =>
155
+ name === `${id}.jsonl` ||
156
+ (name.startsWith(`${id}-`) && name.endsWith(".jsonl"))
157
+ )
158
+ .map(name => path.join(dir, name));
159
+ } catch {
160
+ return [];
161
+ }
162
+ }
163
+
164
+ /**
165
+ * Locate a session's transcript by full id, or by the short id
166
+ * `claude --bg` prints (a full id starts with it).
167
+ * @param {{configDir: string, cwd: string, sessionId: string | null | undefined}} input
168
+ * - Where to look
169
+ * @returns {string | null} The one matching file, or null when there is none
170
+ * or more than one
171
+ */
172
+ export function findTranscript({ configDir, cwd, sessionId }) {
173
+ const id = String(sessionId ?? "").toLowerCase();
174
+ if (!/^[0-9a-f]{8}(?:-[0-9a-f-]{27})?$/.test(id)) return null;
175
+ const found = cwdCandidates(cwd).flatMap(candidate =>
176
+ matchesIn(path.join(configDir, "projects", encodeProjectDir(candidate)), id)
177
+ );
178
+ const unique = [...new Set(found)];
179
+ return unique.length === 1 ? unique[0] : null;
180
+ }
181
+
182
+ /**
183
+ * Read a session's first-prompt verdict, or null when there is no transcript
184
+ * to read.
185
+ * @param {{configDir: string, cwd: string, sessionId: string | null | undefined}} input
186
+ * - Where to look
187
+ * @returns {ReturnType<typeof firstPromptVerdict> | null} Verdict
188
+ */
189
+ export function readFirstPrompt(input) {
190
+ const file = findTranscript(input);
191
+ if (file === null) return null;
192
+ try {
193
+ return firstPromptVerdict(parseTranscript(readFileSync(file, "utf8")));
194
+ } catch {
195
+ return null;
196
+ }
197
+ }
198
+
199
+ /**
200
+ * Re-read the transcript until the first prompt resolves (alive or failed)
201
+ * or `windowMs` runs out. A zero window reads once.
202
+ * @param {{configDir: string, cwd: string, sessionId: string | null | undefined,
203
+ * windowMs: number, intervalMs: number, sleep: (ms: number) => Promise<void>}} input
204
+ * - Where to look, how long to wait, and the sleep seam
205
+ * @returns {Promise<ReturnType<typeof firstPromptVerdict> | null>} The
206
+ * resolved verdict, or null when it never resolved
207
+ */
208
+ export async function awaitFirstPrompt({
209
+ windowMs,
210
+ intervalMs,
211
+ sleep,
212
+ ...where
213
+ }) {
214
+ const rounds = Math.max(0, Math.ceil(windowMs / Math.max(1, intervalMs)));
215
+ for (let round = 0; ; round += 1) {
216
+ const verdict = readFirstPrompt(where);
217
+ if (verdict?.alive || verdict?.failure) return verdict;
218
+ if (round >= rounds) return null;
219
+ await sleep(Math.min(intervalMs, windowMs));
220
+ }
221
+ }
@@ -336,12 +336,22 @@ export function recordProgress(projectRoot, { ref, logsHash }, seams) {
336
336
 
337
337
  /**
338
338
  * Record the worker's own terminal report.
339
+ *
340
+ * `setupGap` marks a FAILED worker whose first prompt never ran (classify
341
+ * said `setup-gap`, lisa#4503): the spawn that started it is refunded, so a
342
+ * machine setup problem never spends the item's attempts. Only a `running`
343
+ * item is refunded, so repeating the finish, or finishing an item that
344
+ * already finished, never takes away a second attempt.
339
345
  * @param {string} projectRoot - Absolute project root
340
- * @param {{ref: string, status: "DONE"|"FAILED", reason: string}} finish - Report
346
+ * @param {{ref: string, status: "DONE"|"FAILED", reason: string, setupGap?: boolean}} finish - Report
341
347
  * @param {LedgerSeams} [seams] - Injected seams
342
348
  * @returns {Promise<LedgerItem>} The updated item
343
349
  */
344
- export function recordFinish(projectRoot, { ref, status, reason }, seams) {
350
+ export function recordFinish(
351
+ projectRoot,
352
+ { ref, status, reason, setupGap = false },
353
+ seams
354
+ ) {
345
355
  if (!FINISH_STATUSES.has(status)) {
346
356
  return Promise.reject(
347
357
  new Error(
@@ -349,19 +359,31 @@ export function recordFinish(projectRoot, { ref, status, reason }, seams) {
349
359
  )
350
360
  );
351
361
  }
362
+ if (setupGap && status !== "FAILED") {
363
+ return Promise.reject(new Error("a setup-gap finish must be FAILED"));
364
+ }
352
365
  return updateLedger(projectRoot, seams, (ledger, at) => {
353
366
  const previous = requireItem(ledger, ref);
367
+ const attempts = previous.attempts ?? 0;
368
+ const refund = setupGap && previous.status === "running";
354
369
  return withItem(ledger, ref, {
355
370
  ...previous,
356
371
  status,
357
372
  reason,
358
373
  finishedAt: at,
374
+ attempts: refund ? Math.max(0, attempts - 1) : attempts,
359
375
  // Kept: a question recorded before the finish still holds its answer
360
376
  // and the tracker marker the manager must remove (lisa#4571).
361
377
  pendingQuestion: previous.pendingQuestion ?? null,
362
378
  history: [
363
379
  ...(previous.history ?? []),
364
- { event: "finish", at, status, reason },
380
+ {
381
+ event: "finish",
382
+ at,
383
+ status,
384
+ reason,
385
+ ...(setupGap ? { setupGap: true } : {}),
386
+ },
365
387
  ],
366
388
  });
367
389
  });
@@ -161,7 +161,10 @@ const LEDGER_SPECS = {
161
161
  options: { "reset-attempts": flag, "expect-answer-at": text },
162
162
  positionals: 1,
163
163
  },
164
- finish: { options: { status: text, sender: text }, positionals: 1 },
164
+ finish: {
165
+ options: { status: text, sender: text, "setup-gap": flag },
166
+ positionals: 1,
167
+ },
165
168
  "validation-failed": { options: { "updated-at": text }, positionals: 1 },
166
169
  "validation-cleared": { options: {}, positionals: 1 },
167
170
  control: {
@@ -10,9 +10,23 @@
10
10
  * the exact step, and the manager skill escalates it instead of counting a
11
11
  * failed attempt. Every other failure keeps the exit-1 message `mustRun`
12
12
  * gives.
13
+ *
14
+ * A spawn that `claude --bg` accepted can still die on its first prompt: the
15
+ * command is unknown in that repo, or a `UserPromptSubmit` hook refuses it
16
+ * (lisa#4503). `confirmFirstPrompt` watches the new session's transcript for
17
+ * a bounded window; a first-prompt failure stops the worker and becomes the
18
+ * same exit 2, so the manager returns the item to Ready without counting an
19
+ * attempt. A transcript that does not resolve in time is not a failure: the
20
+ * spawn proceeds exactly as before and `classify` keeps watching.
13
21
  * @module session-manager/worker-launch
14
22
  */
15
23
  import { CliError, EXIT, run } from "./cli-runtime.mjs";
24
+ import {
25
+ FIRST_PROMPT_INTERVAL_MS,
26
+ FIRST_PROMPT_WINDOW_MS,
27
+ awaitFirstPrompt,
28
+ claudeConfigDir,
29
+ } from "./first-prompt.mjs";
16
30
 
17
31
  /** How claude words the refusal; matched loosely across versions. */
18
32
  const UNTRUSTED_WORKSPACE = /workspace (?:is )?not trusted/i;
@@ -90,3 +104,80 @@ export function resolveFullSessionId(agents, item) {
90
104
  );
91
105
  return row ? row.sessionId.toLowerCase() : null;
92
106
  }
107
+
108
+ /** Overrides the first-prompt wait, in milliseconds (0 reads once). */
109
+ const FIRST_PROMPT_ENV = "LISA_SESSION_MANAGER_FIRST_PROMPT_MS";
110
+
111
+ /**
112
+ * The first-prompt wait: the env override when it is a whole number, else
113
+ * the default.
114
+ * @param {Record<string, string | undefined>} env - Environment
115
+ * @returns {number} Milliseconds
116
+ */
117
+ function firstPromptWindow(env) {
118
+ const raw = env[FIRST_PROMPT_ENV];
119
+ return raw !== undefined && /^\d+$/.test(raw)
120
+ ? Number(raw)
121
+ : FIRST_PROMPT_WINDOW_MS;
122
+ }
123
+
124
+ /**
125
+ * The operator-readable reason a worker's first prompt never ran.
126
+ * @param {{kind: string, detail: string}} failure - From the transcript
127
+ * @param {string} repoDir - Where the worker started
128
+ * @returns {string} Message
129
+ */
130
+ export function firstPromptGapMessage(failure, repoDir) {
131
+ const tail =
132
+ "The worker was stopped; nothing was recorded and no attempt was " +
133
+ "counted. Retrying cannot fix this until the repo is set up.";
134
+ if (failure.kind === "unknown-command") {
135
+ return (
136
+ `The worker could not run ${failure.detail} in ${repoDir}: Claude Code ` +
137
+ `there does not know that command, so Lisa's plugin is not visible in ` +
138
+ `that repo (for example a fresh clone whose dependencies were never ` +
139
+ `installed). Make Lisa available in ${repoDir}, then dispatch again. ${tail}`
140
+ );
141
+ }
142
+ return (
143
+ `A UserPromptSubmit hook in ${repoDir} rejected the worker's first ` +
144
+ `prompt, so the worker never started. The hook said: ` +
145
+ `"${failure.detail}". Fix or sign in to whatever that hook needs, then ` +
146
+ `dispatch again. ${tail}`
147
+ );
148
+ }
149
+
150
+ /**
151
+ * Wait briefly for a new worker's first prompt to resolve. A failure stops
152
+ * the worker (best effort) and throws exit 2; otherwise it reports whether
153
+ * the worker was seen alive.
154
+ * @param {{env: Record<string, string | undefined>, homedir: string}} ctx -
155
+ * CLI context
156
+ * @param {{name: string, sessionId: string | null, repoDir: string,
157
+ * sleep?: (ms: number) => Promise<void>}} worker - The spawned worker
158
+ * @returns {Promise<"alive" | "unconfirmed">} What the transcript showed
159
+ */
160
+ export async function confirmFirstPrompt(
161
+ ctx,
162
+ { name, sessionId, repoDir, sleep }
163
+ ) {
164
+ const verdict = await awaitFirstPrompt({
165
+ configDir: claudeConfigDir(ctx.env, ctx.homedir),
166
+ cwd: repoDir,
167
+ sessionId,
168
+ windowMs: firstPromptWindow(ctx.env),
169
+ intervalMs: FIRST_PROMPT_INTERVAL_MS,
170
+ sleep: sleep ?? (ms => new Promise(done => setTimeout(done, ms))),
171
+ });
172
+ if (verdict?.failure) {
173
+ // probe-direction: fail-open — a stop that fails leaves an idle session
174
+ // holding nothing: no ledger row and no attempt, and exit 2 still lands.
175
+ run("claude", ["stop", name], { env: ctx.env });
176
+ throw new CliError(
177
+ firstPromptGapMessage(verdict.failure, repoDir),
178
+ EXIT.SETUP,
179
+ { name, sessionId, repoDir, setupGap: verdict.failure }
180
+ );
181
+ }
182
+ return verdict?.alive ? "alive" : "unconfirmed";
183
+ }
@@ -355,11 +355,14 @@ function toMillis(value) {
355
355
  *
356
356
  * Order matters: a recorded DONE/FAILED wins; a pending question means the
357
357
  * worker ended its turn on purpose, so it is `waiting` even when its row
358
- * reads `done`; only then is liveness judged. `stalled` and `dead` become
359
- * `exhausted` at `maxAttempts`, which is the manager's cue to move the item to
360
- * Blocked instead of retrying it again.
361
- * @param {{agent: ReturnType<typeof normalizeAgents>[number] | null, entry: {status?: string, startedAt?: string|number, lastProgressAt?: string|number|null, logsHash?: string|null, pendingQuestion?: {askedAt?: string|number, lastPingAt?: string|number|null} | null, attempts?: number}, logsHash?: string | null | undefined, now: Date | number, stall?: {noOutputMinutes: number, requestionHours: number, maxAttempts: number}}} input - Classification inputs
362
- * @returns {"finished"|"waiting"|"requestion"|"working"|"stalled"|"dead"|"exhausted"} Classification
358
+ * reads `done`; then a first prompt that never ran (`firstPromptFailure`,
359
+ * read from the worker's transcript) is a `setup-gap` — a machine problem no
360
+ * retry can fix, so it is never `working` until the stall timer and never
361
+ * `exhausted` (lisa#4503); only then is liveness judged. `stalled` and `dead`
362
+ * become `exhausted` at `maxAttempts`, which is the manager's cue to move the
363
+ * item to Blocked instead of retrying it again.
364
+ * @param {{agent: ReturnType<typeof normalizeAgents>[number] | null, entry: {status?: string, startedAt?: string|number, lastProgressAt?: string|number|null, logsHash?: string|null, pendingQuestion?: {askedAt?: string|number, lastPingAt?: string|number|null} | null, attempts?: number}, logsHash?: string | null | undefined, now: Date | number, stall?: {noOutputMinutes: number, requestionHours: number, maxAttempts: number}, firstPromptFailure?: {kind: string, detail: string} | null}} input - Classification inputs
365
+ * @returns {"finished"|"waiting"|"requestion"|"setup-gap"|"working"|"stalled"|"dead"|"exhausted"} Classification
363
366
  */
364
367
  export function classifyWorker({
365
368
  agent,
@@ -367,6 +370,7 @@ export function classifyWorker({
367
370
  logsHash,
368
371
  now,
369
372
  stall = DEFAULT_STALL,
373
+ firstPromptFailure = null,
370
374
  }) {
371
375
  if (FINISHED_STATUSES.has(entry.status ?? "")) return "finished";
372
376
  const nowMs = toMillis(now) ?? 0;
@@ -378,6 +382,7 @@ export function classifyWorker({
378
382
  ? "requestion"
379
383
  : "waiting";
380
384
  }
385
+ if (firstPromptFailure) return "setup-gap";
381
386
  const outcome = agent?.active
382
387
  ? judgeActive(entry, logsHash, nowMs, stall)
383
388
  : "dead";
@@ -39,9 +39,15 @@
39
39
  * collect one complete native Actions shard without judging
40
40
  * its individual trace. All canonical candidates are supplied.
41
41
  * --merge-traces DIRECTORY --trace-out FILE
42
- * validate all three current run/attempt shard receipts, then
43
- * apply the original judge once to their combined trace.
44
- * A new Actions attempt must reproduce all three shards.
42
+ * validate one complete receipt per shard from the current
43
+ * run, then apply the original judge once to their combined
44
+ * trace. DIRECTORY holds every attempt of the run; for each
45
+ * shard the newest attempt wins, so "Re-run failed jobs"
46
+ * recovers a failed shard (#4634). That newest bundle must be
47
+ * complete — an older attempt is never used in its place —
48
+ * and must match the current run, source, PR head, workflow,
49
+ * runtime and roster. Each refusal names the shard, the
50
+ * attempt and the re-run that recovers it.
45
51
  *
46
52
  * Exit codes (mirroring the sibling check-* scripts):
47
53
  * 0 — the judgment passed, or --collect-only retained a complete eligible