clawvault 3.1.0 → 3.2.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 (289) hide show
  1. package/README.md +422 -141
  2. package/bin/clawvault.js +10 -2
  3. package/bin/command-registration.test.js +3 -1
  4. package/bin/command-runtime.js +9 -1
  5. package/bin/register-core-commands.js +23 -28
  6. package/bin/register-maintenance-commands.js +39 -3
  7. package/bin/register-query-commands.js +58 -29
  8. package/bin/register-tailscale-commands.js +106 -0
  9. package/bin/register-task-commands.js +18 -1
  10. package/bin/register-task-commands.test.js +16 -0
  11. package/bin/register-vault-operations-commands.js +29 -1
  12. package/bin/register-workgraph-commands.js +1368 -0
  13. package/dashboard/lib/graph-diff.js +104 -0
  14. package/dashboard/lib/graph-diff.test.js +75 -0
  15. package/dashboard/lib/vault-parser.js +556 -0
  16. package/dashboard/lib/vault-parser.test.js +254 -0
  17. package/dashboard/public/app.js +796 -0
  18. package/dashboard/public/index.html +52 -0
  19. package/dashboard/public/styles.css +221 -0
  20. package/dashboard/server.js +374 -0
  21. package/dist/{chunk-F2JEUD4J.js → chunk-23YDQ3QU.js} +6 -8
  22. package/dist/{chunk-C7OK5WKP.js → chunk-2JQ3O2YL.js} +4 -4
  23. package/dist/{chunk-VR5NE7PZ.js → chunk-2RAZ4ZFE.js} +1 -1
  24. package/dist/chunk-2ZDO52B4.js +52 -0
  25. package/dist/{chunk-ZZA73MFY.js → chunk-33DOSHTA.js} +176 -36
  26. package/dist/chunk-33VSQP4J.js +37 -0
  27. package/dist/chunk-4BQTQMJP.js +93 -0
  28. package/dist/{chunk-GUKMRGM7.js → chunk-4OXMU5S2.js} +1 -1
  29. package/dist/{chunk-62YTUT6J.js → chunk-4PY655YM.js} +15 -3
  30. package/dist/chunk-6FH3IULF.js +352 -0
  31. package/dist/{chunk-3NSBOUT3.js → chunk-77Q5CSPJ.js} +404 -80
  32. package/dist/{chunk-4VQTUVH7.js → chunk-7YZWHM36.js} +52 -26
  33. package/dist/chunk-BSJ6RIT7.js +447 -0
  34. package/dist/chunk-BUEW6IIK.js +364 -0
  35. package/dist/{chunk-LI4O6NVK.js → chunk-CLJTREDS.js} +74 -14
  36. package/dist/chunk-EK6S23ZB.js +469 -0
  37. package/dist/{chunk-LNJA2UGL.js → chunk-ESFLMDRB.js} +9 -86
  38. package/dist/{chunk-H34S76MB.js → chunk-ESVS6K2B.js} +6 -6
  39. package/dist/{chunk-WAZ3NLWL.js → chunk-F55HGNU4.js} +0 -47
  40. package/dist/{chunk-QK3UCXWL.js → chunk-FHFUXL6G.js} +2 -2
  41. package/dist/{chunk-H62BP7RI.js → chunk-GAOWA7GR.js} +212 -46
  42. package/dist/chunk-GGA32J2R.js +784 -0
  43. package/dist/chunk-GNJL4YGR.js +79 -0
  44. package/dist/chunk-IVRIKYFE.js +520 -0
  45. package/dist/chunk-MDIH26GC.js +183 -0
  46. package/dist/{chunk-LYHGEHXG.js → chunk-MFAWT5O5.js} +0 -1
  47. package/dist/chunk-MM6QGW3P.js +207 -0
  48. package/dist/{chunk-P5EPF6MB.js → chunk-MW5C6ZQA.js} +110 -13
  49. package/dist/chunk-NCKFNBHJ.js +257 -0
  50. package/dist/{chunk-QBLMXKF2.js → chunk-OIWVQYQF.js} +1 -1
  51. package/dist/{chunk-42MXU7A6.js → chunk-P62WHA27.js} +58 -47
  52. package/dist/chunk-PBACDKKP.js +66 -0
  53. package/dist/{chunk-VGLOTGAS.js → chunk-QSHD36LH.js} +2 -2
  54. package/dist/{chunk-OZ7RIXTO.js → chunk-QSRRMEYM.js} +2 -2
  55. package/dist/chunk-QVEERJSP.js +152 -0
  56. package/dist/{chunk-N2AXRYLC.js → chunk-QWQ3TIKS.js} +1 -1
  57. package/dist/{chunk-3DHXQHYG.js → chunk-R2MIW5G7.js} +1 -1
  58. package/dist/{chunk-SJSFRIYS.js → chunk-SLXOR3CC.js} +2 -2
  59. package/dist/chunk-SS4B7P7V.js +99 -0
  60. package/dist/{chunk-JY6FYXIT.js → chunk-STCQGCEQ.js} +6 -11
  61. package/dist/chunk-TIGW564L.js +628 -0
  62. package/dist/chunk-U4O6C46S.js +154 -0
  63. package/dist/{chunk-ITPEXLHA.js → chunk-URXDAUVH.js} +24 -5
  64. package/dist/chunk-VSL7KY3M.js +189 -0
  65. package/dist/{chunk-U55BGUAU.js → chunk-W4SPAEE7.js} +6 -6
  66. package/dist/chunk-WMGIIABP.js +15 -0
  67. package/dist/{chunk-33UGEQRT.js → chunk-X3SPPUFG.js} +151 -64
  68. package/dist/chunk-Y6VJKXGL.js +373 -0
  69. package/dist/{chunk-3WRJEKN4.js → chunk-ZN54U2OZ.js} +123 -10
  70. package/dist/cli/index.js +34 -24
  71. package/dist/commands/archive.js +3 -3
  72. package/dist/commands/backlog.js +3 -3
  73. package/dist/commands/blocked.js +3 -3
  74. package/dist/commands/canvas.d.ts +15 -0
  75. package/dist/commands/canvas.js +200 -0
  76. package/dist/commands/checkpoint.js +2 -2
  77. package/dist/commands/compat.js +2 -2
  78. package/dist/commands/context.js +8 -6
  79. package/dist/commands/doctor.d.ts +11 -7
  80. package/dist/commands/doctor.js +18 -16
  81. package/dist/commands/embed.js +5 -6
  82. package/dist/commands/entities.js +2 -2
  83. package/dist/commands/graph.js +4 -4
  84. package/dist/commands/inject.d.ts +1 -1
  85. package/dist/commands/inject.js +5 -6
  86. package/dist/commands/kanban.js +4 -4
  87. package/dist/commands/link.js +5 -5
  88. package/dist/commands/migrate-observations.js +4 -4
  89. package/dist/commands/observe.d.ts +0 -1
  90. package/dist/commands/observe.js +14 -13
  91. package/dist/commands/project.js +5 -5
  92. package/dist/commands/rebuild-embeddings.d.ts +21 -0
  93. package/dist/commands/rebuild-embeddings.js +91 -0
  94. package/dist/commands/rebuild.js +12 -11
  95. package/dist/commands/recover.js +3 -3
  96. package/dist/commands/reflect.js +6 -7
  97. package/dist/commands/repair-session.js +1 -1
  98. package/dist/commands/replay.js +14 -14
  99. package/dist/commands/session-recap.js +1 -1
  100. package/dist/commands/setup.d.ts +2 -89
  101. package/dist/commands/setup.js +3 -21
  102. package/dist/commands/shell-init.js +1 -1
  103. package/dist/commands/sleep.d.ts +1 -1
  104. package/dist/commands/sleep.js +20 -19
  105. package/dist/commands/status.d.ts +2 -0
  106. package/dist/commands/status.js +57 -35
  107. package/dist/commands/sync-bd.d.ts +10 -0
  108. package/dist/commands/sync-bd.js +10 -0
  109. package/dist/commands/tailscale.d.ts +52 -0
  110. package/dist/commands/tailscale.js +26 -0
  111. package/dist/commands/task.js +4 -4
  112. package/dist/commands/template.js +2 -2
  113. package/dist/commands/wake.d.ts +1 -1
  114. package/dist/commands/wake.js +11 -10
  115. package/dist/commands/workgraph.d.ts +124 -0
  116. package/dist/commands/workgraph.js +38 -0
  117. package/dist/index.d.ts +341 -191
  118. package/dist/index.js +446 -116
  119. package/dist/{inject-Bzi5E-By.d.ts → inject-DYUrDqQO.d.ts} +3 -3
  120. package/dist/ledger-B7g7jhqG.d.ts +44 -0
  121. package/dist/lib/auto-linker.js +2 -2
  122. package/dist/lib/canvas-layout.d.ts +115 -0
  123. package/dist/lib/canvas-layout.js +35 -0
  124. package/dist/lib/config.d.ts +27 -3
  125. package/dist/lib/config.js +4 -2
  126. package/dist/lib/entity-index.js +1 -1
  127. package/dist/lib/project-utils.js +4 -4
  128. package/dist/lib/session-repair.js +1 -1
  129. package/dist/lib/session-utils.js +1 -1
  130. package/dist/lib/tailscale.d.ts +225 -0
  131. package/dist/lib/tailscale.js +50 -0
  132. package/dist/lib/task-utils.js +3 -3
  133. package/dist/lib/template-engine.js +1 -1
  134. package/dist/lib/webdav.d.ts +109 -0
  135. package/dist/lib/webdav.js +35 -0
  136. package/dist/onnxruntime_binding-5QEF3SUC.node +0 -0
  137. package/dist/onnxruntime_binding-BKPKNEGC.node +0 -0
  138. package/dist/onnxruntime_binding-FMOXGIUT.node +0 -0
  139. package/dist/onnxruntime_binding-OI2KMXC5.node +0 -0
  140. package/dist/onnxruntime_binding-UX44MLAZ.node +0 -0
  141. package/dist/onnxruntime_binding-Y2W7N7WY.node +0 -0
  142. package/dist/openclaw-plugin.d.ts +8 -0
  143. package/dist/openclaw-plugin.js +14 -0
  144. package/dist/registry-BR4326o0.d.ts +30 -0
  145. package/dist/store-CA-6sKCJ.d.ts +34 -0
  146. package/dist/thread-B9LhXNU0.d.ts +41 -0
  147. package/dist/transformers.node-A2ZRORSQ.js +46775 -0
  148. package/dist/{types-Y2_Um2Ls.d.ts → types-BbWJoC1c.d.ts} +1 -44
  149. package/dist/workgraph/index.d.ts +5 -0
  150. package/dist/workgraph/index.js +23 -0
  151. package/dist/workgraph/ledger.d.ts +2 -0
  152. package/dist/workgraph/ledger.js +25 -0
  153. package/dist/workgraph/registry.d.ts +2 -0
  154. package/dist/workgraph/registry.js +19 -0
  155. package/dist/workgraph/store.d.ts +2 -0
  156. package/dist/workgraph/store.js +25 -0
  157. package/dist/workgraph/thread.d.ts +2 -0
  158. package/dist/workgraph/thread.js +25 -0
  159. package/dist/workgraph/types.d.ts +54 -0
  160. package/dist/workgraph/types.js +7 -0
  161. package/hooks/clawvault/HOOK.md +113 -0
  162. package/hooks/clawvault/handler.js +1561 -0
  163. package/hooks/clawvault/handler.test.js +510 -0
  164. package/hooks/clawvault/openclaw.plugin.json +72 -0
  165. package/openclaw.plugin.json +65 -38
  166. package/package.json +25 -22
  167. package/dist/chunk-3RG5ZIWI.js +0 -10
  168. package/dist/chunk-3ZIH425O.js +0 -871
  169. package/dist/chunk-6U6MK36V.js +0 -205
  170. package/dist/chunk-CMB7UL7C.js +0 -327
  171. package/dist/chunk-D2H45LON.js +0 -1074
  172. package/dist/chunk-E7MFQB6D.js +0 -163
  173. package/dist/chunk-GQSLDZTS.js +0 -560
  174. package/dist/chunk-MFM6K7PU.js +0 -374
  175. package/dist/chunk-MXSSG3QU.js +0 -42
  176. package/dist/chunk-OCGVIN3L.js +0 -88
  177. package/dist/chunk-PAH27GSN.js +0 -108
  178. package/dist/chunk-YCUNCH2I.js +0 -78
  179. package/dist/cli/index.cjs +0 -8584
  180. package/dist/cli/index.d.cts +0 -5
  181. package/dist/commands/archive.cjs +0 -287
  182. package/dist/commands/archive.d.cts +0 -11
  183. package/dist/commands/backlog.cjs +0 -721
  184. package/dist/commands/backlog.d.cts +0 -53
  185. package/dist/commands/blocked.cjs +0 -204
  186. package/dist/commands/blocked.d.cts +0 -26
  187. package/dist/commands/checkpoint.cjs +0 -244
  188. package/dist/commands/checkpoint.d.cts +0 -41
  189. package/dist/commands/compat.cjs +0 -294
  190. package/dist/commands/compat.d.cts +0 -28
  191. package/dist/commands/context.cjs +0 -2990
  192. package/dist/commands/context.d.cts +0 -2
  193. package/dist/commands/doctor.cjs +0 -2986
  194. package/dist/commands/doctor.d.cts +0 -21
  195. package/dist/commands/embed.cjs +0 -232
  196. package/dist/commands/embed.d.cts +0 -17
  197. package/dist/commands/entities.cjs +0 -141
  198. package/dist/commands/entities.d.cts +0 -7
  199. package/dist/commands/graph.cjs +0 -501
  200. package/dist/commands/graph.d.cts +0 -21
  201. package/dist/commands/inject.cjs +0 -1636
  202. package/dist/commands/inject.d.cts +0 -2
  203. package/dist/commands/kanban.cjs +0 -884
  204. package/dist/commands/kanban.d.cts +0 -63
  205. package/dist/commands/link.cjs +0 -965
  206. package/dist/commands/link.d.cts +0 -11
  207. package/dist/commands/migrate-observations.cjs +0 -362
  208. package/dist/commands/migrate-observations.d.cts +0 -19
  209. package/dist/commands/observe.cjs +0 -4099
  210. package/dist/commands/observe.d.cts +0 -23
  211. package/dist/commands/project.cjs +0 -1341
  212. package/dist/commands/project.d.cts +0 -85
  213. package/dist/commands/rebuild.cjs +0 -3136
  214. package/dist/commands/rebuild.d.cts +0 -11
  215. package/dist/commands/recover.cjs +0 -361
  216. package/dist/commands/recover.d.cts +0 -38
  217. package/dist/commands/reflect.cjs +0 -1008
  218. package/dist/commands/reflect.d.cts +0 -11
  219. package/dist/commands/repair-session.cjs +0 -457
  220. package/dist/commands/repair-session.d.cts +0 -38
  221. package/dist/commands/replay.cjs +0 -4103
  222. package/dist/commands/replay.d.cts +0 -16
  223. package/dist/commands/session-recap.cjs +0 -353
  224. package/dist/commands/session-recap.d.cts +0 -27
  225. package/dist/commands/setup.cjs +0 -1278
  226. package/dist/commands/setup.d.cts +0 -99
  227. package/dist/commands/shell-init.cjs +0 -75
  228. package/dist/commands/shell-init.d.cts +0 -7
  229. package/dist/commands/sleep.cjs +0 -6029
  230. package/dist/commands/sleep.d.cts +0 -36
  231. package/dist/commands/status.cjs +0 -2737
  232. package/dist/commands/status.d.cts +0 -52
  233. package/dist/commands/task.cjs +0 -1236
  234. package/dist/commands/task.d.cts +0 -97
  235. package/dist/commands/template.cjs +0 -457
  236. package/dist/commands/template.d.cts +0 -36
  237. package/dist/commands/wake.cjs +0 -2627
  238. package/dist/commands/wake.d.cts +0 -22
  239. package/dist/context-BUGaWpyL.d.cts +0 -46
  240. package/dist/index.cjs +0 -12373
  241. package/dist/index.d.cts +0 -854
  242. package/dist/inject-Bzi5E-By.d.cts +0 -137
  243. package/dist/lib/auto-linker.cjs +0 -176
  244. package/dist/lib/auto-linker.d.cts +0 -26
  245. package/dist/lib/config.cjs +0 -78
  246. package/dist/lib/config.d.cts +0 -11
  247. package/dist/lib/entity-index.cjs +0 -84
  248. package/dist/lib/entity-index.d.cts +0 -26
  249. package/dist/lib/project-utils.cjs +0 -864
  250. package/dist/lib/project-utils.d.cts +0 -97
  251. package/dist/lib/session-repair.cjs +0 -239
  252. package/dist/lib/session-repair.d.cts +0 -110
  253. package/dist/lib/session-utils.cjs +0 -209
  254. package/dist/lib/session-utils.d.cts +0 -63
  255. package/dist/lib/task-utils.cjs +0 -1137
  256. package/dist/lib/task-utils.d.cts +0 -208
  257. package/dist/lib/template-engine.cjs +0 -47
  258. package/dist/lib/template-engine.d.cts +0 -11
  259. package/dist/plugin/index.cjs +0 -1907
  260. package/dist/plugin/index.d.cts +0 -36
  261. package/dist/plugin/index.d.ts +0 -36
  262. package/dist/plugin/index.js +0 -572
  263. package/dist/plugin/inject.cjs +0 -356
  264. package/dist/plugin/inject.d.cts +0 -54
  265. package/dist/plugin/inject.d.ts +0 -54
  266. package/dist/plugin/inject.js +0 -17
  267. package/dist/plugin/observe.cjs +0 -631
  268. package/dist/plugin/observe.d.cts +0 -39
  269. package/dist/plugin/observe.d.ts +0 -39
  270. package/dist/plugin/observe.js +0 -18
  271. package/dist/plugin/templates.cjs +0 -593
  272. package/dist/plugin/templates.d.cts +0 -52
  273. package/dist/plugin/templates.d.ts +0 -52
  274. package/dist/plugin/templates.js +0 -25
  275. package/dist/plugin/types.cjs +0 -18
  276. package/dist/plugin/types.d.cts +0 -209
  277. package/dist/plugin/types.d.ts +0 -209
  278. package/dist/plugin/types.js +0 -0
  279. package/dist/plugin/vault.cjs +0 -927
  280. package/dist/plugin/vault.d.cts +0 -68
  281. package/dist/plugin/vault.d.ts +0 -68
  282. package/dist/plugin/vault.js +0 -22
  283. package/dist/types-Y2_Um2Ls.d.cts +0 -205
  284. package/templates/memory-event.md +0 -67
  285. package/templates/party.md +0 -63
  286. package/templates/primitive-registry.yaml +0 -551
  287. package/templates/run.md +0 -68
  288. package/templates/trigger.md +0 -68
  289. package/templates/workspace.md +0 -50
@@ -1,1137 +0,0 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
11
- };
12
- var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
- }
18
- return to;
19
- };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
-
30
- // src/lib/task-utils.ts
31
- var task_utils_exports = {};
32
- __export(task_utils_exports, {
33
- completeTask: () => completeTask,
34
- createBacklogItem: () => createBacklogItem,
35
- createTask: () => createTask,
36
- ensureBacklogDir: () => ensureBacklogDir,
37
- ensureTasksDir: () => ensureTasksDir,
38
- getActiveTasks: () => getActiveTasks,
39
- getBacklogDir: () => getBacklogDir,
40
- getBacklogPath: () => getBacklogPath,
41
- getBlockedTasks: () => getBlockedTasks,
42
- getRecentlyCompletedTasks: () => getRecentlyCompletedTasks,
43
- getStatusDisplay: () => getStatusDisplay,
44
- getStatusIcon: () => getStatusIcon,
45
- getTaskPath: () => getTaskPath,
46
- getTasksDir: () => getTasksDir,
47
- listBacklogItems: () => listBacklogItems,
48
- listDependentTasks: () => listDependentTasks,
49
- listSubtasks: () => listSubtasks,
50
- listTasks: () => listTasks,
51
- promoteBacklogItem: () => promoteBacklogItem,
52
- readBacklogItem: () => readBacklogItem,
53
- readTask: () => readTask,
54
- slugify: () => slugify,
55
- updateBacklogItem: () => updateBacklogItem,
56
- updateTask: () => updateTask
57
- });
58
- module.exports = __toCommonJS(task_utils_exports);
59
- var fs3 = __toESM(require("fs"), 1);
60
- var path3 = __toESM(require("path"), 1);
61
- var import_gray_matter2 = __toESM(require("gray-matter"), 1);
62
-
63
- // src/lib/transition-ledger.ts
64
- var fs = __toESM(require("fs"), 1);
65
- var path = __toESM(require("path"), 1);
66
- var REGRESSION_PAIRS = [
67
- ["done", "open"],
68
- ["done", "blocked"],
69
- ["in-progress", "blocked"]
70
- ];
71
- function isRegression(from, to) {
72
- return REGRESSION_PAIRS.some(([f, t]) => f === from && t === to);
73
- }
74
- function getLedgerDir(vaultPath) {
75
- return path.join(path.resolve(vaultPath), "ledger", "transitions");
76
- }
77
- function getTodayLedgerPath(vaultPath) {
78
- const date = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
79
- return path.join(getLedgerDir(vaultPath), `${date}.jsonl`);
80
- }
81
- var RETRYABLE_APPEND_CODES = /* @__PURE__ */ new Set(["ENOENT", "EAGAIN", "EBUSY"]);
82
- var MAX_APPEND_RETRIES = 2;
83
- function asErrno(error) {
84
- if (!error || typeof error !== "object") {
85
- return null;
86
- }
87
- return error;
88
- }
89
- function formatLedgerWriteError(filePath, error) {
90
- const errno = asErrno(error);
91
- const message = error instanceof Error ? error.message : String(error);
92
- if (errno?.code === "ENOSPC") {
93
- return new Error(`Failed to write transition ledger at ${filePath}: no space left on device.`);
94
- }
95
- if (errno?.code === "EACCES" || errno?.code === "EPERM") {
96
- return new Error(`Failed to write transition ledger at ${filePath}: permission denied.`);
97
- }
98
- return new Error(`Failed to write transition ledger at ${filePath}: ${message}`);
99
- }
100
- function appendTransition(vaultPath, event) {
101
- const ledgerDir = getLedgerDir(vaultPath);
102
- try {
103
- fs.mkdirSync(ledgerDir, { recursive: true });
104
- } catch (error) {
105
- throw formatLedgerWriteError(ledgerDir, error);
106
- }
107
- const filePath = getTodayLedgerPath(vaultPath);
108
- const payload = JSON.stringify(event) + "\n";
109
- for (let attempt = 0; attempt <= MAX_APPEND_RETRIES; attempt += 1) {
110
- try {
111
- fs.appendFileSync(filePath, payload);
112
- return;
113
- } catch (error) {
114
- const errno = asErrno(error);
115
- const code = errno?.code;
116
- if (code === "ENOENT") {
117
- try {
118
- fs.mkdirSync(ledgerDir, { recursive: true });
119
- } catch (mkdirError) {
120
- throw formatLedgerWriteError(filePath, mkdirError);
121
- }
122
- }
123
- if (code && RETRYABLE_APPEND_CODES.has(code) && attempt < MAX_APPEND_RETRIES) {
124
- continue;
125
- }
126
- throw formatLedgerWriteError(filePath, error);
127
- }
128
- }
129
- }
130
- function buildTransitionEvent(taskId, fromStatus, toStatus, options = {}) {
131
- const agentId = process.env.OPENCLAW_AGENT_ID || "manual";
132
- const costTokensRaw = process.env.OPENCLAW_TOKEN_ESTIMATE;
133
- const costTokens = costTokensRaw ? parseInt(costTokensRaw, 10) : null;
134
- return {
135
- task_id: taskId,
136
- agent_id: agentId,
137
- from_status: fromStatus,
138
- to_status: toStatus,
139
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
140
- confidence: options.confidence ?? (agentId === "manual" ? 1 : 1),
141
- cost_tokens: costTokens !== null && !isNaN(costTokens) ? costTokens : null,
142
- reason: options.reason || null
143
- };
144
- }
145
- function readAllTransitions(vaultPath) {
146
- const ledgerDir = getLedgerDir(vaultPath);
147
- if (!fs.existsSync(ledgerDir)) return [];
148
- let files = [];
149
- try {
150
- files = fs.readdirSync(ledgerDir).filter((f) => f.endsWith(".jsonl")).sort();
151
- } catch {
152
- return [];
153
- }
154
- const events = [];
155
- for (const file of files) {
156
- let lines = [];
157
- try {
158
- lines = fs.readFileSync(path.join(ledgerDir, file), "utf-8").split("\n").filter((l) => l.trim());
159
- } catch {
160
- continue;
161
- }
162
- for (const line of lines) {
163
- try {
164
- events.push(JSON.parse(line));
165
- } catch {
166
- }
167
- }
168
- }
169
- return events;
170
- }
171
- function countBlockedTransitions(vaultPath, taskId) {
172
- const events = readAllTransitions(vaultPath);
173
- return events.filter((e) => e.task_id === taskId && e.to_status === "blocked").length;
174
- }
175
-
176
- // src/lib/primitive-templates.ts
177
- var fs2 = __toESM(require("fs"), 1);
178
- var path2 = __toESM(require("path"), 1);
179
- var import_url = require("url");
180
- var import_gray_matter = __toESM(require("gray-matter"), 1);
181
-
182
- // src/lib/template-engine.ts
183
- function buildTemplateVariables(input = {}, now = /* @__PURE__ */ new Date()) {
184
- const datetime = input.datetime ?? now.toISOString();
185
- const date = input.date ?? datetime.split("T")[0];
186
- return {
187
- title: input.title ?? "",
188
- type: input.type ?? "",
189
- date,
190
- datetime
191
- };
192
- }
193
- function renderTemplate(template, variables) {
194
- return template.replace(/\{\{\s*([a-zA-Z0-9_-]+)\s*\}\}/g, (match, key) => {
195
- const value = variables[key];
196
- return value !== void 0 ? String(value) : match;
197
- });
198
- }
199
-
200
- // src/lib/primitive-templates.ts
201
- var import_meta = {};
202
- var TEMPLATE_EXTENSION = ".md";
203
- function isRecord(value) {
204
- return typeof value === "object" && value !== null && !Array.isArray(value);
205
- }
206
- function normalizeTemplateName(name) {
207
- const base = path2.basename(name, path2.extname(name));
208
- return base.trim();
209
- }
210
- function resolveBuiltinTemplatesDir(override) {
211
- if (override) {
212
- const resolved = path2.resolve(override);
213
- return fs2.existsSync(resolved) && fs2.statSync(resolved).isDirectory() ? resolved : null;
214
- }
215
- const moduleDir = path2.dirname((0, import_url.fileURLToPath)(import_meta.url));
216
- const candidates = [
217
- path2.resolve(moduleDir, "../templates"),
218
- path2.resolve(moduleDir, "../../templates")
219
- ];
220
- for (const candidate of candidates) {
221
- if (fs2.existsSync(candidate) && fs2.statSync(candidate).isDirectory()) {
222
- return candidate;
223
- }
224
- }
225
- return null;
226
- }
227
- function listTemplateFiles(dir, ignore) {
228
- const entries = /* @__PURE__ */ new Map();
229
- if (!fs2.existsSync(dir)) return entries;
230
- for (const entry of fs2.readdirSync(dir, { withFileTypes: true })) {
231
- if (!entry.isFile() || !entry.name.endsWith(TEMPLATE_EXTENSION)) continue;
232
- const name = normalizeTemplateName(entry.name);
233
- if (!name) continue;
234
- if (ignore?.has(name)) continue;
235
- entries.set(name, path2.join(dir, entry.name));
236
- }
237
- return entries;
238
- }
239
- function buildTemplateIndex(options = {}) {
240
- const index = /* @__PURE__ */ new Map();
241
- const builtinDir = resolveBuiltinTemplatesDir(options.builtinDir);
242
- if (builtinDir) {
243
- for (const [name, filePath] of listTemplateFiles(builtinDir, options.ignoreBuiltinNames)) {
244
- index.set(name, filePath);
245
- }
246
- }
247
- if (options.vaultPath) {
248
- const vaultTemplatesDir = path2.join(path2.resolve(options.vaultPath), "templates");
249
- for (const [name, filePath] of listTemplateFiles(vaultTemplatesDir)) {
250
- index.set(name, filePath);
251
- }
252
- }
253
- return index;
254
- }
255
- function inferFieldType(defaultValue) {
256
- if (Array.isArray(defaultValue)) {
257
- const uniqueItemTypes = [...new Set(defaultValue.map((value) => typeof value))];
258
- if (uniqueItemTypes.length === 1 && uniqueItemTypes[0] === "string") {
259
- return "string[]";
260
- }
261
- return "array";
262
- }
263
- switch (typeof defaultValue) {
264
- case "string":
265
- return "string";
266
- case "number":
267
- return "number";
268
- case "boolean":
269
- return "boolean";
270
- case "object":
271
- if (defaultValue === null) return "string";
272
- return "object";
273
- default:
274
- return "string";
275
- }
276
- }
277
- function normalizeFieldDefinition(rawField) {
278
- if (!isRecord(rawField)) {
279
- return {
280
- type: inferFieldType(rawField),
281
- default: rawField
282
- };
283
- }
284
- const rawType = typeof rawField.type === "string" ? rawField.type.trim() : "";
285
- const normalized = {
286
- type: rawType || inferFieldType(rawField.default)
287
- };
288
- if (typeof rawField.description === "string" && rawField.description.trim()) {
289
- normalized.description = rawField.description.trim();
290
- }
291
- if (typeof rawField.required === "boolean") {
292
- normalized.required = rawField.required;
293
- }
294
- if (Object.prototype.hasOwnProperty.call(rawField, "default")) {
295
- normalized.default = rawField.default;
296
- }
297
- if (Array.isArray(rawField.enum)) {
298
- normalized.enum = rawField.enum;
299
- }
300
- return normalized;
301
- }
302
- function normalizeFieldDefinitions(rawFields) {
303
- const normalized = {};
304
- for (const [fieldName, rawField] of Object.entries(rawFields)) {
305
- const normalizedName = String(fieldName).trim();
306
- if (!normalizedName) continue;
307
- normalized[normalizedName] = normalizeFieldDefinition(rawField);
308
- }
309
- return normalized;
310
- }
311
- function extractSchemaDefinition(frontmatter) {
312
- const primitive = typeof frontmatter.primitive === "string" ? frontmatter.primitive.trim() : "";
313
- const description = typeof frontmatter.description === "string" ? frontmatter.description.trim() : void 0;
314
- if (primitive && isRecord(frontmatter.fields)) {
315
- return {
316
- primitive,
317
- description,
318
- fields: frontmatter.fields
319
- };
320
- }
321
- const containerCandidates = [frontmatter.schema, frontmatter.template];
322
- for (const candidate of containerCandidates) {
323
- if (!isRecord(candidate)) continue;
324
- const nestedPrimitive = typeof candidate.primitive === "string" ? candidate.primitive.trim() : primitive;
325
- if (!nestedPrimitive || !isRecord(candidate.fields)) continue;
326
- const nestedDescription = typeof candidate.description === "string" ? candidate.description.trim() : description;
327
- return {
328
- primitive: nestedPrimitive,
329
- description: nestedDescription,
330
- fields: candidate.fields
331
- };
332
- }
333
- return null;
334
- }
335
- function inferLegacyFieldDefinitions(frontmatter) {
336
- const normalized = {};
337
- const ignoredKeys = /* @__PURE__ */ new Set(["primitive", "fields", "schema", "template"]);
338
- for (const [key, value] of Object.entries(frontmatter)) {
339
- if (ignoredKeys.has(key)) continue;
340
- normalized[key] = {
341
- type: inferFieldType(value),
342
- default: value
343
- };
344
- }
345
- return normalized;
346
- }
347
- function parseTemplateDefinition(rawTemplate, templateName, sourcePath) {
348
- const normalizedName = normalizeTemplateName(templateName);
349
- const { data, content } = (0, import_gray_matter.default)(rawTemplate);
350
- const frontmatter = isRecord(data) ? data : {};
351
- const extractedSchema = extractSchemaDefinition(frontmatter);
352
- if (extractedSchema) {
353
- return {
354
- name: normalizedName,
355
- primitive: extractedSchema.primitive,
356
- description: extractedSchema.description,
357
- fields: normalizeFieldDefinitions(extractedSchema.fields),
358
- body: content,
359
- format: "schema",
360
- sourcePath
361
- };
362
- }
363
- return {
364
- name: normalizedName,
365
- primitive: normalizedName,
366
- description: typeof frontmatter.description === "string" ? frontmatter.description.trim() : void 0,
367
- fields: inferLegacyFieldDefinitions(frontmatter),
368
- body: content,
369
- format: "legacy",
370
- sourcePath
371
- };
372
- }
373
- function readTemplateDefinitionFromPath(filePath, templateName) {
374
- try {
375
- const raw = fs2.readFileSync(filePath, "utf-8");
376
- return parseTemplateDefinition(raw, templateName, filePath);
377
- } catch {
378
- return null;
379
- }
380
- }
381
- function loadTemplateDefinition(templateName, options = {}) {
382
- const normalizedName = normalizeTemplateName(templateName);
383
- if (!normalizedName) return null;
384
- const index = buildTemplateIndex(options);
385
- const filePath = index.get(normalizedName);
386
- if (!filePath) return null;
387
- return readTemplateDefinitionFromPath(filePath, normalizedName);
388
- }
389
- function loadSchemaTemplateDefinition(templateName, options = {}) {
390
- const definition = loadTemplateDefinition(templateName, options);
391
- if (!definition || definition.format !== "schema") {
392
- return null;
393
- }
394
- return definition;
395
- }
396
- function resolveInterpolatedValue(value, variables) {
397
- if (typeof value === "string") {
398
- return renderTemplate(value, variables);
399
- }
400
- if (Array.isArray(value)) {
401
- return value.map((item) => resolveInterpolatedValue(item, variables));
402
- }
403
- if (isRecord(value)) {
404
- const resolved = {};
405
- for (const [key, nested] of Object.entries(value)) {
406
- resolved[key] = resolveInterpolatedValue(nested, variables);
407
- }
408
- return resolved;
409
- }
410
- return value;
411
- }
412
- function pruneFrontmatter(frontmatter, options) {
413
- const dropEmptyStrings = options.dropEmptyStrings ?? true;
414
- const dropEmptyArrays = options.dropEmptyArrays ?? true;
415
- const pruned = {};
416
- for (const [key, value] of Object.entries(frontmatter)) {
417
- if (value === void 0 || value === null) continue;
418
- if (dropEmptyStrings && typeof value === "string" && value.trim() === "") continue;
419
- if (dropEmptyArrays && Array.isArray(value) && value.length === 0) continue;
420
- pruned[key] = value;
421
- }
422
- return pruned;
423
- }
424
- function buildFrontmatterFromTemplate(definition, variables, overrides = {}, options = {}) {
425
- const frontmatter = {};
426
- for (const [fieldName, schema] of Object.entries(definition.fields)) {
427
- if (!Object.prototype.hasOwnProperty.call(schema, "default")) continue;
428
- frontmatter[fieldName] = resolveInterpolatedValue(schema.default, variables);
429
- }
430
- for (const [fieldName, value] of Object.entries(overrides)) {
431
- if (value === void 0) continue;
432
- if (value === null) {
433
- delete frontmatter[fieldName];
434
- continue;
435
- }
436
- frontmatter[fieldName] = value;
437
- }
438
- if (!options.pruneEmpty) {
439
- return frontmatter;
440
- }
441
- return pruneFrontmatter(frontmatter, options);
442
- }
443
- function renderDocumentFromTemplate(definition, options = {}) {
444
- const now = options.now ?? /* @__PURE__ */ new Date();
445
- const variables = {
446
- ...buildTemplateVariables(
447
- {
448
- title: options.title ?? "",
449
- type: options.type ?? definition.primitive
450
- },
451
- now
452
- ),
453
- ...options.variables ?? {}
454
- };
455
- const frontmatter = buildFrontmatterFromTemplate(
456
- definition,
457
- variables,
458
- options.overrides,
459
- options.frontmatter
460
- );
461
- const content = renderTemplate(definition.body, variables);
462
- const markdown = import_gray_matter.default.stringify(content, frontmatter);
463
- return {
464
- frontmatter,
465
- content,
466
- markdown,
467
- variables
468
- };
469
- }
470
-
471
- // src/lib/task-utils.ts
472
- function slugify(text) {
473
- return text.toLowerCase().replace(/[^\w\s-]/g, "").replace(/\s+/g, "-").replace(/-+/g, "-").replace(/^-+|-+$/g, "").trim();
474
- }
475
- function getTasksDir(vaultPath) {
476
- return path3.join(path3.resolve(vaultPath), "tasks");
477
- }
478
- function getBacklogDir(vaultPath) {
479
- return path3.join(path3.resolve(vaultPath), "backlog");
480
- }
481
- function ensureTasksDir(vaultPath) {
482
- const tasksDir = getTasksDir(vaultPath);
483
- if (!fs3.existsSync(tasksDir)) {
484
- fs3.mkdirSync(tasksDir, { recursive: true });
485
- }
486
- }
487
- function ensureBacklogDir(vaultPath) {
488
- const backlogDir = getBacklogDir(vaultPath);
489
- if (!fs3.existsSync(backlogDir)) {
490
- fs3.mkdirSync(backlogDir, { recursive: true });
491
- }
492
- }
493
- function getTaskPath(vaultPath, slug) {
494
- return path3.join(getTasksDir(vaultPath), `${slug}.md`);
495
- }
496
- function getBacklogPath(vaultPath, slug) {
497
- return path3.join(getBacklogDir(vaultPath), `${slug}.md`);
498
- }
499
- function extractTitle(content) {
500
- const match = content.match(/^#\s+(.+)$/m);
501
- return match ? match[1].trim() : "";
502
- }
503
- function parseDueDate(value) {
504
- if (!value) return null;
505
- const timestamp = Date.parse(value);
506
- if (Number.isNaN(timestamp)) return null;
507
- return timestamp;
508
- }
509
- function startOfToday() {
510
- const now = /* @__PURE__ */ new Date();
511
- return new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime();
512
- }
513
- function buildTaskFrontmatterFallback(now, options) {
514
- const frontmatter = {
515
- status: "open",
516
- created: now,
517
- updated: now
518
- };
519
- if (options.source) frontmatter.source = options.source;
520
- if (options.owner) frontmatter.owner = options.owner;
521
- if (options.project) frontmatter.project = options.project;
522
- if (options.priority) frontmatter.priority = options.priority;
523
- if (options.due) frontmatter.due = options.due;
524
- if (options.tags && options.tags.length > 0) frontmatter.tags = options.tags;
525
- if (options.description) frontmatter.description = options.description;
526
- if (options.estimate) frontmatter.estimate = options.estimate;
527
- if (options.parent) frontmatter.parent = options.parent;
528
- if (options.depends_on && options.depends_on.length > 0) frontmatter.depends_on = options.depends_on;
529
- return frontmatter;
530
- }
531
- function buildTaskContentFallback(title, options) {
532
- let content = `# ${title}
533
- `;
534
- const links = [];
535
- if (options.owner) links.push(`[[${options.owner}]]`);
536
- if (options.project) links.push(`[[${options.project}]]`);
537
- if (links.length > 0) {
538
- content += `
539
- ${links.join(" | ")}
540
- `;
541
- }
542
- if (options.content) {
543
- content += `
544
- ${options.content}
545
- `;
546
- }
547
- return content;
548
- }
549
- function buildTaskTemplateOverrides(options) {
550
- const overrides = {};
551
- if (options.source) overrides.source = options.source;
552
- if (options.owner) overrides.owner = options.owner;
553
- if (options.project) overrides.project = options.project;
554
- if (options.priority) overrides.priority = options.priority;
555
- if (options.due) overrides.due = options.due;
556
- if (options.tags && options.tags.length > 0) overrides.tags = options.tags;
557
- if (options.description) overrides.description = options.description;
558
- if (options.estimate) overrides.estimate = options.estimate;
559
- if (options.parent) overrides.parent = options.parent;
560
- if (options.depends_on && options.depends_on.length > 0) overrides.depends_on = options.depends_on;
561
- return overrides;
562
- }
563
- function buildTaskTemplateVariables(title, slug, options) {
564
- const ownerLink = options.owner ? `[[${options.owner}]]` : "";
565
- const projectLink = options.project ? `[[${options.project}]]` : "";
566
- const linksLine = [ownerLink, projectLink].filter(Boolean).join(" | ");
567
- return {
568
- title,
569
- slug,
570
- source: options.source ?? "",
571
- owner: options.owner ?? "",
572
- project: options.project ?? "",
573
- priority: options.priority ?? "",
574
- due: options.due ?? "",
575
- tags_csv: (options.tags || []).join(", "),
576
- description: options.description ?? "",
577
- estimate: options.estimate ?? "",
578
- parent: options.parent ?? "",
579
- depends_on_csv: (options.depends_on || []).join(", "),
580
- content: options.content ?? "",
581
- owner_link: ownerLink,
582
- project_link: projectLink,
583
- links_line: linksLine
584
- };
585
- }
586
- var VALID_TASK_STATUSES = /* @__PURE__ */ new Set([
587
- "open",
588
- "in-progress",
589
- "blocked",
590
- "done"
591
- ]);
592
- function isTaskStatus(value) {
593
- return typeof value === "string" && VALID_TASK_STATUSES.has(value);
594
- }
595
- function persistTaskFrontmatter(task, frontmatter) {
596
- fs3.writeFileSync(task.path, import_gray_matter2.default.stringify(task.content, frontmatter));
597
- }
598
- function resolveStatusTransition(previousStatus, nextStatus) {
599
- if (!isTaskStatus(previousStatus) || !isTaskStatus(nextStatus)) {
600
- return null;
601
- }
602
- if (previousStatus === nextStatus) {
603
- return null;
604
- }
605
- return { fromStatus: previousStatus, toStatus: nextStatus };
606
- }
607
- function logStatusTransition({
608
- vaultPath,
609
- task,
610
- fromStatus,
611
- toStatus,
612
- frontmatter,
613
- options
614
- }) {
615
- const normalizedReason = typeof options.reason === "string" ? options.reason.trim() : "";
616
- const reason = normalizedReason || (isRegression(fromStatus, toStatus) ? `regression: ${fromStatus} -> ${toStatus}` : void 0);
617
- const event = buildTransitionEvent(task.slug, fromStatus, toStatus, {
618
- confidence: options.confidence,
619
- reason
620
- });
621
- try {
622
- appendTransition(vaultPath, event);
623
- } catch {
624
- return frontmatter;
625
- }
626
- if (toStatus !== "blocked" || frontmatter.escalation) {
627
- return frontmatter;
628
- }
629
- let blockedCount = 0;
630
- try {
631
- blockedCount = countBlockedTransitions(vaultPath, task.slug);
632
- } catch {
633
- return frontmatter;
634
- }
635
- if (blockedCount < 3) {
636
- return frontmatter;
637
- }
638
- const escalatedFrontmatter = {
639
- ...frontmatter,
640
- escalation: true
641
- };
642
- try {
643
- persistTaskFrontmatter(task, escalatedFrontmatter);
644
- return escalatedFrontmatter;
645
- } catch {
646
- return frontmatter;
647
- }
648
- }
649
- function readTask(vaultPath, slug) {
650
- const taskPath = getTaskPath(vaultPath, slug);
651
- if (!fs3.existsSync(taskPath)) {
652
- return null;
653
- }
654
- try {
655
- const raw = fs3.readFileSync(taskPath, "utf-8");
656
- const { data, content } = (0, import_gray_matter2.default)(raw);
657
- const title = extractTitle(content) || slug;
658
- return {
659
- slug,
660
- title,
661
- content,
662
- frontmatter: data,
663
- path: taskPath
664
- };
665
- } catch {
666
- return null;
667
- }
668
- }
669
- function readBacklogItem(vaultPath, slug) {
670
- const backlogPath = getBacklogPath(vaultPath, slug);
671
- if (!fs3.existsSync(backlogPath)) {
672
- return null;
673
- }
674
- try {
675
- const raw = fs3.readFileSync(backlogPath, "utf-8");
676
- const { data, content } = (0, import_gray_matter2.default)(raw);
677
- const title = extractTitle(content) || slug;
678
- return {
679
- slug,
680
- title,
681
- content,
682
- frontmatter: data,
683
- path: backlogPath
684
- };
685
- } catch {
686
- return null;
687
- }
688
- }
689
- function listTasks(vaultPath, filters) {
690
- const tasksDir = getTasksDir(vaultPath);
691
- if (!fs3.existsSync(tasksDir)) {
692
- return [];
693
- }
694
- const tasks = [];
695
- const entries = fs3.readdirSync(tasksDir, { withFileTypes: true });
696
- const today = startOfToday();
697
- for (const entry of entries) {
698
- if (!entry.isFile() || !entry.name.endsWith(".md")) {
699
- continue;
700
- }
701
- const slug = entry.name.replace(/\.md$/, "");
702
- const task = readTask(vaultPath, slug);
703
- if (!task) continue;
704
- if (filters) {
705
- if (filters.status && task.frontmatter.status !== filters.status) continue;
706
- if (filters.owner && task.frontmatter.owner !== filters.owner) continue;
707
- if (filters.project && task.frontmatter.project !== filters.project) continue;
708
- if (filters.priority && task.frontmatter.priority !== filters.priority) continue;
709
- if (filters.due && !task.frontmatter.due) continue;
710
- if (filters.tag) {
711
- const tags = task.frontmatter.tags || [];
712
- const hasTag = tags.some((tag) => tag.toLowerCase() === filters.tag?.toLowerCase());
713
- if (!hasTag) continue;
714
- }
715
- if (filters.overdue) {
716
- const dueTime = parseDueDate(task.frontmatter.due);
717
- if (task.frontmatter.status === "done" || dueTime === null || dueTime >= today) continue;
718
- }
719
- }
720
- tasks.push(task);
721
- }
722
- const priorityOrder = {
723
- critical: 0,
724
- high: 1,
725
- medium: 2,
726
- low: 3
727
- };
728
- if (filters?.due || filters?.overdue) {
729
- return tasks.sort((a, b) => {
730
- const aDue = parseDueDate(a.frontmatter.due);
731
- const bDue = parseDueDate(b.frontmatter.due);
732
- if (aDue !== null && bDue !== null && aDue !== bDue) {
733
- return aDue - bDue;
734
- }
735
- if (aDue !== null && bDue === null) return -1;
736
- if (aDue === null && bDue !== null) return 1;
737
- return new Date(b.frontmatter.created).getTime() - new Date(a.frontmatter.created).getTime();
738
- });
739
- }
740
- return tasks.sort((a, b) => {
741
- const aPriority = priorityOrder[a.frontmatter.priority || "low"];
742
- const bPriority = priorityOrder[b.frontmatter.priority || "low"];
743
- if (aPriority !== bPriority) {
744
- return aPriority - bPriority;
745
- }
746
- return new Date(b.frontmatter.created).getTime() - new Date(a.frontmatter.created).getTime();
747
- });
748
- }
749
- function listBacklogItems(vaultPath, filters) {
750
- const backlogDir = getBacklogDir(vaultPath);
751
- if (!fs3.existsSync(backlogDir)) {
752
- return [];
753
- }
754
- const items = [];
755
- const entries = fs3.readdirSync(backlogDir, { withFileTypes: true });
756
- for (const entry of entries) {
757
- if (!entry.isFile() || !entry.name.endsWith(".md")) {
758
- continue;
759
- }
760
- const slug = entry.name.replace(/\.md$/, "");
761
- const item = readBacklogItem(vaultPath, slug);
762
- if (!item) continue;
763
- if (filters) {
764
- if (filters.project && item.frontmatter.project !== filters.project) continue;
765
- if (filters.source && item.frontmatter.source !== filters.source) continue;
766
- }
767
- items.push(item);
768
- }
769
- return items.sort((a, b) => {
770
- return new Date(b.frontmatter.created).getTime() - new Date(a.frontmatter.created).getTime();
771
- });
772
- }
773
- function createTask(vaultPath, title, options = {}) {
774
- ensureTasksDir(vaultPath);
775
- const slug = slugify(title);
776
- const taskPath = getTaskPath(vaultPath, slug);
777
- if (fs3.existsSync(taskPath)) {
778
- throw new Error(`Task already exists: ${slug}`);
779
- }
780
- const now = (/* @__PURE__ */ new Date()).toISOString();
781
- const template = loadSchemaTemplateDefinition("task", {
782
- vaultPath: path3.resolve(vaultPath)
783
- });
784
- let frontmatter;
785
- let content;
786
- if (template) {
787
- const rendered = renderDocumentFromTemplate(template, {
788
- title,
789
- type: "task",
790
- now: new Date(now),
791
- variables: buildTaskTemplateVariables(title, slug, options),
792
- overrides: buildTaskTemplateOverrides(options),
793
- frontmatter: { pruneEmpty: true }
794
- });
795
- const templateFrontmatter = rendered.frontmatter;
796
- frontmatter = {
797
- ...templateFrontmatter,
798
- status: isTaskStatus(templateFrontmatter.status) ? templateFrontmatter.status : "open",
799
- created: typeof templateFrontmatter.created === "string" && templateFrontmatter.created ? templateFrontmatter.created : now,
800
- updated: typeof templateFrontmatter.updated === "string" && templateFrontmatter.updated ? templateFrontmatter.updated : now
801
- };
802
- content = rendered.content;
803
- } else {
804
- frontmatter = buildTaskFrontmatterFallback(now, options);
805
- content = buildTaskContentFallback(title, options);
806
- }
807
- const fileContent = import_gray_matter2.default.stringify(content, frontmatter);
808
- fs3.writeFileSync(taskPath, fileContent);
809
- return {
810
- slug,
811
- title,
812
- content,
813
- frontmatter,
814
- path: taskPath
815
- };
816
- }
817
- function updateTask(vaultPath, slug, updates, options = {}) {
818
- const task = readTask(vaultPath, slug);
819
- if (!task) {
820
- throw new Error(`Task not found: ${slug}`);
821
- }
822
- if (updates.status !== void 0 && !isTaskStatus(updates.status)) {
823
- throw new Error(`Invalid task status: ${String(updates.status)}`);
824
- }
825
- const previousStatus = task.frontmatter.status;
826
- const now = (/* @__PURE__ */ new Date()).toISOString();
827
- let newFrontmatter = {
828
- ...task.frontmatter,
829
- updated: now
830
- };
831
- if (updates.status !== void 0) {
832
- newFrontmatter.status = updates.status;
833
- if (updates.status === "done" && !newFrontmatter.completed) {
834
- newFrontmatter.completed = now;
835
- }
836
- if (updates.status !== "done") {
837
- delete newFrontmatter.completed;
838
- }
839
- }
840
- if (updates.source !== void 0) {
841
- if (updates.source === null || updates.source.trim() === "") {
842
- delete newFrontmatter.source;
843
- } else {
844
- newFrontmatter.source = updates.source;
845
- }
846
- }
847
- if (updates.owner !== void 0) {
848
- if (updates.owner === null || updates.owner.trim() === "") {
849
- delete newFrontmatter.owner;
850
- } else {
851
- newFrontmatter.owner = updates.owner;
852
- }
853
- }
854
- if (updates.project !== void 0) {
855
- if (updates.project === null || updates.project.trim() === "") {
856
- delete newFrontmatter.project;
857
- } else {
858
- newFrontmatter.project = updates.project;
859
- }
860
- }
861
- if (updates.priority !== void 0) {
862
- if (updates.priority === null) {
863
- delete newFrontmatter.priority;
864
- } else {
865
- newFrontmatter.priority = updates.priority;
866
- }
867
- }
868
- if (updates.due !== void 0) {
869
- if (updates.due === null || updates.due.trim() === "") {
870
- delete newFrontmatter.due;
871
- } else {
872
- newFrontmatter.due = updates.due;
873
- }
874
- }
875
- if (updates.tags !== void 0) {
876
- if (updates.tags === null) {
877
- delete newFrontmatter.tags;
878
- } else {
879
- const normalizedTags = updates.tags.map((tag) => tag.trim()).filter(Boolean);
880
- if (normalizedTags.length === 0) {
881
- delete newFrontmatter.tags;
882
- } else {
883
- newFrontmatter.tags = normalizedTags;
884
- }
885
- }
886
- }
887
- if (updates.completed !== void 0) {
888
- if (updates.completed === null || updates.completed.trim() === "") {
889
- delete newFrontmatter.completed;
890
- } else {
891
- newFrontmatter.completed = updates.completed;
892
- }
893
- }
894
- if (updates.escalation !== void 0) {
895
- if (updates.escalation === null) {
896
- delete newFrontmatter.escalation;
897
- } else {
898
- newFrontmatter.escalation = updates.escalation;
899
- }
900
- }
901
- if (updates.confidence !== void 0) {
902
- if (updates.confidence === null) {
903
- delete newFrontmatter.confidence;
904
- } else {
905
- newFrontmatter.confidence = updates.confidence;
906
- }
907
- }
908
- if (updates.reason !== void 0) {
909
- if (updates.reason === null || updates.reason.trim() === "") {
910
- delete newFrontmatter.reason;
911
- } else {
912
- newFrontmatter.reason = updates.reason;
913
- }
914
- }
915
- if (updates.description !== void 0) {
916
- if (updates.description === null || updates.description.trim() === "") {
917
- delete newFrontmatter.description;
918
- } else {
919
- newFrontmatter.description = updates.description;
920
- }
921
- }
922
- if (updates.estimate !== void 0) {
923
- if (updates.estimate === null || updates.estimate.trim() === "") {
924
- delete newFrontmatter.estimate;
925
- } else {
926
- newFrontmatter.estimate = updates.estimate;
927
- }
928
- }
929
- if (updates.parent !== void 0) {
930
- if (updates.parent === null || updates.parent.trim() === "") {
931
- delete newFrontmatter.parent;
932
- } else {
933
- newFrontmatter.parent = updates.parent;
934
- }
935
- }
936
- if (updates.depends_on !== void 0) {
937
- if (updates.depends_on === null) {
938
- delete newFrontmatter.depends_on;
939
- } else {
940
- const normalizedDeps = updates.depends_on.map((dep) => dep.trim()).filter(Boolean);
941
- if (normalizedDeps.length === 0) {
942
- delete newFrontmatter.depends_on;
943
- } else {
944
- newFrontmatter.depends_on = normalizedDeps;
945
- }
946
- }
947
- }
948
- if (updates.blocked_by !== void 0) {
949
- if (updates.blocked_by === null || updates.blocked_by.trim() === "") {
950
- delete newFrontmatter.blocked_by;
951
- } else {
952
- newFrontmatter.blocked_by = updates.blocked_by;
953
- }
954
- } else if (updates.status !== void 0 && updates.status !== "blocked") {
955
- delete newFrontmatter.blocked_by;
956
- }
957
- persistTaskFrontmatter(task, newFrontmatter);
958
- const transition = options.skipTransition ? null : resolveStatusTransition(previousStatus, newFrontmatter.status);
959
- if (transition) {
960
- const confidence = options.confidence ?? (typeof updates.confidence === "number" ? updates.confidence : void 0);
961
- const reason = options.reason ?? updates.reason ?? null;
962
- newFrontmatter = logStatusTransition({
963
- vaultPath,
964
- task,
965
- fromStatus: transition.fromStatus,
966
- toStatus: transition.toStatus,
967
- frontmatter: newFrontmatter,
968
- options: {
969
- confidence,
970
- reason
971
- }
972
- });
973
- }
974
- return {
975
- ...task,
976
- frontmatter: newFrontmatter
977
- };
978
- }
979
- function completeTask(vaultPath, slug, options = {}) {
980
- return updateTask(vaultPath, slug, { status: "done" }, options);
981
- }
982
- function createBacklogItem(vaultPath, title, options = {}) {
983
- ensureBacklogDir(vaultPath);
984
- const slug = slugify(title);
985
- const backlogPath = getBacklogPath(vaultPath, slug);
986
- if (fs3.existsSync(backlogPath)) {
987
- throw new Error(`Backlog item already exists: ${slug}`);
988
- }
989
- const now = (/* @__PURE__ */ new Date()).toISOString();
990
- const frontmatter = {
991
- created: now
992
- };
993
- if (options.source) frontmatter.source = options.source;
994
- if (options.project) frontmatter.project = options.project;
995
- if (options.tags && options.tags.length > 0) frontmatter.tags = options.tags;
996
- let content = `# ${title}
997
- `;
998
- const links = [];
999
- if (options.source) links.push(`[[${options.source}]]`);
1000
- if (options.project) links.push(`[[${options.project}]]`);
1001
- if (links.length > 0) {
1002
- content += `
1003
- ${links.join(" | ")}
1004
- `;
1005
- }
1006
- if (options.content) {
1007
- content += `
1008
- ${options.content}
1009
- `;
1010
- }
1011
- const fileContent = import_gray_matter2.default.stringify(content, frontmatter);
1012
- fs3.writeFileSync(backlogPath, fileContent);
1013
- return {
1014
- slug,
1015
- title,
1016
- content,
1017
- frontmatter,
1018
- path: backlogPath
1019
- };
1020
- }
1021
- function updateBacklogItem(vaultPath, slug, updates) {
1022
- const backlogItem = readBacklogItem(vaultPath, slug);
1023
- if (!backlogItem) {
1024
- throw new Error(`Backlog item not found: ${slug}`);
1025
- }
1026
- const newFrontmatter = {
1027
- ...backlogItem.frontmatter
1028
- };
1029
- if (updates.source !== void 0) newFrontmatter.source = updates.source;
1030
- if (updates.project !== void 0) newFrontmatter.project = updates.project;
1031
- if (updates.tags !== void 0) newFrontmatter.tags = updates.tags;
1032
- if (updates.lastSeen !== void 0) newFrontmatter.lastSeen = updates.lastSeen;
1033
- const fileContent = import_gray_matter2.default.stringify(backlogItem.content, newFrontmatter);
1034
- fs3.writeFileSync(backlogItem.path, fileContent);
1035
- return {
1036
- ...backlogItem,
1037
- frontmatter: newFrontmatter
1038
- };
1039
- }
1040
- function promoteBacklogItem(vaultPath, slug, options = {}) {
1041
- const backlogItem = readBacklogItem(vaultPath, slug);
1042
- if (!backlogItem) {
1043
- throw new Error(`Backlog item not found: ${slug}`);
1044
- }
1045
- const task = createTask(vaultPath, backlogItem.title, {
1046
- owner: options.owner,
1047
- project: backlogItem.frontmatter.project,
1048
- priority: options.priority,
1049
- due: options.due,
1050
- content: backlogItem.content.replace(/^#\s+.+\n/, "").trim(),
1051
- // Remove title from content
1052
- tags: backlogItem.frontmatter.tags
1053
- });
1054
- fs3.unlinkSync(backlogItem.path);
1055
- return task;
1056
- }
1057
- function getBlockedTasks(vaultPath, project) {
1058
- const filters = { status: "blocked" };
1059
- if (project) filters.project = project;
1060
- return listTasks(vaultPath, filters);
1061
- }
1062
- function getActiveTasks(vaultPath, filters) {
1063
- const allTasks = listTasks(vaultPath, filters);
1064
- return allTasks.filter((t) => t.frontmatter.status === "open" || t.frontmatter.status === "in-progress");
1065
- }
1066
- function listSubtasks(vaultPath, parentSlug) {
1067
- return listTasks(vaultPath).filter((task) => task.frontmatter.parent === parentSlug);
1068
- }
1069
- function listDependentTasks(vaultPath, dependencySlug) {
1070
- return listTasks(vaultPath).filter((task) => {
1071
- const dependencies = task.frontmatter.depends_on || [];
1072
- return dependencies.includes(dependencySlug);
1073
- });
1074
- }
1075
- function getRecentlyCompletedTasks(vaultPath, limit = 10) {
1076
- const allTasks = listTasks(vaultPath, { status: "done" });
1077
- return allTasks.filter((t) => t.frontmatter.completed).sort((a, b) => {
1078
- const aCompleted = new Date(a.frontmatter.completed || 0).getTime();
1079
- const bCompleted = new Date(b.frontmatter.completed || 0).getTime();
1080
- return bCompleted - aCompleted;
1081
- }).slice(0, limit);
1082
- }
1083
- function getStatusIcon(status) {
1084
- switch (status) {
1085
- case "in-progress":
1086
- return "\u25CF";
1087
- case "blocked":
1088
- return "\u25A0";
1089
- case "open":
1090
- return "\u25CB";
1091
- case "done":
1092
- return "\u2713";
1093
- default:
1094
- return "\u25CB";
1095
- }
1096
- }
1097
- function getStatusDisplay(status) {
1098
- switch (status) {
1099
- case "in-progress":
1100
- return "active";
1101
- case "blocked":
1102
- return "blocked";
1103
- case "open":
1104
- return "open";
1105
- case "done":
1106
- return "done";
1107
- default:
1108
- return status;
1109
- }
1110
- }
1111
- // Annotate the CommonJS export names for ESM import in node:
1112
- 0 && (module.exports = {
1113
- completeTask,
1114
- createBacklogItem,
1115
- createTask,
1116
- ensureBacklogDir,
1117
- ensureTasksDir,
1118
- getActiveTasks,
1119
- getBacklogDir,
1120
- getBacklogPath,
1121
- getBlockedTasks,
1122
- getRecentlyCompletedTasks,
1123
- getStatusDisplay,
1124
- getStatusIcon,
1125
- getTaskPath,
1126
- getTasksDir,
1127
- listBacklogItems,
1128
- listDependentTasks,
1129
- listSubtasks,
1130
- listTasks,
1131
- promoteBacklogItem,
1132
- readBacklogItem,
1133
- readTask,
1134
- slugify,
1135
- updateBacklogItem,
1136
- updateTask
1137
- });