@oyasmi/pipiclaw 0.9.3-beta.4 → 0.9.3-beta.6

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 (162) hide show
  1. package/README.en.md +12 -12
  2. package/README.md +12 -12
  3. package/dist/agent/channel-runner.d.ts +4 -8
  4. package/dist/agent/channel-runner.js +15 -35
  5. package/dist/agent/job-manager.d.ts +12 -0
  6. package/dist/agent/job-manager.js +43 -3
  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-context.d.ts +2 -2
  11. package/dist/channel/channel-context.js +2 -2
  12. package/dist/channel/channel-event.d.ts +3 -3
  13. package/dist/channel/project-scope-store.d.ts +20 -0
  14. package/dist/channel/project-scope-store.js +22 -7
  15. package/dist/commands/catalog.js +6 -12
  16. package/dist/events/event-commands.js +2 -2
  17. package/dist/events/events.d.ts +51 -30
  18. package/dist/events/events.js +70 -98
  19. package/dist/memory/journal.d.ts +2 -3
  20. package/dist/memory/journal.js +2 -3
  21. package/dist/memory/maintenance-tuning.d.ts +0 -1
  22. package/dist/memory/maintenance-tuning.js +0 -1
  23. package/dist/memory/scheduler.js +8 -16
  24. package/dist/memory/search.js +2 -3
  25. package/dist/memory/session-search.js +3 -9
  26. package/dist/memory/store.d.ts +1 -1
  27. package/dist/memory/store.js +9 -1
  28. package/dist/memory/task-digest.js +10 -11
  29. package/dist/memory/tombstones.js +2 -4
  30. package/dist/models/provider-login.d.ts +1 -1
  31. package/dist/models/provider-login.js +1 -1
  32. package/dist/playbooks/agent-delegation.md +18 -14
  33. package/dist/playbooks/background-jobs.md +2 -2
  34. package/dist/playbooks/event-scheduling.md +22 -13
  35. package/dist/playbooks/memory-and-learning.md +2 -2
  36. package/dist/playbooks/outbound-media.md +1 -1
  37. package/dist/playbooks/runtime-orientation.md +5 -3
  38. package/dist/playbooks/task-lead.md +82 -0
  39. package/dist/runtime/bootstrap.js +107 -196
  40. package/dist/runtime/delivery.d.ts +1 -2
  41. package/dist/runtime/delivery.js +57 -62
  42. package/dist/runtime/dingtalk.d.ts +15 -8
  43. package/dist/runtime/dingtalk.js +101 -35
  44. package/dist/runtime/durable-dispatch.js +30 -3
  45. package/dist/runtime/report-commands.d.ts +30 -0
  46. package/dist/runtime/report-commands.js +71 -0
  47. package/dist/runtime/subagent-commands.js +1 -1
  48. package/dist/runtime/task-commands.d.ts +0 -8
  49. package/dist/runtime/task-commands.js +48 -85
  50. package/dist/runtime/task-driver.d.ts +13 -9
  51. package/dist/runtime/task-driver.js +34 -39
  52. package/dist/runtime/task-migration.d.ts +18 -29
  53. package/dist/runtime/task-migration.js +195 -183
  54. package/dist/runtime/task-spawn.d.ts +24 -0
  55. package/dist/runtime/task-spawn.js +49 -0
  56. package/dist/runtime/task-wake.d.ts +33 -46
  57. package/dist/runtime/task-wake.js +15 -90
  58. package/dist/security/network.js +44 -9
  59. package/dist/settings.d.ts +1 -8
  60. package/dist/settings.js +1 -8
  61. package/dist/subagents/discovery.js +7 -17
  62. package/dist/subagents/external/claude-code.js +3 -1
  63. package/dist/subagents/external/harness.d.ts +4 -2
  64. package/dist/subagents/external/run.d.ts +3 -1
  65. package/dist/subagents/external/run.js +14 -23
  66. package/dist/subagents/external/settlement.d.ts +4 -16
  67. package/dist/subagents/external/settlement.js +16 -67
  68. package/dist/subagents/runs.d.ts +15 -29
  69. package/dist/subagents/runs.js +71 -160
  70. package/dist/subagents/tool.d.ts +20 -4
  71. package/dist/subagents/tool.js +63 -87
  72. package/dist/subagents/verification-outcome.d.ts +13 -19
  73. package/dist/subagents/verification-outcome.js +8 -22
  74. package/dist/subagents/workspace-summary.d.ts +8 -0
  75. package/dist/subagents/workspace-summary.js +29 -0
  76. package/dist/tasks/board.d.ts +43 -0
  77. package/dist/tasks/board.js +134 -0
  78. package/dist/tasks/brief.d.ts +10 -5
  79. package/dist/tasks/brief.js +78 -26
  80. package/dist/tasks/budget.d.ts +13 -14
  81. package/dist/tasks/budget.js +21 -40
  82. package/dist/tasks/contract-input.d.ts +19 -0
  83. package/dist/tasks/contract-input.js +55 -0
  84. package/dist/tasks/create.d.ts +17 -0
  85. package/dist/tasks/create.js +36 -0
  86. package/dist/tasks/frontmatter.d.ts +20 -27
  87. package/dist/tasks/frontmatter.js +18 -31
  88. package/dist/tasks/ledger.d.ts +61 -117
  89. package/dist/tasks/ledger.js +78 -223
  90. package/dist/tasks/log.d.ts +62 -35
  91. package/dist/tasks/log.js +51 -29
  92. package/dist/tasks/session-path.d.ts +3 -3
  93. package/dist/tasks/session-path.js +4 -5
  94. package/dist/tasks/store.d.ts +11 -29
  95. package/dist/tasks/store.js +39 -83
  96. package/dist/tasks/ticket.d.ts +33 -66
  97. package/dist/tasks/ticket.js +31 -120
  98. package/dist/tasks/work-log.d.ts +20 -0
  99. package/dist/tasks/work-log.js +42 -0
  100. package/dist/tools/bash.d.ts +1 -1
  101. package/dist/tools/bash.js +1 -1
  102. package/dist/tools/event-manage.d.ts +16 -2
  103. package/dist/tools/event-manage.js +30 -12
  104. package/dist/tools/index.d.ts +5 -3
  105. package/dist/tools/index.js +5 -5
  106. package/dist/tools/registry.d.ts +6 -4
  107. package/dist/tools/registry.js +1 -4
  108. package/dist/tools/subagent-manage.js +4 -2
  109. package/dist/tools/task-manage/create.js +11 -27
  110. package/dist/tools/task-manage/lifecycle.d.ts +6 -7
  111. package/dist/tools/task-manage/lifecycle.js +23 -106
  112. package/dist/tools/task-manage/log-view.d.ts +3 -2
  113. package/dist/tools/task-manage/log-view.js +6 -6
  114. package/dist/tools/task-manage/schema.d.ts +10 -30
  115. package/dist/tools/task-manage/schema.js +33 -49
  116. package/dist/tools/task-manage/shared.d.ts +35 -42
  117. package/dist/tools/task-manage/shared.js +53 -192
  118. package/dist/tools/task-manage/step-end.d.ts +6 -6
  119. package/dist/tools/task-manage/step-end.js +61 -98
  120. package/dist/tools/task-manage/types.d.ts +8 -9
  121. package/dist/tools/task-manage.js +5 -5
  122. package/dist/tui/app.js +11 -38
  123. package/dist/tui/commands.d.ts +18 -8
  124. package/dist/tui/commands.js +2 -9
  125. package/dist/tui/turn-controller.d.ts +2 -14
  126. package/dist/tui/turn-controller.js +1 -17
  127. package/dist/web/client.js +9 -1
  128. package/examples/sub-agents/README.md +67 -80
  129. package/examples/sub-agents/agents/claude-high.md +23 -0
  130. package/examples/sub-agents/agents/claude-main.md +23 -0
  131. package/examples/sub-agents/agents/codex-flash.md +23 -0
  132. package/examples/sub-agents/agents/codex-high.md +23 -0
  133. package/examples/sub-agents/agents/codex-main.md +23 -0
  134. package/examples/sub-agents/agents/codex-review.md +23 -0
  135. package/examples/sub-agents/agents/glm-flash.md +23 -0
  136. package/examples/sub-agents/agents/glm-high.md +23 -0
  137. package/examples/sub-agents/{verifier.md → roles/verifier.md} +1 -1
  138. package/package.json +1 -1
  139. package/dist/memory/maintenance-migration.d.ts +0 -5
  140. package/dist/memory/maintenance-migration.js +0 -91
  141. package/dist/memory/migrate.d.ts +0 -15
  142. package/dist/memory/migrate.js +0 -364
  143. package/dist/playbooks/task-loop.md +0 -90
  144. package/dist/tasks/artifact-subject.d.ts +0 -40
  145. package/dist/tasks/artifact-subject.js +0 -334
  146. package/dist/tasks/cycle.d.ts +0 -48
  147. package/dist/tasks/cycle.js +0 -94
  148. package/dist/tasks/rounds.d.ts +0 -41
  149. package/dist/tasks/rounds.js +0 -53
  150. package/dist/tasks/task-events.d.ts +0 -6
  151. package/dist/tasks/task-events.js +0 -14
  152. package/dist/tasks/task-schedule.d.ts +0 -18
  153. package/dist/tasks/task-schedule.js +0 -50
  154. package/dist/tasks/verification.d.ts +0 -114
  155. package/dist/tasks/verification.js +0 -226
  156. /package/examples/sub-agents/{builder-hard.md → roles/builder-hard.md} +0 -0
  157. /package/examples/sub-agents/{builder.md → roles/builder.md} +0 -0
  158. /package/examples/sub-agents/{explorer.md → roles/explorer.md} +0 -0
  159. /package/examples/sub-agents/{git-committer.md → roles/git-committer.md} +0 -0
  160. /package/examples/sub-agents/{planner.md → roles/planner.md} +0 -0
  161. /package/examples/sub-agents/{reviewer.md → roles/reviewer.md} +0 -0
  162. /package/examples/sub-agents/{worker.md → roles/worker.md} +0 -0
@@ -1,36 +1,25 @@
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 {
1
+ interface V3Fields {
16
2
  status?: string;
17
- enabled: boolean;
18
- wake?: string;
3
+ enabled?: boolean;
19
4
  schedule?: string;
20
- control?: LegacyControl;
21
- outcome?: "completed" | "cancelled";
22
- closedAt?: string;
5
+ stopReason?: string;
6
+ /** Any v5 key present: the file is already converted. */
7
+ v5: boolean;
23
8
  }
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;
9
+ /** Minimal reader for the v3 frontmatter block; the only place that still understands it. */
10
+ export declare function parseV3Frontmatter(content: string): V3Fields | undefined;
11
+ /** Rename `## Plan` to `## Work Items` and drop the per-cycle sections, the two body changes v5 makes. */
12
+ export declare function convertBody(body: string): string;
13
+ interface TemplateOutcome {
14
+ template?: Record<string, unknown>;
15
+ reason?: string;
28
16
  }
29
17
  /**
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.
18
+ * Build the event template a recurring v3 task becomes. The original Manual and Verification text
19
+ * is carried into the Goal (v5 has no such sections, and a recurring job's accumulated rules are
20
+ * exactly what the template exists to keep), and every checkbox is reset.
32
21
  */
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>;
22
+ export declare function buildTemplate(id: string, body: string): TemplateOutcome;
23
+ /** Convert every v3 task file in every known channel. Failures are logged and skipped. */
24
+ export declare function migrateTasksToV5(workspaceDir: string, stateDir: string): Promise<void>;
36
25
  export {};
@@ -1,42 +1,57 @@
1
1
  import { existsSync } from "node:fs";
2
- import { copyFile, mkdir, readdir, readFile, writeFile } from "node:fs/promises";
2
+ import { copyFile, mkdir, readdir, readFile, rename, 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 { 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 because of the upgrade.
26
29
  *
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.
30
+ * Originals are copied to `tasks/.v3/` and never deleted. Files that already carry v5
31
+ * frontmatter (`state:`) are left alone.
29
32
  */
30
- const MIGRATION_MARKER = "task-migration-v4.done";
33
+ const MIGRATION_MARKER = "task-migration-v5.done";
34
+ const BACKUP_DIRNAME = ".v3";
35
+ const ITEMS_NAMES = ["Plan", "计划"];
36
+ /** v3 per-cycle bookkeeping; v5 keeps this in the loop log instead of the contract. */
37
+ const CYCLE_SECTION_NAMES = ["Current Cycle", "当前周期", "History", "历史"];
38
+ function parseJson(value) {
39
+ try {
40
+ const parsed = JSON.parse(value);
41
+ return isPlainObject(parsed) ? parsed : undefined;
42
+ }
43
+ catch {
44
+ return undefined;
45
+ }
46
+ }
31
47
  /** Minimal reader for the v3 frontmatter block; the only place that still understands it. */
32
- function parseLegacyFrontmatter(content) {
48
+ export function parseV3Frontmatter(content) {
33
49
  if (!content.startsWith("---"))
34
50
  return undefined;
35
51
  const end = content.indexOf("\n---", 3);
36
52
  if (end === -1)
37
53
  return undefined;
38
- const fields = { enabled: true };
39
- let sawLegacy = false;
54
+ const fields = { v5: false };
40
55
  for (const line of content.slice(3, end).split("\n")) {
41
56
  const idx = line.indexOf(":");
42
57
  if (idx === -1)
@@ -44,224 +59,221 @@ function parseLegacyFrontmatter(content) {
44
59
  const key = line.slice(0, idx).trim();
45
60
  const value = line.slice(idx + 1).trim();
46
61
  switch (key) {
62
+ case "state":
63
+ fields.v5 = true;
64
+ break;
47
65
  case "status":
48
66
  fields.status = value;
49
- sawLegacy = true;
50
67
  break;
51
68
  case "enabled":
52
69
  fields.enabled = value !== "false";
53
- sawLegacy = true;
54
- break;
55
- case "wake":
56
- fields.wake = value || undefined;
57
70
  break;
58
71
  case "schedule":
59
72
  fields.schedule = value || undefined;
60
73
  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
74
  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.
77
- }
75
+ const stop = parseJson(value)?.stop;
76
+ if (isPlainObject(stop) && typeof stop.reason === "string")
77
+ fields.stopReason = stop.reason;
78
78
  break;
79
79
  }
80
80
  default:
81
81
  break;
82
82
  }
83
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;
84
+ return fields;
88
85
  }
89
- function legacyCycle(control) {
90
- if (!control?.cycleId)
86
+ function sectionText(body, names) {
87
+ const lines = body.split("\n");
88
+ const bounds = findTaskSectionBounds(lines, names);
89
+ if (!bounds)
91
90
  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
- };
91
+ const text = lines
92
+ .slice(bounds.headingIndex + 1, bounds.end)
93
+ .join("\n")
94
+ .trim();
95
+ return text || undefined;
96
+ }
97
+ /** Rename `## Plan` to `## Work Items` and drop the per-cycle sections, the two body changes v5 makes. */
98
+ export function convertBody(body) {
99
+ const lines = body.split("\n");
100
+ const items = findTaskSectionBounds(lines, ITEMS_NAMES);
101
+ if (items)
102
+ lines[items.headingIndex] = "## Work Items";
103
+ for (const names of [CYCLE_SECTION_NAMES.slice(0, 2), CYCLE_SECTION_NAMES.slice(2)]) {
104
+ const bounds = findTaskSectionBounds(lines, names);
105
+ if (bounds)
106
+ lines.splice(bounds.headingIndex, bounds.end - bounds.headingIndex);
107
+ }
108
+ return lines
109
+ .join("\n")
110
+ .replace(/\n{3,}/g, "\n\n")
111
+ .trimEnd();
101
112
  }
102
113
  /**
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.
114
+ * Build the event template a recurring v3 task becomes. The original Manual and Verification text
115
+ * is carried into the Goal (v5 has no such sections, and a recurring job's accumulated rules are
116
+ * exactly what the template exists to keep), and every checkbox is reset.
105
117
  */
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,
118
+ export function buildTemplate(id, body) {
119
+ const title = extractTaskTitle(`---\n---\n${body}`, id);
120
+ const goal = sectionText(body, ["Goal", "目标"]) ?? title;
121
+ const manual = sectionText(body, ["Manual", "手册"]);
122
+ const verification = sectionText(body, ["Verification", "验收"])
123
+ ?.split("\n")
124
+ .filter((line) => !/^Independent verification:/i.test(line.trim()))
125
+ .join("\n")
126
+ .trim();
127
+ const dod = (sectionText(body, ["DoD"]) ?? "")
128
+ .split("\n")
129
+ .map((line) => line.replace(/^(\s*[-*]\s+)\[[xX]\]/, "$1[ ]"))
130
+ .join("\n")
131
+ .trim();
132
+ const items = parseTaskItems(convertBody(body))?.items.map((item) => ({ text: item.text })) ?? [];
133
+ const template = {
134
+ title,
135
+ goal: [
136
+ goal,
137
+ manual ? `原手册(每次执行都适用):\n${manual}` : undefined,
138
+ verification ? `原检查要求:\n${verification}` : undefined,
139
+ ]
140
+ .filter(Boolean)
141
+ .join("\n\n"),
142
+ dod: dod || "- [ ] 完成上述目标",
143
+ ...(items.length > 0 ? { items } : {}),
113
144
  };
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;
170
- }
171
- current.push(line);
145
+ try {
146
+ validateTaskContractInput(template);
147
+ return { template };
172
148
  }
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
- });
149
+ catch (error) {
150
+ return { reason: errorMessage(error) };
185
151
  }
186
- return kept.length;
187
152
  }
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");
210
- }
211
- return { body: working.replace(/\n{3,}/g, "\n\n").trimEnd(), lastNote };
153
+ /** Write the event template for a recurring task; returns the event name, or why it could not be expressed. */
154
+ async function writeTemplateEvent(workspaceDir, channelId, id, body, schedule) {
155
+ const { template, reason } = buildTemplate(id, body);
156
+ if (!template)
157
+ return { reason };
158
+ const eventsDir = join(workspaceDir, "events");
159
+ await mkdir(eventsDir, { recursive: true });
160
+ let name = id;
161
+ if (existsSync(join(eventsDir, `${name}.json`)))
162
+ name = `${id}-task`;
163
+ if (existsSync(join(eventsDir, `${name}.json`)))
164
+ return { reason: `event ${name} already exists` };
165
+ const event = { type: "periodic", channelId, schedule, task: template };
166
+ await writeFileAtomically(join(eventsDir, `${name}.json`), `${JSON.stringify(event, null, 2)}\n`);
167
+ return { name };
212
168
  }
213
- async function migrateOneTask(channelDir, id, now) {
169
+ async function convertOneTask(workspaceDir, channelId, channelDir, id, now) {
214
170
  return withTaskMutation(channelDir, id, async () => {
215
171
  const path = join(channelDir, "tasks", `${id}.md`);
216
172
  const content = await readFile(path, "utf-8");
217
- const legacy = parseLegacyFrontmatter(content);
218
- if (!legacy)
173
+ const v3 = parseV3Frontmatter(content);
174
+ if (!v3 || v3.v5 || v3.status === undefined)
219
175
  return false;
220
- const backupDir = join(channelDir, "tasks", ".v3");
176
+ const backupDir = join(channelDir, "tasks", BACKUP_DIRNAME);
221
177
  await mkdir(backupDir, { recursive: true });
222
178
  await copyFile(path, join(backupDir, `${id}.md`));
223
- const { fields, repairNote } = convertLegacyTaskFields(legacy, now);
224
179
  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}`);
180
+ const notes = [];
181
+ let origin;
182
+ let retire = false;
183
+ if (v3.schedule) {
184
+ const written = await writeTemplateEvent(workspaceDir, channelId, id, original, v3.schedule);
185
+ if (written.name) {
186
+ origin = written.name;
187
+ retire = v3.status === "sleeping";
188
+ notes.push(retire
189
+ ? `转换到 v5:周期性已移到事件模板 ${written.name}(${v3.schedule}),每次触发会生成一个新的任务实例;本任务不再重复。`
190
+ : `转换到 v5:周期性已移到事件模板 ${written.name}(${v3.schedule})。本次正在进行的执行作为它的一个实例继续,下一次由事件生成。`);
191
+ }
192
+ else {
193
+ notes.push(`转换到 v5:无法把周期性转换为事件模板(${written.reason}),该任务已暂停,需要人工处理。`);
194
+ }
195
+ }
196
+ const fields = { state: "open", origin, usage: createUsage(now) };
197
+ const stopped = v3.enabled === false || v3.stopReason !== undefined;
198
+ if (stopped || (v3.schedule && !origin)) {
199
+ fields.paused = {
200
+ by: stopped ? "user" : "runtime",
201
+ reason: stopped ? (v3.stopReason ?? "v3 中已停用。") : "周期性无法转换为事件模板,需要人工处理。",
202
+ at: formatLocalTime(now),
203
+ };
204
+ }
205
+ if (v3.status === "waiting") {
206
+ notes.push("转换到 v5:该任务此前在等待外部条件,v5 没有对应的等待来源,已改为 open。先核对真实状态,再决定继续还是重新停泊。");
207
+ }
208
+ await writeStoredTask({ id, path, fields, body: convertBody(original) });
209
+ for (const note of notes)
210
+ await appendTaskLog(channelDir, id, { kind: "note", note });
211
+ if (retire)
212
+ await archiveTask(channelDir, id, "cancelled");
213
+ log.logInfo(`Task ${id} converted to v5`, `state=${fields.state}${fields.paused ? " paused" : ""}${origin ? ` origin=${origin}` : ""}${retire ? " (retired)" : ""}`);
233
214
  return true;
234
215
  });
235
216
  }
236
- /** Migrate every task file in every known channel. Failures are logged and skipped. */
237
- export async function migrateTasksToV4(workspaceDir, stateDir) {
217
+ /** Move task-owned sensor events (`task.<channelId>.<taskId>.<use>`) out of the way: v5 has no `signal` ticket. */
218
+ async function moveTaskOwnedEvents(workspaceDir, channelId, channelDir) {
219
+ const eventsDir = join(workspaceDir, "events");
220
+ let names;
221
+ try {
222
+ names = (await readdir(eventsDir)).filter((name) => name.endsWith(".json"));
223
+ }
224
+ catch {
225
+ return;
226
+ }
227
+ const prefix = `task.${channelId}.`;
228
+ for (const name of names) {
229
+ if (!name.startsWith(prefix))
230
+ continue;
231
+ const rest = name.slice(prefix.length, -".json".length);
232
+ const lastDot = rest.lastIndexOf(".");
233
+ const ownerId = lastDot > 0 ? rest.slice(0, lastDot) : undefined;
234
+ const targetDir = join(channelDir, "tasks", BACKUP_DIRNAME, "events");
235
+ await mkdir(targetDir, { recursive: true });
236
+ await rename(join(eventsDir, name), join(targetDir, name));
237
+ if (ownerId && (await readStoredTask(channelDir, ownerId).catch(() => undefined))) {
238
+ await appendTaskLog(channelDir, ownerId, {
239
+ kind: "note",
240
+ note: `转换到 v5:传感器事件 ${name.slice(0, -".json".length)} 已移到 tasks/.v3/events/(v5 没有 signal 票);需要等待外部条件时,改用带超时的后台作业。`,
241
+ });
242
+ }
243
+ }
244
+ }
245
+ /** Convert every v3 task file in every known channel. Failures are logged and skipped. */
246
+ export async function migrateTasksToV5(workspaceDir, stateDir) {
238
247
  const markerPath = join(stateDir, MIGRATION_MARKER);
239
248
  if (existsSync(markerPath))
240
249
  return;
241
250
  const now = new Date();
242
- let migrated = 0;
251
+ let converted = 0;
243
252
  for (const channelId of await discoverTaskChannels(workspaceDir)) {
244
253
  const channelDir = getChannelDir(workspaceDir, channelId);
245
- let filenames;
254
+ let filenames = [];
246
255
  try {
247
256
  filenames = (await readdir(join(channelDir, "tasks"))).filter((name) => name.endsWith(".md"));
248
257
  }
249
258
  catch {
250
- continue;
259
+ // no tasks in this channel
251
260
  }
252
261
  for (const filename of filenames) {
253
262
  const id = filename.slice(0, -".md".length);
254
263
  try {
255
- if (await migrateOneTask(channelDir, normalizeTaskId(id), now))
256
- migrated++;
264
+ if (await convertOneTask(workspaceDir, channelId, channelDir, normalizeTaskId(id), now))
265
+ converted++;
257
266
  }
258
267
  catch (error) {
259
- log.logWarning(`Task ${id} could not be migrated to v4`, errorMessage(error));
268
+ log.logWarning(`Task ${id} could not be converted to v5`, errorMessage(error));
260
269
  }
261
270
  }
271
+ await moveTaskOwnedEvents(workspaceDir, channelId, channelDir).catch((error) => {
272
+ log.logWarning(`Task-owned events of ${channelId} could not be moved`, errorMessage(error));
273
+ });
262
274
  }
263
275
  await mkdir(stateDir, { recursive: true });
264
276
  await writeFile(markerPath, `${formatLocalTime(now)}\n`, "utf-8");
265
- if (migrated > 0)
266
- log.logInfo("Task migration to v4 complete", `${migrated} task(s)`);
277
+ if (converted > 0)
278
+ log.logInfo("Task conversion to v5 complete", `${converted} task(s)`);
267
279
  }
@@ -0,0 +1,24 @@
1
+ import type { SpawnTaskRequest, SpawnTaskResult } from "../events/events.js";
2
+ export interface TaskSpawnerOptions {
3
+ /** The channel's directory under the workspace. */
4
+ getChannelDir: (channelId: string) => string;
5
+ /** Wake the driver so the new instance's first step is queued promptly. */
6
+ nudge: () => void;
7
+ /** Direct, non-LLM message to the channel — used for the "previous instance still running" receipt. */
8
+ notify: (channelId: string, text: string) => Promise<unknown>;
9
+ }
10
+ /**
11
+ * Create the task instance a template event asks for (spec 052, D2).
12
+ *
13
+ * The instance id is `<event>-<YYYYMMDD>-<HHmm>` of the occurrence, so it is a pure function of
14
+ * *which occurrence this is*: a replay after a crash lands on the same id and is recognized as
15
+ * already spawned. That check comes first — otherwise the replay would find the instance it just
16
+ * made and misreport it as a still-running predecessor.
17
+ *
18
+ * A second instance of the same event never runs alongside the first: two copies of the same
19
+ * recurring job mostly duplicate work or collide. The occurrence is skipped and the user is told
20
+ * every time (INV-7) — a stuck instance is something they need to know about, not something to
21
+ * hide behind a quiet skip. The stuck instance itself is bounded by its budget, idle detection and
22
+ * ticket backstops, so the skipping cannot go on forever.
23
+ */
24
+ export declare function createTaskSpawner(options: TaskSpawnerOptions): (request: SpawnTaskRequest) => Promise<SpawnTaskResult>;
@@ -0,0 +1,49 @@
1
+ import { existsSync } from "node:fs";
2
+ import * as log from "../log.js";
3
+ import { createTaskDocument, instanceStamp } from "../tasks/create.js";
4
+ import { readActiveTasks } from "../tasks/ledger.js";
5
+ import { archivedTaskPath, taskPath, tasksDir } from "../tasks/store.js";
6
+ const STATE_LABEL = { open: "进行中", parked: "等待中" };
7
+ /**
8
+ * Create the task instance a template event asks for (spec 052, D2).
9
+ *
10
+ * The instance id is `<event>-<YYYYMMDD>-<HHmm>` of the occurrence, so it is a pure function of
11
+ * *which occurrence this is*: a replay after a crash lands on the same id and is recognized as
12
+ * already spawned. That check comes first — otherwise the replay would find the instance it just
13
+ * made and misreport it as a still-running predecessor.
14
+ *
15
+ * A second instance of the same event never runs alongside the first: two copies of the same
16
+ * recurring job mostly duplicate work or collide. The occurrence is skipped and the user is told
17
+ * every time (INV-7) — a stuck instance is something they need to know about, not something to
18
+ * hide behind a quiet skip. The stuck instance itself is bounded by its budget, idle detection and
19
+ * ticket backstops, so the skipping cannot go on forever.
20
+ */
21
+ export function createTaskSpawner(options) {
22
+ return async (request) => {
23
+ const channelDir = options.getChannelDir(request.channelId);
24
+ const id = `${request.eventName}-${instanceStamp(request.occurrence)}`;
25
+ if (existsSync(taskPath(channelDir, id)) || existsSync(archivedTaskPath(channelDir, id))) {
26
+ return { outcome: "exists", id };
27
+ }
28
+ const active = (await readActiveTasks(tasksDir(channelDir))).find((entry) => entry.fields.origin === request.eventName && !entry.fields.outcome);
29
+ if (active) {
30
+ const state = STATE_LABEL[active.fields.state] ?? active.fields.state;
31
+ await options
32
+ .notify(request.channelId, `周期任务 ${request.eventName} 本次(${instanceStamp(request.occurrence)})未启动:上一实例 ${active.id} 仍在进行(${state}${active.fields.paused ? ",已暂停" : ""})。\n查看:/tasks show ${active.id}`)
33
+ .catch((error) => {
34
+ log.logWarning(`Could not deliver skip receipt for ${request.eventName}`, String(error));
35
+ });
36
+ return { outcome: "skipped", id: active.id };
37
+ }
38
+ await createTaskDocument({
39
+ channelDir,
40
+ id,
41
+ input: request.template,
42
+ origin: request.eventName,
43
+ now: request.occurrence,
44
+ });
45
+ log.logInfo(`[${request.channelId}] Event ${request.eventName} spawned task ${id}`);
46
+ options.nudge();
47
+ return { outcome: "spawned", id };
48
+ };
49
+ }