@staix/agent-mem 0.42.0 → 0.43.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.
Files changed (38) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/README.md +1 -1
  3. package/package.json +2 -2
  4. package/src/cli.ts +32 -3
  5. package/src/commands-table.ts +6 -2
  6. package/src/index.ts +2 -0
  7. package/src/ingest-hosts.ts +440 -0
  8. package/src/memory/candidates.ts +12 -0
  9. package/src/memory/capture.ts +23 -0
  10. package/src/memory/doctor.ts +8 -5
  11. package/src/memory/formats-raise.ts +1 -1
  12. package/src/memory/formats.ts +11 -0
  13. package/src/memory/generation-sync.ts +1 -1
  14. package/src/memory/home-binding-fence.ts +2 -1
  15. package/src/memory/live-state.ts +85 -0
  16. package/src/memory/migrate.ts +3 -3
  17. package/src/memory/mutation.ts +6 -3
  18. package/src/memory/public-prune-activation.ts +1 -1
  19. package/src/memory/public-prune-advance.ts +1 -1
  20. package/src/memory/public-prune-inputs.ts +1 -1
  21. package/src/memory/purge-intent.ts +27 -0
  22. package/src/memory/purge-matcher.ts +101 -0
  23. package/src/memory/purge-plan.ts +90 -0
  24. package/src/memory/read-curated-entries.ts +244 -0
  25. package/src/memory/reader-lease.ts +3 -0
  26. package/src/memory/shard-migration.ts +3 -3
  27. package/src/memory/shard-sync.ts +3 -3
  28. package/src/memory/store.ts +4 -69
  29. package/src/memory/sync-placement-activation-locks.ts +12 -3
  30. package/src/memory/sync-placement-active.ts +2 -0
  31. package/src/memory/sync-placement-guard.ts +2 -0
  32. package/src/memory/sync-placement-journal.ts +1 -1
  33. package/src/memory/sync-placement-transport.ts +8 -3
  34. package/src/memory/sync.ts +3 -2
  35. package/src/setup-console.ts +1 -1
  36. package/src/setup-drift.ts +4 -3
  37. package/src/setup-owned.ts +9 -1
  38. package/src/setup.ts +36 -6
@@ -1,3 +1,4 @@
1
+ import { assertNoPendingPurge } from "./purge-intent.ts";
1
2
  import { assertFormatFloor } from "./formats.ts";
2
3
  import { Database } from "bun:sqlite";
3
4
  import { createHash } from "node:crypto";
@@ -333,6 +334,7 @@ export class CandidateStore {
333
334
  return decodeCandidate(row, () => { this.skippedUnknownKinds++; });
334
335
  }
335
336
  put(rawInput: CandidateInput, verdict: CandidateVerdict, rawOrigin?: CandidateOrigin, screen?: (origin: CandidateOrigin) => boolean): string {
337
+ assertNoPendingPurge(this.dir);
336
338
  // `<private>` spans are never stored: dropped before the input is validated, hashed (so the id) or written.
337
339
  const input = stripPrivateDeep(rawInput);
338
340
  publicOnly(verdict); validate(input);
@@ -362,17 +364,20 @@ export class CandidateStore {
362
364
  }).immediate();
363
365
  }
364
366
  get(id: string, project: string): Candidate | undefined {
367
+ assertNoPendingPurge(this.dir);
365
368
  if (!candidateId(id) || !text(project, 400)) throw new Error("invalid candidate identity");
366
369
  this.prune();
367
370
  const row = this.db.query("SELECT * FROM candidates WHERE id = ? AND project IN (SELECT value FROM json_each(?))").get(id, this.scope(project)) as Parameters<CandidateStore["decode"]>[0] | null;
368
371
  return row ? this.decode(row) : undefined;
369
372
  }
370
373
  reviewedConsolidation(id: string, project: string): ConsolidationReview | undefined {
374
+ assertNoPendingPurge(this.dir);
371
375
  if (!candidateId(id) || !text(project, 400)) throw new Error("invalid candidate identity");
372
376
  const row = this.db.query("SELECT status, note_id FROM consolidation_reviews WHERE id = ? AND project IN (SELECT value FROM json_each(?))").get(id, this.scope(project)) as { status: ConsolidationReview["status"]; note_id: string | null } | null;
373
377
  return row ? { status: row.status, acceptedNoteId: row.note_id } : undefined;
374
378
  }
375
379
  list(filter: CandidateFilter): Candidate[] {
380
+ assertNoPendingPurge(this.dir);
376
381
  if (!text(filter.project, 400) || filter.status !== undefined && !["pending", "accepting", "accepted", "rejected", "all"].includes(filter.status) || filter.kind !== undefined && !KINDS.includes(filter.kind)) throw new Error("invalid candidate filter");
377
382
  const limit = filter.limit ?? CANDIDATE_RETENTION.count;
378
383
  if (!Number.isSafeInteger(limit) || limit < 1 || limit > CANDIDATE_RETENTION.count) throw new Error("candidate limit must be 1..500");
@@ -385,6 +390,7 @@ export class CandidateStore {
385
390
  return (this.db.query(`SELECT * FROM candidates WHERE ${where.join(" AND ")} AND kind IN (SELECT value FROM json_each(?)) ORDER BY at DESC, rowid DESC LIMIT ?`).all(...bind, JSON.stringify(KINDS), limit) as Parameters<CandidateStore["decode"]>[0][]).flatMap(row => this.decode(row) ?? []);
386
391
  }
387
392
  recordCounter(key: CounterKey, values: CounterValues, verdict: CandidateVerdict): string {
393
+ assertNoPendingPurge(this.dir);
388
394
  publicOnly(verdict); const normalized = counterKey(key);
389
395
  for (const value of [values.rendered, values.delivered, values.cited]) if (value !== undefined && value !== null && (!Number.isSafeInteger(value) || value < 0)) throw new Error("counter values must be nonnegative integers or unknown");
390
396
  this.prune(); const id = hash({ schema: "agent-mem.counter/v1", key: normalized });
@@ -394,12 +400,14 @@ export class CandidateStore {
394
400
  this.prune(); return id;
395
401
  }
396
402
  counters(project: string, entry?: string): Counter[] {
403
+ assertNoPendingPurge(this.dir);
397
404
  if (!text(project, 400) || entry !== undefined && !entryId(entry)) throw new Error("invalid counter filter");
398
405
  this.prune();
399
406
  const rows = this.db.query("SELECT * FROM counters WHERE project IN (SELECT value FROM json_each(?)) ORDER BY at DESC, rowid DESC").all(this.scope(project)) as { id: string; payload: string; at: number; rendered: number | null; delivered: number | null; cited: number | null }[];
400
407
  return rows.map(row => ({ id: row.id, key: JSON.parse(row.payload) as CounterKey, createdAt: new Date(row.at).toISOString(), rendered: row.rendered, delivered: row.delivered, cited: row.cited })).filter(row => !entry || row.key.entryId === entry);
401
408
  }
402
409
  reject(id: string, context: { project: string; actor: "person" | "agent"; verdict: CandidateVerdict }): void {
410
+ assertNoPendingPurge(this.dir);
403
411
  validActor(context.actor); publicOnly(context.verdict);
404
412
  this.db.transaction(() => {
405
413
  const candidate = this.get(id, context.project);
@@ -415,6 +423,7 @@ export class CandidateStore {
415
423
  * `restore`: when the row is already gone it is written back as pending with its original time, after the same identity and hash checks as a read.
416
424
  */
417
425
  reopen(id: string, context: { project: string; actor: "person" | "agent"; restore?: Candidate }): void {
426
+ assertNoPendingPurge(this.dir);
418
427
  validActor(context.actor);
419
428
  if (!candidateId(id) || !text(context.project, 400)) throw new Error("invalid candidate identity");
420
429
  this.db.transaction(() => {
@@ -439,9 +448,11 @@ export class CandidateStore {
439
448
  }
440
449
  /** Projects with candidates waiting for review, as stored (an alias key is not resolved here). */
441
450
  projects(): string[] {
451
+ assertNoPendingPurge(this.dir);
442
452
  return (this.db.query("SELECT DISTINCT project FROM candidates WHERE status IN ('pending', 'accepting') ORDER BY project").all() as { project: string }[]).map(row => row.project);
443
453
  }
444
454
  accept(id: string, context: CandidateAcceptance): CandidateAcceptanceResult {
455
+ assertNoPendingPurge(this.dir);
445
456
  validActor(context.actor); publicOnly(context.verdict);
446
457
  if (realPath(context.store.profile.home) !== realPath(this.dir) || typeof context.policy !== "function") throw new Error("candidate acceptance requires its memory store and a current host policy");
447
458
  return context.store.withDeferredPromotions(() => this.acceptDeferred(id, context));
@@ -608,6 +619,7 @@ export class CandidateStore {
608
619
  }
609
620
  /** Reserve before the optional callback, including failed attempts. No table is created on capture/MCP reads. */
610
621
  reserveConsolidationModel(inputBytes: number): boolean {
622
+ assertNoPendingPurge(this.dir);
611
623
  if (!Number.isSafeInteger(inputBytes) || inputBytes < 1 || inputBytes > 8192) throw Error("invalid model input budget");
612
624
  const at = this.now(); if (!Number.isFinite(at)) throw Error("model budget clock unavailable");
613
625
  const day = new Date(at).toISOString().slice(0, 10);
@@ -1,3 +1,4 @@
1
+ import { assertNoPendingPurge } from "./purge-intent.ts";
1
2
  import { invalidateBriefCache } from "../brief-cache.ts";
2
3
  import { assertFormatFloor } from "./formats.ts";
3
4
  import { Database } from "bun:sqlite";
@@ -330,9 +331,11 @@ export class CaptureStore {
330
331
  return value.id;
331
332
  }
332
333
  private writable(): void {
334
+ assertNoPendingPurge(this.base);
333
335
  if (this.readOnly) throw new Error("capture store is read-only");
334
336
  }
335
337
  private checkReadBinding(): void {
338
+ assertNoPendingPurge(this.base);
336
339
  if (this.readOnly && resolveAlias(this.base, this.requestedKey) !== this.key) throw new Error("capture alias binding changed");
337
340
  }
338
341
 
@@ -684,6 +687,26 @@ export class CaptureStore {
684
687
  return rows.map(toRow);
685
688
  }
686
689
 
690
+ /** Read a subset of the same bounded ID-ordered window as rows(), without loading excluded bodies. */
691
+ rowsFiltered(f: { project?: string; sinceId?: number; limit?: number; kinds?: readonly string[]; toolNames?: readonly string[]; since?: string } = {}): CaptureRow[] {
692
+ this.checkReadBinding();
693
+ const window: string[] = [], filters: string[] = [], bind: (string | number)[] = [];
694
+ const add = (clauses: string[], expression: string, value: string | number) => { clauses.push(expression); bind.push(value); };
695
+ if (this.recentReadIds) add(window, "id IN (SELECT value FROM json_each(?))", JSON.stringify(this.recentReadIds));
696
+ if (f.project) add(window, "project = ?", f.project);
697
+ if (f.sinceId !== undefined) add(window, "id > ?", f.sinceId);
698
+ bind.push(f.limit ?? 1000);
699
+ if (f.kinds !== undefined) add(filters, "event IN (SELECT value FROM json_each(?))", JSON.stringify(f.kinds));
700
+ if (f.toolNames !== undefined) add(filters, "tool IN (SELECT value FROM json_each(?))", JSON.stringify(f.toolNames));
701
+ if (f.since !== undefined) add(filters, "at >= ?", f.since);
702
+ const where = (clauses: readonly string[]) => clauses.length ? ` WHERE ${clauses.join(" AND ")}` : "";
703
+ // The two materialized sets contain metadata only. LIMIT comes before filters, and only matched IDs load rows.*.
704
+ const sql = `WITH raw_window AS MATERIALIZED (SELECT id, event, tool, at FROM rows${where(window)} ORDER BY id LIMIT ?),
705
+ matched AS MATERIALIZED (SELECT id FROM raw_window${where(filters)})
706
+ SELECT rows.* FROM matched CROSS JOIN rows ON rows.id = matched.id ORDER BY matched.id`;
707
+ return (this.db.query(sql).all(...bind) as RawRow[]).map(toRow);
708
+ }
709
+
687
710
  /** Generic SQLite index maintenance also covers older writers sharing this file. */
688
711
  private ensureBriefSummaryIndex(bounded: boolean): void {
689
712
  if (this.db.query("SELECT 1 FROM sqlite_master WHERE name='rows_brief_summaries_v1' AND type='index'").get()) return;
@@ -26,6 +26,7 @@ import { nextSyncAt, readSyncState, remoteConfigured, syncDue, usableState } fro
26
26
  import { readSyncStatus } from "./sync-progress.ts";
27
27
  import { readSetupDrift } from "../setup-drift.ts";
28
28
  import { readHookSpoolStatus } from "../hook-spool.ts";
29
+ import { hostIngestSource } from "../ingest-hosts.ts";
29
30
 
30
31
  /**
31
32
  * F15, `amem doctor`: one report over the memory home. It writes nothing into the home. Every check that needs a store (the notes, the brief, the index proof) runs on a
@@ -38,7 +39,7 @@ import { readHookSpoolStatus } from "../hook-spool.ts";
38
39
  export type SectionStatus = "ok" | "attention" | "skipped" | "unavailable";
39
40
  export type Section<T extends object = Record<string, unknown>> = { status: SectionStatus } & T;
40
41
  export const DOCTOR_SCHEMA = "amem.doctor/v1";
41
- export const CLIS = ["claude", "codex", "kimi", "pi", "qwen"] as const;
42
+ export const CLIS = ["claude", "codex", "kimi", "pi", "qwen", "gemini", "opencode", "agy"] as const;
42
43
  export type Cli = typeof CLIS[number];
43
44
  /** A CLI whose last capture is older than this is called stale. */
44
45
  export const CAPTURE_STALE_MS = 7 * 86400_000;
@@ -391,7 +392,7 @@ function captureSection(options: DoctorOptions): Section {
391
392
  const clis: Record<string, unknown> = {};
392
393
  const attention: string[] = [];
393
394
  for (const cli of CLIS) {
394
- const phase = receiptPhase(options.home, cli), registered = phase === "applied", entry = here.get(cli), wide = machine.get(cli);
395
+ const phase = receiptPhase(options.home, cli), registered = phase === "applied" && cli !== "opencode" && cli !== "agy", entry = here.get(cli), wide = machine.get(cli);
395
396
  const last = entry?.last ?? null, state = stateOf(last, options.now);
396
397
  const wideLast = wide?.last ?? null, wideKnown = stateOf(wideLast, options.now);
397
398
  // A fresh row anywhere is definitive; stale or never is only known when every other shard was read.
@@ -405,9 +406,11 @@ function captureSection(options: DoctorOptions): Section {
405
406
  const needs = unsafeRoots.length > 0 || (registered ? decided !== "fresh" : decided === "stale");
406
407
  if (needs) attention.push(cli);
407
408
  const unusedHere = state !== "fresh" && machineState === "fresh";
408
- const hint = needs ? captureHint(cli, registered, decided, trigger, unsafeRoots) : !registered && decided === "never" ? captureHint(cli, registered, decided, "setup") : undefined;
409
+ const hint = needs ? captureHint(cli, registered, decided, trigger, unsafeRoots) : !registered && decided === "never" && cli !== "opencode" && cli !== "agy" ? captureHint(cli, registered, decided, "setup") : undefined;
410
+ // #647 condition 2: an OpenCode store with uncheckpointed WAL frames is skipped by ingest; doctor names that state, never content.
411
+ const source = cli === "opencode" ? hostIngestSource("opencode", env as NodeJS.ProcessEnv).state : undefined;
409
412
  clis[cli] = { hook: registered ? "registered" : "manual", ...(registered ? { hookEvidence: "setup receipt" } : {}), ...(phase === "prepared" ? { setup: "prepared, not applied" } : {}), capture: state, lastCaptureAt: last, rows: entry?.rows ?? 0,
410
- machineCapture: machineState, machineLastCaptureAt: wideLast, machineRows: wide?.rows ?? 0, ...(unusedHere ? { note: "not used in this project" } : {}), ...(hint ? { hint } : {}) };
413
+ machineCapture: machineState, machineLastCaptureAt: wideLast, machineRows: wide?.rows ?? 0, ...(unusedHere ? { note: "not used in this project" } : {}), ...(source === "wal_pending" ? { source: "wal pending: ingest waits until OpenCode checkpoints its database" } : {}), ...(hint ? { hint } : {}) };
411
414
  }
412
415
  return { status: !readable ? "unavailable" : attention.length ? "attention" : "ok", ...(readable ? {} : { reason: "a capture database could not be read" }), clis };
413
416
  }
@@ -505,7 +508,7 @@ function spoolSection(options: DoctorOptions): Section {
505
508
  /** F16: which CLIs ingest at SessionEnd (setup receipts), and the person-owned sync cadence. amem registers no sync hook (a hook may not do network work). */
506
509
  function cadenceSection(options: DoctorOptions): Section {
507
510
  const ingest: Record<string, string> = {};
508
- for (const cli of CLIS) ingest[cli] = receiptPhase(options.home, cli) === "applied" ? (cli === "claude" ? "hooks" : "session end") : "manual";
511
+ for (const cli of CLIS) ingest[cli] = receiptPhase(options.home, cli) === "applied" && cli !== "opencode" && cli !== "agy" ? (cli === "claude" ? "hooks" : "session end") : "manual";
509
512
  const remote = remoteConfigured(options.home), state = usableState(readSyncState(options.home), options.now), next = nextSyncAt(state);
510
513
  const latest = readSyncStatus(options.home, options.now).operations
511
514
  .filter(op => op.state !== "running" && op.state !== "interrupted" && op.lastAliveUnixMs <= options.now)
@@ -115,7 +115,7 @@ export function formatRaiseRefusal(plan: FormatRaisePlan): string | undefined {
115
115
  /** Appends the planned record under the home's mutation fence after rechecking the floors and the inventory are unchanged. */
116
116
  export function applyFormatRaise(plan: FormatRaisePlan, recheck: () => FormatRaisePlan): FormatFloor {
117
117
  const refusal = formatRaiseRefusal(plan); if (refusal) throw new Error(refusal);
118
- const release = acquireMutation(plan.home); if (!release) throw new Error("another memory writer holds this home; rerun when it finishes");
118
+ const release = acquireMutation(plan.home, plan.home); if (!release) throw new Error("another memory writer holds this home; rerun when it finishes");
119
119
  try {
120
120
  const fresh = recheck();
121
121
  if (JSON.stringify(fresh.existing) !== JSON.stringify(plan.existing) || JSON.stringify(fresh.writers) !== JSON.stringify(plan.writers)) throw new Error("formats.json or the writer inventory changed since the preview; rerun the preview");
@@ -1,3 +1,4 @@
1
+ import { assertNoPendingPurge } from "./purge-intent.ts";
1
2
  import { closeSync, constants, fstatSync, lstatSync, openSync, readFileSync, readSync, type BigIntStats } from "node:fs";
2
3
  import { join } from "node:path";
3
4
 
@@ -84,6 +85,7 @@ function readFormatFloorsUncached(file: string): { floors: FormatFloor[]; stamp:
84
85
 
85
86
  /** Refuse before touching `surface` when the home records a floor above this release. */
86
87
  export function assertFormatFloor(home: string, surface: FormatSurface): void {
88
+ assertNoPendingPurge(home);
87
89
  const floors = readFormatFloors(home);
88
90
  if (!floors) return;
89
91
  const reader = READER_VERSION ?? "unknown";
@@ -102,3 +104,12 @@ export function formatFloorAtLeast(home: string, surface: FormatSurface, minimum
102
104
  export function floorRaiseHint(home: string, surface: FormatSurface, minReader: string): string {
103
105
  return `preview amem formats raise ${surface} ${minReader}, then run amem formats raise ${surface} ${minReader} --confirm to append the floor to ${join(home, FORMATS_FILE)}`;
104
106
  }
107
+
108
+
109
+ /** Validate the existing explicit floor before a confirmed local purge installs its intent. */
110
+ export function assertPurgeFormatFloors(home: string, minimum: string, sidecars: readonly ("capture" | "candidates")[] = []): void {
111
+ for (const surface of ["curated", "sync", ...sidecars] as const) {
112
+ assertFormatFloor(home, surface);
113
+ if (!formatFloorAtLeast(home, surface, minimum)) throw new Error(`Local purge requires a ${surface} floor of ${minimum}; ${floorRaiseHint(home, surface, minimum)}.`);
114
+ }
115
+ }
@@ -97,7 +97,7 @@ export async function syncGenerationMemory(store: MemoryStore, opts: SyncOptions
97
97
  if (typeof url !== "string" || !url || url.length > 4096 || url.startsWith("-") || /[\r\n\0]/.test(url)) return result("generation sync remote is invalid");
98
98
  if (await (opts.visibility ?? remoteVisibility)(url) !== "private") return result("generation sync requires positively verified private remote visibility");
99
99
  if (opts.signal?.aborted) return result("stopped");
100
- releaseMutation = acquireMutation(dir);
100
+ releaseMutation = acquireMutation(dir, store.profile.home);
101
101
  if (!releaseMutation) return result("another generation mutation is running");
102
102
  releaseCurated = store.beginCuratedCacheUpdate();
103
103
  releaseSync = lockSync(dir);
@@ -11,6 +11,7 @@
11
11
  * whole set: each path is opened, fstat-ed, read and re-checked against its path, and a mismatch sends the caller back
12
12
  * to the full read for that call. Nothing here claims more than that every comparable input was compared.
13
13
  */
14
+ import { PURGE_INTENT_FILE } from "./purge-intent.ts";
14
15
  import { createHash } from "node:crypto";
15
16
  import { closeSync, constants, fstatSync, lstatSync, openSync, readSync, type BigIntStats } from "node:fs";
16
17
  import { join } from "node:path";
@@ -85,7 +86,7 @@ export interface FenceSelector { readonly pruneInputSetHash?: string; readonly p
85
86
  */
86
87
  export function homeBindingPaths(home: string, selector: FenceSelector | undefined, reported: readonly string[] = []): string[] {
87
88
  const paths = [home, join(home, "profile.json"), join(home, "shards.json"), join(home, "aliases.jsonl"),
88
- join(home, "lifecycle.jsonl"), join(home, "profile.lock"), join(home, PUBLIC_PRUNE_INTENT), join(home, "public-prune-input-sets")];
89
+ join(home, "lifecycle.jsonl"), join(home, "profile.lock"), join(home, PURGE_INTENT_FILE), join(home, PUBLIC_PRUNE_INTENT), join(home, "public-prune-input-sets")];
89
90
  if (selector?.pruneInputSetHash) paths.push(join(home, "public-prune-input-sets", `${selector.pruneInputSetHash}.json`));
90
91
  paths.push(join(home, PLACEMENT_ACTIVATION_INTENT), join(home, "sync-placement"), join(home, "sync-placement", "epochs"), join(home, "sync-placement", "active.json"));
91
92
  if (selector?.placementHead) {
@@ -0,0 +1,85 @@
1
+ import type { Kind } from "./store.ts";
2
+
3
+ // Only a type import from store.ts: the store passes its promoted kinds and unsettled horizon in, so this module adds no runtime cycle.
4
+ /** The lifecycle fold every curated read shares (#680): forgotten, demoted, settled, superseded (with cycle breaking), promoted copies and expiry, from index metadata alone. Pure: it reads nothing. */
5
+ export interface LiveStateInput {
6
+ now: number; ttl: number; unsettledMs: number; promotedKinds: readonly Kind[]; rows: Record<string, string | null>[];
7
+ ops: { id: string; op: string; at: string; target: string; by: string | null }[];
8
+ realms?: Map<string, { id: string; own: number; legacy: number }> | undefined; pruned?: Set<string> | undefined; forgotten?: Iterable<string>;
9
+ }
10
+ export interface LiveState {
11
+ forgotten: Set<string>; demoted: Map<string, string>; promoted: Set<string>; superseded: Map<string, string>; supersedes: Map<string, string[]>;
12
+ expiry: (r: Record<string, string | null>) => string | null;
13
+ }
14
+ export function foldLiveState(input: LiveStateInput): LiveState {
15
+ const { now, rows, ops, realms, pruned } = input;
16
+ const born = realms ? new Set([...realms.values()].filter(row => row.own).map(row => row.id)) : undefined;
17
+ const forgotten = new Set([...ops.filter((o) => o.op === "forget").map((o) => o.target), ...(input.forgotten ?? [])]);
18
+ // Deadlines were fixed when the entries were written, so every process (whatever its own TTL) prunes the same rows.
19
+ const deadline = (o: { at: string; by: string | null }) => o.by && !Number.isNaN(Date.parse(o.by)) ? o.by : new Date(Date.parse(o.at) + input.ttl).toISOString();
20
+ const demoted = new Map(ops.filter((o) => o.op === "demote").map((o) => [o.target, deadline(o)]));
21
+ const settled = new Map<string, string>();
22
+ const settlementKey = (id: string, task: string) => born ? `${born.has(id)}:${task}` : task;
23
+ for (const o of ops) if (o.op === "settle") {
24
+ const source = realms?.get(o.id);
25
+ const keys = !realms ? [o.target] : [
26
+ ...(source?.own ? [`true:${o.target}`] : []),
27
+ ...(source?.legacy || !source?.own ? [`false:${o.target}`] : []),
28
+ ];
29
+ for (const key of keys) if (!settled.has(key)) settled.set(key, deadline(o));
30
+ }
31
+ const superseded = new Map<string, string>(), supersededAt = new Map<string, string>();
32
+ // Relations from ops and from notes' own `supersedes` fold together by write time (then id): the latest intent wins.
33
+ const relate = (old: string, newer: string, when: string) => { if (!(when < (supersededAt.get(old) ?? ""))) { superseded.set(old, newer); supersededAt.set(old, when); } };
34
+ for (const o of ops) if (o.op === "supersede" && o.by) relate(o.target, o.by, `${o.at} ${o.by}`);
35
+ const promoted = new Set<string>();
36
+ for (const r of rows) { if (r.supersedes) relate(r.supersedes, r.id!, `${r.at} ${r.id}`); if (r.promoted_from) promoted.add(r.promoted_from); }
37
+ const expiry = (r: Record<string, string | null>): string | null => {
38
+ const id = r.id!;
39
+ if ((demoted.has(id) ? "short" : r.tier) !== "short") return null;
40
+ // A decision, contract or fail of a settled task not yet copied to long-term waits for its promotion, never expires
41
+ // first; a note saved short-term after the settlement carries its own deadline and stays short-term.
42
+ // A superseded one is held too: if its replacement goes, it shows again, and a rebuild must find it the same way.
43
+ const taskDeadline = r.task ? settled.get(settlementKey(id, r.task)) : undefined;
44
+ if (r.tier === "short" && !demoted.has(id) && !r.expires && taskDeadline && input.promotedKinds.includes(r.kind as Kind)) return null;
45
+ // A deadline written into the note (no task, a late note, an explicit short horizon) is its own, whatever the task does.
46
+ return demoted.get(id) ?? r.expires ?? (r.task ? taskDeadline ?? new Date(Date.parse(r.at!) + input.unsettledMs).toISOString() : new Date(Date.parse(r.at!) + input.ttl).toISOString());
47
+ };
48
+ // A newer entry that was forgotten, expired or pruned no longer replaces anything: the older one shows again. A
49
+ // promoted source lives on as its copy.
50
+ const byId = new Map(rows.map((r) => [r.id!, r]));
51
+ const copyOf = new Map(rows.filter((r) => r.promoted_from).map((r) => [r.promoted_from!, r.id!]));
52
+ const gone = (id: string): boolean => {
53
+ if (pruned?.has(id)) return true;
54
+ const r = byId.get(id);
55
+ if (!r || forgotten.has(id) || (r.promoted_from && forgotten.has(r.promoted_from))) return true;
56
+ const copy = copyOf.get(id);
57
+ if (copy) return gone(copy);
58
+ const e = expiry(r);
59
+ return e !== null && Date.parse(e) <= now;
60
+ };
61
+ // A promoted entry lives on as its copy, on either side of a relation: a promoted replacement still replaces, and a
62
+ // promoted entry that was replaced stays replaced.
63
+ const last = (id: string) => { let to = id; for (let c = copyOf.get(to); c; c = copyOf.get(to)) to = c; return to; };
64
+ for (const [old, newer] of [...superseded]) {
65
+ superseded.set(old, last(newer));
66
+ const copy = last(old);
67
+ if (copy !== old && !superseded.has(copy)) { superseded.set(copy, last(newer)); supersededAt.set(copy, supersededAt.get(old)!); }
68
+ }
69
+ for (const [old, newer] of superseded) if (gone(newer)) superseded.delete(old);
70
+ // Supersessions made apart (two processes, two machines) can close a cycle that would hide every entry in it: the
71
+ // earliest relation in the cycle gives way, so the latest intent stands, the same in every process. Each entry has
72
+ // one replacement, so a chain holds at most one cycle.
73
+ const when = (id: string) => `${supersededAt.get(id) ?? ""} ${id}`; // write time, then ids: the same in every process
74
+ for (const start of [...superseded.keys()]) {
75
+ const seen: string[] = [];
76
+ for (let at: string | undefined = start; at !== undefined && superseded.has(at); at = superseded.get(at)) {
77
+ const i = seen.indexOf(at);
78
+ if (i >= 0) { superseded.delete(seen.slice(i).reduce((x, y) => (when(y) < when(x) ? y : x))); break; }
79
+ seen.push(at);
80
+ }
81
+ }
82
+ const supersedes = new Map<string, string[]>(); // the reverse: what each newer entry replaced
83
+ for (const [old, newer] of superseded) supersedes.set(newer, [...(supersedes.get(newer) ?? []), old]);
84
+ return { forgotten, demoted, promoted, superseded, supersedes, expiry };
85
+ }
@@ -132,7 +132,7 @@ export async function migrate(options: MigrateOptions): Promise<MigrationResult>
132
132
  const safeDirectory = (path: string) => existsSync(path) && lstatSync(path).isDirectory() && !lstatSync(path).isSymbolicLink();
133
133
  if (safeDirectory(parent) && safeDirectory(initial.dir) && existsSync(file) && lstatSync(file).isFile() && !lstatSync(file).isSymbolicLink()) {
134
134
  let unavailable = false;
135
- try { releaseGeneration = acquireMutation(initial.dir); } catch { unavailable = true; }
135
+ try { releaseGeneration = acquireMutation(initial.dir, memoryDir); } catch { unavailable = true; }
136
136
  if (!unavailable && !releaseGeneration) throw new Error("generation mutation lock is busy");
137
137
  }
138
138
  if (readSelector(memoryDir).revision !== initial.selectorRevision) return changed();
@@ -167,7 +167,7 @@ export async function migrate(options: MigrateOptions): Promise<MigrationResult>
167
167
  if (!existing || existing.id !== machine.id || typeof existing.label !== "string") return changed();
168
168
  generationMachine = { id: machine.id, label: existing.label };
169
169
  }
170
- const releaseLegacy = acquireMutation(memoryDir);
170
+ const releaseLegacy = acquireMutation(memoryDir, memoryDir);
171
171
  if (!releaseLegacy) throw new Error("legacy mutation lock is busy");
172
172
  let sources: SourcePrefix[], legacyCommit: string | undefined;
173
173
  try {
@@ -200,7 +200,7 @@ export async function migrate(options: MigrateOptions): Promise<MigrationResult>
200
200
  || canonicalJSON(readProfileJSON(join(dir, "machine.json"))) !== canonicalJSON(journal.machine) || journal.machine.id !== machine.id) return changed();
201
201
  verifySources(memoryDir, journal.generation, journal.sources, journal.legacyCommit);
202
202
  const profile: BoundProfile = { kind: "generation", home: memoryDir, dir, generation: journal.generation, selectorRevision: journal.selectorRevision };
203
- const releaseGeneration = acquireMutation(dir);
203
+ const releaseGeneration = acquireMutation(dir, memoryDir);
204
204
  if (!releaseGeneration) throw new Error("generation mutation lock is busy");
205
205
  try {
206
206
  if (journal.phase !== "sealed" && journal.phase !== "active") writeSources(memoryDir, journal);
@@ -1,3 +1,4 @@
1
+ import { assertNoPendingPurge } from "./purge-intent.ts";
1
2
  import { Database } from "bun:sqlite";
2
3
  import { chmodSync, lstatSync } from "node:fs";
3
4
  import { join } from "node:path";
@@ -25,10 +26,12 @@ export function assertMutationHandle(handle: MutationHandle, dir: string): void
25
26
  || realPath(dir) !== state.dir || stat.dev !== state.dev || stat.ino !== state.ino) throw new Error("mutation handle unavailable or directory changed");
26
27
  }
27
28
  /** Sync holds a separate connection across awaits; an unrelated call cannot bypass it. */
28
- export function acquireMutation(dir: string): MutationHandle | undefined {
29
+ export function acquireMutation(dir: string, memoryHome: string): MutationHandle | undefined {
29
30
  const stat = lstatSync(dir);
30
31
  if (stat.isSymbolicLink() || !stat.isDirectory()) throw new Error("mutation directory unavailable");
31
- const canonical = realPath(dir), db = mutationDatabase(canonical);
32
+ const canonical = realPath(dir);
33
+ assertNoPendingPurge(memoryHome);
34
+ const db = mutationDatabase(canonical);
32
35
  try { db.run("BEGIN IMMEDIATE"); }
33
36
  catch { db.close(); return undefined; }
34
37
  const release = (() => {
@@ -38,7 +41,7 @@ export function acquireMutation(dir: string): MutationHandle | undefined {
38
41
  try { db.run("ROLLBACK"); } finally { db.close(); }
39
42
  }) as MutationHandle;
40
43
  mutations.set(release, { dir: canonical, dev: stat.dev, ino: stat.ino, db, active: true });
41
- try { assertMutationHandle(release, dir); } catch (error) { release(); throw error; }
44
+ try { assertMutationHandle(release, dir); assertNoPendingPurge(memoryHome); } catch (error) { release(); throw error; }
42
45
  return release;
43
46
  }
44
47
 
@@ -230,7 +230,7 @@ export async function activatePublicPruneView(options: PublicPruneActivationOpti
230
230
  try {
231
231
  guard(lstatSync(home).dev === rootStat.dev && lstatSync(home).ino === rootStat.ino);
232
232
  const dirs = [...new Set([home, ...intent.realms.map(realm => realm.profile.dir)])].sort();
233
- for (const dir of dirs) { assertNoLiveReaders(dir, {includeShards:true}); const release = acquireMutation(dir); guard(release); releases.push(release); }
233
+ for (const dir of dirs) { assertNoLiveReaders(dir, {includeShards:true}); const release = acquireMutation(dir, home); guard(release); releases.push(release); }
234
234
  validateAdvance(intent);
235
235
  if (pending) writeImmutableActivationMetadata(intentFile, canonicalJSON(intent) + "\n");
236
236
  if (!pending) {
@@ -108,7 +108,7 @@ function run(intent: AdvanceIntent, provided: readonly MutationHandle[]|undefine
108
108
  const checks=proofs(intent), releases:MutationHandle[]=[];
109
109
  const work=()=>{
110
110
  const dirs=[intent.home,...intent.bindings.map(item=>item.dir)].sort();
111
- const handles=provided??dirs.map(dir=>{const lease=acquireMutation(dir);guard(lease);releases.push(lease);return lease;});
111
+ const handles=provided??dirs.map(dir=>{const lease=acquireMutation(dir, intent.home);guard(lease);releases.push(lease);return lease;});
112
112
  const verify=()=>{
113
113
  const root=owned(intent.home,true);guard(root.dev===intent.root.dev&&root.ino===intent.root.ino&&hashJSON(optional(aliasLogPath(intent.home)))===intent.root.aliasesHash&&hashJSON(raw(join(intent.home,"machine.json")))===intent.root.machineHash);
114
114
  for(const dir of dirs){let found=false;for(const handle of handles){try{assertMutationHandle(handle,dir);found=true;break;}catch{}}guard(found);}
@@ -311,7 +311,7 @@ export function persistPublicPruneInput(plan: PublicPruneInputPlan, options: { o
311
311
  }; current();
312
312
  // The shared SQLite lock is an ownership fence, never an archive or membership source.
313
313
  for (const suffix of ["", "-wal", "-shm", "-journal"]) { const stat = lstatSync(join(dir, "mutation-lock.db" + suffix), { throwIfNoEntry: false }); if (stat) privateStat(stat); }
314
- const release = options.mutation ?? acquireMutation(dir); guard(release); assertMutationHandle(release, dir); try {
314
+ const release = options.mutation ?? acquireMutation(dir, dir); guard(release); assertMutationHandle(release, dir); try {
315
315
  current(); assertMutationHandle(release, dir); recoverLinkedTemps(dir, release); current(); const previous = expected.inputSetHash;
316
316
  const members = previous ? replay({ realm: expected.realm, receivingGeneration: expected.receivingGeneration, ...(expected.publicationFormat ? {publicationFormat:expected.publicationFormat} : {}), inputSetHash: previous }, (kind, id) => read(dir, kind, id)).inputs : [];
317
317
  const inputHash = prepared.input && hashJSON(prepared.input), includes = inputHash !== undefined && members.includes(inputHash);
@@ -0,0 +1,27 @@
1
+ import { lstatSync } from "node:fs";
2
+ import { join } from "node:path";
3
+
4
+ /** Stable-home barriers. Even malformed or link-shaped evidence blocks access. */
5
+ export const PURGE_INTENT_FILE = "purge-intent.json";
6
+ export const PURGE_PUBLICATION_BLOCK_FILE = "purge-publication-block.json";
7
+ export const PURGE_PENDING = "A local purge is pending; keep the home closed and use amem doctor to check status.";
8
+ export const PURGE_PUBLICATION_BLOCKED = "Publication is blocked after a local purge; see docs/purge-design.md, First implementation: local purge and manual remote move.";
9
+
10
+ function barrierPresent(home: string, file: string): boolean {
11
+ try { return lstatSync(join(home, file), { throwIfNoEntry: false }) !== undefined; }
12
+ catch { return true; }
13
+ }
14
+
15
+ export function purgePending(home: string): boolean {
16
+ return barrierPresent(home, PURGE_INTENT_FILE);
17
+ }
18
+
19
+ export function assertNoPendingPurge(home: string): void {
20
+ if (purgePending(home)) throw new Error(PURGE_PENDING);
21
+ }
22
+
23
+ /** Local-first: alternate remote spellings never bypass this home-wide block. */
24
+ export function purgePublicationRefusal(home: string): string | undefined {
25
+ if (purgePending(home)) return PURGE_PENDING;
26
+ if (barrierPresent(home, PURGE_PUBLICATION_BLOCK_FILE)) return PURGE_PUBLICATION_BLOCKED;
27
+ }
@@ -0,0 +1,101 @@
1
+ import { Database, constants as sqlite } from "bun:sqlite";
2
+ import { closeSync, constants, fstatSync, lstatSync, openSync, readdirSync, readSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { pathToFileURL } from "node:url";
5
+ import { hashJSON } from "./generation.ts";
6
+ import { realPath } from "./platform.ts";
7
+
8
+ const MATCHER_BYTES = 4096, MAX_ROWS = 4_000_000, MAX_MATCHES = 1000, MAX_SHARDS = 4096, MAX_SCAN_MS = 120_000;
9
+ const unavailable = (): never => { throw new Error(/* refusal-by-design: operator-knowledge close the sidecar readers or supply a private bounded file. */ "Purge matcher input is unavailable, unclean or over its preview bound; close capture and candidate readers and check docs/purge-design.md."); };
10
+ const stamp = (stat: ReturnType<typeof fstatSync>) => [stat.dev, stat.ino, stat.size, stat.mtimeMs, stat.ctimeMs].join(":");
11
+
12
+ function privateBytes(file: string, maximum: number): Buffer {
13
+ const fd = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
14
+ try {
15
+ const before = fstatSync(fd);
16
+ if (!before.isFile() || before.nlink !== 1 || before.uid !== process.getuid?.() || (before.mode & 0o077) !== 0 || before.size > maximum) return unavailable();
17
+ const result = Buffer.alloc(before.size);
18
+ let offset = 0;
19
+ while (offset < result.length) {
20
+ const count = readSync(fd, result, offset, result.length - offset, offset);
21
+ if (!count) return unavailable();
22
+ offset += count;
23
+ }
24
+ if (stamp(fstatSync(fd)) !== stamp(before) || stamp(lstatSync(file)) !== stamp(before)) return unavailable();
25
+ return result;
26
+ } finally { closeSync(fd); }
27
+ }
28
+
29
+ export function openPurgeMatcher(file: string): string {
30
+ try {
31
+ const raw = new TextDecoder("utf-8", { fatal: true }).decode(privateBytes(file, MATCHER_BYTES));
32
+ if (!raw.length || raw.includes(String.fromCharCode(0))) return unavailable();
33
+ return raw;
34
+ } catch { return unavailable(); }
35
+ }
36
+
37
+ export interface PurgeSidecarMatch { store: "capture" | "candidate"; location: string; id: string; rowHash: string }
38
+ export interface PurgeSidecarSource { store: PurgeSidecarMatch["store"]; location: string; hash: string }
39
+ function contains(value: unknown, needle: string): boolean {
40
+ const pending = [value];
41
+ while (pending.length) {
42
+ const next = pending.pop();
43
+ if (typeof next === "string" && next.includes(needle)) return true;
44
+ if (next && typeof next === "object") for (const child of Object.values(next)) pending.push(child);
45
+ }
46
+ return false;
47
+ }
48
+
49
+ /** Stream immutable, checkpointed databases without opening SQLite sidecars or copying the main files. */
50
+ export function previewPurgeMatches(home: string, machine: string, needle: string): { matches: PurgeSidecarMatch[]; sources: PurgeSidecarSource[] } {
51
+ try {
52
+ const files: { store: PurgeSidecarMatch["store"]; location: string; file: string }[] = [];
53
+ const projects = join(home, "projects"), root = lstatSync(projects, { throwIfNoEntry: false });
54
+ if (root && (!root.isDirectory() || realPath(projects) !== projects)) return unavailable();
55
+ const dirs = root ? readdirSync(projects).sort() : [];
56
+ if (dirs.length > MAX_SHARDS) return unavailable();
57
+ for (const location of dirs) if (/^[a-f0-9]{16}$/.test(location)) files.push({ store: "capture", location, file: join(projects, location, "machine", machine, "capture.db") });
58
+ files.push({ store: "candidate", location: "home", file: join(home, "candidates.db") });
59
+ const matches: PurgeSidecarMatch[] = [], sources: PurgeSidecarSource[] = [];
60
+ let rowsLeft = MAX_ROWS;
61
+ const deadline = performance.now() + MAX_SCAN_MS;
62
+ const observed: { file: string; stamp: string }[] = [];
63
+ const state = (file: string) => {
64
+ const db = lstatSync(file, { bigint: true, throwIfNoEntry: false });
65
+ for (const suffix of ["-wal", "-journal"]) {
66
+ const sidecar = lstatSync(file + suffix, { throwIfNoEntry: false });
67
+ if (sidecar && (!sidecar.isFile() || sidecar.size !== 0)) return unavailable();
68
+ }
69
+ if (db && (!db.isFile() || db.nlink !== 1n || db.uid !== BigInt(process.getuid?.() ?? -1)
70
+ || (db.mode & 0o077n) !== 0n || realPath(file) !== file)) return unavailable();
71
+ return db ? [db.dev, db.ino, db.size, db.mtimeNs, db.ctimeNs].join(":") : "absent";
72
+ };
73
+ for (const { store, location, file } of files) {
74
+ const before = state(file);
75
+ observed.push({ file, stamp: before });
76
+ if (before === "absent") continue;
77
+ if (performance.now() >= deadline) return unavailable();
78
+ // Bun's boolean readonly option omits SQLITE_OPEN_URI. SQLite builds without USE_URI need the flag explicitly.
79
+ const db = new Database(`${pathToFileURL(file).href}?immutable=1`, sqlite.SQLITE_OPEN_READONLY | sqlite.SQLITE_OPEN_URI);
80
+ try {
81
+ const table = store === "capture" ? "rows" : "candidates";
82
+ if (!db.query("SELECT 1 FROM sqlite_schema WHERE type = 'table' AND name = ?").get(table)) return unavailable();
83
+ const query = `SELECT * FROM ${table} ORDER BY id LIMIT ?`;
84
+ for (const row of db.query(query).iterate(rowsLeft + 1) as Iterable<Record<string, unknown>>) {
85
+ if (--rowsLeft < 0 || performance.now() >= deadline) return unavailable();
86
+ const input = store === "capture" ? [row.excerpt, JSON.parse(String(row.paths)), row.tool] : JSON.parse(String(row.payload));
87
+ if (!contains(input, needle)) continue;
88
+ if (store === "capture" ? typeof row.id !== "number" || !Number.isSafeInteger(row.id) || row.id < 1
89
+ : typeof row.id !== "string" || !/^[a-f0-9]{64}$/.test(row.id)) return unavailable();
90
+ if (matches.length >= MAX_MATCHES) return unavailable();
91
+ matches.push({ store, location, id: String(row.id), rowHash: hashJSON(row) });
92
+ }
93
+ } finally { db.close(); }
94
+ if (state(file) !== before) return unavailable();
95
+ // The source digest binds filesystem identity; every selected row also carries its own content hash.
96
+ sources.push({ store, location, hash: hashJSON(before) });
97
+ }
98
+ if (observed.some(item => state(item.file) !== item.stamp) || (root && JSON.stringify(readdirSync(projects).sort()) !== JSON.stringify(dirs))) return unavailable();
99
+ return { matches, sources };
100
+ } catch { return unavailable(); }
101
+ }