@staix/agent-mem 0.32.0 → 0.33.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.
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agent-mem",
3
- "version": "0.32.0",
3
+ "version": "0.33.0",
4
4
  "description": "Bounded project memory tools and seven deterministic capture hooks, without a resident worker.",
5
5
  "mcpServers": {
6
6
  "agent-mem": {
package/README.md CHANGED
@@ -3,7 +3,7 @@
3
3
  Curated memory with append-only JSONL logs, a derived SQLite index, short- and long-term tiers, a typed graph, goals with leases, and git sync between machines. Extracted from [agent-hub](https://github.com/STAIxBWLB/agent-hub), with compatible storage and entry IDs.
4
4
 
5
5
  <!-- facts:version -->
6
- Version: 0.32.0. Requires Bun 1.4.2 or later; no runtime dependencies.
6
+ Version: 0.33.0. Requires Bun 1.4.2 or later; no runtime dependencies.
7
7
  <!-- /facts:version -->
8
8
 
9
9
  ## Quick start
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@staix/agent-mem",
3
- "version": "0.32.0",
3
+ "version": "0.33.0",
4
4
  "description": "Curated, shared memory for coding agents: append-only logs, a derived index, tiers and a typed graph.",
5
5
  "license": "MIT",
6
6
  "type": "module",
package/src/index.ts CHANGED
@@ -1,3 +1,4 @@
1
+ export { HOST_API_VERSION, HOST_API_MIN } from "./memory/platform.ts";
1
2
  export * from "./memory/store.ts";
2
3
  // #431 / agent-hub#1522: hosts that run amem on an agent's behalf attribute its writes to that agent.
3
4
  export { withCliAttribution, cliAttribution, noteDisplayActor, type CliAttribution } from "./memory/cli-attribution.ts";
@@ -1,3 +1,4 @@
1
+ import { RECAP_SCRATCH } from "./recap-scratch.ts";
1
2
  import { existsSync } from "node:fs";
2
3
  import { join } from "node:path";
3
4
  import { MemoryStore, machineId, openShardStore } from "./store.ts";
@@ -8,15 +9,16 @@ import { aliasedKeys, readShardedSelection, resolveAlias, shardDir, shardKeyHash
8
9
  * an unsplit home has one shared store (the project filter selects), a split home has one shard per project. A split home's
9
10
  * capture-only shard (no `generation.json` yet) has no curated store, and the answer is `undefined`, never an empty one made on the spot.
10
11
  */
11
- export function openCuratedForRead(base: string, key: string): MemoryStore | undefined {
12
+ export function openCuratedForRead(base: string, key: string, scratch?: typeof RECAP_SCRATCH): MemoryStore | undefined {
13
+ const internal = scratch === RECAP_SCRATCH ? { [RECAP_SCRATCH]: true as const } : {};
12
14
  const aliases = aliasedKeys(base, key), reconcile = aliases.length ? { canonical: key, aliases } : undefined;
13
15
  if (existsSync(join(base, "shards.json"))) {
14
16
  readShardedSelection(base);
15
17
  if (!existsSync(join(shardDir(base, key), "generation.json"))) return undefined;
16
- return openShardStore({ memoryDir: base, project: key, deferPromotions: true, lifecycle: "ignore", ...(reconcile ? { reconcile } : {}) });
18
+ return openShardStore({ ...internal, memoryDir: base, project: key, deferPromotions: true, lifecycle: "ignore", ...(reconcile ? { reconcile } : {}) });
17
19
  }
18
20
  if (!existsSync(join(base, "log")) && !existsSync(join(base, "local")) && !existsSync(join(base, "generations"))) return undefined;
19
- return new MemoryStore({ memoryDir: base, deferPromotions: true, ...(reconcile ? { reconcile } : {}) });
21
+ return new MemoryStore({ ...internal, memoryDir: base, deferPromotions: true, ...(reconcile ? { reconcile } : {}) });
20
22
  }
21
23
 
22
24
  /** The canonical key of `key`, refused unless a shard of it exists. */
@@ -7,9 +7,11 @@ import { basename, join } from "node:path";
7
7
  import { Database } from "bun:sqlite";
8
8
  import { sessionStartBrief, type BriefOptions } from "../session-brief.ts";
9
9
  import { openCuratedForRead } from "./curated-read.ts";
10
+ import { RECAP_SCRATCH } from "./recap-scratch.ts";
10
11
  import { pendingSummary } from "./candidate-pending.ts";
11
12
  import { inspectNativeRoot, nativeRoots, type NativeRootKind } from "./native-roots.ts";
12
13
  import { readCaptureDrops } from "./metrics.ts";
14
+ import { isRecapTelemetry } from "./recap-telemetry.ts";
13
15
  import { walkShards } from "./catalog.ts";
14
16
  import { loadAmemConfig, repoConfigRoot } from "./config.ts";
15
17
  import { readSelector } from "./generation.ts";
@@ -153,11 +155,11 @@ function copyTree(from: string, to: string, budget: CopyBudget, skipNames: Reado
153
155
  }
154
156
 
155
157
  /** The curated side of the home, without any database: the logs of this project (and its aliases), and the small files that bind them. */
156
- function copyCurated(options: Pick<DoctorOptions, "home" | "project" | "aliases">, layout: Layout, scratch: string, budget: CopyBudget): void {
158
+ function copyCurated(options: Pick<DoctorOptions, "home" | "project" | "aliases">, layout: Layout, scratch: string, budget: CopyBudget, recap = false): void {
157
159
  const home = options.home;
158
- observeDirectory(home, budget, name => !SKIP.test(name) && regularFile(join(home, name)));
160
+ observeDirectory(home, budget, name => !SKIP.test(name) && !(recap && isRecapTelemetry(name)) && regularFile(join(home, name)));
159
161
  for (const name of readdirSync(home)) { // top-level plain files: machine.json, shards.json, profile.json, aliases.jsonl, lifecycle.jsonl, the configuration
160
- if (SKIP.test(name) || !regularFile(join(home, name))) continue;
162
+ if (SKIP.test(name) || recap && isRecapTelemetry(name) || !regularFile(join(home, name))) continue;
161
163
  observedCopy(join(home, name), join(scratch, name), budget);
162
164
  }
163
165
  const selected = readSelector(home).selector;
@@ -218,8 +220,8 @@ export async function withBriefSnapshot<T>(home: string, project: string, read:
218
220
  const options = { home, project, aliases }, workBase = join(scratch, "work-base"); mkdirSync(workBase, { mode: 0o700 });
219
221
  copyWork(options, workBase, budget);
220
222
  if (curatedPresent(home, project, layout)) {
221
- const copy = join(scratch, "home"); copyCurated(options, layout, copy, budget);
222
- curated = openCuratedForRead(copy, project);
223
+ const copy = join(scratch, "home"); copyCurated(options, layout, copy, budget, true);
224
+ curated = openCuratedForRead(copy, project, RECAP_SCRATCH);
223
225
  if (!curated) throw Error("recap curated snapshot unavailable");
224
226
  }
225
227
  check(budget);
@@ -1,3 +1,6 @@
1
+ /** Current host-library API and the oldest host API this implementation supports. */
2
+ export const HOST_API_VERSION = 1 as const;
3
+ export const HOST_API_MIN = 1 as const;
1
4
  // Single-source platform helpers. Hub, local and Pi modules re-export these functions unchanged.
2
5
  import { lstatSync, realpathSync } from "node:fs";
3
6
  import { basename, dirname, join, resolve, sep } from "node:path";
@@ -14,6 +14,10 @@ export interface PublicPruneViewV1 {
14
14
  const unavailable = (): never => { throw new Error("public prune view unavailable"); };
15
15
  function guard(ok: unknown): asserts ok { if (!ok) unavailable(); }
16
16
  function protectedCall<T>(work: () => T): T { try { return work(); } catch { return unavailable(); } }
17
+ /** #225/#302: a stat of an inode whose last link is already gone reports nlink 0, not ENOENT. On a path that is the
18
+ * same normal disappearance as an absent one: treat the path as gone and keep waiting or re-read. Any other count,
19
+ * owner or mode still refuses, and a zero-link profile.json still ends as unavailable. */
20
+ const gone = (stat: Stats | undefined): Stats | undefined => (stat && stat.nlink === 0 ? undefined : stat);
17
21
  const object = (value: unknown): value is Record<string, unknown> => !!value && typeof value === "object" && !Array.isArray(value)
18
22
  && (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null);
19
23
  const hex = (value: unknown, size: number): value is string => typeof value === "string" && value.length === size && /^[a-f0-9]+$/.test(value);
@@ -52,9 +56,10 @@ export function waitForPublicPruneWriter(home: string, absoluteDeadline?: number
52
56
  // #225: a cooperating writer that finishes unlinks its intent, then its lock. If that lands between this reader's
53
57
  // open and fstat, the fd's link count is 0. Only that is the normal disappearance (ENOENT): bytes read through the fd
54
58
  // are discarded and the bounded loop re-resolves the path from scratch. Any other link count still refuses.
59
+ // #302: the same count seen by a path lstat here is `gone`, which yields the same ENOENT-or-absent behavior.
55
60
  const unlinked = (stat: Stats): void => { if (stat.nlink === 0) throw Object.assign(new Error("publication unlinked while open"), { code: "ENOENT" }); };
56
61
  const small = (file: string, limit: number): Record<string, unknown> => {
57
- const before = lstatSync(file); privateStat(before); guard(before.size > 0 && before.size <= limit);
62
+ const before = lstatSync(file); unlinked(before); privateStat(before); guard(before.size > 0 && before.size <= limit);
58
63
  const fd = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW);
59
64
  try {
60
65
  const opened = fstatSync(fd); unlinked(opened); privateStat(opened); guard(opened.size > 0 && opened.size <= limit);
@@ -70,7 +75,7 @@ export function waitForPublicPruneWriter(home: string, absoluteDeadline?: number
70
75
  if (profile.schema !== "agent-mem.profile/v2") return; // v1 admission/intent behavior is unchanged.
71
76
  for (;;) {
72
77
  try {
73
- const intent = lstatSync(intentFile, { throwIfNoEntry: false }), lock = lstatSync(lockFile, { throwIfNoEntry: false });
78
+ const intent = gone(lstatSync(intentFile, { throwIfNoEntry: false })), lock = gone(lstatSync(lockFile, { throwIfNoEntry: false }));
74
79
  if (!intent && !lock) return;
75
80
  if (lock) {
76
81
  privateStat(lock);
@@ -99,7 +104,7 @@ export function waitForPublicPruneWriter(home: string, absoluteDeadline?: number
99
104
  }
100
105
  /** Any unresolved intent blocks reads. Never remove it, including malformed bytes. */
101
106
  export function assertNoPublicPruneIntent(home: string, absoluteDeadline?: number): void {
102
- protectedCall(() => { waitForPublicPruneWriter(home, absoluteDeadline); guard(!lstatSync(join(home, PUBLIC_PRUNE_INTENT), { throwIfNoEntry: false })); });
107
+ protectedCall(() => { waitForPublicPruneWriter(home, absoluteDeadline); guard(!gone(lstatSync(join(home, PUBLIC_PRUNE_INTENT), { throwIfNoEntry: false }))); });
103
108
  }
104
109
  function privateStat(stat: Stats, directory = false): void {
105
110
  guard(!stat.isSymbolicLink() && (directory ? stat.isDirectory() : stat.isFile() && stat.nlink === 1));
@@ -0,0 +1,2 @@
1
+ /** Internal marker for disposable, verified Recap scratch stores; not exported by the package entry point. */
2
+ export const RECAP_SCRATCH = Symbol("recap scratch without search");
@@ -0,0 +1,5 @@
1
+ /** Observation journals are not inputs to Recap or its reusable panel projections. */
2
+ export function isRecapTelemetry(name: string): boolean {
3
+ return name === "metrics.jsonl" || name === "record-variants.jsonl"
4
+ || /^record-variants\.jsonl\.tmp-[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(name);
5
+ }
@@ -87,7 +87,7 @@ export class SearchIndex {
87
87
  db.run("CREATE VIRTUAL TABLE IF NOT EXISTS docs USING fts5(body, ref UNINDEXED, project UNINDEXED, tier UNINDEXED, at UNINDEXED, scope UNINDEXED)");
88
88
  // FTS5 has no unique constraint: refs remembers what is indexed, so a repeated or rebuilt row is never doubled.
89
89
  db.run("CREATE TABLE IF NOT EXISTS refs (ref TEXT PRIMARY KEY)");
90
- try { chmodSync(file, 0o600); } catch { /* best effort */ }
90
+ if (file !== ":memory:") try { chmodSync(file, 0o600); } catch { /* best effort */ }
91
91
  this.db = db;
92
92
  this.available = true;
93
93
  } catch { this.available = false; }
@@ -1,3 +1,4 @@
1
+ import { RECAP_SCRATCH } from "./recap-scratch.ts";
1
2
  import { buildCuratedBriefCache, buildPreferenceBriefCache } from "../brief-curated.ts";
2
3
  import { PREFERENCE_SLOT } from "./preference-brief.ts";
3
4
  import { curatedProfileBinding, invalidateCuratedCaches } from "./curated-cache-state.ts";
@@ -250,8 +251,10 @@ export class MemoryStore {
250
251
  private readonly reconcile?: { canonical: string; aliases: readonly string[] };
251
252
  /** A full rebuild refills FTS in one resync instead of one derived transaction per entry. */
252
253
  private rebuildingSearch = false;
254
+ private readonly recapScratch: boolean;
253
255
 
254
256
  constructor(opts: StoreOptions = {}, bootstrap?: BootstrapBinding) {
257
+ this.recapScratch = (opts as StoreOptions & { [RECAP_SCRATCH]?: true })[RECAP_SCRATCH] === true;
255
258
  if (bootstrap && bootstrap.token !== MIGRATION_BOOTSTRAP) throw new Error("invalid migration bootstrap");
256
259
  this.bootstrapOnly = bootstrap ? bootstrap.authoring !== true : false;
257
260
  this.userOverlay = bootstrap?.userOverlay;
@@ -309,7 +312,7 @@ export class MemoryStore {
309
312
  this.db = db;
310
313
  this.mutationDb = openedMutation = mutationDatabase(this.dir);
311
314
  // One derived FTS copy per profile: a generation handle and a shared-v1 handle on one home never resync-fight.
312
- this.searchIndex = openedSearch = new SearchIndex(this.profile.sharded ? join(this.dir, "search.db") : join(home, this.profile.kind === "generation" ? `search-${this.profile.generation}.db` : "search.db"));
315
+ this.searchIndex = openedSearch = new SearchIndex(this.recapScratch ? ":memory:" : this.profile.sharded ? join(this.dir, "search.db") : join(home, this.profile.kind === "generation" ? `search-${this.profile.generation}.db` : "search.db"));
313
316
  this.memoryBaseDir = home;
314
317
  try { chmodSync(indexFile, 0o600); } catch { /* best effort */ }
315
318
  if (this.profile.kind === "generation") this.generationIndex = new GenerationIndex({ profile: this.profile, db, now: this.now,
@@ -1054,7 +1057,7 @@ export class MemoryStore {
1054
1057
  // The FTS copy follows the committed row. `changes` is only a hint here (bun:sqlite misreports it for ignored
1055
1058
  // inserts inside a transaction): addCurated is idempotent by entry id, and a missed hint becomes a count drift
1056
1059
  // the next search resyncs.
1057
- if (inserted && !this.rebuildingSearch) this.searchIndex.addCurated({ id, at: e.at, project: e.project, tier: e.tier === "long" ? "long" : "short", scope: e.scope === "shared" ? "shared" : "project", body: `${e.title ?? ""}\n${e.text}\n${e.about.map(String).join(" ")}` });
1060
+ if (inserted && !this.rebuildingSearch && !this.recapScratch) this.searchIndex.addCurated({ id, at: e.at, project: e.project, tier: e.tier === "long" ? "long" : "short", scope: e.scope === "shared" ? "shared" : "project", body: `${e.title ?? ""}\n${e.text}\n${e.about.map(String).join(" ")}` });
1058
1061
  for (const node of e.about) this.db.query("INSERT OR IGNORE INTO edges (src, dst) VALUES (?, ?)").run(id, String(node));
1059
1062
  } else if (e.op === "goal") {
1060
1063
  if (!str(e.title, 400) || !Array.isArray(e.milestones) || !Array.isArray(e.dependsOn) || !str(e.project, 400) || !opt(e.actor) || !opt(e.scope)) { this.log(`memory segment ${segment}: a malformed entry was skipped`); return; }
@@ -1295,6 +1298,7 @@ export class MemoryStore {
1295
1298
 
1296
1299
  /** Entries visible from `project` (its own, and `shared` ones of any project), newest first, filtered. */
1297
1300
  list(f: Filter = {}): View[] {
1301
+ if (this.recapScratch && f.q !== undefined) throw new Error("search unavailable for a Recap scratch store; open a normal store to search");
1298
1302
  const q = f.q?.toLowerCase().split(/\s+/).filter(Boolean) ?? [];
1299
1303
  return this.live(f).filter((v) => (!f.project || this.inScope(v.project, f.project) || v.scope === "shared") && (!f.tier || v.tier === f.tier) && (!f.kind || v.kind === f.kind)
1300
1304
  && (!f.peer || v.peer === f.peer) && (!f.machine || v.machine === f.machine) && (!f.since || Date.parse(v.at) >= Date.parse(f.since)) && (f.includeSuperseded || !v.supersededBy)
@@ -1352,6 +1356,7 @@ export class MemoryStore {
1352
1356
 
1353
1357
  /** Exact-project body pages for policy-aware callers. Relations still fold over complete metadata. */
1354
1358
  readPage(window: ReadWindow & { query?: string; includeSuperseded?: boolean }): { rows: View[]; next?: ReadRef } {
1359
+ if (this.recapScratch && window.query !== undefined) throw new Error("search unavailable for a Recap scratch store; open a normal store to search");
1355
1360
  this.ensureFresh(); this.prune();
1356
1361
  const refs: ReadRef[] = [];
1357
1362
  for (const store of this.readStores()) {
@@ -1378,6 +1383,7 @@ export class MemoryStore {
1378
1383
  * R3 cost of the fallback is the pre-#13 behavior: same scan, same memory).
1379
1384
  */
1380
1385
  search(q: string, f: SearchFilter = {}): SearchResult {
1386
+ if (this.recapScratch) throw new Error("search unavailable for a Recap scratch store; open a normal store to search");
1381
1387
  const limit = f.limit ?? 200;
1382
1388
  if (!this.searchIndex.available) {
1383
1389
  const listed = this.list({ ...f, q, limit: f.groupTasks === false ? f.limit : Number.MAX_SAFE_INTEGER });
@@ -1473,6 +1479,7 @@ export class MemoryStore {
1473
1479
 
1474
1480
  /** Bring the derived FTS copy level with the curated rows when a prune, a crash, a lock or a rebuild drifted them apart. */
1475
1481
  private syncSearchIndex(): void {
1482
+ if (this.recapScratch) return; // This disposable store never exposes its unpopulated search index.
1476
1483
  if (!this.searchIndex.available) return;
1477
1484
  const curated = (this.db.query("SELECT COUNT(*) AS n FROM entries").get() as { n: number }).n;
1478
1485
  if (!this.searchIndex.needsResync(curated)) return;
@@ -4,6 +4,7 @@ import { join } from "node:path";
4
4
  import { pendingSummary } from "../memory/candidate-pending.ts";
5
5
  import { realPath } from "../memory/platform.ts";
6
6
  import { inboxPolicyVersion } from "./inbox.ts";
7
+ import { isRecapTelemetry } from "../memory/recap-telemetry.ts";
7
8
 
8
9
  type Scope = "home" | "realm" | "projects" | "generations" | "machines" | "machine" | "work" | "logs" | "evidence";
9
10
  type Source = Scope | "file";
@@ -16,6 +17,7 @@ const databases = /^(?:capture|candidates)\.db(?:-wal|-journal)?$/;
16
17
  const derived = /^(?:index(?:-[a-z0-9]+)*|search(?:-[a-f0-9]+)?|catalog|mutation-lock|reader-admission)\.db(?:-(?:wal|shm|journal))?$/;
17
18
 
18
19
  function source(scope: Scope, name: string): Source | undefined {
20
+ if (scope === "home" && isRecapTelemetry(name)) return;
19
21
  if (name === ".git" || name === "node_modules" || name === "reader-leases" || name === "leases" || name === "readers" || name === "shard-readers"
20
22
  || name.endsWith("-shm") || derived.test(name) || /^brief-(?:capture|curated)\.json$/.test(name)) return;
21
23
  if (scope === "logs") return name.endsWith(".jsonl") ? "file" : undefined;