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 +11 -0
- package/package.json +1 -1
- package/src/adapters/index.ts +4 -1
- package/src/adapters/omp/adapter.ts +2 -1
- package/src/adapters/omp/index.ts +43 -1
- package/src/adapters/omp/launch.ts +111 -1
- package/src/adapters/omp/sessions.ts +70 -3
- package/src/cli/dispatch.ts +6 -0
- package/src/cli/recall.ts +187 -0
- package/src/core/adapter.ts +7 -0
- package/src/core/config.ts +4 -0
- package/src/core/guards.ts +11 -2
- package/src/core/owner-log.ts +218 -0
- package/src/core/owner-topics.ts +525 -0
- package/templates/AGENTS.md +1 -0
- package/templates/config.yml +4 -0
- package/templates/help/recall.txt +18 -0
|
@@ -0,0 +1,525 @@
|
|
|
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
|
+
}
|
|
19
|
+
|
|
20
|
+
export interface CompleteResult {
|
|
21
|
+
text: string;
|
|
22
|
+
usage: { prompt_tokens: number; completion_tokens: number };
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export type Complete = (req: CompleteRequest) => Promise<CompleteResult>;
|
|
26
|
+
|
|
27
|
+
export interface Note {
|
|
28
|
+
id: string;
|
|
29
|
+
text: string;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
// One segment as the model answers it.
|
|
33
|
+
export interface AnswerSegment {
|
|
34
|
+
from: string;
|
|
35
|
+
to: string;
|
|
36
|
+
title: string;
|
|
37
|
+
keywords: string[];
|
|
38
|
+
decisions: Note[];
|
|
39
|
+
questions: Note[];
|
|
40
|
+
names: string[];
|
|
41
|
+
continues: string | null;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
// A segment as stored. The last segment of a run is open: the next run may re-cut it.
|
|
45
|
+
export interface Segment extends AnswerSegment {
|
|
46
|
+
at: number;
|
|
47
|
+
open: boolean;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// A window the model could not segment. It keeps its place in the log, so its entries are not retried.
|
|
51
|
+
export interface Skipped {
|
|
52
|
+
from: string;
|
|
53
|
+
to: string;
|
|
54
|
+
at: number;
|
|
55
|
+
skipped: true;
|
|
56
|
+
why: string;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export type TopicRow = Segment | Skipped;
|
|
60
|
+
|
|
61
|
+
export interface TopicsRun {
|
|
62
|
+
lines: string[];
|
|
63
|
+
failures: number;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
interface Tally {
|
|
67
|
+
calls: number;
|
|
68
|
+
tokensIn: number;
|
|
69
|
+
tokensOut: number;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// A failure the caller prints: the reason code, and the byte sizes of the request and the answer.
|
|
73
|
+
interface Failure {
|
|
74
|
+
reason: string;
|
|
75
|
+
in: number;
|
|
76
|
+
out: number;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
type Attempt =
|
|
80
|
+
| { kind: "ok" }
|
|
81
|
+
| { kind: "rejected"; reason: string; in: number; out: number }
|
|
82
|
+
| { kind: "error"; reason: string; in: number };
|
|
83
|
+
|
|
84
|
+
const TOPICS_FILE = "owner-topics.jsonl";
|
|
85
|
+
const TOPICS_LOG_FILE = "owner-topics.log";
|
|
86
|
+
const LOCK_FILE = "owner-topics.lock";
|
|
87
|
+
const WINDOW = 120;
|
|
88
|
+
const MAX_TOKENS = 4000;
|
|
89
|
+
|
|
90
|
+
const SYSTEM = [
|
|
91
|
+
"You split a chronological log of an owner's messages and the assistant's replies into topic segments.",
|
|
92
|
+
"Answer with one JSON object and nothing else:",
|
|
93
|
+
'{"segments":[{"from":"<entry id>","to":"<entry id>","title":"...","keywords":["..."],"decisions":[{"id":"<entry id>","text":"..."}],"questions":[{"id":"<owner entry id>","text":"..."}],"names":["..."],"continues":null}]}',
|
|
94
|
+
"Rules:",
|
|
95
|
+
"- The segments cover the log in order with no gaps and no overlaps; the last one ends at the last entry.",
|
|
96
|
+
"- from and to are entry ids from the log. A segment that is not the last has 3 to 60 entries.",
|
|
97
|
+
"- 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.",
|
|
98
|
+
"- questions: the owner's open questions, each with the id of an owner entry in the segment.",
|
|
99
|
+
"- Write in your own words. Never copy 8 or more words in a row from the log.",
|
|
100
|
+
"- continues: the from id of an earlier closed segment this one directly continues; null when unsure.",
|
|
101
|
+
].join("\n");
|
|
102
|
+
|
|
103
|
+
export function topicsFile(): string {
|
|
104
|
+
return join(ownerLogDir(), TOPICS_FILE);
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
// stdout and stderr of the background `recall topics` run: stats and `topics: fail` lines only.
|
|
108
|
+
export function topicsLogFile(): string {
|
|
109
|
+
return join(ownerLogDir(), TOPICS_LOG_FILE);
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
export function topicsDue(count: number, every: number): boolean {
|
|
113
|
+
return count >= every;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
function isStrings(v: unknown): v is string[] {
|
|
117
|
+
return Array.isArray(v) && v.every(s => typeof s === "string");
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
function isNotes(v: unknown): v is Note[] {
|
|
121
|
+
return (
|
|
122
|
+
Array.isArray(v) &&
|
|
123
|
+
v.every(n => {
|
|
124
|
+
const note = n as Partial<Note> | null;
|
|
125
|
+
return note !== null && typeof note === "object" && typeof note.id === "string" && typeof note.text === "string";
|
|
126
|
+
})
|
|
127
|
+
);
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
function isSegment(r: TopicRow): r is Segment {
|
|
131
|
+
return !("skipped" in r);
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
function parseRow(line: string): TopicRow | undefined {
|
|
135
|
+
let v: Partial<Segment & Skipped> | null;
|
|
136
|
+
try {
|
|
137
|
+
v = JSON.parse(line) as Partial<Segment & Skipped> | null;
|
|
138
|
+
} catch {
|
|
139
|
+
return undefined;
|
|
140
|
+
}
|
|
141
|
+
if (v === null || typeof v !== "object" || typeof v.from !== "string" || typeof v.to !== "string") return undefined;
|
|
142
|
+
if (typeof v.at !== "number") return undefined;
|
|
143
|
+
if (v.skipped === true) {
|
|
144
|
+
return { from: v.from, to: v.to, at: v.at, skipped: true, why: typeof v.why === "string" ? v.why : "" };
|
|
145
|
+
}
|
|
146
|
+
if (
|
|
147
|
+
typeof v.title !== "string" ||
|
|
148
|
+
typeof v.open !== "boolean" ||
|
|
149
|
+
!isStrings(v.keywords) ||
|
|
150
|
+
!isNotes(v.decisions) ||
|
|
151
|
+
!isNotes(v.questions) ||
|
|
152
|
+
!isStrings(v.names) ||
|
|
153
|
+
!(v.continues === null || typeof v.continues === "string")
|
|
154
|
+
) {
|
|
155
|
+
return undefined;
|
|
156
|
+
}
|
|
157
|
+
return {
|
|
158
|
+
from: v.from,
|
|
159
|
+
to: v.to,
|
|
160
|
+
at: v.at,
|
|
161
|
+
open: v.open,
|
|
162
|
+
title: v.title,
|
|
163
|
+
keywords: v.keywords,
|
|
164
|
+
decisions: v.decisions,
|
|
165
|
+
questions: v.questions,
|
|
166
|
+
names: v.names,
|
|
167
|
+
continues: v.continues,
|
|
168
|
+
};
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
// The index as a reader sees it: file order, where a line replaces every earlier line that reaches into its
|
|
172
|
+
// ids (a re-cut of the open segment, or the closed copy that --close writes). Unparsable lines are skipped.
|
|
173
|
+
function effectiveRows(): TopicRow[] {
|
|
174
|
+
const out: TopicRow[] = [];
|
|
175
|
+
for (const line of [...readLines(topicsFile())].toReversed()) {
|
|
176
|
+
const row = parseRow(line);
|
|
177
|
+
if (row === undefined) continue;
|
|
178
|
+
while (out.length > 0 && out.at(-1)!.to >= row.from) out.pop();
|
|
179
|
+
out.push(row);
|
|
180
|
+
}
|
|
181
|
+
return out;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
export function readTopics(): Segment[] {
|
|
185
|
+
return effectiveRows().filter(isSegment);
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
// The id the next window starts after: the last segment that is closed, or a skipped window.
|
|
189
|
+
function afterClosed(rows: TopicRow[]): string | undefined {
|
|
190
|
+
let to: string | undefined;
|
|
191
|
+
for (const r of rows) if (!(isSegment(r) && r.open)) to = r.to;
|
|
192
|
+
return to;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
function wordCount(s: string): number {
|
|
196
|
+
return s.trim().split(/\s+/).filter(w => w !== "").length;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
// The 8-word runs of a text, lowercased, with punctuation dropped: what the copy check compares.
|
|
200
|
+
function gramsOf(text: string): string[] {
|
|
201
|
+
const ws = text.toLowerCase().split(/[^\p{L}\p{N}]+/u).filter(w => w !== "");
|
|
202
|
+
const out: string[] = [];
|
|
203
|
+
for (let i = 0; i + 8 <= ws.length; i++) out.push(ws.slice(i, i + 8).join(" "));
|
|
204
|
+
return out;
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
// An earlier row as the checks read it: a closed segment, an open one, or a skipped window.
|
|
208
|
+
type Earlier = { from: string; to: string; open?: boolean; skipped?: boolean };
|
|
209
|
+
|
|
210
|
+
// Checks an answer against the window it segments. Returns null, or one message "name: detail" where name
|
|
211
|
+
// `entries` is the window, oldest first; `earlier` is the rows before it, the last one ending where it starts.
|
|
212
|
+
export function checkSegments(
|
|
213
|
+
segments: readonly AnswerSegment[],
|
|
214
|
+
entries: readonly LogEntry[],
|
|
215
|
+
earlier: readonly Earlier[],
|
|
216
|
+
): string | null {
|
|
217
|
+
if (segments.length === 0) return "reach: no segments";
|
|
218
|
+
const index = new Map(entries.map((e, i) => [e.id, i]));
|
|
219
|
+
const seen = new Set<string>();
|
|
220
|
+
const last = earlier.at(-1);
|
|
221
|
+
const start = last === undefined ? 0 : (index.get(last.to) ?? -1) + 1;
|
|
222
|
+
for (const e of entries) for (const g of gramsOf(e.text)) seen.add(g);
|
|
223
|
+
|
|
224
|
+
let prevFrom = -1;
|
|
225
|
+
let prevTo = -1;
|
|
226
|
+
for (let i = 0; i < segments.length; i++) {
|
|
227
|
+
const s = segments[i]!;
|
|
228
|
+
const fi = index.get(s.from);
|
|
229
|
+
const ti = index.get(s.to);
|
|
230
|
+
if (fi === undefined) return `id: ${s.from} not in log`;
|
|
231
|
+
if (ti === undefined) return `id: ${s.to} not in log`;
|
|
232
|
+
if (fi > ti) return `order: segment ${s.from}..${s.to} ends before it starts`;
|
|
233
|
+
if (i === 0) {
|
|
234
|
+
if (fi > start) return `gap: entries before ${s.from} are not covered`;
|
|
235
|
+
if (fi < start) return `overlap: segment ${s.from} starts inside an earlier one`;
|
|
236
|
+
} else if (fi < prevFrom) {
|
|
237
|
+
return `order: segment ${s.from} is out of log order`;
|
|
238
|
+
} else if (fi <= prevTo) {
|
|
239
|
+
return `overlap: segment ${s.from} starts inside the previous one`;
|
|
240
|
+
} else if (fi > prevTo + 1) {
|
|
241
|
+
return `gap: entries after ${segments[i - 1]!.to} are not covered`;
|
|
242
|
+
}
|
|
243
|
+
const count = ti - fi + 1;
|
|
244
|
+
if (i < segments.length - 1 && count < 3) return `short: segment ${s.from}..${s.to} has fewer than 3 entries`;
|
|
245
|
+
if (count > 60) return `long: segment ${s.from}..${s.to} has more than 60 entries`;
|
|
246
|
+
if (wordCount(s.title) > 10) return "title: over 10 words";
|
|
247
|
+
for (const k of s.keywords) if (wordCount(k) > 6) return "keyword: over 6 words";
|
|
248
|
+
for (const d of s.decisions) {
|
|
249
|
+
if (wordCount(d.text) > 60) return "decision: over 60 words";
|
|
250
|
+
const di = index.get(d.id);
|
|
251
|
+
if (di === undefined || di < fi || di > ti) return `decision: id ${d.id} is outside its segment`;
|
|
252
|
+
}
|
|
253
|
+
for (const q of s.questions) {
|
|
254
|
+
const qi = index.get(q.id);
|
|
255
|
+
if (qi === undefined || qi < fi || qi > ti || entries[qi]!.role !== "owner") {
|
|
256
|
+
return `question: id ${q.id} is not an owner entry in its segment`;
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
for (const text of [s.title, ...s.decisions.map(d => d.text), ...s.questions.map(q => q.text)]) {
|
|
260
|
+
if (gramsOf(text).some(g => seen.has(g))) return "copy: 8 words copied in a row from an entry";
|
|
261
|
+
}
|
|
262
|
+
if (s.continues !== null && !earlier.some(e => e.open !== true && e.skipped !== true && e.from === s.continues)) {
|
|
263
|
+
return `continues: ${s.continues} is not an earlier closed segment`;
|
|
264
|
+
}
|
|
265
|
+
prevFrom = fi;
|
|
266
|
+
prevTo = ti;
|
|
267
|
+
}
|
|
268
|
+
if (index.get(segments.at(-1)!.to) !== entries.length - 1) return "reach: segments stop before the last entry";
|
|
269
|
+
return null;
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
// The answer's shape, checked field by field: the model's text is not trusted to carry the named type.
|
|
273
|
+
function shape(value: unknown): AnswerSegment[] | undefined {
|
|
274
|
+
const raw = (value as { segments?: unknown } | null)?.segments;
|
|
275
|
+
if (!Array.isArray(raw)) return undefined;
|
|
276
|
+
const out: AnswerSegment[] = [];
|
|
277
|
+
for (const item of raw) {
|
|
278
|
+
const s = item as Partial<AnswerSegment> | null;
|
|
279
|
+
if (
|
|
280
|
+
s === null ||
|
|
281
|
+
typeof s !== "object" ||
|
|
282
|
+
typeof s.from !== "string" ||
|
|
283
|
+
typeof s.to !== "string" ||
|
|
284
|
+
typeof s.title !== "string" ||
|
|
285
|
+
!isStrings(s.keywords) ||
|
|
286
|
+
!isNotes(s.decisions) ||
|
|
287
|
+
!isNotes(s.questions) ||
|
|
288
|
+
!isStrings(s.names) ||
|
|
289
|
+
!(s.continues === null || typeof s.continues === "string")
|
|
290
|
+
) {
|
|
291
|
+
return undefined;
|
|
292
|
+
}
|
|
293
|
+
out.push({
|
|
294
|
+
from: s.from,
|
|
295
|
+
to: s.to,
|
|
296
|
+
title: s.title,
|
|
297
|
+
keywords: s.keywords,
|
|
298
|
+
decisions: s.decisions,
|
|
299
|
+
questions: s.questions,
|
|
300
|
+
names: s.names,
|
|
301
|
+
continues: s.continues,
|
|
302
|
+
});
|
|
303
|
+
}
|
|
304
|
+
return out;
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
type Parsed = { segments: AnswerSegment[] } | { reason: string };
|
|
308
|
+
|
|
309
|
+
function parseAnswer(text: string, window: readonly LogEntry[], earlier: readonly Earlier[]): Parsed {
|
|
310
|
+
let value: unknown;
|
|
311
|
+
try {
|
|
312
|
+
value = JSON.parse(text);
|
|
313
|
+
} catch {
|
|
314
|
+
return { reason: "bad-json" };
|
|
315
|
+
}
|
|
316
|
+
const segments = shape(value);
|
|
317
|
+
if (segments === undefined) return { reason: "check:shape" };
|
|
318
|
+
const err = checkSegments(segments, window, earlier);
|
|
319
|
+
return err === null ? { segments } : { reason: `check:${err.slice(0, err.indexOf(":"))}` };
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
// A model error keeps its reason code; a timeout is named TimeoutError by the caller's spawn.
|
|
323
|
+
function failureReason(err: unknown): string {
|
|
324
|
+
if (err instanceof Error && err.name === "TimeoutError") return "timeout";
|
|
325
|
+
const reason = (err as { reason?: unknown } | null)?.reason;
|
|
326
|
+
return typeof reason === "string" && reason !== "" ? reason : "model-error";
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
function windowPrompt(window: readonly LogEntry[]): string {
|
|
330
|
+
return ["Log entries, oldest first:", ...window.map(e => `[${e.id}] (${e.role}) ${e.text}`)].join("\n");
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
// Redacts the model's text before it is written: the configured known secrets and extra patterns.
|
|
334
|
+
function appendSegments(cfg: Config, segments: readonly AnswerSegment[]): void {
|
|
335
|
+
const known = loadKnownSecrets(cfg);
|
|
336
|
+
const clean = (text: string): string => redactSecrets(text, known, cfg.secrets.extra_patterns).text;
|
|
337
|
+
const at = nowSec();
|
|
338
|
+
const rows: Segment[] = segments.map((s, i) => ({
|
|
339
|
+
from: s.from,
|
|
340
|
+
to: s.to,
|
|
341
|
+
at,
|
|
342
|
+
open: i === segments.length - 1,
|
|
343
|
+
title: clean(s.title),
|
|
344
|
+
keywords: s.keywords.map(clean),
|
|
345
|
+
decisions: s.decisions.map(d => ({ id: d.id, text: clean(d.text) })),
|
|
346
|
+
questions: s.questions.map(q => ({ id: q.id, text: clean(q.text) })),
|
|
347
|
+
names: s.names.map(clean),
|
|
348
|
+
continues: s.continues,
|
|
349
|
+
}));
|
|
350
|
+
appendJsonLines(topicsFile(), rows);
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
// One model call on the window. On a good answer the segments are appended; otherwise nothing is written.
|
|
354
|
+
async function attemptOnce(
|
|
355
|
+
cfg: Config,
|
|
356
|
+
complete: Complete,
|
|
357
|
+
window: readonly LogEntry[],
|
|
358
|
+
request: string,
|
|
359
|
+
earlier: readonly Earlier[],
|
|
360
|
+
tally: Tally,
|
|
361
|
+
): Promise<Attempt> {
|
|
362
|
+
tally.calls++;
|
|
363
|
+
let answer: CompleteResult;
|
|
364
|
+
try {
|
|
365
|
+
answer = await complete({ model: cfg.recall.topics_model, system: SYSTEM, prompt: request, maxTokens: MAX_TOKENS });
|
|
366
|
+
} catch (err) {
|
|
367
|
+
return { kind: "error", reason: failureReason(err), in: Buffer.byteLength(request) };
|
|
368
|
+
}
|
|
369
|
+
tally.tokensIn += answer.usage.prompt_tokens;
|
|
370
|
+
tally.tokensOut += answer.usage.completion_tokens;
|
|
371
|
+
const parsed = parseAnswer(answer.text, window, earlier);
|
|
372
|
+
if ("segments" in parsed) {
|
|
373
|
+
appendSegments(cfg, parsed.segments);
|
|
374
|
+
return { kind: "ok" };
|
|
375
|
+
}
|
|
376
|
+
return { kind: "rejected", reason: parsed.reason, in: Buffer.byteLength(request), out: Buffer.byteLength(answer.text) };
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
// Segments one window and appends the result. A window whose answer is rejected twice is kept as one skipped
|
|
380
|
+
// line, so the next run starts after it. A model error is not retried and appends nothing.
|
|
381
|
+
async function segmentWindow(
|
|
382
|
+
cfg: Config,
|
|
383
|
+
complete: Complete,
|
|
384
|
+
window: readonly LogEntry[],
|
|
385
|
+
rows: TopicRow[],
|
|
386
|
+
tally: Tally,
|
|
387
|
+
): Promise<Failure | undefined> {
|
|
388
|
+
const earlier = rows.filter(r => !(isSegment(r) && r.open));
|
|
389
|
+
const prompt = windowPrompt(window);
|
|
390
|
+
const first = await attemptOnce(cfg, complete, window, prompt, earlier, tally);
|
|
391
|
+
if (first.kind === "ok") return undefined;
|
|
392
|
+
if (first.kind === "error") return { reason: first.reason, in: first.in, out: 0 };
|
|
393
|
+
const retry = `${prompt}\n\nYour answer was rejected (${first.reason}). Answer again with only the JSON object, following every rule.`;
|
|
394
|
+
const second = await attemptOnce(cfg, complete, window, retry, earlier, tally);
|
|
395
|
+
if (second.kind === "ok") return undefined;
|
|
396
|
+
if (second.kind === "error") return { reason: second.reason, in: second.in, out: 0 };
|
|
397
|
+
appendJsonLines(topicsFile(), [
|
|
398
|
+
{ from: window[0]!.id, to: window.at(-1)!.id, at: nowSec(), skipped: true, why: second.reason },
|
|
399
|
+
]);
|
|
400
|
+
return { reason: second.reason, in: second.in, out: second.out };
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
// `--close`: the open segment becomes closed (a copy with open:false), so the next window starts after it.
|
|
404
|
+
function closeOpen(): void {
|
|
405
|
+
const last = effectiveRows().at(-1);
|
|
406
|
+
if (last !== undefined && isSegment(last) && last.open) appendJsonLines(topicsFile(), [{ ...last, open: false }]);
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
function oldestFirst(): LogEntry[] {
|
|
410
|
+
return [...readEntries()].toReversed();
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
// The entries after `afterId`, oldest first. No id means every entry.
|
|
414
|
+
export function newEntries(afterId?: string): LogEntry[] {
|
|
415
|
+
const all = oldestFirst();
|
|
416
|
+
if (afterId === undefined) return all;
|
|
417
|
+
const i = all.findIndex(e => e.id === afterId);
|
|
418
|
+
return i < 0 ? all : all.slice(i + 1);
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
// The entries from `from` to `to`, both inclusive, oldest first. Empty when either id is missing.
|
|
422
|
+
export function rangeEntries(from: string, to: string): LogEntry[] {
|
|
423
|
+
const all = oldestFirst();
|
|
424
|
+
const a = all.findIndex(e => e.id === from);
|
|
425
|
+
const b = all.findIndex(e => e.id === to);
|
|
426
|
+
return a < 0 || b < 0 || b < a ? [] : all.slice(a, b + 1);
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
// Topics whose text holds every word (case-insensitive, any order), in file order.
|
|
430
|
+
export function searchTopics(query: readonly string[]): Segment[] {
|
|
431
|
+
const want = query.map(w => w.toLowerCase());
|
|
432
|
+
return readTopics().filter(s => {
|
|
433
|
+
const hay = [s.title, ...s.keywords, ...s.decisions.map(d => d.text), ...s.questions.map(q => q.text), ...s.names]
|
|
434
|
+
.join(" ")
|
|
435
|
+
.toLowerCase();
|
|
436
|
+
return want.every(w => hay.includes(w));
|
|
437
|
+
});
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
function percentile(sorted: number[], p: number): number {
|
|
441
|
+
return sorted[Math.min(sorted.length - 1, Math.max(0, Math.ceil(p * sorted.length) - 1))]!;
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
function spread(values: number[]): { mean: number; median: number; p90: number; min: number; max: number } {
|
|
445
|
+
const sorted = values.toSorted((a, b) => a - b);
|
|
446
|
+
if (sorted.length === 0) return { mean: 0, median: 0, p90: 0, min: 0, max: 0 };
|
|
447
|
+
return {
|
|
448
|
+
mean: sorted.reduce((a, b) => a + b, 0) / sorted.length,
|
|
449
|
+
median: percentile(sorted, 0.5),
|
|
450
|
+
p90: percentile(sorted, 0.9),
|
|
451
|
+
min: sorted[0]!,
|
|
452
|
+
max: sorted.at(-1)!,
|
|
453
|
+
};
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
// The ids of the live log file (not the backfill): a segment's lag is measured only where its `to` is live.
|
|
457
|
+
function liveIds(): Set<string> {
|
|
458
|
+
const ids = new Set<string>();
|
|
459
|
+
for (const line of readLines(ownerLogFile())) {
|
|
460
|
+
try {
|
|
461
|
+
const e = JSON.parse(line) as Partial<LogEntry>;
|
|
462
|
+
if (typeof e.id === "string") ids.add(e.id);
|
|
463
|
+
} catch {
|
|
464
|
+
// A torn line is skipped, as the reader skips it.
|
|
465
|
+
}
|
|
466
|
+
}
|
|
467
|
+
return ids;
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
// The one stats line every run ends with. Counts come from the index as it stands; tokens and calls are
|
|
471
|
+
// this run's. Lag is the age, in hours, of each segment's `to` entry, for the segments whose `to` is live.
|
|
472
|
+
function statsLine(tally: Tally): string {
|
|
473
|
+
const rows = effectiveRows();
|
|
474
|
+
const segments = rows.filter(isSegment);
|
|
475
|
+
const skipped = rows.length - segments.length;
|
|
476
|
+
const all = oldestFirst();
|
|
477
|
+
const byId = new Map(all.map((e, index) => [e.id, { index, at: e.at }]));
|
|
478
|
+
const counts = segments.flatMap(s => {
|
|
479
|
+
const a = byId.get(s.from);
|
|
480
|
+
const b = byId.get(s.to);
|
|
481
|
+
return a !== undefined && b !== undefined && b.index >= a.index ? [b.index - a.index + 1] : [];
|
|
482
|
+
});
|
|
483
|
+
const live = liveIds();
|
|
484
|
+
const lags = segments.flatMap(s => {
|
|
485
|
+
const b = byId.get(s.to);
|
|
486
|
+
return b !== undefined && live.has(s.to) ? [(nowSec() - b.at) / 3600] : [];
|
|
487
|
+
});
|
|
488
|
+
const perTopic = spread(counts);
|
|
489
|
+
const days = all.length > 0 ? (all.at(-1)!.at - all[0]!.at) / 86400 : 0;
|
|
490
|
+
const perDay = segments.length / Math.max(1, days);
|
|
491
|
+
const lag = spread(lags);
|
|
492
|
+
const lagText = lags.length === 0 ? "lag n/a" : `lag median ${lag.median.toFixed(1)}h p90 ${lag.p90.toFixed(1)}h`;
|
|
493
|
+
const entries = counts.reduce((a, b) => a + b, 0);
|
|
494
|
+
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}`;
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
// One topic run under the lock: segments the next window of new entries, then prints the stats line. With
|
|
498
|
+
// `close`, closes the open segment instead (no model call). Model errors append nothing; the caller prints
|
|
499
|
+
// the lines and exits by `failures`.
|
|
500
|
+
export async function runTopics(cfg: Config, complete: Complete, opts: { close: boolean }): Promise<TopicsRun> {
|
|
501
|
+
if (!opts.close && cfg.recall.topics_model === "") return { lines: ["topics: off"], failures: 0 };
|
|
502
|
+
const dir = ownerLogDir();
|
|
503
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
504
|
+
chmodSync(dir, 0o700);
|
|
505
|
+
const lock = tryLock(join(dir, LOCK_FILE));
|
|
506
|
+
if (lock === null) return { lines: ["topics: another run holds the lock"], failures: 0 };
|
|
507
|
+
try {
|
|
508
|
+
const tally: Tally = { calls: 0, tokensIn: 0, tokensOut: 0 };
|
|
509
|
+
if (opts.close) {
|
|
510
|
+
closeOpen();
|
|
511
|
+
return { lines: [statsLine(tally)], failures: 0 };
|
|
512
|
+
}
|
|
513
|
+
const rows = effectiveRows();
|
|
514
|
+
const window = newEntries(afterClosed(rows)).slice(0, WINDOW);
|
|
515
|
+
if (window.length === 0) return { lines: [statsLine(tally)], failures: 0 };
|
|
516
|
+
const failed = await segmentWindow(cfg, complete, window, rows, tally);
|
|
517
|
+
const lines = failed
|
|
518
|
+
? [`topics: fail ${window[0]!.id}..${window.at(-1)!.id} ${failed.reason} in=${failed.in} out=${failed.out}`]
|
|
519
|
+
: [];
|
|
520
|
+
lines.push(statsLine(tally));
|
|
521
|
+
return { lines, failures: failed ? 1 : 0 };
|
|
522
|
+
} finally {
|
|
523
|
+
lock.release();
|
|
524
|
+
}
|
|
525
|
+
}
|
package/templates/AGENTS.md
CHANGED
|
@@ -9,6 +9,7 @@ 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
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.
|
package/templates/config.yml
CHANGED
|
@@ -268,6 +268,10 @@ 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_every: 30 # Main owner-log entries between background topic runs; provisional until measured on the backfill
|
|
274
|
+
|
|
271
275
|
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
276
|
enabled: false # on = check every edit; off in the shipped template
|
|
273
277
|
applies_to: sub # "sub" = subagents only; "all" = Main too
|
|
@@ -0,0 +1,18 @@
|
|
|
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
|
+
`--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.
|
|
15
|
+
Usage: recall backfill [--since 7d|12h|YYYY-MM-DD]
|
|
16
|
+
Reads the harness's session files once and logs every owner message and Main answer from before the
|
|
17
|
+
live log began (secrets redacted). A second run adds nothing. Prints `backfill: <n> entries`.
|
|
18
|
+
Exit: 0 on a match, 1 when nothing matches, 2 on bad arguments or an unknown id.
|