@oyasmi/pipiclaw 0.9.3-beta.5 → 0.9.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (144) hide show
  1. package/README.en.md +1 -1
  2. package/README.md +1 -1
  3. package/dist/agent/channel-runner.d.ts +4 -8
  4. package/dist/agent/channel-runner.js +14 -34
  5. package/dist/agent/job-manager.d.ts +12 -0
  6. package/dist/agent/job-manager.js +42 -1
  7. package/dist/agent/prompt/sections.js +2 -2
  8. package/dist/agent/runner-factory.d.ts +2 -2
  9. package/dist/agent/types.d.ts +11 -7
  10. package/dist/channel/channel-index.d.ts +9 -2
  11. package/dist/channel/channel-index.js +25 -6
  12. package/dist/channel/project-scope-store.d.ts +20 -0
  13. package/dist/channel/project-scope-store.js +22 -7
  14. package/dist/commands/catalog.js +6 -12
  15. package/dist/events/event-commands.js +2 -2
  16. package/dist/events/events.d.ts +51 -30
  17. package/dist/events/events.js +70 -98
  18. package/dist/memory/journal.d.ts +2 -3
  19. package/dist/memory/journal.js +2 -3
  20. package/dist/memory/maintenance-tuning.d.ts +0 -1
  21. package/dist/memory/maintenance-tuning.js +0 -1
  22. package/dist/memory/scheduler.js +8 -16
  23. package/dist/memory/search.js +2 -3
  24. package/dist/memory/session-search.js +3 -9
  25. package/dist/memory/store.d.ts +1 -1
  26. package/dist/memory/store.js +9 -1
  27. package/dist/memory/task-digest.js +10 -11
  28. package/dist/memory/tombstones.js +2 -4
  29. package/dist/models/provider-login.d.ts +1 -1
  30. package/dist/models/provider-login.js +1 -1
  31. package/dist/playbooks/agent-delegation.md +6 -6
  32. package/dist/playbooks/background-jobs.md +1 -1
  33. package/dist/playbooks/event-scheduling.md +22 -13
  34. package/dist/playbooks/memory-and-learning.md +2 -2
  35. package/dist/playbooks/outbound-media.md +1 -1
  36. package/dist/playbooks/runtime-orientation.md +3 -3
  37. package/dist/playbooks/task-lead.md +82 -0
  38. package/dist/runtime/bootstrap.js +94 -187
  39. package/dist/runtime/durable-dispatch.js +30 -3
  40. package/dist/runtime/report-commands.d.ts +30 -0
  41. package/dist/runtime/report-commands.js +71 -0
  42. package/dist/runtime/subagent-commands.js +1 -1
  43. package/dist/runtime/task-commands.d.ts +0 -8
  44. package/dist/runtime/task-commands.js +48 -85
  45. package/dist/runtime/task-driver.d.ts +15 -10
  46. package/dist/runtime/task-driver.js +36 -41
  47. package/dist/runtime/task-migration.d.ts +23 -29
  48. package/dist/runtime/task-migration.js +364 -183
  49. package/dist/runtime/task-spawn.d.ts +24 -0
  50. package/dist/runtime/task-spawn.js +49 -0
  51. package/dist/runtime/task-wake.d.ts +33 -46
  52. package/dist/runtime/task-wake.js +15 -90
  53. package/dist/security/network.js +44 -9
  54. package/dist/settings.d.ts +1 -8
  55. package/dist/settings.js +1 -8
  56. package/dist/subagents/discovery.js +3 -15
  57. package/dist/subagents/external/run.d.ts +3 -1
  58. package/dist/subagents/external/run.js +2 -20
  59. package/dist/subagents/external/settlement.d.ts +4 -16
  60. package/dist/subagents/external/settlement.js +16 -67
  61. package/dist/subagents/runs.d.ts +15 -29
  62. package/dist/subagents/runs.js +70 -158
  63. package/dist/subagents/tool.d.ts +20 -4
  64. package/dist/subagents/tool.js +63 -87
  65. package/dist/subagents/verification-outcome.d.ts +13 -19
  66. package/dist/subagents/verification-outcome.js +8 -22
  67. package/dist/subagents/workspace-summary.d.ts +8 -0
  68. package/dist/subagents/workspace-summary.js +29 -0
  69. package/dist/tasks/board.d.ts +43 -0
  70. package/dist/tasks/board.js +134 -0
  71. package/dist/tasks/brief.d.ts +10 -5
  72. package/dist/tasks/brief.js +78 -26
  73. package/dist/tasks/budget.d.ts +13 -14
  74. package/dist/tasks/budget.js +21 -40
  75. package/dist/tasks/contract-input.d.ts +19 -0
  76. package/dist/tasks/contract-input.js +55 -0
  77. package/dist/tasks/create.d.ts +17 -0
  78. package/dist/tasks/create.js +36 -0
  79. package/dist/tasks/frontmatter.d.ts +20 -27
  80. package/dist/tasks/frontmatter.js +18 -31
  81. package/dist/tasks/ledger.d.ts +61 -117
  82. package/dist/tasks/ledger.js +78 -223
  83. package/dist/tasks/log.d.ts +62 -35
  84. package/dist/tasks/log.js +51 -29
  85. package/dist/tasks/session-path.d.ts +3 -3
  86. package/dist/tasks/session-path.js +4 -5
  87. package/dist/tasks/store.d.ts +27 -28
  88. package/dist/tasks/store.js +89 -83
  89. package/dist/tasks/ticket.d.ts +33 -66
  90. package/dist/tasks/ticket.js +31 -120
  91. package/dist/tasks/work-log.d.ts +20 -0
  92. package/dist/tasks/work-log.js +42 -0
  93. package/dist/tools/bash.d.ts +1 -1
  94. package/dist/tools/bash.js +1 -1
  95. package/dist/tools/event-manage.d.ts +16 -2
  96. package/dist/tools/event-manage.js +30 -12
  97. package/dist/tools/index.d.ts +5 -3
  98. package/dist/tools/index.js +5 -5
  99. package/dist/tools/registry.d.ts +6 -4
  100. package/dist/tools/registry.js +1 -4
  101. package/dist/tools/subagent-manage.js +4 -2
  102. package/dist/tools/task-manage/create.js +11 -27
  103. package/dist/tools/task-manage/lifecycle.d.ts +6 -7
  104. package/dist/tools/task-manage/lifecycle.js +23 -106
  105. package/dist/tools/task-manage/log-view.d.ts +3 -2
  106. package/dist/tools/task-manage/log-view.js +6 -6
  107. package/dist/tools/task-manage/schema.d.ts +10 -30
  108. package/dist/tools/task-manage/schema.js +33 -49
  109. package/dist/tools/task-manage/shared.d.ts +35 -42
  110. package/dist/tools/task-manage/shared.js +53 -192
  111. package/dist/tools/task-manage/step-end.d.ts +6 -6
  112. package/dist/tools/task-manage/step-end.js +61 -98
  113. package/dist/tools/task-manage/types.d.ts +8 -9
  114. package/dist/tools/task-manage.js +5 -5
  115. package/dist/tui/app.js +11 -38
  116. package/dist/tui/commands.d.ts +18 -8
  117. package/dist/tui/commands.js +2 -9
  118. package/dist/tui/turn-controller.d.ts +2 -14
  119. package/dist/tui/turn-controller.js +1 -17
  120. package/dist/web/client.js +9 -1
  121. package/examples/sub-agents/README.md +7 -4
  122. package/examples/sub-agents/agents/codex-flash.md +2 -2
  123. package/examples/sub-agents/agents/codex-high.md +1 -1
  124. package/examples/sub-agents/agents/codex-main.md +1 -1
  125. package/examples/sub-agents/agents/codex-review.md +23 -0
  126. package/examples/sub-agents/roles/verifier.md +1 -1
  127. package/package.json +1 -1
  128. package/dist/memory/maintenance-migration.d.ts +0 -5
  129. package/dist/memory/maintenance-migration.js +0 -91
  130. package/dist/memory/migrate.d.ts +0 -15
  131. package/dist/memory/migrate.js +0 -364
  132. package/dist/playbooks/task-loop.md +0 -90
  133. package/dist/tasks/artifact-subject.d.ts +0 -40
  134. package/dist/tasks/artifact-subject.js +0 -334
  135. package/dist/tasks/cycle.d.ts +0 -48
  136. package/dist/tasks/cycle.js +0 -94
  137. package/dist/tasks/rounds.d.ts +0 -41
  138. package/dist/tasks/rounds.js +0 -53
  139. package/dist/tasks/task-events.d.ts +0 -6
  140. package/dist/tasks/task-events.js +0 -14
  141. package/dist/tasks/task-schedule.d.ts +0 -18
  142. package/dist/tasks/task-schedule.js +0 -50
  143. package/dist/tasks/verification.d.ts +0 -114
  144. package/dist/tasks/verification.js +0 -226
@@ -1,42 +1,71 @@
1
- import { existsSync } from "node:fs";
2
- import { copyFile, mkdir, readdir, readFile, writeFile } from "node:fs/promises";
1
+ import { constants, existsSync } from "node:fs";
2
+ import { copyFile, mkdir, readdir, readFile, rm, writeFile } from "node:fs/promises";
3
3
  import { join } from "node:path";
4
4
  import { getChannelDir } from "../channel/channel-paths.js";
5
5
  import * as log from "../log.js";
6
- import { formatLocalTime, parseLocalTime } from "../shared/local-time.js";
6
+ import { writeFileAtomically } from "../shared/atomic-file.js";
7
+ import { formatLocalTime } from "../shared/local-time.js";
7
8
  import { errorMessage } from "../shared/text-utils.js";
8
9
  import { isPlainObject } from "../shared/type-guards.js";
9
- import { writeLastResult } from "../tasks/cycle.js";
10
- import { findTaskSectionBounds, normalizeTaskId, taskBody } from "../tasks/ledger.js";
10
+ import { createUsage } from "../tasks/budget.js";
11
+ import { validateTaskContractInput } from "../tasks/contract-input.js";
12
+ import { extractTaskTitle, findTaskSectionBounds, normalizeTaskId, parseTaskItems, taskBody } from "../tasks/ledger.js";
11
13
  import { appendTaskLog } from "../tasks/log.js";
12
14
  import { withTaskMutation } from "../tasks/mutation-lock.js";
13
- import { writeStoredTask } from "../tasks/store.js";
14
- import { nextTaskWake } from "../tasks/task-schedule.js";
15
+ import { ArchiveUndoError, archiveTask, readStoredTask, writeStoredTask } from "../tasks/store.js";
15
16
  import { discoverTaskChannels } from "./task-driver.js";
16
17
  /**
17
- * One-time, deterministic, no-LLM migration from the v3 task contract to v4 (spec 051, D14).
18
+ * One-time, deterministic, no-LLM conversion of v3 task files (0.9.2: `status` / `enabled` /
19
+ * `wake` / `schedule` / `control` frontmatter) to v5 (spec 052). It ships with the release that
20
+ * introduces v5 and is deleted in the next minor release.
18
21
  *
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.
22
+ * - **Recurring tasks become event templates.** A v3 task with a `schedule` is, from v5's point of
23
+ * view, an event that spawns an instance per occurrence. The converter writes that event, then
24
+ * retires the task if it was only sleeping until its next occurrence, or lets the occurrence in
25
+ * flight finish as an instance of the event.
26
+ * - **Nothing is parked.** v3 waits (`wake`, `waitingFor`) have no v5 equivalent; the task is
27
+ * reopened, and `enabled: false` / `control.stop` become a pause, so a disabled task never
28
+ * starts running as an instance because of the upgrade. Generated recurring events have no
29
+ * disabled flag: review/isolate them before enabling production scheduling.
26
30
  *
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.
31
+ * v4 beta files are NOT supported: any `state:` line skips conversion, even alongside
32
+ * `status:`. Preserve/isolate v4 originals and rebuild through v5 tools before enabling
33
+ * the daemon (docs/events-and-tasks.md).
34
+ *
35
+ * Failure handling: a task whose conversion throws is rolled back (original restored, template
36
+ * event and archive copy removed). If any task or event move failed, the marker is NOT written, a
37
+ * `task-migration-v5.failed.json` report is left in the state dir, and this function throws so
38
+ * bootstrap does not start services. A report that records a failed rollback keeps blocking every
39
+ * later start until the operator resolves it and deletes the report.
40
+ *
41
+ * Originals are copied to `tasks/.v3/` and never deleted or overwritten (a differing existing
42
+ * backup is kept and the new copy gets a numeric suffix). Any file carrying `state:` frontmatter,
43
+ * including unsupported v4 files, is left alone.
29
44
  */
30
- const MIGRATION_MARKER = "task-migration-v4.done";
45
+ const MIGRATION_MARKER = "task-migration-v5.done";
46
+ const FAILURE_REPORT = "task-migration-v5.failed.json";
47
+ const DEFAULT_STOP_REASON = "v3 中已停用。";
48
+ const BACKUP_DIRNAME = ".v3";
49
+ const ITEMS_NAMES = ["Plan", "计划"];
50
+ /** v3 per-cycle bookkeeping; v5 keeps this in the loop log instead of the contract. */
51
+ const CYCLE_SECTION_NAMES = ["Current Cycle", "当前周期", "History", "历史"];
52
+ function parseJson(value) {
53
+ try {
54
+ const parsed = JSON.parse(value);
55
+ return isPlainObject(parsed) ? parsed : undefined;
56
+ }
57
+ catch {
58
+ return undefined;
59
+ }
60
+ }
31
61
  /** Minimal reader for the v3 frontmatter block; the only place that still understands it. */
32
- function parseLegacyFrontmatter(content) {
62
+ export function parseV3Frontmatter(content) {
33
63
  if (!content.startsWith("---"))
34
64
  return undefined;
35
65
  const end = content.indexOf("\n---", 3);
36
66
  if (end === -1)
37
67
  return undefined;
38
- const fields = { enabled: true };
39
- let sawLegacy = false;
68
+ const fields = { v5: false, stopped: false };
40
69
  for (const line of content.slice(3, end).split("\n")) {
41
70
  const idx = line.indexOf(":");
42
71
  if (idx === -1)
@@ -44,36 +73,24 @@ function parseLegacyFrontmatter(content) {
44
73
  const key = line.slice(0, idx).trim();
45
74
  const value = line.slice(idx + 1).trim();
46
75
  switch (key) {
76
+ case "state":
77
+ fields.v5 = true;
78
+ break;
47
79
  case "status":
48
80
  fields.status = value;
49
- sawLegacy = true;
50
81
  break;
51
82
  case "enabled":
52
83
  fields.enabled = value !== "false";
53
- sawLegacy = true;
54
- break;
55
- case "wake":
56
- fields.wake = value || undefined;
57
84
  break;
58
85
  case "schedule":
59
86
  fields.schedule = value || undefined;
60
87
  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
88
  case "control": {
69
- sawLegacy = true;
70
- try {
71
- const parsed = JSON.parse(value);
72
- if (isPlainObject(parsed))
73
- fields.control = parsed;
74
- }
75
- catch {
76
- // An unparseable control block is exactly why the task needs migrating; drop it.
89
+ const stop = parseJson(value)?.stop;
90
+ if (isPlainObject(stop)) {
91
+ fields.stopped = true;
92
+ if (typeof stop.reason === "string" && stop.reason.trim())
93
+ fields.stopReason = stop.reason.trim();
77
94
  }
78
95
  break;
79
96
  }
@@ -81,187 +98,351 @@ function parseLegacyFrontmatter(content) {
81
98
  break;
82
99
  }
83
100
  }
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;
101
+ return fields;
88
102
  }
89
- function legacyCycle(control) {
90
- if (!control?.cycleId)
103
+ function sectionText(body, names) {
104
+ const lines = body.split("\n");
105
+ const bounds = findTaskSectionBounds(lines, names);
106
+ if (!bounds)
91
107
  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
- };
108
+ const text = lines
109
+ .slice(bounds.headingIndex + 1, bounds.end)
110
+ .join("\n")
111
+ .trim();
112
+ return text || undefined;
113
+ }
114
+ /** Rename `## Plan` to `## Work Items` and drop the per-cycle sections, the two body changes v5 makes. */
115
+ export function convertBody(body) {
116
+ const lines = body.split("\n");
117
+ const items = findTaskSectionBounds(lines, ITEMS_NAMES);
118
+ if (items)
119
+ lines[items.headingIndex] = "## Work Items";
120
+ for (const names of [CYCLE_SECTION_NAMES.slice(0, 2), CYCLE_SECTION_NAMES.slice(2)]) {
121
+ const bounds = findTaskSectionBounds(lines, names);
122
+ if (bounds)
123
+ lines.splice(bounds.headingIndex, bounds.end - bounds.headingIndex);
124
+ }
125
+ return lines
126
+ .join("\n")
127
+ .replace(/\n{3,}/g, "\n\n")
128
+ .trimEnd();
101
129
  }
102
130
  /**
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.
131
+ * Build the event template a recurring v3 task becomes. The original Manual and Verification text
132
+ * is carried into the Goal (v5 has no such sections, and a recurring job's accumulated rules are
133
+ * exactly what the template exists to keep), and every checkbox is reset.
105
134
  */
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,
135
+ export function buildTemplate(id, body) {
136
+ const title = extractTaskTitle(`---\n---\n${body}`, id);
137
+ const goal = sectionText(body, ["Goal", "目标"]) ?? title;
138
+ const manual = sectionText(body, ["Manual", "手册"]);
139
+ const verification = sectionText(body, ["Verification", "验收"])
140
+ ?.split("\n")
141
+ .filter((line) => !/^Independent verification:/i.test(line.trim()))
142
+ .join("\n")
143
+ .trim();
144
+ const dod = (sectionText(body, ["DoD"]) ?? "")
145
+ .split("\n")
146
+ .map((line) => line.replace(/^(\s*[-*]\s+)\[[xX]\]/, "$1[ ]"))
147
+ .join("\n")
148
+ .trim();
149
+ const items = parseTaskItems(convertBody(body))?.items.map((item) => ({ text: item.text })) ?? [];
150
+ const template = {
151
+ title,
152
+ goal: [
153
+ goal,
154
+ manual ? `原手册(每次执行都适用):\n${manual}` : undefined,
155
+ verification ? `原检查要求:\n${verification}` : undefined,
156
+ ]
157
+ .filter(Boolean)
158
+ .join("\n\n"),
159
+ dod: dod || "- [ ] 完成上述目标",
160
+ ...(items.length > 0 ? { items } : {}),
113
161
  };
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 };
162
+ try {
163
+ validateTaskContractInput(template);
164
+ return { template };
122
165
  }
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
- };
166
+ catch (error) {
167
+ return { reason: errorMessage(error) };
129
168
  }
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 };
169
+ }
170
+ /** Write the event template for a recurring task; returns the event name, or why it could not be expressed. */
171
+ async function writeTemplateEvent(workspaceDir, channelId, id, body, schedule) {
172
+ const { template, reason } = buildTemplate(id, body);
173
+ if (!template)
174
+ return { reason };
175
+ const eventsDir = join(workspaceDir, "events");
176
+ await mkdir(eventsDir, { recursive: true });
177
+ let name = id;
178
+ if (existsSync(join(eventsDir, `${name}.json`)))
179
+ name = `${id}-task`;
180
+ if (existsSync(join(eventsDir, `${name}.json`)))
181
+ return { reason: `event ${name} already exists` };
182
+ const event = { type: "periodic", channelId, schedule, task: template };
183
+ await writeFileAtomically(join(eventsDir, `${name}.json`), `${JSON.stringify(event, null, 2)}\n`);
184
+ return { name };
185
+ }
186
+ /** `rm` that also treats "a parent is not a directory" as already gone. */
187
+ async function removeIfPresent(path) {
188
+ try {
189
+ await rm(path, { force: true });
138
190
  }
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 };
191
+ catch (error) {
192
+ if (error.code !== "ENOTDIR")
193
+ throw error;
144
194
  }
145
- if (legacy.status === "waiting") {
146
- return {
147
- fields,
148
- repairNote: "迁移提示:该任务此前处于 waiting,但没有任何可兑现的恢复来源(无有效 wake、无在跑的委派或作业)。" +
149
- "已改为 open。先确认真实状态,再决定继续推进还是重新用 task_step_end 停泊到一张明确的等待票上。" +
150
- (control?.nextAction ? `迁移前记录的下一步:${control.nextAction}` : ""),
151
- };
195
+ }
196
+ class TaskConversionError extends Error {
197
+ constructor(stage, cause, rollback) {
198
+ super(`${stage}: ${errorMessage(cause)} (rollback: ${rollback})`);
199
+ this.stage = stage;
200
+ this.cause = cause;
201
+ this.rollback = rollback;
152
202
  }
153
- return { fields };
154
203
  }
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;
204
+ /**
205
+ * Copy `path` into `dir` as `<stem><ext>` without ever overwriting an existing file: an identical
206
+ * one counts as already backed up, a differing one is kept and this copy gets `<stem>.backup-<n><ext>`.
207
+ */
208
+ async function copyWithoutOverwrite(dir, stem, ext, path, content) {
209
+ await mkdir(dir, { recursive: true });
210
+ for (let n = 0;; n++) {
211
+ const target = join(dir, n === 0 ? `${stem}${ext}` : `${stem}.backup-${n}${ext}`);
212
+ try {
213
+ await copyFile(path, target, constants.COPYFILE_EXCL);
214
+ return;
215
+ }
216
+ catch (error) {
217
+ if (error.code !== "EEXIST")
218
+ throw error;
219
+ if ((await readFile(target, "utf-8")) === content)
220
+ return;
170
221
  }
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
222
  }
186
- return kept.length;
187
223
  }
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;
207
- }
208
- lines.splice(bounds.headingIndex, bounds.end - bounds.headingIndex);
209
- working = lines.join("\n");
224
+ const backupOriginal = (backupDir, id, path, content) => copyWithoutOverwrite(backupDir, id, ".md", path, content);
225
+ /** `readdir` that treats only "no such directory" as empty; any other failure (EACCES, EIO, ...) must surface. */
226
+ async function listDirectory(dir) {
227
+ try {
228
+ return await readdir(dir);
229
+ }
230
+ catch (error) {
231
+ const code = error.code;
232
+ if (code === "ENOENT" || code === "ENOTDIR")
233
+ return [];
234
+ throw error;
210
235
  }
211
- return { body: working.replace(/\n{3,}/g, "\n\n").trimEnd(), lastNote };
212
236
  }
213
- async function migrateOneTask(channelDir, id, now) {
237
+ async function convertOneTask(workspaceDir, channelId, channelDir, id, now) {
214
238
  return withTaskMutation(channelDir, id, async () => {
215
239
  const path = join(channelDir, "tasks", `${id}.md`);
216
240
  const content = await readFile(path, "utf-8");
217
- const legacy = parseLegacyFrontmatter(content);
218
- if (!legacy)
241
+ const v3 = parseV3Frontmatter(content);
242
+ if (!v3 || v3.v5 || v3.status === undefined)
219
243
  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;
244
+ let stage = "backup";
245
+ let createdEvent;
246
+ const logPath = join(channelDir, "tasks", `${id}.jsonl`);
247
+ const hadLog = existsSync(logPath);
248
+ try {
249
+ await backupOriginal(join(channelDir, "tasks", BACKUP_DIRNAME), id, path, content);
250
+ const original = taskBody(content);
251
+ const notes = [];
252
+ const stopped = v3.enabled === false || v3.stopped;
253
+ let origin;
254
+ let retire = false;
255
+ if (v3.schedule && stopped) {
256
+ // Event templates have no disabled state, so a stopped recurring task must not get one: it would start running.
257
+ notes.push(`转换到 v5:该周期任务在 v3 中已停用,未生成事件模板(原周期 ${v3.schedule} 未迁移),任务保持暂停;原件在 tasks/.v3/。要恢复周期执行,请人工核对后用 event_manage 新建模板。`);
258
+ }
259
+ else if (v3.schedule) {
260
+ stage = "template";
261
+ const written = await writeTemplateEvent(workspaceDir, channelId, id, original, v3.schedule);
262
+ if (written.name) {
263
+ createdEvent = join(workspaceDir, "events", `${written.name}.json`);
264
+ origin = written.name;
265
+ retire = v3.status === "sleeping";
266
+ notes.push(retire
267
+ ? `转换到 v5:周期性已移到事件模板 ${written.name}(${v3.schedule}),每次触发会生成一个新的任务实例;本任务不再重复。`
268
+ : `转换到 v5:周期性已移到事件模板 ${written.name}(${v3.schedule})。本次正在进行的执行作为它的一个实例继续,下一次由事件生成。`);
269
+ }
270
+ else {
271
+ notes.push(`转换到 v5:无法把周期性转换为事件模板(${written.reason}),该任务已暂停,需要人工处理。`);
272
+ }
273
+ }
274
+ const fields = { state: "open", origin, usage: createUsage(now) };
275
+ if (stopped || (v3.schedule && !origin)) {
276
+ fields.paused = {
277
+ by: stopped ? "user" : "runtime",
278
+ reason: stopped ? (v3.stopReason ?? DEFAULT_STOP_REASON) : "周期性无法转换为事件模板,需要人工处理。",
279
+ at: formatLocalTime(now),
280
+ };
281
+ }
282
+ if (v3.status === "waiting") {
283
+ notes.push("转换到 v5:该任务此前在等待外部条件,v5 没有对应的等待来源,已改为 open。先核对真实状态,再决定继续还是重新停泊。");
284
+ }
285
+ stage = "task";
286
+ await writeStoredTask({ id, path, fields, body: convertBody(original) });
287
+ stage = "log";
288
+ for (const note of notes)
289
+ await appendTaskLog(channelDir, id, { kind: "note", note });
290
+ if (retire) {
291
+ stage = "archive";
292
+ await archiveTask(channelDir, id, "cancelled");
293
+ }
294
+ log.logInfo(`Task ${id} converted to v5`, `state=${fields.state}${fields.paused ? " paused" : ""}${origin ? ` origin=${origin}` : ""}${retire ? " (retired)" : ""}`);
295
+ return true;
296
+ }
297
+ catch (error) {
298
+ // Leave nothing runnable behind: put the v3 original back and drop the artifacts this attempt created.
299
+ const failed = [];
300
+ const attempt = async (what, fn) => {
301
+ try {
302
+ await fn();
303
+ }
304
+ catch (rollbackError) {
305
+ failed.push(`${what}: ${errorMessage(rollbackError)}`);
306
+ }
307
+ };
308
+ if (stage !== "backup") {
309
+ // archiveTask undoes its own partial work. When that undo failed, archive-side files may be the
310
+ // only copy of the old logs: leave them (and the log) alone and report the rollback as failed.
311
+ if (error instanceof ArchiveUndoError)
312
+ failed.push(`rollback failed, archive undo incomplete: ${errorMessage(error)}`);
313
+ else if (!hadLog)
314
+ await attempt("remove log", () => removeIfPresent(logPath));
315
+ if (createdEvent) {
316
+ const eventFile = createdEvent;
317
+ await attempt("remove template event", () => removeIfPresent(eventFile));
318
+ }
319
+ await attempt("restore original", () => writeFileAtomically(path, content));
320
+ }
321
+ throw new TaskConversionError(stage, error, failed.length === 0 ? "ok" : failed.join("; "));
322
+ }
234
323
  });
235
324
  }
236
- /** Migrate every task file in every known channel. Failures are logged and skipped. */
237
- export async function migrateTasksToV4(workspaceDir, stateDir) {
325
+ /** Move task-owned sensor events (`task.<channelId>.<taskId>.<use>`) out of the way: v5 has no `signal` ticket. */
326
+ async function moveTaskOwnedEvents(workspaceDir, channelId, channelDir) {
327
+ const eventsDir = join(workspaceDir, "events");
328
+ const names = (await listDirectory(eventsDir)).filter((name) => name.endsWith(".json"));
329
+ const prefix = `task.${channelId}.`;
330
+ for (const name of names) {
331
+ if (!name.startsWith(prefix))
332
+ continue;
333
+ const rest = name.slice(prefix.length, -".json".length);
334
+ const lastDot = rest.lastIndexOf(".");
335
+ const ownerId = lastDot > 0 ? rest.slice(0, lastDot) : undefined;
336
+ const source = join(eventsDir, name);
337
+ // Copy (never overwriting a same-named backup), then remove the live file: if the removal
338
+ // fails the event is still in place and the retry finds an identical backup.
339
+ await copyWithoutOverwrite(join(channelDir, "tasks", BACKUP_DIRNAME, "events"), name.slice(0, -".json".length), ".json", source, await readFile(source, "utf-8"));
340
+ await rm(source);
341
+ if (ownerId && (await readStoredTask(channelDir, ownerId).catch(() => undefined))) {
342
+ await appendTaskLog(channelDir, ownerId, {
343
+ kind: "note",
344
+ note: `转换到 v5:传感器事件 ${name.slice(0, -".json".length)} 已移到 tasks/.v3/events/(v5 没有 signal 票);需要等待外部条件时,改用带超时的后台作业。`,
345
+ });
346
+ }
347
+ }
348
+ }
349
+ /**
350
+ * Validate a failure report written by this module: a non-empty `failures` array whose entries
351
+ * carry string `channelId` / `stage` / `error` / `rollback` (and an optional string `task`).
352
+ * Anything else is untrustworthy and must block rather than count as "no failed rollback".
353
+ */
354
+ function parseFailureReport(raw) {
355
+ const failures = parseJson(raw)?.failures;
356
+ if (!Array.isArray(failures) || failures.length === 0)
357
+ return undefined;
358
+ for (const entry of failures) {
359
+ if (!isPlainObject(entry))
360
+ return undefined;
361
+ for (const key of ["channelId", "stage", "error", "rollback"]) {
362
+ if (typeof entry[key] !== "string")
363
+ return undefined;
364
+ }
365
+ if (entry.task !== undefined && typeof entry.task !== "string")
366
+ return undefined;
367
+ }
368
+ return failures;
369
+ }
370
+ /**
371
+ * Convert every v3 task file in every known channel. Any failure leaves no marker, writes
372
+ * `state/task-migration-v5.failed.json`, and throws so the caller does not start services.
373
+ */
374
+ export async function migrateTasksToV5(workspaceDir, stateDir) {
238
375
  const markerPath = join(stateDir, MIGRATION_MARKER);
239
376
  if (existsSync(markerPath))
240
377
  return;
378
+ const reportPath = join(stateDir, FAILURE_REPORT);
379
+ if (existsSync(reportPath)) {
380
+ const blocked = (reason) => new Error(`v3 → v5 task conversion is blocked: ${reportPath} ${reason}. The report was kept and no marker was written. Inspect it, restore any listed originals from tasks/.v3/ or your backup, then delete the report.`);
381
+ let raw;
382
+ try {
383
+ raw = await readFile(reportPath, "utf-8");
384
+ }
385
+ catch (error) {
386
+ throw blocked(`could not be read (${errorMessage(error)})`);
387
+ }
388
+ const failures = parseFailureReport(raw);
389
+ if (!failures)
390
+ throw blocked("is not a valid failure report (unparseable or unexpected structure)");
391
+ if (failures.some((entry) => entry.rollback !== "ok"))
392
+ throw blocked("records a failed rollback");
393
+ }
241
394
  const now = new Date();
242
- let migrated = 0;
243
- for (const channelId of await discoverTaskChannels(workspaceDir)) {
395
+ let converted = 0;
396
+ const failures = [];
397
+ let channelIds = [];
398
+ try {
399
+ channelIds = await discoverTaskChannels(workspaceDir, [], { strict: true });
400
+ }
401
+ catch (error) {
402
+ // An undiscoverable workspace is not an empty one: no task was looked at, so no marker.
403
+ log.logWarning("Channels of the workspace could not be discovered", errorMessage(error));
404
+ failures.push({ channelId: "*", stage: "discover", error: errorMessage(error), rollback: "ok" });
405
+ }
406
+ for (const channelId of channelIds) {
244
407
  const channelDir = getChannelDir(workspaceDir, channelId);
245
- let filenames;
408
+ let filenames = [];
246
409
  try {
247
- filenames = (await readdir(join(channelDir, "tasks"))).filter((name) => name.endsWith(".md"));
410
+ filenames = (await listDirectory(join(channelDir, "tasks"))).filter((name) => name.endsWith(".md"));
248
411
  }
249
- catch {
250
- continue;
412
+ catch (error) {
413
+ // An unreadable task directory is not an empty one: the originals were not looked at.
414
+ log.logWarning(`Tasks of ${channelId} could not be listed`, errorMessage(error));
415
+ failures.push({ channelId, stage: "scan", error: errorMessage(error), rollback: "ok" });
251
416
  }
252
417
  for (const filename of filenames) {
253
418
  const id = filename.slice(0, -".md".length);
254
419
  try {
255
- if (await migrateOneTask(channelDir, normalizeTaskId(id), now))
256
- migrated++;
420
+ if (await convertOneTask(workspaceDir, channelId, channelDir, normalizeTaskId(id), now))
421
+ converted++;
257
422
  }
258
423
  catch (error) {
259
- log.logWarning(`Task ${id} could not be migrated to v4`, errorMessage(error));
424
+ log.logWarning(`Task ${id} could not be converted to v5`, errorMessage(error));
425
+ failures.push({
426
+ channelId,
427
+ task: id,
428
+ stage: error instanceof TaskConversionError ? error.stage : "scan",
429
+ error: errorMessage(error instanceof TaskConversionError ? error.cause : error),
430
+ rollback: error instanceof TaskConversionError ? error.rollback : "ok",
431
+ });
260
432
  }
261
433
  }
434
+ await moveTaskOwnedEvents(workspaceDir, channelId, channelDir).catch((error) => {
435
+ log.logWarning(`Task-owned events of ${channelId} could not be moved`, errorMessage(error));
436
+ failures.push({ channelId, stage: "events", error: errorMessage(error), rollback: "ok" });
437
+ });
262
438
  }
263
439
  await mkdir(stateDir, { recursive: true });
440
+ if (failures.length > 0) {
441
+ await writeFileAtomically(reportPath, `${JSON.stringify({ at: formatLocalTime(now), failures }, null, 2)}\n`);
442
+ throw new Error(`v3 → v5 task conversion failed for ${failures.length} item(s); services were not started and no marker was written. See ${reportPath}; fix the cause and restart to retry.`);
443
+ }
444
+ await rm(reportPath, { force: true });
264
445
  await writeFile(markerPath, `${formatLocalTime(now)}\n`, "utf-8");
265
- if (migrated > 0)
266
- log.logInfo("Task migration to v4 complete", `${migrated} task(s)`);
446
+ if (converted > 0)
447
+ log.logInfo("Task conversion to v5 complete", `${converted} task(s)`);
267
448
  }