@oyasmi/pipiclaw 0.9.1 → 0.9.2-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 (167) hide show
  1. package/dist/agent/channel-runner.d.ts +15 -1
  2. package/dist/agent/channel-runner.js +76 -24
  3. package/dist/agent/effect-ledger.js +9 -2
  4. package/dist/agent/job-manager.d.ts +4 -0
  5. package/dist/agent/job-manager.js +17 -2
  6. package/dist/agent/prompt/manifest.d.ts +1 -1
  7. package/dist/agent/prompt/manifest.js +1 -1
  8. package/dist/agent/prompt/sections.js +8 -5
  9. package/dist/agent/session-events.d.ts +2 -0
  10. package/dist/agent/session-events.js +29 -14
  11. package/dist/agent/turn-recovery.js +2 -2
  12. package/dist/agent/type-guards.js +5 -1
  13. package/dist/agent/workspace-resources.d.ts +2 -2
  14. package/dist/agent/workspace-resources.js +41 -3
  15. package/dist/executor.d.ts +14 -0
  16. package/dist/executor.js +96 -24
  17. package/dist/file-store.d.ts +96 -0
  18. package/dist/file-store.js +189 -0
  19. package/dist/memory/consolidation.js +2 -26
  20. package/dist/memory/files.js +7 -7
  21. package/dist/memory/maintenance-jobs.js +2 -34
  22. package/dist/memory/maintenance-state.js +2 -1
  23. package/dist/memory/recall.d.ts +10 -0
  24. package/dist/memory/recall.js +15 -7
  25. package/dist/memory/session-search.js +6 -22
  26. package/dist/memory/transcript.d.ts +10 -0
  27. package/dist/memory/transcript.js +39 -0
  28. package/dist/playbooks/agent-delegation.md +7 -5
  29. package/dist/playbooks/background-jobs.md +1 -1
  30. package/dist/playbooks/catalog.d.ts +1 -1
  31. package/dist/playbooks/catalog.js +1 -1
  32. package/dist/playbooks/event-scheduling.md +2 -0
  33. package/dist/playbooks/memory-and-learning.md +11 -11
  34. package/dist/playbooks/runtime-orientation.md +3 -3
  35. package/dist/playbooks/task-driving.md +7 -7
  36. package/dist/playbooks/task-planning.md +5 -5
  37. package/dist/runtime/app-home.js +1 -1
  38. package/dist/runtime/bootstrap.js +10 -0
  39. package/dist/runtime/dingtalk.js +3 -2
  40. package/dist/runtime/durable-dispatch.d.ts +26 -1
  41. package/dist/runtime/durable-dispatch.js +51 -5
  42. package/dist/runtime/event-commands.js +7 -16
  43. package/dist/runtime/events.d.ts +4 -2
  44. package/dist/runtime/events.js +15 -20
  45. package/dist/runtime/subagent-commands.js +1 -1
  46. package/dist/runtime/task-commands.d.ts +1 -1
  47. package/dist/runtime/task-commands.js +17 -12
  48. package/dist/runtime/task-driver.js +2 -2
  49. package/dist/runtime/task-wake.d.ts +2 -2
  50. package/dist/runtime/task-wake.js +2 -2
  51. package/dist/security/block-message.d.ts +11 -0
  52. package/dist/security/block-message.js +12 -0
  53. package/dist/security/path-guard-check.d.ts +13 -0
  54. package/dist/security/path-guard-check.js +39 -0
  55. package/dist/security/path-guard.js +32 -14
  56. package/dist/settings.js +3 -2
  57. package/dist/shared/atomic-file.d.ts +17 -1
  58. package/dist/shared/atomic-file.js +50 -3
  59. package/dist/shared/duration.d.ts +2 -0
  60. package/dist/shared/duration.js +7 -0
  61. package/dist/shared/safe-id.d.ts +19 -0
  62. package/dist/shared/safe-id.js +24 -0
  63. package/dist/shared/text-utils.d.ts +1 -1
  64. package/dist/shared/text-utils.js +3 -8
  65. package/dist/shared/type-guards.d.ts +2 -0
  66. package/dist/shared/type-guards.js +4 -0
  67. package/dist/subagents/discovery.d.ts +44 -17
  68. package/dist/subagents/discovery.js +82 -111
  69. package/dist/subagents/external/claude-code.js +1 -3
  70. package/dist/subagents/external/harness.d.ts +1 -1
  71. package/dist/subagents/external/run.d.ts +6 -0
  72. package/dist/subagents/external/run.js +122 -58
  73. package/dist/subagents/external/settlement.d.ts +3 -0
  74. package/dist/subagents/external/settlement.js +19 -5
  75. package/dist/subagents/format.d.ts +3 -2
  76. package/dist/subagents/format.js +3 -7
  77. package/dist/subagents/runs.d.ts +45 -9
  78. package/dist/subagents/runs.js +184 -64
  79. package/dist/subagents/tool.d.ts +35 -24
  80. package/dist/subagents/tool.js +631 -577
  81. package/dist/subagents/verification-outcome.js +1 -1
  82. package/dist/subagents/workspace-lease.js +1 -1
  83. package/dist/tasks/artifact-subject.d.ts +30 -4
  84. package/dist/tasks/artifact-subject.js +257 -25
  85. package/dist/tasks/control.js +7 -9
  86. package/dist/tasks/ledger.d.ts +2 -2
  87. package/dist/tasks/ledger.js +3 -7
  88. package/dist/tasks/transitions.d.ts +5 -1
  89. package/dist/tasks/transitions.js +2 -2
  90. package/dist/tasks/verification.d.ts +24 -2
  91. package/dist/tasks/verification.js +113 -21
  92. package/dist/tools/bash.d.ts +0 -1
  93. package/dist/tools/bash.js +45 -40
  94. package/dist/tools/config.d.ts +6 -1
  95. package/dist/tools/config.js +9 -0
  96. package/dist/tools/edit.d.ts +2 -3
  97. package/dist/tools/edit.js +274 -86
  98. package/dist/tools/event-manage.d.ts +13 -7
  99. package/dist/tools/event-manage.js +52 -14
  100. package/dist/tools/glob-match.d.ts +11 -0
  101. package/dist/tools/glob-match.js +75 -0
  102. package/dist/tools/glob.d.ts +15 -0
  103. package/dist/tools/glob.js +113 -0
  104. package/dist/tools/grep.d.ts +0 -1
  105. package/dist/tools/grep.js +57 -42
  106. package/dist/tools/ignore-dirs.d.ts +6 -0
  107. package/dist/tools/ignore-dirs.js +15 -0
  108. package/dist/tools/index.d.ts +3 -0
  109. package/dist/tools/index.js +50 -40
  110. package/dist/tools/job.d.ts +0 -1
  111. package/dist/tools/job.js +1 -8
  112. package/dist/tools/line-index.d.ts +16 -0
  113. package/dist/tools/line-index.js +76 -0
  114. package/dist/tools/memory-manage.d.ts +20 -8
  115. package/dist/tools/memory-manage.js +65 -92
  116. package/dist/tools/presentation.d.ts +2 -0
  117. package/dist/tools/presentation.js +109 -0
  118. package/dist/tools/read.d.ts +2 -2
  119. package/dist/tools/read.js +97 -133
  120. package/dist/tools/registry.d.ts +4 -1
  121. package/dist/tools/registry.js +89 -22
  122. package/dist/tools/send-media.d.ts +6 -6
  123. package/dist/tools/send-media.js +16 -49
  124. package/dist/tools/session-search.d.ts +0 -1
  125. package/dist/tools/session-search.js +0 -1
  126. package/dist/tools/skill-security.d.ts +0 -2
  127. package/dist/tools/skill-security.js +0 -24
  128. package/dist/tools/skill.d.ts +31 -0
  129. package/dist/tools/skill.js +153 -0
  130. package/dist/tools/subagent-manage.d.ts +6 -5
  131. package/dist/tools/subagent-manage.js +60 -60
  132. package/dist/tools/task-manage/create.d.ts +2 -2
  133. package/dist/tools/task-manage/create.js +1 -3
  134. package/dist/tools/task-manage/lifecycle.d.ts +9 -6
  135. package/dist/tools/task-manage/lifecycle.js +56 -60
  136. package/dist/tools/task-manage/schema.d.ts +27 -15
  137. package/dist/tools/task-manage/schema.js +58 -74
  138. package/dist/tools/task-manage/shared.d.ts +11 -6
  139. package/dist/tools/task-manage/shared.js +30 -21
  140. package/dist/tools/task-manage/types.d.ts +14 -15
  141. package/dist/tools/task-manage/verification.d.ts +5 -5
  142. package/dist/tools/task-manage/verification.js +18 -15
  143. package/dist/tools/task-manage.d.ts +8 -11
  144. package/dist/tools/task-manage.js +63 -50
  145. package/dist/tools/tool-details.d.ts +17 -1
  146. package/dist/tools/tool-details.js +24 -0
  147. package/dist/tools/truncate.d.ts +5 -5
  148. package/dist/tools/truncate.js +5 -5
  149. package/dist/tools/web-fetch.d.ts +0 -1
  150. package/dist/tools/web-fetch.js +0 -1
  151. package/dist/tools/web-search.d.ts +0 -1
  152. package/dist/tools/web-search.js +0 -1
  153. package/dist/tools/write-content.d.ts +3 -3
  154. package/dist/tools/write-content.js +12 -51
  155. package/dist/tools/write.d.ts +2 -3
  156. package/dist/tools/write.js +3 -4
  157. package/dist/tui/pitui-frontend.js +3 -3
  158. package/dist/usage/ledger.js +7 -4
  159. package/examples/sub-agents/README.md +13 -13
  160. package/examples/sub-agents/documenter.md +2 -1
  161. package/examples/sub-agents/reviewer.md +2 -0
  162. package/examples/sub-agents/scout.md +2 -1
  163. package/examples/sub-agents/verifier.md +6 -4
  164. package/examples/sub-agents/worker.md +2 -1
  165. package/package.json +5 -5
  166. package/dist/tools/skill-manage.d.ts +0 -41
  167. package/dist/tools/skill-manage.js +0 -232
package/dist/executor.js CHANGED
@@ -1,4 +1,11 @@
1
+ import { createWriteStream } from "node:fs";
1
2
  import { spawn } from "child_process";
3
+ /**
4
+ * Default in-memory capture cap for a command's stdout/stderr, in bytes (spec 044, D6.1/D6.2).
5
+ * This is `Executor`'s own bound for *command output* -- file content never goes through it (see
6
+ * `src/file-store.ts`). A caller that needs a different bound (e.g. `grep`) can override it with
7
+ * `ExecOptions.maxCaptureBytes`.
8
+ */
2
9
  const MAX_CAPTURE_BYTES = 10 * 1024 * 1024;
3
10
  /**
4
11
  * Create an executor that runs commands on the host machine.
@@ -23,6 +30,41 @@ export class CommandTerminatedError extends Error {
23
30
  this.timeoutSeconds = timeoutSeconds;
24
31
  }
25
32
  }
33
+ /** Accumulates raw chunks up to a byte cap without re-copying already-capped data on every event. */
34
+ class CappedByteAccumulator {
35
+ constructor(maxBytes) {
36
+ this.maxBytes = maxBytes;
37
+ this.chunks = [];
38
+ this.bytes = 0;
39
+ this.capped = false;
40
+ }
41
+ push(chunk) {
42
+ if (this.capped)
43
+ return;
44
+ const room = this.maxBytes - this.bytes;
45
+ if (chunk.length <= room) {
46
+ this.chunks.push(chunk);
47
+ this.bytes += chunk.length;
48
+ if (this.bytes >= this.maxBytes) {
49
+ this.capped = true;
50
+ }
51
+ return;
52
+ }
53
+ if (room > 0) {
54
+ this.chunks.push(chunk.subarray(0, room));
55
+ this.bytes += room;
56
+ }
57
+ this.capped = true;
58
+ }
59
+ get truncated() {
60
+ return this.capped;
61
+ }
62
+ /** Decode once, at close, rather than per-chunk -- see D6.1: per-chunk `toString()` can split a
63
+ * multi-byte UTF-8 sequence across chunk boundaries and mint U+FFFD in the middle of valid text. */
64
+ toText() {
65
+ return Buffer.concat(this.chunks).toString("utf-8");
66
+ }
67
+ }
26
68
  class HostExecutor {
27
69
  async exec(command, options) {
28
70
  return new Promise((resolve, reject) => {
@@ -42,32 +84,64 @@ class HostExecutor {
42
84
  if (!child) {
43
85
  return;
44
86
  }
45
- let stdout = "";
46
- let stderr = "";
47
- let stdoutCapped = false;
48
- let stderrCapped = false;
87
+ const maxCaptureBytes = options?.maxCaptureBytes ?? MAX_CAPTURE_BYTES;
88
+ const stdoutAcc = new CappedByteAccumulator(maxCaptureBytes);
89
+ const stderrAcc = new CappedByteAccumulator(maxCaptureBytes);
49
90
  let timedOut = false;
50
91
  let settled = false;
51
- const cleanup = () => {
92
+ let spillStream;
93
+ let spillFailed = false;
94
+ if (options?.spillTo) {
95
+ try {
96
+ spillStream = createWriteStream(options.spillTo, { mode: 0o600 });
97
+ spillStream.on("error", () => {
98
+ spillFailed = true;
99
+ });
100
+ }
101
+ catch {
102
+ spillFailed = true;
103
+ }
104
+ }
105
+ const spill = (chunk) => {
106
+ if (spillStream && !spillFailed) {
107
+ spillStream.write(chunk);
108
+ }
109
+ };
110
+ // Waits for the spill file to actually finish flushing to disk before settling the promise
111
+ // -- `spillStream.end()` alone only *starts* the flush, so a caller that reads the spill
112
+ // path immediately after `exec()` resolves could otherwise race an incomplete write.
113
+ const finalize = (action) => {
52
114
  if (timeoutHandle)
53
115
  clearTimeout(timeoutHandle);
54
116
  if (options?.signal) {
55
117
  options.signal.removeEventListener("abort", onAbort);
56
118
  }
119
+ if (!spillStream) {
120
+ action();
121
+ return;
122
+ }
123
+ const stream = spillStream;
124
+ let settledSpill = false;
125
+ const done = () => {
126
+ if (settledSpill)
127
+ return;
128
+ settledSpill = true;
129
+ action();
130
+ };
131
+ stream.once("error", done);
132
+ stream.end(done);
57
133
  };
58
134
  const rejectOnce = (err) => {
59
135
  if (settled)
60
136
  return;
61
137
  settled = true;
62
- cleanup();
63
- reject(err);
138
+ finalize(() => reject(err));
64
139
  };
65
140
  const resolveOnce = (result) => {
66
141
  if (settled)
67
142
  return;
68
143
  settled = true;
69
- cleanup();
70
- resolve(result);
144
+ finalize(() => resolve(result));
71
145
  };
72
146
  const timeoutHandle = options?.timeout && options.timeout > 0
73
147
  ? setTimeout(() => {
@@ -92,27 +166,19 @@ class HostExecutor {
92
166
  // at the cap, which for a high-output command is many GB of memcpy that blocks the event
93
167
  // loop for the whole daemon (fix plan §2.2).
94
168
  child.stdout?.on("data", (data) => {
95
- if (stdoutCapped)
96
- return;
97
- stdout += data.toString();
98
- if (stdout.length > MAX_CAPTURE_BYTES) {
99
- stdout = stdout.slice(0, MAX_CAPTURE_BYTES);
100
- stdoutCapped = true;
101
- }
169
+ stdoutAcc.push(data);
170
+ spill(data);
102
171
  });
103
172
  child.stderr?.on("data", (data) => {
104
- if (stderrCapped)
105
- return;
106
- stderr += data.toString();
107
- if (stderr.length > MAX_CAPTURE_BYTES) {
108
- stderr = stderr.slice(0, MAX_CAPTURE_BYTES);
109
- stderrCapped = true;
110
- }
173
+ stderrAcc.push(data);
174
+ spill(data);
111
175
  });
112
176
  child.on("error", (err) => {
113
177
  rejectOnce(err instanceof Error ? err : new Error(String(err)));
114
178
  });
115
179
  child.on("close", (code) => {
180
+ const stdout = stdoutAcc.toText();
181
+ const stderr = stderrAcc.toText();
116
182
  if (options?.signal?.aborted) {
117
183
  rejectOnce(new CommandTerminatedError("aborted", stdout, stderr));
118
184
  return;
@@ -121,7 +187,13 @@ class HostExecutor {
121
187
  rejectOnce(new CommandTerminatedError("timeout", stdout, stderr, options?.timeout));
122
188
  return;
123
189
  }
124
- resolveOnce({ stdout, stderr, code: code ?? 0 });
190
+ resolveOnce({
191
+ stdout,
192
+ stderr,
193
+ code: code ?? 0,
194
+ ...(stdoutAcc.truncated ? { stdoutTruncated: true } : {}),
195
+ ...(stderrAcc.truncated ? { stderrTruncated: true } : {}),
196
+ });
125
197
  });
126
198
  if (options?.stdin !== undefined) {
127
199
  child.stdin?.on("error", (err) => {
@@ -0,0 +1,96 @@
1
+ import { type Readable, Writable } from "node:stream";
2
+ /**
3
+ * `FileStore` is the file-content counterpart to `Executor` (spec 044, D1): where `Executor` runs
4
+ * a shell command and captures its stdout/stderr, `FileStore` reads and writes file *content*
5
+ * directly over `node:fs`. File content must never be routed through argv, stdout, or stdin --
6
+ * that path forces every read/write through `Executor`'s bounded capture buffer, which silently
7
+ * truncates and can corrupt multi-byte text mid-stream (see the spec's F2/F3 evidence).
8
+ *
9
+ * All paths passed to a `FileStore` method are expected to be the absolute `resolvedPath` that
10
+ * `guardPath` already produced -- callers resolve a path exactly once and pass that same value to
11
+ * both the guard and the store (spec 044, D1.1).
12
+ */
13
+ export interface FileStat {
14
+ size: number;
15
+ mtimeMs: number;
16
+ ino: number;
17
+ mode: number;
18
+ isDirectory: boolean;
19
+ isFile: boolean;
20
+ }
21
+ /** Lightweight fingerprint used to detect a concurrent write between a read and a later write-back (D2.4). */
22
+ export interface FileFingerprint {
23
+ size: number;
24
+ mtimeMs: number;
25
+ ino: number;
26
+ }
27
+ export declare function fingerprintOf(stat: FileStat): FileFingerprint;
28
+ export declare function fingerprintsEqual(a: FileFingerprint, b: FileFingerprint): boolean;
29
+ export interface DirectoryEntry {
30
+ /** Basename of the entry. */
31
+ name: string;
32
+ /** Path relative to the directory passed to `listDirectory`, using `/` separators. */
33
+ relativePath: string;
34
+ isDirectory: boolean;
35
+ }
36
+ export interface ReadBytesOptions {
37
+ start?: number;
38
+ maxBytes?: number;
39
+ signal?: AbortSignal;
40
+ }
41
+ export interface ReadBytesResult {
42
+ data: Buffer;
43
+ /** Whether this read reached the end of the file -- the caller's cue for "is there more?" (P2). */
44
+ eof: boolean;
45
+ stat: FileStat;
46
+ }
47
+ export interface WriteAtomicOptions {
48
+ createParentDir?: boolean;
49
+ /** Preserve the existing file's permission bits across the rename (see `shared/atomic-file.ts`). */
50
+ preserveMode?: boolean;
51
+ signal?: AbortSignal;
52
+ }
53
+ export interface ReplaceViaTempOptions {
54
+ preserveMode?: boolean;
55
+ signal?: AbortSignal;
56
+ }
57
+ export interface WalkFilesOptions {
58
+ /** Stop once this many file paths have been collected; the walk short-circuits, `truncated` says so. */
59
+ maxEntries: number;
60
+ /** Called with a directory's basename; returning true skips descending into it (never dereferenced). */
61
+ prune?: (dirName: string) => boolean;
62
+ signal?: AbortSignal;
63
+ }
64
+ export interface WalkFilesResult {
65
+ /** Regular-file paths only (never directories or symlinks), `/`-joined and relative to the walked root. */
66
+ files: string[];
67
+ /** True when `maxEntries` was hit before the walk finished -- the result is a partial, not the complete tree. */
68
+ truncated: boolean;
69
+ }
70
+ export interface FileStore {
71
+ /** ENOENT resolves to `undefined` rather than throwing. */
72
+ stat(path: string): Promise<FileStat | undefined>;
73
+ /** Single bounded read. `eof` tells the caller whether there is more file left to fetch. */
74
+ readBytes(path: string, opts?: ReadBytesOptions): Promise<ReadBytesResult>;
75
+ /** Streaming read, for `edit`'s large-file path and `read`'s line-index scan. */
76
+ openRead(path: string, opts?: {
77
+ start?: number;
78
+ end?: number;
79
+ }): Readable;
80
+ /** Write-temp-then-rename with fsync, mirroring `shared/atomic-file.ts`'s guarantees. */
81
+ writeAtomic(path: string, data: Buffer | string, opts?: WriteAtomicOptions): Promise<void>;
82
+ /** Streaming atomic replace: `produce` writes to a temp file; on success it is renamed over `path`. */
83
+ replaceViaTemp(path: string, produce: (out: Writable) => Promise<void>, opts?: ReplaceViaTempOptions): Promise<void>;
84
+ /** Depth-bounded directory listing, replacing the `find -maxdepth` shell-out. */
85
+ listDirectory(path: string, opts: {
86
+ maxDepth: number;
87
+ }): Promise<DirectoryEntry[]>;
88
+ /**
89
+ * Unbounded-depth file discovery for `glob`, replacing the `find` shell-out. Directories are
90
+ * pruned by `opts.prune` before being entered (so a huge `node_modules` is never walked at all,
91
+ * mirroring `grep`'s `--exclude-dir` push-down); symlinks (file or directory) are never followed,
92
+ * since `Dirent.isFile()`/`isDirectory()` reflect the link itself, not its target.
93
+ */
94
+ walkFiles(path: string, opts: WalkFilesOptions): Promise<WalkFilesResult>;
95
+ }
96
+ export declare function createFileStore(): FileStore;
@@ -0,0 +1,189 @@
1
+ import { createReadStream } from "node:fs";
2
+ import { stat as fsStat, mkdir, open, readdir, rename, unlink } from "node:fs/promises";
3
+ import { dirname, join } from "node:path";
4
+ import { Writable } from "node:stream";
5
+ import { createAtomicTempPath, writeFileAtomically } from "./shared/atomic-file.js";
6
+ export function fingerprintOf(stat) {
7
+ return { size: stat.size, mtimeMs: stat.mtimeMs, ino: stat.ino };
8
+ }
9
+ export function fingerprintsEqual(a, b) {
10
+ return a.size === b.size && a.mtimeMs === b.mtimeMs && a.ino === b.ino;
11
+ }
12
+ export function createFileStore() {
13
+ return new HostFileStore();
14
+ }
15
+ function toFileStat(raw) {
16
+ return {
17
+ size: raw.size,
18
+ mtimeMs: raw.mtimeMs,
19
+ ino: raw.ino,
20
+ mode: raw.mode,
21
+ isDirectory: raw.isDirectory(),
22
+ isFile: raw.isFile(),
23
+ };
24
+ }
25
+ function throwIfAborted(signal) {
26
+ if (signal?.aborted) {
27
+ throw new Error("Aborted");
28
+ }
29
+ }
30
+ /** Best-effort directory fsync after a rename; mirrors `shared/atomic-file.ts`'s own tolerance. */
31
+ async function fsyncDir(dir) {
32
+ await open(dir, "r")
33
+ .then(async (dirHandle) => {
34
+ try {
35
+ await dirHandle.sync();
36
+ }
37
+ finally {
38
+ await dirHandle.close();
39
+ }
40
+ })
41
+ .catch(() => undefined);
42
+ }
43
+ class HostFileStore {
44
+ async stat(path) {
45
+ try {
46
+ return toFileStat(await fsStat(path));
47
+ }
48
+ catch (error) {
49
+ if (error.code === "ENOENT") {
50
+ return undefined;
51
+ }
52
+ throw error;
53
+ }
54
+ }
55
+ async readBytes(path, opts = {}) {
56
+ throwIfAborted(opts.signal);
57
+ const handle = await open(path, "r");
58
+ try {
59
+ const stat = toFileStat(await handle.stat());
60
+ const start = Math.max(0, opts.start ?? 0);
61
+ const maxBytes = opts.maxBytes ?? Number.POSITIVE_INFINITY;
62
+ const available = Math.max(0, stat.size - start);
63
+ const toRead = Math.min(available, maxBytes);
64
+ const buffer = Buffer.alloc(toRead);
65
+ let readTotal = 0;
66
+ while (readTotal < toRead) {
67
+ throwIfAborted(opts.signal);
68
+ const { bytesRead } = await handle.read(buffer, readTotal, toRead - readTotal, start + readTotal);
69
+ if (bytesRead === 0) {
70
+ break;
71
+ }
72
+ readTotal += bytesRead;
73
+ }
74
+ const data = readTotal === buffer.length ? buffer : buffer.subarray(0, readTotal);
75
+ return { data, eof: start + readTotal >= stat.size, stat };
76
+ }
77
+ finally {
78
+ await handle.close();
79
+ }
80
+ }
81
+ openRead(path, opts = {}) {
82
+ return createReadStream(path, { start: opts.start, end: opts.end });
83
+ }
84
+ async writeAtomic(path, data, opts = {}) {
85
+ throwIfAborted(opts.signal);
86
+ if (opts.createParentDir) {
87
+ await mkdir(dirname(path), { recursive: true });
88
+ }
89
+ await writeFileAtomically(path, data, { preserveMode: opts.preserveMode });
90
+ }
91
+ async replaceViaTemp(path, produce, opts = {}) {
92
+ throwIfAborted(opts.signal);
93
+ const dir = dirname(path);
94
+ await mkdir(dir, { recursive: true });
95
+ const tempPath = createAtomicTempPath(path);
96
+ try {
97
+ const handle = await open(tempPath, "w");
98
+ try {
99
+ if (opts.preserveMode) {
100
+ const existing = await this.stat(path);
101
+ if (existing) {
102
+ await handle.chmod(existing.mode & 0o777);
103
+ }
104
+ }
105
+ // `handle.createWriteStream()` closes the underlying `FileHandle` itself once the stream
106
+ // ends, so a subsequent `handle.sync()`/`handle.close()` on the same handle would throw
107
+ // "file closed". Write through `handle.write()` directly instead, keeping the handle
108
+ // under our own control until the explicit `sync()` + `close()` below.
109
+ const out = new Writable({
110
+ write(chunk, _encoding, callback) {
111
+ handle.write(chunk).then(() => callback(), (error) => callback(error instanceof Error ? error : new Error(String(error))));
112
+ },
113
+ });
114
+ await produce(out);
115
+ await new Promise((resolve, reject) => {
116
+ out.once("error", reject);
117
+ out.end(() => resolve());
118
+ });
119
+ await handle.sync();
120
+ }
121
+ finally {
122
+ await handle.close();
123
+ }
124
+ await rename(tempPath, path);
125
+ await fsyncDir(dir);
126
+ }
127
+ catch (error) {
128
+ await unlink(tempPath).catch(() => undefined);
129
+ throw error;
130
+ }
131
+ }
132
+ async listDirectory(path, opts) {
133
+ const results = [];
134
+ const walk = async (currentDir, relPrefix, depth) => {
135
+ const entries = await readdir(currentDir, { withFileTypes: true });
136
+ for (const entry of entries) {
137
+ const relativePath = relPrefix ? `${relPrefix}/${entry.name}` : entry.name;
138
+ const isDirectory = entry.isDirectory();
139
+ results.push({ name: entry.name, relativePath, isDirectory });
140
+ if (isDirectory && depth < opts.maxDepth) {
141
+ await walk(join(currentDir, entry.name), relativePath, depth + 1);
142
+ }
143
+ }
144
+ };
145
+ await walk(path, "", 1);
146
+ return results;
147
+ }
148
+ async walkFiles(path, opts) {
149
+ const files = [];
150
+ let truncated = false;
151
+ const walk = async (currentDir, relPrefix) => {
152
+ if (truncated)
153
+ return;
154
+ throwIfAborted(opts.signal);
155
+ let entries;
156
+ try {
157
+ entries = await readdir(currentDir, { withFileTypes: true });
158
+ }
159
+ catch {
160
+ // An unreadable directory (permission, or removed mid-walk) is skipped rather than
161
+ // failing the whole discovery -- one bad subtree must not blank out every other match.
162
+ return;
163
+ }
164
+ for (const entry of entries) {
165
+ if (truncated)
166
+ return;
167
+ const relativePath = relPrefix ? `${relPrefix}/${entry.name}` : entry.name;
168
+ if (entry.isDirectory()) {
169
+ if (opts.prune?.(entry.name))
170
+ continue;
171
+ await walk(join(currentDir, entry.name), relativePath);
172
+ continue;
173
+ }
174
+ // Symlinks (to files or directories) report false from both checks and are skipped: a
175
+ // glob result must never resolve outside the guarded root through a link the walk never
176
+ // asked permission to follow.
177
+ if (!entry.isFile())
178
+ continue;
179
+ files.push(relativePath);
180
+ if (files.length >= opts.maxEntries) {
181
+ truncated = true;
182
+ return;
183
+ }
184
+ }
185
+ };
186
+ await walk(path, "");
187
+ return { files, truncated };
188
+ }
189
+ }
@@ -8,7 +8,7 @@ import { readMemoryMetadata } from "./metadata.js";
8
8
  import { classifyMemoryWrite, DEFAULT_MEMORY_AUTO_WRITE_CONFIDENCE, MAX_PROBATION_WRITES_PER_RUN, } from "./promotion.js";
9
9
  import { MEMORY_INPUT_SAFETY_RULES } from "./prompt-safety.js";
10
10
  import { runSidecarTask } from "./sidecar-worker.js";
11
- import { sanitizeMessagesForMemory } from "./transcript.js";
11
+ import { hasMeaningfulExchange, sanitizeMessagesForMemory } from "./transcript.js";
12
12
  const INLINE_TRANSCRIPT_MAX_CHARS = 28_000;
13
13
  const MEMORY_CLEANUP_LENGTH_THRESHOLD = 5_000;
14
14
  const MEMORY_UPDATE_BLOCK_THRESHOLD = 4;
@@ -73,30 +73,6 @@ function entriesAfterLatestCompactionBoundary(entries) {
73
73
  function extractMessagesFromSessionEntries(entries) {
74
74
  return entries.filter(isMessage).map((entry) => entry.message);
75
75
  }
76
- function hasMeaningfulMessages(messages) {
77
- let meaningfulCount = 0;
78
- for (const message of messages) {
79
- if (message.role === "user") {
80
- const text = typeof message.content === "string"
81
- ? message.content
82
- : message.content.map((part) => (part.type === "text" ? part.text : "[image]")).join("\n");
83
- if (text.trim())
84
- meaningfulCount++;
85
- }
86
- else if (message.role === "assistant") {
87
- const text = message.content
88
- .filter((part) => part.type === "text")
89
- .map((part) => part.text)
90
- .join("\n");
91
- if (text.trim())
92
- meaningfulCount++;
93
- }
94
- if (meaningfulCount >= 2) {
95
- return true;
96
- }
97
- }
98
- return false;
99
- }
100
76
  function countMatchingSectionHeadings(content, prefix) {
101
77
  return splitH2Sections(content).filter((section) => section.heading.startsWith(prefix)).length;
102
78
  }
@@ -135,7 +111,7 @@ export async function runInlineConsolidation(options) {
135
111
  const sourceEntries = options.sourceWindow?.entries ?? entriesAfterLatestCompactionBoundary(options.sessionEntries ?? []);
136
112
  const relevantMessages = options.sourceWindow?.messages ??
137
113
  (sourceEntries.length > 0 ? extractMessagesFromSessionEntries(sourceEntries) : options.messages);
138
- if (!hasMeaningfulMessages(sanitizeMessagesForMemory(relevantMessages))) {
114
+ if (!hasMeaningfulExchange(sanitizeMessagesForMemory(relevantMessages))) {
139
115
  return {
140
116
  skipped: true,
141
117
  appendedMemoryEntries: 0,
@@ -1,10 +1,10 @@
1
1
  import { createHash, randomBytes } from "crypto";
2
- import { existsSync, mkdirSync, writeFileSync } from "fs";
2
+ import { existsSync, mkdirSync } from "fs";
3
3
  import { appendFile, copyFile, readdir, rename, rm, stat } from "fs/promises";
4
4
  import { basename, join } from "path";
5
- import { writeFileAtomically } from "../shared/atomic-file.js";
5
+ import { writeFileAtomically, writeFileAtomicallySync } from "../shared/atomic-file.js";
6
6
  import { readOptionalTextFile } from "../shared/fs-utils.js";
7
- import { formatLocalTime, localStampForFilename } from "../shared/local-time.js";
7
+ import { formatLocalTime, localStampForFilename, parseLocalTime } from "../shared/local-time.js";
8
8
  import { syncMemoryMetadata } from "./metadata.js";
9
9
  import { containsSecret, REDACTED_SECRET } from "./secret-redaction.js";
10
10
  import { appendMemoryTombstone, hashMemoryContent, readMemoryTombstones } from "./tombstones.js";
@@ -92,7 +92,7 @@ export function parseUpdateHeadingTimestamp(heading) {
92
92
  return undefined;
93
93
  }
94
94
  const timestamp = match[1].trim();
95
- return Number.isFinite(Date.parse(timestamp)) ? timestamp : undefined;
95
+ return parseLocalTime(timestamp) !== undefined ? timestamp : undefined;
96
96
  }
97
97
  /** Parse durable MEMORY.md bullet entries with stable ids for op-based edits. */
98
98
  export function parseChannelMemoryEntries(content) {
@@ -339,13 +339,13 @@ export function ensureChannelMemoryFilesSync(channelDir) {
339
339
  const sessionPath = getChannelSessionPath(channelDir);
340
340
  mkdirSync(channelDir, { recursive: true });
341
341
  if (!existsSync(memoryPath)) {
342
- writeFileSync(memoryPath, DEFAULT_CHANNEL_MEMORY, "utf-8");
342
+ writeFileAtomicallySync(memoryPath, DEFAULT_CHANNEL_MEMORY);
343
343
  }
344
344
  if (!existsSync(historyPath)) {
345
- writeFileSync(historyPath, DEFAULT_CHANNEL_HISTORY, "utf-8");
345
+ writeFileAtomicallySync(historyPath, DEFAULT_CHANNEL_HISTORY);
346
346
  }
347
347
  if (!existsSync(sessionPath)) {
348
- writeFileSync(sessionPath, DEFAULT_CHANNEL_SESSION, "utf-8");
348
+ writeFileAtomicallySync(sessionPath, DEFAULT_CHANNEL_SESSION);
349
349
  }
350
350
  }
351
351
  export async function readChannelMemory(channelDir) {
@@ -10,7 +10,7 @@ import { collectExpiredEntryIds, expireMemoryEntries } from "./probation.js";
10
10
  import { appendMemoryReviewLog } from "./review-log.js";
11
11
  import { updateChannelSessionMemory } from "./session.js";
12
12
  import { buildIncrementalMemorySourceWindow } from "./source-window.js";
13
- import { sanitizeMessagesForMemory } from "./transcript.js";
13
+ import { hasMeaningfulExchange, sanitizeMessagesForMemory } from "./transcript.js";
14
14
  /** Evaluate `load` at most once, so a gate and the job body can share one expensive read. */
15
15
  function once(load) {
16
16
  let cached;
@@ -22,40 +22,8 @@ function once(load) {
22
22
  function latestEntryId(entries) {
23
23
  return entries.at(-1)?.id;
24
24
  }
25
- function messageToText(message) {
26
- if (message.role === "user") {
27
- return typeof message.content === "string"
28
- ? message.content
29
- : message.content.map((part) => (part.type === "text" ? part.text : "[image]")).join("\n");
30
- }
31
- if (message.role === "assistant") {
32
- return message.content
33
- .map((part) => (part.type === "text" ? part.text : ""))
34
- .filter(Boolean)
35
- .join("\n");
36
- }
37
- return "";
38
- }
39
25
  function hasMeaningfulMessages(messages) {
40
- const standardMessages = sanitizeMessagesForMemory(messages);
41
- let userSeen = false;
42
- let assistantSeen = false;
43
- for (const message of standardMessages) {
44
- const text = messageToText(message).trim();
45
- if (!text) {
46
- continue;
47
- }
48
- if (message.role === "user") {
49
- userSeen = true;
50
- }
51
- if (message.role === "assistant") {
52
- assistantSeen = true;
53
- }
54
- if (userSeen && assistantSeen) {
55
- return true;
56
- }
57
- }
58
- return false;
26
+ return hasMeaningfulExchange(sanitizeMessagesForMemory(messages));
59
27
  }
60
28
  function makeRunOptions(input, usageCorrelationId) {
61
29
  return {
@@ -2,6 +2,7 @@ import { readFile } from "node:fs/promises";
2
2
  import { join } from "node:path";
3
3
  import * as log from "../log.js";
4
4
  import { writeFileAtomically } from "../shared/atomic-file.js";
5
+ import { parseLocalTime } from "../shared/local-time.js";
5
6
  import { createSerialQueue } from "../shared/serial-queue.js";
6
7
  import { errorMessage } from "../shared/text-utils.js";
7
8
  const stateUpdateQueue = createSerialQueue();
@@ -37,7 +38,7 @@ function laterTimestamp(a, b) {
37
38
  return b;
38
39
  if (!b)
39
40
  return a;
40
- return Date.parse(a) >= Date.parse(b) ? a : b;
41
+ return (parseLocalTime(a) ?? -Infinity) >= (parseLocalTime(b) ?? -Infinity) ? a : b;
41
42
  }
42
43
  function normalizeState(channelId, value) {
43
44
  if (!value || typeof value !== "object" || Array.isArray(value)) {
@@ -46,4 +46,14 @@ export declare const MEMORY_RECALL_MAX_UNITS = 1800;
46
46
  /** The most recent user turn, with injected memory/context wrappers stripped (see `transcript.ts`). */
47
47
  export declare function findPreviousUserText(messages: AgentMessage[]): string | undefined;
48
48
  export declare function tokenizeRecallText(text: string): string[];
49
+ /**
50
+ * Age-bucketed recency boost (≤1 day / ≤7 days / ≤30 days / older), scaled by `weights` — the
51
+ * bucket shape is shared with `session-search.ts`'s scoring, but the two scoring systems live on
52
+ * different magnitudes, so each caller supplies its own weights rather than sharing a fixed scale.
53
+ */
54
+ export declare function recencyBoostByAge(timestamp: string | undefined, weights: {
55
+ day: number;
56
+ week: number;
57
+ month: number;
58
+ }): number;
49
59
  export declare function recallRelevantMemory(request: RecallRequest): Promise<RecallResult>;