@operad-io/memory 0.3.1 → 0.4.0

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.
@@ -0,0 +1,293 @@
1
+ /**
2
+ * Runs the memory regression set against the memory as it is now and records a
3
+ * score. A case is scored by exact phrases, not by a model judge:
4
+ *
5
+ * - The score then moves only when the memory, the compaction window or the
6
+ * answerer moves. A judge model adds its own drift to a number whose job is
7
+ * to show the memory's drift, and a fixed rubric does not remove it.
8
+ * - It costs nothing to run, so it can run after every change to the memory.
9
+ * - The phrases are short phrases the person approved when the case was made
10
+ * (a name, a date, a number), which is the kind of answer a memory misses.
11
+ *
12
+ * The default answerer needs no model. It builds what the bot would have in
13
+ * front of it for the question (the messages a compaction would keep, the
14
+ * memory index cut at its limit, and what a memory search of the question
15
+ * returns) and scores that: a phrase the bot is never shown cannot be answered.
16
+ * A program may stand in for the answerer to score a real bot's answer.
17
+ */
18
+
19
+ import { cpSync, existsSync, appendFileSync, mkdtempSync, mkdirSync, readFileSync, rmSync } from "node:fs";
20
+ import { tmpdir } from "node:os";
21
+ import { join, resolve } from "node:path";
22
+ import { isRecord, type JsonValue } from "@operad-io/engine";
23
+ import { MEMORY_INDEX_MAX } from "../memory.ts";
24
+ import { MemorySearch } from "../search/service.ts";
25
+ import { chatDocument } from "../search/sources.ts";
26
+ import { loadCases, CaseError, type CaseMessage, type MemoryCase } from "./format.ts";
27
+
28
+ /** The messages a compaction keeps whole, when `--window` is not given. */
29
+ export const DEFAULT_WINDOW = 6;
30
+
31
+ /** The file the scores are appended to, in the operad home. */
32
+ export const SCORES_FILE = "memory-scores.jsonl";
33
+
34
+ /** What the answerer is given for one case. */
35
+ export interface AnswerInput {
36
+ readonly question: string;
37
+ /** The messages still in the context after compaction. */
38
+ readonly context: readonly CaseMessage[];
39
+ /** The memory index and what a search of the question found. */
40
+ readonly memory: string;
41
+ }
42
+
43
+ /** Turns what the bot has into an answer. */
44
+ export type Answerer = (input: AnswerInput) => Promise<string>;
45
+
46
+ /** The answerer that needs no model: everything the bot is shown is its answer. */
47
+ export const recallAnswerer: Answerer = async (input) =>
48
+ [...input.context.map((message) => message.text), input.memory].join("\n");
49
+
50
+ /** An answerer that runs a program: the input is JSON on stdin, the answer is its stdout. */
51
+ export function programAnswerer(command: readonly string[], timeoutMs = 120_000): Answerer {
52
+ return async (input) => {
53
+ const child = Bun.spawn({
54
+ cmd: [...command],
55
+ stdin: new Blob([JSON.stringify(input)]),
56
+ stdout: "pipe",
57
+ stderr: "ignore",
58
+ timeout: timeoutMs,
59
+ killSignal: "SIGKILL",
60
+ });
61
+ const [out, code] = await Promise.all([new Response(child.stdout).text(), child.exited]);
62
+ if (code !== 0) throw new CaseError(`the answer program ended with code ${code}`);
63
+ return out;
64
+ };
65
+ }
66
+
67
+ /** Text as phrases are compared: lowercase, with spaces and punctuation removed. */
68
+ export function normalised(text: string): string {
69
+ return text.normalize("NFKC").toLowerCase().replace(/[^\p{L}\p{N}]+/gu, "");
70
+ }
71
+
72
+ /** How one answer fared against one case. */
73
+ export interface CaseScore {
74
+ readonly id: string;
75
+ readonly passed: boolean;
76
+ /** Facts the answer did not state. */
77
+ readonly missing: readonly string[];
78
+ /** Wrong phrases the answer stated. */
79
+ readonly repeated: readonly string[];
80
+ }
81
+
82
+ /** A case passes when every fact is stated and no wrong phrase is. */
83
+ export function scoreAnswer(answer: string, found: MemoryCase): CaseScore {
84
+ const text = normalised(answer);
85
+ const states = (phrase: string): boolean => {
86
+ const wanted = normalised(phrase);
87
+ return wanted.length > 0 && text.includes(wanted);
88
+ };
89
+ const missing = found.answer.include.filter((phrase) => !states(phrase));
90
+ const repeated = found.answer.avoid.filter((phrase) => states(phrase));
91
+ return { id: found.id, passed: missing.length === 0 && repeated.length === 0, missing, repeated };
92
+ }
93
+
94
+ /** The settings a score was taken under, so a change of score can be read against them. */
95
+ export interface ScoreSettings {
96
+ readonly bot: string;
97
+ readonly window: number;
98
+ readonly memoryIndexMax: number;
99
+ /** `recall`, or the program that answered. */
100
+ readonly answerer: string;
101
+ /** A memory directory used in place of the bot's own, when one was given. */
102
+ readonly memory?: string | undefined;
103
+ }
104
+
105
+ /** One line of the score history. It holds ids and counts, never case text. */
106
+ export interface ScoreRecord {
107
+ readonly at: number;
108
+ readonly set: string;
109
+ readonly total: number;
110
+ readonly passed: number;
111
+ readonly score: number;
112
+ readonly settings: ScoreSettings;
113
+ readonly cases: readonly { readonly id: string; readonly passed: boolean }[];
114
+ }
115
+
116
+ /** What one run needs. */
117
+ export interface ScoreOptions {
118
+ readonly home: string;
119
+ readonly casesDir: string;
120
+ readonly settings?: Readonly<Record<string, JsonValue>> | undefined;
121
+ readonly bot?: string | undefined;
122
+ /** Use this directory as the bot's memory instead of the home's. */
123
+ readonly memory?: string | undefined;
124
+ readonly window?: number | undefined;
125
+ readonly answerer?: Answerer | undefined;
126
+ /** Names the answerer in the record. */
127
+ readonly answererName?: string | undefined;
128
+ /** Milliseconds since the epoch; injected so a test needs no real time. */
129
+ readonly now: () => number;
130
+ /** Append the score to the history. */
131
+ readonly record: boolean;
132
+ }
133
+
134
+ /** The result of a run: this score, and the one it follows. */
135
+ export interface ScoreRun {
136
+ readonly record: ScoreRecord;
137
+ readonly scores: readonly CaseScore[];
138
+ readonly previous?: ScoreRecord | undefined;
139
+ }
140
+
141
+ /** The history in the home, oldest first; a line that is not a score is ignored. */
142
+ export function readScores(home: string): readonly ScoreRecord[] {
143
+ const file = join(home, SCORES_FILE);
144
+ if (!existsSync(file)) return [];
145
+ const found: ScoreRecord[] = [];
146
+ for (const line of readFileSync(file, "utf8").split("\n")) {
147
+ if (line.trim().length === 0) continue;
148
+ try {
149
+ const parsed: unknown = JSON.parse(line);
150
+ if (isRecord(parsed) && typeof parsed["at"] === "number" && typeof parsed["score"] === "number" && typeof parsed["set"] === "string") {
151
+ found.push(parsed as unknown as ScoreRecord);
152
+ }
153
+ } catch {
154
+ continue;
155
+ }
156
+ }
157
+ return found;
158
+ }
159
+
160
+ /** Runs every case of the set once and, when asked, records the score. */
161
+ export async function runScore(options: ScoreOptions): Promise<ScoreRun> {
162
+ const cases = loadCases(options.casesDir);
163
+ if (cases.length === 0) throw new CaseError(`there are no cases in ${options.casesDir}`);
164
+ const bot = options.bot ?? "default";
165
+ const window = options.window ?? DEFAULT_WINDOW;
166
+ if (!Number.isInteger(window) || window < 0) throw new CaseError("the window is a whole number of messages, 0 or more");
167
+ const answerer = options.answerer ?? recallAnswerer;
168
+
169
+ const scratch = mkdtempSync(join(tmpdir(), "memory-score-"));
170
+ try {
171
+ let home = options.home;
172
+ if (options.memory !== undefined) {
173
+ // A given memory directory stands in for the bot's own, in a home of its own.
174
+ home = join(scratch, "home");
175
+ mkdirSync(join(home, "bot", bot), { recursive: true });
176
+ cpSync(resolve(options.memory), join(home, "bot", bot, "memory"), { recursive: true });
177
+ }
178
+ const botDir = join(home, "bot", bot);
179
+ const search = new MemorySearch(home, options.settings ?? {}, { file: join(scratch, "search.sqlite") });
180
+ const scores: CaseScore[] = [];
181
+ try {
182
+ await search.refresh();
183
+ const indexFile = join(botDir, "memory", "index.md");
184
+ const index = existsSync(indexFile) ? readFileSync(indexFile, "utf8").slice(0, MEMORY_INDEX_MAX) : "";
185
+ for (const found of cases) {
186
+ const kept = window === 0 ? [] : found.context.slice(-window);
187
+ const older = found.context.slice(0, found.context.length - kept.length);
188
+ const material = recalled(search, botDir, found, older, index);
189
+ const answer = await answerer({ question: found.question, context: kept, memory: material });
190
+ scores.push(scoreAnswer(answer, found));
191
+ }
192
+ } finally {
193
+ search.close();
194
+ }
195
+ const passed = scores.filter((score) => score.passed).length;
196
+ const history = readScores(options.home);
197
+ const set = resolve(options.casesDir);
198
+ const previous = [...history].reverse().find((entry) => entry.set === set);
199
+ const record: ScoreRecord = {
200
+ at: options.now(),
201
+ set,
202
+ total: scores.length,
203
+ passed,
204
+ score: passed / scores.length,
205
+ settings: {
206
+ bot,
207
+ window,
208
+ memoryIndexMax: MEMORY_INDEX_MAX,
209
+ answerer: options.answererName ?? "recall",
210
+ ...(options.memory === undefined ? {} : { memory: resolve(options.memory) }),
211
+ },
212
+ cases: scores.map((score) => ({ id: score.id, passed: score.passed })),
213
+ };
214
+ if (options.record) {
215
+ mkdirSync(options.home, { recursive: true });
216
+ appendFileSync(join(options.home, SCORES_FILE), `${JSON.stringify(record)}\n`);
217
+ }
218
+ return { record, scores, ...(previous === undefined ? {} : { previous }) };
219
+ } finally {
220
+ rmSync(scratch, { recursive: true, force: true });
221
+ }
222
+ }
223
+
224
+ /** The memory index and the search hits for the question, over memory, wiki and the compacted-away messages. */
225
+ function recalled(
226
+ search: MemorySearch,
227
+ botDir: string,
228
+ found: MemoryCase,
229
+ older: readonly CaseMessage[],
230
+ index: string,
231
+ ): string {
232
+ const id = `chat:case-${found.id}`;
233
+ if (older.length > 0) {
234
+ const text = chatDocument(`case-${found.id}`, found.id, older.map((message, at) => ({ id: String(at), role: message.role, text: message.text })));
235
+ search.backend.put({
236
+ id,
237
+ scope: "chats",
238
+ owner: resolve(botDir),
239
+ directory: "",
240
+ name: "",
241
+ title: found.id,
242
+ text,
243
+ fields: {},
244
+ lineCount: text.split("\n").length,
245
+ digest: id,
246
+ });
247
+ }
248
+ const parts = [index];
249
+ try {
250
+ const result = search.search({ text: found.question, cwd: botDir, limit: 5 });
251
+ for (const hit of result.hits) {
252
+ try {
253
+ parts.push(search.read({ id: hit.id, from: hit.lineStart, to: hit.lineEnd }).text);
254
+ } catch {
255
+ parts.push(hit.snippet);
256
+ }
257
+ }
258
+ } catch {
259
+ // A question the index cannot parse finds nothing; the index above still counts.
260
+ } finally {
261
+ if (older.length > 0) search.backend.remove(id);
262
+ }
263
+ return parts.join("\n");
264
+ }
265
+
266
+ /** A run as the command prints it. */
267
+ export function scoreText(run: ScoreRun): string {
268
+ const { record, scores, previous } = run;
269
+ const percent = (value: number): string => `${Math.round(value * 100)}%`;
270
+ const lines = [`memory score: ${record.passed}/${record.total} (${percent(record.score)})`];
271
+ if (previous !== undefined) {
272
+ const change = record.passed - previous.passed;
273
+ const same = JSON.stringify(previous.settings) === JSON.stringify(record.settings);
274
+ lines.push(
275
+ `before: ${previous.passed}/${previous.total} (${percent(previous.score)}), ${change === 0 ? "no change" : `${change > 0 ? "+" : ""}${change} passed`}${same ? "" : "; the settings differ"}`,
276
+ );
277
+ const was = new Map(previous.cases.map((entry) => [entry.id, entry.passed]));
278
+ for (const entry of record.cases) {
279
+ const before = was.get(entry.id);
280
+ if (before === true && !entry.passed) lines.push(`now fails: ${entry.id}`);
281
+ if (before === false && entry.passed) lines.push(`now passes: ${entry.id}`);
282
+ }
283
+ }
284
+ for (const score of scores) {
285
+ if (score.passed) continue;
286
+ const why = [
287
+ ...score.missing.map((fact) => `missing "${fact}"`),
288
+ ...score.repeated.map((phrase) => `states "${phrase}"`),
289
+ ];
290
+ lines.push(`fails: ${score.id}: ${why.join("; ")}`);
291
+ }
292
+ return `${lines.join("\n")}\n`;
293
+ }
package/src/commit.ts CHANGED
@@ -24,6 +24,7 @@ import {
24
24
  TIDY_COMMIT_FACT,
25
25
  TIDY_ORIGIN,
26
26
  applyAppendOnly,
27
+ restoreInstructions,
27
28
  lastTidyCommit,
28
29
  rewriteDrop,
29
30
  } from "./tidy.ts";
@@ -50,6 +51,71 @@ export interface CommitInfo {
50
51
  readonly paths: readonly string[];
51
52
  /** The commit's subject. */
52
53
  readonly message: string;
54
+ /** The notes the commit changed, each with a one-line summary. */
55
+ readonly files: readonly WrittenNote[];
56
+ }
57
+
58
+ /** One note a commit changed: its file, named from the repository's label, and a one-line summary. */
59
+ export interface WrittenNote {
60
+ readonly file: string;
61
+ readonly summary: string;
62
+ }
63
+
64
+ /** The longest summary kept for a note. */
65
+ const SUMMARY_MAX = 120;
66
+
67
+ function cutSummary(text: string): string {
68
+ const chars = [...text];
69
+ return chars.length <= SUMMARY_MAX ? text : `${chars.slice(0, SUMMARY_MAX - 1).join("")}…`;
70
+ }
71
+
72
+ /** The one line that says what a note is: its frontmatter `description`, `summary` or `title`, else its first heading or line. */
73
+ export function noteSummary(text: string): string {
74
+ const lines = text.replace(/\r\n/g, "\n").split("\n");
75
+ let start = 0;
76
+ if ((lines[0] ?? "").trim() === "---") {
77
+ const end = lines.findIndex((line, index) => index > 0 && line.trim() === "---");
78
+ if (end > 0) {
79
+ start = end + 1;
80
+ for (const key of ["description", "summary", "title"]) {
81
+ for (const line of lines.slice(1, end)) {
82
+ const trimmed = line.trim();
83
+ if (!trimmed.toLowerCase().startsWith(`${key}:`)) continue;
84
+ const value = trimmed.slice(key.length + 1).trim().replace(/^["']|["']$/g, "").trim();
85
+ if (value.length > 0) return cutSummary(value);
86
+ }
87
+ }
88
+ }
89
+ }
90
+ for (const line of lines.slice(start)) {
91
+ const clean = line.replace(/^#+\s*/, "").trim();
92
+ if (clean.length > 0) return cutSummary(clean);
93
+ }
94
+ return "";
95
+ }
96
+
97
+ /** The notes a staged change touches, with a summary of each note as it now is; a deleted note says so. */
98
+ function stagedNotes(repository: Repository, paths: string, label: string): readonly WrittenNote[] {
99
+ const listed = memoryGit(repository.root, ["diff", "--cached", "--name-status", "--no-renames", "-z", "--", paths]);
100
+ if (!listed.ok) return [];
101
+ const parts = listed.out.split("\0").filter((part) => part.length > 0);
102
+ const notes: WrittenNote[] = [];
103
+ for (let index = 0; index + 1 < parts.length; index += 2) {
104
+ const status = parts[index] ?? "";
105
+ const path = parts[index + 1] ?? "";
106
+ if (!path.endsWith(".md")) continue;
107
+ const inside = paths === "." ? path : path.slice(paths.length + 1);
108
+ let summary = "";
109
+ if (!status.startsWith("D")) {
110
+ try {
111
+ summary = noteSummary(readFileSync(join(repository.root, path), "utf8"));
112
+ } catch {
113
+ summary = "";
114
+ }
115
+ }
116
+ notes.push({ file: `${label}/${inside}`, summary });
117
+ }
118
+ return notes;
53
119
  }
54
120
 
55
121
  /** A note whose frontmatter says it came from untrusted content. */
@@ -131,7 +197,7 @@ export function commitChanges(
131
197
  repository: Repository,
132
198
  directory: string,
133
199
  message: string,
134
- options: { readonly allowEmpty?: boolean | undefined } = {},
200
+ options: { readonly allowEmpty?: boolean | undefined; readonly label?: string | undefined } = {},
135
201
  ): CommitInfo | undefined {
136
202
  if (!repository.tracked) return undefined;
137
203
  const paths = pathIn(repository.root, directory);
@@ -144,6 +210,7 @@ export function commitChanges(
144
210
  if (!added.ok) {
145
211
  throw new Error(`git add in ${repository.root} failed: ${added.err || "git wrote nothing"}`);
146
212
  }
213
+ const files = stagedNotes(repository, paths, options.label ?? paths);
147
214
  const committed = memoryGit(repository.root, [
148
215
  ...COMMIT_IDENTITY,
149
216
  "commit",
@@ -157,7 +224,7 @@ export function commitChanges(
157
224
  if (!committed.ok) {
158
225
  throw new Error(`git commit in ${repository.root} failed: ${committed.err || "git wrote nothing"}`);
159
226
  }
160
- return { root: repository.root, paths: [paths], message };
227
+ return { root: repository.root, paths: [paths], message, files };
161
228
  }
162
229
 
163
230
  /** What one bot run changed, as the step reports it. */
@@ -167,6 +234,8 @@ export interface MemoryCommitData {
167
234
  readonly memory: CommitInfo | null;
168
235
  readonly wiki: CommitInfo | null;
169
236
  readonly unindexed: readonly string[];
237
+ /** The notes this run wrote, in the memory and in the wiki, each with a one-line summary. */
238
+ readonly wrote: readonly WrittenNote[];
170
239
  }
171
240
 
172
241
  /** The bot and chat a commit step was called for. */
@@ -221,22 +290,24 @@ export async function commitBotRun(
221
290
  const repository = ensureRepository(memoryDir);
222
291
  let message = commitMessage(bot.tidy ? "tidy" : "memory", bot.bot, bot.chat);
223
292
  if (bot.tidy) {
293
+ restoreInstructions(repository, memoryDir);
224
294
  const baseline = lastTidyCommit(repository, memoryDir, bot.bot);
225
295
  if (baseline !== undefined && rewriteDrop(repository, memoryDir, baseline).voided) {
226
296
  applyAppendOnly(repository, memoryDir, baseline);
227
297
  message = `${message}\n\n${TIDY_APPEND_ONLY_NOTE}`;
228
298
  }
229
299
  }
230
- const memory = commitChanges(repository, memoryDir, message, { allowEmpty: bot.tidy });
300
+ const memory = commitChanges(repository, memoryDir, message, { allowEmpty: bot.tidy, label: "memory" });
231
301
  const wiki = ensureWiki(home, settings);
232
302
  const wikiIndex = stripUntrustedFromIndex(wiki.directory);
233
- const wikiCommit = commitChanges(wiki, wiki.directory, commitMessage("wiki", bot.bot, bot.chat));
303
+ const wikiCommit = commitChanges(wiki, wiki.directory, commitMessage("wiki", bot.bot, bot.chat), { label: "wiki" });
234
304
  return {
235
305
  bot: bot.bot,
236
306
  chat: bot.chat,
237
307
  memory: memory ?? null,
238
308
  wiki: wikiCommit ?? null,
239
309
  unindexed: [...new Set([...index.removed, ...wikiIndex.removed])],
310
+ wrote: [...(memory?.files ?? []), ...(wikiCommit?.files ?? [])],
240
311
  };
241
312
  },
242
313
  { label: "memory" },
package/src/index.ts CHANGED
@@ -13,6 +13,8 @@ import { runMemoryCommit } from "./commit.ts";
13
13
  import { openMemorySearch } from "./search/service.ts";
14
14
  import { runMemoryRead, runMemorySearch } from "./search/command.ts";
15
15
  import { botMemoryDirectories } from "./search/sources.ts";
16
+ import { runMemoryPropose, runMemoryScore } from "./cases/command.ts";
17
+ import { CASE_PROPOSAL_TYPE, caseProposalActions, caseProposalItems, caseProposalViews } from "./cases/propose.ts";
16
18
  import {
17
19
  WIKI_FOLDER_TYPE,
18
20
  WIKI_NOTE_TYPE,
@@ -60,6 +62,7 @@ export function createMemoryPlugin() {
60
62
  version: pkg.version,
61
63
  settings: MEMORY_SETTINGS,
62
64
  objects: [
65
+ { name: CASE_PROPOSAL_TYPE },
63
66
  {
64
67
  name: WIKI_FOLDER_TYPE,
65
68
  filters: WIKI_FILTERS,
@@ -73,10 +76,17 @@ export function createMemoryPlugin() {
73
76
  resolve: (ctx, type, id) => claimIfStored(ctx.store, type, resolveWikiNoteId(id)),
74
77
  },
75
78
  ],
79
+ actions: caseProposalActions,
76
80
  steps: [{ name: "commit", results: ["done", "failed"], run: runMemoryCommit }],
77
81
  commands: [
78
82
  { name: "search", args: "[--scope <scope>] [--field <name>=<value>] [--limit <n>] <query>", run: runMemorySearch },
79
83
  { name: "read", args: "<id> [from] [to] [--json]", run: runMemoryRead },
84
+ {
85
+ name: "score",
86
+ args: "[--cases <dir>] [--bot <name>] [--memory <dir>] [--window <n>] [--answer-with <program> [args]] [--no-record]",
87
+ run: runMemoryScore,
88
+ },
89
+ { name: "propose", args: "[--chat <id>]", run: runMemoryPropose },
80
90
  ],
81
91
  // The wiki is there before the first bot needs it; a directory that is
82
92
  // already a git repository is used as it is. The index is brought up to
@@ -114,7 +124,10 @@ export function createMemoryPlugin() {
114
124
  },
115
125
  };
116
126
  },
127
+ // A proposed test case waits for no run; it is a pending item until approved or rejected.
128
+ standing: (ctx) => caseProposalItems(ctx.store),
117
129
  views: {
130
+ [CASE_PROPOSAL_TYPE]: caseProposalViews,
118
131
  [WIKI_FOLDER_TYPE]: wikiFolderViews,
119
132
  [WIKI_NOTE_TYPE]: wikiNoteViews,
120
133
  },
@@ -136,3 +149,7 @@ export * from "./link-report.ts";
136
149
  export * from "./search/sources.ts";
137
150
  export * from "./search/command.ts";
138
151
  export * from "./wiki.ts";
152
+ export * from "./cases/format.ts";
153
+ export * from "./cases/score.ts";
154
+ export * from "./cases/propose.ts";
155
+ export * from "./cases/command.ts";
@@ -380,20 +380,21 @@ export class SqliteSearchBackend implements SearchBackend {
380
380
  const long = terms.filter((term) => characterLength(term) >= 3);
381
381
  const short = terms.filter((term) => characterLength(term) < 3);
382
382
  const found = new Map<string, BackendHit>();
383
+ const keyOf = (hit: BackendHit): string => (query.chunks === true ? `${hit.id}:${hit.lineStart}` : hit.id);
383
384
  // A tokenizer other than trigram is only used to measure it; the substring
384
385
  // fallback is what makes trigram's short-query gap harmless.
385
386
  const fallback = this.tokenizer === "trigram" && short.length > 0;
386
387
  if (long.length > 0) {
387
- for (const hit of this.matchFts(query, long)) found.set(hit.id, hit);
388
+ for (const hit of this.matchFts(query, long)) found.set(keyOf(hit), hit);
388
389
  }
389
390
  if (fallback) {
390
391
  for (const hit of this.matchSubstring(query, short)) {
391
- const before = found.get(hit.id);
392
- if (before === undefined || hit.score > before.score) found.set(hit.id, hit);
392
+ const before = found.get(keyOf(hit));
393
+ if (before === undefined || hit.score > before.score) found.set(keyOf(hit), hit);
393
394
  }
394
395
  } else if (long.length === 0) {
395
396
  // A non-trigram backend still asks FTS for its short terms.
396
- for (const hit of this.matchFts(query, short)) found.set(hit.id, hit);
397
+ for (const hit of this.matchFts(query, short)) found.set(keyOf(hit), hit);
397
398
  }
398
399
  return [...found.values()]
399
400
  .sort((left, right) => right.score - left.score || left.id.localeCompare(right.id))
@@ -408,10 +409,14 @@ export class SqliteSearchBackend implements SearchBackend {
408
409
  private filters(query: BackendQuery): { readonly sql: readonly string[]; readonly params: readonly string[] } {
409
410
  const sql: string[] = [];
410
411
  const params: string[] = [];
412
+ if (query.document !== undefined) {
413
+ sql.push("d.id = ?");
414
+ params.push(query.document);
415
+ }
411
416
  const places = query.scopes.map(() => "?").join(", ");
412
417
  sql.push(`d.scope IN (${places})`);
413
418
  params.push(...query.scopes);
414
- if (query.scopes.some((scope) => scope !== "wiki")) {
419
+ if (query.document === undefined && query.scopes.some((scope) => scope !== "wiki")) {
415
420
  // The wiki is shared; a bot's memory and chats are only the ones whose
416
421
  // owner is the bot's working directory.
417
422
  sql.push("(d.scope = 'wiki' OR d.owner = ?)");
@@ -68,6 +68,8 @@ interface SearchInput {
68
68
  readonly scopes?: readonly SearchScope[] | undefined;
69
69
  readonly fields?: Readonly<Record<string, string | readonly string[]>> | undefined;
70
70
  readonly limit?: number | undefined;
71
+ /** Only from the command line: the tools a bot gets cannot reach into another chat. */
72
+ readonly chat?: string | undefined;
71
73
  }
72
74
 
73
75
  function searchFromJson(parsed: Record<string, unknown>): SearchInput {
@@ -83,8 +85,14 @@ function searchFromArgv(argv: readonly string[]): SearchInput {
83
85
  const scopes: string[] = [];
84
86
  const fields: Record<string, string> = {};
85
87
  let limit: string | undefined;
88
+ let chat: string | undefined;
86
89
  for (let index = 0; index < argv.length; index += 1) {
87
90
  const arg = argv[index] ?? "";
91
+ if (arg === "--chat" || arg.startsWith("--chat=")) {
92
+ chat = arg === "--chat" ? argv[++index] ?? "" : arg.slice("--chat=".length);
93
+ if (chat.length === 0) throw new SearchError("--chat takes a chat id");
94
+ continue;
95
+ }
88
96
  if (arg === "--scope" || arg.startsWith("--scope=")) {
89
97
  const value = arg === "--scope" ? argv[++index] ?? "" : arg.slice("--scope=".length);
90
98
  scopes.push(value);
@@ -110,6 +118,7 @@ function searchFromArgv(argv: readonly string[]): SearchInput {
110
118
  ...(scopes.length === 0 ? {} : { scopes: scopesOf(scopes) }),
111
119
  ...(Object.keys(fields).length === 0 ? {} : { fields }),
112
120
  ...(limit === undefined ? {} : { limit: limitOf(limit) }),
121
+ ...(chat === undefined ? {} : { chat }),
113
122
  };
114
123
  }
115
124
 
@@ -192,6 +201,7 @@ export async function runMemorySearch(ctx: CommandContext, argv: readonly string
192
201
  ...(input.scopes === undefined ? {} : { scopes: requestedScopes(input.scopes) }),
193
202
  ...(input.fields === undefined ? {} : { fields: input.fields }),
194
203
  ...(input.limit === undefined ? {} : { limit: input.limit }),
204
+ ...(input.chat === undefined ? {} : { chat: input.chat, store: ctx.store }),
195
205
  });
196
206
  } finally {
197
207
  search.close();
@@ -30,6 +30,7 @@ import {
30
30
  documentPath,
31
31
  fileName,
32
32
  markdownFiles,
33
+ messageAtLine,
33
34
  } from "./sources.ts";
34
35
  import { wikiDirectory } from "../memory.ts";
35
36
  import {
@@ -294,7 +295,7 @@ export class MemorySearch {
294
295
  const page = await store.list("chat", { ...(cursor === undefined ? {} : { cursor }), limit: 200 });
295
296
  for (const object of page.objects) {
296
297
  const owner = chatOwner(object.data);
297
- if (owner === undefined) continue;
298
+ if (owner === undefined || object.data["run"] === true) continue;
298
299
  const id = `chat:${object.id}`;
299
300
  seen.add(id);
300
301
  const revision = store.latestFactSequence?.({ type: "chat", id: object.id });
@@ -342,7 +343,8 @@ export class MemorySearch {
342
343
  search(request: SearchRequest): SearchResult {
343
344
  const query = request.text.trim();
344
345
  if (query.length === 0) throw new SearchError("search needs a query");
345
- const scopes = requestedScopes(request.scopes);
346
+ const inChat = request.chat === undefined ? undefined : `chat:${request.chat}`;
347
+ const scopes: readonly SearchScope[] = inChat === undefined ? requestedScopes(request.scopes) : ["chats"];
346
348
  const limit = requestedLimit(request.limit);
347
349
  const fields = normaliseFields(request.fields);
348
350
  const hits = this.backend.search({
@@ -351,19 +353,30 @@ export class MemorySearch {
351
353
  owner: resolve(request.cwd),
352
354
  ...(fields === undefined ? {} : { fields }),
353
355
  limit,
356
+ ...(inChat === undefined ? {} : { document: inChat, chunks: true }),
354
357
  });
358
+ const messages =
359
+ request.chat === undefined || request.store === undefined ? undefined : chatMessages(request.store, request.chat);
355
360
  const terms = queryTerms(query);
356
361
  const found = new Map<string, BackendHit>();
357
362
  for (const hit of hits) {
358
- // A backend returns chunks; a reader wants the best chunk per document.
359
- const before = found.get(hit.id);
360
- if (before === undefined || hit.score > before.score) found.set(hit.id, hit);
363
+ // A backend returns chunks; a reader wants the best chunk per document,
364
+ // and a search inside one chat wants every place in it.
365
+ const key = inChat === undefined ? hit.id : `${hit.id}:${hit.lineStart}`;
366
+ const before = found.get(key);
367
+ if (before === undefined || hit.score > before.score) found.set(key, hit);
361
368
  }
362
369
  const results: SearchHit[] = [];
363
370
  const about = new Map<string, AboutDocument>();
364
371
  for (const hit of found.values()) {
365
372
  const document = this.backend.get(hit.id);
366
373
  if (document === undefined) continue;
374
+ // A chunk covers about twenty lines, so the message is the one holding the first matching line.
375
+ const matching = hit.text
376
+ .split(/\r?\n/u)
377
+ .findIndex((line) => terms.some((term) => line.toLocaleLowerCase().includes(term.toLocaleLowerCase())));
378
+ const message =
379
+ messages === undefined ? undefined : messageAtLine(messages, hit.lineStart + Math.max(0, matching));
367
380
  results.push({
368
381
  id: document.id,
369
382
  scope: document.scope,
@@ -374,6 +387,7 @@ export class MemorySearch {
374
387
  snippet: snippetOf(hit.text, terms),
375
388
  score: hit.score,
376
389
  fields: document.fields,
390
+ ...(message === undefined ? {} : { message }),
377
391
  });
378
392
  const key = `${document.scope}\u0000${document.owner}\u0000${document.directory}`;
379
393
  if (about.has(key)) continue;
@@ -381,7 +395,7 @@ export class MemorySearch {
381
395
  if (description === undefined) continue;
382
396
  about.set(key, { id: description.id, title: description.title, text: description.text.trim() });
383
397
  }
384
- results.sort((left, right) => right.score - left.score || left.id.localeCompare(right.id));
398
+ results.sort((left, right) => right.score - left.score || left.id.localeCompare(right.id) || left.lineStart - right.lineStart);
385
399
  return { query, scopes, hits: results.slice(0, limit), about: [...about.values()] };
386
400
  }
387
401
 
@@ -118,6 +118,8 @@ function messageOfFact(fact: { readonly data: Record<string, unknown> }): Indexe
118
118
  const data = fact.data;
119
119
  if (typeof data["id"] !== "string" || typeof data["text"] !== "string") return undefined;
120
120
  if (data["role"] !== "user" && data["role"] !== "assistant") return undefined;
121
+ // A message of a stretch that is not remembered stays out of the index (ADR 0038).
122
+ if (data["private"] === true) return undefined;
121
123
  return { id: data["id"], role: data["role"], text: data["text"] };
122
124
  }
123
125
 
@@ -182,6 +184,21 @@ export function chatDocument(chat: string, title: string, messages: readonly Ind
182
184
  return lines.join("\n");
183
185
  }
184
186
 
187
+ /**
188
+ * The message a line of a chat's document belongs to, or undefined for the
189
+ * heading. It walks the layout `chatDocument` writes: a heading of three
190
+ * lines, then per message a speaker line, its text and one blank line.
191
+ */
192
+ export function messageAtLine(messages: readonly IndexedChatMessage[], line: number): string | undefined {
193
+ let at = 4;
194
+ for (const message of messages) {
195
+ const end = at + 1 + message.text.split(/\r?\n/u).length;
196
+ if (line >= at && line <= end) return message.id;
197
+ at = end + 1;
198
+ }
199
+ return undefined;
200
+ }
201
+
185
202
  /** A chat's title, as its stored object states it. */
186
203
  export function chatTitle(id: string, data: Readonly<Record<string, unknown>>): string {
187
204
  const title = data["title"];