@staix/agent-mem 0.28.2 → 0.29.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 (40) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/README.md +11 -7
  3. package/package.json +1 -1
  4. package/src/brief-work.ts +142 -0
  5. package/src/cli.ts +34 -13
  6. package/src/commands-table.ts +2 -0
  7. package/src/mcp-memory.ts +1 -1
  8. package/src/memory/commands.ts +5 -3
  9. package/src/memory/curated-cache-state.ts +10 -7
  10. package/src/memory/doctor.ts +15 -12
  11. package/src/memory/generation-index.ts +79 -17
  12. package/src/memory/index-file.ts +2 -2
  13. package/src/memory/metrics.ts +1 -0
  14. package/src/memory/shard-sync-history.ts +6 -0
  15. package/src/memory/shard.ts +33 -13
  16. package/src/memory/store.ts +147 -41
  17. package/src/memory/sync-placement-capture.ts +53 -17
  18. package/src/memory/sync-placement-guard.ts +52 -1
  19. package/src/memory/sync-placement-inventory.ts +136 -0
  20. package/src/memory/sync-placement-journal-storage.ts +21 -4
  21. package/src/memory/sync-placement-journal.ts +13 -4
  22. package/src/memory/sync-placement-materialize.ts +14 -3
  23. package/src/memory/sync-placement-publication-plan.ts +8 -4
  24. package/src/memory/sync-placement-realm-admission-storage.ts +128 -0
  25. package/src/memory/sync-placement-realm-admission.ts +335 -0
  26. package/src/memory/sync-placement-realm-attribution.ts +23 -0
  27. package/src/memory/sync-placement-realm-effective.ts +71 -0
  28. package/src/memory/sync-placement-realm-extension-format.ts +66 -0
  29. package/src/memory/sync-placement-realm-extension-storage.ts +82 -0
  30. package/src/memory/sync-placement-realm-intent-format.ts +55 -0
  31. package/src/memory/sync-placement-realm-intent-storage.ts +123 -0
  32. package/src/memory/sync-placement-realm-pending.ts +27 -0
  33. package/src/memory/sync-placement-realm-proof.ts +131 -0
  34. package/src/memory/sync-placement-realm-torn.ts +26 -0
  35. package/src/memory/sync-placement-transport.ts +69 -31
  36. package/src/memory/sync-placement-yield.ts +30 -0
  37. package/src/memory/sync-progress.ts +47 -6
  38. package/src/memory/sync.ts +23 -1
  39. package/src/memory/work-lists.ts +129 -9
  40. package/src/session-brief.ts +34 -1
@@ -11,8 +11,16 @@ import { looksSecret } from "./screen.ts";
11
11
  import { stripPrivateDeep, stripPrivateSpans } from "./private-spans.ts";
12
12
  import { ensureShardDescriptor, resolveAlias, shardDir } from "./shard.ts";
13
13
  import { machineId } from "./machine.ts";
14
+ import type { WorkBrief, WorkBriefBinding, WorkSegment } from "../brief-work.ts";
15
+ import { WORK_BRIEF_BYTES, WORK_BRIEF_VIEWS, pruneWorkBriefs, readWorkBrief, reserveWorkBriefSlot, workLogSegments, workPolicyRevision, writeWorkBrief } from "../brief-work.ts";
16
+ import { configuredPolicyOptions } from "./config.ts";
17
+ import { createStandalonePolicy, type StandalonePolicyOptions } from "./policy.ts";
14
18
 
15
19
  const SCHEMA = "agent-mem.work-list/v1", ROW_BYTES = 16_384;
20
+ /** The size of this store's own log segment at one point in time. */
21
+ type SegmentSize = { bytes: number; mtimeMs: number };
22
+ /** What one append changed: the frontier before and after it, and whether it is the last row the replay would apply. */
23
+ type WriteFrame = { prior?: SegmentSize; appended: SegmentSize; ordered: boolean };
16
24
  export type WorkListFields = Record<string, string | number | boolean | null>;
17
25
  export type WorkListPolicy = (row: unknown) => boolean | Promise<boolean>;
18
26
  export interface WorkListSource { source: string; id: string; machine?: string; at?: number }
@@ -108,10 +116,28 @@ function scan(path: string, consume?: (text: string, end: number) => void, prefi
108
116
  } finally { closeSync(fd); }
109
117
  }
110
118
 
119
+ /** The same fold `read()` performs, applied to one appended row; lists and items stay in the store's sorted order. */
120
+ function applyWorkRow(rows: WorkBrief["rows"], row: { list: string; fields: WorkListFields }): WorkBrief["rows"] {
121
+ let view = rows.find(candidate => candidate.source.list === row.list)?.source;
122
+ if (!view) { view = { list: row.list, fields: {}, items: [], closed: false }; rows.push({ source: view }); }
123
+ const task = row.fields.task;
124
+ let target: WorkListFields = view.fields;
125
+ if (typeof task === "string") {
126
+ const found = view.items.find(item => item.task === task);
127
+ if (found) target = found.fields;
128
+ else { const fields: WorkListFields = {}; view.items.push({ task, fields }); view.items.sort((a, b) => a.task.localeCompare(b.task)); target = fields; }
129
+ }
130
+ for (const [key, value] of Object.entries(row.fields)) if (key !== "task") { if (value === null) delete target[key]; else target[key] = value; }
131
+ view.closed = view.fields.status === "done";
132
+ rows.sort((a, b) => a.source.list.localeCompare(b.source.list));
133
+ return rows;
134
+ }
135
+
111
136
  /** Project-scoped append truth; the index and writer lock are independent of generations and capture eviction. */
112
137
  export class WorkListStore {
113
138
  readonly dir: string;
114
139
  readonly project: string;
140
+ private readonly base: string;
115
141
  private readonly db: Database;
116
142
  private readonly mutation: Database;
117
143
  private readonly machine: string;
@@ -121,10 +147,13 @@ export class WorkListStore {
121
147
  private readonly busyTimeoutMs: number;
122
148
  private readonly readers = new Set<() => void>();
123
149
  private closed = false;
150
+ // ponytail: retry after a possible shrink, at most every 128 writes, or after 1024 writes; a size-aware index could refine this.
151
+ private readonly briefRetryWrites = new Map<string, { remaining: number; shrinkCooldown: number }>();
152
+ private readonly briefPolicyOptions: (() => StandalonePolicyOptions) | undefined;
124
153
  /** #27: the work logs of keys aliased to this project that already have one; read beside this log through their own snapshot cursors, never written. */
125
154
  private readonly aliased: WorkListStore[] = [];
126
155
 
127
- constructor(options: { base: string; project: string; policy: WorkListPolicy; now?: () => number; aliases?: readonly string[]; exact?: boolean; timeRemaining?: () => number; busyTimeoutMs?: number }) {
156
+ constructor(options: { base: string; project: string; policy: WorkListPolicy; briefPolicyOptions?: () => StandalonePolicyOptions; now?: () => number; aliases?: readonly string[]; exact?: boolean; timeRemaining?: () => number; busyTimeoutMs?: number }) {
128
157
  if (!bounded(options.project, 1000) || typeof options.policy !== "function") throw new Error("invalid work-list input");
129
158
  this.timeRemaining = options.timeRemaining;
130
159
  this.busyTimeoutMs = options.busyTimeoutMs ?? 3000;
@@ -132,6 +161,7 @@ export class WorkListStore {
132
161
  || !Number.isSafeInteger(this.busyTimeoutMs) || this.busyTimeoutMs < 0 || this.busyTimeoutMs > 3000) throw new Error("invalid work-list budget");
133
162
  this.checkBudget();
134
163
  const base = canonicalPath(options.base);
164
+ this.base = base;
135
165
  assertFormatFloor(base, "work-lists");
136
166
  this.project = options.exact === true ? options.project : resolveAlias(base, options.project);
137
167
  regular(join(base, "projects"), true); regular(shardDir(base, this.project), true);
@@ -144,7 +174,7 @@ export class WorkListStore {
144
174
  if (lstatSync(this.dir).isSymbolicLink() || lstatSync(join(this.dir, "log")).isSymbolicLink()) throw new Error("work log directory is invalid");
145
175
  this.checkBudget();
146
176
  this.machine = machineId(base).id;
147
- this.policy = options.policy; this.now = options.now ?? Date.now;
177
+ this.policy = options.policy; this.briefPolicyOptions = options.briefPolicyOptions; this.now = options.now ?? Date.now;
148
178
  for (const name of ["mutation-lock.db", "index.db", "index.db-wal", "index.db-shm"]) regular(join(this.dir, name));
149
179
  let openedMutation: Database | undefined, openedDb: Database | undefined;
150
180
  try {
@@ -256,12 +286,12 @@ export class WorkListStore {
256
286
  }).immediate();
257
287
  }
258
288
  rebuild(): void { this.locked(() => this.refresh(true)); }
259
- private async permitted(row: WorkRow): Promise<boolean> {
289
+ private async permitted(row: WorkRow, policy: WorkListPolicy = this.policy): Promise<boolean> {
260
290
  this.checkBudget();
261
291
  if (looksSecret(canonicalJSON(row))) return false;
262
292
  const copy = structuredClone(row); Object.freeze(copy.fields); if (copy.source) Object.freeze(copy.source); Object.freeze(copy);
263
293
  let allowed = false;
264
- try { allowed = await this.policy(copy) === true; } catch { /* Refusal remains a refusal. */ }
294
+ try { allowed = await policy(copy) === true; } catch { /* Refusal remains a refusal. */ }
265
295
  this.checkBudget();
266
296
  return allowed;
267
297
  }
@@ -356,7 +386,9 @@ export class WorkListStore {
356
386
  const row: WorkRow = { ...body, id: hashJSON(body) };
357
387
  if (Buffer.byteLength(canonicalJSON(row)) > ROW_BYTES) return invalid();
358
388
  if (!await this.permitted(row)) throw new Error("work-list privacy policy refused the write");
359
- return this.locked(() => {
389
+ const log = join(this.dir, "log", `${this.machine}.jsonl`);
390
+ let frame: WriteFrame | undefined;
391
+ const stored = this.locked(() => {
360
392
  this.refresh();
361
393
  const key = receipt(row);
362
394
  if (key) {
@@ -368,14 +400,102 @@ export class WorkListStore {
368
400
  }
369
401
  }
370
402
  // No metadata changes after screening: the derived index records same-machine append order.
371
- regular(join(this.dir, "log", `${this.machine}.jsonl`));
372
- appendFileSync(join(this.dir, "log", `${this.machine}.jsonl`), canonicalJSON(row) + "\n", { mode: 0o600 });
403
+ regular(log);
404
+ const before = lstatSync(log, { throwIfNoEntry: false });
405
+ const prior = before ? { bytes: before.size, mtimeMs: before.mtimeMs } : undefined;
406
+ appendFileSync(log, canonicalJSON(row) + "\n", { mode: 0o600 });
407
+ const after = lstatSync(log); // the frontier this append alone reached, read under the same lock
373
408
  this.refresh();
409
+ frame = { prior, appended: { bytes: after.size, mtimeMs: after.mtimeMs }, ordered: this.ordered(row, after.size) };
374
410
  return { id: row.id, already: false };
375
411
  });
412
+ if (!stored.already) await this.publishBrief(row, frame);
413
+ return stored;
414
+ }
415
+
416
+ /** The one write a fold may apply last: an imported row carrying a historical `at` sorts before rows already reduced. */
417
+ private ordered(row: WorkRow, position: number): boolean {
418
+ const order = replayKey(row, position);
419
+ return [this, ...this.aliased].every(store => {
420
+ const latest = store.db.query("SELECT max(replay) AS replay FROM work_ops").get() as { replay: string | null } | null;
421
+ return !latest?.replay || order >= latest.replay;
422
+ });
423
+ }
424
+
425
+ /**
426
+ * Off-hook derived publication for the session-start work section. The common case folds the row just appended into the
427
+ * cached views (a few hundred microseconds); a rebuild reads the whole log and is kept for a foreign or first frontier.
428
+ * The file always records the frontier its rows were read at, so a row another writer appended in between can only make
429
+ * the snapshot stale, never make it claim content it does not hold.
430
+ */
431
+ async publishBrief(row?: WorkRow, frame?: WriteFrame): Promise<void> {
432
+ try {
433
+ const home = configuredPolicyOptions(this.base);
434
+ await this.publishPolicyBrief(home, undefined, row, frame);
435
+ if (this.briefPolicyOptions) {
436
+ const effective = this.briefPolicyOptions();
437
+ const revision = workPolicyRevision(effective);
438
+ if (revision !== workPolicyRevision(home)) await this.publishPolicyBrief(effective, revision, row, frame);
439
+ }
440
+ } catch { /* A later write retries. */ }
441
+ }
442
+
443
+ private async publishPolicyBrief(options: StandalonePolicyOptions, revision: string | undefined, row?: WorkRow, frame?: WriteFrame): Promise<void> {
444
+ const key = revision ?? "home", retry = this.briefRetryWrites.get(key);
445
+ const shrink = !!row && Object.values(row.fields).some(value => value === null);
446
+ const shrinkRetry = !!retry && shrink && retry.shrinkCooldown <= 0;
447
+ if (retry && retry.remaining > 1 && !shrinkRetry) {
448
+ this.briefRetryWrites.set(key, { remaining: retry.remaining - 1, shrinkCooldown: Math.max(0, retry.shrinkCooldown - 1) });
449
+ return;
450
+ }
451
+ this.briefRetryWrites.delete(key);
452
+ const standalone = createStandalonePolicy({ denyPaths: options.denyPaths, piiPatterns: options.piiPatterns });
453
+ const segments = workLogSegments(this.base, this.project, this.aliased.map(store => store.project));
454
+ if (!segments) return;
455
+ const binding = { base: this.base, project: this.project, machine: this.machine, ...(revision ? { revision } : {}) };
456
+ const policy = workPolicyRevision(options);
457
+ if (row && frame?.prior && frame.ordered) {
458
+ const cached = readWorkBrief(binding), allowed = await this.permitted(row, input => standalone.screenStandalone(input));
459
+ const holds = !allowed || !cached?.truncated || cached.rows.some(item => item.source.list === row.list);
460
+ if (cached && holds && cached.policy === policy
461
+ && JSON.stringify(cached.segments) === JSON.stringify(this.frontier(segments, frame.prior))
462
+ && JSON.stringify(segments) === JSON.stringify(this.frontier(segments, frame.appended))) {
463
+ const rows = allowed ? applyWorkRow(cached.rows, row) : cached.rows;
464
+ if (rows.length <= WORK_BRIEF_VIEWS) { this.publish(binding, { ...cached, segments, rows }, key, shrinkRetry); return; }
465
+ }
466
+ }
467
+ const views = await this.read(undefined, true, input => standalone.screenStandalone(input));
468
+ const rest = workLogSegments(this.base, this.project, this.aliased.map(store => store.project));
469
+ if (!rest || JSON.stringify(segments) !== JSON.stringify(rest)) return;
470
+ if (revision && (!this.briefPolicyOptions || workPolicyRevision(this.briefPolicyOptions()) !== revision)) return;
471
+ this.publish(binding, { schema: "agent-mem.brief-work/v1", project: this.project, segments, policy,
472
+ rows: views.slice(0, WORK_BRIEF_VIEWS).map(source => ({ source })), truncated: views.length > WORK_BRIEF_VIEWS }, key, shrinkRetry);
473
+ }
474
+
475
+ /** Publication and revision eviction share the work mutation lock. */
476
+ private publish(binding: WorkBriefBinding, brief: WorkBrief, key: string, shrinkRetry: boolean): boolean {
477
+ const written = this.locked(() => {
478
+ if (binding.revision && Buffer.byteLength(JSON.stringify(brief) + "\n") <= WORK_BRIEF_BYTES) reserveWorkBriefSlot(binding);
479
+ const ok = writeWorkBrief(binding, brief);
480
+ if (ok && binding.revision) pruneWorkBriefs(binding);
481
+ return ok;
482
+ });
483
+ if (!written) {
484
+ this.briefRetryWrites.set(key, { remaining: 1024, shrinkCooldown: shrinkRetry ? 128 : 0 });
485
+ if (this.briefRetryWrites.size > 5) this.briefRetryWrites.delete(this.briefRetryWrites.keys().next().value!);
486
+ }
487
+ return written;
488
+ }
489
+
490
+ /** This log's own segment rewritten to one observed size, so a cached frontier can be compared against a single write. */
491
+ private frontier(segments: WorkSegment[], own: SegmentSize): WorkSegment[] {
492
+ const file = `${this.machine}.jsonl`;
493
+ return segments.map(segment => segment.key !== this.project || segment.file !== file ? segment
494
+ : { ...segment, bytes: own.bytes, mtimeMs: own.mtimeMs });
376
495
  }
377
496
 
378
- async read(rawList?: string, includeClosed = false): Promise<WorkListView[]> {
497
+ /** `policy` screens this read instead of the store's own: the off-hook snapshot uses the standalone policy, never an interactive host prompt. */
498
+ async read(rawList?: string, includeClosed = false, policy?: WorkListPolicy): Promise<WorkListView[]> {
379
499
  this.checkBudget();
380
500
  if (rawList !== undefined && !bounded(rawList, 300) || typeof includeClosed !== "boolean") return invalid();
381
501
  const list = rawList === undefined ? undefined : stripPrivateSpans(rawList).trim(); // the same name a write stored
@@ -387,7 +507,7 @@ export class WorkListStore {
387
507
  try {
388
508
  for (const { row } of rows) {
389
509
  this.checkBudget();
390
- const allowed = await this.permitted(row);
510
+ const allowed = await this.permitted(row, policy);
391
511
  if (this.closed) throw new Error("work-list store is closed");
392
512
  if (!allowed) continue;
393
513
  if (list !== undefined && row.list !== list) continue;
@@ -7,6 +7,7 @@ import { CURATED_CACHE_MIN_READER, readCuratedBriefCache, readPreferenceBriefCac
7
7
  import { PREFERENCE_SLOT, SESSION_PREFERENCE_SHARE } from "./memory/preference-brief.ts";
8
8
  import { curatedProfileBinding } from "./memory/curated-cache-state.ts";
9
9
  import { captureDisplay, displayText, recordDisplay, validCachedCapture } from "./brief-capture.ts";
10
+ import { readWorkBrief, workLogSegments, workPolicyRevision } from "./brief-work.ts";
10
11
  import { assertFormatFloor, FormatFloorError } from "./memory/formats.ts";
11
12
  import { readSelector } from "./memory/generation.ts";
12
13
  import { memoryHome } from "./memory/home.ts";
@@ -101,7 +102,8 @@ export async function sessionStartBrief(options: BriefOptions): Promise<BriefRes
101
102
  const requested = options.project ?? memoryProjectKey(cwd, { repositoryIsolation: true }), project = resolveAlias(base, requested);
102
103
  // #15 T5: a project the person archived or forgot yields no brief at all, before any lease, store or screen is opened.
103
104
  if (projectState(base, project) !== "active") return result;
104
- const policy = createStandalonePolicy(configuredPolicyOptions(base, options.repository === false ? undefined : cwd, options.policy)), release = options.measureOnly ? Object.assign(() => {}, { verify: () => {} }) : registerReaderLease(base, options.nativeSession ? { signature: options.nativeSession.signature, busyTimeoutMs: 0 } : undefined);
105
+ const effectivePolicy = configuredPolicyOptions(base, options.repository === false ? undefined : cwd, options.policy);
106
+ const policy = createStandalonePolicy(effectivePolicy), release = options.measureOnly ? Object.assign(() => {}, { verify: () => {} }) : registerReaderLease(base, options.nativeSession ? { signature: options.nativeSession.signature, busyTimeoutMs: 0 } : undefined);
105
107
  closers.push(release);
106
108
  const selection = readSelector(base).revision;
107
109
  const sharded = !!lstatSync(join(base, "shards.json"), { throwIfNoEntry: false });
@@ -276,6 +278,37 @@ export async function sessionStartBrief(options: BriefOptions): Promise<BriefRes
276
278
  const measured = options.measureOnly;
277
279
  if (measured && !measured.workBase) { coverage.work = "unavailable"; return; }
278
280
  if (measured && ![project, ...aliases].some(key => lstatSync(join(shardDir(measured.workBase!, key), "work", "log"), { throwIfNoEntry: false }))) return; // no work log: the real brief shows an empty list
281
+ // #455: the native brief reads the derived machine-local snapshot only; a stale, foreign or unreadable file is
282
+ // unavailable with today's instruction, never older content. Every kept row is screened again at read.
283
+ if (options.nativeSession && !measured && !effectivePolicy.host) {
284
+ let floor: string | undefined;
285
+ try { assertFormatFloor(base, "work-lists"); }
286
+ catch (error) { floor = error instanceof FormatFloorError && error.code === "format_floor" ? "floor: upgrade amem" : "floor: amem doctor"; }
287
+ if (floor) { coverage.work = "unavailable"; reasons.work = `${floor}; use amem_work_state_read`; return; }
288
+ let machine: string | undefined;
289
+ try { machine = JSON.parse(readFileSync(join(base, "machine.json"), "utf8")).id; } catch { /* no machine, no snapshot */ }
290
+ const effective = effectivePolicy;
291
+ const revision = workPolicyRevision(effective), homeRevision = workPolicyRevision(configuredPolicyOptions(base));
292
+ const segments = workLogSegments(base, project, aliases);
293
+ const snapshot = typeof machine === "string" && /^[a-f0-9]{16}$/.test(machine) && segments ? readWorkBrief({ base, project, machine, ...(revision !== homeRevision ? { revision } : {}) }) : undefined;
294
+ if (!snapshot) { coverage.work = "unavailable"; reasons.work = "work cache missing; use amem_work_state_read"; return; }
295
+ if (!segments || JSON.stringify(snapshot.segments) !== JSON.stringify(segments)
296
+ || snapshot.policy !== revision) {
297
+ coverage.work = "unavailable"; reasons.work = "work cache stale; use amem_work_state_read"; return;
298
+ }
299
+ if (revision !== homeRevision && snapshot.truncated) {
300
+ coverage.work = "unavailable"; reasons.work = "work cache stale (incomplete); use amem_work_state_read"; return;
301
+ }
302
+ let shown = 0;
303
+ for (const row of snapshot.rows) {
304
+ const view = row.source;
305
+ if (view.closed || !await screen(view)) continue;
306
+ if (shown++ >= SECTION_RECORDS) { coverage.work = "partial"; break; }
307
+ await add("work", workDisplay(view), false);
308
+ }
309
+ if (snapshot.truncated) coverage.work = "partial";
310
+ return;
311
+ }
279
312
  const work = new WorkListStore({ base: measured?.workBase ?? base, project, aliases, policy: screen, ...(options.nativeSession ? { busyTimeoutMs: 0, timeRemaining: options.timeRemaining } : {}) }); closers.push(() => work.close());
280
313
  // Complete operation rows AND the composed view are screened before closed-item filtering or display caps.
281
314
  const views = await work.read(undefined, true); guard();