@staix/agent-mem 0.24.0 → 0.25.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 +15 -9
- package/package.json +1 -1
- package/src/brief-cache.ts +7 -1
- package/src/brief-curated-native.ts +22 -2
- package/src/brief-curated.ts +54 -1
- package/src/cli.ts +7 -2
- package/src/hook-contract.ts +18 -2
- package/src/hook-jcode-journal.ts +46 -4
- package/src/hook-record.ts +18 -0
- package/src/hook-spool.ts +23 -12
- package/src/hooks.ts +4 -4
- package/src/index.ts +1 -0
- package/src/ingest-records.ts +113 -0
- package/src/ingest.ts +106 -9
- package/src/mcp-memory.ts +2 -2
- package/src/mcp.ts +1 -1
- package/src/memory/candidates.ts +56 -5
- package/src/memory/capture.ts +20 -0
- package/src/memory/consolidate.ts +35 -1
- package/src/memory/curated-cache-state.ts +4 -3
- package/src/memory/decay-review.ts +3 -1
- package/src/memory/formats.ts +14 -0
- package/src/memory/index-file.ts +1 -1
- package/src/memory/intent-brief.ts +42 -4
- package/src/memory/metrics.ts +3 -3
- package/src/memory/note-add.ts +2 -0
- package/src/memory/ops-contract.ts +1 -1
- package/src/memory/preference-brief.ts +22 -0
- package/src/memory/recall.ts +4 -1
- package/src/memory/record-candidates.ts +179 -0
- package/src/memory/search-fts.ts +3 -0
- package/src/memory/store.ts +55 -4
- package/src/session-brief.ts +23 -3
package/src/memory/store.ts
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
|
-
import { buildCuratedBriefCache } from "../brief-curated.ts";
|
|
1
|
+
import { buildCuratedBriefCache, buildPreferenceBriefCache } from "../brief-curated.ts";
|
|
2
|
+
import { PREFERENCE_SLOT } from "./preference-brief.ts";
|
|
2
3
|
import { curatedProfileBinding, invalidateCuratedCaches } from "./curated-cache-state.ts";
|
|
3
4
|
import { assertPlacementRuntime, placementSelectorRefusal, SyncPlacementRuntimeError } from "./sync-placement-guard.ts";
|
|
4
|
-
import { assertFormatFloor } from "./formats.ts";
|
|
5
|
+
import { assertFormatFloor, floorRaiseHint, formatFloorAtLeast, PREFERENCE_MIN_READER } from "./formats.ts";
|
|
5
6
|
import { readPublicPruneView } from "./public-prune-view.ts";
|
|
6
7
|
import { INDEX_VERSION, indexFileName } from "./index-file.ts";
|
|
7
8
|
import { readShardLegacySnapshot } from "./shard-bridge.ts";
|
|
@@ -41,7 +42,7 @@ import { registerReaderLease, type ReaderLease } from "./reader-lease.ts";
|
|
|
41
42
|
*/
|
|
42
43
|
export const MEMORY_SCHEMA = "agent-hub.memory/v1";
|
|
43
44
|
export const MEMORY_DB_BUSY_TIMEOUT_MS = 3000;
|
|
44
|
-
export const KINDS = ["decision", "finding", "contract", "fail"] as const;
|
|
45
|
+
export const KINDS = ["decision", "finding", "contract", "fail", "preference"] as const;
|
|
45
46
|
export type Kind = (typeof KINDS)[number];
|
|
46
47
|
/** Kinds that move to long-term when their task is approved; findings stay short-term unless a person promotes them. */
|
|
47
48
|
export const PROMOTED_KINDS: readonly Kind[] = ["decision", "contract", "fail"];
|
|
@@ -507,7 +508,8 @@ export class MemoryStore {
|
|
|
507
508
|
const directory = shardMachineDir(this.profile.home, project, machineId(this.profile.home).id);
|
|
508
509
|
mkdirSync(directory, { recursive: true, mode: 0o700 });
|
|
509
510
|
buildCuratedBriefCache(view!, { base: this.profile.home, project, directory, binding, now: this.now });
|
|
510
|
-
|
|
511
|
+
buildPreferenceBriefCache(view!, { base: this.profile.home, project, directory, binding, now: this.now });
|
|
512
|
+
if (curatedProfileBinding(this.profile.home, project) !== binding) for (const name of ["brief-curated.json", "brief-preferences.json"]) rmSync(join(directory, name), { force: true });
|
|
511
513
|
});
|
|
512
514
|
} catch { /* Failed derived publication leaves the invalidated cache unavailable; a later mutation retries. */ }
|
|
513
515
|
finally { try { if (view !== opened) view?.close(); } catch { /* Preserve the authoritative mutation result. */ } }
|
|
@@ -579,6 +581,8 @@ export class MemoryStore {
|
|
|
579
581
|
...(note.title ? { title: stripPrivateSpans(note.title).slice(0, MAX_TITLE) } : {}),
|
|
580
582
|
...(note.tier === "short" && !note.expires ? { expires: new Date(Date.parse(at) + this.ttl).toISOString() } : {}) });
|
|
581
583
|
const body = { schema: MEMORY_SCHEMA, at, machine: this.machine.id, ...normalized } as const;
|
|
584
|
+
// Before `work`: `beginAcceptance` marks the candidate accepting and a later refusal would leave it unreplayable.
|
|
585
|
+
this.assertPreferenceWritable(body);
|
|
582
586
|
const view: View = { ...normalized, id: entryId(body), at, machine: body.machine, title: normalized.title ?? null,
|
|
583
587
|
task: normalized.task ?? null, about: [...normalized.about], supersededBy: null,
|
|
584
588
|
supersedes: normalized.supersedes ? [normalized.supersedes] : [], promotedFrom: normalized.promotedFrom ?? null,
|
|
@@ -609,8 +613,20 @@ export class MemoryStore {
|
|
|
609
613
|
return this.appendBody(body, local);
|
|
610
614
|
}
|
|
611
615
|
|
|
616
|
+
/**
|
|
617
|
+
* #370: a `preference` note is written only into a home whose person-recorded floor already names a reader that understands the kind.
|
|
618
|
+
* A released reader sharing that home drops such a row and refuses its own machine's sync publish over it, so the write fails closed
|
|
619
|
+
* here rather than leaving a row no peer can sync past. Reads, briefs and candidate queueing never reach this check.
|
|
620
|
+
*/
|
|
621
|
+
private assertPreferenceWritable(body: Omit<Entry, "id">): void {
|
|
622
|
+
if (body.op !== "note" || (body as { kind?: unknown }).kind !== "preference") return;
|
|
623
|
+
if (formatFloorAtLeast(this.profile.home, "curated", PREFERENCE_MIN_READER)) return;
|
|
624
|
+
throw new Error(`a preference note needs a curated or home format floor of at least ${PREFERENCE_MIN_READER} on this memory home: an older amem reader sharing it drops the row and refuses its whole sync publish over one. Upgrade every host that shares this home, then ${floorRaiseHint(this.profile.home, "curated", PREFERENCE_MIN_READER)}; see docs/contracts.md, "Versions on one machine (#199)".`);
|
|
625
|
+
}
|
|
626
|
+
|
|
612
627
|
private appendBody(body: Omit<Entry, "id">, local: boolean): string {
|
|
613
628
|
if (this.bootstrapOnly) throw new Error("migration bootstrap cannot author memory");
|
|
629
|
+
this.assertPreferenceWritable(body);
|
|
614
630
|
if (this.userOverlay && (body.op === "note" || body.op === "goal") && "scope" in body && body.scope === "shared") return this.userOverlay.appendBody(body, local);
|
|
615
631
|
if ("target" in body && body.op !== "settle") { const owner = this.ownerOf(body.target as string); if (owner) return owner.appendBody(body, local); }
|
|
616
632
|
if (this.profile.sharded && (body.op === "note" || body.op === "goal") && "scope" in body && "project" in body) {
|
|
@@ -670,6 +686,8 @@ export class MemoryStore {
|
|
|
670
686
|
// The source tuple also recognizes legacy ids whose nodes depended on the checkout or extractor version.
|
|
671
687
|
const known = this.db.query("SELECT id FROM entries WHERE id = ? OR (source = 'claude-mem' AND project = ? AND at = ? AND text = ?)").get(id, n.project, at, stripPrivateSpans(n.text).slice(0, MAX_TEXT)) as { id: string } | null;
|
|
672
688
|
if (known) return { id: known.id, added: false };
|
|
689
|
+
// The second own-segment writer after `appendBody`; an import of a row already present above refuses nothing because it writes nothing.
|
|
690
|
+
this.assertPreferenceWritable(body);
|
|
673
691
|
this.markCuratedChange(n.project);
|
|
674
692
|
appendFileSync(join(this.dir, n.tier === "short" ? "local" : "log", `${this.machine.id}.jsonl`), JSON.stringify({ ...body, id }) + "\n", { mode: 0o600 });
|
|
675
693
|
return { id, added: true };
|
|
@@ -1189,6 +1207,39 @@ export class MemoryStore {
|
|
|
1189
1207
|
});
|
|
1190
1208
|
}
|
|
1191
1209
|
|
|
1210
|
+
/**
|
|
1211
|
+
* #370: this project's newest live preferences, plus shared ones written under any project. A kind predicate, not a page: a project
|
|
1212
|
+
* with more than a page of newer notes of other kinds would otherwise never reach its oldest preference. The brief owns the fence.
|
|
1213
|
+
*/
|
|
1214
|
+
readPreferences(project: string, limit: number = PREFERENCE_SLOT): { rows: View[]; truncated: boolean } {
|
|
1215
|
+
if (!project.trim() || project.length > 400 || !Number.isSafeInteger(limit) || limit < 1 || limit > 32) throw Error("invalid preference read scope or limit");
|
|
1216
|
+
this.ensureFresh();
|
|
1217
|
+
const stores = this.readStores(), scope = JSON.stringify(this.scopeKeys(project)), scan = Math.max(32, limit * 4);
|
|
1218
|
+
const cursors = new Map<number, { at: string; id: string }>(), done = new Set<number>(), live = new Map<string, View>();
|
|
1219
|
+
// Supersession, forget, expiry and promotion fold over rows this query cannot decide in SQL, so page by `at` and resolve liveness
|
|
1220
|
+
// before taking the newest `limit`: a fixed slice can otherwise be filled entirely by dead rows and leave the slot empty while a
|
|
1221
|
+
// current rule still exists. Every candidate row in scope is scanned, so `truncated` means what it says.
|
|
1222
|
+
while (done.size < stores.length) {
|
|
1223
|
+
const refs: { id: string; at: string }[] = [];
|
|
1224
|
+
stores.forEach((store, index) => {
|
|
1225
|
+
if (done.has(index)) return;
|
|
1226
|
+
const after = cursors.get(index);
|
|
1227
|
+
const rows = store.db.query(`SELECT id,at FROM entries WHERE (project IN (SELECT value FROM json_each(?)) OR scope = 'shared') AND kind = 'preference'`
|
|
1228
|
+
+ `${after ? " AND (at < ? OR (at = ? AND id > ?))" : ""} ORDER BY at DESC,id LIMIT ?`)
|
|
1229
|
+
.all(...(after ? [scope, after.at, after.at, after.id] : [scope]), scan) as { id: string; at: string }[];
|
|
1230
|
+
if (rows.length < scan) done.add(index); else cursors.set(index, rows[rows.length - 1]!);
|
|
1231
|
+
refs.push(...rows);
|
|
1232
|
+
});
|
|
1233
|
+
if (!refs.length) continue;
|
|
1234
|
+
for (const view of this.views(false, { project, ids: refs.map(ref => ref.id) })) {
|
|
1235
|
+
if (view.kind !== "preference" || view.supersededBy || !(this.inScope(view.project, project) || view.scope === "shared")) continue;
|
|
1236
|
+
live.set(view.id, view);
|
|
1237
|
+
}
|
|
1238
|
+
}
|
|
1239
|
+
const ordered = [...live.values()].sort((a, b) => b.at.localeCompare(a.at) || a.id.localeCompare(b.id));
|
|
1240
|
+
return { rows: ordered.slice(0, limit), truncated: ordered.length > limit };
|
|
1241
|
+
}
|
|
1242
|
+
|
|
1192
1243
|
/** Exact-project body pages for policy-aware callers. Relations still fold over complete metadata. */
|
|
1193
1244
|
readPage(window: ReadWindow & { query?: string; includeSuperseded?: boolean }): { rows: View[]; next?: ReadRef } {
|
|
1194
1245
|
this.ensureFresh(); this.prune();
|
package/src/session-brief.ts
CHANGED
|
@@ -2,8 +2,9 @@ import { lstatSync, readFileSync } from "node:fs";
|
|
|
2
2
|
import { join } from "node:path";
|
|
3
3
|
import type { CaptureRow, CaptureStore } from "./memory/capture.ts";
|
|
4
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";
|
|
5
|
+
import { noteDisplay, validCachedCurated, validCachedPreference } from "./brief-curated.ts";
|
|
6
|
+
import { CURATED_CACHE_MIN_READER, readCuratedBriefCache, readPreferenceBriefCache } from "./brief-curated-native.ts";
|
|
7
|
+
import { PREFERENCE_SLOT, SESSION_PREFERENCE_SHARE } from "./memory/preference-brief.ts";
|
|
7
8
|
import { curatedProfileBinding } from "./memory/curated-cache-state.ts";
|
|
8
9
|
import { captureDisplay, displayText, recordDisplay, validCachedCapture } from "./brief-capture.ts";
|
|
9
10
|
import { assertFormatFloor, FormatFloorError } from "./memory/formats.ts";
|
|
@@ -149,6 +150,7 @@ export async function sessionStartBrief(options: BriefOptions): Promise<BriefRes
|
|
|
149
150
|
const nativeCache = !!options.nativeSession && !options.measureOnly;
|
|
150
151
|
const nativeCurated = !!options.nativeSession;
|
|
151
152
|
const preparedCurated: { line: string; size: number; partial: boolean }[] = [];
|
|
153
|
+
const preparedPreferences: { line: string; size: number; partial: boolean }[] = [];
|
|
152
154
|
if (nativeCurated) {
|
|
153
155
|
const deferredReason = sharded || readSelector(base).selector?.kind === "generation" ? "generation refresh deferred" : "curated refresh deferred";
|
|
154
156
|
const prepared = readCuratedBriefCache({ base, project, profile: curatedProfileBinding(base, project),
|
|
@@ -163,6 +165,19 @@ export async function sessionStartBrief(options: BriefOptions): Promise<BriefRes
|
|
|
163
165
|
preparedCurated.push({ line, size: Buffer.byteLength(line) + 1, partial: row.partial });
|
|
164
166
|
}
|
|
165
167
|
}
|
|
168
|
+
// #370: the preference slot's own sidecar, admitted under the same profile binding and reserved ahead of the curated rows below.
|
|
169
|
+
// A missing sidecar (no preference on this home, or no off-hook preparation yet) changes neither coverage nor a byte of the brief.
|
|
170
|
+
const preferences = readPreferenceBriefCache({ base, project, profile: curatedProfileBinding(base, project), now: (options.now ?? Date.now)() });
|
|
171
|
+
if (preferences) {
|
|
172
|
+
let reserved = 0;
|
|
173
|
+
for (const row of preferences.rows) {
|
|
174
|
+
if (preparedPreferences.length >= PREFERENCE_SLOT || !validCachedPreference(row, project, (options.now ?? Date.now)())
|
|
175
|
+
|| !await screen(row.source) || !await screen(row.data)) { coverage.curated = "partial"; continue; }
|
|
176
|
+
const line = JSON.stringify({ section: "curated", evidence: true, data: row.data }), size = Buffer.byteLength(line) + 1;
|
|
177
|
+
if (Buffer.byteLength(line) > RECORD_BYTES || reserved + size > SESSION_PREFERENCE_SHARE) { coverage.curated = "partial"; continue; }
|
|
178
|
+
preparedPreferences.push({ line, size, partial: row.partial }); reserved += size;
|
|
179
|
+
}
|
|
180
|
+
}
|
|
166
181
|
guard();
|
|
167
182
|
}
|
|
168
183
|
let capture: CaptureStore | undefined, captureFailed = false;
|
|
@@ -286,7 +301,12 @@ export async function sessionStartBrief(options: BriefOptions): Promise<BriefRes
|
|
|
286
301
|
if (!complete) coverage[section] = "partial";
|
|
287
302
|
};
|
|
288
303
|
if (nativeCurated) {
|
|
289
|
-
// Pre-screened before work, but allocated only now from the remaining pool.
|
|
304
|
+
// Pre-screened before work, but allocated only now from the remaining pool; the preference slot holds its share ahead of curated rows.
|
|
305
|
+
for (const row of preparedPreferences) {
|
|
306
|
+
if (row.size - 1 > RECORD_BYTES || row.size > remaining) { coverage.curated = "partial"; continue; }
|
|
307
|
+
lines.push(row.line); remaining -= row.size;
|
|
308
|
+
if (row.partial) coverage.curated = "partial";
|
|
309
|
+
}
|
|
290
310
|
for (const row of preparedCurated) {
|
|
291
311
|
if (row.size - 1 > RECORD_BYTES || row.size > remaining) { coverage.curated = "partial"; continue; }
|
|
292
312
|
lines.push(row.line); remaining -= row.size;
|