clawvault 2.6.1 → 3.0.0

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