@xzzpig/pi-subagents 0.19.0 → 0.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (153) hide show
  1. package/CHANGELOG.md +214 -0
  2. package/README.md +1 -1
  3. package/agents/oracle.md +8 -19
  4. package/agents/researcher.md +0 -3
  5. package/agents/reviewer.md +17 -61
  6. package/agents/scout.md +1 -4
  7. package/agents/worker.md +8 -25
  8. package/docs/agents.md +86 -11
  9. package/docs/configuration.md +68 -7
  10. package/docs/extension-api.md +37 -12
  11. package/docs/fork-extensions.md +1 -0
  12. package/docs/missions.md +48 -17
  13. package/docs/models.md +7 -3
  14. package/docs/observability.md +18 -8
  15. package/docs/tool-reference.md +138 -80
  16. package/docs/watchdog.md +8 -6
  17. package/docs/workflows.md +18 -9
  18. package/index.ts +5 -0
  19. package/package.json +5 -3
  20. package/prompts/council.md +1 -1
  21. package/skills/pi-subagents/SKILL.md +1 -1
  22. package/skills/pi-subagents/references/constraints-and-recipes.md +1 -1
  23. package/skills/pi-subagents/references/execution-controls.md +16 -16
  24. package/skills/pi-subagents/references/management-authoring-rpc.md +16 -12
  25. package/skills/pi-subagents/references/prompting-and-roles.md +3 -3
  26. package/src/agents/advertised-agent-prompt.ts +9 -1
  27. package/src/agents/agent-management.ts +4 -0
  28. package/src/agents/agent-memory.ts +3 -3
  29. package/src/agents/agent-scope.ts +4 -0
  30. package/src/agents/agent-serializer.ts +8 -1
  31. package/src/agents/agents.ts +224 -122
  32. package/src/api/preflight.ts +50 -5
  33. package/src/extension/config.ts +24 -2
  34. package/src/extension/context-injection.ts +6 -1
  35. package/src/extension/control-notices.ts +1 -9
  36. package/src/extension/declaration-pinning.ts +164 -0
  37. package/src/extension/doctor.ts +7 -10
  38. package/src/extension/fanout-child.ts +7 -8
  39. package/src/extension/index.ts +134 -145
  40. package/src/extension/public-execution.ts +3 -0
  41. package/src/extension/reply-workflow-script.ts +21 -12
  42. package/src/extension/rpc.ts +12 -7
  43. package/src/extension/schemas.ts +39 -33
  44. package/src/extension/subagent-guide.ts +86 -6
  45. package/src/extension/subagent-options.ts +47 -0
  46. package/src/extension/tool-activation.ts +3 -2
  47. package/src/extension/tool-description.ts +51 -68
  48. package/src/inspectors/actions.ts +37 -11
  49. package/src/inspectors/plugins.ts +3 -2
  50. package/src/inspectors/tmux/actions.ts +204 -0
  51. package/src/inspectors/tmux/client.ts +85 -0
  52. package/src/inspectors/tmux/plugin.ts +21 -0
  53. package/src/integrations/herdr-status.ts +18 -49
  54. package/src/integrations/program-status.ts +215 -0
  55. package/src/intercom/native-supervisor-channel.ts +77 -4
  56. package/src/intercom/result-intercom.ts +3 -2
  57. package/src/intercom/supervisor-ui.ts +2 -174
  58. package/src/missions/goal-driver.ts +44 -31
  59. package/src/missions/store.ts +35 -6
  60. package/src/profiles/profiles.ts +29 -23
  61. package/src/runs/background/active-async-capacity.ts +58 -8
  62. package/src/runs/background/async-execution.ts +231 -44
  63. package/src/runs/background/async-job-tracker.ts +12 -4
  64. package/src/runs/background/async-resume.ts +5 -2
  65. package/src/runs/background/await-async-run.ts +18 -11
  66. package/src/runs/background/binary-bootstrap.ts +2 -1
  67. package/src/runs/background/calendar-schedule.ts +90 -0
  68. package/src/runs/background/chain-root-attachment.ts +9 -5
  69. package/src/runs/background/control-channel.ts +43 -0
  70. package/src/runs/background/fleet-view.ts +5 -5
  71. package/src/runs/background/notify.ts +185 -12
  72. package/src/runs/background/result-files.ts +116 -5
  73. package/src/runs/background/result-watcher.ts +99 -66
  74. package/src/runs/background/resume-guidance.ts +2 -2
  75. package/src/runs/background/run-child-session.ts +29 -8
  76. package/src/runs/background/run-id-resolver.ts +8 -5
  77. package/src/runs/background/run-status.ts +21 -16
  78. package/src/runs/background/runner-aliases.ts +7 -4
  79. package/src/runs/background/runner-child-launch.ts +1 -0
  80. package/src/runs/background/runner-http-dispatcher.ts +3 -0
  81. package/src/runs/background/scheduled-runs.ts +282 -72
  82. package/src/runs/background/stale-run-reconciler.ts +13 -2
  83. package/src/runs/background/subagent-runner-bootstrap.ts +4 -1
  84. package/src/runs/background/subagent-runner.ts +75 -16
  85. package/src/runs/background/subagent-wait.ts +38 -19
  86. package/src/runs/background/terminal-run-index.ts +46 -1
  87. package/src/runs/background/wait-completions.ts +1 -0
  88. package/src/runs/background/wait-tool.ts +33 -23
  89. package/src/runs/background/workflow-terminal-proof.ts +39 -22
  90. package/src/runs/foreground/async-stop-action.ts +48 -22
  91. package/src/runs/foreground/command-action.ts +41 -0
  92. package/src/runs/foreground/execution.ts +109 -58
  93. package/src/runs/foreground/foreground-history.ts +1 -0
  94. package/src/runs/foreground/subagent-executor.ts +270 -89
  95. package/src/runs/shared/child-commands.ts +229 -0
  96. package/src/runs/shared/child-hooks.ts +4 -3
  97. package/src/runs/shared/child-launch.ts +3 -0
  98. package/src/runs/shared/child-session.ts +131 -40
  99. package/src/runs/shared/child-tool-plan.ts +14 -27
  100. package/src/runs/shared/claude-code-adapter.ts +157 -2
  101. package/src/runs/shared/dynamic-fanout.ts +2 -2
  102. package/src/runs/shared/external-cli-preflight.ts +54 -6
  103. package/src/runs/shared/external-cli-runner.ts +5 -1
  104. package/src/runs/shared/fork-command-result.ts +10 -0
  105. package/src/runs/shared/herdr-placed-run.ts +5 -4
  106. package/src/runs/shared/mcp-direct-tool-allowlist.ts +8 -5
  107. package/src/runs/shared/model-resolution-diagnostic.ts +25 -0
  108. package/src/runs/shared/model-resolution.ts +39 -2
  109. package/src/runs/shared/nested-events.ts +5 -0
  110. package/src/runs/shared/parallel-handoff.ts +56 -8
  111. package/src/runs/shared/parallel-utils.ts +4 -0
  112. package/src/runs/shared/partial-output.ts +48 -0
  113. package/src/runs/shared/run-history.ts +87 -0
  114. package/src/runs/shared/runner-launcher.ts +25 -0
  115. package/src/runs/shared/single-output.ts +53 -0
  116. package/src/runs/shared/structured-output.ts +14 -7
  117. package/src/runs/shared/subagent-control.ts +33 -18
  118. package/src/runs/shared/subagent-prompt-runtime.ts +59 -30
  119. package/src/runs/shared/workflow-async-child-guidance.ts +1 -1
  120. package/src/runs/shared/worktree-cleanup-apply.ts +160 -0
  121. package/src/runs/shared/worktree-cleanup-plan.ts +41 -19
  122. package/src/runs/shared/worktree-lock.ts +29 -0
  123. package/src/runs/shared/worktree.ts +12 -1
  124. package/src/shared/atomic-json.ts +4 -2
  125. package/src/shared/edit-distance.ts +33 -0
  126. package/src/shared/file-lease.ts +74 -0
  127. package/src/shared/formatters.ts +1 -5
  128. package/src/shared/model-info.ts +22 -0
  129. package/src/shared/package-version.ts +17 -0
  130. package/src/shared/parent-wake.ts +79 -0
  131. package/src/shared/pruned-fork.ts +7 -1
  132. package/src/shared/required-child-extensions.ts +39 -5
  133. package/src/shared/runtime-module-path.ts +19 -0
  134. package/src/shared/settings-file-lease.ts +36 -0
  135. package/src/shared/types.ts +42 -3
  136. package/src/shared/utils.ts +8 -6
  137. package/src/slash/slash-commands.ts +3 -3
  138. package/src/slash/subagent-cost.ts +9 -5
  139. package/src/slash/subagents-admin.ts +2 -1
  140. package/src/tui/fleet-native-transcript.ts +2 -0
  141. package/src/tui/fleet-transcript.ts +12 -3
  142. package/src/tui/fleet.ts +11 -8
  143. package/src/tui/render.ts +28 -20
  144. package/src/tui/subagent-messages.ts +305 -0
  145. package/src/watchdog/diff-tool.ts +2 -2
  146. package/src/watchdog/register-main.ts +2 -22
  147. package/src/watchdog/render.ts +2 -24
  148. package/src/watchdog/runtime.ts +6 -4
  149. package/src/watchdog/settings.ts +18 -13
  150. package/src/watchdog/tool-actions.ts +2 -2
  151. package/src/workflows/scripted-workflow.ts +20 -6
  152. package/src/workflows/workflow-receipt.ts +2 -2
  153. package/src/workflows/workflow-resources.ts +18 -4
@@ -1,11 +1,13 @@
1
1
  import { spawnSync } from "node:child_process";
2
2
  import { createHash, randomUUID } from "node:crypto";
3
3
  import * as fs from "node:fs";
4
+ import * as os from "node:os";
4
5
  import * as path from "node:path";
5
6
  import type { AgentToolResult } from "@earendil-works/pi-agent-core";
6
7
  import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
7
8
  import { getProjectSubagentsDir } from "../../shared/artifacts.ts";
8
9
  import { writePrivateAtomicJson } from "../../shared/atomic-json.ts";
10
+ import { withFileLease } from "../../shared/file-lease.ts";
9
11
  import { shortenPath } from "../../shared/formatters.ts";
10
12
  import type { AsyncStatus, Details, ExtensionConfig } from "../../shared/types.ts";
11
13
  import type { SubagentParamsLike } from "../foreground/subagent-executor.ts";
@@ -16,6 +18,10 @@ import { resolveGitRepositoryIdentity } from "../../workflows/chat-progress.ts";
16
18
  import { getConfigDirName } from "../../shared/utils.ts";
17
19
  import { normalizeWorktreeBaseRef } from "../shared/worktree.ts";
18
20
  import { deepFreezeWorkflowArgs, normalizeWorkflowArgs } from "../../workflows/workflow-resources.ts";
21
+ import { readMission, resolveMissionStoreLocation, validateMissionId } from "../../missions/store.ts";
22
+
23
+ import { calendarDateAfter, latestCalendarOccurrence, nextCalendarOccurrence, normalizeCalendarRule, restoreCalendarTrigger, type CalendarTrigger } from "./calendar-schedule.ts";
24
+ import { reconcileAsyncRun } from "./stale-run-reconciler.ts";
19
25
 
20
26
  export const SCHEDULED_RUN_ACTIONS = [
21
27
  "schedule.create",
@@ -40,11 +46,12 @@ export type ScheduledRunAction = typeof SCHEDULED_RUN_ACTIONS[number];
40
46
  export type ScheduleRunState = "running" | "skipped" | "missed" | "completed" | "failed_launch" | "failed_run";
41
47
  export type ScheduleTrigger =
42
48
  | { kind: "once"; at: string; nextRunAt?: string }
43
- | { kind: "interval"; every: string; everyMs: number; anchorAt: string; nextRunAt: string };
44
- export type ScheduleTarget = { workflowScript: string; args: Record<string, unknown>; baseRef?: string };
49
+ | { kind: "interval"; every: string; everyMs: number; anchorAt: string; nextRunAt: string }
50
+ | CalendarTrigger;
51
+ export type ScheduleTarget = { workflowScript: string; args: Record<string, unknown>; baseRef?: string; missionId?: string };
45
52
 
46
53
  export interface ScheduleRecord {
47
- schemaVersion: 1;
54
+ schemaVersion: 1 | 2;
48
55
  id: string;
49
56
  name: string;
50
57
  cwd: string;
@@ -87,6 +94,7 @@ type ScheduledRunManagerDeps = {
87
94
  randomId?: () => string;
88
95
  resolveCapabilityCeiling?: (sessionId: string) => ResolvedSubagentCapabilityCeiling | undefined;
89
96
  timers?: ScheduledRunTimers;
97
+ kill?: (pid: number, signal?: NodeJS.Signals | 0) => boolean;
90
98
  };
91
99
 
92
100
  export function isScheduledRunAction(action: unknown): action is ScheduledRunAction {
@@ -229,6 +237,18 @@ function resolveSharedGitConfigRoot(projectCwd: string): string | undefined {
229
237
  return undefined;
230
238
  }
231
239
 
240
+ // In the home directory the project config dir is the user's own Pi config dir,
241
+ // which may be a symlink to another disk.
242
+ function resolveHomeConfigRoot(projectPath: string): string | undefined {
243
+ const home = process.env.HOME || process.env.USERPROFILE || os.homedir();
244
+ try {
245
+ if (!samePath(fs.realpathSync.native(home), projectPath)) return undefined;
246
+ return fs.realpathSync.native(path.join(home, getConfigDirName()));
247
+ } catch {
248
+ return undefined;
249
+ }
250
+ }
251
+
232
252
  function assertScheduleRoot(root: string, projectCwd: string | undefined, create: boolean): void {
233
253
  if (!projectCwd) {
234
254
  if (create) fs.mkdirSync(root, { recursive: true, mode: 0o700 });
@@ -248,9 +268,12 @@ function assertScheduleRoot(root: string, projectCwd: string | undefined, create
248
268
  existing = parent;
249
269
  }
250
270
  const existingPath = fs.realpathSync.native(existing);
251
- const sharedGitConfigRoot = pathWithin(projectPath, existingPath) ? undefined : resolveSharedGitConfigRoot(projectCwd);
271
+ const withinProject = pathWithin(projectPath, existingPath);
272
+ const sharedGitConfigRoot = withinProject ? undefined : resolveSharedGitConfigRoot(projectCwd);
273
+ const homeConfigRoot = withinProject ? undefined : resolveHomeConfigRoot(projectPath);
252
274
  const isTrustedPath = (candidate: string): boolean => pathWithin(projectPath, candidate)
253
- || (sharedGitConfigRoot !== undefined && pathWithin(sharedGitConfigRoot, candidate));
275
+ || (sharedGitConfigRoot !== undefined && pathWithin(sharedGitConfigRoot, candidate))
276
+ || (homeConfigRoot !== undefined && pathWithin(homeConfigRoot, candidate));
254
277
  if (!isTrustedPath(existingPath)) throw new Error(`Project schedule root '${root}' resolves outside the real project.`);
255
278
  if (!create) return;
256
279
  fs.mkdirSync(root, { recursive: true, mode: 0o700 });
@@ -284,17 +307,23 @@ function readJson(file: string, label: string): unknown {
284
307
 
285
308
  function parseScheduleTarget(value: unknown, file: string): ScheduleTarget {
286
309
  if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error(`Schedule record '${file}' has invalid trigger or target.`);
287
- const target = value as { workflowScript?: unknown; args?: unknown; baseRef?: unknown; agent?: unknown; task?: unknown };
310
+ const target = value as { workflowScript?: unknown; args?: unknown; baseRef?: unknown; missionId?: unknown; agent?: unknown; task?: unknown };
288
311
  if (typeof target.workflowScript === "string" && target.workflowScript.trim()) {
289
312
  let baseRef: string | undefined;
313
+ let missionId: string | undefined;
290
314
  try {
291
315
  baseRef = normalizeWorktreeBaseRef(target.baseRef);
292
316
  } catch (error) {
293
317
  throw new Error(`Schedule record '${file}' has an invalid baseRef: ${error instanceof Error ? error.message : String(error)}`);
294
318
  }
319
+ try {
320
+ missionId = target.missionId === undefined ? undefined : validateMissionId(target.missionId);
321
+ } catch (error) {
322
+ throw new Error(`Schedule record '${file}' has an invalid missionId: ${error instanceof Error ? error.message : String(error)}`);
323
+ }
295
324
  const normalizedArgs = normalizeWorkflowArgs(target.args);
296
325
  if ("error" in normalizedArgs) throw new Error(`Schedule record '${file}' has invalid args: ${normalizedArgs.error}`);
297
- return { workflowScript: target.workflowScript.trim(), args: deepFreezeWorkflowArgs(normalizedArgs.args), ...(baseRef === undefined ? {} : { baseRef }) };
326
+ return { workflowScript: target.workflowScript.trim(), args: deepFreezeWorkflowArgs(normalizedArgs.args), ...(baseRef === undefined ? {} : { baseRef }), ...(missionId === undefined ? {} : { missionId }) };
298
327
  }
299
328
  if (target.agent !== undefined || target.task !== undefined) throw new Error(`Schedule record '${file}' uses a removed legacy agent target; recreate it with schedule.create and workflow: true or a workflow script path.`);
300
329
  throw new Error(`Schedule record '${file}' requires a workflowScript target.`);
@@ -303,7 +332,7 @@ function parseScheduleTarget(value: unknown, file: string): ScheduleTarget {
303
332
  function parseSchedule(value: unknown, file: string): ScheduleRecord {
304
333
  if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error(`Schedule record '${file}' must be a JSON object.`);
305
334
  const record = value as Partial<ScheduleRecord>;
306
- if (record.schemaVersion !== 1 || typeof record.id !== "string" || typeof record.name !== "string" || typeof record.cwd !== "string" || typeof record.createdAt !== "string" || typeof record.updatedAt !== "string" || typeof record.paused !== "boolean") throw new Error(`Schedule record '${file}' has invalid required fields.`);
335
+ if ((record.schemaVersion !== 1 && record.schemaVersion !== 2) || typeof record.id !== "string" || typeof record.name !== "string" || typeof record.cwd !== "string" || typeof record.createdAt !== "string" || typeof record.updatedAt !== "string" || typeof record.paused !== "boolean") throw new Error(`Schedule record '${file}' has invalid required fields.`);
307
336
  validateScheduleId(record.id);
308
337
  if (!record.trigger || typeof record.trigger !== "object" || !record.target || typeof record.target !== "object") throw new Error(`Schedule record '${file}' has invalid trigger or target.`);
309
338
  if (record.overlap !== "skip" || (record.catchUp !== "none" && record.catchUp !== "latest")) throw new Error(`Schedule record '${file}' has unsupported policy fields.`);
@@ -311,11 +340,15 @@ function parseSchedule(value: unknown, file: string): ScheduleRecord {
311
340
  if (typeof record.trigger.at !== "string" || (record.trigger.nextRunAt !== undefined && typeof record.trigger.nextRunAt !== "string")) throw new Error(`Schedule record '${file}' has an invalid one-shot trigger.`);
312
341
  } else if (record.trigger.kind === "interval") {
313
342
  if (typeof record.trigger.every !== "string" || typeof record.trigger.everyMs !== "number" || typeof record.trigger.anchorAt !== "string" || typeof record.trigger.nextRunAt !== "string") throw new Error(`Schedule record '${file}' has an invalid interval trigger.`);
343
+ } else if (record.trigger.kind === "calendar") {
344
+ restoreCalendarTrigger(record.trigger); // Validate without rewriting during read-only list/show.
314
345
  } else throw new Error(`Schedule record '${file}' has an unsupported trigger.`);
315
346
  if (record.sessionOnly !== undefined && typeof record.sessionOnly !== "boolean") throw new Error(`Schedule record '${file}' has invalid sessionOnly.`);
316
347
  if (record.quiet !== undefined && typeof record.quiet !== "boolean") throw new Error(`Schedule record '${file}' has invalid quiet.`);
317
348
  if (record.sessionOnly === true && (typeof record.ownerSessionFile !== "string" || !record.ownerSessionFile.trim())) throw new Error(`Schedule record '${file}' is session-only but has no owner session file.`);
318
- return { ...record, target: parseScheduleTarget(record.target, file) } as ScheduleRecord;
349
+ const target = parseScheduleTarget(record.target, file);
350
+ if ((record.schemaVersion === 2) !== (target.missionId !== undefined)) throw new Error(`Schedule record '${file}' requires schemaVersion 2 exactly when missionId is present.`);
351
+ return { ...record, target } as ScheduleRecord;
319
352
  }
320
353
 
321
354
  class ScheduleStore {
@@ -372,13 +405,28 @@ class ScheduleStore {
372
405
  return value.runs as ScheduleRunRecord[];
373
406
  }
374
407
 
408
+ /** The run's own receipt; it is written before history.json and is never trimmed. */
409
+ getRun(id: string, runId: string): ScheduleRunRecord | undefined {
410
+ if (!SCHEDULE_ID.test(runId)) throw new Error(`Invalid schedule run id '${runId}'.`);
411
+ const file = path.join(scheduleDir(this.root, id, false, this.projectCwd), "runs", `${runId}.json`);
412
+ if (!fs.existsSync(file)) return undefined;
413
+ const run = readJson(file, "schedule run") as ScheduleRunRecord;
414
+ if (run?.id !== runId || run.scheduleId !== id) throw new Error(`Schedule run '${file}' has invalid fields.`);
415
+ return run;
416
+ }
417
+
375
418
  writeRun(schedule: ScheduleRecord, run: ScheduleRunRecord, event: string): void {
376
419
  const dir = scheduleDir(this.root, schedule.id, true, this.projectCwd);
377
420
  writePrivateAtomicJson(path.join(dir, "runs", `${run.id}.json`), run);
378
- const runs = [run, ...this.history(schedule.id).filter((item) => item.id !== run.id)].slice(0, MAX_HISTORY);
379
- writePrivateAtomicJson(path.join(dir, "history.json"), { schemaVersion: 1, runs });
380
- fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
381
- fs.appendFileSync(path.join(dir, "events.jsonl"), `${JSON.stringify({ schemaVersion: 1, timestamp: new Date().toISOString(), event, scheduleId: schedule.id, runId: run.id, state: run.state })}\n`, { encoding: "utf-8", mode: 0o600 });
421
+ // Sessions sharing this project update history.json from their own snapshots.
422
+ withFileLease(path.join(dir, "history.json"), () => {
423
+ // An earlier update may have timed out; a run's own receipt is newer than a "running" entry.
424
+ const earlier = this.history(schedule.id).filter((item) => item.id !== run.id)
425
+ .map((item) => item.state === "running" ? this.getRun(schedule.id, item.id) ?? item : item);
426
+ const runs = [run, ...earlier].slice(0, MAX_HISTORY);
427
+ writePrivateAtomicJson(path.join(dir, "history.json"), { schemaVersion: 1, runs });
428
+ fs.appendFileSync(path.join(dir, "events.jsonl"), `${JSON.stringify({ schemaVersion: 1, timestamp: new Date().toISOString(), event, scheduleId: schedule.id, runId: run.id, state: run.state })}\n`, { encoding: "utf-8", mode: 0o600 });
429
+ });
382
430
  }
383
431
 
384
432
  appendEvent(schedule: ScheduleRecord, event: string): void {
@@ -397,11 +445,14 @@ function hasPendingScheduleWork(schedule: ScheduleRecord): boolean {
397
445
  return schedule.activeRunId !== undefined || schedule.trigger.nextRunAt !== undefined;
398
446
  }
399
447
 
400
- function nextAfter(trigger: ScheduleTrigger, plannedAt: number, now: number): string | undefined {
401
- if (trigger.kind === "once") return undefined;
402
- let next = plannedAt + trigger.everyMs;
403
- while (next <= now) next += trigger.everyMs;
404
- return timestamp(next);
448
+ function nextAfter(trigger: ScheduleTrigger, plannedAt: number, now: number): ScheduleTrigger {
449
+ if (trigger.kind === "once") return { ...trigger, nextRunAt: undefined };
450
+ if (trigger.kind === "calendar") return {
451
+ ...trigger,
452
+ ...nextCalendarOccurrence(trigger, Math.max(plannedAt, now), calendarDateAfter(trigger, plannedAt, trigger.nextLocalDate)),
453
+ };
454
+ const next = plannedAt + (Math.floor(Math.max(0, now - plannedAt) / trigger.everyMs) + 1) * trigger.everyMs;
455
+ return { ...trigger, nextRunAt: timestamp(next) };
405
456
  }
406
457
 
407
458
  function nextRunAt(schedule: ScheduleRecord): number | undefined {
@@ -414,8 +465,15 @@ function nextRunAt(schedule: ScheduleRecord): number | undefined {
414
465
 
415
466
  function duePlannedAt(schedule: ScheduleRecord, now: number): number | undefined {
416
467
  const next = nextRunAt(schedule);
417
- if (next === undefined || next > now || schedule.catchUp !== "latest" || schedule.trigger.kind !== "interval") return next;
418
- return next + Math.floor((now - next) / schedule.trigger.everyMs) * schedule.trigger.everyMs;
468
+ if (next === undefined || next > now || schedule.catchUp !== "latest") return next;
469
+ if (schedule.trigger.kind === "calendar") return Date.parse(latestCalendarOccurrence(schedule.trigger, now, schedule.trigger.nextLocalDate)!.nextRunAt);
470
+ if (schedule.trigger.kind === "interval") return next + Math.floor((now - next) / schedule.trigger.everyMs) * schedule.trigger.everyMs;
471
+ return next;
472
+ }
473
+
474
+ function triggerLabel(trigger: ScheduleTrigger): string {
475
+ if (trigger.kind === "calendar") return `every ${trigger.every}${trigger.on ? ` (${trigger.on.join(", ")})` : ""} at ${trigger.at} ${trigger.timezone}`;
476
+ return trigger.kind === "once" ? `at ${trigger.at}` : `every ${trigger.every}`;
419
477
  }
420
478
 
421
479
  function textResult(text: string, schedules?: ScheduleRecord[], runs?: ScheduleRunRecord[], isError = false): AgentToolResult<Details> {
@@ -444,8 +502,10 @@ function sanitizeTarget(params: SubagentParamsLike): { target?: ScheduleTarget;
444
502
  if (params.context === "fork") return { error: "Scheduled runs require fresh context." };
445
503
  if (params.async === false) return { error: "Scheduled runs are always async." };
446
504
  let baseRef: string | undefined;
505
+ let missionId: string | undefined;
447
506
  try {
448
507
  baseRef = normalizeWorktreeBaseRef(params.baseRef);
508
+ missionId = params.missionId === undefined ? undefined : validateMissionId(params.missionId);
449
509
  } catch (error) {
450
510
  return { error: error instanceof Error ? error.message : String(error) };
451
511
  }
@@ -453,7 +513,7 @@ function sanitizeTarget(params: SubagentParamsLike): { target?: ScheduleTarget;
453
513
  if (acceptanceErrors.length) return { error: acceptanceErrors.join(" ") };
454
514
  const normalizedArgs = normalizeWorkflowArgs(params.args);
455
515
  if ("error" in normalizedArgs) return { error: normalizedArgs.error };
456
- return { target: { workflowScript: params.workflowScript.trim(), args: deepFreezeWorkflowArgs(normalizedArgs.args), ...(baseRef === undefined ? {} : { baseRef }) } };
516
+ return { target: { workflowScript: params.workflowScript.trim(), args: deepFreezeWorkflowArgs(normalizedArgs.args), ...(baseRef === undefined ? {} : { baseRef }), ...(missionId === undefined ? {} : { missionId }) } };
457
517
  }
458
518
 
459
519
  function executionParams(schedule: ScheduleRecord, quiet = false): SubagentParamsLike {
@@ -462,7 +522,7 @@ function executionParams(schedule: ScheduleRecord, quiet = false): SubagentParam
462
522
  async: true,
463
523
  context: "fresh",
464
524
  cwd: schedule.cwd,
465
- mission: false,
525
+ ...(schedule.target.missionId === undefined ? { mission: false as const } : {}),
466
526
  // Scheduled fires have no operator watching, so completions must name the origin.
467
527
  scheduleOrigin: { id: schedule.id, ...(schedule.name ? { name: schedule.name } : {}), ...(quiet ? { quiet: true } : {}) },
468
528
  ...(schedule.timeoutMs === undefined ? {} : { timeoutMs: schedule.timeoutMs }),
@@ -598,8 +658,10 @@ export class ScheduledRunManager {
598
658
  for (const id of ids) {
599
659
  try {
600
660
  const schedule = store.get(id);
601
- const run = store.history(id).find((item) => item.asyncId === asyncId && item.state === "running");
602
- if (!run) continue;
661
+ const listed: ScheduleRunRecord | undefined = store.history(id).find((item) => item.asyncId === asyncId) ?? this.activeRun(store, schedule);
662
+ // history.json can lag the run's receipt when its update timed out.
663
+ const run: ScheduleRunRecord | undefined = listed && (store.getRun(id, listed.id) ?? listed);
664
+ if (run?.asyncId !== asyncId || run.state !== "running") continue;
603
665
  this.finishRun(store, schedule, run, data.success === true, typeof data.summary === "string" ? data.summary : undefined);
604
666
  return;
605
667
  } catch (error) {
@@ -615,17 +677,21 @@ export class ScheduledRunManager {
615
677
  if (target.error) return textResult(target.error, undefined, undefined, true);
616
678
  const at = params.at?.trim();
617
679
  const every = params.every?.trim();
618
- if (Boolean(at) === Boolean(every)) return textResult("schedule.create requires exactly one trigger: at or every.", undefined, undefined, true);
680
+ const calendar = every === "day" || every === "week";
681
+ if (!calendar && Boolean(at) === Boolean(every)) return textResult("schedule.create requires exactly one trigger: at or every.", undefined, undefined, true);
619
682
  if (params.overlap !== undefined && params.overlap !== "skip") return textResult("This first recurring slice supports overlap='skip' only.", undefined, undefined, true);
620
683
  if (params.catchUp !== undefined && params.catchUp !== "none" && params.catchUp !== "latest") return textResult("catchUp must be 'none' or 'latest'.", undefined, undefined, true);
621
- if (params.missionId !== undefined || params.mission !== undefined || params.missionUpdate !== undefined || params.missionStatus !== undefined || params.missionScope !== undefined) return textResult("Mission attachment is deferred from this first schedule slice.", undefined, undefined, true);
622
- if (params.on !== undefined || params.timezone !== undefined || every === "day" || every === "week" || every === "month" || every === "year") return textResult("Calendar schedules are deferred from this first safe slice. Use a fixed interval such as every:'24h' or every:'7d'.", undefined, undefined, true);
684
+ if (params.mission !== undefined || params.missionUpdate !== undefined || params.missionStatus !== undefined || params.missionScope !== undefined) return textResult("Schedules accept only an existing missionId; mission creation and updates are unsupported.", undefined, undefined, true);
685
+ if (!calendar && (params.on !== undefined || params.timezone !== undefined)) return textResult("on and timezone require every:'day' or every:'week'.", undefined, undefined, true);
623
686
  if (params.quiet !== undefined && typeof params.quiet !== "boolean") return textResult("quiet must be a boolean.", undefined, undefined, true);
624
- if (at && params.quiet === true) return textResult("quiet is only supported for recurring schedules.", undefined, undefined, true);
687
+ if (!calendar && at && params.quiet === true) return textResult("quiet is only supported for recurring schedules.", undefined, undefined, true);
625
688
  const sessionOnly = params.sessionOnly === true;
626
689
  if (sessionOnly && params.cwd !== undefined && !samePath(params.cwd, ctx.cwd)) return textResult("sessionOnly schedules cannot use an explicit cross-project cwd.", undefined, undefined, true);
627
690
  const ownerSessionFile = sessionOnly ? ctx.sessionManager.getSessionFile() : undefined;
628
691
  if (sessionOnly && !ownerSessionFile) return textResult("sessionOnly schedules require a persisted current session.", undefined, undefined, true);
692
+ if (target.target!.missionId !== undefined) {
693
+ readMission(resolveMissionStoreLocation({ projectRoot: path.resolve(params.cwd ?? ctx.cwd), ...(this.deps.config.missions ? { config: this.deps.config.missions } : {}) }), target.target!.missionId);
694
+ }
629
695
  const sessionId = ctx.sessionManager.getSessionId() ?? "unknown";
630
696
  if (this.deps.resolveCapabilityCeiling?.(sessionId)) return textResult("Cannot persist a schedule while a capability ceiling is active.", undefined, undefined, true);
631
697
  const pendingCount = store.list().filter(hasPendingScheduleWork).length;
@@ -635,7 +701,10 @@ export class ScheduledRunManager {
635
701
  if (store.ids().includes(id)) return textResult(`Schedule '${id}' already exists.`, undefined, undefined, true);
636
702
  const now = this.now();
637
703
  let trigger: ScheduleTrigger;
638
- if (at) {
704
+ if (calendar) {
705
+ const rule = normalizeCalendarRule({ every, at, on: params.on, timezone: params.timezone });
706
+ trigger = { kind: "calendar", ...rule, ...nextCalendarOccurrence(rule, now) };
707
+ } else if (at) {
639
708
  const planned = parseScheduledRunTime(at, now);
640
709
  trigger = { kind: "once", at, nextRunAt: timestamp(planned) };
641
710
  } else {
@@ -643,7 +712,8 @@ export class ScheduledRunManager {
643
712
  trigger = { kind: "interval", every: every!, everyMs, anchorAt: timestamp(now), nextRunAt: timestamp(now + everyMs) };
644
713
  }
645
714
  const schedule: ScheduleRecord = {
646
- schemaVersion: 1,
715
+ // Older readers ignore unknown target fields; they must reject mission-bound definitions.
716
+ schemaVersion: target.target!.missionId === undefined ? 1 : 2,
647
717
  id,
648
718
  name: params.name?.trim() || targetLabel(target.target!),
649
719
  cwd: path.resolve(params.cwd ?? ctx.cwd),
@@ -654,25 +724,25 @@ export class ScheduledRunManager {
654
724
  ...(params.timeoutMs === undefined ? {} : { timeoutMs: params.timeoutMs }),
655
725
  paused: false,
656
726
  ...(sessionOnly ? { sessionOnly: true, ownerSessionFile: path.resolve(ownerSessionFile!) } : {}),
657
- ...(trigger.kind === "interval" && params.quiet === true ? { quiet: true } : {}),
727
+ ...(trigger.kind !== "once" && params.quiet === true ? { quiet: true } : {}),
658
728
  createdAt: timestamp(now),
659
729
  updatedAt: timestamp(now),
660
730
  };
661
731
  store.write(schedule);
662
732
  store.appendEvent(schedule, "schedule.created");
663
733
  this.arm(schedule, store);
664
- return textResult(`Created schedule ${id}.\nName: ${schedule.name}\nTrigger: ${at ? `at ${at}` : `every ${every}`}\nSession only: ${schedule.sessionOnly === true ? "yes" : "no"}\nQuiet: ${schedule.quiet === true ? "yes" : "no"}\nNext: ${schedule.trigger.nextRunAt}\nTarget: ${targetLabel(schedule.target)}`, [schedule]);
734
+ return textResult(`Created schedule ${id}.\nName: ${schedule.name}\nTrigger: ${triggerLabel(trigger)}\nSession only: ${schedule.sessionOnly === true ? "yes" : "no"}\nQuiet: ${schedule.quiet === true ? "yes" : "no"}\nNext: ${schedule.trigger.nextRunAt}\nTarget: ${targetLabel(schedule.target)}${schedule.target.missionId === undefined ? "" : `\nMission: ${schedule.target.missionId}`}`, [schedule]);
665
735
  }
666
736
 
667
737
  private list(): AgentToolResult<Details> {
668
738
  const schedules = this.requireStore().list().sort((a, b) => (a.trigger.nextRunAt ?? "").localeCompare(b.trigger.nextRunAt ?? ""));
669
739
  if (!schedules.length) return textResult("No project schedules.", []);
670
- return textResult([`Project schedules: ${schedules.length}`, ...schedules.map((item) => `- ${item.id} | ${item.paused ? "paused" : item.activeRunId ? "running" : "scheduled"} | ${item.trigger.nextRunAt ?? "no next run"} | ${item.sessionOnly === true ? "session-only" : "project"} | ${item.name}`)].join("\n"), schedules);
740
+ return textResult([`Project schedules: ${schedules.length}`, ...schedules.map((item) => `- ${item.id} | ${item.paused ? "paused" : item.activeRunId ? "running" : "scheduled"} | ${item.trigger.nextRunAt ?? "no next run"} | ${item.sessionOnly === true ? "session-only" : "project"} | ${item.name}${item.target.missionId === undefined ? "" : ` | mission ${item.target.missionId}`}`)].join("\n"), schedules);
671
741
  }
672
742
 
673
743
  private show(params: SubagentParamsLike): AgentToolResult<Details> {
674
744
  const schedule = this.resolve(params);
675
- return textResult([`Schedule: ${schedule.id}`, `Name: ${schedule.name}`, `State: ${schedule.paused ? "paused" : schedule.activeRunId ? "running" : "scheduled"}`, `Session only: ${schedule.sessionOnly === true ? "yes" : "no"}`, `Quiet: ${schedule.quiet === true ? "yes" : "no"}`, `Target: ${targetLabel(schedule.target)}`, `CWD: ${shortenPath(schedule.cwd)}`, `Next: ${schedule.trigger.nextRunAt ?? "none"}`, `Catch up: ${schedule.catchUp}`, schedule.activeRunId ? `Active run: ${schedule.activeRunId}` : undefined].filter(Boolean).join("\n"), [schedule]);
745
+ return textResult([`Schedule: ${schedule.id}`, `Name: ${schedule.name}`, `State: ${schedule.paused ? "paused" : schedule.activeRunId ? "running" : "scheduled"}`, `Session only: ${schedule.sessionOnly === true ? "yes" : "no"}`, `Quiet: ${schedule.quiet === true ? "yes" : "no"}`, `Target: ${targetLabel(schedule.target)}`, schedule.target.missionId === undefined ? undefined : `Mission: ${schedule.target.missionId}`, `CWD: ${shortenPath(schedule.cwd)}`, `Trigger: ${triggerLabel(schedule.trigger)}`, `Next: ${schedule.trigger.nextRunAt ?? "none"}`, `Catch up: ${schedule.catchUp}`, schedule.activeRunId ? `Active run: ${schedule.activeRunId}` : undefined].filter(Boolean).join("\n"), [schedule]);
676
746
  }
677
747
 
678
748
  private history(params: SubagentParamsLike): AgentToolResult<Details> {
@@ -701,11 +771,17 @@ export class ScheduledRunManager {
701
771
  return textResult(`Skipped schedule ${schedule.id}: current session is not its owner.`, [schedule]);
702
772
  }
703
773
  if (params.quiet !== undefined && typeof params.quiet !== "boolean") return textResult("quiet must be a boolean.", undefined, undefined, true);
774
+ const manualTrigger = schedule.trigger;
704
775
  const run = await this.launch(store, schedule, this.now(), "manual", false, params.quiet === true);
705
776
  const updated = store.get(schedule.id);
706
777
  if (run.state === "running") {
707
778
  const now = this.now();
708
- if (updated.trigger.kind === "interval") updated.trigger.nextRunAt = timestamp(now + updated.trigger.everyMs);
779
+ if (updated.trigger.kind === "calendar") {
780
+ if (manualTrigger.kind !== "calendar") throw new Error("Schedule trigger changed during manual launch.");
781
+ const consumed = latestCalendarOccurrence(manualTrigger, now, manualTrigger.nextLocalDate)?.nextRunAt ?? manualTrigger.nextRunAt;
782
+ const advanced = nextAfter(manualTrigger, Date.parse(consumed), now) as CalendarTrigger;
783
+ if (advanced.nextLocalDate > updated.trigger.nextLocalDate) updated.trigger = advanced;
784
+ } else if (updated.trigger.kind === "interval") updated.trigger.nextRunAt = timestamp(now + updated.trigger.everyMs);
709
785
  else updated.trigger.nextRunAt = undefined;
710
786
  updated.updatedAt = timestamp(now);
711
787
  store.write(updated);
@@ -732,7 +808,7 @@ export class ScheduledRunManager {
732
808
  const schedule = this.resolve(params);
733
809
  const store = this.requireStore();
734
810
  if (schedule.activeRunId) {
735
- const run = store.history(schedule.id).find((item) => item.id === schedule.activeRunId);
811
+ const run = this.activeRun(store, schedule);
736
812
  let terminal = false;
737
813
  if (run?.scheduleId === schedule.id && run.state === "running" && run.asyncId && run.asyncDir) {
738
814
  const status = readJson(path.join(run.asyncDir, "status.json"), "async status") as Partial<AsyncStatus>;
@@ -752,17 +828,40 @@ export class ScheduledRunManager {
752
828
 
753
829
  private restoreOne(store: ScheduleStore, schedule: ScheduleRecord, notBefore?: number, rearm = true): void {
754
830
  if (!scheduleBelongsToSession(schedule, this.requireContext(store))) return;
831
+ if (schedule.trigger.kind === "calendar") {
832
+ const refreshed = restoreCalendarTrigger(schedule.trigger);
833
+ if (JSON.stringify(refreshed) !== JSON.stringify(schedule.trigger)) {
834
+ schedule.trigger = refreshed;
835
+ schedule.updatedAt = timestamp(this.now());
836
+ store.write(schedule);
837
+ }
838
+ }
755
839
  if (schedule.activeRunId) {
756
- const run = store.history(schedule.id).find((item) => item.id === schedule.activeRunId);
840
+ const run = this.activeRun(store, schedule);
757
841
  if (run?.state === "running" && run.asyncId) this.observedAsyncIds.add(run.asyncId);
758
842
  const startedAt = run?.startedAt ? Date.parse(run.startedAt) : Number.NaN;
759
- if (run?.state === "running" && run.asyncDir) {
843
+ const outcome = this.terminalAsyncOutcome(run);
844
+ if (run && outcome) {
845
+ // Restore releases a dead or terminal claim at most once and never re-enters itself. On success it continues
846
+ // to the existing policy code below with the latest record. On failure it arms the schedule from disk, so the
847
+ // next fire retries the release, and the original error propagates unchanged.
848
+ let latest: ScheduleRecord | undefined;
760
849
  try {
761
- const status = readJson(path.join(run.asyncDir, "status.json"), "async status") as Partial<AsyncStatus>;
762
- if (["complete", "failed", "stopped", "rejected"].includes(String(status.state))) this.finishRun(store, schedule, run, status.state === "complete", typeof status.error === "string" ? status.error : undefined);
850
+ latest = this.finishRun(store, schedule, run, outcome.success, outcome.error, true) ?? store.find(schedule.id);
763
851
  } catch (error) {
764
- if ((error as NodeJS.ErrnoException).code !== "ENOENT" && !(error instanceof Error && /ENOENT/.test(error.message))) throw error;
852
+ if (rearm) {
853
+ try {
854
+ const current = store.find(schedule.id);
855
+ if (current) this.arm(current, store, notBefore);
856
+ } catch { /* Keep the release error. */ }
857
+ }
858
+ throw error;
859
+ }
860
+ if (!latest) {
861
+ this.clearTimer(store, schedule.id);
862
+ return;
765
863
  }
864
+ schedule = latest;
766
865
  }
767
866
  if (schedule.activeRunId && (!run || run.state !== "running" || (!run.asyncId && Number.isFinite(startedAt) && startedAt + STALE_LAUNCH_CLAIM_MS <= this.now()))) {
768
867
  if (run?.state === "running") {
@@ -814,9 +913,9 @@ export class ScheduledRunManager {
814
913
  const schedule = store.find(id);
815
914
  if (!schedule) return;
816
915
  const now = this.now();
817
- const planned = schedule.trigger.kind === "interval" ? duePlannedAt(schedule, now) : undefined;
818
- const notBefore = planned !== undefined && planned <= now ? Date.parse(nextAfter(schedule.trigger, planned, now)!) : undefined;
819
- this.restoreOne(store, schedule, notBefore, schedule.trigger.kind === "interval");
916
+ const planned = schedule.trigger.kind !== "once" ? duePlannedAt(schedule, now) : undefined;
917
+ const notBefore = planned !== undefined && planned <= now ? Date.parse(nextAfter(schedule.trigger, planned, now).nextRunAt!) : undefined;
918
+ this.restoreOne(store, schedule, notBefore, schedule.trigger.kind !== "once");
820
919
  } catch (error) {
821
920
  console.warn(`[pi-subagents] Scheduled run '${id}' could not be restored after fire failure: ${error instanceof Error ? error.message : String(error)}`);
822
921
  }
@@ -840,12 +939,30 @@ export class ScheduledRunManager {
840
939
  private async launch(store: ScheduleStore, schedule: ScheduleRecord, planned: number, dueReason: ScheduleRunRecord["dueReason"], advance: boolean, quiet?: boolean): Promise<ScheduleRunRecord> {
841
940
  const now = this.now();
842
941
  const nextRunAtBeforeClaim = schedule.trigger.nextRunAt;
942
+ const nextLocalDateBeforeClaim = schedule.trigger.kind === "calendar" ? schedule.trigger.nextLocalDate : undefined;
843
943
  const run: ScheduleRunRecord = { schemaVersion: 1, id: this.randomId(), scheduleId: schedule.id, plannedAt: timestamp(planned), dueReason, state: "running", startedAt: timestamp(now) };
944
+ if (schedule.activeRunId) {
945
+ let active: ScheduleRunRecord | undefined;
946
+ let outcome: { success: boolean; error?: string } | undefined;
947
+ try {
948
+ active = this.activeRun(store, schedule);
949
+ outcome = this.terminalAsyncOutcome(active);
950
+ } catch (error) {
951
+ console.warn(`[pi-subagents] Could not reconcile active run '${schedule.activeRunId}' of schedule '${schedule.id}': ${error instanceof Error ? error.message : String(error)}`);
952
+ }
953
+ // A dead runner's completion never reaches this schedule, so its claim would skip every later fire.
954
+ if (active && outcome) {
955
+ const released = this.finishRun(store, schedule, active, outcome.success, outcome.error, true);
956
+ // Another session already released or re-claimed that run for this occurrence.
957
+ if (!released) return this.skipLostClaim(store, schedule.id, run, planned, now);
958
+ schedule = released;
959
+ }
960
+ }
844
961
  if (schedule.activeRunId) {
845
962
  run.state = "skipped";
846
963
  run.completedAt = timestamp(now);
847
964
  if (advance) {
848
- schedule.trigger.nextRunAt = nextAfter(schedule.trigger, planned, now);
965
+ schedule.trigger = nextAfter(schedule.trigger, planned, now);
849
966
  schedule.updatedAt = timestamp(now);
850
967
  store.write(schedule);
851
968
  }
@@ -855,30 +972,50 @@ export class ScheduledRunManager {
855
972
  }
856
973
  const lockPath = path.join(store.directory(schedule.id, true), "active.lock");
857
974
  fs.mkdirSync(path.dirname(lockPath), { recursive: true, mode: 0o700 });
858
- let lock: number;
975
+ let lock: number | undefined;
859
976
  try {
860
977
  lock = fs.openSync(lockPath, "wx", 0o600);
861
978
  fs.writeFileSync(lock, run.id, "utf-8");
862
979
  fs.closeSync(lock);
863
980
  } catch (error) {
864
- if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
865
- run.state = "skipped";
866
- run.completedAt = timestamp(now);
867
- if (advance) {
868
- schedule.trigger.nextRunAt = nextAfter(schedule.trigger, planned, now);
869
- schedule.updatedAt = timestamp(now);
870
- store.write(schedule);
981
+ if (lock !== undefined) {
982
+ // An empty or partial claim would make every later launch skip. Keep the
983
+ // descriptor open until the inode check so a replacement owner's lock survives.
984
+ try {
985
+ // Bigint stats: Windows file ids exceed 2^53, so number inodes of nearby files can compare equal.
986
+ const owned = fs.fstatSync(lock, { bigint: true });
987
+ const current = fs.lstatSync(lockPath, { bigint: true });
988
+ if (owned.ino !== 0n && owned.dev === current.dev && owned.ino === current.ino) fs.rmSync(lockPath);
989
+ } catch { /* Preserve the original error. */ }
990
+ try { fs.closeSync(lock); } catch { /* Preserve the original error. */ }
991
+ throw error;
871
992
  }
872
- store.writeRun(schedule, run, "schedule.skipped_overlap");
873
- this.arm(schedule, store);
874
- return run;
993
+ if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
994
+ return this.skipLostClaim(store, schedule.id, run, planned, now);
875
995
  }
876
996
  schedule.activeRunId = run.id;
877
997
  schedule.lastRunId = run.id;
878
- if (advance) schedule.trigger.nextRunAt = nextAfter(schedule.trigger, planned, now);
998
+ if (advance) schedule.trigger = nextAfter(schedule.trigger, planned, now);
879
999
  schedule.updatedAt = timestamp(now);
880
- store.write(schedule);
881
- store.writeRun(schedule, run, "schedule.run.started");
1000
+ try {
1001
+ store.write(schedule);
1002
+ store.writeRun(schedule, run, "schedule.run.started");
1003
+ } catch (error) {
1004
+ // No child has launched: release this run's claim, then report the original error.
1005
+ // Another session may already have recovered the claim and launched its own run.
1006
+ try {
1007
+ const latest = store.find(schedule.id);
1008
+ if (latest?.activeRunId === run.id) {
1009
+ latest.activeRunId = undefined;
1010
+ latest.updatedAt = timestamp(this.now());
1011
+ store.write(latest);
1012
+ }
1013
+ if (fs.readFileSync(lockPath, "utf-8") === run.id) fs.rmSync(lockPath);
1014
+ } catch (cleanupError) {
1015
+ console.warn(`[pi-subagents] Could not release schedule claim '${run.id}': ${cleanupError instanceof Error ? cleanupError.message : String(cleanupError)}`);
1016
+ }
1017
+ throw error;
1018
+ }
882
1019
  try {
883
1020
  const result = await this.deps.launch(executionParams(schedule, dueReason === "manual" ? quiet === true : schedule.quiet === true), this.requireContext(store), new AbortController().signal);
884
1021
  const asyncId = result.details?.asyncId ?? result.details?.runId;
@@ -890,27 +1027,53 @@ export class ScheduledRunManager {
890
1027
  this.arm(schedule, store);
891
1028
  return run;
892
1029
  } catch (error) {
1030
+ // The child is running, so its claim stays until completion.
1031
+ if (run.asyncId) throw new Error(`Scheduled run '${run.id}' attached to async run '${run.asyncId}', but recording it failed: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
893
1032
  run.state = "failed_launch";
894
1033
  run.completedAt = timestamp(this.now());
895
1034
  run.error = error instanceof Error ? error.message : String(error);
896
1035
  const latest = store.get(schedule.id);
897
1036
  latest.activeRunId = undefined;
898
- if (!advance && nextRunAtBeforeClaim) latest.trigger.nextRunAt = nextRunAtBeforeClaim;
1037
+ if (!advance && nextRunAtBeforeClaim) {
1038
+ if (latest.trigger.kind === "calendar") {
1039
+ // An overlapping timer may have advanced both cursor fields while
1040
+ // this manual attachment was pending. Failure satisfies neither.
1041
+ if (nextLocalDateBeforeClaim !== undefined) {
1042
+ latest.trigger.nextLocalDate = nextLocalDateBeforeClaim;
1043
+ latest.trigger.nextRunAt = nextRunAtBeforeClaim;
1044
+ }
1045
+ } else latest.trigger.nextRunAt = nextRunAtBeforeClaim;
1046
+ }
899
1047
  latest.updatedAt = timestamp(this.now());
900
1048
  store.write(latest);
901
- store.writeRun(latest, run, "schedule.run.failed");
902
1049
  fs.rmSync(lockPath, { force: true });
903
- this.arm(latest, store);
1050
+ try {
1051
+ store.writeRun(latest, run, "schedule.run.failed");
1052
+ } finally {
1053
+ this.arm(latest, store);
1054
+ }
904
1055
  return run;
905
1056
  }
906
1057
  }
907
1058
 
908
- private finishRun(store: ScheduleStore, schedule: ScheduleRecord, run: ScheduleRunRecord, success: boolean, error?: string): void {
1059
+ /**
1060
+ * `releaseOnly` releases a dead run's claim and leaves the pending occurrence to the caller: it neither skips nor re-arms it.
1061
+ * It acts only while the schedule on disk still names that run, and returns the record it wrote, or undefined when another
1062
+ * session already released or re-claimed it.
1063
+ */
1064
+ private finishRun(store: ScheduleStore, schedule: ScheduleRecord, run: ScheduleRunRecord, success: boolean, error?: string, releaseOnly = false): ScheduleRecord | undefined {
909
1065
  const now = this.now();
1066
+ if (run.asyncId) this.observedAsyncIds.delete(run.asyncId);
1067
+ if (releaseOnly) {
1068
+ const latest = store.find(schedule.id);
1069
+ if (latest?.activeRunId !== run.id) return undefined;
1070
+ schedule = latest;
1071
+ }
910
1072
  const next = nextRunAt(schedule);
911
- if (next !== undefined && next <= now) {
1073
+ let skipped: ScheduleRunRecord | undefined;
1074
+ if (!releaseOnly && next !== undefined && next <= now) {
912
1075
  const planned = duePlannedAt(schedule, now)!;
913
- const skipped: ScheduleRunRecord = {
1076
+ skipped = {
914
1077
  schemaVersion: 1,
915
1078
  id: this.randomId(),
916
1079
  scheduleId: schedule.id,
@@ -919,19 +1082,51 @@ export class ScheduledRunManager {
919
1082
  state: "skipped",
920
1083
  completedAt: timestamp(now),
921
1084
  };
922
- schedule.trigger.nextRunAt = nextAfter(schedule.trigger, planned, now);
923
- store.writeRun(schedule, skipped, "schedule.skipped_overlap");
1085
+ schedule.trigger = nextAfter(schedule.trigger, planned, now);
924
1086
  }
925
- if (run.asyncId) this.observedAsyncIds.delete(run.asyncId);
926
1087
  run.state = success ? "completed" : "failed_run";
927
1088
  run.completedAt = timestamp(now);
928
1089
  if (!success && error) run.error = error;
929
1090
  schedule.activeRunId = undefined;
930
1091
  schedule.updatedAt = timestamp(now);
931
1092
  store.write(schedule);
932
- fs.rmSync(path.join(store.directory(schedule.id), "active.lock"), { force: true });
933
- store.writeRun(schedule, run, success ? "schedule.run.completed" : "schedule.run.failed");
934
- this.arm(schedule, store);
1093
+ const lockPath = path.join(store.directory(schedule.id), "active.lock");
1094
+ // A released dead run's lock may already belong to another session's newer claim.
1095
+ let holder: string | undefined;
1096
+ if (releaseOnly) try { holder = fs.readFileSync(lockPath, "utf-8"); } catch { /* No readable lock names this run. */ }
1097
+ if (!releaseOnly || holder === run.id) fs.rmSync(lockPath, { force: true });
1098
+ // The schedule is already released; a history.json timeout must not leave it unarmed.
1099
+ try {
1100
+ store.writeRun(schedule, run, success ? "schedule.run.completed" : "schedule.run.failed");
1101
+ if (skipped) store.writeRun(schedule, skipped, "schedule.skipped_overlap");
1102
+ } finally {
1103
+ if (!releaseOnly) this.arm(schedule, store);
1104
+ }
1105
+ return schedule;
1106
+ }
1107
+
1108
+ private skipLostClaim(store: ScheduleStore, scheduleId: string, run: ScheduleRunRecord, planned: number, now: number): ScheduleRunRecord {
1109
+ run.state = "skipped";
1110
+ run.completedAt = timestamp(now);
1111
+ // Losing the claim gives this snapshot no authority to change the owner.
1112
+ const latest = store.find(scheduleId);
1113
+ if (!latest) {
1114
+ this.clearTimer(store, scheduleId);
1115
+ return run;
1116
+ }
1117
+ store.writeRun(latest, run, "schedule.skipped_overlap");
1118
+ if (latest.trigger.kind === "once") {
1119
+ this.clearTimer(store, latest.id);
1120
+ } else {
1121
+ // The owner may hold the lock before persisting its cursor. Back off
1122
+ // locally without consuming that pending occurrence on disk.
1123
+ const next = nextRunAt(latest);
1124
+ const notBefore = next !== undefined && next <= now
1125
+ ? Date.parse(nextAfter(latest.trigger, duePlannedAt(latest, now) ?? planned, now).nextRunAt!)
1126
+ : undefined;
1127
+ this.arm(latest, store, notBefore);
1128
+ }
1129
+ return run;
935
1130
  }
936
1131
 
937
1132
  private recordMissed(store: ScheduleStore, schedule: ScheduleRecord, planned: number, dueReason: ScheduleRunRecord["dueReason"]): ScheduleRunRecord {
@@ -944,7 +1139,7 @@ export class ScheduledRunManager {
944
1139
  state: "missed",
945
1140
  completedAt: timestamp(this.now()),
946
1141
  };
947
- schedule.trigger.nextRunAt = nextAfter(schedule.trigger, planned, this.now());
1142
+ schedule.trigger = nextAfter(schedule.trigger, planned, this.now());
948
1143
  schedule.updatedAt = timestamp(this.now());
949
1144
  store.write(schedule);
950
1145
  store.writeRun(schedule, run, "schedule.missed");
@@ -989,6 +1184,21 @@ export class ScheduledRunManager {
989
1184
  return ctx;
990
1185
  }
991
1186
 
1187
+ private activeRun(store: ScheduleStore, schedule: ScheduleRecord): ScheduleRunRecord | undefined {
1188
+ if (!schedule.activeRunId) return undefined;
1189
+ return store.getRun(schedule.id, schedule.activeRunId) ?? store.history(schedule.id).find((run) => run.id === schedule.activeRunId);
1190
+ }
1191
+
1192
+ /** Reconciles an attached running run (a dead runner PID becomes failed) and returns its outcome once terminal. */
1193
+ private terminalAsyncOutcome(run: ScheduleRunRecord | undefined): { success: boolean; error?: string } | undefined {
1194
+ if (run?.state !== "running" || !run.asyncDir) return undefined;
1195
+ const status = reconcileAsyncRun(run.asyncDir, { now: this.now, kill: this.deps.kill }).status;
1196
+ if (!status || !["complete", "failed", "stopped", "rejected"].includes(status.state)) return undefined;
1197
+ // Stale-run repair records its reason on the failed steps, not the root status.
1198
+ const error = [status.error, ...(status.steps ?? []).map((step) => step.error)].find((value): value is string => typeof value === "string");
1199
+ return { success: status.state === "complete", error };
1200
+ }
1201
+
992
1202
  private timerKey(store: ScheduleStore, id: string): string {
993
1203
  return `${store.root}\0${id}`;
994
1204
  }