@staix/vault-mem 0.11.0 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +17 -2
  3. package/bin/vmem.js +5 -1
  4. package/package.json +2 -1
  5. package/skills/_shared/vault-adapter.md +131 -0
  6. package/skills/skill-mine/SKILL.md +52 -0
  7. package/skills/skill-mine/vocab/actions.yaml +110 -0
  8. package/skills/skill-mine/vocab/objects.yaml +123 -0
  9. package/skills/vault-connect/SKILL.md +75 -0
  10. package/skills/vault-extract/README.md +20 -0
  11. package/skills/vault-extract/SKILL.md +139 -0
  12. package/skills/vault-graph/SKILL.md +120 -0
  13. package/skills/vault-learn/SKILL.md +111 -0
  14. package/skills/vault-lint/README.md +32 -0
  15. package/skills/vault-lint/SKILL.md +137 -0
  16. package/skills/vault-lint/references/lint-output.md +97 -0
  17. package/skills/vault-lint/references/vault-scope-rules.md +26 -0
  18. package/skills/vault-lint/references/work-scope-checks.md +71 -0
  19. package/skills/vault-refactor/SKILL.md +112 -0
  20. package/skills/vault-remember/SKILL.md +38 -0
  21. package/skills/vault-rethink/README.md +15 -0
  22. package/skills/vault-rethink/SKILL.md +58 -0
  23. package/skills/vault-stats/SKILL.md +49 -0
  24. package/skills/vault-sync/README.md +15 -0
  25. package/skills/vault-sync/SKILL.md +195 -0
  26. package/skills/vault-sync/references/r4-method-evidence.md +12 -0
  27. package/skills/vault-update/SKILL.md +68 -0
  28. package/skills/vmem-status/SKILL.md +30 -0
  29. package/src/amem/host-api.ts +5 -1
  30. package/src/analysis-input.ts +15 -0
  31. package/src/analysis-types.ts +3 -1
  32. package/src/assertion-policy.ts +4 -2
  33. package/src/assertions.ts +48 -8
  34. package/src/cli-output.ts +10 -3
  35. package/src/cli.ts +29 -3
  36. package/src/commands-table.ts +3 -1
  37. package/src/config.ts +21 -7
  38. package/src/enrichment-query.ts +65 -0
  39. package/src/enrichment-search.ts +69 -0
  40. package/src/enrichment-store.ts +197 -0
  41. package/src/enrichment.ts +245 -0
  42. package/src/graph-evidence.ts +2 -2
  43. package/src/index.ts +9 -0
  44. package/src/mcp-vault.ts +46 -8
  45. package/src/proposal-provider.ts +3 -2
  46. package/src/proposals.ts +10 -4
  47. package/src/read-output.ts +1 -1
  48. package/src/registry.ts +57 -2
  49. package/src/setup.ts +12 -3
  50. package/src/skills-install.ts +216 -0
  51. package/src/ui/panel-types.ts +55 -0
  52. package/src/ui/panel.js +76 -0
  53. package/src/ui/plugin.ts +95 -5
  54. package/src/vault-graph.ts +15 -7
  55. package/src/vault-index.ts +17 -0
  56. package/src/vault-lint.ts +12 -4
  57. package/src/write-operations.ts +38 -1
  58. package/src/write-types.ts +1 -0
  59. package/src/write-validation.ts +2 -1
  60. package/src/writer.ts +1 -1
@@ -0,0 +1,68 @@
1
+ ---
2
+ name: vault-update
3
+ trigger: /vault-update
4
+ description: Refresh an outdated note with new context while preserving core insight (via vmem)
5
+ ---
6
+
7
+ # /vault-update [note]
8
+
9
+ > Before the first vmem call, read `references/vault-adapter.md` §Runtime Discovery and select and bind the vmem vault id; pass it as `vault` on every vmem tool call and as the `<vault>` argument of every `vmem` CLI command.
10
+
11
+ Update a note with new information while preserving original meaning. This is the single-note leaf; batch discovery of notes that need updating is `/vault-sync` (its "update" proposals run this procedure). Every update follows `/vault-extract` §Extraction Fidelity and Concurrent Writers, and step 3 applies its rules to a revision.
12
+
13
+ ## Input
14
+ - note: filename or path in `notes/`
15
+
16
+ ## Process
17
+
18
+ 1. Read target note via `vmem_read` (keep its `sha256` for `expectedSha`)
19
+ 2. Identify what's changed (new context, superseded info, additional evidence)
20
+ 3. Draft the update:
21
+ - preserve core insight
22
+ - add new content in an explicit section (e.g., `## Update YYYY-MM-DD`) OR inline-revise with preservation: a revised value that came from a source keeps the earlier value and its source beside it, e.g. `amount 3,000,000 (source: work/<contract>.md); revised 4,000,000 (source: work/<minutes>.md)`
23
+ 4. Apply via vmem:
24
+ - minor edit → `vmem_patch(path, oldString, newString, expectedSha)`
25
+ - new section → `vmem_append(path, section: "Update YYYY-MM-DD", markdown)`
26
+ - major rewrite → there is no overwrite tool: patch section by section, or create a replacement note with `vmem_create` and retire the old one with `vmem_supersede(old, next)`
27
+ - the new information duplicates another note → do not update into a copy: offer `vmem_merge(keep, absorb)` at the approval gate, preview first and confirm with the fingerprint; it unions source and topics and repoints inbound links itself
28
+ - frontmatter change → `vmem_set_frontmatter(path, set, unset, expectedSha)`
29
+ - expect: vmem refuses a stale `expectedSha`, an invalid frontmatter value, a new unresolved wiki link, an edit inside `## Topics`, and a `vmem_merge` of different types, a person or MOC note, or an oversized result
30
+ 5. Check connected notes (via `vmem_links(path)` and `vmem_brief(intent: "<title> <description>", bytes: 1024)`); propose cascading updates if needed
31
+ 6. Record update in note body (timestamp or changelog line)
32
+ 7. Run `/vault-lint note=<path>` on the updated note; `--note` is CLI-only, so an MCP-only run finishes with one vault-wide `vmem_lint` instead
33
+ 8. vmem logs every write with a default `EXTRACT` line; when wiki-links changed, pass `log: {type: "CONNECT", ...}` on the write that changed them (see §Log Append)
34
+
35
+ ## Vault Access
36
+
37
+ Use vmem through the transport in the adapter. No filesystem Read/Write/Edit on vault paths. Use:
38
+
39
+ | Operation | vmem tool |
40
+ |-----------|---------|
41
+ | Read | `vmem_read` |
42
+ | Full rewrite | section `vmem_patch` calls, or `vmem_create` + `vmem_supersede` |
43
+ | Append | `vmem_append` |
44
+ | Targeted edit | `vmem_patch` |
45
+ | Frontmatter and tags | `vmem_set_frontmatter` |
46
+ | Search for impact | `vmem_links`, `vmem_search` |
47
+
48
+ ## Quality Gates
49
+
50
+ - Original insight must be preserved OR explicitly superseded with `status: superseded` frontmatter + link to replacement note
51
+ - All existing wiki-links must remain valid
52
+ - New wiki-links added where relevant
53
+ - Changelog/timestamp line appended to body when content changes materially
54
+
55
+ ## Log Append
56
+
57
+ Each vmem write records exactly one line: its default `EXTRACT` event, or the event the call passes in `log`. Nothing suppresses it, so a body-only edit is logged too and is never silent. When the edit adds or removes a wiki link or MOC membership, pass `log: {type: "CONNECT", project, source: "notes/<note>.md", dest, note: "updated: <summary>"}` on the write that changed them:
58
+
59
+ ```
60
+ YYYY-MM-DD HH:MM CONNECT <project> notes/<note>.md — updated: <summary>
61
+ ```
62
+
63
+ ## Output
64
+
65
+ - Summary of changes made
66
+ - Connected notes reviewed (and any cascading proposals)
67
+ - note-level `/vault-lint` result
68
+ - log append status (if applicable)
@@ -0,0 +1,30 @@
1
+ ---
2
+ name: vmem-status
3
+ description: Use when asked which vmem version is installed, whether vmem is up to date, or whether the vmem install and its vault registry are healthy (not note content; that is vault-stats). Reports the running vmem build, installed skill version, other installs on PATH, registered vaults and doctor findings, read-only.
4
+ ---
5
+
6
+ # vmem-status
7
+
8
+ Answer "what vmem runs here and is it healthy" in one report. Every step is read-only: give repairs as commands for the person to run.
9
+
10
+ ## Process
11
+
12
+ When only MCP is available, call `vmem_status` for its registered vaults and health; use MCP server version metadata if the host exposes it. Compare that version with the local marker when both are available. Report the CLI build, PATH, doctor, recover and other CLI-only checks as unavailable, not healthy or failed. Do not infer fields absent from the MCP response. When only the CLI is available, run steps 1–5 and skip the MCP comparison.
13
+
14
+
15
+ 1. **Build**: run `vmem --version`. Read `version` from `.vmem-skill.json` in this installed skill directory and compare it with the running version. Report a mismatch as stale skills and suggest `vmem setup <host> --apply` for the actual host. If the marker is missing or unreadable, report the skill version as unknown.
16
+ 2. **Other installs**: list every `vmem` on PATH (`which -a vmem`, `where vmem` on Windows) and run `--version` on each distinct resolved file. When versions differ, the lower one is stale. A stale install that runs is replaced by fixing PATH order or removing it; a stale shadowed install runs whenever PATH order changes, so remove it.
17
+ 3. **Registry**: run `vmem status --json`. Take `version`, `home`, `source`, `healthy`, and per vault `id`, `kind`, `write`, `pii`, `healthy`, `path`.
18
+ 4. **Doctor**: run `vmem doctor --json`. Its top-level `healthy` and exit code (1 means unhealthy, a finding to report, not a failure of this skill) are the verdict. Report each vault with `healthy: false` and its `issue`, each `vaults[].checks.<name>` with `ok: false` and its `issue`, each `specs[]` entry with `healthy: false` and its `issue`, and each vault's `tidy` (pending migration) as a warning.
19
+ 5. **Leftovers**: run `vmem recover --json` without `--confirm`; it only previews. Report `lock.state` and any `temporaryFiles`. Exit 1 with `blocked` is a finding: a `live` lock means a writer is running, so wait and rerun; an `unknown` owner (unreadable, or another host's lock) means the person confirms no writer runs on any host, then removes `lock.path` by hand.
20
+ 6. **MCP**: when the vmem MCP tools are available, call `vmem_status`. If step 3 also ran, a vault list that differs from step 3 means the MCP server started before the last registry change (restart the host session) or runs another build or home; report which fits. A `vaults remove` does not show as a mismatch, so after one the server needs a restart either way.
21
+
22
+ A matching skill marker and running version proves only local consistency, not that either is the latest release. When asked whether vmem is up to date, compare the running version with a verifiable current release from the package registry or release source when available; identify that source. If it cannot be checked, report latest-release status as unknown.
23
+
24
+ ## Output
25
+
26
+ - One line: running version, installed skill version and local match verdict; separately report latest-release status as current, outdated, or unknown with its evidence.
27
+ - Other installs with versions, only when step 2 found any.
28
+ - Vaults table: id, kind, write, pii, health, path.
29
+ - Doctor failures and tidy warnings from step 4; "healthy" only when doctor's `healthy` is true.
30
+ - At most one next action with its command: repair stale skills with `vmem setup <host> --apply`, the repair a doctor `issue` names, `vmem recover --confirm` when step 5 is not `blocked` and shows a `stale` lock or `temporaryFiles`, rerunning `vmem recover --json` after a live writer finishes, or removing the file at `lock.path` once no writer runs, `vmem tidy <vault> --all` (preview) for pending migration, or removing a stale install with the package manager that owns it.
@@ -16,8 +16,12 @@ export function installedAmemVersion(entry: string): string {
16
16
  }
17
17
  }
18
18
  export const amemVersion = () => installedAmemVersion(createRequire(import.meta.url).resolve("@staix/agent-mem/platform"));
19
+ export class HostApiVersionError extends Error {
20
+ readonly code = "VMEM_HOST_API_INCOMPATIBLE";
21
+ }
22
+
19
23
  export function checkHostApi(api: { HOST_API_MIN?: unknown; HOST_API_VERSION?: unknown }, version: string): void {
20
24
  const min = api.HOST_API_MIN, max = api.HOST_API_VERSION;
21
25
  if (Number.isSafeInteger(min) && Number.isSafeInteger(max) && (min as number) >= 1 && (min as number) <= 1 && (max as number) >= 1) return;
22
- throw new Error(`agent-mem ${version}: host API ${String(min ?? "missing")}..${String(max ?? "missing")} is incompatible with vmem host API 1; update @staix/agent-mem or @staix/vault-mem to compatible versions`);
26
+ throw new HostApiVersionError(`agent-mem ${version}: host API ${String(min ?? "missing")}..${String(max ?? "missing")} is incompatible with vmem host API 1; update @staix/agent-mem or @staix/vault-mem to compatible versions`);
23
27
  }
@@ -1,3 +1,5 @@
1
+ import { createHash } from "node:crypto";
2
+ import { readEnrichmentStore } from "./enrichment-store.ts";
1
3
  import { localDate } from "./local-date.ts";
2
4
  import { MAX_REPORT_BYTES } from "./write-validation.ts";
3
5
  import { parseFrontmatter } from "./frontmatter.ts";
@@ -92,6 +94,19 @@ export function analysisInput(home: string, id: string, options: { today?: strin
92
94
  if(found.length)warnings[note.path]=found;
93
95
  }catch{ /* Invalid frontmatter remains visible to L02; do not infer missing source paths. */ }
94
96
  if(Object.keys(warnings).length)snapshot.sourceWarnings=warnings;
97
+ if (vault.graph?.resolution !== undefined) snapshot.graphResolution = vault.graph.resolution;
98
+ if (options.hints && vault.enrichment?.enabled) {
99
+ const store = readEnrichmentStore(home, vault, config.vaults, config.denyPaths ?? []);
100
+ const embeddings = new Set(store.records.filter(r => r.kind === "embedding").map(r => JSON.stringify([r.path, r.contentHash])));
101
+ const paths = new Set(store.records.filter(r => r.kind === "embedding").map(r => r.path));
102
+ const enrichmentWarnings: Record<string, string[]> = Object.create(null);
103
+ for (const note of snapshot.notes) {
104
+ const path = `notes/${note.path.replace(/^notes\//, "")}`;
105
+ const hash = createHash("sha256").update(note.source).digest("hex");
106
+ if (!embeddings.has(JSON.stringify([path, hash]))) enrichmentWarnings[note.path] = [`embedding ${paths.has(path) ? "stale" : "missing"}; run enrichment for the current note`];
107
+ }
108
+ snapshot.enrichmentWarnings = enrichmentWarnings;
109
+ }
95
110
  // Evidence drift is a read/lint finding: status and reason only, never the quote or source text.
96
111
  const drift:Record<string,string[]>=Object.create(null),reads:EvidenceReads=new Map();
97
112
  for(const note of snapshot.notes)try{
@@ -3,6 +3,8 @@ import type { TitleSuggestion } from "./links.ts";
3
3
  export interface AnalysisSnapshot {
4
4
  /** Effective selected-vault domain set; standalone snapshots default to the built-ins. */
5
5
  domains?: string[];
6
+ graphResolution?: number;
7
+ enrichmentWarnings?: Record<string, string[]>;
6
8
  notes: { path: string; source: string }[];
7
9
  today: string;
8
10
  logPath: string;
@@ -27,7 +29,7 @@ export interface AnalysisSnapshot {
27
29
  */
28
30
  linkHintBound?: { cap: number; attempted: readonly string[]; skipped: number };
29
31
  }
30
- export type LintCode = "L01" | "L02" | "L03" | "L09" | "L10" | "L11" | "L12" | "L13" | "L14" | "L15" | "L16" | "L17";
32
+ export type LintCode = "L01" | "L02" | "L03" | "L09" | "L10" | "L11" | "L12" | "L13" | "L14" | "L15" | "L16" | "L17" | "L18" | "L19";
31
33
  export interface LintReport {
32
34
  findings: Record<LintCode, string[]>;
33
35
  errors: number;
@@ -8,10 +8,11 @@ import { screenContent } from "./write-validation.ts";
8
8
  import type { AssertionItem } from "./assertions.ts";
9
9
 
10
10
  export type AssertionValue = string | { withheld: "secret" | "pii_policy" };
11
- export type ScreenedAssertion = Omit<AssertionItem, "value" | "evidence" | "source"> & {
11
+ export type ScreenedAssertion = Omit<AssertionItem, "value" | "evidence" | "source" | "origin"> & {
12
12
  value?: AssertionValue;
13
13
  evidence?: Record<string, unknown>[];
14
14
  source?: (string | { withheld: true })[];
15
+ origin?: AssertionItem["origin"] | { withheld: true };
15
16
  availability?: "unavailable";
16
17
  };
17
18
 
@@ -31,8 +32,9 @@ function deniedSource(source: string, vault: VaultSpec, config: VmemConfig): boo
31
32
 
32
33
  /** Screen every field on every read. A denied evidence entry reveals neither its source, quote nor hashes. */
33
34
  export function screenAssertion(item: AssertionItem, vault: VaultSpec, config: VmemConfig, reads: EvidenceReads, budget: EvidenceReadBudget): ScreenedAssertion {
34
- const { value, evidence, source, ...safe } = item;
35
+ const { value, evidence, source, origin, ...safe } = item;
35
36
  const out: ScreenedAssertion = { ...safe };
37
+ if (origin !== undefined) out.origin = !origin || typeof origin !== "object" || typeof origin.path !== "string" || !/^notes\/[^/\\]+\.md$/.test(origin.path) || isDenied(origin.path, config.denyPaths ?? []) || isDenied(canonicalPath(resolve(vault.path, origin.path)), config.denyPaths ?? []) || withheld(JSON.stringify(origin), vault, config) ? { withheld: true } : origin;
36
38
  if (item.purged) { out.availability = "unavailable"; out.evidence = [{ status: "unavailable" }]; return out; }
37
39
  if (typeof value === "string") {
38
40
  const reason = withheld(value, vault, config);
package/src/assertions.ts CHANGED
@@ -6,7 +6,7 @@
6
6
  * `evaluateAssertions` is the pure evaluation the read surface wraps, and `appendAssertions` is the write contract.
7
7
  * Nothing here writes a note, an `updated` stamp or a log line unless the caller supplies a log event.
8
8
  */
9
- import { randomBytes } from "node:crypto";
9
+ import { createHash, randomBytes } from "node:crypto";
10
10
  import { closeSync, constants, fstatSync, fsyncSync, ftruncateSync, lstatSync, mkdirSync, openSync, readdirSync, readSync, realpathSync, renameSync, unlinkSync, writeFileSync, writeSync } from "node:fs";
11
11
  import { hostname } from "node:os";
12
12
  import { join, resolve } from "node:path";
@@ -19,6 +19,7 @@ import { canonicalPath, isDenied } from "./platform.ts";
19
19
  import { loadRegistry, syncDirectory } from "./registry.ts";
20
20
  import { sourceReferences, sourceWorkspaceRoot } from "./source.ts";
21
21
  import { appendLog, checkLogEvent } from "./vault-log.ts";
22
+ import { MAX_NOTE_BYTES } from "./vault-index.ts";
22
23
  import { screenContent, screenMetadata } from "./write-validation.ts";
23
24
  import type { WriteIssue } from "./write-types.ts";
24
25
  import { shellWord } from "./text-output.ts";
@@ -73,7 +74,7 @@ export type Answer = "yes" | "no" | "unknown";
73
74
  export interface AssertionItem {
74
75
  id: string; rev: number; op: "assert" | "revise" | "retract"; subject: string; relation: string; hash: string;
75
76
  value?: string; kind?: "state" | "event"; from?: string; to?: string; held_on?: string; on?: string; reason?: string;
76
- evidence?: unknown[]; source?: string[];
77
+ evidence?: unknown[]; source?: string[]; origin?: EnrichmentOrigin & { status: "unverified" };
77
78
  answer?: Answer; recordedAt: string; effectiveRecordedAt?: string; clockInverted?: true; replacedAt?: string | null;
78
79
  revisionConflict?: true; heads?: string[]; purged?: true;
79
80
  segment?: string; seq?: number;
@@ -384,7 +385,7 @@ function item(state: AssertionState, kept: Kept, t: number | undefined): Asserti
384
385
  const { entry } = kept, payload = entry.payload ?? {};
385
386
  const out: AssertionItem = { id: state.id, rev: entry.op === "assert" ? 1 : entry.purged ? kept.depth + 1 : Number(payload.rev), op: entry.op as AssertionItem["op"], subject: entry.purged ? "" : state.subject, relation: entry.purged ? "" : state.relation, hash: entry.hash, recordedAt: entry.recorded_at };
386
387
  if (entry.purged) { out.purged = true; out.segment = entry.seg; out.seq = entry.seq; }
387
- for (const key of ["value", "kind", "from", "to", "held_on", "on", "reason", "evidence", "source"] as const) if (payload[key] !== undefined) (out as unknown as Record<string, unknown>)[key] = payload[key];
388
+ for (const key of ["value", "kind", "from", "to", "held_on", "on", "reason", "evidence", "source", "origin"] as const) if (payload[key] !== undefined) (out as unknown as Record<string, unknown>)[key] = payload[key];
388
389
  if (kept.inverted) { out.effectiveRecordedAt = kept.effective; out.clockInverted = true; }
389
390
  if (t !== undefined && entry.op !== "retract" && !entry.purged) out.answer = answerOn(payload, t);
390
391
  return out;
@@ -463,6 +464,8 @@ export type AssertOp =
463
464
  | { op: "assert"; subject: string; relation: string; value: string; kind: "state" | "event"; from?: string; to?: string; held_on?: string; on?: string; evidence?: EvidenceEntry[]; source?: string[] }
464
465
  | { op: "revise"; id: string; expected_heads: string[]; value: string; kind: "state" | "event"; from?: string; to?: string; held_on?: string; on?: string; evidence?: EvidenceEntry[]; source?: string[] }
465
466
  | { op: "retract"; id: string; expected_heads: string[]; reason: typeof REASONS[number] };
467
+ export interface EnrichmentOrigin { path: string; sha256: string; producer: { skill: string; version: string; model: string }; createdAt: string; intakeId?: string }
468
+ export interface AssertOptions { env?: NodeJS.ProcessEnv; now?: Date; origin?: EnrichmentOrigin }
466
469
  export interface AssertRequest { vault: string; ops: unknown; channel?: "cli" | "mcp"; dryRun?: boolean; log?: LogEvent }
467
470
  export interface AssertReceipt {
468
471
  ok: boolean; applied: boolean; dryRun: boolean;
@@ -564,7 +567,7 @@ function context(home: string, request: { vault: string; channel?: "cli" | "mcp"
564
567
  return { vault, config, root, channel };
565
568
  }
566
569
  /** Validate a batch against the journal as read (shapes, bounds, temporal rules, evidence, screening, heads). */
567
- function plan(ctx: Context, ops: unknown, journal: VerifiedJournal): Planned[] {
570
+ function plan(ctx: Context, ops: unknown, journal: VerifiedJournal, origin?: EnrichmentOrigin): Planned[] {
568
571
  if (!ops || !Array.isArray(ops) || ops.length < 1 || ops.length > MAX_BATCH_OPS) refuse("V01", `ops must be a list of 1..${MAX_BATCH_OPS} operations; split larger batches`);
569
572
  if (bytes(canonical(ops)) > MAX_BATCH_BYTES) refuse("V09", `the canonical batch exceeds ${MAX_BATCH_BYTES} bytes; split it into smaller batches`);
570
573
  const resolved = resolveEntries(journal), { assertions, subjects } = states(resolved.kept.values());
@@ -614,6 +617,7 @@ function plan(ctx: Context, ops: unknown, journal: VerifiedJournal): Planned[] {
614
617
  entry = { op: "revise", id: op.id, target: op.id, parents: heads, payload: { id: op.id, rev, value: held, ...world, evidence: backing.evidence, ...(backing.source ? { source: backing.source } : {}) } };
615
618
  }
616
619
  }
620
+ if (origin && (entry.op === "assert" || entry.op === "revise")) entry.payload.origin = { ...origin, status: "unverified" };
617
621
  const text = canonical(entry.payload);
618
622
  if (bytes(text) > MAX_PAYLOAD_BYTES) refuse("V09", `${at}: payload exceeds ${MAX_PAYLOAD_BYTES} bytes as canonical JSON; shorten quotes or split evidence`);
619
623
  const screened = [...screenContent(text, ctx.vault, ctx.config, "notes"), ...screenMetadata(entry.payload, { vault: ctx.vault, config: ctx.config, piiSurface: "notes" }, at)]
@@ -701,14 +705,43 @@ function release(lock: { fd: number; file: string; ino: number; dev: number }, i
701
705
  } catch { issues.push({ code: "CLEANUP", severity: "warning", message: "assertions lock retained; inspect before removing it manually" }); }
702
706
  }
703
707
 
708
+ /** Validate untrusted producer claims independently of the public request schema. */
709
+ function validateOrigin(value: unknown): EnrichmentOrigin {
710
+ if (!value || typeof value !== "object" || Array.isArray(value)) refuse("V01", "origin must contain path, sha256, producer and createdAt");
711
+ const origin = value as Record<string, unknown>, producer = origin.producer;
712
+ if ((Object.keys(origin).some(key => !["createdAt", "path", "producer", "sha256", "intakeId"].includes(key)) || (origin.intakeId !== undefined && (typeof origin.intakeId !== "string" || !/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(origin.intakeId)))) || typeof origin.path !== "string" || !/^notes\/[^/\\]+\.md$/.test(origin.path) || /\p{Cc}/u.test(origin.path) || !origin.path.isWellFormed() || typeof origin.sha256 !== "string" || !HEX64.test(origin.sha256) || !(typeof origin.createdAt === "string" && !Number.isNaN(Date.parse(origin.createdAt)) && new Date(origin.createdAt).toISOString() === origin.createdAt) || !producer || typeof producer !== "object" || Array.isArray(producer) || Object.keys(producer).sort().join(",") !== "model,skill,version") refuse("V01", "origin requires a flat note path, lowercase SHA-256, canonical ISO createdAt and producer skill, version and model");
713
+ for (const value of Object.values(producer as Record<string, unknown>)) if (typeof value !== "string" || !value.trim() || bytes(value) > 200 || /\p{Cc}/u.test(value) || !value.isWellFormed()) refuse("V01", "origin producer fields must be nonempty well-formed text of at most 200 bytes without control characters");
714
+ return origin as unknown as EnrichmentOrigin;
715
+ }
716
+ /** Recheck exact bytes of a plain note under the journal lock immediately before publication. */
717
+ function verifyOrigin(ctx: Context, origin: EnrichmentOrigin): void {
718
+ const file = join(ctx.root, origin.path), notes = join(ctx.root, "notes");
719
+ if (isDenied(origin.path, ctx.config.denyPaths ?? []) || isDenied(canonicalPath(file), ctx.config.denyPaths ?? [])) refuse("V06", "origin note is denied by current policy; choose an allowed source");
720
+ let fd: number | undefined;
721
+ try {
722
+ if (realpathSync(notes) !== notes) refuse("V04", "origin notes directory must be a plain directory; inspect the vault path");
723
+ fd = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
724
+ const before = fstatSync(fd, { bigint: true });
725
+ if (!before.isFile() || before.size > BigInt(MAX_NOTE_BYTES)) refuse("V09", "origin note must be a bounded regular file; inspect the source");
726
+ const data = Buffer.alloc(Number(before.size) + 1); let length = 0;
727
+ while (length < data.length) { const n = readSync(fd, data, length, data.length - length, null); if (!n) break; length += n; }
728
+ const after = fstatSync(fd, { bigint: true }), named = lstatSync(file, { bigint: true });
729
+ if (named.isSymbolicLink() || named.dev !== after.dev || named.ino !== after.ino || length !== Number(before.size) || before.dev !== after.dev || before.ino !== after.ino || before.size !== after.size || before.mtimeNs !== after.mtimeNs || before.ctimeNs !== after.ctimeNs) refuse("CONCURRENT", "origin note changed during verification; reread it and regenerate the result");
730
+ if (createHash("sha256").update(data.subarray(0, length)).digest("hex") !== origin.sha256) refuse("STALE_ORIGIN", "origin source content hash is stale; reread the note and regenerate the result before retrying");
731
+ } catch (caught) {
732
+ if (caught instanceof Refused) throw caught;
733
+ refuse("V04", "origin note cannot be read as a plain file; inspect its path and retry");
734
+ } finally { if (fd !== undefined) closeSync(fd); }
735
+ }
736
+
704
737
  /**
705
738
  * Validate and append one batch (design: Write contract). All-or-nothing: any error refuses the whole batch before
706
739
  * any byte is written. A dry run validates against the journal as read, without lock, append or `recordedAt`.
707
740
  */
708
- export function appendAssertions(home: string, request: AssertRequest, options: { env?: NodeJS.ProcessEnv; now?: Date } = {}): AssertReceipt {
741
+ export function appendAssertions(home: string, request: AssertRequest, options: AssertOptions = {}): AssertReceipt {
709
742
  return appendAssertionsInternal(home, request, options);
710
743
  }
711
- function appendAssertionsInternal(home: string, request: AssertRequest, options: { env?: NodeJS.ProcessEnv; now?: Date }, heldRoot?: string): AssertReceipt {
744
+ function appendAssertionsInternal(home: string, request: AssertRequest, options: AssertOptions, heldRoot?: string): AssertReceipt {
712
745
  const env = options.env ?? process.env;
713
746
  const receipt: AssertReceipt = { ok: false, applied: false, dryRun: request?.dryRun === true, segment: null, entries: [], recovery: [], issues: [], indexUpdated: false };
714
747
  let lock: ReturnType<typeof acquire> | undefined;
@@ -721,16 +754,22 @@ function appendAssertionsInternal(home: string, request: AssertRequest, options:
721
754
  const logIssues = checkLogEvent(home, { vault: request.vault, event: request.log, channel: ctx.channel }, env);
722
755
  if (logIssues.length) throw new Refused(logIssues.map(found => ({ ...found, message: `log event refused, nothing written: ${found.message}; fix the event fields (rules as for log append) or omit it` })));
723
756
  }
757
+ const origin = options.origin === undefined ? undefined : validateOrigin(options.origin);
758
+ if (origin) {
759
+ const screened = [...screenContent(canonical(origin), ctx.vault, ctx.config, "notes"), ...screenMetadata({ ...origin }, { vault: ctx.vault, config: ctx.config, piiSurface: "notes" }, "origin")].filter(issue => issue.severity === "error");
760
+ if (screened.length) throw new Refused(screened);
761
+ }
724
762
  if (receipt.dryRun) {
763
+ if (origin) verifyOrigin(ctx, origin);
725
764
  const journal = readJournal(ctx.root, ctx.config.denyPaths ?? []);
726
- const planned = plan(ctx, request.ops, journal);
765
+ const planned = plan(ctx, request.ops, journal, origin);
727
766
  receipt.entries = planned.map(entry => ({ id: entry.id || "(assigned at append)", op: entry.op, ...(entry.op !== "subject" ? { rev: Number(entry.payload.rev) } : {}) }));
728
767
  receipt.ok = true;
729
768
  return receipt;
730
769
  }
731
770
  if (!heldRoot) lock = acquire(ctx.root);
732
771
  const journal = readJournal(ctx.root, ctx.config.denyPaths ?? []);
733
- const planned = plan(ctx, request.ops, journal);
772
+ const planned = plan(ctx, request.ops, journal, origin);
734
773
  if (journal.entries + planned.length > MAX_JOURNAL_ENTRIES) refuse("V09", `the journal would exceed ${MAX_JOURNAL_ENTRIES} entries; appends refuse rather than rotate history`);
735
774
  // An over-estimate only, so a segment chosen on it has room for the real lines; `parents` cost their own bytes.
736
775
  const estimate = planned.reduce((sum, entry) => sum + bytes(canonical(entry.payload)) + 1024 + (entry.parents ?? []).reduce((cost, parent) => cost + parent.length + 4, 0), 0);
@@ -762,6 +801,7 @@ function appendAssertionsInternal(home: string, request: AssertRequest, options:
762
801
  const buffer = Buffer.from(lines.join(""));
763
802
  // The journal bound is checked on the bytes that will be written, before the file is opened.
764
803
  if (journal.bytes + buffer.length > MAX_JOURNAL_BYTES) refuse("V09", `the journal would exceed ${MAX_JOURNAL_BYTES} bytes once this batch is written; appends refuse rather than rotate history`);
804
+ if (origin) verifyOrigin(ctx, origin);
765
805
  const dir = join(ctx.root, ASSERTIONS_DIR);
766
806
  let createdDir = false;
767
807
  try { const stat = lstatSync(dir); if (stat.isSymbolicLink() || !stat.isDirectory()) refuse("V04", "assertions/ must be a plain directory; move the file or link aside"); }
package/src/cli-output.ts CHANGED
@@ -7,6 +7,7 @@ import type { ResolvedHome } from "./home.ts";
7
7
  import type { PiiMatrix, PiiRow } from "./pii.ts";
8
8
  import { effectivePii, type RecoveryReport } from "./registry.ts";
9
9
  import type { SetupReport } from "./setup.ts";
10
+ import type { SkillInstallReport } from "./skills-install.ts";
10
11
  import { blocks, clean, fields, heading, issueTable, marker, nextCommand, paragraph as formatParagraph, plural, shellWord, status, table, tone, type CellInput, type TextOptions, type Tone } from "./text-output.ts";
11
12
  import { MAX_RATIO_NOTES } from "./vault-index.ts";
12
13
  import type { VaultStats } from "./vault-stats.ts";
@@ -147,10 +148,10 @@ export function renderManifest(m: Manifest, o: TextOptions): string {
147
148
 
148
149
  /** `apply` is the exact command that applies a dry run. */
149
150
  export function renderSetup(r: SetupReport, o: TextOptions, apply?: string): string {
150
- const rows = [...r.actions.map(a => ({ host: a.target, ...a })), ...(r.console ? [{ host: "console", ...r.console }] : [])];
151
- 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));
151
+ const rows = [...r.actions.map(a => ({ host: a.target, ...a })), ...(r.console ? [{ host: "console", ...r.console }] : []), ...(r.skills ?? []).flatMap(s => s.report ? s.report.actions.map(a => ({ host: `${s.target} skill`, file: a.path, change: a.change, reason: a.reason })) : [{ host: `${s.target} skill`, file: "-", change: s.refused ? "refused" : "none", reason: s.reason }])];
152
+ const reasons = rows.some(a => a.reason), refused = rows.filter(a => a.change === "refused").length, pending = rows.some(a => !["none", "unchanged", "absent", "refused", "foreign", "modified"].includes(a.change));
152
153
  const title = r.mode === "dry-run" ? "dry run: nothing written" : r.applied ? (r.mode === "apply" ? "setup applied" : "setup undone") : "unchanged: nothing to do";
153
- const changeTone = (change: string) => change === "refused" ? "fail" : ["none", "unchanged"].includes(change) ? "muted" : "info";
154
+ const changeTone = (change: string) => ["refused", "foreign", "modified"].includes(change) ? "fail" : ["none", "unchanged"].includes(change) ? "muted" : "info";
154
155
  return blocks(paragraph(title, o, r.applied ? "ok" : undefined),
155
156
  fields([["server", [r.entry.command, ...r.entry.args].map(shellWord).join(" ")], ["root", r.root ? `${r.root.path} (${r.root.version})` : undefined]], o),
156
157
  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,
@@ -158,3 +159,9 @@ export function renderSetup(r: SetupReport, o: TextOptions, apply?: string): str
158
159
  refused ? paragraph(`${plural(refused, "host")} refused; see REASON.`, o, "fail") : undefined,
159
160
  r.mode === "dry-run" && pending && apply ? nextCommand("apply", apply, o) : undefined);
160
161
  }
162
+
163
+ /** Human-readable summary for an exported skill tree. */
164
+ export function renderSkillsExport(report: SkillInstallReport, o: TextOptions): string {
165
+ const color = (change: string): Tone => ["foreign", "modified", "refused"].includes(change) ? "fail" : ["unchanged", "absent"].includes(change) ? "muted" : "info";
166
+ return blocks(heading(`skills export: ${clean(report.root)}`, o), table(["NAME", "CHANGE", "PATH", "REASON"], report.actions.map(action => [action.name, tone(action.change, color(action.change)), action.path, action.reason]), o));
167
+ }
package/src/cli.ts CHANGED
@@ -18,11 +18,11 @@ import { VMEM_TOOL_NAMES, vaultTools } from "./mcp-vault.ts";
18
18
  import { CONFIG_VERSION, effectiveDomains } from "./config.ts";
19
19
  import { runSetup, type SetupMode } from "./setup.ts";
20
20
  import { resolveHome } from "./home.ts";
21
- import { addVault, addSpec, removeSpec, specStatus, effectivePii, loadRegistry, recoverRegistry, registryStatus, removeVault, setVaultPii } from "./registry.ts";
21
+ import { changeSettings, settingsSnapshot, addVault, addSpec, removeSpec, specStatus, effectivePii, loadRegistry, recoverRegistry, registryStatus, removeVault, setVaultPii } from "./registry.ts";
22
22
  import { piiPolicy } from "./pii.ts";
23
23
  import { vaultStats } from "./vault-stats.ts";
24
24
  import { PLAIN, UsageError, errorLine, shellWord, takeColorFlag, textOptions, type TextOptions } from "./text-output.ts";
25
- import { renderDoctor, renderManifest, renderRecover, renderRemove, renderSetup, renderSpecAdd, renderSpecsList, renderStats, renderStatus, renderVaultAdd, renderVaultPii, renderVaultsList, type StatusResult } from "./cli-output.ts";
25
+ import { renderDoctor, renderManifest, renderRecover, renderSkillsExport, renderRemove, renderSetup, renderSpecAdd, renderSpecsList, renderStats, renderStatus, renderVaultAdd, renderVaultPii, renderVaultsList, type StatusResult } from "./cli-output.ts";
26
26
  function parse(args: string[], allowed: string[], values: string[]) {
27
27
  const flags: Record<string, string | boolean> = {}, positional: string[] = [];
28
28
  for (let i = 0; i < args.length; i++) {
@@ -78,12 +78,29 @@ function runWith(args: string[], env: NodeJS.ProcessEnv, text: TextOptions = PLA
78
78
  const mode: SetupMode = flags["--apply"] ? "apply" : flags["--undo"] ? "undo" : "dry-run";
79
79
  const report = runSetup(positional[0]!, mode, { home: resolveHome(env).home, env, ...(typeof flags["--root"] === "string" ? { root: flags["--root"] } : {}) });
80
80
  const apply = ["vmem", "setup", positional[0]!, "--apply", ...(typeof flags["--root"] === "string" ? ["--root", flags["--root"]] : [])].map(shellWord).join(" ");
81
- return { text: flags["--json"] ? JSON.stringify(report) : renderSetup(report, text, apply), code: [...report.actions, report.console].some(a => a?.change === "refused") ? 1 : 0 };
81
+ const failed = [...report.actions, report.console].some(a => a?.change === "refused") || (report.skills ?? []).some(s => s.refused || s.report?.actions.some(a => ["refused", "foreign", "modified"].includes(a.change)));
82
+ const progress = report.applied || (mode === "dry-run" && (report.actions.some(a => ["add", "replace"].includes(a.change)) || (report.skills ?? []).some(s => s.report?.actions.some(a => ["install", "replace"].includes(a.change)))));
83
+ return { text: flags["--json"] ? JSON.stringify(report) : renderSetup(report, text, apply), code: failed && !progress ? 1 : 0 };
82
84
  }
83
85
  if (args[0] === "completion") {
84
86
  if (args.length !== 2) throw new UsageError("completion: requires bash, zsh or fish");
85
87
  return { text: completionScript(args[1]!).trimEnd(), code: 0 };
86
88
  }
89
+ if (args[0] === "settings") {
90
+ const { flags, positional } = parse(args.slice(1), ["--set", "--confirm", "--fingerprint", "--json"], ["--set", "--fingerprint"]);
91
+ if (positional.length !== 1) throw new UsageError("settings: supply one vault id; use vmem settings <vault> [--set JSON]");
92
+ const home = resolveHome(env).home, value = flags["--set"];
93
+ if (value === undefined) {
94
+ if (flags["--confirm"] || flags["--fingerprint"]) throw new UsageError("settings: confirmation requires changes; use --set JSON with a preview fingerprint");
95
+ return { text: JSON.stringify(settingsSnapshot(home, positional[0]!), null, flags["--json"] ? undefined : 2), code: 0 };
96
+ }
97
+ let changes: unknown;
98
+ try { changes = JSON.parse(String(value)); } catch { throw new UsageError("settings: invalid JSON; supply an object to --set"); }
99
+ if (Boolean(flags["--confirm"]) !== Boolean(flags["--fingerprint"])) throw new UsageError("settings: --confirm and --fingerprint must be supplied together; preview first");
100
+ const result = changeSettings(home, { vault: positional[0]!, changes: changes as import("./registry.ts").SettingsChanges, confirm: flags["--confirm"] === true, ...(typeof flags["--fingerprint"] === "string" ? { fingerprint: flags["--fingerprint"] } : {}) });
101
+ const next = result.applied ? undefined : ["vmem", "settings", positional[0]!, "--set", String(value), "--confirm", "--fingerprint", result.fingerprint].map(shellWord).join(" ");
102
+ return { text: JSON.stringify({ ...result, ...(next ? { next } : {}) }, null, flags["--json"] ? undefined : 2), code: 0 };
103
+ }
87
104
  if (args[0] === "spec") return runSpecCommand(args.slice(1), env, text);
88
105
  if (args[0] === "proposal") return runProposalCommand(args.slice(1), resolveHome(env).home, env, text);
89
106
  if (args[0] === "lint" || args[0] === "graph") return runAnalysisCommand(args[0],args.slice(1),resolveHome(env).home,env,text);
@@ -228,6 +245,15 @@ export async function runAsync(argv: string[], env: NodeJS.ProcessEnv = process.
228
245
  const taken = takeColorFlag(argv), args = taken.args, text = textOptions(taken.color, env, io.stdout ?? {});
229
246
  const usage = commandHelp(args, text);
230
247
  if (usage) return { text: usage, code: 0 };
248
+ if (args[0] === "skills" && args[1] === "export") {
249
+ const { flags, positional } = parse(args.slice(2), ["--json"], []);
250
+ if (positional.length !== 1) throw new UsageError("skills export: provide one destination directory; use vmem skills export <dir>");
251
+ const { exportSkills } = await import("./skills-install.ts");
252
+ const report = exportSkills(positional[0]!);
253
+ const failed = report.actions.some(a => ["refused", "foreign", "modified"].includes(a.change));
254
+ const changed = report.actions.some(a => ["install", "replace"].includes(a.change));
255
+ return { text: flags["--json"] ? JSON.stringify(report) : renderSkillsExport(report, text), code: failed && !changed ? 1 : 0 };
256
+ }
231
257
  if (args[0] === "skills") {
232
258
  const { runSkillsCommand } = await import("./skills-mine.ts");
233
259
  return runSkillsCommand(args.slice(1), resolveHome(env).home, env, text);
@@ -27,6 +27,7 @@ export const COMMANDS = [
27
27
  { 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" },
28
28
  { name: "graph path", usage: "graph path <vault> <from> <to> [--max-hops 1..6] [--relation REL] [--via-hubs] [--json]", mutates: false, section: "Analysis", description: "read the shortest link path between two notes, skipping MOC/bu hubs unless --via-hubs" },
29
29
  { name: "graph explain", usage: "graph explain <vault> <from> <to> [--max-hops 1..6] [--relation REL] [--via-hubs] [--json]", mutates: false, section: "Analysis", description: "explain each hop of the shortest path by its source link occurrences; structural only" },
30
+ { name: "skills export", usage: "skills export <dir> [--json]", mutates: true, section: "Setup", description: "export self-contained vmem skills to a directory" },
30
31
  { 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" },
31
32
  { name: "rebuild", usage: "rebuild <vault> [--json]", mutates: "cache", section: "Read", description: "rebuild the derived search index from the vault files" },
32
33
  { 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" },
@@ -40,6 +41,7 @@ export const COMMANDS = [
40
41
  { name: "history", usage: "history <vault> <note> [--limit 1..100] [--cursor C] [--json]", mutates: false, section: "Read", description: "list one note path's Git snapshot revisions newest first, pinned to the HEAD the page started from" },
41
42
  { name: "changes", usage: "changes <vault> --from OID --to OID [--limit 1..500] [--cursor C] [--json]", mutates: false, section: "Read", description: "compare two pinned Git snapshots over notes/ with before/after blob ids and status" },
42
43
  { name: "status", usage: "status [--json]", mutates: false, section: "Registry", description: "show the home, registered vaults and spec sources, and vault health" },
44
+ { name: "settings", usage: "settings <vault> [--set JSON] [--confirm --fingerprint SHA] [--json]", mutates: "confirm", section: "Registry", description: "read settings or preview and confirm a settings change" },
43
45
  { name: "doctor", usage: "doctor [--json]", mutates: false, section: "Registry", description: "check vault paths, remotes, project registries, pending tidy and spec sources; exits 1 when unhealthy" },
44
46
  { name: "recover", usage: "recover [--confirm] [--json]", mutates: "confirm", section: "Registry", description: "preview, then remove with --confirm, a stale registry lock and leftover temporary files" },
45
47
  { name: "vaults list", usage: "vaults list [--json]", mutates: false, section: "Registry", description: "list registered vaults with kind, write policy and effective PII policy" },
@@ -116,7 +118,7 @@ export function completionScript(shell: string): string {
116
118
  cur="\${COMP_WORDS[COMP_CWORD]}"
117
119
  if [ "$COMP_CWORD" -eq 1 ]; then COMPREPLY=($(compgen -W ${quote(top.join(" "))} -- "$cur")); return; fi
118
120
  key="\${COMP_WORDS[1]}"
119
- case "$key" in spec) if [ "$COMP_CWORD" -eq 2 ]; then COMPREPLY=($(compgen -W '${SPEC_COMMANDS.map(item => item.command).join(" ")}' -- "$cur")); return; fi; key="$key \${COMP_WORDS[2]}" ;; graph) if [ "$COMP_CWORD" -eq 2 ]; then COMPREPLY=($(compgen -W 'build neighbors path explain' -- "$cur")); return; fi; key="$key \${COMP_WORDS[2]}" ;; skills) if [ "$COMP_CWORD" -eq 2 ]; then COMPREPLY=($(compgen -W 'mine' -- "$cur")); return; fi; key="$key \${COMP_WORDS[2]}" ;; specs) if [ "$COMP_CWORD" -eq 2 ]; then COMPREPLY=($(compgen -W 'list add remove' -- "$cur")); return; fi; key="$key \${COMP_WORDS[2]}" ;; vaults|log) if [ "$COMP_CWORD" -eq 2 ]; then COMPREPLY=($(compgen -W "$( [ "$key" = vaults ] && echo 'list add remove' || echo 'tail grep append')" -- "$cur")); return; fi; key="$key \${COMP_WORDS[2]}" ;; esac
121
+ case "$key" in spec) if [ "$COMP_CWORD" -eq 2 ]; then COMPREPLY=($(compgen -W '${SPEC_COMMANDS.map(item => item.command).join(" ")}' -- "$cur")); return; fi; key="$key \${COMP_WORDS[2]}" ;; graph) if [ "$COMP_CWORD" -eq 2 ]; then COMPREPLY=($(compgen -W 'build neighbors path explain' -- "$cur")); return; fi; key="$key \${COMP_WORDS[2]}" ;; skills) if [ "$COMP_CWORD" -eq 2 ]; then COMPREPLY=($(compgen -W 'mine export' -- "$cur")); return; fi; key="$key \${COMP_WORDS[2]}" ;; specs) if [ "$COMP_CWORD" -eq 2 ]; then COMPREPLY=($(compgen -W 'list add remove' -- "$cur")); return; fi; key="$key \${COMP_WORDS[2]}" ;; vaults|log) if [ "$COMP_CWORD" -eq 2 ]; then COMPREPLY=($(compgen -W "$( [ "$key" = vaults ] && echo 'list add remove' || echo 'tail grep append')" -- "$cur")); return; fi; key="$key \${COMP_WORDS[2]}" ;; esac
120
122
  case "$key" in
121
123
  ${cases.join("\n")}
122
124
  *) words='' ;;
package/src/config.ts CHANGED
@@ -15,6 +15,8 @@ export interface VaultSpec {
15
15
  registry?: string;
16
16
  domains?: string[];
17
17
  canonTables?: CanonTableSpec[];
18
+ graph?: { resolution?: number };
19
+ enrichment?: { enabled: boolean };
18
20
  }
19
21
  /** Advisory canonical tables do not participate in mutation identity or policy. */
20
22
  export function mutationVault(vault: VaultSpec): Omit<VaultSpec, "canonTables"> {
@@ -44,11 +46,11 @@ export interface PiiSpec { email?: PiiCell; phone?: PiiCell; custom?: PiiCell; p
44
46
  * The config format this build writes. A build that adds a key bumps it. A config whose `version` is newer
45
47
  * than this build is read tolerantly: unknown keys are kept as they are and written back unchanged, so an
46
48
  * older vmem can share a config with a newer one. At or below this version unknown keys stay errors (typos).
47
- * An absent `version` means 1. Registry writes add format 2 for `specs`, 3 for vault `domains`, and 4 for vault `canonTables`; otherwise they keep the existing version field.
49
+ * An absent `version` means 1. Registry writes add format 2 for `specs`, 3 for vault `domains`, 4 for vault `canonTables`, and 5 for default vault or graph options, and 6 for enrichment; otherwise they keep the existing version field.
48
50
  */
49
- export const CONFIG_VERSION = 4;
51
+ export const CONFIG_VERSION = 6;
50
52
  export interface SpecSourceSpec { id: string; path: string; write: "mcp" | "cli" | "none"; pii: "allow" | "deny" }
51
- export interface VmemConfig { version?: number; home?: string; vaults: VaultSpec[]; specs?: SpecSourceSpec[]; denyPaths?: string[]; piiPatterns?: string[] }
53
+ export interface VmemConfig { version?: number; home?: string; vaults: VaultSpec[]; specs?: SpecSourceSpec[]; denyPaths?: string[]; piiPatterns?: string[]; defaultVault?: string }
52
54
  const controls = /[\x00-\x1f\x7f]/;
53
55
  function object(value: unknown, keys: string[], label: string, tolerant = false): Record<string, unknown> {
54
56
  if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error(`${label}: expected object`);
@@ -155,7 +157,7 @@ function parseCanonTables(value: unknown, tolerant: boolean): CanonTableSpec[] {
155
157
  }
156
158
  }
157
159
  export function parseVault(value: unknown, tolerant = false): VaultSpec {
158
- const keys = ["id", "path", "kind", "write", "pii", "remote", "registry", "domains", "canonTables"], v = object(value, keys, "vault", tolerant);
160
+ const keys = ["id", "path", "kind", "write", "pii", "remote", "registry", "domains", "canonTables", "graph", "enrichment"], v = object(value, keys, "vault", tolerant);
159
161
  const id = string(v.id, "vault.id");
160
162
  if (!/^[a-z][a-z0-9-]{0,31}$/.test(id)) throw new Error("vault.id: invalid id");
161
163
  if (v.kind !== "personal" && v.kind !== "org") throw new Error("vault.kind: expected personal or org");
@@ -171,6 +173,16 @@ export function parseVault(value: unknown, tolerant = false): VaultSpec {
171
173
  result.domains = [...v.domains];
172
174
  }
173
175
  if (v.canonTables !== undefined) result.canonTables = parseCanonTables(v.canonTables, tolerant);
176
+ if (v.enrichment !== undefined) {
177
+ const enrichment = object(v.enrichment, ["enabled"], "vault.enrichment", tolerant);
178
+ if (typeof enrichment.enabled !== "boolean") throw new Error("vault.enrichment.enabled: expected true or false; correct the vault setting");
179
+ result.enrichment = { ...unknown(enrichment, ["enabled"], tolerant), enabled: enrichment.enabled };
180
+ }
181
+ if (v.graph !== undefined) {
182
+ const graph = object(v.graph, ["resolution"], "vault.graph", tolerant);
183
+ if (graph.resolution !== undefined && (typeof graph.resolution !== "number" || !Number.isFinite(graph.resolution) || graph.resolution <= 0 || graph.resolution > 100)) throw new Error("vault.graph.resolution: expected a number above 0 and at most 100; set a valid graph resolution");
184
+ result.graph = { ...unknown(graph, ["resolution"], tolerant), ...(graph.resolution !== undefined ? { resolution: graph.resolution as number } : {}) };
185
+ }
174
186
  return result;
175
187
  }
176
188
  /** Spec sources have their own registry shape; they are not vaults. */
@@ -188,13 +200,13 @@ export function parseSpec(value: unknown, tolerant = false): SpecSourceSpec {
188
200
  }
189
201
  }
190
202
  export function parseConfig(value: unknown): VmemConfig {
191
- const keys = ["version", "home", "vaults", "specs", "denyPaths", "piiPatterns"];
203
+ const keys = ["version", "home", "vaults", "specs", "denyPaths", "piiPatterns", "defaultVault"];
192
204
  const version = (value as Record<string, unknown> | null)?.version;
193
205
  if (version !== undefined && (!Number.isSafeInteger(version) || (version as number) < 1)) throw new Error("config.version: expected a positive integer");
194
206
  const tolerant = newerFormat(value), raw = object(value, keys, "config", tolerant);
195
207
  const stamp = version === undefined ? {} : { version: version as number };
196
208
  if (raw.home !== undefined) {
197
- if (["vaults", "specs", "denyPaths", "piiPatterns"].some(key => raw[key] !== undefined)) throw new Error("config: home pointer must not contain vaults, specs or policy; put source entries in the pointed-to home config");
209
+ if (["vaults", "specs", "denyPaths", "piiPatterns", "defaultVault"].some(key => raw[key] !== undefined)) throw new Error("config: home pointer must not contain vaults, specs or policy; put source entries in the pointed-to home config");
198
210
  return { ...unknown(raw, keys, tolerant), ...stamp, home: absolute(raw.home, "config.home"), vaults: [] };
199
211
  }
200
212
  const vaultInput = raw.vaults === undefined && raw.specs !== undefined ? [] : raw.vaults;
@@ -206,11 +218,13 @@ export function parseConfig(value: unknown): VmemConfig {
206
218
  if (specs && new Set(specs.map(source => source.path)).size !== specs.length) throw new Error("config: duplicate spec source path; keep only one entry for each repository root");
207
219
  if (new Set(vaults.map(v => v.id)).size !== vaults.length) throw new Error("config: duplicate vault id");
208
220
  if (new Set(vaults.map(v => v.path)).size !== vaults.length) throw new Error("config: duplicate vault path");
221
+ const defaultVault = raw.defaultVault === undefined ? undefined : string(raw.defaultVault, "config.defaultVault");
222
+ if (defaultVault !== undefined && !/^[a-z][a-z0-9-]{0,31}$/.test(defaultVault)) throw new Error("config.defaultVault: invalid vault id; choose an id from vmem vaults list");
209
223
  const denyPaths = strings(raw.denyPaths, "denyPaths"), piiPatterns = strings(raw.piiPatterns, "piiPatterns");
210
224
  for (const pattern of piiPatterns ?? []) {
211
225
  try { new RegExp(pattern); } catch { throw new Error("piiPatterns: invalid regular expression"); }
212
226
  }
213
- return { ...unknown(raw, keys, tolerant), ...stamp, vaults, ...(specs !== undefined ? { specs } : {}), ...(denyPaths ? { denyPaths } : {}), ...(piiPatterns ? { piiPatterns } : {}) };
227
+ return { ...unknown(raw, keys, tolerant), ...stamp, vaults, ...(defaultVault !== undefined ? { defaultVault } : {}), ...(specs !== undefined ? { specs } : {}), ...(denyPaths ? { denyPaths } : {}), ...(piiPatterns ? { piiPatterns } : {}) };
214
228
  }
215
229
  /** Bounded descriptor read: reject links, devices and oversized/growing files. */
216
230
  export function readConfig(home: string): VmemConfig {