@oyasmi/pipiclaw 0.9.2 → 0.9.3-beta.2

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 (178) hide show
  1. package/README.en.md +250 -0
  2. package/README.md +3 -1
  3. package/dist/agent/channel-runner.d.ts +59 -2
  4. package/dist/agent/channel-runner.js +177 -76
  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 +19 -0
  40. package/dist/memory/render.js +35 -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/memory/transcript.js +12 -5
  54. package/dist/playbooks/agent-delegation.md +37 -9
  55. package/dist/playbooks/background-jobs.md +1 -1
  56. package/dist/playbooks/event-scheduling.md +6 -2
  57. package/dist/playbooks/memory-and-learning.md +36 -12
  58. package/dist/playbooks/outbound-media.md +1 -1
  59. package/dist/playbooks/runtime-orientation.md +9 -8
  60. package/dist/playbooks/task-loop.md +110 -0
  61. package/dist/runtime/bootstrap.d.ts +3 -3
  62. package/dist/runtime/bootstrap.js +66 -41
  63. package/dist/runtime/events.d.ts +9 -0
  64. package/dist/runtime/events.js +43 -4
  65. package/dist/runtime/task-commands.d.ts +14 -15
  66. package/dist/runtime/task-commands.js +249 -485
  67. package/dist/runtime/task-driver.d.ts +41 -29
  68. package/dist/runtime/task-driver.js +170 -317
  69. package/dist/runtime/task-migration.d.ts +34 -30
  70. package/dist/runtime/task-migration.js +229 -183
  71. package/dist/runtime/task-wake.d.ts +6 -3
  72. package/dist/runtime/task-wake.js +26 -19
  73. package/dist/settings.d.ts +0 -29
  74. package/dist/settings.js +12 -35
  75. package/dist/shared/markdown-sections.d.ts +0 -1
  76. package/dist/shared/markdown-sections.js +0 -3
  77. package/dist/subagents/discovery.d.ts +2 -2
  78. package/dist/subagents/discovery.js +21 -10
  79. package/dist/subagents/external/progress-tail.js +6 -1
  80. package/dist/subagents/external/run.js +1 -0
  81. package/dist/subagents/runs.d.ts +19 -2
  82. package/dist/subagents/runs.js +73 -4
  83. package/dist/subagents/tool.d.ts +10 -8
  84. package/dist/subagents/tool.js +55 -94
  85. package/dist/tasks/brief.d.ts +17 -0
  86. package/dist/tasks/brief.js +57 -0
  87. package/dist/tasks/budget.d.ts +26 -0
  88. package/dist/tasks/budget.js +59 -0
  89. package/dist/tasks/cycle.d.ts +48 -0
  90. package/dist/tasks/cycle.js +94 -0
  91. package/dist/tasks/frontmatter.d.ts +73 -0
  92. package/dist/tasks/frontmatter.js +175 -0
  93. package/dist/tasks/ledger.d.ts +66 -106
  94. package/dist/tasks/ledger.js +90 -546
  95. package/dist/tasks/log.d.ts +88 -0
  96. package/dist/tasks/log.js +97 -0
  97. package/dist/tasks/rounds.d.ts +41 -0
  98. package/dist/tasks/rounds.js +53 -0
  99. package/dist/tasks/session-path.d.ts +9 -0
  100. package/dist/tasks/session-path.js +16 -0
  101. package/dist/tasks/steer.d.ts +8 -0
  102. package/dist/tasks/steer.js +79 -0
  103. package/dist/tasks/store.d.ts +60 -35
  104. package/dist/tasks/store.js +166 -107
  105. package/dist/tasks/ticket.d.ts +102 -0
  106. package/dist/tasks/ticket.js +209 -0
  107. package/dist/tasks/verification.d.ts +47 -0
  108. package/dist/tasks/verification.js +60 -1
  109. package/dist/tools/index.d.ts +13 -4
  110. package/dist/tools/index.js +5 -10
  111. package/dist/tools/memory-manage.d.ts +6 -16
  112. package/dist/tools/memory-manage.js +108 -129
  113. package/dist/tools/presentation.js +2 -1
  114. package/dist/tools/registry.d.ts +11 -2
  115. package/dist/tools/registry.js +17 -6
  116. package/dist/tools/subagent-manage.d.ts +0 -9
  117. package/dist/tools/subagent-manage.js +8 -17
  118. package/dist/tools/task-manage/create.js +2 -2
  119. package/dist/tools/task-manage/lifecycle.d.ts +9 -4
  120. package/dist/tools/task-manage/lifecycle.js +136 -188
  121. package/dist/tools/task-manage/log-view.d.ts +8 -0
  122. package/dist/tools/task-manage/log-view.js +24 -0
  123. package/dist/tools/task-manage/schema.d.ts +38 -14
  124. package/dist/tools/task-manage/schema.js +46 -27
  125. package/dist/tools/task-manage/shared.d.ts +35 -31
  126. package/dist/tools/task-manage/shared.js +130 -141
  127. package/dist/tools/task-manage/step-end.d.ts +11 -0
  128. package/dist/tools/task-manage/step-end.js +134 -0
  129. package/dist/tools/task-manage/types.d.ts +23 -32
  130. package/dist/tools/task-manage.d.ts +4 -3
  131. package/dist/tools/task-manage.js +30 -15
  132. package/dist/tools/tool-details.d.ts +1 -1
  133. package/dist/tui/app.js +0 -2
  134. package/examples/sub-agents/README.md +54 -38
  135. package/examples/sub-agents/builder-hard.md +21 -12
  136. package/examples/sub-agents/builder.md +24 -16
  137. package/examples/sub-agents/explorer.md +17 -15
  138. package/examples/sub-agents/git-committer.md +8 -6
  139. package/examples/sub-agents/planner.md +17 -16
  140. package/examples/sub-agents/reviewer.md +11 -9
  141. package/examples/sub-agents/verifier.md +22 -16
  142. package/examples/sub-agents/worker.md +22 -6
  143. package/package.json +1 -1
  144. package/dist/agent/effect-ledger.d.ts +0 -32
  145. package/dist/agent/effect-ledger.js +0 -89
  146. package/dist/memory/bootstrap.d.ts +0 -17
  147. package/dist/memory/bootstrap.js +0 -120
  148. package/dist/memory/candidates.d.ts +0 -26
  149. package/dist/memory/candidates.js +0 -202
  150. package/dist/memory/consolidation.d.ts +0 -54
  151. package/dist/memory/consolidation.js +0 -292
  152. package/dist/memory/extraction.d.ts +0 -54
  153. package/dist/memory/extraction.js +0 -240
  154. package/dist/memory/files.d.ts +0 -71
  155. package/dist/memory/files.js +0 -419
  156. package/dist/memory/maintenance-jobs.d.ts +0 -41
  157. package/dist/memory/maintenance-jobs.js +0 -265
  158. package/dist/memory/metadata.d.ts +0 -57
  159. package/dist/memory/metadata.js +0 -142
  160. package/dist/memory/probation.d.ts +0 -17
  161. package/dist/memory/probation.js +0 -44
  162. package/dist/memory/promotion.d.ts +0 -38
  163. package/dist/memory/promotion.js +0 -36
  164. package/dist/memory/recall.d.ts +0 -59
  165. package/dist/memory/recall.js +0 -746
  166. package/dist/memory/session.d.ts +0 -24
  167. package/dist/memory/session.js +0 -273
  168. package/dist/playbooks/task-driving.md +0 -92
  169. package/dist/playbooks/task-planning.md +0 -58
  170. package/dist/tasks/control.d.ts +0 -56
  171. package/dist/tasks/control.js +0 -169
  172. package/dist/tasks/transitions.d.ts +0 -16
  173. package/dist/tasks/transitions.js +0 -48
  174. package/dist/tools/task-manage/verification.d.ts +0 -19
  175. package/dist/tools/task-manage/verification.js +0 -91
  176. package/examples/sub-agents/documenter.md +0 -50
  177. package/examples/sub-agents/log-sifter.md +0 -47
  178. package/examples/sub-agents/scout.md +0 -34
@@ -1,37 +1,35 @@
1
1
  import { existsSync } from "node:fs";
2
- import { readdir, readFile } from "node:fs/promises";
3
- import { join, resolve, sep } from "node:path";
4
- import { channelJobTaskIds } from "../agent/job-manager.js";
2
+ import { readdir } from "node:fs/promises";
3
+ import { join } from "node:path";
5
4
  import { renderSubcommandUsage } from "../commands/catalog.js";
6
- import { capReply } from "../commands/reply-limits.js";
7
- import { formatLocalTime, parseLocalTime, parseWakeInput } from "../shared/local-time.js";
8
- import { errorMessage } from "../shared/text-utils.js";
9
- import { channelDelegationTaskIds, getSubAgentRunManager } from "../subagents/runs.js";
10
- import { applyTaskControlPatch, createDefaultTaskControl, taskBudgetViolation } from "../tasks/control.js";
11
- import { countTaskDodItems, extractTaskTitle, missingStandardTaskSections, normalizeTaskId, readActiveTasks, recurringTaskMissedOccurrence, } from "../tasks/ledger.js";
5
+ import { parseLocalTime } from "../shared/local-time.js";
6
+ import { clipText, errorMessage } from "../shared/text-utils.js";
7
+ import { normalizeTaskId, readActiveTasks } from "../tasks/ledger.js";
8
+ import { readTaskLog, renderTaskLogLine } from "../tasks/log.js";
12
9
  import { withTaskMutation } from "../tasks/mutation-lock.js";
13
- import { openRecurringTaskCycle, readStoredTask, taskBodyHash, writeStoredTask } from "../tasks/store.js";
14
- import { parseTaskEventName, taskEventPrefix } from "../tasks/task-events.js";
15
- import { nextTaskWake, validateTaskSchedule } from "../tasks/task-schedule.js";
16
- import { normalizeStoredStatus, resolveTaskTransition } from "../tasks/transitions.js";
17
- import { readVerificationAttestation } from "../tasks/verification.js";
18
- import { parseScheduledEventContent } from "./events.js";
19
- /**
20
- * Fields `/tasks set` can edit directly.
21
- *
22
- * Deliberately a small, flat set: the ones a user already knows they want to change (when it
23
- * should wake, what it should do next, how much rope it has). Everything structural — status
24
- * transitions and verification — stays with `task_update`/`task_close`/`task_verify`, whose state
25
- * machine those fields belong to. The value is the rest of the line, so it may contain spaces.
26
- */
27
- const SETTABLE_TASK_FIELDS = ["wake", "next", "deadline"];
10
+ import { hasTaskSteer, queueTaskSteer } from "../tasks/steer.js";
11
+ import { openCycle, pauseTask as pauseTaskDocument, readStoredTask, redeemTicket, resumeTask as resumeTaskDocument, updateStoredTask, } from "../tasks/store.js";
12
+ import { describeTicket } from "../tasks/ticket.js";
28
13
  /** `/tasks show <id>` head-snippet cap; the full file is always readable at its own path. */
29
- const TASK_SHOW_MAX_CHARS = 4_000;
30
- // Broadcast (subcommand names, args, descriptions, examples) lives once in commands.ts's
14
+ const TASK_SHOW_MAX_CHARS = 2_400;
15
+ const SHOW_LOG_LINES = 8;
16
+ // Broadcast (subcommand names, args, descriptions, examples) lives once in commands/catalog.ts's
31
17
  // `BUILT_IN_COMMANDS` entry for "tasks"; this just renders it (review 2026-08-24 §3.1).
32
18
  function usage() {
33
19
  return renderSubcommandUsage("tasks");
34
20
  }
21
+ /** `+steps 20`, `+rounds 2`, `+usd 5` — the three grants `/tasks resume` accepts. */
22
+ function parseGrants(rest) {
23
+ const grants = {};
24
+ const pattern = /\+(steps|rounds|usd)\s+([0-9]+(?:\.[0-9]+)?)/g;
25
+ for (const match of rest.matchAll(pattern)) {
26
+ const value = Number(match[2]);
27
+ if (!Number.isFinite(value) || value <= 0)
28
+ continue;
29
+ grants[match[1]] = value;
30
+ }
31
+ return grants;
32
+ }
35
33
  /** Exported so `test/commands-subcommands.test.ts` can feed every broadcast example back through it. */
36
34
  export function parseTasksCommand(args) {
37
35
  const trimmed = args.trim();
@@ -42,513 +40,277 @@ export function parseTasksCommand(args) {
42
40
  throw new Error("用法:/tasks list");
43
41
  return { action: "list" };
44
42
  }
45
- if (action === "show") {
46
- const id = parts[1];
47
- if (!id || parts.length > 2)
48
- throw new Error("用法:/tasks show <id>");
49
- return { action: "show", id };
50
- }
51
- if (action === "archive") {
52
- if (parts.length > 1)
53
- throw new Error("用法:/tasks archive");
54
- return { action: "archive" };
55
- }
56
- if (action === "doctor") {
43
+ if (action === "archive" || action === "doctor") {
57
44
  if (parts.length > 1)
58
- throw new Error("用法:/tasks doctor");
59
- return { action: "doctor" };
45
+ throw new Error(`用法:/tasks ${action}`);
46
+ return { action };
60
47
  }
61
- if (action === "pause" || action === "resume") {
48
+ if (action === "show" || action === "pause" || action === "run") {
62
49
  const id = parts[1];
63
50
  if (!id || parts.length > 2)
64
51
  throw new Error(`用法:/tasks ${action} <id>`);
65
52
  return { action, id };
66
53
  }
67
- if (action === "run") {
54
+ if (action === "log") {
68
55
  const id = parts[1];
69
- if (!id || parts.length > 2)
70
- throw new Error("用法:/tasks run <id>");
71
- return { action: "run", id };
56
+ if (!id || parts.length > 3)
57
+ throw new Error("用法:/tasks log <id> [cycle]");
58
+ return { action: "log", id, cycle: parts[2] };
72
59
  }
73
- if (action === "set") {
74
- // Everything after the field name is the value, verbatim — a nextAction is a sentence.
75
- const match = /^set\s+(\S+)\s+(\S+)\s*([\s\S]*)$/.exec(trimmed);
76
- const field = match?.[2];
77
- if (!match || !field || !SETTABLE_TASK_FIELDS.includes(field)) {
78
- throw new Error(`用法:/tasks set <id> <${SETTABLE_TASK_FIELDS.join("|")}> <值>`);
79
- }
80
- return {
81
- action: "set",
82
- id: match[1],
83
- field: field,
84
- value: match[3].trim(),
85
- };
60
+ if (action === "resume") {
61
+ const id = parts[1];
62
+ if (!id)
63
+ throw new Error("用法:/tasks resume <id> [+steps N|+rounds N|+usd X]");
64
+ return { action: "resume", id, grants: parseGrants(parts.slice(2).join(" ")) };
65
+ }
66
+ if (action === "steer" || action === "reply") {
67
+ // Everything after the id is the message, verbatim — guidance is a sentence.
68
+ const match = /^(?:steer|reply)\s+(\S+)\s+([\s\S]+)$/.exec(trimmed);
69
+ if (!match)
70
+ throw new Error(`用法:/tasks ${action} <id> <内容>`);
71
+ return { action, id: match[1], text: match[2].trim() };
86
72
  }
87
73
  throw new Error(`未知的 /tasks 动作:${action}`);
88
74
  }
89
75
  function tasksDir(channelDir) {
90
76
  return join(channelDir, "tasks");
91
77
  }
92
- /** Resolve `<tasksDir>/[archive/]<id>.md`, rejecting any path that escapes the tasks dir. */
93
- function resolveTaskPath(dir, id, subdir) {
94
- const base = resolve(dir);
95
- const target = resolve(base, subdir ?? "", `${id}.md`);
96
- const expected = subdir ? join(base, subdir, `${id}.md`) : join(base, `${id}.md`);
97
- if (target !== expected || !target.startsWith(`${base}${sep}`)) {
98
- throw new Error(`Invalid task id: ${id}`);
99
- }
100
- return target;
101
- }
102
- function relativeWake(wakeMs, now) {
103
- if (wakeMs === undefined)
104
- return "无唤醒时间";
105
- const local = formatLocalTime(new Date(wakeMs));
106
- const diffMs = wakeMs - now;
78
+ /** Compact relative time, e.g. `12m` / `3h` / `2d`; `due` when already past. */
79
+ function relative(atMs, now) {
80
+ if (atMs === undefined || !Number.isFinite(atMs))
81
+ return undefined;
82
+ const diffMs = atMs - now;
107
83
  if (diffMs <= 0)
108
- return `${local}(已到期)`;
84
+ return "已到期";
109
85
  const minutes = Math.round(diffMs / 60000);
110
- const rel = minutes < 60
111
- ? `${minutes}分钟后`
112
- : minutes < 1440
113
- ? `${Math.round(minutes / 60)}小时后`
114
- : `${Math.round(minutes / 1440)}天后`;
115
- return `${local}(${rel})`;
116
- }
117
- function taskStatusLabel(status) {
118
- switch (status) {
119
- case "active":
120
- return "进行中";
121
- case "waiting":
122
- return "等待中";
123
- case "sleeping":
124
- return "睡眠中";
125
- default:
126
- return status;
127
- }
128
- }
129
- function verificationStatusLabel(status) {
130
- switch (status) {
131
- case "pending":
132
- return "待验收";
133
- case "passed":
134
- return "已通过";
135
- case "failed":
136
- return "未通过";
137
- default:
138
- return status;
139
- }
140
- }
141
- function eventDir(workspaceDir) {
142
- return join(workspaceDir, "events");
143
- }
144
- async function readArchivedTaskIds(channelDir) {
145
- const archiveDir = join(tasksDir(channelDir), "archive");
146
- const ids = new Set();
147
- if (!existsSync(archiveDir))
148
- return ids;
149
- for (const filename of await readdir(archiveDir)) {
150
- if (filename.endsWith(".md"))
151
- ids.add(filename.slice(0, -".md".length));
152
- }
153
- return ids;
154
- }
155
- async function readTaskEvents(workspaceDir, channelId) {
156
- const dir = eventDir(workspaceDir);
157
- if (!existsSync(dir))
158
- return [];
159
- const prefix = taskEventPrefix(channelId);
160
- const events = [];
161
- for (const filename of (await readdir(dir)).filter((name) => name.endsWith(".json")).sort()) {
162
- const name = filename.slice(0, -".json".length);
163
- if (!name.startsWith(prefix))
164
- continue;
165
- const split = parseTaskEventName(name, channelId);
166
- const info = { filename, name, ...(split ?? {}) };
167
- try {
168
- info.event = parseScheduledEventContent(await readFile(join(dir, filename), "utf-8"), filename);
169
- }
170
- catch (error) {
171
- info.error = errorMessage(error);
172
- }
173
- events.push(info);
174
- }
175
- return events;
86
+ if (minutes < 60)
87
+ return `${minutes}m`;
88
+ const hours = Math.round(minutes / 60);
89
+ if (hours < 24)
90
+ return `${hours}h`;
91
+ return `${Math.round(hours / 24)}d`;
176
92
  }
177
- function validWakeMs(entry) {
178
- const wake = entry.frontmatter.wake;
179
- if (!wake)
93
+ const STATE_LABEL = { open: "进行中", parked: "等待中", done: "已关闭" };
94
+ function cycleSummary(entry) {
95
+ const cycle = entry.fields.cycle;
96
+ if (!cycle)
180
97
  return undefined;
181
- return parseLocalTime(wake);
182
- }
183
- function issue(problem, nextStep) {
184
- return `- ${problem}(下一步:${nextStep})`;
98
+ const cost = cycle.usd > 0 ? `,$${cycle.usd.toFixed(2)}${cycle.usdEstimated ? "(含估算)" : ""}` : "";
99
+ return `${cycle.id}:${cycle.steps} 步 / ${cycle.rounds} 轮${cost}`;
185
100
  }
186
- async function readActiveTaskContent(channelDir, id) {
187
- try {
188
- return await readFile(join(tasksDir(channelDir), `${id}.md`), "utf-8");
189
- }
190
- catch {
101
+ function ticketSummary(entry, now) {
102
+ const ticket = entry.fields.ticket;
103
+ if (!ticket)
191
104
  return undefined;
192
- }
105
+ const by = relative(parseLocalTime(ticket.by), now);
106
+ return `${describeTicket(ticket)}${by ? `(兜底 ${by})` : ""}`;
107
+ }
108
+ function renderListLine(entry, channelDir, now) {
109
+ const bits = [`${entry.id} — ${entry.title}`, STATE_LABEL[entry.fields.state] ?? entry.fields.state];
110
+ if (entry.fields.paused)
111
+ bits.push(`已暂停(${entry.fields.paused.reason})`);
112
+ const ticket = ticketSummary(entry, now);
113
+ if (ticket)
114
+ bits.push(ticket);
115
+ if (entry.plan)
116
+ bits.push(`plan ${entry.plan.done}/${entry.plan.total}`);
117
+ const cycle = cycleSummary(entry);
118
+ if (cycle)
119
+ bits.push(cycle);
120
+ if (hasTaskSteer(channelDir, entry.id))
121
+ bits.push("有待处理的指示");
122
+ if (!entry.readable)
123
+ bits.push("⚠ frontmatter 不可读");
124
+ return `- ${bits.join(" · ")}`;
193
125
  }
194
126
  async function listTasks(channelDir) {
195
- const dir = tasksDir(channelDir);
196
127
  const now = Date.now();
197
- const entries = (await readActiveTasks(dir, now)).filter((entry) => !entry.frontmatter.archiveOutcome);
128
+ const entries = (await readActiveTasks(tasksDir(channelDir), now)).filter((entry) => !entry.fields.outcome);
198
129
  if (entries.length === 0) {
199
- return "**任务**\n\n暂无进行中的任务。用 `/tasks archive` 查看已归档任务。";
130
+ return "暂无进行中的任务。\n让 Agent 用 task_create 建立一个长程任务后再回来查看。";
200
131
  }
201
- const blocks = entries.map((entry) => {
202
- if (!entry.frontmatter.readable) {
203
- return `**${entry.id}** — ${entry.title}\n- ⚠ frontmatter 无法读取,status/wake 不可信`;
204
- }
205
- const status = entry.frontmatter.status ?? "active";
206
- const lines = [
207
- `**${entry.id}** — ${entry.title}`,
208
- `- 状态:${taskStatusLabel(status)} · 下次唤醒 ${relativeWake(entry.wakeMs, now)}`,
209
- ];
210
- const control = entry.frontmatter.control;
211
- if (control) {
212
- if (control.verification.required)
213
- lines.push(`- 验收:需要验收,${verificationStatusLabel(control.verification.status)}`);
214
- if (control.waitingFor)
215
- lines.push(`- 等待:${control.waitingFor}`);
216
- if (control.stop)
217
- lines.push(`- 已停用:${control.stop.by} — ${control.stop.reason}`);
218
- if (control.deadline)
219
- lines.push(`- 截止:${control.deadline}`);
220
- if (control.nextAction)
221
- lines.push(`- 下一步:${control.nextAction}`);
222
- if (control.cycleId)
223
- lines.push(`- ${status === "sleeping" ? "上一周期" : "当前周期"}:${control.cycleId}`);
224
- }
225
- if (entry.frontmatter.enabled === false)
226
- lines.push("- 已停用(enabled: false)");
227
- if (entry.frontmatter.schedule) {
228
- lines.push(`- 调度时区:${Intl.DateTimeFormat().resolvedOptions().timeZone}(本机)`);
229
- }
230
- return lines.join("\n");
231
- });
232
- const footer = "详情 `/tasks show <id>`,体检 `/tasks doctor`";
233
- const body = `**任务** · ${entries.length} 个进行中\n\n${blocks.join("\n\n")}\n\n${footer}`;
234
- return capReply(body, { nextStepHint: "用 `/tasks show <id>` 查看单个任务的完整状态" }).text;
132
+ return [`**任务(${entries.length})**`, ...entries.map((entry) => renderListLine(entry, channelDir, now))].join("\n");
235
133
  }
236
- export async function pauseTask(options, idInput) {
134
+ async function showTask(channelDir, idInput) {
237
135
  const id = normalizeTaskId(idInput);
238
- return withTaskMutation(options.channelDir, id, () => pauseTaskLocked(options, id));
136
+ const document = (await readStoredTask(channelDir, id, true)) ?? undefined;
137
+ if (!document)
138
+ return `未找到任务 \`${id}\`。\n用 /tasks list 查看进行中的任务,或 /tasks archive 查看已归档的。`;
139
+ const now = Date.now();
140
+ const entry = (await readActiveTasks(tasksDir(channelDir), now)).find((candidate) => candidate.id === id);
141
+ const head = [`**任务 ${id}**`];
142
+ head.push(`- 状态:${STATE_LABEL[document.fields.state] ?? document.fields.state}`);
143
+ if (document.fields.paused)
144
+ head.push(`- 已暂停(${document.fields.paused.by}):${document.fields.paused.reason}`);
145
+ if (document.fields.ticket) {
146
+ const by = relative(parseLocalTime(document.fields.ticket.by), now);
147
+ head.push(`- 等待:${describeTicket(document.fields.ticket)}${by ? `(兜底 ${by})` : ""}`);
148
+ }
149
+ if (document.fields.schedule)
150
+ head.push(`- 周期:${document.fields.schedule}`);
151
+ const cycle = entry ? cycleSummary(entry) : undefined;
152
+ if (cycle)
153
+ head.push(`- 本周期:${cycle}`);
154
+ if (document.fields.verify === "required")
155
+ head.push("- 需要独立验收");
156
+ const rounds = await readTaskLog(channelDir, id, { cycle: document.fields.cycle?.id, kinds: ["round"] });
157
+ if (rounds.length > 0) {
158
+ const verdicts = rounds.map((record) => (record.kind === "round" ? record.verdict : "")).join(" → ");
159
+ head.push(`- 返工:${rounds.length} 轮(${verdicts})`);
160
+ }
161
+ const log = await readTaskLog(channelDir, id, { limit: SHOW_LOG_LINES });
162
+ const logLines = log.length > 0 ? ["", `**最近 ${log.length} 条日志**`, ...log.map(renderTaskLogLine)] : [];
163
+ const body = clipText(document.body.trim(), TASK_SHOW_MAX_CHARS);
164
+ return [...head, ...logLines, "", "**契约**", body, "", `完整日志:/tasks log ${id}`].join("\n");
239
165
  }
240
- async function pauseTaskLocked(options, id) {
241
- const task = await readStoredTask(options.channelDir, id);
242
- if (!task)
243
- return `找不到任务:${id}`;
244
- const from = normalizeStoredStatus(task.fields.status);
245
- try {
246
- resolveTaskTransition("pause", id, from);
247
- }
248
- catch (error) {
249
- return errorMessage(error);
166
+ async function listArchive(channelDir) {
167
+ const archiveDir = join(tasksDir(channelDir), "archive");
168
+ if (!existsSync(archiveDir))
169
+ return "暂无已归档任务。\n任务完成或取消后会出现在这里。";
170
+ const files = (await readdir(archiveDir)).filter((name) => name.endsWith(".md")).sort();
171
+ if (files.length === 0)
172
+ return "暂无已归档任务。\n任务完成或取消后会出现在这里。";
173
+ const lines = [];
174
+ for (const filename of files.slice(0, 20)) {
175
+ const id = filename.slice(0, -".md".length);
176
+ const document = await readStoredTask(channelDir, id, true).catch(() => undefined);
177
+ lines.push(`- ${id}${document?.fields.outcome ? ` · ${document.fields.outcome}` : ""}${document?.fields.closedAt ? ` · ${document.fields.closedAt}` : ""}`);
250
178
  }
251
- if (task.fields.enabled === false)
252
- return `任务 ${id} 已停用。需要继续时用 /tasks resume ${id}。`;
253
- task.fields.enabled = false;
254
- const control = task.fields.control ?? createDefaultTaskControl();
255
- control.stop = { by: "user", reason: "Disabled by /tasks pause.", at: formatLocalTime() };
256
- task.fields.control = control;
257
- await writeStoredTask(task);
258
- return `已停用任务 ${id}。当前阶段与 wake 已保留;需要继续时用 /tasks resume ${id}。`;
179
+ if (files.length > 20)
180
+ lines.push(`- (另有 ${files.length - 20} 个,见 tasks/archive/)`);
181
+ return [`**已归档任务(${files.length})**`, ...lines].join("\n");
259
182
  }
260
- export async function resumeTask(options, idInput) {
183
+ async function showTaskLog(channelDir, idInput, cycle) {
261
184
  const id = normalizeTaskId(idInput);
262
- const task = await readStoredTask(options.channelDir, id);
263
- if (!task)
264
- return `找不到任务:${id}`;
265
- const from = normalizeStoredStatus(task.fields.status);
266
- if (task.fields.enabled !== false)
267
- return `任务 ${id} 已启用。`;
268
- resolveTaskTransition("resume", id, from);
269
- task.fields.enabled = true;
270
- if (task.fields.control) {
271
- task.fields.control.stop = undefined;
272
- }
273
- await writeStoredTask(task);
274
- return `已重新启用任务 ${id},任务驱动器会按当前阶段与 wake 接上。`;
185
+ const records = await readTaskLog(channelDir, id, { cycle, limit: 30 });
186
+ if (records.length === 0)
187
+ return `任务 \`${id}\` 暂无循环日志${cycle ? `(周期 ${cycle})` : ""}。`;
188
+ return [`**任务 ${id} 日志(${records.length} 条)**`, ...records.map(renderTaskLogLine)].join("\n");
275
189
  }
276
- /**
277
- * Edit one task field directly.
278
- *
279
- * The alternative — telling the model "change wake to tomorrow 9am" — costs a whole turn and its
280
- * tokens to reach the same one-line write. Validation is not re-implemented here: `wake` reuses
281
- * the shared local-time parser (accepting a local timestamp or a relative offset like `+2h`) and
282
- * everything else goes through `applyTaskControlPatch`, the same function `task_update` (no note) uses,
283
- * so the two entry points cannot drift apart.
284
- */
285
- async function setTaskField(options, idInput, field, value) {
190
+ export async function pauseTask(options, idInput) {
286
191
  const id = normalizeTaskId(idInput);
287
- const task = await readStoredTask(options.channelDir, id);
288
- if (!task)
289
- return `找不到任务:${id}`;
290
- if (field === "wake") {
291
- if (!value) {
292
- task.fields.wake = undefined;
293
- }
294
- else {
295
- const ms = parseWakeInput(value);
296
- if (ms === undefined) {
297
- return `wake "${value}" 不是合法的本地时间(如 2026-07-27T07:30:00+08:00)或相对时长(如 +2h)。`;
192
+ const document = await pauseTaskDocument(options.channelDir, id, {
193
+ by: "user",
194
+ reason: "用户通过 /tasks pause 暂停。",
195
+ });
196
+ if (!document)
197
+ return `未找到任务 \`${id}\`。`;
198
+ return `已暂停任务 \`${id}\`。当前阶段与等待票已保留;需要继续时用 /tasks resume ${id}。`;
199
+ }
200
+ export async function resumeTask(options, idInput, grants = {}) {
201
+ const id = normalizeTaskId(idInput);
202
+ const document = await resumeTaskDocument(options.channelDir, id);
203
+ if (!document)
204
+ return `未找到任务 \`${id}\`。`;
205
+ const granted = [];
206
+ if (Object.keys(grants).length > 0) {
207
+ await updateStoredTask(options.channelDir, id, (task) => {
208
+ const budget = { ...task.fields.budget };
209
+ for (const key of ["steps", "rounds", "usd"]) {
210
+ const extra = grants[key];
211
+ if (extra === undefined)
212
+ continue;
213
+ // A grant is *additional* headroom on top of whatever this cycle already spent, so
214
+ // resuming a task that hit its ceiling actually lets it run rather than re-stopping
215
+ // on the next step.
216
+ const spent = key === "steps"
217
+ ? task.fields.cycle?.steps
218
+ : key === "rounds"
219
+ ? task.fields.cycle?.rounds
220
+ : task.fields.cycle?.usd;
221
+ budget[key] = (spent ?? 0) + extra;
222
+ granted.push(`${key}+${extra}`);
298
223
  }
299
- task.fields.wake = formatLocalTime(new Date(ms));
300
- }
301
- }
302
- else {
303
- const control = task.fields.control ?? createDefaultTaskControl();
304
- try {
305
- task.fields.control = applyTaskControlPatch(control, field === "next" ? { nextAction: value } : { deadline: value });
306
- }
307
- catch (error) {
308
- return errorMessage(error);
309
- }
224
+ task.fields.budget = budget;
225
+ });
310
226
  }
311
- await writeStoredTask(task);
312
- return `已更新任务 ${id}:${field} = ${value || "(已清除)"}`;
227
+ return `已恢复任务 \`${id}\`${granted.length > 0 ? `(${granted.join(",")})` : ""}。`;
313
228
  }
314
229
  async function runTask(options, idInput) {
315
230
  const id = normalizeTaskId(idInput);
316
- const task = await readStoredTask(options.channelDir, id);
317
- if (!task)
318
- return `找不到任务:${id}`;
319
- const from = normalizeStoredStatus(task.fields.status);
320
- try {
321
- resolveTaskTransition("run", id, from);
322
- }
323
- catch (error) {
324
- return errorMessage(error);
325
- }
326
- const now = new Date();
327
- if (from === "sleeping") {
328
- if (!task.fields.schedule) {
329
- return `任务 ${id} 没有 schedule,不能从 sleeping 打开周期;如需新工作请创建新的 task id。`;
330
- }
331
- const opened = await openRecurringTaskCycle(options.channelDir, id, now, true);
231
+ const document = await readStoredTask(options.channelDir, id);
232
+ if (!document)
233
+ return `未找到任务 \`${id}\`。`;
234
+ if (document.fields.paused) {
235
+ return `任务 \`${id}\` 处于暂停状态;先用 /tasks resume ${id} 恢复,再 /tasks run。`;
236
+ }
237
+ if (!document.fields.cycle || document.fields.state === "parked") {
238
+ const opened = await openCycle(options.channelDir, id);
332
239
  if (!opened)
333
- return `任务 ${id} 无法打开新周期;先用 /tasks doctor 检查任务文件。`;
334
- }
335
- else {
336
- task.fields.status = "active";
337
- task.fields.wake = undefined;
338
- task.fields.enabled = true;
339
- if (task.fields.control) {
340
- task.fields.control.stop = undefined;
341
- task.fields.control.waitingFor = undefined;
342
- }
343
- await writeStoredTask(task);
240
+ return `任务 \`${id}\` 无法开启新周期(可能已归档)。`;
344
241
  }
345
- const enqueued = await options.dispatchTask?.(id);
346
- return enqueued
347
- ? `已把任务 ${id} 排入一次立即执行。`
348
- : `任务 ${id} 已就绪。启动钉钉守护进程可自动派发,或在本会话里直接发一条普通消息推进它。`;
242
+ const dispatched = await options.dispatchTask?.(id);
243
+ return dispatched === false
244
+ ? `任务 \`${id}\` 已就绪,但频道队列暂时无法接受;driver 会在下一轮重试。`
245
+ : `已立即唤醒任务 \`${id}\`。`;
349
246
  }
350
- async function showTask(channelDir, id) {
351
- const dir = tasksDir(channelDir);
352
- const taskId = normalizeTaskId(id);
353
- const activePath = resolveTaskPath(dir, taskId);
354
- const archivePath = resolveTaskPath(dir, taskId, "archive");
355
- const path = existsSync(activePath) ? activePath : existsSync(archivePath) ? archivePath : undefined;
356
- if (!path) {
357
- return `找不到任务:${taskId}`;
358
- }
359
- const location = path === archivePath ? "(已归档)" : "";
360
- const header = `**任务 ${taskId}**${location}`;
361
- const content = await readFile(path, "utf-8");
362
- // The file already lives on disk at `path`; a huge task file (long Plan/DoD history) is shown
363
- // as a head snippet with a pointer to that existing path instead of dumping it whole (review
364
- // 2026-08-24 §2.4/§3.2) — no separate copy needs to be written.
365
- if (content.length <= TASK_SHOW_MAX_CHARS) {
366
- return `${header}\n\n\`\`\`markdown\n${content}\n\`\`\``;
367
- }
368
- const lastNewline = content.lastIndexOf("\n", TASK_SHOW_MAX_CHARS);
369
- const head = content.slice(0, lastNewline > 0 ? lastNewline : TASK_SHOW_MAX_CHARS).trimEnd();
370
- return `${header}\n\n\`\`\`markdown\n${head}\n\`\`\`\n\n(内容过长已截断;完整内容见 \`${path}\`)`;
247
+ async function steerTask(options, idInput, text) {
248
+ const id = normalizeTaskId(idInput);
249
+ const document = await readStoredTask(options.channelDir, id);
250
+ if (!document)
251
+ return `未找到任务 \`${id}\`。`;
252
+ await queueTaskSteer(options.channelDir, id, text);
253
+ return `已把这条指示排给任务 \`${id}\` 的下一步(不会打断当前正在跑的一步)。`;
371
254
  }
372
- async function listArchive(channelDir) {
373
- const dir = join(tasksDir(channelDir), "archive");
374
- if (!existsSync(dir)) {
375
- return "**已归档任务**\n\n暂无已归档任务。";
376
- }
377
- const filenames = (await readdir(dir)).filter((filename) => filename.endsWith(".md")).sort();
378
- if (filenames.length === 0) {
379
- return "**已归档任务**\n\n暂无已归档任务。";
380
- }
381
- const blocks = [];
382
- for (const filename of filenames) {
383
- const id = filename.slice(0, -".md".length);
384
- try {
385
- const content = await readFile(join(dir, filename), "utf-8");
386
- blocks.push(`- ${id} — ${extractTaskTitle(content, id)}`);
387
- }
388
- catch {
389
- blocks.push(`- ${id}`);
390
- }
391
- }
392
- const body = `**已归档任务** · ${blocks.length} 个\n\n${blocks.join("\n")}`;
393
- return capReply(body, { nextStepHint: "用 `/tasks show <id>` 查看单个已归档任务" }).text;
255
+ /**
256
+ * Answer an `ask` ticket: the reply becomes the next step's first input, and redeeming the ticket
257
+ * is what actually reopens the task. A task parked on something else keeps its ticket — the reply
258
+ * is still queued, because the user's words should not be dropped just because the timing was off.
259
+ */
260
+ async function replyToTask(options, idInput, text) {
261
+ const id = normalizeTaskId(idInput);
262
+ const document = await readStoredTask(options.channelDir, id);
263
+ if (!document)
264
+ return `未找到任务 \`${id}\`。`;
265
+ await queueTaskSteer(options.channelDir, id, text, "用户回答");
266
+ const redeemed = await redeemTicket(options.channelDir, id, (ticket) => ticket.kind === "ask");
267
+ if (!redeemed) {
268
+ return `任务 \`${id}\` 当前并没有在等你的回答;内容已记下,下一步会看到。`;
269
+ }
270
+ if (options.dispatchTask)
271
+ await options.dispatchTask(id);
272
+ return `已回复任务 \`${id}\`,它会继续推进。`;
394
273
  }
274
+ function issue(problem, nextStep) {
275
+ return `- ${problem}(下一步:${nextStep})`;
276
+ }
277
+ /**
278
+ * `/tasks doctor`, deliberately shrunk (spec 051, D11).
279
+ *
280
+ * Most of what v3's doctor looked for — `enabled` disagreeing with `control.stop`, `active` with
281
+ * a future wake, an unparsable control block, a park with no recoverable source — cannot be
282
+ * produced any more: the frontmatter normalizer and `resolveTicket` reject those states at write
283
+ * time. What is left is what a *hand edit* can still create.
284
+ */
395
285
  async function doctor(options) {
396
- if (!options.workspaceDir || !options.channelId) {
397
- return "**任务体检**\n\n不可用:需要 workspaceDir 与 channelId。";
398
- }
399
286
  const now = Date.now();
400
287
  const entries = await readActiveTasks(tasksDir(options.channelDir), now);
401
- const activeIds = new Set(entries.map((entry) => entry.id));
402
- const archivedIds = await readArchivedTaskIds(options.channelDir);
403
- const events = await readTaskEvents(options.workspaceDir, options.channelId);
404
- const runningJobTaskIds = channelJobTaskIds(options.channelId);
405
- const runningDelegationTaskIds = channelDelegationTaskIds(options.channelId);
406
- const issues = [];
288
+ const problems = [];
407
289
  for (const entry of entries) {
408
- const status = entry.frontmatter.status ?? "active";
409
- if (!entry.frontmatter.readable) {
410
- issues.push(issue(`tasks/${entry.id}.md 的 frontmatter 无法读取,wake/status 不可信`, `修复 tasks/${entry.id}.md,让它以可读的 status/wake/schedule frontmatter 开头`));
411
- continue;
412
- }
413
- if (entry.frontmatter.controlReadable === false) {
414
- issues.push(issue(`tasks/${entry.id}.md 的 control 元数据无效;治理机制 fail-open,但无法生效`, `用 task_update(不带 note)或直接修复那一行 control JSON,然后再允许任务运行`));
290
+ if (!entry.readable) {
291
+ problems.push(issue(`${entry.id} 的 frontmatter 不可读`, `用 edit 修复 tasks/${entry.id}.md 的首部`));
415
292
  continue;
416
293
  }
417
- const control = entry.frontmatter.control;
418
- if (!control && entry.frontmatter.enabled === false) {
419
- issues.push(issue(`tasks/${entry.id}.md 已停用,但完全没有 control.stop 回执`, `用 task_update(不带 note)修复 control 元数据,确认可以继续后再 /tasks resume ${entry.id}`));
420
- }
421
- if (control) {
422
- const storedTask = await readStoredTask(options.channelDir, entry.id);
423
- const violation = taskBudgetViolation(control, now, status);
424
- if (violation) {
425
- issues.push(issue(`tasks/${entry.id}.md 超出了它的 control 限额:${violation}`, `检查这个任务,明确提高 budget/deadline 或取消它;否则 driver 会升级处理`));
426
- }
427
- if (status !== "sleeping" && control.verification.status === "passed") {
428
- const verificationRun = control.verification.runId && options.channelId
429
- ? getSubAgentRunManager(options.channelId).get(control.verification.runId)
430
- : undefined;
431
- const attestationOk = control.verification.runId
432
- ? await readVerificationAttestation(options.channelDir, control.verification.runId, {
433
- trustedWorkingDirectory: verificationRun?.workingDirectory,
434
- })
435
- .then((attestation) => attestation.taskId === entry.id &&
436
- attestation.verdict === "pass" &&
437
- (!storedTask || attestation.bodyHash === taskBodyHash(storedTask.body)))
438
- .catch(() => false)
439
- : false;
440
- if (!attestationOk) {
441
- issues.push(issue(`tasks/${entry.id}.md 记录了一次独立 PASS,但磁盘上没有匹配且新鲜的验证 attestation`, `跑一次新的 purpose=verify 子代理,并用 task_verify 导入它的 attestation 后再完成`));
442
- }
443
- }
444
- if (entry.frontmatter.enabled === false && !control.stop) {
445
- issues.push(issue(`tasks/${entry.id}.md 已停用,但 control 里没有 stop 回执`, `先弄清是谁停用的,再 /tasks resume ${entry.id};或者用 task_update(不带 note)写一条合法的 stop 记录`));
446
- }
447
- if (entry.frontmatter.enabled !== false && control.stop) {
448
- issues.push(issue(`tasks/${entry.id}.md 有 stop 回执,但 enabled 是 true`, `跑 /tasks resume ${entry.id} 清掉过期的 stop 回执,或者显式停用这个任务`));
449
- }
450
- }
451
- const recurring = Boolean(entry.frontmatter.schedule);
452
- if (status === "sleeping" && !recurring) {
453
- issues.push(issue(`tasks/${entry.id}.md 处于 sleeping,但没有 recurring schedule`, `一次性任务用 task_close outcome=complete/cancel 结束;要保留 sleeping 需要先加一个合法的 schedule`));
454
- }
455
- if (recurring) {
456
- try {
457
- validateTaskSchedule(entry.frontmatter.schedule);
458
- }
459
- catch (error) {
460
- issues.push(issue(`tasks/${entry.id}.md 的 schedule 无效:${errorMessage(error)}`, `修复或清空 ${entry.id} 的 schedule;修复前 driver 会让这个任务保持停用`));
461
- }
462
- if (status === "sleeping" && !entry.frontmatter.wake) {
463
- issues.push(issue(`tasks/${entry.id}.md 处于 sleeping,但没有 wake`, `修复 schedule 和 wake,确认无误后 /tasks resume ${entry.id}`));
464
- }
465
- }
466
- if (status === "active" &&
467
- entry.frontmatter.wake &&
468
- validWakeMs(entry) !== undefined &&
469
- validWakeMs(entry) > now) {
470
- issues.push(issue(`tasks/${entry.id}.md 处于 active,但它的 wake 在未来`, `用 task_update 把它改成 waiting 且 waitingFor=time,或者清空 wake 让它现在继续`));
294
+ if (entry.legacy) {
295
+ problems.push(issue(`${entry.id} 仍是 v3 契约`, "重启一次让迁移器升级它,或用 edit 手动改写 frontmatter"));
471
296
  }
472
- if (recurringTaskMissedOccurrence({ status, schedule: entry.frontmatter.schedule, control }, new Date(now))) {
473
- issues.push(issue(`tasks/${entry.id}.md 有一个已过下次 recurring 时点、仍处于 ${status} 的周期,且没有并行开启新周期`, `完成、跳过或取消 ${entry.id} 当前周期,之后让 driver 计算下一次时点`));
297
+ if (entry.fields.state === "parked" && !entry.fields.ticket) {
298
+ problems.push(issue(`${entry.id} 停泊但没有等待票`, `用 /tasks run ${entry.id} 重新开始,或让 Agent 重新停泊`));
474
299
  }
475
- const content = await readActiveTaskContent(options.channelDir, entry.id);
476
- if (content === undefined) {
477
- issues.push(issue(`tasks/${entry.id}.md 在体检时读取失败`, `手动打开 tasks/${entry.id}.md,修复权限或文件内容`));
300
+ if (entry.expired && !entry.fields.paused) {
301
+ problems.push(issue(`${entry.id} 的等待票已过兜底时限`, "driver 会在下一轮重开或通知;若一直没有,检查 daemon 是否在跑"));
478
302
  }
479
- else {
480
- const missing = missingStandardTaskSections(content);
481
- if (missing.length > 0) {
482
- issues.push(issue(`tasks/${entry.id}.md 缺少标准分节:${missing.join(", ")}`, `让 agent 把 tasks/${entry.id}.md 规范化成标准任务骨架`));
483
- }
484
- // spec 037, D4: two deterministic, zero-LLM-cost drift checks between a Plan and its
485
- // DoD — the first real consumer of "is the plan still pointed at the goal?".
486
- if (entry.plan) {
487
- const dodCount = countTaskDodItems(content);
488
- const invalidRefs = entry.plan.steps.flatMap((step) => step.dodRefs.filter((ref) => ref < 1 || ref > dodCount).map((ref) => `${step.id}→dod:${ref}`));
489
- if (invalidRefs.length > 0) {
490
- issues.push(issue(`tasks/${entry.id}.md 的 Plan 引用了不存在的 DoD 项:${invalidRefs.join(", ")}`, `修正 Plan 里的 "→ dod:N" 引用;如果 DoD 列表变了就重新编号`));
491
- }
492
- const covered = new Set(entry.plan.steps.filter((step) => step.status !== "dropped").flatMap((step) => step.dodRefs));
493
- const uncovered = Array.from({ length: dodCount }, (_, index) => index + 1).filter((dodIndex) => !covered.has(dodIndex));
494
- if (dodCount > 0 && uncovered.length > 0) {
495
- issues.push(issue(`tasks/${entry.id}.md 有 DoD 项没有 Plan 步骤覆盖:dod:${uncovered.join(",")}`, `给某个 Plan 步骤加上或更新 "→ dod:${uncovered[0]}" 引用,或者确认这些 DoD 项确实不需要专门的步骤`));
496
- }
497
- }
498
- }
499
- // A waiting task resumes only via a real durable source: a valid wake (the driver's timed
500
- // reactivation) or an actually-running background job/delegation recorded against this
501
- // id — never by what `waitingFor` merely claims, which is model-written display text and
502
- // no longer gates anything. With neither, resumption is entirely up to the user —
503
- // legitimate when waiting on an answer, and indistinguishable, on disk, from a task
504
- // everyone has forgotten. Report the fact and name every way out.
505
- if (status === "waiting") {
506
- const hasDurableWake = Boolean(entry.frontmatter.wake) && validWakeMs(entry) !== undefined;
507
- const hasRunningSource = runningJobTaskIds.has(entry.id) || runningDelegationTaskIds.has(entry.id);
508
- if (!hasDurableWake && !hasRunningSource) {
509
- issues.push(issue(`tasks/${entry.id}.md 处于 waiting,且没有可靠的恢复方式(没有合法 wake,也没有记录在案的运行中 job/委派)`, `它只能靠你回复、跑 /tasks run ${entry.id},或者用 /tasks set ${entry.id} wake <本地时间或 +2h> 给它一个 wake 才能恢复;如果等待的东西已经不存在了就取消它`));
510
- }
303
+ if (entry.fields.schedule && !entry.fields.cycle) {
304
+ problems.push(issue(`${entry.id} 有 schedule 但没有周期记录`, `用 /tasks run ${entry.id} 开启第一个周期`));
511
305
  }
512
- if (entry.frontmatter.wake && validWakeMs(entry) === undefined) {
513
- issues.push(issue(`tasks/${entry.id}.md 的 wake 值无效(${entry.frontmatter.wake});原生 driver 会把它当成已到期处理`, `用 task_update 把 wake 换成合法本地时间,或者清空它让任务直接继续`));
306
+ const until = entry.fields.budget?.until ? parseLocalTime(entry.fields.budget.until) : undefined;
307
+ if (until !== undefined && until < now && !entry.fields.paused) {
308
+ problems.push(issue(`${entry.id} 已超过 budget.until`, `用 task_update 调整期限,或 /tasks pause ${entry.id}`));
514
309
  }
515
- // A recurring task's wake should always be an occurrence of its own schedule. A wake that
516
- // isn't — a stale value left over from a since-changed cron, or a hand-typed local↔UTC
517
- // slip — silently misses the intended cadence: this is exactly how a production wake got
518
- // left pointing at a day the cron never fires on (spec 037).
519
- const schedule = entry.frontmatter.schedule;
520
- if (recurring && schedule && entry.frontmatter.wake) {
521
- const wakeMs = validWakeMs(entry);
522
- if (wakeMs !== undefined) {
523
- const priorOccurrence = nextTaskWake(schedule, new Date(wakeMs - 1));
524
- if (priorOccurrence?.getTime() !== wakeMs) {
525
- issues.push(issue(`tasks/${entry.id}.md 的 wake(${formatLocalTime(new Date(wakeMs))})不是它 schedule "${schedule}" 的一个合法时点`, `跑 task_update schedule="${schedule}"(不变)用 cron 重新计算 wake,或者手动明确设置 wake`));
526
- }
527
- }
528
- }
529
- }
530
- for (const event of events) {
531
- if (!event.id || !event.use) {
532
- issues.push(issue(`events/${event.filename} 不符合 task.<channelId>.<taskId>.<use>.json 命名`, "把这个事件改名为任务专用命名约定,或者当作普通事件管理"));
533
- continue;
534
- }
535
- if (event.error) {
536
- issues.push(issue(`events/${event.filename} 无法解析:${event.error}`, `修复或删除 events/${event.filename};无效的任务专属事件不可信`));
537
- continue;
538
- }
539
- if (!activeIds.has(event.id) && !archivedIds.has(event.id)) {
540
- issues.push(issue(`events/${event.filename} 指向了不存在的任务 ${event.id}`, `删除 events/${event.filename};如果那个任务在概念上还存在,就重新创建 tasks/${event.id}.md`));
541
- continue;
542
- }
543
- if (archivedIds.has(event.id)) {
544
- issues.push(issue(`events/${event.filename} 指向了已归档任务 ${event.id};已关闭的任务不应该还有存活的事件`, `删除 events/${event.filename};已归档任务不应该唤醒 agent`));
545
- }
546
- }
547
- if (issues.length === 0) {
548
- return "**任务体检**\n\n未发现任务台账问题。";
549
310
  }
550
- const body = `**任务体检** · 发现 ${issues.length} 个问题\n\n${issues.join("\n")}`;
551
- return capReply(body, { nextStepHint: "先处理靠前的问题,再重新运行 `/tasks doctor`" }).text;
311
+ if (problems.length === 0)
312
+ return `**任务体检**\n- ${entries.length} 个任务,未发现问题。`;
313
+ return [`**任务体检(${problems.length} 项)**`, ...problems].join("\n");
552
314
  }
553
315
  export async function handleTasksCommand(options) {
554
316
  let command;
@@ -556,18 +318,16 @@ export async function handleTasksCommand(options) {
556
318
  command = parseTasksCommand(options.args);
557
319
  }
558
320
  catch (error) {
559
- const message = errorMessage(error);
560
- return `${message}\n\n${usage()}`;
321
+ return `${errorMessage(error)}\n\n${usage()}`;
561
322
  }
562
323
  try {
563
- if ("id" in command && command.id && command.action !== "show") {
324
+ if ("id" in command && command.id && command.action !== "show" && command.action !== "log") {
564
325
  return await withTaskMutation(options.channelDir, command.id, () => dispatchTasksCommand(options, command));
565
326
  }
566
327
  return await dispatchTasksCommand(options, command);
567
328
  }
568
329
  catch (error) {
569
- const message = errorMessage(error);
570
- return `执行 /tasks ${command.action} 失败:${message}`;
330
+ return `执行 /tasks ${command.action} 失败:${errorMessage(error)}`;
571
331
  }
572
332
  }
573
333
  async function dispatchTasksCommand(options, command) {
@@ -576,16 +336,20 @@ async function dispatchTasksCommand(options, command) {
576
336
  return await listTasks(options.channelDir);
577
337
  case "show":
578
338
  return await showTask(options.channelDir, command.id);
339
+ case "log":
340
+ return await showTaskLog(options.channelDir, command.id, command.cycle);
579
341
  case "archive":
580
342
  return await listArchive(options.channelDir);
581
343
  case "pause":
582
344
  return await pauseTask(options, command.id);
583
345
  case "resume":
584
- return await resumeTask(options, command.id);
346
+ return await resumeTask(options, command.id, command.grants);
585
347
  case "run":
586
348
  return await runTask(options, command.id);
587
- case "set":
588
- return await setTaskField(options, command.id, command.field, command.value);
349
+ case "steer":
350
+ return await steerTask(options, command.id, command.text);
351
+ case "reply":
352
+ return await replyToTask(options, command.id, command.text);
589
353
  case "doctor":
590
354
  return await doctor(options);
591
355
  }