@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,27 +1,49 @@
1
- import { createHash } from "node:crypto";
2
1
  import { existsSync } from "node:fs";
3
- import { readFile } from "node:fs/promises";
2
+ import { mkdir, readFile, rename, rm } from "node:fs/promises";
4
3
  import { join } from "node:path";
4
+ import * as log from "../log.js";
5
5
  import { writeFileAtomically } from "../shared/atomic-file.js";
6
- import { formatLocalTime, parseLocalTime } from "../shared/local-time.js";
7
- import { createDefaultTaskControl, resetTaskControlForCycle } from "./control.js";
8
- import { normalizeTaskId, parseTaskFrontmatter, renderTaskDocument, startTaskCycle, taskBody, taskContractSegment, } from "./ledger.js";
6
+ import { formatLocalTime } from "../shared/local-time.js";
7
+ import { createCycle, nextCycleId, openCycleBody, readLastResult, stripLastResult, writeLastResult } from "./cycle.js";
8
+ import { normalizeTaskFrontmatter, parseTaskFrontmatterV4, } from "./frontmatter.js";
9
+ import { normalizeTaskId, renderTaskDocument, taskBody } from "./ledger.js";
10
+ import { appendTaskLog, taskLogPath } from "./log.js";
9
11
  import { withTaskMutation } from "./mutation-lock.js";
10
- import { normalizeStoredStatus, resolveTaskTransition } from "./transitions.js";
12
+ import { describeTicket } from "./ticket.js";
11
13
  /**
12
- * Hash the task's *contract* segment (Goal/DoD/Manual/Verification), not the whole body, so
13
- * verification PASS survives routine Current Cycle / History logging and only breaks when the
14
- * contract itself changes (spec 029, D4). Old attestations that hashed the
15
- * whole body naturally fail this check after upgrade and are re-verified — verification should
16
- * always reflect current content, so there is no compatibility burden.
14
+ * The contract's size budget (INV-6).
15
+ *
16
+ * v3 task files on the author's machine sat permanently at 30 KB, 79% of it closed-cycle history,
17
+ * and every wake read all of it. The contract is injected whole into every step brief, so what it
18
+ * must guarantee is that **runtime-written history cannot grow it** — not that the file is under
19
+ * some number no matter what the user wrote.
20
+ *
21
+ * So the budget is enforced against `## 上次结果` only, the one section the runtime authors and
22
+ * whose full content is always recoverable from `task_log`. Everything else — Goal, DoD, Manual,
23
+ * Verification, Plan — is authored by the user or the planning turn, and the runtime does not get
24
+ * to delete it to hit a number. A contract that still exceeds the budget on authored text alone is
25
+ * written as-is and warned about.
26
+ *
27
+ * The first version clipped the body's tail instead, and the migration rehearsal on real data
28
+ * showed exactly why that was wrong: two tasks with a legitimately long `## Manual` silently lost
29
+ * their `## Verification` and `## Plan` sections — the verifier's instructions and the task's own
30
+ * agenda — to make room.
17
31
  */
18
- export function taskBodyHash(body) {
19
- return createHash("sha256").update(taskContractSegment(body)).digest("hex");
32
+ export const MAX_CONTRACT_BYTES = 4 * 1024;
33
+ const LAST_RESULT_CLIP_NOTE = "…(更早的记录见 task_log)";
34
+ export function tasksDir(channelDir) {
35
+ return join(channelDir, "tasks");
20
36
  }
21
- export async function readStoredTask(channelDir, idInput, includeArchive = false, allowInvalidControl = false) {
37
+ export function taskPath(channelDir, id) {
38
+ return join(tasksDir(channelDir), `${normalizeTaskId(id)}.md`);
39
+ }
40
+ export function archivedTaskPath(channelDir, id) {
41
+ return join(tasksDir(channelDir), "archive", `${normalizeTaskId(id)}.md`);
42
+ }
43
+ export async function readStoredTask(channelDir, idInput, includeArchive = false) {
22
44
  const id = normalizeTaskId(idInput);
23
- const activePath = join(channelDir, "tasks", `${id}.md`);
24
- const archivePath = join(channelDir, "tasks", "archive", `${id}.md`);
45
+ const activePath = taskPath(channelDir, id);
46
+ const archivePath = archivedTaskPath(channelDir, id);
25
47
  const path = existsSync(activePath)
26
48
  ? activePath
27
49
  : includeArchive && existsSync(archivePath)
@@ -30,30 +52,44 @@ export async function readStoredTask(channelDir, idInput, includeArchive = false
30
52
  if (!path)
31
53
  return undefined;
32
54
  const content = await readFile(path, "utf-8");
33
- const frontmatter = parseTaskFrontmatter(content);
34
- if (!frontmatter.readable)
35
- throw new Error(`Task "${id}" has unreadable frontmatter.`);
36
- if (frontmatter.controlReadable === false && !allowInvalidControl) {
37
- throw new Error(`Task "${id}" has unreadable control metadata.`);
38
- }
39
- return {
40
- id,
41
- path,
42
- fields: {
43
- status: frontmatter.status ?? "active",
44
- legacyStatus: frontmatter.rawStatus,
45
- enabled: frontmatter.enabled,
46
- wake: frontmatter.wake,
47
- schedule: frontmatter.schedule,
48
- control: frontmatter.control,
49
- outcome: frontmatter.archiveOutcome,
50
- closedAt: frontmatter.closedAt,
51
- },
52
- body: taskBody(content),
53
- };
55
+ const parsed = parseTaskFrontmatterV4(content);
56
+ return { id, path, fields: parsed.fields, body: taskBody(content) };
57
+ }
58
+ /** Clip a body that would push the contract over budget, keeping the head (the contract proper). */
59
+ /** Shrink `## 上次结果` toward the budget; returns the body unchanged when there is none. */
60
+ function clipLastResult(body, overBy) {
61
+ const existing = readLastResult(body);
62
+ if (!existing)
63
+ return body;
64
+ // Cut on a character boundary: slicing a Buffer could split a multi-byte codepoint and write a
65
+ // replacement character into a hand-editable file.
66
+ const buffer = Buffer.from(existing, "utf-8");
67
+ const keepBytes = Math.max(0, buffer.byteLength - overBy - Buffer.byteLength(LAST_RESULT_CLIP_NOTE, "utf-8"));
68
+ if (keepBytes <= 0)
69
+ return stripLastResult(body);
70
+ let clipped = new TextDecoder("utf-8", { fatal: false }).decode(buffer.subarray(0, keepBytes));
71
+ clipped = clipped.replace(/\uFFFD+$/, "");
72
+ const lastNewline = clipped.lastIndexOf("\n");
73
+ if (lastNewline > 0)
74
+ clipped = clipped.slice(0, lastNewline);
75
+ return writeLastResult(body, `${clipped.trimEnd()}${LAST_RESULT_CLIP_NOTE}`);
76
+ }
77
+ function enforceContractBudget(id, fields, body) {
78
+ const size = (candidate) => Buffer.byteLength(renderTaskDocument(fields, candidate), "utf-8");
79
+ if (size(body) <= MAX_CONTRACT_BYTES)
80
+ return body;
81
+ const clipped = clipLastResult(body, size(body) - MAX_CONTRACT_BYTES);
82
+ if (size(clipped) <= MAX_CONTRACT_BYTES)
83
+ return clipped;
84
+ // Authored text alone is over budget. Keep it — deleting a user's Manual or Verification to hit
85
+ // a number is worse than a large file — and say so once per write so it is not silently normal.
86
+ log.logWarning(`Task ${id} exceeds the ${MAX_CONTRACT_BYTES}-byte contract budget`, `${size(clipped)} bytes after clipping 上次结果; shorten Goal/DoD/Manual/Verification, or move detail into the loop log.`);
87
+ return clipped;
54
88
  }
55
89
  export async function writeStoredTask(document) {
56
- await writeFileAtomically(document.path, renderTaskDocument(document.fields, document.body));
90
+ const fields = normalizeTaskFrontmatter(document.fields);
91
+ const body = enforceContractBudget(document.id, fields, document.body);
92
+ await writeFileAtomically(document.path, renderTaskDocument(fields, body));
57
93
  }
58
94
  export async function updateStoredTask(channelDir, id, update, includeArchive = false) {
59
95
  return withTaskMutation(channelDir, id, async () => {
@@ -66,95 +102,118 @@ export async function updateStoredTask(channelDir, id, update, includeArchive =
66
102
  });
67
103
  }
68
104
  /**
69
- * A governor stop: disable the task without changing its lifecycle stage or wake. The structured
70
- * stop record is the durable recovery receipt; notification is handled by the runtime driver.
105
+ * Park a task on a ticket. The ticket must already have been through `resolveTicket` — this
106
+ * function persists a decision, it does not make one.
71
107
  */
72
- export async function escalateTask(channelDir, id, reason) {
73
- const document = await updateStoredTask(channelDir, id, (task) => {
74
- const status = normalizeStoredStatus(task.fields.status);
75
- resolveTaskTransition("governor-stop", id, status);
76
- task.fields.enabled = false;
77
- task.fields.control ??= createDefaultTaskControl();
78
- task.fields.control.stop = { by: "governor", reason, at: formatLocalTime() };
108
+ export async function parkTask(channelDir, id, ticket) {
109
+ return updateStoredTask(channelDir, id, (task) => {
110
+ task.fields.state = "parked";
111
+ task.fields.ticket = ticket;
79
112
  });
80
- return document !== undefined;
81
113
  }
82
114
  /**
83
- * Atomically convert a due/completion-woken task to active. Idempotent by construction: once a
84
- * task is no longer `waiting`, a redelivered wake or retry finds `status !== "waiting"` and is a
85
- * safe no-op, so no separate claim/handoff bookkeeping is needed to detect a duplicate activation.
115
+ * Redeem a ticket: the single, idempotent transition from `parked` back to `open`.
86
116
  *
87
- * Wake legitimacy is entirely the caller's responsibility (spec 043's `waitingFor`
88
- * de-authorization): a completion wake reaches here only after the caller has verified an
89
- * actually-settled run/job whose own recorded `taskId` names this task (`task-wake.ts`'s
90
- * `isVerified*Wake`). `waitingFor` itself is display-only and never gates activation.
117
+ * Idempotent by construction — a task that is no longer parked, or is parked on a *different*
118
+ * ticket, is a no-op. That is what lets every producer (run settlement, job settlement, the
119
+ * events watcher, `/tasks reply`, the driver's timer) push at-least-once without any of them
120
+ * needing its own claim bookkeeping: the outermost wake-claim in `wake-claim.ts` still guards
121
+ * duplicate delivery, and this guards duplicate application.
91
122
  */
92
- export async function activateWaitingTask(channelDir, id, hooks) {
93
- let activated = false;
123
+ export async function redeemTicket(channelDir, id, matches) {
124
+ let redeemed;
94
125
  const document = await updateStoredTask(channelDir, id, (task) => {
95
- const status = normalizeStoredStatus(task.fields.status);
96
- if (status !== "waiting" || task.fields.enabled === false)
126
+ if (task.fields.state !== "parked" || !task.fields.ticket || task.fields.paused)
97
127
  return;
98
- hooks?.beforeActivation?.();
99
- activated = true;
100
- task.fields.control ??= createDefaultTaskControl();
101
- task.fields.status = "active";
102
- task.fields.wake = undefined;
103
- if (task.fields.control)
104
- task.fields.control.waitingFor = undefined;
128
+ if (!matches(task.fields.ticket))
129
+ return;
130
+ redeemed = task.fields.ticket;
131
+ task.fields.state = "open";
132
+ task.fields.ticket = undefined;
105
133
  });
106
- return activated ? document : undefined;
134
+ return document && redeemed ? { document, ticket: redeemed } : undefined;
107
135
  }
108
- /** Return a task to waiting after a transport failed to accept its just-activated turn. */
109
- export async function rollbackWaitingTask(channelDir, id, waitingFor) {
110
- await updateStoredTask(channelDir, id, (task) => {
111
- if (task.fields.status !== "active")
112
- return;
113
- task.fields.status = "waiting";
114
- task.fields.wake = undefined;
115
- if (task.fields.control)
116
- task.fields.control.waitingFor = waitingFor;
136
+ /** Disable a task without losing its stage. `paused` present *is* the disabled state (D1). */
137
+ export async function pauseTask(channelDir, id, paused) {
138
+ return updateStoredTask(channelDir, id, (task) => {
139
+ task.fields.paused = { ...paused, at: paused.at ?? formatLocalTime() };
117
140
  });
118
141
  }
119
- /**
120
- * A stable cycle id for a runtime-opened recurring cycle: `cycle-YYYY-MM-DD`, disambiguated
121
- * with a `-N` suffix when the same task is reopened more than once on the same local day.
122
- */
123
- export function nextCycleId(previousCycleId, occurrence) {
124
- const base = `cycle-${occurrence.getFullYear()}-${String(occurrence.getMonth() + 1).padStart(2, "0")}-${String(occurrence.getDate()).padStart(2, "0")}`;
125
- if (!previousCycleId || !previousCycleId.startsWith(base))
126
- return base;
127
- const suffix = previousCycleId.slice(base.length + 1);
128
- const previousCount = suffix ? Number.parseInt(suffix, 10) : 1;
129
- const nextCount = Number.isFinite(previousCount) && previousCount >= 1 ? previousCount + 1 : 2;
130
- return `${base}-${nextCount}`;
142
+ export async function resumeTask(channelDir, id) {
143
+ return updateStoredTask(channelDir, id, (task) => {
144
+ task.fields.paused = undefined;
145
+ });
146
+ }
147
+ export async function expireTicket(channelDir, id, limit = 2) {
148
+ let outcome;
149
+ let summary = "";
150
+ const document = await updateStoredTask(channelDir, id, (task) => {
151
+ const ticket = task.fields.ticket;
152
+ if (task.fields.state !== "parked" || !ticket || task.fields.paused)
153
+ return;
154
+ summary = describeTicket(ticket);
155
+ const expired = (task.fields.cycle?.expired ?? 0) + 1;
156
+ if (task.fields.cycle)
157
+ task.fields.cycle = { ...task.fields.cycle, expired };
158
+ if (expired >= limit) {
159
+ outcome = "paused";
160
+ task.fields.paused = {
161
+ by: "runtime",
162
+ reason: `等待票连续 ${expired} 次未兑现:${summary}`,
163
+ at: formatLocalTime(),
164
+ };
165
+ return;
166
+ }
167
+ outcome = "reopened";
168
+ task.fields.state = "open";
169
+ task.fields.ticket = undefined;
170
+ });
171
+ if (!document || !outcome)
172
+ return undefined;
173
+ await appendTaskLog(channelDir, id, {
174
+ cycle: document.fields.cycle?.id ?? "-",
175
+ kind: "expired",
176
+ ticket: summary,
177
+ action: outcome,
178
+ });
179
+ return { document, outcome, ticket: summary };
131
180
  }
132
181
  /**
133
- * Open the next cycle of a sleeping recurring task entirely in the runtime (spec 029, D2):
134
- * fold the previous cycle's log into History, reset per-cycle control, clear the wake, and
135
- * mark it `active`. This is the deterministic replacement for the retired
136
- * no LLM turn is spent just to reopen a cycle.
182
+ * Open the next cycle: fresh counters, a fresh cycle id, and (for a recurring task) a Plan and
183
+ * acceptance checklist reset. Deterministic and zero-token — no LLM turn is spent just to start
184
+ * a cycle, which is why a missed occurrence can self-heal without waking anything.
137
185
  */
138
- export async function openRecurringTaskCycle(channelDir, id, now, force = false) {
186
+ export async function openCycle(channelDir, id, now = new Date()) {
139
187
  let cycleId;
140
188
  const document = await updateStoredTask(channelDir, id, (task) => {
141
- const status = normalizeStoredStatus(task.fields.status);
142
- if (status !== "sleeping" || !task.fields.schedule)
189
+ if (task.fields.paused || task.fields.outcome)
143
190
  return;
144
- const wakeMs = task.fields.wake ? parseLocalTime(task.fields.wake) : undefined;
145
- if (!force && (task.fields.enabled === false || wakeMs === undefined || wakeMs > now.getTime()))
146
- return;
147
- const occurrence = !force && wakeMs !== undefined ? new Date(wakeMs) : now;
148
- cycleId = nextCycleId(task.fields.control?.cycleId, occurrence);
149
- task.fields.control ??= createDefaultTaskControl();
150
- const firstCycle = !task.fields.control.cycleId;
151
- task.body = startTaskCycle(task.body, cycleId, !firstCycle);
152
- task.fields.status = "active";
153
- task.fields.enabled = true;
154
- task.fields.wake = undefined;
155
- task.fields.control = resetTaskControlForCycle(task.fields.control, cycleId);
191
+ cycleId = nextCycleId(task.fields.cycle?.id, now);
192
+ const recurring = Boolean(task.fields.schedule) && Boolean(task.fields.cycle);
193
+ task.body = openCycleBody(task.body, recurring);
194
+ task.fields.cycle = createCycle(cycleId, now);
195
+ task.fields.state = "open";
196
+ task.fields.ticket = undefined;
156
197
  });
157
198
  if (!document || !cycleId)
158
199
  return undefined;
159
200
  return { document, cycleId };
160
201
  }
202
+ /** Move a closed task (and its log) into `tasks/archive/`. */
203
+ export async function archiveTask(channelDir, id, outcome) {
204
+ const normalized = normalizeTaskId(id);
205
+ const archiveDir = join(tasksDir(channelDir), "archive");
206
+ await mkdir(archiveDir, { recursive: true });
207
+ const document = await readStoredTask(channelDir, normalized);
208
+ if (!document)
209
+ return;
210
+ document.fields.outcome = outcome;
211
+ document.fields.closedAt = formatLocalTime();
212
+ await writeStoredTask({ ...document, path: archivedTaskPath(channelDir, normalized) });
213
+ await rm(taskPath(channelDir, normalized), { force: true });
214
+ // The loop log travels with its contract so an archived task stays inspectable.
215
+ const logFrom = taskLogPath(channelDir, normalized);
216
+ if (existsSync(logFrom)) {
217
+ await rename(logFrom, join(archiveDir, `${normalized}.jsonl`)).catch(() => undefined);
218
+ }
219
+ }
@@ -0,0 +1,102 @@
1
+ /**
2
+ * The waiting ticket (spec 051, D2) — the only way a task may park.
3
+ *
4
+ * Spec 050-era `waiting` carried a `waitingFor` enum whose own doc comment said it was
5
+ * "diagnostic display only; it does not gate wake activation". The single field describing what a
6
+ * task was waiting for was, by design, unrelated to whether that wait could ever end — and both
7
+ * of the real long-lived tasks on the author's machine died of exactly that: parked with no
8
+ * redeemable source, silent for 9 and 13 days respectively while the governor watched for tasks
9
+ * that spun too much.
10
+ *
11
+ * A ticket fixes that by being a claim the runtime can check at write time (the run exists, is
12
+ * unsettled, and names this task) and, crucially, by always carrying `by` — a backstop instant
13
+ * after which the runtime reopens the task rather than leaving it parked forever. That is
14
+ * D2-INV: a parked task either gets redeemed, or the user hears about it.
15
+ */
16
+ export type TicketKind = "time" | "schedule" | "run" | "job" | "ask" | "signal";
17
+ export type Ticket = {
18
+ kind: "time";
19
+ at: string;
20
+ by: string;
21
+ } | {
22
+ kind: "schedule";
23
+ at: string;
24
+ by: string;
25
+ } | {
26
+ kind: "run";
27
+ id: string;
28
+ by: string;
29
+ } | {
30
+ kind: "job";
31
+ id: string;
32
+ by: string;
33
+ } | {
34
+ kind: "ask";
35
+ asked: string;
36
+ by: string;
37
+ } | {
38
+ kind: "signal";
39
+ event: string;
40
+ by: string;
41
+ };
42
+ /** The minimum a ticket resolver needs to know about a delegation run. */
43
+ export interface TicketRunRef {
44
+ taskId?: string;
45
+ settledAt?: number;
46
+ startedAt: number;
47
+ deadlineAt?: number;
48
+ maxWallTimeSec?: number;
49
+ }
50
+ /** The minimum a ticket resolver needs to know about a background job. */
51
+ export interface TicketJobRef {
52
+ taskId?: string;
53
+ status: string;
54
+ startedAt: number;
55
+ }
56
+ /** The minimum a ticket resolver needs to know about a scheduled event. */
57
+ export interface TicketEventRef {
58
+ type: "one-shot" | "periodic";
59
+ channelId: string;
60
+ schedule?: string;
61
+ }
62
+ /**
63
+ * Everything `resolveTicket` may consult, injected rather than imported: the run/job/event
64
+ * registries are stateful singletons, and keeping them out of this module is what makes the whole
65
+ * validation matrix unit-testable without a runtime.
66
+ */
67
+ export interface TicketContext {
68
+ now: Date;
69
+ taskId: string;
70
+ channelId: string;
71
+ /** The task's own cron cadence; required for a `schedule` ticket. */
72
+ schedule?: string;
73
+ findRun(id: string): TicketRunRef | undefined;
74
+ findJob(id: string): TicketJobRef | undefined;
75
+ findEvent(name: string): TicketEventRef | undefined;
76
+ }
77
+ /**
78
+ * Validate one model-supplied ticket and stamp its backstop.
79
+ *
80
+ * This is the **only** way a `Ticket` value comes into existence — the migrator, `task_step_end`
81
+ * and the `/tasks` commands all funnel through it. Anything that writes the `ticket` frontmatter
82
+ * field directly is a defect: it would produce a park with no verified source or no `by`, which
83
+ * is precisely the failure this whole mechanism exists to make impossible.
84
+ */
85
+ export declare function resolveTicket(input: unknown, ctx: TicketContext): Ticket;
86
+ /** Read a persisted ticket back. Returns `undefined` for anything not shaped like a v4 ticket. */
87
+ export declare function parseTicket(raw: string): Ticket | undefined;
88
+ /** Milliseconds of the ticket's backstop, or `undefined` when it is unparseable (never trusted). */
89
+ export declare function ticketBackstopMs(ticket: Ticket): number | undefined;
90
+ /**
91
+ * Whether this ticket's backstop has passed. An unparseable `by` counts as expired: a park whose
92
+ * deadline cannot be read is exactly the silent-forever state D2-INV forbids, so it fails toward
93
+ * waking the task rather than toward leaving it buried.
94
+ */
95
+ export declare function ticketExpired(ticket: Ticket, now?: Date): boolean;
96
+ /**
97
+ * The moment a `time` ticket is *due* (as opposed to its backstop). Only `time` and `schedule`
98
+ * tickets are driver-polled; every other kind is pushed by its owner, so they have no due time.
99
+ */
100
+ export declare function ticketDueMs(ticket: Ticket): number | undefined;
101
+ /** One-line summary for `/tasks`, receipts, and the step brief. */
102
+ export declare function describeTicket(ticket: Ticket): string;
@@ -0,0 +1,209 @@
1
+ import { formatLocalTime, parseLocalTime, parseWakeInput } from "../shared/local-time.js";
2
+ import { RecoverableToolError } from "../shared/recoverable-error.js";
3
+ import { isPlainObject } from "../shared/type-guards.js";
4
+ import { nextTaskWake } from "./task-schedule.js";
5
+ const TICKET_KINDS = ["time", "schedule", "run", "job", "ask", "signal"];
6
+ /** A ticket the runtime cannot pin to a real occurrence still gets a backstop this far out. */
7
+ const DEFAULT_BACKSTOP_MS = 24 * 60 * 60 * 1000;
8
+ /** Slack added to a run's own wall-clock deadline before the task gives up on it. */
9
+ const RUN_BACKSTOP_SLACK_MS = 10 * 60 * 1000;
10
+ function requiredString(value, field) {
11
+ if (typeof value !== "string" || !value.trim()) {
12
+ throw new RecoverableToolError(`ticket.${field} is required and must be a non-empty string.`);
13
+ }
14
+ return value.trim();
15
+ }
16
+ /**
17
+ * The interval between the next two occurrences of `cron` after `from`, or `undefined` when the
18
+ * cron does not fire at least twice. Used to express backstops as "one/two missed occurrences"
19
+ * rather than a fixed wall-clock guess, so a 30-minute sensor and a monthly job get proportionate
20
+ * patience from the same rule.
21
+ */
22
+ function occurrenceInterval(cron, from) {
23
+ const first = nextTaskWake(cron, from);
24
+ if (!first)
25
+ return undefined;
26
+ const second = nextTaskWake(cron, first);
27
+ if (!second)
28
+ return { first, intervalMs: DEFAULT_BACKSTOP_MS };
29
+ return { first, intervalMs: second.getTime() - first.getTime() };
30
+ }
31
+ function scheduleBackstop(cron, now, missedOccurrences) {
32
+ const occurrence = occurrenceInterval(cron, now);
33
+ if (!occurrence) {
34
+ throw new RecoverableToolError(`schedule "${cron}" never fires again; it cannot back a ticket.`);
35
+ }
36
+ return formatLocalTime(new Date(occurrence.first.getTime() + occurrence.intervalMs * missedOccurrences));
37
+ }
38
+ /**
39
+ * Validate one model-supplied ticket and stamp its backstop.
40
+ *
41
+ * This is the **only** way a `Ticket` value comes into existence — the migrator, `task_step_end`
42
+ * and the `/tasks` commands all funnel through it. Anything that writes the `ticket` frontmatter
43
+ * field directly is a defect: it would produce a park with no verified source or no `by`, which
44
+ * is precisely the failure this whole mechanism exists to make impossible.
45
+ */
46
+ export function resolveTicket(input, ctx) {
47
+ if (!isPlainObject(input)) {
48
+ throw new RecoverableToolError(`ticket must be an object with a "kind" of: ${TICKET_KINDS.join(", ")}.`);
49
+ }
50
+ const kind = input.kind;
51
+ if (typeof kind !== "string" || !TICKET_KINDS.includes(kind)) {
52
+ throw new RecoverableToolError(`Unknown ticket kind "${String(kind)}". Use one of: ${TICKET_KINDS.join(", ")}.`);
53
+ }
54
+ const nowMs = ctx.now.getTime();
55
+ switch (kind) {
56
+ case "time": {
57
+ const raw = requiredString(input.at, "at");
58
+ const atMs = parseWakeInput(raw, ctx.now);
59
+ if (atMs === undefined) {
60
+ throw new RecoverableToolError(`ticket.at "${raw}" is not a valid local time or relative offset (e.g. 2026-09-06T09:00:00+08:00, +2h).`);
61
+ }
62
+ if (atMs <= nowMs) {
63
+ throw new RecoverableToolError(`ticket.at "${raw}" is not in the future; a time ticket must wait for something.`);
64
+ }
65
+ const at = formatLocalTime(new Date(atMs));
66
+ return { kind: "time", at, by: at };
67
+ }
68
+ case "schedule": {
69
+ if (!ctx.schedule) {
70
+ throw new RecoverableToolError("A schedule ticket needs the task to have a `schedule` cron. Set one, or park on a time ticket instead.");
71
+ }
72
+ // The occurrence is stamped, not recomputed on read: a ticket must name a fixed moment,
73
+ // or "is it due yet?" would keep answering "not yet" as the cron rolls forward.
74
+ const occurrence = occurrenceInterval(ctx.schedule, ctx.now);
75
+ if (!occurrence) {
76
+ throw new RecoverableToolError(`schedule "${ctx.schedule}" never fires again; it cannot back a ticket.`);
77
+ }
78
+ return {
79
+ kind: "schedule",
80
+ at: formatLocalTime(occurrence.first),
81
+ by: scheduleBackstop(ctx.schedule, ctx.now, 1),
82
+ };
83
+ }
84
+ case "run": {
85
+ const id = requiredString(input.id, "id");
86
+ const run = ctx.findRun(id);
87
+ if (!run) {
88
+ throw new RecoverableToolError(`No run "${id}" in this channel. Use subagent_list to find the right id, or park on a different ticket.`);
89
+ }
90
+ if (run.settledAt !== undefined) {
91
+ throw new RecoverableToolError(`Run ${id} already settled; read its result and continue instead of parking on it.`);
92
+ }
93
+ if (run.taskId !== ctx.taskId) {
94
+ throw new RecoverableToolError(`Run ${id} belongs to task ${run.taskId ?? "(none)"}; it will never wake this task. Dispatch with taskId=${ctx.taskId}.`);
95
+ }
96
+ const deadline = run.deadlineAt ?? (run.maxWallTimeSec ? run.startedAt + run.maxWallTimeSec * 1000 : undefined);
97
+ const by = (deadline ?? run.startedAt + DEFAULT_BACKSTOP_MS) + RUN_BACKSTOP_SLACK_MS;
98
+ return { kind: "run", id, by: formatLocalTime(new Date(by)) };
99
+ }
100
+ case "job": {
101
+ const id = requiredString(input.id, "id");
102
+ const job = ctx.findJob(id);
103
+ if (!job) {
104
+ throw new RecoverableToolError(`No job "${id}" in this channel. Use job op=list to find the right id, or park on a different ticket.`);
105
+ }
106
+ if (job.status !== "running") {
107
+ throw new RecoverableToolError(`Job ${id} is ${job.status}; read its output and continue instead of parking on it.`);
108
+ }
109
+ if (job.taskId !== ctx.taskId) {
110
+ throw new RecoverableToolError(`Job ${id} belongs to task ${job.taskId ?? "(none)"}; it will never wake this task. Relaunch it with taskId=${ctx.taskId}.`);
111
+ }
112
+ return { kind: "job", id, by: formatLocalTime(new Date(job.startedAt + DEFAULT_BACKSTOP_MS)) };
113
+ }
114
+ case "ask": {
115
+ const asked = requiredString(input.asked, "asked");
116
+ return { kind: "ask", asked, by: formatLocalTime(new Date(nowMs + DEFAULT_BACKSTOP_MS)) };
117
+ }
118
+ case "signal": {
119
+ const name = requiredString(input.event, "event");
120
+ const event = ctx.findEvent(name);
121
+ if (!event) {
122
+ throw new RecoverableToolError(`No event "${name}" in this workspace. Create it with event_manage first, or park on a time ticket.`);
123
+ }
124
+ if (event.channelId !== ctx.channelId) {
125
+ throw new RecoverableToolError(`Event "${name}" belongs to another channel; it cannot wake this task.`);
126
+ }
127
+ if (event.type !== "periodic" || !event.schedule) {
128
+ throw new RecoverableToolError(`Event "${name}" is one-shot; a sensor must be periodic. Use a time ticket instead.`);
129
+ }
130
+ // The event must name this task: a signal ticket is redeemed by the events watcher on a
131
+ // pure name match, so accepting an unrelated event's name here would create a park that
132
+ // nothing can ever redeem (INV-7's write-side half).
133
+ const expectedPrefix = `task.${ctx.channelId}.${ctx.taskId}.`;
134
+ if (!name.startsWith(expectedPrefix)) {
135
+ throw new RecoverableToolError(`Event "${name}" does not belong to this task; a signal ticket needs an event named ${expectedPrefix}<use>.`);
136
+ }
137
+ return { kind: "signal", event: name, by: scheduleBackstop(event.schedule, ctx.now, 2) };
138
+ }
139
+ }
140
+ }
141
+ /** Read a persisted ticket back. Returns `undefined` for anything not shaped like a v4 ticket. */
142
+ export function parseTicket(raw) {
143
+ let value;
144
+ try {
145
+ value = JSON.parse(raw);
146
+ }
147
+ catch {
148
+ return undefined;
149
+ }
150
+ if (!isPlainObject(value))
151
+ return undefined;
152
+ const kind = value.kind;
153
+ const by = typeof value.by === "string" ? value.by.trim() : "";
154
+ if (typeof kind !== "string" || !TICKET_KINDS.includes(kind) || !by)
155
+ return undefined;
156
+ if (parseLocalTime(by) === undefined)
157
+ return undefined;
158
+ switch (kind) {
159
+ case "time":
160
+ return typeof value.at === "string" && value.at ? { kind: "time", at: value.at, by } : undefined;
161
+ case "schedule":
162
+ return typeof value.at === "string" && value.at ? { kind: "schedule", at: value.at, by } : undefined;
163
+ case "run":
164
+ return typeof value.id === "string" && value.id ? { kind: "run", id: value.id, by } : undefined;
165
+ case "job":
166
+ return typeof value.id === "string" && value.id ? { kind: "job", id: value.id, by } : undefined;
167
+ case "ask":
168
+ return typeof value.asked === "string" && value.asked ? { kind: "ask", asked: value.asked, by } : undefined;
169
+ case "signal":
170
+ return typeof value.event === "string" && value.event ? { kind: "signal", event: value.event, by } : undefined;
171
+ }
172
+ }
173
+ /** Milliseconds of the ticket's backstop, or `undefined` when it is unparseable (never trusted). */
174
+ export function ticketBackstopMs(ticket) {
175
+ return parseLocalTime(ticket.by);
176
+ }
177
+ /**
178
+ * Whether this ticket's backstop has passed. An unparseable `by` counts as expired: a park whose
179
+ * deadline cannot be read is exactly the silent-forever state D2-INV forbids, so it fails toward
180
+ * waking the task rather than toward leaving it buried.
181
+ */
182
+ export function ticketExpired(ticket, now = new Date()) {
183
+ const by = ticketBackstopMs(ticket);
184
+ return by === undefined || by <= now.getTime();
185
+ }
186
+ /**
187
+ * The moment a `time` ticket is *due* (as opposed to its backstop). Only `time` and `schedule`
188
+ * tickets are driver-polled; every other kind is pushed by its owner, so they have no due time.
189
+ */
190
+ export function ticketDueMs(ticket) {
191
+ return ticket.kind === "time" || ticket.kind === "schedule" ? parseLocalTime(ticket.at) : undefined;
192
+ }
193
+ /** One-line summary for `/tasks`, receipts, and the step brief. */
194
+ export function describeTicket(ticket) {
195
+ switch (ticket.kind) {
196
+ case "time":
197
+ return `等待时间 ${ticket.at}`;
198
+ case "schedule":
199
+ return `等待下一次计划唤醒 ${ticket.at}`;
200
+ case "run":
201
+ return `等待委派 ${ticket.id}`;
202
+ case "job":
203
+ return `等待作业 ${ticket.id}`;
204
+ case "ask":
205
+ return `等待用户回答:${ticket.asked}`;
206
+ case "signal":
207
+ return `等待事件 ${ticket.event}`;
208
+ }
209
+ }