@oyasmi/pipiclaw 0.9.5-beta.2 → 0.9.5-beta.3

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 (272) hide show
  1. package/README.en.md +9 -11
  2. package/README.md +9 -11
  3. package/dist/agent/channel-runner.d.ts +12 -24
  4. package/dist/agent/channel-runner.js +74 -30
  5. package/dist/agent/maintenance-context.d.ts +2 -0
  6. package/dist/agent/maintenance-context.js +15 -0
  7. package/dist/agent/prompt/sections.js +8 -6
  8. package/dist/agent/prompt/types.d.ts +1 -1
  9. package/dist/agent/runner-factory.js +1 -1
  10. package/dist/agent/session/command-extension.js +11 -0
  11. package/dist/agent/session/compaction-summary.js +6 -2
  12. package/dist/agent/session/execution-trace.d.ts +14 -0
  13. package/dist/agent/session/execution-trace.js +57 -0
  14. package/dist/agent/session/session-events.d.ts +2 -7
  15. package/dist/agent/session/session-events.js +35 -12
  16. package/dist/agent/session/session-host.d.ts +12 -22
  17. package/dist/agent/session/session-host.js +46 -65
  18. package/dist/agent/turn/task-digest.d.ts +1 -2
  19. package/dist/agent/turn/task-digest.js +33 -33
  20. package/dist/agent/turn/turn-context.d.ts +1 -1
  21. package/dist/agent/turn/turn-context.js +1 -1
  22. package/dist/agent/turn/turn-finish.d.ts +2 -2
  23. package/dist/agent/turn/turn-finish.js +3 -2
  24. package/dist/agent/turn/turn-pipeline.d.ts +4 -2
  25. package/dist/agent/turn/turn-pipeline.js +33 -5
  26. package/dist/agent/types.d.ts +64 -14
  27. package/dist/agent/types.js +3 -0
  28. package/dist/app/home.js +3 -4
  29. package/dist/channel/channel-event.d.ts +4 -12
  30. package/dist/channel/ingress.d.ts +1 -9
  31. package/dist/channel/store.d.ts +1 -1
  32. package/dist/commands/catalog.js +25 -19
  33. package/dist/commands/router.d.ts +5 -2
  34. package/dist/commands/router.js +9 -4
  35. package/dist/config/settings.d.ts +5 -12
  36. package/dist/config/settings.js +0 -7
  37. package/dist/config/tools.d.ts +2 -2
  38. package/dist/config/tools.js +2 -2
  39. package/dist/dingtalk/bot.d.ts +2 -0
  40. package/dist/dingtalk/bot.js +4 -0
  41. package/dist/dingtalk/cards.d.ts +7 -0
  42. package/dist/dingtalk/cards.js +32 -2
  43. package/dist/dingtalk/delivery.d.ts +5 -1
  44. package/dist/dingtalk/delivery.js +157 -142
  45. package/dist/dingtalk/progress.d.ts +55 -6
  46. package/dist/dingtalk/progress.js +195 -16
  47. package/dist/file-store.d.ts +4 -0
  48. package/dist/file-store.js +6 -1
  49. package/dist/jobs/completion-observer.d.ts +20 -0
  50. package/dist/jobs/completion-observer.js +107 -0
  51. package/dist/jobs/completion-signal.d.ts +9 -0
  52. package/dist/jobs/completion-signal.js +32 -0
  53. package/dist/jobs/completion-wake.d.ts +1 -1
  54. package/dist/jobs/completion-wake.js +2 -13
  55. package/dist/jobs/manager.d.ts +11 -29
  56. package/dist/jobs/manager.js +103 -176
  57. package/dist/jobs/probe.d.ts +3 -0
  58. package/dist/jobs/probe.js +42 -0
  59. package/dist/jobs/record.d.ts +3 -6
  60. package/dist/jobs/runtime.d.ts +28 -0
  61. package/dist/jobs/runtime.js +69 -0
  62. package/dist/memory/boundary-work.d.ts +2 -0
  63. package/dist/memory/boundary-work.js +79 -37
  64. package/dist/memory/commands.js +4 -1
  65. package/dist/memory/index-budget.js +18 -15
  66. package/dist/memory/journal.js +2 -1
  67. package/dist/memory/lifecycle.d.ts +4 -8
  68. package/dist/memory/lifecycle.js +21 -51
  69. package/dist/memory/reflect-job.d.ts +0 -6
  70. package/dist/memory/reflect-job.js +13 -34
  71. package/dist/memory/reflect.d.ts +4 -0
  72. package/dist/memory/reflect.js +32 -5
  73. package/dist/memory/review-log.d.ts +13 -0
  74. package/dist/memory/review-log.js +49 -0
  75. package/dist/memory/search.js +7 -4
  76. package/dist/memory/source-window.d.ts +18 -1
  77. package/dist/memory/source-window.js +59 -9
  78. package/dist/memory/store.d.ts +2 -0
  79. package/dist/memory/store.js +45 -13
  80. package/dist/playbooks/agent-delegation.md +10 -4
  81. package/dist/playbooks/background-jobs.md +4 -4
  82. package/dist/playbooks/event-scheduling.md +2 -2
  83. package/dist/playbooks/memory-and-learning.md +3 -3
  84. package/dist/playbooks/outbound-media.md +2 -2
  85. package/dist/playbooks/runtime-orientation.md +10 -6
  86. package/dist/playbooks/task-lead.md +54 -33
  87. package/dist/runtime/bootstrap.d.ts +11 -24
  88. package/dist/runtime/bootstrap.js +92 -59
  89. package/dist/runtime/channel-queue.d.ts +2 -0
  90. package/dist/runtime/channel-queue.js +5 -1
  91. package/dist/runtime/durable-dispatch.d.ts +7 -0
  92. package/dist/runtime/durable-dispatch.js +66 -7
  93. package/dist/runtime/ingress-busy.d.ts +1 -2
  94. package/dist/runtime/ingress-busy.js +2 -35
  95. package/dist/runtime/ingress-commands.d.ts +1 -1
  96. package/dist/runtime/ingress-commands.js +28 -20
  97. package/dist/runtime/ingress-deps.d.ts +4 -7
  98. package/dist/runtime/ingress.js +23 -13
  99. package/dist/runtime/shutdown.d.ts +1 -1
  100. package/dist/runtime/shutdown.js +2 -2
  101. package/dist/runtime/task-close.d.ts +4 -0
  102. package/dist/runtime/task-close.js +102 -0
  103. package/dist/runtime/task-control.d.ts +34 -0
  104. package/dist/runtime/task-control.js +225 -0
  105. package/dist/runtime/task-input.d.ts +13 -0
  106. package/dist/runtime/task-input.js +129 -0
  107. package/dist/runtime/task-lane-types.d.ts +123 -0
  108. package/dist/runtime/task-lane-types.js +14 -0
  109. package/dist/runtime/task-lane.d.ts +99 -0
  110. package/dist/runtime/task-lane.js +703 -0
  111. package/dist/runtime/task-pending.d.ts +8 -0
  112. package/dist/runtime/task-pending.js +40 -0
  113. package/dist/runtime/task-spawn.d.ts +4 -4
  114. package/dist/runtime/task-spawn.js +4 -4
  115. package/dist/runtime/task-step.d.ts +32 -0
  116. package/dist/runtime/task-step.js +276 -0
  117. package/dist/runtime/turn-run.d.ts +4 -16
  118. package/dist/runtime/turn-run.js +17 -155
  119. package/dist/runtime/wake-coalescing.d.ts +1 -3
  120. package/dist/runtime/wake-coalescing.js +2 -4
  121. package/dist/shared/format.d.ts +0 -6
  122. package/dist/shared/format.js +0 -17
  123. package/dist/shared/host-process.d.ts +2 -0
  124. package/dist/shared/host-process.js +16 -1
  125. package/dist/shared/jsonl-appender.d.ts +5 -0
  126. package/dist/shared/jsonl-appender.js +25 -2
  127. package/dist/skills/catalog.d.ts +9 -0
  128. package/dist/skills/catalog.js +34 -0
  129. package/dist/skills/commands.d.ts +3 -12
  130. package/dist/skills/commands.js +36 -22
  131. package/dist/skills/loader.d.ts +2 -31
  132. package/dist/skills/loader.js +101 -68
  133. package/dist/skills/roots.d.ts +12 -0
  134. package/dist/skills/roots.js +18 -0
  135. package/dist/skills/types.d.ts +24 -0
  136. package/dist/skills/types.js +1 -0
  137. package/dist/subagents/completion-wake.js +0 -10
  138. package/dist/subagents/discovery.d.ts +1 -1
  139. package/dist/subagents/discovery.js +10 -16
  140. package/dist/subagents/dispatch.js +8 -16
  141. package/dist/subagents/external/cursor-cli.d.ts +2 -0
  142. package/dist/subagents/external/cursor-cli.js +256 -0
  143. package/dist/subagents/external/harness.d.ts +5 -5
  144. package/dist/subagents/external/reconciliation.d.ts +7 -0
  145. package/dist/subagents/external/reconciliation.js +105 -0
  146. package/dist/subagents/external/recovery.d.ts +20 -0
  147. package/dist/subagents/external/recovery.js +71 -0
  148. package/dist/subagents/external/registry.js +2 -0
  149. package/dist/subagents/external/role-warnings.d.ts +17 -0
  150. package/dist/subagents/external/role-warnings.js +42 -0
  151. package/dist/subagents/external/run.js +18 -22
  152. package/dist/subagents/format.d.ts +1 -1
  153. package/dist/subagents/format.js +1 -1
  154. package/dist/subagents/grace.d.ts +2 -2
  155. package/dist/subagents/grace.js +3 -3
  156. package/dist/subagents/internal/run.js +7 -5
  157. package/dist/subagents/internal/worker.js +31 -2
  158. package/dist/subagents/result.js +2 -3
  159. package/dist/subagents/run-record.d.ts +4 -7
  160. package/dist/subagents/run-record.js +2 -2
  161. package/dist/subagents/runs.d.ts +33 -46
  162. package/dist/subagents/runs.js +126 -245
  163. package/dist/subagents/task-settlement.d.ts +3 -0
  164. package/dist/subagents/task-settlement.js +20 -0
  165. package/dist/subagents/types.d.ts +1 -2
  166. package/dist/subagents/workspace-summary.js +5 -1
  167. package/dist/tasks/archive.d.ts +11 -0
  168. package/dist/tasks/archive.js +141 -0
  169. package/dist/tasks/board.d.ts +5 -12
  170. package/dist/tasks/board.js +4 -30
  171. package/dist/tasks/bound-work.d.ts +12 -6
  172. package/dist/tasks/bound-work.js +37 -24
  173. package/dist/tasks/brief.d.ts +38 -14
  174. package/dist/tasks/brief.js +128 -70
  175. package/dist/tasks/budget.d.ts +3 -3
  176. package/dist/tasks/budget.js +9 -4
  177. package/dist/tasks/commands.d.ts +14 -9
  178. package/dist/tasks/commands.js +190 -121
  179. package/dist/tasks/completion.d.ts +12 -0
  180. package/dist/tasks/completion.js +35 -0
  181. package/dist/tasks/contract.d.ts +8 -17
  182. package/dist/tasks/contract.js +41 -43
  183. package/dist/tasks/control.d.ts +138 -0
  184. package/dist/tasks/control.js +1 -0
  185. package/dist/tasks/create.d.ts +1 -1
  186. package/dist/tasks/create.js +3 -3
  187. package/dist/tasks/delivery.d.ts +24 -0
  188. package/dist/tasks/delivery.js +221 -0
  189. package/dist/tasks/file-mutation.d.ts +5 -0
  190. package/dist/tasks/file-mutation.js +38 -0
  191. package/dist/tasks/frontmatter.d.ts +43 -28
  192. package/dist/tasks/frontmatter.js +83 -40
  193. package/dist/tasks/input-receipts.d.ts +7 -0
  194. package/dist/tasks/input-receipts.js +60 -0
  195. package/dist/tasks/loop-log.d.ts +147 -28
  196. package/dist/tasks/loop-log.js +239 -28
  197. package/dist/tasks/receipts.d.ts +19 -0
  198. package/dist/tasks/receipts.js +48 -0
  199. package/dist/tasks/state.d.ts +93 -0
  200. package/dist/tasks/state.js +156 -0
  201. package/dist/tasks/store.d.ts +81 -49
  202. package/dist/tasks/store.js +244 -147
  203. package/dist/tools/bash.d.ts +3 -5
  204. package/dist/tools/bash.js +8 -22
  205. package/dist/tools/contract/details.d.ts +6 -6
  206. package/dist/tools/contract/details.js +6 -6
  207. package/dist/tools/contract/execution-trace.d.ts +4 -0
  208. package/dist/tools/contract/execution-trace.js +23 -0
  209. package/dist/tools/contract/presentation.js +6 -2
  210. package/dist/tools/edit.d.ts +1 -0
  211. package/dist/tools/edit.js +45 -42
  212. package/dist/tools/index.d.ts +8 -12
  213. package/dist/tools/index.js +16 -6
  214. package/dist/tools/memory-manage.js +8 -1
  215. package/dist/tools/registry.d.ts +7 -11
  216. package/dist/tools/registry.js +52 -25
  217. package/dist/tools/skill.d.ts +2 -2
  218. package/dist/tools/skill.js +24 -10
  219. package/dist/tools/subagent-manage.js +7 -4
  220. package/dist/tools/subagent.d.ts +0 -2
  221. package/dist/tools/subagent.js +2 -7
  222. package/dist/tools/task-manage/control-tools.d.ts +4 -0
  223. package/dist/tools/task-manage/control-tools.js +65 -0
  224. package/dist/tools/task-manage/create.js +2 -1
  225. package/dist/tools/task-manage/factory.d.ts +12 -6
  226. package/dist/tools/task-manage/factory.js +72 -57
  227. package/dist/tools/task-manage/lifecycle.d.ts +7 -12
  228. package/dist/tools/task-manage/lifecycle.js +118 -66
  229. package/dist/tools/task-manage/log-view.js +8 -5
  230. package/dist/tools/task-manage/schema.d.ts +21 -26
  231. package/dist/tools/task-manage/schema.js +29 -35
  232. package/dist/tools/task-manage/shared.d.ts +8 -39
  233. package/dist/tools/task-manage/shared.js +19 -68
  234. package/dist/tools/task-manage/step-tools.d.ts +5 -0
  235. package/dist/tools/task-manage/step-tools.js +103 -0
  236. package/dist/tools/task-manage/types.d.ts +25 -18
  237. package/dist/tools/write-content.d.ts +1 -0
  238. package/dist/tools/write-content.js +6 -1
  239. package/dist/tools/write.d.ts +1 -0
  240. package/dist/tools/write.js +1 -0
  241. package/dist/usage/ledger.d.ts +4 -4
  242. package/dist/usage/render.js +2 -2
  243. package/dist/web/search-providers.js +0 -33
  244. package/dist/webapi/request-policy.js +1 -1
  245. package/examples/sub-agents/README.md +23 -16
  246. package/examples/sub-agents/agents/claude-high.md +1 -1
  247. package/examples/sub-agents/agents/claude-main.md +1 -1
  248. package/examples/sub-agents/agents/codex-flash.md +1 -1
  249. package/examples/sub-agents/agents/codex-high.md +1 -1
  250. package/examples/sub-agents/agents/codex-main.md +4 -4
  251. package/examples/sub-agents/agents/cursor-high.md +22 -0
  252. package/examples/sub-agents/agents/cursor-main.md +22 -0
  253. package/examples/sub-agents/agents/glm-flash.md +1 -1
  254. package/examples/sub-agents/agents/glm-high.md +2 -2
  255. package/examples/sub-agents/agents/scout.md +30 -0
  256. package/package.json +6 -6
  257. package/dist/runtime/task-driver.d.ts +0 -116
  258. package/dist/runtime/task-driver.js +0 -443
  259. package/dist/runtime/task-wake.d.ts +0 -48
  260. package/dist/runtime/task-wake.js +0 -32
  261. package/dist/shared/wake-claim.d.ts +0 -23
  262. package/dist/shared/wake-claim.js +0 -26
  263. package/dist/skills/validation.d.ts +0 -8
  264. package/dist/skills/validation.js +0 -91
  265. package/dist/skills/workspace.d.ts +0 -33
  266. package/dist/skills/workspace.js +0 -116
  267. package/dist/tasks/steer.d.ts +0 -8
  268. package/dist/tasks/steer.js +0 -81
  269. package/dist/tasks/ticket.d.ts +0 -71
  270. package/dist/tasks/ticket.js +0 -138
  271. package/dist/tools/task-manage/step-end.d.ts +0 -11
  272. package/dist/tools/task-manage/step-end.js +0 -117
@@ -1,8 +1,11 @@
1
+ import { randomUUID } from "node:crypto";
1
2
  import { existsSync } from "node:fs";
2
3
  import { readFile } from "node:fs/promises";
3
4
  import { join } from "node:path";
5
+ import * as log from "../log.js";
4
6
  import { createJsonlAppender } from "../shared/jsonl-appender.js";
5
7
  import { formatLocalTime } from "../shared/local-time.js";
8
+ import { RecoverableToolError } from "../shared/recoverable-error.js";
6
9
  import { clipText, truncate } from "../shared/text-utils.js";
7
10
  import { isPlainObject } from "../shared/type-guards.js";
8
11
  import { normalizeTaskId } from "./contract.js";
@@ -22,11 +25,44 @@ export function taskLogIsArchived(deskDir, id) {
22
25
  return !existsSync(taskLogPath(deskDir, id)) && existsSync(taskArchiveLogPath(deskDir, id));
23
26
  }
24
27
  const appenders = new Map();
25
- function appenderFor(path) {
28
+ function appenderFor(path, deskDir, id) {
26
29
  const existing = appenders.get(path);
27
30
  if (existing)
28
31
  return existing;
29
- const appender = createJsonlAppender({ path, maxSizeBytes: MAX_LOG_BYTES, maxRotations: 2 });
32
+ const appender = createJsonlAppender({
33
+ path,
34
+ repairTail: true,
35
+ onRepairTail: (path, offset) => log.logWarn("tasks.log.integrity_failed", "Task log integrity check failed", {
36
+ reason: "Unterminated record isolated before append",
37
+ fields: { taskId: id, path, offset },
38
+ }),
39
+ maxSizeBytes: MAX_LOG_BYTES,
40
+ maxRotations: 2,
41
+ canRotate: async () => {
42
+ if (!existsSync(`${path}.2`))
43
+ return true;
44
+ const records = await readTaskLog(deskDir, id, { strict: true });
45
+ const latest = (kind) => [...records].reverse().find((record) => record.kind === kind);
46
+ const required = [
47
+ ...newInputs(records),
48
+ ...records.filter((record) => record.kind === "settle"),
49
+ latest("step"),
50
+ latest("resume"),
51
+ latest("ask_delivered"),
52
+ latest("close"),
53
+ latest("close_rejected"),
54
+ latest("report"),
55
+ ...records.filter((record) => record.kind === "report" && !record.delivered),
56
+ ...records.filter((record) => record.kind === "report_delivered" && record.reportId === latest("report")?.id),
57
+ ...stepEndsSinceResume(records).slice(-3),
58
+ [...records].reverse().find((record) => record.checkpoint),
59
+ ];
60
+ const pinned = new Set(required.flatMap((record) => (record?.id ? [record.id] : [])));
61
+ const oldest = [];
62
+ parseLogLines(await readFile(`${path}.2`, "utf-8"), {}, oldest);
63
+ return !oldest.some((record) => record.id && pinned.has(record.id));
64
+ },
65
+ });
30
66
  appenders.set(path, appender);
31
67
  return appender;
32
68
  }
@@ -41,23 +77,53 @@ export async function resetTaskLogAppenders() {
41
77
  * of what a step did, so a dropped record would make the next brief lie about the task's history.
42
78
  */
43
79
  export async function appendTaskLog(deskDir, id, record) {
44
- const withTs = { ts: record.ts ?? formatLocalTime(), ...record };
45
- if (withTs.kind === "step") {
80
+ const withTs = { ts: record.ts ?? formatLocalTime(), ...record, id: record.id ?? randomUUID() };
81
+ if (withTs.kind === "step_end")
46
82
  withTs.note = clipText(withTs.note, NOTE_MAX_CHARS);
47
- if (withTs.report)
48
- withTs.report = clipText(withTs.report, NOTE_MAX_CHARS);
49
- }
83
+ if (withTs.kind === "report" || withTs.kind === "message")
84
+ withTs.text = clipText(withTs.text, NOTE_MAX_CHARS);
50
85
  // Under the task's mutation lock: the appender rotates by size, and two processes rotating
51
86
  // one log at once would each move the other's fresh records aside.
52
- await withTaskMutation(deskDir, id, () => appenderFor(taskLogPath(deskDir, id)).appendStrict(withTs));
87
+ await withTaskMutation(deskDir, id, () => {
88
+ if (!existsSync(join(deskDir, "tasks", `${normalizeTaskId(id)}.md`)) &&
89
+ existsSync(join(deskDir, "tasks", "archive", `${normalizeTaskId(id)}.md`))) {
90
+ throw new RecoverableToolError(`Task "${id}" is archived. Use task_log to inspect it or create a new task for further work.`);
91
+ }
92
+ if (existsSync(join(deskDir, "tasks", ".closing", `${normalizeTaskId(id)}.json`))) {
93
+ throw new RecoverableToolError(`Task "${id}" is committing its archive. Retry after archive recovery completes.`);
94
+ }
95
+ return appenderFor(taskLogPath(deskDir, id), deskDir, id).appendStrict(withTs);
96
+ });
97
+ return withTs.id;
53
98
  }
54
- const RECORD_KINDS = ["step", "dispatch", "settle", "expired", "close"];
99
+ const RECORD_KINDS = [
100
+ "input_ack",
101
+ "ask_delivered",
102
+ "checkpoint",
103
+ "step",
104
+ "step_end",
105
+ "dispatch",
106
+ "settle",
107
+ "stall",
108
+ "message",
109
+ "ask",
110
+ "wait",
111
+ "report",
112
+ "report_delivered",
113
+ "pause",
114
+ "resume",
115
+ "close",
116
+ "close_rejected",
117
+ ];
118
+ /** Only the current record shapes are read: a `step` without `reason` is a pre-064 record. */
55
119
  function toRecord(value) {
56
120
  if (!isPlainObject(value) || typeof value.ts !== "string")
57
121
  return undefined;
58
122
  const kind = value.kind;
59
123
  if (typeof kind !== "string" || !RECORD_KINDS.includes(kind))
60
124
  return undefined;
125
+ if (kind === "step" && (typeof value.seq !== "number" || typeof value.reason !== "string"))
126
+ return undefined;
61
127
  return value;
62
128
  }
63
129
  /** Rotated-shard paths for `basePath`, oldest first, then the current file — the chronological
@@ -65,6 +131,43 @@ function toRecord(value) {
65
131
  function shardPaths(basePath) {
66
132
  return [`${basePath}.2`, `${basePath}.1`, basePath].filter((path) => existsSync(path));
67
133
  }
134
+ function readableShards(deskDir, id) {
135
+ const active = taskLogPath(deskDir, id);
136
+ const archive = taskArchiveLogPath(deskDir, id);
137
+ if (existsSync(join(deskDir, "tasks", ".closing", `${normalizeTaskId(id)}.json`))) {
138
+ return [".2", ".1", ""]
139
+ .map((suffix) => (existsSync(`${active}${suffix}`) ? `${active}${suffix}` : `${archive}${suffix}`))
140
+ .filter((path) => existsSync(path));
141
+ }
142
+ return shardPaths(existsSync(active) ? active : archive);
143
+ }
144
+ /** Explicit diagnostics are cold-path work: normal reads stay tolerant, doctor exposes damaged history. */
145
+ export async function taskLogIssues(deskDir, id) {
146
+ const issues = [];
147
+ for (const path of readableShards(deskDir, id)) {
148
+ const content = await readFile(path, "utf-8");
149
+ const lines = content.split("\n");
150
+ for (let index = 0; index < lines.length; index++) {
151
+ const line = lines[index];
152
+ if (!line.trim())
153
+ continue;
154
+ try {
155
+ if (toRecord(JSON.parse(line)))
156
+ continue;
157
+ }
158
+ catch {
159
+ /* Report the line without discarding other history. */
160
+ }
161
+ issues.push({ path, line: index + 1 });
162
+ }
163
+ if (content &&
164
+ !content.endsWith("\n") &&
165
+ !issues.some((issue) => issue.path === path && issue.line === lines.length)) {
166
+ issues.push({ path, line: lines.length });
167
+ }
168
+ }
169
+ return issues;
170
+ }
68
171
  function parseLogLines(content, options, into) {
69
172
  for (const line of content.split("\n")) {
70
173
  if (!line.trim())
@@ -96,8 +199,7 @@ function parseLogLines(content, options, into) {
96
199
  export async function readTaskLog(deskDir, id, options = {}) {
97
200
  // Fall back to the archived copy so `task_log` on a completed task returns its history rather
98
201
  // than "暂无日志" — a task that finished still has a loop log worth reading.
99
- const basePath = existsSync(taskLogPath(deskDir, id)) ? taskLogPath(deskDir, id) : taskArchiveLogPath(deskDir, id);
100
- const paths = shardPaths(basePath);
202
+ const paths = readableShards(deskDir, id);
101
203
  if (paths.length === 0)
102
204
  return [];
103
205
  const records = [];
@@ -106,26 +208,57 @@ export async function readTaskLog(deskDir, id, options = {}) {
106
208
  try {
107
209
  content = await readFile(path, "utf-8");
108
210
  }
109
- catch {
211
+ catch (error) {
212
+ if (options.strict)
213
+ throw error;
110
214
  continue;
111
215
  }
112
- parseLogLines(content, options, records);
216
+ parseLogLines(content, {}, records);
113
217
  }
114
- return options.limit !== undefined && records.length > options.limit ? records.slice(-options.limit) : records;
218
+ // Delivery receipts may sit in another shard. Apply them before filtering or limiting.
219
+ const delivered = new Set(records.flatMap((record) => (record.kind === "report_delivered" ? [record.reportId] : [])));
220
+ for (const record of records)
221
+ if (record.kind === "report" && record.id && delivered.has(record.id))
222
+ record.delivered = true;
223
+ const selected = options.kinds ? records.filter((record) => options.kinds.includes(record.kind)) : records;
224
+ return options.limit !== undefined && selected.length > options.limit ? selected.slice(-options.limit) : selected;
115
225
  }
116
226
  /** One line per record, for the step brief and `task_log` (model-facing; `/tasks` uses `renderTaskLogLineForUser`). */
117
227
  export function renderTaskLogLine(record) {
228
+ const at = `[${record.ts}]`;
118
229
  switch (record.kind) {
230
+ case "input_ack":
231
+ case "checkpoint":
232
+ case "report_delivered":
233
+ return "";
234
+ case "ask_delivered":
235
+ return `- ${at} step ${record.seq} 提问已送达`;
119
236
  case "step":
120
- return `- [${record.ts}] step ${record.seq} → ${record.outcome}: ${record.note}${record.report ? " · 已向用户汇报" : ""}`;
237
+ return `- ${at} step ${record.seq} 开始(${record.reason},${record.brief === "full" ? "完整" : "增量"} brief)`;
238
+ case "step_end":
239
+ return `- ${at} step ${record.seq} 结束 ${record.result} → ${record.next}${record.tools.length > 0 ? `(工具:${record.tools.join(", ")})` : ""}: ${record.note}${record.error ? ` · 错误:${record.error}` : ""}`;
121
240
  case "dispatch":
122
- return `- [${record.ts}] 派发 ${record.ref}${record.item ? ` → ${record.item}` : ""}${record.agent ? ` (${record.agent}${record.purpose === "verify" ? ", verify" : ""})` : ""}`;
241
+ return `- ${at} 派发 ${record.ref}${record.item ? ` → ${record.item}` : ""}${record.agent ? ` (${record.agent}${record.purpose === "verify" ? ", verify" : ""})` : ""}`;
123
242
  case "settle":
124
- return `- [${record.ts}] 结算 ${record.ref}: ${record.status}${record.verdict ? ` VERDICT ${record.verdict.toUpperCase()}` : ""}${record.exitCode !== undefined ? ` exit ${record.exitCode}` : ""}${record.output ? ` · ${record.output}` : ""}`;
125
- case "expired":
126
- return `- [${record.ts}] 等待票过期(${record.ticket})→ ${record.action}`;
243
+ return `- ${at} 结算 ${record.ref}: ${record.status}${record.verdict ? ` VERDICT ${record.verdict.toUpperCase()}` : ""}${record.exitCode !== undefined ? ` exit ${record.exitCode}` : ""}${record.output ? ` · ${record.output}` : ""}`;
244
+ case "stall":
245
+ return `- ${at} 卡顿 ${record.ref}: 已 ${record.silentMinutes} 分钟没有输出`;
246
+ case "message":
247
+ return `- ${at} 用户消息(${record.from}): ${record.text}`;
248
+ case "ask":
249
+ return `- ${at} step ${record.seq} 向用户提问: ${record.question}`;
250
+ case "wait":
251
+ return `- ${at} step ${record.seq} 约定等到 ${record.until}`;
252
+ case "report":
253
+ return `- ${at} step ${record.seq} 汇报${record.delivered ? "" : "(未送达)"}: ${record.text}`;
254
+ case "pause":
255
+ return `- ${at} 暂停(${record.by}): ${record.reason}`;
256
+ case "resume":
257
+ return `- ${at} 恢复${record.grants ? `,追加预算 ${JSON.stringify(record.grants)}` : ""}`;
127
258
  case "close":
128
- return `- [${record.ts}] ${record.outcome === "done" ? "完成" : "取消"}:${record.note}`;
259
+ return `- ${at} ${record.outcome === "done" ? "完成" : "取消"}(${record.by}):${record.note}`;
260
+ case "close_rejected":
261
+ return `- ${at} close rejected: ${record.reason}`;
129
262
  }
130
263
  }
131
264
  /** `2026-10-11T14:02:33.000+08:00` → `10-11 14:02`: read straight off the stored wall-clock text, never re-zoned. */
@@ -157,16 +290,31 @@ function oneLine(text, max) {
157
290
  }
158
291
  /**
159
292
  * One line per record for `/tasks show` and `/tasks log` (spec 053, D2). The same records as
160
- * `renderTaskLogLine`, said in the user's terms: no `task_step_end` outcome values, no `VERDICT`,
161
- * no tool names, minute precision.
293
+ * `renderTaskLogLine`, said in the user's terms: no `result` / `next` values, no `VERDICT`, no
294
+ * tool names, minute precision.
162
295
  */
163
296
  export function renderTaskLogLineForUser(record) {
164
297
  const at = minuteStamp(record.ts);
165
298
  switch (record.kind) {
166
- case "step": {
167
- const after = record.outcome === "park" ? "(之后转入等待)" : record.outcome === "done" ? "(任务完成)" : "";
168
- const reported = record.report ? ",已向你汇报" : "";
169
- return `- ${at} 第 ${record.seq} 步:${oneLine(record.note, 160)}${after}${reported}`;
299
+ case "input_ack":
300
+ case "checkpoint":
301
+ case "report_delivered":
302
+ return "";
303
+ case "ask_delivered":
304
+ return `- ${at} 提问已送达`;
305
+ case "step":
306
+ return `- ${at} 开始第 ${record.seq} 步`;
307
+ case "step_end": {
308
+ const outcome = record.result === "ok"
309
+ ? oneLine(record.note, 160)
310
+ : record.result === "timeout"
311
+ ? "这一步超时,已中止"
312
+ : record.result === "error"
313
+ ? "这一步出错"
314
+ : record.result === "aborted"
315
+ ? "这一步被中止"
316
+ : "这一步被服务重启打断";
317
+ return `- ${at} 第 ${record.seq} 步结束:${outcome}`;
170
318
  }
171
319
  case "dispatch": {
172
320
  const who = record.agent && record.agent !== "job"
@@ -176,9 +324,72 @@ export function renderTaskLogLineForUser(record) {
176
324
  }
177
325
  case "settle":
178
326
  return `- ${at} ${describeWorkRef(record.ref)}结束:${describeSettlement(record)}`;
179
- case "expired":
180
- return `- ${at} 等待超时(${oneLine(record.ticket, 80)}),${record.action === "reopened" ? "已重新开始" : "已暂停"}`;
327
+ case "stall":
328
+ return `- ${at} ${describeWorkRef(record.ref)}已 ${record.silentMinutes} 分钟没有输出`;
329
+ case "message":
330
+ return `- ${at} 你说:${oneLine(record.text, 120)}`;
331
+ case "ask":
332
+ return `- ${at} 向你提问:${oneLine(record.question, 160)}`;
333
+ case "wait":
334
+ return `- ${at} 约定等到 ${minuteStamp(record.until)}`;
335
+ case "report":
336
+ return `- ${at} 向你汇报${record.delivered ? "" : "(未送达)"}:${oneLine(record.text, 160)}`;
337
+ case "pause":
338
+ return `- ${at} ${record.by === "user" ? "你暂停了任务" : "系统暂停了任务"}:${oneLine(record.reason, 120)}`;
339
+ case "resume":
340
+ return `- ${at} 任务已恢复`;
181
341
  case "close":
182
342
  return `- ${at} ${record.outcome === "done" ? "任务完成" : "任务取消"}:${oneLine(record.note, 160)}`;
343
+ case "close_rejected":
344
+ return `- ${at} 收尾检查未通过,需补充检查后继续`;
345
+ }
346
+ }
347
+ // === Cursors over the log (spec 064, D3/D16) ===
348
+ /** The last `step` record, and whether a `step_end` for it exists. `undefined` before the first step. */
349
+ export function lastStep(records) {
350
+ for (let index = records.length - 1; index >= 0; index--) {
351
+ const record = records[index];
352
+ if (record?.kind !== "step")
353
+ continue;
354
+ const ended = records.slice(index + 1).some((later) => later.kind === "step_end" && later.seq === record.seq);
355
+ return { step: record, ended };
356
+ }
357
+ return undefined;
358
+ }
359
+ /**
360
+ * Pending inputs, in journal order. Starting a step or accepting a steer never consumes them.
361
+ * Inline results are already returned by their tool; other inputs need a durable receipt.
362
+ */
363
+ export function newInputs(records) {
364
+ const consumed = new Set(records.flatMap((record) => (record.kind === "input_ack" ? record.ids : [])));
365
+ const inputs = [];
366
+ const seen = new Set();
367
+ for (const record of records) {
368
+ if (record.id && (consumed.has(record.id) || seen.has(record.id)))
369
+ continue;
370
+ if (record.id)
371
+ seen.add(record.id);
372
+ if (record.kind === "stall" || record.kind === "resume" || record.kind === "close_rejected")
373
+ inputs.push(record);
374
+ else if (record.kind === "settle" && !record.inline)
375
+ inputs.push(record);
376
+ else if (record.kind === "message")
377
+ inputs.push(record);
378
+ }
379
+ return inputs;
380
+ }
381
+ /**
382
+ * The `step_end` records since the user last resumed the task, oldest first. A guard (idle, timeout,
383
+ * error) counts only these: a resume is the user looking at the problem, so the same evidence must
384
+ * not pause the task a second time.
385
+ */
386
+ export function stepEndsSinceResume(records) {
387
+ let from = 0;
388
+ for (let index = records.length - 1; index >= 0; index--) {
389
+ if (records[index]?.kind === "resume") {
390
+ from = index + 1;
391
+ break;
392
+ }
183
393
  }
394
+ return records.slice(from).filter((record) => record.kind === "step_end");
184
395
  }
@@ -0,0 +1,19 @@
1
+ import type { TaskFrontmatter } from "./frontmatter.js";
2
+ import type { GuardBreach } from "./state.js";
3
+ /**
4
+ * The messages the runtime sends a task's report channel without asking a model (spec 064, D29).
5
+ * User copy under spec 053: Chinese, the four markers, no tool names or internal tags, and every
6
+ * next step is something the user can type.
7
+ */
8
+ /** A `task_ask` question, delivered once the step ends. */
9
+ export declare function askReceipt(id: string, question: string): string;
10
+ /** The runtime paused the task: budget, idle, timeout or errors. A budget stop says how to give it more. */
11
+ export declare function pausedReceipt(id: string, title: string, reason: string, breach?: GuardBreach): string;
12
+ export declare function completedReceipt(id: string, title: string, document: {
13
+ fields: TaskFrontmatter;
14
+ body: string;
15
+ }, closedAt: string): string;
16
+ /** The leader cancelled its own task. */
17
+ export declare function cancelledByLeaderReceipt(id: string, title: string, note: string): string;
18
+ /** The user cancelled from another channel of the desk; the report channel should not be left wondering. */
19
+ export declare function cancelledByUserReceipt(id: string, title: string): string;
@@ -0,0 +1,48 @@
1
+ import { capReply } from "../commands/reply-limits.js";
2
+ import { formatElapsedZh } from "../shared/format.js";
3
+ import { parseLocalTime } from "../shared/local-time.js";
4
+ import { truncate } from "../shared/text-utils.js";
5
+ import { taskCostSummary } from "./budget.js";
6
+ import { parseTaskItems } from "./contract.js";
7
+ /**
8
+ * The messages the runtime sends a task's report channel without asking a model (spec 064, D29).
9
+ * User copy under spec 053: Chinese, the four markers, no tool names or internal tags, and every
10
+ * next step is something the user can type.
11
+ */
12
+ /** A `task_ask` question, delivered once the step ends. */
13
+ export function askReceipt(id, question) {
14
+ return `⚠️ 任务 \`${id}\` 需要你的决定:${question}\n直接回复我,或用 \`/tasks msg ${id} <内容>\` 回答。`;
15
+ }
16
+ /** The runtime paused the task: budget, idle, timeout or errors. A budget stop says how to give it more. */
17
+ export function pausedReceipt(id, title, reason, breach) {
18
+ const grant = breach === "steps" ? " +steps 10" : breach === "usd" ? " +usd 5" : "";
19
+ const resume = grant ? "继续并追加预算" : "继续";
20
+ return (`🛑 任务 \`${id}\`(${title})已暂停:${reason}。\n` +
21
+ `查看:\`/tasks show ${id}\`;${resume}:\`/tasks resume ${id}${grant}\`\n` +
22
+ `不再需要:\`/tasks cancel ${id}\``);
23
+ }
24
+ export function completedReceipt(id, title, document, closedAt) {
25
+ const usage = document.fields.usage;
26
+ const since = usage ? parseLocalTime(usage.startedAt) : undefined;
27
+ const end = parseLocalTime(closedAt);
28
+ const items = parseTaskItems(document.body);
29
+ const dropped = items?.items.filter((item) => item.status === "dropped").map((item) => item.id) ?? [];
30
+ return capReply([
31
+ `**✅ 任务 \`${id}\`(${title})已完成**`,
32
+ ...(since !== undefined && end !== undefined
33
+ ? [`- 历时:${formatElapsedZh(end - since)}(含排队和等待)`]
34
+ : []),
35
+ ...(usage ? [`- 用量:${usage.steps} 步 · ${taskCostSummary(usage)}`] : []),
36
+ ...(items
37
+ ? [`- 工作项:${items.done}/${items.total}${dropped.length > 0 ? `;已放弃:${dropped.join("、")}` : ""}`]
38
+ : []),
39
+ ].join("\n"), { nextStepHint: `用 \`/tasks show ${id}\` 查看详情` }).text;
40
+ }
41
+ /** The leader cancelled its own task. */
42
+ export function cancelledByLeaderReceipt(id, title, note) {
43
+ return `🛑 任务 \`${id}\`(${title})已取消:${truncate(note.replace(/\s+/g, " "), 160)}`;
44
+ }
45
+ /** The user cancelled from another channel of the desk; the report channel should not be left wondering. */
46
+ export function cancelledByUserReceipt(id, title) {
47
+ return `🛑 任务 \`${id}\`(${title})已被取消。`;
48
+ }
@@ -0,0 +1,93 @@
1
+ import type { TaskFrontmatter, TaskState, TaskWaiting } from "./frontmatter.js";
2
+ import { type TaskInputRecord, type TaskLogRecord, type TaskStepNext, type TaskStepReason, type TaskStepResult } from "./loop-log.js";
3
+ /**
4
+ * Task state, derived from facts (spec 064, D7–D10, D16). Pure functions: no I/O, every input
5
+ * explicit, so the whole transition table is testable without a runtime. The lane and
6
+ * `tasks/store.ts` apply what these return; nothing here is a model-declared claim (INV-2).
7
+ */
8
+ /** Consecutive `ok` steps that called no tool at all: the loop is talking to itself. */
9
+ export declare const IDLE_STEP_LIMIT = 2;
10
+ /** Consecutive steps that hit the step time limit. */
11
+ export declare const STEP_TIMEOUT_LIMIT = 2;
12
+ /** Consecutive steps that ended in an error. */
13
+ export declare const STEP_ERROR_LIMIT = 3;
14
+ /** `task_wait` accepts a moment between one minute and thirty days away. */
15
+ export declare const TASK_WAIT_MIN_MS = 60000;
16
+ export declare const TASK_WAIT_MAX_MS: number;
17
+ /** What the runtime observed about a step that just ended (D8). */
18
+ export interface StepFacts {
19
+ result: TaskStepResult;
20
+ /** `task_close` was called this step and the lane honoured it. */
21
+ closed: boolean;
22
+ /** The user paused the task while this step ran. */
23
+ pausedByUser: boolean;
24
+ asked?: {
25
+ question: string;
26
+ };
27
+ /** The moment `task_wait` registered (local-time text). */
28
+ waitUntil?: string;
29
+ /** Delegations and jobs bound to this task that have not settled. */
30
+ pendingWork: number;
31
+ }
32
+ export interface StepDerivation {
33
+ next: TaskStepNext;
34
+ state: TaskState;
35
+ waiting?: TaskWaiting;
36
+ /** The task keeps its execution slot and runner (`continue`, `work`). */
37
+ keepSlot: boolean;
38
+ }
39
+ /**
40
+ * D8: the first rule that holds decides what the task does next. A `continue` after an `ok` step
41
+ * stays `running` (the lane opens the next step at once); after a failed step it goes back to
42
+ * `queued` so the lane can back off before re-admitting it.
43
+ */
44
+ export declare function deriveAfterStep(facts: StepFacts, now?: Date): StepDerivation;
45
+ /** Why a step is starting, from the log: the first step, a resume, new input, a retry, or simply the next one. */
46
+ export declare function deriveStepReason(records: readonly TaskLogRecord[], inputs: readonly TaskInputRecord[]): TaskStepReason;
47
+ export type WaitingDecision = "stay" | "run" | "queue";
48
+ export interface WakeFacts {
49
+ waiting: TaskWaiting;
50
+ /** `newInputs(records)` for this task. */
51
+ inputs: readonly TaskLogRecord[];
52
+ pendingWork: number;
53
+ now: number;
54
+ }
55
+ /**
56
+ * D7/D9: whether a waiting task wakes. New input wakes it — except that a task waiting for the user
57
+ * wakes only for a `message`, so a result that arrives meanwhile does not re-ask an unanswered
58
+ * question. `run` reuses the slot and runner (work waits hold them); `queue` goes back to the line.
59
+ */
60
+ export declare function evaluateWaiting(facts: WakeFacts): WaitingDecision;
61
+ export interface BootReconciliation {
62
+ fields: TaskFrontmatter;
63
+ /** The interrupted step's `step_end`, when one has to be written. */
64
+ appendStepEnd?: {
65
+ seq: number;
66
+ next: TaskStepNext;
67
+ };
68
+ }
69
+ /**
70
+ * D10: a runtime start finds tasks in whatever state the previous process left. `running` means the
71
+ * process died mid-step (or between the step's end record and its state write): record the
72
+ * interruption if the log lacks it and derive the next state as if the step had ended; a work wait
73
+ * with nothing in flight goes back to the line. Writes state and log only — no model call.
74
+ */
75
+ export declare function reconcileOnBoot(fields: TaskFrontmatter, records: readonly TaskLogRecord[], pendingWork: number, now?: Date): BootReconciliation | undefined;
76
+ export type GuardBreach = "steps" | "usd" | "idle" | "timeout" | "error";
77
+ export interface GuardVerdict {
78
+ breach: GuardBreach;
79
+ /** The reason as the user reads it (a runtime receipt). */
80
+ reason: string;
81
+ }
82
+ /**
83
+ * D16: the stops the runtime enforces on a task about to run again. Everything is read from the
84
+ * persisted state and log, so a restart does not forget a streak. Streaks count only the steps
85
+ * since the user last resumed the task. Budget is checked first — it is the one the user can
86
+ * fix with a number.
87
+ */
88
+ export declare function checkGuards(fields: TaskFrontmatter, records: readonly TaskLogRecord[]): GuardVerdict | undefined;
89
+ /**
90
+ * Parse `task_wait`'s `until`: `+30m` / `+2h` / `+1d` or a local timestamp. The moment must lie
91
+ * between one minute and thirty days ahead. Returns the canonical local-time text to store.
92
+ */
93
+ export declare function parseWaitUntil(raw: string, now?: Date): string;