@staix/vault-mem 0.6.0 → 0.7.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/CHANGELOG.md CHANGED
@@ -2,6 +2,14 @@
2
2
 
3
3
  ## [Unreleased]
4
4
 
5
+ ## [0.7.0] - 2026-11-11
6
+
7
+ - N-1: 0.6.0 runs beside 0.7.0 without either version rebuilding the other's derived state or rewriting the other's configuration: both use the same note and spec index files (`links2-schema4`, schema 4) and config format 4, and note/spec files stay shared. The command set only gains `vmem brief` / `vmem_brief`, and the pinned MCP `initialize` instructions are the same bytes, but receipts a client reads change: `vmem_promote` and `vmem_promote_from_amem` omit `refused: true` when the receipt is applied with errors, the amem promotion receipt reports `applied: true` once the note was written, rollback receipts mark which paths stayed applied and keep the original forward cause instead of the rollback drift, a publication-path permission, storage or descriptor failure is `IO` rather than `V09` (note writes) or `DRIFT` (spec writes), and `LINK` is reserved for the native hard-link operation, so a client keyed on `refused`, `applied` or those codes needs 0.7.0.
8
+
9
+ - Add `vmem brief` and read-only `vmem_brief`: intent/path-basename FTS/BM25 pointers with CJK matching, marked one-hop neighbors, deny/metadata PII screening and whole-line output within a 256..4096-byte cap (default 1024). Restricted refreshes preserve already-indexed denied rows and links for other readers while skipping new denied files; individual metadata fields and assembled pointers are both screened (including anchored PII patterns), denied metadata consumes no pointer-read budget, and restricted rebuilds refuse before modifying the index. Omission counts and bounded metadata reads keep body content out of brief responses; host injection remains separate (#206).
10
+
11
+ - Make partial rollback receipts report outstanding paths, keep the original forward cause with one final-state rollback drift diagnostic, and distinguish create rollback from backup restoration. Publication checks preserve I/O failures instead of misclassifying them as drift; amem promotion propagates the note's applied state and both MCP promotion receipts omit the refusal marker after applied errors. Spec-create path-check I/O remains IO; LINK is reserved for the native hard-link operation (#202).
12
+
5
13
  ## [0.6.0] - 2026-11-11
6
14
 
7
15
  - N-1: 0.5.1 runs beside 0.6.0 with separate note/spec index files (`links2-schema3` versus `links2-schema4`); its format-3 reader preserves format-4 `canonTables` without using their promotion hints. The prior CLI/MCP surface remains available in 0.5.1; note merge and spec create/update/delete commands and MCP tools require 0.6.0. Note files remain shared, including automatic date stamps written by 0.6.0.
package/README.md CHANGED
@@ -134,7 +134,7 @@ bun bin/vmem.js links personal "Note or alias" --limit 50 --json
134
134
 
135
135
  All four commands require a registered vault id. They read only flat, regular `notes/*.md` files (case-sensitive `.md` extension), skip subdirectories and symlink files, and refuse a replaced vault/notes directory. Notes are limited to 2 MiB each. They never write note content, registry configuration or `.obsidian/`. `rebuild` rebuilds the derived cache; other commands scan metadata on every invocation and rehash new or metadata-changed files. Content-identical changes only update metadata; deleted/renamed paths leave the index. SQLite transactions make each scan atomic. A concurrently changing note aborts that scan, so retry after its writer finishes. No watcher, model calls or embeddings run.
136
136
 
137
- The cache is `$VMEM_HOME/indexes/<canonical-vault-path-sha256>-links<N>-schema<S>.sqlite` using the resolved home, not necessarily the environment variable. `N` is the link-resolution version (currently <!-- facts:index-links -->2<!-- /facts:index-links -->) and `S` the index schema version (currently <!-- facts:index-schema -->4<!-- /facts:index-schema -->; schema 2 added the CJK bigram table, schema 3 the reference identifiers and schema 4 the arXiv id reference notes are searchable by), so two installed vmem versions that resolve links or store the index differently keep separate caches instead of rebuilding each other's; 0.2.4 and older use the unversioned `<sha256>.sqlite`, 0.3.0 through 0.3.3 use `<sha256>-links2.sqlite`, 0.4.0 uses `<sha256>-links2-schema2.sqlite`, 0.5.0 through 0.5.1 use `<sha256>-links2-schema3.sqlite`, and a first run after upgrading builds the new file once with no manual step. Cache files use mode 0600 on creation. The location must be outside every registered vault, including through symlinks; linked cache directories/files are refused. It contains note text and is disposable private derived state. Removing it while commands are stopped allows the next read to build it again. SQLite uses its own transaction lock and a five-second busy timeout. There is no automatic migration or live vault cutover.
137
+ The cache is `$VMEM_HOME/indexes/<canonical-vault-path-sha256>-links<N>-schema<S>.sqlite` using the resolved home, not necessarily the environment variable. `N` is the link-resolution version (currently <!-- facts:index-links -->2<!-- /facts:index-links -->) and `S` the index schema version (currently <!-- facts:index-schema -->4<!-- /facts:index-schema -->; schema 2 added the CJK bigram table, schema 3 the reference identifiers and schema 4 the arXiv id reference notes are searchable by), so two installed vmem versions that resolve links or store the index differently keep separate caches instead of rebuilding each other's; 0.2.4 and older use the unversioned `<sha256>.sqlite`, 0.3.0 through 0.3.3 use `<sha256>-links2.sqlite`, 0.4.0 uses `<sha256>-links2-schema2.sqlite`, 0.5.0 through 0.5.1 use `<sha256>-links2-schema3.sqlite`, 0.6.0 and later use `<sha256>-links2-schema4.sqlite`, and a first run after upgrading builds the new file once with no manual step. Cache files use mode 0600 on creation. The location must be outside every registered vault, including through symlinks; linked cache directories/files are refused. It contains note text and is disposable private derived state. Removing it while commands are stopped allows the next read to build it again. SQLite uses its own transaction lock and a five-second busy timeout. There is no automatic migration or live vault cutover.
138
138
 
139
139
  Search uses FTS5 `unicode61` over title, description and body with BM25 weights 5:2:1, ascending score and path tie-breaking. Whitespace-separated query terms are literal AND terms, not a raw FTS expression; quote the query as one shell argument. A term whose letters and digits form one run of 2 or more Hangul, Han, Hiragana or Katakana characters (surrounding punctuation is ignored) matches wherever it occurs in the title, description or body, including particle and compound forms: `사업단` finds `사업단은`, `사업단장` and `해외사업단`. That matching uses a side FTS5 table of overlapping character bigrams (Unicode NFC), so a 2-character term is one indexed lookup and a longer term a phrase of consecutive bigrams; it is substring matching, not morphological analysis. Every other term, including Latin words, single CJK characters and terms mixing CJK with Latin letters or digits (`AI교육`), keeps `unicode61` token matching, and a query without CJK terms ranks exactly as before. With a CJK term, notes where every CJK term is a standalone word or occurs in the title or description rank before notes that contain it only inside a longer body word; within each group BM25 over the bigram table (5:2:1) and path break ties, and the snippet is a body window around the first CJK term. `--type` and `--domain` are exact scalar frontmatter filters. Results include a bounded snippet and metadata, not the full body. Search queries and note targets accept at most 1024 UTF-8 bytes. Search/links default to 50 results, with an enforced 1..500 range. Show defaults to 16384 UTF-8 bytes and permits 1..65536, returning `truncated` and the full note SHA-256. `--section "Exact H2"` selects one real H2 through the next H1/H2, including its H3 children; code-fenced headings are ignored and duplicate/missing names refuse. Truncated reads include bounded `headings` (at most 64 names/8KiB metadata; `headingsTruncated` when omitted) and `nextOffset`. `--offset N` is a UTF-8 byte offset within the selected section or whole note; use the returned `nextOffset` to page even a single section larger than 64 KiB, and compare note hashes across pages. Invalid UTF-8 boundaries and zero-progress byte budgets refuse. Link string fields are capped at 1024 bytes in command results. Oversized arguments fail instead of silently raising a bound.
140
140
 
@@ -143,11 +143,19 @@ Link resolution uses NFC and case-insensitive filename stems only, as Obsidian a
143
143
  `parseFrontmatter` retains source bytes alongside semantic YAML data using Bun's built-in YAML parser. `emitFrontmatter(document, changes)` returns the entire note, preserving omitted and semantically unchanged keys byte-identically (comments, quoting, sequences, one-level mappings, folded/literal/chomped scalars, BOM and line endings). Changed keys use canonical JSON-compatible YAML; `undefined` removes a key. Editing requires a block mapping, while an unchanged flow mapping round-trips. This is a library transformation only, not a note-write command. Synthetic fixtures and create/edit/delete/rename parity tests cover this increment; Linux/macOS CI remains the platform verification gate.
144
144
 
145
145
 
146
+ ## Intent-scoped brief
147
+
148
+ `vmem brief <vault> --for "task intent" [--paths src/file.ts]... [--bytes 256..4096] [--json]` returns screened note pointers, without bodies. `vmem_brief` takes `intent`, optional `vault`, `paths` (array) and `bytes`. Use `vmem_read` for a selected note. This command does not inject anything into SessionStart or another host.
149
+
150
+ Intent words and path basenames are literal OR terms, ranked by the existing FTS5/BM25 weights and CJK substring rules. The first five safe hits seed incoming/outgoing one-hop neighbors, marked `[neighbor]`; remaining direct matches follow. Each line names the literal note path, title, type and description. PII warnings/errors under the vault's notes-surface policy and secret-looking metadata omit the whole pointer, including neighbors. Each title, type and description is screened independently (including anchored patterns), in addition to joined metadata and the final output line. Denied files are excluded before metadata refresh reads them. Already-indexed denied rows and their link resolution are preserved for other readers; new denied files stay unindexed, and brief output filtering suppresses every denied pointer before metadata lookup or budget consumption. Restricted rebuilds are refused before clearing the shared search tables; use a restricted metadata refresh or an unrestricted rebuild. Existing metadata refresh may update only the derived cache; no vault note, log or configuration is written.
151
+
152
+ The default cap is 1024 UTF-8 bytes, range 256..4096. Both the serialized result JSON (`vault`, `lines`, `omitted`, `bytes`) and plain text including its omission footer fit the cap; `bytes` is the serialized JSON size. Lines are never truncated: `omitted` counts unique matching/neighbor paths not emitted because of policy, metadata/read limits or the output cap. Input is limited to a 1024-byte intent and 16 path hints of 1024 bytes each, producing at most 32 search words / 4096 bytes. Ranking/neighbor sets each refuse above 10000 paths; metadata attempts cap at 512 and 256 KiB per call, with each row limited to 4096 bytes inside SQL before decoding. Oversized metadata is omitted whole. The index supplies path/metadata only for selection, never body snippets.
153
+
146
154
  # Validated writes
147
155
 
148
156
  Authored note content writes stamp `updated` with the local calendar date (`YYYY-MM-DD`, using the same clock as vault logs): create, append, patch, frontmatter edits (including explicit DOI assignment), both sides of supersession, promotion and link. Mechanical move rewrites (including backlinks), tidy and sanitize preserve existing dates, as do checks, reports and semantic no-ops. Create also fills `created` when the key is absent; existing and caller-supplied values retain their current validation. Automatic stamping takes precedence over an explicit `updated` set or unset on an authored write; the caller candidate still passes normal validation first. The writer validates the final content too, reusing parsed snapshots across the two passes. Writer and promotion previews account for the dates without writing; their date-bearing fingerprints need a fresh preview after a date change. A header that cannot be edited in place, including flow mappings and merge-key block mappings, is never canonicalized just to add dates: the authored candidate keeps its header bytes and gets a V01 warning. If adding only the automatic dates would push an otherwise valid note over 256 KiB, the candidate is saved unstamped with a V01 warning asking you to shorten the note enough to leave room for later automatic dates. Oversized caller content is still refused. Stamping also reparses its candidate and preserves YAML anchor/alias relationships. If emission would remove or change a reference, alter other metadata, or produce an invalid header, the original authored candidate is kept unstamped. A cause-specific V01 warning directs you to open the note in a text editor and rewrite its header as a block mapping with plain literal values. Replace any aliases with their literal values and remove anchors; later authored writes then stamp `updated` automatically. This is a manual header edit, not a vmem frontmatter operation, which cannot repair every flow header or semantic no-op alias. An applied receipt says the content was saved; the warning never advises repeating that content write. Readonly previews do not claim a save. Unrelated anchors and aliases remain intact and do not prevent stamping.
149
157
 
150
- All mutations use `applyWrite(home, request)`: per-vault `mutation.lock`, current-SHA checks, in-memory planning, final-snapshot validation/screening, same-directory flushed temporary files and atomic renames, directory flushes, derived-index refresh and a structured receipt. `write: mcp` allows CLI and MCP writes; `cli` allows CLI only; `none` refuses mutations. `check` is read-only and works with `none`. No command requires a TTY or rejects agent environments. Note and spec publication share a path/cleanup helper. Immediately after rename, link or unlink, it rechecks all captured parent identities and target containment; a mismatch returns an error with recovery steps, retaining `applied`/`changed` when publication already occurred. Note drift receipts annotate planned changes with per-path `applied` state, attribute the drifted target, and list `retainedBackups` by their original relative names. CLI error summaries count only applied changes; a rollback that already restored the original bytes reports a consumed backup rather than claiming it was retained. Backups are not intentionally retained when no change was published. Owned lock/temp descriptors remain open through cleanup; immediately before unlink the helper compares descriptor and named-path identities, retaining and reporting a replacement. A concurrent writer with the same user's access can still edit the target or swap a directory between the last check and publication, or replace a cleanup name after its last identity check. Pure TypeScript cannot atomically close these windows without native relative-directory or inode-checked operations. Stop concurrent writers and inspect the root, target, lock and retained backups before manual recovery; do not automatically retry an applied-with-errors receipt.
158
+ All mutations use `applyWrite(home, request)`: per-vault `mutation.lock`, current-SHA checks, in-memory planning, final-snapshot validation/screening, same-directory flushed temporary files and atomic renames, directory flushes, derived-index refresh and a structured receipt. `write: mcp` allows CLI and MCP writes; `cli` allows CLI only; `none` refuses mutations. `check` is read-only and works with `none`. No command requires a TTY or rejects agent environments. Note and spec publication share a path/cleanup helper. Immediately after rename, link or unlink, it rechecks all captured parent identities and target containment; a mismatch returns an error with recovery steps, retaining `applied`/`changed` when publication already occurred. Partial note-write failures annotate planned changes with per-path `applied` state, attribute the drifted target, and list `retainedBackups` by their original relative names. CLI error summaries count only applied changes; rollback drift retains the original forward cause, records one drift diagnostic and describes the final applied state. A create rollback removes the created target and has no backup. Publication checks preserve I/O errors such as EACCES/EIO instead of classifying them as namespace drift or hard-link failure; spec create reports LINK only for a failed native hard-link operation. A rollback that already restored the original bytes reports a consumed backup rather than claiming it was retained. Backups are not intentionally retained when no change was published. Owned lock/temp descriptors remain open through cleanup; immediately before unlink the helper compares descriptor and named-path identities, retaining and reporting a replacement. A concurrent writer with the same user's access can still edit the target or swap a directory between the last check and publication, or replace a cleanup name after its last identity check. Pure TypeScript cannot atomically close these windows without native relative-directory or inode-checked operations. Stop concurrent writers and inspect the root, target, lock and retained backups before manual recovery; do not automatically retry an applied-with-errors receipt.
151
159
 
152
160
  ```sh
153
161
  vmem new personal example-finding --type insight --domain research --topics research --description "A distinct supporting observation."
@@ -228,7 +236,7 @@ vmem stats personal --days 7 --json
228
236
 
229
237
  `vmem mcp` serves newline-delimited JSON-RPC 2.0 (MCP tools, protocol 2025-06-18 and earlier) on stdio. stdout carries protocol messages only; it needs no TTY and runs in agent sessions. Requests are limited to 64 KiB per frame and results to 256 KiB (a larger result becomes a structured `LIMIT` refusal). Arguments are validated against each tool's bounded schema (`additionalProperties: false`, string/array/integer caps); invalid arguments or unknown tools return JSON-RPC `-32602`, unknown methods `-32601`, malformed frames `-32700`/`-32600`. At startup it loads every module a tool can run, the `@staix/agent-mem` root included, so a server keeps its own code and tool list when its install is replaced or a newer release is installed beside it; restart the host session to pick up the new release.
230
238
 
231
- The vault set is read once at startup: every tool's `vault` property is an enum of the registered ids and defaults to the first `personal` vault. Restart the host session after `vaults add/remove`. Registered spec sources are also read once when `vmem mcp` starts; restart the MCP server after `specs add` or `specs remove`. Reads go through the same index as the CLI; writes go through `applyWrite`/`appendLog` with channel `mcp`, so they require `write: mcp` and pass the same V01-V10 gates. Every tool returns a JSON result: a receipt, or `{refused: true, issues}` for policy, validation or lookup failures. Direct note-write tools return an applied-with-errors receipt (`applied: true`, `ok: false`) without `refused: true`; inspect and recover the recorded write instead of retrying it as an unapplied refusal. Spec mutations add `refused: true` only when no change was applied (`ok: false`, `changed: false`); post-publication errors return the applied receipt (`changed: true`, `ok: false`) without that marker.
239
+ The vault set is read once at startup: every tool's `vault` property is an enum of the registered ids and defaults to the first `personal` vault. Restart the host session after `vaults add/remove`. Registered spec sources are also read once when `vmem mcp` starts; restart the MCP server after `specs add` or `specs remove`. Reads go through the same index as the CLI; writes go through `applyWrite`/`appendLog` with channel `mcp`, so they require `write: mcp` and pass the same V01-V10 gates. Every tool returns a JSON result: a receipt, or `{refused: true, issues}` for policy, validation or lookup failures. Direct note-write and promotion tools (`vmem_promote`, `vmem_promote_from_amem`) return an applied-with-errors receipt (`applied: true`, `ok: false`) without `refused: true`; inspect and recover the recorded write instead of retrying it as an unapplied refusal. Spec mutations add `refused: true` only when no change was applied (`ok: false`, `changed: false`); post-publication errors return the applied receipt (`changed: true`, `ok: false`) without that marker.
232
240
 
233
241
  | tool | arguments (caps) |
234
242
  |---|---|
@@ -237,6 +245,7 @@ The vault set is read once at startup: every tool's `vault` property is an enum
237
245
  | `vmem_spec_grep` | optional `source`, `worktree`, `query`<=1024 UTF-8 bytes, `literal`, `type`, `status`, `tag`, `parent`, `dependsOn`, `coversPath`, `offset`<=10000, `limit`<=500; continuation after filters |
238
246
  | `vmem_spec_validate` | optional `source`, `worktree`, `requireFresh`, `limit`<=500; bounded report; stale is fatal only with `requireFresh` |
239
247
  | `vmem_status` | none; vaults with health, write policy, effective pii and `piiPolicy` (read-only) |
248
+ | `vmem_brief` | `intent`<=1024 bytes, optional `vault`, `paths[]`<=16 (1024 bytes each), `bytes` 256..4096 (default 1024); ranked screened pointers and one-hop neighbors, no bodies |
240
249
  | `vmem_search` | `query`<=1000, `vault`, `limit`<=50, `type`, `domain` |
241
250
  | `vmem_read` | `path` (stem, alias or `notes/` path), `vault`, `maxBytes`<=65536; returns `{path, frontmatter, body, sha256, truncated}` |
242
251
  | `vmem_read_many` | `paths`<=20 (8 KiB each), `vault` |
@@ -265,7 +274,7 @@ The vault set is read once at startup: every tool's `vault` property is an enum
265
274
 
266
275
  <!-- facts:mcp-tools -->
267
276
 
268
- `vmem mcp` lists 36 tools: `vmem_status`, `vmem_search`, `vmem_read`, `vmem_read_many`, `vmem_list`, `vmem_links`, `vmem_mocs`, `vmem_check`, `vmem_log_tail`, `vmem_create`, `vmem_patch`, `vmem_append`, `vmem_set_frontmatter`, `vmem_link`, `vmem_supersede`, `vmem_log_append`, `vmem_move`, `vmem_merge`, `vmem_delete`, `vmem_promote_from_amem`, `vmem_lint`, `vmem_graph_build`, `vmem_graph_neighbors`, `vmem_promote`, `vmem_skills_mine`, `vmem_read_file`, `vmem_list_files`, `vmem_report`, `vmem_stats`, `vmem_spec_get`, `vmem_spec_graph`, `vmem_spec_grep`, `vmem_spec_validate`, `vmem_spec_create`, `vmem_spec_update`, `vmem_spec_delete`.
277
+ `vmem mcp` lists 37 tools: `vmem_status`, `vmem_search`, `vmem_brief`, `vmem_read`, `vmem_read_many`, `vmem_list`, `vmem_links`, `vmem_mocs`, `vmem_check`, `vmem_log_tail`, `vmem_create`, `vmem_patch`, `vmem_append`, `vmem_set_frontmatter`, `vmem_link`, `vmem_supersede`, `vmem_log_append`, `vmem_move`, `vmem_merge`, `vmem_delete`, `vmem_promote_from_amem`, `vmem_lint`, `vmem_graph_build`, `vmem_graph_neighbors`, `vmem_promote`, `vmem_skills_mine`, `vmem_read_file`, `vmem_list_files`, `vmem_report`, `vmem_stats`, `vmem_spec_get`, `vmem_spec_graph`, `vmem_spec_grep`, `vmem_spec_validate`, `vmem_spec_create`, `vmem_spec_update`, `vmem_spec_delete`.
269
278
 
270
279
  <!-- /facts:mcp-tools -->
271
280
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@staix/vault-mem",
3
- "version": "0.6.0",
3
+ "version": "0.7.0",
4
4
  "description": "Validated Obsidian-compatible knowledge vaults for agents and people",
5
5
  "license": "MIT",
6
6
  "type": "module",
package/src/cli.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { runBriefCommand } from "./vault-brief.ts";
1
2
  import { runSpecCommand, specTools } from "./mcp-spec.ts";
2
3
  import { tidyVault, TIDY_RULES } from "./tidy.ts";
3
4
  import { originCheck } from "./sync.ts";
@@ -84,6 +85,7 @@ function runWith(args: string[], env: NodeJS.ProcessEnv, text: TextOptions = PLA
84
85
  if (args[0] === "promote" || args[0] === "sync") return runOrgCommand(args[0], args.slice(1), resolveHome(env).home, env, text);
85
86
  if (args[0] === "log") return runLogCommand(args.slice(1), resolveHome(env).home, env, text);
86
87
  if (isWriteCommand(args[0]!)) return runWriteCommand(args[0]!, args.slice(1), resolveHome(env).home, env, text);
88
+ if (args[0] === "brief") return runBriefCommand(args.slice(1), resolveHome(env).home);
87
89
  if (isReadCommand(args[0]!)) return runReadCommand(args[0]!, args.slice(1), resolveHome(env).home, text);
88
90
  const group = args[0] === "vaults" || args[0] === "specs";
89
91
  const command = group ? `${args[0]} ${args[1] ?? ""}` : args[0];
@@ -21,6 +21,7 @@ export const COMMANDS = [
21
21
  { name: "graph neighbors", usage: "graph neighbors <vault> <stem> [--hops 1..2] [--limit 1..500] [--relation REL] [--json]", mutates: false, section: "Analysis", description: "read a note's graph neighborhood up to two hops, optionally over one link relation" },
22
22
  { name: "skills mine", usage: "skills mine <vault> [--days N] [--project KEY|--all-projects] [--vocab DIR] [--skills DIR] [--min-size N] [--min-novelty X] [--json]", mutates: false, section: "Analysis", description: "rank repeated work patterns in agent memory as new-skill candidates" },
23
23
  { name: "rebuild", usage: "rebuild <vault> [--json]", mutates: "cache", section: "Read", description: "rebuild the derived search index from the vault files" },
24
+ { name: "brief", usage: "brief <vault> --for INTENT [--paths PATH]... [--bytes 256..4096] [--json]", mutates: "cache", section: "Read", description: "rank screened note pointers and one-hop neighbors within a byte cap" },
24
25
  { name: "search", usage: "search <vault> <query> [--type TYPE] [--domain DOMAIN] [--limit 1..500] [--json]", mutates: "cache", section: "Read", description: "full-text search notes, optionally by type and domain" },
25
26
  { name: "show", usage: "show <vault> <target> [--section TEXT] [--offset 0..2097152] [--max-bytes 1..65536] [--json]", mutates: "cache", section: "Read", description: "print a note's fields and body, paged by section, offset and size" },
26
27
  { name: "links", usage: "links <vault> <target> [--limit 1..500] [--json]", mutates: "cache", section: "Read", description: "list a note's outgoing, dead and incoming links" },
package/src/mcp-vault.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { vaultBrief } from "./vault-brief.ts";
1
2
  import { createSpecMcp } from "./mcp-spec.ts";
2
3
  import { SPEC_COMMANDS } from "./spec-command-table.ts";
3
4
  import { analysisInput } from "./analysis-input.ts";
@@ -32,7 +33,7 @@ const scalar = { type: ["string", "number", "boolean", "null", "array"], maxLeng
32
33
  const metadata = { type: "object", maxProperties: 32, properties: { authors: { type: "array", minItems: 1, maxItems: 100, items: string(1024) } }, additionalProperties: scalar };
33
34
 
34
35
  /** Tool names for the implemented read, write, log, analysis and promotion providers. */
35
- export const VMEM_TOOL_NAMES = ["vmem_status", "vmem_search", "vmem_read", "vmem_read_many", "vmem_list", "vmem_links", "vmem_mocs", "vmem_check", "vmem_log_tail",
36
+ export const VMEM_TOOL_NAMES = ["vmem_status", "vmem_search", "vmem_brief", "vmem_read", "vmem_read_many", "vmem_list", "vmem_links", "vmem_mocs", "vmem_check", "vmem_log_tail",
36
37
  "vmem_create", "vmem_patch", "vmem_append", "vmem_set_frontmatter", "vmem_link", "vmem_supersede", "vmem_log_append", "vmem_move", "vmem_merge", "vmem_delete", "vmem_promote_from_amem", "vmem_lint", "vmem_graph_build", "vmem_graph_neighbors", "vmem_promote", "vmem_skills_mine", "vmem_read_file", "vmem_list_files", "vmem_report", "vmem_stats", ...SPEC_COMMANDS.map(item => item.name)] as const;
37
38
 
38
39
  /** Server `initialize` instructions: purpose, navigation order and the write contract. Pinned by a test, under 400 bytes. */
@@ -46,6 +47,7 @@ export function vaultTools(ids: readonly string[], orgIds: readonly string[] = [
46
47
  return [
47
48
  tool("vmem_status", "Registered vaults with health, write policy, effective pii and the piiPolicy matrix (read-only).", object({})),
48
49
  tool("vmem_search", "Full-text (BM25) search over indexed notes. Literal AND terms.", object({ query: string(1000), vault, limit: integer(1, 50), type: string(64), domain: string(64) }, ["query"])),
50
+ tool("vmem_brief", "Intent-ranked note pointers and one-hop neighbors, with metadata PII/deny screening and whole-line byte cap including the result JSON. No note bodies; read a selected pointer with vmem_read.", object({ vault, intent: string(1024), paths: { type: "array", maxItems: 16, items: string(1024) }, bytes: integer(256, 4096) }, ["intent"])),
49
51
  tool("vmem_read", "Read one note by stem, alias or notes/ path: frontmatter, body, sha256. Bounded by maxBytes; section selects an exact H2, offset pages UTF-8 byte ranges, and truncated reads list H2 headings/nextOffset.", object({ path: note, vault, maxBytes: integer(1, 65536), section: string(1024), offset: integer(0, MAX_NOTE_BYTES) }, ["path"])),
50
52
  tool("vmem_read_many", "Read up to 20 notes (8 KiB each).", object({ paths: { type: "array", minItems: 1, maxItems: 20, items: note }, vault }, ["paths"])),
51
53
  tool("vmem_list", "List indexed notes under notes/ in path order, optionally by stem prefix, with each note's mtime and the filtered total. Pass the returned nextCursor as cursor for the next page.", object({ vault, prefix: string(256, 0), limit: integer(1, 500), cursor: string(1024) })),
@@ -112,13 +114,14 @@ export function createVaultMcp(home: string, env: NodeJS.ProcessEnv = process.en
112
114
  return { path, sha256: hash, truncated, frontmatter: parsed.data, body: parsed.body };
113
115
  };
114
116
  const handlers: Record<string, McpHandler> = {
117
+ vmem_brief: args => vaultBrief(home, { vault: pick(args).id, intent: args.intent as string, paths: args.paths as string[] | undefined, bytes: args.bytes as number | undefined }, pick(args)),
115
118
  vmem_promote: async args => {
116
119
  const { promoteToOrg } = await import("./org-promote.ts");
117
120
  const source = vaults.find(v => v.id === defaultVault && v.kind === "personal");
118
121
  if (!source) return refusal("POLICY", "no personal vault registered");
119
122
  const result = promoteToOrg(home, { from: source.id, note: str(args.path)!, to: str(args.to)!, channel: "mcp", again: args.again === true, confirm: args.confirm === true,
120
123
  ...(Array.isArray(args.topics) ? { topics: args.topics as string[] } : {}), ...(str(args.fingerprint) ? { fingerprint: str(args.fingerprint) } : {}) }, { env });
121
- return result.ok ? result : { ...result, refused: true };
124
+ return result.ok || result.applied ? result : { ...result, refused: true };
122
125
  },
123
126
  vmem_promote_from_amem: async args => {
124
127
  const { promoteFromAmem } = await import("./promote.ts");
@@ -126,7 +129,7 @@ export function createVaultMcp(home: string, env: NodeJS.ProcessEnv = process.en
126
129
  const result = await promoteFromAmem(home, { vault: pick(args).id, id, channel: "mcp", confirm: args.confirm === true,
127
130
  ...Object.fromEntries(["stem", "type", "domain", "description", "title", "body", "linkTo", "fingerprint"].filter(key => str(args[key]) !== undefined).map(key => [key, str(args[key])])),
128
131
  ...(Array.isArray(args.topics) ? { topics: args.topics as string[] } : {}) }, { env, ...(str(args.project) ? { project: str(args.project) } : {}) });
129
- return result.ok ? result : { ...result, refused: true };
132
+ return result.ok || result.applied ? result : { ...result, refused: true };
130
133
  },
131
134
  vmem_skills_mine: async args => {
132
135
  const { mineSkills } = await import("./skills-mine.ts");
package/src/promote.ts CHANGED
@@ -155,7 +155,7 @@ export async function promoteFromAmem(home: string, request: PromoteRequest, opt
155
155
  if (request.fingerprint !== fingerprint) return { ...result, ok: false, issues: [issue("V09", "stale or missing preview fingerprint")] };
156
156
  const note = applyWrite(home, { vault: spec.id, operation, channel: request.channel ?? "cli",
157
157
  log: { type: "LEARN", project: logProjectFor(seam.project, request.logProject), source: `mem:${request.id}`, dest: path, note: `promoted: ${entry.kind}` } }, { env: options.env, now });
158
- if (!note.ok || !note.applied) return { ...result, ok: false, note, issues: note.issues };
158
+ if (!note.ok || !note.applied) return { ...result, ok: false, applied: note.applied, note, issues: note.issues };
159
159
  try {
160
160
  await seam.recordLink(request.id, path);
161
161
  return { ...result, ok: note.log?.ok !== false, applied: true, note, linked: path, issues: note.log?.ok === false ? note.log.issues : [] };
package/src/spec-write.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { capturePublicationPath, publishFile, cleanupOwnedFile, PublicationDrift } from "./write-files.ts";
1
+ import { capturePublicationPath, publishFile, cleanupOwnedFile, PublicationDrift, PublicationLinkFailure } from "./write-files.ts";
2
2
  import { createHash, randomUUID } from "node:crypto";
3
3
  import { closeSync, constants, fstatSync, fchmodSync, fsyncSync, lstatSync, mkdirSync, openSync, readSync, realpathSync, rmdirSync, writeFileSync } from "node:fs";
4
4
  import { basename, dirname, isAbsolute, join, relative, sep } from "node:path";
@@ -342,9 +342,9 @@ export function mutateSpec(home: string, request: Pick<SpecUpdateRequest, "id" |
342
342
  if (change.before === null && !result.changed && error instanceof PublicationDrift && error.targetExists) {
343
343
  refuse("EEXIST", "create target appeared before publication; inspect the existing target and choose an absent path before retrying", change.path);
344
344
  }
345
- if (change.before !== null || error instanceof PublicationDrift || result.changed) throw error;
346
- if ((error as NodeJS.ErrnoException).code === "EEXIST") refuse("EEXIST", "create target appeared before publication; inspect the existing file and choose an absent path before retrying", change.path);
347
- refuse("LINK", `create hard-link publication failed (${writeErrorCause(error)}); check filesystem hard-link support and permissions and free space, then choose a writable worktree on a filesystem supporting same-directory hard links; create never falls back to rename`, change.path);
345
+ if (change.before !== null || result.changed || !(error instanceof PublicationLinkFailure)) throw error;
346
+ if ((error.cause as NodeJS.ErrnoException | undefined)?.code === "EEXIST") refuse("EEXIST", "create target appeared before publication; inspect the existing file and choose an absent path before retrying", change.path);
347
+ refuse("LINK", `create hard-link publication failed (${writeErrorCause(error.cause)}); check filesystem hard-link support and permissions and free space, then choose a writable worktree on a filesystem supporting same-directory hard links; create never falls back to rename`, change.path);
348
348
  }
349
349
  if (change.before === null) { cleanupOwnedFile(temp!, tempFd!); temp = undefined; }
350
350
  syncDirectory(parent); syncCreatedParents(createdDirs); result.ok = true;
@@ -0,0 +1,90 @@
1
+ import { join } from "node:path";
2
+ import { isDeepStrictEqual } from "node:util";
3
+ import { unenforceablePii, type VaultSpec } from "./config.ts";
4
+ import { canonicalPath, isDenied } from "./platform.ts";
5
+ import { loadRegistry } from "./registry.ts";
6
+ import { VaultIndex, type BriefPointer } from "./vault-index.ts";
7
+ import { screenContent, screenMetadata } from "./write-validation.ts";
8
+
9
+ export interface VaultBrief { vault: string; lines: string[]; omitted: number; bytes: number }
10
+ export interface BriefRequest { vault: string; intent: string; paths?: string[]; bytes?: number }
11
+ export function briefText(result: VaultBrief): string { return [...result.lines, `${result.omitted} matches omitted`].join("\n"); }
12
+ function sized(vault: string, lines: string[], omitted: number): VaultBrief {
13
+ const result = { vault, lines, omitted, bytes: 0 };
14
+ for (let i = 0; i < 4; i++) {
15
+ const bytes = Buffer.byteLength(JSON.stringify(result));
16
+ if (bytes === result.bytes) break;
17
+ result.bytes = bytes;
18
+ }
19
+ return result;
20
+ }
21
+ const flat = (value: string) => value.replace(/[\p{Cc}\p{Zl}\p{Zp}]/gu, " ");
22
+ /** Metadata pointers only. The normal metadata refresh is the only source-reading/cache-writing phase. */
23
+ export function vaultBrief(home: string, request: BriefRequest, expectedVault?: VaultSpec): VaultBrief {
24
+ const { vault: id, intent, paths = [], bytes = 1024 } = request;
25
+ if (typeof intent !== "string" || !intent.trim() || Buffer.byteLength(intent) > 1024) throw new Error("brief: intent must contain 1..1024 UTF-8 bytes; use --for with a shorter task description");
26
+ if (!Number.isSafeInteger(bytes) || bytes < 256 || bytes > 4096) throw new Error("brief: bytes must be an integer 256..4096; choose a supported byte cap");
27
+ if (!Array.isArray(paths) || paths.length > 16 || paths.some(p => typeof p !== "string" || !p.trim() || Buffer.byteLength(p) > 1024 || /\p{Cc}/u.test(p))) throw new Error("brief: paths must be at most 16 nonempty hints of at most 1024 bytes without control characters; remove control characters, shorten or remove path hints");
28
+ const words = [...new Set([intent, ...paths.map(p => p.split(/[\\/]/).at(-1)!.replace(/\.[^.]+$/, ""))].flatMap(value => value.normalize("NFC").match(/[\p{L}\p{N}]+/gu) ?? []))];
29
+ if (!words.length) throw new Error("brief: intent and path basenames contain no searchable letters or digits; provide words containing letters or digits");
30
+ if (words.length > 32 || Buffer.byteLength(words.join(" ")) > 4096) throw new Error("brief: expected 1..32 searchable words within 4096 bytes; shorten the intent or path basenames");
31
+ const config = loadRegistry(home), vault = config.vaults.find(v => v.id === id);
32
+ if (!vault) throw new Error("brief: unknown vault id; choose a registered id from vmem vaults list");
33
+ if (expectedVault && !isDeepStrictEqual(vault, expectedVault)) throw new Error("brief: vault binding changed since MCP startup; restart the MCP server before reading");
34
+ if (unenforceablePii(vault)) throw new Error("brief: vault PII policy cannot be enforced by this version; inspect vmem doctor and update the client or policy");
35
+ const denied = (file: string) => isDenied(file, config.denyPaths ?? []) || isDenied(canonicalPath(file), config.denyPaths ?? []);
36
+ if (denied(vault.path) || denied(join(vault.path, "notes"))) throw new Error("brief: vault or notes directory is denied; choose an allowed registered vault");
37
+ const index = new VaultIndex(home, vault, config.vaults.map(v => v.path));
38
+ try {
39
+ index.scan(false, { denyPaths: config.denyPaths ?? [] });
40
+ const ranked = index.briefMatches(words), direct = new Set(ranked.map(row => row.path));
41
+ // Count every attempt, including oversized or screened metadata, and pass the remaining bytes into SQL.
42
+ const cache = new Map<string, BriefPointer | undefined>(); let remaining = 256 * 1024, attempts = 0;
43
+ const load = (path: string) => {
44
+ if (cache.has(path)) return cache.get(path);
45
+ if (denied(join(vault.path, "notes", path))) { cache.set(path, undefined); return undefined; }
46
+ if (attempts >= 512 || remaining <= 0) return undefined;
47
+ attempts++;
48
+ let pointer = index.briefPointer(path, Math.min(4096, remaining));
49
+ if (pointer) {
50
+ remaining -= pointer.bytes;
51
+ const text = [pointer.path, pointer.title, pointer.type, pointer.description].join("\n");
52
+ if (/[\p{Cc}\p{Zl}\p{Zp}|]/u.test(pointer.path) || screenMetadata({ title: pointer.title, type: pointer.type, description: pointer.description }, { vault, config }, pointer.path).length || screenContent(text, vault, config).length || screenContent(flat(text), vault, config).length) pointer = undefined;
53
+ }
54
+ cache.set(path, pointer); return pointer;
55
+ };
56
+ const seeds: string[] = [];
57
+ for (const row of ranked) { if (load(row.path)) seeds.push(row.path); if (seeds.length === 5 || attempts >= 512 || remaining <= 0) break; }
58
+ const neighbors = index.briefNeighbors(seeds).filter(path => !direct.has(path));
59
+ const order = [...new Set([...seeds, ...neighbors, ...ranked.map(row => row.path)])];
60
+ const lines: string[] = [];
61
+ for (const path of order) {
62
+ const pointer = load(path);
63
+ if (!pointer) continue;
64
+ const line = `${direct.has(path) ? "" : "[neighbor] "}notes/${pointer.path} | ${flat(pointer.title)} | ${flat(pointer.type)} | ${flat(pointer.description)}`;
65
+ if (screenContent(line, vault, config).length) continue;
66
+ const candidate = sized(vault.id, [...lines, line], order.length - lines.length - 1);
67
+ if (candidate.bytes <= bytes && Buffer.byteLength(briefText(candidate)) + 1 <= bytes) lines.push(line);
68
+ }
69
+ return sized(vault.id, lines, order.length - lines.length);
70
+ } finally { index.close(); }
71
+ }
72
+
73
+ export function runBriefCommand(args: string[], home: string): { text: string; code: number } {
74
+ const paths: string[] = [], positional: string[] = []; let intent: string | undefined, bytes: number | undefined, json = false;
75
+ for (let i = 0; i < args.length; i++) {
76
+ const arg = args[i]!;
77
+ if (!arg.startsWith("-")) { positional.push(arg); continue; }
78
+ if (arg === "--json" && !json) { json = true; continue; }
79
+ if (!["--for", "--paths", "--bytes"].includes(arg)) throw new Error(`brief: unknown or repeated option ${arg}; run vmem brief --help`);
80
+ const value = args[++i];
81
+ if (!value || value.startsWith("--")) throw new Error(`brief: ${arg} requires a value; run vmem brief --help`);
82
+ if (arg === "--paths") paths.push(value);
83
+ else if (arg === "--for" && intent === undefined) intent = value;
84
+ else if (arg === "--bytes" && bytes === undefined && /^[0-9]+$/.test(value)) bytes = Number(value);
85
+ else throw new Error(`brief: repeated option or invalid value for ${arg}; run vmem brief --help`);
86
+ }
87
+ if (positional.length !== 1 || intent === undefined) throw new Error("brief: requires one registered vault and --for intent; run vmem brief --help");
88
+ const result = vaultBrief(home, { vault: positional[0]!, intent, paths, bytes });
89
+ return { text: json ? JSON.stringify(result) : briefText(result), code: 0 };
90
+ }
@@ -1,4 +1,4 @@
1
- import { realPath } from "./platform.ts";
1
+ import { realPath, canonicalPath, isDenied } from "./platform.ts";
2
2
  import { Database } from "bun:sqlite";
3
3
  import { closeSync, constants, fstatSync, lstatSync, mkdirSync, openSync, readSync, readdirSync, realpathSync } from "node:fs";
4
4
  import { createHash } from "node:crypto";
@@ -78,6 +78,7 @@ export interface NoteReadResult {
78
78
  headings?: string[];
79
79
  headingsTruncated?: boolean;
80
80
  }
81
+ export interface BriefPointer { path: string; title: string; type: string; description: string; bytes: number }
81
82
  export interface SearchOptions { limit?: number; type?: string; domain?: string }
82
83
  export interface SearchResult { path: string; title: string; description: string; type: string; domain: string; score: number; snippet: string }
83
84
  interface StoredNote extends IndexedNote { metadata: string; source: string }
@@ -282,7 +283,8 @@ export class VaultIndex<Source extends VaultSpec | SpecSourceSpec = VaultSpec> {
282
283
  return this.db.query<Omit<LinkNote, "aliases"> & { aliases: string }, []>("SELECT path,title,aliases,body FROM notes ORDER BY path").all().map(row => ({ ...row, aliases: JSON.parse(row.aliases) as string[] }));
283
284
  }
284
285
  /** Scan metadata each call; hash only new or metadata-changed files. Atomic cache update. */
285
- scan(rebuild = false, options: { skipInvalidFrontmatter?: boolean; captureInvalidFrontmatter?: boolean } = {}): { notes: number; changed: number; removed: number; skipped?: string[] } {
286
+ scan(rebuild = false, options: { skipInvalidFrontmatter?: boolean; captureInvalidFrontmatter?: boolean; denyPaths?: string[] } = {}): { notes: number; changed: number; removed: number; skipped?: string[] } {
287
+ if (rebuild && options.denyPaths?.length) throw new Error("index: rebuild cannot use denyPaths restrictions; use scan(false, { denyPaths }) for a restricted refresh or vmem rebuild <vault> for an unrestricted rebuild");
286
288
  // Discovery/binding Git calls must never hold a SQLite writer lock.
287
289
  let preparedPaths: string[] | undefined;
288
290
  if (this.adapter) { this.adapter.validate(); preparedPaths = this.adapter.paths(); }
@@ -301,6 +303,13 @@ export class VaultIndex<Source extends VaultSpec | SpecSourceSpec = VaultSpec> {
301
303
  for (const path of paths) {
302
304
  this.adapter?.validatePath(path);
303
305
  const file = join(this.adapter ? this.root : notesDir, path);
306
+ if (options.denyPaths && (isDenied(file, options.denyPaths) || isDenied(canonicalPath(file), options.denyPaths))) {
307
+ // A restricted reader must not delete another reader's cached rows or invalidate link resolution.
308
+ // Preserve known rows without inspecting their metadata/source; a new denied file stays unindexed.
309
+ present.add(path);
310
+ if (previous.has(path)) live.add(path);
311
+ continue;
312
+ }
304
313
  const before = this.adapter ? specFileIO(path, "inspect", () => lstatSync(file)) : lstatSync(file);
305
314
  if (!before.isFile() || before.isSymbolicLink()) throw new Error(this.adapter ? `spec discovery ${path}: selected path changed; restore a plain file and retry` : `vault ${this.vault.id}: note path changed`);
306
315
  if (!this.adapter && before.size > MAX_NOTE_BYTES) throw new Error(`vault ${this.vault.id}, ${path}: note exceeds ${MAX_NOTE_BYTES} bytes`);
@@ -441,6 +450,44 @@ export class VaultIndex<Source extends VaultSpec | SpecSourceSpec = VaultSpec> {
441
450
  .slice(snapshot ? snapshotOffset : 0, (snapshot ? snapshotOffset : 0) + (snapshot && allSnapshotRows ? 10000 : limit))
442
451
  .map(({ sourceHash: _, ...row }) => ({ ...row, title: boundedText(row.title, 512).content, snippet: boundedText(row.snippet, 1024).content, type: boundedText(row.type, 256).content, domain: boundedText(row.domain, 256).content }));
443
452
  }
453
+ /** Intent words are OR terms; reuse the search tokenizer, BM25 weights and CJK substring/strong-match rules.
454
+ * Materialize scores before grouping: FTS5 auxiliary functions cannot run in an aggregate context. No bodies leave SQL. */
455
+ briefMatches(words: string[]): { path: string; score: number }[] {
456
+ if (!words.length || words.length > 32 || words.some(word => !word || Buffer.byteLength(word) > 4096)) throw new Error("brief: expected 1..32 bounded search words; shorten the intent and path hints");
457
+ const { tokens, runs } = splitTerms(words), parts: string[] = [], params: string[] = [];
458
+ if (tokens.length) {
459
+ parts.push("SELECT path,bm25(fts,0,5,2,1) AS score,1 AS strong FROM fts WHERE fts MATCH ?");
460
+ params.push(tokens.join(" OR "));
461
+ }
462
+ if (runs.length) {
463
+ parts.push(`SELECT path,bm25(grams,0,5,2,1) AS score,
464
+ (path IN (SELECT path FROM fts WHERE fts MATCH ?) OR path IN (SELECT path FROM grams WHERE grams MATCH ?)) AS strong
465
+ FROM grams WHERE grams MATCH ?`);
466
+ params.push(runs.map(run => `"${run}"`).join(" OR "), `{title description} : (${runs.map(gramPhrase).join(" OR ")})`, runs.map(gramPhrase).join(" OR "));
467
+ }
468
+ const rows = this.db.query<{ path: string; score: number }, string[]>(`WITH hits AS MATERIALIZED (${parts.join(" UNION ALL ")})
469
+ SELECT path,min(score) AS score,max(strong) AS strength FROM hits GROUP BY path ORDER BY strength DESC,score,path LIMIT 10001`).all(...params);
470
+ if (rows.length > 10000) throw new Error("brief: more than 10000 matched notes; narrow the intent or use vmem search with --type/--domain filters");
471
+ return rows;
472
+ }
473
+ /** Enforce the remaining metadata read budget inside SQL, before values cross into JavaScript. */
474
+ briefPointer(path: string, maximum: number): BriefPointer | undefined {
475
+ if (!Number.isSafeInteger(maximum) || maximum < 1 || maximum > 4096) throw new Error("brief: metadata read bound must be 1..4096 bytes; reduce the requested brief");
476
+ const bytes = "length(CAST(path AS BLOB))+length(CAST(title AS BLOB))+length(CAST(type AS BLOB))+length(CAST(description AS BLOB))";
477
+ return this.db.query<BriefPointer, [string, number]>(`SELECT path,title,type,description,${bytes} AS bytes FROM notes WHERE path=? AND (${bytes})<=?`).get(path, maximum) ?? undefined;
478
+ }
479
+ /** Resolved incoming and outgoing paths only, never link context/aliases or note bodies. */
480
+ briefNeighbors(paths: string[]): string[] {
481
+ if (!paths.length) return [];
482
+ if (paths.length > 5) throw new Error("brief: at most five seed notes; use the top ranked hits");
483
+ const slots = paths.map(() => "?").join(",");
484
+ const rows = this.db.query<{ path: string }, string[]>(`SELECT DISTINCT
485
+ CASE WHEN source IN (${slots}) THEN json_extract(data,'$.resolved') ELSE source END AS path
486
+ FROM links WHERE json_extract(data,'$.resolved') IS NOT NULL AND
487
+ (source IN (${slots}) OR json_extract(data,'$.resolved') IN (${slots})) ORDER BY path LIMIT 10001`).all(...paths, ...paths, ...paths);
488
+ if (rows.length > 10000) throw new Error("brief: more than 10000 linked neighbors; narrow the intent or use graph neighbors");
489
+ return rows.map(row => row.path);
490
+ }
444
491
  /**
445
492
  * The one indexed title closest to a dead link's text, or undefined when no title matches or the best match is at
446
493
  * or below `minimum`. Same literal AND terms as `search`, matched in the title column only, because a hint should
@@ -10,6 +10,10 @@ export class PublicationDrift extends Error {
10
10
  : "this step was not published; stop concurrent writers, inspect the registered root and target, restore the original plain parent directories, and review any earlier applied changes before another mutation"}`);
11
11
  }
12
12
  }
13
+ /** Only failures of the native hard-link operation, rather than either path check. */
14
+ export class PublicationLinkFailure extends Error {
15
+ constructor(cause: unknown) { super("hard-link publication failed", { cause }); }
16
+ }
13
17
  export interface PublicationPath { root: string; file: string; parents: { path: string; identity: string }[] }
14
18
  export type PublicationOperation = { kind: "rename" | "link"; temp: string } | { kind: "unlink" };
15
19
  const identity = (s: { dev: bigint; ino: bigint }) => `${s.dev}:${s.ino}`;
@@ -31,7 +35,7 @@ function checkPublicationPath(path: PublicationPath, deleted: boolean, published
31
35
  try {
32
36
  for (const parent of path.parents) {
33
37
  const stat = lstatSync(parent.path, { bigint: true });
34
- if (!stat.isDirectory() || stat.isSymbolicLink() || identity(stat) !== parent.identity || !within(path.root, realpathSync(parent.path))) throw new Error("parent drift");
38
+ if (!stat.isDirectory() || stat.isSymbolicLink() || identity(stat) !== parent.identity || !within(path.root, realpathSync(parent.path))) throw new PublicationDrift(path.file, published);
35
39
  }
36
40
  try {
37
41
  const stat = lstatSync(path.file);
@@ -39,14 +43,19 @@ function checkPublicationPath(path: PublicationPath, deleted: boolean, published
39
43
  } catch (error) { if (!deleted || (error as NodeJS.ErrnoException).code !== "ENOENT") throw error; }
40
44
  } catch (error) {
41
45
  if (error instanceof PublicationDrift) throw error;
42
- throw new PublicationDrift(path.file, published);
46
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") throw new PublicationDrift(path.file, published);
47
+ // A permissions, storage or descriptor failure is not proof that the namespace changed.
48
+ throw error;
43
49
  }
44
50
  }
45
51
  export function publishFile(path: PublicationPath, operation: PublicationOperation, published: () => void): void {
46
52
  // The target may be absent for create; existing-content guards remain the writer's responsibility.
47
53
  checkPublicationPath(path, true);
48
54
  if (operation.kind === "rename") renameSync(operation.temp, path.file);
49
- else if (operation.kind === "link") linkSync(operation.temp, path.file);
55
+ else if (operation.kind === "link") {
56
+ try { linkSync(operation.temp, path.file); }
57
+ catch (cause) { throw new PublicationLinkFailure(cause); }
58
+ }
50
59
  else unlinkSync(path.file);
51
60
  // Record persisted state before the post-publication guard can fail.
52
61
  published();
package/src/writer.ts CHANGED
@@ -308,9 +308,10 @@ export function applyWrite(home: string, request: WriteRequest, options: { env?:
308
308
  const backup = backups.get(change.path);
309
309
  if (rollbackError instanceof PublicationDrift) {
310
310
  rollbackDrift = rollbackError;
311
- recordError("ROLLBACK", `${restored
312
- ? "rollback restored the original target; its backup name was consumed by publication"
313
- : "rollback was not published; inspect the listed retained backup"}; ${rollbackError.message}`, change.path);
311
+ let outcome: string;
312
+ if (change.before === null) outcome = restored ? "rollback removed the created target" : "rollback could not remove the created target";
313
+ else outcome = restored ? "rollback restored the original target; its backup name was consumed" : "rollback was not published; inspect the listed retained backup";
314
+ recordError("ROLLBACK", `${outcome}; publication path identity or containment changed during rollback; ${outstanding.size > 0 ? "changes remain applied" : "no applied changes remain"}; stop concurrent writers, inspect the registered root and target, and restore the original plain parent directories before another mutation`, change.path);
314
315
  for (const path of outstanding) retainBackup(path);
315
316
  break;
316
317
  }
@@ -318,7 +319,9 @@ export function applyWrite(home: string, request: WriteRequest, options: { env?:
318
319
  }
319
320
  }
320
321
  applied = outstanding.size > 0;
321
- if (rollbackDrift) { appliedPaths = outstanding; throw rollbackDrift; }
322
+ if (applied || rollbackDrift) appliedPaths = outstanding;
323
+ // The rollback diagnostic records drift once; the outer handler must retain the original forward cause.
324
+ if (rollbackDrift) throw error;
322
325
  for (const dir of new Set(committed.map(change => dirname(join(root, change.path))))) {
323
326
  try { syncDirectory(dir); } catch { recordError("ROLLBACK", "rollback directory flush failed"); }
324
327
  }
@@ -340,7 +343,11 @@ export function applyWrite(home: string, request: WriteRequest, options: { env?:
340
343
  if (error instanceof WriteRefusal) issues.push(...error.issues.map(issue => request?.operation?.op === "merge" && !issue.message.includes(";")
341
344
  ? { ...issue, message: `${issue.message}; repair the indicated merge input or note, then request a fresh preview` } : issue));
342
345
  else if (error instanceof PublicationDrift) recordError("V09", error.message, error.file.slice(root.length + 1));
343
- else recordError("IO", "write operation failed; inspect filesystem permissions and retry");
346
+ else {
347
+ const code = (error as NodeJS.ErrnoException | undefined)?.code;
348
+ const cause = error instanceof Error ? error.message.slice(0, 500) : "unknown I/O failure";
349
+ recordError("IO", `write operation failed${typeof code === "string" ? ` (${code})` : ""}: ${cause}; inspect filesystem permissions, storage and the write receipt before retrying`);
350
+ }
344
351
  result = { ok: false, applied, issues, changes: reportedChanges(), ...(fingerprint ? { fingerprint } : {}), indexUpdated };
345
352
  } finally {
346
353
  try { index?.close(); } catch { recordError("INDEX", "derived index close failed"); }