@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
@@ -680,53 +680,20 @@ export class DingTalkBot {
680
680
  }
681
681
  /**
682
682
  * Send a normal message natively mapping DM and Group to correct endpoints (fallback when no card).
683
+ *
684
+ * Only the message shape is decided here; the DM-vs-group routing and the POST itself belong to
685
+ * `sendRobotMessage`, which every other outbound message type already goes through.
683
686
  */
684
687
  async sendPlain(channelId, text) {
685
- const token = await this.getAccessToken();
686
- if (!token)
687
- return false;
688
688
  const meta = this.getConversationMeta(channelId);
689
689
  if (!meta) {
690
690
  log.logWarning(`No conversation metadata for ${channelId}, cannot send plain message`);
691
691
  return false;
692
692
  }
693
- const robotCode = this.config.robotCode || this.config.clientId;
694
- const isGroup = meta.conversationType === "2";
695
693
  const hasMarkdown = /^#{1,6}\s|^\s*[-*]\s|\*\*.*\*\*|```|`[^`]+`|\[.*?\]\(.*?\)/m.test(text);
696
694
  const msgKey = hasMarkdown ? "sampleMarkdown" : "sampleText";
697
695
  const msgParam = hasMarkdown ? JSON.stringify({ text, title: "Bot" }) : JSON.stringify({ content: text });
698
- const url = isGroup
699
- ? `${DINGTALK_API}/v1.0/robot/groupMessages/send`
700
- : `${DINGTALK_API}/v1.0/robot/oToMessages/batchSend`;
701
- const body = {
702
- robotCode,
703
- msgKey,
704
- msgParam,
705
- };
706
- if (isGroup) {
707
- body.openConversationId = meta.conversationId;
708
- }
709
- else {
710
- body.userIds = [meta.senderId];
711
- }
712
- try {
713
- await http.post(url, body, {
714
- headers: {
715
- "x-acs-dingtalk-access-token": token,
716
- "Content-Type": "application/json",
717
- },
718
- });
719
- return true;
720
- }
721
- catch (err) {
722
- if (axios.isAxiosError(err) && err.response) {
723
- log.logWarning(`DingTalk plain send failed (${err.response.status})`, JSON.stringify(err.response.data));
724
- }
725
- else {
726
- log.logWarning("DingTalk plain send error", errorMessage(err));
727
- }
728
- return false;
729
- }
696
+ return this.sendRobotMessage(meta, msgKey, msgParam);
730
697
  }
731
698
  // ==========================================================================
732
699
  // Media (image / file) delivery — MediaSender contract
@@ -810,8 +777,8 @@ export class DingTalkBot {
810
777
  }
811
778
  /**
812
779
  * POST a robot message with an arbitrary msgKey/msgParam, routing DM vs group
813
- * to the correct endpoint. Shared by the media path; `sendPlain` predates this
814
- * and keeps its own inlined copy to avoid a regression-prone refactor.
780
+ * to the correct endpoint. The single outbound path for every non-card message:
781
+ * plain text/markdown, images, and files.
815
782
  */
816
783
  async sendRobotMessage(meta, msgKey, msgParam) {
817
784
  const token = await this.getAccessToken();
@@ -50,9 +50,15 @@ export declare class ChannelStore {
50
50
  private closed;
51
51
  constructor(config: ChannelStoreConfig);
52
52
  /**
53
- * Get or create the directory for a channel/DM
53
+ * The archive path for a channel — resolved, not created.
54
+ *
55
+ * This used to call `ensureChannelDir`, i.e. a synchronous `mkdirSync` on the event loop for
56
+ * every archived message. `logBotResponse` runs on every progress update of a streaming turn,
57
+ * so that was a blocking syscall per progress tick. The appender's own `ensureDir` already
58
+ * creates the directory before it writes, and memoizes it, so the mkdir here was pure
59
+ * duplicated I/O.
54
60
  */
55
- getChannelDir(channelId: string): string;
61
+ private channelArchiveDir;
56
62
  /**
57
63
  * Log a message to the channel's log.jsonl raw archive.
58
64
  * This file is cold storage and is not proactively loaded into memory context.
@@ -3,7 +3,7 @@ import { writeFile } from "fs/promises";
3
3
  import { basename, dirname, join } from "path";
4
4
  import { createJsonlAppender } from "../shared/jsonl-appender.js";
5
5
  import { formatLocalTime } from "../shared/local-time.js";
6
- import { ensureChannelDir } from "./channel-paths.js";
6
+ import { getChannelDir } from "./channel-paths.js";
7
7
  const MAX_LOG_SIZE_BYTES = 1_000_000;
8
8
  const DEDUPE_TTL_MS = 60_000;
9
9
  const DEDUPE_CLEANUP_INTERVAL_MS = 30_000;
@@ -35,10 +35,16 @@ export class ChannelStore {
35
35
  }
36
36
  }
37
37
  /**
38
- * Get or create the directory for a channel/DM
38
+ * The archive path for a channel — resolved, not created.
39
+ *
40
+ * This used to call `ensureChannelDir`, i.e. a synchronous `mkdirSync` on the event loop for
41
+ * every archived message. `logBotResponse` runs on every progress update of a streaming turn,
42
+ * so that was a blocking syscall per progress tick. The appender's own `ensureDir` already
43
+ * creates the directory before it writes, and memoizes it, so the mkdir here was pure
44
+ * duplicated I/O.
39
45
  */
40
- getChannelDir(channelId) {
41
- return ensureChannelDir(this.workingDir, channelId);
46
+ channelArchiveDir(channelId) {
47
+ return getChannelDir(this.workingDir, channelId);
42
48
  }
43
49
  /**
44
50
  * Log a message to the channel's log.jsonl raw archive.
@@ -58,7 +64,7 @@ export class ChannelStore {
58
64
  }
59
65
  this.recentlyLogged.delete(dedupeKey);
60
66
  }
61
- const logPath = join(this.getChannelDir(channelId), "log.jsonl");
67
+ const logPath = join(this.channelArchiveDir(channelId), "log.jsonl");
62
68
  if (!message.date) {
63
69
  message.date = formatLocalTime();
64
70
  }
@@ -72,7 +78,7 @@ export class ChannelStore {
72
78
  async logSubAgentRun(channelId, run) {
73
79
  if (this.closed)
74
80
  return;
75
- const logPath = join(this.getChannelDir(channelId), "subagent-runs.jsonl");
81
+ const logPath = join(this.channelArchiveDir(channelId), "subagent-runs.jsonl");
76
82
  if (!this.archiveAppender.tryAppend({ filePath: logPath, value: run })) {
77
83
  throw new Error("Sub-agent archive queue is full. Retry after pending log writes drain.");
78
84
  }
@@ -8,7 +8,7 @@ import { nextTaskWake } from "../shared/task-schedule.js";
8
8
  import { errorMessage } from "../shared/text-utils.js";
9
9
  import { isRecord } from "../shared/type-guards.js";
10
10
  import { applyTaskControlPatch, createDefaultTaskControl, retiredTaskControlKeys, TASK_PRIORITIES, taskBudgetViolation, } from "../tasks/control.js";
11
- import { extractTaskTitle, isTaskParked, missingStandardTaskSections, normalizeTaskId, readActiveTasks, } from "../tasks/ledger.js";
11
+ import { countTaskDodItems, extractTaskTitle, isTaskParked, missingStandardTaskSections, normalizeTaskId, readActiveTasks, } from "../tasks/ledger.js";
12
12
  import { withTaskMutation } from "../tasks/mutation-lock.js";
13
13
  import { claimTaskAttempt, openRecurringTaskCycle, readStoredTask, releaseTaskAttemptClaim, taskBodyHash, writeStoredTask, } from "../tasks/store.js";
14
14
  import { normalizeStoredStatus, resolveTaskTransition } from "../tasks/transitions.js";
@@ -588,6 +588,20 @@ async function doctor(options) {
588
588
  if (missing.length > 0) {
589
589
  issues.push(issue(`tasks/${entry.id}.md is missing standard section(s): ${missing.join(", ")}.`, `Ask the agent to normalize tasks/${entry.id}.md to the standard task skeleton.`));
590
590
  }
591
+ // spec 037, D4: two deterministic, zero-LLM-cost drift checks between a Plan and its
592
+ // DoD — the first real consumer of "is the plan still pointed at the goal?".
593
+ if (entry.plan) {
594
+ const dodCount = countTaskDodItems(content);
595
+ const invalidRefs = entry.plan.steps.flatMap((step) => step.dodRefs.filter((ref) => ref < 1 || ref > dodCount).map((ref) => `${step.id}→dod:${ref}`));
596
+ if (invalidRefs.length > 0) {
597
+ issues.push(issue(`tasks/${entry.id}.md Plan references DoD item(s) that do not exist: ${invalidRefs.join(", ")}.`, `Fix the "→ dod:N" reference(s) in the Plan, or renumber them if the DoD list changed.`));
598
+ }
599
+ const covered = new Set(entry.plan.steps.filter((step) => step.status !== "dropped").flatMap((step) => step.dodRefs));
600
+ const uncovered = Array.from({ length: dodCount }, (_, index) => index + 1).filter((dodIndex) => !covered.has(dodIndex));
601
+ if (dodCount > 0 && uncovered.length > 0) {
602
+ issues.push(issue(`tasks/${entry.id}.md has DoD item(s) with no Plan step covering them: dod:${uncovered.join(",")}.`, `Add or update a Plan step's "→ dod:${uncovered[0]}" reference, or confirm those DoD items need no dedicated step.`));
603
+ }
604
+ }
591
605
  }
592
606
  // A parked task is waiting for someone to call it: a finished background job, a user
593
607
  // message, or `/tasks run`. The driver deliberately will not (see `isTaskParked`), so with
@@ -43,6 +43,11 @@ function attemptKey(channelId, taskId) {
43
43
  * and let a wake that changed real files count as stalled. The task's own effect tally stands in
44
44
  * for the work itself instead — per task, not per channel, so a neighbour's activity (including
45
45
  * the user chatting) neither certifies progress here nor hides a task that is spinning.
46
+ *
47
+ * `entry.plan` is absent for the same reason (spec 037, D5): checking off a Plan step is a
48
+ * model-reported claim, not evidence of an effect. If plan state fed the fingerprint, ticking a
49
+ * checkbox would reset the futile counter and buy the short retry tier — a governor bypass this
50
+ * driver must not offer. The Plan is a capsule/agenda display concern only.
46
51
  */
47
52
  function taskFingerprint(entry, effects) {
48
53
  const control = entry.frontmatter.control;
@@ -116,6 +121,11 @@ export function createTaskDriverEvent(channelId, entry, nowMs, attemptGeneration
116
121
  const control = entry.frontmatter.control;
117
122
  const capsule = [
118
123
  `Task capsule: title=${entry.title}; status=${entry.frontmatter.status ?? "active"};`,
124
+ // Surfacing the Plan's progress and current step here is the point of spec 037, D2/D4: the
125
+ // model no longer has to re-derive "what step am I on" from latestNote/nextAction each wake.
126
+ entry.plan
127
+ ? `plan=${entry.plan.done}/${entry.plan.total} done, current=${entry.plan.current?.id ?? "none"};`
128
+ : "",
119
129
  entry.latestNote ? `latest=${entry.latestNote};` : "",
120
130
  control?.nextAction ? `next=${control.nextAction};` : "",
121
131
  control ? `budget=${control.usage.attempts}/${control.budget.maxAttempts} attempts;` : "",
@@ -309,16 +309,32 @@ function extractFindExecCommands(parsed) {
309
309
  }
310
310
  return inner;
311
311
  }
312
+ /**
313
+ * How many suffix positions of a wrapper's arguments are treated as candidate command starts.
314
+ *
315
+ * The scan below is a superset heuristic, not a soundness requirement: the wrapper's own direct
316
+ * rule, `sh -c` bodies and `find -exec` are all matched separately and are unaffected by this
317
+ * bound. Without a bound the scan is quadratic in the argument count — every suffix is sliced and
318
+ * re-joined into a normalized command line — and it recurses, so a wrapper whose arguments contain
319
+ * further wrappers multiplied that cost up to `MAX_GUARD_DEPTH` times. Measured: ~6ms at 200
320
+ * arguments, ~36ms at 800, which a long file list reaches without trying.
321
+ *
322
+ * A real inner command starts within the first few tokens, after the wrapper's own flags; no
323
+ * wrapper in `WRAPPER_COMMANDS` takes anything close to 32 of them. Positions beyond this are
324
+ * operands of the inner command, which has already been inspected from its own start position.
325
+ */
326
+ const MAX_WRAPPER_CANDIDATES = 32;
312
327
  // For a generic wrapper, the inner command can sit anywhere after the wrapper's
313
328
  // own options/operands (whose grammar varies per tool). Rather than parse each
314
- // wrapper's flags precisely, evaluate every suffix position as a candidate
315
- // command start — this only ever adds detections, never relaxes them.
329
+ // wrapper's flags precisely, evaluate the leading suffix positions as candidate
330
+ // command starts — this only ever adds detections, never relaxes them.
316
331
  function extractWrapperCandidates(parsed) {
317
332
  if (!WRAPPER_COMMANDS.has(parsed.command)) {
318
333
  return [];
319
334
  }
320
335
  const candidates = [];
321
- for (let i = 0; i < parsed.args.length; i++) {
336
+ const limit = Math.min(parsed.args.length, MAX_WRAPPER_CANDIDATES);
337
+ for (let i = 0; i < limit; i++) {
322
338
  candidates.push(parsed.args.slice(i));
323
339
  }
324
340
  return candidates;
@@ -351,6 +367,30 @@ function hasDangerousDeletionTarget(args) {
351
367
  function joinedArgs(parsed) {
352
368
  return parsed.args.join(" ");
353
369
  }
370
+ /**
371
+ * `matchRule` runs once per atom per recursion level, so compiling the configured patterns inside
372
+ * it recompiled the same regexes many times for a single guarded command. The list comes from
373
+ * `security.json` and is rebuilt only when that file is reloaded, so caching on its identity is
374
+ * enough. Invalid patterns are dropped here, once, instead of throwing on every evaluation.
375
+ */
376
+ const denyPatternCache = new WeakMap();
377
+ function compileDenyPatterns(patterns) {
378
+ const cached = denyPatternCache.get(patterns);
379
+ if (cached) {
380
+ return cached;
381
+ }
382
+ const compiled = [];
383
+ for (const pattern of patterns) {
384
+ try {
385
+ compiled.push({ pattern, regex: new RegExp(pattern, "i") });
386
+ }
387
+ catch {
388
+ // Ignore invalid user patterns.
389
+ }
390
+ }
391
+ denyPatternCache.set(patterns, compiled);
392
+ return compiled;
393
+ }
354
394
  function matchRule(parsed, config) {
355
395
  const argsText = joinedArgs(parsed);
356
396
  const normalized = parsed.normalized;
@@ -470,20 +510,14 @@ function matchRule(parsed, config) {
470
510
  };
471
511
  }
472
512
  }
473
- for (const pattern of config.additionalDenyPatterns) {
474
- try {
475
- const regex = new RegExp(pattern, "i");
476
- if (regex.test(normalized)) {
477
- return {
478
- category: "configured-command-deny",
479
- rule: pattern,
480
- reason: "Command matched a configured deny pattern",
481
- matchedText: normalized,
482
- };
483
- }
484
- }
485
- catch {
486
- // Ignore invalid user patterns.
513
+ for (const { pattern, regex } of compileDenyPatterns(config.additionalDenyPatterns)) {
514
+ if (regex.test(normalized)) {
515
+ return {
516
+ category: "configured-command-deny",
517
+ rule: pattern,
518
+ reason: "Command matched a configured deny pattern",
519
+ matchedText: normalized,
520
+ };
487
521
  }
488
522
  }
489
523
  return null;
@@ -96,6 +96,25 @@ function resolveExistingAncestor(path) {
96
96
  current = parent;
97
97
  }
98
98
  }
99
+ /**
100
+ * `resolveForGuard` for the two roots every call resolves: the workspace and the home directory.
101
+ *
102
+ * Unlike a guarded target, these are existing directories that do not move for the life of the
103
+ * process, so their realpath is stable — but resolving them cost two `realpathSync` calls on
104
+ * *every* guarded read and write. Cached on the literal input so a different workspace (tests,
105
+ * a second runtime in-process) still resolves correctly.
106
+ */
107
+ const rootRealPathCache = new Map();
108
+ function resolveRootForGuard(path, ctx) {
109
+ const key = `${ctx.config.resolveSymlinks !== false}\0${path}`;
110
+ const cached = rootRealPathCache.get(key);
111
+ if (cached !== undefined) {
112
+ return cached;
113
+ }
114
+ const resolved = resolveForGuard(path, ctx);
115
+ rootRealPathCache.set(key, resolved);
116
+ return resolved;
117
+ }
99
118
  function resolveForGuard(path, ctx) {
100
119
  const normalized = normalize(path);
101
120
  const resolveSymlinks = ctx.config.resolveSymlinks !== false;
@@ -112,15 +131,37 @@ function resolveForGuard(path, ctx) {
112
131
  function matchesAnyPath(path, exactPaths, prefixes) {
113
132
  return exactPaths.includes(path) || prefixes.some((prefix) => startsWithPathPrefix(path, prefix));
114
133
  }
134
+ /**
135
+ * The sensitive-path lists are module constants; only `homeDir` varies, and in practice it is one
136
+ * value for the life of the process. Resolving all ~25 of them (null-strip, NFKC-normalize,
137
+ * expand, normalize) on every single guarded read/write was pure repeated work, so the resolved
138
+ * table is memoized per home directory.
139
+ */
140
+ const sensitivePathTables = new Map();
141
+ function getSensitivePathTable(homeDir) {
142
+ const cached = sensitivePathTables.get(homeDir);
143
+ if (cached) {
144
+ return cached;
145
+ }
146
+ const table = {
147
+ homePrefixes: HOME_SENSITIVE_PREFIXES.map((item) => resolveHomeConfiguredPath(item, homeDir)),
148
+ homeFiles: HOME_SENSITIVE_FILES.map((item) => resolveHomeConfiguredPath(item, homeDir)),
149
+ writeDenyHomeFiles: WRITE_DENY_HOME_FILES.map((item) => resolveHomeConfiguredPath(item, homeDir)),
150
+ };
151
+ sensitivePathTables.set(homeDir, table);
152
+ return table;
153
+ }
154
+ /** Path-independent, so resolved once at module load. */
155
+ const SENSITIVE_SYSTEM_PREFIXES = SYSTEM_SENSITIVE_PREFIXES.map((item) => normalize(item));
156
+ const SENSITIVE_SYSTEM_FILES = SYSTEM_SENSITIVE_FILES.map((item) => normalize(item));
157
+ const NORMALIZED_SYSTEM_DENY_PREFIXES = SYSTEM_DENY_PREFIXES.map((prefix) => normalize(prefix));
158
+ const NORMALIZED_TEMP_PREFIXES = TEMP_PREFIXES.map((prefix) => normalize(prefix));
115
159
  function matchesSensitiveReadPath(path, homeDir) {
116
- const sensitiveHomePrefixes = HOME_SENSITIVE_PREFIXES.map((item) => resolveHomeConfiguredPath(item, homeDir));
117
- const sensitiveHomeFiles = HOME_SENSITIVE_FILES.map((item) => resolveHomeConfiguredPath(item, homeDir));
118
- const sensitiveSystemPrefixes = SYSTEM_SENSITIVE_PREFIXES.map((item) => normalize(item));
119
- const sensitiveSystemFiles = SYSTEM_SENSITIVE_FILES.map((item) => normalize(item));
120
- if (matchesAnyPath(path, sensitiveHomeFiles, sensitiveHomePrefixes)) {
160
+ const table = getSensitivePathTable(homeDir);
161
+ if (matchesAnyPath(path, table.homeFiles, table.homePrefixes)) {
121
162
  return true;
122
163
  }
123
- if (matchesAnyPath(path, sensitiveSystemFiles, sensitiveSystemPrefixes)) {
164
+ if (matchesAnyPath(path, SENSITIVE_SYSTEM_FILES, SENSITIVE_SYSTEM_PREFIXES)) {
124
165
  return true;
125
166
  }
126
167
  if (PROC_MEM_PATH.test(path)) {
@@ -137,16 +178,29 @@ function matchesSensitiveWritePath(path, homeDir) {
137
178
  if (matchesSensitiveReadPath(path, homeDir)) {
138
179
  return true;
139
180
  }
140
- const writeDenyHomeFiles = WRITE_DENY_HOME_FILES.map((item) => resolveHomeConfiguredPath(item, homeDir));
141
- return writeDenyHomeFiles.includes(path);
181
+ return getSensitivePathTable(homeDir).writeDenyHomeFiles.includes(path);
142
182
  }
143
- function isWithinTemp(path) {
144
- const configuredPrefixes = TEMP_PREFIXES.map((prefix) => normalize(prefix));
183
+ /**
184
+ * Resolving the runtime temp directory costs an `existsSync` plus a `realpathSync` walk, and
185
+ * `isWithinTemp` is consulted up to twice per guarded path. `tmpdir()` reads TMPDIR/TEMP each
186
+ * time, so the cache is keyed on it: an env change still takes effect, it just stops paying for
187
+ * the syscalls on every tool call.
188
+ */
189
+ let tempPrefixCache = null;
190
+ function getTempPrefixes() {
145
191
  const runtimeTmpDir = normalize(tmpdir());
192
+ if (tempPrefixCache?.tmpDir === runtimeTmpDir) {
193
+ return tempPrefixCache.prefixes;
194
+ }
146
195
  const runtimePrefixes = existsSync(runtimeTmpDir)
147
196
  ? [runtimeTmpDir, resolveExistingAncestor(runtimeTmpDir)]
148
197
  : [runtimeTmpDir];
149
- return [...configuredPrefixes, ...runtimePrefixes].some((prefix) => startsWithPathPrefix(path, prefix));
198
+ const prefixes = [...NORMALIZED_TEMP_PREFIXES, ...runtimePrefixes];
199
+ tempPrefixCache = { tmpDir: runtimeTmpDir, prefixes };
200
+ return prefixes;
201
+ }
202
+ function isWithinTemp(path) {
203
+ return getTempPrefixes().some((prefix) => startsWithPathPrefix(path, prefix));
150
204
  }
151
205
  function isWithinHome(path, homeDir) {
152
206
  return startsWithPathPrefix(path, normalize(homeDir));
@@ -158,8 +212,12 @@ function isDeniedSystemPath(path) {
158
212
  if (isWithinTemp(path)) {
159
213
  return false;
160
214
  }
161
- return SYSTEM_DENY_PREFIXES.some((prefix) => startsWithPathPrefix(path, normalize(prefix)));
215
+ return NORMALIZED_SYSTEM_DENY_PREFIXES.some((prefix) => startsWithPathPrefix(path, prefix));
162
216
  }
217
+ // Deliberately not cached: a configured allow/deny entry may not exist yet, and `resolveForGuard`
218
+ // resolves a missing path through its nearest existing ancestor. Caching that would freeze the
219
+ // pre-creation answer, so a path later created as a symlink would stop being resolved to its
220
+ // target. Both lists are empty by default, so this costs nothing unless the operator opts in.
163
221
  function matchesConfiguredPath(path, entries, ctx) {
164
222
  return entries
165
223
  .map((entry) => resolveForGuard(resolveConfiguredPath(entry, ctx), ctx))
@@ -190,8 +248,8 @@ export function guardPath(rawPath, operation, ctx) {
190
248
  const homeDir = ctx.homeDir ?? homedir();
191
249
  const effectiveCtx = {
192
250
  ...ctx,
193
- workspaceDir: resolveForGuard(ctx.workspaceDir, ctx),
194
- homeDir: resolveForGuard(homeDir, ctx),
251
+ workspaceDir: resolveRootForGuard(ctx.workspaceDir, ctx),
252
+ homeDir: resolveRootForGuard(homeDir, ctx),
195
253
  };
196
254
  const resolvedTarget = resolveTargetPath(rawPath, ctx);
197
255
  const guardedPath = resolveForGuard(resolvedTarget, ctx);
@@ -2,6 +2,7 @@ import { existsSync, statSync } from "node:fs";
2
2
  import { mkdir, writeFile } from "node:fs/promises";
3
3
  import { isAbsolute, join, relative, resolve } from "node:path";
4
4
  import { Agent } from "@earendil-works/pi-agent-core";
5
+ import { streamSimple } from "@earendil-works/pi-ai/compat";
5
6
  import { convertToLlm } from "@earendil-works/pi-coding-agent";
6
7
  import { Type } from "typebox";
7
8
  import { getChannelHistoryPath, getChannelMemoryPath, getChannelSessionPath, readChannelSession, } from "../memory/files.js";
@@ -475,6 +476,7 @@ export function createSubAgentTool(options) {
475
476
  },
476
477
  convertToLlm,
477
478
  getApiKey: async () => apiKey,
479
+ streamFn: streamSimple,
478
480
  });
479
481
  const childController = new AbortController();
480
482
  const unlinkAbortSignals = linkAbortSignals(signal, childController);
@@ -41,6 +41,8 @@ export interface TaskLedgerEntry {
41
41
  wakeMs?: number;
42
42
  /** First bullet/line under a "当前周期"/"current cycle" heading, if any (digest only). */
43
43
  latestNote?: string;
44
+ /** Parsed `## Plan` section, if the task has one (spec 037, D2). */
45
+ plan?: TaskPlanSummary;
44
46
  }
45
47
  export interface TaskSkeletonInput {
46
48
  title: string;
@@ -49,6 +51,8 @@ export interface TaskSkeletonInput {
49
51
  manual?: string;
50
52
  verificationPlan?: string;
51
53
  verificationRequired?: boolean;
54
+ /** Optional initial `## Plan` steps, one per line; a missing `P<n>` prefix is auto-assigned. */
55
+ plan?: string;
52
56
  }
53
57
  export declare const DEFAULT_TASK_MANUAL = "- Follow the DoD, keep the current cycle log updated, and schedule check-ins when waiting.";
54
58
  export declare const STANDARD_TASK_SECTIONS: readonly [{
@@ -78,15 +82,75 @@ export declare function normalizeTaskId(id: string): string;
78
82
  /** The document body after the leading frontmatter block, or the whole content when there is none. */
79
83
  export declare function taskBody(content: string): string;
80
84
  /**
81
- * The task's *contract* segment: the body up to (excluding) the "Current Cycle" heading —
82
- * i.e. the H1 title, Goal, DoD (with its checkbox state), Manual and Verification (spec 029, D4).
85
+ * The task's *contract* segment: the body up to (excluding) whichever of "Plan" or "Current
86
+ * Cycle" appears first — i.e. the H1 title, Goal, DoD (with its checkbox state), Manual and
87
+ * Verification (spec 029, D4).
83
88
  *
84
89
  * Verification PASS and external approval bind to this segment, not the whole body, so routine
85
- * `progress` notes (Current Cycle) and appended History/Completion Evidence never invalidate a
86
- * PASS or approval — only a change to what the task promises to do and how it is checked does.
87
- * A body without a Current Cycle heading (non-standard) falls back to the whole body.
90
+ * `progress` notes (Current Cycle, and — spec 037, D1 — Plan step status) never invalidate a
91
+ * PASS or approval; only a change to what the task promises to do and how it is checked does.
92
+ * Plan is deliberately excluded from the contract even though it always precedes Current Cycle
93
+ * in a freshly rendered skeleton: it is the task's *means*, not its promise, and is meant to be
94
+ * revised without re-triggering verification. This also means a task with an existing PASS can
95
+ * have `## Plan` inserted between Verification and Current Cycle with the contract segment
96
+ * unchanged byte-for-byte, as long as nothing before it changed.
97
+ * A body without either heading (non-standard) falls back to the whole body.
88
98
  */
89
99
  export declare function taskContractSegment(body: string): string;
100
+ export type TaskPlanStepStatus = "todo" | "done" | "blocked" | "dropped";
101
+ export interface TaskPlanStep {
102
+ /** `P<n>` by convention; a hand-written step without one gets its position as a fallback. */
103
+ id: string;
104
+ status: TaskPlanStepStatus;
105
+ text: string;
106
+ /** DoD item numbers this step claims to cover, from a trailing `→ dod:1,2` (or `-> dod:1,2`). */
107
+ dodRefs: number[];
108
+ lineIndex: number;
109
+ }
110
+ export interface TaskPlanSummary {
111
+ steps: TaskPlanStep[];
112
+ /** Count of steps, excluding `dropped` ones. */
113
+ total: number;
114
+ done: number;
115
+ /** The first `todo` or `blocked` step in document order; `undefined` once nothing is left to do. */
116
+ current?: TaskPlanStep;
117
+ }
118
+ /**
119
+ * Parse the optional `## Plan` section: a fourth, hand-maintained layer between the contract
120
+ * (Goal/DoD/Manual/Verification) and the append-only Current Cycle/History log (spec 037, D2).
121
+ *
122
+ * Four checkbox states — `[ ]` todo, `[x]` done, `[!]` blocked, `[~]` dropped — and no separate
123
+ * "doing" marker: the current step is *derived* (first `todo`/`blocked` in document order), not
124
+ * self-reported, for the same reason `task-driver.ts`'s fingerprint excludes the model's own
125
+ * progress notes — a runtime-derived signal cannot be talked into lying about itself.
126
+ *
127
+ * Returns `undefined` when there is no Plan heading, or the heading has no checkbox lines under
128
+ * it (nothing to summarize) — both read the same as "this task has no Plan yet".
129
+ */
130
+ export declare function parseTaskPlan(content: string): TaskPlanSummary | undefined;
131
+ export interface TaskPlanStepPatch {
132
+ id: string;
133
+ status?: TaskPlanStepStatus;
134
+ text?: string;
135
+ }
136
+ export interface ApplyTaskPlanPatchResult {
137
+ body: string;
138
+ /** Human-readable delta, meant to be folded into the caller's Current Cycle note; `""` if nothing changed. */
139
+ summary: string;
140
+ }
141
+ /**
142
+ * Update or append Plan steps by id (spec 037, D3). An id that already exists gets its
143
+ * status/text patched in place, preserving its `dod` refs and position; an unseen id is appended
144
+ * as a new step (`text` is then required — there is nothing sensible to append otherwise). A task
145
+ * with no `## Plan` section yet gets an empty one inserted before Current Cycle first, so the
146
+ * very first `planSteps` call on a task is also the one that creates its Plan.
147
+ *
148
+ * The returned `summary` is deliberately not a new persisted field (see the file-level doc on
149
+ * `TaskPlanSummary`): it is meant to be appended to the caller's own Current Cycle note, so the
150
+ * change history rides on the log `startTaskCycle` already folds into History — no second,
151
+ * unconsumed revision counter.
152
+ */
153
+ export declare function applyTaskPlanPatch(body: string, patches: readonly TaskPlanStepPatch[]): ApplyTaskPlanPatchResult;
90
154
  /** Parse the leading `---` frontmatter block into the three known fields. */
91
155
  export declare function parseTaskFrontmatter(content: string): TaskFrontmatter;
92
156
  /**
@@ -120,6 +184,11 @@ export declare function missingStandardTaskSections(content: string): string[];
120
184
  * `task_manage candidate`/`done` through with nothing ever actually verified.
121
185
  */
122
186
  export declare function uncheckedTaskAcceptanceItems(content: string): string[];
187
+ /**
188
+ * Count of checkbox items (checked or not) under the DoD heading, for cross-referencing a Plan
189
+ * step's `→ dod:N` refs (spec 037, D4 — `/tasks doctor`'s drift checks).
190
+ */
191
+ export declare function countTaskDodItems(content: string): number;
123
192
  export declare function renderStandardTaskBody(input: TaskSkeletonInput): string;
124
193
  export interface TaskDocumentFields {
125
194
  status: string;