@cavelang/cli 0.4.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.
package/README.md CHANGED
@@ -28,11 +28,12 @@ Every command answers `--help` with its options and examples (also
28
28
  | Command | Flags | Behavior |
29
29
  |---|---|---|
30
30
  | `parse [file…]` | `--json` | Lint (stdin by default). Exit 1 when diagnostics exist; `--json` dumps the AST document. |
31
- | `add [--db p] [file…]` | `--strict`, `--no-prelude` | Ingest. Lenient by default (problems on stderr, valid lines land); `--strict` rolls back on any problem; `--no-prelude` starts from an empty registry instead of the standard §5.5 pairs. |
32
- | `import [--db p] [file…]` | `--strict`, `--no-prelude` | Restore/merge a database from CAVE text — same operation as `add`, because canonical text *is* the interchange format. |
31
+ | `add [--db p] [file…]` | `--strict`, `--check`, `--no-prelude`, `--no-src` | Ingest. Lenient by default (problems on stderr, valid lines land); `--strict` rolls back on any problem; `--check` is the shape gate (spec §20.3) — the append rolls back if it introduces new expectation violations; `--no-prelude` starts from an empty registry instead of the standard §5.5 pairs. Claims without a `@src:` context are stamped `@src:cli` (spec §9.5); `--no-src` opts out. |
32
+ | `import [--db p] [file…]` | `--strict`, `--no-prelude` | Restore/merge a database from CAVE text — `add` minus provenance stamping, because canonical text *is* the interchange format and replayed claims must keep their exported claim keys (spec §9.5). |
33
33
  | `query [--db p] <pattern…>` | `--json`, `--all`, `--no-prelude` | CAVE-Q. Extra positionals join as lines, so `WHERE` filters ride as separate arguments. Bindings print as `?x = value`; fully bound patterns print the matched raw line (or the pattern itself for transitive matches, which carry no row). `--no-prelude` aligns the read-time registry with a store written via `add --no-prelude`. |
34
+ | `check [--db p]` | `--stale <days>`, `--json`, `--no-prelude` | Knowledge health report (spec §20, see [`@cavelang/shape`](../shape)): shape violations against in-band `EXPECTS` declarations, stale current beliefs (default horizon 90 days), review candidates (conf 0.3–0.7), alias disagreements, coverage stats. Exit 1 on violations; everything else is advisory. |
34
35
  | `export [--db p]` | `--out <file>`, `--current`, `--no-prelude` | Canonical CAVE text — all rows in tx order, or current beliefs only. Stdout by default; `--out` writes a file and reports the claim count. |
35
- | `mcp [--db p]` | `--no-prelude` | Serve the engine as an MCP server on stdio (see [`@cavelang/mcp`](../mcp)) — tools for add/query/search/about/neighbors/reconstruct/export/lint, with the §22 spec card as server instructions. |
36
+ | `mcp [--db p]` | `--read-only`, `--tools <list>`, `--no-prelude`, `--src <ctx>`, `--no-src` | Serve the engine as an MCP server on stdio (see [`@cavelang/mcp`](../mcp)) — tools for add/query/search/about/neighbors/reconstruct/export/lint, with the §22 spec card as server instructions. `--read-only` / `--tools <list>` narrow the served tool surface (the agent permission boundary), composing by intersection. Appends are stamped `@src:agent/<client-name>` (spec §9.5); `--src` replaces the stamp, `--no-src` disables it. |
36
37
  | `ingest [--db p] <globs/urls…>` | see `cave ingest --help` | LLM-driven ingestion of files and web pages (fetched and readability-extracted) through any headless agent (see [`@cavelang/ingest`](../ingest)): batching, instructions markdown, hybrid knowledge context, MCP or stdout agents, incremental digests, `--plan` NDJSON for SDK drivers. |
37
38
  | `demo` | | The cave-loop multi-hop recovery demo (§18). |
38
39
  | `version` | | Print the cave version. |
package/dist/src/cli.d.ts CHANGED
@@ -6,9 +6,13 @@
6
6
  * Commands:
7
7
  *
8
8
  * - `cave parse [file]` — lint / dump the AST (`--json`)
9
- * - `cave add [--db <path>] [file…]` — ingest into a store (`--strict`)
10
- * - `cave query [--db <path>] '<pattern>'` — CAVE-Q (`--json`, `--all`)
9
+ * - `cave highlight [file]` — ANSI syntax colors (async, routed in `main.ts`)
10
+ * - `cave add [--db <path>] [file…]` — ingest into a store (`--strict`, `--check`)
11
+ * - `cave query [--db <path>] '<pattern>'` — CAVE-Q (`--json`, `--all`, `--aliases`, `--as-of`)
12
+ * - `cave derive [--db <path>] [rules.cave…]` — fire rules (`--dry-run`, `--full`, `--list`, `--retract`)
13
+ * - `cave check [--db <path>]` — knowledge health report (`--stale`, `--json`)
11
14
  * - `cave export [--db <path>]` — canonical text out (`--current`)
15
+ * - `cave connect [--db <path>] <source>` — deterministic structured ingestion (async, routed in `main.ts`)
12
16
  * - `cave demo` — the cave-loop multi-hop recovery demo
13
17
  * - `cave version` — print the cave version
14
18
  * - `cave help [command]` — overview, or one command's help
@@ -21,23 +25,33 @@ export type Output = {
21
25
  readonly out: string;
22
26
  readonly err: string;
23
27
  };
24
- export declare const usage = "cave \u2014 Compressed Atomic Verb Expressions\n\nUsage:\n cave parse [file...] [--json] lint CAVE text (stdin when no file)\n cave add [--db <path>] [file...] ingest into a store [--strict] [--no-prelude]\n cave import [--db <path>] [file...] restore/merge from CAVE text (same as add)\n cave query [--db <path>] <pattern> run a CAVE-Q pattern [--json] [--all] [--no-prelude]\n cave export [--db <path>] [--out <file>] emit canonical CAVE text [--current] [--no-prelude]\n cave mcp [--db <path>] serve the engine as an MCP server on stdio [--no-prelude]\n cave ingest [--db <path>] <globs/urls..> LLM-driven ingestion of files and web pages\n cave demo run the cave-loop reconstruction demo\n cave version print the cave version\n cave help [command] this text, or one command's options and examples\n\nEvery command answers --help. --db defaults to $CAVE_DB, or cave.db in\nthe current directory. The spec lives in the .claude/skills/ directory at\nthe repository root (section index in README.md).";
28
+ export declare const usage = "cave \u2014 Compressed Atomic Verb Expressions\n\nUsage:\n cave parse [file...] [--json] lint CAVE text (stdin when no file)\n cave highlight [file...] print CAVE text with ANSI syntax colors\n cave add [--db <path>] [file...] ingest into a store [--strict] [--check] [--no-prelude] [--no-src]\n cave import [--db <path>] [file...] restore/merge from CAVE text (add without @src: stamping)\n cave query [--db <path>] <pattern> run a CAVE-Q pattern [--json] [--all] [--aliases] [--as-of <t>] [--no-prelude]\n cave derive [--db <path>] [rules.cave..] declare + fire rules (spec \u00A724) [--dry-run] [--full] [--list] [--retract <rule>]\n cave check [--db <path>] knowledge health report (spec \u00A720) [--stale <days>] [--json]\n cave export [--db <path>] [--out <file>] emit canonical CAVE text [--current] [--no-prelude]\n cave mcp [--db <path>] serve the engine as an MCP server on stdio [--no-prelude]\n cave ingest [--db <path>] <globs/urls..> LLM-driven ingestion of files and web pages\n cave connect <source> --map <file> deterministic structured ingestion (CSV/JSON/SQLite/URL, spec \u00A723)\n cave demo run the cave-loop reconstruction demo\n cave version print the cave version\n cave help [command] this text, or one command's options and examples\n\nEvery command answers --help. --db defaults to $CAVE_DB, or cave.db in\nthe current directory. The spec lives in the .claude/skills/ directory at\nthe repository root (section index in README.md).";
25
29
  /** Per-command help, printed for \`cave <command> --help\` and \`cave help <command>\`. */
26
30
  export declare const commandHelp: Record<string, string>;
27
31
  export declare const parseCommand: (argv: readonly string[]) => Output;
32
+ /**
33
+ * `cave highlight` — ANSI syntax colors from the tree-sitter grammar's own
34
+ * highlight query. Async (the grammar WASM loads on first use), so `main.ts`
35
+ * routes it separately, like `mcp` and `ingest`.
36
+ */
37
+ export declare const highlightCommand: (argv: readonly string[]) => Promise<Output>;
28
38
  export declare const addCommand: (argv: readonly string[]) => Output;
29
39
  /**
30
40
  * `cave import` — restore/merge a knowledge database from CAVE text files.
31
- * Identical to `add` by design: canonical CAVE text *is* the interchange
41
+ * `add` minus provenance stamping: canonical CAVE text *is* the interchange
32
42
  * format (spec §2.2), so importing a file exported with `cave export`
33
- * replays its claims append-only. What the text round trip preserves:
34
- * every claim with metadata, full belief-series order (rows export in tx
35
- * order and re-ingest with fresh monotonic tx ids), qualifier/grouping
36
- * edges, and in-band registry declarations. Original tx timestamps are
37
- * re-minted — the text format carries no transaction identity.
43
+ * replays its claims append-only — and because contexts are part of claim
44
+ * identity, replay must not add a `@src:` stamp (spec §9.5). What the text
45
+ * round trip preserves: every claim with metadata, full belief-series order
46
+ * (rows export in tx order and re-ingest with fresh monotonic tx ids),
47
+ * qualifier/grouping edges, and in-band registry declarations. Original tx
48
+ * timestamps are re-minted — the text format carries no transaction
49
+ * identity.
38
50
  */
39
51
  export declare const importCommand: (argv: readonly string[]) => Output;
40
52
  export declare const queryCommand: (argv: readonly string[]) => Output;
53
+ export declare const deriveCommand: (argv: readonly string[]) => Output;
54
+ export declare const checkCommand: (argv: readonly string[]) => Output;
41
55
  export declare const exportCommand: (argv: readonly string[]) => Output;
42
56
  export declare const demoCommand: () => Output;
43
57
  export declare const versionCommand: () => Output;
@@ -1 +1 @@
1
- {"version":3,"file":"cli.d.ts","sourceRoot":"","sources":["../../src/cli.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AAWH,MAAM,MAAM,MAAM,GAAG;IACnB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAA;IACrB,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAA;IACpB,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAA;CACrB,CAAA;AAQD,eAAO,MAAM,KAAK,unCAgBgC,CAAA;AAIlD,2FAA2F;AAC3F,eAAO,MAAM,WAAW,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAsG9C,CAAA;AAOD,eAAO,MAAM,YAAY,GAAI,MAAM,SAAS,MAAM,EAAE,KAAG,MAyBtD,CAAA;AA+BD,eAAO,MAAM,UAAU,SA7BwB,SAAS,MAAM,EAAE,KAAG,MA6BrB,CAAA;AAE9C;;;;;;;;;GASG;AACH,eAAO,MAAM,aAAa,SAzCqB,SAAS,MAAM,EAAE,KAAG,MAyCf,CAAA;AAEpD,eAAO,MAAM,YAAY,GAAI,MAAM,SAAS,MAAM,EAAE,KAAG,MAsCtD,CAAA;AAED,eAAO,MAAM,aAAa,GAAI,MAAM,SAAS,MAAM,EAAE,KAAG,MAuBvD,CAAA;AAED,eAAO,MAAM,WAAW,QAAO,MACS,CAAA;AAExC,eAAO,MAAM,cAAc,QAAO,MACJ,CAAA;AAE9B,wEAAwE;AACxE,eAAO,MAAM,WAAW,GAAI,MAAM,SAAS,MAAM,EAAE,KAAG,MAcrD,CAAA;AAED,iCAAiC;AACjC,eAAO,MAAM,IAAI,GAAI,MAAM,SAAS,MAAM,EAAE,KAAG,MAqC9C,CAAA"}
1
+ {"version":3,"file":"cli.d.ts","sourceRoot":"","sources":["../../src/cli.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;GAqBG;AAeH,MAAM,MAAM,MAAM,GAAG;IACnB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAA;IACrB,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAA;IACpB,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAA;CACrB,CAAA;AAQD,eAAO,MAAM,KAAK,6mDAoBgC,CAAA;AAIlD,2FAA2F;AAC3F,eAAO,MAAM,WAAW,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAiM9C,CAAA;AAOD,eAAO,MAAM,YAAY,GAAI,MAAM,SAAS,MAAM,EAAE,KAAG,MAyBtD,CAAA;AAED;;;;GAIG;AACH,eAAO,MAAM,gBAAgB,GAAU,MAAM,SAAS,MAAM,EAAE,KAAG,OAAO,CAAC,MAAM,CAM9E,CAAA;AAuDD,eAAO,MAAM,UAAU,SA1CkC,SAAS,MAAM,EAAE,KAAG,MA0C/B,CAAA;AAE9C;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,aAAa,SAxD+B,SAAS,MAAM,EAAE,KAAG,MAwDzB,CAAA;AAEpD,eAAO,MAAM,YAAY,GAAI,MAAM,SAAS,MAAM,EAAE,KAAG,MA4CtD,CAAA;AAED,eAAO,MAAM,aAAa,GAAI,MAAM,SAAS,MAAM,EAAE,KAAG,MAsHvD,CAAA;AAqCD,eAAO,MAAM,YAAY,GAAI,MAAM,SAAS,MAAM,EAAE,KAAG,MA0BtD,CAAA;AAED,eAAO,MAAM,aAAa,GAAI,MAAM,SAAS,MAAM,EAAE,KAAG,MAuBvD,CAAA;AAED,eAAO,MAAM,WAAW,QAAO,MACS,CAAA;AAExC,eAAO,MAAM,cAAc,QAAO,MACJ,CAAA;AAE9B,wEAAwE;AACxE,eAAO,MAAM,WAAW,GAAI,MAAM,SAAS,MAAM,EAAE,KAAG,MAcrD,CAAA;AAED,iCAAiC;AACjC,eAAO,MAAM,IAAI,GAAI,MAAM,SAAS,MAAM,EAAE,KAAG,MAyC9C,CAAA"}
package/dist/src/cli.js CHANGED
@@ -6,9 +6,13 @@
6
6
  * Commands:
7
7
  *
8
8
  * - `cave parse [file]` — lint / dump the AST (`--json`)
9
- * - `cave add [--db <path>] [file…]` — ingest into a store (`--strict`)
10
- * - `cave query [--db <path>] '<pattern>'` — CAVE-Q (`--json`, `--all`)
9
+ * - `cave highlight [file]` — ANSI syntax colors (async, routed in `main.ts`)
10
+ * - `cave add [--db <path>] [file…]` — ingest into a store (`--strict`, `--check`)
11
+ * - `cave query [--db <path>] '<pattern>'` — CAVE-Q (`--json`, `--all`, `--aliases`, `--as-of`)
12
+ * - `cave derive [--db <path>] [rules.cave…]` — fire rules (`--dry-run`, `--full`, `--list`, `--retract`)
13
+ * - `cave check [--db <path>]` — knowledge health report (`--stale`, `--json`)
11
14
  * - `cave export [--db <path>]` — canonical text out (`--current`)
15
+ * - `cave connect [--db <path>] <source>` — deterministic structured ingestion (async, routed in `main.ts`)
12
16
  * - `cave demo` — the cave-loop multi-hop recovery demo
13
17
  * - `cave version` — print the cave version
14
18
  * - `cave help [command]` — overview, or one command's help
@@ -23,6 +27,8 @@ import { parseDocument } from '@cavelang/parser';
23
27
  import { Registry, standardRegistry } from '@cavelang/canonical';
24
28
  import { defaultDbPath, open } from '@cavelang/store';
25
29
  import { query as caveQuery } from '@cavelang/query';
30
+ import { check as caveCheck, defaultStaleDays, gatedIngest } from '@cavelang/shape';
31
+ import { declareRules, defaultMaxPasses, defaultMinConf, derive, listRules, retractRule } from '@cavelang/rules';
26
32
  import { Demo } from '@cavelang/loop';
27
33
  const ok = (out) => ({ code: 0, out, err: '' });
28
34
  const fail = (err, code = 1) => ({ code, out: '', err });
@@ -30,12 +36,16 @@ export const usage = `cave — Compressed Atomic Verb Expressions
30
36
 
31
37
  Usage:
32
38
  cave parse [file...] [--json] lint CAVE text (stdin when no file)
33
- cave add [--db <path>] [file...] ingest into a store [--strict] [--no-prelude]
34
- cave import [--db <path>] [file...] restore/merge from CAVE text (same as add)
35
- cave query [--db <path>] <pattern> run a CAVE-Q pattern [--json] [--all] [--no-prelude]
39
+ cave highlight [file...] print CAVE text with ANSI syntax colors
40
+ cave add [--db <path>] [file...] ingest into a store [--strict] [--check] [--no-prelude] [--no-src]
41
+ cave import [--db <path>] [file...] restore/merge from CAVE text (add without @src: stamping)
42
+ cave query [--db <path>] <pattern> run a CAVE-Q pattern [--json] [--all] [--aliases] [--as-of <t>] [--no-prelude]
43
+ cave derive [--db <path>] [rules.cave..] declare + fire rules (spec §24) [--dry-run] [--full] [--list] [--retract <rule>]
44
+ cave check [--db <path>] knowledge health report (spec §20) [--stale <days>] [--json]
36
45
  cave export [--db <path>] [--out <file>] emit canonical CAVE text [--current] [--no-prelude]
37
46
  cave mcp [--db <path>] serve the engine as an MCP server on stdio [--no-prelude]
38
47
  cave ingest [--db <path>] <globs/urls..> LLM-driven ingestion of files and web pages
48
+ cave connect <source> --map <file> deterministic structured ingestion (CSV/JSON/SQLite/URL, spec §23)
39
49
  cave demo run the cave-loop reconstruction demo
40
50
  cave version print the cave version
41
51
  cave help [command] this text, or one command's options and examples
@@ -61,23 +71,44 @@ Examples:
61
71
  cave parse notes.cave
62
72
  echo 'auth USES jwt @ 90%' | cave parse
63
73
  cave parse notes.cave --json | jq '.lines[0]'`,
74
+ highlight: `cave highlight — print CAVE text with ANSI syntax colors
75
+
76
+ Usage:
77
+ cave highlight [file...]
78
+
79
+ Reads stdin when no file (or \`-\`) is given. Colors come from the
80
+ tree-sitter grammar's highlight query (@cavelang/tree-sitter-cave), the
81
+ same source editors use. Output always carries ANSI codes — pipe through
82
+ \`less -R\` to page. \`cave export\` colors its output the same way when
83
+ stdout is a terminal (disable with NO_COLOR).
84
+
85
+ Examples:
86
+ cave highlight notes.cave
87
+ echo 'auth USES jwt @ 90%' | cave highlight
88
+ cave highlight notes.cave | less -R`,
64
89
  add: `cave add — ingest CAVE text into a knowledge database
65
90
 
66
91
  Usage:
67
- cave add [--db <path>] [file...] [--strict] [--no-prelude]
92
+ cave add [--db <path>] [file...] [--strict] [--check] [--no-prelude] [--no-src]
68
93
 
69
94
  Options:
70
95
  ${dbHelp}
71
96
  --strict reject the whole ingest on any problem
97
+ --check shape gate (spec §20.3): roll the append back if it
98
+ introduces new expectation violations
72
99
  --no-prelude open the store without the standard verb registry
100
+ --no-src do not stamp actor provenance on appended claims
73
101
 
74
- Reads stdin when no file (or \`-\`) is given.
102
+ Reads stdin when no file (or \`-\`) is given. Claims that carry no @src:
103
+ context are stamped @src:cli (spec §9.5); use \`cave import\` to replay
104
+ exported text without stamping.
75
105
 
76
106
  Examples:
77
107
  cave add --db k.db notes.cave
78
108
  echo 'auth USES jwt @ 90%' | cave add
79
- cave add --db k.db --strict reviewed.cave`,
80
- import: `cave import — restore/merge a database from CAVE text (same as add)
109
+ cave add --db k.db --strict reviewed.cave
110
+ cave add --db k.db --check new-services.cave`,
111
+ import: `cave import — restore/merge a database from CAVE text (add without @src: stamping)
81
112
 
82
113
  Usage:
83
114
  cave import [--db <path>] [file...] [--strict] [--no-prelude]
@@ -89,7 +120,9 @@ Options:
89
120
 
90
121
  Canonical CAVE text is the interchange format (spec §2.2): importing a
91
122
  file written by \`cave export\` replays its claims append-only, preserving
92
- the belief series, qualifier edges and in-band declarations.
123
+ the belief series, qualifier edges and in-band declarations. Unlike
124
+ \`cave add\`, import never stamps actor provenance — replayed claims must
125
+ keep the claim keys they were exported with (spec §9.5).
93
126
 
94
127
  Examples:
95
128
  cave export --db old.db --out backup.cave
@@ -97,12 +130,16 @@ Examples:
97
130
  query: `cave query — run a CAVE-Q pattern against a store
98
131
 
99
132
  Usage:
100
- cave query [--db <path>] <pattern> [WHERE <filter>] [--json] [--all] [--no-prelude]
133
+ cave query [--db <path>] <pattern> [WHERE <filter>] [--json] [--all] [--aliases] [--as-of <t>] [--no-prelude]
101
134
 
102
135
  Options:
103
136
  ${dbHelp}
104
137
  --json emit matches as JSON
105
138
  --all match all beliefs, not just current ones
139
+ --aliases resolve entities through current ALIAS claims (spec §13.6)
140
+ --as-of <t> resolve beliefs as of a past moment (spec §12.3): a date
141
+ (whole day included), a timestamp (whole second), or a
142
+ transaction id — rows recorded later are invisible
106
143
  --no-prelude open the store without the standard verb registry
107
144
 
108
145
  Patterns are claim triples with ?variables and optional metadata filters
@@ -114,7 +151,68 @@ Examples:
114
151
  cave query --db k.db '?x HAS bug: ?bug #security'
115
152
  cave query --db k.db '?cause CAUSE app/crash' 'WHERE conf >= 0.5'
116
153
  cave query --db k.db 'terrier EXTENDS+ animal'
154
+ cave query --db k.db '?x USES postgres' --aliases
155
+ cave query --db k.db 'server IS compromised' --as-of 2026-01-15
117
156
  cave query --db k.db '?x ?verb ?y @production' --json`,
157
+ derive: `cave derive — declare and fire rules (spec §24)
158
+
159
+ Usage:
160
+ cave derive [--db <path>] [rules.cave...] [--dry-run] [--full] [--aliases]
161
+ [--min-conf <p>] [--max-passes <n>] [--json] [--no-prelude]
162
+ cave derive [--db <path>] --list
163
+ cave derive [--db <path>] --retract <digest|subject>
164
+
165
+ Options:
166
+ ${dbHelp}
167
+ --dry-run compute and report inside a rolled-back transaction
168
+ --full ignore stored watermarks — re-fire every rule (spec §24.4)
169
+ --aliases premises match through the alias closure (spec §13.6)
170
+ --min-conf <p> do not assert conclusions below this confidence
171
+ (0..1 or N%, default ${defaultMinConf})
172
+ --max-passes <n> fixpoint guard (default ${defaultMaxPasses})
173
+ --list print the store's current rules and exit
174
+ --retract <r> retract a rule (digest, unambiguous prefix, or subject)
175
+ together with everything it derived, and exit
176
+ --json emit the report as JSON
177
+ --no-prelude open the store without the standard verb registry
178
+
179
+ Rule files are CAVE documents whose \`premises => conclusion\` lines are
180
+ rules (spec §24.1); other lines — verb declarations the rules need — are
181
+ prelude, ingested first. Rules are stored in-band as
182
+ \`rule/<digest> HAS rule: \\\`…\\\`\` claims, so \`cave derive\` with no file
183
+ fires whatever the store already knows. Derived claims are stamped
184
+ @src:rule/<digest>, carry BECAUSE edges to their premise rows and a VIA
185
+ edge to the rule, and update append-only: re-runs are idempotent and
186
+ watermark-incremental, and conclusions whose premises no longer hold are
187
+ retracted (spec §24.2–§24.5).
188
+
189
+ Examples:
190
+ cave derive --db k.db rules.cave
191
+ cave derive --db k.db
192
+ echo '?x NEEDS ?y, ?y NEEDS ?z => ?x NEEDS ?z' | cave derive --db k.db -
193
+ cave derive --db k.db --dry-run --json
194
+ cave derive --db k.db --list
195
+ cave derive --db k.db --retract 4a0bb974f43c`,
196
+ check: `cave check — knowledge health report (spec §20)
197
+
198
+ Usage:
199
+ cave check [--db <path>] [--stale <days>] [--json] [--no-prelude]
200
+
201
+ Options:
202
+ ${dbHelp}
203
+ --stale <days> staleness horizon (default: ${defaultStaleDays})
204
+ --json emit the full report as JSON
205
+ --no-prelude open the store without the standard verb registry
206
+
207
+ Reads the store against its own in-band EXPECTS declarations (spec §20.1)
208
+ and reports shape violations, stale current beliefs, review candidates
209
+ (conf 0.3–0.7), alias disagreements (spec §13.6) and coverage stats.
210
+ Exits 1 when violations exist; everything else is advisory.
211
+
212
+ Examples:
213
+ cave check --db k.db
214
+ cave check --db k.db --stale 30
215
+ cave check --db k.db --json | jq '.violations'`,
118
216
  export: `cave export — emit canonical CAVE text from a store
119
217
 
120
218
  Usage:
@@ -171,26 +269,60 @@ export const parseCommand = (argv) => {
171
269
  .join('\n');
172
270
  return { code: 1, out: `${summary}\n`, err: `${problems}\n` };
173
271
  };
272
+ /**
273
+ * `cave highlight` — ANSI syntax colors from the tree-sitter grammar's own
274
+ * highlight query. Async (the grammar WASM loads on first use), so `main.ts`
275
+ * routes it separately, like `mcp` and `ingest`.
276
+ */
277
+ export const highlightCommand = async (argv) => {
278
+ const { positionals } = parseArgs({ args: [...argv], options: {}, allowPositionals: true });
279
+ const input = readInput(positionals);
280
+ const { highlighter } = await import('@cavelang/highlight');
281
+ const { ansi } = await highlighter();
282
+ return ok(ansi(input));
283
+ };
284
+ /**
285
+ * Shared by `add` and `import`; the difference is actor provenance
286
+ * (spec §9.5). `add` records knowledge authored now, so claims without a
287
+ * `@src:` context are stamped `@src:cli` (`--no-src` opts out); `import`
288
+ * replays interchange text, which must preserve claim keys as exported,
289
+ * so it never stamps.
290
+ */
291
+ const formatViolation = (violation) => `${violation.entity} missing ${violation.expectation.kind} ${violation.expectation.name} ` +
292
+ `(${violation.entity} IS ${violation.via}; ${violation.expectation.type} EXPECTS ${violation.expectation.name})`;
174
293
  const ingestCommand = (name) => (argv) => {
175
294
  const { values, positionals } = parseArgs({
176
295
  args: [...argv],
177
296
  options: {
178
297
  db: { type: 'string' },
179
298
  strict: { type: 'boolean' },
180
- 'no-prelude': { type: 'boolean' }
299
+ 'no-prelude': { type: 'boolean' },
300
+ ...name === 'add' ? { 'no-src': { type: 'boolean' }, check: { type: 'boolean' } } : {}
181
301
  },
182
302
  allowPositionals: true
183
303
  });
184
304
  const input = readInput(positionals);
185
305
  const store = open(values.db ?? defaultDbPath(), values['no-prelude'] === true ? { registry: Registry.empty } : {});
186
306
  try {
187
- const result = store.ingest(input, { strict: values.strict === true });
188
- const problems = result.problems
307
+ const options = {
308
+ strict: values.strict === true,
309
+ ...name === 'add' && values['no-src'] !== true ? { source: 'cli' } : {}
310
+ };
311
+ // The shape gate (spec §20.3): append + check in one transaction,
312
+ // rolled back when the append introduces new expectation violations.
313
+ const outcome = name === 'add' && values.check === true ?
314
+ gatedIngest(store, input, options) :
315
+ { ok: true, result: store.ingest(input, options) };
316
+ if (!outcome.ok) {
317
+ const detail = outcome.violations.map(violation => ` ${formatViolation(violation)}`).join('\n');
318
+ return fail(`rejected: ${outcome.violations.length} new violation(s), nothing added (spec §20.3)\n${detail}\n`);
319
+ }
320
+ const problems = outcome.result.problems
189
321
  .map(problem => `line ${problem.line}: ${problem.message}`)
190
322
  .join('\n');
191
323
  return {
192
324
  code: 0,
193
- out: `added ${result.ids.length} claim(s), ${result.edges} edge(s)\n`,
325
+ out: `added ${outcome.result.ids.length} claim(s), ${outcome.result.edges} edge(s)\n`,
194
326
  err: problems === '' ? '' : `${problems}\n`
195
327
  };
196
328
  }
@@ -204,13 +336,15 @@ const ingestCommand = (name) => (argv) => {
204
336
  export const addCommand = ingestCommand('add');
205
337
  /**
206
338
  * `cave import` — restore/merge a knowledge database from CAVE text files.
207
- * Identical to `add` by design: canonical CAVE text *is* the interchange
339
+ * `add` minus provenance stamping: canonical CAVE text *is* the interchange
208
340
  * format (spec §2.2), so importing a file exported with `cave export`
209
- * replays its claims append-only. What the text round trip preserves:
210
- * every claim with metadata, full belief-series order (rows export in tx
211
- * order and re-ingest with fresh monotonic tx ids), qualifier/grouping
212
- * edges, and in-band registry declarations. Original tx timestamps are
213
- * re-minted — the text format carries no transaction identity.
341
+ * replays its claims append-only — and because contexts are part of claim
342
+ * identity, replay must not add a `@src:` stamp (spec §9.5). What the text
343
+ * round trip preserves: every claim with metadata, full belief-series order
344
+ * (rows export in tx order and re-ingest with fresh monotonic tx ids),
345
+ * qualifier/grouping edges, and in-band registry declarations. Original tx
346
+ * timestamps are re-minted — the text format carries no transaction
347
+ * identity.
214
348
  */
215
349
  export const importCommand = ingestCommand('import');
216
350
  export const queryCommand = (argv) => {
@@ -220,6 +354,8 @@ export const queryCommand = (argv) => {
220
354
  db: { type: 'string' },
221
355
  json: { type: 'boolean' },
222
356
  all: { type: 'boolean' },
357
+ aliases: { type: 'boolean' },
358
+ 'as-of': { type: 'string' },
223
359
  'no-prelude': { type: 'boolean' }
224
360
  },
225
361
  allowPositionals: true
@@ -230,7 +366,11 @@ export const queryCommand = (argv) => {
230
366
  const pattern = positionals.join('\n');
231
367
  const store = open(values.db ?? defaultDbPath(), values['no-prelude'] === true ? { registry: Registry.empty } : {});
232
368
  try {
233
- const matches = caveQuery(store, pattern, { all: values.all === true });
369
+ const matches = caveQuery(store, pattern, {
370
+ all: values.all === true,
371
+ aliases: values.aliases === true,
372
+ ...values['as-of'] === undefined ? {} : { asOf: values['as-of'] }
373
+ });
234
374
  if (values.json === true) {
235
375
  return ok(`${JSON.stringify(matches, undefined, 2)}\n`);
236
376
  }
@@ -254,6 +394,186 @@ export const queryCommand = (argv) => {
254
394
  store.close();
255
395
  }
256
396
  };
397
+ export const deriveCommand = (argv) => {
398
+ const { values, positionals } = parseArgs({
399
+ args: [...argv],
400
+ options: {
401
+ db: { type: 'string' },
402
+ 'dry-run': { type: 'boolean' },
403
+ full: { type: 'boolean' },
404
+ aliases: { type: 'boolean' },
405
+ 'min-conf': { type: 'string' },
406
+ 'max-passes': { type: 'string' },
407
+ list: { type: 'boolean' },
408
+ retract: { type: 'string' },
409
+ json: { type: 'boolean' },
410
+ 'no-prelude': { type: 'boolean' }
411
+ },
412
+ allowPositionals: true
413
+ });
414
+ const minConf = values['min-conf'] === undefined ?
415
+ undefined :
416
+ values['min-conf'].endsWith('%') ? Number(values['min-conf'].slice(0, -1)) / 100 : Number(values['min-conf']);
417
+ if (minConf !== undefined && (!Number.isFinite(minConf) || minConf < 0 || minConf > 1)) {
418
+ return fail(`cave derive: --min-conf expects a confidence in 0..1 or N%, got ${JSON.stringify(values['min-conf'])}\n`);
419
+ }
420
+ const maxPasses = values['max-passes'] === undefined ? undefined : Number(values['max-passes']);
421
+ if (maxPasses !== undefined && (!Number.isInteger(maxPasses) || maxPasses < 1)) {
422
+ return fail(`cave derive: --max-passes expects a positive integer, got ${JSON.stringify(values['max-passes'])}\n`);
423
+ }
424
+ const store = open(values.db ?? defaultDbPath(), values['no-prelude'] === true ? { registry: Registry.empty } : {});
425
+ try {
426
+ if (values.list === true) {
427
+ const rules = listRules(store);
428
+ if (values.json === true) {
429
+ return ok(`${JSON.stringify(rules, undefined, 2)}\n`);
430
+ }
431
+ if (rules.length === 0) {
432
+ return ok('no rules\n');
433
+ }
434
+ const lines = rules.map(rule => `${rule.subject} \`${rule.text}\`${rule.label === undefined ? '' : ` ; ${rule.label}`}` +
435
+ (rule.ok ? '' : `\n problems: ${rule.problems.join('; ')}`));
436
+ return ok(`${lines.join('\n')}\n`);
437
+ }
438
+ if (values.retract !== undefined) {
439
+ const outcome = retractRule(store, values.retract);
440
+ if (!outcome.ok) {
441
+ return fail(`cave derive: ${outcome.error}\n`);
442
+ }
443
+ return ok(`retracted ${outcome.subjects.join(', ')} and ${outcome.derived} derived claim(s)\n`);
444
+ }
445
+ const err = [];
446
+ const out = [];
447
+ // Unlike parse/add, no positional means "fire the stored rules", never
448
+ // stdin — pass `-` to read a rule file from stdin explicitly.
449
+ const input = positionals.length > 0 ? readInput(positionals) : undefined;
450
+ const options = {
451
+ full: values.full === true,
452
+ aliases: values.aliases === true,
453
+ ...minConf === undefined ? {} : { minConf },
454
+ ...maxPasses === undefined ? {} : { maxPasses }
455
+ };
456
+ let declaration;
457
+ let report;
458
+ if (values['dry-run'] === true) {
459
+ // A dry run persists nothing — rule declarations from the file
460
+ // included, so declare + fire share one rolled-back transaction.
461
+ const rolledBack = Symbol('cave derive --dry-run');
462
+ let outcome;
463
+ try {
464
+ store.transaction(() => {
465
+ outcome = {
466
+ ...input === undefined ? {} : { declaration: declareRules(store, input) },
467
+ report: derive(store, options)
468
+ };
469
+ throw rolledBack;
470
+ });
471
+ }
472
+ catch (error) {
473
+ if (error !== rolledBack) {
474
+ throw error;
475
+ }
476
+ }
477
+ declaration = outcome.declaration;
478
+ report = outcome.report;
479
+ }
480
+ else {
481
+ declaration = input === undefined ? undefined : declareRules(store, input);
482
+ report = derive(store, options);
483
+ }
484
+ if (declaration !== undefined) {
485
+ err.push(...declaration.problems.map(problem => `rules line ${problem.line}: ${problem.message}`));
486
+ out.push(`declared ${declaration.declared} rule(s)` +
487
+ (declaration.unchanged > 0 ? `, ${declaration.unchanged} unchanged` : '') +
488
+ (declaration.prelude > 0 ? `, +${declaration.prelude} prelude claim(s)` : ''));
489
+ }
490
+ if (values.json === true) {
491
+ return { code: report.problems.length > 0 ? 1 : 0, out: `${JSON.stringify(report, undefined, 2)}\n`, err: err.join('\n') + (err.length > 0 ? '\n' : '') };
492
+ }
493
+ for (const problem of report.problems) {
494
+ err.push(`${problem.subject}: ${problem.problems.join('; ')}`);
495
+ }
496
+ for (const rule of report.rules) {
497
+ const state = rule.fired ?
498
+ `${rule.solutions} solution(s), +${rule.appended} appended, ${rule.updated} updated, ${rule.retracted} retracted, ${rule.unchanged} unchanged` :
499
+ 'unchanged premises, skipped';
500
+ out.push(`${rule.subject}: ${state}${rule.label === undefined ? '' : ` ; ${rule.label}`}`);
501
+ err.push(...rule.problems.map(problem => `${rule.subject}: ${problem}`));
502
+ }
503
+ out.push(...report.notes.map(note => `note: ${note}`));
504
+ out.push(`derived${values['dry-run'] === true ? ' (dry run)' : ''}: ` +
505
+ `+${report.appended} appended, ${report.updated} updated, ${report.retracted} retracted, ` +
506
+ `${report.unchanged} unchanged (${report.passes} pass(es))`);
507
+ const hasProblems = report.problems.length > 0 || report.rules.some(rule => rule.problems.length > 0);
508
+ return { code: hasProblems ? 1 : 0, out: `${out.join('\n')}\n`, err: err.length === 0 ? '' : `${err.join('\n')}\n` };
509
+ }
510
+ catch (error) {
511
+ return fail(`${error instanceof Error ? error.message : String(error)}\n`);
512
+ }
513
+ finally {
514
+ store.close();
515
+ }
516
+ };
517
+ /** Text rendering of the §20.2 report: always shape + coverage, non-empty advisory sections. */
518
+ const renderReport = (report, staleDays) => {
519
+ const lines = [];
520
+ const { coverage } = report;
521
+ lines.push(`shape: ${coverage.expectations} expectation(s), ${coverage.instances} instance(s), ${coverage.satisfied}/${coverage.checks} satisfied`);
522
+ if (report.violations.length > 0) {
523
+ lines.push(`violations (${report.violations.length}):`);
524
+ lines.push(...report.violations.map(violation => ` ${formatViolation(violation)}`));
525
+ }
526
+ if (report.stale.length > 0) {
527
+ lines.push(`stale (${report.stale.length}, older than ${staleDays} day(s)):`);
528
+ lines.push(...report.stale.map(({ row, ageDays }) => ` ${row.raw_line} (${ageDays}d)`));
529
+ }
530
+ if (report.review.length > 0) {
531
+ lines.push(`review candidates (${report.review.length}, conf 0.3-0.7):`);
532
+ lines.push(...report.review.map(row => ` ${row.raw_line}`));
533
+ }
534
+ if (report.disagreements.length > 0) {
535
+ lines.push(`alias disagreements (${report.disagreements.length}):`);
536
+ for (const disagreement of report.disagreements) {
537
+ lines.push(` ${disagreement.about} across ${disagreement.entities.join(', ')}:`);
538
+ lines.push(...disagreement.rows.map(row => ` ${row.raw_line}`));
539
+ }
540
+ }
541
+ const confidence = coverage.averageConfidence === null ?
542
+ '' :
543
+ `; avg conf ${Math.round(coverage.averageConfidence * 100)}%, ${coverage.lowConfidence} low (< 0.3)`;
544
+ lines.push(`coverage: ${coverage.rows} row(s), ${coverage.facts} fact(s) — ` +
545
+ `${coverage.current} current, ${coverage.retracted} retracted, ${coverage.negated} negated` +
546
+ `${confidence}; ${coverage.entities} entities, ${coverage.typedEntities} typed`);
547
+ return `${lines.join('\n')}\n`;
548
+ };
549
+ export const checkCommand = (argv) => {
550
+ const { values } = parseArgs({
551
+ args: [...argv],
552
+ options: {
553
+ db: { type: 'string' },
554
+ stale: { type: 'string' },
555
+ json: { type: 'boolean' },
556
+ 'no-prelude': { type: 'boolean' }
557
+ },
558
+ allowPositionals: false
559
+ });
560
+ const staleDays = values.stale === undefined ? defaultStaleDays : Number(values.stale);
561
+ if (!Number.isFinite(staleDays) || staleDays < 0) {
562
+ return fail(`cave check: --stale expects a non-negative number of days, got ${JSON.stringify(values.stale)}\n`);
563
+ }
564
+ const store = open(values.db ?? defaultDbPath(), values['no-prelude'] === true ? { registry: Registry.empty } : {});
565
+ try {
566
+ const report = caveCheck(store, { staleDays });
567
+ const out = values.json === true ?
568
+ `${JSON.stringify(report, undefined, 2)}\n` :
569
+ renderReport(report, staleDays);
570
+ // Violations fail the check (spec §20.2); the other sections are advisory.
571
+ return { code: report.violations.length > 0 ? 1 : 0, out, err: '' };
572
+ }
573
+ finally {
574
+ store.close();
575
+ }
576
+ };
257
577
  export const exportCommand = (argv) => {
258
578
  const { values } = parseArgs({
259
579
  args: [...argv],
@@ -291,8 +611,8 @@ export const helpCommand = (argv) => {
291
611
  if (text !== undefined) {
292
612
  return ok(`${text}\n`);
293
613
  }
294
- // mcp and ingest own their help (main.ts forwards `help X` to `X --help`).
295
- if (topic === 'mcp' || topic === 'ingest') {
614
+ // mcp, ingest and connect own their help (main.ts forwards `help X` to `X --help`).
615
+ if (topic === 'mcp' || topic === 'ingest' || topic === 'connect') {
296
616
  return ok(`see: cave ${topic} --help\n`);
297
617
  }
298
618
  return fail(`cave help: unknown command ${JSON.stringify(topic)}\n\n${usage}\n`, 2);
@@ -315,6 +635,10 @@ export const cave = (argv) => {
315
635
  return importCommand(rest);
316
636
  case 'query':
317
637
  return queryCommand(rest);
638
+ case 'derive':
639
+ return deriveCommand(rest);
640
+ case 'check':
641
+ return checkCommand(rest);
318
642
  case 'export':
319
643
  return exportCommand(rest);
320
644
  case 'demo':