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