@oyasmi/pipiclaw 0.9.5-beta.2 → 0.9.5-beta.3

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 (272) hide show
  1. package/README.en.md +9 -11
  2. package/README.md +9 -11
  3. package/dist/agent/channel-runner.d.ts +12 -24
  4. package/dist/agent/channel-runner.js +74 -30
  5. package/dist/agent/maintenance-context.d.ts +2 -0
  6. package/dist/agent/maintenance-context.js +15 -0
  7. package/dist/agent/prompt/sections.js +8 -6
  8. package/dist/agent/prompt/types.d.ts +1 -1
  9. package/dist/agent/runner-factory.js +1 -1
  10. package/dist/agent/session/command-extension.js +11 -0
  11. package/dist/agent/session/compaction-summary.js +6 -2
  12. package/dist/agent/session/execution-trace.d.ts +14 -0
  13. package/dist/agent/session/execution-trace.js +57 -0
  14. package/dist/agent/session/session-events.d.ts +2 -7
  15. package/dist/agent/session/session-events.js +35 -12
  16. package/dist/agent/session/session-host.d.ts +12 -22
  17. package/dist/agent/session/session-host.js +46 -65
  18. package/dist/agent/turn/task-digest.d.ts +1 -2
  19. package/dist/agent/turn/task-digest.js +33 -33
  20. package/dist/agent/turn/turn-context.d.ts +1 -1
  21. package/dist/agent/turn/turn-context.js +1 -1
  22. package/dist/agent/turn/turn-finish.d.ts +2 -2
  23. package/dist/agent/turn/turn-finish.js +3 -2
  24. package/dist/agent/turn/turn-pipeline.d.ts +4 -2
  25. package/dist/agent/turn/turn-pipeline.js +33 -5
  26. package/dist/agent/types.d.ts +64 -14
  27. package/dist/agent/types.js +3 -0
  28. package/dist/app/home.js +3 -4
  29. package/dist/channel/channel-event.d.ts +4 -12
  30. package/dist/channel/ingress.d.ts +1 -9
  31. package/dist/channel/store.d.ts +1 -1
  32. package/dist/commands/catalog.js +25 -19
  33. package/dist/commands/router.d.ts +5 -2
  34. package/dist/commands/router.js +9 -4
  35. package/dist/config/settings.d.ts +5 -12
  36. package/dist/config/settings.js +0 -7
  37. package/dist/config/tools.d.ts +2 -2
  38. package/dist/config/tools.js +2 -2
  39. package/dist/dingtalk/bot.d.ts +2 -0
  40. package/dist/dingtalk/bot.js +4 -0
  41. package/dist/dingtalk/cards.d.ts +7 -0
  42. package/dist/dingtalk/cards.js +32 -2
  43. package/dist/dingtalk/delivery.d.ts +5 -1
  44. package/dist/dingtalk/delivery.js +157 -142
  45. package/dist/dingtalk/progress.d.ts +55 -6
  46. package/dist/dingtalk/progress.js +195 -16
  47. package/dist/file-store.d.ts +4 -0
  48. package/dist/file-store.js +6 -1
  49. package/dist/jobs/completion-observer.d.ts +20 -0
  50. package/dist/jobs/completion-observer.js +107 -0
  51. package/dist/jobs/completion-signal.d.ts +9 -0
  52. package/dist/jobs/completion-signal.js +32 -0
  53. package/dist/jobs/completion-wake.d.ts +1 -1
  54. package/dist/jobs/completion-wake.js +2 -13
  55. package/dist/jobs/manager.d.ts +11 -29
  56. package/dist/jobs/manager.js +103 -176
  57. package/dist/jobs/probe.d.ts +3 -0
  58. package/dist/jobs/probe.js +42 -0
  59. package/dist/jobs/record.d.ts +3 -6
  60. package/dist/jobs/runtime.d.ts +28 -0
  61. package/dist/jobs/runtime.js +69 -0
  62. package/dist/memory/boundary-work.d.ts +2 -0
  63. package/dist/memory/boundary-work.js +79 -37
  64. package/dist/memory/commands.js +4 -1
  65. package/dist/memory/index-budget.js +18 -15
  66. package/dist/memory/journal.js +2 -1
  67. package/dist/memory/lifecycle.d.ts +4 -8
  68. package/dist/memory/lifecycle.js +21 -51
  69. package/dist/memory/reflect-job.d.ts +0 -6
  70. package/dist/memory/reflect-job.js +13 -34
  71. package/dist/memory/reflect.d.ts +4 -0
  72. package/dist/memory/reflect.js +32 -5
  73. package/dist/memory/review-log.d.ts +13 -0
  74. package/dist/memory/review-log.js +49 -0
  75. package/dist/memory/search.js +7 -4
  76. package/dist/memory/source-window.d.ts +18 -1
  77. package/dist/memory/source-window.js +59 -9
  78. package/dist/memory/store.d.ts +2 -0
  79. package/dist/memory/store.js +45 -13
  80. package/dist/playbooks/agent-delegation.md +10 -4
  81. package/dist/playbooks/background-jobs.md +4 -4
  82. package/dist/playbooks/event-scheduling.md +2 -2
  83. package/dist/playbooks/memory-and-learning.md +3 -3
  84. package/dist/playbooks/outbound-media.md +2 -2
  85. package/dist/playbooks/runtime-orientation.md +10 -6
  86. package/dist/playbooks/task-lead.md +54 -33
  87. package/dist/runtime/bootstrap.d.ts +11 -24
  88. package/dist/runtime/bootstrap.js +92 -59
  89. package/dist/runtime/channel-queue.d.ts +2 -0
  90. package/dist/runtime/channel-queue.js +5 -1
  91. package/dist/runtime/durable-dispatch.d.ts +7 -0
  92. package/dist/runtime/durable-dispatch.js +66 -7
  93. package/dist/runtime/ingress-busy.d.ts +1 -2
  94. package/dist/runtime/ingress-busy.js +2 -35
  95. package/dist/runtime/ingress-commands.d.ts +1 -1
  96. package/dist/runtime/ingress-commands.js +28 -20
  97. package/dist/runtime/ingress-deps.d.ts +4 -7
  98. package/dist/runtime/ingress.js +23 -13
  99. package/dist/runtime/shutdown.d.ts +1 -1
  100. package/dist/runtime/shutdown.js +2 -2
  101. package/dist/runtime/task-close.d.ts +4 -0
  102. package/dist/runtime/task-close.js +102 -0
  103. package/dist/runtime/task-control.d.ts +34 -0
  104. package/dist/runtime/task-control.js +225 -0
  105. package/dist/runtime/task-input.d.ts +13 -0
  106. package/dist/runtime/task-input.js +129 -0
  107. package/dist/runtime/task-lane-types.d.ts +123 -0
  108. package/dist/runtime/task-lane-types.js +14 -0
  109. package/dist/runtime/task-lane.d.ts +99 -0
  110. package/dist/runtime/task-lane.js +703 -0
  111. package/dist/runtime/task-pending.d.ts +8 -0
  112. package/dist/runtime/task-pending.js +40 -0
  113. package/dist/runtime/task-spawn.d.ts +4 -4
  114. package/dist/runtime/task-spawn.js +4 -4
  115. package/dist/runtime/task-step.d.ts +32 -0
  116. package/dist/runtime/task-step.js +276 -0
  117. package/dist/runtime/turn-run.d.ts +4 -16
  118. package/dist/runtime/turn-run.js +17 -155
  119. package/dist/runtime/wake-coalescing.d.ts +1 -3
  120. package/dist/runtime/wake-coalescing.js +2 -4
  121. package/dist/shared/format.d.ts +0 -6
  122. package/dist/shared/format.js +0 -17
  123. package/dist/shared/host-process.d.ts +2 -0
  124. package/dist/shared/host-process.js +16 -1
  125. package/dist/shared/jsonl-appender.d.ts +5 -0
  126. package/dist/shared/jsonl-appender.js +25 -2
  127. package/dist/skills/catalog.d.ts +9 -0
  128. package/dist/skills/catalog.js +34 -0
  129. package/dist/skills/commands.d.ts +3 -12
  130. package/dist/skills/commands.js +36 -22
  131. package/dist/skills/loader.d.ts +2 -31
  132. package/dist/skills/loader.js +101 -68
  133. package/dist/skills/roots.d.ts +12 -0
  134. package/dist/skills/roots.js +18 -0
  135. package/dist/skills/types.d.ts +24 -0
  136. package/dist/skills/types.js +1 -0
  137. package/dist/subagents/completion-wake.js +0 -10
  138. package/dist/subagents/discovery.d.ts +1 -1
  139. package/dist/subagents/discovery.js +10 -16
  140. package/dist/subagents/dispatch.js +8 -16
  141. package/dist/subagents/external/cursor-cli.d.ts +2 -0
  142. package/dist/subagents/external/cursor-cli.js +256 -0
  143. package/dist/subagents/external/harness.d.ts +5 -5
  144. package/dist/subagents/external/reconciliation.d.ts +7 -0
  145. package/dist/subagents/external/reconciliation.js +105 -0
  146. package/dist/subagents/external/recovery.d.ts +20 -0
  147. package/dist/subagents/external/recovery.js +71 -0
  148. package/dist/subagents/external/registry.js +2 -0
  149. package/dist/subagents/external/role-warnings.d.ts +17 -0
  150. package/dist/subagents/external/role-warnings.js +42 -0
  151. package/dist/subagents/external/run.js +18 -22
  152. package/dist/subagents/format.d.ts +1 -1
  153. package/dist/subagents/format.js +1 -1
  154. package/dist/subagents/grace.d.ts +2 -2
  155. package/dist/subagents/grace.js +3 -3
  156. package/dist/subagents/internal/run.js +7 -5
  157. package/dist/subagents/internal/worker.js +31 -2
  158. package/dist/subagents/result.js +2 -3
  159. package/dist/subagents/run-record.d.ts +4 -7
  160. package/dist/subagents/run-record.js +2 -2
  161. package/dist/subagents/runs.d.ts +33 -46
  162. package/dist/subagents/runs.js +126 -245
  163. package/dist/subagents/task-settlement.d.ts +3 -0
  164. package/dist/subagents/task-settlement.js +20 -0
  165. package/dist/subagents/types.d.ts +1 -2
  166. package/dist/subagents/workspace-summary.js +5 -1
  167. package/dist/tasks/archive.d.ts +11 -0
  168. package/dist/tasks/archive.js +141 -0
  169. package/dist/tasks/board.d.ts +5 -12
  170. package/dist/tasks/board.js +4 -30
  171. package/dist/tasks/bound-work.d.ts +12 -6
  172. package/dist/tasks/bound-work.js +37 -24
  173. package/dist/tasks/brief.d.ts +38 -14
  174. package/dist/tasks/brief.js +128 -70
  175. package/dist/tasks/budget.d.ts +3 -3
  176. package/dist/tasks/budget.js +9 -4
  177. package/dist/tasks/commands.d.ts +14 -9
  178. package/dist/tasks/commands.js +190 -121
  179. package/dist/tasks/completion.d.ts +12 -0
  180. package/dist/tasks/completion.js +35 -0
  181. package/dist/tasks/contract.d.ts +8 -17
  182. package/dist/tasks/contract.js +41 -43
  183. package/dist/tasks/control.d.ts +138 -0
  184. package/dist/tasks/control.js +1 -0
  185. package/dist/tasks/create.d.ts +1 -1
  186. package/dist/tasks/create.js +3 -3
  187. package/dist/tasks/delivery.d.ts +24 -0
  188. package/dist/tasks/delivery.js +221 -0
  189. package/dist/tasks/file-mutation.d.ts +5 -0
  190. package/dist/tasks/file-mutation.js +38 -0
  191. package/dist/tasks/frontmatter.d.ts +43 -28
  192. package/dist/tasks/frontmatter.js +83 -40
  193. package/dist/tasks/input-receipts.d.ts +7 -0
  194. package/dist/tasks/input-receipts.js +60 -0
  195. package/dist/tasks/loop-log.d.ts +147 -28
  196. package/dist/tasks/loop-log.js +239 -28
  197. package/dist/tasks/receipts.d.ts +19 -0
  198. package/dist/tasks/receipts.js +48 -0
  199. package/dist/tasks/state.d.ts +93 -0
  200. package/dist/tasks/state.js +156 -0
  201. package/dist/tasks/store.d.ts +81 -49
  202. package/dist/tasks/store.js +244 -147
  203. package/dist/tools/bash.d.ts +3 -5
  204. package/dist/tools/bash.js +8 -22
  205. package/dist/tools/contract/details.d.ts +6 -6
  206. package/dist/tools/contract/details.js +6 -6
  207. package/dist/tools/contract/execution-trace.d.ts +4 -0
  208. package/dist/tools/contract/execution-trace.js +23 -0
  209. package/dist/tools/contract/presentation.js +6 -2
  210. package/dist/tools/edit.d.ts +1 -0
  211. package/dist/tools/edit.js +45 -42
  212. package/dist/tools/index.d.ts +8 -12
  213. package/dist/tools/index.js +16 -6
  214. package/dist/tools/memory-manage.js +8 -1
  215. package/dist/tools/registry.d.ts +7 -11
  216. package/dist/tools/registry.js +52 -25
  217. package/dist/tools/skill.d.ts +2 -2
  218. package/dist/tools/skill.js +24 -10
  219. package/dist/tools/subagent-manage.js +7 -4
  220. package/dist/tools/subagent.d.ts +0 -2
  221. package/dist/tools/subagent.js +2 -7
  222. package/dist/tools/task-manage/control-tools.d.ts +4 -0
  223. package/dist/tools/task-manage/control-tools.js +65 -0
  224. package/dist/tools/task-manage/create.js +2 -1
  225. package/dist/tools/task-manage/factory.d.ts +12 -6
  226. package/dist/tools/task-manage/factory.js +72 -57
  227. package/dist/tools/task-manage/lifecycle.d.ts +7 -12
  228. package/dist/tools/task-manage/lifecycle.js +118 -66
  229. package/dist/tools/task-manage/log-view.js +8 -5
  230. package/dist/tools/task-manage/schema.d.ts +21 -26
  231. package/dist/tools/task-manage/schema.js +29 -35
  232. package/dist/tools/task-manage/shared.d.ts +8 -39
  233. package/dist/tools/task-manage/shared.js +19 -68
  234. package/dist/tools/task-manage/step-tools.d.ts +5 -0
  235. package/dist/tools/task-manage/step-tools.js +103 -0
  236. package/dist/tools/task-manage/types.d.ts +25 -18
  237. package/dist/tools/write-content.d.ts +1 -0
  238. package/dist/tools/write-content.js +6 -1
  239. package/dist/tools/write.d.ts +1 -0
  240. package/dist/tools/write.js +1 -0
  241. package/dist/usage/ledger.d.ts +4 -4
  242. package/dist/usage/render.js +2 -2
  243. package/dist/web/search-providers.js +0 -33
  244. package/dist/webapi/request-policy.js +1 -1
  245. package/examples/sub-agents/README.md +23 -16
  246. package/examples/sub-agents/agents/claude-high.md +1 -1
  247. package/examples/sub-agents/agents/claude-main.md +1 -1
  248. package/examples/sub-agents/agents/codex-flash.md +1 -1
  249. package/examples/sub-agents/agents/codex-high.md +1 -1
  250. package/examples/sub-agents/agents/codex-main.md +4 -4
  251. package/examples/sub-agents/agents/cursor-high.md +22 -0
  252. package/examples/sub-agents/agents/cursor-main.md +22 -0
  253. package/examples/sub-agents/agents/glm-flash.md +1 -1
  254. package/examples/sub-agents/agents/glm-high.md +2 -2
  255. package/examples/sub-agents/agents/scout.md +30 -0
  256. package/package.json +6 -6
  257. package/dist/runtime/task-driver.d.ts +0 -116
  258. package/dist/runtime/task-driver.js +0 -443
  259. package/dist/runtime/task-wake.d.ts +0 -48
  260. package/dist/runtime/task-wake.js +0 -32
  261. package/dist/shared/wake-claim.d.ts +0 -23
  262. package/dist/shared/wake-claim.js +0 -26
  263. package/dist/skills/validation.d.ts +0 -8
  264. package/dist/skills/validation.js +0 -91
  265. package/dist/skills/workspace.d.ts +0 -33
  266. package/dist/skills/workspace.js +0 -116
  267. package/dist/tasks/steer.d.ts +0 -8
  268. package/dist/tasks/steer.js +0 -81
  269. package/dist/tasks/ticket.d.ts +0 -71
  270. package/dist/tasks/ticket.js +0 -138
  271. package/dist/tools/task-manage/step-end.d.ts +0 -11
  272. package/dist/tools/task-manage/step-end.js +0 -117
@@ -2,18 +2,19 @@ import { randomBytes } from "node:crypto";
2
2
  import { chmod, mkdir, readdir, readFile, unlink } from "node:fs/promises";
3
3
  import { tmpdir } from "node:os";
4
4
  import { join } from "node:path";
5
- import { getDeskDir, getDeskLogsDir, isDeskName } from "../desk/paths.js";
6
5
  import { createFileStore } from "../file-store.js";
7
6
  import * as log from "../log.js";
8
7
  import { writeFileAtomically } from "../shared/atomic-file.js";
9
8
  import { shellEscape } from "../shared/os.js";
10
9
  import { createSerialQueue } from "../shared/serial-queue.js";
11
10
  import { errorMessage } from "../shared/text-utils.js";
12
- import { beginWakeClaim, finishWakeClaim } from "../shared/wake-claim.js";
13
11
  import { logTaskDispatch, logTaskSettlement } from "../tasks/bound-work.js";
14
- import { redeemTicket } from "../tasks/store.js";
15
- import { buildJobCompletionWake, jobWakeDispatchId } from "./completion-wake.js";
12
+ import { readStoredTask } from "../tasks/store.js";
13
+ import { JobCompletionObserver } from "./completion-observer.js";
14
+ import { CompletionSignal } from "./completion-signal.js";
15
+ import { buildJobCompletionWake } from "./completion-wake.js";
16
16
  import { buildLaunchScript, jobArtifacts, parseLaunchOutput } from "./launch.js";
17
+ import { probeJobs } from "./probe.js";
17
18
  import { isTerminal, parseJobRecord, toSnapshot } from "./record.js";
18
19
  /** Outcomes that prove the job's process is gone — safe to apply a terminal status. */
19
20
  const KILL_CONFIRMED_GONE = new Set([
@@ -40,7 +41,7 @@ export const SWEEP_INTERVAL_MS = 10_000;
40
41
  * How long a finished job's record, spill file, and exit file are kept. The model has to be able
41
42
  * to read the output after the completion wake, so they cannot be deleted the moment the job ends.
42
43
  */
43
- export const FINISHED_JOB_RETENTION_MS = 24 * 60 * 60_000;
44
+ export const FINISHED_JOB_RETENTION_MS = 7 * 24 * 60 * 60_000;
44
45
  /** Bytes of captured output carried inline in the completion wake. */
45
46
  const WAKE_OUTPUT_TAIL_BYTES = 2_000;
46
47
  /** Upper bound on how much of a spill file's tail `readOutput` reads (spec 044, D8). */
@@ -48,22 +49,14 @@ const JOB_OUTPUT_READ_MAX_BYTES = 512 * 1024;
48
49
  function jobSpillPath(id, spillDir) {
49
50
  return join(spillDir ?? tmpdir(), `pipiclaw-job-${id}.log`);
50
51
  }
51
- function sleep(ms, signal) {
52
- return new Promise((resolve) => {
53
- const timer = setTimeout(resolve, ms);
54
- signal?.addEventListener("abort", () => {
55
- clearTimeout(timer);
56
- resolve();
57
- }, { once: true });
58
- });
59
- }
60
52
  export class DeskJobManager {
61
53
  /** `target` owns these jobs (task logs live in its directory); each job's own channel gets its wake. */
62
54
  constructor(target, executor, options = {}) {
63
55
  this.target = target;
64
56
  this.executor = executor;
57
+ this.pendingCompletion = new Set();
58
+ this.completion = new CompletionSignal();
65
59
  this.jobs = new Map();
66
- this.wakeQueue = createSerialQueue();
67
60
  /**
68
61
  * Serializes every probe → decide → terminal-transition sequence for a single job. The sweeper,
69
62
  * `list`/`poll`/`restore` (via `refresh`), `cancel`, and the persist-failure rollback all pass
@@ -78,6 +71,21 @@ export class DeskJobManager {
78
71
  this.options = typeof options === "number" ? { sweepIntervalMs: options } : options;
79
72
  this.sweepIntervalMs = this.options.sweepIntervalMs ?? SWEEP_INTERVAL_MS;
80
73
  this.fileStore = this.options.fileStore ?? createFileStore();
74
+ this.observer = new JobCompletionObserver(this.fileStore, async (ids) => {
75
+ log.logEvent("debug", "job.completion.hinted", "Background job completion check requested", {
76
+ fields: { desk: this.target.desk, jobIds: ids, trigger: "watch" },
77
+ });
78
+ const records = ids.flatMap((id) => {
79
+ const record = this.jobs.get(id);
80
+ return record?.status === "running" ? [record] : [];
81
+ });
82
+ const probes = await this.probeAll(records);
83
+ for (const record of records)
84
+ await this.reconcileQueue.run(record.id, async () => {
85
+ if (!this.stopped && record.status === "running")
86
+ await this.applyProbe(record, probes.get(record.id) ?? "");
87
+ });
88
+ });
81
89
  }
82
90
  recordPath(id) {
83
91
  return this.options.stateDir ? join(this.options.stateDir, `${id}.json`) : undefined;
@@ -128,7 +136,10 @@ export class DeskJobManager {
128
136
  */
129
137
  async collectGarbage(now = Date.now()) {
130
138
  for (const record of Array.from(this.jobs.values())) {
131
- if (isTerminal(record.status) && record.finishedAt && now - record.finishedAt >= FINISHED_JOB_RETENTION_MS) {
139
+ if (isTerminal(record.status) &&
140
+ (!record.contract.taskId || record.taskLogged) &&
141
+ record.finishedAt &&
142
+ now - record.finishedAt >= FINISHED_JOB_RETENTION_MS) {
132
143
  await this.forget(record);
133
144
  }
134
145
  }
@@ -183,6 +194,7 @@ export class DeskJobManager {
183
194
  const spillFile = jobSpillPath(id, this.options.spillDir);
184
195
  const art = jobArtifacts(spillFile);
185
196
  const launch = buildLaunchScript(command, art);
197
+ this.observer.add(id, art.exitFile);
186
198
  let result;
187
199
  try {
188
200
  result = await this.executor.exec(launch, { signal: options.signal });
@@ -190,6 +202,7 @@ export class DeskJobManager {
190
202
  catch (error) {
191
203
  // The launch was aborted (or the executor could not run it). A detached child may
192
204
  // already be running — try to recover its pid and clean it up honestly.
205
+ this.observer.remove(id);
193
206
  throw await this.recoverInterruptedLaunch(art, error);
194
207
  }
195
208
  const launched = parseLaunchOutput(result.stdout);
@@ -197,6 +210,7 @@ export class DeskJobManager {
197
210
  // The wrapper's readiness handshake never completed: the inner shell could not start
198
211
  // (spill unwritable, `setsid`/`sh` exec failure, …). It has already killed whatever it
199
212
  // spawned; drop the scratch files and surface the inner error.
213
+ this.observer.remove(id);
200
214
  await this.unlinkArtifacts(art);
201
215
  const detail = result.stdout
202
216
  .split("\n")
@@ -209,6 +223,7 @@ export class DeskJobManager {
209
223
  }
210
224
  const pid = launched.pid;
211
225
  if (pid === undefined || !Number.isFinite(pid) || pid <= 0) {
226
+ this.observer.remove(id);
212
227
  await this.unlinkArtifacts(art);
213
228
  throw new Error(`Failed to start background job "${label}": ${result.stderr.trim() || "no PID returned"}`);
214
229
  }
@@ -259,6 +274,10 @@ export class DeskJobManager {
259
274
  const tail = outcome === "terminated" ? "its process was terminated" : "its process was already gone";
260
275
  return new Error(`Background job started but ${reason}; ${tail}. No job was created.`);
261
276
  });
277
+ if (record.status === "running")
278
+ this.observer.ready(id);
279
+ else
280
+ this.observer.remove(id);
262
281
  throw failure;
263
282
  }
264
283
  if (options.taskId && this.target.deskDir) {
@@ -273,6 +292,7 @@ export class DeskJobManager {
273
292
  });
274
293
  });
275
294
  }
295
+ this.observer.ready(id);
276
296
  this.ensureSweeper();
277
297
  return toSnapshot(record);
278
298
  }
@@ -320,7 +340,7 @@ export class DeskJobManager {
320
340
  * so their slots free up even when the model never polls, and stops itself once nothing is running.
321
341
  */
322
342
  ensureSweeper() {
323
- if (this.stopped || this.sweepTimer || this.runningCount() === 0) {
343
+ if (this.stopped || this.sweepTimer || (this.runningCount() === 0 && this.pendingCompletion.size === 0)) {
324
344
  return;
325
345
  }
326
346
  this.sweepTimer = setInterval(() => {
@@ -337,6 +357,8 @@ export class DeskJobManager {
337
357
  /** Stop observation at application shutdown; detached jobs keep running. */
338
358
  stop() {
339
359
  this.stopped = true;
360
+ this.observer.stop();
361
+ this.completion.stop();
340
362
  this.stopSweeper();
341
363
  if (this.garbageCollectionTimer)
342
364
  clearTimeout(this.garbageCollectionTimer);
@@ -352,9 +374,13 @@ export class DeskJobManager {
352
374
  if (this.stopped || this.sweeping) {
353
375
  return; // A prior sweep is still awaiting the executor; skip this tick.
354
376
  }
377
+ this.observer.retry();
355
378
  this.sweeping = true;
356
379
  try {
357
380
  const running = Array.from(this.jobs.values()).filter((record) => record.status === "running");
381
+ log.logEvent("debug", "job.completion.hinted", "Background job completion check requested", {
382
+ fields: { desk: this.target.desk, jobIds: running.map((r) => r.id), trigger: "sweep" },
383
+ });
358
384
  // One shell for the whole sweep, not one per job: the sweeper runs every 10s for as
359
385
  // long as any job lives, so per-job spawns are the steady-state cost of backgrounding.
360
386
  const probes = await this.probeAll(running);
@@ -374,11 +400,20 @@ export class DeskJobManager {
374
400
  });
375
401
  });
376
402
  }
403
+ for (const id of this.pendingCompletion) {
404
+ const record = this.jobs.get(id);
405
+ if (!record || this.stopped)
406
+ break;
407
+ await this.refresh(record).catch((error) => log.logWarn("job.completion.retry_failed", "Background job completion failed", {
408
+ reason: errorMessage(error),
409
+ fields: { jobId: id },
410
+ }));
411
+ }
377
412
  await this.collectGarbage();
378
413
  }
379
414
  finally {
380
415
  this.sweeping = false;
381
- if (this.runningCount() === 0) {
416
+ if (this.runningCount() === 0 && this.pendingCompletion.size === 0) {
382
417
  this.stopSweeper();
383
418
  }
384
419
  }
@@ -390,46 +425,8 @@ export class DeskJobManager {
390
425
  * Each job contributes one branch that reads its exit-code file if present and otherwise checks
391
426
  * liveness (three-state when a start time was captured — see the inline comment).
392
427
  */
393
- async probeAll(records, signal) {
394
- const states = new Map();
395
- if (records.length === 0) {
396
- return states;
397
- }
398
- const script = records
399
- .map((record) => {
400
- const id = shellEscape(record.id);
401
- const exitFile = shellEscape(record.exitFile);
402
- // Liveness: when the job's start time was captured, require the pid to still report
403
- // that exact `ps -o lstart=` — a recycled pid then reads as GONE, not ALIVE, so the
404
- // manager never mistakes an unrelated process for the job. Older records without a
405
- // captured start time fall back to a bare `kill -0`, the best they can do.
406
- // `-s`, not `-f`: an existing-but-empty `.exit` file (a torn write) must not count as
407
- // a finished job. The writer renames a fully-written temp file into place, so `-s`
408
- // here only ever sees the settled value (T4).
409
- //
410
- // Identity liveness is three-state: with a captured start time, `ps` reporting the
411
- // *same* lstart is ALIVE, a *different* one is DIFFERENT (pid recycled — our process
412
- // is gone), and `ps` returning nothing while `kill -0` still says alive is UNKNOWN
413
- // (do not conclude anything — a later probe retries). Legacy records have only
414
- // `kill -0`: ALIVE / GONE.
415
- const liveness = record.pidStartedAt
416
- ? `__pc_cur="$(ps -o lstart= -p ${record.pid} 2>/dev/null)"; ` +
417
- `if [ -z "$__pc_cur" ]; then ` +
418
- `if kill -0 ${record.pid} 2>/dev/null; then printf '%s UNKNOWN\\n' ${id}; else printf '%s GONE\\n' ${id}; fi; ` +
419
- `elif [ "$__pc_cur" = ${shellEscape(record.pidStartedAt)} ]; then printf '%s ALIVE\\n' ${id}; ` +
420
- `else printf '%s DIFFERENT\\n' ${id}; fi`
421
- : `if kill -0 ${record.pid} 2>/dev/null; then printf '%s ALIVE\\n' ${id}; else printf '%s GONE\\n' ${id}; fi`;
422
- return `if [ -s ${exitFile} ]; then printf '%s EXIT:%s\\n' ${id} "$(cat ${exitFile})"; else ${liveness}; fi`;
423
- })
424
- .join("\n");
425
- const probe = await this.executor.exec(script, { signal });
426
- for (const line of probe.stdout.split("\n")) {
427
- const separator = line.indexOf(" ");
428
- if (separator <= 0)
429
- continue;
430
- states.set(line.slice(0, separator), line.slice(separator + 1).trim());
431
- }
432
- return states;
428
+ probeAll(records, signal) {
429
+ return probeJobs(this.executor, records, signal);
433
430
  }
434
431
  /**
435
432
  * Refresh the status of a single running job by consulting its `.exit` file and liveness.
@@ -447,6 +444,7 @@ export class DeskJobManager {
447
444
  */
448
445
  async reconcileLocked(record, signal, announce = true) {
449
446
  if (record.status !== "running") {
447
+ await this.commitCompletion(record, signal);
450
448
  return;
451
449
  }
452
450
  const probes = await this.probeAll([record], signal);
@@ -527,6 +525,7 @@ export class DeskJobManager {
527
525
  }
528
526
  /** Move a job to a terminal status: record it, persist it, and wake the channel once. */
529
527
  async finish(record, status, signal, announce = true) {
528
+ this.pendingCompletion.add(record.id);
530
529
  record.status = status;
531
530
  record.durationMs = Date.now() - record.startedAt;
532
531
  record.finishedAt = Date.now();
@@ -536,21 +535,33 @@ export class DeskJobManager {
536
535
  record.notified = true;
537
536
  }
538
537
  await this.persist(record);
538
+ await this.commitCompletion(record, signal);
539
+ this.scheduleGarbageCollection();
540
+ }
541
+ async commitCompletion(record, signal) {
542
+ this.pendingCompletion.add(record.id);
539
543
  await this.logSettlementToTask(record);
540
544
  await this.announce(record, signal);
545
+ if (!record.notified && record.contract.notify && this.options.dispatch)
546
+ return;
547
+ this.pendingCompletion.delete(record.id);
548
+ this.observer.remove(record.id);
549
+ this.completion.publish();
550
+ log.logInfoEvent("job.completion.committed", "Background job completion committed", {
551
+ fields: { desk: this.target.desk, jobId: record.id, taskId: record.contract.taskId },
552
+ });
541
553
  this.scheduleGarbageCollection();
542
554
  }
543
555
  /**
544
- * Tell the owning task this job settled (spec 052, D4). Runs before the completion wake is
545
- * dispatched, so the step the wake starts already finds the result on its board. Best-effort and
546
- * once-only: a task that no longer exists, or a replayed finish, writes nothing.
556
+ * Tell the owning task this job settled (spec 052, D4). Runs before the lane is told, so the step
557
+ * it starts already finds the result in its inputs. Best-effort and once-only: a task that no
558
+ * longer exists, or a replayed finish, writes nothing.
547
559
  */
548
560
  async logSettlementToTask(record) {
549
561
  const taskId = record.contract.taskId;
550
562
  const deskDir = this.target.deskDir;
551
563
  if (!taskId || !deskDir || record.taskLogged)
552
564
  return;
553
- record.taskLogged = true;
554
565
  const output = await this.readOutput(record.id).catch(() => undefined);
555
566
  await logTaskSettlement(deskDir, taskId, {
556
567
  ref: record.id,
@@ -559,12 +570,10 @@ export class DeskJobManager {
559
570
  output: record.spillFile,
560
571
  tail: output?.text.slice(-WAKE_OUTPUT_TAIL_BYTES).trim() || undefined,
561
572
  durationMs: record.durationMs,
562
- }).catch((error) => {
563
- log.logWarn("job.task_settle.log_failed", "Task settlement record failed", {
564
- reason: errorMessage(error),
565
- fields: { jobId: record.id, taskId },
566
- });
573
+ // The caller delivered this result to the model in the same tool call (`announce: false`).
574
+ ...(record.notified ? { inline: true } : {}),
567
575
  });
576
+ record.taskLogged = true;
568
577
  await this.persist(record);
569
578
  }
570
579
  /**
@@ -575,7 +584,19 @@ export class DeskJobManager {
575
584
  * version that persisted `notified` first, which could crash-lose the wake entirely).
576
585
  */
577
586
  async announce(record, signal) {
578
- if (!this.options.dispatch || !record.contract.notify || record.notified) {
587
+ if (record.notified)
588
+ return;
589
+ // A task-bound job reports to its task, not to a channel (spec 064, D19): the settle record
590
+ // is in the task's log, so the lane only has to look. A task that has since vanished has
591
+ // nowhere to read the result, so the job falls back to waking the chat.
592
+ const taskId = record.contract.taskId;
593
+ if (taskId && this.target.deskDir && (await readStoredTask(this.target.deskDir, taskId))) {
594
+ this.options.onTaskInput?.(this.target.desk, taskId);
595
+ record.notified = true;
596
+ await this.persist(record);
597
+ return;
598
+ }
599
+ if (!this.options.dispatch || !record.contract.notify) {
579
600
  return;
580
601
  }
581
602
  const channelId = record.channelId;
@@ -599,21 +620,12 @@ export class DeskJobManager {
599
620
  record.notified = true;
600
621
  await this.persist(record);
601
622
  }
602
- /** Same contract as `SubAgentRunManager.suppressWake`: drop the wake, still redeem the `work` ticket. */
623
+ /** Same contract as `SubAgentRunManager.suppressWake`: drop the chat wake of a job whose channel left the desk. */
603
624
  async suppressWake(record) {
604
625
  log.logInfoEvent("job.wake.suppressed", "Completion wake dropped: channel not bound to the job's desk", {
605
626
  channelId: record.channelId,
606
- fields: { jobId: record.id, desk: this.target.desk, taskId: record.contract.taskId },
627
+ fields: { jobId: record.id, desk: this.target.desk },
607
628
  });
608
- const taskId = record.contract.taskId;
609
- if (taskId && this.target.deskDir) {
610
- await redeemTicket(this.target.deskDir, taskId, (ticket) => ticket.kind === "work").catch((error) => {
611
- log.logWarn("job.wake.redeem_failed", "Work ticket redeem for a dropped wake failed", {
612
- reason: errorMessage(error),
613
- fields: { jobId: record.id, taskId },
614
- });
615
- });
616
- }
617
629
  record.notified = true;
618
630
  await this.persist(record);
619
631
  }
@@ -680,40 +692,6 @@ export class DeskJobManager {
680
692
  }
681
693
  return Array.from(this.jobs.values()).map(toSnapshot);
682
694
  }
683
- async beginWakeConsumption(id, taskId, dispatchId) {
684
- return this.wakeQueue.run(id, async () => {
685
- const record = this.jobs.get(id);
686
- const expected = jobWakeDispatchId(this.target.desk, id);
687
- if (!record)
688
- return false;
689
- const eligible = record.status !== "running" && record.contract.taskId === taskId && dispatchId === expected;
690
- const previousClaim = record.wakeClaimDispatchId;
691
- if (!beginWakeClaim(record, eligible, dispatchId))
692
- return false;
693
- try {
694
- await this.persist(record, true);
695
- }
696
- catch (error) {
697
- record.wakeClaimDispatchId = previousClaim;
698
- throw error;
699
- }
700
- return true;
701
- });
702
- }
703
- async finishWakeConsumption(id, dispatchId) {
704
- await this.wakeQueue.run(id, async () => {
705
- const record = this.jobs.get(id);
706
- if (!record || !finishWakeClaim(record, dispatchId))
707
- return;
708
- try {
709
- await this.persist(record, true);
710
- }
711
- catch (error) {
712
- record.wakeConsumedAt = undefined;
713
- throw error;
714
- }
715
- });
716
- }
717
695
  async cancel(ids, signal) {
718
696
  const results = [];
719
697
  for (const id of ids) {
@@ -760,6 +738,9 @@ export class DeskJobManager {
760
738
  */
761
739
  async poll(ids, signal) {
762
740
  const deadline = Date.now() + POLL_WAIT_MS;
741
+ log.logEvent("debug", "job.completion.hinted", "Background job completion check requested", {
742
+ fields: { desk: this.target.desk, jobIds: ids, trigger: "poll" },
743
+ });
763
744
  // Freeze the observation set once, up front. `refresh(..., announce=false)` marks a job's
764
745
  // completion wake as consumed (the result is being returned inline), so if we re-derived the
765
746
  // watch list each iteration a job that finished mid-poll would drop out of "running", never
@@ -773,6 +754,7 @@ export class DeskJobManager {
773
754
  .filter((job) => job.status === "running")
774
755
  .map((job) => job.id);
775
756
  while (true) {
757
+ const revision = this.completion.revision;
776
758
  for (const id of watchedIds) {
777
759
  const record = this.jobs.get(id);
778
760
  if (record) {
@@ -785,10 +767,10 @@ export class DeskJobManager {
785
767
  .map((id) => this.jobs.get(id))
786
768
  .filter((record) => record !== undefined);
787
769
  const anyDone = watched.some((record) => record.status !== "running");
788
- if (watched.length === 0 || anyDone || Date.now() >= deadline || signal?.aborted) {
770
+ if (watched.length === 0 || anyDone || this.stopped || Date.now() >= deadline || signal?.aborted) {
789
771
  return watched.map(toSnapshot);
790
772
  }
791
- await sleep(POLL_CHECK_INTERVAL_MS, signal);
773
+ await this.completion.wait(revision, Math.min(POLL_CHECK_INTERVAL_MS, Math.max(0, deadline - Date.now())), signal);
792
774
  }
793
775
  }
794
776
  /**
@@ -827,6 +809,8 @@ export class DeskJobManager {
827
809
  continue;
828
810
  }
829
811
  this.jobs.set(record.id, record);
812
+ if (record.status === "running")
813
+ this.observer.add(record.id, record.exitFile);
830
814
  restored++;
831
815
  // One probe decides between "still running", "finished while we were down", and "gone";
832
816
  // refresh already encodes all three, including the late completion wake.
@@ -836,6 +820,10 @@ export class DeskJobManager {
836
820
  fields: { jobId: record?.id },
837
821
  });
838
822
  });
823
+ if (record.status === "running")
824
+ this.observer.ready(record.id);
825
+ else
826
+ this.observer.remove(record.id);
839
827
  }
840
828
  await this.collectGarbage();
841
829
  this.scheduleGarbageCollection();
@@ -863,64 +851,3 @@ export class DeskJobManager {
863
851
  return { spillFile: record.spillFile, text };
864
852
  }
865
853
  }
866
- /** One application's jobs; the executor and configuration cannot change after construction. */
867
- export function createJobRuntime(executor, options = {}) {
868
- const config = { ...options };
869
- const managers = new Map();
870
- let stopped = false;
871
- function get(desk) {
872
- let manager = managers.get(desk);
873
- if (!manager) {
874
- const deskDir = config.workspaceDir ? getDeskDir(config.workspaceDir, desk) : undefined;
875
- manager = new DeskJobManager({ desk, deskDir }, executor, {
876
- ...(config.jobsStateDir ? { stateDir: join(config.jobsStateDir, desk) } : {}),
877
- ...(deskDir ? { spillDir: getDeskLogsDir(deskDir) } : {}),
878
- ...(config.dispatch ? { dispatch: config.dispatch } : {}),
879
- ...(config.isBoundTo ? { isBoundTo: config.isBoundTo } : {}),
880
- ...(config.sweepIntervalMs ? { sweepIntervalMs: config.sweepIntervalMs } : {}),
881
- });
882
- managers.set(desk, manager);
883
- if (stopped)
884
- manager.stop();
885
- }
886
- return manager;
887
- }
888
- /**
889
- * Re-adopt every desk's persisted jobs at startup. Desks are the record directories themselves,
890
- * and restore does not depend on bindings (spec 058, D6): a job still running when its desk went
891
- * dormant survives the restart too.
892
- */
893
- async function restore() {
894
- const jobsStateDir = config.jobsStateDir;
895
- if (!jobsStateDir)
896
- return 0;
897
- let desks;
898
- try {
899
- await mkdir(jobsStateDir, { recursive: true });
900
- desks = (await readdir(jobsStateDir, { withFileTypes: true }))
901
- .filter((entry) => entry.isDirectory() && isDeskName(entry.name))
902
- .map((entry) => entry.name);
903
- }
904
- catch (error) {
905
- log.logWarn("job.scan.failed", "Persisted background job scan failed", { reason: errorMessage(error) });
906
- return 0;
907
- }
908
- let restored = 0;
909
- for (const desk of desks) {
910
- restored += await get(desk).restore();
911
- }
912
- if (restored > 0) {
913
- log.logInfoEvent("job.restore.done", "Background job records restored", { fields: { count: restored } });
914
- }
915
- return restored;
916
- }
917
- return {
918
- get,
919
- restore,
920
- stop: () => {
921
- stopped = true;
922
- for (const manager of managers.values())
923
- manager.stop();
924
- },
925
- };
926
- }
@@ -0,0 +1,3 @@
1
+ import type { Executor } from "../executor.js";
2
+ import type { JobRecord } from "./record.js";
3
+ export declare function probeJobs(executor: Executor, records: JobRecord[], signal?: AbortSignal): Promise<Map<string, string>>;
@@ -0,0 +1,42 @@
1
+ import { shellEscape } from "../shared/os.js";
2
+ export async function probeJobs(executor, records, signal) {
3
+ const states = new Map();
4
+ if (records.length === 0) {
5
+ return states;
6
+ }
7
+ const script = records
8
+ .map((record) => {
9
+ const id = shellEscape(record.id);
10
+ const exitFile = shellEscape(record.exitFile);
11
+ // Liveness: when the job's start time was captured, require the pid to still report
12
+ // that exact `ps -o lstart=` — a recycled pid then reads as GONE, not ALIVE, so the
13
+ // manager never mistakes an unrelated process for the job. Older records without a
14
+ // captured start time fall back to a bare `kill -0`, the best they can do.
15
+ // `-s`, not `-f`: an existing-but-empty `.exit` file (a torn write) must not count as
16
+ // a finished job. The writer renames a fully-written temp file into place, so `-s`
17
+ // here only ever sees the settled value (T4).
18
+ //
19
+ // Identity liveness is three-state: with a captured start time, `ps` reporting the
20
+ // *same* lstart is ALIVE, a *different* one is DIFFERENT (pid recycled — our process
21
+ // is gone), and `ps` returning nothing while `kill -0` still says alive is UNKNOWN
22
+ // (do not conclude anything — a later probe retries). Legacy records have only
23
+ // `kill -0`: ALIVE / GONE.
24
+ const liveness = record.pidStartedAt
25
+ ? `__pc_cur="$(ps -o lstart= -p ${record.pid} 2>/dev/null)"; ` +
26
+ `if [ -z "$__pc_cur" ]; then ` +
27
+ `if kill -0 ${record.pid} 2>/dev/null; then printf '%s UNKNOWN\\n' ${id}; else printf '%s GONE\\n' ${id}; fi; ` +
28
+ `elif [ "$__pc_cur" = ${shellEscape(record.pidStartedAt)} ]; then printf '%s ALIVE\\n' ${id}; ` +
29
+ `else printf '%s DIFFERENT\\n' ${id}; fi`
30
+ : `if kill -0 ${record.pid} 2>/dev/null; then printf '%s ALIVE\\n' ${id}; else printf '%s GONE\\n' ${id}; fi`;
31
+ return `if [ -s ${exitFile} ]; then printf '%s EXIT:%s\\n' ${id} "$(cat ${exitFile})"; else ${liveness}; fi`;
32
+ })
33
+ .join("\n");
34
+ const probe = await executor.exec(script, { signal });
35
+ for (const line of probe.stdout.split("\n")) {
36
+ const separator = line.indexOf(" ");
37
+ if (separator <= 0)
38
+ continue;
39
+ states.set(line.slice(0, separator), line.slice(separator + 1).trim());
40
+ }
41
+ return states;
42
+ }
@@ -7,10 +7,9 @@ export interface JobSnapshot {
7
7
  startedAt: number;
8
8
  durationMs: number;
9
9
  exitCode?: number;
10
- /** The job's own wall-clock limit; a task's `work` ticket derives its backstop from it. */
10
+ /** The job's own wall-clock limit: the longest it can keep a bound task waiting. */
11
11
  timeoutSeconds: number;
12
- /** The task this job's completion wake belongs to, if any — lets a caller verify that a
13
- * `[JOB:<id>] ... belongs to task <taskId>.` wake actually names the job it claims to (T9). */
12
+ /** The task whose step started this job, if any (spec 064, INV-8). Its completion goes to the task, not to a channel. */
14
13
  taskId?: string;
15
14
  /** The channel that started the job, where its completion wake goes; jobs are shared per desk. */
16
15
  channelId: string;
@@ -19,7 +18,7 @@ export interface JobSnapshot {
19
18
  export interface JobWakeContract {
20
19
  /** Wake the channel on completion. Defaults to true — that is the point of the mechanism. */
21
20
  notify: boolean;
22
- /** The task this job is advancing, surfaced in the wake so the model lands in context. */
21
+ /** The task whose step started the job; its completion is recorded on the task instead of waking a channel. */
23
22
  taskId?: string;
24
23
  }
25
24
  export interface JobRecord extends JobSnapshot {
@@ -48,8 +47,6 @@ export interface JobRecord extends JobSnapshot {
48
47
  * point this terminal status is applied. Internal only — never surfaced in a `JobSnapshot`.
49
48
  */
50
49
  pendingKill?: "cancelled" | "failed";
51
- wakeClaimDispatchId?: string;
52
- wakeConsumedAt?: number;
53
50
  }
54
51
  export declare function isTerminal(status: JobStatus): boolean;
55
52
  /** Accept a persisted record only if the fields the manager actually relies on are intact. */
@@ -0,0 +1,28 @@
1
+ import type { WakeEvent } from "../channel/channel-event.js";
2
+ import type { Executor } from "../executor.js";
3
+ import type { FileStore } from "../file-store.js";
4
+ import { DeskJobManager, type JobManagerOptions } from "./manager.js";
5
+ interface JobRuntimeConfig {
6
+ /** Root of the per-desk record directories (`<jobsStateDir>/<desk>/`). */
7
+ jobsStateDir?: string;
8
+ /**
9
+ * The agent workspace root. A job's full-output spill goes to `<desk>/logs/` so the
10
+ * "Full output: …" pointer is a file the model can read (fix plan §2.2). The path is stable
11
+ * across restarts, so a re-adopted job's spill is still found.
12
+ */
13
+ workspaceDir?: string;
14
+ dispatch?: (event: WakeEvent) => boolean | Promise<boolean>;
15
+ isBoundTo?: JobManagerOptions["isBoundTo"];
16
+ onTaskInput?: JobManagerOptions["onTaskInput"];
17
+ /** Sweep cadence override for the lazily-built desk managers (tests). */
18
+ sweepIntervalMs?: number;
19
+ fileStore?: FileStore;
20
+ }
21
+ /** One application's jobs; the executor and configuration cannot change after construction. */
22
+ export declare function createJobRuntime(executor: Executor, options?: JobRuntimeConfig): {
23
+ get: (desk: string) => DeskJobManager;
24
+ restore: () => Promise<number>;
25
+ stop: () => void;
26
+ };
27
+ export type JobRuntime = ReturnType<typeof createJobRuntime>;
28
+ export {};