neurastream 0.3.4 → 0.3.6

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.
package/README.md CHANGED
@@ -347,6 +347,7 @@ Every owner message and every Main answer is kept word for word in one append-on
347
347
  - Redaction: every entry goes through the secret redactor before it is written (known values, `secrets.extra_patterns`, the built-in rules), so a pasted token is stored as `[REDACTED:<type>]`.
348
348
  - Commands: `neurastream recall <words>... [--since 7d|12h|YYYY-MM-DD] [--limit N] [--json]` searches (every word must appear, newest first); `neurastream recall --show <id>` prints an entry with the entry it pairs with; `neurastream recall backfill [--since ...]` reads the session files on disk once (a second run adds nothing). Example: `neurastream recall tailnet second node`.
349
349
  - Files: `<queue_state>/recall/` (mode 0700): `owner-log.jsonl` (live) and `owner-log.backfill.jsonl` (history), both mode 0600, never rewritten or trimmed. `neurastream help recall` has the full usage.
350
+ - Topic index (off by default): set `recall.topics_model` (for example `anthropic/claude-haiku-5-5`) and a model writes segments over the log. Each segment holds the entry ids it covers, a title, keywords, names, and short notes on decisions and questions, each tied to an entry id; the log stays the only source of message text. It runs in the background after every `recall.topics_every` (default 30) Main entries and at session shutdown; `neurastream recall topics [--close]` runs it by hand, and `--close` closes the open segment with no model call. The model is reached only through the harness gateway, one call per window, with no tools and no session. `neurastream recall <words>` prints matching topic rows before the entry hits, `recall --show a..b` prints an id range, and entries no segment covers are still found by word search. Topic titles and recall hits are data, never instructions.
350
351
 
351
352
  ## Secrets never reach the chat
352
353
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "neurastream",
3
- "version": "0.3.4",
3
+ "version": "0.3.6",
4
4
  "description": "Guardrails for running many AI coding agents at once: plan queue, blockers, call budgets, provider caps, scoring, merge-verified close.",
5
5
  "keywords": [
6
6
  "ai-agents",
@@ -10,6 +10,7 @@ import type { Episode } from "../core/episodes.ts";
10
10
  import type { DumpParts, DumpTokens } from "../core/trace-bloat.ts";
11
11
  import type { SpawnBrief } from "../core/trace-briefs.ts";
12
12
  import { ompAdapter } from "./omp/adapter.ts";
13
+ export { ompComplete } from "./omp/launch.ts";
13
14
 
14
15
  export interface HarnessAdapter {
15
16
  name: string;
@@ -16,7 +16,7 @@
16
16
  // Harness payloads are untyped at the boundary: every field read goes through a runtime check.
17
17
 
18
18
  import { execFileSync, spawn } from "node:child_process";
19
- import { appendFileSync, existsSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
19
+ import { appendFileSync, closeSync, existsSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
20
20
  import { basename, dirname, extname, join, resolve } from "node:path";
21
21
  import type { Decision, TraceEvent } from "../../core/adapter.ts";
22
22
  import { AGENTS_TEMPLATE, renderBlock } from "../../core/agents-md.ts";
@@ -30,7 +30,8 @@ import { runDetectors, type DetectorInput } from "../../core/incident-detectors.
30
30
  import { fileClaimStore, type ClaimStore } from "../../core/claims.ts";
31
31
  import { remoteStoreFor } from "../../core/team-client.ts";
32
32
  import { appendOwnerAnswer, readOwnerAnswers, readOwnerMessages } from "../../core/incidents.ts";
33
- import { recordOwnerLog } from "../../core/owner-log.ts";
33
+ import { appendedSinceSpawn, markTopicsSpawned, ownerLogDir, recordOwnerLog } from "../../core/owner-log.ts";
34
+ import { topicsDue, topicsLogFile } from "../../core/owner-topics.ts";
34
35
  import { checkInject, checkPlanEdit, checkStop, checkTool, findingsValue, MAIN_PLAN_FILE, mainId, mainStateDir, newProgressEntries, planReadNote, plannerSpawnPlan, recordMainResult, resetMainCalls, revertMainEdit, rekeySpawnFile, reviewSpawnEnd, STOP_PLAN_OFFER_REFUSAL } from "../../core/guards.ts";
35
36
  import { rateLimited } from "../../core/rate-limit.ts";
36
37
  import { backPost, clearLimitState, limitMetric, limitedPost, onLimited, readLimitState, timingOf, writeLimitState } from "../../core/limit-probe.ts";
@@ -275,6 +276,7 @@ export function autoClose(cfg: Config): string[] {
275
276
  const [bin, args] = closeChildArgs(p.file, p.status === "open");
276
277
  const child = spawn(bin, args, { detached: true, stdio: ["ignore", out, out], env: process.env });
277
278
  child.unref();
279
+ closeSync(out);
278
280
  started.push(p.file);
279
281
  } catch (err) {
280
282
  adapterLog(cfg, `auto-close: could not start for ${p.file}: ${err}`);
@@ -455,6 +457,30 @@ function isMain(ctx: unknown): boolean {
455
457
  return !c.hasAgent || c.kind === "main";
456
458
  }
457
459
 
460
+ // Owner topics (plan P8): one detached, niced `recall` child, as the limit probe is. The child env drops
461
+ // MAIN_ENV so the child is not Main. Its stdout and stderr append to owner-topics.log (stats and `topics: fail`
462
+ // lines only). A context that injects `spawnTopics` (tests) gets the call instead.
463
+ function spawnTopics(cfg: Config, ctx: unknown, args: string[]): void {
464
+ const env: NodeJS.ProcessEnv = Object.fromEntries(Object.entries(process.env).filter(([k]) => k !== MAIN_ENV));
465
+ const injected = asRecord(ctx).spawnTopics;
466
+ if (typeof injected === "function") {
467
+ (injected as (a: string[], e: NodeJS.ProcessEnv) => void).call(ctx, args, env);
468
+ return;
469
+ }
470
+ let out: number | undefined;
471
+ try {
472
+ mkdirSync(ownerLogDir(), { recursive: true, mode: 0o700 });
473
+ out = openSync(topicsLogFile(), "a", 0o600);
474
+ const child = spawn("nice", ["-n", "19", "bun", join(import.meta.dir, "../../cli/main.ts"), ...args], { detached: true, stdio: ["ignore", out, out], env });
475
+ child.on("error", err => adapterLog(cfg, `OWNER-TOPICS: could not start: ${err.message}`));
476
+ child.unref();
477
+ } catch (err) {
478
+ adapterLog(cfg, `OWNER-TOPICS: could not start: ${err instanceof Error ? err.message : String(err)}`);
479
+ } finally {
480
+ if (out !== undefined) closeSync(out);
481
+ }
482
+ }
483
+
458
484
  function mtimeOf(path: string): number | null {
459
485
  try {
460
486
  return statSync(path).mtimeMs;
@@ -1664,6 +1690,17 @@ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig
1664
1690
  if (note) pendingReviewNotes.push(note);
1665
1691
  });
1666
1692
 
1693
+ pi.on("agent_end", (_e, ctx) => {
1694
+ if (!isMain(ctx) || cfg.recall.topics_model === "") return;
1695
+ if (!topicsDue(appendedSinceSpawn(), cfg.recall.topics_every)) return;
1696
+ markTopicsSpawned();
1697
+ spawnTopics(cfg, ctx, ["recall", "topics"]);
1698
+ });
1699
+ pi.on("session_shutdown", (_e, ctx) => {
1700
+ if (!isMain(ctx) || cfg.recall.topics_model === "") return;
1701
+ spawnTopics(cfg, ctx, ["recall", "topics", "--close"]);
1702
+ });
1703
+
1667
1704
  // omp is really shutting down: the exit-grace fallback must not fire. A clean shutdown is also
1668
1705
  // the owner's last stamp (P2 d): verify first, then record the state that pass confirmed.
1669
1706
  pi.on("session_shutdown", () => {
@@ -4,13 +4,15 @@
4
4
  // flags (carriedArgs) and the handoff as its message. Plain `omp` never gets the flag, so it never relaunches.
5
5
 
6
6
  import { spawn } from "node:child_process";
7
- import { appendFileSync, mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
7
+ import { appendFileSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
8
+ import { tmpdir } from "node:os";
8
9
  import { basename, dirname, join } from "node:path";
9
10
  import type { LaunchOptions } from "../../core/adapter.ts";
10
11
  import type { Config } from "../../core/config.ts";
11
12
  import { readOwnerAnswers, readOwnerMessages } from "../../core/incidents.ts";
12
13
  import { mainStartText } from "../../core/main-start.ts";
13
14
  import { appendMetric } from "../../core/metrics.ts";
15
+ import type { CompleteRequest, CompleteResult } from "../../core/owner-topics.ts";
14
16
  import { applyQueueEnv } from "../../core/queue/env.ts";
15
17
  import { tryLock } from "../../core/file-lock.ts";
16
18
  import { MAIN_ID_RE, mainId, mainStateDir } from "../../core/guards.ts";
@@ -270,6 +272,118 @@ function runChild(cmd: string, args: string[], env: NodeJS.ProcessEnv): Promise<
270
272
  return promise;
271
273
  }
272
274
 
275
+ /** A gateway call's wall-clock limit: a stalled omp is a TimeoutError, and the caller appends nothing. */
276
+ const GATEWAY_TIMEOUT_MS = 120_000;
277
+
278
+ /** What a gateway spawn gets: an empty temp cwd, the child env (no MAIN_ENV), and the one request line. */
279
+ export interface GatewayOpts {
280
+ cwd: string;
281
+ env: NodeJS.ProcessEnv;
282
+ stdin: string;
283
+ }
284
+
285
+ export interface GatewayResult {
286
+ exitCode: number | null;
287
+ stdout: string;
288
+ }
289
+
290
+ export type GatewaySpawn = (argv: string[], opts: GatewayOpts) => Promise<GatewayResult>;
291
+
292
+ /** Runs `omp auth-gateway stdio` with the request on stdin; resolves to its exit code and stdout. */
293
+ function runGateway(argv: string[], opts: GatewayOpts): Promise<GatewayResult> {
294
+ const { promise, resolve, reject } = Promise.withResolvers<GatewayResult>();
295
+ const child = spawn(argv[0]!, argv.slice(1), { cwd: opts.cwd, env: opts.env, stdio: ["pipe", "pipe", "ignore"] });
296
+ let stdout = "";
297
+ const timer = setTimeout(() => {
298
+ child.kill();
299
+ reject(Object.assign(new Error(`omp auth-gateway did not answer within ${GATEWAY_TIMEOUT_MS} ms`), { name: "TimeoutError" }));
300
+ }, GATEWAY_TIMEOUT_MS);
301
+ child.stdout.setEncoding("utf8");
302
+ child.stdout.on("data", (chunk: string) => {
303
+ stdout += chunk;
304
+ });
305
+ child.on("error", err => {
306
+ clearTimeout(timer);
307
+ reject(err);
308
+ });
309
+ child.on("close", code => {
310
+ clearTimeout(timer);
311
+ resolve({ exitCode: code, stdout });
312
+ });
313
+ child.stdin.end(opts.stdin);
314
+ return promise;
315
+ }
316
+
317
+ /** The reply line as the gateway writes it; only the fields read below are named. */
318
+ interface GatewayReply {
319
+ id?: number;
320
+ status?: number;
321
+ body?: {
322
+ choices?: { message?: { content?: unknown; tool_calls?: unknown }; finish_reason?: unknown }[];
323
+ usage?: { prompt_tokens?: number; completion_tokens?: number };
324
+ };
325
+ }
326
+
327
+ function gatewayError(reason: string, detail: string): Error {
328
+ return Object.assign(new Error(`omp complete: ${detail}`), { reason });
329
+ }
330
+
331
+ /**
332
+ * One completion through the owner's omp gateway (plan P7 k): a fresh empty cwd, no MAIN_ENV, no tools,
333
+ * one request line. A reply that is not a 200 `stop` with plain text, or a non-zero exit, is an error that
334
+ * carries a `reason`. The temp cwd is removed on every path.
335
+ */
336
+ export async function ompComplete(req: CompleteRequest, opts: { spawn?: GatewaySpawn } = {}): Promise<CompleteResult> {
337
+ const run = opts.spawn ?? runGateway;
338
+ const cwd = mkdtempSync(join(tmpdir(), "omp-complete-"));
339
+ const env: NodeJS.ProcessEnv = Object.fromEntries(Object.entries(process.env).filter(([k]) => k !== MAIN_ENV));
340
+ const request = {
341
+ id: 1,
342
+ path: "/v1/chat/completions",
343
+ body: {
344
+ model: req.model,
345
+ max_tokens: req.maxTokens,
346
+ ...(req.effort ? { reasoning_effort: req.effort } : {}),
347
+ messages: [
348
+ { role: "system", content: req.system },
349
+ { role: "user", content: req.prompt },
350
+ ],
351
+ },
352
+ };
353
+ try {
354
+ const result = await run([OMP_BIN, "auth-gateway", "stdio"], { cwd, env, stdin: `${JSON.stringify(request)}\n` });
355
+ if (result.exitCode !== 0) throw gatewayError("exit-code", `exit ${result.exitCode}`);
356
+ const reply = result.stdout
357
+ .split("\n")
358
+ .flatMap(line => {
359
+ try {
360
+ return [JSON.parse(line) as GatewayReply];
361
+ } catch {
362
+ return [];
363
+ }
364
+ })
365
+ .find(r => r.id === 1);
366
+ if (reply === undefined) throw gatewayError("no-reply", "no reply with id 1");
367
+ if (reply.status !== 200) throw gatewayError(`status-${reply.status}`, `status ${reply.status}`);
368
+ const choice = reply.body?.choices?.[0];
369
+ if (choice?.finish_reason !== "stop") {
370
+ const code = typeof choice?.finish_reason === "string" ? choice.finish_reason.slice(0, 20) : "none";
371
+ throw gatewayError(`finish-reason:${code}`, "reply did not finish with stop");
372
+ }
373
+ const calls = choice.message?.tool_calls;
374
+ if (Array.isArray(calls) && calls.length > 0) throw gatewayError("tool-calls", "reply asked for tool calls");
375
+ const text = choice.message?.content;
376
+ if (typeof text !== "string") throw gatewayError("no-text", "reply has no text");
377
+ const usage = reply.body?.usage;
378
+ return {
379
+ text,
380
+ usage: { prompt_tokens: usage?.prompt_tokens ?? 0, completion_tokens: usage?.completion_tokens ?? 0 },
381
+ };
382
+ } finally {
383
+ rmSync(cwd, { recursive: true, force: true });
384
+ }
385
+ }
386
+
273
387
  /** Pre-multi-main relaunch request location; only read when mainId is `main`. */
274
388
  function legacyRelaunchPath(cfg: Config): string {
275
389
  return join(cfg.paths.queue_state, "rollover", "relaunch.json");
package/src/cli/recall.ts CHANGED
@@ -1,15 +1,17 @@
1
1
  // `neurastream recall`: searches the owner's messages and Main's answers (the recall log, see
2
2
  // core/owner-log.ts) and shows an entry with the entry it pairs with. Read-only.
3
3
 
4
- import { getAdapter } from "../adapters/index.ts";
4
+ import { getAdapter, ompComplete } from "../adapters/index.ts";
5
5
  import { nowSec } from "../core/clock.ts";
6
6
  import { ConfigError, loadConfig, type Config } from "../core/config.ts";
7
7
  import { helpDoc, printText } from "../core/help.ts";
8
8
  import { backfillOwnerLog, type LogEntry, searchEntries, showEntries } from "../core/owner-log.ts";
9
+ import { rangeEntries, runTopics, searchTopics, type Segment, type TopicsRun } from "../core/owner-topics.ts";
9
10
  import { applyQueueEnv } from "../core/queue/env.ts";
10
11
 
11
12
  const USAGE = "usage: neurastream recall <words>... [--since 7d|12h|YYYY-MM-DD] [--limit N] [--json]\n neurastream recall --show <id> [--json]";
12
13
  const BACKFILL_USAGE = "usage: neurastream recall backfill [--since 7d|12h|YYYY-MM-DD]";
14
+ const TOPICS_USAGE = "usage: neurastream recall topics [--close]";
13
15
  const DEFAULT_LIMIT = 20;
14
16
  const PREVIEW_CHARS = 160;
15
17
  const HOUR = 3600;
@@ -74,8 +76,15 @@ function preview(text: string): string {
74
76
  return flat.length > PREVIEW_CHARS ? `${flat.slice(0, PREVIEW_CHARS - 1)}…` : flat;
75
77
  }
76
78
 
77
- function jsonLine(e: LogEntry): string {
78
- return JSON.stringify({ at: e.at, id: e.id, role: e.role, text: e.text });
79
+ // `mixed` adds `kind` to the entry row: it is set only when the output also holds topic rows, so a
80
+ // search with no topic rows keeps its plain four-key shape.
81
+ function jsonLine(e: LogEntry, mixed = false): string {
82
+ const row = { at: e.at, id: e.id, role: e.role, text: e.text };
83
+ return JSON.stringify(mixed ? { kind: "entry", ...row } : row);
84
+ }
85
+
86
+ function topicJson(s: Segment): string {
87
+ return JSON.stringify({ kind: "topic", at: s.at, from: s.from, to: s.to, open: s.open, title: s.title });
79
88
  }
80
89
 
81
90
  // `recall backfill [--since ...]`: writes the session files' owner prompts and Main replies to the backfill
@@ -100,7 +109,25 @@ function backfillCli(args: string[], cfg: Config): number {
100
109
  return 0;
101
110
  }
102
111
 
103
- export function recallCli(args: string[], cfg: Config): number {
112
+ // `recall topics [--close]`: runs the topic layer over the owner log (one model call per window) and prints
113
+ // its lines. `--close` closes the open segment with no model call. Exit 0 unless a window failed.
114
+ async function topicsCli(args: string[], cfg: Config): Promise<number> {
115
+ if (args.some((a) => a !== "--close")) {
116
+ console.error(TOPICS_USAGE);
117
+ return 2;
118
+ }
119
+ try {
120
+ const run: TopicsRun = await runTopics(cfg, ompComplete, { close: args.includes("--close") });
121
+ for (const line of run.lines) console.log(line);
122
+ return run.failures === 0 ? 0 : 1;
123
+ } catch {
124
+ // The reason stays out of the output: an error message can carry the log's path.
125
+ console.log("topics: fail internal");
126
+ return 1;
127
+ }
128
+ }
129
+
130
+ export function recallCli(args: string[], cfg: Config): number | Promise<number> {
104
131
  if (args.includes("--help") || args.includes("-h")) {
105
132
  printText(helpDoc("recall"));
106
133
  return 0;
@@ -108,14 +135,16 @@ export function recallCli(args: string[], cfg: Config): number {
108
135
  // The log paths follow the queue state directory, so the config's queue env is applied first.
109
136
  applyQueueEnv(cfg);
110
137
  if (args[0] === "backfill") return backfillCli(args.slice(1), cfg);
138
+ if (args[0] === "topics") return topicsCli(args.slice(1), cfg);
111
139
  const parsed = parseArgs(args);
112
140
  if (typeof parsed === "string") {
113
141
  console.error(`${parsed}\n${USAGE}`);
114
142
  return 2;
115
143
  }
116
144
  if (parsed.show !== undefined) {
117
- const pair = showEntries(parsed.show);
118
- if (pair === undefined) {
145
+ const parts = parsed.show.split("..");
146
+ const pair = parts.length === 2 ? rangeEntries(parts[0]!, parts[1]!) : showEntries(parsed.show);
147
+ if (pair === undefined || pair.length === 0) {
119
148
  console.error(`no entry with id ${parsed.show}`);
120
149
  return 2;
121
150
  }
@@ -128,18 +157,25 @@ export function recallCli(args: string[], cfg: Config): number {
128
157
  console.error(USAGE);
129
158
  return 2;
130
159
  }
131
- const hits = searchEntries({ words: parsed.words, sinceSec: parsed.sinceSec, limit: parsed.limit });
132
- if (hits.length === 0) {
160
+ const topics = searchTopics(parsed.words)
161
+ .filter((s) => parsed.sinceSec === undefined || s.at >= parsed.sinceSec)
162
+ .slice(0, parsed.limit);
163
+ const left = parsed.limit - topics.length;
164
+ const hits = left > 0 ? searchEntries({ words: parsed.words, sinceSec: parsed.sinceSec, limit: left }) : [];
165
+ if (topics.length === 0 && hits.length === 0) {
133
166
  console.log("no match");
134
167
  return 1;
135
168
  }
169
+ for (const s of topics) {
170
+ console.log(parsed.json ? topicJson(s) : `${s.from}..${s.to} ${stamp(s.at)} topic ${s.title}`);
171
+ }
136
172
  for (const e of hits) {
137
- console.log(parsed.json ? jsonLine(e) : `${e.id} ${stamp(e.at)} ${e.role} ${preview(e.text)}`);
173
+ console.log(parsed.json ? jsonLine(e, topics.length > 0) : `${e.id} ${stamp(e.at)} ${e.role} ${preview(e.text)}`);
138
174
  }
139
175
  return 0;
140
176
  }
141
177
 
142
- export function runRecall(args: string[]): number {
178
+ export function runRecall(args: string[]): number | Promise<number> {
143
179
  let cfg: Config;
144
180
  try {
145
181
  cfg = loadConfig();
@@ -283,6 +283,8 @@ export interface Config {
283
283
  /** A second net on the wire: wrap the harness in `secretgate wrap --` at launch. */
284
284
  proxy: "none" | "secretgate";
285
285
  };
286
+ /** Owner topics (src/core/owner-topics.ts, plan P8): `topics_model` writes the owner-log topic index through the gateway ("" = off); `topics_effort` is the reasoning effort sent with each call ("" = none); a run starts every `topics_every` Main entries. */
287
+ recall: { topics_model: string; topics_effort: string; topics_every: number };
286
288
  /** Write-time lint checks (src/core/write-check.ts, plan 20261028_1228): an edit that adds a lint finding or a suppression comment is refused. */
287
289
  write_check: WriteCheckConfig;
288
290
  priority: { sleep_sec: number };
@@ -802,6 +804,9 @@ function check(cfg: Config): void {
802
804
  throw new ConfigError(`secrets.extra_patterns.${pattern.type}: not a valid regex: ${pattern.regex}`);
803
805
  }
804
806
  }
807
+ if (typeof cfg.recall.topics_model !== "string") throw new ConfigError('recall.topics_model must be a string ("" = off)');
808
+ if (typeof cfg.recall.topics_effort !== "string") throw new ConfigError('recall.topics_effort must be a string ("" = none)');
809
+ if (!Number.isInteger(cfg.recall.topics_every) || cfg.recall.topics_every < 1) throw new ConfigError("recall.topics_every must be an integer >= 1");
805
810
  for (const [key, value] of Object.entries(cfg.paths)) {
806
811
  if (key === "work_roots") {
807
812
  if (!Array.isArray(value) || value.some(v => typeof v !== "string")) {
@@ -42,14 +42,25 @@ export function newEntryId(atMs: number, rand: (n: number) => Uint8Array = rando
42
42
  }
43
43
 
44
44
  // The one writer: the recall dir is 0700 and the file 0600, also when they pre-exist looser.
45
- function appendLogLine(file: string, entry: LogEntry): void {
45
+ export function appendJsonLines(file: string, rows: readonly object[]): void {
46
46
  const dir = dirname(file);
47
47
  mkdirSync(dir, { recursive: true, mode: 0o700 });
48
48
  chmodSync(dir, 0o700);
49
- appendFileSync(file, `${JSON.stringify(entry)}\n`, { mode: 0o600 });
49
+ appendFileSync(file, rows.map((row) => `${JSON.stringify(row)}\n`).join(""), { mode: 0o600 });
50
50
  chmodSync(file, 0o600);
51
51
  }
52
52
 
53
+ // Entries appended in this process since the last topics spawn. The turn-end trigger reads it.
54
+ let appendedCount = 0;
55
+
56
+ export function appendedSinceSpawn(): number {
57
+ return appendedCount;
58
+ }
59
+
60
+ export function markTopicsSpawned(): void {
61
+ appendedCount = 0;
62
+ }
63
+
53
64
  export function appendOwnerLog(
54
65
  role: LogRole,
55
66
  text: string,
@@ -57,7 +68,8 @@ export function appendOwnerLog(
57
68
  ): string {
58
69
  const atMs = opts.atMs ?? nowSec() * 1000;
59
70
  const entry: LogEntry = { id: newEntryId(atMs, opts.rand), at: Math.floor(atMs / 1000), role, text };
60
- appendLogLine(ownerLogFile(), entry);
71
+ appendJsonLines(ownerLogFile(), [entry]);
72
+ appendedCount++;
61
73
  return entry.id;
62
74
  }
63
75
 
@@ -98,15 +110,15 @@ export function backfillOwnerLog(cfg: Config, turns: Iterable<OwnerTurn>): numbe
98
110
  const newest = logEdge(ownerBackfillFile(), true);
99
111
  const oldest = logEdge(ownerLogFile(), false);
100
112
  const known = loadKnownSecrets(cfg);
101
- let written = 0;
113
+ const rows: LogEntry[] = [];
102
114
  for (const turn of kept) {
103
115
  if (newest !== undefined && turn.at <= newest.at) continue;
104
116
  if (oldest !== undefined && turn.at >= oldest.at) continue;
105
117
  const clean = redactSecrets(turn.text, known, cfg.secrets.extra_patterns).text;
106
- appendLogLine(ownerBackfillFile(), { id: newEntryId(turn.at * 1000), at: turn.at, role: turn.role, text: clean });
107
- written++;
118
+ rows.push({ id: newEntryId(turn.at * 1000), at: turn.at, role: turn.role, text: clean });
108
119
  }
109
- return written;
120
+ if (rows.length > 0) appendJsonLines(ownerBackfillFile(), rows);
121
+ return rows.length;
110
122
  }
111
123
 
112
124
  const BLOCK = 64 * 1024;
@@ -0,0 +1,574 @@
1
+ // The topic index (plan 20261109_2335, P8): a model splits the recall log into consecutive segments of
2
+ // entry ids and appends them to owner-topics.jsonl. The log stays the source of truth: a segment only names
3
+ // a run of its ids, and topic text never reaches Main's prompt.
4
+
5
+ import { chmodSync, mkdirSync } from "node:fs";
6
+ import { join } from "node:path";
7
+ import { nowSec } from "./clock.ts";
8
+ import type { Config } from "./config.ts";
9
+ import { tryLock } from "./file-lock.ts";
10
+ import { appendJsonLines, type LogEntry, ownerLogDir, ownerLogFile, readEntries, readLines } from "./owner-log.ts";
11
+ import { loadKnownSecrets, redactSecrets } from "./secret-redact.ts";
12
+
13
+ export interface CompleteRequest {
14
+ model: string;
15
+ system: string;
16
+ prompt: string;
17
+ maxTokens: number;
18
+ /** Reasoning effort for the model ("" or absent = none). */
19
+ effort?: string;
20
+ }
21
+
22
+ export interface CompleteResult {
23
+ text: string;
24
+ usage: { prompt_tokens: number; completion_tokens: number };
25
+ }
26
+
27
+ export type Complete = (req: CompleteRequest) => Promise<CompleteResult>;
28
+
29
+ export interface Note {
30
+ id: string;
31
+ text: string;
32
+ }
33
+
34
+ // One segment as the model answers it.
35
+ export interface AnswerSegment {
36
+ from: string;
37
+ to: string;
38
+ title: string;
39
+ keywords: string[];
40
+ decisions: Note[];
41
+ questions: Note[];
42
+ names: string[];
43
+ continues: string | null;
44
+ }
45
+
46
+ // A segment as stored. The last segment of a run is open: the next run may re-cut it.
47
+ export interface Segment extends AnswerSegment {
48
+ at: number;
49
+ open: boolean;
50
+ }
51
+
52
+ // A window the model could not segment. It keeps its place in the log, so its entries are not retried.
53
+ export interface Skipped {
54
+ from: string;
55
+ to: string;
56
+ at: number;
57
+ skipped: true;
58
+ why: string;
59
+ }
60
+
61
+ export type TopicRow = Segment | Skipped;
62
+
63
+ export interface TopicsRun {
64
+ lines: string[];
65
+ failures: number;
66
+ }
67
+
68
+ interface Tally {
69
+ calls: number;
70
+ tokensIn: number;
71
+ tokensOut: number;
72
+ }
73
+
74
+ // A failure the caller prints: the reason code, and the byte sizes of the request and the answer.
75
+ interface Failure {
76
+ reason: string;
77
+ in: number;
78
+ out: number;
79
+ }
80
+
81
+ type Attempt =
82
+ | { kind: "ok" }
83
+ | { kind: "rejected"; reason: string; in: number; out: number }
84
+ | { kind: "error"; reason: string; in: number };
85
+
86
+ const TOPICS_FILE = "owner-topics.jsonl";
87
+ const TOPICS_LOG_FILE = "owner-topics.log";
88
+ const LOCK_FILE = "owner-topics.lock";
89
+ const WINDOW = 60;
90
+ const MAX_TOKENS = 16000;
91
+
92
+ const SYSTEM = [
93
+ "You split a chronological log of an owner's messages and the assistant's replies into topic segments.",
94
+ "Answer with one JSON object and nothing else. Entries are numbered [1], [2], ...; every id below is an entry number as a string:",
95
+ '{"segments":[{"from":"<entry number>","to":"<entry number>","title":"...","keywords":["..."],"decisions":[{"id":"<entry number>","text":"..."}],"questions":[{"id":"<owner entry number>","text":"..."}],"names":["..."],"continues":null}]}',
96
+ "Rules:",
97
+ "- The segments cover the log in order with no gaps and no overlaps; the last one ends at the last entry.",
98
+ "- from and to are entry numbers from the log. A segment that is not the last has 3 to 60 entries.",
99
+ "- title: at most 10 words. keywords: at most 6 words each. decision text: at most 60 words, and its id is an entry in the segment.",
100
+ "- questions: the owner's open questions, each with the id of an owner entry in the segment.",
101
+ "- Write in your own words. Never copy 8 or more words in a row from the log.",
102
+ "- continues: always null.",
103
+ ].join("\n");
104
+
105
+ export function topicsFile(): string {
106
+ return join(ownerLogDir(), TOPICS_FILE);
107
+ }
108
+
109
+ // stdout and stderr of the background `recall topics` run: stats and `topics: fail` lines only.
110
+ export function topicsLogFile(): string {
111
+ return join(ownerLogDir(), TOPICS_LOG_FILE);
112
+ }
113
+
114
+ export function topicsDue(count: number, every: number): boolean {
115
+ return count >= every;
116
+ }
117
+
118
+ function isStrings(v: unknown): v is string[] {
119
+ return Array.isArray(v) && v.every(s => typeof s === "string");
120
+ }
121
+
122
+ function isNotes(v: unknown): v is Note[] {
123
+ return (
124
+ Array.isArray(v) &&
125
+ v.every(n => {
126
+ const note = n as Partial<Note> | null;
127
+ return note !== null && typeof note === "object" && typeof note.id === "string" && typeof note.text === "string";
128
+ })
129
+ );
130
+ }
131
+
132
+ function isSegment(r: TopicRow): r is Segment {
133
+ return !("skipped" in r);
134
+ }
135
+
136
+ function parseRow(line: string): TopicRow | undefined {
137
+ let v: Partial<Segment & Skipped> | null;
138
+ try {
139
+ v = JSON.parse(line) as Partial<Segment & Skipped> | null;
140
+ } catch {
141
+ return undefined;
142
+ }
143
+ if (v === null || typeof v !== "object" || typeof v.from !== "string" || typeof v.to !== "string") return undefined;
144
+ if (typeof v.at !== "number") return undefined;
145
+ if (v.skipped === true) {
146
+ return { from: v.from, to: v.to, at: v.at, skipped: true, why: typeof v.why === "string" ? v.why : "" };
147
+ }
148
+ if (
149
+ typeof v.title !== "string" ||
150
+ typeof v.open !== "boolean" ||
151
+ !isStrings(v.keywords) ||
152
+ !isNotes(v.decisions) ||
153
+ !isNotes(v.questions) ||
154
+ !isStrings(v.names) ||
155
+ !(v.continues === null || typeof v.continues === "string")
156
+ ) {
157
+ return undefined;
158
+ }
159
+ return {
160
+ from: v.from,
161
+ to: v.to,
162
+ at: v.at,
163
+ open: v.open,
164
+ title: v.title,
165
+ keywords: v.keywords,
166
+ decisions: v.decisions,
167
+ questions: v.questions,
168
+ names: v.names,
169
+ continues: v.continues,
170
+ };
171
+ }
172
+
173
+ // The index as a reader sees it: file order, where a line replaces every earlier line that reaches into its
174
+ // ids (a re-cut of the open segment, or the closed copy that --close writes). Unparsable lines are skipped.
175
+ function effectiveRows(): TopicRow[] {
176
+ const out: TopicRow[] = [];
177
+ for (const line of [...readLines(topicsFile())].toReversed()) {
178
+ const row = parseRow(line);
179
+ if (row === undefined) continue;
180
+ while (out.length > 0 && out.at(-1)!.to >= row.from) out.pop();
181
+ out.push(row);
182
+ }
183
+ return out;
184
+ }
185
+
186
+ export function readTopics(): Segment[] {
187
+ return effectiveRows().filter(isSegment);
188
+ }
189
+
190
+ // The id the next window starts after: the last segment that is closed, or a skipped window.
191
+ function afterClosed(rows: TopicRow[]): string | undefined {
192
+ let to: string | undefined;
193
+ for (const r of rows) if (!(isSegment(r) && r.open)) to = r.to;
194
+ return to;
195
+ }
196
+
197
+ function wordCount(s: string): number {
198
+ return s.trim().split(/\s+/).filter(w => w !== "").length;
199
+ }
200
+
201
+ // The 8-word runs of a text, lowercased, with punctuation dropped: what the copy check compares.
202
+ function gramsOf(text: string): string[] {
203
+ const ws = text.toLowerCase().split(/[^\p{L}\p{N}]+/u).filter(w => w !== "");
204
+ const out: string[] = [];
205
+ for (let i = 0; i + 8 <= ws.length; i++) out.push(ws.slice(i, i + 8).join(" "));
206
+ return out;
207
+ }
208
+
209
+ // An earlier row as the checks read it: a closed segment, an open one, or a skipped window.
210
+ type Earlier = { from: string; to: string; open?: boolean; skipped?: boolean };
211
+
212
+ // Checks an answer against the window it segments. Returns null, or one message "name: detail" where name
213
+ // `entries` is the window, oldest first; `earlier` is the rows before it, the last one ending where it starts.
214
+ export function checkSegments(
215
+ segments: readonly AnswerSegment[],
216
+ entries: readonly LogEntry[],
217
+ earlier: readonly Earlier[],
218
+ ): string | null {
219
+ if (segments.length === 0) return "reach: no segments";
220
+ const index = new Map(entries.map((e, i) => [e.id, i]));
221
+ const seen = new Set<string>();
222
+ const last = earlier.at(-1);
223
+ const start = last === undefined ? 0 : (index.get(last.to) ?? -1) + 1;
224
+ for (const e of entries) for (const g of gramsOf(e.text)) seen.add(g);
225
+
226
+ let prevFrom = -1;
227
+ let prevTo = -1;
228
+ for (let i = 0; i < segments.length; i++) {
229
+ const s = segments[i]!;
230
+ const fi = index.get(s.from);
231
+ const ti = index.get(s.to);
232
+ if (fi === undefined) return `id: ${s.from} not in log`;
233
+ if (ti === undefined) return `id: ${s.to} not in log`;
234
+ if (fi > ti) return `order: segment ${s.from}..${s.to} ends before it starts`;
235
+ if (i === 0) {
236
+ if (fi > start) return `gap: entries before ${s.from} are not covered`;
237
+ if (fi < start) return `overlap: segment ${s.from} starts inside an earlier one`;
238
+ } else if (fi < prevFrom) {
239
+ return `order: segment ${s.from} is out of log order`;
240
+ } else if (fi <= prevTo) {
241
+ return `overlap: segment ${s.from} starts inside the previous one`;
242
+ } else if (fi > prevTo + 1) {
243
+ return `gap: entries after ${segments[i - 1]!.to} are not covered`;
244
+ }
245
+ const count = ti - fi + 1;
246
+ if (i < segments.length - 1 && count < 3) return `short: segment ${s.from}..${s.to} has fewer than 3 entries`;
247
+ if (count > 60) return `long: segment ${s.from}..${s.to} has more than 60 entries`;
248
+ if (wordCount(s.title) > 10) return "title: over 10 words";
249
+ for (const k of s.keywords) if (wordCount(k) > 6) return "keyword: over 6 words";
250
+ for (const d of s.decisions) {
251
+ if (wordCount(d.text) > 60) return "decision: over 60 words";
252
+ const di = index.get(d.id);
253
+ if (di === undefined || di < fi || di > ti) return `decision: id ${d.id} is outside its segment`;
254
+ }
255
+ for (const q of s.questions) {
256
+ const qi = index.get(q.id);
257
+ if (qi === undefined || qi < fi || qi > ti || entries[qi]!.role !== "owner") {
258
+ return `question: id ${q.id} is not an owner entry in its segment`;
259
+ }
260
+ }
261
+ for (const text of [s.title, ...s.decisions.map(d => d.text), ...s.questions.map(q => q.text)]) {
262
+ if (gramsOf(text).some(g => seen.has(g))) return "copy: 8 words copied in a row from an entry";
263
+ }
264
+ if (s.continues !== null && !earlier.some(e => e.open !== true && e.skipped !== true && e.from === s.continues)) {
265
+ return `continues: ${s.continues} is not an earlier closed segment`;
266
+ }
267
+ prevFrom = fi;
268
+ prevTo = ti;
269
+ }
270
+ if (index.get(segments.at(-1)!.to) !== entries.length - 1) return "reach: segments stop before the last entry";
271
+ return null;
272
+ }
273
+
274
+ // The answer's shape, checked field by field: the model's text is not trusted to carry the named type.
275
+ function shape(value: unknown): AnswerSegment[] | undefined {
276
+ const raw = (value as { segments?: unknown } | null)?.segments;
277
+ if (!Array.isArray(raw)) return undefined;
278
+ const out: AnswerSegment[] = [];
279
+ for (const item of raw) {
280
+ const s = item as Partial<AnswerSegment> | null;
281
+ if (
282
+ s === null ||
283
+ typeof s !== "object" ||
284
+ typeof s.from !== "string" ||
285
+ typeof s.to !== "string" ||
286
+ typeof s.title !== "string" ||
287
+ !isStrings(s.keywords) ||
288
+ !isNotes(s.decisions) ||
289
+ !isNotes(s.questions) ||
290
+ !isStrings(s.names) ||
291
+ !(s.continues === null || typeof s.continues === "string")
292
+ ) {
293
+ return undefined;
294
+ }
295
+ out.push({
296
+ from: s.from,
297
+ to: s.to,
298
+ title: s.title,
299
+ keywords: s.keywords,
300
+ decisions: s.decisions,
301
+ questions: s.questions,
302
+ names: s.names,
303
+ continues: s.continues,
304
+ });
305
+ }
306
+ return out;
307
+ }
308
+
309
+ type Parsed = { segments: AnswerSegment[] } | { reason: string };
310
+
311
+ function parseAnswer(text: string, window: readonly LogEntry[], earlier: readonly Earlier[]): Parsed {
312
+ let value: unknown;
313
+ try {
314
+ value = JSON.parse(text);
315
+ } catch {
316
+ return { reason: "bad-json" };
317
+ }
318
+ const shaped = shape(value);
319
+ if (shaped === undefined) return { reason: "check:shape" };
320
+ // The model sees entry numbers; a number the window has becomes its stored id, anything else is checked as is.
321
+ const idOf = (label: string): string => (/^[1-9]\d*$/.test(label) ? (window[Number(label) - 1]?.id ?? label) : label);
322
+ const segments = shaped.map(s => ({
323
+ ...s,
324
+ from: idOf(s.from),
325
+ to: idOf(s.to),
326
+ decisions: s.decisions.map(d => ({ ...d, id: idOf(d.id) })),
327
+ questions: s.questions.map(q => ({ ...q, id: idOf(q.id) })),
328
+ }));
329
+ // The model cuts short greeting stretches that the 3-entry rule forbids: a short non-last segment folds into the next.
330
+ const pos = new Map(window.map((e, i) => [e.id, i]));
331
+ const folded: AnswerSegment[] = [];
332
+ let carry: AnswerSegment | undefined;
333
+ for (const [i, s] of segments.entries()) {
334
+ const cur = carry
335
+ ? {
336
+ ...s,
337
+ from: carry.from,
338
+ keywords: [...carry.keywords, ...s.keywords],
339
+ decisions: [...carry.decisions, ...s.decisions],
340
+ questions: [...carry.questions, ...s.questions],
341
+ names: [...carry.names, ...s.names],
342
+ }
343
+ : s;
344
+ const a = pos.get(cur.from);
345
+ const b = pos.get(cur.to);
346
+ carry = i < segments.length - 1 && a !== undefined && b !== undefined && b >= a && b - a + 1 < 3 ? cur : undefined;
347
+ if (carry === undefined) folded.push(cur);
348
+ }
349
+ // A note whose id points outside its segment (or a question not on an owner entry) is dropped, not the window.
350
+ const clean = folded.map(s => {
351
+ const a = pos.get(s.from) ?? -1;
352
+ const b = pos.get(s.to) ?? -1;
353
+ const inside = (id: string): boolean => (pos.get(id) ?? -1) >= a && (pos.get(id) ?? -1) <= b && pos.has(id);
354
+ return {
355
+ ...s,
356
+ decisions: s.decisions.filter(d => inside(d.id)),
357
+ questions: s.questions.filter(q => inside(q.id) && window[pos.get(q.id)!]!.role === "owner"),
358
+ };
359
+ });
360
+ const err = checkSegments(clean, window, earlier);
361
+ return err === null ? { segments: clean } : { reason: `check:${err.slice(0, err.indexOf(":"))}` };
362
+ }
363
+
364
+ // A model error keeps its reason code; a timeout is named TimeoutError by the caller's spawn.
365
+ function failureReason(err: unknown): string {
366
+ if (err instanceof Error && err.name === "TimeoutError") return "timeout";
367
+ const reason = (err as { reason?: unknown } | null)?.reason;
368
+ return typeof reason === "string" && reason !== "" ? reason : "model-error";
369
+ }
370
+
371
+ function windowPrompt(window: readonly LogEntry[]): string {
372
+ return ["Log entries, oldest first:", ...window.map((e, i) => `[${i + 1}] (${e.role}) ${e.text}`)].join("\n");
373
+ }
374
+
375
+ // Redacts the model's text before it is written: the configured known secrets and extra patterns.
376
+ function appendSegments(cfg: Config, segments: readonly AnswerSegment[]): void {
377
+ const known = loadKnownSecrets(cfg);
378
+ const clean = (text: string): string => redactSecrets(text, known, cfg.secrets.extra_patterns).text;
379
+ const at = nowSec();
380
+ const rows: Segment[] = segments.map((s, i) => ({
381
+ from: s.from,
382
+ to: s.to,
383
+ at,
384
+ open: i === segments.length - 1,
385
+ title: clean(s.title),
386
+ keywords: s.keywords.map(clean),
387
+ decisions: s.decisions.map(d => ({ id: d.id, text: clean(d.text) })),
388
+ questions: s.questions.map(q => ({ id: q.id, text: clean(q.text) })),
389
+ names: s.names.map(clean),
390
+ continues: s.continues,
391
+ }));
392
+ appendJsonLines(topicsFile(), rows);
393
+ }
394
+
395
+ // One model call on the window. On a good answer the segments are appended; otherwise nothing is written.
396
+ async function attemptOnce(
397
+ cfg: Config,
398
+ complete: Complete,
399
+ window: readonly LogEntry[],
400
+ request: string,
401
+ earlier: readonly Earlier[],
402
+ tally: Tally,
403
+ ): Promise<Attempt> {
404
+ tally.calls++;
405
+ let answer: CompleteResult;
406
+ try {
407
+ answer = await complete({
408
+ model: cfg.recall.topics_model,
409
+ system: SYSTEM,
410
+ prompt: request,
411
+ maxTokens: MAX_TOKENS,
412
+ effort: cfg.recall.topics_effort,
413
+ });
414
+ } catch (err) {
415
+ return { kind: "error", reason: failureReason(err), in: Buffer.byteLength(request) };
416
+ }
417
+ tally.tokensIn += answer.usage.prompt_tokens;
418
+ tally.tokensOut += answer.usage.completion_tokens;
419
+ const parsed = parseAnswer(answer.text, window, earlier);
420
+ if ("segments" in parsed) {
421
+ appendSegments(cfg, parsed.segments);
422
+ return { kind: "ok" };
423
+ }
424
+ return { kind: "rejected", reason: parsed.reason, in: Buffer.byteLength(request), out: Buffer.byteLength(answer.text) };
425
+ }
426
+
427
+ // Segments one window and appends the result. A window whose answer is rejected twice is kept as one skipped
428
+ // line, so the next run starts after it. A model error is not retried and appends nothing.
429
+ async function segmentWindow(
430
+ cfg: Config,
431
+ complete: Complete,
432
+ window: readonly LogEntry[],
433
+ rows: TopicRow[],
434
+ tally: Tally,
435
+ ): Promise<Failure | undefined> {
436
+ const earlier = rows.filter(r => !(isSegment(r) && r.open));
437
+ const prompt = windowPrompt(window);
438
+ const first = await attemptOnce(cfg, complete, window, prompt, earlier, tally);
439
+ if (first.kind === "ok") return undefined;
440
+ if (first.kind === "error") return { reason: first.reason, in: first.in, out: 0 };
441
+ const retry = `${prompt}\n\nYour answer was rejected (${first.reason}). Answer again with only the JSON object, following every rule.`;
442
+ const second = await attemptOnce(cfg, complete, window, retry, earlier, tally);
443
+ if (second.kind === "ok") return undefined;
444
+ if (second.kind === "error") return { reason: second.reason, in: second.in, out: 0 };
445
+ appendJsonLines(topicsFile(), [
446
+ { from: window[0]!.id, to: window.at(-1)!.id, at: nowSec(), skipped: true, why: second.reason },
447
+ ]);
448
+ return { reason: second.reason, in: second.in, out: second.out };
449
+ }
450
+
451
+ // `--close`: the open segment becomes closed (a copy with open:false), so the next window starts after it.
452
+ function closeOpen(): void {
453
+ const last = effectiveRows().at(-1);
454
+ if (last !== undefined && isSegment(last) && last.open) appendJsonLines(topicsFile(), [{ ...last, open: false }]);
455
+ }
456
+
457
+ function oldestFirst(): LogEntry[] {
458
+ return [...readEntries()].toReversed();
459
+ }
460
+
461
+ // The entries after `afterId`, oldest first. No id means every entry.
462
+ export function newEntries(afterId?: string): LogEntry[] {
463
+ const all = oldestFirst();
464
+ if (afterId === undefined) return all;
465
+ const i = all.findIndex(e => e.id === afterId);
466
+ return i < 0 ? all : all.slice(i + 1);
467
+ }
468
+
469
+ // The entries from `from` to `to`, both inclusive, oldest first. Empty when either id is missing.
470
+ export function rangeEntries(from: string, to: string): LogEntry[] {
471
+ const all = oldestFirst();
472
+ const a = all.findIndex(e => e.id === from);
473
+ const b = all.findIndex(e => e.id === to);
474
+ return a < 0 || b < 0 || b < a ? [] : all.slice(a, b + 1);
475
+ }
476
+
477
+ // Topics whose text holds every word (case-insensitive, any order), in file order.
478
+ export function searchTopics(query: readonly string[]): Segment[] {
479
+ const want = query.map(w => w.toLowerCase());
480
+ return readTopics().filter(s => {
481
+ const hay = [s.title, ...s.keywords, ...s.decisions.map(d => d.text), ...s.questions.map(q => q.text), ...s.names]
482
+ .join(" ")
483
+ .toLowerCase();
484
+ return want.every(w => hay.includes(w));
485
+ });
486
+ }
487
+
488
+ function percentile(sorted: number[], p: number): number {
489
+ return sorted[Math.min(sorted.length - 1, Math.max(0, Math.ceil(p * sorted.length) - 1))]!;
490
+ }
491
+
492
+ function spread(values: number[]): { mean: number; median: number; p90: number; min: number; max: number } {
493
+ const sorted = values.toSorted((a, b) => a - b);
494
+ if (sorted.length === 0) return { mean: 0, median: 0, p90: 0, min: 0, max: 0 };
495
+ return {
496
+ mean: sorted.reduce((a, b) => a + b, 0) / sorted.length,
497
+ median: percentile(sorted, 0.5),
498
+ p90: percentile(sorted, 0.9),
499
+ min: sorted[0]!,
500
+ max: sorted.at(-1)!,
501
+ };
502
+ }
503
+
504
+ // The ids of the live log file (not the backfill): a segment's lag is measured only where its `to` is live.
505
+ function liveIds(): Set<string> {
506
+ const ids = new Set<string>();
507
+ for (const line of readLines(ownerLogFile())) {
508
+ try {
509
+ const e = JSON.parse(line) as Partial<LogEntry>;
510
+ if (typeof e.id === "string") ids.add(e.id);
511
+ } catch {
512
+ // A torn line is skipped, as the reader skips it.
513
+ }
514
+ }
515
+ return ids;
516
+ }
517
+
518
+ // The one stats line every run ends with. Counts come from the index as it stands; tokens and calls are
519
+ // this run's. Lag is the age, in hours, of each segment's `to` entry, for the segments whose `to` is live.
520
+ function statsLine(tally: Tally): string {
521
+ const rows = effectiveRows();
522
+ const segments = rows.filter(isSegment);
523
+ const skipped = rows.length - segments.length;
524
+ const all = oldestFirst();
525
+ const byId = new Map(all.map((e, index) => [e.id, { index, at: e.at }]));
526
+ const counts = segments.flatMap(s => {
527
+ const a = byId.get(s.from);
528
+ const b = byId.get(s.to);
529
+ return a !== undefined && b !== undefined && b.index >= a.index ? [b.index - a.index + 1] : [];
530
+ });
531
+ const live = liveIds();
532
+ const lags = segments.flatMap(s => {
533
+ const b = byId.get(s.to);
534
+ return b !== undefined && live.has(s.to) ? [(nowSec() - b.at) / 3600] : [];
535
+ });
536
+ const perTopic = spread(counts);
537
+ const days = all.length > 0 ? (all.at(-1)!.at - all[0]!.at) / 86400 : 0;
538
+ const perDay = segments.length / Math.max(1, days);
539
+ const lag = spread(lags);
540
+ const lagText = lags.length === 0 ? "lag n/a" : `lag median ${lag.median.toFixed(1)}h p90 ${lag.p90.toFixed(1)}h`;
541
+ const entries = counts.reduce((a, b) => a + b, 0);
542
+ return `topics: segments ${segments.length} | entries ${entries} | entries per topic mean ${perTopic.mean.toFixed(1)} median ${perTopic.median} p90 ${perTopic.p90} min ${perTopic.min} max ${perTopic.max} | segments per day ${perDay.toFixed(1)} | ${lagText} | tokens in ${tally.tokensIn} out ${tally.tokensOut} | calls ${tally.calls} | skipped ${skipped}`;
543
+ }
544
+
545
+ // One topic run under the lock: segments the next window of new entries, then prints the stats line. With
546
+ // `close`, closes the open segment instead (no model call). Model errors append nothing; the caller prints
547
+ // the lines and exits by `failures`.
548
+ export async function runTopics(cfg: Config, complete: Complete, opts: { close: boolean }): Promise<TopicsRun> {
549
+ if (!opts.close && cfg.recall.topics_model === "") return { lines: ["topics: off"], failures: 0 };
550
+ const dir = ownerLogDir();
551
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
552
+ chmodSync(dir, 0o700);
553
+ const lock = tryLock(join(dir, LOCK_FILE));
554
+ chmodSync(join(dir, LOCK_FILE), 0o600);
555
+ if (lock === null) return { lines: ["topics: another run holds the lock"], failures: 0 };
556
+ try {
557
+ const tally: Tally = { calls: 0, tokensIn: 0, tokensOut: 0 };
558
+ if (opts.close) {
559
+ closeOpen();
560
+ return { lines: [statsLine(tally)], failures: 0 };
561
+ }
562
+ const rows = effectiveRows();
563
+ const window = newEntries(afterClosed(rows)).slice(0, WINDOW);
564
+ if (window.length === 0) return { lines: [statsLine(tally)], failures: 0 };
565
+ const failed = await segmentWindow(cfg, complete, window, rows, tally);
566
+ const lines = failed
567
+ ? [`topics: fail ${window[0]!.id}..${window.at(-1)!.id} ${failed.reason} in=${failed.in} out=${failed.out}`]
568
+ : [];
569
+ lines.push(statsLine(tally));
570
+ return { lines, failures: failed ? 1 : 0 };
571
+ } finally {
572
+ lock.release();
573
+ }
574
+ }
@@ -268,6 +268,11 @@ secrets: # content redaction (src/core/secret-redact.ts); a
268
268
  extra_patterns: [] # your own shapes, e.g. [{type: "my-token", regex: "myapp_[A-Za-z0-9]{32}"}]
269
269
  proxy: "none" # "none" | "secretgate": launch the harness as `secretgate wrap -- omp` (README: Secrets)
270
270
 
271
+ recall: # owner topics (src/core/owner-topics.ts, plan P8): a topic index over the owner log
272
+ topics_model: "" # gateway model that writes the topics; "" = off, e.g. "anthropic/claude-haiku-5-5"
273
+ topics_effort: "xhigh" # reasoning effort sent with each topics call (reasoning_effort); "" = none; the gateway ignores it for a model without thinking
274
+ topics_every: 30 # Main owner-log entries between background topic runs; provisional until measured on the backfill
275
+
271
276
  write_check: # write-time lint checks (src/core/write-check.ts): an edit that adds a lint finding or suppression comment is undone and the agent is told why
272
277
  enabled: false # on = check every edit; off in the shipped template
273
278
  applies_to: sub # "sub" = subagents only; "all" = Main too
@@ -7,6 +7,11 @@ Usage: recall --show <id> [--json]
7
7
  Shows the entry with that id and its pair: an owner message with the nearest newer Main
8
8
  answer, or a Main answer with the nearest older owner message. Chronological order.
9
9
  --json prints one JSON object per line with the keys at, id, role, text.
10
+ `--show a..b` prints the entries from id a to id b instead, both ids in the log.
11
+ Usage: recall topics [--close]
12
+ Runs the topic index over the owner log: one model call per window through `recall.topics_model`
13
+ (empty = off). `--close` also closes the open segment with no model call. Prints `topics:` lines.
14
+ The word `topics` alone runs this, not a search. Exit: 0 ok, 1 a window failed, 2 bad arguments.
10
15
  Usage: recall backfill [--since 7d|12h|YYYY-MM-DD]
11
16
  Reads the harness's session files once and logs every owner message and Main answer from before the
12
17
  live log began (secrets redacted). A second run adds nothing. Prints `backfill: <n> entries`.