@staix/agent-mem 0.23.1 → 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 +28 -12
- package/package.json +1 -1
- package/src/brief-cache.ts +60 -0
- package/src/brief-capture.ts +82 -0
- package/src/brief-curated-native.ts +52 -0
- package/src/brief-curated.ts +118 -0
- package/src/cli.ts +8 -2
- package/src/curated-brief-cache.ts +29 -0
- package/src/hook-contract.ts +22 -2
- package/src/hook-jcode-journal.ts +46 -4
- package/src/hook-record.ts +40 -2
- package/src/hook-spool-replay.ts +8 -1
- package/src/hook-spool.ts +25 -14
- package/src/hook-transcript.ts +10 -2
- package/src/hooks.ts +68 -17
- package/src/index.ts +6 -1
- 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/candidate-pending.ts +6 -2
- package/src/memory/candidates.ts +60 -7
- package/src/memory/capture-input.ts +7 -0
- package/src/memory/capture-plan.ts +10 -0
- package/src/memory/capture.ts +98 -8
- package/src/memory/consolidate.ts +35 -1
- package/src/memory/curated-cache-state.ts +36 -0
- package/src/memory/decay-review.ts +3 -1
- package/src/memory/formats.ts +20 -0
- package/src/memory/generation-index.ts +2 -0
- package/src/memory/generation-sync.ts +3 -0
- package/src/memory/index-file.ts +1 -1
- package/src/memory/intent-brief.ts +42 -4
- package/src/memory/metrics.ts +10 -4
- package/src/memory/migrate.ts +7 -1
- 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/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/recall.ts +4 -1
- package/src/memory/record-candidates.ts +179 -0
- package/src/memory/record-instruction.ts +26 -0
- package/src/memory/record-variant-log.ts +90 -0
- package/src/memory/search-fts.ts +3 -0
- package/src/memory/shard-migration.ts +4 -1
- package/src/memory/shard-sync.ts +3 -0
- package/src/memory/store.ts +184 -4
- 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 +150 -70
- package/src/ui/plugin.ts +104 -30
- package/src/ui/snapshot-cache.ts +141 -0
- package/src/ui/snapshot-revision.ts +87 -0
|
@@ -10,6 +10,7 @@ import { canonicalPath, realPath } from "./platform.ts";
|
|
|
10
10
|
import { assertNoLiveReaders } from "./reader-lease.ts";
|
|
11
11
|
import { assertCuratedShardPaths, ensureShardDescriptor, shardDir, SHARDED_SCHEMA, SHARDED_V2_SCHEMA, userShardDir, SHARD_SCHEMA } from "./shard.ts";
|
|
12
12
|
import { buildGenerationIndex, type Entry } from "./store.ts";
|
|
13
|
+
import { invalidateCuratedCaches } from "./curated-cache-state.ts";
|
|
13
14
|
import { readMigrationSources, type SourcePrefix } from "./migrate.ts";
|
|
14
15
|
import { label, PLAIN, singleLine, type Style } from "./style.ts";
|
|
15
16
|
|
|
@@ -510,7 +511,7 @@ export async function migrateShards(options: ShardMigrationOptions): Promise<Sha
|
|
|
510
511
|
// Validate every immutable prune and routing decision before even a profile/mutation lock creates metadata.
|
|
511
512
|
const initial = preflight(memoryDir, options, undefined, options.mode === "dry-run");
|
|
512
513
|
if (options.mode === "dry-run") return { mode: options.mode, generation: initial.generation, active: initial.previous?.phase === "active", counts: counts(initial.plan), ...refusalSummary(initial.plan), consequence: CONSEQUENCE, ...removalEvidence(initial.previous) };
|
|
513
|
-
|
|
514
|
+
const result = await withProfileLock(memoryDir, async () => {
|
|
514
515
|
const release = acquireMutation(memoryDir);
|
|
515
516
|
if (!release) throw new Error("legacy mutation lock is busy");
|
|
516
517
|
let releaseOwn: (() => void) | undefined;
|
|
@@ -546,6 +547,7 @@ export async function migrateShards(options: ShardMigrationOptions): Promise<Sha
|
|
|
546
547
|
let affected: Set<Destination>;
|
|
547
548
|
try {
|
|
548
549
|
for (const destination of plan.destinations) assessDestination(memoryDir, destination, plan, generation, machine);
|
|
550
|
+
invalidateCuratedCaches(memoryDir);
|
|
549
551
|
if (!alreadyActive) journal.phase = "captured";
|
|
550
552
|
persist();
|
|
551
553
|
affected = writeRoutes(memoryDir, plan, generation, machine);
|
|
@@ -561,6 +563,7 @@ export async function migrateShards(options: ShardMigrationOptions): Promise<Sha
|
|
|
561
563
|
persist();
|
|
562
564
|
return { mode: options.mode, generation, active: true, ...(alreadyActive ? { alreadyActive: true } : {}), counts: counts(plan), ...refusalSummary(plan), consequence: CONSEQUENCE, ...removalEvidence(journal) };
|
|
563
565
|
});
|
|
566
|
+
return result;
|
|
564
567
|
}
|
|
565
568
|
|
|
566
569
|
/** Render a shard migration result for a person; JSON output remains owned by the CLI. */
|
package/src/memory/shard-sync.ts
CHANGED
|
@@ -443,6 +443,7 @@ async function prepareHolds(targets: readonly Target[], root: string, url: strin
|
|
|
443
443
|
}
|
|
444
444
|
}
|
|
445
445
|
export async function syncShardedMemory(store: MemoryStore, opts: SyncOptions = {}, testOnlyUnexpectedError?: (error: unknown) => void, testOnlyPhase?: (phase: SyncPhase) => void): Promise<SyncResult> {
|
|
446
|
+
let releaseCurated: (() => void) | undefined;
|
|
446
447
|
const placementRefusal = placementRuntimeRefusal(store.profile.home, store.profile);
|
|
447
448
|
if (placementRefusal) return { ok: false, pushed: false, entries: 0, error: placementRefusal };
|
|
448
449
|
if (store.profile.publicationFormat === "agent-mem.sync-placement/v1") return (await import("./sync-placement-transport.ts")).syncPlacementMemory(store, opts);
|
|
@@ -541,6 +542,7 @@ export async function syncShardedMemory(store: MemoryStore, opts: SyncOptions =
|
|
|
541
542
|
const release = acquireMutation(target.store.dir); if (!release) refuse(`${shardSyncLabel(target.realm)}: another source mutation is running`); releases.push(release); target.mutation=release;
|
|
542
543
|
if (v2) ensurePublisherBoundary(target.store.profile,release);
|
|
543
544
|
}
|
|
545
|
+
releaseCurated = store.beginCuratedCacheUpdate();
|
|
544
546
|
const blobCache = new Map<string, Buffer>();
|
|
545
547
|
const blob = async (object: string, path: string): Promise<Buffer> => {
|
|
546
548
|
const maximum = path === "shard.json" || isShardManifestPath(path) ? 64 * 1024 : SHARD_PACK_MAX_BYTES, prior = blobCache.get(object);
|
|
@@ -729,6 +731,7 @@ export async function syncShardedMemory(store: MemoryStore, opts: SyncOptions =
|
|
|
729
731
|
for (const release of releases.reverse()) { try { release(); } catch { /* fail-open cleanup */ } }
|
|
730
732
|
try { releaseSync?.(); } catch { /* private lock cleanup */ }
|
|
731
733
|
try { releaseTransport?.(); } catch { /* private lock cleanup */ }
|
|
734
|
+
releaseCurated?.();
|
|
732
735
|
}
|
|
733
736
|
}
|
|
734
737
|
|
package/src/memory/store.ts
CHANGED
|
@@ -1,5 +1,8 @@
|
|
|
1
|
+
import { buildCuratedBriefCache, buildPreferenceBriefCache } from "../brief-curated.ts";
|
|
2
|
+
import { PREFERENCE_SLOT } from "./preference-brief.ts";
|
|
3
|
+
import { curatedProfileBinding, invalidateCuratedCaches } from "./curated-cache-state.ts";
|
|
1
4
|
import { assertPlacementRuntime, placementSelectorRefusal, SyncPlacementRuntimeError } from "./sync-placement-guard.ts";
|
|
2
|
-
import { assertFormatFloor } from "./formats.ts";
|
|
5
|
+
import { assertFormatFloor, floorRaiseHint, formatFloorAtLeast, PREFERENCE_MIN_READER } from "./formats.ts";
|
|
3
6
|
import { readPublicPruneView } from "./public-prune-view.ts";
|
|
4
7
|
import { INDEX_VERSION, indexFileName } from "./index-file.ts";
|
|
5
8
|
import { readShardLegacySnapshot } from "./shard-bridge.ts";
|
|
@@ -39,7 +42,7 @@ import { registerReaderLease, type ReaderLease } from "./reader-lease.ts";
|
|
|
39
42
|
*/
|
|
40
43
|
export const MEMORY_SCHEMA = "agent-hub.memory/v1";
|
|
41
44
|
export const MEMORY_DB_BUSY_TIMEOUT_MS = 3000;
|
|
42
|
-
export const KINDS = ["decision", "finding", "contract", "fail"] as const;
|
|
45
|
+
export const KINDS = ["decision", "finding", "contract", "fail", "preference"] as const;
|
|
43
46
|
export type Kind = (typeof KINDS)[number];
|
|
44
47
|
/** Kinds that move to long-term when their task is approved; findings stay short-term unless a person promotes them. */
|
|
45
48
|
export const PROMOTED_KINDS: readonly Kind[] = ["decision", "contract", "fail"];
|
|
@@ -203,7 +206,15 @@ export interface StoreOptions { home?: string; memoryDir?: string; ttlMs?: numbe
|
|
|
203
206
|
|
|
204
207
|
const MIGRATION_BOOTSTRAP = Symbol("migration index bootstrap");
|
|
205
208
|
interface BootstrapBinding { token: typeof MIGRATION_BOOTSTRAP; profile: BoundProfile; limits?: readonly LegacyCheckpoint[]; commit?: string; authoring?: boolean; userOverlay?: MemoryStore; aliasStores?: MemoryStore[] }
|
|
209
|
+
// Defer publication until the outermost source fence in this process has released.
|
|
210
|
+
const curatedDepth = new Map<string, number>();
|
|
211
|
+
const curatedPending = new Map<string, Map<MemoryStore, Set<string>>>();
|
|
212
|
+
let publishingCurated = false;
|
|
213
|
+
|
|
206
214
|
export class MemoryStore {
|
|
215
|
+
private curatedParent?: MemoryStore;
|
|
216
|
+
private curatedRebuildAll = false;
|
|
217
|
+
|
|
207
218
|
readonly dir: string;
|
|
208
219
|
readonly profile: BoundProfile;
|
|
209
220
|
private readonly generationIndex?: GenerationIndex;
|
|
@@ -231,6 +242,7 @@ export class MemoryStore {
|
|
|
231
242
|
this.bootstrapOnly = bootstrap ? bootstrap.authoring !== true : false;
|
|
232
243
|
this.userOverlay = bootstrap?.userOverlay;
|
|
233
244
|
this.aliasStores = bootstrap?.aliasStores ?? [];
|
|
245
|
+
for (const child of [...this.aliasStores, ...(this.userOverlay ? [this.userOverlay] : [])]) child.curatedParent = this;
|
|
234
246
|
this.reconcile = opts.reconcile && opts.reconcile.aliases.length ? { canonical: opts.reconcile.canonical, aliases: [...opts.reconcile.aliases] } : undefined;
|
|
235
247
|
if (opts.memoryDir !== undefined && (opts.home !== undefined || typeof opts.memoryDir !== "string" || !opts.memoryDir.trim())) throw new Error("choose a memory home or one explicit memory directory");
|
|
236
248
|
const home = bootstrap?.profile.home ?? opts.memoryDir ?? (opts.home === undefined ? memoryHome() : join(opts.home, "memory"));
|
|
@@ -287,7 +299,11 @@ export class MemoryStore {
|
|
|
287
299
|
this.memoryBaseDir = home;
|
|
288
300
|
try { chmodSync(indexFile, 0o600); } catch { /* best effort */ }
|
|
289
301
|
if (this.profile.kind === "generation") this.generationIndex = new GenerationIndex({ profile: this.profile, db, now: this.now,
|
|
290
|
-
apply: (line, source) => this.apply(line, source), withMutation: work => this.withMutation(work),
|
|
302
|
+
apply: (line, source) => this.apply(line, source), withMutation: work => this.withMutation(work), beforeCuratedWrite: targets => {
|
|
303
|
+
invalidateCuratedCaches(this.profile.home);
|
|
304
|
+
const rows = this.db.query("SELECT DISTINCT project FROM entries WHERE id IN (SELECT value FROM json_each(?))").all(JSON.stringify(targets)) as { project: string }[];
|
|
305
|
+
this.queueCuratedProjects(rows.map(row => row.project));
|
|
306
|
+
},
|
|
291
307
|
...(bootstrap ? { limits: bootstrap.limits } : {}), ...(bootstrap?.commit ? { commit: bootstrap.commit } : {}) });
|
|
292
308
|
this.refresh();
|
|
293
309
|
} catch (error) {
|
|
@@ -385,7 +401,119 @@ export class MemoryStore {
|
|
|
385
401
|
}
|
|
386
402
|
|
|
387
403
|
private withMutation<T>(work: () => T): T {
|
|
388
|
-
|
|
404
|
+
const release = this.deferCuratedPublication();
|
|
405
|
+
try { return this.mutationDb.transaction(work).immediate(); }
|
|
406
|
+
finally { release(); }
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
private deferCuratedPublication(): () => void {
|
|
410
|
+
const home = this.profile.home;
|
|
411
|
+
curatedDepth.set(home, (curatedDepth.get(home) ?? 0) + 1);
|
|
412
|
+
return () => {
|
|
413
|
+
const depth = (curatedDepth.get(home) ?? 1) - 1;
|
|
414
|
+
if (depth) { curatedDepth.set(home, depth); return; }
|
|
415
|
+
curatedDepth.delete(home);
|
|
416
|
+
if (publishingCurated) return;
|
|
417
|
+
const pending = curatedPending.get(home); curatedPending.delete(home);
|
|
418
|
+
if (!pending) return;
|
|
419
|
+
publishingCurated = true;
|
|
420
|
+
try { for (const [store, projects] of pending) store.publishCurated(projects); }
|
|
421
|
+
finally { publishingCurated = false; }
|
|
422
|
+
};
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
private markCuratedChange(project?: string): void {
|
|
426
|
+
if (this.bootstrapOnly) return;
|
|
427
|
+
invalidateCuratedCaches(this.profile.home);
|
|
428
|
+
this.queueCuratedProjects(project ? [project] : []);
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
private queueCuratedProjects(touched: Iterable<string>): void {
|
|
432
|
+
let owner: MemoryStore = this;
|
|
433
|
+
while (owner.curatedParent) owner = owner.curatedParent;
|
|
434
|
+
const pending = curatedPending.get(this.profile.home) ?? new Map<MemoryStore, Set<string>>();
|
|
435
|
+
const projects = pending.get(owner) ?? new Set<string>();
|
|
436
|
+
for (const project of touched) projects.add(project);
|
|
437
|
+
if (owner.profile.shardKey) projects.add(owner.profile.shardKey);
|
|
438
|
+
pending.set(owner, projects); curatedPending.set(this.profile.home, pending);
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
private curatedProjectRevisions(): Map<string, string> {
|
|
442
|
+
this.ensureFresh();
|
|
443
|
+
const projects = new Map<string, string[]>();
|
|
444
|
+
for (const view of this.views()) {
|
|
445
|
+
const rows = projects.get(view.project) ?? [];
|
|
446
|
+
rows.push(JSON.stringify([view.id, view.tier, view.expiresAt, view.supersededBy]));
|
|
447
|
+
projects.set(view.project, rows);
|
|
448
|
+
}
|
|
449
|
+
return new Map([...projects].map(([project, rows]) => [project, JSON.stringify(rows.sort())]));
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
/** Internal derived-cache port; the sync caller already holds the authoritative writer fences. */
|
|
453
|
+
beginCuratedCacheUpdate(): () => void {
|
|
454
|
+
const release = this.deferCuratedPublication();
|
|
455
|
+
let before: Map<string, string>;
|
|
456
|
+
try { before = this.curatedProjectRevisions(); invalidateCuratedCaches(this.profile.home); }
|
|
457
|
+
catch (error) { release(); throw error; }
|
|
458
|
+
return () => {
|
|
459
|
+
try {
|
|
460
|
+
const after = this.curatedProjectRevisions();
|
|
461
|
+
const touched = [...new Set([...before.keys(), ...after.keys()])].filter(project => before.get(project) !== after.get(project));
|
|
462
|
+
if (touched.length) this.queueCuratedProjects(touched);
|
|
463
|
+
} catch { /* The invalidated cache stays unavailable if the committed source cannot be read. */ }
|
|
464
|
+
finally { release(); }
|
|
465
|
+
};
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
/** Off-hook preparation; callers never invoke this from native SessionStart. */
|
|
469
|
+
prepareCuratedBriefs(projects?: readonly string[]): void {
|
|
470
|
+
try { this.curatedRebuildAll = projects === undefined; this.publishCurated(new Set(projects ?? []), projects?.length === 1 ? this : undefined); }
|
|
471
|
+
catch { /* An off-hook read still succeeds when its optional derived cache cannot be prepared. */ }
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
private publishCurated(input: ReadonlySet<string>, opened?: MemoryStore): void {
|
|
475
|
+
const projects = new Set(input);
|
|
476
|
+
if (this.curatedRebuildAll) {
|
|
477
|
+
this.curatedRebuildAll = false;
|
|
478
|
+
for (const source of this.readStores()) for (const value of source.db.query("SELECT DISTINCT project FROM entries").all() as { project: string }[]) projects.add(value.project);
|
|
479
|
+
const root = join(this.profile.home, "projects");
|
|
480
|
+
if (existsSync(root)) for (const hash of readdirSync(root)) { const descriptor = /^[a-f0-9]{16}$/.test(hash) ? readShardDescriptor(this.profile.home, hash) : undefined; if (descriptor) projects.add(descriptor.key); }
|
|
481
|
+
}
|
|
482
|
+
for (const raw of projects) {
|
|
483
|
+
let view: MemoryStore | undefined;
|
|
484
|
+
try {
|
|
485
|
+
const project = resolveAlias(this.profile.home, raw), aliases = aliasedKeys(this.profile.home, project);
|
|
486
|
+
const common = { memoryDir: this.profile.home, deferPromotions: true, now: this.now, ...(aliases.length ? { reconcile: { canonical: project, aliases } } : {}) };
|
|
487
|
+
const sharded = existsSync(join(this.profile.home, "shards.json"));
|
|
488
|
+
// Cache preparation cannot replace project admission with a user-only view.
|
|
489
|
+
// The ordinary off-hook read may initialize a missing shard only where the source API permits it.
|
|
490
|
+
if (sharded && !existsSync(join(shardDir(this.profile.home, project), "generation.json"))) continue;
|
|
491
|
+
const reusable = opened && (!sharded || opened.profile.shardKey === project)
|
|
492
|
+
&& (aliases.length ? opened.reconcile?.canonical === project && opened.reconcile.aliases.join("\n") === aliases.join("\n") : !opened.reconcile);
|
|
493
|
+
if (opened && !reusable) continue; // Explicit single-project preparation never retries with a second store.
|
|
494
|
+
view = reusable ? opened! : sharded ? openShardStore({ ...common, project }) : new MemoryStore(common);
|
|
495
|
+
view.withStoreFences(() => {
|
|
496
|
+
const selected = readSelector(this.profile.home);
|
|
497
|
+
const shards = sharded ? readShardedSelection(this.profile.home) : null;
|
|
498
|
+
if (view!.profile.selectorRevision !== selected.revision || view!.profile.kind !== (shards ? "generation" : selected.selector?.kind ?? "shared-v1")
|
|
499
|
+
|| view!.profile.generation !== (shards?.generation ?? selected.selector?.generation) || resolveAlias(this.profile.home, raw) !== project
|
|
500
|
+
|| shards && (shards.selectorRevision !== selected.revision || shards.generation !== view!.profile.generation)
|
|
501
|
+
|| aliasedKeys(this.profile.home, project).join("\n") !== aliases.join("\n")
|
|
502
|
+
|| (view!.reconcile?.aliases.join("\n") ?? "") !== aliases.join("\n")) {
|
|
503
|
+
throw Error("curated snapshot source binding changed; retry an off-hook amem brief");
|
|
504
|
+
}
|
|
505
|
+
// Stamp the source handle's inputs, never a newer metadata read that it did not open.
|
|
506
|
+
const binding = JSON.stringify({ selector: selected.revision, shards, aliases });
|
|
507
|
+
ensureShardDescriptor(this.profile.home, project);
|
|
508
|
+
const directory = shardMachineDir(this.profile.home, project, machineId(this.profile.home).id);
|
|
509
|
+
mkdirSync(directory, { recursive: true, mode: 0o700 });
|
|
510
|
+
buildCuratedBriefCache(view!, { base: this.profile.home, project, directory, binding, now: this.now });
|
|
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 });
|
|
513
|
+
});
|
|
514
|
+
} catch { /* Failed derived publication leaves the invalidated cache unavailable; a later mutation retries. */ }
|
|
515
|
+
finally { try { if (view !== opened) view?.close(); } catch { /* Preserve the authoritative mutation result. */ } }
|
|
516
|
+
}
|
|
389
517
|
}
|
|
390
518
|
|
|
391
519
|
/** Synchronous exact-target work under every opened shard's existing writer fence. No read-time promotions. */
|
|
@@ -453,6 +581,8 @@ export class MemoryStore {
|
|
|
453
581
|
...(note.title ? { title: stripPrivateSpans(note.title).slice(0, MAX_TITLE) } : {}),
|
|
454
582
|
...(note.tier === "short" && !note.expires ? { expires: new Date(Date.parse(at) + this.ttl).toISOString() } : {}) });
|
|
455
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);
|
|
456
586
|
const view: View = { ...normalized, id: entryId(body), at, machine: body.machine, title: normalized.title ?? null,
|
|
457
587
|
task: normalized.task ?? null, about: [...normalized.about], supersededBy: null,
|
|
458
588
|
supersedes: normalized.supersedes ? [normalized.supersedes] : [], promotedFrom: normalized.promotedFrom ?? null,
|
|
@@ -483,8 +613,20 @@ export class MemoryStore {
|
|
|
483
613
|
return this.appendBody(body, local);
|
|
484
614
|
}
|
|
485
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
|
+
|
|
486
627
|
private appendBody(body: Omit<Entry, "id">, local: boolean): string {
|
|
487
628
|
if (this.bootstrapOnly) throw new Error("migration bootstrap cannot author memory");
|
|
629
|
+
this.assertPreferenceWritable(body);
|
|
488
630
|
if (this.userOverlay && (body.op === "note" || body.op === "goal") && "scope" in body && body.scope === "shared") return this.userOverlay.appendBody(body, local);
|
|
489
631
|
if ("target" in body && body.op !== "settle") { const owner = this.ownerOf(body.target as string); if (owner) return owner.appendBody(body, local); }
|
|
490
632
|
if (this.profile.sharded && (body.op === "note" || body.op === "goal") && "scope" in body && "project" in body) {
|
|
@@ -496,6 +638,8 @@ export class MemoryStore {
|
|
|
496
638
|
return this.withMutation(() => {
|
|
497
639
|
this.generationIndex?.assertAppendable(local, this.machine.id);
|
|
498
640
|
const id = entryId(body);
|
|
641
|
+
const affected = "project" in body ? String(body.project) : "target" in body && typeof body.target === "string" ? (this.db.query("SELECT project FROM entries WHERE id=? OR task=?").get(body.target, body.target) as { project: string } | null)?.project : undefined;
|
|
642
|
+
if (body.op !== "goal" && body.op !== "goal_state" && body.op !== "goal_link") this.markCuratedChange(affected);
|
|
499
643
|
appendFileSync(join(this.dir, local ? "local" : "log", `${this.machine.id}.jsonl`), JSON.stringify({ ...body, id }) + "\n", { mode: 0o600 });
|
|
500
644
|
// The line is durable even if indexing fails; the next refresh catches up from the authoritative log.
|
|
501
645
|
try { this.refresh(); } catch (e) { this.stale = true; this.log(`hub memory index not updated yet: ${(e as Error).message}`); }
|
|
@@ -542,6 +686,9 @@ export class MemoryStore {
|
|
|
542
686
|
// The source tuple also recognizes legacy ids whose nodes depended on the checkout or extractor version.
|
|
543
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;
|
|
544
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);
|
|
691
|
+
this.markCuratedChange(n.project);
|
|
545
692
|
appendFileSync(join(this.dir, n.tier === "short" ? "local" : "log", `${this.machine.id}.jsonl`), JSON.stringify({ ...body, id }) + "\n", { mode: 0o600 });
|
|
546
693
|
return { id, added: true };
|
|
547
694
|
});
|
|
@@ -1060,6 +1207,39 @@ export class MemoryStore {
|
|
|
1060
1207
|
});
|
|
1061
1208
|
}
|
|
1062
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
|
+
|
|
1063
1243
|
/** Exact-project body pages for policy-aware callers. Relations still fold over complete metadata. */
|
|
1064
1244
|
readPage(window: ReadWindow & { query?: string; includeSuperseded?: boolean }): { rows: View[]; next?: ReadRef } {
|
|
1065
1245
|
this.ensureFresh(); this.prune();
|
|
@@ -4,6 +4,7 @@ import { closeSync, constants, fstatSync, fsyncSync, lstatSync, openSync } from
|
|
|
4
4
|
import { dirname, join } from "node:path";
|
|
5
5
|
import { types } from "node:util";
|
|
6
6
|
import { canonicalJSON, hashJSON, writeProfileJSON, fsyncDirectory } from "./generation.ts";
|
|
7
|
+
import { invalidateCuratedCaches } from "./curated-cache-state.ts";
|
|
7
8
|
import { assertMutationHandle, type MutationHandle } from "./mutation.ts";
|
|
8
9
|
import { withPlacementActivationFences, PlacementInventoryFenceError } from "./sync-placement-activation-locks.ts";
|
|
9
10
|
import { realPath } from "./platform.ts";
|
|
@@ -134,7 +135,8 @@ export async function activateSyncPlacement(options:PlacementActivationOptions)
|
|
|
134
135
|
if(options.mode==="dry-run")return{mode:options.mode,active:false,forwardOnly:true,quiescence:"deferred-to-apply",realms:source!.base.realms.length,writers:writer!.measurement.roots,source:report};
|
|
135
136
|
if(!pending&&!options.writerRoots.length)throw Error("Initial sync placement apply requires an explicit complete --writer-root inventory; run amem migrate --sync-placement --dry-run, then apply the reviewed roots.");
|
|
136
137
|
const directories=pending?pending.plan.realms.map(realm=>realm.scope==="user"?join(home,"user"):join(home,"projects",realm.keyHash.slice(0,16))):source!.directories;
|
|
137
|
-
try{
|
|
138
|
+
try{
|
|
139
|
+
const result=await withPlacementActivationFences(home,directories,async(mutation,owner)=>{
|
|
138
140
|
let intent=pending;
|
|
139
141
|
const initialCheck=()=>{assertPlacementActivationOwner(owner);source!.assertSourcesUnchanged();writer!.attest();if(requirePlacementHomeFloor(home)!==initialFloorHash)fail("changed");};
|
|
140
142
|
if(!intent){
|
|
@@ -152,7 +154,10 @@ export async function activateSyncPlacement(options:PlacementActivationOptions)
|
|
|
152
154
|
}
|
|
153
155
|
const fixed=intent,epochHash=placementEpochHash(fixed.epoch);
|
|
154
156
|
const metadataCheck=()=>{assertPlacementActivationOwner(owner);requirePlacementHomeFloor(home);if(!committed(home,fixed))fail("changed");readSyncPlacementWriterRoots(home);assertMutationHandle(mutation,home);};
|
|
155
|
-
if(committed(home,fixed))
|
|
157
|
+
if(committed(home,fixed)){
|
|
158
|
+
invalidateCuratedCaches(home);
|
|
159
|
+
return finishCommittedActivation(home,fixed,options,mutation,owner,fixed,report);
|
|
160
|
+
}
|
|
156
161
|
let current:PlacementWriterContext;
|
|
157
162
|
try{current=writer??initialPlacementWriterContext(home,fixed.roots,options.ownRoot);}catch(error){writerInputFailure(error);}
|
|
158
163
|
if(canonicalJSON(current.measurement.writers)!==canonicalJSON(fixed.plan.writers))throw new PlacementActivationInputError("writer root");
|
|
@@ -173,12 +178,15 @@ export async function activateSyncPlacement(options:PlacementActivationOptions)
|
|
|
173
178
|
preparePlacementEpoch(home,fixed.epoch,fixed.plan,{mutation,assertCurrent:check});await options.checkpoint?.("after-epoch");check();
|
|
174
179
|
writeSyncPlacementWriterRoots(home,{epochHash,homeHash:fixed.epoch.homeHash,activationHash:fixed.plan.seal,roots:current.measurement.roots},fixed.plan.writers,{mutation,assertCurrent:check});await options.checkpoint?.("after-root-map");check();
|
|
175
180
|
const final=placementActivationFinalMarkers(fixed),markers=readPlacementRuntimeMarkers(home);
|
|
181
|
+
invalidateCuratedCaches(home);
|
|
176
182
|
if(canonicalJSON(markers.shards)+"\n"!==final.shards)writeProfileJSON(join(home,"shards.json"),JSON.parse(final.shards));else syncFile(join(home,"shards.json"));
|
|
177
183
|
await options.checkpoint?.("after-shards");check();
|
|
178
184
|
if(canonicalJSON(readPlacementRuntimeMarkers(home).profile)+"\n"!==final.profile)writeProfileJSON(join(home,"profile.json"),JSON.parse(final.profile));else syncFile(join(home,"profile.json"));
|
|
179
185
|
await options.checkpoint?.("after-profile");check();
|
|
180
186
|
ensurePlacementFence(home,epochHash,{mutation,assertCurrent:check});await options.checkpoint?.("after-fence");metadataCheck();return finishCommittedActivation(home,fixed,options,mutation,owner,fixed,report);
|
|
181
|
-
});
|
|
187
|
+
});
|
|
188
|
+
return result;
|
|
189
|
+
}catch(error){
|
|
182
190
|
try{options.testOnlyFailure?.(error);}catch{/* observers never affect production outcomes */}
|
|
183
191
|
return rethrowActivationFailure(error);
|
|
184
192
|
}
|
|
@@ -50,6 +50,7 @@ export async function syncPlacementMemory(store: MemoryStore, opts: SyncOptions
|
|
|
50
50
|
class PlacementTransport {
|
|
51
51
|
readonly store: MemoryStore; readonly opts: SyncOptions; readonly phase?: Phase; readonly testOnlyError?: (error:unknown)=>void; readonly home: string; readonly root: string; readonly cache: string;
|
|
52
52
|
readonly releases: (() => void)[] = []; readonly temporary: string[] = []; readonly refs: string[] = [];
|
|
53
|
+
releaseCurated?: () => void;
|
|
53
54
|
targets: Target[] = []; homeMutation?: MutationHandle; rootMutation?: MutationHandle; cacheIdentity?: {dev:number;ino:number}; cacheConfigIdentity?: string; epochHash = ""; journal!: PlacementJournalRead; capture?: PlacementCapture;
|
|
54
55
|
machineId = ""; url = ""; revision = ""; accepted = false; factual = false; attempted = false; lastPolicyCheckUnixMs?: number; lastPolicyHash?: string; policyCheckSource?: "live"|"durable-intent"; attemptHash?: string;
|
|
55
56
|
evaluator?: ReturnType<typeof outboundPolicyEvaluator>; applications?: ShardSyncApplications; current?: Materialized; recovered = false;
|
|
@@ -136,6 +137,7 @@ class PlacementTransport {
|
|
|
136
137
|
const handle = acquireMutation(dir); if (!handle) refuse(); this.releases.push(handle); if (dir === this.home) this.homeMutation = handle;
|
|
137
138
|
for (const target of this.targets) if (target.store.dir === dir) target.mutation = handle;
|
|
138
139
|
}
|
|
140
|
+
this.releaseCurated = this.store.beginCuratedCacheUpdate();
|
|
139
141
|
this.journal = readPlacementJournal(this.home, this.epochHash); this.revision = readSelector(this.home).revision; this.attest();
|
|
140
142
|
if (!existing) await this.required(["init", "--bare", "--template=", "--object-format=sha1", "-q", this.cache]);
|
|
141
143
|
if (!await this.independent()) refuse();
|
|
@@ -495,6 +497,7 @@ class PlacementTransport {
|
|
|
495
497
|
for(const file of this.temporary)try{this.metadata();rmSync(file,{force:true});}catch{}
|
|
496
498
|
}
|
|
497
499
|
for(const release of this.releases.reverse())try{release();}catch{}
|
|
500
|
+
this.releaseCurated?.();
|
|
498
501
|
}
|
|
499
502
|
}
|
|
500
503
|
}
|
package/src/memory/sync.ts
CHANGED
|
@@ -274,10 +274,11 @@ export async function syncMemory(store: MemoryStore, opts: SyncOptions = {}): Pr
|
|
|
274
274
|
if (!opts.remote && !existsSync(join(dir, ".git"))) return fail(noRemote); // never set up: nothing to do, nothing created
|
|
275
275
|
const release = lock(dir);
|
|
276
276
|
if (!release) return fail("another sync is running on this machine");
|
|
277
|
-
let releaseMutation: (() => void) | undefined;
|
|
277
|
+
let releaseMutation: (() => void) | undefined, releaseCurated: (() => void) | undefined;
|
|
278
278
|
try {
|
|
279
279
|
releaseMutation = acquireMutation(dir);
|
|
280
280
|
if (!releaseMutation) return fail("another memory mutation is running on this machine");
|
|
281
|
+
releaseCurated = store.beginCuratedCacheUpdate();
|
|
281
282
|
// Holding sync.lock, no other git runs in this repository: what a killed one left behind is stale.
|
|
282
283
|
rmSync(join(dir, ".git", "index.lock"), { force: true });
|
|
283
284
|
if (existsSync(join(dir, ".git", "MERGE_HEAD"))) await git(dir, ["merge", "--abort"]);
|
|
@@ -341,5 +342,5 @@ export async function syncMemory(store: MemoryStore, opts: SyncOptions = {}): Pr
|
|
|
341
342
|
});
|
|
342
343
|
} catch (e) {
|
|
343
344
|
return fail((e as Error).message.slice(0, 200));
|
|
344
|
-
} finally { try { releaseMutation?.(); } finally { release(); } }
|
|
345
|
+
} finally { try { releaseMutation?.(); } finally { try { releaseCurated?.(); } finally { release(); } } }
|
|
345
346
|
}
|
|
@@ -63,9 +63,10 @@ if (import.meta.main) {
|
|
|
63
63
|
const line = await next();
|
|
64
64
|
if (line === undefined) stop();
|
|
65
65
|
const first = JSON.parse(line) as Record<string, unknown>;
|
|
66
|
-
type Scan = { cwd: string; base: string; transcript: unknown; policy?: BriefOptions["policy"]; deadlineAt: number };
|
|
66
|
+
type Scan = { cwd: string; base: string; transcript: unknown; policy?: BriefOptions["policy"]; deadlineAt: number; event?: "Stop" | "SessionEnd" };
|
|
67
67
|
type DrainOptions = BriefOptions & { current: string; event: string; identity?: unknown; deadlineAt: number; ownedGroup: boolean; hookStartAt?: number };
|
|
68
68
|
const scan = first.scan as Scan | undefined;
|
|
69
|
+
const scanEvent = scan?.event === "Stop" || scan?.event === "SessionEnd" ? scan.event : undefined;
|
|
69
70
|
const deadlineAt = scan?.deadlineAt ?? first.deadlineAt;
|
|
70
71
|
if (!Number.isFinite(deadlineAt) || first.ownedGroup !== true) stop();
|
|
71
72
|
owned = true;
|
|
@@ -89,6 +90,7 @@ if (import.meta.main) {
|
|
|
89
90
|
ready.then(() => { receiptReady = true; }, () => { /* The final drain reports failure inside the owned helper. */ });
|
|
90
91
|
const budget = hookReplayBudget();
|
|
91
92
|
let drainedCount = 0, captured = false, drainStarted = false;
|
|
93
|
+
let summaryThrough = 0, preparedThrough = 0;
|
|
92
94
|
const replay = async (until: number, waitForReady = true) => {
|
|
93
95
|
// Scanning must not wait on native metadata or cold store imports between summary lines.
|
|
94
96
|
// The final replay may await them; publication/backpressure callbacks only use ready resources.
|
|
@@ -107,9 +109,17 @@ if (import.meta.main) {
|
|
|
107
109
|
const drained = await drainHookCaptures({ ...options, base: options.base!, project, expectedScope, timeRemaining: remaining, replayBudget: budget }, (input, receipt) => {
|
|
108
110
|
store ??= new CaptureStore({ memoryDir: options.base!, project, busyTimeoutMs: 0, cwd: options.cwd });
|
|
109
111
|
const appended = store.append(input, { receipt });
|
|
112
|
+
summaryThrough = Math.max(summaryThrough, store.briefCommitId);
|
|
110
113
|
drain({ drained: ++drainedCount }); // DB commit or durable capture-spool acknowledgement, as in the existing contract.
|
|
111
114
|
return appended;
|
|
112
115
|
});
|
|
116
|
+
if (summaryThrough > preparedThrough && store) {
|
|
117
|
+
try {
|
|
118
|
+
const { buildCaptureBriefCache } = await import("./brief-capture.ts");
|
|
119
|
+
await buildCaptureBriefCache(store, { base: options.base!, project, cwd: options.cwd, builtThrough: summaryThrough, policy: options.policy });
|
|
120
|
+
preparedThrough = summaryThrough;
|
|
121
|
+
} catch { /* Derived cache failure never loses committed capture. A later summary retries. */ }
|
|
122
|
+
}
|
|
113
123
|
captured ||= drained.captured.includes(options.current);
|
|
114
124
|
return drained.captured.length > 0;
|
|
115
125
|
};
|
|
@@ -123,7 +133,8 @@ if (import.meta.main) {
|
|
|
123
133
|
const scanned = await scanHookTranscriptTail(scan.transcript, {
|
|
124
134
|
cwd: scan.cwd, base: scan.base, policy: scan.policy, workBudgetMs: 60, deadline: performance.now() + (scanEnd - now()),
|
|
125
135
|
// Same existing oldest-first drain and one shared budget, never a new 32-file allowance per publication.
|
|
126
|
-
|
|
136
|
+
// SessionEnd stages its bounded tail first; pressure and the final replay keep the same allowance.
|
|
137
|
+
onPublication: scanEvent === "SessionEnd" ? undefined : async () => { await replay(scanEnd, false); },
|
|
127
138
|
onBackpressure: () => replay(scanEnd, false),
|
|
128
139
|
});
|
|
129
140
|
if (scanned) progress(scanned);
|