@oyasmi/pipiclaw 0.8.10 → 0.8.11-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 (56) hide show
  1. package/dist/agent/channel-runner.d.ts +10 -0
  2. package/dist/agent/channel-runner.js +56 -27
  3. package/dist/memory/commands.js +6 -1
  4. package/dist/memory/consolidation.d.ts +8 -1
  5. package/dist/memory/consolidation.js +34 -6
  6. package/dist/memory/extraction.d.ts +11 -3
  7. package/dist/memory/extraction.js +19 -6
  8. package/dist/memory/files.d.ts +2 -0
  9. package/dist/memory/files.js +14 -0
  10. package/dist/memory/maintenance-gates.d.ts +3 -0
  11. package/dist/memory/maintenance-gates.js +5 -2
  12. package/dist/memory/maintenance-jobs.js +19 -2
  13. package/dist/memory/maintenance-state.d.ts +29 -0
  14. package/dist/memory/maintenance-state.js +100 -8
  15. package/dist/memory/metadata.d.ts +9 -0
  16. package/dist/memory/metadata.js +5 -0
  17. package/dist/memory/probation.d.ts +21 -0
  18. package/dist/memory/probation.js +48 -0
  19. package/dist/memory/promotion.d.ts +26 -1
  20. package/dist/memory/promotion.js +34 -4
  21. package/dist/memory/recall.js +38 -19
  22. package/dist/memory/session-corpus.js +12 -11
  23. package/dist/memory/session-search.js +25 -6
  24. package/dist/memory/sidecar-worker.js +2 -0
  25. package/dist/memory/task-digest.js +6 -0
  26. package/dist/playbooks/memory-and-learning.md +7 -1
  27. package/dist/playbooks/task-driving.md +2 -2
  28. package/dist/playbooks/task-planning.md +14 -0
  29. package/dist/runtime/bootstrap.js +1 -1
  30. package/dist/runtime/delivery.js +8 -2
  31. package/dist/runtime/dingtalk.d.ts +5 -2
  32. package/dist/runtime/dingtalk.js +6 -39
  33. package/dist/runtime/store.d.ts +8 -2
  34. package/dist/runtime/store.js +12 -6
  35. package/dist/runtime/task-commands.js +15 -1
  36. package/dist/runtime/task-driver.js +10 -0
  37. package/dist/security/command-guard.js +51 -17
  38. package/dist/security/path-guard.js +72 -14
  39. package/dist/subagents/tool.js +2 -0
  40. package/dist/tasks/ledger.d.ts +74 -5
  41. package/dist/tasks/ledger.js +261 -7
  42. package/dist/tools/memory-manage.js +8 -1
  43. package/dist/tools/read.js +19 -5
  44. package/dist/tools/task-manage/lifecycle.js +8 -2
  45. package/dist/tools/task-manage/schema.d.ts +6 -0
  46. package/dist/tools/task-manage/schema.js +14 -0
  47. package/dist/tools/task-manage/shared.js +1 -0
  48. package/dist/tui/app.js +1 -1
  49. package/dist/tui/commands.d.ts +1 -1
  50. package/dist/tui/commands.js +1 -1
  51. package/dist/tui/turn-controller.d.ts +1 -1
  52. package/dist/usage/ledger.d.ts +1 -1
  53. package/dist/usage/ledger.js +47 -22
  54. package/dist/usage/render.d.ts +1 -1
  55. package/dist/usage/render.js +8 -6
  56. package/package.json +6 -6
@@ -1,6 +1,7 @@
1
1
  import { readdir, readFile, stat } from "node:fs/promises";
2
2
  import { join } from "node:path";
3
3
  import { formatLocalTime, parseLocalTime } from "../shared/local-time.js";
4
+ import { RecoverableToolError } from "../shared/recoverable-error.js";
4
5
  import { nextTaskWake } from "../shared/task-schedule.js";
5
6
  import { parseTaskControl, taskPriorityRank } from "./control.js";
6
7
  import { normalizeStoredStatus, TERMINAL_TASK_STATUSES, wasLegacyEscalated } from "./transitions.js";
@@ -15,6 +16,12 @@ export const STANDARD_TASK_SECTIONS = [
15
16
  { label: "Current Cycle", names: ["Current Cycle", "当前周期"] },
16
17
  { label: "History", names: ["History", "历史"] },
17
18
  ];
19
+ /**
20
+ * `## Plan` is a deliberately optional section (spec 037, D2) — it is not part of
21
+ * `STANDARD_TASK_SECTIONS`, so `missingStandardTaskSections` never flags its absence. A two-step
22
+ * task or any pre-existing task simply has no Plan.
23
+ */
24
+ const PLAN_SECTION_NAMES = ["Plan", "计划"];
18
25
  /** Recurring task files are working context, not an unbounded audit log. */
19
26
  export const MAX_INLINE_TASK_HISTORY_ENTRIES = 8;
20
27
  export const MAX_INLINE_TASK_HISTORY_CHARS = 24 * 1024;
@@ -41,24 +48,196 @@ export function taskBody(content) {
41
48
  return after === -1 ? "" : content.slice(after + 1);
42
49
  }
43
50
  /**
44
- * The task's *contract* segment: the body up to (excluding) the "Current Cycle" heading —
45
- * i.e. the H1 title, Goal, DoD (with its checkbox state), Manual and Verification (spec 029, D4).
51
+ * The task's *contract* segment: the body up to (excluding) whichever of "Plan" or "Current
52
+ * Cycle" appears first — i.e. the H1 title, Goal, DoD (with its checkbox state), Manual and
53
+ * Verification (spec 029, D4).
46
54
  *
47
55
  * Verification PASS and external approval bind to this segment, not the whole body, so routine
48
- * `progress` notes (Current Cycle) and appended History/Completion Evidence never invalidate a
49
- * PASS or approval — only a change to what the task promises to do and how it is checked does.
50
- * A body without a Current Cycle heading (non-standard) falls back to the whole body.
56
+ * `progress` notes (Current Cycle, and — spec 037, D1 — Plan step status) never invalidate a
57
+ * PASS or approval; only a change to what the task promises to do and how it is checked does.
58
+ * Plan is deliberately excluded from the contract even though it always precedes Current Cycle
59
+ * in a freshly rendered skeleton: it is the task's *means*, not its promise, and is meant to be
60
+ * revised without re-triggering verification. This also means a task with an existing PASS can
61
+ * have `## Plan` inserted between Verification and Current Cycle with the contract segment
62
+ * unchanged byte-for-byte, as long as nothing before it changed.
63
+ * A body without either heading (non-standard) falls back to the whole body.
51
64
  */
52
65
  export function taskContractSegment(body) {
53
66
  const lines = body.split("\n");
54
67
  for (let index = 0; index < lines.length; index++) {
55
68
  const match = /^#{1,6}\s+(.+?)\s*$/.exec(lines[index] ?? "");
56
- if (match && matchesTaskSectionTitle(match[1] ?? "", ["Current Cycle", "当前周期"])) {
69
+ if (match &&
70
+ (matchesTaskSectionTitle(match[1] ?? "", PLAN_SECTION_NAMES) ||
71
+ matchesTaskSectionTitle(match[1] ?? "", ["Current Cycle", "当前周期"]))) {
57
72
  return lines.slice(0, index).join("\n").replace(/\s+$/, "");
58
73
  }
59
74
  }
60
75
  return body;
61
76
  }
77
+ const PLAN_STEP_STATUS_BY_MARKER = {
78
+ " ": "todo",
79
+ x: "done",
80
+ X: "done",
81
+ "!": "blocked",
82
+ "~": "dropped",
83
+ };
84
+ const PLAN_CHECKBOX_LINE = /^\s*[-*]\s+\[([ xX!~])\]\s+(.*)$/;
85
+ const PLAN_STEP_ID_PREFIX = /^(P\d+)[.、)]?\s+(\S.*)$/i;
86
+ const PLAN_DOD_REF_SUFFIX = /(?:→|->)\s*dod:\s*([\d,\s]+)\s*$/i;
87
+ function parsePlanStepLine(line, lineIndex, fallbackId) {
88
+ const checkbox = PLAN_CHECKBOX_LINE.exec(line);
89
+ if (!checkbox)
90
+ return undefined;
91
+ const status = PLAN_STEP_STATUS_BY_MARKER[checkbox[1] ?? " "] ?? "todo";
92
+ let rest = (checkbox[2] ?? "").trim();
93
+ let dodRefs = [];
94
+ const dodMatch = PLAN_DOD_REF_SUFFIX.exec(rest);
95
+ if (dodMatch) {
96
+ dodRefs = (dodMatch[1] ?? "")
97
+ .split(",")
98
+ .map((part) => Number.parseInt(part.trim(), 10))
99
+ .filter((n) => Number.isInteger(n) && n > 0);
100
+ rest = rest.slice(0, dodMatch.index).trim();
101
+ }
102
+ const idMatch = PLAN_STEP_ID_PREFIX.exec(rest);
103
+ const id = idMatch ? (idMatch[1] ?? fallbackId).toUpperCase() : fallbackId;
104
+ const text = idMatch ? (idMatch[2] ?? "").trim() : rest;
105
+ return { id, status, text, dodRefs, lineIndex };
106
+ }
107
+ /**
108
+ * Parse the optional `## Plan` section: a fourth, hand-maintained layer between the contract
109
+ * (Goal/DoD/Manual/Verification) and the append-only Current Cycle/History log (spec 037, D2).
110
+ *
111
+ * Four checkbox states — `[ ]` todo, `[x]` done, `[!]` blocked, `[~]` dropped — and no separate
112
+ * "doing" marker: the current step is *derived* (first `todo`/`blocked` in document order), not
113
+ * self-reported, for the same reason `task-driver.ts`'s fingerprint excludes the model's own
114
+ * progress notes — a runtime-derived signal cannot be talked into lying about itself.
115
+ *
116
+ * Returns `undefined` when there is no Plan heading, or the heading has no checkbox lines under
117
+ * it (nothing to summarize) — both read the same as "this task has no Plan yet".
118
+ */
119
+ export function parseTaskPlan(content) {
120
+ const lines = content.split("\n");
121
+ let sectionStart = -1;
122
+ let sectionLevel = 0;
123
+ for (let index = 0; index < lines.length; index++) {
124
+ const match = /^(#{1,6})\s+(.+?)\s*$/.exec(lines[index] ?? "");
125
+ if (!match || !matchesTaskSectionTitle(match[2] ?? "", PLAN_SECTION_NAMES))
126
+ continue;
127
+ sectionStart = index;
128
+ sectionLevel = match[1]?.length ?? 0;
129
+ break;
130
+ }
131
+ if (sectionStart === -1)
132
+ return undefined;
133
+ let sectionEnd = lines.length;
134
+ for (let index = sectionStart + 1; index < lines.length; index++) {
135
+ const match = /^(#{1,6})\s+/.exec(lines[index] ?? "");
136
+ if (match && (match[1]?.length ?? 7) <= sectionLevel) {
137
+ sectionEnd = index;
138
+ break;
139
+ }
140
+ }
141
+ const steps = [];
142
+ let position = 0;
143
+ for (let index = sectionStart + 1; index < sectionEnd; index++) {
144
+ const line = lines[index] ?? "";
145
+ if (!/^\s*[-*]\s+\[/.test(line))
146
+ continue;
147
+ position++;
148
+ const step = parsePlanStepLine(line, index, `P${position}`);
149
+ if (step)
150
+ steps.push(step);
151
+ }
152
+ if (steps.length === 0)
153
+ return undefined;
154
+ return {
155
+ steps,
156
+ total: steps.filter((step) => step.status !== "dropped").length,
157
+ done: steps.filter((step) => step.status === "done").length,
158
+ current: steps.find((step) => step.status === "todo" || step.status === "blocked"),
159
+ };
160
+ }
161
+ const PLAN_STATUS_MARKER = { todo: " ", done: "x", blocked: "!", dropped: "~" };
162
+ function renderPlanStepLine(id, status, text, dodRefs = []) {
163
+ const suffix = dodRefs.length > 0 ? ` → dod:${dodRefs.join(",")}` : "";
164
+ return `- [${PLAN_STATUS_MARKER[status]}] ${id} ${text}${suffix}`;
165
+ }
166
+ /** Insert an empty "## Plan" heading immediately before "## Current Cycle" (spec 037, D3). */
167
+ function insertEmptyPlanSection(body) {
168
+ const lines = body.split("\n");
169
+ for (let index = 0; index < lines.length; index++) {
170
+ const match = /^(#{1,6})\s+(.+?)\s*$/.exec(lines[index] ?? "");
171
+ if (match && matchesTaskSectionTitle(match[2] ?? "", ["Current Cycle", "当前周期"])) {
172
+ lines.splice(index, 0, "## Plan", "");
173
+ return lines.join("\n");
174
+ }
175
+ }
176
+ throw new RecoverableToolError('Task body has no "Current Cycle" section, so a Plan cannot be inserted; normalize the task skeleton with edit first.');
177
+ }
178
+ /**
179
+ * Update or append Plan steps by id (spec 037, D3). An id that already exists gets its
180
+ * status/text patched in place, preserving its `dod` refs and position; an unseen id is appended
181
+ * as a new step (`text` is then required — there is nothing sensible to append otherwise). A task
182
+ * with no `## Plan` section yet gets an empty one inserted before Current Cycle first, so the
183
+ * very first `planSteps` call on a task is also the one that creates its Plan.
184
+ *
185
+ * The returned `summary` is deliberately not a new persisted field (see the file-level doc on
186
+ * `TaskPlanSummary`): it is meant to be appended to the caller's own Current Cycle note, so the
187
+ * change history rides on the log `startTaskCycle` already folds into History — no second,
188
+ * unconsumed revision counter.
189
+ */
190
+ export function applyTaskPlanPatch(body, patches) {
191
+ if (patches.length === 0)
192
+ return { body, summary: "" };
193
+ let working = parseTaskPlan(body) ? body : insertEmptyPlanSection(body);
194
+ const deltas = [];
195
+ for (const patch of patches) {
196
+ const trimmedId = patch.id.trim();
197
+ if (!trimmedId)
198
+ throw new RecoverableToolError("A planSteps entry's id must not be empty.");
199
+ const existing = parseTaskPlan(working)?.steps.find((step) => step.id.toUpperCase() === trimmedId.toUpperCase());
200
+ if (existing) {
201
+ const lines = working.split("\n");
202
+ const nextStatus = patch.status ?? existing.status;
203
+ const nextText = patch.text?.trim() || existing.text;
204
+ lines[existing.lineIndex] = renderPlanStepLine(existing.id, nextStatus, nextText, existing.dodRefs);
205
+ working = lines.join("\n");
206
+ deltas.push(patch.status ? `${existing.id}→${patch.status}` : `${existing.id} updated`);
207
+ continue;
208
+ }
209
+ const text = patch.text?.trim();
210
+ if (!text) {
211
+ throw new RecoverableToolError(`Plan step "${trimmedId}" does not exist yet; adding a new step requires text.`);
212
+ }
213
+ const id = trimmedId.toUpperCase();
214
+ const lines = working.split("\n");
215
+ let sectionStart = -1;
216
+ let sectionLevel = 0;
217
+ for (let index = 0; index < lines.length; index++) {
218
+ const match = /^(#{1,6})\s+(.+?)\s*$/.exec(lines[index] ?? "");
219
+ if (match && matchesTaskSectionTitle(match[2] ?? "", PLAN_SECTION_NAMES)) {
220
+ sectionStart = index;
221
+ sectionLevel = match[1]?.length ?? 0;
222
+ break;
223
+ }
224
+ }
225
+ let insertAt = lines.length;
226
+ for (let index = sectionStart + 1; index < lines.length; index++) {
227
+ const match = /^(#{1,6})\s+/.exec(lines[index] ?? "");
228
+ if (match && (match[1]?.length ?? 7) <= sectionLevel) {
229
+ insertAt = index;
230
+ break;
231
+ }
232
+ }
233
+ while (insertAt > sectionStart + 1 && (lines[insertAt - 1] ?? "").trim() === "")
234
+ insertAt--;
235
+ lines.splice(insertAt, 0, renderPlanStepLine(id, patch.status ?? "todo", text));
236
+ working = lines.join("\n");
237
+ deltas.push(`+${id} ${text}`);
238
+ }
239
+ return { body: working, summary: deltas.length > 0 ? `plan: ${deltas.join("; ")}` : "" };
240
+ }
62
241
  /** Parse the leading `---` frontmatter block into the three known fields. */
63
242
  export function parseTaskFrontmatter(content) {
64
243
  if (!content.startsWith("---"))
@@ -222,10 +401,44 @@ export function uncheckedTaskAcceptanceItems(content) {
222
401
  }
223
402
  return unchecked;
224
403
  }
404
+ /**
405
+ * Count of checkbox items (checked or not) under the DoD heading, for cross-referencing a Plan
406
+ * step's `→ dod:N` refs (spec 037, D4 — `/tasks doctor`'s drift checks).
407
+ */
408
+ export function countTaskDodItems(content) {
409
+ let inDod = false;
410
+ let sectionLevel = 0;
411
+ let count = 0;
412
+ for (const line of content.split("\n")) {
413
+ const heading = /^(#{1,6})\s+(.+?)\s*$/.exec(line);
414
+ if (heading) {
415
+ const level = heading[1]?.length ?? 7;
416
+ if (matchesTaskSectionTitle(heading[2] ?? "", ["DoD"])) {
417
+ inDod = true;
418
+ sectionLevel = level;
419
+ }
420
+ else if (inDod && level <= sectionLevel) {
421
+ inDod = false;
422
+ }
423
+ continue;
424
+ }
425
+ if (inDod && /^\s*[-*]\s+\[[ xX]\]/.test(line))
426
+ count++;
427
+ }
428
+ return count;
429
+ }
430
+ /** A plain plan-step line gets an auto-assigned `P<n>` id unless it already starts with one. */
431
+ function ensurePlanStepId(line, fallbackIndex) {
432
+ return PLAN_STEP_ID_PREFIX.test(line) ? line : `P${fallbackIndex} ${line}`;
433
+ }
225
434
  export function renderStandardTaskBody(input) {
226
435
  const manual = input.manual?.trim() || DEFAULT_TASK_MANUAL;
227
436
  const verificationPlan = input.verificationPlan?.trim() ||
228
437
  "- Check every DoD item against concrete evidence.\n- Run the relevant deterministic checks before declaring PASS.";
438
+ const planLines = (input.plan ?? "")
439
+ .split("\n")
440
+ .map((line) => line.trim())
441
+ .filter(Boolean);
229
442
  return [
230
443
  `# ${input.title}`,
231
444
  "",
@@ -244,6 +457,11 @@ export function renderStandardTaskBody(input) {
244
457
  ...(input.verificationRequired ? ["Independent verification: required"] : []),
245
458
  verificationPlan,
246
459
  "",
460
+ // Plan is optional (spec 037, D2/D3): omitted entirely when create was not given one,
461
+ // rather than rendering an empty section a doctor check would then have to special-case.
462
+ ...(planLines.length > 0
463
+ ? ["## Plan", ...planLines.map((line, index) => `- [ ] ${ensurePlanStepId(line, index + 1)}`), ""]
464
+ : []),
247
465
  "## Current Cycle",
248
466
  "- Created; next step: start work and append progress here before ending each turn.",
249
467
  "",
@@ -552,7 +770,7 @@ export function startTaskCycle(content, cycleId) {
552
770
  // canonical History heading remains predictable and preserves all older notes.
553
771
  lines.splice(shiftedHistoryStart + 1, 0, ...historyEntry);
554
772
  const compacted = compactTaskHistory(lines.join("\n"), legacy.blocks.length > 1);
555
- return resetTaskAcceptanceCheckboxes(compacted);
773
+ return resetPlanStepCheckboxes(resetTaskAcceptanceCheckboxes(compacted));
556
774
  }
557
775
  /**
558
776
  * Uncheck every "- [x]" under DoD/Verification.
@@ -592,6 +810,41 @@ function resetTaskAcceptanceCheckboxes(content) {
592
810
  }
593
811
  return lines.join("\n");
594
812
  }
813
+ /**
814
+ * Reset `## Plan` steps for a new cycle: `[x]` done and `[!]` blocked both go back to `[ ]`
815
+ * todo, exactly like `resetTaskAcceptanceCheckboxes` — a stale "done" step from the previous
816
+ * cycle must not silently pass as still true. `[~]` dropped is left alone: that step was
817
+ * deliberately abandoned, not merely finished, and a new cycle should not resurrect it.
818
+ */
819
+ function resetPlanStepCheckboxes(content) {
820
+ const lines = content.split("\n");
821
+ let sectionStart = -1;
822
+ let sectionLevel = 0;
823
+ for (let index = 0; index < lines.length; index++) {
824
+ const match = /^(#{1,6})\s+(.+?)\s*$/.exec(lines[index] ?? "");
825
+ if (!match || !matchesTaskSectionTitle(match[2] ?? "", PLAN_SECTION_NAMES))
826
+ continue;
827
+ sectionStart = index;
828
+ sectionLevel = match[1]?.length ?? 0;
829
+ break;
830
+ }
831
+ if (sectionStart === -1)
832
+ return content;
833
+ let sectionEnd = lines.length;
834
+ for (let index = sectionStart + 1; index < lines.length; index++) {
835
+ const match = /^(#{1,6})\s+/.exec(lines[index] ?? "");
836
+ if (match && (match[1]?.length ?? 7) <= sectionLevel) {
837
+ sectionEnd = index;
838
+ break;
839
+ }
840
+ }
841
+ for (let index = sectionStart + 1; index < sectionEnd; index++) {
842
+ const checkbox = /^(\s*[-*]\s+)\[[xX!]\](\s*.*)$/.exec(lines[index] ?? "");
843
+ if (checkbox)
844
+ lines[index] = `${checkbox[1]}[ ]${checkbox[2]}`;
845
+ }
846
+ return lines.join("\n");
847
+ }
595
848
  /** Last non-empty bullet/line under a "当前周期"/"current cycle" heading. */
596
849
  function extractLatestNote(content) {
597
850
  const lines = content.split("\n");
@@ -655,6 +908,7 @@ function toEntry(id, content, now) {
655
908
  actionable: isTaskActionable(frontmatter, now),
656
909
  wakeMs: parseWakeMs(frontmatter),
657
910
  latestNote: extractLatestNote(content),
911
+ plan: parseTaskPlan(content),
658
912
  };
659
913
  }
660
914
  const parseCache = new Map();
@@ -91,7 +91,14 @@ export function createMemoryManageTool(options) {
91
91
  {
92
92
  op: "add",
93
93
  content: trimmed,
94
- metadata: { kind: normalizeMemoryKind(kind), sourceType: "user", trust: "explicit" },
94
+ // A user explicitly saying "remember this" is never probationary, and restating a
95
+ // fact the runtime had already put on probation promotes it (spec 037, D7).
96
+ metadata: {
97
+ kind: normalizeMemoryKind(kind),
98
+ sourceType: "user",
99
+ trust: "explicit",
100
+ probationUntil: null,
101
+ },
95
102
  },
96
103
  ]));
97
104
  options.memoryCandidateStore.invalidate(getChannelMemoryPath(options.channelDir));
@@ -70,11 +70,15 @@ const readSchema = Type.Object({
70
70
  offset: Type.Optional(Type.Integer({ minimum: 1, description: "Line number to start reading from (1-indexed)" })),
71
71
  limit: Type.Optional(Type.Integer({ minimum: 1, description: "Maximum number of lines to read" })),
72
72
  });
73
- function countTextLines(content) {
73
+ /** Lines in `content`, given its `split("\n")` — callers that already split should pass it. */
74
+ function countSplitLines(content, lines) {
74
75
  if (content.length === 0) {
75
76
  return 0;
76
77
  }
77
- return content.endsWith("\n") ? content.split("\n").length - 1 : content.split("\n").length;
78
+ return content.endsWith("\n") ? lines.length - 1 : lines.length;
79
+ }
80
+ function countTextLines(content) {
81
+ return countSplitLines(content, content.split("\n"));
78
82
  }
79
83
  function formatPathBlockMessage(resolvedPath, category, reason) {
80
84
  const lines = [`Path blocked${category ? ` [${category}]` : ""}`];
@@ -195,8 +199,18 @@ export function createReadTool(executor, options = {}) {
195
199
  .join("\n");
196
200
  }
197
201
  else {
198
- const cmd = startLine === 1 ? `cat ${shellEscape(path)}` : `tail -n +${startLine} ${shellEscape(path)}`;
199
- const result = await executor.exec(cmd, { signal });
202
+ // Bounded at the source. The output is capped below at min(DEFAULT_MAX_LINES,
203
+ // DEFAULT_MAX_BYTES) anyway, so piping a multi-hundred-megabyte log through the
204
+ // executor and materializing it as a JS string first only bought a second full read
205
+ // of the file and the peak memory to hold it. Reading twice the byte cap always
206
+ // leaves `truncateHead` enough to apply whichever limit binds first — the byte cap
207
+ // is half the window, and however short the lines are, DEFAULT_MAX_LINES of them
208
+ // are either within the window or already past the byte cap.
209
+ const readWindowBytes = DEFAULT_MAX_BYTES * 2;
210
+ const source = startLine === 1 ? `cat ${shellEscape(path)}` : `tail -n +${startLine} ${shellEscape(path)}`;
211
+ // `sh -c` runs without pipefail, so the pipeline reports head's status; head closing
212
+ // the pipe early is the point, not a failure.
213
+ const result = await executor.exec(`${source} | head -c ${readWindowBytes}`, { signal });
200
214
  if (result.code !== 0) {
201
215
  throw new Error(result.stderr || `Failed to read file: ${path}`);
202
216
  }
@@ -206,7 +220,7 @@ export function createReadTool(executor, options = {}) {
206
220
  // Apply user limit if specified
207
221
  if (limit !== undefined) {
208
222
  const lines = selectedContent.split("\n");
209
- const endLine = Math.min(limit, countTextLines(selectedContent));
223
+ const endLine = Math.min(limit, countSplitLines(selectedContent, lines));
210
224
  selectedContent = lines.slice(0, endLine).join("\n");
211
225
  userLimitedLines = endLine;
212
226
  }
@@ -3,7 +3,7 @@ import { join } from "node:path";
3
3
  import { writeFileAtomically } from "../../shared/atomic-file.js";
4
4
  import { workspaceSubjectHash } from "../../tasks/artifact-subject.js";
5
5
  import { invalidateTaskVerification } from "../../tasks/control.js";
6
- import { appendCurrentCycleNote, normalizeTaskId, readActiveTasks, uncheckedTaskAcceptanceItems, } from "../../tasks/ledger.js";
6
+ import { appendCurrentCycleNote, applyTaskPlanPatch, normalizeTaskId, readActiveTasks, uncheckedTaskAcceptanceItems, } from "../../tasks/ledger.js";
7
7
  import { taskBodyHash } from "../../tasks/store.js";
8
8
  import { normalizeStoredStatus, resolveTaskTransition } from "../../tasks/transitions.js";
9
9
  import { RecoverableToolError } from "../tool-details.js";
@@ -51,7 +51,13 @@ export async function progressTask(options, request) {
51
51
  if (nextFields.control && request.status !== "waiting" && request.control?.blockedReason === undefined) {
52
52
  nextFields.control.blockedReason = undefined;
53
53
  }
54
- const nextBody = appendCurrentCycleNote(body, note);
54
+ // planSteps deltas fold into the same Current Cycle note (spec 037, D3): the plan's change
55
+ // history rides on the log startTaskCycle already archives into History, rather than a second,
56
+ // separately-maintained revision trail nothing else consumes.
57
+ const { body: bodyWithPlan, summary: planSummary } = request.planSteps?.length
58
+ ? applyTaskPlanPatch(body, request.planSteps)
59
+ : { body, summary: "" };
60
+ const nextBody = appendCurrentCycleNote(bodyWithPlan, planSummary ? `${note} ${planSummary}` : note);
55
61
  await writeFileAtomically(taskPath, renderTaskFile(nextFields, nextBody));
56
62
  return {
57
63
  action: "progress",
@@ -10,6 +10,12 @@ export declare const taskManageSchema: Type.TObject<{
10
10
  dod: Type.TOptional<Type.TString>;
11
11
  manual: Type.TOptional<Type.TString>;
12
12
  verificationPlan: Type.TOptional<Type.TString>;
13
+ plan: Type.TOptional<Type.TString>;
14
+ planSteps: Type.TOptional<Type.TArray<Type.TObject<{
15
+ id: Type.TString;
16
+ status: Type.TOptional<Type.TUnion<[Type.TLiteral<"todo">, Type.TLiteral<"done">, Type.TLiteral<"blocked">, Type.TLiteral<"dropped">]>>;
17
+ text: Type.TOptional<Type.TString>;
18
+ }>>>;
13
19
  control: Type.TOptional<Type.TObject<{
14
20
  priority: Type.TOptional<Type.TUnion<[Type.TLiteral<"low">, Type.TLiteral<"normal">, Type.TLiteral<"high">, Type.TLiteral<"critical">]>>;
15
21
  deadline: Type.TOptional<Type.TString>;
@@ -46,6 +46,20 @@ export const taskManageSchema = Type.Object({
46
46
  })),
47
47
  manual: Type.Optional(Type.String({ description: "Optional for create: initial operating steps or checklist." })),
48
48
  verificationPlan: Type.Optional(Type.String({ description: "Optional for create: deterministic checks the verifier must perform." })),
49
+ plan: Type.Optional(Type.String({
50
+ description: 'Optional for create: initial "## Plan" steps, one per line — the means, not the DoD. A step without a ' +
51
+ 'leading "P<n>" id gets one auto-assigned in order. Update step status/text later via progress\'s planSteps, not by editing this at create time.',
52
+ })),
53
+ planSteps: Type.Optional(Type.Array(Type.Object({
54
+ id: Type.String({
55
+ description: 'Plan step id, e.g. "P2". An id not yet present is appended as a new step.',
56
+ }),
57
+ status: Type.Optional(Type.Union([Type.Literal("todo"), Type.Literal("done"), Type.Literal("blocked"), Type.Literal("dropped")], { description: "New status for this step; omit to leave it unchanged." })),
58
+ text: Type.Optional(Type.String({ description: "New step text; required when appending a step with an unseen id." })),
59
+ }), {
60
+ description: "For progress: update or append Plan steps by id, e.g. mark P2 done, P3 blocked, and add a new P5. " +
61
+ 'Requires the task to already have a "## Plan" section, or this call is the one that creates it.',
62
+ })),
49
63
  control: Type.Optional(taskControlSchema),
50
64
  status: Type.Optional(Type.Union(SETTABLE_STATUSES.map((status) => Type.Literal(status)), { description: "New status for create/progress/set. To close a task use action done, not status." })),
51
65
  wake: Type.Optional(Type.String({
@@ -83,6 +83,7 @@ export function renderTaskSkeleton(request) {
83
83
  manual: request.manual,
84
84
  verificationPlan: request.verificationPlan,
85
85
  verificationRequired: control.verification.required,
86
+ plan: request.plan,
86
87
  });
87
88
  return { fields, body };
88
89
  }
package/dist/tui/app.js CHANGED
@@ -103,7 +103,7 @@ export async function runTuiApp(options) {
103
103
  channelId,
104
104
  userName: safeUserName(),
105
105
  renderHelp: () => renderBuiltInHelp(),
106
- renderUsage: (args) => renderUsageReport(getUsageLedger(), channelId, parseUsageMode(args), new Date()),
106
+ renderUsage: async (args) => renderUsageReport(getUsageLedger(), channelId, parseUsageMode(args), new Date()),
107
107
  runEvents: (args) => handleEventsCommand({ args, workspaceDir: paths.workspaceDir, historyPath: paths.eventHistoryPath }),
108
108
  runTasks: (args) => handleTasksCommand({
109
109
  args,
@@ -36,7 +36,7 @@ export interface DispatchDeps {
36
36
  renderHelp(): string;
37
37
  renderStatus(): string;
38
38
  renderContext(args: string): string;
39
- renderUsage(args: string): string;
39
+ renderUsage(args: string): Promise<string>;
40
40
  runEvents(args: string): Promise<string>;
41
41
  runTasks(args: string): Promise<string>;
42
42
  }
@@ -34,7 +34,7 @@ export async function dispatch(input, deps) {
34
34
  case "context":
35
35
  return { kind: "reply", text: deps.renderContext(command.args) };
36
36
  case "usage":
37
- return { kind: "reply", text: deps.renderUsage(command.args) };
37
+ return { kind: "reply", text: await deps.renderUsage(command.args) };
38
38
  case "events":
39
39
  return { kind: "reply", text: await deps.runEvents(command.args) };
40
40
  case "tasks":
@@ -19,7 +19,7 @@ export interface TurnControllerDeps {
19
19
  userName: string;
20
20
  /** Info commands that do not depend on run state. */
21
21
  renderHelp: () => string;
22
- renderUsage: (args: string) => string;
22
+ renderUsage: (args: string) => Promise<string>;
23
23
  runEvents: (args: string) => Promise<string>;
24
24
  runTasks: (args: string) => Promise<string>;
25
25
  /** Static bits the status renderer needs alongside the live run state. */
@@ -41,7 +41,7 @@ export interface UsageSummaryQuery {
41
41
  export declare const UNTRACKED_CHANNEL_ID = "(untracked)";
42
42
  export interface UsageLedger {
43
43
  record(entry: Omit<UsageLedgerEntry, "ts">): void;
44
- summarize(query: UsageSummaryQuery): UsageSummary;
44
+ summarize(query: UsageSummaryQuery): Promise<UsageSummary>;
45
45
  flush?(): Promise<void>;
46
46
  close?(): Promise<void>;
47
47
  }
@@ -1,4 +1,4 @@
1
- import { existsSync, readFileSync } from "node:fs";
1
+ import { readFile, stat } from "node:fs/promises";
2
2
  import { join } from "node:path";
3
3
  import * as log from "../log.js";
4
4
  import { USAGE_STATE_DIR } from "../paths.js";
@@ -22,6 +22,50 @@ export function createUsageLedger(options = {}) {
22
22
  const baseDir = options.baseDir ?? USAGE_STATE_DIR;
23
23
  const fileFor = (date) => join(baseDir, `usage-${monthKey(date)}.jsonl`);
24
24
  const appender = createJsonlAppender({ pathFor: fileFor });
25
+ /**
26
+ * Parsed month files, keyed on path and invalidated by size/mtime.
27
+ *
28
+ * One `/usage` report calls `summarize` several times — a global and a per-channel figure for
29
+ * every window it renders — and each call used to re-read and re-parse the same month file,
30
+ * synchronously, on the daemon's event loop. The cache collapses those into one parse; the
31
+ * fingerprint means an appended entry is still picked up on the next report.
32
+ */
33
+ const monthCache = new Map();
34
+ const loadMonth = async (path) => {
35
+ let fingerprint;
36
+ try {
37
+ const stats = await stat(path);
38
+ fingerprint = { mtimeMs: stats.mtimeMs, size: stats.size };
39
+ }
40
+ catch {
41
+ monthCache.delete(path);
42
+ return [];
43
+ }
44
+ const cached = monthCache.get(path);
45
+ if (cached && cached.mtimeMs === fingerprint.mtimeMs && cached.size === fingerprint.size) {
46
+ return cached.entries;
47
+ }
48
+ let content;
49
+ try {
50
+ content = await readFile(path, "utf-8");
51
+ }
52
+ catch {
53
+ return [];
54
+ }
55
+ const entries = [];
56
+ for (const line of content.split("\n")) {
57
+ if (!line)
58
+ continue;
59
+ try {
60
+ entries.push(JSON.parse(line));
61
+ }
62
+ catch {
63
+ // Tolerate a torn trailing line.
64
+ }
65
+ }
66
+ monthCache.set(path, { ...fingerprint, entries });
67
+ return entries;
68
+ };
25
69
  return {
26
70
  record(entry) {
27
71
  // Record anything that consumed tokens, even at zero cost: a local model, or one whose
@@ -42,7 +86,7 @@ export function createUsageLedger(options = {}) {
42
86
  },
43
87
  flush: () => appender.flush(),
44
88
  close: () => appender.close(),
45
- summarize(query) {
89
+ async summarize(query) {
46
90
  const until = query.until ?? new Date();
47
91
  const sinceMs = query.since.getTime();
48
92
  const untilMs = until.getTime();
@@ -55,26 +99,7 @@ export function createUsageLedger(options = {}) {
55
99
  byChannel: {},
56
100
  };
57
101
  for (const key of monthKeysBetween(query.since, until)) {
58
- const path = join(baseDir, `usage-${key}.jsonl`);
59
- if (!existsSync(path))
60
- continue;
61
- let content;
62
- try {
63
- content = readFileSync(path, "utf-8");
64
- }
65
- catch {
66
- continue;
67
- }
68
- for (const line of content.split("\n")) {
69
- if (!line)
70
- continue;
71
- let entry;
72
- try {
73
- entry = JSON.parse(line);
74
- }
75
- catch {
76
- continue; // tolerate a torn trailing line
77
- }
102
+ for (const entry of await loadMonth(join(baseDir, `usage-${key}.jsonl`))) {
78
103
  const tsMs = parseLocalTime(entry.ts);
79
104
  if (tsMs === undefined || tsMs < sinceMs || tsMs > untilMs)
80
105
  continue;
@@ -7,5 +7,5 @@ interface UsageWindow {
7
7
  until: Date;
8
8
  }
9
9
  export declare function usageWindows(mode: UsageQueryMode, now: Date): UsageWindow[];
10
- export declare function renderUsageReport(ledger: UsageLedger, channelId: string, mode: UsageQueryMode, now: Date): string;
10
+ export declare function renderUsageReport(ledger: UsageLedger, channelId: string, mode: UsageQueryMode, now: Date): Promise<string>;
11
11
  export {};
@@ -46,9 +46,11 @@ function renderKindBreakdown(summary) {
46
46
  const parts = topEntries(summary.byKind, 3).map(([kind, cost]) => `${kind} ${money(cost)}`);
47
47
  return parts.length > 0 ? parts.join(" · ") : null;
48
48
  }
49
- function renderWindow(window, ledger, channelId) {
50
- const global = ledger.summarize({ since: window.since, until: window.until });
51
- const channel = ledger.summarize({ since: window.since, until: window.until, channelId });
49
+ async function renderWindow(window, ledger, channelId) {
50
+ const [global, channel] = await Promise.all([
51
+ ledger.summarize({ since: window.since, until: window.until }),
52
+ ledger.summarize({ since: window.since, until: window.until, channelId }),
53
+ ]);
52
54
  const lines = [`## ${window.title}`];
53
55
  if (global.entryCount === 0) {
54
56
  lines.push("暂无用量记录。");
@@ -69,8 +71,8 @@ function renderWindow(window, ledger, channelId) {
69
71
  }
70
72
  return lines.join("\n");
71
73
  }
72
- export function renderUsageReport(ledger, channelId, mode, now) {
74
+ export async function renderUsageReport(ledger, channelId, mode, now) {
73
75
  const windows = usageWindows(mode, now);
74
- const body = windows.map((window) => renderWindow(window, ledger, channelId)).join("\n\n");
75
- return `# 用量\n\n${body}`;
76
+ const rendered = await Promise.all(windows.map((window) => renderWindow(window, ledger, channelId)));
77
+ return `# 用量\n\n${rendered.join("\n\n")}`;
76
78
  }