@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
@@ -77,6 +77,9 @@ export interface JobManagerOptions {
77
77
  sweepIntervalMs?: number;
78
78
  /** File-content port for reading a job's spill file (spec 044, D8). Defaults to `createFileStore()`. */
79
79
  fileStore?: FileStore;
80
+ /** Directory the full-output spill (and its `.exit`/`.ready`/`.meta` siblings) is written to.
81
+ * Defaults to the OS temp dir; the runtime passes `<channelDir>/logs` so the model can read it. */
82
+ spillDir?: string;
80
83
  }
81
84
  /** Cap on concurrently running jobs per channel, so a runaway model can't spawn unbounded processes. */
82
85
  export declare const MAX_RUNNING_JOBS = 5;
@@ -248,6 +251,12 @@ export declare class ChannelJobManager {
248
251
  interface JobRuntimeConfig {
249
252
  /** Root of the per-channel record directories (`<jobsStateDir>/<channelId>/`). */
250
253
  jobsStateDir?: string;
254
+ /**
255
+ * The agent workspace root. A job's full-output spill goes to `<workspaceDir>/<channelId>/logs/`
256
+ * so the "Full output: …" pointer resolves under both path-guard boundaries (fix plan §2.2). The
257
+ * path is stable across restarts, so a re-adopted job's spill is still found.
258
+ */
259
+ workspaceDir?: string;
251
260
  dispatch?: (event: ChannelEvent) => boolean | Promise<boolean>;
252
261
  /** Sweep cadence override for the lazily-built channel managers (tests). */
253
262
  sweepIntervalMs?: number;
@@ -2,6 +2,7 @@ import { randomBytes } from "node:crypto";
2
2
  import { chmod, mkdir, readdir, readFile, unlink } from "node:fs/promises";
3
3
  import { tmpdir } from "node:os";
4
4
  import { join } from "node:path";
5
+ import { getChannelDir } from "../channel/channel-paths.js";
5
6
  import { createFileStore } from "../file-store.js";
6
7
  import * as log from "../log.js";
7
8
  import { writeFileAtomically } from "../shared/atomic-file.js";
@@ -108,8 +109,8 @@ export const FINISHED_JOB_RETENTION_MS = 24 * 60 * 60_000;
108
109
  const WAKE_OUTPUT_TAIL_BYTES = 2_000;
109
110
  /** Upper bound on how much of a spill file's tail `readOutput` reads (spec 044, D8). */
110
111
  const JOB_OUTPUT_READ_MAX_BYTES = 512 * 1024;
111
- function jobSpillPath(id) {
112
- return join(tmpdir(), `pipiclaw-job-${id}.log`);
112
+ function jobSpillPath(id, spillDir) {
113
+ return join(spillDir ?? tmpdir(), `pipiclaw-job-${id}.log`);
113
114
  }
114
115
  function isTerminal(status) {
115
116
  return status !== "running";
@@ -321,7 +322,10 @@ export class ChannelJobManager {
321
322
  throw new Error(`Too many background jobs already running (>= ${MAX_RUNNING_JOBS}). Poll or cancel some with the job tool first.`);
322
323
  }
323
324
  const id = randomBytes(6).toString("hex");
324
- const spillFile = jobSpillPath(id);
325
+ if (this.options.spillDir) {
326
+ await mkdir(this.options.spillDir, { recursive: true }).catch(() => undefined);
327
+ }
328
+ const spillFile = jobSpillPath(id, this.options.spillDir);
325
329
  const art = jobArtifacts(spillFile);
326
330
  const launch = buildLaunchScript(command, art);
327
331
  let result;
@@ -862,13 +866,20 @@ export class ChannelJobManager {
862
866
  */
863
867
  async poll(ids, signal) {
864
868
  const deadline = Date.now() + POLL_WAIT_MS;
865
- const watchIds = () => ids && ids.length > 0
869
+ // Freeze the observation set once, up front. `refresh(..., announce=false)` marks a job's
870
+ // completion wake as consumed (the result is being returned inline), so if we re-derived the
871
+ // watch list each iteration a job that finished mid-poll would drop out of "running", never
872
+ // make it into the returned snapshot, and never wake the channel either — the closure lost
873
+ // entirely. With `ids` omitted this is a snapshot of the jobs running *now*; a job started
874
+ // after poll begins is not folded into this call (poll is snapshot semantics — see the tool
875
+ // description).
876
+ const watchedIds = ids && ids.length > 0
866
877
  ? ids.filter((id) => this.jobs.has(id))
867
878
  : Array.from(this.jobs.values())
868
879
  .filter((job) => job.status === "running")
869
880
  .map((job) => job.id);
870
881
  while (true) {
871
- for (const id of watchIds()) {
882
+ for (const id of watchedIds) {
872
883
  const record = this.jobs.get(id);
873
884
  if (record) {
874
885
  // poll returns the finished job's output to the model inline, so it must not
@@ -876,7 +887,7 @@ export class ChannelJobManager {
876
887
  await this.refresh(record, signal, false);
877
888
  }
878
889
  }
879
- const watched = watchIds()
890
+ const watched = watchedIds
880
891
  .map((id) => this.jobs.get(id))
881
892
  .filter((record) => record !== undefined);
882
893
  const anyDone = watched.some((record) => record.status !== "running");
@@ -980,6 +991,9 @@ export function getChannelJobManager(channelId, executor) {
980
991
  if (!manager) {
981
992
  manager = new ChannelJobManager(channelId, executor, {
982
993
  ...(runtimeConfig.jobsStateDir ? { stateDir: join(runtimeConfig.jobsStateDir, channelId) } : {}),
994
+ ...(runtimeConfig.workspaceDir
995
+ ? { spillDir: join(getChannelDir(runtimeConfig.workspaceDir, channelId), "logs") }
996
+ : {}),
983
997
  ...(runtimeConfig.dispatch ? { dispatch: runtimeConfig.dispatch } : {}),
984
998
  ...(runtimeConfig.sweepIntervalMs ? { sweepIntervalMs: runtimeConfig.sweepIntervalMs } : {}),
985
999
  });
@@ -13,7 +13,7 @@
13
13
  */
14
14
  import type { PromptBuildContext, PromptBuildResult, PromptSectionDefinition } from "./types.js";
15
15
  /** Bumped whenever the runtime-authored prompt text changes in a way worth attributing in telemetry. */
16
- export declare const RUNTIME_PROMPT_VERSION = 3;
16
+ export declare const RUNTIME_PROMPT_VERSION = 4;
17
17
  /** Over this, the runtime-authored prompt still works but is worth a warning (spec 026 §5.2). */
18
18
  export declare const RUNTIME_PROMPT_TARGET_UNITS = 700;
19
19
  /** Over this it is a development error: runtime text has drifted well past its budget. */
@@ -16,7 +16,7 @@ import { countPromptUnits } from "../../shared/prompt-units.js";
16
16
  import { estimateTokens } from "../../shared/token-estimate.js";
17
17
  import { FINAL_BOUNDARY_SECTION, MAIN_PROMPT_SECTIONS } from "./sections.js";
18
18
  /** Bumped whenever the runtime-authored prompt text changes in a way worth attributing in telemetry. */
19
- export const RUNTIME_PROMPT_VERSION = 3;
19
+ export const RUNTIME_PROMPT_VERSION = 4;
20
20
  /**
21
21
  * The sections Pipiclaw authors and must keep tight (spec 026 §10.3): identity,
22
22
  * execution, invariants, persistent-task rules, the runtime-guide catalog and the
@@ -59,8 +59,8 @@ export const EXECUTION_SECTION = {
59
59
  "## Working Contract",
60
60
  "- For actionable requests, continue until the requested outcome exists or you are genuinely blocked. Inspect before changing and verify material results.",
61
61
  "- State what remains unverified. Tool definitions are the source of truth for available capabilities and parameters.",
62
- "- Background jobs and delegations wake this channel when they finish: end the turn instead of polling, scheduling a check-in, or looping to wait.",
63
- "- Before non-trivial use of a Pipiclaw mechanism or workspace procedure, read the matching runtime guide or skill.",
62
+ "- Jobs and delegations wake this channel on completion. Finish independent work and dispatches; when only waiting remains, end the turn without polling or check-in events.",
63
+ "- Before non-trivial use of a runtime mechanism or workspace procedure, read its guide or skill; reuse it while it remains in context.",
64
64
  ].join("\n"),
65
65
  };
66
66
  export const INVARIANTS_SECTION = {
@@ -95,7 +95,7 @@ export const TASK_CORE_SECTION = {
95
95
  overflow: "error",
96
96
  render: () => [
97
97
  "## Persistent Work",
98
- "Use a task only when work must survive this turn. Follow the exact task file and runtime guide named by a task wake; use `task_update`/`task_close` for lifecycle state and never expand the task's stated scope or bypass its verification gate.",
98
+ "Use a task only when work must survive this turn. Chat creates or manages tasks; the runtime drives them in task sessions. Follow the task's contract and runtime guide without expanding its scope or bypassing verification.",
99
99
  ].join("\n"),
100
100
  };
101
101
  export const PLAYBOOKS_SECTION = {
@@ -1,3 +1,5 @@
1
+ /** True when the executor found a real `bash`; `bash.ts` uses this to keep its description honest. */
2
+ export declare const EXECUTOR_SHELL_IS_BASH: boolean;
1
3
  /**
2
4
  * Create an executor that runs commands on the host machine.
3
5
  */
@@ -14,7 +16,9 @@ export declare class CommandTerminatedError extends Error {
14
16
  readonly stderr: string;
15
17
  readonly reason: "timeout" | "aborted";
16
18
  readonly timeoutSeconds?: number;
17
- constructor(reason: "timeout" | "aborted", stdout: string, stderr: string, timeoutSeconds?: number);
19
+ /** True when the in-memory `stdout`/`stderr` here is only the head of a larger stream (D6.2). */
20
+ readonly captureTruncated: boolean;
21
+ constructor(reason: "timeout" | "aborted", stdout: string, stderr: string, timeoutSeconds?: number, captureTruncated?: boolean);
18
22
  }
19
23
  export interface Executor {
20
24
  /**
package/dist/executor.js CHANGED
@@ -1,5 +1,33 @@
1
- import { createWriteStream } from "node:fs";
1
+ import { createWriteStream, existsSync } from "node:fs";
2
+ import { join as joinPath, delimiter as PATH_DELIMITER } from "node:path";
2
3
  import { spawn } from "child_process";
4
+ import { logWarning } from "./log.js";
5
+ /**
6
+ * The `bash` tool's schema says "Bash command" and models write bash-only syntax (`[[ ]]`, arrays,
7
+ * `set -o pipefail`, process substitution). `/bin/sh` is `dash` on many hosts, so those fail with a
8
+ * confusing error on the model's first try. Resolve a real `bash` once at load and run commands
9
+ * through it; only fall back to `/bin/sh` when no `bash` exists, and say so. POSIX `shellEscape`
10
+ * quoting is still correct for bash, and the command guard inspects the command text either way.
11
+ */
12
+ function resolveShell() {
13
+ const candidates = ["/bin/bash", "/usr/bin/bash", "/usr/local/bin/bash"];
14
+ for (const dir of (process.env.PATH ?? "").split(PATH_DELIMITER)) {
15
+ if (dir)
16
+ candidates.push(joinPath(dir, "bash"));
17
+ }
18
+ for (const candidate of candidates) {
19
+ if (existsSync(candidate)) {
20
+ return { path: candidate, isBash: true };
21
+ }
22
+ }
23
+ return { path: "/bin/sh", isBash: false };
24
+ }
25
+ const RESOLVED_SHELL = resolveShell();
26
+ if (!RESOLVED_SHELL.isBash) {
27
+ logWarning("executor: no `bash` binary found on this host; the bash tool is running commands via POSIX /bin/sh");
28
+ }
29
+ /** True when the executor found a real `bash`; `bash.ts` uses this to keep its description honest. */
30
+ export const EXECUTOR_SHELL_IS_BASH = RESOLVED_SHELL.isBash;
3
31
  /**
4
32
  * Default in-memory capture cap for a command's stdout/stderr, in bytes (spec 044, D6.1/D6.2).
5
33
  * This is `Executor`'s own bound for *command output* -- file content never goes through it (see
@@ -21,13 +49,14 @@ export function createExecutor() {
21
49
  * tail instead of losing the partial output outright.
22
50
  */
23
51
  export class CommandTerminatedError extends Error {
24
- constructor(reason, stdout, stderr, timeoutSeconds) {
52
+ constructor(reason, stdout, stderr, timeoutSeconds, captureTruncated = false) {
25
53
  super(reason === "timeout" ? `Command timed out after ${timeoutSeconds} seconds` : "Command aborted");
26
54
  this.name = "CommandTerminatedError";
27
55
  this.reason = reason;
28
56
  this.stdout = stdout;
29
57
  this.stderr = stderr;
30
58
  this.timeoutSeconds = timeoutSeconds;
59
+ this.captureTruncated = captureTruncated;
31
60
  }
32
61
  }
33
62
  /** Accumulates raw chunks up to a byte cap without re-copying already-capped data on every event. */
@@ -70,7 +99,7 @@ class HostExecutor {
70
99
  return new Promise((resolve, reject) => {
71
100
  const child = (() => {
72
101
  try {
73
- return spawn("sh", ["-c", command], {
102
+ return spawn(RESOLVED_SHELL.path, ["-c", command], {
74
103
  detached: true,
75
104
  stdio: ["pipe", "pipe", "pipe"],
76
105
  ...(options?.cwd ? { cwd: options.cwd } : {}),
@@ -179,12 +208,13 @@ class HostExecutor {
179
208
  child.on("close", (code) => {
180
209
  const stdout = stdoutAcc.toText();
181
210
  const stderr = stderrAcc.toText();
211
+ const captureTruncated = stdoutAcc.truncated || stderrAcc.truncated;
182
212
  if (options?.signal?.aborted) {
183
- rejectOnce(new CommandTerminatedError("aborted", stdout, stderr));
213
+ rejectOnce(new CommandTerminatedError("aborted", stdout, stderr, undefined, captureTruncated));
184
214
  return;
185
215
  }
186
216
  if (timedOut) {
187
- rejectOnce(new CommandTerminatedError("timeout", stdout, stderr, options?.timeout));
217
+ rejectOnce(new CommandTerminatedError("timeout", stdout, stderr, options?.timeout, captureTruncated));
188
218
  return;
189
219
  }
190
220
  resolveOnce({
@@ -81,9 +81,12 @@ export interface FileStore {
81
81
  writeAtomic(path: string, data: Buffer | string, opts?: WriteAtomicOptions): Promise<void>;
82
82
  /** Streaming atomic replace: `produce` writes to a temp file; on success it is renamed over `path`. */
83
83
  replaceViaTemp(path: string, produce: (out: Writable) => Promise<void>, opts?: ReplaceViaTempOptions): Promise<void>;
84
- /** Depth-bounded directory listing, replacing the `find -maxdepth` shell-out. */
84
+ /** Depth-bounded directory listing, replacing the `find -maxdepth` shell-out. `maxEntries` caps
85
+ * the total collected so a directory with tens of thousands of children cannot be materialized
86
+ * whole before the caller truncates it. */
85
87
  listDirectory(path: string, opts: {
86
88
  maxDepth: number;
89
+ maxEntries?: number;
87
90
  }): Promise<DirectoryEntry[]>;
88
91
  /**
89
92
  * Unbounded-depth file discovery for `glob`, replacing the `find` shell-out. Directories are
@@ -131,9 +131,14 @@ class HostFileStore {
131
131
  }
132
132
  async listDirectory(path, opts) {
133
133
  const results = [];
134
+ const cap = opts.maxEntries ?? Number.POSITIVE_INFINITY;
134
135
  const walk = async (currentDir, relPrefix, depth) => {
136
+ if (results.length >= cap)
137
+ return;
135
138
  const entries = await readdir(currentDir, { withFileTypes: true });
136
139
  for (const entry of entries) {
140
+ if (results.length >= cap)
141
+ return;
137
142
  const relativePath = relPrefix ? `${relPrefix}/${entry.name}` : entry.name;
138
143
  const isDirectory = entry.isDirectory();
139
144
  results.push({ name: entry.name, relativePath, isDirectory });
@@ -7,6 +7,19 @@ export declare function getJournalDir(channelDir: string): string;
7
7
  export declare function getJournalPath(channelDir: string, date: string): string;
8
8
  export declare function readJournalDay(channelDir: string, date?: string): Promise<string>;
9
9
  export declare function listJournalDates(channelDir: string): Promise<string[]>;
10
+ /** Search stays bounded even after years of journals, or one unusually busy day. */
11
+ export declare const JOURNAL_SEARCH_MAX_DAYS = 30;
12
+ export declare const JOURNAL_SEARCH_DAY_BYTES: number;
13
+ export interface JournalSearchWindow {
14
+ days: Array<{
15
+ date: string;
16
+ content: string;
17
+ }>;
18
+ omittedDays: number;
19
+ truncatedDates: string[];
20
+ }
21
+ /** Newest day files first; retain only whole lines when a day's older bytes are omitted. */
22
+ export declare function readJournalForSearch(channelDir: string): Promise<JournalSearchWindow>;
10
23
  export interface JournalAppendResult {
11
24
  appended: number;
12
25
  skippedDuplicate: number;
@@ -1,7 +1,7 @@
1
- import { mkdir, readdir } from "node:fs/promises";
1
+ import { mkdir, open, readdir } from "node:fs/promises";
2
2
  import { join } from "node:path";
3
3
  import { writeFileAtomically } from "../shared/atomic-file.js";
4
- import { readOptionalTextFile } from "../shared/fs-utils.js";
4
+ import { isNodeError, readOptionalTextFile } from "../shared/fs-utils.js";
5
5
  import { localDayKey } from "../shared/local-time.js";
6
6
  /**
7
7
  * Spec 050, D5: `journal/YYYY-MM-DD.md`, append-only, one file per local day. Replaces
@@ -25,10 +25,53 @@ export async function listJournalDates(channelDir) {
25
25
  .map((f) => f.slice(0, -3))
26
26
  .sort();
27
27
  }
28
- catch {
29
- return [];
28
+ catch (error) {
29
+ if (isNodeError(error) && error.code === "ENOENT")
30
+ return [];
31
+ throw error;
30
32
  }
31
33
  }
34
+ /** Search stays bounded even after years of journals, or one unusually busy day. */
35
+ export const JOURNAL_SEARCH_MAX_DAYS = 30;
36
+ export const JOURNAL_SEARCH_DAY_BYTES = 64 * 1024;
37
+ /** Newest day files first; retain only whole lines when a day's older bytes are omitted. */
38
+ export async function readJournalForSearch(channelDir) {
39
+ const dates = (await listJournalDates(channelDir)).reverse();
40
+ const window = {
41
+ days: [],
42
+ omittedDays: Math.max(0, dates.length - JOURNAL_SEARCH_MAX_DAYS),
43
+ truncatedDates: [],
44
+ };
45
+ for (const date of dates.slice(0, JOURNAL_SEARCH_MAX_DAYS)) {
46
+ try {
47
+ const file = await open(getJournalPath(channelDir, date), "r");
48
+ try {
49
+ const stat = await file.stat();
50
+ if (!stat.isFile())
51
+ continue;
52
+ const start = Math.max(0, stat.size - JOURNAL_SEARCH_DAY_BYTES);
53
+ const buffer = Buffer.alloc(Math.min(stat.size, JOURNAL_SEARCH_DAY_BYTES));
54
+ const { bytesRead } = await file.read(buffer, 0, buffer.length, start);
55
+ let content = buffer.subarray(0, bytesRead).toString("utf-8");
56
+ if (start > 0) {
57
+ window.truncatedDates.push(date);
58
+ const newline = content.indexOf("\n");
59
+ content = newline < 0 ? "" : content.slice(newline + 1);
60
+ }
61
+ window.days.push({ date, content });
62
+ }
63
+ finally {
64
+ await file.close();
65
+ }
66
+ }
67
+ catch (error) {
68
+ // A day can disappear between listing and opening; real IO failures must stay visible.
69
+ if (!isNodeError(error) || error.code !== "ENOENT")
70
+ throw error;
71
+ }
72
+ }
73
+ return window;
74
+ }
32
75
  function normalizeLine(line) {
33
76
  return line
34
77
  .replace(/^[-*]\s*/, "")
@@ -252,11 +252,18 @@ function scoreText(queryTokens, text) {
252
252
  score += 0.5;
253
253
  }
254
254
  }
255
- const firstLine = text
255
+ // Prefer the line that actually contains a query token (the hit may be in the body, not the
256
+ // description); fall back to the first non-empty line only when nothing matches on a line.
257
+ const nonEmptyLines = text
256
258
  .split("\n")
257
- .find((l) => l.trim().length > 0)
258
- ?.trim() ?? text.trim();
259
- return { score, line: firstLine.length > 200 ? `${firstLine.slice(0, 197)}…` : firstLine };
259
+ .map((l) => l.trim())
260
+ .filter((l) => l.length > 0);
261
+ const matchingLine = nonEmptyLines.find((l) => {
262
+ const low = l.toLowerCase();
263
+ return [...queryTokens].some((token) => token.length >= 2 && low.includes(token));
264
+ });
265
+ const chosen = matchingLine ?? nonEmptyLines[0] ?? text.trim();
266
+ return { score, line: chosen.length > 200 ? `${chosen.slice(0, 197)}…` : chosen };
260
267
  }
261
268
  export function searchMemory(input) {
262
269
  const queryTokens = new Set(tokenizeRecallText(input.query));
@@ -276,9 +283,9 @@ export function searchMemory(input) {
276
283
  if (!line || line.startsWith("#")) {
277
284
  continue;
278
285
  }
279
- const { score } = scoreText(queryTokens, line);
286
+ const { score, line: snippet } = scoreText(queryTokens, line);
280
287
  if (score > 0) {
281
- hits.push({ kind: "journal", label: day.date, date: day.date, line, score });
288
+ hits.push({ kind: "journal", label: day.date, date: day.date, line: snippet, score });
282
289
  }
283
290
  }
284
291
  }
@@ -6,9 +6,20 @@ export interface SessionSearchDocument {
6
6
  path: string;
7
7
  timestamp?: string;
8
8
  role: SessionSearchRole;
9
+ /** The full scannable message text (up to {@link SESSION_SCAN_MAX_CHARS}) — matching runs on
10
+ * this, display windows are cut from it at query time (fix plan §2.5). */
9
11
  text: string;
12
+ /** True when even the scan text was clipped: a keyword past this point cannot be found here. */
13
+ scanTruncated?: boolean;
10
14
  sessionId?: string;
11
15
  }
16
+ /**
17
+ * Ceiling on how much of one message is kept for *matching*. The old code clipped each message to
18
+ * the small display window at ingest, so a keyword in the middle of a long message was gone from
19
+ * the corpus entirely and widening the query could never bring it back. This is deliberately much
20
+ * larger than the display window; a single pathological message still cannot blow out memory.
21
+ */
22
+ export declare const SESSION_SCAN_MAX_CHARS = 20000;
12
23
  export interface BuildSessionCorpusOptions {
13
24
  channelDir: string;
14
25
  maxFiles: number;
@@ -1,8 +1,14 @@
1
1
  import { readdir, stat } from "node:fs/promises";
2
2
  import { basename, join } from "node:path";
3
3
  import { isNodeError, readOptionalTextFile } from "../shared/fs-utils.js";
4
- import { clipText } from "../shared/text-utils.js";
5
4
  import { isRecord } from "../shared/type-guards.js";
5
+ /**
6
+ * Ceiling on how much of one message is kept for *matching*. The old code clipped each message to
7
+ * the small display window at ingest, so a keyword in the middle of a long message was gone from
8
+ * the corpus entirely and widening the query could never bring it back. This is deliberately much
9
+ * larger than the display window; a single pathological message still cannot blow out memory.
10
+ */
11
+ export const SESSION_SCAN_MAX_CHARS = 20_000;
6
12
  const DEFAULT_MAX_CHARS_PER_DOCUMENT = 4_000;
7
13
  const DEFAULT_MAX_DOCUMENTS_TOTAL = 5_000;
8
14
  const IGNORED_JSONL_FILES = new Set([
@@ -83,17 +89,22 @@ function getNestedRecord(record, key) {
83
89
  return isRecord(value) ? value : null;
84
90
  }
85
91
  function createDocument(params) {
86
- const text = clipText(params.text, params.maxChars, { headRatio: 0.55, omitHint: "\n[...]\n" }).trim();
87
- if (!text) {
92
+ // The ingest clip is a fixed, generous scan cap — not the caller's display window. Trimming for
93
+ // display happens later, at query time, centered on the match (fix plan §2.5). `params.maxChars`
94
+ // is kept in the signature for callers that still pass it but no longer drives the clip.
95
+ const raw = params.text.trim();
96
+ if (!raw) {
88
97
  return null;
89
98
  }
99
+ const scanTruncated = raw.length > SESSION_SCAN_MAX_CHARS;
90
100
  return {
91
101
  id: params.id,
92
102
  source: params.source,
93
103
  path: params.path,
94
104
  timestamp: params.timestamp,
95
105
  role: params.role,
96
- text,
106
+ text: scanTruncated ? raw.slice(0, SESSION_SCAN_MAX_CHARS) : raw,
107
+ ...(scanTruncated ? { scanTruncated: true } : {}),
97
108
  sessionId: params.sessionId,
98
109
  };
99
110
  }
@@ -27,5 +27,8 @@ export interface SessionSearchResponse {
27
27
  query: string;
28
28
  results: SessionSearchResult[];
29
29
  searchedDocuments: number;
30
+ /** Documents whose text was itself clipped at the scan cap — a keyword past that point is not
31
+ * findable in this corpus, so "no match" there is not proof it was never said. */
32
+ partialDocuments: number;
30
33
  }
31
34
  export declare function searchChannelSessions(request: SearchChannelSessionsRequest): Promise<SessionSearchResponse>;
@@ -1,6 +1,5 @@
1
1
  import { relative } from "node:path";
2
2
  import { parseLocalTime } from "../shared/local-time.js";
3
- import { clipText } from "../shared/text-utils.js";
4
3
  import { recencyBoostByAge, tokenizeRecallText } from "./search.js";
5
4
  import { buildSessionCorpus } from "./session-corpus.js";
6
5
  import { runSidecarTask } from "./sidecar-worker.js";
@@ -64,12 +63,13 @@ function scoreDocument(document, lowerQuery, queryTokens) {
64
63
  // reported failure mode from this term. Changing it blind, without that guardrail, risks
65
64
  // swapping one unverified scoring bias for another.
66
65
  const coverage = queryTokens.length > 0 ? matchedTokens / queryTokens.length : 0;
67
- const exactBoost = lowerQuery && lowerText.includes(lowerQuery) ? 1 : 0;
68
- const score = matchedTokens * 1.4 + coverage * 2 + exactBoost + computeRecencyBoost(document.timestamp);
66
+ const exactHit = Boolean(lowerQuery) && lowerText.includes(lowerQuery);
67
+ const score = matchedTokens * 1.4 + coverage * 2 + (exactHit ? 1 : 0) + computeRecencyBoost(document.timestamp);
69
68
  return {
70
69
  document,
71
70
  score,
72
71
  matches: Array.from(new Set(matches)),
72
+ exactHit,
73
73
  };
74
74
  }
75
75
  function sortRecentDocuments(a, b) {
@@ -77,8 +77,36 @@ function sortRecentDocuments(a, b) {
77
77
  const bTime = (b.timestamp ? parseLocalTime(b.timestamp) : undefined) ?? 0;
78
78
  return bTime - aTime;
79
79
  }
80
- async function summarizeHit(request, document, query) {
81
- const fallback = clipText(document.text, request.maxCharsPerChunk, { headRatio: 0.65, omitHint: "\n[...]\n" });
80
+ /**
81
+ * Cut a display window from the (possibly large) scan text, centered on the first place the query
82
+ * or one of its tokens appears. The old code always took the head, so a hit deep in a long message
83
+ * came back as a preview that did not even contain the keyword (fix plan §2.5).
84
+ */
85
+ function windowAroundMatch(text, query, queryTokens, maxChars) {
86
+ if (text.length <= maxChars) {
87
+ return text;
88
+ }
89
+ const lower = text.toLowerCase();
90
+ let at = query.trim() ? lower.indexOf(query.trim().toLowerCase()) : -1;
91
+ if (at < 0) {
92
+ for (const token of queryTokens) {
93
+ at = lower.indexOf(token);
94
+ if (at >= 0)
95
+ break;
96
+ }
97
+ }
98
+ if (at < 0) {
99
+ return `${text.slice(0, maxChars)}\n[...]`;
100
+ }
101
+ const half = Math.floor(maxChars / 2);
102
+ const start = Math.max(0, at - half);
103
+ const end = Math.min(text.length, start + maxChars);
104
+ const prefix = start > 0 ? "[...]\n" : "";
105
+ const suffix = end < text.length ? "\n[...]" : "";
106
+ return `${prefix}${text.slice(start, end)}${suffix}`;
107
+ }
108
+ async function summarizeHit(request, document, query, queryTokens) {
109
+ const fallback = windowAroundMatch(document.text, query, queryTokens, request.maxCharsPerChunk);
82
110
  if (!request.summarizeWithModel || !query.trim() || fallback.length < SESSION_SEARCH_SUMMARY_MIN_CHARS) {
83
111
  return fallback;
84
112
  }
@@ -158,21 +186,30 @@ export async function searchChannelSessions(request) {
158
186
  const selected = query
159
187
  ? documents
160
188
  .map((document) => scoreDocument(document, lowerQuery, queryTokens))
161
- .filter((entry) => entry.score > 0)
189
+ // Require actual match evidence: recency alone used to lift a completely unrelated
190
+ // recent message above 0 and return it with an empty `matches` array — wasted tokens
191
+ // and a misleading "hit". Recency now only ranks among documents that did match.
192
+ .filter((entry) => entry.matches.length > 0 || entry.exactHit)
162
193
  .sort((a, b) => b.score - a.score)
163
194
  .slice(0, limit)
164
195
  : documents
165
196
  .sort(sortRecentDocuments)
166
197
  .slice(0, limit)
167
- .map((document) => ({ document, score: computeRecencyBoost(document.timestamp), matches: [] }));
198
+ .map((document) => ({
199
+ document,
200
+ score: computeRecencyBoost(document.timestamp),
201
+ matches: [],
202
+ exactHit: false,
203
+ }));
168
204
  const results = [];
169
205
  for (const hit of selected) {
170
- const summary = await summarizeHit(request, hit.document, query);
206
+ const summary = await summarizeHit(request, hit.document, query, queryTokens);
171
207
  results.push(toResult(request, hit.document, hit.score, hit.matches, summary));
172
208
  }
173
209
  return {
174
210
  query,
175
211
  results,
176
212
  searchedDocuments: documents.length,
213
+ partialDocuments: documents.filter((document) => document.scanTruncated).length,
177
214
  };
178
215
  }
@@ -32,6 +32,13 @@ export interface MemoryTombstoneRecord {
32
32
  contentHash: string;
33
33
  deletedAt: string;
34
34
  reason: string;
35
+ /**
36
+ * A later append that cancels the tombstone for this `contentHash`: the user explicitly saved
37
+ * the fact again, so the background reflect pass is no longer blocked from re-learning it. The
38
+ * file stays append-only — `isDescriptionTombstoned` replays records in order and the last one
39
+ * for a hash wins.
40
+ */
41
+ revoked?: boolean;
35
42
  }
36
43
  export declare function getChannelMemoryDir(channelDir: string): string;
37
44
  export declare function getChannelMemoryIndexPath(channelDir: string): string;
@@ -54,6 +61,8 @@ export declare function rebuildMemoryIndex(channelDir: string): Promise<MemoryEn
54
61
  export declare function readMemoryTombstoneRecords(channelDir: string): Promise<MemoryTombstoneRecord[]>;
55
62
  export declare function appendMemoryTombstoneRecord(channelDir: string, record: MemoryTombstoneRecord): Promise<void>;
56
63
  export declare function isDescriptionTombstoned(channelDir: string, description: string): Promise<boolean>;
64
+ /** Cancel the tombstone for `description` (append-only): a user re-authorized the fact. */
65
+ export declare function revokeMemoryTombstone(channelDir: string, description: string, today?: string): Promise<void>;
57
66
  /**
58
67
  * Mechanical store mutations. Policy — per-pass caps, confidence bars, user-source protection —
59
68
  * lives in the reflect pass (spec 050, D7), never here.
@@ -276,7 +276,22 @@ export async function appendMemoryTombstoneRecord(channelDir, record) {
276
276
  }
277
277
  export async function isDescriptionTombstoned(channelDir, description) {
278
278
  const hash = hashMemoryContent(description);
279
- return (await readMemoryTombstoneRecords(channelDir)).some((record) => record.contentHash === hash);
279
+ let tombstoned = false;
280
+ for (const record of await readMemoryTombstoneRecords(channelDir)) {
281
+ if (record.contentHash === hash) {
282
+ tombstoned = record.revoked !== true;
283
+ }
284
+ }
285
+ return tombstoned;
286
+ }
287
+ /** Cancel the tombstone for `description` (append-only): a user re-authorized the fact. */
288
+ export async function revokeMemoryTombstone(channelDir, description, today = localDayKey()) {
289
+ await appendMemoryTombstoneRecord(channelDir, {
290
+ contentHash: hashMemoryContent(description),
291
+ deletedAt: today,
292
+ reason: "re-authorized by explicit user save",
293
+ revoked: true,
294
+ });
280
295
  }
281
296
  export async function applyMemoryOps(channelDir, ops, options = {}) {
282
297
  const today = options.today ?? localDayKey();
@@ -366,7 +381,12 @@ export async function applyMemoryOps(channelDir, ops, options = {}) {
366
381
  result.skippedSecret++;
367
382
  continue;
368
383
  }
369
- if (await isDescriptionTombstoned(channelDir, description)) {
384
+ // A tombstone exists to stop the *background* reflect pass from silently re-learning a fact
385
+ // the user deleted. It must not also block the user's own explicit `memory_save` (source
386
+ // "user") — that path is the user re-authorizing the fact, and a successful save here
387
+ // revokes the tombstone so the background pass stops fighting it too.
388
+ const tombstoned = await isDescriptionTombstoned(channelDir, description);
389
+ if (tombstoned && op.source !== "user") {
370
390
  result.skippedTombstone++;
371
391
  continue;
372
392
  }
@@ -387,6 +407,9 @@ export async function applyMemoryOps(channelDir, ops, options = {}) {
387
407
  malformed: false,
388
408
  };
389
409
  await writeEntryFile(channelDir, entry);
410
+ if (tombstoned && op.source === "user") {
411
+ await revokeMemoryTombstone(channelDir, description, today);
412
+ }
390
413
  byName.set(name, entry);
391
414
  liveNames.add(name);
392
415
  result.added.push(name);