@oyasmi/pipiclaw 0.9.2 → 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,6 +1,4 @@
1
1
  import { Type } from "typebox";
2
- import { SETTABLE_TASK_STATUSES } from "../../tasks/transitions.js";
3
- export const SETTABLE_STATUSES = SETTABLE_TASK_STATUSES;
4
2
  const idField = Type.String({ description: "Task id (filename without .md)." });
5
3
  const planStepsField = Type.Optional(Type.Array(Type.Object({
6
4
  id: Type.String({ description: 'Plan step id, e.g. "P2"; new ids append a step.' }),
@@ -9,12 +7,35 @@ const planStepsField = Type.Optional(Type.Array(Type.Object({
9
7
  })),
10
8
  text: Type.Optional(Type.String({ description: "Step text; required when appending a new id." })),
11
9
  }), { description: "Update or append Plan steps by id." }));
12
- const wakeField = Type.Optional(Type.String({
13
- description: "Earliest-recheck time; empty string clears it. Local time e.g. 2026-07-27T07:30:00+08:00, or relative +2h/+45m/+3d.",
14
- }));
15
10
  const scheduleField = Type.Optional(Type.String({
16
11
  description: "Five-field cron cadence; makes this recurring. Empty string clears it. Min every 30 minutes.",
17
12
  }));
13
+ const budgetField = Type.Optional(Type.Object({
14
+ steps: Type.Optional(Type.Number({ description: "Max model steps in one cycle." })),
15
+ wallMin: Type.Optional(Type.Number({ description: "Max working minutes in one cycle." })),
16
+ usd: Type.Optional(Type.Number({ description: "Max attributable cost in one cycle." })),
17
+ rounds: Type.Optional(Type.Number({ description: "Max delegate→verify rework rounds in one cycle." })),
18
+ until: Type.Optional(Type.String({ description: "Hard local-time stop, e.g. 2026-09-06T18:00:00+08:00." })),
19
+ }, { description: "Per-task budget; omitted keys fall back to the runtime defaults." }));
20
+ /**
21
+ * The waiting ticket a park must carry (spec 051, D2). Every field the runtime cannot derive is
22
+ * here and nothing else: `by` is stamped by the runtime, never by the model, because a backstop
23
+ * the model can choose is a backstop it can choose not to have.
24
+ */
25
+ const ticketField = Type.Object({
26
+ kind: Type.Union([
27
+ Type.Literal("time"),
28
+ Type.Literal("schedule"),
29
+ Type.Literal("run"),
30
+ Type.Literal("job"),
31
+ Type.Literal("ask"),
32
+ Type.Literal("signal"),
33
+ ], { description: "What will wake this task." }),
34
+ at: Type.Optional(Type.String({ description: 'kind=time: when, e.g. "+2h" or a local timestamp.' })),
35
+ id: Type.Optional(Type.String({ description: "kind=run/job: the run or job id this task is waiting on." })),
36
+ asked: Type.Optional(Type.String({ description: "kind=ask: the question the user must answer." })),
37
+ event: Type.Optional(Type.String({ description: "kind=signal: the task-owned periodic event name." })),
38
+ }, { description: "Ticket describing what will resume this task." });
18
39
  export const taskListSchema = Type.Object({});
19
40
  export const taskCreateSchema = Type.Object({
20
41
  id: idField,
@@ -28,32 +49,16 @@ export const taskCreateSchema = Type.Object({
28
49
  })),
29
50
  manual: Type.Optional(Type.String({ description: "Initial operating steps or checklist." })),
30
51
  verificationPlan: Type.Optional(Type.String({ description: "Deterministic checks the verifier must perform." })),
31
- verificationRequired: Type.Optional(Type.Boolean({ description: "Whether complete requires a verifier attestation. Default false." })),
32
- status: Type.Optional(Type.Union(SETTABLE_STATUSES.map((status) => Type.Literal(status)), { description: "Initial status; default active." })),
33
- wake: wakeField,
52
+ verificationRequired: Type.Optional(Type.Boolean({ description: "Whether done requires an independent verifier PASS. Default false." })),
34
53
  schedule: scheduleField,
35
- deadline: Type.Optional(Type.String({ description: "Local time deadline, e.g. 2026-07-27T18:00:00+08:00." })),
36
- });
37
- const taskControlSchema = Type.Object({
38
- deadline: Type.Optional(Type.String({
39
- description: "Local time deadline, e.g. 2026-07-27T18:00:00+08:00; empty string clears it.",
40
- })),
41
- nextAction: Type.Optional(Type.String({ description: "Concrete next executable step; empty string clears it." })),
42
- waitingFor: Type.Optional(Type.Union([Type.Literal("time"), Type.Literal("user"), Type.Literal("job"), Type.Literal("external-signal")], {
43
- description: "Diagnostic recovery source; record-only.",
44
- })),
45
- verificationRequired: Type.Optional(Type.Boolean({ description: "Whether complete requires a verifier attestation. Default false." })),
54
+ budget: budgetField,
46
55
  });
47
56
  export const taskUpdateSchema = Type.Object({
48
57
  id: idField,
49
- note: Type.Optional(Type.String({
50
- description: "Current Cycle checkpoint — what changed, evidence, next step.",
51
- })),
52
58
  planSteps: planStepsField,
53
- status: Type.Optional(Type.Union(SETTABLE_STATUSES.map((status) => Type.Literal(status)), { description: "New status; use task_close for lifecycle close-out." })),
54
- wake: wakeField,
55
59
  schedule: scheduleField,
56
- control: Type.Optional(taskControlSchema),
60
+ budget: budgetField,
61
+ verificationRequired: Type.Optional(Type.Boolean({ description: "Whether done requires an independent verifier PASS." })),
57
62
  });
58
63
  export const taskCloseSchema = Type.Object({
59
64
  id: idField,
@@ -67,7 +72,21 @@ export const taskCloseSchema = Type.Object({
67
72
  residualRisk: Type.Optional(Type.String({ description: "Remaining risk or follow-up note; optional." })),
68
73
  reason: Type.Optional(Type.String({ description: "Why this occurrence was skipped or the task abandoned; required for skip/cancel." })),
69
74
  });
70
- export const taskVerifySchema = Type.Object({
75
+ export const taskLogSchema = Type.Object({
71
76
  id: idField,
72
- verifierRunId: Type.String({ description: "Run id returned by a purpose=verify sub-agent." }),
77
+ cycle: Type.Optional(Type.String({ description: "Only this cycle's records, e.g. c-2026-09-05." })),
78
+ limit: Type.Optional(Type.Number({ description: "Most recent N records; default 20." })),
79
+ });
80
+ export const taskStepEndSchema = Type.Object({
81
+ outcome: Type.Union([Type.Literal("continue"), Type.Literal("park"), Type.Literal("done"), Type.Literal("blocked")], {
82
+ description: "continue = more work now; park = wait on a ticket; done = close the cycle; blocked = ask the user.",
83
+ }),
84
+ note: Type.String({ description: "What this step did, the evidence, and the next step. Goes to the loop log." }),
85
+ planSteps: planStepsField,
86
+ ticket: Type.Optional(ticketField),
87
+ notify: Type.Optional(Type.String({ description: "Message to send the user. Omit to stay silent." })),
88
+ summary: Type.Optional(Type.String({ description: "Required for outcome=done: what was achieved." })),
89
+ evidence: Type.Optional(Type.String({ description: "Required for outcome=done: concrete proof." })),
90
+ residualRisk: Type.Optional(Type.String({ description: "Remaining risk after outcome=done." })),
91
+ reason: Type.Optional(Type.String({ description: "Required for outcome=blocked: what is blocking." })),
73
92
  });
@@ -1,46 +1,39 @@
1
- import type { TaskCloseRequest, TaskCreateRequest, TaskFields, TaskManageToolOptions, TaskUpdateRequest } from "./types.js";
1
+ import type { TaskBudget, TaskFrontmatterV4 } from "../../tasks/frontmatter.js";
2
+ import { type TicketContext } from "../../tasks/ticket.js";
3
+ import type { TaskCloseRequest, TaskCreateRequest, TaskManageToolOptions, TaskUpdateRequest } from "./types.js";
2
4
  export declare function tasksDir(options: TaskManageToolOptions): string;
3
5
  export declare function eventsDir(options: TaskManageToolOptions): string;
4
- export declare function renderTaskFile(fields: TaskFields, body: string): string;
6
+ export declare function renderTaskFile(fields: TaskFrontmatterV4, body: string): string;
5
7
  export declare function requiredField(value: string | undefined, field: string, action: string): string;
6
- export declare function requireNonEmpty(value: string | undefined, field: string): string;
7
8
  export declare function markdownValue(value: string): string;
8
- export declare function appendCompletionEvidence(body: string, request: TaskCloseRequest): string;
9
- export declare function renderTaskSkeleton(request: TaskCreateRequest): {
10
- fields: TaskFields;
11
- body: string;
12
- };
9
+ /** The `## 上次结果` paragraph a close writes into the contract. */
10
+ export declare function renderCloseEvidence(request: TaskCloseRequest): string;
11
+ export declare function normalizeBudget(budget: TaskUpdateRequest["budget"]): Partial<TaskBudget> | undefined;
12
+ export declare function normalizeSchedule(schedule: string | undefined): string | undefined | null;
13
13
  /**
14
- * Read a task file and split it into validated frontmatter and a verbatim body.
15
- * Fail-closed: an unreadable frontmatter block is rejected (fix it with edit first)
16
- * rather than guessed at, so these tools never silently mangle a body.
14
+ * A newly created task starts `open` — even a recurring one. Creation opens its first cycle
15
+ * immediately rather than parking until the next cron occurrence, because "create it and it does
16
+ * nothing until tomorrow morning" was consistently surprising; the cadence still governs every
17
+ * *subsequent* cycle through the `schedule` ticket the loop parks on when it finishes.
17
18
  */
18
- export declare function readTaskDocument(taskPath: string, id: string, allowControlRepair?: boolean): Promise<{
19
- fields: TaskFields;
19
+ export declare function renderTaskSkeleton(request: TaskCreateRequest, now?: Date): {
20
+ fields: TaskFrontmatterV4;
20
21
  body: string;
21
- }>;
22
+ };
23
+ /** The scheduling half of a lifecycle notice: where the task stands and who will wake it. */
24
+ export declare function describeTaskState(fields: TaskFrontmatterV4): string;
22
25
  /**
23
- * The scheduling half of a lifecycle notice: where the task stands and who will wake it.
24
- *
25
- * Parking (`waiting` with no wake) is the one state whose consequence is not obvious from the
26
- * status alone — the driver deliberately never returns to it — so the notice says so at the
27
- * moment the model chooses it, rather than leaving it to be rediscovered by a task that goes quiet.
26
+ * Build the injected lookup a ticket resolver needs. The run/job/event registries are read here —
27
+ * once, at the call site — rather than imported inside `ticket.ts`, which is what keeps the whole
28
+ * validation matrix unit-testable against plain fakes.
28
29
  */
29
- export declare function describeTaskSchedule(fields: TaskFields): string;
30
- /** Apply a metadata patch (status/wake/schedule/control) onto the existing frontmatter. */
31
- export declare function applySet(fields: TaskFields, request: Pick<TaskUpdateRequest, "status" | "wake" | "schedule" | "control">): TaskFields;
30
+ export declare function buildTicketContext(options: TaskManageToolOptions, taskId: string, schedule: string | undefined, now?: Date): Promise<TicketContext>;
32
31
  /**
33
32
  * On close-out (complete or cancel), delete every task-owned event.
34
33
  *
35
- * Recurrence cadence now lives solely in the task's `schedule` frontmatter (027/029), so a
36
- * recurring task needs no surviving `.schedule` event — the driver reopens each cycle from
37
- * frontmatter. Any remaining task-owned events are temporary sensors/check-ins that a closed
38
- * task should not keep alive. A file that cannot be parsed is left for `/events` to handle.
39
- *
40
- * Matching is done by parsing each candidate name and comparing the full task id, not by
41
- * prefix — a prefix match on `task.<channel>.<id>.` would also match a *different* task whose
42
- * id happens to start with this one plus a dot (e.g. closing "v1" must not delete events owned
43
- * by "v1.2-release").
34
+ * Matching is done by parsing each candidate name and comparing the full task id, not by prefix —
35
+ * a prefix match on `task.<channel>.<id>.` would also match a *different* task whose id happens to
36
+ * start with this one plus a dot (e.g. closing "v1" must not delete events owned by "v1.2-release").
44
37
  */
45
38
  export declare function cleanupTaskEvents(options: TaskManageToolOptions, id: string): Promise<{
46
39
  deleted: string[];
@@ -1,17 +1,18 @@
1
1
  import { existsSync } from "node:fs";
2
2
  import { readdir, readFile, unlink } from "node:fs/promises";
3
3
  import { join } from "node:path";
4
+ import { getChannelJobManager } from "../../agent/job-manager.js";
5
+ import { createExecutor } from "../../executor.js";
4
6
  import * as log from "../../log.js";
5
7
  import { parseScheduledEventContent } from "../../runtime/events.js";
6
- import { formatLocalTime, parseWakeInput } from "../../shared/local-time.js";
7
8
  import { errorMessage } from "../../shared/text-utils.js";
8
- import { applyTaskControlPatch, createDefaultTaskControl } from "../../tasks/control.js";
9
- import { normalizeTaskFields, parseTaskFrontmatter, renderStandardTaskBody, renderTaskDocument, taskBody, upsertCurrentCycleCompletionEvidence, } from "../../tasks/ledger.js";
9
+ import { getSubAgentRunManager } from "../../subagents/runs.js";
10
+ import { createCycle, nextCycleId } from "../../tasks/cycle.js";
11
+ import { renderStandardTaskBody, renderTaskDocument } from "../../tasks/ledger.js";
10
12
  import { parseTaskEventName } from "../../tasks/task-events.js";
11
- import { nextTaskWake, validateTaskSchedule } from "../../tasks/task-schedule.js";
12
- import { isSettableTaskStatus } from "../../tasks/transitions.js";
13
+ import { validateTaskSchedule } from "../../tasks/task-schedule.js";
14
+ import { describeTicket } from "../../tasks/ticket.js";
13
15
  import { RecoverableToolError } from "../tool-details.js";
14
- import { SETTABLE_STATUSES } from "./schema.js";
15
16
  export function tasksDir(options) {
16
17
  return join(options.channelDir, "tasks");
17
18
  }
@@ -23,178 +24,139 @@ export function renderTaskFile(fields, body) {
23
24
  }
24
25
  export function requiredField(value, field, action) {
25
26
  const trimmed = value?.trim();
26
- if (!trimmed) {
27
+ if (!trimmed)
27
28
  throw new RecoverableToolError(`${action} requires ${field}.`);
28
- }
29
29
  return trimmed;
30
30
  }
31
- export function requireNonEmpty(value, field) {
32
- return requiredField(value, field, "task_close outcome=complete");
33
- }
34
31
  export function markdownValue(value) {
35
32
  const lines = value.trim().split(/\r?\n/);
36
33
  if (lines.length === 1)
37
34
  return lines[0];
38
35
  return lines.map((line, index) => (index === 0 ? line : ` ${line}`)).join("\n");
39
36
  }
40
- export function appendCompletionEvidence(body, request) {
41
- const summary = requireNonEmpty(request.summary, "summary");
42
- const evidence = requireNonEmpty(request.evidence, "evidence");
37
+ /** The `## 上次结果` paragraph a close writes into the contract. */
38
+ export function renderCloseEvidence(request) {
39
+ const summary = requiredField(request.summary, "summary", "task_close outcome=complete");
40
+ const evidence = requiredField(request.evidence, "evidence", "task_close outcome=complete");
43
41
  const lines = [`- Summary: ${markdownValue(summary)}`, `- Evidence: ${markdownValue(evidence)}`];
44
42
  const residualRisk = request.residualRisk?.trim();
45
- if (residualRisk) {
43
+ if (residualRisk)
46
44
  lines.push(`- Residual risk: ${markdownValue(residualRisk)}`);
45
+ return lines.join("\n");
46
+ }
47
+ export function normalizeBudget(budget) {
48
+ if (!budget)
49
+ return undefined;
50
+ const next = {};
51
+ for (const key of ["steps", "wallMin", "usd", "rounds"]) {
52
+ const value = budget[key];
53
+ if (value === undefined)
54
+ continue;
55
+ if (!Number.isFinite(value) || value <= 0) {
56
+ throw new RecoverableToolError(`budget.${key} must be a positive number.`);
57
+ }
58
+ next[key] = value;
47
59
  }
48
- return upsertCurrentCycleCompletionEvidence(body, lines);
60
+ if (budget.until !== undefined)
61
+ next.until = budget.until.trim() || undefined;
62
+ return Object.keys(next).length > 0 ? next : undefined;
49
63
  }
50
- function normalizeCreateStatus(status) {
51
- if (status === undefined)
52
- return "active";
53
- if (isSettableTaskStatus(status))
54
- return status;
55
- throw new RecoverableToolError(`Invalid status "${status}". Use one of ${SETTABLE_STATUSES.join(", ")}.`);
64
+ export function normalizeSchedule(schedule) {
65
+ if (schedule === undefined)
66
+ return undefined;
67
+ const trimmed = schedule.trim();
68
+ if (!trimmed)
69
+ return null; // explicit clear
70
+ validateTaskSchedule(trimmed);
71
+ return trimmed;
56
72
  }
57
- export function renderTaskSkeleton(request) {
58
- // Independent verification is opt-in: it is a quality fact, not an external-action policy.
59
- // `deadline`/`verificationRequired` are flattened onto task_create (spec 046, D3.1) — creation
60
- // has no `nextAction`/`waitingFor` to set, so there is nothing a nested `control` would add.
61
- const control = applyTaskControlPatch(createDefaultTaskControl(request.verificationRequired ?? false), {
62
- deadline: request.deadline,
63
- verificationRequired: request.verificationRequired,
64
- });
65
- const fields = applySet({ status: normalizeCreateStatus(request.status), enabled: true, control }, { status: request.status, wake: request.wake, schedule: request.schedule });
66
- if (!fields.schedule && fields.status === "sleeping") {
67
- throw new RecoverableToolError('A one-shot task cannot use status "sleeping"; create it as active or waiting.');
68
- }
69
- // Recurring creation always starts asleep. The first occurrence and every later occurrence use
70
- // the same runtime cycle-open operation; creation itself never dispatches work.
71
- if (fields.schedule) {
72
- fields.status = "sleeping";
73
- fields.enabled = true;
74
- }
75
- if (fields.schedule && request.wake === undefined) {
76
- const next = nextTaskWake(fields.schedule);
77
- fields.wake = next ? formatLocalTime(next) : undefined;
78
- }
73
+ /**
74
+ * A newly created task starts `open` — even a recurring one. Creation opens its first cycle
75
+ * immediately rather than parking until the next cron occurrence, because "create it and it does
76
+ * nothing until tomorrow morning" was consistently surprising; the cadence still governs every
77
+ * *subsequent* cycle through the `schedule` ticket the loop parks on when it finishes.
78
+ */
79
+ export function renderTaskSkeleton(request, now = new Date()) {
80
+ const schedule = normalizeSchedule(request.schedule);
81
+ const fields = {
82
+ state: "open",
83
+ schedule: schedule ?? undefined,
84
+ // The first cycle opens at creation: steps, rework rounds and cost all accumulate onto a
85
+ // cycle, so a task without one would have nowhere to record what it did.
86
+ cycle: createCycle(nextCycleId(undefined, now), now),
87
+ budget: normalizeBudget(request.budget),
88
+ verify: request.verificationRequired ? "required" : undefined,
89
+ };
79
90
  const body = renderStandardTaskBody({
80
91
  title: request.title,
81
92
  goal: request.goal,
82
93
  dod: request.dod,
83
94
  manual: request.manual,
84
95
  verificationPlan: request.verificationPlan,
85
- verificationRequired: control.verification.required,
96
+ verificationRequired: request.verificationRequired ?? false,
86
97
  plan: request.plan,
87
98
  });
88
99
  return { fields, body };
89
100
  }
90
- /**
91
- * Read a task file and split it into validated frontmatter and a verbatim body.
92
- * Fail-closed: an unreadable frontmatter block is rejected (fix it with edit first)
93
- * rather than guessed at, so these tools never silently mangle a body.
94
- */
95
- export async function readTaskDocument(taskPath, id, allowControlRepair = false) {
96
- if (!existsSync(taskPath)) {
97
- throw new RecoverableToolError(`Task "${id}" does not exist; create it with task_create first.`);
101
+ /** The scheduling half of a lifecycle notice: where the task stands and who will wake it. */
102
+ export function describeTaskState(fields) {
103
+ if (fields.paused)
104
+ return `state: ${fields.state}(已暂停:${fields.paused.reason})`;
105
+ if (fields.state === "parked" && fields.ticket) {
106
+ return `state: parked(${describeTicket(fields.ticket)};兜底 ${fields.ticket.by})`;
98
107
  }
99
- const content = await readFile(taskPath, "utf-8");
100
- const frontmatter = parseTaskFrontmatter(content);
101
- if (!frontmatter.readable) {
102
- throw new RecoverableToolError(`Task "${id}" has no readable frontmatter; fix it with edit before using task_update.`);
103
- }
104
- if (frontmatter.controlReadable === false && !allowControlRepair) {
105
- throw new RecoverableToolError(`Task "${id}" has invalid control metadata; repair it with task_update (no note) and an explicit control patch first.`);
106
- }
107
- return {
108
- fields: {
109
- status: frontmatter.status ?? "active",
110
- enabled: frontmatter.enabled,
111
- wake: frontmatter.wake,
112
- schedule: frontmatter.schedule,
113
- // A successful write upgrades a hand-written/v0 task to the v2 control contract
114
- // instead of preserving an ungoverned task indefinitely.
115
- control: frontmatter.control ?? createDefaultTaskControl(),
116
- outcome: frontmatter.archiveOutcome,
117
- closedAt: frontmatter.closedAt,
118
- },
119
- body: taskBody(content),
120
- };
108
+ return `state: ${fields.state}`;
121
109
  }
122
110
  /**
123
- * The scheduling half of a lifecycle notice: where the task stands and who will wake it.
124
- *
125
- * Parking (`waiting` with no wake) is the one state whose consequence is not obvious from the
126
- * status alone — the driver deliberately never returns to it — so the notice says so at the
127
- * moment the model chooses it, rather than leaving it to be rediscovered by a task that goes quiet.
111
+ * Build the injected lookup a ticket resolver needs. The run/job/event registries are read here —
112
+ * once, at the call site — rather than imported inside `ticket.ts`, which is what keeps the whole
113
+ * validation matrix unit-testable against plain fakes.
128
114
  */
129
- export function describeTaskSchedule(fields) {
130
- if (fields.enabled === false) {
131
- return `status: ${fields.status}(已停用${fields.control?.stop ? `:${fields.control.stop.reason}` : ""})`;
132
- }
133
- if (fields.status === "waiting" && !fields.wake) {
134
- return `status: waiting(已停泊:等待 ${fields.control?.waitingFor ?? "external-signal"};driver 不会轮询)`;
135
- }
136
- return `status: ${fields.status}${fields.wake ? `, wake: ${fields.wake}` : ""}`;
115
+ export async function buildTicketContext(options, taskId, schedule, now = new Date()) {
116
+ const runManager = getSubAgentRunManager(options.channelId);
117
+ const jobs = await getChannelJobManager(options.channelId, createExecutor())
118
+ .list()
119
+ .catch(() => []);
120
+ const events = await readChannelEvents(options);
121
+ return {
122
+ now,
123
+ taskId,
124
+ channelId: options.channelId,
125
+ schedule,
126
+ findRun: (id) => runManager.get(id),
127
+ findJob: (id) => jobs.find((job) => job.id === id),
128
+ findEvent: (name) => events.get(name),
129
+ };
137
130
  }
138
- /** Apply a metadata patch (status/wake/schedule/control) onto the existing frontmatter. */
139
- export function applySet(fields, request) {
140
- const next = { ...fields };
141
- if (request.status !== undefined) {
142
- if (!isSettableTaskStatus(request.status)) {
143
- throw new RecoverableToolError(`Invalid status "${request.status}". Use one of ${SETTABLE_STATUSES.join(", ")}, or task_close.`);
144
- }
145
- next.status = request.status;
146
- }
147
- if (request.wake !== undefined) {
148
- const trimmed = request.wake.trim();
149
- if (trimmed === "") {
150
- next.wake = undefined;
151
- }
152
- else {
153
- const ms = parseWakeInput(trimmed);
154
- if (ms === undefined) {
155
- throw new RecoverableToolError(`wake "${request.wake}" is not a valid local time (e.g. 2026-07-27T07:30:00+08:00) or relative offset (e.g. +2h).`);
156
- }
157
- next.wake = formatLocalTime(new Date(ms));
158
- }
159
- }
160
- if (request.schedule !== undefined) {
161
- const trimmed = request.schedule.trim();
162
- if (trimmed === "") {
163
- next.schedule = undefined;
131
+ /** Every parseable event definition in the workspace, by name. Missing directory → empty. */
132
+ async function readChannelEvents(options) {
133
+ const dir = eventsDir(options);
134
+ const events = new Map();
135
+ if (!existsSync(dir))
136
+ return events;
137
+ for (const filename of await readdir(dir)) {
138
+ if (!filename.endsWith(".json"))
139
+ continue;
140
+ try {
141
+ const event = parseScheduledEventContent(await readFile(join(dir, filename), "utf-8"), filename);
142
+ events.set(filename.slice(0, -".json".length), {
143
+ type: event.type,
144
+ channelId: event.channelId,
145
+ schedule: event.type === "periodic" ? event.schedule : undefined,
146
+ });
164
147
  }
165
- else {
166
- validateTaskSchedule(trimmed);
167
- next.schedule = trimmed;
168
- // A cadence change without an explicit new wake in the same call means the old
169
- // wake belongs to the old rhythm — recompute it against the new cron so a stale
170
- // or hand-typed value can never silently point at an occurrence the new schedule
171
- // doesn't have. A parked task (waiting, no wake) is left parked: it intentionally
172
- // has no wake at all, and this must not be the thing that gives it one.
173
- const parked = next.status === "waiting" && next.wake === undefined;
174
- if (request.wake === undefined && !parked) {
175
- const nextWake = nextTaskWake(trimmed);
176
- if (nextWake)
177
- next.wake = formatLocalTime(nextWake);
178
- }
148
+ catch {
149
+ // An unparseable event cannot back a ticket; leave it for /events to clean up.
179
150
  }
180
151
  }
181
- if (request.control !== undefined) {
182
- next.control = applyTaskControlPatch(next.control ?? createDefaultTaskControl(), request.control);
183
- }
184
- return normalizeTaskFields(next);
152
+ return events;
185
153
  }
186
154
  /**
187
155
  * On close-out (complete or cancel), delete every task-owned event.
188
156
  *
189
- * Recurrence cadence now lives solely in the task's `schedule` frontmatter (027/029), so a
190
- * recurring task needs no surviving `.schedule` event — the driver reopens each cycle from
191
- * frontmatter. Any remaining task-owned events are temporary sensors/check-ins that a closed
192
- * task should not keep alive. A file that cannot be parsed is left for `/events` to handle.
193
- *
194
- * Matching is done by parsing each candidate name and comparing the full task id, not by
195
- * prefix — a prefix match on `task.<channel>.<id>.` would also match a *different* task whose
196
- * id happens to start with this one plus a dot (e.g. closing "v1" must not delete events owned
197
- * by "v1.2-release").
157
+ * Matching is done by parsing each candidate name and comparing the full task id, not by prefix —
158
+ * a prefix match on `task.<channel>.<id>.` would also match a *different* task whose id happens to
159
+ * start with this one plus a dot (e.g. closing "v1" must not delete events owned by "v1.2-release").
198
160
  */
199
161
  export async function cleanupTaskEvents(options, id) {
200
162
  const dir = eventsDir(options);
@@ -0,0 +1,11 @@
1
+ import type { TaskManageResult, TaskManageToolOptions, TaskStepEndRequest } from "./types.js";
2
+ /**
3
+ * `task_step_end` — the loop's only closing move (spec 051, D4/§12.4).
4
+ *
5
+ * One tool with four outcomes replaces v3's `task_update(note)` + `task_close` + the
6
+ * status/wake/waitingFor triple the model had to keep mutually consistent. The model states an
7
+ * *intent* ("keep going", "wait for this", "we're done", "I'm stuck") and the runtime derives the
8
+ * state, so an illegal combination — parked with nothing to wait for, active with a future wake —
9
+ * is not expressible rather than merely diagnosed afterwards by `/tasks doctor`.
10
+ */
11
+ export declare function endTaskStep(options: TaskManageToolOptions, request: TaskStepEndRequest): Promise<TaskManageResult>;
@@ -0,0 +1,136 @@
1
+ import { renderCloseSummary, writeLastResult } from "../../tasks/cycle.js";
2
+ import { applyTaskPlanPatch, normalizeTaskId, uncheckedTaskAcceptanceItems } from "../../tasks/ledger.js";
3
+ import { appendTaskLog } from "../../tasks/log.js";
4
+ import { hasPassingRound } from "../../tasks/rounds.js";
5
+ import { queueTaskNotice } from "../../tasks/steer.js";
6
+ import { archiveTask, readStoredTask, writeStoredTask } from "../../tasks/store.js";
7
+ import { describeTicket, resolveTicket } from "../../tasks/ticket.js";
8
+ import { RecoverableToolError } from "../tool-details.js";
9
+ import { buildTicketContext, cleanupTaskEvents, requiredField } from "./shared.js";
10
+ /**
11
+ * `task_step_end` — the loop's only closing move (spec 051, D4/§12.4).
12
+ *
13
+ * One tool with four outcomes replaces v3's `task_update(note)` + `task_close` + the
14
+ * status/wake/waitingFor triple the model had to keep mutually consistent. The model states an
15
+ * *intent* ("keep going", "wait for this", "we're done", "I'm stuck") and the runtime derives the
16
+ * state, so an illegal combination — parked with nothing to wait for, active with a future wake —
17
+ * is not expressible rather than merely diagnosed afterwards by `/tasks doctor`.
18
+ */
19
+ export async function endTaskStep(options, request) {
20
+ if (!options.taskId) {
21
+ throw new RecoverableToolError("task_step_end is only available inside a task loop step.");
22
+ }
23
+ const id = normalizeTaskId(options.taskId);
24
+ const document = await readStoredTask(options.channelDir, id);
25
+ if (!document)
26
+ throw new RecoverableToolError(`Task "${id}" no longer exists; nothing to end.`);
27
+ const cycleId = document.fields.cycle?.id ?? options.cycleId ?? "-";
28
+ const note = requiredField(request.note, "note", "task_step_end");
29
+ if (request.planSteps?.length) {
30
+ document.body = applyTaskPlanPatch(document.body, request.planSteps).body;
31
+ }
32
+ const seq = (document.fields.cycle?.steps ?? 0) + 1;
33
+ if (document.fields.cycle)
34
+ document.fields.cycle = { ...document.fields.cycle, steps: seq };
35
+ const tools = [...new Set(options.getToolsUsed?.() ?? [])];
36
+ const logStep = async (outcome) => {
37
+ await appendTaskLog(options.channelDir, id, { cycle: cycleId, kind: "step", seq, outcome, note, tools });
38
+ };
39
+ // Steps are silent by default (D3); `notify` is the explicit opt-in the runtime delivers once
40
+ // the step ends. `blocked` always speaks — a task waiting on the user that says nothing is the
41
+ // same silent dead end tickets exist to prevent.
42
+ if (request.notify?.trim())
43
+ await queueTaskNotice(options.channelDir, id, request.notify);
44
+ else if (request.outcome === "blocked") {
45
+ await queueTaskNotice(options.channelDir, id, `任务 ${id} 需要你的决定:${request.reason ?? note}`);
46
+ }
47
+ if (request.outcome === "done") {
48
+ const summary = requiredField(request.summary, "summary", "task_step_end outcome=done");
49
+ const evidence = requiredField(request.evidence, "evidence", "task_step_end outcome=done");
50
+ const unchecked = uncheckedTaskAcceptanceItems(document.body);
51
+ if (unchecked.length > 0) {
52
+ throw new RecoverableToolError(`Task "${id}" still has unmet acceptance items: ${unchecked.slice(0, 3).join("; ")}. Check them off with edit once the evidence holds.`);
53
+ }
54
+ // Verification is imported by the runtime when a purpose=verify run settles (D7), so what
55
+ // gates `done` here is whether a PASS actually landed in this cycle — not whether the model
56
+ // remembered to call an import tool.
57
+ if (document.fields.verify === "required" &&
58
+ !(await hasPassingRound(options.channelDir, id, document.fields.cycle?.id))) {
59
+ throw new RecoverableToolError(`Task "${id}" requires independent verification; dispatch a purpose=verify sub-agent with taskId=${id} and let its PASS land before finishing.`);
60
+ }
61
+ const cycle = document.fields.cycle;
62
+ document.body = writeLastResult(document.body, renderCloseSummary({
63
+ cycleId,
64
+ outcome: "done",
65
+ summary,
66
+ evidence,
67
+ residualRisk: request.residualRisk,
68
+ steps: cycle?.steps ?? seq,
69
+ rounds: cycle?.rounds ?? 0,
70
+ usd: cycle?.usd ?? 0,
71
+ usdEstimated: cycle?.usdEstimated ?? false,
72
+ }));
73
+ await appendTaskLog(options.channelDir, id, {
74
+ cycle: cycleId,
75
+ kind: "close",
76
+ outcome: "done",
77
+ summary,
78
+ evidence,
79
+ residualRisk: request.residualRisk,
80
+ steps: cycle?.steps ?? seq,
81
+ rounds: cycle?.rounds ?? 0,
82
+ usd: cycle?.usd ?? 0,
83
+ });
84
+ if (document.fields.schedule) {
85
+ // Recurring: park on the next occurrence rather than archiving. The contract, the Plan
86
+ // and the loop log all survive into the next cycle; only the counters reset.
87
+ const context = await buildTicketContext(options, id, document.fields.schedule);
88
+ const ticket = resolveTicket({ kind: "schedule" }, context);
89
+ document.fields.state = "parked";
90
+ document.fields.ticket = ticket;
91
+ await writeStoredTask(document);
92
+ await logStep("done");
93
+ return {
94
+ action: "step_end",
95
+ id,
96
+ state: "parked",
97
+ notice: `任务 \`${id}\` 本周期完成,${describeTicket(ticket)}。`,
98
+ };
99
+ }
100
+ await writeStoredTask(document);
101
+ await logStep("done");
102
+ const { deleted } = await cleanupTaskEvents(options, id);
103
+ await archiveTask(options.channelDir, id, "completed");
104
+ return {
105
+ action: "step_end",
106
+ id,
107
+ archived: true,
108
+ deletedEvents: deleted,
109
+ notice: `任务 \`${id}\` 已完成并归档。`,
110
+ };
111
+ }
112
+ let notice;
113
+ if (request.outcome === "continue") {
114
+ document.fields.state = "open";
115
+ document.fields.ticket = undefined;
116
+ notice = `步骤已记录,任务 \`${id}\` 继续。`;
117
+ }
118
+ else {
119
+ // `blocked` is `park` on an `ask` ticket: a task that needs the user is still a task with a
120
+ // verifiable, backstopped wait, not a special state that could go quiet.
121
+ const input = request.outcome === "blocked"
122
+ ? { kind: "ask", asked: requiredField(request.reason, "reason", "task_step_end outcome=blocked") }
123
+ : request.ticket;
124
+ if (!input) {
125
+ throw new RecoverableToolError("task_step_end outcome=park requires a ticket describing what will wake this task.");
126
+ }
127
+ const context = await buildTicketContext(options, id, document.fields.schedule);
128
+ const ticket = resolveTicket(input, context);
129
+ document.fields.state = "parked";
130
+ document.fields.ticket = ticket;
131
+ notice = `任务 \`${id}\` 已停泊:${describeTicket(ticket)}(兜底 ${ticket.by})。`;
132
+ }
133
+ await writeStoredTask(document);
134
+ await logStep(request.outcome);
135
+ return { action: "step_end", id, state: document.fields.state, notice };
136
+ }