@staix/vault-mem 0.4.0 → 0.5.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 +40 -0
- package/README.md +12 -6
- package/bin/vmem.js +9 -3
- package/package.json +2 -2
- package/src/analysis-commands.ts +22 -13
- package/src/analysis-input.ts +2 -2
- package/src/analysis-types.ts +2 -0
- package/src/cli-output.ts +140 -0
- package/src/cli.ts +75 -42
- package/src/commands-table.ts +85 -44
- package/src/config.ts +22 -3
- package/src/links.ts +2 -0
- package/src/log-commands.ts +10 -5
- package/src/mcp-spec.ts +5 -2
- package/src/mcp-vault.ts +6 -5
- package/src/org-commands.ts +5 -3
- package/src/org-promote.ts +3 -0
- package/src/promote-command.ts +6 -4
- package/src/read-commands.ts +12 -2
- package/src/read-output.ts +99 -0
- package/src/registry.ts +3 -2
- package/src/setup.ts +58 -12
- package/src/skills-mine.ts +3 -2
- package/src/spec-git.ts +7 -4
- package/src/spec-output.ts +119 -0
- package/src/sync.ts +62 -18
- package/src/text-output.ts +120 -0
- package/src/ui/panel.css +1 -5
- package/src/ui/panel.js +60 -70
- package/src/ui/plugin.ts +33 -2
- package/src/vault-graph.ts +21 -2
- package/src/vault-index.ts +10 -4
- package/src/vault-lint.ts +8 -2
- package/src/vault-log.ts +97 -0
- package/src/workspace-graph.ts +9 -1
- package/src/write-commands.ts +5 -3
- package/src/write-operations.ts +25 -2
- package/src/write-output.ts +151 -0
- package/src/write-validation.ts +30 -8
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,46 @@
|
|
|
2
2
|
|
|
3
3
|
## [Unreleased]
|
|
4
4
|
|
|
5
|
+
## [0.5.0] - 2026-11-04
|
|
6
|
+
|
|
7
|
+
- Git timeouts and signals are named accurately: `timed out after 60 s` for `vmem sync` and `1 s` for the console check (from Bun's `exitedDueToTimeout`), else `killed by <signal>`, each with its own next step (`check git -C <vault> status, then rerun vmem sync`, the same for `vmem doctor`, or `inspect the vault Git state in System`). `vmem sync` FETCH and PUSH issues with an empty stderr now say why and name a next step. The console sync alert names the staged paths from the same list sync stages (#143).
|
|
8
|
+
|
|
9
|
+
- Docs: the README says an older agent-console loads the plugin but the panel fails with a TypeError on `host.ui`, fixed by upgrading agent-console, and the spec fixture README says the files need only be tracked, with a commit required only for verification-stamp cases (#142).
|
|
10
|
+
|
|
11
|
+
- The org sync inbox alert counts only paths `vmem sync` would stage (notes/, reports/, log), with a rename counted once. Other dirty paths are named in the detail but not counted, and a vault with no usable upstream drops the "ahead of upstream" clause. A git call that times out or is killed now logs the signal (`git status failed: timed out (SIGTERM) under the 1 s budget`) and the next step, instead of an empty cause (#138).
|
|
12
|
+
|
|
13
|
+
- Spec schema fixtures validate every error/warning class in separate default-budget tests and skip unused commit/HEAD setup, avoiding the aggregate macOS timeout. Git inspection failures now name the termination signal and 10-second inspection budget, including shorter parent/test timeouts (#137).
|
|
14
|
+
|
|
15
|
+
- The console panel's "shown" and "selected" chips use the neutral tone, because they mark a selection and not a state. Two unused panel CSS rules are removed, and the README states that the panel needs agent-console 0.1.0 or later (#129).
|
|
16
|
+
|
|
17
|
+
- The console `log` snapshot returns an opaque string `cursor`; passing it back as `since` returns only the rows appended since, oldest first up to 100 per poll with `more: true` when rows remain, identical lines included. A rewritten, truncated or far-behind log answers with the latest rows and `reset: true`. The cursor travels as `since` because the console reserves the numeric `after`. Each poll reads a 256 KiB tail or at most 1 MiB forward, plus a back-scan of at most 1 MiB when the tail sits inside one long line. The Log panel keeps re-reading the latest rows, because the shell's poll already refreshes it and skips unchanged data (#48).
|
|
18
|
+
|
|
19
|
+
- **Behaviour change:** citekey uniqueness now ignores ASCII case while preserving the stored case; retained legacy duplicates warn only on unrelated edits. Reference metadata enforces year-specific arXiv widths, names how to fix reference-only keys, and skips redundant DOI-normalization parsing without changing output (#134).
|
|
20
|
+
|
|
21
|
+
- Inbox alerts show each org vault's uncommitted paths plus local commits ahead of its tracking ref, with a stable first-seen time and an Overview link. Checks stay local, bounded and cached for 60 seconds; one vault's Git failure is logged and skipped (#48).
|
|
22
|
+
|
|
23
|
+
- `vmem setup codex` reads TOML table headers quote-aware, so a table such as `[mcp_servers."x]y"]` after the vmem table is no longer swallowed by apply. When the planned file would not parse, the refusal names the right fix: convert a root inline `mcp_servers = { ... }` to `[mcp_servers.<name>]` tables, and on undo rerun `vmem setup codex --undo` (#133).
|
|
24
|
+
|
|
25
|
+
- Missing or invalid domain ids get a direct set-domain hint without echoing the value; undeclared ids keep their named refusal. L02 domain findings use the neighbouring Korean form, list the selected vault's allowed ids and point to its domains config (#128).
|
|
26
|
+
|
|
27
|
+
- The console panel uses the kit's `ui.button` and `ui.notice(text, "err")`, which screen readers announce assertively, instead of its own button and error helpers; the truncated-body note is a polite warning. `@staix/agent-console` moves to 4c4c1e0 (#122).
|
|
28
|
+
|
|
29
|
+
- The console panel builds every view from the agent-console panel kit (`host.ui`): lists use `ui.rows`/`ui.row`, so `j`/`k`/`Enter` work on them, and a note opens in `ui.detail`. The panel CSS uses only the kit's public classes and `--acon-*` tokens, and the `@staix/agent-console` devDependency moves to 5af4dcc, which has `ConsoleUi` (#57).
|
|
30
|
+
|
|
31
|
+
- `vmem lint` and `vmem graph build` / `graph neighbors` name an option they do not take and where it applies (`graph build: --relation applies only to graph neighbors`) instead of `requires one vault id`. `graph neighbors` now refuses `--dry-run`, which it used to accept and ignore. A wrong positional count keeps its message (#121, #127).
|
|
32
|
+
|
|
33
|
+
- `vmem graph build` keeps the relation of `- [[x]] (relation)` lines from `vmem link --relation` as `rel` on the `wiki_link` edge, and `vmem graph neighbors --relation` / `vmem_graph_neighbors` `relation` follow only edges of one relation (`wiki_link` for untyped links); an unknown relation is refused. Node and edge sets are unchanged (#74).
|
|
34
|
+
|
|
35
|
+
- Vault entries accept up to 16 extra domain ids; writers, lint and promotion use the selected target set alongside the six built-ins, and status/list report the effective domains. Malformed declarations fail closed; registry writes with domains use config format 3 (#72).
|
|
36
|
+
|
|
37
|
+
- Reference notes accept typed citekey, DOI, arXiv id, authors, year and venue metadata with offline syntax checks, lowercase DOI assignments and vault-wide citekey uniqueness. Search includes reference DOI/citekey text; the first run rebuilds the index once in a separate schema3 derived cache without modifying existing notes (#73).
|
|
38
|
+
|
|
39
|
+
- `vmem setup codex` replaces a vmem entry whose table header uses quoted or spaced keys (`["mcp_servers".vmem]`, `[mcp_servers."vmem"]`, `[ mcp_servers . vmem ]`) and its subtables in place instead of adding a second table and refusing. The dry run now renders and parses the planned file, so a refusal shows in the preview as it does on apply (#116).
|
|
40
|
+
|
|
41
|
+
- Every CLI command prints text for people by default, following agent-hub's conventions: tables, field blocks, LEVEL/CHECK/FINDING checks with a verdict, one result line per write, and the exact confirm or next-page command after a preview or a cut-off read. Help is grouped into sections with a description per command, and `vmem help <command>` prints one command. `--color=auto|always|never` works everywhere and honors `NO_COLOR` and `TERM=dumb`. **Breaking for scripts:** the default output was pretty JSON and is now text, so pass `--json`, which prints the same compact JSON as before (#114).
|
|
42
|
+
|
|
43
|
+
- N-1: Against 0.4.0, the derived index moves to `<sha>-links2-schema3.sqlite` (spec caches likewise), so each version keeps its own cache and the first 0.5.0 run builds it once. Configs with vault `domains` use format 3; 0.4.0 reads and preserves those newer-format fields but refuses to create or explicitly set an extra domain id, warning only when an existing value is retained on an unrelated edit. In 0.5.0, `vmem lint`/`vmem_lint` reports an L02 error for a `domain` outside the vault's effective set; 0.4.0 lint had no domain check, so a hand-edited note can pass lint there and fail in 0.5.0. CLI status and `vmem_status` add the effective `domains` field per vault. Note files remain Markdown/YAML, with new reference-only citekey/DOI/arXiv/authors/year/venue fields that 0.4.0 does not validate or author; use 0.5.0 for this metadata and extra-domain writes. Citekey uniqueness is ASCII case-insensitive in 0.5.0; retained legacy duplicates warn only on unrelated edits. Log line format is unchanged. CLI output now defaults to text: scripts must pass `--json` for structured output. Existing MCP tools remain available; reference metadata and the optional `vmem_graph_neighbors` `relation` parameter are additive, and graph wiki-link edges may add `rel`. The console `log` snapshot adds `cursor` and accepts `since`; older callers can omit `since` for the latest rows. These CLI and validation behavior changes require a minor release.
|
|
44
|
+
|
|
5
45
|
## [0.4.0] - 2026-11-04
|
|
6
46
|
|
|
7
47
|
- Search, `vmem_search`, spec grep and writer duplicate hints match a Hangul or other CJK term of 2+ characters inside particle and compound forms (`사업단` finds `사업단은`, `사업단장`, `해외사업단`) through a side FTS5 bigram table. Latin terms keep token matching and their ranking; standalone-word and title/description hits rank before substring-only body hits. The index file name gains a schema version (`-links2-schema2.sqlite`), so the first run builds a new index once and older vmem versions keep their own file (#59).
|
package/README.md
CHANGED
|
@@ -17,6 +17,8 @@ bun bin/vmem.js recover --confirm
|
|
|
17
17
|
bun run check
|
|
18
18
|
```
|
|
19
19
|
|
|
20
|
+
Output: every command prints text for people by default, following agent-hub's CLI style. Lists are tables with uppercase headers, single objects are a title line and aligned fields, checks (`doctor`, `check`, `lint`, `spec validate`) print LEVEL/CHECK/FINDING rows and a verdict, and writes print what changed or would change. A preview prints the exact confirm command with its fingerprint; a truncated read or full page prints the command for the next one. `--json` prints compact JSON objects for scripts and agents; existing fields keep their shape; status and vaults list additionally report effective `domains`. `--color=auto|always|never` is accepted by every command: auto colors only a terminal, and `NO_COLOR` or `TERM=dumb` turn it off. Text wraps to the terminal width, or to `COLUMNS` when output is not a terminal. Errors stay `vmem: <message>` on stderr, and exit codes are unchanged. `vmem help <command>` or `<command> --help` prints one command's entries.
|
|
21
|
+
|
|
20
22
|
The first remove prints a preview; `--confirm` unregisters the vault. It never deletes vault files. Commands work without a TTY and in agent environments. Add requires an existing `notes/` directory, stores the canonical vault path, and rejects duplicate ids and paths. Doctor returns a nonzero status when a registered vault becomes unavailable or its notes directory is replaced by a symlink.
|
|
21
23
|
|
|
22
24
|
Home precedence: `VMEM_HOME` (the pointer is not consulted), else a `home` pointer in the default home's `vmem.config.json`, else the default home itself. The default home is `$AGENTHUB_HOME/vmem` when `AGENTHUB_HOME` is set, otherwise `~/.agenthub/vmem`. Home paths are reported absolute and lexically normalized (`.`, `..` and trailing slashes removed, symlinks not resolved); registered vault paths are stored and reported canonical (symlinks resolved). Environment paths and configured paths must be absolute. A redirect file contains only `home`; the target contains the registry and policy, and cannot redirect again. Missing config means an empty registry. Malformed, oversized, linked or nonregular config files fail closed.
|
|
@@ -25,7 +27,9 @@ Home precedence: `VMEM_HOME` (the pointer is not consulted), else a `home` point
|
|
|
25
27
|
{"vaults":[{"id":"personal","path":"/absolute/vault","kind":"personal","write":"mcp"}],"denyPaths":[],"piiPatterns":[]}
|
|
26
28
|
```
|
|
27
29
|
|
|
28
|
-
Configuration is limited to 64 KiB both on read and after serialization (a change whose pretty-printed result exceeds the limit is refused and the file is unchanged), rejects unknown keys, and is updated under an exclusive lock using a flushed temporary file and atomic rename. An optional top-level `version` (positive integer, absent means 1) names the config format; this build supports format
|
|
30
|
+
Configuration is limited to 64 KiB both on read and after serialization (a change whose pretty-printed result exceeds the limit is refused and the file is unchanged), rejects unknown keys, and is updated under an exclusive lock using a flushed temporary file and atomic rename. An optional top-level `version` (positive integer, absent means 1) names the config format; this build supports format 3. Registry writes add `version: 3` when a vault declares `domains`, or at least `version: 2` when `specs` is present. Configurations without either keep their existing version field (or its absence). A config whose `version` is newer than this build's format is read tolerantly: unknown keys at the top level, in vaults and in PII policies are kept and written back unchanged by registry commands, while the keys this build knows are still validated. A PII policy with members this build does not know cannot be enforced, so it fails closed: every write on that vault (note writes and `check`, two-step previews and confirms, tidy, `promote-from-amem`, `promote` and log appends) is refused with `PII_POLICY`, naming the members, until the newer vmem that wrote the policy does the write. Reads and `vaults pii` show are unaffected. `vaults pii --set` refuses to replace a policy that carries such members, since the replacement would drop them; change it with the newer vmem. Versions that add a key bump the format. Errors name the config file or vault id and path but never echo config or note contents.
|
|
31
|
+
|
|
32
|
+
A vault entry may declare `"domains": ["finance", "health", "household"]` in `vmem.config.json` (or in the object passed to `addVault`). This adds at most 16 ids matching `[a-z][a-z0-9-]{0,31}` to the built-ins `research`, `projects`, `teaching`, `operations`, `people`, `ai-practice`; an empty or omitted array leaves the built-ins available. Duplicate ids count toward the 16-entry declaration bound and appear once in the effective set. `status --json`, MCP `vmem_status` and `vaults list` report the effective set as `domains` (the text list has a DOMAINS column). Reads do not rewrite config. Writers and lint check domain values against the selected vault; missing-domain lint behavior is unchanged. `promote` and `promote-from-amem` check the target vault's set and name an undeclared domain with how to fix it; a personal-only domain is refused by an org vault that does not declare it. The existing per-vault PII policy applies to every domain; note types remain fixed.
|
|
29
33
|
|
|
30
34
|
Durability: the temporary file is fsynced before the rename and the home directory is fsynced after it. On Linux this makes the new config durable once the command returns. On macOS directory fsync succeeds but does not flush the drive cache (no `F_FULLFSYNC`), so a power loss right after a change can revert to the previous complete config, never to a partial one. Windows is not a supported platform for durability claims; the rename stays atomic.
|
|
31
35
|
|
|
@@ -120,6 +124,8 @@ vmem tidy personal --all --json # migration sanitize preview (se
|
|
|
120
124
|
|
|
121
125
|
Syntax follows indexed reads: the vault id comes first. `new` supports `--title`, `--source`, `--confidence`, `--status`, `--extra JSON` and `--body file|-`; omitted body gets an H1/Relevant Notes/Topics skeleton. Patch accepts nonempty old/new strings up to 8192 bytes and requires exactly one occurrence (including overlapping occurrences). `--edits file|-` (MCP `edits`) instead takes a JSON array of 1 to 32 `{oldString, newString}` pairs with the same bounds: each `oldString` must match exactly once in the original note, edits must not overlap and none may start in frontmatter. They apply all-or-nothing, so any failing edit (or a stale `--expected-sha`) refuses the whole patch; a success gives one receipt and one log event, and the 256 KiB bound applies to the combined result. Use exactly one form per call; both or neither is refused. Append uses an existing section or inserts it before Topics; it refuses targeting or introducing a Topics H2. `frontmatter` supports `--set JSON`, `--unset key,key` and `--expected-sha`; changing `topics` also replaces only the body Topics wiki-list items in the same write, preserving other content and line endings; setting an equal topics value leaves the body unchanged; append also supports `--expected-sha`. Link relations are `supports`, `contradicts`, `extends`, `applies-to`, `context-for`; links are bidirectional unless `--one-way`. Supersede sets `status`/`superseded_by` on the old note and adds a reverse link in the next note. Report permits plain paths below `reports/` or `ops/`, is schema-exempt and still screened. Inputs are bounded to 256 KiB, follow no file symlinks and accept stdin with `-`.
|
|
122
126
|
|
|
127
|
+
Reference notes may optionally hold `citekey` (`[A-Za-z0-9_:-]{1,64}`, unique vault-wide ignoring ASCII case (stored case is preserved)), `doi` (`10.` plus a 4..9-digit registrant, `/` and a nonempty suffix without whitespace or control characters), `arxiv_id` (`YYMM.NNNN` for YY < 15, `YYMM.NNNNN` for YY >= 15, or `archive/YYMMNNN`, optionally `vN` with N >= 1 and month 01..12), `authors` (1..100 nonempty strings), `year` (integer 1000..2100) and `venue` (1..200 Unicode characters). These keys are refused on other note types. Create and explicit DOI assignments store lowercase; body-only edits preserve legacy metadata. Identifier validation is offline syntax only, with no existence lookup or model call. `vmem search <vault> "10.1234/example" --type reference` (MCP `vmem_search` with `type: "reference"`) searches DOI and citekey as well as title, description and body. The derived cache uses `-links2-schema3.sqlite`, rebuilt once independently of older versions; stored note bodies and lint input stay unchanged.
|
|
128
|
+
|
|
123
129
|
`--dry-run` plans and validates any writer without creating locks, temporary files, directories or caches. `check` always takes this path, even without `--dry-run`. Move, delete and tidy first return a preview with planned path/hash changes and a fingerprint; confirmation requires that fingerprint. It covers canonical operation input, the canonical vault path/identity and policy, expected SHAs, every scanned note and all touched files, so even a new inbound reference after preview forces another preview. Move rewrites visible wiki/heading/block/embed targets and wiki references in frontmatter across the vault, preserving explicit `|label` text, anchors and code. Alias-only links resolve to no note and are left as written. The move source may be an existing note with a legacy file name (lint L13, for example a dot in the stem); the destination must be a valid stem. Tidy folds Connections sections into Relevant Notes. Delete refuses when it would newly break inbound links or MOC topics; fix those references first.
|
|
124
130
|
|
|
125
131
|
Validation returns named issues with severity and no matched secret text: V01 schema/enums/description; V02 existing MOC topics; V03 newly unresolved links; V04 flat ASCII note paths (maximum 200 bytes) and safe report paths; V05 final Topics placement/content (error when the write introduces a placement or content problem the note did not already have, or on create; warning when every problem was already present), with explicit append-to-Topics refusal; V06 pinned agent-mem secret regex parity and denied sources/input/snapshot paths; V07 email/phone/configured PII patterns when denied; V08 create duplicates (stem/NFKC H1); V09 256 KiB prospective note size / 16 MiB report size, exact patch and expected-SHA/drift; V10 supersession target integrity. Unchanged pre-existing broken links warn, including after a move. `possibleDuplicates` lists candidate paths for warnings from a disposable in-memory FTS5 query of title terms, matched like search terms (CJK substrings included), with BM25 <= -0.000001, up to three paths; no disk cache is written for that check. `LOCKED`, `IO`, `ROLLBACK`, `INDEX` and `CLEANUP` identify operational failures. CLI returns exit 1 when `ok` is false.
|
|
@@ -237,10 +243,10 @@ vmem promote-from-amem personal mem:<id> --link-to existing-note # link an exis
|
|
|
237
243
|
|
|
238
244
|
## Console plugin
|
|
239
245
|
|
|
240
|
-
`vmem setup <target> --apply` also writes `$AGENTHUB_HOME/console/plugins/vmem.json` (default `~/.agenthub`; directory 0700, file 0600) with the absolute path and sha256 of `src/ui/plugin.ts`. `acon ui` then shows a Vault area. Re-run setup after upgrading vmem: acon refuses a module whose hash changed.
|
|
246
|
+
`vmem setup <target> --apply` also writes `$AGENTHUB_HOME/console/plugins/vmem.json` (default `~/.agenthub`; directory 0700, file 0600) with the absolute path and sha256 of `src/ui/plugin.ts`. `acon ui` then shows a Vault area. The panel needs agent-console 0.1.0 or later, the first release with the `host.ui` panel kit and `ui.button`. An older acon still loads the plugin, but the panel then fails with a TypeError on `host.ui`; upgrade agent-console to fix it. Re-run setup after upgrading vmem: acon refuses a module whose hash changed.
|
|
241
247
|
|
|
242
248
|
- Panels: Overview (vaults, maps, recent log), Search, Note (body, links, actions), Promote (agent-mem candidates), Lint (typed findings linked to notes) and Log (parsed rows).
|
|
243
|
-
- Inbox: promotion candidates (group `candidate`), lint errors
|
|
249
|
+
- Inbox: promotion candidates (group `candidate`), lint errors, a stale graph report and org-vault sync pending (group `alert`). Sync pending counts uncommitted paths plus local commits ahead of the upstream tracking ref; without an upstream it counts only uncommitted paths. It reads local Git state only (no fetch or credential prompt), caches each vault result or failure for 60 seconds, and opens Overview with that vault, with no one-key sync verb. The palette searches notes.
|
|
244
250
|
- Actions: `delete`, `move`, `promote` (to an org vault) and `promote-from-amem` reuse the two-step MCP tools. Each first answers a preview with the planned changes; the write happens only after the console's confirm dialog, and only while the fingerprint still matches.
|
|
245
251
|
- The provider calls the `vmem mcp` handlers in process, so the console has exactly the MCP rights: writes need a vault with `write: mcp`, and log lines carry the agent attribution.
|
|
246
252
|
- The module is exported as `@staix/vault-mem/ui-plugin`. Lint results are cached for 60 seconds per vault.
|
|
@@ -249,7 +255,7 @@ vmem promote-from-amem personal mem:<id> --link-to existing-note # link an exis
|
|
|
249
255
|
|
|
250
256
|
`vmem lint <vault>` checks L01/L02/L03/L09/L10/L11/L12 and L13 (lowercase ASCII kebab-case filenames). `--note notes/example.md` limits note findings. Section names and `SUMMARY errors=N warnings=N` follow the Python reference. `--write` writes a screened lint report and LINT event; `--dry-run` previews without persistence. Findings may identify paths, link targets and malformed log prefixes. Note bodies are never included in analysis results.
|
|
251
257
|
|
|
252
|
-
`vmem graph build <vault> [--dry-run]` writes `reports/vault-graph.json`, a dated graph report, graph trend history and GRAPH events through `applyWrite`. Old dated reports are preserved. Trend history appends one row per build, including repeated builds on the same date. Output receipts expose partial report/log failure; these separate writes are not a single transaction. `vmem graph neighbors <vault> <stem> [--hops 1..2] [--limit 1..500]` reads a bounded neighborhood. Matching MCP tools are `vmem_lint`, `vmem_graph_build`, and `vmem_graph_neighbors`; MCP report writes require `write=mcp`.
|
|
258
|
+
`vmem graph build <vault> [--dry-run]` writes `reports/vault-graph.json`, a dated graph report, graph trend history and GRAPH events through `applyWrite`. Old dated reports are preserved. Trend history appends one row per build, including repeated builds on the same date. Output receipts expose partial report/log failure; these separate writes are not a single transaction. A `- [[x]] (relation)` line written by `vmem link --relation` keeps its relation as `rel` on the `wiki_link` edge (`supports`, `contradicts`, `extends`, `applies-to`, `context-for`); other links carry no `rel`. Edges stay undirected, so `rel` does not say which note supports which, and when a pair carries different relations the first in note path order is kept. `vmem graph neighbors <vault> <stem> [--hops 1..2] [--limit 1..500] [--relation REL]` reads a bounded neighborhood; `--relation` (MCP `relation`) follows only edges of that relation, `wiki_link` meaning untyped links, and an unknown relation is refused. Matching MCP tools are `vmem_lint`, `vmem_graph_build`, and `vmem_graph_neighbors`; MCP report writes require `write=mcp`.
|
|
253
259
|
|
|
254
260
|
**Communities** come from a deterministic, dependency-free Leiden (Traag, Waltman and van Eck 2019) optimizing modularity with resolution γ = 1.0: fast local moving with a node queue, refinement that merges only well-connected nodes inside each community (the greedy variant, so no random step), and aggregation on the refined partition initialized from the unrefined one, repeated while modularity improves. Nodes are processed in code-point id order and gain ties go to the lowest community id, so the same graph gives byte-identical output whatever the input order. Every community induces a connected subgraph. MOC (and, in the workspace graph, `bu`) nodes are excluded and get `community: null`; an isolated note is its own community. Community ids are numbered by size (descending), then by smallest member id; they are build-local, so cite a member, not the id. `vault-graph.json` records `graph.partitioner: "leiden"`, `resolution`, the achieved `modularity` and the number of levels, and the report Overview prints the partitioner, resolution and modularity. Modularity has a resolution limit: communities smaller than a size that grows with the whole graph cannot be separated, so a very small cluster may merge into a neighbor. There is no resolution setting yet. Skill mining (`vmem skills mine`) and the workspace graph use the same function. `bun scripts/leiden-live.ts <vault-id>` prints counts only: modularity, community count, largest share, connectivity, clustering time and NMI against the Python reference's Leiden partition.
|
|
255
261
|
|
|
@@ -264,7 +270,7 @@ vmem promote-from-amem personal mem:<id> --link-to existing-note # link an exis
|
|
|
264
270
|
|
|
265
271
|
Analysis consumes note sources from the derived SQLite index, including invalid-frontmatter rows retained separately from searchable notes. Normal scans also retain note sources in `analysis_notes`, roughly doubling cached source storage outside the vault; the cache remains derived and can be rebuilt. Read-only analysis and dry runs clone any existing derived cache through a readonly connection, then refresh changed notes in memory. A missing cache is built in memory. They create no cache, locks, reports or events. Auxiliary log, registry and report inputs use bounded plain-file reads. Snapshot limits are 10,000 notes / 64 MiB source, 1,000 reports / 16 MiB per file and combined, and 32 MiB log; oversized inputs fail explicitly. Graph limits are 100,000 edges. MOCs are excluded from clustering; ties sort by node id. Graph extraction intentionally retains the reference's body-only legacy wiki-link semantics, distinct from the richer navigation resolver.
|
|
266
272
|
|
|
267
|
-
`bun scripts/lint-parity.ts` and `bun scripts/graph-parity.ts` compare the synthetic corpus against frozen Python reference oracles. Use `--reference /absolute/path/to/lint.py` or `--reference /absolute/path/to/build-graph.py` to run the unchanged Python tools directly (`PYTHON` selects an interpreter with PyYAML/networkx). Keep those references until a separate retirement decision after two consecutive zero-diff runs. Fixture parity does not establish private-corpus parity or authorize a live vault cutover. Private corpus evidence stays private; no note bodies belong in public fixtures.
|
|
273
|
+
`bun scripts/lint-parity.ts` and `bun scripts/graph-parity.ts` compare the synthetic corpus against frozen Python reference oracles. Use `--reference /absolute/path/to/lint.py` or `--reference /absolute/path/to/build-graph.py` to run the unchanged Python tools directly (`PYTHON` selects an interpreter with PyYAML/networkx). `graph-parity.ts` compares node attributes and edge pairs only; `workspace-parity.ts` also compares edge `relation`, `field` and `rel`, but ignores `rel` on `wiki_link` edges, so the vmem-only link relation stays outside both comparisons. Keep those references until a separate retirement decision after two consecutive zero-diff runs. L02 additionally validates explicitly present `domain` values against the selected vault's effective domain set; this is a vmem-only check that the Python reference never performed. An undeclared domain can therefore add L02 findings in a live-corpus comparison as an intentional extension, not parser drift; the frozen legacy fixture does not trigger this additional check. Fixture parity does not establish private-corpus parity or authorize a live vault cutover. Private corpus evidence stays private; no note bodies belong in public fixtures.
|
|
268
274
|
|
|
269
275
|
Analysis uses YAML 1.1 scalar compatibility for Python parity, including implicit booleans, octal/sexagesimal numbers, floats and timestamps, while preserving quoted/block strings and merge keys. Explicit tags, complex/non-string mapping keys, recursive aliases and nesting beyond 64 levels are refused explicitly instead of reporting misleading findings. These bounded-parser refusals require manual resolution before parity can be established for an affected corpus.
|
|
270
276
|
# Org promotion and sync
|
|
@@ -364,7 +370,7 @@ vmem specs remove project-specs --confirm
|
|
|
364
370
|
|
|
365
371
|
The config `specs` array holds `id`, canonical git working-tree root `path`, `write` (`mcp|cli|none`, default `none`) and `pii` (`allow|deny`, default `deny`). IDs are unique across vaults and spec sources. A spec source does not need a `notes/` directory. Registration and removal reuse the vault registry lock and atomic config write. Removal previews first, then `--confirm` unregisters only; repository files remain in place.
|
|
366
372
|
|
|
367
|
-
Config writes containing `specs` use format 2;
|
|
373
|
+
Config writes containing `specs` use at least format 2; vault `domains` requires format 3. A config without either keeps its existing serialization and version field. `status` lists spec entries under a separate `specs` key, and `doctor` checks that every registered path is still its canonical git working-tree root. An unavailable or changed root makes doctor exit 1 with a per-source issue. Existing vault entries remain valid; `vaults list` also reports each effective domain set.
|
|
368
374
|
|
|
369
375
|
The registry, read-only MCP tools and CLI commands are implemented. `resolveSpecWorktree` checks the registered git common directory; `discoverSpecs` discovers nested Markdown specs in memory; `SpecIndex` reuses the vault scanner and BM25 with a separate `spec-` cache prefix per canonical worktree. Call `scan()` to refresh a `SpecIndex`; its `snapshot()` uses the last completed scan and `search()` admits only shared-cache rows matching that snapshot's paths and hashes. Call `scan()` again to see documents another index instance inserted or replaced. A failed scan invalidates the instance snapshot; the next read refreshes it or propagates the original failure. `buildSpecGraph` resolves typed links by frontmatter id, and `specSlice` returns bounded subtree/ancestor/neighbor slices (depth 0..3, at most 500 nodes). Discovery uses Git's tracked/untracked non-ignored Markdown list, reports skipped symlinks/missing/nonregular paths, accepts NFC/NFD and filesystem case aliases, and keeps the first duplicate id in NFC path order with a diagnostic. Root device/inode identity and per-file physical containment remain checked while accepting these spelling aliases. Unknown type/status strings remain readable. To exclude large or vendored untracked Markdown, add it to `.gitignore`; already-tracked ignored files must also be untracked with `git rm --cached`. Discovery/indexing is bounded to 10000 Markdown inputs, 2 MiB each and 64 MiB total; graphs allow 10000 inputs and 100000 unique edges. Graph results omit raw note sources. Library validation (`validateSpecs`), introduced-error comparison (`introducedSpecErrors`), computed freshness (`specFreshness`), tracked-file ownership (`specsCoveringPath`) and registry-free CI logic (`validateSpecRepo`) are implemented. The read tools are `vmem_spec_get`, `vmem_spec_graph`, `vmem_spec_grep` and `vmem_spec_validate`. Spec content tools `vmem_spec_create`, `vmem_spec_update` and `vmem_spec_delete` are not implemented (T4, #97); `write` stores a policy for later capabilities. Commands do not edit repository content or run git commit, branch or push.
|
|
370
376
|
|
package/bin/vmem.js
CHANGED
|
@@ -5,8 +5,14 @@ if (!version || Number(version[1]) < 1 || (Number(version[1]) === 1 && (Number(v
|
|
|
5
5
|
process.exit(1);
|
|
6
6
|
}
|
|
7
7
|
const { main, mainAsync, runMcp } = await import("../src/cli.ts");
|
|
8
|
-
|
|
8
|
+
const { resolveColor, takeColorFlag } = await import("../src/text-output.ts");
|
|
9
|
+
const argv = process.argv.slice(2);
|
|
10
|
+
// `--color=` may stand anywhere, so the dispatch looks at the words without it; main/mainAsync take it off again.
|
|
11
|
+
let words;
|
|
12
|
+
try { const taken = takeColorFlag(argv); resolveColor(taken.color, { isTTY: false }); words = taken.args; }
|
|
13
|
+
catch (error) { console.error(`vmem: ${error instanceof Error ? error.message : "invalid --color"}`); process.exit(1); }
|
|
14
|
+
if (words.length === 1 && words[0] === "mcp") {
|
|
9
15
|
try { await runMcp(); }
|
|
10
16
|
catch (error) { console.error(`vmem mcp: ${error instanceof Error ? error.message : "failed"}`); process.exitCode = 1; }
|
|
11
|
-
} else if (
|
|
12
|
-
else process.exitCode = main(
|
|
17
|
+
} else if (words[0] === "promote-from-amem" || words[0] === "skills") process.exitCode = await mainAsync(argv);
|
|
18
|
+
else process.exitCode = main(argv);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@staix/vault-mem",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.5.0",
|
|
4
4
|
"description": "Validated Obsidian-compatible knowledge vaults for agents and people",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -15,7 +15,7 @@
|
|
|
15
15
|
"@staix/agent-mem": "0.17.0"
|
|
16
16
|
},
|
|
17
17
|
"devDependencies": {
|
|
18
|
-
"@staix/agent-console": "github:STAIxBWLB/agent-console#
|
|
18
|
+
"@staix/agent-console": "github:STAIxBWLB/agent-console#4c4c1e0",
|
|
19
19
|
"@types/bun": "^1.3.0",
|
|
20
20
|
"typescript": "^5.8.0"
|
|
21
21
|
},
|
package/src/analysis-commands.ts
CHANGED
|
@@ -1,36 +1,45 @@
|
|
|
1
1
|
import { analysisInput } from "./analysis-input.ts";
|
|
2
|
-
import {
|
|
2
|
+
import { lintDetails } from "./vault-lint.ts";
|
|
3
|
+
import { analysisWriteText, lintText, neighborsText } from "./read-output.ts";
|
|
3
4
|
import { buildGraph, graphNeighbors } from "./vault-graph.ts";
|
|
4
5
|
import { writeAnalysisReports } from "./analysis-reports.ts";
|
|
6
|
+
import { PLAIN, type TextOptions } from "./text-output.ts";
|
|
5
7
|
|
|
6
|
-
|
|
8
|
+
const OPTION_SCOPE: Record<string, string> = {
|
|
9
|
+
"--hops": "graph neighbors", "--limit": "graph neighbors", "--relation": "graph neighbors",
|
|
10
|
+
"--note": "lint", "--write": "lint", "--workspace": "graph build", "--dry-run": "lint --write and graph build",
|
|
11
|
+
};
|
|
12
|
+
export function runAnalysisCommand(command: string, args: string[], home: string, env: NodeJS.ProcessEnv = process.env, text: TextOptions = PLAIN): { text: string; code: number } {
|
|
7
13
|
const values: Record<string,string> = {}, flags = new Set<string>(), positional: string[] = [];
|
|
8
14
|
for (let i=0;i<args.length;i++) {
|
|
9
15
|
const word = args[i]!;
|
|
10
16
|
if (!word.startsWith("-")) { positional.push(word); continue; }
|
|
11
17
|
if (word in values || flags.has(word)) throw new Error("analysis: repeated option");
|
|
12
18
|
if (["--json","--dry-run","--write","--workspace"].includes(word)) flags.add(word);
|
|
13
|
-
else if (["--note","--hops","--limit"].includes(word)) { const value = args[++i]; if (!value || value.startsWith("--")) throw new Error(`${word}: requires value`); values[word]=value; }
|
|
19
|
+
else if (["--note","--hops","--limit","--relation"].includes(word)) { const value = args[++i]; if (!value || value.startsWith("--")) throw new Error(`${word}: requires value`); values[word]=value; }
|
|
14
20
|
else throw new Error(`analysis: unknown option ${word}`);
|
|
15
21
|
}
|
|
22
|
+
// An option the subcommand does not take is named with where it applies, before any positional check.
|
|
23
|
+
const subcommand = command === "lint" ? "lint" : `graph ${positional[0] ?? ""}`.trim();
|
|
24
|
+
const accepted = command === "lint" ? ["--json", "--dry-run", "--write", "--note"] : positional[0] === "build" ? ["--json", "--dry-run", "--workspace"] : positional[0] === "neighbors" ? ["--json", "--hops", "--limit", "--relation"] : undefined;
|
|
25
|
+
if (accepted) for (const option of [...flags, ...Object.keys(values)]) if (!accepted.includes(option)) throw new Error(`${subcommand}: ${option} applies only to ${OPTION_SCOPE[option]}`);
|
|
16
26
|
if (command === "lint") {
|
|
17
|
-
if (positional.length !== 1
|
|
18
|
-
if (flags.has("--write")) { const result = writeAnalysisReports(home,{vault:positional[0]!,kind:"lint",note:values["--note"],dryRun:flags.has("--dry-run")},env); return {text:JSON.stringify(result),code:result.ok && (result.summary as {errors?:number}).errors === 0 ? 0 : 1}; }
|
|
27
|
+
if (positional.length !== 1) throw new Error("lint: requires one vault id");
|
|
28
|
+
if (flags.has("--write")) { const result = writeAnalysisReports(home,{vault:positional[0]!,kind:"lint",note:values["--note"],dryRun:flags.has("--dry-run")},env); return {text:flags.has("--json") ? JSON.stringify(result) : analysisWriteText(result,text,{kind:"lint",dryRun:flags.has("--dry-run")}),code:result.ok && (result.summary as {errors?:number}).errors === 0 ? 0 : 1}; }
|
|
19
29
|
const {snapshot} = analysisInput(home,positional[0]!);
|
|
20
|
-
const
|
|
21
|
-
return {text:flags.has("--json") ? JSON.stringify(report) :
|
|
30
|
+
const details = lintDetails(snapshot,values["--note"]), report = details.report;
|
|
31
|
+
return {text:flags.has("--json") ? JSON.stringify(report) : lintText(details,text,{vault:positional[0]!,note:values["--note"]}),code:report.errors ? 1 : 0};
|
|
22
32
|
}
|
|
23
33
|
const action = positional.shift();
|
|
24
|
-
if (values["--note"] || flags.has("--write")) throw new Error("graph: unsupported option");
|
|
25
34
|
if (action === "build") {
|
|
26
|
-
if (positional.length !== 1
|
|
35
|
+
if (positional.length !== 1) throw new Error("graph build: requires one vault id");
|
|
27
36
|
const result = writeAnalysisReports(home,{vault:positional[0]!,kind:"graph",workspace:flags.has("--workspace"),dryRun:flags.has("--dry-run")},env);
|
|
28
|
-
return {text:JSON.stringify(result),code:result.ok ? 0 : 1};
|
|
37
|
+
return {text:flags.has("--json") ? JSON.stringify(result) : analysisWriteText(result,text,{kind:"graph",dryRun:flags.has("--dry-run")}),code:result.ok ? 0 : 1};
|
|
29
38
|
}
|
|
30
|
-
if (action !== "neighbors" || positional.length !== 2
|
|
39
|
+
if (action !== "neighbors" || positional.length !== 2) throw new Error("graph: use build <vault> or neighbors <vault> <stem>");
|
|
31
40
|
const hops = Number(values["--hops"] ?? 1), limit = Number(values["--limit"] ?? 50);
|
|
32
41
|
if ((hops !== 1 && hops !== 2) || !Number.isInteger(limit) || limit < 1 || limit > 500) throw new Error("graph neighbors: hops 1..2, limit 1..500");
|
|
33
42
|
const {snapshot} = analysisInput(home,positional[0]!);
|
|
34
|
-
const result = graphNeighbors(buildGraph(snapshot),positional[1]!,hops,limit);
|
|
35
|
-
return {text:JSON.stringify(result),code:0};
|
|
43
|
+
const result = graphNeighbors(buildGraph(snapshot),positional[1]!,hops,limit,values["--relation"]);
|
|
44
|
+
return {text:flags.has("--json") ? JSON.stringify(result) : neighborsText(result,text,{vault:positional[0]!,limit,relation:values["--relation"]}),code:0};
|
|
36
45
|
}
|
package/src/analysis-input.ts
CHANGED
|
@@ -5,7 +5,7 @@ import { sourceWorkspaceRoot, missingSourceWarnings, sourceReferences } from "./
|
|
|
5
5
|
import { parseAnalysisYaml } from "./analysis-yaml.ts";
|
|
6
6
|
import { closeSync, constants, fstatSync, lstatSync, openSync, readSync, readdirSync, realpathSync } from "node:fs";
|
|
7
7
|
import { dirname, join, resolve } from "node:path";
|
|
8
|
-
import type
|
|
8
|
+
import { effectiveDomains, type VaultSpec, type VmemConfig } from "./config.ts";
|
|
9
9
|
import type { AnalysisSnapshot } from "./analysis-types.ts";
|
|
10
10
|
import { canonicalPath, isDenied } from "./platform.ts";
|
|
11
11
|
import { loadRegistry } from "./registry.ts";
|
|
@@ -64,7 +64,7 @@ export function analysisInput(home: string, id: string, options: { today?: strin
|
|
|
64
64
|
registryIds = (registry?.projects ?? []).filter(v => v && typeof v === "object").map(v => v.id).filter((v): v is string => typeof v === "string");
|
|
65
65
|
}
|
|
66
66
|
}
|
|
67
|
-
const inputs = { today, logPath, log: analysisRead(logPath, 32 * 1024 * 1024), registryIds, reports };
|
|
67
|
+
const inputs = { ...(vault.domains !== undefined ? { domains: effectiveDomains(vault) } : {}), today, logPath, log: analysisRead(logPath, 32 * 1024 * 1024), registryIds, reports };
|
|
68
68
|
const index = new VaultIndex(home,vault,config.vaults.map(v => v.path),{ memory: options.memory ?? true });
|
|
69
69
|
try {
|
|
70
70
|
index.scan(false,{captureInvalidFrontmatter:true});
|
package/src/analysis-types.ts
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
/** Private provider input. Never serialize a snapshot into CLI/MCP results or public evidence. */
|
|
2
2
|
export interface AnalysisSnapshot {
|
|
3
|
+
/** Effective selected-vault domain set; standalone snapshots default to the built-ins. */
|
|
4
|
+
domains?: string[];
|
|
3
5
|
notes: { path: string; source: string }[];
|
|
4
6
|
today: string;
|
|
5
7
|
logPath: string;
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Text renderers for the registry, health, setup and manifest commands (#114). Each is a pure function of the
|
|
3
|
+
* command's JSON result; `--json` never comes through here, and the text shows no more than that JSON carries.
|
|
4
|
+
*/
|
|
5
|
+
import { effectiveDomains, PII_SURFACES, type SpecSourceSpec, type VaultSpec } from "./config.ts";
|
|
6
|
+
import type { ResolvedHome } from "./home.ts";
|
|
7
|
+
import type { PiiMatrix, PiiRow } from "./pii.ts";
|
|
8
|
+
import { effectivePii, type RecoveryReport } from "./registry.ts";
|
|
9
|
+
import type { SetupReport } from "./setup.ts";
|
|
10
|
+
import { blocks, clean, fields, heading, issueTable, nextCommand, paint, paragraph, plural, shellWord, table, tone, type CellInput, type TextOptions } from "./text-output.ts";
|
|
11
|
+
import type { VaultStats } from "./vault-stats.ts";
|
|
12
|
+
|
|
13
|
+
type Check = { ok: boolean; issue?: string };
|
|
14
|
+
export type VaultRow = Omit<VaultSpec, "pii"> & { pii: string; healthy?: boolean; issue?: string; checks?: Record<string, Check>;
|
|
15
|
+
tidy?: { pending: Record<string, number>; notes: number; unparsable: string[]; hint: string } };
|
|
16
|
+
export type SpecRow = SpecSourceSpec & { healthy?: boolean; issue?: string };
|
|
17
|
+
export interface StatusResult extends ResolvedHome { version: string; healthy: boolean; vaults: VaultRow[]; specs?: SpecRow[] }
|
|
18
|
+
export interface Manifest { name: string; version: string; configVersion: number; mcp: { server: string; tools: (string | { name: string; readOnly: boolean })[] }; commands: string[] }
|
|
19
|
+
|
|
20
|
+
const OK = tone("ok", "ok"), WARN = tone("warn", "warn"), FAIL = tone("fail", "fail");
|
|
21
|
+
const homeLine = (r: StatusResult, o: TextOptions) => `${heading(`vmem ${r.version}`, o)} home ${clean(r.home)} (${r.source})`;
|
|
22
|
+
const NO_VAULTS = "no vaults registered; add one with vmem vaults add <id> <absolute-path> --kind personal|org --write mcp|cli|none";
|
|
23
|
+
|
|
24
|
+
export function renderStatus(r: StatusResult, o: TextOptions): string {
|
|
25
|
+
const title = `${homeLine(r, o)} ${r.healthy ? paint("healthy", "ok", o) : paint("unhealthy", "fail", o)}`;
|
|
26
|
+
const vaults = r.vaults.length ? table(["VAULT", "KIND", "WRITE", "PII", "HEALTH", "PATH"], r.vaults.map(v => [v.id, v.kind, v.write, v.pii, v.healthy ? OK : FAIL, v.path]), o) : paragraph(NO_VAULTS, o);
|
|
27
|
+
const issues = r.vaults.filter(v => v.issue).map(v => paragraph(`${v.id}: ${v.issue}`, o, "fail")).join("\n");
|
|
28
|
+
const specs = r.specs?.length ? table(["SOURCE", "WRITE", "PII", "PATH"], r.specs.map(s => [s.id, s.write, s.pii, s.path]), o) : undefined;
|
|
29
|
+
return blocks(title, issues ? `${vaults}\n${issues}` : vaults, specs);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function tidyFinding(t: NonNullable<VaultRow["tidy"]>): string {
|
|
33
|
+
const pending = Object.entries(t.pending).filter(([, n]) => n > 0).map(([rule, n]) => `${rule} ${n}`).join(", ");
|
|
34
|
+
return [`${plural(t.notes, "note")} to migrate${pending ? ` (${pending})` : ""}`, t.unparsable.length ? `${plural(t.unparsable.length, "unparsable note")} skipped` : ""].filter(Boolean).join("; ");
|
|
35
|
+
}
|
|
36
|
+
export function renderDoctor(r: StatusResult, o: TextOptions): string {
|
|
37
|
+
let failed = 0;
|
|
38
|
+
const vaults = r.vaults.map(v => {
|
|
39
|
+
const rows: CellInput[][] = [[v.healthy ? OK : FAIL, "path", v.healthy ? v.path : `${v.path}: ${v.issue ?? "unavailable"}`]];
|
|
40
|
+
if (!v.healthy) failed++;
|
|
41
|
+
for (const [name, check] of Object.entries(v.checks ?? {})) {
|
|
42
|
+
if (!check.ok) failed++;
|
|
43
|
+
rows.push([check.ok ? OK : FAIL, name, check.ok ? (name === "remote" ? v.remote : name === "registry" ? v.registry : "ok") : check.issue]);
|
|
44
|
+
}
|
|
45
|
+
if (v.tidy) rows.push([WARN, "tidy", tidyFinding(v.tidy)]);
|
|
46
|
+
const next = v.tidy ? `\n${nextCommand("next", `vmem tidy ${shellWord(v.id)} --all`, o)}, then confirm its fingerprint to apply the migration` : "";
|
|
47
|
+
return `${heading(`Vault ${v.id}`, o)}\n${table(["LEVEL", "CHECK", "FINDING"], rows, o)}${next}`;
|
|
48
|
+
});
|
|
49
|
+
const specs = (r.specs ?? []).map(s => {
|
|
50
|
+
if (s.healthy === false) failed++;
|
|
51
|
+
return `${heading(`Spec source ${s.id}`, o)}\n${table(["LEVEL", "CHECK", "FINDING"], [[s.healthy === false ? FAIL : OK, "root", s.healthy === false ? s.issue : s.path]], o)}`;
|
|
52
|
+
});
|
|
53
|
+
const checked = [plural(r.vaults.length, "vault"), ...(r.specs ? [plural(r.specs.length, "spec source")] : [])].join(" and ");
|
|
54
|
+
const verdict = r.healthy ? paragraph(`healthy: ${checked} checked`, o, "ok")
|
|
55
|
+
: paragraph(`unhealthy: ${plural(failed, "failed check")}; fix the findings above, then run vmem doctor again`, o, "fail");
|
|
56
|
+
return blocks(homeLine(r, o), r.vaults.length ? undefined : paragraph(NO_VAULTS, o), ...vaults, ...specs, verdict);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export function renderStats(r: VaultStats, o: TextOptions): string {
|
|
60
|
+
const counts = (record: Record<string, number>) => fields(Object.entries(record).sort(([a, x], [b, y]) => y - x || a.localeCompare(b)), o);
|
|
61
|
+
const block = (name: string, body: string) => body ? `${heading(name, o)}\n${body}` : undefined;
|
|
62
|
+
const log = r.log.total === null ? paragraph("unreadable; see the issues below", o, "fail", " ")
|
|
63
|
+
: fields([["total", r.log.total], ...Object.entries(r.log.byType ?? {}).filter(([, n]) => n > 0).sort(([a, x], [b, y]) => y - x || a.localeCompare(b))], o);
|
|
64
|
+
return blocks(`${heading(r.vault, o)} ${plural(r.notes.total, "note")} as of ${r.asOf}`,
|
|
65
|
+
block("Notes by type", counts(r.notes.byType)), block("Notes by domain", counts(r.notes.byDomain)), block("Notes by status", counts(r.notes.byStatus)),
|
|
66
|
+
block("Modified", fields([["last 7 days", r.modified.last7Days], ["last 30 days", r.modified.last30Days]], o)),
|
|
67
|
+
block(`Log since ${r.log.since} (${plural(r.log.days, "day")})`, log),
|
|
68
|
+
r.log.warnings.map(w => paragraph(`warning: ${w}`, o, "warn")).join("\n"), issueTable(r.log.issues, o));
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export function renderRecover(r: RecoveryReport, o: TextOptions): string {
|
|
72
|
+
const owner = r.lock.owner ? `pid ${r.lock.owner.pid} on ${r.lock.owner.host} since ${r.lock.owner.created}` : undefined;
|
|
73
|
+
const detail = fields([["lock", r.lock.path], ["state", r.lock.state], ["owner", owner], ["temporary files", r.temporaryFiles.join(", ")]], o);
|
|
74
|
+
if (r.blocked) return blocks(paragraph(`recovery blocked: ${r.blocked}`, o, "fail"), detail);
|
|
75
|
+
if (r.applied) {
|
|
76
|
+
const done = [r.lock.removed ? "the stale registry lock" : "", r.removedTemporaryFiles.length ? plural(r.removedTemporaryFiles.length, "temporary config file") : ""].filter(Boolean);
|
|
77
|
+
return paragraph(done.length ? `recovered: removed ${done.join(" and ")}` : "nothing to recover: no stale lock and no temporary config files", o, done.length ? "ok" : undefined);
|
|
78
|
+
}
|
|
79
|
+
const work = [r.lock.state === "stale" ? "the stale registry lock" : "", r.temporaryFiles.length ? plural(r.temporaryFiles.length, "temporary config file") : ""].filter(Boolean);
|
|
80
|
+
if (!work.length) return paragraph("nothing to recover: no stale lock and no temporary config files", o);
|
|
81
|
+
return blocks(paragraph(`dry run: would remove ${work.join(" and ")}`, o), detail, nextCommand("confirm", "vmem recover --confirm", o));
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export function renderVaultsList(vaults: VaultRow[], o: TextOptions): string {
|
|
85
|
+
return vaults.length ? table(["VAULT", "KIND", "WRITE", "PII", "DOMAINS", "PATH"], vaults.map(v => [v.id, v.kind, v.write, v.pii, effectiveDomains(v).join(", "), v.path]), o) : paragraph(NO_VAULTS, o);
|
|
86
|
+
}
|
|
87
|
+
export function renderVaultAdd(r: { vault: VaultSpec }, o: TextOptions): string {
|
|
88
|
+
const v = r.vault;
|
|
89
|
+
return paragraph(`registered vault ${v.id}: ${v.kind}, write ${v.write}, PII ${effectivePii(v)}, at ${v.path}`, o, "ok");
|
|
90
|
+
}
|
|
91
|
+
export function renderSpecsList(specs: SpecSourceSpec[], o: TextOptions): string {
|
|
92
|
+
return specs.length ? table(["SOURCE", "WRITE", "PII", "PATH"], specs.map(s => [s.id, s.write, s.pii, s.path]), o)
|
|
93
|
+
: paragraph("no spec sources registered; add one with vmem specs add <id> <absolute-path>", o);
|
|
94
|
+
}
|
|
95
|
+
export function renderSpecAdd(r: { spec: SpecSourceSpec }, o: TextOptions): string {
|
|
96
|
+
return paragraph(`registered spec source ${r.spec.id}: write ${r.spec.write}, PII ${r.spec.pii}, at ${r.spec.path}`, o, "ok");
|
|
97
|
+
}
|
|
98
|
+
/** `vaults remove` and `specs remove`: unregistering only, so the files are always said to stay. */
|
|
99
|
+
export function renderRemove(group: "vaults" | "specs", r: { applied: boolean; vault?: { id: string; path: string }; spec?: { id: string; path: string } }, o: TextOptions): string {
|
|
100
|
+
const entry = (r.vault ?? r.spec)!, what = `${group === "vaults" ? "vault" : "spec source"} ${entry.id} at ${entry.path}`;
|
|
101
|
+
const stays = group === "vaults" ? "its files stay on disk" : "the repository stays on disk";
|
|
102
|
+
if (r.applied) return paragraph(`unregistered ${what}; ${stays}`, o, "ok");
|
|
103
|
+
return blocks(paragraph(`dry run: would unregister ${what}; ${stays}`, o), nextCommand("confirm", `vmem ${group} remove ${shellWord(entry.id)} --confirm`, o));
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
export interface PiiResult { vault: string; pii: string; piiPolicy: PiiMatrix; applied?: boolean; changed?: boolean; loosened?: string[]; preview?: true }
|
|
107
|
+
/** `confirm` is the exact command that applies a preview; the result itself does not carry the `--set` value. */
|
|
108
|
+
export function renderVaultPii(r: PiiResult, o: TextOptions, confirm?: string): string {
|
|
109
|
+
const row = (name: string, cells: PiiRow): CellInput[] => [name, ...PII_SURFACES.map(surface => cells[surface])];
|
|
110
|
+
const matrix = table(["CATEGORY", "NOTES", "LOG", "PROMOTION"], [row("email", r.piiPolicy.email), row("phone", r.piiPolicy.phone), row("custom", r.piiPolicy.custom),
|
|
111
|
+
...r.piiPolicy.patterns.map(p => row(`pattern ${p.name}`, p.action))], o);
|
|
112
|
+
const allow = r.piiPolicy.allow.length ? paragraph(`allow list: ${plural(r.piiPolicy.allow.length, "entry", "entries")} (shown with --json)`, o) : undefined;
|
|
113
|
+
const title = r.changed === undefined ? `Vault ${r.vault} PII policy: ${r.pii}`
|
|
114
|
+
: !r.changed ? `unchanged: vault ${r.vault} already has this PII policy (${r.pii})`
|
|
115
|
+
: r.applied ? `set the PII policy of vault ${r.vault} to ${r.pii}` : `dry run: would set the PII policy of vault ${r.vault} to ${r.pii}`;
|
|
116
|
+
const loosened = r.loosened?.length ? r.loosened.map(cell => paragraph(`loosens ${cell}`, o, "warn")).join("\n") : undefined;
|
|
117
|
+
const next = r.preview && r.changed && confirm ? nextCommand("confirm", confirm, o) : undefined;
|
|
118
|
+
return blocks(paragraph(title, o, r.applied ? "ok" : undefined), matrix, allow, loosened, next);
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
export function renderManifest(m: Manifest, o: TextOptions): string {
|
|
122
|
+
const tools = m.mcp.tools.map(t => typeof t === "string" ? [t, "may write"] : [t.name, tone("read-only", "muted")]);
|
|
123
|
+
return blocks(`${heading(`${m.name} ${m.version}`, o)} config format ${m.configVersion}`,
|
|
124
|
+
`${heading(`MCP server ${m.mcp.server}`, o)}: ${plural(tools.length, "tool")}\n${table(["TOOL", "ACCESS"], tools, o)}`,
|
|
125
|
+
`${heading("Commands", o)}: ${m.commands.length}\n${paragraph(m.commands.join(", "), o, undefined, " ")}`);
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** `apply` is the exact command that applies a dry run. */
|
|
129
|
+
export function renderSetup(r: SetupReport, o: TextOptions, apply?: string): string {
|
|
130
|
+
const rows = [...r.actions.map(a => ({ host: a.target, ...a })), ...(r.console ? [{ host: "console", ...r.console }] : [])];
|
|
131
|
+
const reasons = rows.some(a => a.reason), refused = rows.filter(a => a.change === "refused").length, pending = rows.some(a => !["none", "unchanged", "refused"].includes(a.change));
|
|
132
|
+
const title = r.mode === "dry-run" ? "dry run: nothing written" : r.applied ? (r.mode === "apply" ? "setup applied" : "setup undone") : "unchanged: nothing to do";
|
|
133
|
+
const changeTone = (change: string) => change === "refused" ? "fail" : ["none", "unchanged"].includes(change) ? "muted" : "info";
|
|
134
|
+
return blocks(paragraph(title, o, r.applied ? "ok" : undefined),
|
|
135
|
+
fields([["server", [r.entry.command, ...r.entry.args].map(shellWord).join(" ")], ["root", r.root ? `${r.root.path} (${r.root.version})` : undefined]], o),
|
|
136
|
+
rows.length ? table(["HOST", "CHANGE", "PATH", ...(reasons ? ["REASON"] : [])], rows.map(a => [a.host, tone(a.change, changeTone(a.change)), a.file, a.reason]), o) : undefined,
|
|
137
|
+
r.notes.map(note => paragraph(note, o)).join("\n"),
|
|
138
|
+
refused ? paragraph(`${plural(refused, "host")} refused; see REASON.`, o, "fail") : undefined,
|
|
139
|
+
r.mode === "dry-run" && pending && apply ? nextCommand("apply", apply, o) : undefined);
|
|
140
|
+
}
|