@oyasmi/pipiclaw 0.9.2 → 0.9.3-beta.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 (165) hide show
  1. package/README.en.md +250 -0
  2. package/README.md +2 -0
  3. package/dist/agent/channel-runner.d.ts +43 -2
  4. package/dist/agent/channel-runner.js +135 -75
  5. package/dist/agent/job-manager.d.ts +76 -21
  6. package/dist/agent/job-manager.js +447 -63
  7. package/dist/agent/maintenance-context.js +4 -5
  8. package/dist/agent/prompt/manifest.d.ts +0 -2
  9. package/dist/agent/prompt/manifest.js +2 -3
  10. package/dist/agent/prompt/sections.js +3 -3
  11. package/dist/agent/session-events.js +4 -8
  12. package/dist/agent/turn-prompt.d.ts +7 -7
  13. package/dist/agent/turn-prompt.js +6 -9
  14. package/dist/agent/types.d.ts +12 -0
  15. package/dist/agent/types.js +1 -0
  16. package/dist/channel/channel-context.d.ts +13 -0
  17. package/dist/channel/channel-context.js +21 -1
  18. package/dist/commands/catalog.js +47 -20
  19. package/dist/memory/commands.d.ts +8 -0
  20. package/dist/memory/commands.js +113 -148
  21. package/dist/memory/index-budget.d.ts +27 -0
  22. package/dist/memory/index-budget.js +99 -0
  23. package/dist/memory/journal.d.ts +20 -0
  24. package/dist/memory/journal.js +78 -0
  25. package/dist/memory/lifecycle.d.ts +9 -15
  26. package/dist/memory/lifecycle.js +55 -145
  27. package/dist/memory/maintenance-gates.d.ts +13 -47
  28. package/dist/memory/maintenance-gates.js +13 -92
  29. package/dist/memory/maintenance-state.d.ts +10 -16
  30. package/dist/memory/maintenance-state.js +12 -59
  31. package/dist/memory/maintenance-tuning.d.ts +7 -27
  32. package/dist/memory/maintenance-tuning.js +11 -28
  33. package/dist/memory/migrate.d.ts +15 -0
  34. package/dist/memory/migrate.js +364 -0
  35. package/dist/memory/reflect-job.d.ts +43 -0
  36. package/dist/memory/reflect-job.js +117 -0
  37. package/dist/memory/reflect.d.ts +52 -0
  38. package/dist/memory/reflect.js +313 -0
  39. package/dist/memory/render.d.ts +14 -0
  40. package/dist/memory/render.js +28 -0
  41. package/dist/memory/review-log.d.ts +2 -1
  42. package/dist/memory/scheduler.d.ts +2 -3
  43. package/dist/memory/scheduler.js +14 -49
  44. package/dist/memory/search.d.ts +35 -0
  45. package/dist/memory/search.js +297 -0
  46. package/dist/memory/session-search.js +1 -1
  47. package/dist/memory/store.d.ts +108 -0
  48. package/dist/memory/store.js +418 -0
  49. package/dist/memory/task-digest.d.ts +2 -2
  50. package/dist/memory/task-digest.js +29 -36
  51. package/dist/memory/tombstones.d.ts +0 -11
  52. package/dist/memory/tombstones.js +6 -37
  53. package/dist/playbooks/agent-delegation.md +4 -2
  54. package/dist/playbooks/background-jobs.md +1 -1
  55. package/dist/playbooks/event-scheduling.md +6 -2
  56. package/dist/playbooks/memory-and-learning.md +18 -11
  57. package/dist/playbooks/outbound-media.md +1 -1
  58. package/dist/playbooks/runtime-orientation.md +9 -8
  59. package/dist/playbooks/task-loop.md +88 -0
  60. package/dist/runtime/bootstrap.d.ts +3 -3
  61. package/dist/runtime/bootstrap.js +66 -41
  62. package/dist/runtime/events.d.ts +9 -0
  63. package/dist/runtime/events.js +43 -4
  64. package/dist/runtime/task-commands.d.ts +14 -15
  65. package/dist/runtime/task-commands.js +249 -485
  66. package/dist/runtime/task-driver.d.ts +41 -29
  67. package/dist/runtime/task-driver.js +170 -317
  68. package/dist/runtime/task-migration.d.ts +34 -30
  69. package/dist/runtime/task-migration.js +229 -183
  70. package/dist/runtime/task-wake.d.ts +6 -3
  71. package/dist/runtime/task-wake.js +26 -19
  72. package/dist/settings.d.ts +0 -29
  73. package/dist/settings.js +12 -35
  74. package/dist/shared/markdown-sections.d.ts +0 -1
  75. package/dist/shared/markdown-sections.js +0 -3
  76. package/dist/subagents/discovery.d.ts +2 -2
  77. package/dist/subagents/discovery.js +21 -10
  78. package/dist/subagents/external/progress-tail.js +6 -1
  79. package/dist/subagents/external/run.js +1 -0
  80. package/dist/subagents/runs.d.ts +19 -2
  81. package/dist/subagents/runs.js +73 -4
  82. package/dist/subagents/tool.d.ts +10 -8
  83. package/dist/subagents/tool.js +55 -94
  84. package/dist/tasks/brief.d.ts +17 -0
  85. package/dist/tasks/brief.js +57 -0
  86. package/dist/tasks/budget.d.ts +26 -0
  87. package/dist/tasks/budget.js +59 -0
  88. package/dist/tasks/cycle.d.ts +48 -0
  89. package/dist/tasks/cycle.js +94 -0
  90. package/dist/tasks/frontmatter.d.ts +73 -0
  91. package/dist/tasks/frontmatter.js +175 -0
  92. package/dist/tasks/ledger.d.ts +66 -106
  93. package/dist/tasks/ledger.js +90 -546
  94. package/dist/tasks/log.d.ts +88 -0
  95. package/dist/tasks/log.js +97 -0
  96. package/dist/tasks/rounds.d.ts +43 -0
  97. package/dist/tasks/rounds.js +57 -0
  98. package/dist/tasks/session-path.d.ts +9 -0
  99. package/dist/tasks/session-path.js +16 -0
  100. package/dist/tasks/steer.d.ts +8 -0
  101. package/dist/tasks/steer.js +79 -0
  102. package/dist/tasks/store.d.ts +60 -35
  103. package/dist/tasks/store.js +166 -107
  104. package/dist/tasks/ticket.d.ts +102 -0
  105. package/dist/tasks/ticket.js +209 -0
  106. package/dist/tasks/verification.d.ts +16 -0
  107. package/dist/tasks/verification.js +40 -1
  108. package/dist/tools/index.d.ts +13 -4
  109. package/dist/tools/index.js +5 -10
  110. package/dist/tools/memory-manage.d.ts +6 -16
  111. package/dist/tools/memory-manage.js +108 -129
  112. package/dist/tools/presentation.js +2 -1
  113. package/dist/tools/registry.d.ts +11 -2
  114. package/dist/tools/registry.js +17 -6
  115. package/dist/tools/subagent-manage.d.ts +0 -9
  116. package/dist/tools/subagent-manage.js +8 -17
  117. package/dist/tools/task-manage/create.js +2 -2
  118. package/dist/tools/task-manage/lifecycle.d.ts +9 -4
  119. package/dist/tools/task-manage/lifecycle.js +139 -187
  120. package/dist/tools/task-manage/log-view.d.ts +8 -0
  121. package/dist/tools/task-manage/log-view.js +24 -0
  122. package/dist/tools/task-manage/schema.d.ts +38 -14
  123. package/dist/tools/task-manage/schema.js +46 -27
  124. package/dist/tools/task-manage/shared.d.ts +24 -31
  125. package/dist/tools/task-manage/shared.js +103 -141
  126. package/dist/tools/task-manage/step-end.d.ts +11 -0
  127. package/dist/tools/task-manage/step-end.js +136 -0
  128. package/dist/tools/task-manage/types.d.ts +23 -32
  129. package/dist/tools/task-manage.d.ts +4 -3
  130. package/dist/tools/task-manage.js +30 -15
  131. package/dist/tools/tool-details.d.ts +1 -1
  132. package/dist/tui/app.js +0 -2
  133. package/package.json +1 -1
  134. package/dist/agent/effect-ledger.d.ts +0 -32
  135. package/dist/agent/effect-ledger.js +0 -89
  136. package/dist/memory/bootstrap.d.ts +0 -17
  137. package/dist/memory/bootstrap.js +0 -120
  138. package/dist/memory/candidates.d.ts +0 -26
  139. package/dist/memory/candidates.js +0 -202
  140. package/dist/memory/consolidation.d.ts +0 -54
  141. package/dist/memory/consolidation.js +0 -292
  142. package/dist/memory/extraction.d.ts +0 -54
  143. package/dist/memory/extraction.js +0 -240
  144. package/dist/memory/files.d.ts +0 -71
  145. package/dist/memory/files.js +0 -419
  146. package/dist/memory/maintenance-jobs.d.ts +0 -41
  147. package/dist/memory/maintenance-jobs.js +0 -265
  148. package/dist/memory/metadata.d.ts +0 -57
  149. package/dist/memory/metadata.js +0 -142
  150. package/dist/memory/probation.d.ts +0 -17
  151. package/dist/memory/probation.js +0 -44
  152. package/dist/memory/promotion.d.ts +0 -38
  153. package/dist/memory/promotion.js +0 -36
  154. package/dist/memory/recall.d.ts +0 -59
  155. package/dist/memory/recall.js +0 -746
  156. package/dist/memory/session.d.ts +0 -24
  157. package/dist/memory/session.js +0 -273
  158. package/dist/playbooks/task-driving.md +0 -92
  159. package/dist/playbooks/task-planning.md +0 -58
  160. package/dist/tasks/control.d.ts +0 -56
  161. package/dist/tasks/control.js +0 -169
  162. package/dist/tasks/transitions.d.ts +0 -16
  163. package/dist/tasks/transitions.js +0 -48
  164. package/dist/tools/task-manage/verification.d.ts +0 -19
  165. package/dist/tools/task-manage/verification.js +0 -91
@@ -10,6 +10,81 @@ import { shellEscape } from "../shared/shell-escape.js";
10
10
  import { errorMessage } from "../shared/text-utils.js";
11
11
  import { isRecord } from "../shared/type-guards.js";
12
12
  import { beginWakeClaim, finishWakeClaim } from "../shared/wake-claim.js";
13
+ function jobArtifacts(spillFile) {
14
+ return {
15
+ spillFile,
16
+ exitFile: `${spillFile}.exit`,
17
+ exitTmp: `${spillFile}.exit.tmp`,
18
+ readyFile: `${spillFile}.ready`,
19
+ readyTmp: `${spillFile}.ready.tmp`,
20
+ metaFile: `${spillFile}.meta`,
21
+ metaTmp: `${spillFile}.meta.tmp`,
22
+ };
23
+ }
24
+ /** ~2s of readiness polling: 40 iterations of a 50ms sleep in the wrapper shell. */
25
+ const LAUNCH_HANDSHAKE_MAX_POLLS = 40;
26
+ /**
27
+ * Build the wrapper shell that launches a background job with a verifiable startup handshake.
28
+ *
29
+ * The inner shell writes an atomic `ready` marker as its very first action — *before* the user
30
+ * command — so the parent can distinguish "wrapper live, spill writable, command about to run"
31
+ * from "launch silently failed" (a read-only spill dir, a `setsid`/`sh` that could not exec). The
32
+ * parent also writes a metadata file (pid, and under `setsid` the pgid/start-time) *before* it
33
+ * waits on the handshake, so an abort that lands mid-handshake still leaves a recoverable pid.
34
+ *
35
+ * `setsid` (when present) makes the job its own session/process-group leader (pgid == pid), so a
36
+ * later cancel/timeout can terminate the whole group. A host without it falls back to `nohup` —
37
+ * still detached and restart-safe, but single-pid, so pgid/identity are deliberately not claimed.
38
+ *
39
+ * On handshake success the parent prints `MODE`/`PID`(/`PGID`/`LSTART`) and exits 0. On failure it
40
+ * kills whatever it spawned, echoes the inner error, removes the scratch files, and exits 1.
41
+ */
42
+ function buildLaunchScript(command, art) {
43
+ const spill = shellEscape(art.spillFile);
44
+ const exitFile = shellEscape(art.exitFile);
45
+ const exitTmp = shellEscape(art.exitTmp);
46
+ const ready = shellEscape(art.readyFile);
47
+ const readyTmp = shellEscape(art.readyTmp);
48
+ const meta = shellEscape(art.metaFile);
49
+ const metaTmp = shellEscape(art.metaTmp);
50
+ // Subshell around the user command so its own `exit N` only leaves the subshell and the
51
+ // exit-capture still runs; the exit code is written temp-then-renamed so a probe never reads a
52
+ // half-written `.exit`.
53
+ const inner = `printf 'ready\\n' > ${readyTmp} && mv -f ${readyTmp} ${ready} || exit 127; ` +
54
+ `( ${command} )\n__pc_rc=$?; ` +
55
+ `printf '%s\\n' "$__pc_rc" > ${exitTmp} && mv -f ${exitTmp} ${exitFile}`;
56
+ const escInner = shellEscape(inner);
57
+ // `ps` can momentarily miss a just-forked process on a loaded host: one short retry.
58
+ const psField = (field) => `"$(ps -o ${field}= -p "$__pc_pid" 2>/dev/null || { sleep 0.1; ps -o ${field}= -p "$__pc_pid" 2>/dev/null; })"`;
59
+ const handshake = (killExpr) => `__pc_i=0; while [ ! -s ${ready} ] && [ "$__pc_i" -lt ${LAUNCH_HANDSHAKE_MAX_POLLS} ]; do ` +
60
+ `sleep 0.05; __pc_i=$((__pc_i+1)); done; ` +
61
+ `if [ ! -s ${ready} ]; then ${killExpr}printf 'HANDSHAKE failed\\n'; cat ${spill} 2>/dev/null; ` +
62
+ `rm -f ${ready} ${readyTmp} ${meta} ${metaTmp} ${exitFile} ${exitTmp} ${spill}; exit 1; fi`;
63
+ const setsidKill = `kill -TERM "-$__pc_pid" 2>/dev/null; kill -TERM "$__pc_pid" 2>/dev/null; sleep 0.1; ` +
64
+ `kill -KILL "-$__pc_pid" 2>/dev/null; `;
65
+ const nohupKill = `kill -TERM "$__pc_pid" 2>/dev/null; sleep 0.1; kill -KILL "$__pc_pid" 2>/dev/null; `;
66
+ const setsidBranch = `setsid sh -c ${escInner} > ${spill} 2>&1 & __pc_pid=$!; ` +
67
+ `__pc_pgid=$(printf '%s' ${psField("pgid")} | tr -d ' '); __pc_lstart=${psField("lstart")}; ` +
68
+ `printf 'MODE setsid\\nPID %s\\nPGID %s\\nLSTART %s\\n' "$__pc_pid" "$__pc_pgid" "$__pc_lstart" ` +
69
+ `> ${metaTmp} && mv -f ${metaTmp} ${meta}; ` +
70
+ `${handshake(setsidKill)}; ` +
71
+ `printf 'MODE setsid\\nPID %s\\nPGID %s\\nLSTART %s\\n' "$__pc_pid" "$__pc_pgid" "$__pc_lstart"`;
72
+ const nohupBranch = `nohup sh -c ${escInner} > ${spill} 2>&1 & __pc_pid=$!; ` +
73
+ `printf 'MODE nohup\\nPID %s\\n' "$__pc_pid" > ${metaTmp} && mv -f ${metaTmp} ${meta}; ` +
74
+ `${handshake(nohupKill)}; ` +
75
+ `printf 'MODE nohup\\nPID %s\\n' "$__pc_pid"`;
76
+ // `umask 077`: the spill holds whatever the command printed (routinely credentials) in a
77
+ // world-readable /tmp; set the mask rather than chmod afterwards so there is no readable window.
78
+ return (`umask 077; rm -f ${exitFile} ${exitTmp} ${ready} ${readyTmp} ${meta} ${metaTmp}; ` +
79
+ `if command -v setsid >/dev/null 2>&1; then ${setsidBranch}; else ${nohupBranch}; fi`);
80
+ }
81
+ /** Outcomes that prove the job's process is gone — safe to apply a terminal status. */
82
+ const KILL_CONFIRMED_GONE = new Set([
83
+ "terminated",
84
+ "gone",
85
+ "identity-mismatch",
86
+ "no-target",
87
+ ]);
13
88
  /** Cap on concurrently running jobs per channel, so a runaway model can't spawn unbounded processes. */
14
89
  export const MAX_RUNNING_JOBS = 5;
15
90
  /** Longest a single `poll` call blocks before returning a snapshot; the model can poll again. */
@@ -54,6 +129,51 @@ function parseJobRecord(raw) {
54
129
  }
55
130
  return value;
56
131
  }
132
+ /**
133
+ * Read the launch command's stdout: an optional `MODE setsid|nohup` line followed by `PID <n>`
134
+ * and — only in `setsid` mode — `PGID <n>` / `LSTART <...>`. A bare number on its own line is also
135
+ * accepted as the pid so older/simpler executor fakes keep working. `pgid` and `pidStartedAt` are
136
+ * returned only when the job was launched under `setsid` *and* `ps` actually reported them; the
137
+ * `nohup` fallback never yields them, and the caller must then treat identity as unprovable.
138
+ */
139
+ function parseLaunchOutput(stdout) {
140
+ let pid;
141
+ let pgid;
142
+ let pidStartedAt;
143
+ let mode;
144
+ let handshakeFailed = false;
145
+ for (const raw of stdout.split("\n")) {
146
+ const line = raw.trim();
147
+ if (!line)
148
+ continue;
149
+ if (line === "HANDSHAKE failed") {
150
+ handshakeFailed = true;
151
+ continue;
152
+ }
153
+ if (/^\d+$/.test(line)) {
154
+ pid ??= Number.parseInt(line, 10);
155
+ continue;
156
+ }
157
+ const match = line.match(/^(MODE|PID|PGID|LSTART)\s+(.*)$/);
158
+ if (!match)
159
+ continue;
160
+ const [, key, value] = match;
161
+ if (key === "MODE" && (value === "setsid" || value === "nohup"))
162
+ mode = value;
163
+ else if (key === "PID" && /^\d+$/.test(value))
164
+ pid = Number.parseInt(value, 10);
165
+ else if (key === "PGID" && /^\d+$/.test(value))
166
+ pgid = Number.parseInt(value, 10);
167
+ else if (key === "LSTART" && value)
168
+ pidStartedAt = value;
169
+ }
170
+ // The nohup fallback cannot capture these reliably; drop them even if something printed them.
171
+ if (mode === "nohup") {
172
+ pgid = undefined;
173
+ pidStartedAt = undefined;
174
+ }
175
+ return { pid, pgid, pidStartedAt, mode, handshakeFailed };
176
+ }
57
177
  function sleep(ms, signal) {
58
178
  return new Promise((resolve) => {
59
179
  const timer = setTimeout(resolve, ms);
@@ -81,6 +201,14 @@ export class ChannelJobManager {
81
201
  this.executor = executor;
82
202
  this.jobs = new Map();
83
203
  this.wakeQueue = createSerialQueue();
204
+ /**
205
+ * Serializes every probe → decide → terminal-transition sequence for a single job. The sweeper,
206
+ * `list`/`poll`/`restore` (via `refresh`), `cancel`, and the persist-failure rollback all pass
207
+ * through it, so two callers can never race the same job to two terminal states (e.g. both see
208
+ * `pendingKill`, both `finish`, the second reading a now-cleared `pendingKill` and writing a
209
+ * bogus status). Inside the slot each op re-checks `record.status`.
210
+ */
211
+ this.reconcileQueue = createSerialQueue();
84
212
  this.sweeping = false;
85
213
  // A bare number keeps the original `sweepIntervalMs` positional form working for tests.
86
214
  this.options = typeof options === "number" ? { sweepIntervalMs: options } : options;
@@ -108,8 +236,22 @@ export class ChannelJobManager {
108
236
  }
109
237
  async forget(record) {
110
238
  this.jobs.delete(record.id);
111
- const path = this.recordPath(record.id);
112
- await Promise.all([path, record.spillFile, record.exitFile]
239
+ const art = jobArtifacts(record.spillFile);
240
+ await this.unlinkArtifacts(art, this.recordPath(record.id));
241
+ }
242
+ /** Remove a job's scratch files (and optionally its persisted record). Every unlink is best-effort. */
243
+ async unlinkArtifacts(art, recordPath) {
244
+ const targets = [
245
+ recordPath,
246
+ art.spillFile,
247
+ art.exitFile,
248
+ art.exitTmp,
249
+ art.readyFile,
250
+ art.readyTmp,
251
+ art.metaFile,
252
+ art.metaTmp,
253
+ ];
254
+ await Promise.all(targets
113
255
  .filter((target) => Boolean(target))
114
256
  .map((target) => unlink(target).catch(() => undefined)));
115
257
  }
@@ -168,9 +310,11 @@ export class ChannelJobManager {
168
310
  return ids;
169
311
  }
170
312
  /**
171
- * Launch a command in the background and return its job id. The wrapper writes merged
172
- * stdout/stderr to a spill file and the command's exit code to a sibling `.exit` file, then
173
- * `echo $!` hands back the nohup PID for later probing/cancellation.
313
+ * Launch a command in the background and return its snapshot. The wrapper (`buildLaunchScript`)
314
+ * runs a readiness handshake before the command executes: only after the inner shell proves it
315
+ * started — spill writable, `setsid`/`sh` execed — does the parent print `MODE`/`PID` and exit
316
+ * 0. A failed handshake, a non-zero launch, or an interrupted launch never creates a `running`
317
+ * record; a persist failure right after a successful launch terminates the process (see below).
174
318
  */
175
319
  async start(command, label, timeoutSeconds, options = {}) {
176
320
  if (this.runningCount() >= MAX_RUNNING_JOBS) {
@@ -178,20 +322,36 @@ export class ChannelJobManager {
178
322
  }
179
323
  const id = randomBytes(6).toString("hex");
180
324
  const spillFile = jobSpillPath(id);
181
- const exitFile = `${spillFile}.exit`;
182
- // Run the user command inside a subshell so its own `exit` only leaves the subshell and the
183
- // exit-capture line still runs; otherwise a command ending in `exit N` would skip it and the
184
- // job would look `lost` instead of finished.
185
- const inner = `( ${command} )\n__pc_rc=$?; echo "$__pc_rc" > ${shellEscape(exitFile)}`;
186
- // `umask 077` first: the spill file holds whatever the command printed, which routinely
187
- // includes credentials, and it is created in a world-readable /tmp. Setting the mask rather
188
- // than chmod-ing afterwards leaves no window where the file is readable by others.
189
- const launch = `umask 077; rm -f ${shellEscape(exitFile)}; ` +
190
- `nohup sh -c ${shellEscape(inner)} > ${shellEscape(spillFile)} 2>&1 & echo $!`;
191
- const result = await this.executor.exec(launch, { signal: options.signal });
192
- const pid = Number.parseInt(result.stdout.trim(), 10);
193
- if (!Number.isFinite(pid) || pid <= 0) {
194
- throw new Error(`Failed to start background job: ${result.stderr.trim() || "no PID returned"}`);
325
+ const art = jobArtifacts(spillFile);
326
+ const launch = buildLaunchScript(command, art);
327
+ let result;
328
+ try {
329
+ result = await this.executor.exec(launch, { signal: options.signal });
330
+ }
331
+ catch (error) {
332
+ // The launch was aborted (or the executor could not run it). A detached child may
333
+ // already be running — try to recover its pid and clean it up honestly.
334
+ throw await this.recoverInterruptedLaunch(command, art, error);
335
+ }
336
+ const launched = parseLaunchOutput(result.stdout);
337
+ if (result.code !== 0 || launched.handshakeFailed) {
338
+ // The wrapper's readiness handshake never completed: the inner shell could not start
339
+ // (spill unwritable, `setsid`/`sh` exec failure, …). It has already killed whatever it
340
+ // spawned; drop the scratch files and surface the inner error.
341
+ await this.unlinkArtifacts(art);
342
+ const detail = result.stdout
343
+ .split("\n")
344
+ .filter((line) => line.trim() &&
345
+ !/^(MODE|PID|PGID|LSTART|HANDSHAKE) /.test(line) &&
346
+ line.trim() !== "HANDSHAKE failed")
347
+ .join(" ")
348
+ .trim() || result.stderr.trim();
349
+ throw new Error(`Failed to start background job "${label}"${detail ? `: ${detail}` : " — launch handshake did not complete"}`);
350
+ }
351
+ const pid = launched.pid;
352
+ if (pid === undefined || !Number.isFinite(pid) || pid <= 0) {
353
+ await this.unlinkArtifacts(art);
354
+ throw new Error(`Failed to start background job "${label}": ${result.stderr.trim() || "no PID returned"}`);
195
355
  }
196
356
  const now = Date.now();
197
357
  const record = {
@@ -202,16 +362,97 @@ export class ChannelJobManager {
202
362
  startedAt: now,
203
363
  durationMs: 0,
204
364
  pid,
365
+ ...(launched.pgid !== undefined ? { pgid: launched.pgid } : {}),
366
+ ...(launched.pidStartedAt ? { pidStartedAt: launched.pidStartedAt } : {}),
205
367
  spillFile,
206
- exitFile,
368
+ exitFile: art.exitFile,
207
369
  timeoutSeconds,
208
370
  contract: { notify: options.notify ?? true, ...(options.taskId ? { taskId: options.taskId } : {}) },
209
371
  };
210
372
  this.jobs.set(id, record);
211
- await this.persist(record);
373
+ // The persisted record is the only thing that survives a restart — a detached process
374
+ // outlives the daemon, and losing its record means an orphan holding a slot with unreachable
375
+ // output. So the first persist is required: if it fails, terminate what we just launched and
376
+ // surface the failure instead of returning a job the caller can never recover (T1).
377
+ try {
378
+ await this.persist(record, true);
379
+ }
380
+ catch (error) {
381
+ // The rollback kill + bookkeeping run inside the job's reconcile slot so a sweeper tick
382
+ // that has already adopted this record cannot transition it underneath us. Cleanup must
383
+ // not inherit the caller's AbortSignal (it may already be aborted).
384
+ const reason = `its record could not be persisted (${errorMessage(error)})`;
385
+ const failure = await this.reconcileQueue.run(id, async () => {
386
+ const outcome = await this.runKill(record);
387
+ if (!KILL_CONFIRMED_GONE.has(outcome)) {
388
+ // The process could not be confirmed gone (kill unconfirmed, or the executor could
389
+ // not run it). Deleting the only trace of a live process is exactly the orphan this
390
+ // path exists to prevent — keep the in-memory record manageable so the sweeper keeps
391
+ // trying, and say so plainly.
392
+ record.pendingKill = "cancelled";
393
+ this.ensureSweeper();
394
+ return new Error(`Background job started but ${reason}; its process (pid ${pid}) could not be confirmed terminated. ` +
395
+ `The job is left tracked in memory (id ${id}) so the sweeper keeps retrying — cancel it once the executor recovers. No record was persisted.`);
396
+ }
397
+ this.jobs.delete(id);
398
+ await this.forget(record).catch(() => undefined);
399
+ const tail = outcome === "terminated" ? "its process was terminated" : "its process was already gone";
400
+ return new Error(`Background job started but ${reason}; ${tail}. No job was created.`);
401
+ });
402
+ throw failure;
403
+ }
212
404
  this.ensureSweeper();
213
405
  return toSnapshot(record);
214
406
  }
407
+ /**
408
+ * Recover from a launch that rejected (an abort landed after the wrapper had already spawned the
409
+ * detached child, or the executor failed outright). The wrapper writes a metadata file *before*
410
+ * its readiness handshake, so even an interrupted launch usually leaves a recoverable pid;
411
+ * clean it up with no caller signal and return an error that is honest about what is known.
412
+ */
413
+ async recoverInterruptedLaunch(command, art, error) {
414
+ const cause = errorMessage(error);
415
+ const partialStdout = typeof error.stdout === "string" ? error.stdout : "";
416
+ let launched = parseLaunchOutput(partialStdout);
417
+ for (const metaPath of [art.metaFile, art.metaTmp]) {
418
+ if (launched.pid !== undefined)
419
+ break;
420
+ try {
421
+ launched = parseLaunchOutput(await readFile(metaPath, "utf-8"));
422
+ }
423
+ catch {
424
+ // no metadata at this path
425
+ }
426
+ }
427
+ const pid = launched.pid;
428
+ if (pid === undefined || !Number.isFinite(pid) || pid <= 0) {
429
+ await this.unlinkArtifacts(art);
430
+ return new Error(`Background job launch was interrupted (${cause}); no pid could be recovered, so whether the command actually started cannot be confirmed. No job was created.`);
431
+ }
432
+ const provisional = {
433
+ id: "(interrupted-launch)",
434
+ label: "(interrupted launch)",
435
+ command,
436
+ status: "running",
437
+ startedAt: Date.now(),
438
+ durationMs: 0,
439
+ pid,
440
+ ...(launched.pgid !== undefined ? { pgid: launched.pgid } : {}),
441
+ ...(launched.pidStartedAt ? { pidStartedAt: launched.pidStartedAt } : {}),
442
+ spillFile: art.spillFile,
443
+ exitFile: art.exitFile,
444
+ timeoutSeconds: 0,
445
+ contract: { notify: false },
446
+ };
447
+ const outcome = await this.runKill(provisional); // deliberately no signal
448
+ await this.unlinkArtifacts(art);
449
+ const tail = KILL_CONFIRMED_GONE.has(outcome)
450
+ ? outcome === "terminated"
451
+ ? `its process (pid ${pid}) was terminated`
452
+ : `its process (pid ${pid}) was already gone`
453
+ : `termination of its process (pid ${pid}) could not be confirmed — verify it manually`;
454
+ return new Error(`Background job launch was interrupted (${cause}); recovered and ${tail}. No job was created.`);
455
+ }
215
456
  /**
216
457
  * Start the low-frequency sweeper if it is not already running. It reaps finished/timed-out jobs
217
458
  * so their slots free up even when the model never polls, and stops itself once nothing is running.
@@ -248,7 +489,15 @@ export class ChannelJobManager {
248
489
  // long as any job lives, so per-job spawns are the steady-state cost of backgrounding.
249
490
  const probes = await this.probeAll(running);
250
491
  for (const record of running) {
251
- await this.applyProbe(record, probes.get(record.id) ?? "").catch((error) => {
492
+ // The batched probe is a read; the state transition it implies still goes through the
493
+ // per-job slot so it cannot race a concurrent list/poll/cancel.
494
+ await this.reconcileQueue
495
+ .run(record.id, async () => {
496
+ if (record.status !== "running")
497
+ return;
498
+ await this.applyProbe(record, probes.get(record.id) ?? "");
499
+ })
500
+ .catch((error) => {
252
501
  log.logWarning(`Background job sweep failed to refresh job ${record.id}`, errorMessage(error));
253
502
  });
254
503
  }
@@ -262,10 +511,11 @@ export class ChannelJobManager {
262
511
  }
263
512
  }
264
513
  /**
265
- * Probe every given job in one shell invocation, returning `id → EXIT:<code>|ALIVE|GONE`.
514
+ * Probe every given job in one shell invocation, returning
515
+ * `id → EXIT:<code> | ALIVE | GONE | DIFFERENT | UNKNOWN`.
266
516
  *
267
517
  * Each job contributes one branch that reads its exit-code file if present and otherwise checks
268
- * PID liveness — exactly what the single-job probe did, just batched.
518
+ * liveness (three-state when a start time was captured — see the inline comment).
269
519
  */
270
520
  async probeAll(records, signal) {
271
521
  const states = new Map();
@@ -276,9 +526,27 @@ export class ChannelJobManager {
276
526
  .map((record) => {
277
527
  const id = shellEscape(record.id);
278
528
  const exitFile = shellEscape(record.exitFile);
279
- return (`if [ -f ${exitFile} ]; then printf '%s EXIT:%s\\n' ${id} "$(cat ${exitFile})"; ` +
280
- `elif kill -0 ${record.pid} 2>/dev/null; then printf '%s ALIVE\\n' ${id}; ` +
281
- `else printf '%s GONE\\n' ${id}; fi`);
529
+ // Liveness: when the job's start time was captured, require the pid to still report
530
+ // that exact `ps -o lstart=` — a recycled pid then reads as GONE, not ALIVE, so the
531
+ // manager never mistakes an unrelated process for the job. Older records without a
532
+ // captured start time fall back to a bare `kill -0`, the best they can do.
533
+ // `-s`, not `-f`: an existing-but-empty `.exit` file (a torn write) must not count as
534
+ // a finished job. The writer renames a fully-written temp file into place, so `-s`
535
+ // here only ever sees the settled value (T4).
536
+ //
537
+ // Identity liveness is three-state: with a captured start time, `ps` reporting the
538
+ // *same* lstart is ALIVE, a *different* one is DIFFERENT (pid recycled — our process
539
+ // is gone), and `ps` returning nothing while `kill -0` still says alive is UNKNOWN
540
+ // (do not conclude anything — a later probe retries). Legacy records have only
541
+ // `kill -0`: ALIVE / GONE.
542
+ const liveness = record.pidStartedAt
543
+ ? `__pc_cur="$(ps -o lstart= -p ${record.pid} 2>/dev/null)"; ` +
544
+ `if [ -z "$__pc_cur" ]; then ` +
545
+ `if kill -0 ${record.pid} 2>/dev/null; then printf '%s UNKNOWN\\n' ${id}; else printf '%s GONE\\n' ${id}; fi; ` +
546
+ `elif [ "$__pc_cur" = ${shellEscape(record.pidStartedAt)} ]; then printf '%s ALIVE\\n' ${id}; ` +
547
+ `else printf '%s DIFFERENT\\n' ${id}; fi`
548
+ : `if kill -0 ${record.pid} 2>/dev/null; then printf '%s ALIVE\\n' ${id}; else printf '%s GONE\\n' ${id}; fi`;
549
+ return `if [ -s ${exitFile} ]; then printf '%s EXIT:%s\\n' ${id} "$(cat ${exitFile})"; else ${liveness}; fi`;
282
550
  })
283
551
  .join("\n");
284
552
  const probe = await this.executor.exec(script, { signal });
@@ -298,33 +566,90 @@ export class ChannelJobManager {
298
566
  * to say nothing.
299
567
  */
300
568
  async refresh(record, signal, announce = true) {
569
+ await this.reconcileQueue.run(record.id, () => this.reconcileLocked(record, signal, announce));
570
+ }
571
+ /**
572
+ * Probe one job and apply the result. The unlocked core of `refresh` — every caller must already
573
+ * hold the job's `reconcileQueue` slot (`refresh`, or `cancel`'s combined critical section).
574
+ */
575
+ async reconcileLocked(record, signal, announce = true) {
301
576
  if (record.status !== "running") {
302
577
  return;
303
578
  }
304
579
  const probes = await this.probeAll([record], signal);
305
580
  await this.applyProbe(record, probes.get(record.id) ?? "", signal, announce);
306
581
  }
307
- /** Turn one probe result into a status transition; an unrecognized result only ages the job. */
582
+ /**
583
+ * The terminal status for a job a probe just showed as finished/gone. A cancel or timeout kill
584
+ * already in flight (`pendingKill`) wins over the raw probe result — a job the model asked to
585
+ * cancel lands `cancelled`, a timed-out one `failed`/124 — even if the process happened to exit
586
+ * on its own first. Clears `pendingKill`; call only immediately before `finish`.
587
+ */
588
+ takePendingTerminal(record, fallbackStatus, fallbackExitCode) {
589
+ const pending = record.pendingKill;
590
+ record.pendingKill = undefined;
591
+ if (pending === "cancelled")
592
+ return { status: "cancelled", exitCode: undefined };
593
+ if (pending === "failed")
594
+ return { status: "failed", exitCode: 124 };
595
+ return { status: fallbackStatus, exitCode: fallbackExitCode };
596
+ }
597
+ /** Turn one probe result into a status transition; an inconclusive result only ages the job. */
308
598
  async applyProbe(record, out, signal, announce = true) {
309
599
  if (record.status !== "running") {
310
600
  return;
311
601
  }
312
602
  if (out.startsWith("EXIT:")) {
313
- const code = Number.parseInt(out.slice("EXIT:".length).trim(), 10);
314
- record.exitCode = Number.isFinite(code) ? code : undefined;
315
- await this.finish(record, code === 0 ? "completed" : "failed", signal, announce);
603
+ const rawCode = out.slice("EXIT:".length).trim();
604
+ // A present `.exit` file whose contents are not yet a whole integer means the writer is
605
+ // mid-write (or wrote garbage). Do not force a terminal status off it — leave the job
606
+ // running so a later probe can read the settled value; only the checks below still apply.
607
+ if (/^-?\d+$/.test(rawCode)) {
608
+ const code = Number.parseInt(rawCode, 10);
609
+ const t = this.takePendingTerminal(record, code === 0 ? "completed" : "failed", code);
610
+ record.exitCode = t.exitCode;
611
+ await this.finish(record, t.status, signal, announce);
612
+ return;
613
+ }
614
+ }
615
+ else if (out === "GONE" || out === "DIFFERENT") {
616
+ // GONE: vanished without an exit code (killed externally, host rebooted). DIFFERENT: the
617
+ // pid now belongs to an unrelated process, so ours is definitively gone. Either way the
618
+ // job is over. (`UNKNOWN` deliberately does NOT land here — `ps` being briefly
619
+ // unavailable must not terminalize a live job; a later probe retries.)
620
+ const t = this.takePendingTerminal(record, "lost", undefined);
621
+ record.exitCode = t.exitCode;
622
+ await this.finish(record, t.status, signal, announce);
316
623
  return;
317
624
  }
318
- if (out === "GONE") {
319
- // Process vanished without writing an exit code (killed externally, or the host rebooted).
320
- await this.finish(record, "lost", signal, announce);
625
+ // Still running (ALIVE / UNKNOWN / torn-EXIT). A cancel or timeout whose kill could not be
626
+ // confirmed earlier retries here every sweep until the process is proven gone.
627
+ if (record.pendingKill) {
628
+ const outcome = await this.runKill(record, signal);
629
+ if (record.status === "running" && KILL_CONFIRMED_GONE.has(outcome)) {
630
+ const t = this.takePendingTerminal(record, "lost", undefined);
631
+ record.exitCode = t.exitCode;
632
+ await this.finish(record, t.status, signal, announce);
633
+ }
321
634
  return;
322
635
  }
323
- // Still alive: enforce the wall-clock budget from JS so we do not depend on a `timeout` binary.
636
+ // Wall-clock budget, enforced from JS so we do not depend on a `timeout` binary. Only fall
637
+ // to a terminal status once the kill is confirmed; otherwise mark it pending and keep
638
+ // managing it (the sweeper retries).
324
639
  if (Date.now() - record.startedAt > record.timeoutSeconds * 1000) {
325
- await this.kill(record, signal);
326
- record.exitCode = 124;
327
- await this.finish(record, "failed", signal, announce);
640
+ const outcome = await this.runKill(record, signal);
641
+ if (record.status !== "running")
642
+ return;
643
+ if (KILL_CONFIRMED_GONE.has(outcome)) {
644
+ const t = this.takePendingTerminal(record, "failed", 124);
645
+ record.exitCode = t.exitCode;
646
+ await this.finish(record, t.status, signal, announce);
647
+ }
648
+ else if (!record.pendingKill) {
649
+ // Kill unconfirmed: keep managing it. A cancel already in flight keeps its intent.
650
+ record.pendingKill = "failed";
651
+ await this.persist(record).catch(() => undefined);
652
+ }
328
653
  }
329
654
  }
330
655
  /** Move a job to a terminal status: record it, persist it, and wake the channel once. */
@@ -394,10 +719,62 @@ export class ChannelJobManager {
394
719
  record.notified = true;
395
720
  await this.persist(record);
396
721
  }
397
- async kill(record, signal) {
398
- await this.executor
399
- .exec(`kill ${record.pid} 2>/dev/null; sleep 0.2; kill -9 ${record.pid} 2>/dev/null; true`, { signal })
400
- .catch(() => { });
722
+ /**
723
+ * The shell command that terminates `record`'s process and prints one token describing what
724
+ * happened (`TERMINATED` / `GONE` / `IDENTITY_MISMATCH` / `UNCONFIRMED`), or `undefined` when
725
+ * there is no pid we can safely signal.
726
+ *
727
+ * A negative-PGID target is used only when `setsid` gave the job pgid == pid (spec: everything
728
+ * the command spawned dies with it). When a start time was captured it is checked first: a
729
+ * recycled pid reads as `IDENTITY_MISMATCH` and is never signalled; a pid `ps` cannot see but
730
+ * that `kill -0` says is alive reads as `UNCONFIRMED` (do not signal what we cannot prove is
731
+ * ours). Legacy / nohup records have only `kill -0` liveness and a plain pid kill.
732
+ */
733
+ killCommand(record) {
734
+ const pid = record.pid;
735
+ if (!Number.isFinite(pid) || pid <= 1)
736
+ return undefined;
737
+ const groupSafe = record.pgid !== undefined && record.pgid === pid;
738
+ const target = groupSafe ? `"-${pid}"` : `${pid}`;
739
+ const gate = record.pidStartedAt
740
+ ? `__pc_cur="$(ps -o lstart= -p ${pid} 2>/dev/null)"; ` +
741
+ `if [ -z "$__pc_cur" ]; then ` +
742
+ `if kill -0 ${pid} 2>/dev/null; then printf 'UNCONFIRMED\\n'; exit 0; else printf 'GONE\\n'; exit 0; fi; fi; ` +
743
+ `if [ "$__pc_cur" != ${shellEscape(record.pidStartedAt)} ]; then printf 'IDENTITY_MISMATCH\\n'; exit 0; fi; `
744
+ : `if ! kill -0 ${pid} 2>/dev/null; then printf 'GONE\\n'; exit 0; fi; `;
745
+ return (gate +
746
+ `kill -TERM ${target} 2>/dev/null; sleep 0.2; kill -KILL ${target} 2>/dev/null; sleep 0.05; ` +
747
+ `if kill -0 ${pid} 2>/dev/null; then printf 'UNCONFIRMED\\n'; else printf 'TERMINATED\\n'; fi`);
748
+ }
749
+ /**
750
+ * Run one kill attempt and classify it from the printed token plus the executor result — never
751
+ * from "the shell exited 0". Used by cancel, timeout, the persist-failure rollback and the
752
+ * interrupted-launch recovery; the last two pass no signal so an aborted caller cannot skip it.
753
+ */
754
+ async runKill(record, signal) {
755
+ const command = this.killCommand(record);
756
+ if (!command)
757
+ return "no-target";
758
+ let result;
759
+ try {
760
+ result = await this.executor.exec(command, signal ? { signal } : {});
761
+ }
762
+ catch {
763
+ return "not-submitted";
764
+ }
765
+ const token = result.stdout.trim().split("\n").pop()?.trim() ?? "";
766
+ switch (token) {
767
+ case "TERMINATED":
768
+ return "terminated";
769
+ case "GONE":
770
+ return "gone";
771
+ case "IDENTITY_MISMATCH":
772
+ return "identity-mismatch";
773
+ case "UNCONFIRMED":
774
+ return "unconfirmed";
775
+ default:
776
+ return "not-submitted";
777
+ }
401
778
  }
402
779
  async list(signal) {
403
780
  for (const record of this.jobs.values()) {
@@ -447,16 +824,34 @@ export class ChannelJobManager {
447
824
  results.push({ id, status: "not_found" });
448
825
  continue;
449
826
  }
450
- await this.refresh(record, signal);
451
- if (record.status !== "running") {
452
- results.push({ id, status: record.status });
453
- continue;
454
- }
455
- await this.kill(record, signal);
456
- // An explicit cancel is the model's own decision, so it needs no wake to learn about it.
457
- record.contract.notify = false;
458
- await this.finish(record, "cancelled", signal);
459
- results.push({ id, status: "cancelled" });
827
+ // Whole per-job critical section (refresh + kill + transition) under one slot, so the
828
+ // sweeper cannot land a different terminal state on this job while we decide.
829
+ const result = await this.reconcileQueue.run(id, async () => {
830
+ await this.reconcileLocked(record, signal);
831
+ if (record.status !== "running") {
832
+ return { id, status: record.status };
833
+ }
834
+ // An explicit cancel is the model's own decision, so it needs no wake to learn about it.
835
+ record.contract.notify = false;
836
+ const outcome = await this.runKill(record, signal);
837
+ if (KILL_CONFIRMED_GONE.has(outcome)) {
838
+ // A timeout kill already pending (`failed`/124) outranks this cancel — the job did
839
+ // overrun its budget. `takePendingTerminal` applies that precedence and only falls
840
+ // back to `cancelled` when nothing was pending.
841
+ const t = this.takePendingTerminal(record, "cancelled", undefined);
842
+ record.exitCode = t.exitCode;
843
+ await this.finish(record, t.status, signal);
844
+ return { id, status: t.status };
845
+ }
846
+ // The kill ran but the process is still alive, or the executor could not run it. Keep
847
+ // the job running and managed — the sweeper and a repeat `cancel` keep trying — and
848
+ // report the still-running status. Do not clobber an existing timeout intent.
849
+ record.pendingKill ??= "cancelled";
850
+ await this.persist(record).catch(() => undefined);
851
+ this.ensureSweeper();
852
+ return { id, status: record.status };
853
+ });
854
+ results.push(result);
460
855
  }
461
856
  return results;
462
857
  }
@@ -569,17 +964,6 @@ let runtimeConfig = {};
569
964
  export function configureJobRuntime(config) {
570
965
  runtimeConfig = config;
571
966
  }
572
- /**
573
- * Which of this channel's tasks a running background job will wake, without needing an `Executor`.
574
- *
575
- * Read-only view for `/tasks doctor`: a parked task (`waiting`, no `wake`) is healthy exactly when
576
- * something is going to call it. Managers are created lazily by the tool layer *and* eagerly at
577
- * startup by `restoreChannelJobs`, so a channel with live jobs always has one; a channel with no
578
- * manager simply has no jobs, and the empty set is the right answer.
579
- */
580
- export function channelJobTaskIds(channelId) {
581
- return managers.get(channelId)?.runningTaskIds() ?? new Set();
582
- }
583
967
  /**
584
968
  * Human-readable lines naming this channel's currently running background jobs, for the `/project
585
969
  * set|reset` blocker check (spec 043, D4.3) — mirrors `channelJobTaskIds`'s "no manager means no