@oyasmi/pipiclaw 0.9.2 → 0.9.3-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (165) hide show
  1. package/README.en.md +250 -0
  2. package/README.md +2 -0
  3. package/dist/agent/channel-runner.d.ts +43 -2
  4. package/dist/agent/channel-runner.js +135 -75
  5. package/dist/agent/job-manager.d.ts +76 -21
  6. package/dist/agent/job-manager.js +447 -63
  7. package/dist/agent/maintenance-context.js +4 -5
  8. package/dist/agent/prompt/manifest.d.ts +0 -2
  9. package/dist/agent/prompt/manifest.js +2 -3
  10. package/dist/agent/prompt/sections.js +3 -3
  11. package/dist/agent/session-events.js +4 -8
  12. package/dist/agent/turn-prompt.d.ts +7 -7
  13. package/dist/agent/turn-prompt.js +6 -9
  14. package/dist/agent/types.d.ts +12 -0
  15. package/dist/agent/types.js +1 -0
  16. package/dist/channel/channel-context.d.ts +13 -0
  17. package/dist/channel/channel-context.js +21 -1
  18. package/dist/commands/catalog.js +47 -20
  19. package/dist/memory/commands.d.ts +8 -0
  20. package/dist/memory/commands.js +113 -148
  21. package/dist/memory/index-budget.d.ts +27 -0
  22. package/dist/memory/index-budget.js +99 -0
  23. package/dist/memory/journal.d.ts +20 -0
  24. package/dist/memory/journal.js +78 -0
  25. package/dist/memory/lifecycle.d.ts +9 -15
  26. package/dist/memory/lifecycle.js +55 -145
  27. package/dist/memory/maintenance-gates.d.ts +13 -47
  28. package/dist/memory/maintenance-gates.js +13 -92
  29. package/dist/memory/maintenance-state.d.ts +10 -16
  30. package/dist/memory/maintenance-state.js +12 -59
  31. package/dist/memory/maintenance-tuning.d.ts +7 -27
  32. package/dist/memory/maintenance-tuning.js +11 -28
  33. package/dist/memory/migrate.d.ts +15 -0
  34. package/dist/memory/migrate.js +364 -0
  35. package/dist/memory/reflect-job.d.ts +43 -0
  36. package/dist/memory/reflect-job.js +117 -0
  37. package/dist/memory/reflect.d.ts +52 -0
  38. package/dist/memory/reflect.js +313 -0
  39. package/dist/memory/render.d.ts +14 -0
  40. package/dist/memory/render.js +28 -0
  41. package/dist/memory/review-log.d.ts +2 -1
  42. package/dist/memory/scheduler.d.ts +2 -3
  43. package/dist/memory/scheduler.js +14 -49
  44. package/dist/memory/search.d.ts +35 -0
  45. package/dist/memory/search.js +297 -0
  46. package/dist/memory/session-search.js +1 -1
  47. package/dist/memory/store.d.ts +108 -0
  48. package/dist/memory/store.js +418 -0
  49. package/dist/memory/task-digest.d.ts +2 -2
  50. package/dist/memory/task-digest.js +29 -36
  51. package/dist/memory/tombstones.d.ts +0 -11
  52. package/dist/memory/tombstones.js +6 -37
  53. package/dist/playbooks/agent-delegation.md +4 -2
  54. package/dist/playbooks/background-jobs.md +1 -1
  55. package/dist/playbooks/event-scheduling.md +6 -2
  56. package/dist/playbooks/memory-and-learning.md +18 -11
  57. package/dist/playbooks/outbound-media.md +1 -1
  58. package/dist/playbooks/runtime-orientation.md +9 -8
  59. package/dist/playbooks/task-loop.md +88 -0
  60. package/dist/runtime/bootstrap.d.ts +3 -3
  61. package/dist/runtime/bootstrap.js +66 -41
  62. package/dist/runtime/events.d.ts +9 -0
  63. package/dist/runtime/events.js +43 -4
  64. package/dist/runtime/task-commands.d.ts +14 -15
  65. package/dist/runtime/task-commands.js +249 -485
  66. package/dist/runtime/task-driver.d.ts +41 -29
  67. package/dist/runtime/task-driver.js +170 -317
  68. package/dist/runtime/task-migration.d.ts +34 -30
  69. package/dist/runtime/task-migration.js +229 -183
  70. package/dist/runtime/task-wake.d.ts +6 -3
  71. package/dist/runtime/task-wake.js +26 -19
  72. package/dist/settings.d.ts +0 -29
  73. package/dist/settings.js +12 -35
  74. package/dist/shared/markdown-sections.d.ts +0 -1
  75. package/dist/shared/markdown-sections.js +0 -3
  76. package/dist/subagents/discovery.d.ts +2 -2
  77. package/dist/subagents/discovery.js +21 -10
  78. package/dist/subagents/external/progress-tail.js +6 -1
  79. package/dist/subagents/external/run.js +1 -0
  80. package/dist/subagents/runs.d.ts +19 -2
  81. package/dist/subagents/runs.js +73 -4
  82. package/dist/subagents/tool.d.ts +10 -8
  83. package/dist/subagents/tool.js +55 -94
  84. package/dist/tasks/brief.d.ts +17 -0
  85. package/dist/tasks/brief.js +57 -0
  86. package/dist/tasks/budget.d.ts +26 -0
  87. package/dist/tasks/budget.js +59 -0
  88. package/dist/tasks/cycle.d.ts +48 -0
  89. package/dist/tasks/cycle.js +94 -0
  90. package/dist/tasks/frontmatter.d.ts +73 -0
  91. package/dist/tasks/frontmatter.js +175 -0
  92. package/dist/tasks/ledger.d.ts +66 -106
  93. package/dist/tasks/ledger.js +90 -546
  94. package/dist/tasks/log.d.ts +88 -0
  95. package/dist/tasks/log.js +97 -0
  96. package/dist/tasks/rounds.d.ts +43 -0
  97. package/dist/tasks/rounds.js +57 -0
  98. package/dist/tasks/session-path.d.ts +9 -0
  99. package/dist/tasks/session-path.js +16 -0
  100. package/dist/tasks/steer.d.ts +8 -0
  101. package/dist/tasks/steer.js +79 -0
  102. package/dist/tasks/store.d.ts +60 -35
  103. package/dist/tasks/store.js +166 -107
  104. package/dist/tasks/ticket.d.ts +102 -0
  105. package/dist/tasks/ticket.js +209 -0
  106. package/dist/tasks/verification.d.ts +16 -0
  107. package/dist/tasks/verification.js +40 -1
  108. package/dist/tools/index.d.ts +13 -4
  109. package/dist/tools/index.js +5 -10
  110. package/dist/tools/memory-manage.d.ts +6 -16
  111. package/dist/tools/memory-manage.js +108 -129
  112. package/dist/tools/presentation.js +2 -1
  113. package/dist/tools/registry.d.ts +11 -2
  114. package/dist/tools/registry.js +17 -6
  115. package/dist/tools/subagent-manage.d.ts +0 -9
  116. package/dist/tools/subagent-manage.js +8 -17
  117. package/dist/tools/task-manage/create.js +2 -2
  118. package/dist/tools/task-manage/lifecycle.d.ts +9 -4
  119. package/dist/tools/task-manage/lifecycle.js +139 -187
  120. package/dist/tools/task-manage/log-view.d.ts +8 -0
  121. package/dist/tools/task-manage/log-view.js +24 -0
  122. package/dist/tools/task-manage/schema.d.ts +38 -14
  123. package/dist/tools/task-manage/schema.js +46 -27
  124. package/dist/tools/task-manage/shared.d.ts +24 -31
  125. package/dist/tools/task-manage/shared.js +103 -141
  126. package/dist/tools/task-manage/step-end.d.ts +11 -0
  127. package/dist/tools/task-manage/step-end.js +136 -0
  128. package/dist/tools/task-manage/types.d.ts +23 -32
  129. package/dist/tools/task-manage.d.ts +4 -3
  130. package/dist/tools/task-manage.js +30 -15
  131. package/dist/tools/tool-details.d.ts +1 -1
  132. package/dist/tui/app.js +0 -2
  133. package/package.json +1 -1
  134. package/dist/agent/effect-ledger.d.ts +0 -32
  135. package/dist/agent/effect-ledger.js +0 -89
  136. package/dist/memory/bootstrap.d.ts +0 -17
  137. package/dist/memory/bootstrap.js +0 -120
  138. package/dist/memory/candidates.d.ts +0 -26
  139. package/dist/memory/candidates.js +0 -202
  140. package/dist/memory/consolidation.d.ts +0 -54
  141. package/dist/memory/consolidation.js +0 -292
  142. package/dist/memory/extraction.d.ts +0 -54
  143. package/dist/memory/extraction.js +0 -240
  144. package/dist/memory/files.d.ts +0 -71
  145. package/dist/memory/files.js +0 -419
  146. package/dist/memory/maintenance-jobs.d.ts +0 -41
  147. package/dist/memory/maintenance-jobs.js +0 -265
  148. package/dist/memory/metadata.d.ts +0 -57
  149. package/dist/memory/metadata.js +0 -142
  150. package/dist/memory/probation.d.ts +0 -17
  151. package/dist/memory/probation.js +0 -44
  152. package/dist/memory/promotion.d.ts +0 -38
  153. package/dist/memory/promotion.js +0 -36
  154. package/dist/memory/recall.d.ts +0 -59
  155. package/dist/memory/recall.js +0 -746
  156. package/dist/memory/session.d.ts +0 -24
  157. package/dist/memory/session.js +0 -273
  158. package/dist/playbooks/task-driving.md +0 -92
  159. package/dist/playbooks/task-planning.md +0 -58
  160. package/dist/tasks/control.d.ts +0 -56
  161. package/dist/tasks/control.js +0 -169
  162. package/dist/tasks/transitions.d.ts +0 -16
  163. package/dist/tasks/transitions.js +0 -48
  164. package/dist/tools/task-manage/verification.d.ts +0 -19
  165. package/dist/tools/task-manage/verification.js +0 -91
@@ -1,32 +1,36 @@
1
+ import type { TaskFrontmatterV4 } from "../tasks/frontmatter.js";
2
+ interface LegacyControl {
3
+ deadline?: string;
4
+ nextAction?: string;
5
+ cycleId?: string;
6
+ verification?: {
7
+ required?: boolean;
8
+ };
9
+ stop?: {
10
+ by?: string;
11
+ reason?: string;
12
+ at?: string;
13
+ };
14
+ }
15
+ interface LegacyFields {
16
+ status?: string;
17
+ enabled: boolean;
18
+ wake?: string;
19
+ schedule?: string;
20
+ control?: LegacyControl;
21
+ outcome?: "completed" | "cancelled";
22
+ closedAt?: string;
23
+ }
24
+ export interface LegacyTaskConversion {
25
+ fields: TaskFrontmatterV4;
26
+ /** Set when the v3 park had no reconstructible source and the task was reopened instead. */
27
+ repairNote?: string;
28
+ }
1
29
  /**
2
- * RETIRE AT v0.9.3 (code review 2026-08-30): both migrations in this file are startup self-heal
3
- * passes for on-disk state written by pre-0.9 betas (the pre-spec-029 `.schedule` event format,
4
- * and pre-spec-043 v1/v2 task control blocks and status vocabulary). Every 0.9.2-beta install is
5
- * a small, actively-developed fleet; by the 0.9.3 stable cut every install will have booted at
6
- * least once on a version that already runs these passes, so there is no longer any on-disk
7
- * state left for them to find. At 0.9.3: delete both exported functions here, their call sites
8
- * in `bootstrap.ts`, `parseLegacyTaskControl` in `../tasks/control.js` (this file's only caller),
9
- * and the paired legacy-state fold in `../memory/maintenance-state.js` (same rationale, unrelated
10
- * subsystem). Confirm first that no currently-supported version predates the pass being removed.
30
+ * The v3 → v4 field mapping. Exported for the migration test, which pins the one branch that
31
+ * matters most: a `waiting` task with no wake and no schedule becomes `open`, not a dead park.
11
32
  */
12
- /**
13
- * One-time migration closing the 027 window (spec 029, D6).
14
- *
15
- * Recurrence cadence now lives solely in a task's `schedule` frontmatter; the driver no
16
- * longer reads legacy canonical `.schedule` periodic events. On daemon start we fold any
17
- * residual `task.<channelId>.<id>.schedule.json` cron into the owning task's frontmatter
18
- * (frontmatter wins if it already has a schedule) and delete the event, so there is never
19
- * "two sources of truth" for a cadence again. Missing/archived tasks simply have their
20
- * orphaned event removed. Failures are logged and skipped — this must never block startup.
21
- */
22
- export declare function migrateLegacyTaskScheduleEvents(workspaceDir: string): Promise<void>;
23
- /**
24
- * Deterministically upgrade every active task file to the current (v3) control contract and
25
- * status vocabulary (spec 043, phase 5). Unlike the earlier marker-gated pass, this scans and
26
- * self-heals on every startup: each file is judged independently by what it actually contains
27
- * (`control.version` and the raw `status` value), not by whether a one-time marker was written.
28
- * A hand-edited or freshly-restored legacy file is repaired the next time the daemon starts, no
29
- * matter how it got there. It never dispatches a task or performs an external action, and every
30
- * file is protected by the same per-task mutation lock as normal lifecycle writes.
31
- */
32
- export declare function migrateLegacyTaskState(workspaceDir: string): Promise<void>;
33
+ export declare function convertLegacyTaskFields(legacy: LegacyFields, now?: Date): LegacyTaskConversion;
34
+ /** Migrate every task file in every known channel. Failures are logged and skipped. */
35
+ export declare function migrateTasksToV4(workspaceDir: string, stateDir: string): Promise<void>;
36
+ export {};
@@ -1,155 +1,250 @@
1
- import { mkdir, readdir, readFile, rename, stat, unlink } from "node:fs/promises";
1
+ import { existsSync } from "node:fs";
2
+ import { copyFile, mkdir, readdir, readFile, writeFile } from "node:fs/promises";
2
3
  import { join } from "node:path";
3
4
  import { getChannelDir } from "../channel/channel-paths.js";
4
5
  import * as log from "../log.js";
5
- import { formatLocalTime } from "../shared/local-time.js";
6
+ import { formatLocalTime, parseLocalTime } from "../shared/local-time.js";
6
7
  import { errorMessage } from "../shared/text-utils.js";
7
- import { createDefaultTaskControl, parseLegacyTaskControl } from "../tasks/control.js";
8
- import { appendCurrentCycleNote, parseTaskFrontmatter } from "../tasks/ledger.js";
8
+ import { isPlainObject } from "../shared/type-guards.js";
9
+ import { writeLastResult } from "../tasks/cycle.js";
10
+ import { findTaskSectionBounds, normalizeTaskId, taskBody } from "../tasks/ledger.js";
11
+ import { appendTaskLog } from "../tasks/log.js";
9
12
  import { withTaskMutation } from "../tasks/mutation-lock.js";
10
- import { readStoredTask, updateStoredTask, writeStoredTask } from "../tasks/store.js";
11
- import { parseTaskEventName, taskEventPrefix } from "../tasks/task-events.js";
12
- import { TASK_STATUSES } from "../tasks/transitions.js";
13
- import { parseScheduledEventContent } from "./events.js";
13
+ import { writeStoredTask } from "../tasks/store.js";
14
+ import { nextTaskWake } from "../tasks/task-schedule.js";
14
15
  import { discoverTaskChannels } from "./task-driver.js";
15
16
  /**
16
- * RETIRE AT v0.9.3 (code review 2026-08-30): both migrations in this file are startup self-heal
17
- * passes for on-disk state written by pre-0.9 betas (the pre-spec-029 `.schedule` event format,
18
- * and pre-spec-043 v1/v2 task control blocks and status vocabulary). Every 0.9.2-beta install is
19
- * a small, actively-developed fleet; by the 0.9.3 stable cut every install will have booted at
20
- * least once on a version that already runs these passes, so there is no longer any on-disk
21
- * state left for them to find. At 0.9.3: delete both exported functions here, their call sites
22
- * in `bootstrap.ts`, `parseLegacyTaskControl` in `../tasks/control.js` (this file's only caller),
23
- * and the paired legacy-state fold in `../memory/maintenance-state.js` (same rationale, unrelated
24
- * subsystem). Confirm first that no currently-supported version predates the pass being removed.
25
- */
26
- /**
27
- * One-time migration closing the 027 window (spec 029, D6).
17
+ * One-time, deterministic, no-LLM migration from the v3 task contract to v4 (spec 051, D14).
18
+ *
19
+ * The single most valuable thing this pass does is the `waiting` conversion. A v3 task could be
20
+ * `waiting` with no `wake` and a purely decorative `waitingFor`, which meant *nothing would ever
21
+ * resume it* — on the author's own machine two tasks had been silently dead for 9 and 13 days.
22
+ * v4 has no such state: a park needs a ticket the runtime can redeem. So a `waiting` task whose
23
+ * resumption source can still be reconstructed (a real future `wake`, or a live schedule) is
24
+ * parked on the matching ticket, and **anything else is reopened** with a note explaining why.
25
+ * Upgrading is therefore also the repair.
28
26
  *
29
- * Recurrence cadence now lives solely in a task's `schedule` frontmatter; the driver no
30
- * longer reads legacy canonical `.schedule` periodic events. On daemon start we fold any
31
- * residual `task.<channelId>.<id>.schedule.json` cron into the owning task's frontmatter
32
- * (frontmatter wins if it already has a schedule) and delete the event, so there is never
33
- * "two sources of truth" for a cadence again. Missing/archived tasks simply have their
34
- * orphaned event removed. Failures are logged and skipped — this must never block startup.
27
+ * Originals are copied to `tasks/.v3/` and never deleted. `workspace/events/` is not touched at
28
+ * all — spec 051 D8 keeps the events subsystem exactly as it is.
35
29
  */
36
- export async function migrateLegacyTaskScheduleEvents(workspaceDir) {
37
- const eventsDir = join(workspaceDir, "events");
38
- let filenames;
39
- try {
40
- filenames = (await readdir(eventsDir)).filter((name) => name.endsWith(".json"));
41
- }
42
- catch {
43
- return; // no events directory ⇒ nothing to migrate
44
- }
45
- if (filenames.length === 0)
46
- return;
47
- const channels = await discoverTaskChannels(workspaceDir);
48
- for (const filename of filenames) {
49
- const name = filename.slice(0, -".json".length);
50
- const channelId = channels.find((id) => name.startsWith(taskEventPrefix(id)));
51
- if (!channelId)
52
- continue;
53
- const parsed = parseTaskEventName(name, channelId);
54
- if (!parsed || parsed.use !== "schedule")
30
+ const MIGRATION_MARKER = "task-migration-v4.done";
31
+ /** Minimal reader for the v3 frontmatter block; the only place that still understands it. */
32
+ function parseLegacyFrontmatter(content) {
33
+ if (!content.startsWith("---"))
34
+ return undefined;
35
+ const end = content.indexOf("\n---", 3);
36
+ if (end === -1)
37
+ return undefined;
38
+ const fields = { enabled: true };
39
+ let sawLegacy = false;
40
+ for (const line of content.slice(3, end).split("\n")) {
41
+ const idx = line.indexOf(":");
42
+ if (idx === -1)
55
43
  continue;
56
- const eventPath = join(eventsDir, filename);
57
- let cron;
58
- try {
59
- const event = parseScheduledEventContent(await readFile(eventPath, "utf-8"), filename);
60
- if (event.type !== "periodic")
61
- continue; // not a cadence event; leave it for /events
62
- cron = event.schedule;
63
- }
64
- catch {
65
- continue; // unparseable ⇒ let /tasks doctor / the user handle it
66
- }
67
- try {
68
- let folded = false;
69
- const document = await updateStoredTask(getChannelDir(workspaceDir, channelId), parsed.id, (task) => {
70
- if (!task.fields.schedule) {
71
- task.fields.schedule = cron;
72
- folded = true;
44
+ const key = line.slice(0, idx).trim();
45
+ const value = line.slice(idx + 1).trim();
46
+ switch (key) {
47
+ case "status":
48
+ fields.status = value;
49
+ sawLegacy = true;
50
+ break;
51
+ case "enabled":
52
+ fields.enabled = value !== "false";
53
+ sawLegacy = true;
54
+ break;
55
+ case "wake":
56
+ fields.wake = value || undefined;
57
+ break;
58
+ case "schedule":
59
+ fields.schedule = value || undefined;
60
+ break;
61
+ case "outcome":
62
+ if (value === "completed" || value === "cancelled")
63
+ fields.outcome = value;
64
+ break;
65
+ case "closedAt":
66
+ fields.closedAt = value || undefined;
67
+ break;
68
+ case "control": {
69
+ sawLegacy = true;
70
+ try {
71
+ const parsed = JSON.parse(value);
72
+ if (isPlainObject(parsed))
73
+ fields.control = parsed;
73
74
  }
74
- });
75
- await unlink(eventPath).catch(() => { });
76
- if (folded) {
77
- log.logInfo(`Migrated legacy schedule event ${name} into tasks/${parsed.id}.md`, cron);
78
- }
79
- else {
80
- log.logInfo(`Removed legacy schedule event ${name}`, document ? "task frontmatter already owns a schedule" : "no active task");
75
+ catch {
76
+ // An unparseable control block is exactly why the task needs migrating; drop it.
77
+ }
78
+ break;
81
79
  }
80
+ default:
81
+ break;
82
82
  }
83
- catch (error) {
84
- log.logWarning(`Could not migrate legacy schedule event ${name}`, errorMessage(error));
85
- }
86
- }
87
- }
88
- function legacyStatusMigration(rawStatus, recurring) {
89
- switch (rawStatus) {
90
- case "done":
91
- return recurring ? { status: "sleeping" } : { status: "active", archiveOutcome: "completed" };
92
- case "cancelled":
93
- return { status: "active", archiveOutcome: "cancelled" };
94
- case "paused":
95
- return { status: "active", stopActor: "user" };
96
- case "escalated":
97
- return { status: "active", stopActor: "governor" };
98
- case "awaiting-user":
99
- case "blocked":
100
- return { status: "waiting" };
101
- default:
102
- return {
103
- status: rawStatus !== undefined && TASK_STATUSES.includes(rawStatus)
104
- ? rawStatus
105
- : "active",
106
- };
107
83
  }
84
+ // `state:` means this file is already v4.
85
+ if (/^state:/m.test(content.slice(3, end)))
86
+ return undefined;
87
+ return sawLegacy || fields.outcome ? fields : undefined;
108
88
  }
109
- /** Whether the control block needs a durable upgrade: absent, or not strict-v3-parseable. */
110
- function needsControlMigration(frontmatter) {
111
- return frontmatter.controlReadable === false || !frontmatter.control;
112
- }
113
- /** Whether the raw on-disk status needs a durable rewrite into the current vocabulary. */
114
- function needsStatusMigration(frontmatter) {
115
- const raw = frontmatter.rawStatus;
116
- return raw !== undefined && !TASK_STATUSES.includes(raw);
89
+ function legacyCycle(control) {
90
+ if (!control?.cycleId)
91
+ return undefined;
92
+ return {
93
+ id: control.cycleId.replace(/^cycle-/, "c-"),
94
+ startedAt: formatLocalTime(),
95
+ steps: 0,
96
+ rounds: 0,
97
+ usd: 0,
98
+ usdEstimated: false,
99
+ expired: 0,
100
+ };
117
101
  }
118
102
  /**
119
- * Reconstruct a v3 control block for a file the strict reader rejected. Returns `undefined` only
120
- * when the stored control is genuinely unparseable (neither v3, nor legacy v1/v2) — that file is
121
- * left untouched for `/tasks doctor` to report, exactly like before this migration ran.
103
+ * The v3 → v4 field mapping. Exported for the migration test, which pins the one branch that
104
+ * matters most: a `waiting` task with no wake and no schedule becomes `open`, not a dead park.
122
105
  */
123
- function resolveMigratedControl(frontmatter) {
124
- if (frontmatter.controlReadable === false) {
125
- if (!frontmatter.controlRaw)
126
- return createDefaultTaskControl();
127
- try {
128
- return parseLegacyTaskControl(frontmatter.controlRaw);
106
+ export function convertLegacyTaskFields(legacy, now = new Date()) {
107
+ const control = legacy.control;
108
+ const fields = {
109
+ state: "open",
110
+ schedule: legacy.schedule,
111
+ cycle: legacyCycle(control),
112
+ verify: control?.verification?.required ? "required" : undefined,
113
+ };
114
+ if (control?.deadline && parseLocalTime(control.deadline) !== undefined) {
115
+ fields.budget = { until: control.deadline };
116
+ }
117
+ if (legacy.outcome) {
118
+ fields.outcome = legacy.outcome;
119
+ fields.closedAt = legacy.closedAt ?? formatLocalTime(now);
120
+ fields.state = "done";
121
+ return { fields };
122
+ }
123
+ if (!legacy.enabled) {
124
+ fields.paused = {
125
+ by: control?.stop?.by === "governor" ? "runtime" : "user",
126
+ reason: control?.stop?.reason ?? "迁移前该任务已被停用。",
127
+ at: control?.stop?.at ?? formatLocalTime(now),
128
+ };
129
+ }
130
+ const wakeMs = legacy.wake ? parseLocalTime(legacy.wake) : undefined;
131
+ const futureWake = wakeMs !== undefined && wakeMs > now.getTime();
132
+ if (legacy.status === "sleeping" && legacy.schedule && nextTaskWake(legacy.schedule, now)) {
133
+ const by = nextTaskWake(legacy.schedule, now);
134
+ const second = by ? nextTaskWake(legacy.schedule, by) : undefined;
135
+ fields.state = "parked";
136
+ fields.ticket = { kind: "schedule", at: formatLocalTime(by ?? now), by: formatLocalTime(second ?? by ?? now) };
137
+ return { fields };
138
+ }
139
+ if (legacy.status === "waiting" && futureWake && legacy.wake) {
140
+ const at = formatLocalTime(new Date(wakeMs));
141
+ fields.state = "parked";
142
+ fields.ticket = { kind: "time", at, by: at };
143
+ return { fields };
144
+ }
145
+ if (legacy.status === "waiting") {
146
+ return {
147
+ fields,
148
+ repairNote: "迁移提示:该任务此前处于 waiting,但没有任何可兑现的恢复来源(无有效 wake、无在跑的委派或作业)。" +
149
+ "已改为 open。先确认真实状态,再决定继续推进还是重新用 task_step_end 停泊到一张明确的等待票上。" +
150
+ (control?.nextAction ? `迁移前记录的下一步:${control.nextAction}` : ""),
151
+ };
152
+ }
153
+ return { fields };
154
+ }
155
+ /** Move the v3 `## History` entries into the loop log so nothing is lost when the section goes. */
156
+ async function importLegacyHistory(channelDir, id, body, cycleId) {
157
+ const lines = body.split("\n");
158
+ const bounds = findTaskSectionBounds(lines, ["History", "历史"]);
159
+ if (!bounds)
160
+ return 0;
161
+ const entries = [];
162
+ let current = [];
163
+ for (let index = bounds.headingIndex + 1; index < bounds.end; index++) {
164
+ const line = lines[index] ?? "";
165
+ if (/^#{3,6}\s+/.test(line)) {
166
+ if (current.length > 0)
167
+ entries.push(current.join("\n").trim());
168
+ current = [line];
169
+ continue;
129
170
  }
130
- catch {
131
- return undefined;
171
+ current.push(line);
172
+ }
173
+ if (current.length > 0)
174
+ entries.push(current.join("\n").trim());
175
+ const kept = entries.filter(Boolean);
176
+ for (const [index, entry] of kept.entries()) {
177
+ await appendTaskLog(channelDir, id, {
178
+ cycle: cycleId,
179
+ kind: "step",
180
+ seq: index + 1,
181
+ outcome: "continue",
182
+ note: entry,
183
+ tools: [],
184
+ });
185
+ }
186
+ return kept.length;
187
+ }
188
+ /** Strip `## Current Cycle` and `## History` from a v3 body, returning the last cycle note. */
189
+ function stripLegacySections(body) {
190
+ let working = body;
191
+ let lastNote;
192
+ for (const names of [
193
+ ["Current Cycle", "当前周期"],
194
+ ["History", "历史"],
195
+ ]) {
196
+ const lines = working.split("\n");
197
+ const bounds = findTaskSectionBounds(lines, names);
198
+ if (!bounds)
199
+ continue;
200
+ if (names[0] === "Current Cycle") {
201
+ const text = lines
202
+ .slice(bounds.headingIndex + 1, bounds.end)
203
+ .join("\n")
204
+ .trim();
205
+ if (text)
206
+ lastNote = text;
132
207
  }
208
+ lines.splice(bounds.headingIndex, bounds.end - bounds.headingIndex);
209
+ working = lines.join("\n");
133
210
  }
134
- return createDefaultTaskControl();
211
+ return { body: working.replace(/\n{3,}/g, "\n\n").trimEnd(), lastNote };
135
212
  }
136
- /**
137
- * Deterministically upgrade every active task file to the current (v3) control contract and
138
- * status vocabulary (spec 043, phase 5). Unlike the earlier marker-gated pass, this scans and
139
- * self-heals on every startup: each file is judged independently by what it actually contains
140
- * (`control.version` and the raw `status` value), not by whether a one-time marker was written.
141
- * A hand-edited or freshly-restored legacy file is repaired the next time the daemon starts, no
142
- * matter how it got there. It never dispatches a task or performs an external action, and every
143
- * file is protected by the same per-task mutation lock as normal lifecycle writes.
144
- */
145
- export async function migrateLegacyTaskState(workspaceDir) {
146
- const channels = await discoverTaskChannels(workspaceDir);
147
- for (const channelId of channels) {
213
+ async function migrateOneTask(channelDir, id, now) {
214
+ return withTaskMutation(channelDir, id, async () => {
215
+ const path = join(channelDir, "tasks", `${id}.md`);
216
+ const content = await readFile(path, "utf-8");
217
+ const legacy = parseLegacyFrontmatter(content);
218
+ if (!legacy)
219
+ return false;
220
+ const backupDir = join(channelDir, "tasks", ".v3");
221
+ await mkdir(backupDir, { recursive: true });
222
+ await copyFile(path, join(backupDir, `${id}.md`));
223
+ const { fields, repairNote } = convertLegacyTaskFields(legacy, now);
224
+ const original = taskBody(content);
225
+ const stripped = stripLegacySections(original);
226
+ const imported = await importLegacyHistory(channelDir, id, original, fields.cycle?.id ?? "c-legacy");
227
+ let body = stripped.body;
228
+ const lastResult = [repairNote, stripped.lastNote].filter(Boolean).join("\n\n");
229
+ if (lastResult)
230
+ body = writeLastResult(body, lastResult);
231
+ await writeStoredTask({ id, path, fields, body });
232
+ log.logInfo(`Task ${id} migrated to v4`, `state=${fields.state}${fields.ticket ? ` ticket=${fields.ticket.kind}` : ""} history=${imported}`);
233
+ return true;
234
+ });
235
+ }
236
+ /** Migrate every task file in every known channel. Failures are logged and skipped. */
237
+ export async function migrateTasksToV4(workspaceDir, stateDir) {
238
+ const markerPath = join(stateDir, MIGRATION_MARKER);
239
+ if (existsSync(markerPath))
240
+ return;
241
+ const now = new Date();
242
+ let migrated = 0;
243
+ for (const channelId of await discoverTaskChannels(workspaceDir)) {
148
244
  const channelDir = getChannelDir(workspaceDir, channelId);
149
- const dir = join(channelDir, "tasks");
150
245
  let filenames;
151
246
  try {
152
- filenames = (await readdir(dir)).filter((name) => name.endsWith(".md")).sort();
247
+ filenames = (await readdir(join(channelDir, "tasks"))).filter((name) => name.endsWith(".md"));
153
248
  }
154
249
  catch {
155
250
  continue;
@@ -157,65 +252,16 @@ export async function migrateLegacyTaskState(workspaceDir) {
157
252
  for (const filename of filenames) {
158
253
  const id = filename.slice(0, -".md".length);
159
254
  try {
160
- await withTaskMutation(channelDir, id, async () => {
161
- const activePath = join(dir, filename);
162
- const raw = await readFile(activePath, "utf-8");
163
- const frontmatter = parseTaskFrontmatter(raw);
164
- if (!frontmatter.readable)
165
- return;
166
- const controlNeedsMigration = needsControlMigration(frontmatter);
167
- if (!controlNeedsMigration && !needsStatusMigration(frontmatter))
168
- return; // already v3
169
- let migratedControl = frontmatter.control;
170
- if (controlNeedsMigration) {
171
- migratedControl = resolveMigratedControl(frontmatter);
172
- if (!migratedControl)
173
- return; // genuinely corrupt; leave for doctor
174
- }
175
- const document = await readStoredTask(channelDir, id, false, true);
176
- if (!document)
177
- return;
178
- document.fields.control = migratedControl;
179
- const legacy = legacyStatusMigration(frontmatter.rawStatus, Boolean(frontmatter.schedule));
180
- document.fields.status = legacy.status;
181
- if (legacy.archiveOutcome)
182
- document.fields.outcome = legacy.archiveOutcome;
183
- if (legacy.stopActor) {
184
- document.fields.enabled = false;
185
- if (document.fields.control && !document.fields.control.stop) {
186
- document.fields.control.stop = {
187
- by: legacy.stopActor,
188
- reason: `Task stopped by ${legacy.stopActor}.`,
189
- at: formatLocalTime(),
190
- };
191
- }
192
- }
193
- // Very old hand-written tasks may have parked without ever recording a wake. Give the
194
- // waiting state an explicit note before any active driver wake can act on it silently.
195
- if (legacy.status === "waiting" &&
196
- !document.fields.wake &&
197
- document.fields.control &&
198
- !document.fields.control.waitingFor) {
199
- document.fields.control.waitingFor = "external-signal";
200
- document.body = appendCurrentCycleNote(document.body, "Migration note: this task remains waiting after the autonomy state upgrade; review its external condition before resuming.");
201
- }
202
- if (document.fields.outcome) {
203
- const fileStat = await stat(activePath);
204
- document.fields.closedAt ??= formatLocalTime(new Date(fileStat.mtimeMs));
205
- await writeStoredTask(document);
206
- const archiveDir = join(dir, "archive");
207
- await mkdir(archiveDir, { recursive: true });
208
- await rename(activePath, join(archiveDir, filename));
209
- log.logInfo(`Migrated legacy terminal task ${id} to archive`, document.fields.outcome);
210
- return;
211
- }
212
- await writeStoredTask(document);
213
- log.logInfo(`Migrated task ${id} to TaskControl v3`, channelId);
214
- });
255
+ if (await migrateOneTask(channelDir, normalizeTaskId(id), now))
256
+ migrated++;
215
257
  }
216
258
  catch (error) {
217
- log.logWarning(`Could not migrate task ${channelId}/${id}`, `${errorMessage(error)}. Use /tasks doctor to repair it.`);
259
+ log.logWarning(`Task ${id} could not be migrated to v4`, errorMessage(error));
218
260
  }
219
261
  }
220
262
  }
263
+ await mkdir(stateDir, { recursive: true });
264
+ await writeFile(markerPath, `${formatLocalTime(now)}\n`, "utf-8");
265
+ if (migrated > 0)
266
+ log.logInfo("Task migration to v4 complete", `${migrated} task(s)`);
221
267
  }
@@ -8,7 +8,6 @@ import { type JobSnapshot } from "../agent/job-manager.js";
8
8
  import type { ChannelEvent } from "../channel/channel-event.js";
9
9
  import type { Executor } from "../executor.js";
10
10
  import { type RunRecord } from "../subagents/runs.js";
11
- import { type WakeTaskTransitionHooks } from "../tasks/store.js";
12
11
  /**
13
12
  * Whether a `[JOB:<jobId>] ... belongs to task <taskId>.` wake actually names a job that: exists
14
13
  * on this channel, has actually finished (a still-`running` job cannot have produced this wake —
@@ -34,12 +33,16 @@ export declare function isTrustedInternalWake(event: ChannelEvent, kind: "job" |
34
33
  export interface ClaimedDelegationWake {
35
34
  taskId: string;
36
35
  activated: boolean;
37
- /** True when it is safe to drop this wake without a turn even though it did not activate the
38
- * task itself — see `isTaskActivelyDriven`. Always true when `activated` is true. */
36
+ /** True when it is safe to drop this wake without a turn even though it did not redeem a
37
+ * ticket itself — see `isTaskActivelyDriven`. Always true when `activated` is true. */
39
38
  taskStillDriven: boolean;
40
39
  finish(): Promise<void>;
41
40
  rollback(): Promise<void>;
42
41
  }
42
+ /** Test-only fault seam, kept for the restart/interrupt cases that exercise a failed write. */
43
+ export interface WakeTaskTransitionHooks {
44
+ beforeActivation?: () => void;
45
+ }
43
46
  /** Claim and activate a producer-created delegation wake without consuming it yet. Keeping the
44
47
  * final marker separate lets transports such as TUI mark it consumed only after they have accepted
45
48
  * the corresponding turn; a rejected submit remains replayable in the same or next process. */
@@ -7,21 +7,18 @@
7
7
  import { getChannelJobManager } from "../agent/job-manager.js";
8
8
  import { getChannelDir } from "../channel/channel-paths.js";
9
9
  import { getSubAgentRunManager } from "../subagents/runs.js";
10
- import { activateWaitingTask, readStoredTask, rollbackWaitingTask, } from "../tasks/store.js";
11
- import { normalizeStoredStatus } from "../tasks/transitions.js";
10
+ import { parkTask, readStoredTask, redeemTicket } from "../tasks/store.js";
12
11
  /**
13
- * True when `taskId` is currently `active` and enabled — i.e. the task driver already owns
14
- * advancing it. A completion wake that could not activate the task (because it was not
15
- * `waiting`) is safe to drop without spending an agent turn only in this case: some other wake in
16
- * the same fan-out already activated it, and the driver will pick up the result. Every other case
17
- * — `done`, archived, disabled, or the task missing entirely — has nobody left to look at the
18
- * wake's result if it is dropped here, so the caller must still route it to a normal turn.
12
+ * True when `taskId` is already `open` and not paused — i.e. the driver already owns advancing
13
+ * it. A completion wake that could not redeem a ticket (because the task was not parked on one)
14
+ * is safe to drop without spending an agent turn only in this case: some other wake in the same
15
+ * fan-out already reopened it, and the driver will pick up the result. Every other case — done,
16
+ * archived, paused, or the task missing entirely — has nobody left to look at the wake's result
17
+ * if it is dropped here, so the caller must still route it to a normal turn.
19
18
  */
20
19
  async function isTaskActivelyDriven(channelDir, taskId) {
21
- const document = await readStoredTask(channelDir, taskId, false, true).catch(() => undefined);
22
- return (document !== undefined &&
23
- normalizeStoredStatus(document.fields.status) === "active" &&
24
- document.fields.enabled !== false);
20
+ const document = await readStoredTask(channelDir, taskId).catch(() => undefined);
21
+ return document !== undefined && document.fields.state === "open" && !document.fields.paused;
25
22
  }
26
23
  /**
27
24
  * Whether a `[JOB:<jobId>] ... belongs to task <taskId>.` wake actually names a job that: exists
@@ -70,16 +67,25 @@ export async function claimVerifiedDelegationWake(event, workspaceDir, hooks) {
70
67
  return undefined;
71
68
  }
72
69
  const channelDir = getChannelDir(workspaceDir, event.channelId);
73
- const activated = await activateWaitingTask(channelDir, wake.taskId, hooks);
74
- const taskStillDriven = activated !== undefined || (await isTaskActivelyDriven(channelDir, wake.taskId));
70
+ hooks?.beforeActivation?.();
71
+ // Only a `run` ticket naming this very run may be redeemed: a task parked on something else
72
+ // (a job, a question to the user) is not waiting for this delegation, and reopening it here
73
+ // would be exactly the unverified resumption path spec 051 D2 exists to remove.
74
+ const redeemed = await redeemTicket(channelDir, wake.taskId, (ticket) => ticket.kind === "run" && ticket.id === wake.resourceId);
75
+ const taskStillDriven = redeemed !== undefined || (await isTaskActivelyDriven(channelDir, wake.taskId));
75
76
  return {
76
77
  taskId: wake.taskId,
77
- activated: activated !== undefined,
78
+ activated: redeemed !== undefined,
78
79
  taskStillDriven,
79
80
  finish: async () => {
80
81
  await runManager.finishWakeConsumption(wake.resourceId, event.dispatchId);
81
82
  },
82
- rollback: () => rollbackWaitingTask(channelDir, wake.taskId, "external-signal"),
83
+ // Re-park on the same ticket when the transport could not accept the turn, so a rejected
84
+ // submit leaves the task exactly as it was rather than silently `open` with no step queued.
85
+ rollback: async () => {
86
+ if (redeemed)
87
+ await parkTask(channelDir, wake.taskId, redeemed.ticket);
88
+ },
83
89
  };
84
90
  }
85
91
  /** Same shape as `claimVerifiedDelegationWake`, for a `[JOB:<jobId>] ... belongs to task
@@ -97,11 +103,12 @@ export async function claimVerifiedJobWake(event, workspaceDir, executor, hooks)
97
103
  return undefined;
98
104
  }
99
105
  const channelDir = getChannelDir(workspaceDir, event.channelId);
100
- const activated = await activateWaitingTask(channelDir, wake.taskId, hooks);
101
- const taskStillDriven = activated !== undefined || (await isTaskActivelyDriven(channelDir, wake.taskId));
106
+ hooks?.beforeActivation?.();
107
+ const redeemed = await redeemTicket(channelDir, wake.taskId, (ticket) => ticket.kind === "job" && ticket.id === wake.resourceId);
108
+ const taskStillDriven = redeemed !== undefined || (await isTaskActivelyDriven(channelDir, wake.taskId));
102
109
  return {
103
110
  taskId: wake.taskId,
104
- activated: activated !== undefined,
111
+ activated: redeemed !== undefined,
105
112
  taskStillDriven,
106
113
  finish: async () => {
107
114
  await jobManager.finishWakeConsumption(wake.resourceId, event.dispatchId);