@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.
Files changed (58) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/README.md +28 -12
  3. package/package.json +1 -1
  4. package/src/brief-cache.ts +60 -0
  5. package/src/brief-capture.ts +82 -0
  6. package/src/brief-curated-native.ts +52 -0
  7. package/src/brief-curated.ts +118 -0
  8. package/src/cli.ts +8 -2
  9. package/src/curated-brief-cache.ts +29 -0
  10. package/src/hook-contract.ts +22 -2
  11. package/src/hook-jcode-journal.ts +46 -4
  12. package/src/hook-record.ts +40 -2
  13. package/src/hook-spool-replay.ts +8 -1
  14. package/src/hook-spool.ts +25 -14
  15. package/src/hook-transcript.ts +10 -2
  16. package/src/hooks.ts +68 -17
  17. package/src/index.ts +6 -1
  18. package/src/ingest-records.ts +113 -0
  19. package/src/ingest.ts +106 -9
  20. package/src/mcp-memory.ts +2 -2
  21. package/src/mcp.ts +1 -1
  22. package/src/memory/candidate-pending.ts +6 -2
  23. package/src/memory/candidates.ts +60 -7
  24. package/src/memory/capture-input.ts +7 -0
  25. package/src/memory/capture-plan.ts +10 -0
  26. package/src/memory/capture.ts +98 -8
  27. package/src/memory/consolidate.ts +35 -1
  28. package/src/memory/curated-cache-state.ts +36 -0
  29. package/src/memory/decay-review.ts +3 -1
  30. package/src/memory/formats.ts +20 -0
  31. package/src/memory/generation-index.ts +2 -0
  32. package/src/memory/generation-sync.ts +3 -0
  33. package/src/memory/index-file.ts +1 -1
  34. package/src/memory/intent-brief.ts +42 -4
  35. package/src/memory/metrics.ts +10 -4
  36. package/src/memory/migrate.ts +7 -1
  37. package/src/memory/note-add.ts +2 -0
  38. package/src/memory/ops-contract.ts +1 -1
  39. package/src/memory/preference-brief.ts +22 -0
  40. package/src/memory/public-prune-activation.ts +4 -1
  41. package/src/memory/public-prune-advance.ts +2 -0
  42. package/src/memory/reader-lease.ts +5 -3
  43. package/src/memory/recall.ts +4 -1
  44. package/src/memory/record-candidates.ts +179 -0
  45. package/src/memory/record-instruction.ts +26 -0
  46. package/src/memory/record-variant-log.ts +90 -0
  47. package/src/memory/search-fts.ts +3 -0
  48. package/src/memory/shard-migration.ts +4 -1
  49. package/src/memory/shard-sync.ts +3 -0
  50. package/src/memory/store.ts +184 -4
  51. package/src/memory/sync-placement-activation.ts +11 -3
  52. package/src/memory/sync-placement-transport.ts +3 -0
  53. package/src/memory/sync.ts +3 -2
  54. package/src/session-brief-worker.ts +13 -2
  55. package/src/session-brief.ts +150 -70
  56. package/src/ui/plugin.ts +104 -30
  57. package/src/ui/snapshot-cache.ts +141 -0
  58. package/src/ui/snapshot-revision.ts +87 -0
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agent-mem",
3
- "version": "0.23.1",
3
+ "version": "0.25.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.23.1. Requires Bun 1.4.2 or later; no runtime dependencies.
6
+ Version: 0.25.0. Requires Bun 1.4.2 or later; no runtime dependencies.
7
7
  <!-- /facts:version -->
8
8
 
9
9
  ## Quick start
@@ -112,7 +112,7 @@ The machine-local file `amem.config.json` in the memory home (see `amem status`
112
112
  ```
113
113
 
114
114
  - `denyPaths`: substrings of a path that are never captured and that decline any note, candidate or MCP answer naming them. `piiPatterns`: case-insensitive literal substrings (never regular expressions) that decline a value and redact a capture excerpt. Each list holds up to 64 entries of up to 256 bytes.
115
- - `records`: optional boolean, enabled by default. `false` disables the static native SessionStart instruction and new Claude `Record` extraction; a repository may disable it but cannot re-enable a machine opt-out. See [assistant records](#assistant-records-313).
115
+ - `records`: optional boolean, enabled by default. `false` disables the static native SessionStart instruction and new Claude, Codex, Pi and Kimi `Record` extraction; a repository may disable it but cannot re-enable a machine opt-out. See [assistant records](#assistant-records-313).
116
116
  - `briefBytes`, `excerptBytes`, `capturePaths` can only lower the built-in ceilings (the 1200-byte SessionStart context, 2000-character capture excerpt, 32 captured paths). `capture.capMb` and `capture.retentionDays` are the lowest layer of the capture size and retention bounds: a shard's own `config.json` and the home's `capture-config.json` still override them.
117
117
  - A file with an unknown key, a bad value, a link, or more than 64 KiB is an error that names the file. An unreadable policy is never treated as no policy.
118
118
  - `<private>...</private>` spans are dropped before anything else reads the text, at every write boundary (capture, MCP candidates and work lists, notes, goals, promotion and import), so they are never screened, counted or stored. Tags match like HTML (case-insensitive, with attributes or spaces, and `<private/>` opens a span); an unclosed span drops the rest of the text.
@@ -127,7 +127,7 @@ If the screen misses a secret or personal data, `amem forget <id>` hides the ent
127
127
 
128
128
  ## Writing notes and reviewing candidates
129
129
 
130
- `amem note add [--kind decision|finding|contract|fail] [--tier short|long] [--scope project|shared] [--title T] [text... | -]` writes one curated note with CLI peer attribution (agent-mem#40 F6). The text is the arguments, `-` to read stdin through end of input, or nothing to open `$VISUAL` (an empty one is skipped) or `$EDITOR` on a private temporary file when a terminal is available (the command is run without a shell: an existing path with spaces works as is, otherwise quotes and backslashes split it, and Ctrl-C reaches the editor while it runs). A `fail` note takes its five fields instead of free text: `--approach`, `--symptom`, `--cause`, `--evidence` (repeatable) and `--retry-when`. All five are required, and the command names the ones that are missing; with none given it opens a labelled template in the editor. The configured policy screens the title and text before anything is written, and a refusal never echoes them.
130
+ `amem note add [--kind decision|finding|contract|fail|preference] [--tier short|long] [--scope project|shared] [--title T] [text... | -]` writes one curated note with CLI peer attribution (agent-mem#40 F6). The text is the arguments, `-` to read stdin through end of input, or nothing to open `$VISUAL` (an empty one is skipped) or `$EDITOR` on a private temporary file when a terminal is available (the command is run without a shell: an existing path with spaces works as is, otherwise quotes and backslashes split it, and Ctrl-C reaches the editor while it runs). A `fail` note takes its five fields instead of free text: `--approach`, `--symptom`, `--cause`, `--evidence` (repeatable) and `--retry-when`. All five are required, and the command names the ones that are missing; with none given it opens a labelled template in the editor. A `preference` is a standing instruction such as "always answer in Korean": it is long-term, shown by its own slot in both briefs (up to five current ones, project plus shared, newest first, whole lines only), and refused until the memory home's `formats.json` records a `curated` or `home` floor of at least `0.25.0`, because a release older than that drops the row and then refuses its whole sync publish over it (agent-mem#370). The configured policy screens the title and text before anything is written, and a refusal never echoes them.
131
131
 
132
132
  The SessionStart brief carries one line when candidates wait, for example `2 candidates pending, oldest expires in 27 days` (agent-mem#40 F7). It holds numbers only, is read-only (the hook never marks anything shown), comes out of the brief's own byte budget, and is left out when it does not fit. `amem status --json` adds a `candidates` object (bare `amem status` shows the same as a labelled row and next action) (or `unavailable` when `candidates.db` exists but cannot be read, never a false zero) and a warning when any is within 7 days of expiry. `amem review walk` needs a terminal on both stdin and stdout (it refuses when stdout is redirected to a file or a pipe, because nobody would see what it asks about). It prints each pending candidate, oldest first, and only then asks accept, edit, reject, skip or quit: accept goes through the normal policy, edit opens the text in your editor and writes it as a note under the current CLI actor (a candidate proposed as a fail note opens the labelled template), and what it prints has control characters removed. Nothing expires unseen: a candidate counts as shown only when `review walk` has printed it (the plain `review list` prints no content and runs in scripts, and the brief line cannot know you read it, so neither marks anything). A candidate is kept past its 30 days until it has been shown, and then for 7 more days. When 500 unseen candidates wait, a new one is refused with a named error (an MCP tool returns a fixed queue-full response) instead of dropping an unseen one.
133
133
 
@@ -237,7 +237,7 @@ These interactive checks remain unrun until a person checks them in each install
237
237
 
238
238
  `memoryHome()` selects `AMEM_HOME` first; then the `home` of a pointer file `amem.config.json` in the default home (a file with `home` carries nothing else, and a redirected home's own file cannot redirect again); then `$AGENTHUB_HOME/memory`, otherwise `~/.agenthub/memory`. `amem status` prints the home in use, which of these chose it, and the configuration files in effect. `AMEM_HOME` names the memory directory itself; `AGENTHUB_HOME` names its parent. Existing agent-hub memory directories need no migration. An explicit `StoreOptions.home` retains the parent-directory convention and appends `/memory`.
239
239
 
240
- The JSONL segments are authoritative. `index.db` is derived and can be rebuilt. Entries are immutable; changes append operations. The compatibility schema remains `agent-hub.memory/v1` because it participates in entry IDs.
240
+ The JSONL segments are authoritative. The curated index (`index-v4.db`; 0.14.0 through 0.24.0 use `index.db`) is derived and can be rebuilt. Entries are immutable; changes append operations. The compatibility schema remains `agent-hub.memory/v1` because it participates in entry IDs.
241
241
 
242
242
  ## Capture tier and full-text search
243
243
 
@@ -249,7 +249,7 @@ Selected-project `store.search` and `amem_search` first reserve the existing unw
249
249
 
250
250
  Project identity (#15 D2) keeps `memoryProjectKey`: a worktree, a submodule and the main checkout of one repository share its key; two unrelated same-named repositories without a remote get distinct path-hash keys, flagged `local` in the shard's `project.json` and the catalog. A no-remote key hashes the main working root (using the actual top-level for a separate git dir), so keys written from the repository root keep their pre-#15 value. Known limit: a linked worktree of a no-remote separate-git-dir repository gets its own key, because git does not record that repository's main working root (probe: `alpha` and `alpha/sub` share `alpha@<hash>`, `alpha-wt` gets `alpha-wt@<hash>`); the key stays as is for root-key compatibility, and a reviewed alias reconciles its capture. Keys written by older builds from a subdirectory or worktree still used that invocation's cwd hash; an explicitly written alias maps such a key to its canonical one for capture, work lists and the CLI and MCP project binding. Curated rows written under the old key keep their key in the log (nothing is rewritten), and the CLI and MCP read them under the canonical project: the project filter of notes, goals, candidates, vault candidates and work lists covers the canonical key and every key aliased to it, and presents those rows under the canonical key (#27). The library `MemoryStore` still reads by the raw key unless a host passes `reconcile`, and shared rows stay visible as before. Writes still go to the key's own log and shard, and a settle or forget of an aliased row lands in the shard that holds it. `amem alias add <from-key> <to-key>` appends an op to `aliases.jsonl` (latest wins, never chained, never automatic), `amem alias remove <from-key>` appends a removal (the old key reads under itself again, the history stays), `amem alias list` shows the ops including removals. Both append an alias operation without a general TTY gate. An amem or hub older than this change ignores a removal and keeps the old binding until it is upgraded, so upgrade every host that shares the home first. A correction accepted on an aliased row lives under the canonical key, so after a removal the old key shows the superseded note again (see `docs/contracts.md`). `catalog.db` in the memory home (#15 D3's storage part) is derived only from the shards and the alias log and rebuilds to the same rows; the D3 management commands (`amem projects`, `usage`, `gc` and `project`) are #15 T5, described in [Managing the project shards](#managing-the-project-shards-15-t5).
251
251
 
252
- `store.search(query, filter)` searches the curated tier and the current project's capture shard with SQLite FTS5 and BM25 plus tier/recency weighting: natural multi-word queries match partial term sets (the substring filter required every word), and a curated row outranks the same text in the capture tier. Prefix terms match inflections and Korean particles in either direction by retaining the original query term and adding a common-particle-stripped alternative. The FTS copy of the curated rows lives in its own derived `search.db` (`index.db`'s table set is a frozen contract and gains nothing); it is written from the same apply path as the index, and a prune, crash or rebuild is detected and resynced, so the incremental FTS copy equals a full resync. Where FTS5 is unavailable the engine falls back to the substring filter and reports `engine: "substring"`; capture recall needs FTS5 and is skipped in the fallback. The library entry exports `CaptureStore`, `captureSearch`, `readCaptureConfig`, `writeCaptureConfig`, `SearchIndex`, `fts5Available`, the shard helpers (`resolveAlias`, `appendAlias`, `listAliases`, `shardKeyHash`), the catalog (`rebuildCatalog`, `readCatalog`, `scanCatalog`) and the capacity advisor (`capacityReport`).
252
+ `store.search(query, filter)` searches the curated tier and the current project's capture shard with SQLite FTS5 and BM25 plus tier/recency weighting: natural multi-word queries match partial term sets (the substring filter required every word), and a curated row outranks the same text in the capture tier. Prefix terms match inflections and Korean particles in either direction by retaining the original query term and adding a common-particle-stripped alternative. The FTS copy of the curated rows lives in its own derived `search.db` (the curated index's table set is a frozen contract and gains nothing); it is written from the same apply path as the index, and a prune, crash or rebuild is detected and resynced, so the incremental FTS copy equals a full resync. Where FTS5 is unavailable the engine falls back to the substring filter and reports `engine: "substring"`; capture recall needs FTS5 and is skipped in the fallback. The library entry exports `CaptureStore`, `captureSearch`, `readCaptureConfig`, `writeCaptureConfig`, `SearchIndex`, `fts5Available`, the shard helpers (`resolveAlias`, `appendAlias`, `listAliases`, `shardKeyHash`), the catalog (`rebuildCatalog`, `readCatalog`, `scanCatalog`) and the capacity advisor (`capacityReport`).
253
253
 
254
254
  `amem search <words...>` ranks the current project's current curated notes with `store.search` (FTS5/BM25 plus tier and recency weights). Natural multi-word queries can match partial term sets: `amem search lighthouse beacon` can return a note containing only one of those terms. Add `--filter` to retain the previous behavior for current-project curated notes: every query word must appear as a substring, and results are newest first. `--history`, `--as-of` and an empty query retain the previous filter/newest-first path. Repository-scope notes remain a separately screened append to these results. `--all-projects` keeps its existing ranked path and cannot be combined with `--filter`. JSON output retains the existing note fields.
255
255
 
@@ -291,7 +291,7 @@ amem capacity apply --split [--confirm] # each shard's share of the global cap
291
291
 
292
292
  - `archive`, `unarchive` and `forget` are append-only ops in `lifecycle.jsonl` of the memory home (local, never synced, like `aliases.jsonl`): nothing rewrites a line and nothing deletes a shard. The latest op wins and `forgotten` is terminal. An alias resolves to its one canonical project, and the reply names it. An archived or forgotten project has no writable capture store, no SessionStart brief and no MCP server; `unarchive` restores an archived one. A forgotten project's bytes stay on disk: `forget` is an append-only lifecycle record, not an erase. An alias shard of an archived or forgotten project counts as that state, `alias add` to or from a forgotten key is refused, and hooks that staged capture for a project before it was archived or forgotten are retired at the next drain (counted as `project_archived` or `project_forgotten`). `openShardStore` refuses such a project at the open, so a library caller such as agent-hub is gated too once it pins this release.
293
293
  - `gc` opens only the capture store of each shard and calls its bounded `evict()` (at most four batches of 256 rows and 25 ms per call), so a cap shrink never takes a shard in one pass: the report says `remainingOverCap` and the next run continues. It never opens a curated store, a goal or a work list. An archived shard is still bounded; a forgotten one is skipped and listed as skipped.
294
- - `export` changes no content under the memory home: it opens the capture databases read-only and reads the curated store, and the only files that may appear or refresh are derived (the curated `index.db` and `search.db`, SQLite sidecars and `catalog.db`), which every reader rebuilds from the logs. A destination inside the home is refused. The bundle is screened like sync and promotion are, so a secret-looking value, a PII pattern or a denied path is withheld and counted in `withheld`.
294
+ - `export` changes no content under the memory home: it opens the capture databases read-only and reads the curated store, and the only files that may appear or refresh are derived (the curated `index-v4.db` and `search.db`, SQLite sidecars and `catalog.db`), which every reader rebuilds from the logs. A destination inside the home is refused. The bundle is screened like sync and promotion are, so a secret-looking value, a PII pattern or a denied path is withheld and counted in `withheld`.
295
295
  - `search --all-projects` runs one ordinary project-scoped search per active project and merges by score. It is a person command: the MCP server stays bound to one project and has no all-projects argument, and the raw memory command (what a host exposes as its own `memory` command) refuses the flag.
296
296
  - `capacity` also prints a per-shard split of the global disk-share budget. Each shard's weight halves every 14 days since its last capture, so recently used projects keep more capture and cold ones shrink first; the split never exceeds the budget, gives every shard at least 1 MB, keeps every shard at what it holds whenever the total fits, never proposes a retention shorter than a shard's idle time plus 30 days, and says when the budget forces a shard below what it holds. When the budget holds fewer whole MB than there are shards, no split is proposed and `capacity` says why (`splitRefused`). It proposes capture bounds only, and never evicts curated notes, goals or work lists. `capacity apply --split` previews, then `--confirm` writes exactly the previewed values to each shard's `config.json`, and only if the preview is under an hour old and the set of shards and every shard's config are unchanged since then (a `--disk-share` given only to `--confirm` changes nothing that is written).
297
297
  - amem lists vault candidates and never writes the vault.
@@ -322,7 +322,7 @@ Known-format pending records whose cwd is positively absent can retire after one
322
322
 
323
323
  If both replayable tiers fill, or SessionStart's reserve alone fills, the current event can be dropped. The library receipt reports `dropped: true`, `dropReason: "spool_full"`, `dropCount: 1`, and the metric reports `captureDrops: 1` with `captureDropReason: "spool_full"`. Non-SessionStart native stdout remains empty. Native SessionStart emits only `hookSpecificOutput`, placing a bounded notice with reason counts from the last 200 metric samples after its untrusted-data header inside `additionalContext`, not in new top-level fields. These are rolling-window counts, not all-time totals. The header stays before all memory data even when the brief is otherwise unavailable; the optional trusted Record instruction precedes it. The combined instruction and context stay within the same byte bound. Finite-capacity and retirement losses are observable rather than reported as captured. Exact-once replay applies to positively bound retained records that can progress; unlimited lossless intake is not promised. Soft-cap overshoot, unpublished `.writing/` leftovers and power-loss durability retain the [contracts ceiling](docs/contracts.md#p3-hook-and-native-intake-boundaries-13).
324
324
 
325
- SessionStart prioritizes known open work and defers unsafe curated refresh with a fixed coverage reason. Native capture reads the newest 128 rows through an existing read-only time index and marks excluded older history partial, instead of rejecting a larger store. It never creates schema/FTS or repairs indexes. Missing/locked/incompatible sources are explicitly unavailable. The standalone `sessionStartBrief()` retains all its original sources. Recovery failure cannot discard a computed brief. Work, reader-lease and capture host ports use zero busy-wait and cooperative deadline checks; ordinary library callers retain their original defaults, including 3,000 ms waits. No watcher, resident worker, model/network call, embedding job or vault access is added. Host policy callbacks remain unsupported by `runHook`, while the standalone brief composes them normally.
325
+ SessionStart prioritizes known open work. Native curated notes use a private prebuilt section prepared after curated writes and sync, with current policy screening before work and whole-line output after work. Admission requires all writers to be upgraded and a person-raised `home` or `curated` floor of 0.24.0 or later; code never changes that floor. Below it, native curated stays deferred. Migration and profile/selector changes invalidate caches without rebuilding; a later curated write or explicit trigger prepares them. Only an unmarked person `amem brief` or an explicit off-hook host call to the root export `prepareCuratedBriefCache(base, project)` prepares a quiet project cache. The export is a write: it opens one selected store, reads at most four 32-row pages and writes one file up to 32 KiB. MCP, agent-marked CLI reads and library `sessionStartBrief()` never prepare it. A project with no curated writes and neither explicit trigger keeps native curated unavailable; mutations rebuild only their touched projects after invalidating old derived files. Missing and stale files report `curated cache missing` or `curated cache stale` without rebuilding. Profile/generation binding, selected-note expiry and a 24-hour age cap bound freshness; see [the curated cache contract](docs/contracts.md#r2-hook-budget-150-mb-ceiling-per-runner-baseline-regression-300-ms-maximum-228). Native capture uses the prebuilt Record/Recap/Compact section; raw chronological history remains a library source. Neither native cache path creates schema/FTS or repairs indexes. Missing/locked/incompatible sources are explicitly unavailable. The standalone `sessionStartBrief()` retains all its original sources. Recovery failure cannot discard a computed brief. Work and reader-lease host ports use zero busy-wait and cooperative deadline checks; ordinary library callers retain their original defaults, including 3,000 ms waits. No watcher, resident worker, model/network call, embedding job or vault access is added. Host policy callbacks remain unsupported by `runHook`, while the standalone brief composes them normally.
326
326
 
327
327
  SessionStart admits directly to the reserve with at most 32 metadata entries and performs no active-tier scan or replay. Both tiers use per-cwd fair shares (64 active records, 8 reserve records), grouping together all HOME/scope variants of a cwd. Admission can retire native records from an overrepresented cwd, counting each loss as `scope_capacity` before removal. Accepted summaries survive same-cwd pressure; new summaries backpressure without advancing their transcript cursor. A fully verified foreign all-summary inventory can use counted `summary_capacity` eviction; otherwise it stays pending for replay. All admission maintenance shares a 32-file/256 KiB body-read bound; unknown/newer schemas retain their seven-day protection. Non-SessionStart hooks maintain and drain both tiers. This is bounded reserve admission, not O(1) accounting; an atomic slot-reservation protocol is the upgrade. Parent brief storage still contains synchronous filesystem/SQLite work between cooperative deadline checks; asynchronous/deadline-aware storage remains the upgrade, not a larger handler limit. The R2 limits remain 150 ms p95, with a 140 ms handler budget; the absolute 100 MB peak RSS was retired by #228 for a 150 MB per-invocation ceiling plus a per-runner baseline regression gate. Functional tests construct a programmatic host-only deadline; the actual executable exposes no environment or CLI deadline extension. Its exec-only boot-clock handoff can only shorten the deadline and is cleared before hook import. Dedicated budget scripts retain the actual CLI, original sample counts, cold attempt 0 and timeout/reaper assertions. The [P3 receipt](docs/p3-hook-budget-2026-10-23.md) identifies prior-head evidence separately from current acceptance; the current rework has no newly claimed both-OS green CI result.
328
328
 
@@ -367,6 +367,10 @@ Qwen Code uses `QWEN_RUNTIME_DIR`, then `QWEN_HOME`, then `~/.qwen`, with bounde
367
367
 
368
368
  A receipt with `reason: "unsupported_version"` and a `version` (for example `0.27.0` for Qwen or `1.6` for Kimi) means the client wrote a native format version this amem does not read (newer or older than the supported ones): nothing from those records is captured. Qwen records are read again once an amem update supports that version, because the Qwen cursor is keyed to its decoder contract. `schema_or_time` still means a malformed or untimed record (#136).
369
369
 
370
+ Record extraction is capture-only and follows the existing cursor forward, without resetting it or backfilling old messages. With `recordsEnabled` true, Codex requires `phase: "final_answer"` and a main-session header; Pi requires `stopReason: "stop"` and an ordinary root session; Kimi 1.5 requires a matched main-agent `step.end` whose `finishReason` is the native `end_turn`. Tool output, reasoning and explicit child/subagent sources supply no Records. The canonical parser, privacy/anchor checks, staging receipts and replay are shared with Claude. Either the home or repository `records: false` disables extraction. The additive JSON `records` object reports `supported`, `found`, `staged`, `refused` by reason and `duplicatesSkipped`.
371
+
372
+ Qwen 0.26.1 and Jcode's journal cannot prove finality. They stage no Records and report recognized candidates as refused with `finality-unavailable`; ordinary Qwen capture and Jcode Title/Compact intake are unchanged. Jcode exposes the same unsupported receipt in journal progress and numeric refusal metrics, without adding an `ingest jcode` command, and a Record refusal never appears as a `capture dropped` notice in the SessionStart brief. Kimi completion correlation is bounded to the newly read source window; a missing completion witness is a counted refusal, never a guessed final answer. Prompt instruction delivery to these clients remains the host's responsibility.
373
+
370
374
  Per-source cursor databases and a fair rotation cursor live in the capture shard's private `ingest/` directory. Filenames and source identities are hashes; cursor contents retain offsets, anchor hashes, scope/protocol/cutoff and ownership metadata, not raw transcript paths or text. Capture receipts make replay idempotent across a crash between append and cursor acknowledgement. Repeating the command resumes its bounded tour instead of repeatedly favoring the first files. Broadening `--since` rechecks earlier history while existing capture receipts prevent duplicates. The JSON receipt reports `files`, `read`, `imported`, `skipped`, `spooled`, `remaining`, `errors` and an optional bounded `reason`; unavailable coverage is not silently represented by zero imported rows.
371
375
 
372
376
  The default invocation reads at most 4 MiB and attempts 32 sources; trusted library options can raise those limits to 16 MiB and 128 sources. It examines at most 4,096 records, bounds a record at 256 KiB, and caps discovery at 4,096 directory entries/depth 8. Re-run a receipt with `remaining: true` after inspecting its reason; ingest creates no polling timer or watcher. Oversized records, including an unbroken record longer than the 4 MiB default window, are counted once and discarded through their next newline using a durable byte offset/skip flag. Later valid records remain reachable without retaining oversized content; an unfinished oversized tail stays pending until its newline arrives. The cursor assumes append-only native files and verifies file identity plus the last 1,024 acknowledged bytes. Historical rewrites outside that anchor are a declared ceiling, not full-file verification. These readers do not establish account-backed native interoperability, P5 cutover or P6 live-week acceptance.
@@ -432,13 +436,13 @@ Only explicit serialized expiry is eligible: a note's `expires`, or an exact dem
432
436
 
433
437
  Standalone CLI prune is local-only, even over a synced target. No `--policy-free` escape enables public prune. A later policy-aware host integration must authenticate intent and attest the exact public payload and current policy revision; only verified public target/basis provenance may sync. Local masks, plans, journals, caches and sidecars never sync. Generation sync refuses public or unknown remote visibility. An interrupted apply resumes the same durable row IDs and exact partial tail; it never rewrites complete lines.
434
438
 
435
- Candidate/counter sidecars are not migrated. `amem review list --kind memory` lists the new machine-local memory candidates under a selected generation; the default legacy review list retains its generation refusal. General memory candidates can be accepted with `review accept --kind memory` into the current project store after current standalone screening; older correction/fail candidates still require profile-aware host integration for generation acceptance.
439
+ Candidate/counter sidecars are not migrated. `amem review list` lists machine-local candidates under the selected generation. General memory, correction and fail candidates can be accepted into the selected project store after current standalone screening and applicable target checks.
436
440
 
437
441
  Real migration remains blocked until the separately reviewed generation-capable amem release and exact-pinned agent-hub integration are installed and their running stores prove the same home/G/selector revision. Synthetic cross-writes and exact prune readbacks precede separately confirmed real migration; known local handles must be quiesced/closed and reopened through the supported session-preserving lifecycle. Release, deployment, real migration, host evidence/capture receipts and real multi-machine sync are not established by these source changes. Deactivation omits generation-only notes/prunes from the v1 view and is not a lossless rollback.
438
442
 
439
443
  ## Curated shard migration (#15 T2)
440
444
 
441
- Bare `amem migrate --shards` is a preview; `--apply` writes the migration. `amem migrate --shards --apply` moves the curated single home into `projects/<key-hash>/` and `user/` through a resumable generation journal. The original single-home log bytes are never rewritten. A populated selected generation is supported and keeps its generation ID. Each shard keeps private legacy inputs in read-only `legacy/`, public-main inputs in read-only `legacy-main/`, and generation-born rows in its own `log/` and `local/`. It has its own `index.db`, `search.db` and mutation lock; original IDs, hashes, placement and own/local/public provenance are preserved. The source generation bytes stay unchanged. Immutable prune proofs are validated before effects; a multi-shard prune is translated into one deterministic row per shard, with a receipt naming the original row. Existing capture and `work/` directories are not migration inputs and are left untouched. `catalog.db` remains derived and rebuildable, now including curated entry counts and last use. Split curated stores sync the opened canonical project and user overlay to separate private-remote refs (`amem/p/<key-hash>` and `amem/u`) with `amem sync --policy-free`; unopened projects and machine data are not fetched. Original IDs and attribution survive independent generations. See `docs/contracts.md`, "Per-shard private sync", for prune transport and application boundaries.
445
+ Bare `amem migrate --shards` is a preview; `--apply` writes the migration. `amem migrate --shards --apply` moves the curated single home into `projects/<key-hash>/` and `user/` through a resumable generation journal. The original single-home log bytes are never rewritten. A populated selected generation is supported and keeps its generation ID. Each shard keeps private legacy inputs in read-only `legacy/`, public-main inputs in read-only `legacy-main/`, and generation-born rows in its own `log/` and `local/`. It has its own `index-v4.db`, `search.db` and mutation lock; original IDs, hashes, placement and own/local/public provenance are preserved. The source generation bytes stay unchanged. Immutable prune proofs are validated before effects; a multi-shard prune is translated into one deterministic row per shard, with a receipt naming the original row. Existing capture and `work/` directories are not migration inputs and are left untouched. `catalog.db` remains derived and rebuildable, now including curated entry counts and last use. Split curated stores sync the opened canonical project and user overlay to separate private-remote refs (`amem/p/<key-hash>` and `amem/u`) with `amem sync --policy-free`; unopened projects and machine data are not fetched. Original IDs and attribution survive independent generations. See `docs/contracts.md`, "Per-shard private sync", for prune transport and application boundaries.
442
446
 
443
447
  Before splitting a live home, every installed host must open it through `openShardStore({ project })` or the explicit user shard. Plain `new MemoryStore()` refuses any split marker, including an interrupted split, so it cannot silently keep writing the old layout. No host capability registry currently exists; migration preflight output states that limitation. Do not release T2 for agent-hub use until its memory factory is integrated with `openShardStore` and that host version is installed. Existing unannounced older builds remain the documented unchanged-source ceiling.
444
448
 
@@ -458,7 +462,7 @@ Library callers open an already sealed shard directly with `openShardStore({ hom
458
462
 
459
463
  Dry run reports v1, generation-owned/local, prune and translated-prune counts, plus refused relations. A private-to-private replacement across projects refuses before effects. A shared entry superseded by a private entry also refuses: the dry run reports `shared superseded by private: N` and entry IDs only. Un-supersede it, or promote the replacement to shared, then rerun. `ponytail:` supporting that direction requires a body-free lifecycle witness; revisit when a read-only dry run on a copy of the person's home reports a nonzero count, never by probing or migrating the live home here. Private-to-shared replacements remain supported. See [the T2 contract](docs/curated-shard-migration.md).
460
464
 
461
- After a split, ordinary generation `amem migrate` modes (including `--deactivate`) refuse without changing the selector. Use `amem migrate --shards --resume` to finish the split. General memory candidates can be accepted with `review accept --kind memory` into the selected project shard after standalone screening; correction/fail candidates still refuse pending shard-aware host integration. Default `prune` selects the current project's shard; use `amem prune --user --cutoff <UTC> --dry-run` and `amem prune --user --apply --plan <file>` for shared/user entries. The current project, reader-admission and split-marker checks remain in force.
465
+ After a split, ordinary generation `amem migrate` modes (including `--deactivate`) refuse without changing the selector. Use `amem migrate --shards --resume` to finish the split. General memory, correction and fail candidates can be accepted into the selected project shard after standalone screening and applicable target checks. Default `prune` selects the current project's shard; use `amem prune --user --cutoff <UTC> --dry-run` and `amem prune --user --apply --plan <file>` for shared/user entries. The current project, reader-admission and split-marker checks remain in force.
462
466
 
463
467
  A native shard crash tail is left to its original writer's recovery. Migration checks planned copy tails and translation-receipt tails before changing activation; matching copies finish append-only and mismatches give an inspection hint. Dangling lifecycle/suggestion metadata is carried as ids-only user data and counted, so a target arriving later retains its intent. Cross-private replacements have their own ids-only count and the un-supersede/promote-to-shared remedy. During interruption the catalog keeps capture information available while `curatedEntries` is `null` and `curatedAvailable` is `false`; its cached capture counts may still lag.
464
468
 
@@ -535,13 +539,15 @@ The library exports `buildIntentBrief`, `planGuardNodes`, `matchingPlanFails` an
535
539
 
536
540
  Run `amem consolidate [--project <current-key>]` (another project is refused) to queue deterministic proposals for `amem review`. It compares a bounded project-local window using indexed text overlap, shared paths and current supersession-chain metadata. It does not edit curated notes. The CLI reviews each merge, replacement or recurring-failure summary under the current caller identity, and acceptance rechecks every source revision. A recurring-failure summary preserves its source failures and decisions. Large source quotations are counted as too large instead of silently shortened into a proposed note.
537
541
 
542
+ The same run also proposes curated candidates from the newest 32 capture `Record` rows of the project, so a decision, contract, fix or fail an agent recorded in its final answer reaches review without retyping. Each candidate cites up to eight rows and is grouped by kind and anchors, or by kind and text when the Record carried `-` anchors. A group already queued or already decided is not queued again, and acceptance point-reads the rows the candidate cites, so it still works after newer Records have pushed them out of the window.
543
+
538
544
  The CLI runs the deterministic pass only. A library host may explicitly enable an injected model callback for the person; no provider is built in. It has batch, byte, deadline and persistent daily limits. Model answers remain marked machine-local candidates that cannot be accepted; `amem note add` is the separate path for an independently authored note. A non-answer is never saved.
539
545
 
540
546
  Agents use `amem_evidence` with a question to get cited, live curated entries, not an answer. The complete JSON bundle is byte-capped (`maxBytes`, default 4096, range 256..8192); excerpted entries retain an exact `mem:` reference for fetching the full note. Capture, repository-only rows, pending candidates and model answers are excluded. amem makes no model call for this tool. Rendering a citation in the bundle records only `rendered` after successful output, never `delivered` or `cited`.
541
547
 
542
548
  ### Public prune view and v2 sync (opt-in)
543
549
 
544
- On an active curated split, the person can preview and enable the forward-only v2 reader floor. This keeps the receiving generation and native logs/seals, builds a separate `index-v2.db`, and preserves every native/local mask. Once activated, explicit sync uses the v2 transport and can install complete generation-neutral public-prune proof; historical hold receipts alone never authorize a mask.
550
+ On an active curated split, the person can preview and enable the forward-only v2 reader floor. This keeps the receiving generation and native logs/seals, builds a separate `index-v2-i4.db`, and preserves every native/local mask. Once activated, explicit sync uses the v2 transport and can install complete generation-neutral public-prune proof; historical hold receipts alone never authorize a mask.
545
551
 
546
552
  ```sh
547
553
  AMEM_HOME=/path/to/synthetic-memory amem migrate --public-prune-view --dry-run
@@ -571,11 +577,21 @@ Search gives these events the existing 1.25 conversation weight and session grou
571
577
 
572
578
  ## Assistant records (#313)
573
579
 
580
+ Native SessionStart (`startup` and `compact`) preloads and screens the capture cache before work can spend the deadline, reserving only the newest permitted main-session Recap/Compact line. Work consumes the remaining pool. At the existing capture output position, up to five whole canonical Records use the then-remaining bytes; the reserved newest summary follows Records, and a second summary may use only bytes left after Records. The library brief follows the same reservation and output order. A line that cannot fit whole after the header and Record instruction is skipped and marks capture partial; budget allocation never truncates a display line or Record. The library and CLI still query capture directly and retain chronological raw-row fill after the preferred rows.
581
+
582
+ Stop/SessionEnd Record/summary commits and hook-spool replay prepare `brief-capture.json` (0600) in the project's machine directory. It preserves up to five canonical Records before up to two screened main-session summaries, including the current session, with their display values and the committed capture row watermark. Ordinary raw recent captures are excluded. Record commits refresh the cache too. The native read is one byte-capped file read, re-screens full source values under current policy, and never opens a capture database or rebuilds the cache. Missing or unreadable caches report `capture: capture cache missing`; total context bytes and native deadlines are unchanged. A busy snapshot can leave the cache missing until a later Record or summary commit. Refs #337.
583
+
574
584
  Since 0.23.0, native Claude SessionStart can prepend the package-owned `RECORD_INSTRUCTION` before the untrusted memory header, including on resume. Its three lines occupy 331 UTF-8 bytes, or 332 with the separator, reserved from the existing 1,200-byte context budget. The metric reports the actual emitted `recordInstructionBytes` and `recordInstructionEstimatedTokens` (83 when emitted, an approximation). The full block is omitted when it cannot fit; it never turns a failed or timed-out hook into valid context. Set `records: false` in the home's `amem.config.json` or the repository's `.amem/config` to disable the instruction and new extraction; false wins across both files.
575
585
 
586
+ For the #313 AC6 comparison week (#325), the person can create a private `record-instruction.json` in the memory home containing `{"instruction":"alternate"}` (`a`, `b` and `alternate` are the only values). This is separate from `amem.config.json`, whose `records` key remains boolean-only. The file must be regular, single-link, owned by the current uid and not group- or other-writable (`mode & 022 == 0`): normal 0644 is accepted; 0664 and 0666 are rejected. Core never writes the selection file. Missing means A; an invalid, unreadable, group/other-writable, oversized, foreign-owned or linked file also means A, with numeric `recordInstructionInvalid: 1` in the hook metric, without refusing the hook. Existing 0.23.x readers ignore this file and retain A. B uses purpose framing with a `basis:` hint and `?` for unverified text. Both reserve 332 bytes before the untrusted header; A emits 332 bytes including the separator, B emits 331 (about 83 estimated tokens each). Alternate uses even/odd parity of the last hex digit of the existing 16-character capture session hash for A/B, so resume keeps the same variant without exposing a raw session id. A missing or invalid session id falls back to A rather than guessing parity; metrics record that resolved A choice. `records: false` in either configuration file still wins. `RECORD_INSTRUCTION` remains the exact A text; `RECORD_INSTRUCTION_B`, `RECORD_INSTRUCTIONS`, `readRecordInstruction`, `captureSessionKey`, `recordInstructionVariant` and their mode/variant types let hosts reuse the package-owned text and selection rule. `basis:` and `?` remain ordinary Record text, with no grammar or capture-field change. The person compares the variants during the live week before deciding the default. [Record variant measurements](docs/bench/record-instruction-variants.md) records the public fixture protocol and its evidence status.
587
+
588
+ The live-week counters use a separate `record-variants.jsonl` beside the existing resource metrics. Each row contains `at`, the hook `event`, resolved `variant` (`a` or `b`) and allowlisted numeric Record fields; no Record text is written. Observations use single short `O_APPEND` writes and 0600 creation, retaining eight days within a 4 MiB hard cap. Capture rows, spool events/status values and the general resource metrics retention are unchanged. One session is one SessionStart with source `startup` or `resume`, including an omitted instruction; `recordInstructionEmitted` and `recordEnabled` distinguish exposure and opt-out. One turn is one Stop invocation. Stop/SessionEnd report eligible parsed Record counts, the number containing `basis:` and the number starting with `?`; these are parsing observations, not durable-publication counts. SessionEnd contributes Records but no Stop-turn denominator. An unavailable scan leaves counts unknown, and the report never converts missing counters into zero. SessionStart reports actual emitted brief bytes including the instruction. Capacity trims leave 1 MiB of headroom (4 MiB trigger, 3 MiB retained). Incomplete or unknown transcript scans are excluded from exact Stop-turn observations; the full-window exact share stays null until coverage is complete.
589
+
590
+ Run `bun scripts/report-record-variants.ts --input /path/to/memory/record-variants.jsonl` read-only to report sessions, Records/session, the share of Stop turns with a Record, basis and uncertainty shares, and mean brief bytes with explicit denominators. Missing Stop scan counters produce an incomplete/null exact turn share and a separate observed share. The bounded first-line probe triggers an age rewrite only past nine days, keeping eight days (daily hysteresis). Ordinary appends never read the tail or rewrite it. When the 4 MiB cap forces older observations out, numeric `capTrimmed` markers make `window.capForcedTrim` true and coverage incomplete; do not treat a capped window as a complete AC6 week. The general metrics file retains its existing 64 KiB trigger and newest-200 discipline.
591
+
576
592
  At Stop/SessionEnd, complete native assistant text can yield `Record` capture events through the existing transcript scan. `parseRecordLines`, `RECORD_INSTRUCTION` and `recordsEnabled(base, cwd?)` are public root exports; hosts check `recordsEnabled` before emitting the instruction or capturing parsed Records. The canonical grammar is maintained in `src/hook-record.ts`. The parser checks format and explicit text exclusions; hosts still apply their capture privacy policy before storage. It accepts the five kinds decision/fix/fail/contract/finding, repository-relative anchors and at most 300 text characters, excludes fenced/quoted examples, and requires the fix/fail relation. Missing native row time or stable `message.id` refuses extraction. At most two syntactically valid record lines are considered per stable message per scan call, with no persisted count. Whole records are declined on a denied anchor, policy refusal, truncation or redaction; no partial record is saved.
577
593
 
578
- Records stay machine-local capture, not curated evidence or review candidates. They reuse Title/Recap/Compact staging, deterministic receipts and replay, with canonical line content and the native row timestamp; no Record-only receipt or capture-row schema is added. Source-row privacy flags are screened before capture, and replay refuses to clip or remove anchors from a pending Record when caps change. A slow replay opportunity cannot strand the second Record in the same transcript row. A crash after staging but before cursor save retains the existing duplicate window. A message-ID/ordinal receipt is a future upgrade if the AC6 duplicate experiment requires it. Record-to-candidate conversion and other ingest/Jcode paths remain outside this change; AC6 and real-home rollout are person-run checks.
594
+ Records stay machine-local capture, not curated evidence; `amem consolidate` can queue them as review candidates (#368, [consolidation](#consolidation-and-evidence)). They reuse Title/Recap/Compact staging, deterministic receipts and replay, with canonical line content and the native row timestamp; no Record-only receipt or capture-row schema is added. Source-row privacy flags are screened before capture, and replay refuses to clip or remove anchors from a pending Record when caps change. A slow replay opportunity cannot strand the second Record in the same transcript row. A crash after staging but before cursor save retains the existing duplicate window. A message-ID/ordinal receipt is a future upgrade if the AC6 duplicate experiment requires it. Codex, Pi and Kimi ingest Records and the Qwen/Jcode refusals (#369) are described with `amem ingest` above; AC6 and real-home rollout are person-run checks.
579
595
 
580
596
  The brief puts up to five recent, screened main-session Records bound to this project before summaries and raw capture lines, using the same remaining byte budget. Repository-relative anchors must match the stored paths; `-` is valid only for project-bound decision/contract Records. Subagent or malformed Records stay out. Large legacy stores read only the newest 128 rows until an off-hook search prepares the separate Record partial index; hooks do not build it above 128 rows. Search weights Record at 1.5 versus 1.25 for conversational capture without changing curated slots or session grouping. MCP preserves the canonical line and paths, and the existing all-project CLI capture display keeps the complete Record line and anchors.
581
597
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@staix/agent-mem",
3
- "version": "0.23.1",
3
+ "version": "0.25.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",
@@ -0,0 +1,60 @@
1
+ import { randomBytes } from "node:crypto";
2
+ import { closeSync, constants, fstatSync, openSync, readSync, renameSync, rmSync, writeFileSync } from "node:fs";
3
+ import { join } from "node:path";
4
+
5
+ /** Shared bounded transport for prebuilt brief sections; never a database or a refresh on read. */
6
+ export const BRIEF_CACHE_BYTES = 32 * 1024;
7
+ /** `preferences` (#370) is a separate file, so a reader that only knows `curated` never opens it. */
8
+ export interface BriefCacheBinding { directory: string; project: string; section: "capture" | "curated" | "preferences" }
9
+ export interface BriefCacheRow { source: unknown; data: unknown; partial: boolean }
10
+ export interface CuratedBriefMetadata { builtAt: number; binding: string; expiresAt: number | null }
11
+ export interface BriefCache {
12
+ schema: "agent-mem.brief-cache/v1"; project: string; section: BriefCacheBinding["section"];
13
+ builtThrough: number; partial: boolean; rows: BriefCacheRow[];
14
+ curated?: CuratedBriefMetadata;
15
+ /** #370: the preference sidecar's stamp, in its own key so the curated file's `curated` stamp parses exactly as released readers expect. */
16
+ preferences?: CuratedBriefMetadata;
17
+ }
18
+ export function briefCacheFile(binding: BriefCacheBinding): string { return join(binding.directory, `brief-${binding.section}.json`); }
19
+
20
+ export function readBriefCache(binding: BriefCacheBinding): BriefCache | undefined {
21
+ let fd: number | undefined;
22
+ try {
23
+ fd = openSync(briefCacheFile(binding), constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
24
+ const stat = fstatSync(fd);
25
+ if (!stat.isFile() || stat.nlink !== 1 || stat.uid !== process.getuid?.() || stat.size < 1 || stat.size > BRIEF_CACHE_BYTES || (stat.mode & 0o077) !== 0) return;
26
+ const bytes = Buffer.alloc(BRIEF_CACHE_BYTES + 1);
27
+ const size = readSync(fd, bytes, 0, bytes.length, 0); // one bounded read, including an oversize sentinel
28
+ const after = fstatSync(fd);
29
+ if (size !== stat.size || size > BRIEF_CACHE_BYTES || stat.size !== after.size || stat.mtimeMs !== after.mtimeMs || stat.ctimeMs !== after.ctimeMs) return;
30
+ const cache = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes.subarray(0, size))) as BriefCache;
31
+ if (cache.schema !== "agent-mem.brief-cache/v1" || cache.project !== binding.project || cache.section !== binding.section
32
+ || !Number.isSafeInteger(cache.builtThrough) || cache.builtThrough < 1 || typeof cache.partial !== "boolean"
33
+ || (cache.curated !== undefined && (cache.section !== "curated" || !cache.curated || !Number.isFinite(cache.curated.builtAt)
34
+ || typeof cache.curated.binding !== "string" || !cache.curated.binding
35
+ || !(cache.curated.expiresAt === null || Number.isFinite(cache.curated.expiresAt))))
36
+ || (cache.preferences !== undefined && (cache.section !== "preferences" || !cache.preferences || !Number.isFinite(cache.preferences.builtAt)
37
+ || typeof cache.preferences.binding !== "string" || !cache.preferences.binding
38
+ || !(cache.preferences.expiresAt === null || Number.isFinite(cache.preferences.expiresAt))))
39
+ || !Array.isArray(cache.rows) || cache.rows.length > 8
40
+ || cache.rows.some(row => !row || typeof row.partial !== "boolean" || row.source === undefined || row.data === undefined)) return;
41
+ return cache;
42
+ } catch { return undefined; }
43
+ finally { if (fd !== undefined) closeSync(fd); }
44
+ }
45
+
46
+ /** Invalidate under the source store's write transaction, before a summary can commit. */
47
+ export function invalidateBriefCache(binding: BriefCacheBinding): void { rmSync(briefCacheFile(binding), { force: true }); }
48
+
49
+ /** Atomic private replacement; callers serialize publication with their source-store writers. Refuse a replacement when a newer committed-row watermark is already visible. */
50
+ export function writeBriefCache(binding: BriefCacheBinding, cache: BriefCache): void {
51
+ const text = JSON.stringify(cache) + "\n";
52
+ if (Buffer.byteLength(text) > BRIEF_CACHE_BYTES) throw new Error("brief cache byte bound");
53
+ const file = briefCacheFile(binding), temporary = `${file}.${process.pid}.${randomBytes(8).toString("hex")}.tmp`;
54
+ try {
55
+ writeFileSync(temporary, text, { mode: 0o600, flag: "wx" });
56
+ const prior = readBriefCache(binding);
57
+ if (prior && prior.builtThrough > cache.builtThrough) return;
58
+ renameSync(temporary, file);
59
+ } finally { rmSync(temporary, { force: true }); }
60
+ }
@@ -0,0 +1,82 @@
1
+ import { parseRecordLines } from "./hook-record.ts";
2
+ import type { CaptureRow, CaptureStore } from "./memory/capture.ts";
3
+ import { configuredPolicyOptions } from "./memory/config.ts";
4
+ import { createStandalonePolicy, type StandalonePolicyOptions } from "./memory/policy.ts";
5
+ import { BRIEF_CACHE_BYTES, writeBriefCache, type BriefCacheRow } from "./brief-cache.ts";
6
+
7
+ /** Bound display values only after complete-row policy; flatten controls before serialization. */
8
+ export function displayText(text: string, maximum: number): { text: string; partial: boolean } {
9
+ const flattened = text.replace(/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/gu, " ");
10
+ let out = "", bytes = 0;
11
+ for (const character of flattened) {
12
+ const size = Buffer.byteLength(character);
13
+ if (bytes + size > maximum) return { text: out, partial: true };
14
+ out += character; bytes += size;
15
+ }
16
+ return { text: out, partial: flattened !== text };
17
+ }
18
+ export function captureDisplay(row: CaptureRow): { data: unknown; partial: boolean } {
19
+ const excerpt = displayText(row.excerpt, 240), event = displayText(row.event, 64);
20
+ const paths = row.paths.slice(0, 2).map(path => displayText(path, 80));
21
+ return { data: { id: row.id, at: row.at, event: event.text, paths: paths.map(path => path.text), excerpt: excerpt.text },
22
+ partial: excerpt.partial || event.partial || row.paths.length > paths.length || paths.some(path => path.partial) };
23
+ }
24
+ /** Preserve #313 whole canonical Records before summaries. */
25
+ export function recordDisplay(row: CaptureRow): { data: unknown; partial: boolean } | undefined {
26
+ const parsed = parseRecordLines(row.excerpt), record = parsed.records[0];
27
+ if (!record || parsed.records.length !== 1 || Object.keys(parsed.drops).length || record.line !== row.excerpt
28
+ || JSON.stringify(record.anchors) !== JSON.stringify(row.paths)) return;
29
+ return { data: { event: "Record", paths: record.anchors, excerpt: record.line }, partial: false };
30
+ }
31
+
32
+ export interface CaptureBriefOptions { base: string; project: string; cwd: string; builtThrough: number; policy?: StandalonePolicyOptions }
33
+ /** Reuse the library's #201 summary query, full-row screen, two-summary selection and display, with existing Record priority. */
34
+ export function buildCaptureBriefCache(store: CaptureStore, options: CaptureBriefOptions): void {
35
+ if (options.policy?.host) throw new Error("prebuilt capture requires synchronous standalone screening");
36
+ const policy = createStandalonePolicy(configuredPolicyOptions(options.base, options.cwd, options.policy));
37
+ store.withBriefCaptureSnapshot((summaries, builtThrough) => {
38
+ const records = store.readBriefRecords(), recordRows: BriefCacheRow[] = [], summaryRows: BriefCacheRow[] = [];
39
+ const watermark = Math.max(options.builtThrough, builtThrough);
40
+ let partial = summaries.partial || records.partial, count = 0;
41
+ let storedBytes = Buffer.byteLength(JSON.stringify({ schema: "agent-mem.brief-cache/v1", project: options.project,
42
+ section: "capture", builtThrough: watermark, partial: false, rows: [] })) + 1;
43
+ const keep = (target: BriefCacheRow[], source: CaptureRow, shown: { data: unknown; partial: boolean }) => {
44
+ const row = { source, ...shown }, bytes = Buffer.byteLength(JSON.stringify(row)) + (count ? 1 : 0);
45
+ const displayBytes = Buffer.byteLength(JSON.stringify({ section: "capture", evidence: false, data: shown.data }));
46
+ if (displayBytes > 768 || storedBytes + bytes > BRIEF_CACHE_BYTES) { partial = true; return false; }
47
+ target.push(row); count++; storedBytes += bytes; partial ||= shown.partial; return true;
48
+ };
49
+ // Keep the two summary candidates independently of Record/context allocation. The reader alone owns the brief pool.
50
+ let selectedSummaries = 0;
51
+ for (const source of summaries.rows) {
52
+ if (source.project !== options.project || source.subagent === true || !policy.screenStandalone(source)) continue;
53
+ if (selectedSummaries >= 2) break;
54
+ const shown = captureDisplay(source);
55
+ if (!policy.screenStandalone(shown.data)) continue;
56
+ selectedSummaries++; keep(summaryRows, source, shown);
57
+ }
58
+ let selectedRecords = 0;
59
+ for (const source of records.rows) {
60
+ if (source.project !== options.project || source.subagent === true) continue;
61
+ if (selectedRecords >= 5) { partial = true; break; }
62
+ if (!policy.screenStandalone(source)) continue;
63
+ const shown = recordDisplay(source);
64
+ if (!shown || !policy.screenStandalone(shown.data)) continue;
65
+ if (keep(recordRows, source, shown)) selectedRecords++;
66
+ }
67
+ writeBriefCache({ directory: store.dir, project: options.project, section: "capture" }, {
68
+ schema: "agent-mem.brief-cache/v1", project: options.project, section: "capture", builtThrough: watermark, partial,
69
+ rows: [...recordRows, ...summaryRows],
70
+ });
71
+ });
72
+ }
73
+
74
+ /** Cache files are untrusted derived data: require the same project and canonical summary display. */
75
+ export function validCachedCapture(row: BriefCacheRow, project: string): boolean {
76
+ const source = row.source as CaptureRow | null;
77
+ if (!source || source.project !== project || source.subagent === true || !["Record", "Recap", "Compact"].includes(source.event)
78
+ || !Number.isSafeInteger(source.id) || source.id < 1 || typeof source.at !== "string" || !Number.isFinite(Date.parse(source.at))
79
+ || typeof source.excerpt !== "string" || !Array.isArray(source.paths) || source.paths.some(value => typeof value !== "string")) return false;
80
+ const shown = source.event === "Record" ? recordDisplay(source) : captureDisplay(source);
81
+ return !!shown && JSON.stringify(shown.data) === JSON.stringify(row.data) && shown.partial === row.partial;
82
+ }
@@ -0,0 +1,52 @@
1
+ import { lstatSync, readFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { briefCacheFile, readBriefCache, type BriefCache } from "./brief-cache.ts";
4
+ import { briefCacheFresh, curatedCacheFresh } from "./brief-curated.ts";
5
+ import { assertFormatFloor, formatFloorAtLeast, FormatFloorError, PREFERENCE_MIN_READER } from "./memory/formats.ts";
6
+ import { captureShardDir } from "./memory/shard.ts";
7
+
8
+ // ponytail: #322 is planned for 0.24.0. If that release ships before this change,
9
+ // the release PR must move this constant to the first release containing invalidation.
10
+ export const CURATED_CACHE_MIN_READER = "0.24.0";
11
+
12
+ /**
13
+ * ponytail: a missed invalidation path can serve at most 24 hours of stale curated data.
14
+ * Upgrade to the bounded authoritative manifest frontier if real missed paths justify it.
15
+ * No writer or reader raises the person-owned floor.
16
+ */
17
+ export function readCuratedBriefCache(options: { base: string; project: string; profile: string; supportingRelease: string; deferredReason: string; now: number }): { cache?: BriefCache; reason?: string } {
18
+ try {
19
+ assertFormatFloor(options.base, "curated");
20
+ if (!formatFloorAtLeast(options.base, "curated", options.supportingRelease)) return { reason: options.deferredReason };
21
+ let machine: unknown;
22
+ try { machine = JSON.parse(readFileSync(join(options.base, "machine.json"), "utf8")).id; } catch { /* No machine means no prebuilt section. */ }
23
+ if (typeof machine !== "string" || !/^[a-f0-9]{16}$/.test(machine)) return { reason: "curated cache missing" };
24
+ const binding = { directory: captureShardDir(options.base, options.project, machine), project: options.project, section: "curated" as const };
25
+ if (!lstatSync(briefCacheFile(binding), { throwIfNoEntry: false })) return { reason: "curated cache missing" };
26
+ const cache = readBriefCache(binding);
27
+ return cache && curatedCacheFresh(cache, options.profile, options.now) ? { cache } : { reason: "curated cache stale" };
28
+ } catch (error) {
29
+ if (error instanceof FormatFloorError) return { reason: error.code === "format_floor" ? "floor: upgrade amem" : "floor: amem doctor" };
30
+ return { reason: "curated cache stale" };
31
+ }
32
+ }
33
+
34
+ /**
35
+ * #370: the SessionStart preference slot's sidecar. It carries the curated section's gate, not one of its own: a person-recorded floor
36
+ * above this reader refuses before any prebuilt row is served, and a home whose floor does not admit the kind cannot legitimately hold
37
+ * a preference row at all. A missing or stale sidecar yields no slot, never a coverage reason, so a home without preferences keeps a
38
+ * byte-identical brief.
39
+ */
40
+ export function readPreferenceBriefCache(options: { base: string; project: string; profile: string; now: number }): BriefCache | undefined {
41
+ try {
42
+ assertFormatFloor(options.base, "curated");
43
+ if (!formatFloorAtLeast(options.base, "curated", PREFERENCE_MIN_READER)) return;
44
+ let machine: unknown;
45
+ try { machine = JSON.parse(readFileSync(join(options.base, "machine.json"), "utf8")).id; } catch { /* No machine means no prebuilt section. */ }
46
+ if (typeof machine !== "string" || !/^[a-f0-9]{16}$/.test(machine)) return;
47
+ const binding = { directory: captureShardDir(options.base, options.project, machine), project: options.project, section: "preferences" as const };
48
+ if (!lstatSync(briefCacheFile(binding), { throwIfNoEntry: false })) return;
49
+ const cache = readBriefCache(binding);
50
+ return cache && briefCacheFresh(cache.preferences, options.profile, options.now) ? cache : undefined;
51
+ } catch { return undefined; }
52
+ }
@@ -0,0 +1,118 @@
1
+ import { createStandalonePolicy, type StandalonePolicyOptions } from "./memory/policy.ts";
2
+ import { configuredPolicyOptions } from "./memory/config.ts";
3
+ import type { MemoryStore, View } from "./memory/store.ts";
4
+ import { displayText } from "./brief-capture.ts";
5
+ import { BRIEF_CACHE_BYTES, writeBriefCache, type BriefCacheRow } from "./brief-cache.ts";
6
+ import { PREFERENCE_SLOT } from "./memory/preference-brief.ts";
7
+
8
+ const PAGE_ROWS = 32, MAX_PAGES = 4, SECTION_RECORDS = 4, RECORD_BYTES = 768, MAX_AGE = 24 * 60 * 60 * 1000;
9
+
10
+ /** Canonical curated display shared by the library brief and snapshot writer. */
11
+ export function noteDisplay(view: View): { data: unknown; partial: boolean } {
12
+ const body = displayText(view.text, 240), title = view.title === null ? undefined : displayText(view.title, 96);
13
+ return { data: { id: view.id, at: view.at, kind: view.kind, ...(title ? { title: title.text } : {}), text: body.text },
14
+ partial: body.partial || title?.partial === true };
15
+ }
16
+
17
+ export function validCachedCurated(row: BriefCacheRow, project: string, now = Date.now()): boolean {
18
+ const source = row.source as View | null;
19
+ if (!source || source.project !== project || typeof source.id !== "string" || !/^[a-f0-9]{32}$/.test(source.id)
20
+ || typeof source.at !== "string" || !Number.isFinite(Date.parse(source.at)) || typeof source.text !== "string"
21
+ || !(source.title === null || typeof source.title === "string") || typeof source.kind !== "string"
22
+ || source.supersededBy !== null || (source.expiresAt !== null && (!Number.isFinite(Date.parse(source.expiresAt)) || Date.parse(source.expiresAt) <= now))) return false;
23
+ const shown = noteDisplay(source);
24
+ return JSON.stringify(shown.data) === JSON.stringify(row.data) && shown.partial === row.partial;
25
+ }
26
+
27
+ /**
28
+ * #370: the preference slot's rows are this project's own plus any preference shared with every project, so a shared row written under
29
+ * another project is valid here. Liveness, supersession, expiry and the canonical display are the curated rule, reused as-is.
30
+ */
31
+ export function validCachedPreference(row: BriefCacheRow, project: string, now = Date.now()): boolean {
32
+ const source = row.source as View | null;
33
+ if (!source || source.kind !== "preference" || (source.project !== project && source.scope !== "shared")) return false;
34
+ return validCachedCurated({ ...row, source: { ...source, project } }, project, now);
35
+ }
36
+
37
+ export function curatedCacheFresh(cache: { curated?: { builtAt: number; binding: string; expiresAt: number | null } }, binding: string, now: number): boolean {
38
+ return briefCacheFresh(cache.curated, binding, now);
39
+ }
40
+
41
+ /** Both prebuilt stamps age the same way: at most 24 hours, and never past a named expiry of a row they carry. */
42
+ export function briefCacheFresh(metadata: { builtAt: number; binding: string; expiresAt: number | null } | undefined, binding: string, now: number): boolean {
43
+ return !!metadata && metadata.binding === binding && Number.isFinite(metadata.builtAt) && metadata.builtAt <= now
44
+ && now - metadata.builtAt < MAX_AGE && (metadata.expiresAt === null || Number.isFinite(metadata.expiresAt) && metadata.expiresAt > now);
45
+ }
46
+
47
+ /**
48
+ * #370: the SessionStart preference slot's sidecar, written by the same off-hook preparation as the curated cache and read by the native
49
+ * hook without opening a store. Its own file name, so a released reader neither parses it (it only opens `brief-curated.json`) nor
50
+ * invalidates it; a missed invalidation from such a reader ages out at the same 24-hour bound as the curated cache.
51
+ */
52
+ export function buildPreferenceBriefCache(store: Pick<MemoryStore, "readPreferences" | "withDeferredPromotions">,
53
+ options: { base: string; project: string; directory: string; binding: string; cwd?: string; now?: () => number; policy?: StandalonePolicyOptions }): void {
54
+ if (options.policy?.host) throw new Error("prebuilt preference brief requires synchronous standalone policy; remove host policy or use the async session brief");
55
+ const now = (options.now ?? Date.now)(), policy = createStandalonePolicy(configuredPolicyOptions(options.base, options.cwd, options.policy));
56
+ const rows: BriefCacheRow[] = [], expires: number[] = [];
57
+ let partial = false, bytes = Buffer.byteLength(JSON.stringify({ schema: "agent-mem.brief-cache/v1", project: options.project, section: "preferences", builtThrough: 1, partial: false, rows: [], preferences: { builtAt: now, binding: options.binding, expiresAt: null } })) + 1;
58
+ store.withDeferredPromotions(() => {
59
+ // Newest first with no paging: the slot must not hide an old preference behind newer notes of other kinds.
60
+ const page = store.readPreferences(options.project, PREFERENCE_SLOT);
61
+ partial ||= page.truncated;
62
+ for (const source of page.rows) {
63
+ if (!policy.screenStandalone(source)) continue;
64
+ const shown = noteDisplay(source);
65
+ if (!policy.screenStandalone(shown.data)) continue;
66
+ // #370: a standing instruction is shown whole or not at all, the rule `amem_brief` applies. `noteDisplay` clips at 240 bytes, so a
67
+ // clipped rule is dropped and the section reports truncation rather than emitting half a rule that reads as the whole one.
68
+ if (shown.partial) { partial = true; continue; }
69
+ const row = { source, data: shown.data, partial: shown.partial }, rowBytes = Buffer.byteLength(JSON.stringify(row)) + (rows.length ? 1 : 0);
70
+ const displayBytes = Buffer.byteLength(JSON.stringify({ section: "curated", evidence: true, data: shown.data })); // the brief emits these as curated evidence lines
71
+ if (displayBytes > RECORD_BYTES || bytes + rowBytes > BRIEF_CACHE_BYTES) { partial = true; continue; }
72
+ rows.push(row); bytes += rowBytes;
73
+ if (source.expiresAt !== null) expires.push(Date.parse(source.expiresAt));
74
+ }
75
+ });
76
+ const expiresAt = expires.length ? Math.min(...expires) : null;
77
+ writeBriefCache({ directory: options.directory, project: options.project, section: "preferences" }, {
78
+ schema: "agent-mem.brief-cache/v1", project: options.project, section: "preferences", builtThrough: Math.max(1, now), partial, rows,
79
+ preferences: { builtAt: now, binding: options.binding, expiresAt },
80
+ });
81
+ }
82
+
83
+ export function buildCuratedBriefCache(store: Pick<MemoryStore, "readPage" | "withDeferredPromotions">,
84
+ options: { base: string; project: string; directory: string; binding: string; cwd?: string; now?: () => number; policy?: StandalonePolicyOptions }): void {
85
+ if (options.policy?.host) throw new Error("prebuilt curated brief requires synchronous standalone policy; remove host policy or use the async session brief");
86
+ const now = (options.now ?? Date.now)(), policy = createStandalonePolicy(configuredPolicyOptions(options.base, options.cwd, options.policy));
87
+ const rows: BriefCacheRow[] = [], expires: number[] = [];
88
+ let partial = false, after: { position: number; id: string } | undefined, complete = false;
89
+ let bytes = Buffer.byteLength(JSON.stringify({ schema: "agent-mem.brief-cache/v1", project: options.project, section: "curated", builtThrough: 1, partial: false, rows: [], curated: { builtAt: now, binding: options.binding, expiresAt: null } })) + 1;
90
+ store.withDeferredPromotions(() => {
91
+ for (let pageNo = 0; pageNo < MAX_PAGES; pageNo++) {
92
+ const page = store.readPage({ project: options.project, limit: PAGE_ROWS, after });
93
+ for (const source of page.rows) {
94
+ if (source.project !== options.project) { partial = true; continue; }
95
+ if (source.supersededBy || source.expiresAt !== null && Date.parse(source.expiresAt) <= now) continue;
96
+ // #370: a preference is emitted by its own slot, so it never spends one of this section's rows (or its byte budget).
97
+ if (source.kind === "preference") continue;
98
+ if (!policy.screenStandalone(source)) continue;
99
+ if (rows.length >= SECTION_RECORDS) { partial = true; complete = true; break; }
100
+ const shown = noteDisplay(source);
101
+ if (!policy.screenStandalone(shown.data)) continue;
102
+ const row = { source, data: shown.data, partial: shown.partial }, rowBytes = Buffer.byteLength(JSON.stringify(row)) + (rows.length ? 1 : 0);
103
+ const displayBytes = Buffer.byteLength(JSON.stringify({ section: "curated", evidence: true, data: shown.data }));
104
+ if (displayBytes > RECORD_BYTES || bytes + rowBytes > BRIEF_CACHE_BYTES) { partial = true; continue; }
105
+ rows.push(row); bytes += rowBytes; partial ||= shown.partial;
106
+ if (source.expiresAt !== null) expires.push(Date.parse(source.expiresAt));
107
+ }
108
+ if (complete || !page.next) { complete = true; break; }
109
+ after = { position: page.next.position, id: page.next.id };
110
+ }
111
+ if (!complete) partial = true;
112
+ });
113
+ const expiresAt = expires.length ? Math.min(...expires) : null;
114
+ writeBriefCache({ directory: options.directory, project: options.project, section: "curated" }, {
115
+ schema: "agent-mem.brief-cache/v1", project: options.project, section: "curated", builtThrough: Math.max(1, now), partial, rows,
116
+ curated: { builtAt: now, binding: options.binding, expiresAt },
117
+ });
118
+ }
package/src/cli.ts CHANGED
@@ -8,6 +8,7 @@ import { randomUUID } from "node:crypto";
8
8
  import type { Writable } from "node:stream";
9
9
  import { buildIntentBrief } from "./memory/intent-brief.ts";
10
10
  import { proposeConsolidation } from "./memory/consolidate.ts";
11
+ import { recordCaptureLookup, recordSourceCheck, recordWindow } from "./memory/record-candidates.ts";
11
12
  import { createIntentBriefSource, recallViewIsLive } from "./memory/recall.ts";
12
13
  import { createRecallStalenessProbe } from "./memory/recall-staleness.ts";
13
14
  import { recordMemoryUse } from "./memory/use-telemetry.ts";
@@ -458,8 +459,9 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
458
459
  const binding = commandBinding(store.profile.home, boundProject()), policyKey = () => JSON.stringify(configuredPolicyOptions(base, policyCwd));
459
460
  const assertCurrent = () => { binding(); assertProjectActive(base, project); if (resolveAlias(base, requested) !== project || aliasedKeys(base, project).join("\n") !== aliases.join("\n")) throw Error("consolidation project binding changed"); };
460
461
  candidates = new CandidateStore({ memoryDir: base, reconcile: { canonical: project, aliases } });
461
- const report = await proposeConsolidation(store, candidates, { project, actor, policy: policyOf, policyVersion: policyKey, assertCurrent });
462
- return options["--json"] ? JSON.stringify(report, null, 2) : `${report.candidates.length} consolidation candidates queued for amem review; no curated notes changed${report.alreadyReviewed ? `; ${report.alreadyReviewed} already reviewed` : ""}${report.truncated ? "; scan truncated" : ""}${report.oversized ? `; ${report.oversized} proposals too large` : ""}${report.localExcluded ? `; ${report.localExcluded} local sources excluded` : ""}`;
462
+ const readRecords = recordWindow(base, project, policyCwd);
463
+ const report = await proposeConsolidation(store, candidates, { project, actor, policy: policyOf, policyVersion: policyKey, assertCurrent, ...(readRecords ? { records: readRecords } : {}) });
464
+ return options["--json"] ? JSON.stringify(report, null, 2) : `${report.candidates.length} consolidation candidates queued for amem review; no curated notes changed${report.records ? `; ${report.records.queued} of ${report.records.found} Record(s)${report.records.truncated ? " in the newest 32" : ""}` : ""}${report.alreadyReviewed ? `; ${report.alreadyReviewed} already reviewed` : ""}${report.truncated ? "; scan truncated" : ""}${report.oversized ? `; ${report.oversized} proposals too large` : ""}${report.localExcluded ? `; ${report.localExcluded} local sources excluded` : ""}`;
463
465
  } finally { candidates?.close(); store.close(); }
464
466
  }
465
467
  if (sub === "brief") {
@@ -479,6 +481,7 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
479
481
  const result = await buildIntentBrief(createIntentBriefSource(store, project),
480
482
  { project, cwd: root, repo: project, intent, paths, symbols, maxBytes, policy, policyVersion, assertCurrent, now: () => store.readNow(), stale: createRecallStalenessProbe({ cwd: root, rootConfirmed, policy }) });
481
483
  assertCurrent(); outputReady(result.items.map(view => view.id), project);
484
+ if (actor === "person") store.prepareCuratedBriefs([project]);
482
485
  return options["--json"] ? JSON.stringify({ brief: result.text, bytes: result.bytes, truncated: result.truncated, state: result.state }, null, 2) : result.text;
483
486
  } finally { store.close(); }
484
487
  }
@@ -751,6 +754,9 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
751
754
  const result = candidates.accept(id!, { project, actor, verdict: "public", store,
752
755
  policyVersion: () => JSON.stringify(configuredPolicyOptions(realPath(store.profile.home), policyCwd)),
753
756
  policy: (proposal, target, note, goal) => { assertCurrent(); return policyOf().screenStandalone({ ...proposal.input, ...(target ? { targetView: target } : {}), note, ...(goal ? { goalView: goal } : {}) }); },
757
+ // #368: a Record candidate quotes capture rows, so acceptance point-reads exactly those turns of its shard,
758
+ // rather than the brief window a candidate can outlive.
759
+ recordSource: recordSourceCheck(recordCaptureLookup(realPath(store.profile.home), policyCwd)),
754
760
  });
755
761
  return options["--json"] ? JSON.stringify(result, null, 2) : `accepted candidate ${id} as ${candidate.input.kind === "promotion" ? "promoted" : "ordinary"} note ${result.noteId}`;
756
762
  } finally { store.close(); }