neurastream 0.3.3 → 0.3.5

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
@@ -338,6 +338,17 @@ A team queue shares one plan queue between the members of a team, through a serv
338
338
  - Share cap: `teams[].max_share` (above 0, at most 1) caps the team's share of today's model calls. This is a soft rule. The spawn log is not locked, so concurrent spawns can overshoot the cap. When a team sets `max_share`, a spawn without a name is refused so its calls count against the cap; that refusal is not covered by a test yet.
339
339
  - Cross review is soft too: it checks only the last claimer, so handing a claim to another member lets the same person claim and approve.
340
340
 
341
+ ## Recall
342
+
343
+ Every owner message and every Main answer is kept word for word in one append-only log, so a question or decision from a month ago is one command away.
344
+
345
+ - Logged: the owner's words (not guard output, system notices, task results or a handoff wrapper) and Main's answer to each; entries from sessions before this feature come from `neurastream recall backfill`.
346
+ - Not logged: tool calls and results, subagent output, anything Main never said to the owner.
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
+ - 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
+ - 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.
351
+
341
352
  ## Secrets never reach the chat
342
353
 
343
354
  A value the machine holds is hidden before the model, the chat and the session log see it (`src/core/secret-redact.ts`, plan 20261025_2204, incident I-20261025-197). Detection is by **content**, not by file name — the old name list never knew about `~/.npmrc`.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "neurastream",
3
- "version": "0.3.3",
3
+ "version": "0.3.5",
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",
@@ -3,13 +3,14 @@
3
3
  // is one folder under src/adapters plus one entry in ADAPTERS below — zero core changes
4
4
  // (docs/adapter.md, "Adding a harness").
5
5
 
6
- import type { DumpRef, LaunchOptions, RelatedTrace, RunSource, TaskResult, TraceRun, TraceSource } from "../core/adapter.ts";
6
+ import type { DumpRef, LaunchOptions, OwnerTurn, RelatedTrace, RunSource, TaskResult, TraceRun, TraceSource } from "../core/adapter.ts";
7
7
  import type { Config } from "../core/config.ts";
8
8
  import type { ProviderStatus } from "../core/provider-state.ts";
9
9
  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;
@@ -17,6 +18,8 @@ export interface HarnessAdapter {
17
18
  bin: string;
18
19
  /** Session reader: the runs and the main session (docs/adapter.md). */
19
20
  runSource(cfg: Config): RunSource;
21
+ /** Owner prompts and Main replies in the session files at or after the epoch second `since` (the recall backfill, plan 20261109_2335 P3). */
22
+ ownerTurns(cfg: Config, since: number): OwnerTurn[];
20
23
  /** Completed subagent task-results announced in the newest main session file. */
21
24
  completedResults(cfg: Config): TaskResult[];
22
25
  /** TraceSource for agent-score, over the config's sessions root. */
@@ -6,13 +6,14 @@ import { runDoctor } from "./doctor.ts";
6
6
  import { ompProviders } from "./providers.ts";
7
7
  import { runAdapterInstall } from "./install.ts";
8
8
  import { runMainLauncher } from "./launch.ts";
9
- import { defaultCompletedResults, defaultRunSource } from "./sessions.ts";
9
+ import { defaultCompletedResults, defaultOwnerTurns, defaultRunSource } from "./sessions.ts";
10
10
  import { dumpModel, dumpParts, dumpPromptTokens, ompDumps, ompEpisodes, ompScoreTraces, ompTraceRuns, ompTraceSource, ompTraceStart, spawnBriefsIn, subagentTraces } from "./traces.ts";
11
11
 
12
12
  export const ompAdapter: HarnessAdapter = {
13
13
  name: "omp",
14
14
  bin: "omp",
15
15
  runSource: defaultRunSource,
16
+ ownerTurns: defaultOwnerTurns,
16
17
  completedResults: defaultCompletedResults,
17
18
  scoreTraces: ompScoreTraces,
18
19
  traceRuns: ompTraceRuns,
@@ -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,6 +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 { appendedSinceSpawn, markTopicsSpawned, ownerLogDir, recordOwnerLog } from "../../core/owner-log.ts";
34
+ import { topicsDue, topicsLogFile } from "../../core/owner-topics.ts";
33
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";
34
36
  import { rateLimited } from "../../core/rate-limit.ts";
35
37
  import { backPost, clearLimitState, limitMetric, limitedPost, onLimited, readLimitState, timingOf, writeLimitState } from "../../core/limit-probe.ts";
@@ -454,6 +456,30 @@ function isMain(ctx: unknown): boolean {
454
456
  return !c.hasAgent || c.kind === "main";
455
457
  }
456
458
 
459
+ // Owner topics (plan P8): one detached, niced `recall` child, as the limit probe is. The child env drops
460
+ // MAIN_ENV so the child is not Main. Its stdout and stderr append to owner-topics.log (stats and `topics: fail`
461
+ // lines only). A context that injects `spawnTopics` (tests) gets the call instead.
462
+ function spawnTopics(cfg: Config, ctx: unknown, args: string[]): void {
463
+ const env: NodeJS.ProcessEnv = Object.fromEntries(Object.entries(process.env).filter(([k]) => k !== MAIN_ENV));
464
+ const injected = asRecord(ctx).spawnTopics;
465
+ if (typeof injected === "function") {
466
+ (injected as (a: string[], e: NodeJS.ProcessEnv) => void).call(ctx, args, env);
467
+ return;
468
+ }
469
+ let out: number | undefined;
470
+ try {
471
+ mkdirSync(ownerLogDir(), { recursive: true, mode: 0o700 });
472
+ out = openSync(topicsLogFile(), "a", 0o600);
473
+ const child = spawn("nice", ["-n", "19", "bun", join(import.meta.dir, "../../cli/main.ts"), ...args], { detached: true, stdio: ["ignore", out, out], env });
474
+ child.on("error", err => adapterLog(cfg, `OWNER-TOPICS: could not start: ${err.message}`));
475
+ child.unref();
476
+ } catch (err) {
477
+ adapterLog(cfg, `OWNER-TOPICS: could not start: ${err instanceof Error ? err.message : String(err)}`);
478
+ } finally {
479
+ if (out !== undefined) closeSync(out);
480
+ }
481
+ }
482
+
457
483
  function mtimeOf(path: string): number | null {
458
484
  try {
459
485
  return statSync(path).mtimeMs;
@@ -753,6 +779,11 @@ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig
753
779
  // blocked and mid-run ends are not turn ends: nothing is recorded.
754
780
  const recordTurnAnswer = (reply: EventReply | null): void => {
755
781
  if (!reply?.text) return;
782
+ try {
783
+ recordOwnerLog(cfg, "main", reply.text);
784
+ } catch (err) {
785
+ adapterLog(cfg, `RECALL-LOG record failed: ${err instanceof Error ? err.message : String(err)}`);
786
+ }
756
787
  try {
757
788
  appendOwnerAnswer(reply.text);
758
789
  } catch (err) {
@@ -1658,6 +1689,17 @@ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig
1658
1689
  if (note) pendingReviewNotes.push(note);
1659
1690
  });
1660
1691
 
1692
+ pi.on("agent_end", (_e, ctx) => {
1693
+ if (!isMain(ctx) || cfg.recall.topics_model === "") return;
1694
+ if (!topicsDue(appendedSinceSpawn(), cfg.recall.topics_every)) return;
1695
+ markTopicsSpawned();
1696
+ spawnTopics(cfg, ctx, ["recall", "topics"]);
1697
+ });
1698
+ pi.on("session_shutdown", (_e, ctx) => {
1699
+ if (!isMain(ctx) || cfg.recall.topics_model === "") return;
1700
+ spawnTopics(cfg, ctx, ["recall", "topics", "--close"]);
1701
+ });
1702
+
1661
1703
  // omp is really shutting down: the exit-grace fallback must not fire. A clean shutdown is also
1662
1704
  // the owner's last stamp (P2 d): verify first, then record the state that pass confirmed.
1663
1705
  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,114 @@ 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
+ messages: [
347
+ { role: "system", content: req.system },
348
+ { role: "user", content: req.prompt },
349
+ ],
350
+ },
351
+ };
352
+ try {
353
+ const result = await run([OMP_BIN, "auth-gateway", "stdio"], { cwd, env, stdin: `${JSON.stringify(request)}\n` });
354
+ if (result.exitCode !== 0) throw gatewayError("exit-code", `exit ${result.exitCode}`);
355
+ const reply = result.stdout
356
+ .split("\n")
357
+ .flatMap(line => {
358
+ try {
359
+ return [JSON.parse(line) as GatewayReply];
360
+ } catch {
361
+ return [];
362
+ }
363
+ })
364
+ .find(r => r.id === 1);
365
+ if (reply === undefined) throw gatewayError("no-reply", "no reply with id 1");
366
+ if (reply.status !== 200) throw gatewayError(`status-${reply.status}`, `status ${reply.status}`);
367
+ const choice = reply.body?.choices?.[0];
368
+ if (choice?.finish_reason !== "stop") throw gatewayError("finish-reason", "reply did not finish with stop");
369
+ const calls = choice.message?.tool_calls;
370
+ if (Array.isArray(calls) && calls.length > 0) throw gatewayError("tool-calls", "reply asked for tool calls");
371
+ const text = choice.message?.content;
372
+ if (typeof text !== "string") throw gatewayError("no-text", "reply has no text");
373
+ const usage = reply.body?.usage;
374
+ return {
375
+ text,
376
+ usage: { prompt_tokens: usage?.prompt_tokens ?? 0, completion_tokens: usage?.completion_tokens ?? 0 },
377
+ };
378
+ } finally {
379
+ rmSync(cwd, { recursive: true, force: true });
380
+ }
381
+ }
382
+
273
383
  /** Pre-multi-main relaunch request location; only read when mainId is `main`. */
274
384
  function legacyRelaunchPath(cfg: Config): string {
275
385
  return join(cfg.paths.queue_state, "rollover", "relaunch.json");
@@ -1,10 +1,11 @@
1
1
  import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
2
2
  import { basename, dirname, join } from "node:path";
3
3
  import type { Config } from "../../core/config.ts";
4
- import type { MainSession, Run, RunMessage, RunSource, RunStatus, TaskResult } from "../../core/adapter.ts";
4
+ import type { MainSession, OwnerTurn, Run, RunMessage, RunSource, RunStatus, TaskResult } from "../../core/adapter.ts";
5
5
  import { bootSec, nowSec } from "../../core/clock.ts";
6
6
  import { readBudgets } from "../../core/guards.ts";
7
7
  import { pyDumps } from "../../core/pyjson.ts";
8
+ import { readLines } from "../../core/owner-log.ts";
8
9
 
9
10
  function walk(dir: string, depth: number, out: string[]): void {
10
11
  if (depth < 0 || !existsSync(dir)) return;
@@ -376,8 +377,74 @@ export function ompRunSource(root: string, cfg: Config): RunSource {
376
377
  }
377
378
 
378
379
  export function defaultRunSource(cfg: Config): RunSource {
379
- const root = cfg.adapter?.sessions || join(cfg.paths.home, ".omp", "agent", "sessions");
380
- return ompRunSource(root, cfg);
380
+ return ompRunSource(cfg.adapter?.sessions || join(cfg.paths.home, ".omp", "agent", "sessions"), cfg);
381
+ }
382
+
383
+ /** The text of a user message: a string, or the text parts joined. */
384
+ function userText(content: unknown): string {
385
+ if (typeof content === "string") return content;
386
+ if (!Array.isArray(content)) return "";
387
+ return content
388
+ .map(p => asObj(p))
389
+ .filter((p): p is Record<string, unknown> => p !== null && typeof p.text === "string")
390
+ .map(p => p.text as string)
391
+ .join(" ");
392
+ }
393
+
394
+ /** A Main reply's text, or null when it is not one: no text parts, or a tool call in it. */
395
+ function replyText(message: Record<string, unknown>): string | null {
396
+ if (!Array.isArray(message.content)) return null;
397
+ const parts = message.content.map(p => asObj(p));
398
+ if (parts.some(p => p?.type === "toolCall")) return null;
399
+ const text = parts
400
+ .filter((p): p is Record<string, unknown> => p !== null && p.type === "text" && typeof p.text === "string")
401
+ .map(p => p.text as string)
402
+ .join("\n")
403
+ .trim();
404
+ return text || null;
405
+ }
406
+
407
+ /** The owner's prompts and Main's replies in the depth-1 session files, at or after the epoch second `since` (plan 20261109_2335 P3). Each file is read newest line first, so a reply is the last text message before the next user line; a message with a tool call, or one that did not stop, is not a reply, as on the live path. Unparsable lines are skipped. */
408
+ export function ompOwnerTurns(root: string, since: number): OwnerTurn[] {
409
+ const out: OwnerTurn[] = [];
410
+ for (const file of jsonlAt(root, 1)) {
411
+ let mtime: number;
412
+ try {
413
+ mtime = statSync(file).mtimeMs / 1000;
414
+ } catch {
415
+ continue;
416
+ }
417
+ if (mtime < since) continue;
418
+ let reply: { at: number; text: string } | undefined;
419
+ for (const line of readLines(file)) {
420
+ let obj: Record<string, unknown> | null;
421
+ try {
422
+ obj = asObj(JSON.parse(line) as unknown);
423
+ } catch {
424
+ continue;
425
+ }
426
+ const message = obj ? asObj(obj.message) : null;
427
+ const at = obj && typeof obj.timestamp === "string" ? parseTs(obj.timestamp) : null;
428
+ if (!message || at === null) continue;
429
+ if (message.role === "assistant") {
430
+ if (reply === undefined && message.stopReason === "stop") {
431
+ const text = replyText(message);
432
+ if (text) reply = { at, text };
433
+ }
434
+ continue;
435
+ }
436
+ if (message.role !== "user") continue;
437
+ const prompt = userText(message.content).trim();
438
+ if (prompt && at >= since) out.push({ at, role: "owner", text: prompt });
439
+ if (reply && reply.at >= since) out.push({ at: reply.at, role: "main", text: reply.text });
440
+ reply = undefined;
441
+ }
442
+ }
443
+ return out;
444
+ }
445
+
446
+ export function defaultOwnerTurns(cfg: Config, since: number): OwnerTurn[] {
447
+ return ompOwnerTurns(cfg.adapter?.sessions || join(cfg.paths.home, ".omp", "agent", "sessions"), since);
381
448
  }
382
449
 
383
450
  /**
@@ -5,6 +5,7 @@ import { ConfigError, configFile, loadConfig, type Config } from "../core/config
5
5
  import { beat, withHeartbeat } from "../core/heartbeat.ts";
6
6
  import { helpDoc } from "../core/help.ts";
7
7
  import { watchOnce, systemUnitLister, watchDoctorLine, watchHealth, timerStaffedPlans } from "../core/watch.ts";
8
+ import { runRecall } from "./recall.ts";
8
9
  import { defaultGather } from "../core/main-start.ts";
9
10
  import { gatherReleaseTags } from "../core/results.ts";
10
11
  import { nowSec } from "../core/clock.ts";
@@ -83,6 +84,10 @@ export function helpText(): string {
83
84
  " neurastream notify test post a test message to the configured Discord/Slack webhooks",
84
85
  " neurastream redact filter stdin through the secret redactor: stdout gets the text,",
85
86
  " stderr the hit summary (types and counts only)",
87
+ " neurastream recall <words>... [--since 7d|12h|YYYY-MM-DD] [--limit N] [--json]",
88
+ " search the owner's messages and Main's answers",
89
+ " neurastream recall --show <id> [--json]",
90
+ " show an entry with the entry it pairs with",
86
91
  " neurastream queue migrate fold the old repo INDEX.md files into the one main index",
87
92
  " neurastream claim next|list|release <plan> [--force]",
88
93
  " claim the highest free plan for this Main, list the holders,",
@@ -206,6 +211,7 @@ export async function run(cmd: string, args: string[]): Promise<number> {
206
211
  }
207
212
  if (cmd === "notify") return runNotify(args);
208
213
  if (cmd === "redact") return runRedact(args);
214
+ if (cmd === "recall") return runRecall(args);
209
215
  // Hidden: not in helpText. Beats once — the live check (plan P8) and the owner's own cron jobs.
210
216
  if (cmd === "heartbeat") {
211
217
  const failIdx = args.indexOf("--fail");
@@ -0,0 +1,187 @@
1
+ // `neurastream recall`: searches the owner's messages and Main's answers (the recall log, see
2
+ // core/owner-log.ts) and shows an entry with the entry it pairs with. Read-only.
3
+
4
+ import { getAdapter, ompComplete } from "../adapters/index.ts";
5
+ import { nowSec } from "../core/clock.ts";
6
+ import { ConfigError, loadConfig, type Config } from "../core/config.ts";
7
+ import { helpDoc, printText } from "../core/help.ts";
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";
10
+ import { applyQueueEnv } from "../core/queue/env.ts";
11
+
12
+ const USAGE = "usage: neurastream recall <words>... [--since 7d|12h|YYYY-MM-DD] [--limit N] [--json]\n neurastream recall --show <id> [--json]";
13
+ const BACKFILL_USAGE = "usage: neurastream recall backfill [--since 7d|12h|YYYY-MM-DD]";
14
+ const TOPICS_USAGE = "usage: neurastream recall topics [--close]";
15
+ const DEFAULT_LIMIT = 20;
16
+ const PREVIEW_CHARS = 160;
17
+ const HOUR = 3600;
18
+ const DAY = 86400;
19
+
20
+ interface Opts {
21
+ words: string[];
22
+ show?: string;
23
+ sinceSec?: number;
24
+ limit: number;
25
+ json: boolean;
26
+ }
27
+
28
+ // The earliest epoch second a --since value admits: a relative 7d or 12h, or a date.
29
+ function sinceAt(text: string, now: number): number | undefined {
30
+ const m = /^(\d+)([hd])$/.exec(text);
31
+ if (m) return now - Number(m[1]) * (m[2] === "d" ? DAY : HOUR);
32
+ const ms = Date.parse(text);
33
+ return Number.isNaN(ms) ? undefined : ms / 1000;
34
+ }
35
+
36
+ // A usage problem comes back as its message; the caller prints it with USAGE.
37
+ function parseArgs(args: string[]): Opts | string {
38
+ const opts: Opts = { words: [], limit: DEFAULT_LIMIT, json: false };
39
+ let since: string | undefined;
40
+ for (let i = 0; i < args.length; i++) {
41
+ const a = args[i]!;
42
+ if (a === "--json") {
43
+ opts.json = true;
44
+ } else if (a === "--show" || a === "--since" || a === "--limit") {
45
+ const v = args[++i];
46
+ if (v === undefined) return `${a} needs a value`;
47
+ if (a === "--show") {
48
+ opts.show = v;
49
+ } else if (a === "--since") {
50
+ since = v;
51
+ } else {
52
+ const n = Number(v);
53
+ if (!Number.isInteger(n) || n < 1) return "--limit needs a whole number of 1 or more";
54
+ opts.limit = n;
55
+ }
56
+ } else if (a.startsWith("--")) {
57
+ return `unknown flag ${a}`;
58
+ } else {
59
+ opts.words.push(a);
60
+ }
61
+ }
62
+ if (since !== undefined) {
63
+ opts.sinceSec = sinceAt(since, nowSec());
64
+ if (opts.sinceSec === undefined) return `--since takes 7d, 12h or a date (YYYY-MM-DD), not ${since}`;
65
+ }
66
+ return opts;
67
+ }
68
+
69
+ // Times are shown in UTC, minute precision.
70
+ function stamp(at: number): string {
71
+ return new Date(at * 1000).toISOString().slice(0, 16).replace("T", " ");
72
+ }
73
+
74
+ function preview(text: string): string {
75
+ const flat = text.replace(/\s+/g, " ").trim();
76
+ return flat.length > PREVIEW_CHARS ? `${flat.slice(0, PREVIEW_CHARS - 1)}…` : flat;
77
+ }
78
+
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 });
88
+ }
89
+
90
+ // `recall backfill [--since ...]`: writes the session files' owner prompts and Main replies to the backfill
91
+ // file, once. Reads the session files only; no model call.
92
+ function backfillCli(args: string[], cfg: Config): number {
93
+ let since = 0;
94
+ if (args.length > 0) {
95
+ const value = args[1];
96
+ if (args.length !== 2 || args[0] !== "--since" || value === undefined) {
97
+ console.error(BACKFILL_USAGE);
98
+ return 2;
99
+ }
100
+ const at = sinceAt(value, nowSec());
101
+ if (at === undefined) {
102
+ console.error(`--since takes 7d, 12h or a date (YYYY-MM-DD), not ${value}\n${BACKFILL_USAGE}`);
103
+ return 2;
104
+ }
105
+ since = at;
106
+ }
107
+ const written = backfillOwnerLog(cfg, getAdapter(cfg).ownerTurns(cfg, since));
108
+ console.log(`backfill: ${written} entries`);
109
+ return 0;
110
+ }
111
+
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> {
131
+ if (args.includes("--help") || args.includes("-h")) {
132
+ printText(helpDoc("recall"));
133
+ return 0;
134
+ }
135
+ // The log paths follow the queue state directory, so the config's queue env is applied first.
136
+ applyQueueEnv(cfg);
137
+ if (args[0] === "backfill") return backfillCli(args.slice(1), cfg);
138
+ if (args[0] === "topics") return topicsCli(args.slice(1), cfg);
139
+ const parsed = parseArgs(args);
140
+ if (typeof parsed === "string") {
141
+ console.error(`${parsed}\n${USAGE}`);
142
+ return 2;
143
+ }
144
+ if (parsed.show !== 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) {
148
+ console.error(`no entry with id ${parsed.show}`);
149
+ return 2;
150
+ }
151
+ for (const e of pair) {
152
+ console.log(parsed.json ? jsonLine(e) : `${e.id} ${stamp(e.at)} ${e.role}\n${e.text}\n`);
153
+ }
154
+ return 0;
155
+ }
156
+ if (parsed.words.length === 0) {
157
+ console.error(USAGE);
158
+ return 2;
159
+ }
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) {
166
+ console.log("no match");
167
+ return 1;
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
+ }
172
+ for (const e of hits) {
173
+ console.log(parsed.json ? jsonLine(e, topics.length > 0) : `${e.id} ${stamp(e.at)} ${e.role} ${preview(e.text)}`);
174
+ }
175
+ return 0;
176
+ }
177
+
178
+ export function runRecall(args: string[]): number | Promise<number> {
179
+ let cfg: Config;
180
+ try {
181
+ cfg = loadConfig();
182
+ } catch (err) {
183
+ console.error(err instanceof ConfigError ? err.message : String(err));
184
+ return 1;
185
+ }
186
+ return recallCli(args, cfg);
187
+ }
@@ -49,6 +49,13 @@ export interface RunSource {
49
49
  mainSession(file?: string): MainSession | null;
50
50
  }
51
51
 
52
+ /** One line of the recall backfill (plan 20261109_2335 P3): an owner prompt or a Main reply found in a session file. `at` is epoch seconds. */
53
+ export interface OwnerTurn {
54
+ at: number;
55
+ role: "owner" | "main";
56
+ text: string;
57
+ }
58
+
52
59
  // Trace events: the raw activity of one run, used for claimed-vs-done checks and cross-run
53
60
  // questions. Harness-specific parsing lives in the adapters; core only defines the shape.
54
61
 
@@ -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); a run starts every `topics_every` Main entries. */
287
+ recall: { topics_model: 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,8 @@ 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 (!Number.isInteger(cfg.recall.topics_every) || cfg.recall.topics_every < 1) throw new ConfigError("recall.topics_every must be an integer >= 1");
805
809
  for (const [key, value] of Object.entries(cfg.paths)) {
806
810
  if (key === "work_roots") {
807
811
  if (!Array.isArray(value) || value.some(v => typeof v !== "string")) {
@@ -31,7 +31,8 @@ import { approvalProblem, MAIN_ONLY_LINE, reviewHash } from "./plan-approval.ts"
31
31
  export { reviewHash };
32
32
  import type { Config } from "./config.ts";
33
33
  import { openIncidents, ownerMessagesFile, ownerSaid, readOwnerAnswers, readOwnerMessages, type IncidentView, type OwnerMessage, writeOwnerStore } from "./incidents.ts";
34
- import { UNANSWERED_PREFIX } from "./rollover.ts";
34
+ import { ownerText, UNANSWERED_PREFIX } from "./rollover.ts";
35
+ import { ownerLogFile, recordOwnerLog } from "./owner-log.ts";
35
36
  import { notifyProtectedPaths, notifySecretReadHit } from "./notify.ts";
36
37
  import { defaultRunner, listOpenMrs, mentioned, type CommandRunner, type OpenMr } from "./mr-sweep.ts";
37
38
  import { unlandedRows } from "./wip-check.ts";
@@ -497,13 +498,21 @@ function staffingFile(): string {
497
498
  // (20261028_0900 P3): dismissIncident needs them too, and guards already imports incidents.
498
499
 
499
500
  /** P3 (plan 20261031_1207): the text is owner prose — not Main's own guard output, a system notice, a task result — so its words are the owner's. Gates both the owner-message store and the cancel flag. The P5b resume prefix makes a wrapped machine prompt owner-shaped, so it is excluded here like its unwrapped form. */
500
- function isOwnerProse(text: string): boolean {
501
+ export function isOwnerProse(text: string): boolean {
501
502
  const t = text.trimStart();
502
503
  return !(t.startsWith("main-guard:") || t.startsWith(UNANSWERED_PREFIX) || t.startsWith("<system-notice>") || text.includes("<task-result"));
503
504
  }
504
505
 
505
506
  function recordOwnerMessage(text: string, cfg: Config): void {
506
507
  if (!isOwnerProse(text)) return;
508
+ const owner = ownerText(text);
509
+ if (owner) {
510
+ try {
511
+ recordOwnerLog(cfg, "owner", owner);
512
+ } catch (err) {
513
+ log(cfg.paths.guard_log, `cannot write ${ownerLogFile()}: ${err}`);
514
+ }
515
+ }
507
516
  try {
508
517
  writeOwnerStore([...readOwnerMessages(), { at: nowSec(), text }], readOwnerAnswers());
509
518
  } catch (err) {