clawvault 3.1.0 → 3.2.1

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 (273) hide show
  1. package/README.md +422 -141
  2. package/bin/clawvault.js +10 -2
  3. package/bin/command-registration.test.js +3 -1
  4. package/bin/command-runtime.js +9 -1
  5. package/bin/register-core-commands.js +23 -28
  6. package/bin/register-maintenance-commands.js +39 -3
  7. package/bin/register-query-commands.js +58 -29
  8. package/bin/register-tailscale-commands.js +106 -0
  9. package/bin/register-task-commands.js +18 -1
  10. package/bin/register-task-commands.test.js +16 -0
  11. package/bin/register-vault-operations-commands.js +29 -1
  12. package/bin/register-workgraph-commands.js +451 -0
  13. package/dashboard/lib/graph-diff.js +104 -0
  14. package/dashboard/lib/graph-diff.test.js +75 -0
  15. package/dashboard/lib/vault-parser.js +556 -0
  16. package/dashboard/lib/vault-parser.test.js +254 -0
  17. package/dashboard/public/app.js +796 -0
  18. package/dashboard/public/index.html +52 -0
  19. package/dashboard/public/styles.css +221 -0
  20. package/dashboard/server.js +374 -0
  21. package/dist/{chunk-C7OK5WKP.js → chunk-2JQ3O2YL.js} +4 -4
  22. package/dist/{chunk-VR5NE7PZ.js → chunk-2RAZ4ZFE.js} +1 -1
  23. package/dist/{chunk-F2JEUD4J.js → chunk-4ITRXIVT.js} +5 -7
  24. package/dist/{chunk-GUKMRGM7.js → chunk-4OXMU5S2.js} +1 -1
  25. package/dist/chunk-5PJ4STIC.js +465 -0
  26. package/dist/{chunk-62YTUT6J.js → chunk-AZYOKJYC.js} +2 -2
  27. package/dist/chunk-BSJ6RIT7.js +447 -0
  28. package/dist/chunk-ECRZL5XR.js +50 -0
  29. package/dist/chunk-ERNE2FZ5.js +189 -0
  30. package/dist/{chunk-WAZ3NLWL.js → chunk-F55HGNU4.js} +0 -47
  31. package/dist/{chunk-VGLOTGAS.js → chunk-FAKNOB7Y.js} +2 -2
  32. package/dist/{chunk-QK3UCXWL.js → chunk-FHFUXL6G.js} +2 -2
  33. package/dist/chunk-GNJL4YGR.js +79 -0
  34. package/dist/chunk-HR4KN6S2.js +152 -0
  35. package/dist/{chunk-OZ7RIXTO.js → chunk-IIOU45CK.js} +1 -1
  36. package/dist/chunk-IJBFGPCS.js +33 -0
  37. package/dist/chunk-IVRIKYFE.js +520 -0
  38. package/dist/chunk-K7PNYS45.js +93 -0
  39. package/dist/chunk-MDIH26GC.js +183 -0
  40. package/dist/{chunk-LYHGEHXG.js → chunk-MFAWT5O5.js} +0 -1
  41. package/dist/{chunk-H34S76MB.js → chunk-MNPUYCHQ.js} +6 -6
  42. package/dist/chunk-NTOPJI7W.js +207 -0
  43. package/dist/{chunk-QBLMXKF2.js → chunk-OIWVQYQF.js} +1 -1
  44. package/dist/chunk-PG56HX5T.js +154 -0
  45. package/dist/{chunk-LNJA2UGL.js → chunk-PI4WMLMG.js} +7 -84
  46. package/dist/chunk-QMHPQYUV.js +363 -0
  47. package/dist/{chunk-H62BP7RI.js → chunk-QPDDIHXE.js} +209 -43
  48. package/dist/{chunk-N2AXRYLC.js → chunk-QWQ3TIKS.js} +1 -1
  49. package/dist/{chunk-3DHXQHYG.js → chunk-R2MIW5G7.js} +1 -1
  50. package/dist/{chunk-SJSFRIYS.js → chunk-S5OJEGFG.js} +2 -2
  51. package/dist/chunk-SS4B7P7V.js +99 -0
  52. package/dist/chunk-TIGW564L.js +628 -0
  53. package/dist/chunk-U67V476Y.js +35 -0
  54. package/dist/{chunk-JY6FYXIT.js → chunk-UCQAOZHW.js} +6 -11
  55. package/dist/{chunk-ITPEXLHA.js → chunk-URXDAUVH.js} +24 -5
  56. package/dist/chunk-WIOLLGAD.js +190 -0
  57. package/dist/{chunk-3WRJEKN4.js → chunk-WJVWINEM.js} +72 -8
  58. package/dist/chunk-WMGIIABP.js +15 -0
  59. package/dist/{chunk-33UGEQRT.js → chunk-X3SPPUFG.js} +151 -64
  60. package/dist/{chunk-3NSBOUT3.js → chunk-Y3TIJEBP.js} +314 -79
  61. package/dist/chunk-Y6VJKXGL.js +373 -0
  62. package/dist/{chunk-LI4O6NVK.js → chunk-YDWHS4LJ.js} +49 -9
  63. package/dist/{chunk-U55BGUAU.js → chunk-YNIPYN4F.js} +5 -5
  64. package/dist/chunk-YXQCA6B7.js +226 -0
  65. package/dist/cli/index.js +26 -22
  66. package/dist/commands/archive.js +3 -3
  67. package/dist/commands/backlog.js +3 -3
  68. package/dist/commands/blocked.js +3 -3
  69. package/dist/commands/canvas.d.ts +15 -0
  70. package/dist/commands/canvas.js +200 -0
  71. package/dist/commands/checkpoint.js +2 -2
  72. package/dist/commands/compat.js +2 -2
  73. package/dist/commands/context.js +7 -5
  74. package/dist/commands/doctor.d.ts +11 -7
  75. package/dist/commands/doctor.js +16 -14
  76. package/dist/commands/embed.js +5 -6
  77. package/dist/commands/entities.js +2 -2
  78. package/dist/commands/graph.js +3 -3
  79. package/dist/commands/inject.d.ts +1 -1
  80. package/dist/commands/inject.js +4 -5
  81. package/dist/commands/kanban.js +4 -4
  82. package/dist/commands/link.js +2 -2
  83. package/dist/commands/migrate-observations.js +4 -4
  84. package/dist/commands/observe.d.ts +0 -1
  85. package/dist/commands/observe.js +13 -12
  86. package/dist/commands/project.js +5 -5
  87. package/dist/commands/rebuild-embeddings.d.ts +21 -0
  88. package/dist/commands/rebuild-embeddings.js +91 -0
  89. package/dist/commands/rebuild.js +12 -11
  90. package/dist/commands/recover.js +3 -3
  91. package/dist/commands/reflect.js +6 -7
  92. package/dist/commands/repair-session.js +1 -1
  93. package/dist/commands/replay.js +14 -14
  94. package/dist/commands/session-recap.js +1 -1
  95. package/dist/commands/setup.d.ts +2 -89
  96. package/dist/commands/setup.js +3 -21
  97. package/dist/commands/shell-init.js +1 -1
  98. package/dist/commands/sleep.d.ts +1 -1
  99. package/dist/commands/sleep.js +18 -17
  100. package/dist/commands/status.d.ts +2 -0
  101. package/dist/commands/status.js +40 -30
  102. package/dist/commands/sync-bd.d.ts +10 -0
  103. package/dist/commands/sync-bd.js +10 -0
  104. package/dist/commands/tailscale.d.ts +52 -0
  105. package/dist/commands/tailscale.js +26 -0
  106. package/dist/commands/task.js +4 -4
  107. package/dist/commands/template.js +2 -2
  108. package/dist/commands/wake.d.ts +1 -1
  109. package/dist/commands/wake.js +11 -10
  110. package/dist/index.d.ts +334 -191
  111. package/dist/index.js +432 -108
  112. package/dist/{inject-Bzi5E-By.d.ts → inject-DYUrDqQO.d.ts} +3 -3
  113. package/dist/ledger-B7g7jhqG.d.ts +44 -0
  114. package/dist/lib/auto-linker.js +1 -1
  115. package/dist/lib/canvas-layout.d.ts +115 -0
  116. package/dist/lib/canvas-layout.js +35 -0
  117. package/dist/lib/config.d.ts +27 -3
  118. package/dist/lib/config.js +4 -2
  119. package/dist/lib/entity-index.js +1 -1
  120. package/dist/lib/project-utils.js +4 -4
  121. package/dist/lib/session-repair.js +1 -1
  122. package/dist/lib/session-utils.js +1 -1
  123. package/dist/lib/tailscale.d.ts +225 -0
  124. package/dist/lib/tailscale.js +50 -0
  125. package/dist/lib/task-utils.js +3 -3
  126. package/dist/lib/template-engine.js +1 -1
  127. package/dist/lib/webdav.d.ts +109 -0
  128. package/dist/lib/webdav.js +35 -0
  129. package/dist/plugin/index.d.ts +344 -28
  130. package/dist/plugin/index.js +3919 -227
  131. package/dist/registry-BR4326o0.d.ts +30 -0
  132. package/dist/store-CA-6sKCJ.d.ts +34 -0
  133. package/dist/thread-B9LhXNU0.d.ts +41 -0
  134. package/dist/{types-Y2_Um2Ls.d.ts → types-BbWJoC1c.d.ts} +1 -44
  135. package/dist/workgraph/index.d.ts +5 -0
  136. package/dist/workgraph/index.js +23 -0
  137. package/dist/workgraph/ledger.d.ts +2 -0
  138. package/dist/workgraph/ledger.js +25 -0
  139. package/dist/workgraph/registry.d.ts +2 -0
  140. package/dist/workgraph/registry.js +19 -0
  141. package/dist/workgraph/store.d.ts +2 -0
  142. package/dist/workgraph/store.js +25 -0
  143. package/dist/workgraph/thread.d.ts +2 -0
  144. package/dist/workgraph/thread.js +25 -0
  145. package/dist/workgraph/types.d.ts +54 -0
  146. package/dist/workgraph/types.js +7 -0
  147. package/hooks/clawvault/HOOK.md +113 -0
  148. package/hooks/clawvault/handler.js +1559 -0
  149. package/hooks/clawvault/handler.test.js +510 -0
  150. package/hooks/clawvault/openclaw.plugin.json +72 -0
  151. package/openclaw.plugin.json +235 -30
  152. package/package.json +20 -20
  153. package/dist/chunk-3RG5ZIWI.js +0 -10
  154. package/dist/chunk-3ZIH425O.js +0 -871
  155. package/dist/chunk-6U6MK36V.js +0 -205
  156. package/dist/chunk-CMB7UL7C.js +0 -327
  157. package/dist/chunk-D2H45LON.js +0 -1074
  158. package/dist/chunk-E7MFQB6D.js +0 -163
  159. package/dist/chunk-GQSLDZTS.js +0 -560
  160. package/dist/chunk-MFM6K7PU.js +0 -374
  161. package/dist/chunk-MXSSG3QU.js +0 -42
  162. package/dist/chunk-OCGVIN3L.js +0 -88
  163. package/dist/chunk-PAH27GSN.js +0 -108
  164. package/dist/chunk-YCUNCH2I.js +0 -78
  165. package/dist/cli/index.cjs +0 -8584
  166. package/dist/cli/index.d.cts +0 -5
  167. package/dist/commands/archive.cjs +0 -287
  168. package/dist/commands/archive.d.cts +0 -11
  169. package/dist/commands/backlog.cjs +0 -721
  170. package/dist/commands/backlog.d.cts +0 -53
  171. package/dist/commands/blocked.cjs +0 -204
  172. package/dist/commands/blocked.d.cts +0 -26
  173. package/dist/commands/checkpoint.cjs +0 -244
  174. package/dist/commands/checkpoint.d.cts +0 -41
  175. package/dist/commands/compat.cjs +0 -294
  176. package/dist/commands/compat.d.cts +0 -28
  177. package/dist/commands/context.cjs +0 -2990
  178. package/dist/commands/context.d.cts +0 -2
  179. package/dist/commands/doctor.cjs +0 -2986
  180. package/dist/commands/doctor.d.cts +0 -21
  181. package/dist/commands/embed.cjs +0 -232
  182. package/dist/commands/embed.d.cts +0 -17
  183. package/dist/commands/entities.cjs +0 -141
  184. package/dist/commands/entities.d.cts +0 -7
  185. package/dist/commands/graph.cjs +0 -501
  186. package/dist/commands/graph.d.cts +0 -21
  187. package/dist/commands/inject.cjs +0 -1636
  188. package/dist/commands/inject.d.cts +0 -2
  189. package/dist/commands/kanban.cjs +0 -884
  190. package/dist/commands/kanban.d.cts +0 -63
  191. package/dist/commands/link.cjs +0 -965
  192. package/dist/commands/link.d.cts +0 -11
  193. package/dist/commands/migrate-observations.cjs +0 -362
  194. package/dist/commands/migrate-observations.d.cts +0 -19
  195. package/dist/commands/observe.cjs +0 -4099
  196. package/dist/commands/observe.d.cts +0 -23
  197. package/dist/commands/project.cjs +0 -1341
  198. package/dist/commands/project.d.cts +0 -85
  199. package/dist/commands/rebuild.cjs +0 -3136
  200. package/dist/commands/rebuild.d.cts +0 -11
  201. package/dist/commands/recover.cjs +0 -361
  202. package/dist/commands/recover.d.cts +0 -38
  203. package/dist/commands/reflect.cjs +0 -1008
  204. package/dist/commands/reflect.d.cts +0 -11
  205. package/dist/commands/repair-session.cjs +0 -457
  206. package/dist/commands/repair-session.d.cts +0 -38
  207. package/dist/commands/replay.cjs +0 -4103
  208. package/dist/commands/replay.d.cts +0 -16
  209. package/dist/commands/session-recap.cjs +0 -353
  210. package/dist/commands/session-recap.d.cts +0 -27
  211. package/dist/commands/setup.cjs +0 -1278
  212. package/dist/commands/setup.d.cts +0 -99
  213. package/dist/commands/shell-init.cjs +0 -75
  214. package/dist/commands/shell-init.d.cts +0 -7
  215. package/dist/commands/sleep.cjs +0 -6029
  216. package/dist/commands/sleep.d.cts +0 -36
  217. package/dist/commands/status.cjs +0 -2737
  218. package/dist/commands/status.d.cts +0 -52
  219. package/dist/commands/task.cjs +0 -1236
  220. package/dist/commands/task.d.cts +0 -97
  221. package/dist/commands/template.cjs +0 -457
  222. package/dist/commands/template.d.cts +0 -36
  223. package/dist/commands/wake.cjs +0 -2627
  224. package/dist/commands/wake.d.cts +0 -22
  225. package/dist/context-BUGaWpyL.d.cts +0 -46
  226. package/dist/index.cjs +0 -12373
  227. package/dist/index.d.cts +0 -854
  228. package/dist/inject-Bzi5E-By.d.cts +0 -137
  229. package/dist/lib/auto-linker.cjs +0 -176
  230. package/dist/lib/auto-linker.d.cts +0 -26
  231. package/dist/lib/config.cjs +0 -78
  232. package/dist/lib/config.d.cts +0 -11
  233. package/dist/lib/entity-index.cjs +0 -84
  234. package/dist/lib/entity-index.d.cts +0 -26
  235. package/dist/lib/project-utils.cjs +0 -864
  236. package/dist/lib/project-utils.d.cts +0 -97
  237. package/dist/lib/session-repair.cjs +0 -239
  238. package/dist/lib/session-repair.d.cts +0 -110
  239. package/dist/lib/session-utils.cjs +0 -209
  240. package/dist/lib/session-utils.d.cts +0 -63
  241. package/dist/lib/task-utils.cjs +0 -1137
  242. package/dist/lib/task-utils.d.cts +0 -208
  243. package/dist/lib/template-engine.cjs +0 -47
  244. package/dist/lib/template-engine.d.cts +0 -11
  245. package/dist/plugin/index.cjs +0 -1907
  246. package/dist/plugin/index.d.cts +0 -36
  247. package/dist/plugin/inject.cjs +0 -356
  248. package/dist/plugin/inject.d.cts +0 -54
  249. package/dist/plugin/inject.d.ts +0 -54
  250. package/dist/plugin/inject.js +0 -17
  251. package/dist/plugin/observe.cjs +0 -631
  252. package/dist/plugin/observe.d.cts +0 -39
  253. package/dist/plugin/observe.d.ts +0 -39
  254. package/dist/plugin/observe.js +0 -18
  255. package/dist/plugin/templates.cjs +0 -593
  256. package/dist/plugin/templates.d.cts +0 -52
  257. package/dist/plugin/templates.d.ts +0 -52
  258. package/dist/plugin/templates.js +0 -25
  259. package/dist/plugin/types.cjs +0 -18
  260. package/dist/plugin/types.d.cts +0 -209
  261. package/dist/plugin/types.d.ts +0 -209
  262. package/dist/plugin/types.js +0 -0
  263. package/dist/plugin/vault.cjs +0 -927
  264. package/dist/plugin/vault.d.cts +0 -68
  265. package/dist/plugin/vault.d.ts +0 -68
  266. package/dist/plugin/vault.js +0 -22
  267. package/dist/types-Y2_Um2Ls.d.cts +0 -205
  268. package/templates/memory-event.md +0 -67
  269. package/templates/party.md +0 -63
  270. package/templates/primitive-registry.yaml +0 -551
  271. package/templates/run.md +0 -68
  272. package/templates/trigger.md +0 -68
  273. package/templates/workspace.md +0 -50
@@ -1,2737 +0,0 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
11
- };
12
- var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
- }
18
- return to;
19
- };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
-
30
- // src/commands/status.ts
31
- var status_exports = {};
32
- __export(status_exports, {
33
- formatStatus: () => formatStatus,
34
- getStatus: () => getStatus,
35
- statusCommand: () => statusCommand
36
- });
37
- module.exports = __toCommonJS(status_exports);
38
- var fs7 = __toESM(require("fs"), 1);
39
- var path8 = __toESM(require("path"), 1);
40
- var import_child_process2 = require("child_process");
41
-
42
- // src/lib/vault.ts
43
- var fs3 = __toESM(require("fs"), 1);
44
- var path3 = __toESM(require("path"), 1);
45
- var import_url = require("url");
46
- var import_gray_matter2 = __toESM(require("gray-matter"), 1);
47
- var import_glob2 = require("glob");
48
-
49
- // src/types.ts
50
- var DEFAULT_CATEGORIES = [
51
- "rules",
52
- "preferences",
53
- "decisions",
54
- "patterns",
55
- "people",
56
- "projects",
57
- "goals",
58
- "transcripts",
59
- "inbox",
60
- "templates",
61
- "lessons",
62
- "agents",
63
- "commitments",
64
- "handoffs",
65
- "research",
66
- "tasks",
67
- "backlog"
68
- ];
69
- var TYPE_TO_CATEGORY = {
70
- fact: "facts",
71
- feeling: "feelings",
72
- decision: "decisions",
73
- lesson: "lessons",
74
- commitment: "commitments",
75
- preference: "preferences",
76
- relationship: "people",
77
- project: "projects"
78
- };
79
-
80
- // src/lib/search.ts
81
- var import_child_process = require("child_process");
82
- var fs = __toESM(require("fs"), 1);
83
- var path = __toESM(require("path"), 1);
84
-
85
- // src/lib/reweave.ts
86
- var SUPERSEDED_MARKER_RE = /\[superseded\|by=([^\]|]+)\|detected=([^\]]+)\]/;
87
- function isSuperseded(line) {
88
- return SUPERSEDED_MARKER_RE.test(line);
89
- }
90
-
91
- // src/lib/search.ts
92
- var QMD_INSTALL_COMMAND = "bun install -g github:tobi/qmd";
93
- var QMD_NOT_INSTALLED_MESSAGE = `ClawVault requires qmd. Install: ${QMD_INSTALL_COMMAND}`;
94
- var QMD_INDEX_ENV_VAR = "CLAWVAULT_QMD_INDEX";
95
- var QmdUnavailableError = class extends Error {
96
- constructor(message = QMD_NOT_INSTALLED_MESSAGE) {
97
- super(message);
98
- this.name = "QmdUnavailableError";
99
- }
100
- };
101
- function ensureJsonArgs(args) {
102
- return args.includes("--json") ? args : [...args, "--json"];
103
- }
104
- function resolveQmdIndexName(indexName) {
105
- const explicit = indexName?.trim();
106
- if (explicit) {
107
- return explicit;
108
- }
109
- const fromEnv = process.env[QMD_INDEX_ENV_VAR]?.trim();
110
- return fromEnv || void 0;
111
- }
112
- function withQmdIndexArgs(args, indexName) {
113
- if (args.includes("--index")) {
114
- return [...args];
115
- }
116
- const resolvedIndexName = resolveQmdIndexName(indexName);
117
- if (!resolvedIndexName) {
118
- return [...args];
119
- }
120
- return ["--index", resolvedIndexName, ...args];
121
- }
122
- function tryParseJson(raw) {
123
- try {
124
- return JSON.parse(raw);
125
- } catch {
126
- return null;
127
- }
128
- }
129
- function extractJsonPayload(raw) {
130
- const start = raw.search(/[\[{]/);
131
- if (start === -1) return null;
132
- const end = Math.max(raw.lastIndexOf("]"), raw.lastIndexOf("}"));
133
- if (end <= start) return null;
134
- return raw.slice(start, end + 1);
135
- }
136
- function stripQmdNoise(raw) {
137
- return raw.split("\n").filter((line) => {
138
- const t = line.trim();
139
- if (!t) return true;
140
- if (t.startsWith("[node-llama-cpp]")) return false;
141
- if (t.startsWith("Expanding query")) return false;
142
- if (t.startsWith("Searching ") && t.endsWith("queries...")) return false;
143
- if (/^[├└─│]/.test(t)) return false;
144
- return true;
145
- }).join("\n");
146
- }
147
- function parseQmdOutput(raw) {
148
- const trimmed = stripQmdNoise(raw).trim();
149
- if (!trimmed) return [];
150
- if (trimmed.startsWith("No results") || trimmed.startsWith("No matches")) return [];
151
- const direct = tryParseJson(trimmed);
152
- const extracted = direct ? null : extractJsonPayload(trimmed);
153
- const parsed = direct ?? (extracted ? tryParseJson(extracted) : null);
154
- if (!parsed) {
155
- throw new Error("qmd returned non-JSON output. Ensure qmd supports --json.");
156
- }
157
- if (Array.isArray(parsed)) {
158
- return parsed;
159
- }
160
- if (parsed && typeof parsed === "object") {
161
- const candidate = parsed.results ?? parsed.items ?? parsed.data;
162
- if (Array.isArray(candidate)) {
163
- return candidate;
164
- }
165
- }
166
- throw new Error("qmd returned an unexpected JSON shape.");
167
- }
168
- function ensureQmdAvailable() {
169
- if (!hasQmd()) {
170
- throw new QmdUnavailableError();
171
- }
172
- }
173
- function execQmd(args, indexName) {
174
- ensureQmdAvailable();
175
- const finalArgs = withQmdIndexArgs(ensureJsonArgs(args), indexName);
176
- try {
177
- const result = (0, import_child_process.execFileSync)("qmd", finalArgs, {
178
- encoding: "utf-8",
179
- stdio: ["ignore", "pipe", "pipe"],
180
- maxBuffer: 10 * 1024 * 1024
181
- // 10MB
182
- });
183
- return parseQmdOutput(result);
184
- } catch (err) {
185
- if (err?.code === "ENOENT") {
186
- throw new QmdUnavailableError();
187
- }
188
- const output = [err?.stdout, err?.stderr].filter(Boolean).join("\n");
189
- if (output) {
190
- try {
191
- return parseQmdOutput(output);
192
- } catch {
193
- }
194
- }
195
- const message = err?.message ? `qmd failed: ${err.message}` : "qmd failed";
196
- throw new Error(message);
197
- }
198
- }
199
- function hasQmd() {
200
- const result = (0, import_child_process.spawnSync)("qmd", ["--version"], { stdio: "ignore" });
201
- return !result.error;
202
- }
203
- function qmdUpdate(collection, indexName) {
204
- ensureQmdAvailable();
205
- const args = ["update"];
206
- if (collection) {
207
- args.push("-c", collection);
208
- }
209
- (0, import_child_process.execFileSync)("qmd", withQmdIndexArgs(args, indexName), { stdio: "inherit" });
210
- }
211
- function qmdEmbed(collection, indexName) {
212
- ensureQmdAvailable();
213
- const args = ["embed"];
214
- if (collection) {
215
- args.push("-c", collection);
216
- }
217
- (0, import_child_process.execFileSync)("qmd", withQmdIndexArgs(args, indexName), { stdio: "inherit" });
218
- }
219
- function sentenceChunk(text, maxChars = 600, overlapSentences = 1) {
220
- const sentences = text.split(/(?<=[.!?])\s+|\n{2,}/).map((s) => s.trim()).filter(Boolean);
221
- if (sentences.length === 0) return text.trim() ? [text] : [];
222
- const chunks = [];
223
- let i = 0;
224
- while (i < sentences.length) {
225
- const chunkSents = [];
226
- let chunkLen = 0;
227
- let j = i;
228
- while (j < sentences.length && chunkLen + sentences[j].length < maxChars) {
229
- chunkSents.push(sentences[j]);
230
- chunkLen += sentences[j].length + 1;
231
- j++;
232
- }
233
- if (chunkSents.length === 0) {
234
- chunkSents.push(sentences[j].slice(0, maxChars));
235
- j++;
236
- }
237
- chunks.push(chunkSents.join(" "));
238
- i = Math.max(j - overlapSentences, i + 1);
239
- }
240
- return chunks;
241
- }
242
- var STOPWORDS = /* @__PURE__ */ new Set([
243
- "what",
244
- "when",
245
- "where",
246
- "which",
247
- "that",
248
- "this",
249
- "have",
250
- "from",
251
- "with",
252
- "they",
253
- "been",
254
- "were",
255
- "will",
256
- "about",
257
- "would",
258
- "could",
259
- "should",
260
- "their",
261
- "there",
262
- "does",
263
- "your",
264
- "more",
265
- "some",
266
- "than",
267
- "into",
268
- "also",
269
- "just",
270
- "very",
271
- "much",
272
- "most",
273
- "many",
274
- "only",
275
- "other",
276
- "each",
277
- "every",
278
- "after",
279
- "before",
280
- "did",
281
- "the",
282
- "and",
283
- "for",
284
- "are",
285
- "was",
286
- "not",
287
- "but",
288
- "can",
289
- "had",
290
- "has",
291
- "how",
292
- "who",
293
- "why",
294
- "its",
295
- "you",
296
- "my",
297
- "me",
298
- "is",
299
- "it",
300
- "do",
301
- "so",
302
- "if",
303
- "or",
304
- "an",
305
- "on",
306
- "at",
307
- "by",
308
- "no",
309
- "up",
310
- "to",
311
- "in",
312
- "of",
313
- "am",
314
- "be"
315
- ]);
316
- function tokenize(text) {
317
- return text.toLowerCase().split(/\s+/).map((w) => w.replace(/^[?.,!"'\-():;[\]{}*]+|[?.,!"'\-():;[\]{}*]+$/g, "")).filter((w) => w.length > 1);
318
- }
319
- function queryTerms(query) {
320
- return tokenize(query).filter((w) => !STOPWORDS.has(w));
321
- }
322
- function bm25RankChunks(chunks, terms, max = 5) {
323
- if (chunks.length === 0) return [];
324
- const termSet = new Set(terms);
325
- const scored = chunks.map((text, idx) => {
326
- const words = new Set(tokenize(text));
327
- let overlap = 0;
328
- for (const t of termSet) if (words.has(t)) overlap++;
329
- return { text, score: overlap, idx };
330
- });
331
- scored.sort((a, b) => b.score - a.score);
332
- const seen = /* @__PURE__ */ new Set();
333
- const result = [];
334
- seen.add(0);
335
- result.push({ text: chunks[0], score: scored.find((s) => s.idx === 0)?.score ?? 0 });
336
- for (const s of scored) {
337
- if (result.length >= max) break;
338
- if (!seen.has(s.idx) && s.score > 0) {
339
- seen.add(s.idx);
340
- result.push({ text: s.text, score: s.score });
341
- }
342
- }
343
- return result;
344
- }
345
- var MONTH_NAMES = {
346
- january: 1,
347
- february: 2,
348
- march: 3,
349
- april: 4,
350
- may: 5,
351
- june: 6,
352
- july: 7,
353
- august: 8,
354
- september: 9,
355
- october: 10,
356
- november: 11,
357
- december: 12,
358
- jan: 1,
359
- feb: 2,
360
- mar: 3,
361
- apr: 4,
362
- jun: 6,
363
- jul: 7,
364
- aug: 8,
365
- sep: 9,
366
- sept: 9,
367
- oct: 10,
368
- nov: 11,
369
- dec: 12
370
- };
371
- var MONTH_RE_PART = Object.keys(MONTH_NAMES).join("|");
372
- var DATE_ISO_RE = /\b(\d{4})[/-](\d{1,2})[/-](\d{1,2})\b/g;
373
- var DATE_US_RE = /\b(\d{1,2})\/(\d{1,2})\/(\d{4})\b/g;
374
- var DATE_MONTH_DAY_YEAR_RE = new RegExp(
375
- `\\b(${MONTH_RE_PART})\\s+(\\d{1,2})(?:st|nd|rd|th)?,?\\s*(\\d{4})\\b`,
376
- "gi"
377
- );
378
- var DATE_DAY_MONTH_YEAR_RE = new RegExp(
379
- `\\b(\\d{1,2})(?:st|nd|rd|th)?\\s+(${MONTH_RE_PART}),?\\s*(\\d{4})\\b`,
380
- "gi"
381
- );
382
- var DATE_MONTH_DAY_RE = new RegExp(
383
- `\\b(${MONTH_RE_PART})\\s+(\\d{1,2})(?:st|nd|rd|th)?\\b`,
384
- "gi"
385
- );
386
- var RELATIVE_AGO_RE = /\b(\d+)\s+(days?|weeks?|months?|years?)\s+ago\b/gi;
387
- var RELATIVE_IN_RE = /\bin\s+(\d+)\s+(days?|weeks?|months?|years?)\b/gi;
388
- var DURATION_RE = /(?:for|took|spent|lasted|about|approximately|around)\s+(\d+)\s+(days?|weeks?|months?|years?|hours?|minutes?)/gi;
389
- function tryParseISODate(y, m, d) {
390
- const dt = new Date(Date.UTC(y, m - 1, d));
391
- if (dt.getUTCFullYear() === y && dt.getUTCMonth() === m - 1 && dt.getUTCDate() === d) return dt;
392
- return null;
393
- }
394
- function unitToDays(n, unit) {
395
- const u = unit.toLowerCase().replace(/s$/, "");
396
- switch (u) {
397
- case "day":
398
- return n;
399
- case "week":
400
- return n * 7;
401
- case "month":
402
- return n * 30;
403
- case "year":
404
- return n * 365;
405
- default:
406
- return null;
407
- }
408
- }
409
- function contextSnippet(text, start, end, maxLen = 150) {
410
- const s = Math.max(0, start - Math.floor(maxLen / 2));
411
- const e = Math.min(text.length, end + Math.floor(maxLen / 2));
412
- return text.slice(s, e).replace(/\n/g, " ").trim();
413
- }
414
- function isoStr(d) {
415
- const yy = d.getUTCFullYear();
416
- const mm = String(d.getUTCMonth() + 1).padStart(2, "0");
417
- const dd = String(d.getUTCDate()).padStart(2, "0");
418
- return `${yy}-${mm}-${dd}`;
419
- }
420
- function extractDates(text, sessionDateStr) {
421
- const results = [];
422
- const sessionDate = sessionDateStr ? new Date(sessionDateStr) : null;
423
- const seen = /* @__PURE__ */ new Set();
424
- function push(date, ctx, docId = "") {
425
- const key = `${date}|${ctx.slice(0, 60)}`;
426
- if (seen.has(key)) return;
427
- seen.add(key);
428
- results.push({ date, context: ctx, documentId: docId });
429
- }
430
- for (const m of text.matchAll(DATE_ISO_RE)) {
431
- const dt = tryParseISODate(+m[1], +m[2], +m[3]);
432
- if (dt) push(isoStr(dt), contextSnippet(text, m.index, m.index + m[0].length));
433
- }
434
- for (const m of text.matchAll(DATE_US_RE)) {
435
- const dt = tryParseISODate(+m[3], +m[1], +m[2]);
436
- if (dt) push(isoStr(dt), contextSnippet(text, m.index, m.index + m[0].length));
437
- }
438
- for (const m of text.matchAll(DATE_MONTH_DAY_YEAR_RE)) {
439
- const mon = MONTH_NAMES[m[1].toLowerCase()];
440
- if (mon) {
441
- const dt = tryParseISODate(+m[3], mon, +m[2]);
442
- if (dt) push(isoStr(dt), contextSnippet(text, m.index, m.index + m[0].length));
443
- }
444
- }
445
- for (const m of text.matchAll(DATE_DAY_MONTH_YEAR_RE)) {
446
- const mon = MONTH_NAMES[m[2].toLowerCase()];
447
- if (mon) {
448
- const dt = tryParseISODate(+m[3], mon, +m[1]);
449
- if (dt) push(isoStr(dt), contextSnippet(text, m.index, m.index + m[0].length));
450
- }
451
- }
452
- if (sessionDate) {
453
- for (const m of text.matchAll(DATE_MONTH_DAY_RE)) {
454
- const mon = MONTH_NAMES[m[1].toLowerCase()];
455
- if (mon) {
456
- const dt = tryParseISODate(sessionDate.getFullYear(), mon, +m[2]);
457
- if (dt) push(isoStr(dt), contextSnippet(text, m.index, m.index + m[0].length));
458
- }
459
- }
460
- }
461
- if (sessionDate) {
462
- for (const m of text.matchAll(RELATIVE_AGO_RE)) {
463
- const days = unitToDays(+m[1], m[2]);
464
- if (days !== null) {
465
- const dt = new Date(sessionDate.getTime() - days * 864e5);
466
- push(isoStr(dt), contextSnippet(text, m.index, m.index + m[0].length));
467
- }
468
- }
469
- for (const m of text.matchAll(RELATIVE_IN_RE)) {
470
- const days = unitToDays(+m[1], m[2]);
471
- if (days !== null) {
472
- const dt = new Date(sessionDate.getTime() + days * 864e5);
473
- push(isoStr(dt), contextSnippet(text, m.index, m.index + m[0].length));
474
- }
475
- }
476
- }
477
- for (const m of text.matchAll(DURATION_RE)) {
478
- push(`duration:${m[1]} ${m[2]}`, contextSnippet(text, m.index, m.index + m[0].length));
479
- }
480
- return results;
481
- }
482
- var PREF_PATTERNS = [
483
- // "I use/prefer/like/love/enjoy X"
484
- /\bi\s+(?:use|prefer|like|love|enjoy|favor|chose|switched to|started using|always use|usually use)\s+(.{3,60}?)(?:[.,;!?\n]|$)/gi,
485
- // "my favorite X is Y"
486
- /\bmy\s+(?:favorite|preferred|go-to|usual)\s+\w+\s+(?:is|are|was)\s+(.{3,60}?)(?:[.,;!?\n]|$)/gi,
487
- // "I'm a big fan of X"
488
- /\bi(?:'m| am)\s+(?:a )?(?:big |huge )?fan of\s+(.{3,60}?)(?:[.,;!?\n]|$)/gi,
489
- // "I switched from X to Y"
490
- /\bi\s+switched\s+from\s+(.{3,40}?)\s+to\s+(.{3,40}?)(?:[.,;!?\n]|$)/gi
491
- ];
492
- function extractPreferences(text, documentId = "") {
493
- const results = [];
494
- const seen = /* @__PURE__ */ new Set();
495
- for (const pattern of PREF_PATTERNS) {
496
- for (const m of text.matchAll(pattern)) {
497
- const value = (m[1] || "").trim();
498
- if (!value || value.length < 3) continue;
499
- const key = value.toLowerCase();
500
- if (seen.has(key)) continue;
501
- seen.add(key);
502
- const ctx = contextSnippet(text, m.index, m.index + m[0].length, 200);
503
- let category = "general";
504
- if (/tool|software|app|editor|ide|framework|library|language/i.test(ctx)) category = "tool";
505
- else if (/hobby|sport|exercise|game|play/i.test(ctx)) category = "hobby";
506
- else if (/brand|product|model|device|hardware/i.test(ctx)) category = "brand";
507
- else if (/food|drink|restaurant|cuisine|recipe/i.test(ctx)) category = "food";
508
- else if (/music|movie|show|book|podcast|artist|band/i.test(ctx)) category = "entertainment";
509
- results.push({ category, value, documentId, context: ctx });
510
- }
511
- }
512
- return results;
513
- }
514
- var PREFERENCE_Q_RE = /(?:can you (?:recommend|suggest)|any (?:tips|advice|suggestions|recommendations)|what .*(?:recommend|suggest)|what should i|where should i|which .* should i|please (?:recommend|suggest)|based on .* (?:interest|preference|taste)|personalized|tailored to (?:my|me))/i;
515
- var TEMPORAL_Q_RE = /(?:how many (?:days|weeks|months|years|hours|minutes) (?:passed|did|have|ago|between|since|in total|took)|how long (?:did|was|were|have|has|does)|how long ago|what (?:is the )?order|in order|which .* (?:first|last|earlier|later|before|after|most recent|oldest|newest)|chronological|(?:earlier|later|sooner|newer|older) than)/i;
516
- var AGGREGATION_Q_RE = /(?:how many|how much|total|all the|count|list all|every|what are all|name all)/i;
517
- function classifyQuestion(q) {
518
- if (PREFERENCE_Q_RE.test(q)) return "preference";
519
- if (TEMPORAL_Q_RE.test(q)) return "temporal";
520
- if (!TEMPORAL_Q_RE.test(q) && AGGREGATION_Q_RE.test(q)) return "aggregation";
521
- return "default";
522
- }
523
- var SearchEngine = class {
524
- documents = /* @__PURE__ */ new Map();
525
- collection = "clawvault";
526
- vaultPath = "";
527
- collectionRoot = "";
528
- qmdIndexName;
529
- /** v2.7 — Per-document date index built at ingest time */
530
- dateIndex = /* @__PURE__ */ new Map();
531
- /** v2.7 — Per-document preference index built at ingest time */
532
- preferenceIndex = /* @__PURE__ */ new Map();
533
- /** v2.7 — Per-document chunk cache for BM25 pre-filtering */
534
- chunkCache = /* @__PURE__ */ new Map();
535
- /**
536
- * Set the collection name (usually vault name)
537
- */
538
- setCollection(name) {
539
- this.collection = name;
540
- }
541
- /**
542
- * Set the vault path for file resolution
543
- */
544
- setVaultPath(vaultPath) {
545
- this.vaultPath = vaultPath;
546
- }
547
- /**
548
- * Set the collection root for qmd:// URI resolution
549
- */
550
- setCollectionRoot(root) {
551
- this.collectionRoot = path.resolve(root);
552
- }
553
- /**
554
- * Set qmd index name (defaults to qmd global default when omitted)
555
- */
556
- setIndexName(indexName) {
557
- this.qmdIndexName = indexName;
558
- }
559
- /**
560
- * Add or update a document in the local cache.
561
- * v2.7: also extracts dates, preferences, and chunks at ingest time.
562
- * Note: qmd indexing happens via qmd update command
563
- */
564
- addDocument(doc) {
565
- this.documents.set(doc.id, doc);
566
- if (doc.content) {
567
- const sessionDate = doc.modified ? isoStr(doc.modified) : void 0;
568
- const dates = extractDates(doc.content, sessionDate);
569
- for (const d of dates) d.documentId = doc.id;
570
- if (dates.length > 0) this.dateIndex.set(doc.id, dates);
571
- const prefs = extractPreferences(doc.content, doc.id);
572
- if (prefs.length > 0) this.preferenceIndex.set(doc.id, prefs);
573
- const chunks = sentenceChunk(doc.content, 600, 1);
574
- if (chunks.length > 0) this.chunkCache.set(doc.id, chunks);
575
- }
576
- }
577
- /**
578
- * Remove a document from the local cache
579
- */
580
- removeDocument(id) {
581
- this.documents.delete(id);
582
- this.dateIndex.delete(id);
583
- this.preferenceIndex.delete(id);
584
- this.chunkCache.delete(id);
585
- }
586
- /**
587
- * No-op for qmd - indexing is managed externally
588
- */
589
- rebuildIDF() {
590
- }
591
- /**
592
- * BM25 search via qmd
593
- */
594
- search(query, options = {}) {
595
- return this.runQmdQuery("search", query, options);
596
- }
597
- /**
598
- * Vector/semantic search via qmd vsearch
599
- */
600
- vsearch(query, options = {}) {
601
- return this.runQmdQuery("vsearch", query, options);
602
- }
603
- /**
604
- * Combined search with query expansion (qmd query command)
605
- */
606
- query(query, options = {}) {
607
- return this.runQmdQuery("query", query, options);
608
- }
609
- runQmdQuery(command, query, options) {
610
- const {
611
- limit = 10,
612
- minScore = 0,
613
- category,
614
- tags,
615
- fullContent = false,
616
- temporalBoost = false,
617
- relevanceThreshold,
618
- thresholdMaxResults = 40
619
- } = options;
620
- if (!query.trim()) return [];
621
- const fetchLimit = relevanceThreshold !== void 0 ? thresholdMaxResults * 2 : limit * 2;
622
- const args = [
623
- command,
624
- query,
625
- "-n",
626
- String(fetchLimit),
627
- "--json"
628
- ];
629
- if (this.collection) {
630
- args.push("-c", this.collection);
631
- }
632
- const qmdResults = execQmd(args, this.qmdIndexName);
633
- const effectiveLimit = relevanceThreshold !== void 0 ? thresholdMaxResults : limit;
634
- const results = this.convertResults(qmdResults, {
635
- limit: effectiveLimit,
636
- minScore: relevanceThreshold !== void 0 ? relevanceThreshold : minScore,
637
- category,
638
- tags,
639
- fullContent,
640
- temporalBoost
641
- });
642
- return results;
643
- }
644
- // -------------------------------------------------------------------------
645
- // v2.7 — New public APIs
646
- // -------------------------------------------------------------------------
647
- /**
648
- * v2.7 — Chunk-level BM25 pre-filtered search. Ranks chunks within each
649
- * document by keyword relevance before semantic ranking, so relevant
650
- * content deep in long documents isn't missed.
651
- *
652
- * Returns results with snippets from the best-matching chunks.
653
- */
654
- chunkPrefilterSearch(query, options = {}) {
655
- const terms = queryTerms(query);
656
- const results = this.runQmdQuery("query", query, options);
657
- for (const r of results) {
658
- const chunks = this.chunkCache.get(r.document.id);
659
- if (chunks && chunks.length > 0 && terms.length > 0) {
660
- const ranked = bm25RankChunks(chunks, terms, 3);
661
- if (ranked.length > 0 && ranked[0].score > 0) {
662
- r.snippet = ranked.map((c) => c.text).join("\n...\n").slice(0, 600);
663
- }
664
- }
665
- }
666
- return results;
667
- }
668
- /**
669
- * v2.7 — Exhaustive threshold-based search for aggregation queries.
670
- * Keeps pulling results until relevance drops below threshold.
671
- */
672
- exhaustiveSearch(query, threshold = 0.01, maxResults = 40) {
673
- return this.runQmdQuery("query", query, {
674
- relevanceThreshold: threshold,
675
- thresholdMaxResults: maxResults,
676
- fullContent: false
677
- });
678
- }
679
- /**
680
- * v2.7 — Get all extracted dates, optionally filtered by document ids.
681
- */
682
- getDates(documentIds) {
683
- const all = [];
684
- const iter = documentIds ? documentIds.map((id) => [id, this.dateIndex.get(id)]).filter(([, v]) => v) : this.dateIndex.entries();
685
- for (const [, dates] of iter) {
686
- if (dates) all.push(...dates);
687
- }
688
- return all;
689
- }
690
- /**
691
- * v2.7 — Get all extracted preferences, optionally filtered by document ids.
692
- */
693
- getPreferences(documentIds) {
694
- const all = [];
695
- const iter = documentIds ? documentIds.map((id) => [id, this.preferenceIndex.get(id)]).filter(([, v]) => v) : this.preferenceIndex.entries();
696
- for (const [, prefs] of iter) {
697
- if (prefs) all.push(...prefs);
698
- }
699
- return all;
700
- }
701
- /**
702
- * v2.7 — Search with automatic strategy selection based on question type.
703
- * Classifies the query and routes to the appropriate pipeline.
704
- */
705
- smartQuery(query, options = {}) {
706
- const qtype = classifyQuestion(query);
707
- switch (qtype) {
708
- case "aggregation":
709
- return this.exhaustiveSearch(query, 0.01, options.thresholdMaxResults ?? 40);
710
- case "preference":
711
- case "temporal":
712
- default:
713
- return this.chunkPrefilterSearch(query, { ...options, limit: options.limit ?? 10 });
714
- }
715
- }
716
- /**
717
- * Convert qmd results to ClawVault SearchResult format
718
- */
719
- convertResults(qmdResults, options) {
720
- const { limit = 10, minScore = 0, category, tags, fullContent = false, temporalBoost = false } = options;
721
- const results = [];
722
- const maxScore = qmdResults[0]?.score || 1;
723
- for (const qr of qmdResults) {
724
- const filePath = this.qmdUriToPath(qr.file);
725
- const relativePath = this.vaultPath ? path.relative(this.vaultPath, filePath) : filePath;
726
- const normalizedRelativePath = relativePath.replace(/\\/g, "/");
727
- if (normalizedRelativePath.startsWith("ledger/archive/") || normalizedRelativePath.includes("/ledger/archive/")) {
728
- continue;
729
- }
730
- const docId = normalizedRelativePath.replace(/\.md$/, "");
731
- let doc = this.documents.get(docId) ?? this.documents.get(docId.split("/").join(path.sep));
732
- const modifiedAt = this.resolveModifiedAt(doc, filePath);
733
- const parts = normalizedRelativePath.split("/");
734
- const docCategory = parts.length > 1 ? parts[0] : "root";
735
- if (category && docCategory !== category) continue;
736
- if (tags && tags.length > 0 && doc) {
737
- const docTags = new Set(doc.tags);
738
- if (!tags.some((t) => docTags.has(t))) continue;
739
- }
740
- const normalizedScore = maxScore > 0 ? qr.score / maxScore : 0;
741
- const finalScore = temporalBoost ? normalizedScore * this.getRecencyFactor(modifiedAt) : normalizedScore;
742
- if (finalScore < minScore) continue;
743
- if (!doc) {
744
- doc = {
745
- id: docId,
746
- path: filePath,
747
- category: docCategory,
748
- title: qr.title || path.basename(relativePath, ".md"),
749
- content: "",
750
- // Content loaded separately if needed
751
- frontmatter: {},
752
- links: [],
753
- tags: [],
754
- modified: modifiedAt
755
- };
756
- }
757
- results.push({
758
- document: fullContent ? doc : { ...doc, content: "" },
759
- score: finalScore,
760
- snippet: this.stripSupersededFromSnippet(this.cleanSnippet(qr.snippet)),
761
- matchedTerms: []
762
- // qmd doesn't provide this
763
- });
764
- }
765
- return results.sort((a, b) => b.score - a.score).slice(0, limit);
766
- }
767
- resolveModifiedAt(doc, filePath) {
768
- if (doc) return doc.modified;
769
- try {
770
- return fs.statSync(filePath).mtime;
771
- } catch {
772
- return /* @__PURE__ */ new Date(0);
773
- }
774
- }
775
- getRecencyFactor(modifiedAt) {
776
- const ageMs = Math.max(0, Date.now() - modifiedAt.getTime());
777
- const ageDays = ageMs / (24 * 60 * 60 * 1e3);
778
- if (ageDays < 1) return 1;
779
- if (ageDays <= 7) return 0.9;
780
- return 0.7;
781
- }
782
- /**
783
- * Convert qmd:// URI to file path
784
- */
785
- qmdUriToPath(uri) {
786
- if (uri.startsWith("qmd://")) {
787
- const withoutScheme = uri.slice(6);
788
- const slashIndex = withoutScheme.indexOf("/");
789
- if (slashIndex > -1) {
790
- const relativePath = withoutScheme.slice(slashIndex + 1);
791
- const root = this.collectionRoot || this.vaultPath;
792
- if (root) {
793
- return path.join(root, relativePath);
794
- }
795
- return relativePath;
796
- }
797
- }
798
- return uri;
799
- }
800
- /**
801
- * v2.8 — Filter superseded observation lines from snippet text.
802
- * Ensures search results prefer the latest version of knowledge.
803
- */
804
- stripSupersededFromSnippet(snippet) {
805
- if (!snippet) return snippet;
806
- return snippet.split("\n").filter((line) => !isSuperseded(line)).join("\n");
807
- }
808
- /**
809
- * Clean up qmd snippet format
810
- */
811
- cleanSnippet(snippet) {
812
- if (!snippet) return "";
813
- return snippet.replace(/@@ [-+]?\d+,?\d* @@ \([^)]+\)/g, "").trim().split("\n").slice(0, 3).join("\n").slice(0, 300);
814
- }
815
- /**
816
- * Get all cached documents
817
- */
818
- getAllDocuments() {
819
- return [...this.documents.values()];
820
- }
821
- /**
822
- * Get document count
823
- */
824
- get size() {
825
- return this.documents.size;
826
- }
827
- /**
828
- * Clear the local document cache and all v2.7 indices
829
- */
830
- clear() {
831
- this.documents.clear();
832
- this.dateIndex.clear();
833
- this.preferenceIndex.clear();
834
- this.chunkCache.clear();
835
- }
836
- /**
837
- * Export documents for persistence
838
- */
839
- export() {
840
- return {
841
- documents: [...this.documents.values()]
842
- };
843
- }
844
- /**
845
- * Import from persisted data
846
- */
847
- import(data) {
848
- this.clear();
849
- for (const doc of data.documents) {
850
- this.addDocument(doc);
851
- }
852
- }
853
- };
854
- function extractWikiLinks(content) {
855
- const matches = content.match(/\[\[([^\]]+)\]\]/g) || [];
856
- return matches.map((m) => m.slice(2, -2).toLowerCase());
857
- }
858
- function extractTags(content) {
859
- const matches = content.match(/#[\w-]+/g) || [];
860
- return [...new Set(matches.map((m) => m.slice(1).toLowerCase()))];
861
- }
862
-
863
- // src/lib/memory-graph.ts
864
- var fs2 = __toESM(require("fs"), 1);
865
- var path2 = __toESM(require("path"), 1);
866
- var import_gray_matter = __toESM(require("gray-matter"), 1);
867
- var import_glob = require("glob");
868
- var MEMORY_GRAPH_SCHEMA_VERSION = 1;
869
- var GRAPH_INDEX_RELATIVE_PATH = path2.join(".clawvault", "graph-index.json");
870
- var WIKI_LINK_RE = /\[\[([^\]]+)\]\]/g;
871
- var HASH_TAG_RE = /(^|\s)#([\w-]+)/g;
872
- var FRONTMATTER_RELATION_FIELDS = [
873
- "related",
874
- "depends_on",
875
- "dependsOn",
876
- "blocked_by",
877
- "blocks",
878
- "owner",
879
- "project",
880
- "people",
881
- "links"
882
- ];
883
- function normalizeRelativePath(value) {
884
- return value.split(path2.sep).join("/").replace(/^\.\//, "").replace(/^\/+/, "");
885
- }
886
- function toNoteKey(relativePath) {
887
- const normalized = normalizeRelativePath(relativePath);
888
- return normalized.toLowerCase().endsWith(".md") ? normalized.slice(0, -3) : normalized;
889
- }
890
- function toNoteNodeId(noteKey) {
891
- return `note:${noteKey}`;
892
- }
893
- function toTagNodeId(tag) {
894
- return `tag:${tag.toLowerCase()}`;
895
- }
896
- function normalizeUnresolvedKey(raw) {
897
- const normalized = raw.trim().toLowerCase().replace(/\\/g, "/").replace(/^\.\//, "").replace(/^\/+/, "").replace(/\.md$/, "").replace(/[^a-z0-9/_-]+/g, "-").replace(/\/+/g, "/").replace(/-+/g, "-").replace(/^[-/]+|[-/]+$/g, "");
898
- return normalized || "unknown";
899
- }
900
- function toUnresolvedNodeId(raw) {
901
- return `unresolved:${normalizeUnresolvedKey(raw)}`;
902
- }
903
- function titleFromNoteKey(noteKey) {
904
- const basename3 = noteKey.split("/").pop() ?? noteKey;
905
- return basename3.replace(/[-_]+/g, " ").replace(/\s+/g, " ").trim().replace(/\b\w/g, (char) => char.toUpperCase());
906
- }
907
- function inferNodeType(relativePath, frontmatter) {
908
- const normalized = normalizeRelativePath(relativePath).toLowerCase();
909
- const category = normalized.split("/")[0] ?? "note";
910
- const explicitType = typeof frontmatter.type === "string" ? frontmatter.type.toLowerCase() : "";
911
- if (category.includes("daily") || explicitType === "daily") return "daily";
912
- if (category === "observations" || explicitType === "observation") return "observation";
913
- if (category === "handoffs" || explicitType === "handoff") return "handoff";
914
- if (category === "decisions" || explicitType === "decision") return "decision";
915
- if (category === "lessons" || explicitType === "lesson") return "lesson";
916
- if (category === "projects" || explicitType === "project") return "project";
917
- if (category === "people" || explicitType === "person") return "person";
918
- if (category === "commitments" || explicitType === "commitment") return "commitment";
919
- return "note";
920
- }
921
- function ensureClawvaultDir(vaultPath) {
922
- const dirPath = path2.join(vaultPath, ".clawvault");
923
- if (!fs2.existsSync(dirPath)) {
924
- fs2.mkdirSync(dirPath, { recursive: true });
925
- }
926
- return dirPath;
927
- }
928
- function getGraphIndexPath(vaultPath) {
929
- return path2.join(vaultPath, GRAPH_INDEX_RELATIVE_PATH);
930
- }
931
- function normalizeWikiTarget(target) {
932
- let value = target.trim();
933
- if (!value) return "";
934
- const pipeIndex = value.indexOf("|");
935
- if (pipeIndex >= 0) {
936
- value = value.slice(0, pipeIndex);
937
- }
938
- const hashIndex = value.indexOf("#");
939
- if (hashIndex >= 0) {
940
- value = value.slice(0, hashIndex);
941
- }
942
- value = value.trim().replace(/\\/g, "/").replace(/^\.\//, "").replace(/^\/+/, "");
943
- if (value.toLowerCase().endsWith(".md")) {
944
- value = value.slice(0, -3);
945
- }
946
- return value.trim();
947
- }
948
- function collectTags(frontmatter, markdownContent) {
949
- const tags = /* @__PURE__ */ new Set();
950
- const fmTags = frontmatter.tags;
951
- if (Array.isArray(fmTags)) {
952
- for (const tag of fmTags) {
953
- if (typeof tag === "string" && tag.trim()) tags.add(tag.trim().toLowerCase());
954
- }
955
- } else if (typeof fmTags === "string") {
956
- for (const token of fmTags.split(",")) {
957
- const normalized = token.trim().toLowerCase();
958
- if (normalized) tags.add(normalized);
959
- }
960
- }
961
- const markdownMatches = markdownContent.matchAll(HASH_TAG_RE);
962
- for (const match of markdownMatches) {
963
- const tag = match[2]?.trim().toLowerCase();
964
- if (tag) tags.add(tag);
965
- }
966
- return [...tags].sort((a, b) => a.localeCompare(b));
967
- }
968
- function extractWikiTargets(markdownContent) {
969
- const targets = /* @__PURE__ */ new Set();
970
- for (const match of markdownContent.matchAll(WIKI_LINK_RE)) {
971
- const candidate = match[1];
972
- if (!candidate) continue;
973
- const normalized = normalizeWikiTarget(candidate);
974
- if (normalized) targets.add(normalized);
975
- }
976
- return [...targets];
977
- }
978
- function toStringArray(value) {
979
- if (typeof value === "string") {
980
- return value.split(",").map((entry) => entry.trim()).filter(Boolean);
981
- }
982
- if (Array.isArray(value)) {
983
- return value.flatMap((entry) => typeof entry === "string" ? entry.split(",") : []).map((entry) => entry.trim()).filter(Boolean);
984
- }
985
- return [];
986
- }
987
- function extractFrontmatterRelations(frontmatter) {
988
- const relations = [];
989
- for (const field of FRONTMATTER_RELATION_FIELDS) {
990
- const raw = frontmatter[field];
991
- for (const value of toStringArray(raw)) {
992
- const normalized = normalizeWikiTarget(value);
993
- if (normalized) relations.push({ field, target: normalized });
994
- }
995
- }
996
- return relations;
997
- }
998
- function buildNoteRegistry(relativePaths) {
999
- const byLowerPath = /* @__PURE__ */ new Map();
1000
- const byLowerBasename = /* @__PURE__ */ new Map();
1001
- for (const relativePath of relativePaths) {
1002
- const noteKey = toNoteKey(relativePath);
1003
- const lowerKey = noteKey.toLowerCase();
1004
- if (!byLowerPath.has(lowerKey)) {
1005
- byLowerPath.set(lowerKey, noteKey);
1006
- }
1007
- const base = noteKey.split("/").pop() ?? noteKey;
1008
- const lowerBase = base.toLowerCase();
1009
- const existing = byLowerBasename.get(lowerBase) ?? [];
1010
- existing.push(noteKey);
1011
- byLowerBasename.set(lowerBase, existing);
1012
- }
1013
- return { byLowerPath, byLowerBasename };
1014
- }
1015
- function resolveTargetNodeId(rawTarget, registry) {
1016
- const normalized = normalizeWikiTarget(rawTarget);
1017
- if (!normalized) {
1018
- return toUnresolvedNodeId(rawTarget);
1019
- }
1020
- const lowerTarget = normalized.toLowerCase();
1021
- const direct = registry.byLowerPath.get(lowerTarget);
1022
- if (direct) {
1023
- return toNoteNodeId(direct);
1024
- }
1025
- if (!normalized.includes("/")) {
1026
- const basenameMatches = registry.byLowerBasename.get(lowerTarget) ?? [];
1027
- if (basenameMatches.length === 1) {
1028
- return toNoteNodeId(basenameMatches[0]);
1029
- }
1030
- }
1031
- return toUnresolvedNodeId(normalized);
1032
- }
1033
- function createEdgeId(type, source, target, label) {
1034
- const suffix = label ? `:${label}` : "";
1035
- return `${type}:${source}->${target}${suffix}`;
1036
- }
1037
- function buildFragmentNode(id, title, type, category, pathValue, tags, missing, modifiedAt) {
1038
- return {
1039
- id,
1040
- title,
1041
- type,
1042
- category,
1043
- path: pathValue,
1044
- tags,
1045
- missing,
1046
- degree: 0,
1047
- modifiedAt
1048
- };
1049
- }
1050
- function parseFileFragment(vaultPath, relativePath, mtimeMs, registry) {
1051
- const absolutePath = path2.join(vaultPath, relativePath);
1052
- const raw = fs2.readFileSync(absolutePath, "utf-8");
1053
- const parsed = (0, import_gray_matter.default)(raw);
1054
- const frontmatter = parsed.data ?? {};
1055
- const noteKey = toNoteKey(relativePath);
1056
- const noteNodeId = toNoteNodeId(noteKey);
1057
- const noteType = inferNodeType(relativePath, frontmatter);
1058
- const tags = collectTags(frontmatter, parsed.content);
1059
- const modifiedAt = new Date(mtimeMs).toISOString();
1060
- const nodes = /* @__PURE__ */ new Map();
1061
- const edges = /* @__PURE__ */ new Map();
1062
- nodes.set(
1063
- noteNodeId,
1064
- buildFragmentNode(
1065
- noteNodeId,
1066
- typeof frontmatter.title === "string" && frontmatter.title.trim() ? frontmatter.title.trim() : titleFromNoteKey(noteKey),
1067
- noteType,
1068
- noteType,
1069
- normalizeRelativePath(relativePath),
1070
- tags,
1071
- false,
1072
- modifiedAt
1073
- )
1074
- );
1075
- for (const tag of tags) {
1076
- const tagNodeId = toTagNodeId(tag);
1077
- if (!nodes.has(tagNodeId)) {
1078
- nodes.set(tagNodeId, buildFragmentNode(tagNodeId, `#${tag}`, "tag", "tag", null, [], false, null));
1079
- }
1080
- const edgeId = createEdgeId("tag", noteNodeId, tagNodeId);
1081
- edges.set(edgeId, {
1082
- id: edgeId,
1083
- source: noteNodeId,
1084
- target: tagNodeId,
1085
- type: "tag"
1086
- });
1087
- }
1088
- const wikiTargets = extractWikiTargets(parsed.content);
1089
- for (const target of wikiTargets) {
1090
- const targetNodeId = resolveTargetNodeId(target, registry);
1091
- if (targetNodeId.startsWith("unresolved:") && !nodes.has(targetNodeId)) {
1092
- nodes.set(
1093
- targetNodeId,
1094
- buildFragmentNode(targetNodeId, titleFromNoteKey(normalizeUnresolvedKey(target)), "unresolved", "unresolved", null, [], true, null)
1095
- );
1096
- }
1097
- const edgeId = createEdgeId("wiki_link", noteNodeId, targetNodeId);
1098
- edges.set(edgeId, {
1099
- id: edgeId,
1100
- source: noteNodeId,
1101
- target: targetNodeId,
1102
- type: "wiki_link"
1103
- });
1104
- }
1105
- for (const relation of extractFrontmatterRelations(frontmatter)) {
1106
- const targetNodeId = resolveTargetNodeId(relation.target, registry);
1107
- if (targetNodeId.startsWith("unresolved:") && !nodes.has(targetNodeId)) {
1108
- nodes.set(
1109
- targetNodeId,
1110
- buildFragmentNode(
1111
- targetNodeId,
1112
- titleFromNoteKey(normalizeUnresolvedKey(relation.target)),
1113
- "unresolved",
1114
- "unresolved",
1115
- null,
1116
- [],
1117
- true,
1118
- null
1119
- )
1120
- );
1121
- }
1122
- const edgeId = createEdgeId("frontmatter_relation", noteNodeId, targetNodeId, relation.field);
1123
- edges.set(edgeId, {
1124
- id: edgeId,
1125
- source: noteNodeId,
1126
- target: targetNodeId,
1127
- type: "frontmatter_relation",
1128
- label: relation.field
1129
- });
1130
- }
1131
- return {
1132
- relativePath: normalizeRelativePath(relativePath),
1133
- mtimeMs,
1134
- nodes: [...nodes.values()],
1135
- edges: [...edges.values()]
1136
- };
1137
- }
1138
- function combineFragments(fragments, generatedAt) {
1139
- const nodes = /* @__PURE__ */ new Map();
1140
- const edges = /* @__PURE__ */ new Map();
1141
- for (const fragment of Object.values(fragments)) {
1142
- for (const node of fragment.nodes) {
1143
- const existing = nodes.get(node.id);
1144
- if (!existing) {
1145
- nodes.set(node.id, { ...node, degree: 0 });
1146
- } else if (node.modifiedAt && (!existing.modifiedAt || node.modifiedAt > existing.modifiedAt)) {
1147
- nodes.set(node.id, { ...existing, ...node, degree: 0 });
1148
- }
1149
- }
1150
- for (const edge of fragment.edges) {
1151
- edges.set(edge.id, edge);
1152
- }
1153
- }
1154
- const degreeByNode = /* @__PURE__ */ new Map();
1155
- for (const edge of edges.values()) {
1156
- degreeByNode.set(edge.source, (degreeByNode.get(edge.source) ?? 0) + 1);
1157
- degreeByNode.set(edge.target, (degreeByNode.get(edge.target) ?? 0) + 1);
1158
- }
1159
- for (const node of nodes.values()) {
1160
- node.degree = degreeByNode.get(node.id) ?? 0;
1161
- }
1162
- const nodeTypeCounts = {};
1163
- for (const node of nodes.values()) {
1164
- nodeTypeCounts[node.type] = (nodeTypeCounts[node.type] ?? 0) + 1;
1165
- }
1166
- const edgeTypeCounts = {};
1167
- for (const edge of edges.values()) {
1168
- edgeTypeCounts[edge.type] = (edgeTypeCounts[edge.type] ?? 0) + 1;
1169
- }
1170
- const sortedNodes = [...nodes.values()].sort((a, b) => a.id.localeCompare(b.id));
1171
- const sortedEdges = [...edges.values()].sort((a, b) => a.id.localeCompare(b.id));
1172
- return {
1173
- schemaVersion: MEMORY_GRAPH_SCHEMA_VERSION,
1174
- nodes: sortedNodes,
1175
- edges: sortedEdges,
1176
- stats: {
1177
- generatedAt,
1178
- nodeCount: sortedNodes.length,
1179
- edgeCount: sortedEdges.length,
1180
- nodeTypeCounts,
1181
- edgeTypeCounts
1182
- }
1183
- };
1184
- }
1185
- function isValidIndex(index) {
1186
- if (!index || typeof index !== "object") return false;
1187
- const typed = index;
1188
- return typed.schemaVersion === MEMORY_GRAPH_SCHEMA_VERSION && typeof typed.vaultPath === "string" && typeof typed.generatedAt === "string" && Boolean(typed.files && typeof typed.files === "object") && Boolean(typed.graph && typeof typed.graph === "object");
1189
- }
1190
- function loadMemoryGraphIndex(vaultPath) {
1191
- const indexPath = getGraphIndexPath(path2.resolve(vaultPath));
1192
- if (!fs2.existsSync(indexPath)) {
1193
- return null;
1194
- }
1195
- try {
1196
- const parsed = JSON.parse(fs2.readFileSync(indexPath, "utf-8"));
1197
- if (!isValidIndex(parsed)) {
1198
- return null;
1199
- }
1200
- return parsed;
1201
- } catch {
1202
- return null;
1203
- }
1204
- }
1205
- async function buildOrUpdateMemoryGraphIndex(vaultPathInput, options = {}) {
1206
- const vaultPath = path2.resolve(vaultPathInput);
1207
- ensureClawvaultDir(vaultPath);
1208
- const existing = options.forceFull ? null : loadMemoryGraphIndex(vaultPath);
1209
- const markdownFiles = await (0, import_glob.glob)("**/*.md", {
1210
- cwd: vaultPath,
1211
- ignore: ["**/node_modules/**", "**/.git/**", "**/.obsidian/**", "**/.trash/**", "**/ledger/archive/**"]
1212
- });
1213
- const normalizedFiles = markdownFiles.map(normalizeRelativePath).sort((a, b) => a.localeCompare(b));
1214
- const registry = buildNoteRegistry(normalizedFiles);
1215
- const nextFragments = {};
1216
- const existingFragments = existing?.files ?? {};
1217
- const currentFileSet = new Set(normalizedFiles);
1218
- for (const relativePath of normalizedFiles) {
1219
- const absolutePath = path2.join(vaultPath, relativePath);
1220
- const stat = fs2.statSync(absolutePath);
1221
- const existingFragment = existingFragments[relativePath];
1222
- if (!options.forceFull && existingFragment && existingFragment.mtimeMs === stat.mtimeMs) {
1223
- nextFragments[relativePath] = existingFragment;
1224
- continue;
1225
- }
1226
- nextFragments[relativePath] = parseFileFragment(vaultPath, relativePath, stat.mtimeMs, registry);
1227
- }
1228
- for (const [relativePath, fragment] of Object.entries(existingFragments)) {
1229
- if (!currentFileSet.has(relativePath)) {
1230
- continue;
1231
- }
1232
- if (!nextFragments[relativePath]) {
1233
- nextFragments[relativePath] = fragment;
1234
- }
1235
- }
1236
- const generatedAt = (/* @__PURE__ */ new Date()).toISOString();
1237
- const graph = combineFragments(nextFragments, generatedAt);
1238
- const nextIndex = {
1239
- schemaVersion: MEMORY_GRAPH_SCHEMA_VERSION,
1240
- vaultPath,
1241
- generatedAt,
1242
- files: nextFragments,
1243
- graph
1244
- };
1245
- fs2.writeFileSync(getGraphIndexPath(vaultPath), JSON.stringify(nextIndex, null, 2));
1246
- return nextIndex;
1247
- }
1248
-
1249
- // src/lib/vault.ts
1250
- var import_meta = {};
1251
- var CONFIG_FILE = ".clawvault.json";
1252
- var INDEX_FILE = ".clawvault-index.json";
1253
- var ClawVault = class {
1254
- config;
1255
- search;
1256
- initialized = false;
1257
- constructor(vaultPath) {
1258
- if (!hasQmd()) {
1259
- throw new QmdUnavailableError();
1260
- }
1261
- this.config = {
1262
- path: path3.resolve(vaultPath),
1263
- name: path3.basename(vaultPath),
1264
- categories: DEFAULT_CATEGORIES,
1265
- qmdCollection: void 0,
1266
- qmdRoot: void 0
1267
- };
1268
- this.search = new SearchEngine();
1269
- this.applyQmdConfig();
1270
- }
1271
- /**
1272
- * Initialize a new vault
1273
- */
1274
- async init(options = {}, initFlags) {
1275
- if (!hasQmd()) {
1276
- throw new QmdUnavailableError();
1277
- }
1278
- const vaultPath = this.config.path;
1279
- const flags = initFlags || {};
1280
- this.config = { ...this.config, ...options };
1281
- this.applyQmdConfig();
1282
- if (flags.skipTasks) {
1283
- this.config.categories = this.config.categories.filter(
1284
- (c) => !["tasks", "backlog"].includes(c)
1285
- );
1286
- }
1287
- if (!fs3.existsSync(vaultPath)) {
1288
- fs3.mkdirSync(vaultPath, { recursive: true });
1289
- }
1290
- for (const category of this.config.categories) {
1291
- const catPath = path3.join(vaultPath, category);
1292
- if (!fs3.existsSync(catPath)) {
1293
- fs3.mkdirSync(catPath, { recursive: true });
1294
- }
1295
- }
1296
- const ledgerDirs = ["ledger/raw", "ledger/observations", "ledger/reflections"];
1297
- for (const dir of ledgerDirs) {
1298
- const dirPath = path3.join(vaultPath, dir);
1299
- if (!fs3.existsSync(dirPath)) {
1300
- fs3.mkdirSync(dirPath, { recursive: true });
1301
- }
1302
- }
1303
- await this.createTemplates();
1304
- const readmePath = path3.join(vaultPath, "README.md");
1305
- if (!fs3.existsSync(readmePath)) {
1306
- fs3.writeFileSync(readmePath, this.generateReadme());
1307
- }
1308
- await this.createWelcomeNote();
1309
- const configPath = path3.join(vaultPath, CONFIG_FILE);
1310
- const meta = {
1311
- name: this.config.name,
1312
- version: "1.0.0",
1313
- created: (/* @__PURE__ */ new Date()).toISOString(),
1314
- lastUpdated: (/* @__PURE__ */ new Date()).toISOString(),
1315
- categories: this.config.categories,
1316
- documentCount: 0,
1317
- qmdCollection: this.getQmdCollection(),
1318
- qmdRoot: this.getQmdRoot()
1319
- };
1320
- fs3.writeFileSync(configPath, JSON.stringify(meta, null, 2));
1321
- if (!flags.skipBases && this.config.categories.includes("tasks")) {
1322
- this.createBasesFiles();
1323
- }
1324
- if (!flags.skipGraph) {
1325
- await this.syncMemoryGraphIndex({ forceFull: true });
1326
- }
1327
- this.initialized = true;
1328
- }
1329
- createBasesFiles() {
1330
- const vaultPath = this.config.path;
1331
- const basesFiles = {
1332
- "all-tasks.base": [
1333
- "filters:",
1334
- " and:",
1335
- ' - file.inFolder("tasks")',
1336
- ' - status != "done"',
1337
- "formulas:",
1338
- " age: (now() - file.ctime).days",
1339
- ' status_icon: if(status == "blocked", "\u{1F534}", if(status == "in-progress", "\u{1F528}", if(status == "open", "\u26AA", "\u2705")))',
1340
- "views:",
1341
- " - type: table",
1342
- " name: All Active Tasks",
1343
- " groupBy:",
1344
- " property: status",
1345
- " direction: ASC",
1346
- " order:",
1347
- " - formula.status_icon",
1348
- " - file.name",
1349
- " - status",
1350
- " - owner",
1351
- " - project",
1352
- " - priority",
1353
- " - blocked_by",
1354
- " - formula.age",
1355
- " - type: cards",
1356
- " name: Task Board",
1357
- " groupBy:",
1358
- " property: status",
1359
- " direction: ASC",
1360
- " order:",
1361
- " - file.name",
1362
- " - owner",
1363
- " - project",
1364
- " - priority"
1365
- ].join("\n"),
1366
- "blocked.base": [
1367
- "filters:",
1368
- " and:",
1369
- ' - file.inFolder("tasks")',
1370
- ' - status == "blocked"',
1371
- "formulas:",
1372
- " days_blocked: (now() - file.ctime).days",
1373
- "views:",
1374
- " - type: table",
1375
- " name: Blocked Tasks",
1376
- " order:",
1377
- " - file.name",
1378
- " - owner",
1379
- " - project",
1380
- " - blocked_by",
1381
- " - formula.days_blocked",
1382
- " - priority"
1383
- ].join("\n"),
1384
- "by-project.base": [
1385
- "filters:",
1386
- " and:",
1387
- ' - file.inFolder("tasks")',
1388
- ' - status != "done"',
1389
- "formulas:",
1390
- ' status_icon: if(status == "blocked", "\u{1F534}", if(status == "in-progress", "\u{1F528}", "\u26AA"))',
1391
- "views:",
1392
- " - type: table",
1393
- " name: By Project",
1394
- " groupBy:",
1395
- " property: project",
1396
- " direction: ASC",
1397
- " order:",
1398
- " - formula.status_icon",
1399
- " - file.name",
1400
- " - status",
1401
- " - owner",
1402
- " - priority"
1403
- ].join("\n"),
1404
- "backlog.base": [
1405
- "filters:",
1406
- " and:",
1407
- ' - file.inFolder("backlog")',
1408
- "views:",
1409
- " - type: table",
1410
- " name: Backlog",
1411
- " order:",
1412
- " - file.name",
1413
- " - source",
1414
- " - project",
1415
- " - file.ctime"
1416
- ].join("\n")
1417
- };
1418
- for (const [filename, content] of Object.entries(basesFiles)) {
1419
- const filePath = path3.join(vaultPath, filename);
1420
- if (!fs3.existsSync(filePath)) {
1421
- fs3.writeFileSync(filePath, content);
1422
- }
1423
- }
1424
- }
1425
- /**
1426
- * Load an existing vault
1427
- */
1428
- async load() {
1429
- if (!hasQmd()) {
1430
- throw new QmdUnavailableError();
1431
- }
1432
- const vaultPath = this.config.path;
1433
- const configPath = path3.join(vaultPath, CONFIG_FILE);
1434
- if (!fs3.existsSync(configPath)) {
1435
- throw new Error(`Not a ClawVault: ${vaultPath} (missing ${CONFIG_FILE})`);
1436
- }
1437
- const meta = JSON.parse(fs3.readFileSync(configPath, "utf-8"));
1438
- this.config.name = meta.name;
1439
- this.config.categories = meta.categories;
1440
- this.config.qmdCollection = meta.qmdCollection;
1441
- this.config.qmdRoot = meta.qmdRoot;
1442
- if (!meta.qmdCollection || !meta.qmdRoot) {
1443
- meta.qmdCollection = meta.qmdCollection || meta.name;
1444
- meta.qmdRoot = meta.qmdRoot || this.config.path;
1445
- fs3.writeFileSync(configPath, JSON.stringify(meta, null, 2));
1446
- }
1447
- this.applyQmdConfig(meta);
1448
- await this.reindex();
1449
- this.initialized = true;
1450
- }
1451
- /**
1452
- * Reindex all documents
1453
- */
1454
- async reindex() {
1455
- this.search.clear();
1456
- const files = await (0, import_glob2.glob)("**/*.md", {
1457
- cwd: this.config.path,
1458
- ignore: ["**/node_modules/**", "**/.*", "**/ledger/archive/**"]
1459
- });
1460
- for (const file of files) {
1461
- const doc = await this.loadDocument(file);
1462
- if (doc) {
1463
- this.search.addDocument(doc);
1464
- }
1465
- }
1466
- await this.saveIndex();
1467
- await this.syncMemoryGraphIndex();
1468
- return this.search.size;
1469
- }
1470
- /**
1471
- * Load a document from disk
1472
- */
1473
- async loadDocument(relativePath) {
1474
- try {
1475
- const fullPath = path3.join(this.config.path, relativePath);
1476
- const content = fs3.readFileSync(fullPath, "utf-8");
1477
- const { data: frontmatter, content: body } = (0, import_gray_matter2.default)(content);
1478
- const stats = fs3.statSync(fullPath);
1479
- const parts = relativePath.split(path3.sep);
1480
- const category = parts.length > 1 ? parts[0] : "root";
1481
- const filename = path3.basename(relativePath, ".md");
1482
- return {
1483
- id: relativePath.replace(/\.md$/, ""),
1484
- path: fullPath,
1485
- category,
1486
- title: frontmatter.title || filename,
1487
- content: body,
1488
- frontmatter,
1489
- links: extractWikiLinks(body),
1490
- tags: extractTags(body),
1491
- modified: stats.mtime
1492
- };
1493
- } catch (err) {
1494
- console.error(`Error loading ${relativePath}:`, err);
1495
- return null;
1496
- }
1497
- }
1498
- /**
1499
- * Store a new document
1500
- */
1501
- async store(options) {
1502
- const {
1503
- category,
1504
- title,
1505
- content,
1506
- frontmatter = {},
1507
- overwrite = false,
1508
- qmdUpdate: triggerUpdate = false,
1509
- qmdEmbed: triggerEmbed = false,
1510
- qmdIndexName
1511
- } = options;
1512
- const filename = this.slugify(title) + ".md";
1513
- const relativePath = path3.join(category, filename);
1514
- const fullPath = path3.join(this.config.path, relativePath);
1515
- if (fs3.existsSync(fullPath) && !overwrite) {
1516
- throw new Error(`Document already exists: ${relativePath}. Use overwrite: true to replace.`);
1517
- }
1518
- const categoryPath = path3.join(this.config.path, category);
1519
- if (!fs3.existsSync(categoryPath)) {
1520
- fs3.mkdirSync(categoryPath, { recursive: true });
1521
- }
1522
- const fm = {
1523
- title,
1524
- date: (/* @__PURE__ */ new Date()).toISOString().split("T")[0],
1525
- ...frontmatter
1526
- };
1527
- const fileContent = import_gray_matter2.default.stringify(content, fm);
1528
- fs3.writeFileSync(fullPath, fileContent);
1529
- const doc = await this.loadDocument(relativePath);
1530
- if (doc) {
1531
- this.search.addDocument(doc);
1532
- await this.saveIndex();
1533
- await this.syncMemoryGraphIndex();
1534
- }
1535
- if (triggerUpdate || triggerEmbed) {
1536
- qmdUpdate(this.getQmdCollection(), qmdIndexName);
1537
- if (triggerEmbed) {
1538
- qmdEmbed(this.getQmdCollection(), qmdIndexName);
1539
- }
1540
- }
1541
- return doc;
1542
- }
1543
- /**
1544
- * Quick store to inbox
1545
- */
1546
- async capture(note, title) {
1547
- const autoTitle = title || `note-${Date.now()}`;
1548
- return this.store({
1549
- category: "inbox",
1550
- title: autoTitle,
1551
- content: note
1552
- });
1553
- }
1554
- /**
1555
- * Search the vault (BM25 via qmd)
1556
- */
1557
- async find(query, options = {}) {
1558
- return this.search.search(query, options);
1559
- }
1560
- /**
1561
- * Semantic/vector search (via qmd vsearch)
1562
- */
1563
- async vsearch(query, options = {}) {
1564
- return this.search.vsearch(query, options);
1565
- }
1566
- /**
1567
- * Combined search with query expansion (via qmd query)
1568
- */
1569
- async query(query, options = {}) {
1570
- return this.search.query(query, options);
1571
- }
1572
- /**
1573
- * Get a document by ID or path
1574
- */
1575
- async get(idOrPath) {
1576
- const normalized = idOrPath.replace(/\.md$/, "");
1577
- const docs = this.search.getAllDocuments();
1578
- return docs.find((d) => d.id === normalized) || null;
1579
- }
1580
- /**
1581
- * List documents in a category
1582
- */
1583
- async list(category) {
1584
- const docs = this.search.getAllDocuments();
1585
- if (category) {
1586
- return docs.filter((d) => d.category === category);
1587
- }
1588
- return docs;
1589
- }
1590
- /**
1591
- * Sync vault to another location (for Obsidian on Windows, etc.)
1592
- */
1593
- async sync(options) {
1594
- const { target, deleteOrphans = false, dryRun = false } = options;
1595
- const result = {
1596
- copied: [],
1597
- deleted: [],
1598
- unchanged: [],
1599
- errors: []
1600
- };
1601
- const sourceFiles = await (0, import_glob2.glob)("**/*.md", {
1602
- cwd: this.config.path,
1603
- ignore: ["**/node_modules/**"]
1604
- });
1605
- if (!dryRun && !fs3.existsSync(target)) {
1606
- fs3.mkdirSync(target, { recursive: true });
1607
- }
1608
- for (const file of sourceFiles) {
1609
- const sourcePath = path3.join(this.config.path, file);
1610
- const targetPath = path3.join(target, file);
1611
- try {
1612
- const sourceStats = fs3.statSync(sourcePath);
1613
- let shouldCopy = true;
1614
- if (fs3.existsSync(targetPath)) {
1615
- const targetStats = fs3.statSync(targetPath);
1616
- if (sourceStats.mtime <= targetStats.mtime) {
1617
- result.unchanged.push(file);
1618
- shouldCopy = false;
1619
- }
1620
- }
1621
- if (shouldCopy) {
1622
- if (!dryRun) {
1623
- const targetDir = path3.dirname(targetPath);
1624
- if (!fs3.existsSync(targetDir)) {
1625
- fs3.mkdirSync(targetDir, { recursive: true });
1626
- }
1627
- fs3.copyFileSync(sourcePath, targetPath);
1628
- }
1629
- result.copied.push(file);
1630
- }
1631
- } catch (err) {
1632
- result.errors.push(`${file}: ${err}`);
1633
- }
1634
- }
1635
- if (deleteOrphans) {
1636
- const targetFiles = await (0, import_glob2.glob)("**/*.md", { cwd: target });
1637
- const sourceSet = new Set(sourceFiles);
1638
- for (const file of targetFiles) {
1639
- if (!sourceSet.has(file)) {
1640
- if (!dryRun) {
1641
- fs3.unlinkSync(path3.join(target, file));
1642
- }
1643
- result.deleted.push(file);
1644
- }
1645
- }
1646
- }
1647
- return result;
1648
- }
1649
- /**
1650
- * Get vault statistics
1651
- */
1652
- async stats() {
1653
- const docs = this.search.getAllDocuments();
1654
- const categories = {};
1655
- const allTags = /* @__PURE__ */ new Set();
1656
- let totalLinks = 0;
1657
- for (const doc of docs) {
1658
- categories[doc.category] = (categories[doc.category] || 0) + 1;
1659
- totalLinks += doc.links.length;
1660
- doc.tags.forEach((t) => allTags.add(t));
1661
- }
1662
- return {
1663
- documents: docs.length,
1664
- categories,
1665
- links: totalLinks,
1666
- tags: [...allTags].sort()
1667
- };
1668
- }
1669
- /**
1670
- * Get all categories
1671
- */
1672
- getCategories() {
1673
- return this.config.categories;
1674
- }
1675
- /**
1676
- * Check if vault is initialized
1677
- */
1678
- isInitialized() {
1679
- return this.initialized;
1680
- }
1681
- /**
1682
- * Get vault path
1683
- */
1684
- getPath() {
1685
- return this.config.path;
1686
- }
1687
- /**
1688
- * Get vault name
1689
- */
1690
- getName() {
1691
- return this.config.name;
1692
- }
1693
- /**
1694
- * Get qmd collection name
1695
- */
1696
- getQmdCollection() {
1697
- return this.config.qmdCollection || this.config.name;
1698
- }
1699
- /**
1700
- * Get qmd collection root
1701
- */
1702
- getQmdRoot() {
1703
- return this.config.qmdRoot || this.config.path;
1704
- }
1705
- // === Memory Type System ===
1706
- /**
1707
- * Store a memory with type classification
1708
- * Automatically routes to correct category based on type
1709
- */
1710
- async remember(type, title, content, frontmatter = {}) {
1711
- const category = TYPE_TO_CATEGORY[type];
1712
- return this.store({
1713
- category,
1714
- title,
1715
- content,
1716
- frontmatter: { ...frontmatter, memoryType: type }
1717
- });
1718
- }
1719
- // === Handoff System ===
1720
- /**
1721
- * Create a session handoff document
1722
- * Call this before context death or long pauses
1723
- */
1724
- async createHandoff(handoff) {
1725
- const now = /* @__PURE__ */ new Date();
1726
- const dateStr = now.toISOString().split("T")[0];
1727
- const timeStr = now.toISOString().split("T")[1].slice(0, 5).replace(":", "");
1728
- const fullHandoff = {
1729
- ...handoff,
1730
- created: now.toISOString()
1731
- };
1732
- const content = this.formatHandoff(fullHandoff);
1733
- const frontmatter = {
1734
- type: "handoff",
1735
- workingOn: handoff.workingOn,
1736
- blocked: handoff.blocked,
1737
- nextSteps: handoff.nextSteps
1738
- };
1739
- if (handoff.sessionKey) frontmatter.sessionKey = handoff.sessionKey;
1740
- if (handoff.feeling) frontmatter.feeling = handoff.feeling;
1741
- if (handoff.decisions) frontmatter.decisions = handoff.decisions;
1742
- if (handoff.openQuestions) frontmatter.openQuestions = handoff.openQuestions;
1743
- return this.store({
1744
- category: "handoffs",
1745
- title: `handoff-${dateStr}-${timeStr}`,
1746
- content,
1747
- frontmatter
1748
- });
1749
- }
1750
- /**
1751
- * Format handoff as readable markdown
1752
- */
1753
- formatHandoff(h) {
1754
- let md = `# Session Handoff
1755
-
1756
- `;
1757
- md += `**Created:** ${h.created}
1758
- `;
1759
- if (h.sessionKey) md += `**Session:** ${h.sessionKey}
1760
- `;
1761
- if (h.feeling) md += `**Feeling:** ${h.feeling}
1762
- `;
1763
- md += `
1764
- `;
1765
- md += `## Working On
1766
- `;
1767
- h.workingOn.forEach((w) => md += `- ${w}
1768
- `);
1769
- md += `
1770
- `;
1771
- md += `## Blocked
1772
- `;
1773
- if (h.blocked.length === 0) md += `- Nothing currently blocked
1774
- `;
1775
- else h.blocked.forEach((b) => md += `- ${b}
1776
- `);
1777
- md += `
1778
- `;
1779
- md += `## Next Steps
1780
- `;
1781
- h.nextSteps.forEach((n) => md += `- ${n}
1782
- `);
1783
- if (h.decisions && h.decisions.length > 0) {
1784
- md += `
1785
- ## Decisions Made
1786
- `;
1787
- h.decisions.forEach((d) => md += `- ${d}
1788
- `);
1789
- }
1790
- if (h.openQuestions && h.openQuestions.length > 0) {
1791
- md += `
1792
- ## Open Questions
1793
- `;
1794
- h.openQuestions.forEach((q) => md += `- ${q}
1795
- `);
1796
- }
1797
- return md;
1798
- }
1799
- // === Session Recap (Bootstrap Hook) ===
1800
- /**
1801
- * Generate a session recap - who I was
1802
- * Call this on bootstrap to restore context
1803
- */
1804
- async generateRecap(options = {}) {
1805
- const { handoffLimit = 3, brief = false } = options;
1806
- const handoffDocs = await this.list("handoffs");
1807
- const recentHandoffs = handoffDocs.sort((a, b) => b.modified.getTime() - a.modified.getTime()).slice(0, handoffLimit).map((doc) => this.parseHandoff(doc));
1808
- const projectDocs = await this.list("projects");
1809
- const activeProjects = projectDocs.filter((d) => d.frontmatter.status !== "completed" && d.frontmatter.status !== "archived").map((d) => d.title);
1810
- const commitmentDocs = await this.list("commitments");
1811
- const pendingCommitments = commitmentDocs.filter((d) => d.frontmatter.status !== "done").map((d) => d.title);
1812
- const decisionDocs = await this.list("decisions");
1813
- const recentDecisions = decisionDocs.sort((a, b) => b.modified.getTime() - a.modified.getTime()).slice(0, brief ? 3 : 5).map((d) => d.title);
1814
- const lessonDocs = await this.list("lessons");
1815
- const recentLessons = lessonDocs.sort((a, b) => b.modified.getTime() - a.modified.getTime()).slice(0, brief ? 3 : 5).map((d) => d.title);
1816
- let keyRelationships = [];
1817
- if (!brief) {
1818
- const peopleDocs = await this.list("people");
1819
- keyRelationships = peopleDocs.filter((d) => d.frontmatter.importance === "high" || d.frontmatter.role).map((d) => `${d.title}${d.frontmatter.role ? ` (${d.frontmatter.role})` : ""}`);
1820
- }
1821
- const feelings = recentHandoffs.map((h) => h.feeling).filter(Boolean);
1822
- const emotionalArc = feelings.length > 0 ? feelings.join(" \u2192 ") : void 0;
1823
- return {
1824
- generated: (/* @__PURE__ */ new Date()).toISOString(),
1825
- recentHandoffs,
1826
- activeProjects,
1827
- pendingCommitments,
1828
- recentDecisions,
1829
- recentLessons,
1830
- keyRelationships,
1831
- emotionalArc
1832
- };
1833
- }
1834
- /**
1835
- * Format recap as readable markdown for injection
1836
- */
1837
- formatRecap(recap, options = {}) {
1838
- const { brief = false } = options;
1839
- let md = `# Who I Was
1840
-
1841
- `;
1842
- md += `*Generated: ${recap.generated}*
1843
-
1844
- `;
1845
- if (recap.emotionalArc) {
1846
- md += `**Emotional arc:** ${recap.emotionalArc}
1847
-
1848
- `;
1849
- }
1850
- if (recap.recentHandoffs.length > 0) {
1851
- md += `## Recent Sessions
1852
- `;
1853
- for (const h of recap.recentHandoffs) {
1854
- if (brief) {
1855
- md += `- **${h.created.split("T")[0]}:** ${h.workingOn.slice(0, 2).join(", ")}`;
1856
- if (h.nextSteps.length > 0) md += ` \u2192 ${h.nextSteps[0]}`;
1857
- md += `
1858
- `;
1859
- } else {
1860
- md += `
1861
- ### ${h.created.split("T")[0]}
1862
- `;
1863
- md += `**Working on:** ${h.workingOn.join(", ")}
1864
- `;
1865
- if (h.blocked.length > 0) md += `**Blocked:** ${h.blocked.join(", ")}
1866
- `;
1867
- md += `**Next:** ${h.nextSteps.join(", ")}
1868
- `;
1869
- }
1870
- }
1871
- md += `
1872
- `;
1873
- }
1874
- if (recap.activeProjects.length > 0) {
1875
- md += `## Active Projects
1876
- `;
1877
- recap.activeProjects.forEach((p) => md += `- ${p}
1878
- `);
1879
- md += `
1880
- `;
1881
- }
1882
- if (recap.pendingCommitments.length > 0) {
1883
- md += `## Pending Commitments
1884
- `;
1885
- recap.pendingCommitments.forEach((c) => md += `- ${c}
1886
- `);
1887
- md += `
1888
- `;
1889
- }
1890
- if (recap.recentDecisions && recap.recentDecisions.length > 0) {
1891
- md += `## Recent Decisions
1892
- `;
1893
- recap.recentDecisions.forEach((d) => md += `- ${d}
1894
- `);
1895
- md += `
1896
- `;
1897
- }
1898
- if (recap.recentLessons.length > 0) {
1899
- md += `## Recent Lessons
1900
- `;
1901
- recap.recentLessons.forEach((l) => md += `- ${l}
1902
- `);
1903
- md += `
1904
- `;
1905
- }
1906
- if (!brief && recap.keyRelationships.length > 0) {
1907
- md += `## Key People
1908
- `;
1909
- recap.keyRelationships.forEach((r) => md += `- ${r}
1910
- `);
1911
- }
1912
- return md;
1913
- }
1914
- /**
1915
- * Parse a handoff document back into structured form
1916
- */
1917
- parseHandoff(doc) {
1918
- return {
1919
- created: doc.frontmatter.date || doc.modified.toISOString(),
1920
- sessionKey: doc.frontmatter.sessionKey,
1921
- workingOn: doc.frontmatter.workingOn || [],
1922
- blocked: doc.frontmatter.blocked || [],
1923
- nextSteps: doc.frontmatter.nextSteps || [],
1924
- decisions: doc.frontmatter.decisions,
1925
- openQuestions: doc.frontmatter.openQuestions,
1926
- feeling: doc.frontmatter.feeling
1927
- };
1928
- }
1929
- // === Private helpers ===
1930
- applyQmdConfig(meta) {
1931
- const collection = meta?.qmdCollection || this.config.qmdCollection || this.config.name;
1932
- const root = meta?.qmdRoot || this.config.qmdRoot || this.config.path;
1933
- this.config.qmdCollection = collection;
1934
- this.config.qmdRoot = root;
1935
- this.search.setVaultPath(this.config.path);
1936
- this.search.setCollection(collection);
1937
- this.search.setCollectionRoot(root);
1938
- }
1939
- slugify(text) {
1940
- return text.toLowerCase().replace(/[^\w\s-]/g, "").replace(/\s+/g, "-").replace(/-+/g, "-").trim();
1941
- }
1942
- async saveIndex() {
1943
- const indexPath = path3.join(this.config.path, INDEX_FILE);
1944
- const data = this.search.export();
1945
- fs3.writeFileSync(indexPath, JSON.stringify(data, null, 2));
1946
- const configPath = path3.join(this.config.path, CONFIG_FILE);
1947
- if (fs3.existsSync(configPath)) {
1948
- const meta = JSON.parse(fs3.readFileSync(configPath, "utf-8"));
1949
- meta.lastUpdated = (/* @__PURE__ */ new Date()).toISOString();
1950
- meta.documentCount = this.search.size;
1951
- fs3.writeFileSync(configPath, JSON.stringify(meta, null, 2));
1952
- }
1953
- }
1954
- async createTemplates() {
1955
- const templatesPath = path3.join(this.config.path, "templates");
1956
- if (!fs3.existsSync(templatesPath)) {
1957
- fs3.mkdirSync(templatesPath, { recursive: true });
1958
- }
1959
- const moduleDir = path3.dirname((0, import_url.fileURLToPath)(import_meta.url));
1960
- const candidates = [
1961
- path3.resolve(moduleDir, "../templates"),
1962
- path3.resolve(moduleDir, "../../templates")
1963
- ];
1964
- const builtinDir = candidates.find((dir) => fs3.existsSync(dir) && fs3.statSync(dir).isDirectory());
1965
- if (!builtinDir) return;
1966
- for (const entry of fs3.readdirSync(builtinDir, { withFileTypes: true })) {
1967
- if (!entry.isFile() || !entry.name.endsWith(".md")) continue;
1968
- if (entry.name === "daily.md") continue;
1969
- const sourcePath = path3.join(builtinDir, entry.name);
1970
- const targetPath = path3.join(templatesPath, entry.name);
1971
- if (!fs3.existsSync(targetPath)) {
1972
- fs3.copyFileSync(sourcePath, targetPath);
1973
- }
1974
- }
1975
- }
1976
- async createWelcomeNote() {
1977
- if (!this.config.categories.includes("inbox")) return;
1978
- const inboxPath = path3.join(this.config.path, "inbox", "welcome.md");
1979
- if (fs3.existsSync(inboxPath)) return;
1980
- const now = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
1981
- const content = `---
1982
- title: "Welcome to ${this.config.name}"
1983
- date: ${now}
1984
- type: fact
1985
- tags: [welcome, getting-started]
1986
- ---
1987
-
1988
- # Welcome to ${this.config.name}
1989
-
1990
- Your vault is ready. Here's what you can do:
1991
-
1992
- ## Quick Start
1993
-
1994
- - **Capture a thought:** \`clawvault capture "your note here"\`
1995
- - **Store structured memory:** \`clawvault store --category decisions --title "My Choice" --content "..."\`
1996
- - **Search your vault:** \`clawvault search "query"\`
1997
- - **See your knowledge graph:** \`clawvault graph\`
1998
- - **Get context for a topic:** \`clawvault context "topic"\`
1999
-
2000
- ## Vault Structure
2001
-
2002
- Your vault organizes memories by type \u2014 decisions, lessons, people, projects, and more.
2003
- Each category is a folder. Each memory is a markdown file with frontmatter.
2004
-
2005
- ## Observational Memory
2006
-
2007
- When connected to an AI agent (like OpenClaw), your vault can automatically observe
2008
- conversations and extract important memories \u2014 decisions, lessons, commitments \u2014 without
2009
- manual effort.
2010
-
2011
- ## Wiki-Links
2012
-
2013
- Use \`[[double brackets]]\` to link between notes. Your memory graph tracks these
2014
- connections, building a knowledge network that grows with you.
2015
-
2016
- ---
2017
-
2018
- *Delete this file anytime. It's just here to say hello.*
2019
- `;
2020
- fs3.writeFileSync(inboxPath, content);
2021
- }
2022
- async syncMemoryGraphIndex(options = {}) {
2023
- try {
2024
- await buildOrUpdateMemoryGraphIndex(this.config.path, options);
2025
- } catch {
2026
- }
2027
- }
2028
- generateReadme() {
2029
- const coreCategories = this.config.categories.filter((c) => !["templates", "tasks", "backlog"].includes(c));
2030
- const workCategories = this.config.categories.filter((c) => ["tasks", "backlog"].includes(c));
2031
- return `# ${this.config.name}
2032
-
2033
- An elephant never forgets.
2034
-
2035
- ## Structure
2036
-
2037
- ### Memory Categories
2038
- ${coreCategories.map((c) => `- \`${c}/\` \u2014 ${this.getCategoryDescription(c)}`).join("\n")}
2039
-
2040
- ### Work Tracking
2041
- ${workCategories.map((c) => `- \`${c}/\` \u2014 ${this.getCategoryDescription(c)}`).join("\n")}
2042
-
2043
- ### Observational Memory
2044
- - \`ledger/raw/\` \u2014 Raw session transcripts (source of truth)
2045
- - \`ledger/observations/\` \u2014 Compressed observations with importance scores
2046
- - \`ledger/reflections/\` \u2014 Weekly reflection summaries
2047
-
2048
- ## Quick Reference
2049
-
2050
- \`\`\`bash
2051
- # Capture a thought
2052
- clawvault capture "important insight about X"
2053
-
2054
- # Store structured memory
2055
- clawvault store --category decisions --title "Choice" --content "We chose X because..."
2056
-
2057
- # Search
2058
- clawvault search "query"
2059
- clawvault vsearch "semantic query" # vector search
2060
-
2061
- # Knowledge graph
2062
- clawvault graph # vault stats
2063
- clawvault context "topic" # graph-aware context retrieval
2064
-
2065
- # Session lifecycle
2066
- clawvault checkpoint --working-on "task"
2067
- clawvault sleep "what I did" --next "what's next"
2068
- clawvault wake # restore context on startup
2069
- \`\`\`
2070
-
2071
- ---
2072
-
2073
- *Managed by [ClawVault](https://clawvault.dev)*
2074
- `;
2075
- }
2076
- getCategoryDescription(category) {
2077
- const descriptions = {
2078
- // Memory type categories (Benthic's taxonomy)
2079
- facts: "Raw information, data points, things that are true",
2080
- feelings: "Emotional states, reactions, energy levels",
2081
- decisions: "Choices made with context and reasoning",
2082
- rules: "Injectable operational constraints, guardrails, and runbooks",
2083
- lessons: "What I learned, insights, patterns observed",
2084
- commitments: "Promises, goals, obligations to fulfill",
2085
- preferences: "Likes, dislikes, how I want things",
2086
- people: "Relationships, one file per person",
2087
- projects: "Active work, ventures, ongoing efforts",
2088
- // System categories
2089
- handoffs: "Session bridges \u2014 what I was doing, what comes next",
2090
- transcripts: "Session summaries and logs",
2091
- goals: "Long-term and short-term objectives",
2092
- patterns: "Recurring behaviors (\u2192 lessons)",
2093
- inbox: "Quick capture \u2192 process later",
2094
- templates: "Templates for each document type",
2095
- agents: "Other agents \u2014 capabilities, trust levels, coordination notes",
2096
- research: "Deep dives, analysis, reference material",
2097
- tasks: "Active work items with status and context",
2098
- backlog: "Future work \u2014 ideas and tasks not yet started"
2099
- };
2100
- return descriptions[category] || category;
2101
- }
2102
- };
2103
-
2104
- // src/lib/time.ts
2105
- function formatAge(ms) {
2106
- if (!Number.isFinite(ms)) return "unknown";
2107
- const seconds = Math.max(0, Math.floor(ms / 1e3));
2108
- const minutes = Math.floor(seconds / 60);
2109
- const hours = Math.floor(minutes / 60);
2110
- const days = Math.floor(hours / 24);
2111
- if (days > 0) return `${days}d ${hours % 24}h`;
2112
- if (hours > 0) return `${hours}h ${minutes % 60}m`;
2113
- if (minutes > 0) return `${minutes}m ${seconds % 60}s`;
2114
- return `${seconds}s`;
2115
- }
2116
-
2117
- // src/lib/backlinks.ts
2118
- var fs5 = __toESM(require("fs"), 1);
2119
- var path5 = __toESM(require("path"), 1);
2120
-
2121
- // src/lib/entity-index.ts
2122
- var fs4 = __toESM(require("fs"), 1);
2123
- var path4 = __toESM(require("path"), 1);
2124
- var import_gray_matter3 = __toESM(require("gray-matter"), 1);
2125
- function buildEntityIndex(vaultPath) {
2126
- const entries = /* @__PURE__ */ new Map();
2127
- const byPath = /* @__PURE__ */ new Map();
2128
- const entityFolders = ["people", "projects", "agents", "lessons", "decisions", "commitments"];
2129
- for (const folder of entityFolders) {
2130
- const folderPath = path4.join(vaultPath, folder);
2131
- if (!fs4.existsSync(folderPath)) continue;
2132
- const files = fs4.readdirSync(folderPath).filter((f) => f.endsWith(".md"));
2133
- for (const file of files) {
2134
- const filePath = path4.join(folderPath, file);
2135
- const content = fs4.readFileSync(filePath, "utf-8");
2136
- const { data: frontmatter } = (0, import_gray_matter3.default)(content);
2137
- const relativePath = `${folder}/${file.replace(".md", "")}`;
2138
- const baseName = file.replace(".md", "");
2139
- const aliases = [baseName];
2140
- if (frontmatter.title && frontmatter.title.toLowerCase() !== baseName.toLowerCase()) {
2141
- aliases.push(frontmatter.title);
2142
- }
2143
- if (Array.isArray(frontmatter.aliases)) {
2144
- aliases.push(...frontmatter.aliases);
2145
- }
2146
- for (const alias of aliases) {
2147
- const key = alias.toLowerCase();
2148
- if (!entries.has(key)) {
2149
- entries.set(key, relativePath);
2150
- }
2151
- }
2152
- byPath.set(relativePath, { path: relativePath, aliases });
2153
- }
2154
- }
2155
- return { entries, byPath };
2156
- }
2157
-
2158
- // src/lib/backlinks.ts
2159
- var WIKI_LINK_REGEX = /\[\[([^\]]+)\]\]/g;
2160
- function toVaultId(vaultPath, filePath) {
2161
- const relative3 = path5.relative(vaultPath, filePath).replace(/\.md$/, "");
2162
- return relative3.split(path5.sep).join("/");
2163
- }
2164
- function normalizeLinkTarget(raw) {
2165
- let target = raw.trim();
2166
- if (!target) return "";
2167
- if (target.startsWith("[[") && target.endsWith("]]")) {
2168
- target = target.slice(2, -2);
2169
- }
2170
- const pipeIndex = target.indexOf("|");
2171
- if (pipeIndex !== -1) {
2172
- target = target.slice(0, pipeIndex);
2173
- }
2174
- if (target.startsWith("#")) return "";
2175
- const hashIndex = target.indexOf("#");
2176
- if (hashIndex !== -1) {
2177
- target = target.slice(0, hashIndex);
2178
- }
2179
- target = target.trim();
2180
- if (!target) return "";
2181
- if (target.endsWith(".md")) {
2182
- target = target.slice(0, -3);
2183
- }
2184
- if (target.startsWith("/")) {
2185
- target = target.slice(1);
2186
- }
2187
- return target.replace(/\\/g, "/");
2188
- }
2189
- function listMarkdownFiles(vaultPath) {
2190
- const files = [];
2191
- const skipDirs = /* @__PURE__ */ new Set(["archive", "templates", "node_modules"]);
2192
- function walk(dir) {
2193
- const entries = fs5.readdirSync(dir, { withFileTypes: true });
2194
- for (const entry of entries) {
2195
- const fullPath = path5.join(dir, entry.name);
2196
- if (entry.isDirectory()) {
2197
- if (entry.name.startsWith(".") || skipDirs.has(entry.name)) continue;
2198
- walk(fullPath);
2199
- } else if (entry.isFile() && entry.name.endsWith(".md")) {
2200
- files.push(fullPath);
2201
- }
2202
- }
2203
- }
2204
- walk(vaultPath);
2205
- return files;
2206
- }
2207
- function buildKnownIds(vaultPath, files) {
2208
- const ids = /* @__PURE__ */ new Set();
2209
- const idsLower = /* @__PURE__ */ new Map();
2210
- for (const file of files) {
2211
- const id = toVaultId(vaultPath, file);
2212
- ids.add(id);
2213
- const lower = id.toLowerCase();
2214
- if (!idsLower.has(lower)) {
2215
- idsLower.set(lower, id);
2216
- }
2217
- }
2218
- return { ids, idsLower };
2219
- }
2220
- function resolveTarget(target, known, entityIndex) {
2221
- if (!target) return null;
2222
- if (known.ids.has(target)) return target;
2223
- const lower = target.toLowerCase();
2224
- if (known.idsLower.has(lower)) return known.idsLower.get(lower);
2225
- if (entityIndex?.entries.has(lower)) return entityIndex.entries.get(lower);
2226
- return null;
2227
- }
2228
- function scanVaultLinks(vaultPath, options = {}) {
2229
- const files = listMarkdownFiles(vaultPath);
2230
- const known = buildKnownIds(vaultPath, files);
2231
- const entityIndex = options.entityIndex ?? buildEntityIndex(vaultPath);
2232
- const backlinks = /* @__PURE__ */ new Map();
2233
- const orphans = [];
2234
- let linkCount = 0;
2235
- for (const file of files) {
2236
- const sourceId = toVaultId(vaultPath, file);
2237
- const content = fs5.readFileSync(file, "utf-8");
2238
- const matches = content.match(WIKI_LINK_REGEX) || [];
2239
- linkCount += matches.length;
2240
- for (const match of matches) {
2241
- const target = normalizeLinkTarget(match);
2242
- if (!target) continue;
2243
- const resolved = resolveTarget(target, known, entityIndex);
2244
- if (!resolved) {
2245
- orphans.push({ source: sourceId, target });
2246
- continue;
2247
- }
2248
- if (!backlinks.has(resolved)) {
2249
- backlinks.set(resolved, /* @__PURE__ */ new Set());
2250
- }
2251
- backlinks.get(resolved).add(sourceId);
2252
- }
2253
- }
2254
- const backlinksMap = /* @__PURE__ */ new Map();
2255
- for (const [target, sources] of backlinks) {
2256
- backlinksMap.set(target, [...sources].sort());
2257
- }
2258
- return { backlinks: backlinksMap, orphans, linkCount };
2259
- }
2260
-
2261
- // src/observer/active-session-observer.ts
2262
- var fs6 = __toESM(require("fs"), 1);
2263
- var path7 = __toESM(require("path"), 1);
2264
-
2265
- // src/lib/claude-credentials.ts
2266
- var EXPIRY_BUFFER_MS = 5 * 60 * 1e3;
2267
-
2268
- // src/lib/task-utils.ts
2269
- var import_gray_matter5 = __toESM(require("gray-matter"), 1);
2270
-
2271
- // src/lib/primitive-templates.ts
2272
- var import_gray_matter4 = __toESM(require("gray-matter"), 1);
2273
-
2274
- // src/lib/project-utils.ts
2275
- var import_gray_matter6 = __toESM(require("gray-matter"), 1);
2276
-
2277
- // src/lib/session-utils.ts
2278
- var path6 = __toESM(require("path"), 1);
2279
- var os = __toESM(require("os"), 1);
2280
- function validateEnvPath(envValue) {
2281
- if (!envValue) return null;
2282
- const trimmed = envValue.trim();
2283
- if (!trimmed) return null;
2284
- const resolved = path6.resolve(trimmed);
2285
- if (!path6.isAbsolute(resolved)) return null;
2286
- return resolved;
2287
- }
2288
- function getOpenClawDir() {
2289
- const customHome = validateEnvPath(process.env.OPENCLAW_HOME);
2290
- if (customHome) {
2291
- return customHome;
2292
- }
2293
- return path6.join(os.homedir(), ".openclaw");
2294
- }
2295
- function getOpenClawAgentsDir() {
2296
- const stateDir = validateEnvPath(process.env.OPENCLAW_STATE_DIR);
2297
- if (stateDir) {
2298
- return path6.join(stateDir, "agents");
2299
- }
2300
- return path6.join(getOpenClawDir(), "agents");
2301
- }
2302
- function getSessionsDir(agentId) {
2303
- return path6.join(getOpenClawAgentsDir(), agentId, "sessions");
2304
- }
2305
-
2306
- // src/observer/active-session-observer.ts
2307
- var ONE_KIB = 1024;
2308
- var ONE_MIB = ONE_KIB * ONE_KIB;
2309
- var SMALL_SESSION_THRESHOLD_BYTES = 50 * ONE_KIB;
2310
- var MEDIUM_SESSION_THRESHOLD_BYTES = 150 * ONE_KIB;
2311
- var LARGE_SESSION_THRESHOLD_BYTES = 300 * ONE_KIB;
2312
- var DEFAULT_AGENT_ID = "main";
2313
- var AGENT_ID_RE = /^[a-zA-Z0-9_-]{1,100}$/;
2314
- var SESSION_ID_RE = /^[a-zA-Z0-9._-]{1,200}$/;
2315
- var CURSOR_FILE_NAME = "observe-cursors.json";
2316
- var STALE_CURSOR_THRESHOLD_MS = 12 * 60 * 60 * 1e3;
2317
- function isFiniteNonNegative(value) {
2318
- return typeof value === "number" && Number.isFinite(value) && value >= 0;
2319
- }
2320
- function getCursorPath(vaultPath) {
2321
- return path7.join(vaultPath, ".clawvault", CURSOR_FILE_NAME);
2322
- }
2323
- function getScaledObservationThresholdBytes(fileSizeBytes) {
2324
- if (fileSizeBytes < ONE_MIB) {
2325
- return SMALL_SESSION_THRESHOLD_BYTES;
2326
- }
2327
- if (fileSizeBytes <= 5 * ONE_MIB) {
2328
- return MEDIUM_SESSION_THRESHOLD_BYTES;
2329
- }
2330
- return LARGE_SESSION_THRESHOLD_BYTES;
2331
- }
2332
- function parseCursorStore(raw) {
2333
- if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
2334
- return {};
2335
- }
2336
- const input = raw;
2337
- const store = {};
2338
- for (const [sessionId, value] of Object.entries(input)) {
2339
- if (!SESSION_ID_RE.test(sessionId)) continue;
2340
- if (!value || typeof value !== "object" || Array.isArray(value)) continue;
2341
- const entry = value;
2342
- if (!isFiniteNonNegative(entry.lastObservedOffset)) continue;
2343
- if (!isFiniteNonNegative(entry.lastFileSize)) continue;
2344
- if (typeof entry.lastObservedAt !== "string" || !entry.lastObservedAt.trim()) continue;
2345
- if (typeof entry.sessionKey !== "string" || !entry.sessionKey.trim()) continue;
2346
- store[sessionId] = {
2347
- lastObservedOffset: entry.lastObservedOffset,
2348
- lastObservedAt: entry.lastObservedAt,
2349
- sessionKey: entry.sessionKey,
2350
- lastFileSize: entry.lastFileSize
2351
- };
2352
- }
2353
- return store;
2354
- }
2355
- function loadObserveCursorStore(vaultPath) {
2356
- const cursorPath = getCursorPath(vaultPath);
2357
- if (!fs6.existsSync(cursorPath)) {
2358
- return {};
2359
- }
2360
- try {
2361
- const raw = JSON.parse(fs6.readFileSync(cursorPath, "utf-8"));
2362
- return parseCursorStore(raw);
2363
- } catch {
2364
- return {};
2365
- }
2366
- }
2367
- function parseAgentIdFromSessionKey(sessionKey) {
2368
- const match = /^agent:([^:]+):/.exec(sessionKey);
2369
- if (!match?.[1]) {
2370
- return null;
2371
- }
2372
- const candidate = match[1].trim();
2373
- if (!AGENT_ID_RE.test(candidate)) {
2374
- return null;
2375
- }
2376
- return candidate;
2377
- }
2378
- function resolveSessionFileForCursor(sessionId, cursor, sessionsDirOverride) {
2379
- const candidates = /* @__PURE__ */ new Set();
2380
- if (sessionsDirOverride?.trim()) {
2381
- candidates.add(path7.join(path7.resolve(sessionsDirOverride.trim()), `${sessionId}.jsonl`));
2382
- }
2383
- const agentId = parseAgentIdFromSessionKey(cursor.sessionKey) ?? DEFAULT_AGENT_ID;
2384
- candidates.add(path7.join(getSessionsDir(agentId), `${sessionId}.jsonl`));
2385
- for (const filePath of candidates) {
2386
- try {
2387
- const stat = fs6.statSync(filePath);
2388
- if (stat.isFile()) {
2389
- return filePath;
2390
- }
2391
- } catch {
2392
- continue;
2393
- }
2394
- }
2395
- return null;
2396
- }
2397
- function getObserverStaleness(vaultPath, options = {}) {
2398
- const nowDate = options.now ? options.now() : /* @__PURE__ */ new Date();
2399
- const nowMs = nowDate.getTime();
2400
- if (!Number.isFinite(nowMs)) {
2401
- return {
2402
- staleCount: 0,
2403
- oldestMs: 0,
2404
- newestMs: 0
2405
- };
2406
- }
2407
- const cursorStore = loadObserveCursorStore(path7.resolve(vaultPath));
2408
- let staleCount = 0;
2409
- let oldestMs = 0;
2410
- let newestMs = Number.POSITIVE_INFINITY;
2411
- for (const [sessionId, cursor] of Object.entries(cursorStore)) {
2412
- const observedAtMs = Date.parse(cursor.lastObservedAt);
2413
- if (!Number.isFinite(observedAtMs)) {
2414
- continue;
2415
- }
2416
- const ageMs = Math.max(0, nowMs - observedAtMs);
2417
- if (ageMs <= STALE_CURSOR_THRESHOLD_MS) {
2418
- continue;
2419
- }
2420
- const sessionFilePath = resolveSessionFileForCursor(sessionId, cursor, options.sessionsDir);
2421
- if (!sessionFilePath) {
2422
- continue;
2423
- }
2424
- let sessionStat;
2425
- try {
2426
- sessionStat = fs6.statSync(sessionFilePath);
2427
- } catch {
2428
- continue;
2429
- }
2430
- if (!sessionStat.isFile()) {
2431
- continue;
2432
- }
2433
- const newBytes = sessionStat.size - cursor.lastFileSize;
2434
- if (newBytes <= 0) {
2435
- continue;
2436
- }
2437
- const processThreshold = getScaledObservationThresholdBytes(sessionStat.size);
2438
- if (newBytes < processThreshold) {
2439
- continue;
2440
- }
2441
- staleCount += 1;
2442
- oldestMs = Math.max(oldestMs, ageMs);
2443
- newestMs = Math.min(newestMs, ageMs);
2444
- }
2445
- return {
2446
- staleCount,
2447
- oldestMs: staleCount > 0 ? oldestMs : 0,
2448
- newestMs: staleCount > 0 ? newestMs : 0
2449
- };
2450
- }
2451
-
2452
- // src/commands/status.ts
2453
- var CLAWVAULT_DIR = ".clawvault";
2454
- var CHECKPOINT_FILE = "last-checkpoint.json";
2455
- var DIRTY_DEATH_FLAG = "dirty-death.flag";
2456
- function findGitRoot(startPath) {
2457
- let current = path8.resolve(startPath);
2458
- while (true) {
2459
- if (fs7.existsSync(path8.join(current, ".git"))) {
2460
- return current;
2461
- }
2462
- const parent = path8.dirname(current);
2463
- if (parent === current) return null;
2464
- current = parent;
2465
- }
2466
- }
2467
- function getGitStatus(repoRoot) {
2468
- const output = (0, import_child_process2.execFileSync)("git", ["-C", repoRoot, "status", "--porcelain"], {
2469
- encoding: "utf-8"
2470
- });
2471
- const lines = output.split("\n").filter(Boolean);
2472
- return { clean: lines.length === 0, dirtyCount: lines.length };
2473
- }
2474
- function getLatestVaultMarkdownMtime(vaultPath) {
2475
- const skipDirs = /* @__PURE__ */ new Set([".git", ".obsidian", ".trash", "node_modules", ".clawvault"]);
2476
- let latest = null;
2477
- function walk(currentPath) {
2478
- const entries = fs7.readdirSync(currentPath, { withFileTypes: true });
2479
- for (const entry of entries) {
2480
- const absolute = path8.join(currentPath, entry.name);
2481
- if (entry.isDirectory()) {
2482
- if (!skipDirs.has(entry.name)) {
2483
- walk(absolute);
2484
- }
2485
- continue;
2486
- }
2487
- if (!entry.isFile() || !entry.name.endsWith(".md")) {
2488
- continue;
2489
- }
2490
- const mtime = fs7.statSync(absolute).mtime;
2491
- if (!latest || mtime.getTime() > latest.getTime()) {
2492
- latest = mtime;
2493
- }
2494
- }
2495
- }
2496
- walk(vaultPath);
2497
- return latest;
2498
- }
2499
- function parseQmdCollectionsText(raw) {
2500
- const names = [];
2501
- const regex = /^(\S+)\s+\(qmd:\/\/\1\/\)/gm;
2502
- let match;
2503
- while ((match = regex.exec(raw)) !== null) {
2504
- names.push(match[1]);
2505
- }
2506
- return names;
2507
- }
2508
- function getQmdIndexStatus(collection, root, indexName) {
2509
- const output = (0, import_child_process2.execFileSync)("qmd", withQmdIndexArgs(["collection", "list"], indexName), { encoding: "utf-8" });
2510
- const names = parseQmdCollectionsText(output);
2511
- if (names.includes(collection)) {
2512
- return "present";
2513
- }
2514
- return "missing";
2515
- }
2516
- function loadCheckpoint(vaultPath) {
2517
- const checkpointPath = path8.join(vaultPath, CLAWVAULT_DIR, CHECKPOINT_FILE);
2518
- if (!fs7.existsSync(checkpointPath)) {
2519
- return { data: null };
2520
- }
2521
- try {
2522
- const data = JSON.parse(fs7.readFileSync(checkpointPath, "utf-8"));
2523
- return { data };
2524
- } catch (err) {
2525
- return { data: null, error: err?.message || "Failed to parse checkpoint" };
2526
- }
2527
- }
2528
- async function getStatus(vaultPath, options = {}) {
2529
- if (!hasQmd()) {
2530
- throw new QmdUnavailableError();
2531
- }
2532
- const vault = new ClawVault(path8.resolve(vaultPath));
2533
- await vault.load();
2534
- const stats = await vault.stats();
2535
- const linkScan = scanVaultLinks(vault.getPath());
2536
- const issues = [];
2537
- const checkpointInfo = loadCheckpoint(vault.getPath());
2538
- const checkpoint = checkpointInfo.data;
2539
- if (checkpointInfo.error) {
2540
- issues.push(`Checkpoint parse error: ${checkpointInfo.error}`);
2541
- }
2542
- const checkpointStatus = {
2543
- exists: Boolean(checkpoint),
2544
- timestamp: checkpoint?.timestamp,
2545
- age: checkpoint?.timestamp ? formatAge(Date.now() - new Date(checkpoint.timestamp).getTime()) : void 0,
2546
- sessionKey: checkpoint?.sessionKey,
2547
- model: checkpoint?.model,
2548
- tokenEstimate: checkpoint?.tokenEstimate
2549
- };
2550
- if (!checkpointStatus.exists) {
2551
- issues.push("No checkpoint found");
2552
- }
2553
- const dirtyFlagPath = path8.join(vault.getPath(), CLAWVAULT_DIR, DIRTY_DEATH_FLAG);
2554
- if (fs7.existsSync(dirtyFlagPath)) {
2555
- issues.push("Dirty death flag is set");
2556
- }
2557
- const qmdCollection = vault.getQmdCollection();
2558
- const qmdRoot = vault.getQmdRoot();
2559
- let qmdIndexStatus = "missing";
2560
- let qmdError;
2561
- try {
2562
- qmdIndexStatus = getQmdIndexStatus(qmdCollection, qmdRoot, options.qmdIndexName);
2563
- if (qmdIndexStatus !== "present") {
2564
- issues.push(`qmd collection ${qmdIndexStatus.replace("-", " ")}`);
2565
- }
2566
- } catch (err) {
2567
- qmdError = err?.message || "Failed to check qmd index";
2568
- issues.push(`qmd status error: ${qmdError}`);
2569
- }
2570
- let gitStatus;
2571
- const gitRoot = findGitRoot(vault.getPath());
2572
- if (gitRoot) {
2573
- try {
2574
- const gitInfo = getGitStatus(gitRoot);
2575
- gitStatus = { repoRoot: gitRoot, ...gitInfo };
2576
- if (!gitInfo.clean) {
2577
- issues.push(`Uncommitted changes: ${gitInfo.dirtyCount}`);
2578
- }
2579
- } catch (err) {
2580
- issues.push(`Git status error: ${err?.message || "unknown error"}`);
2581
- }
2582
- }
2583
- const graphIndex = loadMemoryGraphIndex(vault.getPath());
2584
- let graphStatus = {
2585
- indexStatus: "missing"
2586
- };
2587
- if (!graphIndex) {
2588
- issues.push("Memory graph index missing");
2589
- } else {
2590
- const generatedAt = graphIndex.generatedAt;
2591
- const latestDocMtime = getLatestVaultMarkdownMtime(vault.getPath());
2592
- const isStale = latestDocMtime ? latestDocMtime.getTime() > new Date(generatedAt).getTime() + 1e3 : false;
2593
- graphStatus = {
2594
- indexStatus: isStale ? "stale" : "present",
2595
- generatedAt,
2596
- nodeCount: graphIndex.graph.stats.nodeCount,
2597
- edgeCount: graphIndex.graph.stats.edgeCount
2598
- };
2599
- if (isStale) {
2600
- issues.push("Memory graph index stale");
2601
- }
2602
- }
2603
- const observerStaleness = getObserverStaleness(vault.getPath());
2604
- if (observerStaleness.staleCount > 0) {
2605
- issues.push(`Observer stale sessions: ${observerStaleness.staleCount}`);
2606
- }
2607
- return {
2608
- vaultName: vault.getName(),
2609
- vaultPath: vault.getPath(),
2610
- health: issues.length === 0 ? "ok" : "warning",
2611
- issues,
2612
- checkpoint: checkpointStatus,
2613
- qmd: {
2614
- collection: qmdCollection,
2615
- root: qmdRoot,
2616
- indexStatus: qmdIndexStatus,
2617
- error: qmdError
2618
- },
2619
- graph: graphStatus,
2620
- observer: observerStaleness,
2621
- git: gitStatus,
2622
- links: {
2623
- total: linkScan.linkCount,
2624
- orphans: linkScan.orphans.length
2625
- },
2626
- documents: stats.documents,
2627
- categories: stats.categories
2628
- };
2629
- }
2630
- function formatStatus(status) {
2631
- let output = "ClawVault Status\n";
2632
- output += "-".repeat(40) + "\n";
2633
- output += `Vault: ${status.vaultName}
2634
- `;
2635
- output += `Path: ${status.vaultPath}
2636
- `;
2637
- output += `Health: ${status.health}
2638
- `;
2639
- if (status.issues.length > 0) {
2640
- output += `Issues: ${status.issues.join("; ")}
2641
- `;
2642
- } else {
2643
- output += "Issues: none\n";
2644
- }
2645
- output += "\nCheckpoint:\n";
2646
- if (!status.checkpoint.exists) {
2647
- output += " - none\n";
2648
- } else {
2649
- output += ` - Timestamp: ${status.checkpoint.timestamp}
2650
- `;
2651
- if (status.checkpoint.age) {
2652
- output += ` - Age: ${status.checkpoint.age}
2653
- `;
2654
- }
2655
- if (status.checkpoint.sessionKey) {
2656
- output += ` - Session key: ${status.checkpoint.sessionKey}
2657
- `;
2658
- }
2659
- if (status.checkpoint.model) {
2660
- output += ` - Model: ${status.checkpoint.model}
2661
- `;
2662
- }
2663
- if (status.checkpoint.tokenEstimate !== void 0) {
2664
- output += ` - Token estimate: ${status.checkpoint.tokenEstimate}
2665
- `;
2666
- }
2667
- }
2668
- output += "\nqmd:\n";
2669
- output += ` - Collection: ${status.qmd.collection}
2670
- `;
2671
- output += ` - Root: ${status.qmd.root}
2672
- `;
2673
- output += ` - Index: ${status.qmd.indexStatus}
2674
- `;
2675
- if (status.qmd.error) {
2676
- output += ` - Error: ${status.qmd.error}
2677
- `;
2678
- }
2679
- if (status.git) {
2680
- output += "\nGit:\n";
2681
- output += ` - Repo: ${status.git.repoRoot}
2682
- `;
2683
- output += ` - Status: ${status.git.clean ? "clean" : "dirty"} (${status.git.dirtyCount} change(s))
2684
- `;
2685
- }
2686
- output += "\nGraph:\n";
2687
- output += ` - Index: ${status.graph.indexStatus}
2688
- `;
2689
- if (status.graph.generatedAt) {
2690
- output += ` - Generated: ${status.graph.generatedAt}
2691
- `;
2692
- }
2693
- if (status.graph.nodeCount !== void 0 && status.graph.edgeCount !== void 0) {
2694
- output += ` - Size: ${status.graph.nodeCount} nodes, ${status.graph.edgeCount} edges
2695
- `;
2696
- }
2697
- output += "\nObserver:\n";
2698
- output += ` - Stale sessions: ${status.observer.staleCount}
2699
- `;
2700
- if (status.observer.staleCount > 0) {
2701
- output += ` - Oldest stale age: ${formatAge(status.observer.oldestMs)}
2702
- `;
2703
- output += ` - Newest stale age: ${formatAge(status.observer.newestMs)}
2704
- `;
2705
- }
2706
- output += "\nLinks:\n";
2707
- output += ` - Total: ${status.links.total}
2708
- `;
2709
- if (status.links.orphans > 0) {
2710
- output += ` - Orphans: ${status.links.orphans}
2711
- `;
2712
- }
2713
- output += "\nDocuments:\n";
2714
- output += ` - Total: ${status.documents}
2715
- `;
2716
- output += " - By category:\n";
2717
- for (const [category, count] of Object.entries(status.categories)) {
2718
- output += ` * ${category}: ${count}
2719
- `;
2720
- }
2721
- output += "-".repeat(40) + "\n";
2722
- return output;
2723
- }
2724
- async function statusCommand(vaultPath, options = {}) {
2725
- const status = await getStatus(vaultPath, { qmdIndexName: options.qmdIndexName });
2726
- if (options.json) {
2727
- console.log(JSON.stringify(status, null, 2));
2728
- return;
2729
- }
2730
- console.log(formatStatus(status));
2731
- }
2732
- // Annotate the CommonJS export names for ESM import in node:
2733
- 0 && (module.exports = {
2734
- formatStatus,
2735
- getStatus,
2736
- statusCommand
2737
- });