@staix/agent-mem 0.23.1 → 0.24.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/plugin.json +1 -1
- package/README.md +14 -4
- package/package.json +1 -1
- package/src/brief-cache.ts +54 -0
- package/src/brief-capture.ts +82 -0
- package/src/brief-curated-native.ts +32 -0
- package/src/brief-curated.ts +65 -0
- package/src/cli.ts +1 -0
- package/src/curated-brief-cache.ts +29 -0
- package/src/hook-contract.ts +6 -2
- package/src/hook-record.ts +22 -2
- package/src/hook-spool-replay.ts +8 -1
- package/src/hook-spool.ts +2 -2
- package/src/hook-transcript.ts +10 -2
- package/src/hooks.ts +65 -14
- package/src/index.ts +5 -1
- package/src/memory/candidate-pending.ts +6 -2
- package/src/memory/candidates.ts +4 -2
- package/src/memory/capture-input.ts +7 -0
- package/src/memory/capture-plan.ts +10 -0
- package/src/memory/capture.ts +78 -8
- package/src/memory/curated-cache-state.ts +35 -0
- package/src/memory/formats.ts +6 -0
- package/src/memory/generation-index.ts +2 -0
- package/src/memory/generation-sync.ts +3 -0
- package/src/memory/metrics.ts +7 -1
- package/src/memory/migrate.ts +7 -1
- package/src/memory/public-prune-activation.ts +4 -1
- package/src/memory/public-prune-advance.ts +2 -0
- package/src/memory/reader-lease.ts +5 -3
- package/src/memory/record-instruction.ts +26 -0
- package/src/memory/record-variant-log.ts +90 -0
- package/src/memory/shard-migration.ts +4 -1
- package/src/memory/shard-sync.ts +3 -0
- package/src/memory/store.ts +131 -2
- package/src/memory/sync-placement-activation.ts +11 -3
- package/src/memory/sync-placement-transport.ts +3 -0
- package/src/memory/sync.ts +3 -2
- package/src/session-brief-worker.ts +13 -2
- package/src/session-brief.ts +130 -70
- package/src/ui/plugin.ts +104 -30
- package/src/ui/snapshot-cache.ts +141 -0
- package/src/ui/snapshot-revision.ts +87 -0
package/src/session-brief.ts
CHANGED
|
@@ -1,7 +1,12 @@
|
|
|
1
1
|
import { lstatSync, readFileSync } from "node:fs";
|
|
2
2
|
import { join } from "node:path";
|
|
3
|
-
import type { CaptureRow } from "./memory/capture.ts";
|
|
4
|
-
import {
|
|
3
|
+
import type { CaptureRow, CaptureStore } from "./memory/capture.ts";
|
|
4
|
+
import { readBriefCache } from "./brief-cache.ts";
|
|
5
|
+
import { noteDisplay, validCachedCurated } from "./brief-curated.ts";
|
|
6
|
+
import { CURATED_CACHE_MIN_READER, readCuratedBriefCache } from "./brief-curated-native.ts";
|
|
7
|
+
import { curatedProfileBinding } from "./memory/curated-cache-state.ts";
|
|
8
|
+
import { captureDisplay, displayText, recordDisplay, validCachedCapture } from "./brief-capture.ts";
|
|
9
|
+
import { assertFormatFloor, FormatFloorError } from "./memory/formats.ts";
|
|
5
10
|
import { readSelector } from "./memory/generation.ts";
|
|
6
11
|
import { memoryHome } from "./memory/home.ts";
|
|
7
12
|
import { canonicalPath, realPath } from "./memory/platform.ts";
|
|
@@ -14,7 +19,7 @@ import { type ReadRef, type ReadWindow } from "./memory/search-fts.ts";
|
|
|
14
19
|
import { aliasedKeys, captureShardDir, readShardedSelection, resolveAlias, shardDir } from "./memory/shard.ts";
|
|
15
20
|
import { projectState } from "./memory/lifecycle.ts";
|
|
16
21
|
import { boundRepoRoot, nearestRepoRootWithLog, readRepoScope, repoLogNearby, repoLogPresent, repoReadPolicy, type RepoView } from "./memory/repo-scope.ts";
|
|
17
|
-
import type { MemoryStore
|
|
22
|
+
import type { MemoryStore } from "./memory/store.ts";
|
|
18
23
|
import { WorkListStore, type WorkListFields, type WorkListView } from "./memory/work-lists.ts";
|
|
19
24
|
|
|
20
25
|
export interface BriefOptions { cwd: string; base?: string; project?: string; maxTokens?: number; policy?: StandalonePolicyOptions;
|
|
@@ -32,6 +37,7 @@ export interface BriefOptions { cwd: string; base?: string; project?: string; ma
|
|
|
32
37
|
* Read-only diagnostic/console projection: build the brief without writing to the memory home. No reader lease is taken. The caller supplies the two sections that would otherwise
|
|
33
38
|
* open a store read-write: `curated` is a store opened on a private copy of the logs (absent: the project has no curated notes, an empty complete section) and
|
|
34
39
|
* `workBase` is a private base holding a copy of the project's and its aliases' work logs (absent: the work section is `unavailable`, never claimed complete).
|
|
40
|
+
* With `nativeSession`, curated uses the same read-only cache/floor path as the native hook, rather than this copied curated store.
|
|
35
41
|
* The capture section opens this machine's capture database read-only, and only when it exists.
|
|
36
42
|
*/
|
|
37
43
|
measureOnly?: { curated?: MemoryStore; workBase?: string };
|
|
@@ -52,17 +58,6 @@ const unavailable = (): BriefResult => ({ context: "", tokens: 0, partial: true,
|
|
|
52
58
|
coverage: { work: "unavailable", curated: "unavailable", capture: "unavailable" } });
|
|
53
59
|
class BindingChanged extends Error {}
|
|
54
60
|
|
|
55
|
-
/** Bound display values only after complete-row policy. JSON records and flattened controls prevent line/header forgery. */
|
|
56
|
-
function displayText(text: string, maximum: number): { text: string; partial: boolean } {
|
|
57
|
-
const flattened = text.replace(/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/gu, " ");
|
|
58
|
-
let out = "", bytes = 0;
|
|
59
|
-
for (const character of flattened) {
|
|
60
|
-
const size = Buffer.byteLength(character);
|
|
61
|
-
if (bytes + size > maximum) return { text: out, partial: true };
|
|
62
|
-
out += character; bytes += size;
|
|
63
|
-
}
|
|
64
|
-
return { text: out, partial: flattened !== text };
|
|
65
|
-
}
|
|
66
61
|
function workDisplay(view: WorkListView): { data: unknown; partial: boolean } {
|
|
67
62
|
let partial = false;
|
|
68
63
|
const text = (value: string, bytes: number) => { const result = displayText(value, bytes); partial ||= result.partial; return result.text; };
|
|
@@ -83,31 +78,11 @@ function workDisplay(view: WorkListView): { data: unknown; partial: boolean } {
|
|
|
83
78
|
items: open.slice(0, 2).map(item => ({ task: text(item.task, 96), fields: fields(item.fields, 2) })) };
|
|
84
79
|
return { data, partial };
|
|
85
80
|
}
|
|
86
|
-
function noteDisplay(view: View): { data: unknown; partial: boolean } {
|
|
87
|
-
const body = displayText(view.text, 240), title = view.title === null ? undefined : displayText(view.title, 96);
|
|
88
|
-
return { data: { id: view.id, at: view.at, kind: view.kind, ...(title ? { title: title.text } : {}), text: body.text },
|
|
89
|
-
partial: body.partial || title?.partial === true };
|
|
90
|
-
}
|
|
91
81
|
function repoDisplay(view: RepoView): { data: unknown; partial: boolean } {
|
|
92
82
|
const body = displayText(view.text, 240), title = view.title === null ? undefined : displayText(view.title, 96);
|
|
93
83
|
return { data: { id: `repo:${view.id}`, at: view.at, kind: view.kind, ...(title ? { title: title.text } : {}), text: body.text },
|
|
94
84
|
partial: body.partial || title?.partial === true };
|
|
95
85
|
}
|
|
96
|
-
function captureDisplay(row: CaptureRow): { data: unknown; partial: boolean } {
|
|
97
|
-
const excerpt = displayText(row.excerpt, 240), event = displayText(row.event, 64);
|
|
98
|
-
const paths = row.paths.slice(0, 2).map(path => displayText(path, 80));
|
|
99
|
-
return { data: { id: row.id, at: row.at, event: event.text, paths: paths.map(path => path.text), excerpt: excerpt.text },
|
|
100
|
-
partial: excerpt.partial || event.partial || row.paths.length > paths.length || paths.some(path => path.partial) };
|
|
101
|
-
}
|
|
102
|
-
|
|
103
|
-
/** Keep the canonical Record whole; '-' is valid only for project-bound decisions/contracts. */
|
|
104
|
-
function recordDisplay(row: CaptureRow): { data: unknown; partial: boolean } | undefined {
|
|
105
|
-
const parsed = parseRecordLines(row.excerpt), record = parsed.records[0];
|
|
106
|
-
if (!record || parsed.records.length !== 1 || Object.keys(parsed.drops).length || record.line !== row.excerpt
|
|
107
|
-
|| JSON.stringify(record.anchors) !== JSON.stringify(row.paths)) return;
|
|
108
|
-
return { data: { event: "Record", paths: record.anchors, excerpt: record.line }, partial: false };
|
|
109
|
-
}
|
|
110
|
-
|
|
111
86
|
/** A short-lived, model-free projection. The hook host supplies the hard process deadline; this function owns no timer or child. */
|
|
112
87
|
export async function sessionStartBrief(options: BriefOptions): Promise<BriefResult> {
|
|
113
88
|
let result = unavailable();
|
|
@@ -154,13 +129,98 @@ export async function sessionStartBrief(options: BriefOptions): Promise<BriefRes
|
|
|
154
129
|
const lines: string[] = [];
|
|
155
130
|
const reasons: Partial<Record<Section, string>> = {};
|
|
156
131
|
// Reserve the longest possible fixed header before selecting data; later coverage changes cannot overrun it.
|
|
157
|
-
let remaining = maximum - Buffer.byteLength(header({ work: "unavailable", curated: "unavailable", capture: "unavailable", ...(coverage.repo ? { repo: "unavailable" as const } : {}) }, options.nativeSession ? { work: "deadline exhausted", curated: "generation refresh deferred", capture: "capture
|
|
132
|
+
let remaining = maximum - Buffer.byteLength(header({ work: "unavailable", curated: "unavailable", capture: "unavailable", ...(coverage.repo ? { repo: "unavailable" as const } : {}) }, options.nativeSession ? { work: "deadline exhausted", curated: "generation refresh deferred", capture: "capture cache missing" } : {}));
|
|
158
133
|
// F7: one line, "N candidates pending, oldest expires in D days", only when some wait, so a brief with none is byte-identical to before. It is numbers only (no candidate text),
|
|
159
134
|
// read-only (no database is created, pruned or altered here, and neither the brief nor the hook ever stamps a candidate as shown: only `amem review walk` does) and reserved out of the
|
|
160
135
|
// same byte budget as everything else; when it does not fit it is left out.
|
|
161
136
|
let candidateLine: string | undefined;
|
|
162
137
|
const line = pendingLine(pendingSummary(base, [project, ...aliases], (options.now ?? Date.now)()));
|
|
163
138
|
if (line !== undefined && Buffer.byteLength(line) + 1 <= remaining) { remaining -= Buffer.byteLength(line) + 1; candidateLine = line; }
|
|
139
|
+
// Preload and screen before work can spend the deadline; only the newest summary reserves bytes here.
|
|
140
|
+
type PreparedCapture = { line: string; size: number; partial: boolean };
|
|
141
|
+
const preparedRecords: PreparedCapture[] = [], preparedSummaries: PreparedCapture[] = [];
|
|
142
|
+
const summaryIds = new Set<number>();
|
|
143
|
+
const prepare = (shown: { data: unknown; partial: boolean }): PreparedCapture => {
|
|
144
|
+
const line = JSON.stringify({ section: "capture", evidence: false, data: shown.data });
|
|
145
|
+
return { line, size: Buffer.byteLength(line) + 1, partial: shown.partial };
|
|
146
|
+
};
|
|
147
|
+
// Capture diagnostics retain the read-only library projection, including raw chronological fill.
|
|
148
|
+
// Curated diagnostics mirror native cache admission so they cannot claim context the hook would omit.
|
|
149
|
+
const nativeCache = !!options.nativeSession && !options.measureOnly;
|
|
150
|
+
const nativeCurated = !!options.nativeSession;
|
|
151
|
+
const preparedCurated: { line: string; size: number; partial: boolean }[] = [];
|
|
152
|
+
if (nativeCurated) {
|
|
153
|
+
const deferredReason = sharded || readSelector(base).selector?.kind === "generation" ? "generation refresh deferred" : "curated refresh deferred";
|
|
154
|
+
const prepared = readCuratedBriefCache({ base, project, profile: curatedProfileBinding(base, project),
|
|
155
|
+
supportingRelease: CURATED_CACHE_MIN_READER, deferredReason, now: (options.now ?? Date.now)() });
|
|
156
|
+
if (!prepared.cache) { coverage.curated = "unavailable"; reasons.curated = prepared.reason!; }
|
|
157
|
+
else {
|
|
158
|
+
coverage.curated = prepared.cache.partial ? "partial" : "complete";
|
|
159
|
+
for (const row of prepared.cache.rows) {
|
|
160
|
+
if (preparedCurated.length >= SECTION_RECORDS || !validCachedCurated(row, project, (options.now ?? Date.now)())
|
|
161
|
+
|| !await screen(row.source) || !await screen(row.data)) { coverage.curated = "partial"; continue; }
|
|
162
|
+
const line = JSON.stringify({ section: "curated", evidence: true, data: row.data });
|
|
163
|
+
preparedCurated.push({ line, size: Buffer.byteLength(line) + 1, partial: row.partial });
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
guard();
|
|
167
|
+
}
|
|
168
|
+
let capture: CaptureStore | undefined, captureFailed = false;
|
|
169
|
+
if (nativeCache) {
|
|
170
|
+
let floorReason: string | undefined;
|
|
171
|
+
try { assertFormatFloor(base, "capture"); }
|
|
172
|
+
catch (error) { floorReason = error instanceof FormatFloorError && error.code === "format_floor" ? "floor: upgrade amem" : "floor: amem doctor"; }
|
|
173
|
+
let machine: string | undefined;
|
|
174
|
+
if (!floorReason) try { machine = JSON.parse(readFileSync(join(base, "machine.json"), "utf8")).id; } catch { /* no machine, no cache */ }
|
|
175
|
+
const cache = !floorReason && typeof machine === "string" && /^[a-f0-9]{16}$/.test(machine)
|
|
176
|
+
? readBriefCache({ directory: captureShardDir(base, project, machine), project, section: "capture" }) : undefined;
|
|
177
|
+
if (floorReason) { coverage.capture = "unavailable"; reasons.capture = floorReason; }
|
|
178
|
+
else if (!cache) { coverage.capture = "unavailable"; reasons.capture = "capture cache missing"; }
|
|
179
|
+
else {
|
|
180
|
+
coverage.capture = cache.partial ? "partial" : "complete";
|
|
181
|
+
for (const row of cache.rows) {
|
|
182
|
+
if (!validCachedCapture(row, project) || !await screen(row.source) || !await screen(row.data)) { coverage.capture = "partial"; continue; }
|
|
183
|
+
const target = (row.source as CaptureRow).event === "Record" ? preparedRecords : preparedSummaries;
|
|
184
|
+
if (target.length >= (target === preparedRecords ? 5 : 2)) { coverage.capture = "partial"; continue; }
|
|
185
|
+
target.push(prepare(row));
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
} else try {
|
|
189
|
+
const { CaptureStore } = await import("./memory/capture.ts");
|
|
190
|
+
const machine = (() => { try { return JSON.parse(readFileSync(join(base, "machine.json"), "utf8")).id; } catch { return undefined; } })();
|
|
191
|
+
const present = !options.measureOnly || typeof machine === "string" && /^[a-f0-9]{16}$/.test(machine)
|
|
192
|
+
&& !!lstatSync(join(captureShardDir(base, project, machine), "capture.db"), { throwIfNoEntry: false });
|
|
193
|
+
if (present) {
|
|
194
|
+
capture = new CaptureStore({ memoryDir: base, project, cwd, ...(options.nativeSession || options.measureOnly ? { readOnly: true, busyTimeoutMs: options.measureOnly ? 1000 : 0, maxReadRows: 128, recentReadRows: true } : {}) });
|
|
195
|
+
closers.push(() => capture!.close());
|
|
196
|
+
const summaries = capture.readBriefSummaries();
|
|
197
|
+
if (capture.recentReadTruncated || summaries.partial) coverage.capture = "partial";
|
|
198
|
+
for (const row of summaries.rows) {
|
|
199
|
+
if (row.project !== project) continue;
|
|
200
|
+
if (preparedSummaries.length >= 2) break;
|
|
201
|
+
summaryIds.add(row.id);
|
|
202
|
+
if (row.subagent === true || !await screen(row)) continue;
|
|
203
|
+
const shown = captureDisplay(row);
|
|
204
|
+
if (await screen(shown.data)) preparedSummaries.push(prepare(shown));
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
} catch (error) {
|
|
208
|
+
if (error instanceof BindingChanged || drifted) throw new BindingChanged();
|
|
209
|
+
captureFailed = true;
|
|
210
|
+
}
|
|
211
|
+
const newest = preparedSummaries[0];
|
|
212
|
+
const reservedSummary = newest && newest.size - 1 <= RECORD_BYTES && newest.size <= remaining ? newest : undefined;
|
|
213
|
+
if (reservedSummary) remaining -= reservedSummary.size;
|
|
214
|
+
else if (newest) coverage.capture = "partial";
|
|
215
|
+
const emitPrepared = (row: PreparedCapture): boolean => {
|
|
216
|
+
if (row.size - 1 > RECORD_BYTES || row.size > remaining) { coverage.capture = "partial"; return false; }
|
|
217
|
+
lines.push(row.line); remaining -= row.size;
|
|
218
|
+
if (row.partial) coverage.capture = "partial";
|
|
219
|
+
return true;
|
|
220
|
+
};
|
|
221
|
+
const emitReserved = () => {
|
|
222
|
+
if (reservedSummary) { lines.push(reservedSummary.line); if (reservedSummary.partial) coverage.capture = "partial"; }
|
|
223
|
+
};
|
|
164
224
|
const add = async (section: Section, shown: { data: unknown; partial: boolean }, evidence: boolean): Promise<boolean> => {
|
|
165
225
|
if (!await screen(shown.data)) return false;
|
|
166
226
|
coverage[section] = shown.partial ? "partial" : coverage[section] ?? "complete";
|
|
@@ -225,11 +285,13 @@ export async function sessionStartBrief(options: BriefOptions): Promise<BriefRes
|
|
|
225
285
|
}
|
|
226
286
|
if (!complete) coverage[section] = "partial";
|
|
227
287
|
};
|
|
228
|
-
if (
|
|
229
|
-
//
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
288
|
+
if (nativeCurated) {
|
|
289
|
+
// Pre-screened before work, but allocated only now from the remaining pool.
|
|
290
|
+
for (const row of preparedCurated) {
|
|
291
|
+
if (row.size - 1 > RECORD_BYTES || row.size > remaining) { coverage.curated = "partial"; continue; }
|
|
292
|
+
lines.push(row.line); remaining -= row.size;
|
|
293
|
+
if (row.partial) coverage.curated = "partial";
|
|
294
|
+
}
|
|
233
295
|
} else if (options.measureOnly) await run("curated", async () => {
|
|
234
296
|
const store = options.measureOnly!.curated;
|
|
235
297
|
if (store) await recent("curated", window => store.readPage(window), noteDisplay); // no store: no curated notes, an empty and complete section
|
|
@@ -253,37 +315,35 @@ export async function sessionStartBrief(options: BriefOptions): Promise<BriefRes
|
|
|
253
315
|
await add("repo", repoDisplay(view), false); // repo lines are reviewed repository content, not the person's own curated evidence
|
|
254
316
|
}
|
|
255
317
|
});
|
|
256
|
-
|
|
257
|
-
const
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
if (await add("capture", captureDisplay(row), false)) selectedSummaries++;
|
|
318
|
+
if (nativeCache) {
|
|
319
|
+
for (const row of preparedRecords) emitPrepared(row);
|
|
320
|
+
emitReserved();
|
|
321
|
+
for (const row of preparedSummaries.slice(1)) emitPrepared(row);
|
|
322
|
+
} else {
|
|
323
|
+
const firstCaptureLine = lines.length;
|
|
324
|
+
await run("capture", async () => {
|
|
325
|
+
if (captureFailed) throw new Error("capture unavailable");
|
|
326
|
+
if (!capture) return;
|
|
327
|
+
const records = capture.readBriefRecords();
|
|
328
|
+
if (records.partial) coverage.capture = "partial";
|
|
329
|
+
let selectedRecords = 0;
|
|
330
|
+
for (const row of records.rows) {
|
|
331
|
+
if (row.project !== project || row.subagent === true) continue;
|
|
332
|
+
if (selectedRecords >= 5) { coverage.capture = "partial"; break; }
|
|
333
|
+
if (!await screen(row)) continue;
|
|
334
|
+
const shown = recordDisplay(row);
|
|
335
|
+
if (shown && await add("capture", shown, false)) selectedRecords++;
|
|
336
|
+
}
|
|
337
|
+
emitReserved();
|
|
338
|
+
let selectedSummaries = reservedSummary ? 1 : 0;
|
|
339
|
+
for (const row of preparedSummaries.slice(1)) if (emitPrepared(row)) selectedSummaries++;
|
|
340
|
+
await recent("capture", window => capture!.readPage(window), captureDisplay, selectedSummaries, summaryIds);
|
|
341
|
+
});
|
|
342
|
+
// A slow work section may defer optional database reads, but cannot discard the already-screened reservation.
|
|
343
|
+
if (reservedSummary && !lines.slice(firstCaptureLine).includes(reservedSummary.line)) {
|
|
344
|
+
emitReserved(); coverage.capture = "partial";
|
|
284
345
|
}
|
|
285
|
-
|
|
286
|
-
});
|
|
346
|
+
}
|
|
287
347
|
guard();
|
|
288
348
|
const context = [header(coverage, reasons), ...(candidateLine ? [candidateLine] : []), ...lines].join("\n");
|
|
289
349
|
result = { context, tokens: Buffer.byteLength(context), partial: Object.values(coverage).some(value => value !== "complete"), coverage };
|
package/src/ui/plugin.ts
CHANGED
|
@@ -5,6 +5,9 @@
|
|
|
5
5
|
*/
|
|
6
6
|
import { createHash } from "node:crypto";
|
|
7
7
|
import { InboxCache } from "./inbox-cache.ts";
|
|
8
|
+
import { SnapshotCache } from "./snapshot-cache.ts";
|
|
9
|
+
import { snapshotRevision } from "./snapshot-revision.ts";
|
|
10
|
+
import { canonicalJSON, readSelector } from "../memory/generation.ts";
|
|
8
11
|
import { candidateText, candidateTargets as targetsOf, visibleCandidate as visible } from "./inbox.ts";
|
|
9
12
|
export { candidateText } from "./inbox.ts";
|
|
10
13
|
import { existsSync, readFileSync } from "node:fs";
|
|
@@ -13,7 +16,8 @@ import { createMemoryMcp } from "../mcp-memory.ts";
|
|
|
13
16
|
import { sessionStartBrief } from "../session-brief.ts";
|
|
14
17
|
import { withBriefSnapshot } from "../memory/doctor.ts";
|
|
15
18
|
import { MCP_TOOLS } from "../mcp.ts";
|
|
16
|
-
import { CandidateStore, type Candidate, type CandidateInput } from "../memory/candidates.ts";
|
|
19
|
+
import { CandidateStore, withPendingCandidates, type Candidate, type CandidateInput } from "../memory/candidates.ts";
|
|
20
|
+
import { pendingSummary } from "../memory/candidate-pending.ts";
|
|
17
21
|
import { candidateOverlapsBatch } from "../memory/candidate-overlaps.ts";
|
|
18
22
|
import { capacityReport } from "../memory/capacity.ts";
|
|
19
23
|
import { readCaptureConfigFile, writeCaptureConfigFile } from "../memory/capture.ts";
|
|
@@ -111,15 +115,22 @@ export const plugin = {
|
|
|
111
115
|
try { return run(store); } finally { store.close(); }
|
|
112
116
|
};
|
|
113
117
|
|
|
118
|
+
const snapshots = new SnapshotCache(() => snapshotRevision(base));
|
|
119
|
+
let catalog: { revision: string; list: string[]; until: number; sampledAt: number } | undefined;
|
|
120
|
+
let catalogExpiry = Infinity;
|
|
121
|
+
const expiryOf = (views: View[]) => views.reduce((until, view) => view.expiresAt === null ? until : Math.min(until, Date.parse(view.expiresAt)), Infinity);
|
|
114
122
|
/** Projects with notes in an unsplit (shared-v1 or generation) home: that store is one file set for every project, with no shard per project. */
|
|
115
123
|
function sharedStoreProjects(): string[] {
|
|
116
124
|
if (existsSync(join(base, "shards.json")) || !["log", "local", "generations"].some(dir => existsSync(join(base, dir)))) return [];
|
|
117
125
|
const store = new MemoryStore({ memoryDir: base, deferPromotions: true });
|
|
118
|
-
|
|
119
|
-
|
|
126
|
+
try {
|
|
127
|
+
const views = store.list({ limit: Number.MAX_SAFE_INTEGER, includeSuperseded: true });
|
|
128
|
+
catalogExpiry = Math.min(catalogExpiry, expiryOf(views));
|
|
129
|
+
return [...new Set(views.filter(view => !view.supersededBy).map(view => view.project))];
|
|
130
|
+
} finally { store.close(); }
|
|
120
131
|
}
|
|
121
|
-
// ponytail: the catalog scan walks every shard on each snapshot; cache it by shard mtimes if polls get slow on a large home.
|
|
122
132
|
function projects(): string[] {
|
|
133
|
+
catalogExpiry = Infinity;
|
|
123
134
|
if (!existsSync(base)) return [];
|
|
124
135
|
const keys = new Set<string>(), waiting = new Set<string>();
|
|
125
136
|
try { for (const p of readCatalogFresh(base)) keys.add(p.key); } catch (e) { ctx.log(`amem: project catalog unavailable: ${errorText(e)}`); }
|
|
@@ -127,9 +138,26 @@ export const plugin = {
|
|
|
127
138
|
if (hasCandidates()) for (const key of withCandidates(undefined, store => store.projects())) { const canonical = resolveAlias(base, key); keys.add(canonical); waiting.add(canonical); }
|
|
128
139
|
return [...keys].filter(key => projectState(base, key) === "active").sort((a, b) => Number(waiting.has(b)) - Number(waiting.has(a)) || a.localeCompare(b));
|
|
129
140
|
}
|
|
141
|
+
function projectList(): { list: string[]; cacheable: boolean } {
|
|
142
|
+
let revision: string;
|
|
143
|
+
try { revision = snapshotRevision(base); }
|
|
144
|
+
catch { catalog = undefined; return { list: projects(), cacheable: false }; }
|
|
145
|
+
const now = Date.now();
|
|
146
|
+
if (catalog?.revision === revision && now >= catalog.sampledAt && now < catalog.until) return { list: [...catalog.list], cacheable: true };
|
|
147
|
+
const list = projects();
|
|
148
|
+
// A missing witness affects reuse only; ordinary fresh reads remain available.
|
|
149
|
+
try {
|
|
150
|
+
if (snapshotRevision(base) === revision) {
|
|
151
|
+
catalog = { revision, list: [...list], sampledAt: now, until: catalogExpiry };
|
|
152
|
+
return { list, cacheable: true };
|
|
153
|
+
}
|
|
154
|
+
} catch { /* Uncacheable; do not turn an inventory race into a panel failure. */ }
|
|
155
|
+
catalog = undefined;
|
|
156
|
+
return { list, cacheable: false };
|
|
157
|
+
}
|
|
130
158
|
// The shell's tabs navigate without params, so the project chosen on one panel is kept for the others and the palette.
|
|
131
159
|
// ponytail: one choice per provider; fine for H0's single person, per session once a console serves several.
|
|
132
|
-
let chosen: string | undefined;
|
|
160
|
+
let chosen: string | undefined, actionVersion = 0;
|
|
133
161
|
/** An active project whose curated store holds a note of its own, also when no listing source named it. */
|
|
134
162
|
const exists = (key: string) => {
|
|
135
163
|
if (projectState(base, key) !== "active") return false;
|
|
@@ -163,11 +191,12 @@ export const plugin = {
|
|
|
163
191
|
}
|
|
164
192
|
|
|
165
193
|
const projectOf = new Map<string, string>();
|
|
166
|
-
async function pending(project: string, detail: boolean) {
|
|
194
|
+
async function pending(project: string, detail: boolean, onExpiry?: (at: number) => void) {
|
|
167
195
|
if (!hasCandidates()) return { rows: [], hidden: 0 };
|
|
168
196
|
const p = policy(), store = openCuratedForRead(base, project);
|
|
169
197
|
try {
|
|
170
|
-
|
|
198
|
+
if (store && onExpiry) onExpiry(expiryOf(store.list({ project, limit: Number.MAX_SAFE_INTEGER, includeSuperseded: true })));
|
|
199
|
+
const all = withPendingCandidates(base, reader => reader.list([project, ...aliasedKeys(base, project)]));
|
|
171
200
|
const shown = all.filter(c => visible(c, project, store, p));
|
|
172
201
|
for (const c of shown) projectOf.set(c.id, project);
|
|
173
202
|
const overlaps = detail && store ? await candidateOverlapsBatch(shown, store, { project, policy, policyVersion }) : [];
|
|
@@ -204,14 +233,18 @@ export const plugin = {
|
|
|
204
233
|
...(view?.title ? { detail: oneLine(view.text, 120) } : {}), ...(view?.at ?? capture?.at ? { at: view?.at ?? capture?.at } : {}), link: { panel: "find", params: { project, q } } };
|
|
205
234
|
}
|
|
206
235
|
|
|
207
|
-
async function panel(name: string, args: Args, project: string): Promise<Args> {
|
|
236
|
+
async function panel(name: string, args: Args, project: string, onExpiry?: (at: number) => void): Promise<Args> {
|
|
208
237
|
switch (name) {
|
|
209
|
-
case "review": return { ...(await pending(project, true)), selected: str(args.id) ?? null };
|
|
238
|
+
case "review": return { ...(await pending(project, true, onExpiry)), selected: str(args.id) ?? null };
|
|
210
239
|
case "recap": {
|
|
211
240
|
const revision = policyVersion(), generatedAt = new Date().toISOString();
|
|
212
241
|
assertProjectActive(base, project);
|
|
213
|
-
|
|
214
|
-
|
|
242
|
+
if (onExpiry && pendingSummary(base, [project, ...aliasedKeys(base, project)], Date.now(), true, onExpiry) === null)
|
|
243
|
+
onExpiry(-Infinity); // Unknown candidate timing disables reuse, never the fresh projection.
|
|
244
|
+
const brief = await withBriefSnapshot(base, project, measureOnly => {
|
|
245
|
+
if (measureOnly.curated && onExpiry) onExpiry(expiryOf(measureOnly.curated.list({ project, limit: Number.MAX_SAFE_INTEGER, includeSuperseded: true })));
|
|
246
|
+
return sessionStartBrief({ cwd: base, base, project, repository: false, policy: configuredPolicyOptions(base), measureOnly });
|
|
247
|
+
});
|
|
215
248
|
assertProjectActive(base, project);
|
|
216
249
|
if (policyVersion() !== revision) throw Error("recap policy changed");
|
|
217
250
|
return { brief, generatedAt, repoAbsent: true };
|
|
@@ -395,35 +428,76 @@ export const plugin = {
|
|
|
395
428
|
return { ok: false, error: `unknown action ${String(input.action)}` };
|
|
396
429
|
}
|
|
397
430
|
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
431
|
+
const preparedReads = new Set<string>();
|
|
432
|
+
const cachedPanels = new Set(["review", "recap", "work"]);
|
|
433
|
+
async function snapshot(input: { after: number; panel: string } & Args): Promise<Args> {
|
|
434
|
+
const args = input as Args;
|
|
435
|
+
if (input.panel === "inbox") {
|
|
436
|
+
const value = await inboxCache.snapshot();
|
|
437
|
+
for (const item of value.items) if (item.group === "candidate" && item.link.params?.project) projectOf.set(item.id, item.link.params.project);
|
|
438
|
+
return { ...value };
|
|
439
|
+
}
|
|
440
|
+
let list: string[] = [], project: string | undefined;
|
|
441
|
+
try {
|
|
442
|
+
if (input.panel === "timeline" || input.panel === "work") {
|
|
443
|
+
const requested = str(args.project), selected = requested ? resolveAlias(base, requested) : chosen;
|
|
444
|
+
const bindingOf = (key: string) => canonicalJSON([key, readSelector(base).revision, aliasedKeys(base, key)]);
|
|
445
|
+
if (!selected || !preparedReads.has(bindingOf(selected))) {
|
|
446
|
+
// Settle cold MCP schemas/pruning before the first cache revision read.
|
|
447
|
+
// This is ordinary setup, never a published revision or a retained lease.
|
|
448
|
+
const initial = pick(args, projects());
|
|
449
|
+
if (initial) {
|
|
450
|
+
const prepared = createMemoryMcp({ cwd: base, base, project: initial }); prepared.close();
|
|
451
|
+
if (preparedReads.size >= 16) preparedReads.delete(preparedReads.values().next().value!);
|
|
452
|
+
preparedReads.add(bindingOf(initial)); catalog = undefined;
|
|
453
|
+
}
|
|
454
|
+
}
|
|
407
455
|
}
|
|
408
|
-
const
|
|
456
|
+
const selection = cachedPanels.has(input.panel) ? projectList() : { list: projects(), cacheable: false };
|
|
457
|
+
list = selection.list; project = pick(args, list);
|
|
409
458
|
if (str(args.project) && !project) return { projects: list, project: null, error: "The requested memory project is unavailable; choose an active project from the project selector." };
|
|
410
459
|
if (input.panel === "search") {
|
|
411
460
|
const q = str(args.q);
|
|
412
461
|
if (!q || !project) return { hits: [], total: 0 };
|
|
413
462
|
const limit = Math.min(10, Math.max(1, Number(args.limit) || 10));
|
|
414
463
|
const result = await read(project, "amem_search", { query: q, limit }) as { hits: Args[] };
|
|
415
|
-
const hits = result.hits.map(hit => searchHit(hit, project
|
|
464
|
+
const hits = result.hits.map(hit => searchHit(hit, project!, q));
|
|
416
465
|
return { hits, total: hits.length };
|
|
417
466
|
}
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
}
|
|
425
|
-
|
|
467
|
+
const load = async (onExpiry?: (at: number) => void): Promise<Args> => input.panel === "capacity"
|
|
468
|
+
? { projects: list, project: project ?? null, ...(await capacity() ?? { report: null }) }
|
|
469
|
+
: !project ? { projects: list, project: null } : { projects: list, project, ...(await panel(input.panel, args, project, onExpiry)) };
|
|
470
|
+
// Capacity samples resources/time; Timeline probes arbitrary referenced files.
|
|
471
|
+
// Neither has a cheap complete revision, so both stay uncached.
|
|
472
|
+
if (!cachedPanels.has(input.panel)) return await load();
|
|
473
|
+
const key = canonicalJSON({ ...args, after: undefined, project: project ?? null, projects: list });
|
|
474
|
+
let projectionVersion = actionVersion;
|
|
475
|
+
const projection = async () => {
|
|
476
|
+
if (projectionVersion !== actionVersion) {
|
|
477
|
+
list = projects(); project = pick(args, list); catalog = undefined;
|
|
478
|
+
projectionVersion = actionVersion;
|
|
479
|
+
}
|
|
480
|
+
let until = Math.min(catalogExpiry,
|
|
481
|
+
withPendingCandidates(base, reader => reader.nextExpiry()) ?? Infinity);
|
|
482
|
+
const data = await load(at => { until = Math.min(until, at); });
|
|
483
|
+
return { data, until };
|
|
484
|
+
};
|
|
485
|
+
return selection.cacheable ? await snapshots.snapshot(key, input.after, projection) : await snapshots.fresh(projection);
|
|
486
|
+
} catch (e) {
|
|
487
|
+
ctx.log(`amem: ${input.panel} for ${project ?? "project"} failed: ${errorText(e)}`);
|
|
488
|
+
return { projects: list, project: project ?? null, error: "Memory is unavailable for this project right now; details are in the terminal." };
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
// The measured cold Review path opens the curated index and computes overlaps.
|
|
492
|
+
// Warm only the initial selection, once; never enumerate every project's bodies.
|
|
493
|
+
try { projects(); await snapshot({ panel: "review", after: 0 }); }
|
|
494
|
+
catch (e) { ctx.log(`amem: review warm-up unavailable: ${errorText(e)}`); }
|
|
495
|
+
return {
|
|
496
|
+
assets: { js: asset("./panel.js"), css: asset("./panel.css") },
|
|
497
|
+
close: async () => { catalog = undefined; preparedReads.clear(); await Promise.all([snapshots.close(), inboxCache.close()]); },
|
|
498
|
+
snapshot,
|
|
426
499
|
async action(input) {
|
|
500
|
+
actionVersion++; snapshots.invalidate(); catalog = undefined;
|
|
427
501
|
const result = await performAction(input);
|
|
428
502
|
if (result.ok) {
|
|
429
503
|
const id = str(input.id);
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
|
|
3
|
+
type Data = Record<string, unknown>;
|
|
4
|
+
interface Entry { sampledAt: number; generation: number; epoch: number; data: Data; revision: string; cursor: number; until: number; bytes: number }
|
|
5
|
+
export interface SnapshotValue { data: Data; until: number }
|
|
6
|
+
interface Reading extends SnapshotValue { sampledAt: number; generation: number; entry?: Entry }
|
|
7
|
+
|
|
8
|
+
/** Provider-local screened snapshots. No disk cache, timer, watcher or retained store. */
|
|
9
|
+
export class SnapshotCache {
|
|
10
|
+
private entries = new Map<string, Entry>();
|
|
11
|
+
private flights = new Map<string, Promise<Reading>>();
|
|
12
|
+
private active = new Set<Promise<unknown>>();
|
|
13
|
+
private generation = 0;
|
|
14
|
+
private epoch = 0;
|
|
15
|
+
private reuseUnavailable = false;
|
|
16
|
+
// Cached digests occupy the lower 52 bits; fresh replies have distinct safe-integer cursors above them.
|
|
17
|
+
private freshCursor = 2 ** 52;
|
|
18
|
+
private bytes = 0;
|
|
19
|
+
private closed = false;
|
|
20
|
+
constructor(private readonly revision: () => string, private readonly now: () => number = Date.now) {}
|
|
21
|
+
private clearReusable(): void { this.epoch++; this.entries.clear(); this.bytes = 0; this.flights.clear(); }
|
|
22
|
+
invalidate(): void { this.generation++; this.clearReusable(); }
|
|
23
|
+
async close(): Promise<void> { this.closed = true; this.invalidate(); await Promise.allSettled([...this.active]); }
|
|
24
|
+
private disableReuse(): void {
|
|
25
|
+
if (!this.reuseUnavailable) this.clearReusable();
|
|
26
|
+
this.reuseUnavailable = true;
|
|
27
|
+
}
|
|
28
|
+
private sourceRevision(): string | undefined {
|
|
29
|
+
let revision: string;
|
|
30
|
+
try { revision = this.revision(); }
|
|
31
|
+
catch { this.disableReuse(); return undefined; }
|
|
32
|
+
this.reuseUnavailable = false;
|
|
33
|
+
return revision;
|
|
34
|
+
}
|
|
35
|
+
private timely(sampledAt: number, until: number): boolean {
|
|
36
|
+
const now = this.now();
|
|
37
|
+
return now >= sampledAt && now < until;
|
|
38
|
+
}
|
|
39
|
+
private readable(value?: SnapshotValue): void {
|
|
40
|
+
if (this.closed) throw Error("console snapshots are closed");
|
|
41
|
+
if (value?.data.error !== undefined) throw Error("console snapshot unavailable");
|
|
42
|
+
}
|
|
43
|
+
private track<T>(work: Promise<T>): Promise<T> {
|
|
44
|
+
this.active.add(work);
|
|
45
|
+
void work.then(() => this.active.delete(work), () => this.active.delete(work));
|
|
46
|
+
return work;
|
|
47
|
+
}
|
|
48
|
+
private freshReply(data: Data): Data {
|
|
49
|
+
this.readable();
|
|
50
|
+
if (this.freshCursor >= Number.MAX_SAFE_INTEGER) throw Error("console fresh cursor limit");
|
|
51
|
+
const copy = structuredClone(data);
|
|
52
|
+
delete copy.changed;
|
|
53
|
+
return { ...copy, cursor: ++this.freshCursor };
|
|
54
|
+
}
|
|
55
|
+
private readFresh(read: () => Promise<SnapshotValue>, retryAction: boolean): Promise<Data> {
|
|
56
|
+
this.readable();
|
|
57
|
+
if (this.active.size >= 16) throw Error("console snapshot concurrency limit");
|
|
58
|
+
const generation = this.generation;
|
|
59
|
+
return this.track((async () => {
|
|
60
|
+
let value = await read();
|
|
61
|
+
this.readable(value);
|
|
62
|
+
// One post-action reread only. Further changes still yield full uncached data, never a retry loop.
|
|
63
|
+
if (retryAction && generation !== this.generation) { value = await read(); this.readable(value); }
|
|
64
|
+
return this.freshReply(value.data);
|
|
65
|
+
})());
|
|
66
|
+
}
|
|
67
|
+
/** A request with no complete revision computes independently without consulting another revision or retaining data. */
|
|
68
|
+
async fresh(read: () => Promise<SnapshotValue>): Promise<Data> {
|
|
69
|
+
this.readable(); this.disableReuse();
|
|
70
|
+
return this.readFresh(read, true);
|
|
71
|
+
}
|
|
72
|
+
private dropEntry(key: string, entry: Entry | undefined): void {
|
|
73
|
+
if (entry && this.entries.get(key) === entry) { this.entries.delete(key); this.bytes -= entry.bytes; }
|
|
74
|
+
}
|
|
75
|
+
async snapshot(key: string, after: number, read: () => Promise<SnapshotValue>): Promise<Data> {
|
|
76
|
+
this.readable();
|
|
77
|
+
const revision = this.sourceRevision();
|
|
78
|
+
this.readable();
|
|
79
|
+
if (revision === undefined) return this.fresh(read);
|
|
80
|
+
const cached = this.entries.get(key);
|
|
81
|
+
if (cached && cached.revision === revision && this.timely(cached.sampledAt, cached.until)) {
|
|
82
|
+
this.entries.delete(key); this.entries.set(key, cached);
|
|
83
|
+
return this.reply(cached, after);
|
|
84
|
+
}
|
|
85
|
+
// Revision is part of the flight key: a new write never joins an older read.
|
|
86
|
+
const flightKey = JSON.stringify([this.generation, this.epoch, revision, key]);
|
|
87
|
+
let flight = this.flights.get(flightKey);
|
|
88
|
+
if (!flight) {
|
|
89
|
+
if (this.active.size >= 16) throw Error("console snapshot concurrency limit");
|
|
90
|
+
const generation = this.generation, epoch = this.epoch, sampledAt = this.now();
|
|
91
|
+
flight = (async () => {
|
|
92
|
+
const value = await read();
|
|
93
|
+
this.readable(value);
|
|
94
|
+
const observed = this.sourceRevision();
|
|
95
|
+
this.readable(value);
|
|
96
|
+
const data = structuredClone(value.data); delete data.changed;
|
|
97
|
+
const reading: Reading = { data, until: value.until, sampledAt, generation };
|
|
98
|
+
if (observed !== revision || epoch !== this.epoch || generation !== this.generation || !this.timely(sampledAt, value.until)) {
|
|
99
|
+
this.dropEntry(key, cached);
|
|
100
|
+
if (this.flights.get(flightKey) === flight) this.flights.delete(flightKey);
|
|
101
|
+
return reading;
|
|
102
|
+
}
|
|
103
|
+
const serialized = JSON.stringify(data), bytes = Buffer.byteLength(serialized);
|
|
104
|
+
const cursor = Number.parseInt(createHash("sha256").update(JSON.stringify([key, revision, value.until])).update(serialized).digest("hex").slice(0, 13), 16) + 1;
|
|
105
|
+
const entry = { sampledAt, generation, epoch, data, revision, cursor, until: value.until, bytes };
|
|
106
|
+
// ponytail: 16 selections and 4 MiB per provider. Larger views are served once;
|
|
107
|
+
// upgrade with paged panel results rather than retaining an unbounded corpus.
|
|
108
|
+
if (bytes <= 4 * 1024 * 1024) {
|
|
109
|
+
const old = this.entries.get(key); if (old) { this.bytes -= old.bytes; this.entries.delete(key); }
|
|
110
|
+
while (this.entries.size >= 16 || this.bytes + bytes > 4 * 1024 * 1024) {
|
|
111
|
+
const first = this.entries.keys().next().value!; this.bytes -= this.entries.get(first)!.bytes; this.entries.delete(first);
|
|
112
|
+
}
|
|
113
|
+
this.entries.set(key, entry); this.bytes += bytes;
|
|
114
|
+
}
|
|
115
|
+
reading.entry = entry;
|
|
116
|
+
return reading;
|
|
117
|
+
})();
|
|
118
|
+
this.flights.set(flightKey, flight);
|
|
119
|
+
this.track(flight);
|
|
120
|
+
}
|
|
121
|
+
try {
|
|
122
|
+
const reading = await flight;
|
|
123
|
+
this.readable(reading);
|
|
124
|
+
if (reading.generation !== this.generation) { this.dropEntry(key, reading.entry); return this.readFresh(read, false); }
|
|
125
|
+
const entry = reading.entry;
|
|
126
|
+
if (!entry) return this.freshReply(reading.data);
|
|
127
|
+
const observed = this.sourceRevision();
|
|
128
|
+
this.readable(reading);
|
|
129
|
+
if (reading.generation !== this.generation) { this.dropEntry(key, entry); return this.readFresh(read, false); }
|
|
130
|
+
if (observed !== entry.revision || entry.epoch !== this.epoch || !this.timely(entry.sampledAt, entry.until)) {
|
|
131
|
+
this.dropEntry(key, entry); return this.freshReply(reading.data);
|
|
132
|
+
}
|
|
133
|
+
return this.reply(entry, after);
|
|
134
|
+
}
|
|
135
|
+
finally { if (this.flights.get(flightKey) === flight) this.flights.delete(flightKey); }
|
|
136
|
+
}
|
|
137
|
+
private reply(entry: Entry, after: number): Data {
|
|
138
|
+
// acon's no-op contract requires exactly these two keys.
|
|
139
|
+
return after === entry.cursor ? { changed: false, cursor: entry.cursor } : { ...structuredClone(entry.data), cursor: entry.cursor };
|
|
140
|
+
}
|
|
141
|
+
}
|