@staix/agent-mem 0.29.0 → 0.30.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 (50) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/README.md +9 -7
  3. package/package.json +3 -2
  4. package/src/cli.ts +69 -10
  5. package/src/commands-table.ts +4 -0
  6. package/src/mcp-memory.ts +36 -8
  7. package/src/memory/bridge.ts +26 -1
  8. package/src/memory/capacity.ts +5 -2
  9. package/src/memory/catalog.ts +10 -1
  10. package/src/memory/doctor.ts +17 -14
  11. package/src/memory/formats.ts +4 -3
  12. package/src/memory/intent-brief.ts +34 -6
  13. package/src/memory/metrics.ts +173 -14
  14. package/src/memory/shard-bridge.ts +18 -6
  15. package/src/memory/shard-sync-format.ts +18 -0
  16. package/src/memory/shard-sync.ts +52 -4
  17. package/src/memory/sync-placement-bound.ts +21 -4
  18. package/src/memory/sync-placement-cache.ts +16 -1
  19. package/src/memory/sync-placement-capture.ts +14 -2
  20. package/src/memory/sync-placement-checkpoint-format.ts +199 -0
  21. package/src/memory/sync-placement-checkpoint-person.ts +209 -0
  22. package/src/memory/sync-placement-checkpoint-prospective.ts +141 -0
  23. package/src/memory/sync-placement-checkpoint-storage.ts +218 -0
  24. package/src/memory/sync-placement-checkpoint.ts +234 -0
  25. package/src/memory/sync-placement-dependencies.ts +42 -9
  26. package/src/memory/sync-placement-effective-writers.ts +12 -6
  27. package/src/memory/sync-placement-git.ts +17 -7
  28. package/src/memory/sync-placement-inspection-evidence.ts +1 -1
  29. package/src/memory/sync-placement-inventory.ts +5 -0
  30. package/src/memory/sync-placement-journal-format.ts +4 -1
  31. package/src/memory/sync-placement-journal-storage.ts +129 -26
  32. package/src/memory/sync-placement-materialize.ts +33 -19
  33. package/src/memory/sync-placement-projection.ts +7 -1
  34. package/src/memory/sync-placement-publication-events.ts +42 -0
  35. package/src/memory/sync-placement-publication-plan.ts +18 -1
  36. package/src/memory/sync-placement-realm-admission.ts +20 -3
  37. package/src/memory/sync-placement-realm-discovery.ts +42 -0
  38. package/src/memory/sync-placement-remote-admission.ts +190 -0
  39. package/src/memory/sync-placement-remote-adoption-format.ts +54 -0
  40. package/src/memory/sync-placement-remote-materialization.ts +49 -0
  41. package/src/memory/sync-placement-remote-refusal.ts +21 -0
  42. package/src/memory/sync-placement-remote-stage.ts +275 -0
  43. package/src/memory/sync-placement-transport.ts +202 -51
  44. package/src/memory/sync-placement-writer-history.ts +75 -17
  45. package/src/memory/sync-placement-writer-renewal.ts +18 -10
  46. package/src/memory/sync-placement-writer-revision-format.ts +16 -13
  47. package/src/memory/sync-placement-yield.ts +14 -0
  48. package/src/memory/sync.ts +4 -1
  49. package/src/sync-placement-writer-context.ts +5 -5
  50. package/src/ui/plugin.ts +1 -1
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agent-mem",
3
- "version": "0.29.0",
3
+ "version": "0.30.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.29.0. Requires Bun 1.4.2 or later; no runtime dependencies.
6
+ Version: 0.30.0. Requires Bun 1.4.2 or later; no runtime dependencies.
7
7
  <!-- /facts:version -->
8
8
 
9
9
  ## Quick start
@@ -92,7 +92,7 @@ Memory commands: `list`, `search`, `show`, `graph`, `suggestions`, `confirm`, `r
92
92
 
93
93
  `amem import codex` reads Codex's Markdown memory as review candidates. It supports both on-disk layouts: memories v1 under `$CODEX_HOME/memories` (else `~/.codex/memories`) and memories v2, the default for fresh profiles since Codex 0.165.0, under the sibling `memories_v2/` (`memory_summary.md`, `rollout_summaries/`, `extensions/`; v2 titles start with `memories_v2/`). The v2 SQLite state is never read. With `--from` only the given directory is read. When neither layout exists, the receipt names the locations it checked.
94
94
 
95
- Agent markers are honest-session identity context, not authentication. Marked `amem note add` writes use the existing peer field for attribution. An agent-marked session runs every amem command a person runs (#431): `doctor`, `project export`, history and as-of reads, `migrate --sync-placement` and the rest, with the same preview and `--confirm`/`--apply` steps; its reads keep the configured policy screen. Outbound publication (npm publish, release tags) still needs the person. Unmarked reads retain their existing unscreened behavior. `amem mcp` remains scoped to its startup project and can write only candidate and work-list data; hooks and ingest append capture only. Curated candidate acceptance and other CLI writes use the current configured policy. The CLI no longer has a general agent-marker refusal or stdin-TTY gate; use each command's explicit preview and `--confirm`/`--apply` flow where provided. `amem review walk` stays interactive and requires terminal input and output; `amem review decide <id> accept|reject|defer` is its non-interactive form: without `--confirm` it prints the candidate and its overlaps and marks it shown, and `--confirm` applies that one decision; `$EDITOR` opens only when a terminal is available.
95
+ Agent markers are honest-session identity context, not authentication. Marked `amem note add` writes use the existing peer field for attribution. An agent-marked session runs every amem command a person runs (#431): `doctor`, `project export`, history and as-of reads, `migrate --sync-placement` and the rest, with the same preview and `--confirm`/`--apply` steps; its reads keep the configured policy screen. Outbound publication (npm publish, release tags) still needs the person. Unmarked reads retain their existing unscreened behavior. `amem mcp` remains scoped to its startup project and can write only candidate and work-list data, plus content-free read-call telemetry; hooks and ingest append capture only. Curated candidate acceptance and other CLI writes use the current configured policy. The CLI no longer has a general agent-marker refusal or stdin-TTY gate; use each command's explicit preview and `--confirm`/`--apply` flow where provided. `amem review walk` stays interactive and requires terminal input and output; `amem review decide <id> accept|reject|defer` is its non-interactive form: without `--confirm` it prints the candidate and its overlaps and marks it shown, and `--confirm` applies that one decision; `$EDITOR` opens only when a terminal is available.
96
96
 
97
97
  ## Configuration and privacy policy
98
98
 
@@ -496,7 +496,7 @@ The MCP server exposes these tools. The nine-tool contract frozen for dotfiles#2
496
496
  | `amem_capacity` | yes | Read this machine's bounded capture capacity proposal; applying it requires the matching CLI preview and `--confirm`. |
497
497
  <!-- /facts:mcp-tools -->
498
498
 
499
- Search/show/timeline label capture as recall with `evidence: false`; capture never enters the curated graph. Policy screens complete rows before selection, limits or graph construction. The standalone secret screen, private flags, PII patterns and deny paths compose with a host's stricter policy through `createMemoryMcp({cwd, base, policy})`. Screening errors fail closed. `base` is the exact memory root; historical library `home` options still name its parent. Scope and profile changes refuse further access instead of silently reopening another store. Graph reads retain the 5,000-row curated ceiling; work-list reads stream the complete ordered history without an operation-count ceiling, applying policy before latest-value reduction. The working state scales with the current result, not historical payloads. The graph ceiling is an operational bound, not an exposed count of unscreened data. Graphs cover curated-note relationships, not goal/suggestion tables.
499
+ Search/show/timeline label capture as recall with `evidence: false`; capture never enters the curated graph. Search, show, timeline and graph screen complete rows before result selection, limits or graph construction. The intent brief first selects candidates by plan-node references or, without them, intent-word matches in titles and text; it then screens each row before it can contribute a line or bridge to a neighbour; at most 96 candidates are screened and exceeding that cap reports truncation. The standalone secret screen, private flags, PII patterns and deny paths compose with a host's stricter policy through `createMemoryMcp({cwd, base, policy})`. Screening errors fail closed. `base` is the exact memory root; historical library `home` options still name its parent. Scope and profile changes refuse further access instead of silently reopening another store. Graph reads retain the 5,000-row curated ceiling; work-list reads stream the complete ordered history without an operation-count ceiling, applying policy before latest-value reduction. The working state scales with the current result, not historical payloads. The graph ceiling is an operational bound, not an exposed count of unscreened data. Graphs cover curated-note relationships, not goal/suggestion tables.
500
500
 
501
501
  `WorkListStore` writes `projects/<key-hash>/work/` with its own append log, derived index and lock. Scalar fields reduce by latest value, null clears, list status `done` closes, and item status is `todo|doing|done|dropped`. Work lists are outside generation selection and capture eviction. `amem import claude-mem` additionally imports `work_state_entries` only through persisted D2 aliases, preserving source DB bytes and stable replay receipts; JSON keeps observation fields and adds `work` counts/cursor. `--capture-days N` also imports observations and session summaries from the last N days into machine-local capture under the same aliases, with read/added/spooled/skipped counts, stable replay receipts and the configured capture cap and retention. Widening N after an earlier import requires `--restart` to revisit rows below the saved cursor. Chroma vectors are never read.
502
502
 
@@ -588,9 +588,9 @@ Since 0.23.0, native Claude SessionStart can prepend the package-owned `RECORD_I
588
588
 
589
589
  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.
590
590
 
591
- 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.
591
+ 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 and spool events/status values are unchanged; general resource metrics use the per-kind rolling window below. 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.
592
592
 
593
- 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.
593
+ 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 64 KiB trim trigger; a trim keeps up to the newest 200 samples per kind.
594
594
 
595
595
  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.
596
596
 
@@ -623,10 +623,12 @@ Dry-run shows root versions/pins and safe policy counts, never row text or patte
623
623
 
624
624
  A long first sync reports its phase, row counters and last progress on stderr when stderr is a terminal (`--progress json` for one versioned event per line, `--progress off` to silence it); stdout and `--json` output are unchanged. From another terminal, `amem sync --status` shows running, finished or interrupted operations without opening memory or taking a lock. One placement sync covers the effective home-wide inventory, publishing the user realm first and then project realms in key-hash order in batches of at most two realms. A failed publication stops the run; a retry resumes it first. Activation and each publication share a 64 MiB/20000-row source envelope; a refusal names its phase, bound kind, limit and observed size.
625
625
 
626
- To add a curated project realm that appears after activation, preview `amem migrate --sync-placement --admit <project> --dry-run`, then use `--apply` if the preview is acceptable. An interrupted admission uses `--resume`; `--abandon` previews removal of eligible unpublished intent bytes and `--abandon --confirm` applies that removal. It appends a same-epoch inventory extension and does not rewrite activation metadata. Discovery of a realm that exists only on the remote remains out of scope. See [the admission contract](docs/contracts.md#person-reviewed-realm-admission-448).
626
+ To add a curated project realm that appears after activation, preview `amem migrate --sync-placement --admit <project> --dry-run`, then use `--apply` if the preview is acceptable. An interrupted admission uses `--resume`; `--abandon` previews removal of eligible unpublished intent bytes and `--abandon --confirm` applies that removal. It appends a same-epoch inventory extension and does not rewrite activation metadata. To discover remote-only curated project realms, run `amem migrate --sync-placement --list-remote`; it reports scope and key hash only, using the already configured private placement remote. Map a hash to a project key yourself, then preview `amem migrate --sync-placement --admit <project> --from-remote --dry-run` and use `--apply` to adopt it. Targeted rows withheld by a remote prune witness are omitted from the staged subset; the receipt counts omissions and names `amem sync` as the next step to import the remaining history and witnesses. The standard `--resume` and `--abandon` commands recognize a retained remote operation. See [the remote admission contract](docs/contracts.md#remote-only-realm-discovery-and-admission-461).
627
627
 
628
- A placement sync that refuses before any publication attempt names the failing check by a fixed category (`epoch`, `source-selection`, `policy`, `remote`, `writer-pin`, `size-bound`, `lock` or `other`) and the phase, with one next step; the result carries `placementPublication.refusal` and `amem sync --status` shows the category. No path, row or remote URL is printed (#426). Failed placement syncs also expose a closed `failure.cause` in the library result; the existing error text is unchanged (#462).
628
+ A placement sync that returns a refusal before publication names the failing check by a fixed category (`epoch`, `source-selection`, `policy`, `remote`, `writer-pin`, `size-bound`, `lock` or `other`) and the phase, with one next step; the result carries `placementPublication.refusal` and `amem sync --status` shows the category. No path, row or remote URL is printed (#426). Returned failures also expose a closed `failure.cause` in the library result (#462). Some early inventory failures instead throw before publication; for example an unknown epoch member raises `SyncPlacementJournalError` with code `corrupt` (#492).
629
629
 
630
630
  On an active home, the same dry-run/apply commands explicitly renew the writer inventory on its existing epoch (#282). Declare the complete new 0.22.0-or-later roots after updating host pins and managed setup receipts. Ordinary and cadence sync then locate the new inventory and measure it afresh; original activation data, holds and prior receipts are unchanged. Pending publication or source-recovery work must first be finished with the inventoried install, for example after `dot ai rollback amem` or restoring the host's previous pin.
631
631
 
632
632
  An interrupted renewal resumes only its exact intent. Before commit append starts, person `--abandon` can discard its unpublished metadata; after the first commit-log byte, only forward resume is supported. Unpublished intent staging requires explicit `--abandon`, then a fresh dry-run; it is never cleaned automatically. Compatible ordinary reads remain available while only renewal metadata is pending. After a crash, a retained `profile.lock` still blocks new reader admission until person `--resume` or, before commit append, `--abandon`. Never edit activation files, downgrade markers or start another epoch to discard a hold. See the [renewal contract](docs/contracts.md#same-epoch-writer-inventory-renewal-282). Real-home renewal and release remain separately authorized person operations.
633
+
634
+ When the live window reaches its revision or object bound, preview `amem migrate --sync-placement --checkpoint --writer-root '<install-root>' --json` with every writer root. The preview reports whether a new window leaves enough room for a renewal and the next observed plan; a plan too large for one window needs the separate multi-plan work. Confirming the saved preview requires a person-written `home` floor of 0.30.0 or later and every writer at or above the recorded floors. The checkpoint preserves the frozen history and carries one writer renewal into the new window. An interrupted checkpoint uses `--checkpoint --resume`, or `--checkpoint --abandon` before the first commit byte. See the [checkpoint contract](docs/contracts.md#placement-history-checkpoint-windows-288).
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@staix/agent-mem",
3
- "version": "0.29.0",
3
+ "version": "0.30.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",
@@ -27,7 +27,8 @@
27
27
  "bun-types-host-1-4-2": "npm:bun-types@1.4.2",
28
28
  "@staix/agent-mem-v0220": "npm:@staix/agent-mem@0.22.0",
29
29
  "@types/bun-host-1-4-2": "npm:@types/bun@1.4.2",
30
- "@staix/agent-mem-v0221": "npm:@staix/agent-mem@0.22.1"
30
+ "@staix/agent-mem-v0221": "npm:@staix/agent-mem@0.22.1",
31
+ "@staix/agent-mem-v0290": "npm:@staix/agent-mem@0.29.0"
31
32
  },
32
33
  "exports": {
33
34
  ".": "./src/index.ts",
package/src/cli.ts CHANGED
@@ -5,7 +5,7 @@ import { readActivePlacementBinding } from "./memory/sync-placement-active.ts";
5
5
  import { activatePublicPruneView } from "./memory/public-prune-activation.ts";
6
6
  import { AgentUsageError, agentCliRead } from "./cli-agent-reads.ts";
7
7
  import { cliAttribution, withCliAttribution } from "./memory/cli-attribution.ts";
8
- import { randomUUID } from "node:crypto";
8
+ import { createHash, randomUUID } from "node:crypto";
9
9
  import type { Writable } from "node:stream";
10
10
  import { buildIntentBrief } from "./memory/intent-brief.ts";
11
11
  import { proposeConsolidation } from "./memory/consolidate.ts";
@@ -16,6 +16,7 @@ import { recordMemoryUse } from "./memory/use-telemetry.ts";
16
16
  import { DecayApplyError } from "./memory/decay-review.ts";
17
17
  import { createMemoryMcp } from "./mcp-memory.ts";
18
18
  import { safeProfileLockMessage } from "./memory/profile-lock-diagnostic.ts";
19
+ import { PLACEMENT_CHECKPOINT_PENDING_MESSAGE } from "./memory/sync-placement-journal-format.ts";
19
20
  import { MCP_TOOLS, serveMcp, writeConfirmed } from "./mcp.ts";
20
21
  import { createStandalonePolicy } from "./memory/policy.ts";
21
22
  import { configuredPolicy, configuredPolicyOptions, loadAmemConfig, repoConfigRoot } from "./memory/config.ts";
@@ -41,6 +42,7 @@ import { COMMANDS, commandHelp, parseCommand } from "./commands-table.ts";
41
42
  import { completionScript } from "./completion.ts";
42
43
  import { memoryHome, resolveMemoryHome } from "./memory/home.ts";
43
44
  import { realPath } from "./memory/platform.ts";
45
+ import { RemoteRealmRefusal } from "./memory/sync-placement-remote-refusal.ts";
44
46
  import { hashJSON, readSelector, resolveProfile } from "./memory/generation.ts";
45
47
  import { migrate, migrationText } from "./memory/migrate.ts";
46
48
  import { migrateShards, shardMigrationStatus, shardMigrationText } from "./memory/shard-migration.ts";
@@ -122,13 +124,13 @@ const planFileIO: PrunePlanFileIO = {
122
124
  };
123
125
 
124
126
  /** Open once: pathname replacement cannot redirect the read and growth cannot exceed the fixed byte budget. */
125
- export function readPrunePlanFile(path: string, io: PrunePlanFileIO = planFileIO): string {
127
+ export function readPrunePlanFile(path: string, io: PrunePlanFileIO = planFileIO, maximum = PRUNE_PLAN_MAX_BYTES): string {
126
128
  try {
127
129
  const fd = io.open(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
128
130
  try {
129
131
  const before = io.stat(fd);
130
- if (!before.isFile() || !Number.isSafeInteger(before.size) || before.size < 0 || before.size > PRUNE_PLAN_MAX_BYTES) throw new Error();
131
- const data = Buffer.alloc(PRUNE_PLAN_MAX_BYTES + 1);
132
+ if (!before.isFile() || !Number.isSafeInteger(before.size) || before.size < 0 || before.size > maximum) throw new Error();
133
+ const data = Buffer.alloc(maximum + 1);
132
134
  let length = 0;
133
135
  while (length < data.length) {
134
136
  const n = io.read(fd, data, length, data.length - length, length);
@@ -136,7 +138,7 @@ export function readPrunePlanFile(path: string, io: PrunePlanFileIO = planFileIO
136
138
  if (n === 0) break;
137
139
  length += n;
138
140
  }
139
- if (length > PRUNE_PLAN_MAX_BYTES) throw new Error();
141
+ if (length > maximum) throw new Error();
140
142
  const after = io.stat(fd);
141
143
  if (!after.isFile() || after.size !== before.size || length !== before.size) throw new Error();
142
144
  return new TextDecoder("utf-8", { fatal: true }).decode(data.subarray(0, length));
@@ -324,7 +326,7 @@ export async function runCli(argv: readonly string[], context: CliContext = {}):
324
326
  }
325
327
  }
326
328
  return output;
327
- }).catch((error: unknown) => {
329
+ }).catch(async (error: unknown) => {
328
330
  // Preserve the authoritative partial outcome, without exposing a cause or a withheld target.
329
331
  if (marked && error instanceof DecayApplyError) {
330
332
  let readable = false;
@@ -334,6 +336,11 @@ export async function runCli(argv: readonly string[], context: CliContext = {}):
334
336
  }
335
337
  // Data-free errors (decided before any store or file is opened) keep their own message.
336
338
  if (marked && error instanceof AgentUsageError) throw error;
339
+ if (marked && error instanceof RemoteRealmRefusal) throw error;
340
+ // The checkpoint pending message is a fixed data-free remedy shared by journal and writer guards.
341
+ if (marked && error instanceof Error && error.message === PLACEMENT_CHECKPOINT_PENDING_MESSAGE) throw new Error(PLACEMENT_CHECKPOINT_PENDING_MESSAGE);
342
+ // #288 step 3: checkpoint refusals are fixed cause-and-next-step strings with numbers only (no path, row or project).
343
+ if (marked && error instanceof Error && error.name === "PlacementCheckpointError" && error instanceof (await import("./memory/sync-placement-checkpoint-person.ts")).PlacementCheckpointError) throw new Error(error.message);
337
344
  const recovery=marked?safeProfileLockMessage(error):undefined;if(recovery)throw new Error(recovery);
338
345
  if (marked) {
339
346
  // parseCommand is pure: when it rejects argv, the error it raised is a usage error, not memory data.
@@ -408,14 +415,26 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
408
415
  const modes = ["--dry-run","--apply","--resume","--abandon","--deactivate"].filter(key=>options[key]===true);
409
416
  if (modes.length>1 || parsed.positionals.length || ["--shards","--public-prune-view","--generation","--deactivate"].some(key=>options[key]!==undefined))
410
417
  throw new AgentUsageError("Sync placement is a home-wide forward-only migration; use only --sync-placement with --dry-run, --apply, --resume or pre-marker --abandon and the writer roots, never combine migration families or deactivate.");
411
- if (options["--admit"] !== undefined) {
418
+ if (options["--list-remote"] === true && (modes.length || options["--admit"] !== undefined || options["--from-remote"] === true || options["--writer-root"] !== undefined || options["--confirm"] === true || options["--checkpoint"] === true || options["--plan"] !== undefined))
419
+ throw new AgentUsageError("Remote realm listing uses only --sync-placement --list-remote and optional --json.");
420
+ if (options["--from-remote"] === true && options["--admit"] === undefined)
421
+ throw new AgentUsageError("--from-remote requires --sync-placement --admit <project>.");
422
+ if (options["--checkpoint"] === true) {
423
+ // #288 step 3: preview (default), --confirm --plan, --resume or --abandon; one mode at a time.
424
+ const chosen = [options["--confirm"] === true, options["--resume"] === true, options["--abandon"] === true].filter(Boolean).length;
425
+ if (options["--admit"] !== undefined || options["--list-remote"] === true || options["--from-remote"] === true || options["--apply"] === true || options["--dry-run"] === true || chosen > 1 || (options["--confirm"] === true) !== (options["--plan"] !== undefined)
426
+ || (options["--resume"] === true || options["--abandon"] === true) && options["--writer-root"] !== undefined)
427
+ throw new AgentUsageError("A placement checkpoint uses --sync-placement --checkpoint --writer-root <install root> (repeat) to preview, then --confirm --plan <saved preview JSON> with the same writer roots, or --resume / --abandon alone.");
428
+ } else if (options["--plan"] !== undefined) {
429
+ throw new AgentUsageError("--plan applies only to --sync-placement --checkpoint --confirm.");
430
+ } else if (options["--admit"] !== undefined) {
412
431
  if (options["--writer-root"] !== undefined || options["--confirm"] === true && options["--abandon"] !== true)
413
432
  throw new AgentUsageError("Admitting one realm uses only --sync-placement --admit <project> with --dry-run, --apply, --resume or --abandon --confirm; writer roots belong to initial activation.");
414
433
  } else if (options["--confirm"] === true) {
415
- throw new AgentUsageError("--confirm applies only to --sync-placement --admit <project> --abandon; other placement modes keep their own confirmation.");
434
+ throw new AgentUsageError("--confirm applies only to --sync-placement --admit <project> --abandon or --sync-placement --checkpoint --plan <file>; other placement modes keep their own confirmation.");
416
435
  }
417
- } else if (parsed.path[0] === "migrate" && (options["--writer-root"] !== undefined||options["--abandon"]!==undefined||options["--admit"]!==undefined)) {
418
- throw new AgentUsageError("--writer-root, --abandon and --admit apply only to --sync-placement; run amem migrate --sync-placement --dry-run to review the inventory.");
436
+ } else if (parsed.path[0] === "migrate" && (options["--writer-root"] !== undefined||options["--abandon"]!==undefined||options["--admit"]!==undefined||options["--list-remote"]!==undefined||options["--from-remote"]!==undefined||options["--checkpoint"]!==undefined||options["--plan"]!==undefined)) {
437
+ throw new AgentUsageError("--writer-root, --abandon, --admit, --list-remote, --from-remote, --checkpoint and --plan apply only to --sync-placement; run amem migrate --sync-placement --dry-run to review the inventory.");
419
438
  }
420
439
  if (parsed.path[0] === "setup") {
421
440
  if (parsed.positionals.length !== 1 || options["--apply"] === true && options["--undo"] === true
@@ -518,9 +537,49 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
518
537
  if (modes.length > 1) throw new Error("migration modes are mutually exclusive");
519
538
  const mode = options["--apply"] ? "apply" : options["--resume"] ? "resume" : options["--deactivate"] ? "deactivate" : "dry-run";
520
539
  if (options["--sync-placement"] === true) {
540
+ if (options["--list-remote"] === true) {
541
+ const { discoverRemotePlacementRealms } = await import("./memory/sync-placement-transport.ts");
542
+ const realms = await discoverRemotePlacementRealms(memoryHome(), { ...(context.visibility ? { visibility: context.visibility } : {}) });
543
+ const nextStep = "amem migrate --sync-placement --admit <project> --from-remote --dry-run";
544
+ return options["--json"] === true ? JSON.stringify({ realms, nextStep }, null, 2) : `${realms.map(realm => `scope=${realm.scope} keyHash=${realm.keyHash}; next ${nextStep}`).join("\n") || "no remote-only placement realms"}`;
545
+ }
546
+ if (options["--checkpoint"] === true) {
547
+ const person = await import("./memory/sync-placement-checkpoint-person.ts");
548
+ const writerRoots = repeated(argv, "--writer-root"), ownRoot = fileURLToPath(new URL("..", import.meta.url));
549
+ if (options["--resume"] === true) { const r = await person.resumePlacementCheckpointPerson(memoryHome()); return options["--json"] === true ? JSON.stringify(r, null, 2) : `sync placement checkpoint: ${r.resumed ? "resumed" : "nothing pending"}; window ${r.window}\nnext: ${r.nextStep}\n`; }
550
+ if (options["--abandon"] === true) { const r = await person.abandonPlacementCheckpointPerson(memoryHome()); return options["--json"] === true ? JSON.stringify(r, null, 2) : `sync placement checkpoint: ${r.abandoned ? `abandoned (${r.removed} staged files removed)` : "nothing pending"}\nnext: ${r.nextStep}\n`; }
551
+ if (options["--confirm"] === true) {
552
+ let saved: unknown;
553
+ try { saved = JSON.parse(readPrunePlanFile(String(options["--plan"]), undefined, 4 * 1024 * 1024)); } catch { throw new Error("The checkpoint --plan file is unreadable or not the saved preview JSON; rerun amem migrate --sync-placement --checkpoint --json with the writer roots and save its output."); }
554
+ const r = await person.confirmPlacementCheckpoint(memoryHome(), saved, { writerRoots, ownRoot });
555
+ return options["--json"] === true ? JSON.stringify(r, null, 2) : `sync placement checkpoint: committed window ${r.window} with one writer renewal (plan ${r.planHash})\nnext: ${r.nextStep}\n`;
556
+ }
557
+ const preview = await person.previewPlacementCheckpoint(memoryHome(), { writerRoots, ownRoot });
558
+ if (options["--json"] === true) return JSON.stringify(preview, null, 2);
559
+ const { placementJournalObjectCompositionText } = await import("./memory/sync-placement-journal-storage.ts"), h = preview.headroom;
560
+ // Counts and hashes only; the sealed plan itself is in --json for the confirm step.
561
+ return `sync placement checkpoint preview: window ${preview.window} -> ${preview.nextWindow}; ${preview.currentObjects} of ${h.limit} live objects now\n`
562
+ + `${placementJournalObjectCompositionText(preview.journalObjects)}\n`
563
+ + `completed plan: ${h.completedPlan.slots} slots + ${h.completedPlan.reservedJournalChunks} reserved journal chunks; prospective plan: ${h.prospectivePlan.state === "cache-only" ? `${h.prospectivePlan.slots} slots + ${h.prospectivePlan.reservedJournalChunks} reserved journal chunks (cache-only; remote may have changed)` : h.prospectivePlan.state === "none" ? "none" : "unavailable without current remote evidence; using completed history"}\n`
564
+ + `headroom after checkpoint: ${h.remaining} of ${h.limit} (live ${h.liveAfter}, next renewal ${h.nextRenewal}, largest plan ${h.largestPlan.slots} + ${h.largestPlan.reservedJournalChunks} reserved journal chunks)\n`
565
+ + `home floor ${preview.requiredHomeFloor}: ${preview.floorReady ? "ready" : `missing; preview amem formats raise home ${preview.requiredHomeFloor}, then --confirm it`}; writers ${preview.writers}; plan ${preview.planHash}\n`
566
+ + `next: save this preview with --json, then ${preview.nextStep}\n`;
567
+ }
521
568
  if (options["--admit"] !== undefined) {
522
569
  const { previewRealmAdmission, planRealmAbandon, applyRealmAdmission } = await import("./memory/sync-placement-realm-admission.ts");
523
570
  const project = String(options["--admit"]);
571
+ const { readRemoteAdoption, inspectRemoteAdoptionPending, pendingRemoteAdoptions } = await import("./memory/sync-placement-remote-stage.ts");
572
+ const realm = createHash("sha256").update(project).digest("hex"), recovery = options["--resume"] === true || options["--abandon"] === true;
573
+ const pending = recovery ? pendingRemoteAdoptions(memoryHome()) : undefined;
574
+ const remotePending = recovery && (!!readRemoteAdoption(memoryHome(), realm) || inspectRemoteAdoptionPending(memoryHome(), realm).length > 0 || !!pending?.unknown || !!pending?.hashes.includes(realm));
575
+ if (options["--from-remote"] === true || remotePending) {
576
+ const { remoteRealmAdmission } = await import("./memory/sync-placement-remote-admission.ts");
577
+ const result = await remoteRealmAdmission(memoryHome(), project, { mode: options["--apply"] === true ? "apply" : options["--resume"] === true ? "resume" : options["--abandon"] === true ? "abandon" : "dry-run",
578
+ ...(options["--confirm"] === true ? { confirm: true } : {}), ...(context.visibility ? { visibility: context.visibility } : {}) });
579
+ if (result.state === "preview") result.nextStep = "amem migrate --sync-placement --admit <project> --from-remote --apply";
580
+ if (options["--json"] === true) return JSON.stringify(result, null, 2);
581
+ return `sync placement remote admission: ${result.state}; realm ${result.realm}${result.remoteHead ? `; remote head ${result.remoteHead}` : ""}${result.omitted !== undefined ? `; omitted ${result.omitted}` : ""}${result.nextStep ? `; next ${result.nextStep}` : ""}\n`;
582
+ }
524
583
  const result = options["--apply"] === true ? await applyRealmAdmission(memoryHome(), project, { mode: "apply" })
525
584
  : options["--resume"] === true ? await applyRealmAdmission(memoryHome(), project, { mode: "resume" })
526
585
  : options["--abandon"] === true ? options["--confirm"] === true ? await applyRealmAdmission(memoryHome(), project, { mode: "abandon", confirm: true })
@@ -121,9 +121,13 @@ export const COMMANDS: Record<string, CommandDefinition> = {
121
121
  "--shards": flag("Migrate the curated home into project and user shards"),
122
122
  "--public-prune-view": flag("Enable the forward-only v2 public prune view on an active split"),
123
123
  "--sync-placement": flag("Person-only forward-only placement activation on this memory home; no automatic migration or renewal"),
124
+ "--list-remote": flag("List remote placement project refs outside the active inventory by hash"),
124
125
  "--abandon": flag("Person-only: discard an interrupted sync-placement attempt only before either v3 marker is installed"),
125
126
  "--admit": text("Admit one curated project realm that appeared after activation into the same epoch; previews without --apply"),
127
+ "--from-remote": flag("Admit the named remote-only realm using the configured placement sync remote"),
126
128
  "--confirm": flag("Confirm the previewed realm admission abandonment"),
129
+ "--checkpoint": flag("Person-reviewed placement checkpoint: preview by default, then --confirm --plan, --resume or --abandon"),
130
+ "--plan": { description: "Saved --checkpoint --json preview to confirm", value: "path" },
127
131
  "--writer-root": { description: "Repeatable absolute amem install root in the complete local writer inventory", value: "path" },
128
132
  } },
129
133
  status: { description: "Report shard migration and pending old-layout appends", options: json },
package/src/mcp-memory.ts CHANGED
@@ -14,6 +14,7 @@ import { capacityReport } from "./memory/capacity.ts";
14
14
  import { CaptureStore, type CaptureRow } from "./memory/capture.ts";
15
15
  import { hashJSON, readSelector } from "./memory/generation.ts";
16
16
  import { memoryHome } from "./memory/home.ts";
17
+ import { appendMetricsLater, createPeakTracker } from "./memory/metrics.ts";
17
18
  import { canonicalPath, realPath } from "./memory/platform.ts";
18
19
  import { createStandalonePolicy, type StandalonePolicy, type StandalonePolicyOptions } from "./memory/policy.ts";
19
20
  import { configuredPolicyOptions } from "./memory/config.ts";
@@ -341,17 +342,44 @@ export function createMemoryMcp(options: MemoryMcpOptions): MemoryMcp {
341
342
  };
342
343
  const exposed = { ...tools };
343
344
  const readTools = ["amem_search", "amem_evidence", "amem_show", "amem_timeline", "amem_graph", "amem_brief", "amem_vault_candidates"] as const;
345
+ // #485: the process peak is monotonic, so a call can be credited with raising it only when no other read call was
346
+ // in flight while it grew; the tracker owns that rule and the observed baseline.
347
+ const peaks = createPeakTracker();
344
348
  for (const name of readTools) exposed[name] = async args => {
345
- fullGuard();
346
- const configured = policyOptions(), revision = policyKey(configured), snapshot = createStandalonePolicy(configured);
347
- const sourceCurrent = store.beginRecallRead();
348
- if (policyKey(policyOptions()) !== revision) return unavailable();
349
- return calls.run({ policy: snapshot, revision, configured }, async () => {
350
- const result = await tools[name](args);
351
- fullGuard(); sourceCurrent();
349
+ // #485: the sample measures the served span, so the clock and the peak window open at entry, before the guard, the
350
+ // policy snapshot and `beginRecallRead()` - whose preparation (an index refresh, a prune) the caller waits for.
351
+ const started = performance.now();
352
+ let window: ReturnType<typeof peaks.begin> | undefined;
353
+ try { window = peaks.begin(); } catch { /* telemetry is an observation, never a precondition */ }
354
+ // One bounded sample per completed call: the tool name, the wall time and the process peak. Never the arguments,
355
+ // the query text, an id or a result. It is handed off, not written: the response is queued first and the write is
356
+ // asynchronous, so telemetry can neither fail, refuse, delay nor block a completed call on disk.
357
+ const recorded = (): void => {
358
+ try {
359
+ const ended = window === undefined ? undefined : peaks.end(window);
360
+ window = undefined;
361
+ if (ended?.peakKB === undefined) return;
362
+ appendMetricsLater(base, [{ at: new Date().toISOString(), kind: "search", tool: name, wallMs: performance.now() - started, rssMB: ended.peakKB / 1024, peakRaised: ended.raised }]);
363
+ } catch { /* a lost telemetry sample is never a failed call */ }
364
+ };
365
+ try {
366
+ fullGuard();
367
+ const configured = policyOptions(), revision = policyKey(configured), snapshot = createStandalonePolicy(configured);
368
+ const sourceCurrent = store.beginRecallRead();
352
369
  if (policyKey(policyOptions()) !== revision) return unavailable();
370
+ const result = await calls.run({ policy: snapshot, revision, configured }, async () => {
371
+ const value = await tools[name](args);
372
+ fullGuard(); sourceCurrent();
373
+ if (policyKey(policyOptions()) !== revision) return unavailable();
374
+ return value;
375
+ });
376
+ recorded();
353
377
  return result;
354
- });
378
+ } catch (error) {
379
+ // A refused or failed call records nothing, but the peak it may have raised still advances the baseline.
380
+ try { if (window !== undefined) peaks.abort(window); } catch { /* nothing recorded, nothing to correct */ }
381
+ throw error;
382
+ }
355
383
  };
356
384
  return { tools: exposed, close, onEmitted };
357
385
  } catch (error) { close(); throw error; }
@@ -4,6 +4,7 @@ import { closeSync, constants, fstatSync, fsyncSync, linkSync, lstatSync, mkdirS
4
4
  import { basename, dirname, join } from "node:path";
5
5
  import { isDeepStrictEqual } from "node:util";
6
6
  import { memoryGitArgv, memoryGitEnv, realPath } from "./platform.ts";
7
+ import { drainSteps } from "./sync-placement-yield.ts";
7
8
  import { canonicalJSON, fsyncDirectory, readProfileJSON, writeProfileJSON } from "./generation.ts";
8
9
  import { OP_CONTRACTS } from "./ops-contract.ts";
9
10
  import type { InspectionBound } from "./inspection-bound.ts";
@@ -193,10 +194,20 @@ export function* completeLines(bytes: Buffer): Generator<Buffer> {
193
194
 
194
195
  /** Preserve original IDs; row order and JSON key order never produce duplicate evidence. */
195
196
  export function legacyEntries(segments: readonly LegacySegment[], options: { strict?: boolean; onMalformed?: () => void } = {}): Entry[] {
197
+ return drainSteps(legacyEntrySteps(segments, options));
198
+ }
199
+
200
+ /** Rows between step boundaries: one row's own canonicalisation and id check is the floor of an uninterrupted stretch. */
201
+ const LEGACY_ENTRY_STEP_LINES = 512;
202
+
203
+ /** #462: the same validation, handing the caller's event loop back every few hundred rows instead of once per read. */
204
+ export function* legacyEntrySteps(segments: readonly LegacySegment[], options: { strict?: boolean; onMalformed?: () => void } = {}): Generator<void, Entry[], void> {
196
205
  const rows = new Map<string, Entry>();
206
+ let stepped = 0;
197
207
  for (const segment of segments) {
198
208
  if (segment.bytes.length !== segment.offset || digest(segment.bytes) !== segment.hash || segment.offset && segment.bytes.at(-1) !== 10) failure();
199
209
  for (const bytes of completeLines(segment.bytes)) {
210
+ if (++stepped >= LEGACY_ENTRY_STEP_LINES) { stepped = 0; yield; }
200
211
  let row: Entry;
201
212
  try {
202
213
  let line: string;
@@ -225,6 +236,13 @@ function inspectArchivedSegment(inspect: LegacySegmentInspector, file: string, c
225
236
 
226
237
  /** Raw authoritative inputs only: never constructs a legacy store, opens its index or performs network I/O. */
227
238
  function snapshot(homeM: string, options: LegacySnapshotOptions, inspect?: LegacySegmentInspector): LegacySegment[] {
239
+ return drainSteps(snapshotSteps(homeM, options, inspect));
240
+ }
241
+ /**
242
+ * #462: the same read, written once as steps so a caller that owns a collector yields between legacy segments instead of
243
+ * inside one call. Every fence, receipt check and row validation stays in the same order.
244
+ */
245
+ function* snapshotSteps(homeM: string, options: LegacySnapshotOptions, inspect?: LegacySegmentInspector): Generator<void, LegacySegment[], void> {
228
246
  const root = realPath(homeM);
229
247
  directory(root);
230
248
  if (inspect && (options.incremental || options.limits)) failure();
@@ -248,6 +266,7 @@ function snapshot(homeM: string, options: LegacySnapshotOptions, inspect?: Legac
248
266
  const machineId = (machine as { id?: unknown } | undefined)?.id;
249
267
  if (typeof machineId !== "string" || !/^[a-f0-9]{16}$/.test(machineId)) failure();
250
268
  for (const folder of ["log", "local"]) {
269
+ yield;
251
270
  const dir = join(root, folder);
252
271
  if (!directory(dir, true)) continue;
253
272
  for (const name of options.reader ? options.reader.listFiles(dir) : readdirSync(dir).sort()) {
@@ -255,6 +274,7 @@ function snapshot(homeM: string, options: LegacySnapshotOptions, inspect?: Legac
255
274
  const path = `${folder}/${name}`;
256
275
  if (!segmentPath(path)) failure();
257
276
  if (folder === "local" && name !== `${machineId}.jsonl`) continue;
277
+ yield;
258
278
  if (inspect) {
259
279
  result.push(inspect(join(dir, name), { source: diskSource, path, local: folder === "local" }, checkpoints.get(`${diskSource}:${path}`)));
260
280
  continue;
@@ -275,6 +295,7 @@ function snapshot(homeM: string, options: LegacySnapshotOptions, inspect?: Legac
275
295
  directory(join(archiveDir(root, options.generation, commit), "log"));
276
296
  for (const prior of new Set([...(options.previousCommit ? [options.previousCommit] : []), ...[...checkpoints.values()].filter(row => row.source === remoteSource).map(row => row.commit!)])) if (!archivedAncestor(root, options.generation, prior, commit, options.reader?.sourceByteLimit)) failure();
277
297
  for (const segment of manifest.segments) {
298
+ yield;
278
299
  if (inspect) {
279
300
  result.push(inspectArchivedSegment(inspect, join(archiveDir(root, options.generation, commit), segment.path),
280
301
  { source: remoteSource, path: segment.path, local: false, commit }, checkpoints.get(`${remoteSource}:${segment.path}`), segment));
@@ -298,7 +319,7 @@ function snapshot(homeM: string, options: LegacySnapshotOptions, inspect?: Legac
298
319
  const bytes = segment.bytes.subarray(Math.max(0, start - (segment.start ?? 0)));
299
320
  return { ...segment, bytes, offset: bytes.length, hash: digest(bytes) };
300
321
  });
301
- legacyEntries(suffixes, { onMalformed: options.onMalformed });
322
+ yield* legacyEntrySteps(suffixes, { onMalformed: options.onMalformed });
302
323
  return result;
303
324
  }
304
325
 
@@ -350,6 +371,10 @@ function head(homeM: string, generation: string, maximumArchiveBytes?: number, m
350
371
  export function readLegacySnapshot(homeM: string, options: LegacySnapshotOptions = {}): LegacySegment[] {
351
372
  try { return snapshot(homeM, options); } catch (error) { if (error instanceof SegmentReadBudgetError) throw error; return failure(); }
352
373
  }
374
+ /** #462: the same snapshot as steps, so the transport's capture yields between legacy segments instead of inside one read. */
375
+ export function* legacySnapshotSteps(homeM: string, options: LegacySnapshotOptions = {}): Generator<void, LegacySegment[], void> {
376
+ try { return yield* snapshotSteps(homeM, options); } catch (error) { if (error instanceof SegmentReadBudgetError) throw error; return failure(); }
377
+ }
353
378
  /** Read-only enumeration reuses the legacy frontier checks without retaining source bodies or refreshing an index. */
354
379
  export function inspectLegacySnapshot(homeM: string, options: LegacySnapshotOptions, inspect: LegacySegmentInspector): LegacySegment[] {
355
380
  return snapshot(homeM, options, inspect);
@@ -212,8 +212,11 @@ export function capacityReport(opts: {
212
212
  const samples = opts.inject?.metrics ?? readMetrics(base);
213
213
  const hookWalls = samples.filter((s) => s.kind === "hook" && typeof s.wallMs === "number").map((s) => s.wallMs!);
214
214
  const hookRss = samples.filter((s) => s.kind === "hook" && typeof s.rssMB === "number").map((s) => s.rssMB!);
215
- const searchWalls = samples.filter((s) => s.kind === "search" && typeof s.wallMs === "number").map((s) => s.wallMs!);
216
- const searchRss = samples.filter((s) => s.kind === "search" && typeof s.rssMB === "number").map((s) => s.rssMB!);
215
+ // #485: every completed read-tool call appends a `search` sample carrying its tool name; R3's reading is `amem_search`'s.
216
+ // A sample without a tool name counts as a search reading, so a hand-written or pre-#485 sample is still read.
217
+ const searchSamples = samples.filter((s) => s.kind === "search" && (s.tool === undefined || s.tool === "amem_search"));
218
+ const searchWalls = searchSamples.filter((s) => typeof s.wallMs === "number").map((s) => s.wallMs!);
219
+ const searchRss = searchSamples.filter((s) => typeof s.rssMB === "number").map((s) => s.rssMB!);
217
220
  const metrics = { samples: samples.length, hookP95Ms: p95(hookWalls), hookRssMB: p95(hookRss), searchP95Ms: p95(searchWalls), searchRssMB: p95(searchRss) };
218
221
 
219
222
  const homeConfig = readCaptureConfigFile(join(base, "capture-config.json"));
@@ -8,6 +8,7 @@ import { readProfileJSON, validGeneration } from "./generation.ts";
8
8
  import { captureShardStats, readCaptureConfig } from "./capture.ts";
9
9
  import { openShardStore } from "./store.ts";
10
10
  import { lifecycleResolver, type LifecycleState } from "./lifecycle.ts";
11
+ import { placementSelectorRefusal } from "./sync-placement-guard.ts";
11
12
 
12
13
  /**
13
14
  * #15 D3 (storage part only): the user-level catalog of project shards. `catalog.db` in the memory home is derived
@@ -35,7 +36,15 @@ const fromRow = (r: CatalogRow): CatalogProject => ({ hash: r.hash, key: r.key,
35
36
 
36
37
  /** Interrupted splits expose capture facts, but cannot authorize any curated store open or initialization. */
37
38
  function capturedSelection(base: string): boolean {
38
- const value = readProfileJSON(join(base, "shards.json")) as { schema?: unknown; generation?: unknown; phase?: unknown; selectorRevision?: unknown } | undefined;
39
+ let value: { schema?: unknown; generation?: unknown; phase?: unknown; selectorRevision?: unknown } | undefined, shardError: unknown;
40
+ try { value = readProfileJSON(join(base, "shards.json")) as typeof value; } catch (error) { shardError = error; }
41
+ let profile: { schema?: unknown } | undefined;
42
+ try { profile = readProfileJSON(join(base, "profile.json")) as typeof profile; } catch { /* Legacy selector diagnostics remain with their original reader. */ }
43
+ if (value?.schema === "agent-mem.shards/v3" || profile?.schema === "agent-mem.profile/v3") {
44
+ const refusal = placementSelectorRefusal(base); if (refusal) throw new Error(refusal);
45
+ return false;
46
+ }
47
+ if (shardError !== undefined) throw shardError;
39
48
  if (value === undefined) return false;
40
49
  if (!value || (value.schema !== SHARDED_SCHEMA && value.schema !== SHARDED_V2_SCHEMA) || !validGeneration(value.generation) || (value.phase !== "captured" && value.phase !== "active") || typeof value.selectorRevision !== "string") throw new Error("curated shard selection is unavailable or invalid");
41
50
  return value.phase === "captured";
@@ -1,5 +1,5 @@
1
1
  import { placementRuntimeRefusal, withDoctorPlacementScratch } from "./sync-placement-guard.ts";
2
- import { chmodSync, copyFileSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync } from "node:fs";
2
+ import { chmodSync, copyFileSync, existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync } from "node:fs";
3
3
  import { indexFileName } from "./index-file.ts";
4
4
  import { assertFormatFloor } from "./formats.ts";
5
5
  import { tmpdir } from "node:os";
@@ -177,7 +177,6 @@ function copyWork(options: Pick<DoctorOptions, "home" | "project" | "aliases">,
177
177
  /** Reuse doctor's bounded private inputs for an on-demand brief, never a live store or reader lease. */
178
178
  export async function withBriefSnapshot<T>(home: string, project: string, read: (inputs: NonNullable<BriefOptions["measureOnly"]>) => Promise<T>): Promise<T> {
179
179
  const aliases = aliasedKeys(home, project), selection = readSelector(home).revision, layout = layoutOf(home), guard = guardScratch();
180
- let scratch: string | undefined, curated: MemoryStore | undefined;
181
180
  const budget: CopyBudget = { bytes: 0, verify: [] };
182
181
  const inputDirectories = [join(home, "projects"), ...(layout === "split" ? [join(home, "user")] : [join(home, "log"), join(home, "local")]),
183
182
  ...(layout === "generation" ? [join(home, "generations")] : []),
@@ -192,22 +191,26 @@ export async function withBriefSnapshot<T>(home: string, project: string, read:
192
191
  };
193
192
  try {
194
193
  checkDirectories();
195
- scratch = mkdtempSync(join(tmpdir(), `amem-doctor-${process.pid}-`)); chmodSync(scratch, 0o700); guard.adopt(scratch);
196
- const options = { home, project, aliases }, workBase = join(scratch, "work-base"); mkdirSync(workBase, { mode: 0o700 });
197
- copyWork(options, workBase, budget);
198
- if (curatedPresent(home, project, layout)) {
199
- const copy = join(scratch, "home"); mkdirSync(copy, { mode: 0o700 }); copyCurated(options, layout, copy, budget);
200
- curated = openCuratedForRead(copy, project);
201
- if (!curated) throw Error("recap curated snapshot unavailable");
202
- }
203
- check();
204
- const result = await read({ ...(curated ? { curated } : {}), workBase });
205
- check(); return result;
194
+ return await withDoctorPlacementScratch(home, guard.adopt, async scratch => {
195
+ let curated: MemoryStore | undefined;
196
+ try {
197
+ const options = { home, project, aliases }, workBase = join(scratch, "work-base"); mkdirSync(workBase, { mode: 0o700 });
198
+ copyWork(options, workBase, budget);
199
+ if (curatedPresent(home, project, layout)) {
200
+ const copy = join(scratch, "home"); copyCurated(options, layout, copy, budget);
201
+ curated = openCuratedForRead(copy, project);
202
+ if (!curated) throw Error("recap curated snapshot unavailable");
203
+ }
204
+ check();
205
+ const result = await read({ ...(curated ? { curated } : {}), workBase });
206
+ check(); return result;
207
+ } finally { curated?.close(); }
208
+ });
206
209
  } catch (error) {
207
210
  if (error instanceof TooBig) throw Error("recap snapshot exceeds the 64 MiB copy limit");
208
211
  throw error;
209
212
  } finally {
210
- try { curated?.close(); } finally { try { if (scratch) rmSync(scratch, { recursive: true, force: true }); } finally { guard.release(); } }
213
+ guard.release();
211
214
  }
212
215
  }
213
216
 
@@ -32,7 +32,8 @@ const READER_VERSION: string | undefined = (() => {
32
32
  catch { return undefined; }
33
33
  })();
34
34
  const parts = (version: string) => SEMVER.exec(version)!.slice(1, 4).map(Number);
35
- function below(reader: string, floor: string): boolean {
35
+ /** Compare versions accepted by format-floor records, using their numeric release components. */
36
+ export function formatVersionBelow(reader: string, floor: string): boolean {
36
37
  const a = parts(reader), b = parts(floor);
37
38
  for (let i = 0; i < 3; i++) if (a[i] !== b[i]) return a[i]! < b[i]!;
38
39
  return false;
@@ -65,7 +66,7 @@ export function assertFormatFloor(home: string, surface: FormatSurface): void {
65
66
  const floors = readFormatFloors(home);
66
67
  if (!floors) return;
67
68
  const reader = READER_VERSION ?? "unknown";
68
- for (const floor of floors) if ((floor.surface === surface || floor.surface === "home") && (READER_VERSION === undefined || below(READER_VERSION, floor.minReader))) {
69
+ for (const floor of floors) if ((floor.surface === surface || floor.surface === "home") && (READER_VERSION === undefined || formatVersionBelow(READER_VERSION, floor.minReader))) {
69
70
  throw new FormatFloorError("format_floor", `amem ${reader} is below the ${surface} format floor ${floor.minReader} (since ${floor.since}) recorded in ${join(home, FORMATS_FILE)}; nothing was read or written. Upgrade amem to ${floor.minReader} or later.`, { ...floor, reader });
70
71
  }
71
72
  }
@@ -73,7 +74,7 @@ export function assertFormatFloor(home: string, surface: FormatSurface): void {
73
74
  /** A person opts into a capability only by an applicable floor, never by this code writing one. */
74
75
  export function formatFloorAtLeast(home: string, surface: FormatSurface, minimum: string): boolean {
75
76
  if (!SEMVER.test(minimum)) return false;
76
- return (readFormatFloors(home) ?? []).some(floor => (floor.surface === surface || floor.surface === "home") && !below(floor.minReader, minimum));
77
+ return (readFormatFloors(home) ?? []).some(floor => (floor.surface === surface || floor.surface === "home") && !formatVersionBelow(floor.minReader, minimum));
77
78
  }
78
79
 
79
80
  /**