@oyasmi/pipiclaw 0.9.2-beta.6 → 0.9.3-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (165) hide show
  1. package/README.en.md +250 -0
  2. package/README.md +2 -0
  3. package/dist/agent/channel-runner.d.ts +43 -2
  4. package/dist/agent/channel-runner.js +135 -75
  5. package/dist/agent/job-manager.d.ts +76 -21
  6. package/dist/agent/job-manager.js +447 -63
  7. package/dist/agent/maintenance-context.js +4 -5
  8. package/dist/agent/prompt/manifest.d.ts +0 -2
  9. package/dist/agent/prompt/manifest.js +2 -3
  10. package/dist/agent/prompt/sections.js +3 -3
  11. package/dist/agent/session-events.js +4 -8
  12. package/dist/agent/turn-prompt.d.ts +7 -7
  13. package/dist/agent/turn-prompt.js +6 -9
  14. package/dist/agent/types.d.ts +12 -0
  15. package/dist/agent/types.js +1 -0
  16. package/dist/channel/channel-context.d.ts +13 -0
  17. package/dist/channel/channel-context.js +21 -1
  18. package/dist/commands/catalog.js +47 -20
  19. package/dist/memory/commands.d.ts +8 -0
  20. package/dist/memory/commands.js +113 -148
  21. package/dist/memory/index-budget.d.ts +27 -0
  22. package/dist/memory/index-budget.js +99 -0
  23. package/dist/memory/journal.d.ts +20 -0
  24. package/dist/memory/journal.js +78 -0
  25. package/dist/memory/lifecycle.d.ts +9 -15
  26. package/dist/memory/lifecycle.js +55 -145
  27. package/dist/memory/maintenance-gates.d.ts +13 -47
  28. package/dist/memory/maintenance-gates.js +13 -92
  29. package/dist/memory/maintenance-state.d.ts +10 -16
  30. package/dist/memory/maintenance-state.js +12 -59
  31. package/dist/memory/maintenance-tuning.d.ts +7 -27
  32. package/dist/memory/maintenance-tuning.js +11 -28
  33. package/dist/memory/migrate.d.ts +15 -0
  34. package/dist/memory/migrate.js +364 -0
  35. package/dist/memory/reflect-job.d.ts +43 -0
  36. package/dist/memory/reflect-job.js +117 -0
  37. package/dist/memory/reflect.d.ts +52 -0
  38. package/dist/memory/reflect.js +313 -0
  39. package/dist/memory/render.d.ts +14 -0
  40. package/dist/memory/render.js +28 -0
  41. package/dist/memory/review-log.d.ts +2 -1
  42. package/dist/memory/scheduler.d.ts +2 -3
  43. package/dist/memory/scheduler.js +14 -49
  44. package/dist/memory/search.d.ts +35 -0
  45. package/dist/memory/search.js +297 -0
  46. package/dist/memory/session-search.js +1 -1
  47. package/dist/memory/store.d.ts +108 -0
  48. package/dist/memory/store.js +418 -0
  49. package/dist/memory/task-digest.d.ts +2 -2
  50. package/dist/memory/task-digest.js +29 -36
  51. package/dist/memory/tombstones.d.ts +0 -11
  52. package/dist/memory/tombstones.js +6 -37
  53. package/dist/playbooks/agent-delegation.md +4 -2
  54. package/dist/playbooks/background-jobs.md +1 -1
  55. package/dist/playbooks/event-scheduling.md +6 -2
  56. package/dist/playbooks/memory-and-learning.md +18 -11
  57. package/dist/playbooks/outbound-media.md +1 -1
  58. package/dist/playbooks/runtime-orientation.md +9 -8
  59. package/dist/playbooks/task-loop.md +88 -0
  60. package/dist/runtime/bootstrap.d.ts +3 -3
  61. package/dist/runtime/bootstrap.js +66 -41
  62. package/dist/runtime/events.d.ts +9 -0
  63. package/dist/runtime/events.js +43 -4
  64. package/dist/runtime/task-commands.d.ts +14 -15
  65. package/dist/runtime/task-commands.js +249 -485
  66. package/dist/runtime/task-driver.d.ts +41 -29
  67. package/dist/runtime/task-driver.js +170 -317
  68. package/dist/runtime/task-migration.d.ts +34 -30
  69. package/dist/runtime/task-migration.js +229 -183
  70. package/dist/runtime/task-wake.d.ts +6 -3
  71. package/dist/runtime/task-wake.js +26 -19
  72. package/dist/settings.d.ts +0 -29
  73. package/dist/settings.js +12 -35
  74. package/dist/shared/markdown-sections.d.ts +0 -1
  75. package/dist/shared/markdown-sections.js +0 -3
  76. package/dist/subagents/discovery.d.ts +2 -2
  77. package/dist/subagents/discovery.js +21 -10
  78. package/dist/subagents/external/progress-tail.js +6 -1
  79. package/dist/subagents/external/run.js +1 -0
  80. package/dist/subagents/runs.d.ts +19 -2
  81. package/dist/subagents/runs.js +73 -4
  82. package/dist/subagents/tool.d.ts +10 -8
  83. package/dist/subagents/tool.js +55 -94
  84. package/dist/tasks/brief.d.ts +17 -0
  85. package/dist/tasks/brief.js +57 -0
  86. package/dist/tasks/budget.d.ts +26 -0
  87. package/dist/tasks/budget.js +59 -0
  88. package/dist/tasks/cycle.d.ts +48 -0
  89. package/dist/tasks/cycle.js +94 -0
  90. package/dist/tasks/frontmatter.d.ts +73 -0
  91. package/dist/tasks/frontmatter.js +175 -0
  92. package/dist/tasks/ledger.d.ts +66 -106
  93. package/dist/tasks/ledger.js +90 -546
  94. package/dist/tasks/log.d.ts +88 -0
  95. package/dist/tasks/log.js +97 -0
  96. package/dist/tasks/rounds.d.ts +43 -0
  97. package/dist/tasks/rounds.js +57 -0
  98. package/dist/tasks/session-path.d.ts +9 -0
  99. package/dist/tasks/session-path.js +16 -0
  100. package/dist/tasks/steer.d.ts +8 -0
  101. package/dist/tasks/steer.js +79 -0
  102. package/dist/tasks/store.d.ts +60 -35
  103. package/dist/tasks/store.js +166 -107
  104. package/dist/tasks/ticket.d.ts +102 -0
  105. package/dist/tasks/ticket.js +209 -0
  106. package/dist/tasks/verification.d.ts +16 -0
  107. package/dist/tasks/verification.js +40 -1
  108. package/dist/tools/index.d.ts +13 -4
  109. package/dist/tools/index.js +5 -10
  110. package/dist/tools/memory-manage.d.ts +6 -16
  111. package/dist/tools/memory-manage.js +108 -129
  112. package/dist/tools/presentation.js +2 -1
  113. package/dist/tools/registry.d.ts +11 -2
  114. package/dist/tools/registry.js +17 -6
  115. package/dist/tools/subagent-manage.d.ts +0 -9
  116. package/dist/tools/subagent-manage.js +8 -17
  117. package/dist/tools/task-manage/create.js +2 -2
  118. package/dist/tools/task-manage/lifecycle.d.ts +9 -4
  119. package/dist/tools/task-manage/lifecycle.js +139 -187
  120. package/dist/tools/task-manage/log-view.d.ts +8 -0
  121. package/dist/tools/task-manage/log-view.js +24 -0
  122. package/dist/tools/task-manage/schema.d.ts +38 -14
  123. package/dist/tools/task-manage/schema.js +46 -27
  124. package/dist/tools/task-manage/shared.d.ts +24 -31
  125. package/dist/tools/task-manage/shared.js +103 -141
  126. package/dist/tools/task-manage/step-end.d.ts +11 -0
  127. package/dist/tools/task-manage/step-end.js +136 -0
  128. package/dist/tools/task-manage/types.d.ts +23 -32
  129. package/dist/tools/task-manage.d.ts +4 -3
  130. package/dist/tools/task-manage.js +30 -15
  131. package/dist/tools/tool-details.d.ts +1 -1
  132. package/dist/tui/app.js +0 -2
  133. package/package.json +1 -1
  134. package/dist/agent/effect-ledger.d.ts +0 -32
  135. package/dist/agent/effect-ledger.js +0 -89
  136. package/dist/memory/bootstrap.d.ts +0 -17
  137. package/dist/memory/bootstrap.js +0 -120
  138. package/dist/memory/candidates.d.ts +0 -26
  139. package/dist/memory/candidates.js +0 -202
  140. package/dist/memory/consolidation.d.ts +0 -54
  141. package/dist/memory/consolidation.js +0 -292
  142. package/dist/memory/extraction.d.ts +0 -54
  143. package/dist/memory/extraction.js +0 -240
  144. package/dist/memory/files.d.ts +0 -71
  145. package/dist/memory/files.js +0 -419
  146. package/dist/memory/maintenance-jobs.d.ts +0 -41
  147. package/dist/memory/maintenance-jobs.js +0 -265
  148. package/dist/memory/metadata.d.ts +0 -57
  149. package/dist/memory/metadata.js +0 -142
  150. package/dist/memory/probation.d.ts +0 -17
  151. package/dist/memory/probation.js +0 -44
  152. package/dist/memory/promotion.d.ts +0 -38
  153. package/dist/memory/promotion.js +0 -36
  154. package/dist/memory/recall.d.ts +0 -59
  155. package/dist/memory/recall.js +0 -746
  156. package/dist/memory/session.d.ts +0 -24
  157. package/dist/memory/session.js +0 -273
  158. package/dist/playbooks/task-driving.md +0 -92
  159. package/dist/playbooks/task-planning.md +0 -58
  160. package/dist/tasks/control.d.ts +0 -56
  161. package/dist/tasks/control.js +0 -169
  162. package/dist/tasks/transitions.d.ts +0 -16
  163. package/dist/tasks/transitions.js +0 -48
  164. package/dist/tools/task-manage/verification.d.ts +0 -19
  165. package/dist/tools/task-manage/verification.js +0 -91
@@ -1,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,169 @@
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 { hasPassingRound } from "../../tasks/rounds.js";
6
+ import { archiveTask, readStoredTask, writeStoredTask } from "../../tasks/store.js";
7
+ import { describeTicket, resolveTicket } from "../../tasks/ticket.js";
11
8
  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";
9
+ import { buildTicketContext, cleanupTaskEvents, describeTaskState, normalizeBudget, normalizeSchedule, renderCloseEvidence, requiredField, tasksDir, } from "./shared.js";
10
+ async function requireTask(options, id) {
11
+ const document = await readStoredTask(options.channelDir, id);
12
+ if (!document) {
13
+ throw new RecoverableToolError(`Task "${id}" does not exist; create it with task_create first.`);
14
+ }
15
+ return document;
16
+ }
14
17
  /**
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).
18
+ * `task_update` is metadata only (spec 051, D4): plan steps, cadence, budget, and whether a done
19
+ * needs an independent PASS. Progress notes are no longer written here — they belong to the loop
20
+ * log via `task_step_end`, which is the only writer that can also change what the task is waiting
21
+ * for. Keeping the two apart is what stops "checkpoint" from quietly becoming a state transition.
19
22
  */
20
23
  export async function updateTask(options, request) {
21
24
  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.`);
25
+ const document = await requireTask(options, id);
26
+ const changes = [];
27
+ if (request.planSteps?.length) {
28
+ const patched = applyTaskPlanPatch(document.body, request.planSteps);
29
+ document.body = patched.body;
30
+ if (patched.summary)
31
+ changes.push(patched.summary);
30
32
  }
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.`);
33
+ const schedule = normalizeSchedule(request.schedule);
34
+ if (schedule !== undefined) {
35
+ document.fields.schedule = schedule ?? undefined;
36
+ changes.push(schedule ? `schedule=${schedule}` : "schedule 已清除");
33
37
  }
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
- }
38
+ const budget = normalizeBudget(request.budget);
39
+ if (budget) {
40
+ document.fields.budget = { ...document.fields.budget, ...budget };
41
+ changes.push("budget 已更新");
41
42
  }
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;
48
- }
49
- else if (hasNote) {
50
- nextBody = appendCurrentCycleNote(body, request.note);
43
+ if (request.verificationRequired !== undefined) {
44
+ document.fields.verify = request.verificationRequired ? "required" : undefined;
45
+ changes.push(`verify=${request.verificationRequired ? "required" : "off"}`);
51
46
  }
52
- await writeFileAtomically(taskPath, renderTaskFile(nextFields, nextBody));
47
+ await writeStoredTask(document);
53
48
  return {
54
49
  action: "update",
55
50
  id,
56
- path: taskPath,
57
- status: nextFields.status,
58
- notice: hasNote
59
- ? `已记录任务 \`${id}\` 的进展(${describeTaskSchedule(nextFields)})。`
60
- : `已更新任务 \`${id}\`(${describeTaskSchedule(nextFields)})。`,
51
+ path: document.path,
52
+ state: document.fields.state,
53
+ notice: `任务 \`${id}\` 已更新(${changes.length > 0 ? changes.join(";") : "无字段变化"})。${describeTaskState(document.fields)}`,
61
54
  };
62
55
  }
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
- }
56
+ /**
57
+ * Close a task from the chat surface: `complete` archives it, `cancel` archives it as abandoned,
58
+ * `skip` closes the current recurring occurrence and parks on the next one. The loop's own
59
+ * `task_step_end outcome=done` shares the same close-out path.
60
+ */
61
+ export async function closeTask(options, request) {
62
+ const id = normalizeTaskId(request.id);
63
+ const document = await requireTask(options, id);
64
+ const cycleId = document.fields.cycle?.id ?? "-";
65
+ if (request.outcome === "complete") {
66
+ const unchecked = uncheckedTaskAcceptanceItems(document.body);
67
+ if (unchecked.length > 0) {
68
+ throw new RecoverableToolError(`Task "${id}" still has unmet acceptance items: ${unchecked.slice(0, 3).join("; ")}. Check them off with edit once the evidence holds.`);
91
69
  }
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 与测试结果。";
70
+ if (document.fields.verify === "required" &&
71
+ !(await hasPassingRound(options.channelDir, id, document.fields.cycle?.id))) {
72
+ throw new RecoverableToolError(`Task "${id}" requires independent verification; dispatch a purpose=verify sub-agent with taskId=${id} and let its PASS land before completing.`);
98
73
  }
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,
114
- };
115
- await writeFileAtomically(taskPath, renderTaskFile(sleepingFields, bodyWithEvidence));
116
- }
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,
74
+ const evidence = renderCloseEvidence(request);
75
+ document.body = writeLastResult(document.body, evidence);
76
+ await writeStoredTask(document);
77
+ await appendTaskLog(options.channelDir, id, {
78
+ cycle: cycleId,
79
+ kind: "close",
80
+ outcome: "done",
81
+ summary: requiredField(request.summary, "summary", "task_close outcome=complete"),
82
+ evidence: request.evidence,
83
+ residualRisk: request.residualRisk,
84
+ steps: document.fields.cycle?.steps ?? 0,
85
+ rounds: document.fields.cycle?.rounds ?? 0,
86
+ usd: document.fields.cycle?.usd ?? 0,
87
+ });
88
+ const { deleted } = await cleanupTaskEvents(options, id);
89
+ await archiveTask(options.channelDir, id, "completed");
90
+ return {
91
+ action: "close",
92
+ id,
93
+ archived: true,
94
+ deletedEvents: deleted,
95
+ notice: `任务 \`${id}\` 已完成并归档。`,
125
96
  };
126
- await writeFileAtomically(taskPath, renderTaskFile(archiveFields, bodyWithEvidence));
127
- finalPath = join(archiveDir, `${id}.md`);
128
- await rename(taskPath, finalPath);
129
- archived = true;
130
97
  }
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.`);
98
+ if (request.outcome === "cancel") {
99
+ const reason = requiredField(request.reason, "reason", "task_close outcome=cancel");
100
+ document.body = writeLastResult(document.body, `- 已取消:${reason}`);
101
+ await writeStoredTask(document);
102
+ await appendTaskLog(options.channelDir, id, {
103
+ cycle: cycleId,
104
+ kind: "close",
105
+ outcome: "cancelled",
106
+ summary: reason,
107
+ steps: document.fields.cycle?.steps ?? 0,
108
+ rounds: document.fields.cycle?.rounds ?? 0,
109
+ usd: document.fields.cycle?.usd ?? 0,
110
+ });
111
+ const { deleted } = await cleanupTaskEvents(options, id);
112
+ await archiveTask(options.channelDir, id, "cancelled");
113
+ return { action: "close", id, archived: true, deletedEvents: deleted, notice: `任务 \`${id}\` 已取消并归档。` };
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" };
115
+ // skip: recurring only — park on the next occurrence without faking completion evidence.
116
+ if (!document.fields.schedule) {
117
+ throw new RecoverableToolError(`Task "${id}" is one-shot; skip applies to a recurring occurrence. Use outcome=cancel to abandon it.`);
155
118
  }
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);
119
+ const reason = requiredField(request.reason, "reason", "task_close outcome=skip");
120
+ const context = await buildTicketContext(options, id, document.fields.schedule);
121
+ const ticket = resolveTicket({ kind: "schedule" }, context);
122
+ document.body = writeLastResult(document.body, renderCloseSummary({
123
+ cycleId,
124
+ outcome: "cancelled",
125
+ summary: `本次 occurrence 跳过:${reason}`,
126
+ steps: document.fields.cycle?.steps ?? 0,
127
+ rounds: document.fields.cycle?.rounds ?? 0,
128
+ usd: document.fields.cycle?.usd ?? 0,
129
+ usdEstimated: document.fields.cycle?.usdEstimated ?? false,
130
+ }));
131
+ document.fields.state = "parked";
132
+ document.fields.ticket = ticket;
133
+ await writeStoredTask(document);
134
+ await appendTaskLog(options.channelDir, id, {
135
+ cycle: cycleId,
136
+ kind: "close",
137
+ outcome: "cancelled",
138
+ summary: `skip: ${reason}`,
139
+ steps: document.fields.cycle?.steps ?? 0,
140
+ rounds: document.fields.cycle?.rounds ?? 0,
141
+ usd: document.fields.cycle?.usd ?? 0,
142
+ });
181
143
  return {
182
144
  action: "close",
183
145
  id,
184
- path: finalPath,
185
- status: undefined,
186
- archived: true,
187
- deletedEvents: deleted,
188
- notice: `任务 \`${id}\` 已取消并归档${deleted.length ? `,清理事件 ${deleted.join(", ")}` : ""}。`,
146
+ state: "parked",
147
+ notice: `任务 \`${id}\` 本周期已跳过,${describeTicket(ticket)}。`,
189
148
  };
190
149
  }
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
150
  export async function listTasks(options) {
203
- const entries = (await readActiveTasks(tasksDir(options))).filter((entry) => !entry.frontmatter.archiveOutcome);
151
+ const dir = tasksDir(options);
152
+ await mkdir(dir, { recursive: true });
153
+ const entries = await readActiveTasks(dir);
154
+ const tasks = entries.map((entry) => ({
155
+ id: entry.id,
156
+ title: entry.title,
157
+ state: entry.fields.state,
158
+ paused: Boolean(entry.fields.paused),
159
+ ticket: entry.fields.ticket ? describeTicket(entry.fields.ticket) : undefined,
160
+ cycle: entry.fields.cycle?.id,
161
+ steps: entry.fields.cycle?.steps,
162
+ rounds: entry.fields.cycle?.rounds,
163
+ }));
204
164
  return {
205
165
  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 目录任务。`,
166
+ tasks,
167
+ notice: tasks.length === 0 ? "暂无进行中的任务。" : `共 ${tasks.length} 个进行中的任务。`,
216
168
  };
217
169
  }
@@ -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
  }>;