@oyasmi/pipiclaw 0.9.2 → 0.9.3-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (178) hide show
  1. package/README.en.md +250 -0
  2. package/README.md +3 -1
  3. package/dist/agent/channel-runner.d.ts +59 -2
  4. package/dist/agent/channel-runner.js +177 -76
  5. package/dist/agent/job-manager.d.ts +76 -21
  6. package/dist/agent/job-manager.js +447 -63
  7. package/dist/agent/maintenance-context.js +4 -5
  8. package/dist/agent/prompt/manifest.d.ts +0 -2
  9. package/dist/agent/prompt/manifest.js +2 -3
  10. package/dist/agent/prompt/sections.js +3 -3
  11. package/dist/agent/session-events.js +4 -8
  12. package/dist/agent/turn-prompt.d.ts +7 -7
  13. package/dist/agent/turn-prompt.js +6 -9
  14. package/dist/agent/types.d.ts +12 -0
  15. package/dist/agent/types.js +1 -0
  16. package/dist/channel/channel-context.d.ts +13 -0
  17. package/dist/channel/channel-context.js +21 -1
  18. package/dist/commands/catalog.js +47 -20
  19. package/dist/memory/commands.d.ts +8 -0
  20. package/dist/memory/commands.js +113 -148
  21. package/dist/memory/index-budget.d.ts +27 -0
  22. package/dist/memory/index-budget.js +99 -0
  23. package/dist/memory/journal.d.ts +20 -0
  24. package/dist/memory/journal.js +78 -0
  25. package/dist/memory/lifecycle.d.ts +9 -15
  26. package/dist/memory/lifecycle.js +55 -145
  27. package/dist/memory/maintenance-gates.d.ts +13 -47
  28. package/dist/memory/maintenance-gates.js +13 -92
  29. package/dist/memory/maintenance-state.d.ts +10 -16
  30. package/dist/memory/maintenance-state.js +12 -59
  31. package/dist/memory/maintenance-tuning.d.ts +7 -27
  32. package/dist/memory/maintenance-tuning.js +11 -28
  33. package/dist/memory/migrate.d.ts +15 -0
  34. package/dist/memory/migrate.js +364 -0
  35. package/dist/memory/reflect-job.d.ts +43 -0
  36. package/dist/memory/reflect-job.js +117 -0
  37. package/dist/memory/reflect.d.ts +52 -0
  38. package/dist/memory/reflect.js +313 -0
  39. package/dist/memory/render.d.ts +19 -0
  40. package/dist/memory/render.js +35 -0
  41. package/dist/memory/review-log.d.ts +2 -1
  42. package/dist/memory/scheduler.d.ts +2 -3
  43. package/dist/memory/scheduler.js +14 -49
  44. package/dist/memory/search.d.ts +35 -0
  45. package/dist/memory/search.js +297 -0
  46. package/dist/memory/session-search.js +1 -1
  47. package/dist/memory/store.d.ts +108 -0
  48. package/dist/memory/store.js +418 -0
  49. package/dist/memory/task-digest.d.ts +2 -2
  50. package/dist/memory/task-digest.js +29 -36
  51. package/dist/memory/tombstones.d.ts +0 -11
  52. package/dist/memory/tombstones.js +6 -37
  53. package/dist/memory/transcript.js +12 -5
  54. package/dist/playbooks/agent-delegation.md +37 -9
  55. package/dist/playbooks/background-jobs.md +1 -1
  56. package/dist/playbooks/event-scheduling.md +6 -2
  57. package/dist/playbooks/memory-and-learning.md +36 -12
  58. package/dist/playbooks/outbound-media.md +1 -1
  59. package/dist/playbooks/runtime-orientation.md +9 -8
  60. package/dist/playbooks/task-loop.md +110 -0
  61. package/dist/runtime/bootstrap.d.ts +3 -3
  62. package/dist/runtime/bootstrap.js +66 -41
  63. package/dist/runtime/events.d.ts +9 -0
  64. package/dist/runtime/events.js +43 -4
  65. package/dist/runtime/task-commands.d.ts +14 -15
  66. package/dist/runtime/task-commands.js +249 -485
  67. package/dist/runtime/task-driver.d.ts +41 -29
  68. package/dist/runtime/task-driver.js +170 -317
  69. package/dist/runtime/task-migration.d.ts +34 -30
  70. package/dist/runtime/task-migration.js +229 -183
  71. package/dist/runtime/task-wake.d.ts +6 -3
  72. package/dist/runtime/task-wake.js +26 -19
  73. package/dist/settings.d.ts +0 -29
  74. package/dist/settings.js +12 -35
  75. package/dist/shared/markdown-sections.d.ts +0 -1
  76. package/dist/shared/markdown-sections.js +0 -3
  77. package/dist/subagents/discovery.d.ts +2 -2
  78. package/dist/subagents/discovery.js +21 -10
  79. package/dist/subagents/external/progress-tail.js +6 -1
  80. package/dist/subagents/external/run.js +1 -0
  81. package/dist/subagents/runs.d.ts +19 -2
  82. package/dist/subagents/runs.js +73 -4
  83. package/dist/subagents/tool.d.ts +10 -8
  84. package/dist/subagents/tool.js +55 -94
  85. package/dist/tasks/brief.d.ts +17 -0
  86. package/dist/tasks/brief.js +57 -0
  87. package/dist/tasks/budget.d.ts +26 -0
  88. package/dist/tasks/budget.js +59 -0
  89. package/dist/tasks/cycle.d.ts +48 -0
  90. package/dist/tasks/cycle.js +94 -0
  91. package/dist/tasks/frontmatter.d.ts +73 -0
  92. package/dist/tasks/frontmatter.js +175 -0
  93. package/dist/tasks/ledger.d.ts +66 -106
  94. package/dist/tasks/ledger.js +90 -546
  95. package/dist/tasks/log.d.ts +88 -0
  96. package/dist/tasks/log.js +97 -0
  97. package/dist/tasks/rounds.d.ts +41 -0
  98. package/dist/tasks/rounds.js +53 -0
  99. package/dist/tasks/session-path.d.ts +9 -0
  100. package/dist/tasks/session-path.js +16 -0
  101. package/dist/tasks/steer.d.ts +8 -0
  102. package/dist/tasks/steer.js +79 -0
  103. package/dist/tasks/store.d.ts +60 -35
  104. package/dist/tasks/store.js +166 -107
  105. package/dist/tasks/ticket.d.ts +102 -0
  106. package/dist/tasks/ticket.js +209 -0
  107. package/dist/tasks/verification.d.ts +47 -0
  108. package/dist/tasks/verification.js +60 -1
  109. package/dist/tools/index.d.ts +13 -4
  110. package/dist/tools/index.js +5 -10
  111. package/dist/tools/memory-manage.d.ts +6 -16
  112. package/dist/tools/memory-manage.js +108 -129
  113. package/dist/tools/presentation.js +2 -1
  114. package/dist/tools/registry.d.ts +11 -2
  115. package/dist/tools/registry.js +17 -6
  116. package/dist/tools/subagent-manage.d.ts +0 -9
  117. package/dist/tools/subagent-manage.js +8 -17
  118. package/dist/tools/task-manage/create.js +2 -2
  119. package/dist/tools/task-manage/lifecycle.d.ts +9 -4
  120. package/dist/tools/task-manage/lifecycle.js +136 -188
  121. package/dist/tools/task-manage/log-view.d.ts +8 -0
  122. package/dist/tools/task-manage/log-view.js +24 -0
  123. package/dist/tools/task-manage/schema.d.ts +38 -14
  124. package/dist/tools/task-manage/schema.js +46 -27
  125. package/dist/tools/task-manage/shared.d.ts +35 -31
  126. package/dist/tools/task-manage/shared.js +130 -141
  127. package/dist/tools/task-manage/step-end.d.ts +11 -0
  128. package/dist/tools/task-manage/step-end.js +134 -0
  129. package/dist/tools/task-manage/types.d.ts +23 -32
  130. package/dist/tools/task-manage.d.ts +4 -3
  131. package/dist/tools/task-manage.js +30 -15
  132. package/dist/tools/tool-details.d.ts +1 -1
  133. package/dist/tui/app.js +0 -2
  134. package/examples/sub-agents/README.md +54 -38
  135. package/examples/sub-agents/builder-hard.md +21 -12
  136. package/examples/sub-agents/builder.md +24 -16
  137. package/examples/sub-agents/explorer.md +17 -15
  138. package/examples/sub-agents/git-committer.md +8 -6
  139. package/examples/sub-agents/planner.md +17 -16
  140. package/examples/sub-agents/reviewer.md +11 -9
  141. package/examples/sub-agents/verifier.md +22 -16
  142. package/examples/sub-agents/worker.md +22 -6
  143. package/package.json +1 -1
  144. package/dist/agent/effect-ledger.d.ts +0 -32
  145. package/dist/agent/effect-ledger.js +0 -89
  146. package/dist/memory/bootstrap.d.ts +0 -17
  147. package/dist/memory/bootstrap.js +0 -120
  148. package/dist/memory/candidates.d.ts +0 -26
  149. package/dist/memory/candidates.js +0 -202
  150. package/dist/memory/consolidation.d.ts +0 -54
  151. package/dist/memory/consolidation.js +0 -292
  152. package/dist/memory/extraction.d.ts +0 -54
  153. package/dist/memory/extraction.js +0 -240
  154. package/dist/memory/files.d.ts +0 -71
  155. package/dist/memory/files.js +0 -419
  156. package/dist/memory/maintenance-jobs.d.ts +0 -41
  157. package/dist/memory/maintenance-jobs.js +0 -265
  158. package/dist/memory/metadata.d.ts +0 -57
  159. package/dist/memory/metadata.js +0 -142
  160. package/dist/memory/probation.d.ts +0 -17
  161. package/dist/memory/probation.js +0 -44
  162. package/dist/memory/promotion.d.ts +0 -38
  163. package/dist/memory/promotion.js +0 -36
  164. package/dist/memory/recall.d.ts +0 -59
  165. package/dist/memory/recall.js +0 -746
  166. package/dist/memory/session.d.ts +0 -24
  167. package/dist/memory/session.js +0 -273
  168. package/dist/playbooks/task-driving.md +0 -92
  169. package/dist/playbooks/task-planning.md +0 -58
  170. package/dist/tasks/control.d.ts +0 -56
  171. package/dist/tasks/control.js +0 -169
  172. package/dist/tasks/transitions.d.ts +0 -16
  173. package/dist/tasks/transitions.js +0 -48
  174. package/dist/tools/task-manage/verification.d.ts +0 -19
  175. package/dist/tools/task-manage/verification.js +0 -91
  176. package/examples/sub-agents/documenter.md +0 -50
  177. package/examples/sub-agents/log-sifter.md +0 -47
  178. package/examples/sub-agents/scout.md +0 -34
@@ -1,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,47 +1,51 @@
1
- import type { TaskCloseRequest, TaskCreateRequest, TaskFields, TaskManageToolOptions, TaskUpdateRequest } from "./types.js";
1
+ import type { TaskBudget, TaskFrontmatterV4 } from "../../tasks/frontmatter.js";
2
+ import type { StoredTaskDocument } from "../../tasks/store.js";
3
+ import { type TicketContext } from "../../tasks/ticket.js";
4
+ import type { TaskCloseRequest, TaskCreateRequest, TaskManageToolOptions, TaskUpdateRequest } from "./types.js";
2
5
  export declare function tasksDir(options: TaskManageToolOptions): string;
3
6
  export declare function eventsDir(options: TaskManageToolOptions): string;
4
- export declare function renderTaskFile(fields: TaskFields, body: string): string;
7
+ export declare function renderTaskFile(fields: TaskFrontmatterV4, body: string): string;
5
8
  export declare function requiredField(value: string | undefined, field: string, action: string): string;
6
- export declare function requireNonEmpty(value: string | undefined, field: string): string;
7
9
  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
- };
10
+ /** The `## 上次结果` paragraph a close writes into the contract. */
11
+ export declare function renderCloseEvidence(request: TaskCloseRequest): string;
12
+ export declare function normalizeBudget(budget: TaskUpdateRequest["budget"]): Partial<TaskBudget> | undefined;
13
+ export declare function normalizeSchedule(schedule: string | undefined): string | undefined | null;
13
14
  /**
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.
15
+ * A newly created task starts `open` — even a recurring one. Creation opens its first cycle
16
+ * immediately rather than parking until the next cron occurrence, because "create it and it does
17
+ * nothing until tomorrow morning" was consistently surprising; the cadence still governs every
18
+ * *subsequent* cycle through the `schedule` ticket the loop parks on when it finishes.
17
19
  */
18
- export declare function readTaskDocument(taskPath: string, id: string, allowControlRepair?: boolean): Promise<{
19
- fields: TaskFields;
20
+ export declare function renderTaskSkeleton(request: TaskCreateRequest, now?: Date): {
21
+ fields: TaskFrontmatterV4;
20
22
  body: string;
21
- }>;
23
+ };
24
+ /** The scheduling half of a lifecycle notice: where the task stands and who will wake it. */
25
+ export declare function describeTaskState(fields: TaskFrontmatterV4): string;
22
26
  /**
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.
27
+ * Build the injected lookup a ticket resolver needs. The run/job/event registries are read here —
28
+ * once, at the call site — rather than imported inside `ticket.ts`, which is what keeps the whole
29
+ * validation matrix unit-testable against plain fakes.
28
30
  */
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;
31
+ export declare function buildTicketContext(options: TaskManageToolOptions, taskId: string, schedule: string | undefined, now?: Date): Promise<TicketContext>;
32
32
  /**
33
33
  * On close-out (complete or cancel), delete every task-owned event.
34
34
  *
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").
35
+ * Matching is done by parsing each candidate name and comparing the full task id, not by prefix —
36
+ * a prefix match on `task.<channel>.<id>.` would also match a *different* task whose id happens to
37
+ * start with this one plus a dot (e.g. closing "v1" must not delete events owned by "v1.2-release").
44
38
  */
45
39
  export declare function cleanupTaskEvents(options: TaskManageToolOptions, id: string): Promise<{
46
40
  deleted: string[];
47
41
  }>;
42
+ /**
43
+ * The verification gate both close entry points share (`task_step_end outcome=done` and
44
+ * `task_close outcome=complete`).
45
+ *
46
+ * It exists as one function because the two used to ask the question separately and both asked
47
+ * the weaker one — "did a PASS ever land in this cycle" — which a contract edit or a further code
48
+ * change made *after* the PASS would still satisfy. The real check is re-run here, against the
49
+ * contract and the checkout as they stand at close time.
50
+ */
51
+ export declare function assertVerificationHoldsForClose(options: TaskManageToolOptions, document: StoredTaskDocument, id: string): Promise<void>;
@@ -1,17 +1,19 @@
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";
15
+ import { completionVerificationBlockReason } from "../../tasks/verification.js";
13
16
  import { RecoverableToolError } from "../tool-details.js";
14
- import { SETTABLE_STATUSES } from "./schema.js";
15
17
  export function tasksDir(options) {
16
18
  return join(options.channelDir, "tasks");
17
19
  }
@@ -23,178 +25,139 @@ export function renderTaskFile(fields, body) {
23
25
  }
24
26
  export function requiredField(value, field, action) {
25
27
  const trimmed = value?.trim();
26
- if (!trimmed) {
28
+ if (!trimmed)
27
29
  throw new RecoverableToolError(`${action} requires ${field}.`);
28
- }
29
30
  return trimmed;
30
31
  }
31
- export function requireNonEmpty(value, field) {
32
- return requiredField(value, field, "task_close outcome=complete");
33
- }
34
32
  export function markdownValue(value) {
35
33
  const lines = value.trim().split(/\r?\n/);
36
34
  if (lines.length === 1)
37
35
  return lines[0];
38
36
  return lines.map((line, index) => (index === 0 ? line : ` ${line}`)).join("\n");
39
37
  }
40
- export function appendCompletionEvidence(body, request) {
41
- const summary = requireNonEmpty(request.summary, "summary");
42
- const evidence = requireNonEmpty(request.evidence, "evidence");
38
+ /** The `## 上次结果` paragraph a close writes into the contract. */
39
+ export function renderCloseEvidence(request) {
40
+ const summary = requiredField(request.summary, "summary", "task_close outcome=complete");
41
+ const evidence = requiredField(request.evidence, "evidence", "task_close outcome=complete");
43
42
  const lines = [`- Summary: ${markdownValue(summary)}`, `- Evidence: ${markdownValue(evidence)}`];
44
43
  const residualRisk = request.residualRisk?.trim();
45
- if (residualRisk) {
44
+ if (residualRisk)
46
45
  lines.push(`- Residual risk: ${markdownValue(residualRisk)}`);
46
+ return lines.join("\n");
47
+ }
48
+ export function normalizeBudget(budget) {
49
+ if (!budget)
50
+ return undefined;
51
+ const next = {};
52
+ for (const key of ["steps", "wallMin", "usd", "rounds"]) {
53
+ const value = budget[key];
54
+ if (value === undefined)
55
+ continue;
56
+ if (!Number.isFinite(value) || value <= 0) {
57
+ throw new RecoverableToolError(`budget.${key} must be a positive number.`);
58
+ }
59
+ next[key] = value;
47
60
  }
48
- return upsertCurrentCycleCompletionEvidence(body, lines);
61
+ if (budget.until !== undefined)
62
+ next.until = budget.until.trim() || undefined;
63
+ return Object.keys(next).length > 0 ? next : undefined;
49
64
  }
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(", ")}.`);
65
+ export function normalizeSchedule(schedule) {
66
+ if (schedule === undefined)
67
+ return undefined;
68
+ const trimmed = schedule.trim();
69
+ if (!trimmed)
70
+ return null; // explicit clear
71
+ validateTaskSchedule(trimmed);
72
+ return trimmed;
56
73
  }
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
- }
74
+ /**
75
+ * A newly created task starts `open` — even a recurring one. Creation opens its first cycle
76
+ * immediately rather than parking until the next cron occurrence, because "create it and it does
77
+ * nothing until tomorrow morning" was consistently surprising; the cadence still governs every
78
+ * *subsequent* cycle through the `schedule` ticket the loop parks on when it finishes.
79
+ */
80
+ export function renderTaskSkeleton(request, now = new Date()) {
81
+ const schedule = normalizeSchedule(request.schedule);
82
+ const fields = {
83
+ state: "open",
84
+ schedule: schedule ?? undefined,
85
+ // The first cycle opens at creation: steps, rework rounds and cost all accumulate onto a
86
+ // cycle, so a task without one would have nowhere to record what it did.
87
+ cycle: createCycle(nextCycleId(undefined, now), now),
88
+ budget: normalizeBudget(request.budget),
89
+ verify: request.verificationRequired ? "required" : undefined,
90
+ };
79
91
  const body = renderStandardTaskBody({
80
92
  title: request.title,
81
93
  goal: request.goal,
82
94
  dod: request.dod,
83
95
  manual: request.manual,
84
96
  verificationPlan: request.verificationPlan,
85
- verificationRequired: control.verification.required,
97
+ verificationRequired: request.verificationRequired ?? false,
86
98
  plan: request.plan,
87
99
  });
88
100
  return { fields, body };
89
101
  }
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.`);
98
- }
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.`);
102
+ /** The scheduling half of a lifecycle notice: where the task stands and who will wake it. */
103
+ export function describeTaskState(fields) {
104
+ if (fields.paused)
105
+ return `state: ${fields.state}(已暂停:${fields.paused.reason})`;
106
+ if (fields.state === "parked" && fields.ticket) {
107
+ return `state: parked(${describeTicket(fields.ticket)};兜底 ${fields.ticket.by})`;
103
108
  }
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
- };
109
+ return `state: ${fields.state}`;
121
110
  }
122
111
  /**
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.
112
+ * Build the injected lookup a ticket resolver needs. The run/job/event registries are read here —
113
+ * once, at the call site — rather than imported inside `ticket.ts`, which is what keeps the whole
114
+ * validation matrix unit-testable against plain fakes.
128
115
  */
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}` : ""}`;
116
+ export async function buildTicketContext(options, taskId, schedule, now = new Date()) {
117
+ const runManager = getSubAgentRunManager(options.channelId);
118
+ const jobs = await getChannelJobManager(options.channelId, createExecutor())
119
+ .list()
120
+ .catch(() => []);
121
+ const events = await readChannelEvents(options);
122
+ return {
123
+ now,
124
+ taskId,
125
+ channelId: options.channelId,
126
+ schedule,
127
+ findRun: (id) => runManager.get(id),
128
+ findJob: (id) => jobs.find((job) => job.id === id),
129
+ findEvent: (name) => events.get(name),
130
+ };
137
131
  }
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;
132
+ /** Every parseable event definition in the workspace, by name. Missing directory → empty. */
133
+ async function readChannelEvents(options) {
134
+ const dir = eventsDir(options);
135
+ const events = new Map();
136
+ if (!existsSync(dir))
137
+ return events;
138
+ for (const filename of await readdir(dir)) {
139
+ if (!filename.endsWith(".json"))
140
+ continue;
141
+ try {
142
+ const event = parseScheduledEventContent(await readFile(join(dir, filename), "utf-8"), filename);
143
+ events.set(filename.slice(0, -".json".length), {
144
+ type: event.type,
145
+ channelId: event.channelId,
146
+ schedule: event.type === "periodic" ? event.schedule : undefined,
147
+ });
164
148
  }
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
- }
149
+ catch {
150
+ // An unparseable event cannot back a ticket; leave it for /events to clean up.
179
151
  }
180
152
  }
181
- if (request.control !== undefined) {
182
- next.control = applyTaskControlPatch(next.control ?? createDefaultTaskControl(), request.control);
183
- }
184
- return normalizeTaskFields(next);
153
+ return events;
185
154
  }
186
155
  /**
187
156
  * On close-out (complete or cancel), delete every task-owned event.
188
157
  *
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").
158
+ * Matching is done by parsing each candidate name and comparing the full task id, not by prefix —
159
+ * a prefix match on `task.<channel>.<id>.` would also match a *different* task whose id happens to
160
+ * start with this one plus a dot (e.g. closing "v1" must not delete events owned by "v1.2-release").
198
161
  */
199
162
  export async function cleanupTaskEvents(options, id) {
200
163
  const dir = eventsDir(options);
@@ -227,3 +190,29 @@ export async function cleanupTaskEvents(options, id) {
227
190
  }
228
191
  return { deleted };
229
192
  }
193
+ /**
194
+ * The verification gate both close entry points share (`task_step_end outcome=done` and
195
+ * `task_close outcome=complete`).
196
+ *
197
+ * It exists as one function because the two used to ask the question separately and both asked
198
+ * the weaker one — "did a PASS ever land in this cycle" — which a contract edit or a further code
199
+ * change made *after* the PASS would still satisfy. The real check is re-run here, against the
200
+ * contract and the checkout as they stand at close time.
201
+ */
202
+ export async function assertVerificationHoldsForClose(options, document, id) {
203
+ if (document.fields.verify !== "required")
204
+ return;
205
+ const runManager = getSubAgentRunManager(options.channelId);
206
+ const reason = await completionVerificationBlockReason({
207
+ channelDir: options.channelDir,
208
+ taskId: id,
209
+ taskBody: document.body,
210
+ cycleId: document.fields.cycle?.id,
211
+ findRunWorkingDirectory: (runId) => runManager.get(runId)?.workingDirectory,
212
+ fallbackWorkingDirectory: options.workingDirectory,
213
+ });
214
+ if (!reason)
215
+ return;
216
+ throw new RecoverableToolError(`Task "${id}" requires independent verification and it does not currently hold: ${reason}. ` +
217
+ `Dispatch a purpose=verify sub-agent with taskId=${id} against the artifact you are about to deliver, and let its PASS land before finishing.`);
218
+ }
@@ -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>;