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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/dist/agent/job-manager.d.ts +9 -0
  2. package/dist/agent/job-manager.js +20 -6
  3. package/dist/agent/prompt/builder.d.ts +1 -1
  4. package/dist/agent/prompt/builder.js +1 -1
  5. package/dist/agent/prompt/sections.js +3 -3
  6. package/dist/executor.d.ts +5 -1
  7. package/dist/executor.js +35 -5
  8. package/dist/file-store.d.ts +4 -1
  9. package/dist/file-store.js +5 -0
  10. package/dist/memory/journal.d.ts +13 -0
  11. package/dist/memory/journal.js +47 -4
  12. package/dist/memory/search.js +13 -6
  13. package/dist/memory/session-corpus.d.ts +11 -0
  14. package/dist/memory/session-corpus.js +15 -4
  15. package/dist/memory/session-search.d.ts +3 -0
  16. package/dist/memory/session-search.js +45 -8
  17. package/dist/memory/store.d.ts +9 -0
  18. package/dist/memory/store.js +25 -2
  19. package/dist/playbooks/agent-delegation.md +35 -76
  20. package/dist/playbooks/background-jobs.md +14 -16
  21. package/dist/playbooks/event-scheduling.md +20 -25
  22. package/dist/playbooks/memory-and-learning.md +28 -61
  23. package/dist/playbooks/outbound-media.md +10 -12
  24. package/dist/playbooks/runtime-orientation.md +34 -53
  25. package/dist/playbooks/task-loop.md +49 -69
  26. package/dist/runtime/bootstrap.js +25 -11
  27. package/dist/security/path-guard-filter.d.ts +22 -0
  28. package/dist/security/path-guard-filter.js +35 -0
  29. package/dist/subagents/discovery.d.ts +2 -3
  30. package/dist/subagents/discovery.js +3 -1
  31. package/dist/subagents/tool.d.ts +6 -0
  32. package/dist/subagents/tool.js +10 -2
  33. package/dist/tasks/brief.d.ts +1 -1
  34. package/dist/tasks/brief.js +11 -2
  35. package/dist/tasks/log.d.ts +4 -0
  36. package/dist/tasks/log.js +13 -1
  37. package/dist/tools/bash.d.ts +13 -0
  38. package/dist/tools/bash.js +123 -20
  39. package/dist/tools/edit.js +36 -5
  40. package/dist/tools/event-manage.d.ts +25 -4
  41. package/dist/tools/event-manage.js +81 -33
  42. package/dist/tools/glob.js +57 -4
  43. package/dist/tools/grep.d.ts +2 -0
  44. package/dist/tools/grep.js +187 -14
  45. package/dist/tools/job.js +16 -4
  46. package/dist/tools/memory-manage.js +80 -41
  47. package/dist/tools/read.js +42 -5
  48. package/dist/tools/registry.d.ts +6 -0
  49. package/dist/tools/registry.js +4 -1
  50. package/dist/tools/send-media.js +6 -4
  51. package/dist/tools/session-search.js +4 -1
  52. package/dist/tools/skill.d.ts +2 -0
  53. package/dist/tools/skill.js +12 -0
  54. package/dist/tools/subagent-manage.js +1 -1
  55. package/dist/tools/subagent-tool-names.d.ts +11 -0
  56. package/dist/tools/subagent-tool-names.js +19 -0
  57. package/dist/tools/task-manage/log-view.js +6 -3
  58. package/dist/tools/task-manage/schema.d.ts +6 -6
  59. package/dist/tools/task-manage/schema.js +5 -12
  60. package/dist/tools/task-manage/shared.js +16 -2
  61. package/dist/tools/task-manage/step-end.js +22 -5
  62. package/dist/tools/task-manage.js +9 -1
  63. package/dist/tools/web-cache.d.ts +11 -3
  64. package/dist/tools/web-cache.js +26 -8
  65. package/dist/tools/web-fetch.d.ts +1 -0
  66. package/dist/tools/web-fetch.js +68 -15
  67. package/dist/tools/write.js +3 -0
  68. package/dist/web/fetch.d.ts +5 -0
  69. package/dist/web/fetch.js +36 -1
  70. package/examples/sub-agents/README.md +14 -4
  71. package/examples/sub-agents/builder-hard.md +12 -34
  72. package/examples/sub-agents/builder.md +11 -31
  73. package/examples/sub-agents/explorer.md +10 -16
  74. package/examples/sub-agents/git-committer.md +15 -20
  75. package/examples/sub-agents/planner.md +11 -21
  76. package/examples/sub-agents/reviewer.md +10 -31
  77. package/examples/sub-agents/verifier.md +12 -27
  78. package/examples/sub-agents/worker.md +11 -35
  79. package/package.json +7 -3
@@ -1,7 +1,8 @@
1
- import { join } from "node:path";
1
+ import { isAbsolute, join, relative } from "node:path";
2
2
  import { Type } from "typebox";
3
3
  import { DEFAULT_SECURITY_CONFIG } from "../security/config.js";
4
4
  import { checkPathGuard } from "../security/path-guard-check.js";
5
+ import { partitionByReadGuard } from "../security/path-guard-filter.js";
5
6
  import { RecoverableToolError } from "../shared/recoverable-error.js";
6
7
  import { errorMessage } from "../shared/text-utils.js";
7
8
  import { compileGlobPattern } from "./glob-match.js";
@@ -26,6 +27,18 @@ const globSchema = Type.Object({
26
27
  }),
27
28
  path: Type.Optional(Type.String({ description: "Directory to search in. Defaults to the workspace/project root." })),
28
29
  });
30
+ /** Turn a path relative to the search root into an address `read` accepts unchanged. */
31
+ function toReadableAddress(target, rel, securityContext) {
32
+ const abs = join(target, ...rel.split("/"));
33
+ const root = securityContext.projectRoot;
34
+ if (root) {
35
+ const fromRoot = relative(root, abs);
36
+ if (fromRoot && !fromRoot.startsWith("..") && !isAbsolute(fromRoot)) {
37
+ return fromRoot;
38
+ }
39
+ }
40
+ return abs;
41
+ }
29
42
  export function createGlobTool(fileStore, options = {}) {
30
43
  const securityConfig = options.securityConfig ?? DEFAULT_SECURITY_CONFIG;
31
44
  const securityContext = options.securityContext ?? {
@@ -58,13 +71,41 @@ export function createGlobTool(fileStore, options = {}) {
58
71
  // simplifying it, which "invalid pattern" alone does not tell the model.
59
72
  throw new RecoverableToolError(`Invalid glob pattern: ${pattern} (${errorMessage(error)})`);
60
73
  }
74
+ // `walkFiles` swallows a failed top-level readdir and returns an empty tree, so an
75
+ // illegal root would read as "no matches" and send the model looking for a broader
76
+ // pattern. Distinguish the three cases up front.
77
+ const rootStat = await fileStore.stat(target);
78
+ if (!rootStat) {
79
+ throw new RecoverableToolError(`Search root not found: ${searchPath}. Pass an existing directory, or omit path to search the workspace root.`);
80
+ }
81
+ if (!rootStat.isDirectory) {
82
+ throw new RecoverableToolError(`Search root is not a directory: ${searchPath}. glob searches a directory tree; to match one file, read it directly.`);
83
+ }
61
84
  const walk = await fileStore.walkFiles(target, {
62
85
  maxEntries: MAX_SCAN_ENTRIES,
63
86
  prune: (name) => IGNORED_DIR_SEGMENTS.has(name),
64
87
  signal,
65
88
  });
66
- const matched = walk.files.filter((relativePath) => matcher.test(relativePath));
89
+ const matchedRaw = walk.files.filter((relativePath) => matcher.test(relativePath));
90
+ // Backstop: `walkFiles` descends into `readDeny`/sensitive subtrees the per-path guard
91
+ // would refuse for a direct `read`. Drop those paths so `glob` never leaks them (a path
92
+ // name is less than `grep`'s content leak, but it is still a leak).
93
+ const { allowed: allowedAbs, deniedCount: readDenyExcluded } = partitionByReadGuard(matchedRaw.map((rel) => join(target, ...rel.split("/"))), securityConfig, securityContext);
94
+ const allowedAbsSet = new Set(allowedAbs);
95
+ const matched = matchedRaw.filter((rel) => allowedAbsSet.has(join(target, ...rel.split("/"))));
67
96
  if (matched.length === 0) {
97
+ if (readDenyExcluded > 0) {
98
+ return {
99
+ content: [
100
+ {
101
+ type: "text",
102
+ text: `All ${readDenyExcluded} path(s) matching "${pattern}" are excluded by the read policy. ` +
103
+ "Search a path you are allowed to read.",
104
+ },
105
+ ],
106
+ details: { matchCount: 0, readDenyExcluded },
107
+ };
108
+ }
68
109
  const scope = path ? `${searchPath}` : "the workspace";
69
110
  const text = walk.truncated
70
111
  ? `Scan of ${scope} hit the ${MAX_SCAN_ENTRIES.toLocaleString()}-file limit before any path matched "${pattern}". ` +
@@ -86,7 +127,11 @@ export function createGlobTool(fileStore, options = {}) {
86
127
  else {
87
128
  ordered = matched;
88
129
  }
89
- const page = ordered.slice(0, GLOB_MAX_RESULTS);
130
+ // Render each hit as an address `read` can take verbatim: a path relative to
131
+ // `target` alone is ambiguous (read resolves relative paths against projectRoot, not
132
+ // the search root), so emit a projectRoot-relative path when the hit is inside it and
133
+ // an absolute path otherwise.
134
+ const page = ordered.slice(0, GLOB_MAX_RESULTS).map((rel) => toReadableAddress(target, rel, securityContext));
90
135
  const footerParts = [];
91
136
  if (ordered.length > page.length) {
92
137
  footerParts.push(`Showing ${page.length} of ${ordered.length} matches${sortableByMtime ? ", newest first" : ""}. ` +
@@ -98,6 +143,9 @@ export function createGlobTool(fileStore, options = {}) {
98
143
  if (walk.truncated) {
99
144
  footerParts.push(`Scan stopped after ${MAX_SCAN_ENTRIES.toLocaleString()} files; results may be incomplete. Narrow path to search a smaller subtree.`);
100
145
  }
146
+ if (readDenyExcluded > 0) {
147
+ footerParts.push(`${readDenyExcluded} matching path(s) excluded by the read policy.`);
148
+ }
101
149
  const body = page.join("\n");
102
150
  const truncation = truncateHead(body);
103
151
  let outputText = truncation.content;
@@ -109,7 +157,12 @@ export function createGlobTool(fileStore, options = {}) {
109
157
  }
110
158
  return {
111
159
  content: [{ type: "text", text: outputText }],
112
- details: { matchCount: ordered.length, shownCount: page.length, scanTruncated: walk.truncated },
160
+ details: {
161
+ matchCount: ordered.length,
162
+ shownCount: page.length,
163
+ scanTruncated: walk.truncated,
164
+ ...(readDenyExcluded > 0 ? { readDenyExcluded } : {}),
165
+ },
113
166
  };
114
167
  },
115
168
  };
@@ -6,6 +6,8 @@ declare const grepSchema: Type.TObject<{
6
6
  pattern: Type.TString;
7
7
  path: Type.TOptional<Type.TString>;
8
8
  glob: Type.TOptional<Type.TString>;
9
+ literal: Type.TOptional<Type.TBoolean>;
10
+ mode: Type.TOptional<Type.TUnion<[Type.TLiteral<"content">, Type.TLiteral<"files">, Type.TLiteral<"count">]>>;
9
11
  caseSensitive: Type.TOptional<Type.TBoolean>;
10
12
  skip: Type.TOptional<Type.TInteger>;
11
13
  }>;
@@ -1,6 +1,8 @@
1
+ import { basename } from "node:path";
1
2
  import { Type } from "typebox";
2
3
  import { DEFAULT_SECURITY_CONFIG } from "../security/config.js";
3
4
  import { checkPathGuard } from "../security/path-guard-check.js";
5
+ import { partitionByReadGuard, readGuardAllows } from "../security/path-guard-filter.js";
4
6
  import { RecoverableToolError } from "../shared/recoverable-error.js";
5
7
  import { shellEscape } from "../shared/shell-escape.js";
6
8
  import { IGNORED_DIR_SEGMENTS } from "./ignore-dirs.js";
@@ -29,21 +31,77 @@ const SEARCH_TIMEOUT_SECONDS = 30;
29
31
  */
30
32
  const MAX_RAW_RESULT_BYTES = 768 * 1024;
31
33
  const grepSchema = Type.Object({
32
- pattern: Type.String({ description: "Extended regular expression (ERE) to search for in file contents." }),
34
+ pattern: Type.String({
35
+ description: "Text to search for. An extended regular expression (ERE) unless `literal` is set.",
36
+ }),
33
37
  path: Type.Optional(Type.String({ description: "File or directory to search. Defaults to the workspace root." })),
34
38
  glob: Type.Optional(Type.String({
35
- description: 'Filename filter for directory searches, e.g. "*.ts". Matched against the basename.',
39
+ description: 'Filename filter for directory searches, matched against the basename. Supports `*`, `?`, `[abc]`, and `{a,b}` — e.g. "*.{ts,tsx}".',
40
+ })),
41
+ literal: Type.Optional(Type.Boolean({ description: "Treat `pattern` as a literal string, not a regex (like `grep -F`)." })),
42
+ mode: Type.Optional(Type.Union([Type.Literal("content"), Type.Literal("files"), Type.Literal("count")], {
43
+ description: '"content" (default) = matching lines; "files" = matching paths only; "count" = per-file counts. files/count cost far fewer tokens when you only need to locate.',
36
44
  })),
37
45
  caseSensitive: Type.Optional(Type.Boolean({ description: "Case-sensitive match. Defaults to true." })),
38
46
  skip: Type.Optional(Type.Integer({ minimum: 0, description: "File-page offset for paging through many matching files." })),
39
47
  });
40
- /** Convert a simple `*`/`?` glob into an anchored regex matched against a basename. */
48
+ /**
49
+ * Convert a basename glob into an anchored regex. Supports `*`, `?`, character classes `[...]`, and
50
+ * brace alternation `{a,b}` so the JS-side backstop filter is never *stricter* than the `--include`
51
+ * glob pushed to `grep` — a mismatch there produced silent "no results" (fix plan §3.5).
52
+ */
41
53
  function globToRegExp(glob) {
42
- const escaped = glob
43
- .replace(/[.+^${}()|[\]\\]/g, "\\$&")
44
- .replace(/\*/g, ".*")
45
- .replace(/\?/g, ".");
46
- return new RegExp(`^${escaped}$`);
54
+ let out = "";
55
+ for (let i = 0; i < glob.length; i++) {
56
+ const ch = glob[i];
57
+ if (ch === "*") {
58
+ out += ".*";
59
+ }
60
+ else if (ch === "?") {
61
+ out += ".";
62
+ }
63
+ else if (ch === "[") {
64
+ // Copy the class verbatim to the closing `]` (leading `!` -> `^` for negation).
65
+ let j = i + 1;
66
+ let cls = "";
67
+ if (glob[j] === "!" || glob[j] === "^") {
68
+ cls += "^";
69
+ j++;
70
+ }
71
+ while (j < glob.length && glob[j] !== "]") {
72
+ cls += glob[j];
73
+ j++;
74
+ }
75
+ if (j < glob.length) {
76
+ out += `[${cls}]`;
77
+ i = j;
78
+ }
79
+ else {
80
+ out += "\\[";
81
+ }
82
+ }
83
+ else if (ch === "{") {
84
+ const end = glob.indexOf("}", i);
85
+ if (end > i) {
86
+ const alts = glob
87
+ .slice(i + 1, end)
88
+ .split(",")
89
+ .map((alt) => alt.replace(/[.+^${}()|[\]\\]/g, "\\$&"));
90
+ out += `(?:${alts.join("|")})`;
91
+ i = end;
92
+ }
93
+ else {
94
+ out += "\\{";
95
+ }
96
+ }
97
+ else if (/[.+^$()|\\]/.test(ch)) {
98
+ out += `\\${ch}`;
99
+ }
100
+ else {
101
+ out += ch;
102
+ }
103
+ }
104
+ return new RegExp(`^${out}$`);
47
105
  }
48
106
  function truncateLine(text) {
49
107
  return text.length > LINE_MAX_CHARS ? `${text.slice(0, LINE_MAX_CHARS)}…` : text;
@@ -136,14 +194,16 @@ export function createGrepTool(executor, options = {}) {
136
194
  return {
137
195
  name: "grep",
138
196
  label: "grep",
139
- description: "Search file contents with an extended regular expression across a file or directory tree. Output is " +
140
- "grouped by file, capped per file, paginated, and token-bounded — prefer this over `bash grep -rn`, which " +
141
- "floods context. Match lines are marked with `*`, context lines with a space.",
197
+ description: "Search file contents across a file or directory tree — an ERE regex, or a literal string with `literal:true`. " +
198
+ "Output is grouped by file, capped per file, paginated, and token-bounded — prefer this over `bash grep -rn`, " +
199
+ 'which floods context. `mode:"files"` returns just matching paths and `mode:"count"` per-file counts (both ' +
200
+ "much cheaper when you only need to locate). Match lines are marked with `*`, context lines with a space.",
142
201
  parameters: grepSchema,
143
- execute: async (_toolCallId, { pattern, path, glob, caseSensitive, skip, }, signal) => {
202
+ execute: async (_toolCallId, { pattern, path, glob, literal, mode, caseSensitive, skip, }, signal) => {
144
203
  if (!pattern.trim()) {
145
204
  throw new RecoverableToolError("Pattern must not be empty.");
146
205
  }
206
+ const effectiveMode = mode ?? "content";
147
207
  const searchPath = path?.trim() || ".";
148
208
  // Resolved once, then used for both the guard's judgment and the actual `grep` target
149
209
  // (spec 044, D1.1): no separate `cwd` needed on the executor call, so there is no chance of
@@ -153,7 +213,13 @@ export function createGrepTool(executor, options = {}) {
153
213
  tool: "grep",
154
214
  channelId: options.channelId,
155
215
  });
156
- const flags = ["-rnH", "-E", `-B${CONTEXT_BEFORE}`, `-A${CONTEXT_AFTER}`];
216
+ // `-rnH` for content; `-rlH` (paths only) for `files`; `-rcH` (per-file counts) for `count`.
217
+ const flags = effectiveMode === "files"
218
+ ? ["-rlH"]
219
+ : effectiveMode === "count"
220
+ ? ["-rcH"]
221
+ : ["-rnH", `-B${CONTEXT_BEFORE}`, `-A${CONTEXT_AFTER}`];
222
+ flags.push(literal ? "-F" : "-E");
157
223
  if (caseSensitive === false) {
158
224
  flags.push("-i");
159
225
  }
@@ -165,6 +231,22 @@ export function createGrepTool(executor, options = {}) {
165
231
  for (const segment of IGNORED_DIR_SEGMENTS) {
166
232
  flags.push(`--exclude-dir=${segment}`);
167
233
  }
234
+ // Push `readDeny` down into `grep` so a denied subtree is never opened (D5.1). `grep`'s
235
+ // `--exclude`/`--exclude-dir` match a *basename* glob, so a plain (non-glob) deny entry
236
+ // becomes a basename exclude — coarser than the path guard (it also skips a same-named
237
+ // dir elsewhere), but only ever *more* restrictive, and the post-parse read-guard filter
238
+ // below is the actual guarantee that no denied content is returned.
239
+ const denyBasenames = new Set();
240
+ for (const entry of securityConfig.pathGuard.readDeny) {
241
+ if (!/[*?[\]{}]/.test(entry)) {
242
+ const base = basename(entry.replace(/\/+$/, ""));
243
+ if (base && base !== "." && base !== "..")
244
+ denyBasenames.add(base);
245
+ }
246
+ }
247
+ for (const base of denyBasenames) {
248
+ flags.push(`--exclude-dir=${shellEscape(base)}`, `--exclude=${shellEscape(base)}`);
249
+ }
168
250
  if (glob) {
169
251
  // Model-controlled, so it must be shell-escaped like the pattern and path below -- the
170
252
  // executor runs the command via `sh -c`, and an unescaped glob such as `*.ts; rm -rf x`
@@ -184,13 +266,75 @@ export function createGrepTool(executor, options = {}) {
184
266
  // grep exit code 1 = no matches (normal), 0 = matches, >=2 = error.
185
267
  if (result.code >= 2) {
186
268
  const stderr = result.stderr.trim();
187
- throw new RecoverableToolError(`grep failed: ${stderr || `exit code ${result.code}`}. Check the regex (ERE syntax) and that the path exists.`);
269
+ throw new RecoverableToolError(`grep failed: ${stderr || `exit code ${result.code}`}. ${literal
270
+ ? "Check that the path exists."
271
+ : "Check the regex (ERE syntax) and that the path exists, or pass literal:true."}`);
188
272
  }
189
273
  const rawTruncated = result.stdoutTruncated === true;
190
274
  // A truncated capture may end mid-line; drop that dangling partial line rather than feed
191
275
  // it to the parser, which expects each line to be a complete match or context line.
192
276
  const boundedStdout = rawTruncated ? result.stdout.slice(0, result.stdout.lastIndexOf("\n")) : result.stdout;
193
277
  const globRegExp = glob ? globToRegExp(glob) : undefined;
278
+ const keepFile = (file) => {
279
+ const normalized = file.replace(/^\.\//, "");
280
+ if (isIgnoredPath(normalized))
281
+ return false;
282
+ if (globRegExp) {
283
+ const base = normalized.split("/").pop() ?? normalized;
284
+ if (!globRegExp.test(base))
285
+ return false;
286
+ }
287
+ return readGuardAllows(normalized, securityConfig, securityContext);
288
+ };
289
+ const truncationFooter = rawTruncated
290
+ ? `\n\n[Search hit the ${formatSize(MAX_RAW_RESULT_BYTES)} raw result cap; narrow the path or pattern to see the rest.]`
291
+ : "";
292
+ // `mode: "files"` — just the paths that matched, one per line.
293
+ if (effectiveMode === "files") {
294
+ const paths = [
295
+ ...new Set(boundedStdout
296
+ .split("\n")
297
+ .map((l) => l.trim())
298
+ .filter(Boolean)),
299
+ ]
300
+ .filter(keepFile)
301
+ .sort((a, b) => a.localeCompare(b));
302
+ if (paths.length === 0) {
303
+ return {
304
+ content: [{ type: "text", text: `No files contain a match in ${searchPath}.${truncationFooter}` }],
305
+ details: { matchCount: 0, fileCount: 0 },
306
+ };
307
+ }
308
+ return {
309
+ content: [{ type: "text", text: truncateHead(paths.join("\n")).content + truncationFooter }],
310
+ details: { fileCount: paths.length, mode: "files" },
311
+ };
312
+ }
313
+ // `mode: "count"` — `path:N` per file that matched.
314
+ if (effectiveMode === "count") {
315
+ const rows = [];
316
+ for (const line of boundedStdout.split("\n")) {
317
+ const m = line.match(/^(.*):(\d+)$/);
318
+ if (!m)
319
+ continue;
320
+ const count = Number.parseInt(m[2], 10);
321
+ if (count > 0 && keepFile(m[1]))
322
+ rows.push([m[1].replace(/^\.\//, ""), count]);
323
+ }
324
+ rows.sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]));
325
+ if (rows.length === 0) {
326
+ return {
327
+ content: [{ type: "text", text: `No matches in ${searchPath}.${truncationFooter}` }],
328
+ details: { matchCount: 0, fileCount: 0 },
329
+ };
330
+ }
331
+ const total = rows.reduce((sum, [, n]) => sum + n, 0);
332
+ const body = rows.map(([f, n]) => `${n}\t${f}`).join("\n");
333
+ return {
334
+ content: [{ type: "text", text: truncateHead(body).content + truncationFooter }],
335
+ details: { matchCount: total, fileCount: rows.length, mode: "count" },
336
+ };
337
+ }
194
338
  const parsed = parseGrepOutput(boundedStdout);
195
339
  // Filter ignored dirs and (for directory scopes) the optional glob, on the basename.
196
340
  const files = [];
@@ -207,7 +351,32 @@ export function createGrepTool(executor, options = {}) {
207
351
  }
208
352
  files.push([normalized, entries]);
209
353
  }
354
+ // Backstop: a recursive `grep` descends into `readDeny`/sensitive subtrees the per-path
355
+ // guard would refuse. Drop any hit file the read guard denies before it is rendered or
356
+ // counted (the residual risk — grep already read the bytes — is documented in
357
+ // path-guard-filter.ts).
358
+ let readDenyExcluded = 0;
359
+ if (files.length > 0) {
360
+ const { allowed } = partitionByReadGuard(files.map(([file]) => file), securityConfig, securityContext);
361
+ const allowedSet = new Set(allowed);
362
+ const kept = files.filter(([file]) => allowedSet.has(file));
363
+ readDenyExcluded = files.length - kept.length;
364
+ files.length = 0;
365
+ files.push(...kept);
366
+ }
210
367
  if (files.length === 0) {
368
+ if (readDenyExcluded > 0) {
369
+ return {
370
+ content: [
371
+ {
372
+ type: "text",
373
+ text: `All ${readDenyExcluded} matching file(s) in ${searchPath} are excluded by the read policy. ` +
374
+ "Search a path you are allowed to read.",
375
+ },
376
+ ],
377
+ details: { matchCount: 0, fileCount: 0, readDenyExcluded },
378
+ };
379
+ }
211
380
  const scope = glob ? `${searchPath} (glob ${glob})` : searchPath;
212
381
  // D5.3: a result set that hit the raw-line cap but still filtered down to nothing must
213
382
  // not be reported as "no matches" -- that tells the model to try a *broader* search,
@@ -258,6 +427,9 @@ export function createGrepTool(executor, options = {}) {
258
427
  if (rawTruncated) {
259
428
  footerLines.push(`[Search hit the ${formatSize(MAX_RAW_RESULT_BYTES)} raw result cap; there may be matches beyond what's shown above. Narrow the path or pattern to see them.]`);
260
429
  }
430
+ if (readDenyExcluded > 0) {
431
+ footerLines.push(`[${readDenyExcluded} matching file(s) were excluded by the read policy and are not shown.]`);
432
+ }
261
433
  const body = blocks.join("\n\n");
262
434
  const footer = footerLines.length > 0 ? `\n\n${footerLines.join("\n")}` : "";
263
435
  const truncation = truncateHead(body);
@@ -271,6 +443,7 @@ export function createGrepTool(executor, options = {}) {
271
443
  matchCount: shownMatchCount,
272
444
  fileCount: files.length,
273
445
  shownFileCount: page.length,
446
+ ...(readDenyExcluded > 0 ? { readDenyExcluded } : {}),
274
447
  },
275
448
  };
276
449
  },
package/dist/tools/job.js CHANGED
@@ -7,9 +7,12 @@ const jobSchema = Type.Object({
7
7
  description: '"list" a snapshot of background jobs, "poll" to wait (briefly) for one to finish, or "cancel" jobs by id.',
8
8
  }),
9
9
  ids: Type.Optional(Type.Array(Type.String(), {
10
- description: "Job ids for poll/cancel. For poll, omit to watch all running jobs.",
10
+ description: "Job ids for poll/cancel. For poll, omit to watch every job running when the call starts " +
11
+ "(a job started later is not folded into that same poll).",
11
12
  })),
12
13
  });
14
+ /** Total bytes of job output `op=poll` inlines across all finished jobs in one call. */
15
+ const COMPLETED_DETAIL_TOTAL_BUDGET = 96 * 1024;
13
16
  function formatJobLine(job) {
14
17
  const exit = job.exitCode !== undefined ? `, exit ${job.exitCode}` : "";
15
18
  return `- [${job.id}] ${job.label} — ${job.status} (${formatDuration(job.durationMs)}${exit})`;
@@ -18,12 +21,21 @@ export function createJobTool(options) {
18
21
  const { jobManager } = options;
19
22
  async function completedDetail(jobs) {
20
23
  const sections = [];
24
+ let spent = 0;
21
25
  for (const job of jobs) {
26
+ const header = `### [${job.id}] ${job.label} — ${job.status}${job.exitCode !== undefined ? `, exit ${job.exitCode}` : ""}`;
22
27
  const output = await jobManager.readOutput(job.id);
28
+ // Total budget across all finished jobs in one poll: 5 jobs × the 50KB per-job tail would
29
+ // otherwise be 250KB of context. Once spent, later jobs get a header + a pointer only.
30
+ if (spent >= COMPLETED_DETAIL_TOTAL_BUDGET) {
31
+ sections.push(`${header}\n(output omitted to stay within budget — run \`job op=poll ids=["${job.id}"]\` for it)${output ? `\nFull output: ${output.spillFile}` : ""}`);
32
+ continue;
33
+ }
23
34
  const tail = output ? truncateTail(output.text).content : "";
24
35
  const body = tail.trim() ? tail : "(no output)";
25
36
  const path = output ? `\nFull output: ${output.spillFile}` : "";
26
- sections.push(`### [${job.id}] ${job.label} — ${job.status}${job.exitCode !== undefined ? `, exit ${job.exitCode}` : ""}\n${body}${path}`);
37
+ spent += Buffer.byteLength(body, "utf-8");
38
+ sections.push(`${header}\n${body}${path}`);
27
39
  }
28
40
  return sections;
29
41
  }
@@ -32,7 +44,7 @@ export function createJobTool(options) {
32
44
  label: "job",
33
45
  description: "Inspect and control background bash jobs (started with bash async:true). op=list shows a snapshot; " +
34
46
  "op=poll waits briefly for a running job to finish and returns its output; op=cancel stops jobs by id. " +
35
- "A finished job wakes this channel by itself, so never schedule a check-in for one — end the turn instead.",
47
+ "Completion wakes this channel; finish independent work, then end the turn when only waiting remains.",
36
48
  parameters: jobSchema,
37
49
  execute: async (_toolCallId, { op, ids }, signal) => {
38
50
  if (op === "cancel") {
@@ -75,7 +87,7 @@ export function createJobTool(options) {
75
87
  }
76
88
  if (running.length > 0) {
77
89
  parts.push(`## Still running (${running.length})`, ...running.map(formatJobLine));
78
- parts.push("Poll again to keep waiting, or just end your turn — you are woken when the job finishes.");
90
+ parts.push("Finish independent work, then end the turn; completion wakes this channel. Do not loop on poll.");
79
91
  }
80
92
  return {
81
93
  content: [{ type: "text", text: parts.join("\n\n") }],
@@ -3,6 +3,7 @@ import { join } from "node:path";
3
3
  import { Type } from "typebox";
4
4
  import * as log from "../log.js";
5
5
  import { getDefaultChannelMemoryQueue } from "../memory/channel-maintenance-queue.js";
6
+ import { readJournalForSearch } from "../memory/journal.js";
6
7
  import { appendMemoryReviewLog } from "../memory/review-log.js";
7
8
  import { findNearDuplicateEntries, searchMemory } from "../memory/search.js";
8
9
  import { containsSecret } from "../memory/secret-redaction.js";
@@ -32,7 +33,7 @@ const memorySaveSchema = Type.Object({
32
33
  });
33
34
  const memorySearchSchema = Type.Object({
34
35
  query: Type.String({
35
- description: "What to look for across this channel's memory, journal, and workspace MEMORY.md.",
36
+ description: "What to look for across this channel's memory, recent journal files, and workspace MEMORY.md.",
36
37
  }),
37
38
  });
38
39
  const memoryForgetSchema = Type.Object({
@@ -64,73 +65,111 @@ function buildMemoryClosures(options) {
64
65
  if (args.name && !isValidMemoryName(args.name)) {
65
66
  throw new RecoverableToolError(`"${args.name}" is not a valid memory name. Use lowercase letters, digits, and hyphens only (e.g. deploy-window-thursday).`);
66
67
  }
67
- const entries = await listMemoryEntries(options.channelDir);
68
- if (!args.replaces) {
69
- const similar = findNearDuplicateEntries(content, entries);
70
- if (similar.length > 0) {
71
- throw new RecoverableToolError(`Nothing was saved yet. This channel already stores ${similar.length} similar entr${similar.length === 1 ? "y" : "ies"}:\n` +
72
- similar.map((entry) => `- ${entry.name}: ${entry.description}`).join("\n") +
73
- '\nRe-issue the save with "replaces" set to the name this replaces, or to "none" if both facts are true at once.');
74
- }
75
- }
76
68
  const replaces = args.replaces && args.replaces !== "none" ? args.replaces : undefined;
77
- const result = await queue.run(options.channelId, () => applyMemoryOps(options.channelDir, [
78
- replaces
79
- ? {
80
- op: "update",
81
- name: replaces,
82
- description: content,
83
- type: args.type,
84
- details: args.details,
85
- expires: null,
69
+ // The near-duplicate judgment ("read existing facts → decide → write") has to run inside the
70
+ // same per-channel critical section as the write, or two concurrent saves of the same fact
71
+ // each see "no duplicate" and both add it. A `null` return means "blocked by near-duplicates,
72
+ // nothing written".
73
+ let similar = [];
74
+ const result = await queue.run(options.channelId, async () => {
75
+ // `replaces: "none"` is an explicit "both facts are true, keep both" waiver, so it skips
76
+ // the near-duplicate gate just like naming a real target does.
77
+ if (!args.replaces) {
78
+ const existing = await listMemoryEntries(options.channelDir);
79
+ const near = findNearDuplicateEntries(content, existing);
80
+ if (near.length > 0) {
81
+ similar = near;
82
+ return null;
86
83
  }
87
- : {
88
- op: "add",
89
- description: content,
90
- source: "user",
91
- name: args.name,
92
- type: args.type ?? "project",
93
- details: args.details,
94
- },
95
- ]));
84
+ }
85
+ return applyMemoryOps(options.channelDir, [
86
+ replaces
87
+ ? {
88
+ op: "update",
89
+ name: replaces,
90
+ description: content,
91
+ type: args.type,
92
+ details: args.details,
93
+ expires: null,
94
+ }
95
+ : {
96
+ op: "add",
97
+ description: content,
98
+ source: "user",
99
+ name: args.name,
100
+ type: args.type ?? "project",
101
+ details: args.details,
102
+ },
103
+ ]);
104
+ });
105
+ if (result === null) {
106
+ throw new RecoverableToolError(`Nothing was saved yet. This channel already stores ${similar.length} similar entr${similar.length === 1 ? "y" : "ies"}:\n` +
107
+ similar.map((entry) => `- ${entry.name}: ${entry.description}`).join("\n") +
108
+ '\nRe-issue the save with "replaces" set to the name this replaces, or to "none" if both facts are true at once.');
109
+ }
96
110
  if (replaces && result.updated.length === 0 && result.missingTarget > 0) {
97
111
  throw new RecoverableToolError(`No memory named "${replaces}" exists in this channel. Check the name, or omit "replaces" to save a new entry.`);
98
112
  }
99
- await appendMemoryReviewLog(options.channelDir, {
113
+ // Report what actually landed on disk — never a name for an entry that was not written.
114
+ // The old code read `replaces ?? result.added[0]` unconditionally, so a skipped add
115
+ // rendered "Saved ... as `undefined`." and told the user a lie the model could not see.
116
+ if (replaces) {
117
+ await logMemorySave(options, replaces, "update");
118
+ return textResult(`Replaced channel memory \`${replaces}\`.`, { saved: true, name: replaces });
119
+ }
120
+ const addedName = result.added[0];
121
+ if (addedName) {
122
+ await logMemorySave(options, addedName, "add");
123
+ return textResult(`Saved to channel memory as \`${addedName}\`.`, { saved: true, name: addedName });
124
+ }
125
+ if (result.skippedSecret > 0) {
126
+ return textResult("Not saved: the content still reads as a credential or secret after the first check. Store the secret itself in an approved secret manager and save only a pointer to it here.", { saved: false, blockedReason: "secret" });
127
+ }
128
+ if (result.skippedTombstone > 0) {
129
+ return textResult(`Not saved: "${content}" was explicitly forgotten in this channel and is still tombstoned. ` +
130
+ "Confirm with the user that they want it back, then re-save (an explicit user save is allowed through), or reword it so it is not byte-for-byte the forgotten fact.", { saved: false, blockedReason: "tombstone" });
131
+ }
132
+ return textResult("Not saved, and the store reported no specific reason (it may already be stored under another entry). " +
133
+ "Run memory_search for this fact before trying again.", { saved: false, blockedReason: "unknown" });
134
+ }
135
+ async function logMemorySave(opts, name, op) {
136
+ await appendMemoryReviewLog(opts.channelDir, {
100
137
  timestamp: new Date().toISOString(),
101
- channelId: options.channelId,
138
+ channelId: opts.channelId,
102
139
  reason: "memory-save",
103
- actions: [{ op: replaces ? "update" : "add", name: replaces ?? result.added[0] }],
140
+ actions: [{ op, name }],
104
141
  }).catch(() => { });
105
- const savedName = replaces ?? result.added[0];
106
- return textResult(replaces ? `Replaced channel memory \`${savedName}\`.` : `Saved to channel memory as \`${savedName}\`.`, { saved: result.added.length > 0 || result.updated.length > 0, name: savedName });
107
142
  }
108
143
  async function search({ query }) {
109
144
  const trimmed = query.trim();
110
145
  if (!trimmed) {
111
146
  throw new RecoverableToolError("memory_search requires a non-empty query.");
112
147
  }
113
- const [entries, workspaceMemory] = await Promise.all([
148
+ const [entries, workspaceMemory, journal] = await Promise.all([
114
149
  listMemoryEntries(options.channelDir),
115
150
  readWorkspaceMemory(options.workspaceDir),
151
+ readJournalForSearch(options.channelDir),
116
152
  ]);
117
- const hits = searchMemory({ query: trimmed, entries, workspaceMemory });
153
+ const hits = searchMemory({ query: trimmed, entries, workspaceMemory, journal: journal.days });
154
+ const scopeHint = journal.omittedDays > 0 || journal.truncatedDates.length > 0
155
+ ? `\nJournal search omitted ${journal.omittedDays} older day files and older text in ${journal.truncatedDates.length} large files. Use grep in ${join(options.channelDir, "journal")} or read a dated file to search the omitted history.`
156
+ : "";
118
157
  if (hits.length === 0) {
119
- return textResult(`No stored memory matched "${trimmed}". Try a broader query, or the fact may not be saved yet.`, {
158
+ return textResult(`No stored memory matched "${trimmed}". Try a broader query; no match does not prove the fact was never recorded.${scopeHint}`, {
120
159
  resultCount: 0,
121
160
  });
122
161
  }
123
162
  const rendered = hits
124
163
  .map((hit) => {
125
164
  const where = hit.kind === "memory"
126
- ? `memory/${hit.label}`
165
+ ? `memory/${hit.label}.md`
127
166
  : hit.kind === "journal"
128
- ? `journal ${hit.date}`
167
+ ? `journal/${hit.date}.md`
129
168
  : `workspace MEMORY.md › ${hit.label}`;
130
169
  return `- [${where}] ${hit.line}`;
131
170
  })
132
171
  .join("\n");
133
- return textResult(`Found ${hits.length} match${hits.length === 1 ? "" : "es"}:\n\n${rendered}`, {
172
+ return textResult(`Found ${hits.length} match${hits.length === 1 ? "" : "es"}:\n\n${rendered}${scopeHint}\nResults are excerpts. Read a cited file for full context; narrow the query for more specific matches.`, {
134
173
  resultCount: hits.length,
135
174
  });
136
175
  }
@@ -164,7 +203,7 @@ export function createMemorySaveTool(options) {
164
203
  name: "memory_save",
165
204
  label: "memory_save",
166
205
  description: "Save a durable fact into this channel's memory when the user asks you to remember it. Not for transient task state — " +
167
- "put in-progress work in the journal or a task instead.",
206
+ "keep in-progress work in a task (task_log) instead; the journal is written only by the background reflect pass.",
168
207
  parameters: memorySaveSchema,
169
208
  execute: async (_toolCallId, args) => save(args),
170
209
  };
@@ -174,7 +213,7 @@ export function createMemorySearchTool(options) {
174
213
  return {
175
214
  name: "memory_search",
176
215
  label: "memory_search",
177
- description: "Search this channel's stored memory, journal, and the workspace MEMORY.md on demand. The memory index is only " +
216
+ description: "Search this channel's stored memory, recent journal, and the workspace MEMORY.md on demand. The memory index is only " +
178
217
  "injected at the start of a session, so use this when you suspect something was recorded since.",
179
218
  parameters: memorySearchSchema,
180
219
  execute: async (_toolCallId, args) => search(args),