@staix/agent-mem 0.24.0 → 0.25.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/plugin.json +1 -1
- package/README.md +15 -9
- package/package.json +1 -1
- package/src/brief-cache.ts +7 -1
- package/src/brief-curated-native.ts +22 -2
- package/src/brief-curated.ts +54 -1
- package/src/cli.ts +7 -2
- package/src/hook-contract.ts +18 -2
- package/src/hook-jcode-journal.ts +46 -4
- package/src/hook-record.ts +18 -0
- package/src/hook-spool.ts +23 -12
- package/src/hooks.ts +4 -4
- package/src/index.ts +1 -0
- package/src/ingest-records.ts +113 -0
- package/src/ingest.ts +106 -9
- package/src/mcp-memory.ts +2 -2
- package/src/mcp.ts +1 -1
- package/src/memory/candidates.ts +56 -5
- package/src/memory/capture.ts +20 -0
- package/src/memory/consolidate.ts +35 -1
- package/src/memory/curated-cache-state.ts +4 -3
- package/src/memory/decay-review.ts +3 -1
- package/src/memory/formats.ts +14 -0
- package/src/memory/index-file.ts +1 -1
- package/src/memory/intent-brief.ts +42 -4
- package/src/memory/metrics.ts +3 -3
- package/src/memory/note-add.ts +2 -0
- package/src/memory/ops-contract.ts +1 -1
- package/src/memory/preference-brief.ts +22 -0
- package/src/memory/recall.ts +4 -1
- package/src/memory/record-candidates.ts +179 -0
- package/src/memory/search-fts.ts +3 -0
- package/src/memory/store.ts +55 -4
- package/src/session-brief.ts +23 -3
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.
|
|
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` (
|
|
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.
|
|
@@ -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.
|
|
@@ -438,7 +442,7 @@ Real migration remains blocked until the separately reviewed generation-capable
|
|
|
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
|
|
|
@@ -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
|
|
@@ -585,7 +591,7 @@ Run `bun scripts/report-record-variants.ts --input /path/to/memory/record-varian
|
|
|
585
591
|
|
|
586
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.
|
|
587
593
|
|
|
588
|
-
Records stay machine-local capture, not curated evidence
|
|
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.
|
|
589
595
|
|
|
590
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.
|
|
591
597
|
|
package/package.json
CHANGED
package/src/brief-cache.ts
CHANGED
|
@@ -4,13 +4,16 @@ import { join } from "node:path";
|
|
|
4
4
|
|
|
5
5
|
/** Shared bounded transport for prebuilt brief sections; never a database or a refresh on read. */
|
|
6
6
|
export const BRIEF_CACHE_BYTES = 32 * 1024;
|
|
7
|
-
|
|
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" }
|
|
8
9
|
export interface BriefCacheRow { source: unknown; data: unknown; partial: boolean }
|
|
9
10
|
export interface CuratedBriefMetadata { builtAt: number; binding: string; expiresAt: number | null }
|
|
10
11
|
export interface BriefCache {
|
|
11
12
|
schema: "agent-mem.brief-cache/v1"; project: string; section: BriefCacheBinding["section"];
|
|
12
13
|
builtThrough: number; partial: boolean; rows: BriefCacheRow[];
|
|
13
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;
|
|
14
17
|
}
|
|
15
18
|
export function briefCacheFile(binding: BriefCacheBinding): string { return join(binding.directory, `brief-${binding.section}.json`); }
|
|
16
19
|
|
|
@@ -30,6 +33,9 @@ export function readBriefCache(binding: BriefCacheBinding): BriefCache | undefin
|
|
|
30
33
|
|| (cache.curated !== undefined && (cache.section !== "curated" || !cache.curated || !Number.isFinite(cache.curated.builtAt)
|
|
31
34
|
|| typeof cache.curated.binding !== "string" || !cache.curated.binding
|
|
32
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))))
|
|
33
39
|
|| !Array.isArray(cache.rows) || cache.rows.length > 8
|
|
34
40
|
|| cache.rows.some(row => !row || typeof row.partial !== "boolean" || row.source === undefined || row.data === undefined)) return;
|
|
35
41
|
return cache;
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { lstatSync, readFileSync } from "node:fs";
|
|
2
2
|
import { join } from "node:path";
|
|
3
3
|
import { briefCacheFile, readBriefCache, type BriefCache } from "./brief-cache.ts";
|
|
4
|
-
import { curatedCacheFresh } from "./brief-curated.ts";
|
|
5
|
-
import { assertFormatFloor, formatFloorAtLeast, FormatFloorError } from "./memory/formats.ts";
|
|
4
|
+
import { briefCacheFresh, curatedCacheFresh } from "./brief-curated.ts";
|
|
5
|
+
import { assertFormatFloor, formatFloorAtLeast, FormatFloorError, PREFERENCE_MIN_READER } from "./memory/formats.ts";
|
|
6
6
|
import { captureShardDir } from "./memory/shard.ts";
|
|
7
7
|
|
|
8
8
|
// ponytail: #322 is planned for 0.24.0. If that release ships before this change,
|
|
@@ -30,3 +30,23 @@ export function readCuratedBriefCache(options: { base: string; project: string;
|
|
|
30
30
|
return { reason: "curated cache stale" };
|
|
31
31
|
}
|
|
32
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
|
+
}
|
package/src/brief-curated.ts
CHANGED
|
@@ -3,6 +3,7 @@ import { configuredPolicyOptions } from "./memory/config.ts";
|
|
|
3
3
|
import type { MemoryStore, View } from "./memory/store.ts";
|
|
4
4
|
import { displayText } from "./brief-capture.ts";
|
|
5
5
|
import { BRIEF_CACHE_BYTES, writeBriefCache, type BriefCacheRow } from "./brief-cache.ts";
|
|
6
|
+
import { PREFERENCE_SLOT } from "./memory/preference-brief.ts";
|
|
6
7
|
|
|
7
8
|
const PAGE_ROWS = 32, MAX_PAGES = 4, SECTION_RECORDS = 4, RECORD_BYTES = 768, MAX_AGE = 24 * 60 * 60 * 1000;
|
|
8
9
|
|
|
@@ -23,12 +24,62 @@ export function validCachedCurated(row: BriefCacheRow, project: string, now = Da
|
|
|
23
24
|
return JSON.stringify(shown.data) === JSON.stringify(row.data) && shown.partial === row.partial;
|
|
24
25
|
}
|
|
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
|
+
|
|
26
37
|
export function curatedCacheFresh(cache: { curated?: { builtAt: number; binding: string; expiresAt: number | null } }, binding: string, now: number): boolean {
|
|
27
|
-
|
|
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 {
|
|
28
43
|
return !!metadata && metadata.binding === binding && Number.isFinite(metadata.builtAt) && metadata.builtAt <= now
|
|
29
44
|
&& now - metadata.builtAt < MAX_AGE && (metadata.expiresAt === null || Number.isFinite(metadata.expiresAt) && metadata.expiresAt > now);
|
|
30
45
|
}
|
|
31
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
|
+
|
|
32
83
|
export function buildCuratedBriefCache(store: Pick<MemoryStore, "readPage" | "withDeferredPromotions">,
|
|
33
84
|
options: { base: string; project: string; directory: string; binding: string; cwd?: string; now?: () => number; policy?: StandalonePolicyOptions }): void {
|
|
34
85
|
if (options.policy?.host) throw new Error("prebuilt curated brief requires synchronous standalone policy; remove host policy or use the async session brief");
|
|
@@ -42,6 +93,8 @@ export function buildCuratedBriefCache(store: Pick<MemoryStore, "readPage" | "wi
|
|
|
42
93
|
for (const source of page.rows) {
|
|
43
94
|
if (source.project !== options.project) { partial = true; continue; }
|
|
44
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;
|
|
45
98
|
if (!policy.screenStandalone(source)) continue;
|
|
46
99
|
if (rows.length >= SECTION_RECORDS) { partial = true; complete = true; break; }
|
|
47
100
|
const shown = noteDisplay(source);
|
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
|
|
462
|
-
|
|
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") {
|
|
@@ -752,6 +754,9 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
752
754
|
const result = candidates.accept(id!, { project, actor, verdict: "public", store,
|
|
753
755
|
policyVersion: () => JSON.stringify(configuredPolicyOptions(realPath(store.profile.home), policyCwd)),
|
|
754
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)),
|
|
755
760
|
});
|
|
756
761
|
return options["--json"] ? JSON.stringify(result, null, 2) : `accepted candidate ${id} as ${candidate.input.kind === "promotion" ? "promoted" : "ordinary"} note ${result.noteId}`;
|
|
757
762
|
} finally { store.close(); }
|
package/src/hook-contract.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { RecordIntakeCounts } from "./hook-record.ts";
|
|
1
2
|
export const HOOK_EVENTS = ["SessionStart", "UserPromptSubmit", "PreToolUse", "PostToolUse", "PostToolUseFailure", "Stop", "SessionEnd"] as const;
|
|
2
3
|
export type HookEvent = typeof HOOK_EVENTS[number];
|
|
3
4
|
export const HOOK_INPUT_BYTES = 64 * 1024, HOOK_CONTEXT_BYTES = 1200, HOOK_OUTPUT_BYTES = 8192;
|
|
@@ -5,11 +6,12 @@ export const HOOK_INPUT_BYTES = 64 * 1024, HOOK_CONTEXT_BYTES = 1200, HOOK_OUTPU
|
|
|
5
6
|
export type HookTranscriptStopReason = "cap" | "deadline" | "spool_full" | "unavailable";
|
|
6
7
|
export const HOOK_TRANSCRIPT_STOP_REASONS: readonly HookTranscriptStopReason[] = ["cap", "deadline", "spool_full", "unavailable"];
|
|
7
8
|
export interface HookRecordCounts { recordValidRecords: number; recordBasisRecords: number; recordUnverifiedRecords: number }
|
|
8
|
-
export interface HookTranscriptProgress extends Partial<HookRecordCounts> { offset?: number; stopReason?: HookTranscriptStopReason }
|
|
9
|
+
export interface HookTranscriptProgress extends Partial<HookRecordCounts> { offset?: number; stopReason?: HookTranscriptStopReason; records?: RecordIntakeCounts }
|
|
9
10
|
export function isHookTranscriptProgress(value: unknown): value is HookTranscriptProgress {
|
|
10
11
|
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
|
|
11
12
|
const row = value as Record<string, unknown>;
|
|
12
|
-
return Object.keys(row).every(key => ["offset", "stopReason", "recordValidRecords", "recordBasisRecords", "recordUnverifiedRecords"].includes(key))
|
|
13
|
+
return Object.keys(row).every(key => ["offset", "stopReason", "recordValidRecords", "recordBasisRecords", "recordUnverifiedRecords", "records"].includes(key))
|
|
14
|
+
&& (row.records === undefined || isRecordIntakeCounts(row.records))
|
|
13
15
|
&& (["recordValidRecords", "recordBasisRecords", "recordUnverifiedRecords"].every(key => row[key] === undefined)
|
|
14
16
|
|| ["recordValidRecords", "recordBasisRecords", "recordUnverifiedRecords"].every(key => Number.isSafeInteger(row[key]) && (row[key] as number) >= 0)
|
|
15
17
|
&& (row.recordBasisRecords as number) <= (row.recordValidRecords as number) && (row.recordUnverifiedRecords as number) <= (row.recordValidRecords as number))
|
|
@@ -17,3 +19,17 @@ export function isHookTranscriptProgress(value: unknown): value is HookTranscrip
|
|
|
17
19
|
&& (row.offset === undefined || Number.isSafeInteger(row.offset) && (row.offset as number) >= 0)
|
|
18
20
|
&& (row.stopReason === undefined || (HOOK_TRANSCRIPT_STOP_REASONS as readonly string[]).includes(row.stopReason as string));
|
|
19
21
|
}
|
|
22
|
+
|
|
23
|
+
/** The worker protocol permits only bounded numeric receipts, never captured text. */
|
|
24
|
+
function isRecordIntakeCounts(value: unknown): value is RecordIntakeCounts {
|
|
25
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
|
|
26
|
+
const row = value as Record<string, unknown>;
|
|
27
|
+
const numeric = (n: unknown): n is number => Number.isSafeInteger(n) && (n as number) >= 0;
|
|
28
|
+
if (Object.keys(row).length !== 5 || !Object.keys(row).every(key => ["supported", "found", "staged", "duplicatesSkipped", "refused"].includes(key))
|
|
29
|
+
|| typeof row.supported !== "boolean" || !numeric(row.found) || !numeric(row.staged) || !numeric(row.duplicatesSkipped)
|
|
30
|
+
|| row.staged > row.found || row.duplicatesSkipped > row.found || (!row.supported && row.staged !== 0)
|
|
31
|
+
|| !row.refused || typeof row.refused !== "object" || Array.isArray(row.refused)) return false;
|
|
32
|
+
const reasons = ["record_invalid", "record_count", "record_length", "record_policy", "record_identity", "record_timestamp", "finality-unavailable"];
|
|
33
|
+
return Object.entries(row.refused).every(([reason, count]) => reasons.includes(reason) && numeric(count))
|
|
34
|
+
&& Object.values(row.refused).reduce<number>((sum, count) => sum + (count as number), 0) + row.staged + row.duplicatesSkipped <= row.found;
|
|
35
|
+
}
|
|
@@ -4,16 +4,17 @@ import { join } from "node:path";
|
|
|
4
4
|
import type { Database } from "bun:sqlite";
|
|
5
5
|
import { assertFormatFloor } from "./memory/formats.ts";
|
|
6
6
|
import { appendMetrics } from "./memory/metrics.ts";
|
|
7
|
-
import { configuredPolicyOptions } from "./memory/config.ts";
|
|
7
|
+
import { configuredPolicyOptions, recordsEnabled } from "./memory/config.ts";
|
|
8
8
|
import { canonicalPath, realPath } from "./memory/platform.ts";
|
|
9
9
|
import { createStandalonePolicy, type StandalonePolicyOptions } from "./memory/policy.ts";
|
|
10
10
|
import { HookSpoolFull, stageTranscriptCapture } from "./hook-spool.ts";
|
|
11
11
|
import { cursorDatabase, HOOK_TRANSCRIPT_BYTES, privateDirectory } from "./hook-transcript.ts";
|
|
12
|
+
import { parseRecordLines, recordIntakeCounts, recordRefusal, type RecordIntakeCounts, type RecordDropReason } from "./hook-record.ts";
|
|
12
13
|
import type { HookTranscriptProgress } from "./hook-contract.ts";
|
|
13
14
|
|
|
14
15
|
// #216: jcode writes `<sessions>/<stem>.journal.jsonl`, one `{"meta":{...},"append_messages":[...]}` line per save. Only `meta.title` and
|
|
15
|
-
// `meta.compaction.summary_text` are read
|
|
16
|
-
// before `,"append_messages"` (an unescaped quote cannot occur inside a JSON string, so that marker cannot hide in text).
|
|
16
|
+
// `meta.compaction.summary_text` are read for capture. Enabled Record receipts inspect only main assistant text; finality is unavailable,
|
|
17
|
+
// so no Record is staged. Snapshots and reasoning are never read for Records. Metadata is sliced out before `,"append_messages"` (an unescaped quote cannot occur inside a JSON string, so that marker cannot hide in text).
|
|
17
18
|
const hash = (value: string) => createHash("sha256").update(value).digest("hex");
|
|
18
19
|
const META = '{"meta":', BODIES = ',"append_messages"', TITLE_BYTES = 512;
|
|
19
20
|
const object = (value: unknown): Record<string, unknown> | undefined => value !== null && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : undefined;
|
|
@@ -43,6 +44,7 @@ export async function scanJcodeJournal(target: { cwd: string; session: string; j
|
|
|
43
44
|
const cwd = realPath(target.cwd), base = canonicalPath(options.base);
|
|
44
45
|
assertFormatFloor(base, "hook-spool");
|
|
45
46
|
const policy = createStandalonePolicy(configuredPolicyOptions(base, cwd, options.policy));
|
|
47
|
+
const intake = recordsEnabled(base, cwd) ? recordIntakeCounts(false) : undefined;
|
|
46
48
|
const session = hash(`amem-session\0${target.session}`).slice(0, 16);
|
|
47
49
|
if (!lstatSync(target.journal, { throwIfNoEntry: false })) return;
|
|
48
50
|
if (lstatSync(target.journal).isSymbolicLink()) throw new Error("jcode journal unavailable");
|
|
@@ -71,6 +73,7 @@ export async function scanJcodeJournal(target: { cwd: string; session: string; j
|
|
|
71
73
|
const workStart = clock();
|
|
72
74
|
const due = () => clock() >= options.deadline || options.workBudgetMs !== undefined && clock() - workStart >= options.workBudgetMs;
|
|
73
75
|
let unpublished = false, start = 0, skipping = partial, stopReason: HookTranscriptProgress["stopReason"], newestLine: string | undefined;
|
|
76
|
+
const recordLines: { end: number; counts: RecordIntakeCounts }[] = [];
|
|
74
77
|
const compactions: { covers: unknown; text: string; at: string | undefined; subagent: boolean; dir: unknown }[] = [];
|
|
75
78
|
// #216 review (codex P2): a row belongs to the project of its own line. A journal of a session that moved between projects carries other
|
|
76
79
|
// `meta.working_dir` values; those rows are not staged under this hook's cwd. A missing working_dir keeps the hook's cwd (unchanged).
|
|
@@ -91,11 +94,41 @@ export async function scanJcodeJournal(target: { cwd: string; session: string; j
|
|
|
91
94
|
if (start === 0 && length >= HOOK_TRANSCRIPT_BYTES) { skipping = true; start = length; oversized++; }
|
|
92
95
|
break;
|
|
93
96
|
}
|
|
97
|
+
const lineStart = start;
|
|
94
98
|
let line: string;
|
|
95
99
|
try { line = new TextDecoder("utf-8", { fatal: true }).decode(bytes.subarray(start, newline)); } catch { start = newline + 1; continue; }
|
|
96
100
|
start = newline + 1;
|
|
97
101
|
if (!line.startsWith(META)) continue;
|
|
98
102
|
const metaEnd = line.indexOf(BODIES, META.length), head = metaEnd >= 0 ? line.slice(0, metaEnd) : line;
|
|
103
|
+
if (intake && line.includes("amem:")) {
|
|
104
|
+
const meta = journalMeta(line);
|
|
105
|
+
if (meta?.parent_id === null && ownsDir(meta.working_dir)) {
|
|
106
|
+
let entry: Record<string, unknown> | undefined;
|
|
107
|
+
try { entry = object(JSON.parse(line)); } catch { /* malformed body does not change metadata capture */ }
|
|
108
|
+
const counts = recordIntakeCounts(false);
|
|
109
|
+
let incomplete = false;
|
|
110
|
+
if (Array.isArray(entry?.append_messages)) for (const value of entry.append_messages) {
|
|
111
|
+
if (due()) { incomplete = true; break; }
|
|
112
|
+
const message = object(value);
|
|
113
|
+
if (message?.role !== "assistant" || typeof message.id !== "string" || !message.id
|
|
114
|
+
|| message.display_role != null || !Array.isArray(message.content)) continue;
|
|
115
|
+
// Native tool-call, background and reasoning messages are not final-answer evidence.
|
|
116
|
+
const blocks = message.content.map(object);
|
|
117
|
+
if (!blocks.length || blocks.some(block => block?.type !== "text" || typeof block.text !== "string")) continue;
|
|
118
|
+
const parsed = parseRecordLines(blocks.map(block => block!.text as string).join("\n"), due);
|
|
119
|
+
if (parsed.incomplete) { incomplete = true; break; }
|
|
120
|
+
counts.found += parsed.records.length;
|
|
121
|
+
if (parsed.records.length) recordRefusal(counts, "finality-unavailable", parsed.records.length);
|
|
122
|
+
for (const [reason, count] of Object.entries(parsed.drops)) {
|
|
123
|
+
counts.found += count;
|
|
124
|
+
recordRefusal(counts, reason as RecordDropReason, count);
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
if (incomplete) { start = lineStart; stopReason = "deadline"; break; }
|
|
128
|
+
recordLines.push({ end: start, counts });
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
|
|
99
132
|
if (head.includes('"compaction":{')) {
|
|
100
133
|
const meta = journalMeta(line), compaction = object(meta?.compaction);
|
|
101
134
|
if (meta && compaction && typeof compaction.summary_text === "string" && compaction.summary_text.trim()) {
|
|
@@ -144,7 +177,16 @@ export async function scanJcodeJournal(target: { cwd: string; session: string; j
|
|
|
144
177
|
db.query("UPDATE cursor SET offset=?,dev=?,ino=?,size=?,title=?,at=?,skipping=? WHERE id=1")
|
|
145
178
|
.run(offset, String(stat.dev), String(stat.ino), stat.size, cursor.title, cursor.at, skipping ? 1 : 0);
|
|
146
179
|
db.run("COMMIT");
|
|
147
|
-
|
|
180
|
+
if (intake) {
|
|
181
|
+
// Only acknowledged forward bytes produce receipts; a retry never recounts an unpublished prefix.
|
|
182
|
+
for (const line of recordLines) if (from + line.end <= offset) {
|
|
183
|
+
intake.found += line.counts.found;
|
|
184
|
+
for (const [reason, count] of Object.entries(line.counts.refused)) recordRefusal(intake, reason as RecordDropReason | "finality-unavailable", count);
|
|
185
|
+
}
|
|
186
|
+
if (Object.keys(intake.refused).length) appendMetrics(base, Object.entries(intake.refused).map(([reason, count]) => ({ at: new Date().toISOString(), kind: "hook" as const,
|
|
187
|
+
captureDrops: count, captureDropReason: reason as RecordDropReason | "finality-unavailable" })));
|
|
188
|
+
}
|
|
189
|
+
return { offset, ...(stopReason ? { stopReason } : {}), ...(intake ? { records: intake } : {}) };
|
|
148
190
|
} finally {
|
|
149
191
|
if (db) try { db.run("ROLLBACK"); } catch { /* committed */ }
|
|
150
192
|
db?.close();
|
package/src/hook-record.ts
CHANGED
|
@@ -109,3 +109,21 @@ export function parseRecordLines(text: string, shouldStop?: () => boolean): Pars
|
|
|
109
109
|
}
|
|
110
110
|
return result;
|
|
111
111
|
}
|
|
112
|
+
|
|
113
|
+
/** Additive numeric intake receipt; an unsupported reader never turns text into capture. */
|
|
114
|
+
export type RecordIntakeRefusal = RecordDropReason | "finality-unavailable";
|
|
115
|
+
/**
|
|
116
|
+
* Whether a drop reason records a Record parsing refusal rather than a lost capture. Those stay observable metrics but
|
|
117
|
+
* never reach the SessionStart loss notice: a deliberate `finality-unavailable` refusal is not capture that went missing.
|
|
118
|
+
*/
|
|
119
|
+
export const recordRefusalReason = (reason: string): reason is RecordIntakeRefusal => reason.startsWith("record_") || reason === "finality-unavailable";
|
|
120
|
+
export interface RecordIntakeCounts {
|
|
121
|
+
supported: boolean; found: number; staged: number; duplicatesSkipped: number;
|
|
122
|
+
refused: Partial<Record<RecordIntakeRefusal, number>>;
|
|
123
|
+
}
|
|
124
|
+
export function recordIntakeCounts(supported = true): RecordIntakeCounts {
|
|
125
|
+
return { supported, found: 0, staged: 0, refused: {}, duplicatesSkipped: 0 };
|
|
126
|
+
}
|
|
127
|
+
export function recordRefusal(counts: RecordIntakeCounts, reason: RecordIntakeRefusal, count = 1): void {
|
|
128
|
+
counts.refused[reason] = (counts.refused[reason] ?? 0) + count;
|
|
129
|
+
}
|