@staix/agent-mem 0.28.1 → 0.29.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/plugin.json +1 -1
- package/README.md +11 -7
- package/package.json +1 -1
- package/src/brief-work.ts +142 -0
- package/src/cli.ts +34 -3
- package/src/commands-table.ts +2 -0
- package/src/mcp-memory.ts +1 -1
- package/src/memory/commands.ts +5 -3
- package/src/memory/curated-cache-state.ts +10 -7
- package/src/memory/doctor.ts +15 -12
- package/src/memory/generation-index.ts +79 -17
- package/src/memory/index-file.ts +2 -2
- package/src/memory/metrics.ts +1 -0
- package/src/memory/public-prune-advance.ts +2 -1
- package/src/memory/shard-sync-applications.ts +1 -1
- package/src/memory/shard-sync-history.ts +6 -0
- package/src/memory/shard.ts +41 -14
- package/src/memory/store.ts +147 -41
- package/src/memory/sync-placement-capture.ts +53 -17
- package/src/memory/sync-placement-guard.ts +52 -1
- package/src/memory/sync-placement-inventory.ts +136 -0
- package/src/memory/sync-placement-journal-storage.ts +21 -4
- package/src/memory/sync-placement-journal.ts +13 -4
- package/src/memory/sync-placement-materialize.ts +14 -3
- package/src/memory/sync-placement-publication-plan.ts +8 -4
- package/src/memory/sync-placement-realm-admission-storage.ts +128 -0
- package/src/memory/sync-placement-realm-admission.ts +335 -0
- package/src/memory/sync-placement-realm-attribution.ts +23 -0
- package/src/memory/sync-placement-realm-effective.ts +71 -0
- package/src/memory/sync-placement-realm-extension-format.ts +66 -0
- package/src/memory/sync-placement-realm-extension-storage.ts +82 -0
- package/src/memory/sync-placement-realm-intent-format.ts +55 -0
- package/src/memory/sync-placement-realm-intent-storage.ts +123 -0
- package/src/memory/sync-placement-realm-pending.ts +27 -0
- package/src/memory/sync-placement-realm-proof.ts +131 -0
- package/src/memory/sync-placement-realm-torn.ts +26 -0
- package/src/memory/sync-placement-transport.ts +70 -31
- package/src/memory/sync-placement-yield.ts +30 -0
- package/src/memory/sync-progress.ts +47 -6
- package/src/memory/sync.ts +23 -1
- package/src/memory/work-lists.ts +129 -9
- package/src/session-brief.ts +34 -1
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.29.0. Requires Bun 1.4.2 or later; no runtime dependencies.
|
|
7
7
|
<!-- /facts:version -->
|
|
8
8
|
|
|
9
9
|
## Quick start
|
|
@@ -238,7 +238,7 @@ These interactive checks remain unrun until a person checks them in each install
|
|
|
238
238
|
|
|
239
239
|
`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`.
|
|
240
240
|
|
|
241
|
-
The JSONL segments are authoritative. The curated index (`index-
|
|
241
|
+
The JSONL segments are authoritative. The curated index (`index-v5.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.
|
|
242
242
|
|
|
243
243
|
## Capture tier and full-text search
|
|
244
244
|
|
|
@@ -292,7 +292,7 @@ amem capacity apply --split [--confirm] # each shard's share of the global cap
|
|
|
292
292
|
|
|
293
293
|
- `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.
|
|
294
294
|
- `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.
|
|
295
|
-
- `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-
|
|
295
|
+
- `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-v5.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`.
|
|
296
296
|
- `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.
|
|
297
297
|
- `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).
|
|
298
298
|
- amem lists vault candidates and never writes the vault.
|
|
@@ -325,6 +325,8 @@ If both replayable tiers fill, or SessionStart's reserve alone fills, the curren
|
|
|
325
325
|
|
|
326
326
|
SessionStart prioritizes known open work. Native curated notes use a private prebuilt section prepared after curated writes and sync, with current policy screening before work and whole-line output after work. Admission requires all writers to be upgraded and a `home` or `curated` floor of 0.24.0 or later, raised explicitly with `amem formats raise` after checking writers. Below it, native curated stays deferred. Migration and profile/selector changes invalidate caches without rebuilding; a later curated write or explicit trigger prepares them. A CLI `amem brief`, including an agent-marked call, or an explicit off-hook host call to the root export `prepareCuratedBriefCache(base, project)` prepares a quiet project cache. The export is a write: it opens one selected store, reads at most four 32-row pages and writes one file up to 32 KiB. MCP and library `sessionStartBrief()` never prepare it. A project with no curated writes and neither explicit trigger keeps native curated unavailable; mutations rebuild only their touched projects after invalidating old derived files. Missing and stale files report `curated cache missing` or `curated cache stale` without rebuilding. Profile/generation binding, selected-note expiry and a 24-hour age cap bound freshness; see [the curated cache contract](docs/contracts.md#r2-hook-budget-150-mb-ceiling-per-runner-baseline-regression-300-ms-maximum-228). Native capture uses the prebuilt Record/Recap/Compact section; raw chronological history remains a library source. Neither native cache path creates schema/FTS or repairs indexes. Missing/locked/incompatible sources are explicitly unavailable. The standalone `sessionStartBrief()` retains all its original sources. Recovery failure cannot discard a computed brief. Work and reader-lease host ports use zero busy-wait and cooperative deadline checks; ordinary library callers retain their original defaults, including 3,000 ms waits. No watcher, resident worker, model/network call, embedding job or vault access is added. Host policy callbacks remain unsupported by `runHook`, while the standalone brief composes them normally.
|
|
327
327
|
|
|
328
|
+
Native work uses a bounded snapshot prepared by a work write, selected for the current static repository and host policy. A missing, stale, oversized or incompatible snapshot reports the work section unavailable with `use amem_work_state_read`; the hook does not replay the work log. A standalone brief with a host screen callback instead uses the deadline-bound live read. See [the work snapshot contract](docs/contracts.md#r2-hook-budget-150-mb-ceiling-per-runner-baseline-regression-300-ms-maximum-228).
|
|
329
|
+
|
|
328
330
|
SessionStart admits directly to the reserve with at most 32 metadata entries and performs no active-tier scan or replay. Both tiers use per-cwd fair shares (64 active records, 8 reserve records), grouping together all HOME/scope variants of a cwd. Admission can retire native records from an overrepresented cwd, counting each loss as `scope_capacity` before removal. Accepted summaries survive same-cwd pressure; new summaries backpressure without advancing their transcript cursor. A fully verified foreign all-summary inventory can use counted `summary_capacity` eviction; otherwise it stays pending for replay. All admission maintenance shares a 32-file/256 KiB body-read bound; unknown/newer schemas retain their seven-day protection. Non-SessionStart hooks maintain and drain both tiers. This is bounded reserve admission, not O(1) accounting; an atomic slot-reservation protocol is the upgrade. Parent brief storage still contains synchronous filesystem/SQLite work between cooperative deadline checks; asynchronous/deadline-aware storage remains the upgrade, not a larger handler limit. The default R2 wall limit remains 150 ms p95, with the scoped hosted-runner exceptions in [the R2 contract](docs/contracts.md#r2-hook-budget-150-mb-ceiling-per-runner-baseline-regression-300-ms-maximum-228), including 181 ms for hosted macOS M1 transcript hooks. The production handler budget remains 140 ms; the absolute 100 MB peak RSS was retired by #228 for a 150 MB per-invocation ceiling plus a per-runner baseline regression gate. Functional tests construct a programmatic host-only deadline; the actual executable exposes no environment or CLI deadline extension. Its exec-only boot-clock handoff can only shorten the deadline and is cleared before hook import. Dedicated budget scripts retain the actual CLI, original sample counts, cold attempt 0 and timeout/reaper assertions. The [P3 receipt](docs/p3-hook-budget-2026-10-23.md) identifies prior-head evidence separately from current acceptance; the current rework has no newly claimed both-OS green CI result.
|
|
329
331
|
|
|
330
332
|
A private admission cursor rotates bounded inspection across pending records (at most 32 files/256 KiB per pass), so a healthy first slice cannot indefinitely hide later removed/unknown entries from retirement checks. Git include/conditional identity dependencies are traversed within depth four and 16 files. Pending scope hashes relevant semantic project-identity values rather than unrelated full-config or HEAD churn; derived cache validity may additionally hash raw configuration/HEAD bytes. Unconditional and `gitdir` includes bind semantic identity values. Dynamic `onbranch`/`hasconfig` or unknown conditional trees without identity keys bind nothing; if they contain origin/rewrite/worktree identity keys, scope stays unknown. Native read-only identity may still supply known work, but it never adopts that pending capture; counted `scope_unknown` retirement needs seven days. This conservative ceiling is upgraded by evaluating `onbranch` against HEAD at drain time, not by adding a condition interpreter in this PR.
|
|
@@ -443,7 +445,7 @@ Real migration remains blocked until the separately reviewed generation-capable
|
|
|
443
445
|
|
|
444
446
|
## Curated shard migration (#15 T2)
|
|
445
447
|
|
|
446
|
-
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-
|
|
448
|
+
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-v5.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. Without active placement, split curated stores sync the opened canonical project and user overlay to separate private-remote refs (`amem/p/<key-hash>` and `amem/u`); unopened projects and machine data are not fetched. Active placement instead syncs the effective home-wide inventory as described below. `--policy-free` remains accepted and never bypasses screening. Original IDs and attribution survive independent generations. See `docs/contracts.md`, "Per-shard private sync", for prune transport and application boundaries.
|
|
447
449
|
|
|
448
450
|
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.
|
|
449
451
|
|
|
@@ -548,7 +550,7 @@ Agents use `amem_evidence` with a question to get cited, live curated entries, n
|
|
|
548
550
|
|
|
549
551
|
### Public prune view and v2 sync (opt-in)
|
|
550
552
|
|
|
551
|
-
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-
|
|
553
|
+
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-i5.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.
|
|
552
554
|
|
|
553
555
|
```sh
|
|
554
556
|
AMEM_HOME=/path/to/synthetic-memory amem migrate --public-prune-view --dry-run
|
|
@@ -619,9 +621,11 @@ amem migrate --sync-placement --abandon --json
|
|
|
619
621
|
|
|
620
622
|
Dry-run shows root versions/pins and safe policy counts, never row text or patterns, and writes nothing. Initial writer errors name the root category and cause, with upgrade/setup instructions. If a pre-marker interruption retained an intent and its inputs changed, person `--abandon` removes only its owned initial metadata so a fresh preview/apply can follow. It cannot remove a v3 marker, active fence or journal history. After apply, choose the private remote on the first v3 sync (`amem sync --remote <private-git-url>`); ordinary and cadence sync then read the immutable root locator and measure the installs afresh. Allowed originals can publish while declined originals remain in the local append-only history, with counts in the sync receipt. No writer roots need to be repeated on sync.
|
|
621
623
|
|
|
622
|
-
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 sync covers the
|
|
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
|
+
|
|
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).
|
|
623
627
|
|
|
624
|
-
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).
|
|
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).
|
|
625
629
|
|
|
626
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.
|
|
627
631
|
|
package/package.json
CHANGED
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
2
|
+
import { closeSync, constants, fstatSync, futimesSync, lstatSync, mkdirSync, openSync, readdirSync, readSync, renameSync, rmSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import type { StandalonePolicyOptions } from "./memory/policy.ts";
|
|
5
|
+
import { shardDir, shardMachineDir } from "./memory/shard.ts";
|
|
6
|
+
import type { WorkListFields, WorkListView } from "./memory/work-lists.ts";
|
|
7
|
+
|
|
8
|
+
/** Shared bound for the derived work snapshot; it holds every current list, closed ones included, with every item. */
|
|
9
|
+
export const WORK_BRIEF_BYTES = 16 * 1024;
|
|
10
|
+
const SCHEMA = "agent-mem.brief-work/v1", MAX_FIELDS = 64;
|
|
11
|
+
/** Lists one snapshot keeps; past this the brief reports the work section partial. */
|
|
12
|
+
export const WORK_BRIEF_VIEWS = 32;
|
|
13
|
+
|
|
14
|
+
export interface WorkBriefBinding { base: string; project: string; machine: string; revision?: string }
|
|
15
|
+
/** One work-log segment's write frontier: a later append changes `bytes` (and `mtimeMs`), which makes a snapshot stale. */
|
|
16
|
+
export interface WorkSegment { key: string; file: string; bytes: number; mtimeMs: number }
|
|
17
|
+
export interface WorkBrief {
|
|
18
|
+
schema: typeof SCHEMA; project: string;
|
|
19
|
+
/** The segments the rows were read at; a changed frontier makes the file stale, never wrong. */
|
|
20
|
+
segments: WorkSegment[];
|
|
21
|
+
/** The home policy configuration the rows were screened with; a change invalidates the file. */
|
|
22
|
+
policy: string;
|
|
23
|
+
/** Composed views, sorted by list name, closed lists included so a later write can update one in place. */
|
|
24
|
+
rows: { source: WorkListView }[];
|
|
25
|
+
/** More lists existed than the snapshot keeps. */
|
|
26
|
+
truncated: boolean;
|
|
27
|
+
}
|
|
28
|
+
export function workBriefFile(binding: WorkBriefBinding): string {
|
|
29
|
+
if (binding.revision !== undefined && !/^[a-f0-9]{64}$/.test(binding.revision)) throw new Error("invalid work policy revision");
|
|
30
|
+
return join(shardMachineDir(binding.base, binding.project, binding.machine), binding.revision ? `brief-work-${binding.revision}.json` : "brief-work.json");
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Static policy inputs only. A host callback has no stable identity and cannot be bound to a snapshot.
|
|
35
|
+
*/
|
|
36
|
+
export function workPolicyRevision(options: StandalonePolicyOptions): string {
|
|
37
|
+
return createHash("sha256").update(JSON.stringify({ schema: "agent-mem.standalone-policy/v1",
|
|
38
|
+
denyPaths: [...(options.denyPaths ?? [])].sort(), piiPatterns: [...(options.piiPatterns ?? [])].sort() })).digest("hex");
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Called under the work mutation lock after publishing a revision file. */
|
|
42
|
+
export function pruneWorkBriefs(binding: WorkBriefBinding): void {
|
|
43
|
+
const directory = shardMachineDir(binding.base, binding.project, binding.machine);
|
|
44
|
+
const files = readdirSync(directory).filter(name => /^brief-work-[a-f0-9]{64}\.json$/.test(name))
|
|
45
|
+
.map(name => ({ name, stat: lstatSync(join(directory, name), { throwIfNoEntry: false }) }))
|
|
46
|
+
.filter(entry => entry.stat?.isFile() && !entry.stat.isSymbolicLink())
|
|
47
|
+
.sort((a, b) => b.stat!.mtimeMs - a.stat!.mtimeMs || a.name.localeCompare(b.name));
|
|
48
|
+
const current = workBriefFile(binding), latest = Math.max(Date.now(), ...files.map(entry => entry.stat!.mtimeMs + 1));
|
|
49
|
+
const fd = openSync(current, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
|
50
|
+
try { futimesSync(fd, latest / 1000, latest / 1000); } finally { closeSync(fd); }
|
|
51
|
+
const currentName = `brief-work-${binding.revision}.json`;
|
|
52
|
+
files.sort((a, b) => Number(b.name === currentName) - Number(a.name === currentName) || b.stat!.mtimeMs - a.stat!.mtimeMs || a.name.localeCompare(b.name));
|
|
53
|
+
for (const entry of files.slice(4)) rmSync(join(directory, entry.name), { force: true });
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** Reserve a slot before replacement so a crash cannot leave a fifth revision. Caller holds the mutation lock. */
|
|
57
|
+
export function reserveWorkBriefSlot(binding: WorkBriefBinding): void {
|
|
58
|
+
const directory = shardMachineDir(binding.base, binding.project, binding.machine);
|
|
59
|
+
mkdirSync(directory, { recursive: true, mode: 0o700 });
|
|
60
|
+
const current = `brief-work-${binding.revision}.json`;
|
|
61
|
+
const files = readdirSync(directory).filter(name => /^brief-work-[a-f0-9]{64}\.json$/.test(name))
|
|
62
|
+
.map(name => ({ name, stat: lstatSync(join(directory, name)) }))
|
|
63
|
+
.sort((a, b) => b.stat.mtimeMs - a.stat.mtimeMs || a.name.localeCompare(b.name));
|
|
64
|
+
const others = files.filter(entry => entry.name !== current);
|
|
65
|
+
for (const entry of others.slice(3)) rmSync(join(directory, entry.name), { force: true });
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* The work log's frontier for a project and its aliases, in stable order. An unsafe segment path answers undefined,
|
|
70
|
+
* which no published snapshot matches.
|
|
71
|
+
*/
|
|
72
|
+
export function workLogSegments(base: string, project: string, aliases: readonly string[]): WorkSegment[] | undefined {
|
|
73
|
+
const segments: WorkSegment[] = [];
|
|
74
|
+
for (const key of [project, ...aliases]) {
|
|
75
|
+
const directory = join(shardDir(base, key), "work", "log");
|
|
76
|
+
let files: string[];
|
|
77
|
+
try { files = readdirSync(directory).sort(); } catch { continue; }
|
|
78
|
+
for (const file of files) {
|
|
79
|
+
if (!/^[a-f0-9]{16}\.jsonl$/.test(file)) continue;
|
|
80
|
+
const stat = lstatSync(join(directory, file), { throwIfNoEntry: false });
|
|
81
|
+
if (!stat || !stat.isFile() || stat.isSymbolicLink()) return;
|
|
82
|
+
segments.push({ key, file, bytes: stat.size, mtimeMs: stat.mtimeMs });
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
return segments;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
const text = (value: unknown, maximum: number): boolean => typeof value === "string" && value.length <= maximum && !/[\x00-\x1f\x7f]/.test(value);
|
|
89
|
+
function validFields(input: unknown): input is WorkListFields {
|
|
90
|
+
if (!input || typeof input !== "object" || Array.isArray(input)) return false;
|
|
91
|
+
const entries = Object.entries(input);
|
|
92
|
+
if (entries.length > MAX_FIELDS) return false;
|
|
93
|
+
return entries.every(([key, value]) => text(key, 100) && (value === null || typeof value === "boolean"
|
|
94
|
+
|| typeof value === "number" && Number.isFinite(value) || typeof value === "string" && value.length <= 8000 && !value.includes("\0")));
|
|
95
|
+
}
|
|
96
|
+
/** Cache files are untrusted derived data: require the only view shape `read()` composes before any display. */
|
|
97
|
+
export function validCachedWork(source: unknown): source is WorkListView {
|
|
98
|
+
if (!source || typeof source !== "object" || Array.isArray(source)) return false;
|
|
99
|
+
const view = source as WorkListView;
|
|
100
|
+
return text(view.list, 300) && validFields(view.fields) && typeof view.closed === "boolean"
|
|
101
|
+
&& Array.isArray(view.items)
|
|
102
|
+
&& view.items.every(item => !!item && typeof item === "object" && text(item.task, 300) && validFields(item.fields));
|
|
103
|
+
}
|
|
104
|
+
const validSegments = (input: unknown): input is WorkSegment[] => Array.isArray(input) && input.length <= 64
|
|
105
|
+
&& input.every(segment => !!segment && typeof segment === "object" && text(segment.key, 1000) && text(segment.file, 64)
|
|
106
|
+
&& Number.isSafeInteger(segment.bytes) && segment.bytes >= 0 && Number.isFinite(segment.mtimeMs));
|
|
107
|
+
|
|
108
|
+
export function readWorkBrief(binding: WorkBriefBinding): WorkBrief | undefined {
|
|
109
|
+
let fd: number | undefined;
|
|
110
|
+
try {
|
|
111
|
+
fd = openSync(workBriefFile(binding), constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
|
112
|
+
const stat = fstatSync(fd);
|
|
113
|
+
if (!stat.isFile() || stat.nlink !== 1 || stat.uid !== process.getuid?.() || stat.size < 1 || stat.size > WORK_BRIEF_BYTES || (stat.mode & 0o077) !== 0) return;
|
|
114
|
+
const bytes = Buffer.alloc(WORK_BRIEF_BYTES + 1);
|
|
115
|
+
const size = readSync(fd, bytes, 0, bytes.length, 0); // one bounded read, including an oversize sentinel
|
|
116
|
+
const after = fstatSync(fd);
|
|
117
|
+
if (size !== stat.size || size > WORK_BRIEF_BYTES || stat.size !== after.size || stat.mtimeMs !== after.mtimeMs || stat.ctimeMs !== after.ctimeMs) return;
|
|
118
|
+
const brief = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes.subarray(0, size))) as WorkBrief;
|
|
119
|
+
if (brief.schema !== SCHEMA || brief.project !== binding.project || !validSegments(brief.segments)
|
|
120
|
+
|| typeof brief.policy !== "string" || !brief.policy || typeof brief.truncated !== "boolean"
|
|
121
|
+
|| !Array.isArray(brief.rows) || brief.rows.length > WORK_BRIEF_VIEWS
|
|
122
|
+
|| brief.rows.some(row => !row || !validCachedWork(row.source))) return;
|
|
123
|
+
return brief;
|
|
124
|
+
} catch { return undefined; }
|
|
125
|
+
finally { if (fd !== undefined) closeSync(fd); }
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* Atomic private replacement. The caller proves the frontier its rows were read at and writes nothing when the composed set
|
|
130
|
+
* passes the bound, so an over-cap set leaves the previous file (stale) rather than a subset that reads as complete.
|
|
131
|
+
*/
|
|
132
|
+
export function writeWorkBrief(binding: WorkBriefBinding, brief: WorkBrief): boolean {
|
|
133
|
+
const body = JSON.stringify(brief) + "\n";
|
|
134
|
+
if (Buffer.byteLength(body) > WORK_BRIEF_BYTES) return false;
|
|
135
|
+
const file = workBriefFile(binding), temporary = `${file}.${process.pid}.${randomBytes(8).toString("hex")}.tmp`;
|
|
136
|
+
try {
|
|
137
|
+
mkdirSync(join(file, ".."), { recursive: true, mode: 0o700 });
|
|
138
|
+
writeFileSync(temporary, body, { mode: 0o600, flag: "wx" });
|
|
139
|
+
renameSync(temporary, file);
|
|
140
|
+
return true;
|
|
141
|
+
} finally { rmSync(temporary, { force: true }); }
|
|
142
|
+
}
|
package/src/cli.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { parseRecordLines } from "./hook-record.ts";
|
|
2
2
|
import { assertFormatFloor } from "./memory/formats.ts";
|
|
3
3
|
import { placementRuntimeRefusal, readPlacementRuntimeMarkers } from "./memory/sync-placement-guard.ts";
|
|
4
|
+
import { readActivePlacementBinding } from "./memory/sync-placement-active.ts";
|
|
4
5
|
import { activatePublicPruneView } from "./memory/public-prune-activation.ts";
|
|
5
6
|
import { AgentUsageError, agentCliRead } from "./cli-agent-reads.ts";
|
|
6
7
|
import { cliAttribution, withCliAttribution } from "./memory/cli-attribution.ts";
|
|
@@ -162,6 +163,16 @@ function assertSpoolReplayArguments(path: readonly string[], options: Record<str
|
|
|
162
163
|
if (!isAbsolute(source)) throw new AgentUsageError("--source is a relative path; pass the absolute path of the parked directory");
|
|
163
164
|
}
|
|
164
165
|
}
|
|
166
|
+
/** Realm admission receipts name hashes and counts only; the project key is the caller's own argument. */
|
|
167
|
+
function realmAdmissionDetail(result: { state: string; next?: { sequence: number; mode: "new" | "existing" }; sequence?: number; headHash?: string; created?: boolean; discarded?: number; discards?: number; staged?: number; nextStep?: string }): string {
|
|
168
|
+
if (result.staged) return `; ${result.state === "abandoned" ? "removed" : "would remove"} ${result.staged} private intent stage(s), ${result.discarded ?? result.discards ?? 0} bytes${result.state === "abandoned" ? "" : "; rerun with --confirm"}`;
|
|
169
|
+
if (result.state === "admitted") return `; appended record ${result.sequence} ${result.headHash}${result.created ? "; wrote the realm's empty curated metadata first" : ""}`;
|
|
170
|
+
if (result.state === "already-admitted") return result.nextStep ? `; ${result.nextStep}` : "; the realm is already in the effective inventory and nothing was appended";
|
|
171
|
+
if (result.state === "abandoned") return `; removed the retained intent for record ${result.sequence} and discarded ${result.discarded ?? 0} incomplete bytes`;
|
|
172
|
+
if (result.next) return `; would append record ${result.next.sequence} over the ${result.next.mode} realm's curated metadata; writes nothing until --apply`;
|
|
173
|
+
if (result.state === "abandonable" || result.state === "retained") return `; would remove the retained intent for record ${result.sequence} and discard ${result.discards ?? result.discarded ?? 0} incomplete bytes; rerun with --confirm`;
|
|
174
|
+
return result.nextStep ? `; ${result.nextStep}` : `; no change`;
|
|
175
|
+
}
|
|
165
176
|
/** Body-free preview text: counts by class, then each record's cwd, current project and class for explicit confirmation. */
|
|
166
177
|
function replayPreviewText(plan: { records: { name: string; cwd: string; project: string | null; class: string; event: string | null }[]; counts: Record<string, number>; digest: string; needsConfirmation: { cwd: string; project: string; count: number }[] }): string {
|
|
167
178
|
const lines = [`spool replay preview (no record bodies shown; plan ${plan.digest.slice(0, 12)})`,
|
|
@@ -397,8 +408,14 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
397
408
|
const modes = ["--dry-run","--apply","--resume","--abandon","--deactivate"].filter(key=>options[key]===true);
|
|
398
409
|
if (modes.length>1 || parsed.positionals.length || ["--shards","--public-prune-view","--generation","--deactivate"].some(key=>options[key]!==undefined))
|
|
399
410
|
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.");
|
|
400
|
-
|
|
401
|
-
|
|
411
|
+
if (options["--admit"] !== undefined) {
|
|
412
|
+
if (options["--writer-root"] !== undefined || options["--confirm"] === true && options["--abandon"] !== true)
|
|
413
|
+
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
|
+
} 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.");
|
|
416
|
+
}
|
|
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.");
|
|
402
419
|
}
|
|
403
420
|
if (parsed.path[0] === "setup") {
|
|
404
421
|
if (parsed.positionals.length !== 1 || options["--apply"] === true && options["--undo"] === true
|
|
@@ -501,6 +518,18 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
501
518
|
if (modes.length > 1) throw new Error("migration modes are mutually exclusive");
|
|
502
519
|
const mode = options["--apply"] ? "apply" : options["--resume"] ? "resume" : options["--deactivate"] ? "deactivate" : "dry-run";
|
|
503
520
|
if (options["--sync-placement"] === true) {
|
|
521
|
+
if (options["--admit"] !== undefined) {
|
|
522
|
+
const { previewRealmAdmission, planRealmAbandon, applyRealmAdmission } = await import("./memory/sync-placement-realm-admission.ts");
|
|
523
|
+
const project = String(options["--admit"]);
|
|
524
|
+
const result = options["--apply"] === true ? await applyRealmAdmission(memoryHome(), project, { mode: "apply" })
|
|
525
|
+
: options["--resume"] === true ? await applyRealmAdmission(memoryHome(), project, { mode: "resume" })
|
|
526
|
+
: options["--abandon"] === true ? options["--confirm"] === true ? await applyRealmAdmission(memoryHome(), project, { mode: "abandon", confirm: true })
|
|
527
|
+
: planRealmAbandon(memoryHome(), project)
|
|
528
|
+
: previewRealmAdmission(memoryHome(), project);
|
|
529
|
+
if (options["--json"] === true) return JSON.stringify(result, null, 2);
|
|
530
|
+
// Identifiers and counts only: the named project key never reaches output.
|
|
531
|
+
return `sync placement realm admission: ${result.state}; realm ${result.realm}${realmAdmissionDetail(result)}\n`;
|
|
532
|
+
}
|
|
504
533
|
const { activateSyncPlacement } = await import("./memory/sync-placement-activation.ts");
|
|
505
534
|
const result = await activateSyncPlacement({ memoryDir:memoryHome(),mode:options["--abandon"]?"abandon":mode as "dry-run"|"apply"|"resume",
|
|
506
535
|
writerRoots:repeated(argv,"--writer-root"),ownRoot:fileURLToPath(new URL("..",import.meta.url)),
|
|
@@ -1213,8 +1242,10 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
1213
1242
|
const { activePlacementWriterContext } = await import("./sync-placement-writer-context.ts");
|
|
1214
1243
|
progress = await placementProgress(syncHome, typeof options["--progress"] === "string" ? options["--progress"] as string : "auto", context);
|
|
1215
1244
|
placementWriters = activePlacementWriterContext(syncHome,fileURLToPath(new URL("..",import.meta.url)));
|
|
1245
|
+
const markers = readPlacementRuntimeMarkers(syncHome);
|
|
1246
|
+
if (!readActivePlacementBinding(syncHome, markers.profile, markers.shards)) throw Error("sync placement activation metadata unavailable or changed; inspect the retained activation before continuing");
|
|
1216
1247
|
}
|
|
1217
|
-
output = await withRepoRows(await rawMemoryCommand(memoryArgs, cwd, { person: true, rankedSearch: !legacySearch, ...(identity.actor === "agent" ? { screenGraph: true } : {}), ...(explainSearch ? { explainSearch: true } : {}), project: boundProject(), open, readable: notes => identity.actor === "person" ? notes : notes.filter(view => view.project === boundProject() && policyOf().screenStandalone(view)), stale: createRecallStalenessProbe({ cwd: recallRoot ?? cwd, rootConfirmed, policy: () => configured }), outputReady: notes => outputReady(notes.map(view => view.id)), importPolicy: () => text => configured.declinesPersonal(text),
|
|
1248
|
+
output = await withRepoRows(await rawMemoryCommand(memoryArgs, cwd, { person: true, rankedSearch: !legacySearch, ...(identity.actor === "agent" ? { screenGraph: true } : {}), ...(explainSearch ? { explainSearch: true } : {}), project: boundProject(), open: sub === "sync" && placementWriters ? () => openShardStore({ memoryDir: syncHome, user: true, deferPromotions: true }) : open, readable: notes => identity.actor === "person" ? notes : notes.filter(view => view.project === boundProject() && policyOf().screenStandalone(view)), stale: createRecallStalenessProbe({ cwd: recallRoot ?? cwd, rootConfirmed, policy: () => configured }), outputReady: notes => outputReady(notes.map(view => view.id)), importPolicy: () => text => configured.declinesPersonal(text),
|
|
1218
1249
|
sync: { ...(placementWriters ? { placementAttestation:placementWriters.attest } : {}), ...(progress ? { progress } : {}), screen: row => configured.screenStandalone(row), policyVersion: () => JSON.stringify(configuredPolicyOptions(memoryHome(), policyCwd)), ...(stop ? { signal: stop.signal } : {}) }, // the repository-narrowed policy binds what sync publishes too
|
|
1219
1250
|
onBridgeStatus: status => { receipt.bridgeStatus = status; },
|
|
1220
1251
|
// #188: ids-only listing of nearby machine-local rows; policy-refused rows are neither listed nor counted.
|
package/src/commands-table.ts
CHANGED
|
@@ -122,6 +122,8 @@ export const COMMANDS: Record<string, CommandDefinition> = {
|
|
|
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
124
|
"--abandon": flag("Person-only: discard an interrupted sync-placement attempt only before either v3 marker is installed"),
|
|
125
|
+
"--admit": text("Admit one curated project realm that appeared after activation into the same epoch; previews without --apply"),
|
|
126
|
+
"--confirm": flag("Confirm the previewed realm admission abandonment"),
|
|
125
127
|
"--writer-root": { description: "Repeatable absolute amem install root in the complete local writer inventory", value: "path" },
|
|
126
128
|
} },
|
|
127
129
|
status: { description: "Report shard migration and pending old-layout appends", options: json },
|
package/src/mcp-memory.ts
CHANGED
|
@@ -86,7 +86,7 @@ export function createMemoryMcp(options: MemoryMcpOptions): MemoryMcp {
|
|
|
86
86
|
return read.state === "ok" ? read.views : [];
|
|
87
87
|
};
|
|
88
88
|
const candidates = new CandidateStore({ memoryDir: base, ...(reconcile ? { reconcile } : {}) }); closers.push(() => candidates.close());
|
|
89
|
-
const work = new WorkListStore({ base, project, aliases, policy: async row => { const permitted = await policy.screen(row); guard(); return permitted; } }); closers.push(() => work.close());
|
|
89
|
+
const work = new WorkListStore({ base, project, aliases, briefPolicyOptions: policyOptions, policy: async row => { const permitted = await policy.screen(row); guard(); return permitted; } }); closers.push(() => work.close());
|
|
90
90
|
const fullGuard = () => {
|
|
91
91
|
if (!permitted()) unavailable();
|
|
92
92
|
if (closed) unavailable(); options.assertCurrent?.();
|
package/src/memory/commands.ts
CHANGED
|
@@ -215,13 +215,15 @@ export async function rawMemoryCommand(args: string[], cwd: string, opts: Memory
|
|
|
215
215
|
if (rest.length) fail(`usage: ${names.memory} sync [--remote <private git url>]`);
|
|
216
216
|
const r = await syncMemory(store, { ...opts.sync, ...(remote ? { remote } : {}) });
|
|
217
217
|
if (json) return JSON.stringify(r, null, 2);
|
|
218
|
-
if (!r.ok) fail(`${names.memory} sync: ${r.error}`);
|
|
219
218
|
const placement = r.placementPublication, placementText = placement ? `; placement ${placement.outcome}, ${placement.exported} exported, ${placement.withheld} withheld this attempt` : "";
|
|
219
|
+
// #450: one line per activated realm (`user` or a key hash; never a project name).
|
|
220
|
+
const realmLines = r.placementRealms?.length ? `\n${r.placementRealms.map(item => `realm ${item.realm === "user" ? "user" : item.realm.slice(0, 16)}: ${item.outcome}${item.publication ? ` (publication ${item.publication})` : ""}`).join("\n")}` : "";
|
|
221
|
+
if (!r.ok) fail(`${names.memory} sync: ${r.error}${realmLines}`);
|
|
220
222
|
if (r.pruneApplication) {
|
|
221
223
|
const a = r.pruneApplication;
|
|
222
|
-
return `synced${r.pushed ? " and pushed" : ""}: ${r.entries} long-term entries transported; ${a.proofComplete} prune proofs complete, ${a.projectionActive ?? "pending"} foreign projections active, ${a.nativeApplied ?? "pending"} native prunes applied, ${a.held} held${placementText}${r.warning ? `\nnote: ${r.warning}` : ""}`;
|
|
224
|
+
return `synced${r.pushed ? " and pushed" : ""}: ${r.entries} long-term entries transported; ${a.proofComplete} prune proofs complete, ${a.projectionActive ?? "pending"} foreign projections active, ${a.nativeApplied ?? "pending"} native prunes applied, ${a.held} held${placementText}${r.warning ? `\nnote: ${r.warning}` : ""}${realmLines}`;
|
|
223
225
|
}
|
|
224
|
-
return `synced${r.pushed ? " and pushed" : ""}: ${r.entries} long-term entries visible here${placementText}${r.warning ? `\nnote: ${r.warning}` : ""}`;
|
|
226
|
+
return `synced${r.pushed ? " and pushed" : ""}: ${r.entries} long-term entries visible here${placementText}${r.warning ? `\nnote: ${r.warning}` : ""}${realmLines}`;
|
|
225
227
|
}
|
|
226
228
|
case "dedupe": {
|
|
227
229
|
const apply = rest.includes("--apply");
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { existsSync, lstatSync, readdirSync, rmSync } from "node:fs";
|
|
2
2
|
import { join } from "node:path";
|
|
3
3
|
import { readSelector } from "./generation.ts";
|
|
4
|
-
import { aliasedKeys, readShardDescriptor, readShardedSelection } from "./shard.ts";
|
|
4
|
+
import { aliasedKeys, readShardDescriptor, readShardedSelection, resolveAlias, shardKeyHash } from "./shard.ts";
|
|
5
5
|
|
|
6
6
|
/** Small selected-profile binding only; never a generation/source refresh. */
|
|
7
7
|
export function curatedProfileBinding(base: string, project: string): string {
|
|
@@ -9,12 +9,15 @@ export function curatedProfileBinding(base: string, project: string): string {
|
|
|
9
9
|
shards: existsSync(join(base, "shards.json")) ? readShardedSelection(base) : null,
|
|
10
10
|
aliases: aliasedKeys(base, project) });
|
|
11
11
|
}
|
|
12
|
-
/** Off-hook conservative invalidation: derived directories only, never enumerate authoritative logs.
|
|
13
|
-
|
|
14
|
-
|
|
12
|
+
/** Off-hook conservative invalidation: derived directories only, never enumerate authoritative logs.
|
|
13
|
+
* #424: `projects` limits removal to those projects' cache directories (an alias resolves to its canonical directory),
|
|
14
|
+
* so one project's write keeps every other project's prebuilt brief. Omitted, every project is invalidated. */
|
|
15
|
+
export function invalidateCuratedCaches(base: string, projects?: readonly string[]): string[] {
|
|
16
|
+
const invalidated = new Set<string>(), root = join(base, "projects");
|
|
15
17
|
if (!existsSync(root)) return [];
|
|
18
|
+
const only = projects && new Set(projects.flatMap(project => [shardKeyHash(project), shardKeyHash(resolveAlias(base, project))]));
|
|
16
19
|
for (const hash of readdirSync(root)) {
|
|
17
|
-
if (!/^[a-f0-9]{16}$/.test(hash)) continue;
|
|
20
|
+
if (!/^[a-f0-9]{16}$/.test(hash) || only && !only.has(hash)) continue;
|
|
18
21
|
const directory = join(root, hash), stat = lstatSync(directory);
|
|
19
22
|
if (!stat.isDirectory() || stat.isSymbolicLink()) continue;
|
|
20
23
|
const descriptor = readShardDescriptor(base, hash);
|
|
@@ -29,8 +32,8 @@ export function invalidateCuratedCaches(base: string): string[] {
|
|
|
29
32
|
const files = ["brief-curated.json", "brief-preferences.json"].map(name => join(scope, name));
|
|
30
33
|
if (!files.some(file => lstatSync(file, { throwIfNoEntry: false }))) continue;
|
|
31
34
|
for (const file of files) rmSync(file, { force: true });
|
|
32
|
-
if (descriptor)
|
|
35
|
+
if (descriptor) invalidated.add(descriptor.key);
|
|
33
36
|
}
|
|
34
37
|
}
|
|
35
|
-
return [...
|
|
38
|
+
return [...invalidated];
|
|
36
39
|
}
|
package/src/memory/doctor.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { placementRuntimeRefusal, withDoctorPlacementScratch } from "./sync-placement-guard.ts";
|
|
1
2
|
import { chmodSync, copyFileSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync } from "node:fs";
|
|
2
3
|
import { indexFileName } from "./index-file.ts";
|
|
3
4
|
import { assertFormatFloor } from "./formats.ts";
|
|
@@ -141,7 +142,7 @@ function copyCurated(options: Pick<DoctorOptions, "home" | "project" | "aliases"
|
|
|
141
142
|
observedCopy(join(home, name), join(scratch, name), budget);
|
|
142
143
|
}
|
|
143
144
|
const selected = readSelector(home).selector;
|
|
144
|
-
if (selected?.schema === "agent-mem.profile/v2") {
|
|
145
|
+
if (selected?.schema === "agent-mem.profile/v2" || selected?.schema === "agent-mem.profile/v3") {
|
|
145
146
|
const name = `${selected.pruneInputSetHash}.json`, source = join(home, "public-prune-input-sets", name), stat = lstatSync(source);
|
|
146
147
|
if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1) throw new Error("the committed public prune view is not a plain file");
|
|
147
148
|
const directory = join(scratch, "public-prune-input-sets"); mkdirSync(directory, { mode: 0o700 });
|
|
@@ -252,7 +253,9 @@ function duplicatesAndStale(options: DoctorOptions, rows: View[], store: MemoryS
|
|
|
252
253
|
|
|
253
254
|
/** The incremental index, as a reader would refresh it from the snapshot of the live one, against a full rebuild of the same logs. Both live in the scratch copy. */
|
|
254
255
|
function indexSection(store: MemoryStore, layout: Layout, snapshotted: boolean): Section {
|
|
255
|
-
if (layout !== "shared-v1") return skipped(
|
|
256
|
+
if (layout !== "shared-v1") return skipped(store.profile.publicationFormat === "agent-mem.sync-placement/v1"
|
|
257
|
+
? "the live placement index cannot be compared without rebuilding it on open; run amem rebuild to rebuild the index"
|
|
258
|
+
: "a curated split or generation home builds and seals its index when it is created; amem rebuild repeats it");
|
|
256
259
|
try {
|
|
257
260
|
store.list({ limit: 1 }); // brings the snapshot level with the logs, as the next reader would
|
|
258
261
|
const incremental = store.dump(); store.rebuild();
|
|
@@ -464,21 +467,21 @@ export const DOCTOR_GIT_TIMEOUT_MS = 5_000;
|
|
|
464
467
|
export function doctorReport(options: DoctorOptions): Promise<DoctorReport> {
|
|
465
468
|
// Doctor reads every surface below, live or through a scratch copy: a floor on any of them refuses the whole report before anything is read (#199 AC5).
|
|
466
469
|
for (const surface of ["curated", "capture", "candidates", "work-lists", "hook-spool"] as const) assertFormatFloor(options.home, surface);
|
|
467
|
-
return withGitTimeout(DOCTOR_GIT_TIMEOUT_MS, () =>
|
|
470
|
+
return withGitTimeout(DOCTOR_GIT_TIMEOUT_MS, async () => {
|
|
471
|
+
const guard = guardScratch();
|
|
472
|
+
try { return await withDoctorPlacementScratch(options.home, guard.adopt, scratch => runDoctor(options, scratch)); }
|
|
473
|
+
finally { guard.release(); }
|
|
474
|
+
});
|
|
468
475
|
}
|
|
469
|
-
async function runDoctor(options: DoctorOptions): Promise<DoctorReport> {
|
|
470
|
-
let scratch: string | undefined, unguard: (() => void) | undefined;
|
|
476
|
+
async function runDoctor(options: DoctorOptions, scratch: string): Promise<DoctorReport> {
|
|
471
477
|
let duplicates: Section, stale: Section, index: Section;
|
|
472
478
|
let curated: MemoryStore | undefined, workBase: string | undefined, copyFailed: string | undefined;
|
|
473
479
|
try {
|
|
474
480
|
let layout: Layout | undefined;
|
|
475
481
|
try { layout = layoutOf(options.home); } catch (error) { throw new Error(`the memory profile cannot be read: ${message(error)}`); }
|
|
482
|
+
const refusal = placementRuntimeRefusal(options.home);
|
|
483
|
+
if (refusal) throw Error(refusal);
|
|
476
484
|
sweepStaleScratch();
|
|
477
|
-
// The guard is installed BEFORE the directory exists and told its name afterwards: a signal in the few microseconds between `mkdtemp` and a guard installed after it would
|
|
478
|
-
// meet no handler, take the default action and strand the directory (measured: 4 of 60 runs when a signal lands the instant it appears).
|
|
479
|
-
const guard = guardScratch(); unguard = guard.release;
|
|
480
|
-
scratch = mkdtempSync(join(tmpdir(), `amem-doctor-${process.pid}-`)); // a scratch directory, never inside the home: a home nobody used stays absent
|
|
481
|
-
guard.adopt(scratch);
|
|
482
485
|
options.afterScratch?.(scratch);
|
|
483
486
|
const budget = { bytes: 0 };
|
|
484
487
|
try {
|
|
@@ -487,7 +490,7 @@ async function runDoctor(options: DoctorOptions): Promise<DoctorReport> {
|
|
|
487
490
|
if (!curatedPresent(options.home, options.project, layout)) {
|
|
488
491
|
duplicates = stale = index = skipped("no curated notes for this project yet");
|
|
489
492
|
} else {
|
|
490
|
-
const home = join(scratch, "home");
|
|
493
|
+
const home = join(scratch, "home");
|
|
491
494
|
copyCurated(options, layout, home, budget);
|
|
492
495
|
const snapshotted = layout === "shared-v1" && snapshotIndex(options.home, join(home, indexFileName(false)));
|
|
493
496
|
curated = options.openCurated(home);
|
|
@@ -518,7 +521,7 @@ async function runDoctor(options: DoctorOptions): Promise<DoctorReport> {
|
|
|
518
521
|
await tick();
|
|
519
522
|
sections = { duplicates, stale, candidates, capture: captureSection(options), brief: await briefSection(options, curated, workBase, copyFailed), index, readers: readersSection(options), policy: policySection(options), cadence: cadenceSection(options), drops: dropsSection(options), spool: spoolSection(options), setup, ...maskedSection(curated) };
|
|
520
523
|
await tick(); // a signal that arrived during the last synchronous stage is handled while the guard is still installed
|
|
521
|
-
} finally {
|
|
524
|
+
} finally { curated?.close(); }
|
|
522
525
|
return { schema: DOCTOR_SCHEMA, status: worst(Object.values(sections).map(section => section.status)), home: { path: options.home, source: options.homeSource }, project: options.project, sections };
|
|
523
526
|
}
|
|
524
527
|
|