neurastream 0.3.2 → 0.3.4

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,16 @@ 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
+
341
351
  ## Secrets never reach the chat
342
352
 
343
353
  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.2",
3
+ "version": "0.3.4",
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,7 +3,7 @@
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";
@@ -17,6 +17,8 @@ export interface HarnessAdapter {
17
17
  bin: string;
18
18
  /** Session reader: the runs and the main session (docs/adapter.md). */
19
19
  runSource(cfg: Config): RunSource;
20
+ /** Owner prompts and Main replies in the session files at or after the epoch second `since` (the recall backfill, plan 20261109_2335 P3). */
21
+ ownerTurns(cfg: Config, since: number): OwnerTurn[];
20
22
  /** Completed subagent task-results announced in the newest main session file. */
21
23
  completedResults(cfg: Config): TaskResult[];
22
24
  /** 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,
@@ -30,6 +30,7 @@ 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
34
  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
35
  import { rateLimited } from "../../core/rate-limit.ts";
35
36
  import { backPost, clearLimitState, limitMetric, limitedPost, onLimited, readLimitState, timingOf, writeLimitState } from "../../core/limit-probe.ts";
@@ -753,6 +754,11 @@ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig
753
754
  // blocked and mid-run ends are not turn ends: nothing is recorded.
754
755
  const recordTurnAnswer = (reply: EventReply | null): void => {
755
756
  if (!reply?.text) return;
757
+ try {
758
+ recordOwnerLog(cfg, "main", reply.text);
759
+ } catch (err) {
760
+ adapterLog(cfg, `RECALL-LOG record failed: ${err instanceof Error ? err.message : String(err)}`);
761
+ }
756
762
  try {
757
763
  appendOwnerAnswer(reply.text);
758
764
  } catch (err) {
@@ -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,151 @@
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 } 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 { applyQueueEnv } from "../core/queue/env.ts";
10
+
11
+ const USAGE = "usage: neurastream recall <words>... [--since 7d|12h|YYYY-MM-DD] [--limit N] [--json]\n neurastream recall --show <id> [--json]";
12
+ const BACKFILL_USAGE = "usage: neurastream recall backfill [--since 7d|12h|YYYY-MM-DD]";
13
+ const DEFAULT_LIMIT = 20;
14
+ const PREVIEW_CHARS = 160;
15
+ const HOUR = 3600;
16
+ const DAY = 86400;
17
+
18
+ interface Opts {
19
+ words: string[];
20
+ show?: string;
21
+ sinceSec?: number;
22
+ limit: number;
23
+ json: boolean;
24
+ }
25
+
26
+ // The earliest epoch second a --since value admits: a relative 7d or 12h, or a date.
27
+ function sinceAt(text: string, now: number): number | undefined {
28
+ const m = /^(\d+)([hd])$/.exec(text);
29
+ if (m) return now - Number(m[1]) * (m[2] === "d" ? DAY : HOUR);
30
+ const ms = Date.parse(text);
31
+ return Number.isNaN(ms) ? undefined : ms / 1000;
32
+ }
33
+
34
+ // A usage problem comes back as its message; the caller prints it with USAGE.
35
+ function parseArgs(args: string[]): Opts | string {
36
+ const opts: Opts = { words: [], limit: DEFAULT_LIMIT, json: false };
37
+ let since: string | undefined;
38
+ for (let i = 0; i < args.length; i++) {
39
+ const a = args[i]!;
40
+ if (a === "--json") {
41
+ opts.json = true;
42
+ } else if (a === "--show" || a === "--since" || a === "--limit") {
43
+ const v = args[++i];
44
+ if (v === undefined) return `${a} needs a value`;
45
+ if (a === "--show") {
46
+ opts.show = v;
47
+ } else if (a === "--since") {
48
+ since = v;
49
+ } else {
50
+ const n = Number(v);
51
+ if (!Number.isInteger(n) || n < 1) return "--limit needs a whole number of 1 or more";
52
+ opts.limit = n;
53
+ }
54
+ } else if (a.startsWith("--")) {
55
+ return `unknown flag ${a}`;
56
+ } else {
57
+ opts.words.push(a);
58
+ }
59
+ }
60
+ if (since !== undefined) {
61
+ opts.sinceSec = sinceAt(since, nowSec());
62
+ if (opts.sinceSec === undefined) return `--since takes 7d, 12h or a date (YYYY-MM-DD), not ${since}`;
63
+ }
64
+ return opts;
65
+ }
66
+
67
+ // Times are shown in UTC, minute precision.
68
+ function stamp(at: number): string {
69
+ return new Date(at * 1000).toISOString().slice(0, 16).replace("T", " ");
70
+ }
71
+
72
+ function preview(text: string): string {
73
+ const flat = text.replace(/\s+/g, " ").trim();
74
+ return flat.length > PREVIEW_CHARS ? `${flat.slice(0, PREVIEW_CHARS - 1)}…` : flat;
75
+ }
76
+
77
+ function jsonLine(e: LogEntry): string {
78
+ return JSON.stringify({ at: e.at, id: e.id, role: e.role, text: e.text });
79
+ }
80
+
81
+ // `recall backfill [--since ...]`: writes the session files' owner prompts and Main replies to the backfill
82
+ // file, once. Reads the session files only; no model call.
83
+ function backfillCli(args: string[], cfg: Config): number {
84
+ let since = 0;
85
+ if (args.length > 0) {
86
+ const value = args[1];
87
+ if (args.length !== 2 || args[0] !== "--since" || value === undefined) {
88
+ console.error(BACKFILL_USAGE);
89
+ return 2;
90
+ }
91
+ const at = sinceAt(value, nowSec());
92
+ if (at === undefined) {
93
+ console.error(`--since takes 7d, 12h or a date (YYYY-MM-DD), not ${value}\n${BACKFILL_USAGE}`);
94
+ return 2;
95
+ }
96
+ since = at;
97
+ }
98
+ const written = backfillOwnerLog(cfg, getAdapter(cfg).ownerTurns(cfg, since));
99
+ console.log(`backfill: ${written} entries`);
100
+ return 0;
101
+ }
102
+
103
+ export function recallCli(args: string[], cfg: Config): number {
104
+ if (args.includes("--help") || args.includes("-h")) {
105
+ printText(helpDoc("recall"));
106
+ return 0;
107
+ }
108
+ // The log paths follow the queue state directory, so the config's queue env is applied first.
109
+ applyQueueEnv(cfg);
110
+ if (args[0] === "backfill") return backfillCli(args.slice(1), cfg);
111
+ const parsed = parseArgs(args);
112
+ if (typeof parsed === "string") {
113
+ console.error(`${parsed}\n${USAGE}`);
114
+ return 2;
115
+ }
116
+ if (parsed.show !== undefined) {
117
+ const pair = showEntries(parsed.show);
118
+ if (pair === undefined) {
119
+ console.error(`no entry with id ${parsed.show}`);
120
+ return 2;
121
+ }
122
+ for (const e of pair) {
123
+ console.log(parsed.json ? jsonLine(e) : `${e.id} ${stamp(e.at)} ${e.role}\n${e.text}\n`);
124
+ }
125
+ return 0;
126
+ }
127
+ if (parsed.words.length === 0) {
128
+ console.error(USAGE);
129
+ return 2;
130
+ }
131
+ const hits = searchEntries({ words: parsed.words, sinceSec: parsed.sinceSec, limit: parsed.limit });
132
+ if (hits.length === 0) {
133
+ console.log("no match");
134
+ return 1;
135
+ }
136
+ for (const e of hits) {
137
+ console.log(parsed.json ? jsonLine(e) : `${e.id} ${stamp(e.at)} ${e.role} ${preview(e.text)}`);
138
+ }
139
+ return 0;
140
+ }
141
+
142
+ export function runRecall(args: string[]): number {
143
+ let cfg: Config;
144
+ try {
145
+ cfg = loadConfig();
146
+ } catch (err) {
147
+ console.error(err instanceof ConfigError ? err.message : String(err));
148
+ return 1;
149
+ }
150
+ return recallCli(args, cfg);
151
+ }
@@ -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
 
@@ -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";
@@ -308,6 +309,7 @@ function reviewRole(name: string | undefined, named: string[], brief: string, ag
308
309
  const reviewed = named.filter(f => isReviewSpawn(f, brief, agent, cfg, spawner));
309
310
  if (reviewed.length > 1) return { plan: null, problem: "a review spawn reviews one plan; split the spawn." };
310
311
  if (reviewed.length && !name) return { plan: null, problem: "a review spawn needs a name (the task name keys its review lock)." };
312
+ if (reviewed.length && !/^Scope: whole plan\s*$/m.test(brief)) return { plan: null, problem: "a review spawn reviews the whole plan: add the line `Scope: whole plan` to the brief (every unticked phase, one pass; no per-phase reviews)." };
311
313
  const plan = reviewed[0] ?? null;
312
314
  if (plan) {
313
315
  const rec = readPlanReviews()[plan];
@@ -496,13 +498,21 @@ function staffingFile(): string {
496
498
  // (20261028_0900 P3): dismissIncident needs them too, and guards already imports incidents.
497
499
 
498
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. */
499
- function isOwnerProse(text: string): boolean {
501
+ export function isOwnerProse(text: string): boolean {
500
502
  const t = text.trimStart();
501
503
  return !(t.startsWith("main-guard:") || t.startsWith(UNANSWERED_PREFIX) || t.startsWith("<system-notice>") || text.includes("<task-result"));
502
504
  }
503
505
 
504
506
  function recordOwnerMessage(text: string, cfg: Config): void {
505
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
+ }
506
516
  try {
507
517
  writeOwnerStore([...readOwnerMessages(), { at: nowSec(), text }], readOwnerAnswers());
508
518
  } catch (err) {
@@ -0,0 +1,206 @@
1
+ // The recall log (plan 20261109_2335, P2): one JSON line per owner message and per Main answer,
2
+ // kept in <state>/recall/owner-log.jsonl. The inject path and the turn end write it; `neurastream
3
+ // recall` reads it through readLines, which walks the file backwards in 64 KiB blocks so a search
4
+ // over a long log never loads it whole. The backfill file (P3) is read after the live log.
5
+
6
+ import { appendFileSync, chmodSync, closeSync, fstatSync, mkdirSync, openSync, readSync } from "node:fs";
7
+ import { randomBytes } from "node:crypto";
8
+ import { dirname, join } from "node:path";
9
+ import { nowSec } from "./clock.ts";
10
+ import type { Config } from "./config.ts";
11
+ import { ownerMessagesFile } from "./incidents.ts";
12
+ import { loadKnownSecrets, redactSecrets } from "./secret-redact.ts";
13
+ import type { OwnerTurn } from "./adapter.ts";
14
+ import { isOwnerProse } from "./guards.ts";
15
+ import { ownerText } from "./rollover.ts";
16
+
17
+ export type LogRole = "owner" | "main";
18
+
19
+ export interface LogEntry {
20
+ id: string;
21
+ at: number;
22
+ role: LogRole;
23
+ text: string;
24
+ }
25
+
26
+ export function ownerLogDir(): string {
27
+ return join(dirname(ownerMessagesFile()), "recall");
28
+ }
29
+
30
+ export function ownerLogFile(): string {
31
+ return join(ownerLogDir(), "owner-log.jsonl");
32
+ }
33
+
34
+ export function ownerBackfillFile(): string {
35
+ return join(ownerLogDir(), "owner-log.backfill.jsonl");
36
+ }
37
+
38
+ // Ids sort by time: nine base-36 digits of the millisecond clock, then eight hex digits of
39
+ // randomness, so two entries written in the same millisecond collide with probability 2^-32.
40
+ export function newEntryId(atMs: number, rand: (n: number) => Uint8Array = randomBytes): string {
41
+ return atMs.toString(36).padStart(9, "0") + Buffer.from(rand(4)).toString("hex");
42
+ }
43
+
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 {
46
+ const dir = dirname(file);
47
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
48
+ chmodSync(dir, 0o700);
49
+ appendFileSync(file, `${JSON.stringify(entry)}\n`, { mode: 0o600 });
50
+ chmodSync(file, 0o600);
51
+ }
52
+
53
+ export function appendOwnerLog(
54
+ role: LogRole,
55
+ text: string,
56
+ opts: { atMs?: number; rand?: (n: number) => Uint8Array } = {},
57
+ ): string {
58
+ const atMs = opts.atMs ?? nowSec() * 1000;
59
+ const entry: LogEntry = { id: newEntryId(atMs, opts.rand), at: Math.floor(atMs / 1000), role, text };
60
+ appendLogLine(ownerLogFile(), entry);
61
+ return entry.id;
62
+ }
63
+
64
+ // Redacts the text (the configured known secrets and extra patterns) before it is written. Throws
65
+ // on a failed write; the callers decide where that is logged.
66
+ export function recordOwnerLog(cfg: Config, role: LogRole, text: string): void {
67
+ const clean = redactSecrets(text, loadKnownSecrets(cfg), cfg.secrets.extra_patterns).text;
68
+ appendOwnerLog(role, clean);
69
+ }
70
+
71
+ // The first (newest) or last (oldest) parsable entry of one log file; undefined when it has none.
72
+ function logEdge(file: string, newest: boolean): LogEntry | undefined {
73
+ let edge: LogEntry | undefined;
74
+ for (const line of readLines(file)) {
75
+ const entry = parseEntry(line);
76
+ if (entry === undefined) continue;
77
+ edge = entry;
78
+ if (newest) break;
79
+ }
80
+ return edge;
81
+ }
82
+
83
+ // Writes the session files' owner prompts and Main replies to the backfill file, once. A turn is kept
84
+ // only strictly between the newest backfill entry and the oldest live entry, so a rerun adds nothing and
85
+ // the live log is never touched. Owner prompts pass the live path's gates (owner prose, then the owner's
86
+ // part of a handoff or unanswered prompt). Returns the number of entries written.
87
+ export function backfillOwnerLog(cfg: Config, turns: Iterable<OwnerTurn>): number {
88
+ const kept: OwnerTurn[] = [];
89
+ for (const turn of turns) {
90
+ if (turn.role === "main") {
91
+ kept.push(turn);
92
+ } else if (isOwnerProse(turn.text)) {
93
+ const owner = ownerText(turn.text);
94
+ if (owner !== undefined) kept.push({ at: turn.at, role: "owner", text: owner });
95
+ }
96
+ }
97
+ kept.sort((a, b) => a.at - b.at);
98
+ const newest = logEdge(ownerBackfillFile(), true);
99
+ const oldest = logEdge(ownerLogFile(), false);
100
+ const known = loadKnownSecrets(cfg);
101
+ let written = 0;
102
+ for (const turn of kept) {
103
+ if (newest !== undefined && turn.at <= newest.at) continue;
104
+ if (oldest !== undefined && turn.at >= oldest.at) continue;
105
+ 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++;
108
+ }
109
+ return written;
110
+ }
111
+
112
+ const BLOCK = 64 * 1024;
113
+ const LF = 0x0a;
114
+
115
+ // The file's lines, newest first. A missing file yields nothing; empty lines are skipped.
116
+ export function* readLines(file: string): Generator<string> {
117
+ let fd: number;
118
+ try {
119
+ fd = openSync(file, "r");
120
+ } catch {
121
+ return;
122
+ }
123
+ try {
124
+ let pos = fstatSync(fd).size;
125
+ let pending = Buffer.alloc(0);
126
+ while (pos > 0) {
127
+ const n = Math.min(BLOCK, pos);
128
+ pos -= n;
129
+ const block = Buffer.alloc(n);
130
+ readSync(fd, block, 0, n, pos);
131
+ const data = pending.length > 0 ? Buffer.concat([block, pending]) : block;
132
+ let end = data.length;
133
+ let nl = data.lastIndexOf(LF);
134
+ while (nl >= 0) {
135
+ if (end > nl + 1) yield data.toString("utf8", nl + 1, end);
136
+ end = nl;
137
+ nl = end > 0 ? data.lastIndexOf(LF, end - 1) : -1;
138
+ }
139
+ // What is left precedes the block's first newline: the head of a line that starts earlier.
140
+ pending = data.subarray(0, end);
141
+ }
142
+ if (pending.length > 0) yield pending.toString("utf8");
143
+ } finally {
144
+ closeSync(fd);
145
+ }
146
+ }
147
+
148
+ function parseEntry(line: string): LogEntry | undefined {
149
+ try {
150
+ return JSON.parse(line) as LogEntry;
151
+ } catch {
152
+ // A torn last line (the writer was killed mid-append) is skipped, not fatal to a search.
153
+ return undefined;
154
+ }
155
+ }
156
+
157
+ // Every entry, newest first: the live log, then the backfill (older by construction).
158
+ export function* readEntries(): Generator<LogEntry> {
159
+ for (const file of [ownerLogFile(), ownerBackfillFile()]) {
160
+ for (const line of readLines(file)) {
161
+ const entry = parseEntry(line);
162
+ if (entry !== undefined) yield entry;
163
+ }
164
+ }
165
+ }
166
+
167
+ export interface SearchOpts {
168
+ words: string[];
169
+ sinceSec?: number;
170
+ limit: number;
171
+ }
172
+
173
+ // Entries whose text contains every word (case-insensitive, any order), newest first.
174
+ export function searchEntries(opts: SearchOpts): LogEntry[] {
175
+ const words = opts.words.map((w) => w.toLowerCase());
176
+ const out: LogEntry[] = [];
177
+ for (const e of readEntries()) {
178
+ if (opts.sinceSec !== undefined && e.at < opts.sinceSec) continue;
179
+ const text = e.text.toLowerCase();
180
+ if (!words.every((w) => text.includes(w))) continue;
181
+ out.push(e);
182
+ if (out.length >= opts.limit) break;
183
+ }
184
+ return out;
185
+ }
186
+
187
+ // The entry with this id plus the entry it pairs with, in chronological order: an owner message
188
+ // with the nearest newer Main answer, a Main answer with the nearest older owner message. Undefined
189
+ // when no entry has the id. One streaming pass, newest first.
190
+ export function showEntries(id: string): LogEntry[] | undefined {
191
+ let target: LogEntry | undefined;
192
+ let newerMain: LogEntry | undefined;
193
+ for (const e of readEntries()) {
194
+ if (target === undefined) {
195
+ if (e.id === id) {
196
+ target = e;
197
+ if (e.role === "owner") return newerMain ? [e, newerMain] : [e];
198
+ } else if (e.role === "main") {
199
+ newerMain = e;
200
+ }
201
+ continue;
202
+ }
203
+ if (e.role === "owner") return [e, target];
204
+ }
205
+ return target ? [target] : undefined;
206
+ }
@@ -9,8 +9,9 @@ You are Main, the orchestrator. Main plans, delegates, reviews and lands; implem
9
9
  - INDEX.md order is priority: free agents go to the top plans first. A lower plan goes first only when the higher one says `Waits on: <plan>`, is WAITING on owner, or the brief quotes the owner: `Priority skip: <plan> — owner: "<his words>"`.
10
10
  - A hold is one line: `WAITING on owner: <what to do> — blocked: <what stays stuck until then> — why you: <why Main cannot do it>`. The phone page shows those three parts; a missing part is left out.
11
11
  - Entering a repo: read its AGENTS.md first.
12
+ - When the owner asks about, or refers to, something said earlier that is not in your context, run `neurastream recall <words>` and read the hit with `--show <id>` before you answer, guess or ask him again.
12
13
  - Main writes every plan in `<repo>/docs/plans/`, shaped like `{{AGENT_DIR}}/queue/TEMPLATE.md`. Do the research yourself; never base a plan on another agent's findings. In `planner delegated` mode the planner agent writes the plan instead (`Planner: <agent>` header; the research and the `## Code read by Main` list are the planner's): Main routes the owner's asks to it, dispatches implementers, checks the outcomes (verify commands, CI, the reviewer's PASS) and lands, and Main does not read repo code to plan. The owner's whole message `planner main` returns this rule; `autonomy.planner` (default `main`) is the same switch in the config.
13
- - Planner choice is Main's: a small mechanical plan (a tick, a done-check or verify fix, one doc line) goes to `glm`, or `haiku` when the fast planner is unavailable; anything else goes to `opus-planner` (always thinking medium). The plan's `Planner: <agent>` header is the record; no tier code.
14
+ - Planner choice is Main's: only a complex plan (open design, several files or subsystems, real choices) goes to `opus-planner` (always thinking medium); every other plan goes to `glm`, or `haiku` when the fast planner is unavailable. A really simple change (one guard line, a template wording, a test brief, a tick, a few lines in 1-3 files) is not a plan: Main edits it itself with a targeted test, and if the edit cap blocks it, says so and asks for the unlock instead of spawning an agent. The plan's `Planner: <agent>` header is the record; no tier code.
14
15
  - In delegated mode Main may correct only a plan's `## Done check` command and a phase line's `verify:` command; every other plan line belongs to the planner.
15
16
  - Phase 0 of every plan: blocker scripts that stop the implementer from going against the plan. They must exist before any spawn.
16
17
  - Every plan has `## Reuse`; no spawn without a current reviewer PASS (`templates/plan-review-brief.md`, recorded only from the reviewer's own Progress edit); a brief names every open MR of its plan with an `MR !N:` line.
@@ -0,0 +1,13 @@
1
+ recall: search the owner's messages and Main's answers, and show an entry with the entry it pairs with.
2
+
3
+ Usage: recall <words>... [--since 7d|12h|YYYY-MM-DD] [--limit N] [--json]
4
+ Words match case-insensitively; every word must appear in the entry, in any order.
5
+ Newest first. Default limit 20. Times are UTC.
6
+ Usage: recall --show <id> [--json]
7
+ Shows the entry with that id and its pair: an owner message with the nearest newer Main
8
+ answer, or a Main answer with the nearest older owner message. Chronological order.
9
+ --json prints one JSON object per line with the keys at, id, role, text.
10
+ Usage: recall backfill [--since 7d|12h|YYYY-MM-DD]
11
+ Reads the harness's session files once and logs every owner message and Main answer from before the
12
+ live log began (secrets redacted). A second run adds nothing. Prints `backfill: <n> entries`.
13
+ Exit: 0 on a match, 1 when nothing matches, 2 on bad arguments or an unknown id.
@@ -6,7 +6,7 @@ Reviewer: read-only — you never edit code, never write repo files, never push,
6
6
  Stop and report within ~20 tool calls.
7
7
 
8
8
  ## Goal
9
- - Review P<n> of the plan against its phases: is it free of redundant, inefficient and insecure work before anyone is spawned on it? Name exactly one unticked phase here (the spawn gate requires it).
9
+ - Review the WHOLE plan: every unticked phase, one pass: is it free of redundant, inefficient and insecure work before anyone is spawned on it? The brief carries the line `Scope: whole plan` (the spawn gate requires it); never review one phase only.
10
10
 
11
11
  ## Forbidden
12
12
  - never push, never open a PR, never edit a file (read-only review)