@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
@@ -9,7 +9,7 @@ import { createReadTool } from "./read.js";
9
9
  import { createSendMediaTool } from "./send-media.js";
10
10
  import { createSessionSearchTool } from "./session-search.js";
11
11
  import { createSkillTool } from "./skill.js";
12
- import { createTaskCloseTool, createTaskCreateTool, createTaskListTool, createTaskUpdateTool, createTaskVerifyTool, } from "./task-manage.js";
12
+ import { createTaskCloseTool, createTaskCreateTool, createTaskListTool, createTaskLogTool, createTaskStepEndTool, createTaskUpdateTool, } from "./task-manage.js";
13
13
  import { withToolDetails } from "./tool-details.js";
14
14
  import { createWebFetchTool } from "./web-fetch.js";
15
15
  import { createWebSearchTool } from "./web-search.js";
@@ -32,9 +32,6 @@ function memoryToolOptions(ctx) {
32
32
  channelId: ctx.channelId,
33
33
  channelDir: ctx.channelDir,
34
34
  workspaceDir: ctx.workspaceDir,
35
- memoryCandidateStore: req(ctx.memoryCandidateStore, "memoryCandidateStore"),
36
- getCurrentModel: req(ctx.getCurrentModel, "getCurrentModel"),
37
- resolveApiKey: req(ctx.resolveApiKey, "resolveApiKey"),
38
35
  };
39
36
  }
40
37
  function webEnabled(ctx) {
@@ -210,14 +207,28 @@ export const TOOL_REGISTRY = [
210
207
  }),
211
208
  },
212
209
  {
213
- name: "task_verify",
210
+ name: "task_log",
214
211
  availableToSubagents: false,
215
212
  enabledBy: (ctx) => ctx.toolsConfig?.tools.tasks.enabled !== false,
216
- create: (ctx) => createTaskVerifyTool({
213
+ create: (ctx) => createTaskLogTool({
214
+ workspaceDir: ctx.workspaceDir,
215
+ channelDir: ctx.channelDir,
216
+ channelId: ctx.channelId,
217
+ }),
218
+ },
219
+ {
220
+ name: "task_step_end",
221
+ availableToSubagents: false,
222
+ // Only inside a task session: it is the loop's closing move, not a chat action.
223
+ enabledBy: (ctx) => ctx.toolsConfig?.tools.tasks.enabled !== false && ctx.taskLoop !== undefined,
224
+ create: (ctx) => createTaskStepEndTool({
217
225
  workspaceDir: ctx.workspaceDir,
218
226
  channelDir: ctx.channelDir,
219
227
  channelId: ctx.channelId,
220
228
  workingDirectory: ctx.securityContext.projectRoot,
229
+ taskId: ctx.taskLoop?.taskId,
230
+ cycleId: ctx.taskLoop?.cycleId,
231
+ getToolsUsed: ctx.getToolsUsed,
221
232
  }),
222
233
  },
223
234
  {
@@ -1,9 +1,6 @@
1
1
  import type { AgentTool } from "@earendil-works/pi-agent-core";
2
- import type { Api, Model } from "@earendil-works/pi-ai";
3
2
  import { Type } from "typebox";
4
- import type { MemoryCandidateStore } from "../memory/candidates.js";
5
3
  import type { SecurityConfig } from "../security/types.js";
6
- import type { PipiclawMemoryRecallSettings } from "../settings.js";
7
4
  import { type SubAgentDiscoveryResult } from "../subagents/discovery.js";
8
5
  declare const subagentListSchema: Type.TObject<{}>;
9
6
  declare const subagentRunSchema: Type.TObject<{
@@ -33,12 +30,6 @@ export interface SubAgentManageToolOptions {
33
30
  /** Needed only for `follow_up`: re-resolves the role's current config by name. */
34
31
  getSubAgentDiscovery?: () => SubAgentDiscoveryResult;
35
32
  securityConfig?: SecurityConfig;
36
- /** Spec 042 D7: `follow_up` builds its envelope through the same `buildContextualBlocks` the
37
- * initial dispatch uses — these three are what that function needs beyond `channelDir`/`workspaceDir`. */
38
- getCurrentModel?: () => Model<Api>;
39
- resolveApiKey?: (model: Model<Api>) => Promise<string>;
40
- getMemoryRecallSettings?: () => PipiclawMemoryRecallSettings;
41
- memoryCandidateStore?: MemoryCandidateStore;
42
33
  }
43
34
  export declare function createSubAgentListTool(options: SubAgentManageToolOptions): AgentTool<typeof subagentListSchema>;
44
35
  export declare function createSubAgentRunTool(options: SubAgentManageToolOptions): AgentTool<typeof subagentRunSchema>;
@@ -238,25 +238,16 @@ export function createSubAgentRunTool(options) {
238
238
  artifactDir,
239
239
  };
240
240
  // Spec 042 D7: the same envelope construction the initial dispatch uses — runtime context
241
- // (including this run's own artifact directory), paths/session/memory context blocks, and
242
- // (for a verify run) the verification protocol — not a hand-rolled "task + maybe verify
243
- // protocol" that left the external agent unaware of its own working/artifact directories.
244
- // `getCurrentModel`/`resolveApiKey` are only needed for the `memory: relevant` recall path
245
- // inside `buildContextualBlocks` — optional here so a caller that only ever exercises
246
- // list/cancel is not forced to wire an LLM-backed dependency it will never use. Absent
247
- // either, context blocks degrade to none rather than guessing at a model or key.
241
+ // (including this run's own artifact directory), paths/memory context blocks, and (for a
242
+ // verify run) the verification protocol — not a hand-rolled "task + maybe verify protocol"
243
+ // that left the external agent unaware of its own working/artifact directories.
248
244
  let launchResult;
249
245
  try {
250
- const contextualBlocks = options.getCurrentModel && options.resolveApiKey
251
- ? await buildContextualBlocks(task, role, {
252
- channelDir: options.channelDir,
253
- workspaceDir: options.workspaceDir,
254
- runtimeContext: { workspaceDir: options.workspaceDir, channelId: options.channelId },
255
- getMemoryRecallSettings: options.getMemoryRecallSettings,
256
- resolveApiKey: options.resolveApiKey,
257
- memoryCandidateStore: options.memoryCandidateStore,
258
- }, options.getCurrentModel())
259
- : [];
246
+ const contextualBlocks = await buildContextualBlocks(role, {
247
+ channelDir: options.channelDir,
248
+ workspaceDir: options.workspaceDir,
249
+ runtimeContext: { workspaceDir: options.workspaceDir, channelId: options.channelId },
250
+ });
260
251
  const envelopedTask = buildSubAgentTask(task, role, { workspaceDir: options.workspaceDir, channelId: options.channelId }, contextualBlocks, runContext);
261
252
  launchResult = await launchExternalRun({
262
253
  runId: newRunId,
@@ -26,7 +26,7 @@ export async function createTask(options, request) {
26
26
  action: "create",
27
27
  id,
28
28
  path: taskPath,
29
- status: fields.status,
30
- notice: `已创建任务 \`${id}\`(status: ${fields.status}${fields.wake ? `, 首次唤醒: ${fields.wake}` : ""})。`,
29
+ state: fields.state,
30
+ notice: `已创建任务 \`${id}\`(state: ${fields.state}${fields.schedule ? `, schedule: ${fields.schedule}` : ""})。`,
31
31
  };
32
32
  }
@@ -1,10 +1,15 @@
1
1
  import type { TaskCloseRequest, TaskManageResult, TaskManageToolOptions, TaskUpdateRequest } from "./types.js";
2
2
  /**
3
- * `task_update` merges the old `progress`/`set` actions into one, branching on whether `note` is
4
- * present (spec 046, D3.2): a note means "checkpoint an open cycle" (active/waiting only, and
5
- * never repairs a bad control line in the same call); no note means "metadata-only edit" (also
6
- * allowed on sleeping, and the only path that can repair an unparsable control line).
3
+ * `task_update` is metadata only (spec 051, D4): plan steps, cadence, budget, and whether a done
4
+ * needs an independent PASS. Progress notes are no longer written here — they belong to the loop
5
+ * log via `task_step_end`, which is the only writer that can also change what the task is waiting
6
+ * for. Keeping the two apart is what stops "checkpoint" from quietly becoming a state transition.
7
7
  */
8
8
  export declare function updateTask(options: TaskManageToolOptions, request: TaskUpdateRequest): Promise<TaskManageResult>;
9
+ /**
10
+ * Close a task from the chat surface: `complete` archives it, `cancel` archives it as abandoned,
11
+ * `skip` closes the current recurring occurrence and parks on the next one. The loop's own
12
+ * `task_step_end outcome=done` shares the same close-out path.
13
+ */
9
14
  export declare function closeTask(options: TaskManageToolOptions, request: TaskCloseRequest): Promise<TaskManageResult>;
10
15
  export declare function listTasks(options: TaskManageToolOptions): Promise<TaskManageResult>;
@@ -1,217 +1,165 @@
1
- import { mkdir, rename } from "node:fs/promises";
2
- import { join } from "node:path";
3
- import { writeFileAtomically } from "../../shared/atomic-file.js";
4
- import { formatLocalTime } from "../../shared/local-time.js";
5
- import { getSubAgentRunManager } from "../../subagents/runs.js";
6
- import { workspaceSubjectHash } from "../../tasks/artifact-subject.js";
7
- import { appendCurrentCycleNote, applyTaskPlanPatch, normalizeTaskId, readActiveTasks, uncheckedTaskAcceptanceItems, } from "../../tasks/ledger.js";
8
- import { taskBodyHash } from "../../tasks/store.js";
9
- import { normalizeStoredStatus, resolveTaskTransition } from "../../tasks/transitions.js";
10
- import { getVerificationSubjectHashOptions } from "../../tasks/verification.js";
1
+ import { mkdir } from "node:fs/promises";
2
+ import { renderCloseSummary, writeLastResult } from "../../tasks/cycle.js";
3
+ import { applyTaskPlanPatch, normalizeTaskId, readActiveTasks, uncheckedTaskAcceptanceItems, } from "../../tasks/ledger.js";
4
+ import { appendTaskLog } from "../../tasks/log.js";
5
+ import { archiveTask, readStoredTask, writeStoredTask } from "../../tasks/store.js";
6
+ import { describeTicket, resolveTicket } from "../../tasks/ticket.js";
11
7
  import { RecoverableToolError } from "../tool-details.js";
12
- import { appendCompletionEvidence, applySet, cleanupTaskEvents, describeTaskSchedule, markdownValue, readTaskDocument, renderTaskFile, requiredField, tasksDir, } from "./shared.js";
13
- import { assertVerificationAttestationMatches } from "./verification.js";
8
+ import { assertVerificationHoldsForClose, buildTicketContext, cleanupTaskEvents, describeTaskState, normalizeBudget, normalizeSchedule, renderCloseEvidence, requiredField, tasksDir, } from "./shared.js";
9
+ async function requireTask(options, id) {
10
+ const document = await readStoredTask(options.channelDir, id);
11
+ if (!document) {
12
+ throw new RecoverableToolError(`Task "${id}" does not exist; create it with task_create first.`);
13
+ }
14
+ return document;
15
+ }
14
16
  /**
15
- * `task_update` merges the old `progress`/`set` actions into one, branching on whether `note` is
16
- * present (spec 046, D3.2): a note means "checkpoint an open cycle" (active/waiting only, and
17
- * never repairs a bad control line in the same call); no note means "metadata-only edit" (also
18
- * allowed on sleeping, and the only path that can repair an unparsable control line).
17
+ * `task_update` is metadata only (spec 051, D4): plan steps, cadence, budget, and whether a done
18
+ * needs an independent PASS. Progress notes are no longer written here — they belong to the loop
19
+ * log via `task_step_end`, which is the only writer that can also change what the task is waiting
20
+ * for. Keeping the two apart is what stops "checkpoint" from quietly becoming a state transition.
19
21
  */
20
22
  export async function updateTask(options, request) {
21
23
  const id = normalizeTaskId(request.id);
22
- const hasNote = request.note !== undefined;
23
- const taskPath = join(tasksDir(options), `${id}.md`);
24
- const { fields, body } = await readTaskDocument(taskPath, id, !hasNote && request.control !== undefined);
25
- const from = normalizeStoredStatus(fields.status);
26
- resolveTaskTransition(hasNote ? "checkpoint" : "metadata", id, from, request.status);
27
- const nextFields = applySet(fields, request);
28
- if (nextFields.status === "sleeping" && !nextFields.schedule) {
29
- throw new RecoverableToolError(`Task "${id}" is one-shot; sleeping is valid only for recurring tasks.`);
30
- }
31
- if (hasNote && nextFields.status === "sleeping") {
32
- throw new RecoverableToolError(`Progress cannot open a recurring cycle; use /tasks run ${id} or wait for its wake.`);
24
+ const document = await requireTask(options, id);
25
+ const changes = [];
26
+ if (request.planSteps?.length) {
27
+ const patched = applyTaskPlanPatch(document.body, request.planSteps);
28
+ document.body = patched.body;
29
+ if (patched.summary)
30
+ changes.push(patched.summary);
33
31
  }
34
- if (hasNote && nextFields.control) {
35
- if (nextFields.status === "active") {
36
- nextFields.control.waitingFor = undefined;
37
- }
38
- else if (!nextFields.control.waitingFor) {
39
- nextFields.control.waitingFor = nextFields.wake ? "time" : "external-signal";
40
- }
32
+ const schedule = normalizeSchedule(request.schedule);
33
+ if (schedule !== undefined) {
34
+ document.fields.schedule = schedule ?? undefined;
35
+ changes.push(schedule ? `schedule=${schedule}` : "schedule 已清除");
41
36
  }
42
- let nextBody = body;
43
- if (request.planSteps?.length) {
44
- const patched = applyTaskPlanPatch(body, request.planSteps);
45
- nextBody = hasNote
46
- ? appendCurrentCycleNote(patched.body, patched.summary ? `${request.note} ${patched.summary}` : request.note)
47
- : patched.body;
37
+ const budget = normalizeBudget(request.budget);
38
+ if (budget) {
39
+ document.fields.budget = { ...document.fields.budget, ...budget };
40
+ changes.push("budget 已更新");
48
41
  }
49
- else if (hasNote) {
50
- nextBody = appendCurrentCycleNote(body, request.note);
42
+ if (request.verificationRequired !== undefined) {
43
+ document.fields.verify = request.verificationRequired ? "required" : undefined;
44
+ changes.push(`verify=${request.verificationRequired ? "required" : "off"}`);
51
45
  }
52
- await writeFileAtomically(taskPath, renderTaskFile(nextFields, nextBody));
46
+ await writeStoredTask(document);
53
47
  return {
54
48
  action: "update",
55
49
  id,
56
- path: taskPath,
57
- status: nextFields.status,
58
- notice: hasNote
59
- ? `已记录任务 \`${id}\` 的进展(${describeTaskSchedule(nextFields)})。`
60
- : `已更新任务 \`${id}\`(${describeTaskSchedule(nextFields)})。`,
50
+ path: document.path,
51
+ state: document.fields.state,
52
+ notice: `任务 \`${id}\` 已更新(${changes.length > 0 ? changes.join(";") : "无字段变化"})。${describeTaskState(document.fields)}`,
61
53
  };
62
54
  }
63
- async function closeAsComplete(options, id, request) {
64
- const dir = tasksDir(options);
65
- const taskPath = join(dir, `${id}.md`);
66
- const { fields, body } = await readTaskDocument(taskPath, id);
67
- resolveTaskTransition("complete", id, normalizeStoredStatus(fields.status));
68
- const uncheckedAcceptance = uncheckedTaskAcceptanceItems(body);
69
- if (uncheckedAcceptance.length > 0) {
70
- throw new RecoverableToolError(`Task "${id}" still has unchecked acceptance items: ${uncheckedAcceptance.join("; ")}. Check them with evidence before task_close.`);
71
- }
72
- let verificationNote = "";
73
- if (fields.control?.verification.required) {
74
- const verification = fields.control.verification;
75
- if (verification.status !== "passed" || !verification.runId) {
76
- throw new RecoverableToolError(`Task "${id}" requires an independent PASS. Dispatch a purpose=verify sub-agent, then task_verify with its run id.`);
77
- }
78
- // The attestation file is the sole authority — for the verdict, the body-hash freshness
79
- // check, and the artifact subject. The task Markdown is agent-writable and proves nothing.
80
- const trustedWorkingDirectory = getSubAgentRunManager(options.channelId).get(verification.runId)?.workingDirectory;
81
- const attestation = await assertVerificationAttestationMatches(options.channelDir, id, verification.runId, taskBodyHash(body), trustedWorkingDirectory);
82
- if (attestation.subjectHash) {
83
- const subjectDir = attestation.subjectDir ?? trustedWorkingDirectory ?? options.workingDirectory ?? process.cwd();
84
- const currentSubject = await workspaceSubjectHash(subjectDir, getVerificationSubjectHashOptions(attestation));
85
- if (!currentSubject) {
86
- throw new RecoverableToolError(`Task "${id}" has an independent PASS bound to ${subjectDir}, but that checkout cannot be read. Restore it or request verification again.`);
87
- }
88
- if (currentSubject !== attestation.subjectHash) {
89
- throw new RecoverableToolError(`Task "${id}" artifacts changed after its independent PASS; request verification again. If this is a legacy attestation without a base commit, a normal Git commit can also require re-verification.`);
90
- }
91
- }
92
- // advisory means runtime could not structurally prove the verifier left artifacts alone
93
- // (external harness, or bash left in an internal verifier's tool set) — surface it at the
94
- // one moment completion is actually decided, not just in a file nobody re-reads (review
95
- // 2026-08-23 §2.1).
96
- if (attestation.verificationStrength === "advisory") {
97
- verificationNote = " ⚠️ 验收结论为 advisory:runtime 无法证明验收者未改动产物,请自行抽查 diff 与测试结果。";
55
+ /**
56
+ * Close a task from the chat surface: `complete` archives it, `cancel` archives it as abandoned,
57
+ * `skip` closes the current recurring occurrence and parks on the next one. The loop's own
58
+ * `task_step_end outcome=done` shares the same close-out path.
59
+ */
60
+ export async function closeTask(options, request) {
61
+ const id = normalizeTaskId(request.id);
62
+ const document = await requireTask(options, id);
63
+ const cycleId = document.fields.cycle?.id ?? "-";
64
+ if (request.outcome === "complete") {
65
+ const unchecked = uncheckedTaskAcceptanceItems(document.body);
66
+ if (unchecked.length > 0) {
67
+ throw new RecoverableToolError(`Task "${id}" still has unmet acceptance items: ${unchecked.slice(0, 3).join("; ")}. Check them off with edit once the evidence holds.`);
98
68
  }
99
- }
100
- const bodyWithEvidence = appendCompletionEvidence(body, request);
101
- if (fields.control) {
102
- fields.control.waitingFor = undefined;
103
- }
104
- const recurring = Boolean(fields.schedule);
105
- const closedAt = formatLocalTime();
106
- let finalPath = taskPath;
107
- let archived = false;
108
- if (recurring) {
109
- const sleepingFields = {
110
- ...fields,
111
- status: "sleeping",
112
- enabled: true,
113
- wake: undefined,
69
+ await assertVerificationHoldsForClose(options, document, id);
70
+ const evidence = renderCloseEvidence(request);
71
+ document.body = writeLastResult(document.body, evidence);
72
+ await writeStoredTask(document);
73
+ await appendTaskLog(options.channelDir, id, {
74
+ cycle: cycleId,
75
+ kind: "close",
76
+ outcome: "done",
77
+ summary: requiredField(request.summary, "summary", "task_close outcome=complete"),
78
+ evidence: request.evidence,
79
+ residualRisk: request.residualRisk,
80
+ steps: document.fields.cycle?.steps ?? 0,
81
+ rounds: document.fields.cycle?.rounds ?? 0,
82
+ usd: document.fields.cycle?.usd ?? 0,
83
+ });
84
+ const { deleted } = await cleanupTaskEvents(options, id);
85
+ await archiveTask(options.channelDir, id, "completed");
86
+ return {
87
+ action: "close",
88
+ id,
89
+ archived: true,
90
+ deletedEvents: deleted,
91
+ notice: `任务 \`${id}\` 已完成并归档。`,
114
92
  };
115
- await writeFileAtomically(taskPath, renderTaskFile(sleepingFields, bodyWithEvidence));
116
93
  }
117
- else {
118
- const archiveDir = join(dir, "archive");
119
- await mkdir(archiveDir, { recursive: true });
120
- const archiveFields = {
121
- ...fields,
122
- outcome: "completed",
123
- closedAt,
124
- enabled: undefined,
125
- };
126
- await writeFileAtomically(taskPath, renderTaskFile(archiveFields, bodyWithEvidence));
127
- finalPath = join(archiveDir, `${id}.md`);
128
- await rename(taskPath, finalPath);
129
- archived = true;
94
+ if (request.outcome === "cancel") {
95
+ const reason = requiredField(request.reason, "reason", "task_close outcome=cancel");
96
+ document.body = writeLastResult(document.body, `- 已取消:${reason}`);
97
+ await writeStoredTask(document);
98
+ await appendTaskLog(options.channelDir, id, {
99
+ cycle: cycleId,
100
+ kind: "close",
101
+ outcome: "cancelled",
102
+ summary: reason,
103
+ steps: document.fields.cycle?.steps ?? 0,
104
+ rounds: document.fields.cycle?.rounds ?? 0,
105
+ usd: document.fields.cycle?.usd ?? 0,
106
+ });
107
+ const { deleted } = await cleanupTaskEvents(options, id);
108
+ await archiveTask(options.channelDir, id, "cancelled");
109
+ return { action: "close", id, archived: true, deletedEvents: deleted, notice: `任务 \`${id}\` 已取消并归档。` };
130
110
  }
131
- const { deleted } = await cleanupTaskEvents(options, id);
132
- const cleanup = deleted.length > 0 ? `,清理事件 ${deleted.join(", ")}` : "";
133
- return {
134
- action: "close",
135
- id,
136
- path: finalPath,
137
- status: recurring ? "sleeping" : undefined,
138
- archived,
139
- deletedEvents: deleted,
140
- notice: `任务 \`${id}\` 已完成(${archived ? "已归档" : "已进入 sleeping,等待下一 occurrence"}${cleanup})。${verificationNote}`,
141
- };
142
- }
143
- async function closeAsSkip(options, id, request) {
144
- const reason = requiredField(request.reason, "reason", "task_close outcome=skip");
145
- const taskPath = join(tasksDir(options), `${id}.md`);
146
- const { fields, body } = await readTaskDocument(taskPath, id);
147
- resolveTaskTransition("skip", id, normalizeStoredStatus(fields.status));
148
- if (!fields.schedule) {
149
- throw new RecoverableToolError(`Task "${id}" is not recurring; use task_close outcome=complete after satisfying its DoD, or outcome=cancel.`);
111
+ // skip: recurring only — park on the next occurrence without faking completion evidence.
112
+ if (!document.fields.schedule) {
113
+ throw new RecoverableToolError(`Task "${id}" is one-shot; skip applies to a recurring occurrence. Use outcome=cancel to abandon it.`);
150
114
  }
151
- const skippedBody = appendCurrentCycleNote(body, `Skipped: ${reason}`);
152
- if (fields.control) {
153
- fields.control.waitingFor = undefined;
154
- fields.control.verification = { required: fields.control.verification.required, status: "pending" };
155
- }
156
- await writeFileAtomically(taskPath, renderTaskFile({ ...fields, status: "sleeping", enabled: true, wake: undefined }, skippedBody));
157
- const { deleted } = await cleanupTaskEvents(options, id);
158
- return {
159
- action: "close",
160
- id,
161
- path: taskPath,
162
- status: "sleeping",
163
- archived: false,
164
- deletedEvents: deleted,
165
- notice: `任务 \`${id}\` 本周期已跳过并进入 sleeping,等待下一次计划唤醒;若无需通知用户,请回复 [SILENT]。`,
166
- };
167
- }
168
- async function closeAsCancel(options, id, request) {
169
- const reason = requiredField(request.reason, "reason", "task_close outcome=cancel");
170
- const dir = tasksDir(options);
171
- const taskPath = join(dir, `${id}.md`);
172
- const { fields, body } = await readTaskDocument(taskPath, id);
173
- resolveTaskTransition("cancel", id, normalizeStoredStatus(fields.status));
174
- const cancelledBody = `${body.replace(/\n+$/, "\n")}\n## Cancellation\n\n- Reason: ${markdownValue(reason)}\n`;
175
- const archiveDir = join(dir, "archive");
176
- await mkdir(archiveDir, { recursive: true });
177
- await writeFileAtomically(taskPath, renderTaskFile({ ...fields, outcome: "cancelled", closedAt: formatLocalTime(), enabled: undefined }, cancelledBody));
178
- const { deleted } = await cleanupTaskEvents(options, id);
179
- const finalPath = join(archiveDir, `${id}.md`);
180
- await rename(taskPath, finalPath);
115
+ const reason = requiredField(request.reason, "reason", "task_close outcome=skip");
116
+ const context = await buildTicketContext(options, id, document.fields.schedule);
117
+ const ticket = resolveTicket({ kind: "schedule" }, context);
118
+ document.body = writeLastResult(document.body, renderCloseSummary({
119
+ cycleId,
120
+ outcome: "cancelled",
121
+ summary: `本次 occurrence 跳过:${reason}`,
122
+ steps: document.fields.cycle?.steps ?? 0,
123
+ rounds: document.fields.cycle?.rounds ?? 0,
124
+ usd: document.fields.cycle?.usd ?? 0,
125
+ usdEstimated: document.fields.cycle?.usdEstimated ?? false,
126
+ }));
127
+ document.fields.state = "parked";
128
+ document.fields.ticket = ticket;
129
+ await writeStoredTask(document);
130
+ await appendTaskLog(options.channelDir, id, {
131
+ cycle: cycleId,
132
+ kind: "close",
133
+ outcome: "cancelled",
134
+ summary: `skip: ${reason}`,
135
+ steps: document.fields.cycle?.steps ?? 0,
136
+ rounds: document.fields.cycle?.rounds ?? 0,
137
+ usd: document.fields.cycle?.usd ?? 0,
138
+ });
181
139
  return {
182
140
  action: "close",
183
141
  id,
184
- path: finalPath,
185
- status: undefined,
186
- archived: true,
187
- deletedEvents: deleted,
188
- notice: `任务 \`${id}\` 已取消并归档${deleted.length ? `,清理事件 ${deleted.join(", ")}` : ""}。`,
142
+ state: "parked",
143
+ notice: `任务 \`${id}\` 本周期已跳过,${describeTicket(ticket)}。`,
189
144
  };
190
145
  }
191
- export async function closeTask(options, request) {
192
- const id = normalizeTaskId(request.id);
193
- switch (request.outcome) {
194
- case "complete":
195
- return closeAsComplete(options, id, request);
196
- case "skip":
197
- return closeAsSkip(options, id, request);
198
- case "cancel":
199
- return closeAsCancel(options, id, request);
200
- }
201
- }
202
146
  export async function listTasks(options) {
203
- const entries = (await readActiveTasks(tasksDir(options))).filter((entry) => !entry.frontmatter.archiveOutcome);
147
+ const dir = tasksDir(options);
148
+ await mkdir(dir, { recursive: true });
149
+ const entries = await readActiveTasks(dir);
150
+ const tasks = entries.map((entry) => ({
151
+ id: entry.id,
152
+ title: entry.title,
153
+ state: entry.fields.state,
154
+ paused: Boolean(entry.fields.paused),
155
+ ticket: entry.fields.ticket ? describeTicket(entry.fields.ticket) : undefined,
156
+ cycle: entry.fields.cycle?.id,
157
+ steps: entry.fields.cycle?.steps,
158
+ rounds: entry.fields.cycle?.rounds,
159
+ }));
204
160
  return {
205
161
  action: "list",
206
- tasks: entries.map((entry) => ({
207
- id: entry.id,
208
- title: entry.title,
209
- status: entry.frontmatter.readable ? (entry.frontmatter.status ?? "active") : "unreadable",
210
- enabled: entry.frontmatter.enabled,
211
- wake: entry.frontmatter.wake,
212
- actionable: entry.actionable,
213
- control: entry.frontmatter.control,
214
- })),
215
- notice: `台账共有 ${entries.length} 个 active 目录任务。`,
162
+ tasks,
163
+ notice: tasks.length === 0 ? "暂无进行中的任务。" : `共 ${tasks.length} 个进行中的任务。`,
216
164
  };
217
165
  }
@@ -0,0 +1,8 @@
1
+ import type { TaskLogRequest, TaskManageResult, TaskManageToolOptions } from "./types.js";
2
+ /**
3
+ * `task_log` — read the loop log (spec 051, D5).
4
+ *
5
+ * This is what makes the 4 KB contract affordable: the history the task file used to carry
6
+ * inline is still there, just addressed on demand instead of injected into every step.
7
+ */
8
+ export declare function readTaskLogTool(options: TaskManageToolOptions, request: TaskLogRequest): Promise<TaskManageResult>;
@@ -0,0 +1,24 @@
1
+ import { normalizeTaskId } from "../../tasks/ledger.js";
2
+ import { readTaskLog, renderTaskLogLine } from "../../tasks/log.js";
3
+ const DEFAULT_LIMIT = 20;
4
+ const MAX_LIMIT = 100;
5
+ /**
6
+ * `task_log` — read the loop log (spec 051, D5).
7
+ *
8
+ * This is what makes the 4 KB contract affordable: the history the task file used to carry
9
+ * inline is still there, just addressed on demand instead of injected into every step.
10
+ */
11
+ export async function readTaskLogTool(options, request) {
12
+ const id = normalizeTaskId(request.id);
13
+ const limit = Math.min(Math.max(1, Math.trunc(request.limit ?? DEFAULT_LIMIT)), MAX_LIMIT);
14
+ const records = await readTaskLog(options.channelDir, id, { cycle: request.cycle, limit });
15
+ const entries = records.map(renderTaskLogLine);
16
+ return {
17
+ action: "log",
18
+ id,
19
+ entries,
20
+ notice: entries.length === 0
21
+ ? `任务 \`${id}\` 暂无循环日志${request.cycle ? `(周期 ${request.cycle})` : ""}。`
22
+ : `任务 \`${id}\` 最近 ${entries.length} 条记录${request.cycle ? `(周期 ${request.cycle})` : ""}。`,
23
+ };
24
+ }
@@ -1,5 +1,4 @@
1
1
  import { Type } from "typebox";
2
- export declare const SETTABLE_STATUSES: readonly ["active", "waiting", "sleeping"];
3
2
  export declare const taskListSchema: Type.TObject<{}>;
4
3
  export declare const taskCreateSchema: Type.TObject<{
5
4
  id: Type.TString;
@@ -10,28 +9,31 @@ export declare const taskCreateSchema: Type.TObject<{
10
9
  manual: Type.TOptional<Type.TString>;
11
10
  verificationPlan: Type.TOptional<Type.TString>;
12
11
  verificationRequired: Type.TOptional<Type.TBoolean>;
13
- status: Type.TOptional<Type.TUnion<Type.TLiteral<"active" | "waiting" | "sleeping">[]>>;
14
- wake: Type.TOptional<Type.TString>;
15
12
  schedule: Type.TOptional<Type.TString>;
16
- deadline: Type.TOptional<Type.TString>;
13
+ budget: Type.TOptional<Type.TObject<{
14
+ steps: Type.TOptional<Type.TNumber>;
15
+ wallMin: Type.TOptional<Type.TNumber>;
16
+ usd: Type.TOptional<Type.TNumber>;
17
+ rounds: Type.TOptional<Type.TNumber>;
18
+ until: Type.TOptional<Type.TString>;
19
+ }>>;
17
20
  }>;
18
21
  export declare const taskUpdateSchema: Type.TObject<{
19
22
  id: Type.TString;
20
- note: Type.TOptional<Type.TString>;
21
23
  planSteps: Type.TOptional<Type.TArray<Type.TObject<{
22
24
  id: Type.TString;
23
25
  status: Type.TOptional<Type.TUnion<[Type.TLiteral<"todo">, Type.TLiteral<"done">, Type.TLiteral<"blocked">, Type.TLiteral<"dropped">]>>;
24
26
  text: Type.TOptional<Type.TString>;
25
27
  }>>>;
26
- status: Type.TOptional<Type.TUnion<Type.TLiteral<"active" | "waiting" | "sleeping">[]>>;
27
- wake: Type.TOptional<Type.TString>;
28
28
  schedule: Type.TOptional<Type.TString>;
29
- control: Type.TOptional<Type.TObject<{
30
- deadline: Type.TOptional<Type.TString>;
31
- nextAction: Type.TOptional<Type.TString>;
32
- waitingFor: Type.TOptional<Type.TUnion<[Type.TLiteral<"time">, Type.TLiteral<"user">, Type.TLiteral<"job">, Type.TLiteral<"external-signal">]>>;
33
- verificationRequired: Type.TOptional<Type.TBoolean>;
29
+ budget: Type.TOptional<Type.TObject<{
30
+ steps: Type.TOptional<Type.TNumber>;
31
+ wallMin: Type.TOptional<Type.TNumber>;
32
+ usd: Type.TOptional<Type.TNumber>;
33
+ rounds: Type.TOptional<Type.TNumber>;
34
+ until: Type.TOptional<Type.TString>;
34
35
  }>>;
36
+ verificationRequired: Type.TOptional<Type.TBoolean>;
35
37
  }>;
36
38
  export declare const taskCloseSchema: Type.TObject<{
37
39
  id: Type.TString;
@@ -41,7 +43,29 @@ export declare const taskCloseSchema: Type.TObject<{
41
43
  residualRisk: Type.TOptional<Type.TString>;
42
44
  reason: Type.TOptional<Type.TString>;
43
45
  }>;
44
- export declare const taskVerifySchema: Type.TObject<{
46
+ export declare const taskLogSchema: Type.TObject<{
45
47
  id: Type.TString;
46
- verifierRunId: Type.TString;
48
+ cycle: Type.TOptional<Type.TString>;
49
+ limit: Type.TOptional<Type.TNumber>;
50
+ }>;
51
+ export declare const taskStepEndSchema: Type.TObject<{
52
+ outcome: Type.TUnion<[Type.TLiteral<"continue">, Type.TLiteral<"park">, Type.TLiteral<"done">, Type.TLiteral<"blocked">]>;
53
+ note: Type.TString;
54
+ planSteps: Type.TOptional<Type.TArray<Type.TObject<{
55
+ id: Type.TString;
56
+ status: Type.TOptional<Type.TUnion<[Type.TLiteral<"todo">, Type.TLiteral<"done">, Type.TLiteral<"blocked">, Type.TLiteral<"dropped">]>>;
57
+ text: Type.TOptional<Type.TString>;
58
+ }>>>;
59
+ ticket: Type.TOptional<Type.TObject<{
60
+ kind: Type.TUnion<[Type.TLiteral<"time">, Type.TLiteral<"schedule">, Type.TLiteral<"run">, Type.TLiteral<"job">, Type.TLiteral<"ask">, Type.TLiteral<"signal">]>;
61
+ at: Type.TOptional<Type.TString>;
62
+ id: Type.TOptional<Type.TString>;
63
+ asked: Type.TOptional<Type.TString>;
64
+ event: Type.TOptional<Type.TString>;
65
+ }>>;
66
+ notify: Type.TOptional<Type.TString>;
67
+ summary: Type.TOptional<Type.TString>;
68
+ evidence: Type.TOptional<Type.TString>;
69
+ residualRisk: Type.TOptional<Type.TString>;
70
+ reason: Type.TOptional<Type.TString>;
47
71
  }>;