@wirecat/drive-cli 0.61.0 → 0.62.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 (148) hide show
  1. package/dist/bin/drive.js +2 -2
  2. package/dist/browse.d.ts +20 -0
  3. package/dist/browse.d.ts.map +1 -0
  4. package/dist/browse.js +146 -0
  5. package/dist/browse.js.map +1 -0
  6. package/dist/bundle/{all-profiles-H4L3Z5UM.js → all-profiles-CKD2DWUK.js} +14 -14
  7. package/dist/bundle/{anthropic-PPGFISVP.js → anthropic-E3T4USLA.js} +9 -9
  8. package/dist/bundle/{app-server-YXVK2FUZ.js → app-server-JB2AEWWL.js} +58 -55
  9. package/dist/bundle/{bun-DKZAL6ML.js → bun-CC44AAND.js} +2 -2
  10. package/dist/bundle/{bun-sqlite-MTZY36QK.js → bun-sqlite-AUMFKYVR.js} +8 -8
  11. package/dist/bundle/{chunk-KV4267S4.js → chunk-27YUUGXQ.js} +1 -1
  12. package/dist/bundle/{chunk-6IBM4Z3V.js → chunk-2HF2MRXI.js} +1 -1
  13. package/dist/bundle/{chunk-3I2D5TK2.js → chunk-2KN35F32.js} +10 -10
  14. package/dist/bundle/{chunk-WZ5XK74U.js → chunk-4OSSOWDM.js} +1 -1
  15. package/dist/bundle/{chunk-UO2IUDVK.js → chunk-4SIZEJ3M.js} +2 -2
  16. package/dist/bundle/{chunk-6Y2FWJZ4.js → chunk-67ZQCWBV.js} +3 -3
  17. package/dist/bundle/{chunk-OFFA54TW.js → chunk-6EY46GAN.js} +2 -2
  18. package/dist/bundle/{chunk-ECEYAQGN.js → chunk-7W5HYGVW.js} +4 -2
  19. package/dist/bundle/{chunk-67HS46KM.js → chunk-7ZXIWZQ6.js} +12 -12
  20. package/dist/bundle/{chunk-J5UDQD5S.js → chunk-AH5C3D3D.js} +5 -5
  21. package/dist/bundle/{chunk-BCWUDTYQ.js → chunk-AQVUEZEP.js} +2 -2
  22. package/dist/bundle/{chunk-K7LS3NGM.js → chunk-CJHY5YIF.js} +494 -227
  23. package/dist/bundle/{chunk-PY7LKNOS.js → chunk-CZ2GJHLL.js} +2 -2
  24. package/dist/bundle/{chunk-NIX2MWHZ.js → chunk-DJOAMGF4.js} +39 -25
  25. package/dist/bundle/{chunk-AWN22PJK.js → chunk-DRZZBN3V.js} +3 -3
  26. package/dist/bundle/{chunk-DEPMQHXQ.js → chunk-DWJHL6DV.js} +4 -4
  27. package/dist/bundle/{chunk-QSGT4ZH4.js → chunk-E43ENLJJ.js} +1 -1
  28. package/dist/bundle/{chunk-NZ2EIZLX.js → chunk-EOOGWUTP.js} +10 -10
  29. package/dist/bundle/{chunk-5W56YMQS.js → chunk-EW7PKB4M.js} +58 -49
  30. package/dist/bundle/{chunk-VYXVPYA3.js → chunk-FEZF3TII.js} +6 -6
  31. package/dist/bundle/{chunk-I26VL4W7.js → chunk-FNWIJ6EJ.js} +2 -2
  32. package/dist/bundle/{chunk-OLPJRD4S.js → chunk-FUITWY7O.js} +1 -1
  33. package/dist/bundle/{chunk-XZBR2O63.js → chunk-HCNQT3QE.js} +1439 -770
  34. package/dist/bundle/{chunk-Q4XVBKX4.js → chunk-HG6CAYJH.js} +3 -3
  35. package/dist/bundle/{chunk-O5CUFS7T.js → chunk-IR4SQLBR.js} +2 -2
  36. package/dist/bundle/{chunk-VPDAH7PJ.js → chunk-JK3U25QZ.js} +1 -1
  37. package/dist/bundle/{chunk-UKOYQC5O.js → chunk-JN5TVEEL.js} +94 -26
  38. package/dist/bundle/{chunk-5W7D5H2R.js → chunk-KLFSRKHB.js} +1 -1
  39. package/dist/bundle/{chunk-RFRCOAWS.js → chunk-L7K2MOIC.js} +22 -22
  40. package/dist/bundle/{chunk-XYCCGGKN.js → chunk-LQKD257P.js} +582 -424
  41. package/dist/bundle/{chunk-73WSULMI.js → chunk-LWE4JGRN.js} +2 -2
  42. package/dist/bundle/{chunk-XGMDWIUP.js → chunk-MN4VXU3M.js} +4 -4
  43. package/dist/bundle/{chunk-N2RLJTIW.js → chunk-N7OZPKU7.js} +4 -4
  44. package/dist/bundle/{chunk-OGNOQDWB.js → chunk-O2XOX4HB.js} +34 -10
  45. package/dist/bundle/{chunk-3SJQNS72.js → chunk-O7ALBI2I.js} +5 -5
  46. package/dist/bundle/{chunk-3WZH3WV3.js → chunk-OBH5BA62.js} +3 -3
  47. package/dist/bundle/{chunk-DCBFNBEB.js → chunk-OD4U7GUY.js} +20 -20
  48. package/dist/bundle/{chunk-PJTX2MOI.js → chunk-ONP2IBHY.js} +26 -26
  49. package/dist/bundle/{chunk-BXR7BKM3.js → chunk-OTROVC4E.js} +1 -1
  50. package/dist/bundle/{chunk-JVBLXSAA.js → chunk-PEQA6LA5.js} +617 -243
  51. package/dist/bundle/{chunk-XLFJLZJL.js → chunk-Q2LRPOKL.js} +22 -14
  52. package/dist/bundle/{chunk-E5EXJ2XS.js → chunk-QCKZ3GAA.js} +4 -4
  53. package/dist/bundle/{chunk-BQMIDYBA.js → chunk-QCX6XZLA.js} +12 -12
  54. package/dist/bundle/{chunk-TKGAYKXW.js → chunk-QH7DOVO3.js} +204 -58
  55. package/dist/bundle/{chunk-YMBFZA3H.js → chunk-QTI6IVHZ.js} +8 -8
  56. package/dist/bundle/{chunk-YWIU4HOT.js → chunk-R347FPYU.js} +1 -1
  57. package/dist/bundle/chunk-RIDQNVZM.js +64 -0
  58. package/dist/bundle/{chunk-AM4RIWOZ.js → chunk-RPMKG63Z.js} +18 -4
  59. package/dist/bundle/{chunk-EPCJUL6M.js → chunk-RWSXVCSG.js} +3 -3
  60. package/dist/bundle/{chunk-36CWGEVX.js → chunk-SVPCHFKI.js} +2 -2
  61. package/dist/bundle/{chunk-ZHYRHERD.js → chunk-SW4I5BR7.js} +2 -2
  62. package/dist/bundle/{chunk-FE5JJXKA.js → chunk-T5NWWXS2.js} +2 -2
  63. package/dist/bundle/{chunk-E6J5YH2N.js → chunk-T7X53FCJ.js} +34 -34
  64. package/dist/bundle/{chunk-X2CXW4HM.js → chunk-TDX4GZFO.js} +7 -7
  65. package/dist/bundle/{chunk-3UPIJ7DW.js → chunk-U2BFYSQV.js} +14158 -2039
  66. package/dist/bundle/{chunk-HFM653T3.js → chunk-UGXN5D7U.js} +719 -128
  67. package/dist/bundle/{chunk-WUP2MJDN.js → chunk-UOXOLGNG.js} +2 -2
  68. package/dist/bundle/{chunk-J4HQVHMN.js → chunk-UQLWMGSD.js} +5 -5
  69. package/dist/bundle/{chunk-6DN4VPA7.js → chunk-VAYB52HF.js} +33 -31
  70. package/dist/bundle/{chunk-BF6TQMNB.js → chunk-VQDD64A4.js} +8 -8
  71. package/dist/bundle/{chunk-ZMNYK3FC.js → chunk-W4RTIL7S.js} +5 -5
  72. package/dist/bundle/{chunk-HGOYQUT7.js → chunk-WZKEU7WR.js} +4 -2
  73. package/dist/bundle/{chunk-QR5VQXQ5.js → chunk-XEW2EN6F.js} +51 -37
  74. package/dist/bundle/{chunk-DXPOVLQC.js → chunk-XFRRKZHQ.js} +223 -89
  75. package/dist/bundle/{chunk-XGNC5OJG.js → chunk-XS5POQST.js} +1 -1
  76. package/dist/bundle/{chunk-LARQTWIL.js → chunk-XZUS7XRO.js} +1 -1
  77. package/dist/bundle/{chunk-6SUGANRJ.js → chunk-YALI4C7C.js} +6 -6
  78. package/dist/bundle/{chunk-WIU733D2.js → chunk-YMWENGKH.js} +1 -1
  79. package/dist/bundle/{chunk-CACYL36O.js → chunk-YOJDGAPT.js} +8 -8
  80. package/dist/bundle/{chunk-S4YK6TTG.js → chunk-YPFUYQDP.js} +13 -13
  81. package/dist/bundle/{chunk-3252WXOL.js → chunk-YUWPNG7B.js} +1 -1
  82. package/dist/bundle/{chunk-2RJA4BQB.js → chunk-YXYTY4GF.js} +39 -26
  83. package/dist/bundle/{chunk-YPF6OS37.js → chunk-ZMOUUOT2.js} +1 -1
  84. package/dist/bundle/command-contract-OB5BRABN.js +39 -0
  85. package/dist/bundle/{decode-62A3HGPW.js → decode-WIIX3Y2X.js} +8 -8
  86. package/dist/bundle/{dispatch-IE7PBEQC.js → dispatch-GEFIXA6X.js} +9 -9
  87. package/dist/bundle/drive.js +11 -11
  88. package/dist/bundle/{echarts-BGBPRGR5.js → echarts-OYINM4C4.js} +2 -2
  89. package/dist/bundle/{embed-J3IBVV2V.js → embed-DWZIYMBX.js} +9 -9
  90. package/dist/bundle/{embedder-QFPMDRT2.js → embedder-ILWH7ZRM.js} +12 -12
  91. package/dist/bundle/entry-V5V3TOTY.js +22 -0
  92. package/dist/bundle/{failure-BKOGBMIC.js → failure-GV77W3CD.js} +4 -4
  93. package/dist/bundle/first-run-V3VVLQF4.js +30 -0
  94. package/dist/bundle/first-screen-Y3RIN7FU.js +37 -0
  95. package/dist/bundle/{google-RXM2XEPD.js → google-KLZSUAVY.js} +13 -13
  96. package/dist/bundle/{google-api-NC65BZO4.js → google-api-HZQ5R4ZO.js} +57 -57
  97. package/dist/bundle/grants-L7XLHLUT.js +105 -0
  98. package/dist/bundle/{identity-PI6F2GWA.js → identity-J2DON4IO.js} +6 -6
  99. package/dist/bundle/{instructions-6LPDSKAD.js → instructions-HGOJ23AJ.js} +1 -1
  100. package/dist/bundle/{login-HTY7GT2S.js → login-BD2TS4GY.js} +63 -63
  101. package/dist/bundle/{mcp-PPVOM4SE.js → mcp-GWDA3HOA.js} +2 -2
  102. package/dist/bundle/{node-IB246NCQ.js → node-CPKTDPH7.js} +2 -2
  103. package/dist/bundle/{node-sqlite-G2Y5SFJM.js → node-sqlite-IXDCRLSX.js} +9 -9
  104. package/dist/bundle/oauth-HOGY4YBB.js +22 -0
  105. package/dist/bundle/{open-WD4GFSJD.js → open-O7P3ZV3Y.js} +8 -8
  106. package/dist/bundle/{openai-QVM4PMY7.js → openai-RCFQKCXC.js} +17 -17
  107. package/dist/bundle/{process-SWPJGPQC.js → process-KXDRJO22.js} +1 -1
  108. package/dist/bundle/{program-WHYFAMXR.js → program-UCHFC7JQ.js} +228 -85
  109. package/dist/bundle/prompt-EVPPBN5W.js +17 -0
  110. package/dist/bundle/{reasons-Q34DQWB6.js → reasons-57J2D77K.js} +5 -5
  111. package/dist/bundle/{recognize-DM3YWHSE.js → recognize-MRCYGP2J.js} +7 -7
  112. package/dist/bundle/{remote-KXVWRK7J.js → remote-L3L4PHKF.js} +10 -10
  113. package/dist/bundle/{rerank-TINXM3MY.js → rerank-PSOE6XFT.js} +10 -10
  114. package/dist/bundle/{serve-IY2WL656.js → serve-72OGS3BF.js} +12 -12
  115. package/dist/bundle/server-C5TGNFXW.js +70 -0
  116. package/dist/bundle/{server-VPY3OWPC.js → server-SCXKYHBO.js} +44 -44
  117. package/dist/bundle/{services-PXNBOCOC.js → services-YAFTELBI.js} +42 -32
  118. package/dist/bundle/{sqlite-runtime-5ZK2CV7Y.js → sqlite-runtime-DLK4SU33.js} +9 -9
  119. package/dist/bundle/{start-LDVCN3DK.js → start-AFFA3LKM.js} +9 -7
  120. package/dist/bundle/{state-3MKTT3VS.js → state-T5VNAJSZ.js} +9 -9
  121. package/dist/bundle/{store-7M4MSUJV.js → store-4OFK7PKQ.js} +48 -28
  122. package/dist/bundle/{store-4VQOT5IJ.js → store-R6MSY2IM.js} +20 -18
  123. package/dist/bundle/store-maintenance-command-QDMCXGV6.js +60 -0
  124. package/dist/bundle/tokens-HIG36RNS.js +103 -0
  125. package/dist/commands/folders.d.ts +2 -1
  126. package/dist/commands/folders.d.ts.map +1 -1
  127. package/dist/commands/folders.js +16 -3
  128. package/dist/commands/folders.js.map +1 -1
  129. package/dist/program.js +1 -1
  130. package/dist/program.js.map +1 -1
  131. package/dist/tokens.d.ts.map +1 -1
  132. package/dist/tokens.js +15 -6
  133. package/dist/tokens.js.map +1 -1
  134. package/dist/version.d.ts +1 -1
  135. package/dist/version.js +1 -1
  136. package/package.json +3 -3
  137. package/dist/bundle/chunk-W767AUNR.js +0 -132
  138. package/dist/bundle/command-contract-T3EO5AYD.js +0 -39
  139. package/dist/bundle/entry-YQSYER66.js +0 -22
  140. package/dist/bundle/first-run-ZIFPVZAI.js +0 -30
  141. package/dist/bundle/first-screen-L5U26EY7.js +0 -37
  142. package/dist/bundle/grants-SEWUYYH3.js +0 -105
  143. package/dist/bundle/oauth-MWBKBI4T.js +0 -22
  144. package/dist/bundle/prompt-OVYCGZB7.js +0 -17
  145. package/dist/bundle/server-EMWVVT2C.js +0 -70
  146. package/dist/bundle/store-maintenance-command-NRATYBWD.js +0 -60
  147. package/dist/bundle/tokens-XUKLM3SL.js +0 -103
  148. /package/dist/bundle/{chunk-LU3WKZBA.js → chunk-ZQ3GWKDQ.js} +0 -0
@@ -3,7 +3,7 @@ const require = __bundleRequire(import.meta.url);
3
3
  import {
4
4
  answerOf,
5
5
  messengerContext
6
- } from "./chunk-5W56YMQS.js";
6
+ } from "./chunk-EW7PKB4M.js";
7
7
  import {
8
8
  chatEventAnswer,
9
9
  memberAnswer,
@@ -12,7 +12,7 @@ import {
12
12
  serveRelay,
13
13
  typedQuery,
14
14
  withQuery
15
- } from "./chunk-2RJA4BQB.js";
15
+ } from "./chunk-YXYTY4GF.js";
16
16
  import {
17
17
  stringWidth,
18
18
  wrapAnsi
@@ -40,24 +40,24 @@ import {
40
40
  snakeKeys,
41
41
  storeTable,
42
42
  withoutProviderRefs
43
- } from "./chunk-JVBLXSAA.js";
43
+ } from "./chunk-PEQA6LA5.js";
44
44
  import {
45
45
  envName
46
- } from "./chunk-ECEYAQGN.js";
46
+ } from "./chunk-7W5HYGVW.js";
47
47
  import {
48
48
  holdLock,
49
49
  lockPath,
50
50
  releaseLock,
51
51
  servingProfiles,
52
52
  takeLock
53
- } from "./chunk-Q4XVBKX4.js";
53
+ } from "./chunk-HG6CAYJH.js";
54
54
  import {
55
55
  holdersOf
56
- } from "./chunk-WIU733D2.js";
56
+ } from "./chunk-YMWENGKH.js";
57
57
  import {
58
58
  checkedOptions,
59
59
  range
60
- } from "./chunk-AWN22PJK.js";
60
+ } from "./chunk-DRZZBN3V.js";
61
61
  import {
62
62
  FETCHING,
63
63
  RULES_VERSION,
@@ -69,29 +69,42 @@ import {
69
69
  patiently,
70
70
  senderIsMe,
71
71
  servicesFor,
72
- syncsOneChat
73
- } from "./chunk-XYCCGGKN.js";
72
+ syncsOneChat,
73
+ withTimeLimit
74
+ } from "./chunk-LQKD257P.js";
74
75
  import {
75
76
  codeOf,
76
77
  currentRun,
77
78
  levelFor,
78
79
  parseDuration
79
- } from "./chunk-6DN4VPA7.js";
80
+ } from "./chunk-VAYB52HF.js";
80
81
  import {
81
82
  failureKey
82
- } from "./chunk-BCWUDTYQ.js";
83
+ } from "./chunk-AQVUEZEP.js";
83
84
  import {
84
85
  messagesFor,
85
86
  systemFor,
86
87
  validateImages
87
- } from "./chunk-FE5JJXKA.js";
88
+ } from "./chunk-T5NWWXS2.js";
88
89
  import {
90
+ QUICK_HEALTH_CHECKS,
91
+ explainDamage,
92
+ fts5Tables,
93
+ invalidJson,
94
+ storeHealth
95
+ } from "./chunk-QH7DOVO3.js";
96
+ import {
97
+ CORPORA,
89
98
  MIGRATIONS,
99
+ drainCorpus,
100
+ drainMeetingIndex,
90
101
  drainNoteIndex,
91
102
  dropAllUnusedVectors,
92
103
  fileFacts,
93
104
  fillSearchIndex,
94
105
  fillStems,
106
+ fillTrigrams,
107
+ fillVectorIndexes,
95
108
  formatLocator,
96
109
  involvementStoreOver,
97
110
  migrate,
@@ -102,10 +115,12 @@ import {
102
115
  parseLocator,
103
116
  pendingNormalization,
104
117
  readStoreTables,
118
+ rebuildMentions,
105
119
  resetAttachmentWords,
106
120
  resetNoteIndex,
107
121
  resetSearchIndex,
108
122
  resetStems,
123
+ rollBack,
109
124
  rowCounts,
110
125
  searchIndexState,
111
126
  stemmerCache,
@@ -113,29 +128,29 @@ import {
113
128
  storeClients,
114
129
  storeContents,
115
130
  vectorIndexCounts
116
- } from "./chunk-3UPIJ7DW.js";
131
+ } from "./chunk-U2BFYSQV.js";
117
132
  import {
118
133
  queryFieldsOf
119
- } from "./chunk-NZ2EIZLX.js";
134
+ } from "./chunk-EOOGWUTP.js";
120
135
  import {
121
136
  storePath
122
- } from "./chunk-I26VL4W7.js";
137
+ } from "./chunk-FNWIJ6EJ.js";
123
138
  import {
124
139
  openCache
125
- } from "./chunk-6SUGANRJ.js";
140
+ } from "./chunk-YALI4C7C.js";
126
141
  import {
127
142
  readSecret
128
- } from "./chunk-EPCJUL6M.js";
143
+ } from "./chunk-RWSXVCSG.js";
129
144
  import {
130
145
  Credentials,
131
146
  pathsAreOverridden,
132
147
  resolvePaths,
133
148
  writeSecurely
134
- } from "./chunk-DCBFNBEB.js";
149
+ } from "./chunk-OD4U7GUY.js";
135
150
  import {
136
151
  singleLine,
137
152
  visibleControls
138
- } from "./chunk-6IBM4Z3V.js";
153
+ } from "./chunk-2HF2MRXI.js";
139
154
  import {
140
155
  array,
141
156
  boolean,
@@ -159,10 +174,10 @@ import {
159
174
  transform,
160
175
  trim,
161
176
  union
162
- } from "./chunk-VYXVPYA3.js";
177
+ } from "./chunk-FEZF3TII.js";
163
178
  import {
164
179
  CliError
165
- } from "./chunk-WZ5XK74U.js";
180
+ } from "./chunk-4OSSOWDM.js";
166
181
  import {
167
182
  __commonJS,
168
183
  __name,
@@ -1816,7 +1831,7 @@ var require_liquid_node = __commonJS({
1816
1831
  return readFileAsync(filepath, "utf8");
1817
1832
  }
1818
1833
  __name(readFile, "readFile");
1819
- function existsSync8(filepath) {
1834
+ function existsSync10(filepath) {
1820
1835
  try {
1821
1836
  fs$1.statSync(filepath);
1822
1837
  return true;
@@ -1824,11 +1839,11 @@ var require_liquid_node = __commonJS({
1824
1839
  return false;
1825
1840
  }
1826
1841
  }
1827
- __name(existsSync8, "existsSync");
1828
- function readFileSync4(filepath) {
1842
+ __name(existsSync10, "existsSync");
1843
+ function readFileSync5(filepath) {
1829
1844
  return fs$1.readFileSync(filepath, "utf8");
1830
1845
  }
1831
- __name(readFileSync4, "readFileSync");
1846
+ __name(readFileSync5, "readFileSync");
1832
1847
  function resolve2(root, file2, ext) {
1833
1848
  if (!path.extname(file2))
1834
1849
  file2 += ext;
@@ -1842,10 +1857,10 @@ var require_liquid_node = __commonJS({
1842
1857
  }
1843
1858
  }
1844
1859
  __name(fallback, "fallback");
1845
- function dirname2(filepath) {
1860
+ function dirname3(filepath) {
1846
1861
  return path.dirname(filepath);
1847
1862
  }
1848
- __name(dirname2, "dirname");
1863
+ __name(dirname3, "dirname");
1849
1864
  var realpathAsync = promisify(fs$1.realpath);
1850
1865
  async function contains(root, file2) {
1851
1866
  try {
@@ -1873,11 +1888,11 @@ var require_liquid_node = __commonJS({
1873
1888
  __proto__: null,
1874
1889
  exists,
1875
1890
  readFile,
1876
- existsSync: existsSync8,
1877
- readFileSync: readFileSync4,
1891
+ existsSync: existsSync10,
1892
+ readFileSync: readFileSync5,
1878
1893
  resolve: resolve2,
1879
1894
  fallback,
1880
- dirname: dirname2,
1895
+ dirname: dirname3,
1881
1896
  contains,
1882
1897
  containsSync,
1883
1898
  sep: path.sep
@@ -3602,7 +3617,7 @@ var require_liquid_node = __commonJS({
3602
3617
  uri_escape,
3603
3618
  slugify
3604
3619
  });
3605
- var join4 = argumentsToValue(function(v, arg) {
3620
+ var join5 = argumentsToValue(function(v, arg) {
3606
3621
  const array2 = toArray(v);
3607
3622
  const sep = isNil(arg) ? " " : stringify(arg);
3608
3623
  let outputSize = sep.length * Math.max(array2.length - 1, 0);
@@ -3878,7 +3893,7 @@ var require_liquid_node = __commonJS({
3878
3893
  __name(sample, "sample");
3879
3894
  var arrayFilters = /* @__PURE__ */ Object.freeze({
3880
3895
  __proto__: null,
3881
- join: join4,
3896
+ join: join5,
3882
3897
  last,
3883
3898
  first,
3884
3899
  reverse,
@@ -5502,11 +5517,11 @@ var require_liquid_node = __commonJS({
5502
5517
  }
5503
5518
  });
5504
5519
 
5505
- // node_modules/.pnpm/@wirecat+cli-core@0.566.0_@wirecat+cli-base@0.77.1_commander@15.0.0_esbuild@0.28.2_type_2c70ab84360472ff0036a7904a884c42/node_modules/@wirecat/cli-core/dist/cli/messenger/store-maintenance-command.js
5506
- import { chmodSync, constants, copyFileSync, existsSync as existsSync7, mkdirSync, realpathSync, renameSync as renameSync2, rmSync as rmSync2, statfsSync, statSync as statSync3, writeFileSync } from "node:fs";
5507
- import { dirname, resolve } from "node:path";
5520
+ // node_modules/.pnpm/@wirecat+cli-core@0.604.0_@wirecat+cli-base@0.80.9_commander@15.0.0_esbuild@0.28.2_type_4b96f151b4ca40121094ad166c695991/node_modules/@wirecat/cli-core/dist/cli/messenger/store-maintenance-command.js
5521
+ import { chmodSync, constants, copyFileSync, existsSync as existsSync9, mkdirSync, realpathSync as realpathSync2, renameSync as renameSync3, rmSync as rmSync3, statfsSync as statfsSync2, statSync as statSync4, writeFileSync as writeFileSync2 } from "node:fs";
5522
+ import { dirname as dirname2, resolve } from "node:path";
5508
5523
 
5509
- // node_modules/.pnpm/@wirecat+cli-core@0.566.0_@wirecat+cli-base@0.77.1_commander@15.0.0_esbuild@0.28.2_type_2c70ab84360472ff0036a7904a884c42/node_modules/@wirecat/cli-core/dist/sealed.js
5524
+ // node_modules/.pnpm/@wirecat+cli-core@0.604.0_@wirecat+cli-base@0.80.9_commander@15.0.0_esbuild@0.28.2_type_4b96f151b4ca40121094ad166c695991/node_modules/@wirecat/cli-core/dist/sealed.js
5510
5525
  import { createCipheriv, createDecipheriv, createHash, randomBytes, scrypt, timingSafeEqual } from "node:crypto";
5511
5526
  import { closeSync, createReadStream, createWriteStream, existsSync, openSync, readSync, renameSync, rmSync, statSync } from "node:fs";
5512
5527
  import { Transform } from "node:stream";
@@ -5613,7 +5628,7 @@ var unsealFile = /* @__PURE__ */ __name(async (from, to, password) => {
5613
5628
  renameSync(pending, to);
5614
5629
  }, "unsealFile");
5615
5630
 
5616
- // node_modules/.pnpm/@wirecat+cli-core@0.566.0_@wirecat+cli-base@0.77.1_commander@15.0.0_esbuild@0.28.2_type_2c70ab84360472ff0036a7904a884c42/node_modules/@wirecat/cli-core/dist/store/compatibility.js
5631
+ // node_modules/.pnpm/@wirecat+cli-core@0.604.0_@wirecat+cli-base@0.80.9_commander@15.0.0_esbuild@0.28.2_type_4b96f151b4ca40121094ad166c695991/node_modules/@wirecat/cli-core/dist/store/compatibility.js
5617
5632
  var SPEAKS = MIGRATIONS.at(-1)?.version ?? 0;
5618
5633
  var fileSchemaOf = /* @__PURE__ */ __name((database) => {
5619
5634
  const tracked = database.prepare("SELECT 1 FROM sqlite_master WHERE name = 'schema_migrations'").get();
@@ -5637,7 +5652,7 @@ var compatibilityOf = /* @__PURE__ */ __name((file2, migrations = MIGRATIONS) =>
5637
5652
  };
5638
5653
  }, "compatibilityOf");
5639
5654
 
5640
- // node_modules/.pnpm/@wirecat+cli-core@0.566.0_@wirecat+cli-base@0.77.1_commander@15.0.0_esbuild@0.28.2_type_2c70ab84360472ff0036a7904a884c42/node_modules/@wirecat/cli-core/dist/store/repair.js
5655
+ // node_modules/.pnpm/@wirecat+cli-core@0.604.0_@wirecat+cli-base@0.80.9_commander@15.0.0_esbuild@0.28.2_type_4b96f151b4ca40121094ad166c695991/node_modules/@wirecat/cli-core/dist/store/repair.js
5641
5656
  import { createHash as createHash2 } from "node:crypto";
5642
5657
  var COPY_MARK = "__repair_";
5643
5658
  var COPY_NAME = /__repair_[0-9a-f]{8}(_\d+)?$/;
@@ -5891,10 +5906,528 @@ var deleteCopy = /* @__PURE__ */ __name((database, name) => {
5891
5906
  return found;
5892
5907
  }, "deleteCopy");
5893
5908
 
5894
- // node_modules/.pnpm/@wirecat+cli-core@0.566.0_@wirecat+cli-base@0.77.1_commander@15.0.0_esbuild@0.28.2_type_2c70ab84360472ff0036a7904a884c42/node_modules/@wirecat/cli-core/dist/cli/store-info.js
5895
- import { existsSync as existsSync2, statSync as statSync2 } from "node:fs";
5909
+ // node_modules/.pnpm/@wirecat+cli-core@0.604.0_@wirecat+cli-base@0.80.9_commander@15.0.0_esbuild@0.28.2_type_4b96f151b4ca40121094ad166c695991/node_modules/@wirecat/cli-core/dist/cli/store-info.js
5910
+ import { existsSync as existsSync4, statSync as statSync3 } from "node:fs";
5911
+
5912
+ // node_modules/.pnpm/@wirecat+cli-core@0.604.0_@wirecat+cli-base@0.80.9_commander@15.0.0_esbuild@0.28.2_type_4b96f151b4ca40121094ad166c695991/node_modules/@wirecat/cli-core/dist/cli/store-recover.js
5913
+ import { existsSync as existsSync3 } from "node:fs";
5914
+
5915
+ // node_modules/.pnpm/@wirecat+cli-core@0.604.0_@wirecat+cli-base@0.80.9_commander@15.0.0_esbuild@0.28.2_type_4b96f151b4ca40121094ad166c695991/node_modules/@wirecat/cli-core/dist/store/recover.js
5916
+ import { execFileSync, spawn } from "node:child_process";
5917
+ import { existsSync as existsSync2, readFileSync, realpathSync, renameSync as renameSync2, rmSync as rmSync2, statfsSync, statSync as statSync2, writeFileSync } from "node:fs";
5918
+ import { basename, dirname, join } from "node:path";
5919
+ import { Transform as Transform2 } from "node:stream";
5920
+ var SQLITE3_MINIMUM = [3, 43, 0];
5921
+ var STORE_PARTS = ["", "-wal", "-shm"];
5922
+ var RECOVER_LOCK = ".recover-lock";
5923
+ var INSERTED = /^INSERT OR IGNORE INTO '([^']+)'/;
5924
+ var LOST_AND_FOUND = "recover_lost_and_found";
5925
+ var recovers = /* @__PURE__ */ __name((program) => {
5926
+ try {
5927
+ execFileSync(program, [":memory:", ".recover"], { stdio: ["ignore", "ignore", "pipe"] });
5928
+ return true;
5929
+ } catch {
5930
+ return false;
5931
+ }
5932
+ }, "recovers");
5933
+ var sqlite3Program = /* @__PURE__ */ __name((program = "sqlite3") => {
5934
+ let version = null;
5935
+ try {
5936
+ version = execFileSync(program, ["--version"], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).split(" ")[0] ?? null;
5937
+ } catch {
5938
+ return { program, version: null, usable: false };
5939
+ }
5940
+ const parts2 = (version ?? "").split(".").map(Number);
5941
+ const at = SQLITE3_MINIMUM.findIndex((wanted, i) => (parts2[i] ?? 0) !== wanted);
5942
+ const recent = at === -1 || (parts2[at] ?? 0) > (SQLITE3_MINIMUM[at] ?? 0);
5943
+ return { program, version, usable: recent && recovers(program) };
5944
+ }, "sqlite3Program");
5945
+ var activeTimers = /* @__PURE__ */ __name(() => {
5946
+ if (process.platform !== "linux")
5947
+ return void 0;
5948
+ try {
5949
+ return execFileSync("systemctl", ["--user", "list-timers", "--plain", "--no-legend"], {
5950
+ encoding: "utf8",
5951
+ stdio: ["ignore", "pipe", "ignore"]
5952
+ }).split("\n").map((line) => line.trim().split(/\s+/).at(-2) ?? "").filter((unit) => /^(memo|mail|tg|max|whatsapp|zoom|drive|gcal|wirecat)-.*\.timer$/.test(unit));
5953
+ } catch {
5954
+ return void 0;
5955
+ }
5956
+ }, "activeTimers");
5957
+ var alive = /* @__PURE__ */ __name((pid) => {
5958
+ try {
5959
+ process.kill(pid, 0);
5960
+ return true;
5961
+ } catch (error) {
5962
+ return error.code === "EPERM";
5963
+ }
5964
+ }, "alive");
5965
+ var runningRecovery = /* @__PURE__ */ __name((path) => {
5966
+ let pid;
5967
+ try {
5968
+ pid = Number(readFileSync(`${path}${RECOVER_LOCK}`, "utf8").trim());
5969
+ } catch {
5970
+ return null;
5971
+ }
5972
+ return Number.isInteger(pid) && pid > 0 && alive(pid) ? pid : null;
5973
+ }, "runningRecovery");
5974
+ var takeRecoverLock = /* @__PURE__ */ __name((path) => {
5975
+ const lock = `${path}${RECOVER_LOCK}`;
5976
+ const take = /* @__PURE__ */ __name(() => writeFileSync(lock, String(process.pid), { flag: "wx", mode: 384 }), "take");
5977
+ try {
5978
+ take();
5979
+ } catch (error) {
5980
+ if (error.code !== "EEXIST")
5981
+ throw error;
5982
+ const pid = runningRecovery(path);
5983
+ if (pid === null) {
5984
+ rmSync2(lock, { force: true });
5985
+ take();
5986
+ } else {
5987
+ throw new CliError("validation_error", `the store is being recovered by process ${pid} \u2014 wait for it to finish`, {
5988
+ reason: "store.recovering"
5989
+ });
5990
+ }
5991
+ }
5992
+ return () => rmSync2(lock, { force: true });
5993
+ }, "takeRecoverLock");
5994
+ var storeHolders = /* @__PURE__ */ __name((path) => {
5995
+ const folder = realpathSync(dirname(path));
5996
+ const files = STORE_PARTS.map((suffix) => join(folder, `${basename(path)}${suffix}`));
5997
+ const wanted = process.platform === "linux" ? files.flatMap((file2) => [file2, `${file2} (deleted)`]) : files.filter(existsSync2);
5998
+ const recovering = runningRecovery(path);
5999
+ const pids = holdersOf(wanted);
6000
+ if (pids === void 0 && recovering === null)
6001
+ return void 0;
6002
+ const all = [
6003
+ .../* @__PURE__ */ new Set([...pids ?? [], ...recovering !== null && recovering !== process.pid ? [recovering] : []])
6004
+ ];
6005
+ return all.map((pid) => {
6006
+ let name = "?";
6007
+ try {
6008
+ name = readFileSync(`/proc/${pid}/comm`, "utf8").trim();
6009
+ } catch {
6010
+ }
6011
+ return { pid, name };
6012
+ });
6013
+ }, "storeHolders");
6014
+ var tableRows = /* @__PURE__ */ __name((database) => {
6015
+ const indexes = fts5Tables(database).map((index) => index.name);
6016
+ const tables = database.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND rootpage > 0 AND name NOT LIKE 'sqlite_%' AND name NOT LIKE 'vector_index_%' ORDER BY name").all().map((row) => String(row.name)).filter((name) => !indexes.some((index) => name.startsWith(`${index}_`)));
6017
+ return Object.fromEntries(tables.map((table) => {
6018
+ try {
6019
+ return [table, Number(database.prepare(`SELECT count(*) AS n FROM "${table}"`).get()?.n)];
6020
+ } catch {
6021
+ return [table, null];
6022
+ }
6023
+ }));
6024
+ }, "tableRows");
6025
+ var copyReadableRows = /* @__PURE__ */ __name((path, target, program = "sqlite3") => new Promise((resolve2, reject) => {
6026
+ const reader = spawn(program, ["-readonly", path, `.recover --ignore-freelist --lost-and-found ${LOST_AND_FOUND}`], {
6027
+ stdio: ["ignore", "pipe", "pipe"]
6028
+ });
6029
+ const writer = spawn(program, ["-cmd", ".dbconfig defensive off", target], { stdio: ["pipe", "ignore", "pipe"] });
6030
+ const errors = [];
6031
+ const collect = /* @__PURE__ */ __name((chunk) => {
6032
+ for (const line of chunk.toString("utf8").split("\n"))
6033
+ if (line && errors.length < 50)
6034
+ errors.push(line.slice(0, 300));
6035
+ }, "collect");
6036
+ reader.stderr.on("data", collect);
6037
+ writer.stderr.on("data", collect);
6038
+ const read = {};
6039
+ let rest = "";
6040
+ const counter = new Transform2({
6041
+ transform(chunk, _encoding, done) {
6042
+ const lines = (rest + chunk.toString("latin1")).split("\n");
6043
+ rest = lines.pop() ?? "";
6044
+ for (const line of lines) {
6045
+ const table = INSERTED.exec(line)?.[1];
6046
+ if (table)
6047
+ read[table] = (read[table] ?? 0) + 1;
6048
+ }
6049
+ done(null, chunk);
6050
+ }
6051
+ });
6052
+ reader.stdout.pipe(counter).pipe(writer.stdin);
6053
+ let exits = 0;
6054
+ let readerCode = null;
6055
+ const exited = /* @__PURE__ */ __name(() => {
6056
+ exits += 1;
6057
+ if (exits < 2)
6058
+ return;
6059
+ if (readerCode !== 0)
6060
+ reject(new CliError("validation_error", `sqlite3 could not read the store: ${errors.join("; ")}`));
6061
+ else
6062
+ resolve2({ errors, read });
6063
+ }, "exited");
6064
+ reader.on("error", reject);
6065
+ writer.on("error", reject);
6066
+ reader.on("close", (code) => {
6067
+ readerCode = code;
6068
+ exited();
6069
+ });
6070
+ writer.on("close", exited);
6071
+ }), "copyReadableRows");
6072
+ var FILLERS = {
6073
+ message_words: /* @__PURE__ */ __name((database, now) => {
6074
+ resetSearchIndex(database);
6075
+ fillSearchIndex(database, { now });
6076
+ }, "message_words"),
6077
+ message_stems: /* @__PURE__ */ __name((database, now) => {
6078
+ resetStems(database, { force: true, now });
6079
+ fillStems(database, { now });
6080
+ }, "message_stems"),
6081
+ attachment_words: /* @__PURE__ */ __name((database) => void resetAttachmentWords(database), "attachment_words"),
6082
+ attachment_name_words: /* @__PURE__ */ __name((database) => (
6083
+ // As migration 20 filled it: й and ё fold as the triggers fold them.
6084
+ database.exec("INSERT INTO attachment_name_words (rowid, name) SELECT id, replace(replace(replace(replace(name, '\u0439', '\u0438'), '\u0419', '\u0418'), '\u0451', '\u0435'), '\u0401', '\u0415') FROM attachments WHERE name IS NOT NULL")
6085
+ ), "attachment_name_words"),
6086
+ meeting_words: /* @__PURE__ */ __name((database) => {
6087
+ database.exec("INSERT OR IGNORE INTO meeting_index_pending (indexable_type, id) SELECT 'meeting_transcript_row', id FROM meeting_transcript_rows UNION ALL SELECT 'meeting_chat_message', id FROM meeting_chat_messages UNION ALL SELECT 'meeting_summary', id FROM meeting_summaries");
6088
+ drainMeetingIndex(database);
6089
+ }, "meeting_words"),
6090
+ // Built per account by the first search that needs them.
6091
+ meeting_stems: /* @__PURE__ */ __name((database) => database.exec("UPDATE search_index_state SET filled_through = 0, built_at = NULL WHERE name LIKE 'meeting_stems:%'"), "meeting_stems")
6092
+ };
6093
+ var CORPUS_TABLES = new Set(Object.values(CORPORA).flatMap((corpus) => [`${corpus.type}_words`, `${corpus.type}_stems`]));
6094
+ var TRIGRAMS = ["note_trigrams", "document_trigrams"];
6095
+ var rebuildDerived = /* @__PURE__ */ __name((database, { now = Date.now, note = /* @__PURE__ */ __name(() => {
6096
+ }, "note") } = {}) => {
6097
+ const lost = database.prepare("SELECT 1 FROM sqlite_master WHERE name = ?").get(LOST_AND_FOUND);
6098
+ const lostAndFound = lost ? Number(database.prepare(`SELECT count(*) AS n FROM ${LOST_AND_FOUND}`).get()?.n) : 0;
6099
+ if (lost)
6100
+ database.exec(`DROP TABLE ${LOST_AND_FOUND}`);
6101
+ const indexes = fts5Tables(database);
6102
+ for (const { name, sql } of indexes) {
6103
+ database.exec(`DROP TABLE "${name}"`);
6104
+ database.exec(sql);
6105
+ }
6106
+ const vectors = database.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name GLOB 'vector_index_[0-9]*' AND sql LIKE 'CREATE VIRTUAL%'").all().map((row) => String(row.name));
6107
+ for (const table of vectors) {
6108
+ database.exec(`DROP TRIGGER IF EXISTS "${table}_redo"`);
6109
+ database.exec(`DROP TABLE "${table}"`);
6110
+ database.prepare("DELETE FROM vector_indexes WHERE id = ?").run(Number(table.replace("vector_index_", "")));
6111
+ }
6112
+ const unfilled = [];
6113
+ const stemmerFor = stemmerCache();
6114
+ for (const { name, external } of indexes) {
6115
+ note(`rebuilding ${name}`);
6116
+ if (external)
6117
+ database.exec(`INSERT INTO "${name}" ("${name}") VALUES ('rebuild')`);
6118
+ else if (FILLERS[name])
6119
+ FILLERS[name](database, now);
6120
+ else if (!CORPUS_TABLES.has(name) && !TRIGRAMS.includes(name))
6121
+ unfilled.push(name);
6122
+ }
6123
+ note("rebuilding the words of notes, documents, memories, mail, tasks, transcripts and events");
6124
+ resetNoteIndex(database);
6125
+ for (const corpus of Object.values(CORPORA))
6126
+ drainCorpus(database, corpus, stemmerFor);
6127
+ for (const name of TRIGRAMS) {
6128
+ const type = name.replace("_trigrams", "");
6129
+ database.prepare(`UPDATE search_index_state SET filled_through = 0, watermark = (SELECT coalesce(max(id), 0) FROM ${type}s) WHERE name = ?`).run(name);
6130
+ }
6131
+ fillTrigrams(database);
6132
+ note("finding mentions again");
6133
+ const mentions = rebuildMentions(database, { now: now() }).mentions;
6134
+ involvementStoreOver({ database, now }).rebuild();
6135
+ note("indexing the stored vectors");
6136
+ const vectorModels = fillVectorIndexes(database);
6137
+ const without = database.prepare("SELECT count(*) AS n FROM chunks k WHERE NOT EXISTS (SELECT 1 FROM embeddings v WHERE v.model = ? AND v.content_hash = k.content_hash)");
6138
+ const chunksWithoutVector = Object.fromEntries(database.prepare("SELECT model FROM vector_indexes ORDER BY model").all().map((row) => [String(row.model), Number(without.get(String(row.model))?.n)]));
6139
+ return {
6140
+ lostAndFound,
6141
+ searchIndexes: indexes.map((index) => index.name),
6142
+ unfilled,
6143
+ mentions,
6144
+ vectorModels,
6145
+ chunksWithoutVector
6146
+ };
6147
+ }, "rebuildDerived");
6148
+ var danglingRows = /* @__PURE__ */ __name((database) => database.prepare(`SELECT "table" AS child, parent, fkid, count(*) AS n FROM pragma_foreign_key_check GROUP BY 1, 2, 3 ORDER BY 4 DESC`).all().map((group) => {
6149
+ const child = String(group.child);
6150
+ const column = database.prepare(`SELECT "from" AS name FROM pragma_foreign_key_list(?) WHERE id = ? ORDER BY seq LIMIT 1`).get(child, Number(group.fkid))?.name;
6151
+ let missing = [];
6152
+ try {
6153
+ missing = database.prepare(`SELECT DISTINCT "${String(column)}" AS id FROM "${child}" WHERE rowid IN (SELECT rowid FROM pragma_foreign_key_check(?) WHERE fkid = ?) ORDER BY 1 LIMIT 20`).all(child, Number(group.fkid)).map((row) => typeof row.id === "number" ? row.id : String(row.id));
6154
+ } catch {
6155
+ }
6156
+ return { table: child, parent: String(group.parent), rows: Number(group.n), missing };
6157
+ }), "danglingRows");
6158
+ var mailToFetch = /* @__PURE__ */ __name((database) => {
6159
+ try {
6160
+ return database.prepare(`SELECT a.external_id AS account, count(DISTINCT l.email_id) AS n FROM email_locations l
6161
+ JOIN mailboxes b ON b.id = l.mailbox_id JOIN accounts a ON a.id = b.account_id
6162
+ WHERE NOT EXISTS (SELECT 1 FROM emails e WHERE e.id = l.email_id) GROUP BY a.id ORDER BY a.external_id`).all().map((row) => ({ account: String(row.account), emails: Number(row.n) }));
6163
+ } catch {
6164
+ return [];
6165
+ }
6166
+ }, "mailToFetch");
6167
+ var clearInvalidJson = /* @__PURE__ */ __name((database) => {
6168
+ const found = invalidJson(database);
6169
+ for (const { table, column, required } of found) {
6170
+ const invalid = `"${column}" IS NOT NULL AND NOT json_valid("${column}")`;
6171
+ database.exec(required ? `DELETE FROM "${table}" WHERE ${invalid}` : `UPDATE "${table}" SET "${column}" = NULL WHERE ${invalid}`);
6172
+ }
6173
+ return found;
6174
+ }, "clearInvalidJson");
6175
+ var refuseInUse = /* @__PURE__ */ __name((path) => {
6176
+ const holders = storeHolders(path);
6177
+ if (holders && holders.length > 0) {
6178
+ const timers = activeTimers() ?? [];
6179
+ throw new CliError("validation_error", `the store is open in ${holders.map(({ pid, name }) => `${name} (process ${pid})`).join(", ")} \u2014 stop it first` + (timers.length ? `, and the timers: systemctl --user stop ${timers.join(" ")}` : ""), { reason: "store.in-use" });
6180
+ }
6181
+ }, "refuseInUse");
6182
+ var recoverStore = /* @__PURE__ */ __name(async ({ path, command, version, sqlite3 = "sqlite3", now = Date.now, note = /* @__PURE__ */ __name(() => {
6183
+ }, "note"), copy }) => {
6184
+ const started = Date.now();
6185
+ if (!existsSync2(path))
6186
+ throw new CliError("not_found", `no store at ${path}`);
6187
+ const program = copy ? { program: sqlite3, version: "given", usable: true } : sqlite3Program(sqlite3);
6188
+ if (!program.usable) {
6189
+ throw new CliError("configuration_error", program.version ? `sqlite3 ${program.version} cannot recover: the recovery needs ${SQLITE3_MINIMUM.join(".")} or newer, built with .recover` : "the recovery needs the sqlite3 program with its .recover command: install it (apt install sqlite3, brew install sqlite)", { reason: "store.sqlite3-missing" });
6190
+ }
6191
+ const releaseLock2 = takeRecoverLock(path);
6192
+ try {
6193
+ refuseInUse(path);
6194
+ const bytes = STORE_PARTS.reduce((sum, suffix) => sum + (statSync2(`${path}${suffix}`, { throwIfNoEntry: false })?.size ?? 0), 0);
6195
+ const { bavail, bsize } = statfsSync(dirname(path));
6196
+ if (Number(bavail) * Number(bsize) < bytes * 1.2)
6197
+ throw new CliError("validation_error", `the recovery needs about ${Math.ceil(bytes * 1.2 / 1e9)} GB free beside the store`);
6198
+ return await recoverLocked({ path, command, version, sqlite3, now, note, copy, started, program });
6199
+ } finally {
6200
+ releaseLock2();
6201
+ }
6202
+ }, "recoverStore");
6203
+ var recoverLocked = /* @__PURE__ */ __name(async ({ path, command, version, sqlite3, now, note, copy, started, program }) => {
6204
+ const watch = (await openSqlite(path, { readOnly: true })).database;
6205
+ let watching = true;
6206
+ const stopWatching = /* @__PURE__ */ __name(() => {
6207
+ if (watching)
6208
+ watch.close();
6209
+ watching = false;
6210
+ }, "stopWatching");
6211
+ try {
6212
+ const dataVersion = /* @__PURE__ */ __name(() => Number(watch.prepare("PRAGMA data_version").get()?.data_version), "dataVersion");
6213
+ const rowsBefore = tableRows(watch);
6214
+ const before = { data: dataVersion(), inode: statSync2(path).ino };
6215
+ const stamp = new Date(now()).toISOString().replace(/[:.]/g, "-");
6216
+ const target = `${path}.recovering-${stamp}`;
6217
+ writeFileSync(target, "", { flag: "wx", mode: 384 });
6218
+ const dropTarget = /* @__PURE__ */ __name(() => {
6219
+ for (const suffix of [...STORE_PARTS, "-journal"])
6220
+ rmSync2(`${target}${suffix}`, { force: true });
6221
+ }, "dropTarget");
6222
+ note(`copying the readable rows into ${target}`);
6223
+ let copied;
6224
+ let copyErrors;
6225
+ let read;
6226
+ let opened;
6227
+ try {
6228
+ ;
6229
+ ({ errors: copyErrors, read } = await (copy ?? ((from, to) => copyReadableRows(from, to, sqlite3)))(path, target));
6230
+ copied = Date.now();
6231
+ opened = await openSqlite(target);
6232
+ } catch (error) {
6233
+ dropTarget();
6234
+ throw error;
6235
+ }
6236
+ let rebuilt;
6237
+ let kept;
6238
+ let dangling;
6239
+ let json;
6240
+ let fetch2;
6241
+ try {
6242
+ kept = tableRows(opened.database);
6243
+ migrate(opened.database, { command, ...version ? { version } : {} });
6244
+ note("clearing values that are not valid JSON");
6245
+ json = clearInvalidJson(opened.database);
6246
+ rebuilt = rebuildDerived(opened.database, { now, note });
6247
+ note("looking for rows that point at rows that were lost");
6248
+ dangling = danglingRows(opened.database);
6249
+ fetch2 = mailToFetch(opened.database);
6250
+ opened.database.exec("PRAGMA wal_checkpoint(TRUNCATE)");
6251
+ } catch (error) {
6252
+ opened.database.close();
6253
+ dropTarget();
6254
+ throw error;
6255
+ }
6256
+ opened.database.close();
6257
+ const rebuiltAt = Date.now();
6258
+ note("checking the recovered file");
6259
+ const health = await storeHealth(target, { deep: true });
6260
+ const checkedAt = Date.now();
6261
+ if (!health.ok) {
6262
+ throw new CliError("validation_error", `the recovered file did not pass its check, so the store was left as it was; the file is kept at ${target}`, { reason: "store.recovery-failed" });
6263
+ }
6264
+ refuseInUse(path);
6265
+ const changed = dataVersion() !== before.data || statSync2(path, { throwIfNoEntry: false })?.ino !== before.inode;
6266
+ stopWatching();
6267
+ if (changed) {
6268
+ throw new CliError("validation_error", `the store was written to during the recovery, so it was left as it was \u2014 stop every timer and run it again; ${target} can be deleted`, { reason: "store.changed-during-recovery" });
6269
+ }
6270
+ const keptAt = `${path}.before-recover-${stamp}`;
6271
+ for (const suffix of STORE_PARTS)
6272
+ if (existsSync2(`${path}${suffix}`))
6273
+ renameSync2(`${path}${suffix}`, `${keptAt}${suffix}`);
6274
+ for (const suffix of STORE_PARTS)
6275
+ if (existsSync2(`${target}${suffix}`))
6276
+ renameSync2(`${target}${suffix}`, `${path}${suffix}`);
6277
+ const lost = Object.entries(rowsBefore).map(([table, before2]) => ({ table, before: before2, read: read[table] ?? 0, kept: kept[table] ?? 0 })).filter(({ before: before2, read: read2, kept: kept2 }) => before2 === null || before2 > kept2 || read2 > kept2);
6278
+ const seconds = /* @__PURE__ */ __name((from, to) => Math.round((to - from) / 100) / 10, "seconds");
6279
+ return {
6280
+ path,
6281
+ keptAt,
6282
+ sqlite3: program.version,
6283
+ lost,
6284
+ dangling,
6285
+ invalidJson: json,
6286
+ mailToFetch: fetch2,
6287
+ rebuilt,
6288
+ copyErrors,
6289
+ health,
6290
+ seconds: {
6291
+ copy: seconds(started, copied),
6292
+ rebuild: seconds(copied, rebuiltAt),
6293
+ check: seconds(rebuiltAt, checkedAt),
6294
+ total: seconds(started, Date.now())
6295
+ }
6296
+ };
6297
+ } finally {
6298
+ stopWatching();
6299
+ }
6300
+ }, "recoverLocked");
6301
+
6302
+ // node_modules/.pnpm/@wirecat+cli-core@0.604.0_@wirecat+cli-base@0.80.9_commander@15.0.0_esbuild@0.28.2_type_4b96f151b4ca40121094ad166c695991/node_modules/@wirecat/cli-core/dist/cli/store-recover.js
6303
+ var COUNTED = [
6304
+ "accounts",
6305
+ "chats",
6306
+ "messages",
6307
+ "attachments",
6308
+ "emails",
6309
+ "documents",
6310
+ "notes",
6311
+ "meetings",
6312
+ "chunks",
6313
+ "embeddings",
6314
+ "mentions"
6315
+ ];
6316
+ var stopTimers = /* @__PURE__ */ __name((timers) => `systemctl --user stop ${timers.join(" ")}`, "stopTimers");
6317
+ var storeRecoveryCheck = /* @__PURE__ */ __name(async (env, command) => {
6318
+ const path = storePath(env);
6319
+ if (!existsSync3(path))
6320
+ return { path, exists: false, ok: true, next: [] };
6321
+ const health = await storeHealth(path, { deep: true });
6322
+ let rows = {};
6323
+ try {
6324
+ const { database } = await openSqlite(path, { readOnly: true });
6325
+ try {
6326
+ const all = tableRows(database);
6327
+ rows = Object.fromEntries(COUNTED.filter((table) => table in all).map((table) => [table, all[table] ?? null]));
6328
+ } finally {
6329
+ database.close();
6330
+ }
6331
+ } catch {
6332
+ }
6333
+ const explanation = explainDamage(health, command);
6334
+ const inUse = storeHolders(path) ?? null;
6335
+ const timers = activeTimers() ?? null;
6336
+ const sqlite3 = sqlite3Program();
6337
+ const next = health.ok ? [] : [
6338
+ ...timers?.length ? [stopTimers(timers)] : [],
6339
+ ...(inUse ?? []).map(({ pid, name }) => `stop ${name} (process ${pid}): it has the store open`),
6340
+ ...sqlite3.usable ? [] : ["install sqlite3 3.43 or newer (apt install sqlite3, brew install sqlite)"],
6341
+ `${command} store recover run`
6342
+ ];
6343
+ return {
6344
+ path,
6345
+ exists: true,
6346
+ ok: health.ok,
6347
+ seconds: Math.round(health.ms / 100) / 10,
6348
+ problems: health.problems ?? 0,
6349
+ damagedTables: health.damagedTables ?? [],
6350
+ damagedSearchIndexes: (health.searchIndexes ?? []).filter((index) => !index.ok).map(({ name, error }) => ({ name, ...error ? { error } : {} })),
6351
+ invalidJson: health.invalidJson ?? [],
6352
+ rows,
6353
+ explanation,
6354
+ inUse,
6355
+ timers,
6356
+ sqlite3: { version: sqlite3.version, usable: sqlite3.usable },
6357
+ next
6358
+ };
6359
+ }, "storeRecoveryCheck");
6360
+ var storeRecoveryRun = /* @__PURE__ */ __name(async (env, { command, version, note, timers: scheduled = activeTimers, copy }) => {
6361
+ const timers = scheduled() ?? [];
6362
+ if (timers.length > 0)
6363
+ throw new CliError("validation_error", `stop the timers first, they open the store: ${stopTimers(timers)}`, {
6364
+ reason: "store.in-use"
6365
+ });
6366
+ const recovery = await recoverStore({
6367
+ path: storePath(env),
6368
+ command,
6369
+ ...version ? { version } : {},
6370
+ ...note ? { note } : {},
6371
+ ...copy ? { copy } : {}
6372
+ });
6373
+ const mail = recovery.mailToFetch.map(({ account, emails }) => `mail <profile of ${account}> sync --rescan # ${emails} emails`);
6374
+ const lostMail = recovery.lost.some(({ table }) => table === "emails") && mail.length === 0 ? ["mail <profile> sync --rescan # each mail profile"] : [];
6375
+ const { health, copyErrors, ...kept } = recovery;
6376
+ return {
6377
+ ...kept,
6378
+ copyErrors: copyErrors.length,
6379
+ checkedOk: health.ok,
6380
+ next: [...mail, ...lostMail, "systemctl --user start <the timers stopped before>"]
6381
+ };
6382
+ }, "storeRecoveryRun");
6383
+ var recoveryNotes = /* @__PURE__ */ __name((answer) => {
6384
+ if ("keptAt" in answer) {
6385
+ const lost = answer.lost.map(({ table, before, read, kept }) => `${table}: ${kept} kept of ${before ?? "an uncountable number"}${read > kept ? `, ${read - kept} read but unusable` : ""}`);
6386
+ return [
6387
+ `recovered in ${answer.seconds.total} s; the damaged file is kept at ${answer.keptAt}`,
6388
+ ...lost.length ? lost : ["no table lost a row"],
6389
+ ...answer.dangling.map(({ table, parent, rows }) => `${rows} rows of ${table} point at ${parent} rows the store does not hold`),
6390
+ ...answer.invalidJson.map(({ table, column, rows, required }) => `${table}.${column}: ${rows} values were not valid JSON \u2014 ${required ? "those rows were dropped" : "set to empty"}`),
6391
+ ...answer.next.map((line) => `next: ${line}`)
6392
+ ];
6393
+ }
6394
+ if (!answer.exists)
6395
+ return ["no store yet"];
6396
+ if (answer.ok)
6397
+ return [`the store is healthy (checked every page and search index in ${answer.seconds} s)`];
6398
+ const why = answer.explanation;
6399
+ return [
6400
+ ...why ? [why.what, ...why.impact, why.externalUnaffected] : [],
6401
+ ...answer.next.map((line) => `next: ${line}`)
6402
+ ];
6403
+ }, "recoveryNotes");
6404
+ var storeRecoverCommand = /* @__PURE__ */ __name(({ command, version }) => {
6405
+ const recover = annotate(new Command("recover"), { effects: LOCAL_READ, examples: [`${command} store recover`] }).summary("what is damaged in the store and how to recover it").description("check every page and search index of the store, say what is damaged, what it means and the commands that recover it; changes nothing").action(async function() {
6406
+ const output = outputFor(this);
6407
+ const answer = await storeRecoveryCheck(environmentOf(this).env ?? process.env, command);
6408
+ renderAnswer(this, output, itemOf(snakeKeys(answer)));
6409
+ if (output.format === "pretty")
6410
+ for (const line of recoveryNotes(answer))
6411
+ output.renderer.note(line);
6412
+ });
6413
+ recover.addCommand(annotate(new Command("run"), { effects: LOCAL_WRITE, examples: [`${command} store recover run`] }).summary("rebuild a damaged store from every row it can read").description("copy every readable row into a new file with the sqlite3 program, rebuild the search indexes, mentions and vector index, check it, and put it in place of the store; the damaged file is kept beside it. Refuses while a WireCat timer or process has the store").action(async function() {
6414
+ const output = outputFor(this);
6415
+ const answer = await storeRecoveryRun(environmentOf(this).env ?? process.env, {
6416
+ command,
6417
+ ...version ? { version } : {},
6418
+ note: /* @__PURE__ */ __name((text) => output.renderer.note(text), "note")
6419
+ });
6420
+ renderAnswer(this, output, itemOf(snakeKeys(answer)));
6421
+ if (output.format === "pretty")
6422
+ for (const line of recoveryNotes(answer))
6423
+ output.renderer.note(line);
6424
+ }));
6425
+ return recover;
6426
+ }, "storeRecoverCommand");
6427
+
6428
+ // node_modules/.pnpm/@wirecat+cli-core@0.604.0_@wirecat+cli-base@0.80.9_commander@15.0.0_esbuild@0.28.2_type_4b96f151b4ca40121094ad166c695991/node_modules/@wirecat/cli-core/dist/cli/store-info.js
5896
6429
  var pendingIfKnown = /* @__PURE__ */ __name((database) => database.prepare("SELECT 1 FROM pragma_table_info('messages') WHERE name = 'normalized_text'").get() ? pendingNormalization(database) : null, "pendingIfKnown");
5897
- var bytesOf = /* @__PURE__ */ __name((path) => existsSync2(path) ? statSync2(path).size : 0, "bytesOf");
6430
+ var bytesOf = /* @__PURE__ */ __name((path) => existsSync4(path) ? statSync3(path).size : 0, "bytesOf");
5898
6431
  var messageOf = /* @__PURE__ */ __name((error) => error instanceof Error ? error.message : String(error), "messageOf");
5899
6432
  var contentsOf = /* @__PURE__ */ __name((database, version, writable) => version > 0 && writable ? {
5900
6433
  rows: rowCounts(database),
@@ -5905,7 +6438,7 @@ var contentsOf = /* @__PURE__ */ __name((database, version, writable) => version
5905
6438
  } : { rows: {}, pendingNormalization: null, wordIndex: null, stemIndex: null }, "contentsOf");
5906
6439
  var storeInfo = /* @__PURE__ */ __name(async (env) => {
5907
6440
  const path = storePath(env);
5908
- if (!existsSync2(path))
6441
+ if (!existsSync4(path))
5909
6442
  return snakeKeys({ path, exists: false, schema: compatibilityOf(void 0) });
5910
6443
  let schema = compatibilityOf(void 0);
5911
6444
  try {
@@ -5938,7 +6471,7 @@ var storeInfoCommand = /* @__PURE__ */ __name(() => annotate(new Command("info")
5938
6471
  renderAnswer(this, outputFor(this), itemOf(answer));
5939
6472
  }), "storeInfoCommand");
5940
6473
 
5941
- // node_modules/.pnpm/@wirecat+cli-core@0.566.0_@wirecat+cli-base@0.77.1_commander@15.0.0_esbuild@0.28.2_type_2c70ab84360472ff0036a7904a884c42/node_modules/@wirecat/cli-core/dist/cli/messenger/password.js
6474
+ // node_modules/.pnpm/@wirecat+cli-core@0.604.0_@wirecat+cli-base@0.80.9_commander@15.0.0_esbuild@0.28.2_type_4b96f151b4ca40121094ad166c695991/node_modules/@wirecat/cli-core/dist/cli/messenger/password.js
5942
6475
  var ENCRYPT_OPTION = [
5943
6476
  "--encrypt",
5944
6477
  "compress and encrypt with a password, typed at a hidden prompt or piped on stdin; it is never kept \u2014 lose it and the file cannot be opened"
@@ -5957,9 +6490,9 @@ var passwordOf = /* @__PURE__ */ __name(async (command, { twice }) => {
5957
6490
  return password;
5958
6491
  }, "passwordOf");
5959
6492
 
5960
- // node_modules/.pnpm/@wirecat+cli-core@0.566.0_@wirecat+cli-base@0.77.1_commander@15.0.0_esbuild@0.28.2_type_2c70ab84360472ff0036a7904a884c42/node_modules/@wirecat/cli-core/dist/replies/rules.js
5961
- import { existsSync as existsSync3, readFileSync } from "node:fs";
5962
- import { join } from "node:path";
6493
+ // node_modules/.pnpm/@wirecat+cli-core@0.604.0_@wirecat+cli-base@0.80.9_commander@15.0.0_esbuild@0.28.2_type_4b96f151b4ca40121094ad166c695991/node_modules/@wirecat/cli-core/dist/replies/rules.js
6494
+ import { existsSync as existsSync5, readFileSync as readFileSync2 } from "node:fs";
6495
+ import { join as join2 } from "node:path";
5963
6496
  var REPLY_ACTIONS = ["reply", "task"];
5964
6497
  var REPLY_MODELS = ["fill-only", "may-reword"];
5965
6498
  var REPLY_KINDS = ["dialog", "group"];
@@ -6045,7 +6578,7 @@ var defaultRule = /* @__PURE__ */ __name((id) => ({
6045
6578
  reply: { template: "", asReply: true },
6046
6579
  limits: { perChat: "1/1d", perPerson: "1/1d" }
6047
6580
  }), "defaultRule");
6048
- var repliesPathFor = /* @__PURE__ */ __name((app, profile, env = process.env) => join(resolvePaths({ appName: app.appName, prefix: app.envPrefix, env }).config, `${profile}.replies.json`), "repliesPathFor");
6581
+ var repliesPathFor = /* @__PURE__ */ __name((app, profile, env = process.env) => join2(resolvePaths({ appName: app.appName, prefix: app.envPrefix, env }).config, `${profile}.replies.json`), "repliesPathFor");
6049
6582
  var EVERYONE = { reply: "all", allow: { people: [], chats: [] }, deny: { people: [], chats: [] } };
6050
6583
  var outsideAudience = /* @__PURE__ */ __name((audience, person, chat) => {
6051
6584
  if (person !== null && audience.deny.people.includes(person))
@@ -6075,11 +6608,11 @@ var readReplies = /* @__PURE__ */ __name((path, provider) => {
6075
6608
  return parseReplies(readRepliesFile(path, provider), path, provider);
6076
6609
  }, "readReplies");
6077
6610
  var readRepliesFile = /* @__PURE__ */ __name((path, provider) => {
6078
- if (!existsSync3(path))
6611
+ if (!existsSync5(path))
6079
6612
  return { audience: structuredClone(EVERYONE), rules: [] };
6080
6613
  let parsed;
6081
6614
  try {
6082
- parsed = JSON.parse(readFileSync(path, "utf8"));
6615
+ parsed = JSON.parse(readFileSync2(path, "utf8"));
6083
6616
  } catch (error) {
6084
6617
  throw broken(path, error instanceof Error ? error.message : String(error));
6085
6618
  }
@@ -6128,9 +6661,9 @@ var problem = /* @__PURE__ */ __name((issue) => {
6128
6661
  }, "problem");
6129
6662
  var broken = /* @__PURE__ */ __name((path, why) => new CliError("configuration_error", `the reply rules ${path} cannot be read (${why}) \u2014 fix the file`), "broken");
6130
6663
 
6131
- // node_modules/.pnpm/@wirecat+cli-core@0.566.0_@wirecat+cli-base@0.77.1_commander@15.0.0_esbuild@0.28.2_type_2c70ab84360472ff0036a7904a884c42/node_modules/@wirecat/cli-core/dist/replies/state.js
6132
- import { existsSync as existsSync4, readFileSync as readFileSync2 } from "node:fs";
6133
- import { join as join2 } from "node:path";
6664
+ // node_modules/.pnpm/@wirecat+cli-core@0.604.0_@wirecat+cli-base@0.80.9_commander@15.0.0_esbuild@0.28.2_type_4b96f151b4ca40121094ad166c695991/node_modules/@wirecat/cli-core/dist/replies/state.js
6665
+ import { existsSync as existsSync6, readFileSync as readFileSync3 } from "node:fs";
6666
+ import { join as join3 } from "node:path";
6134
6667
  var ANSWERED_KEPT = 1e3;
6135
6668
  var times = record(string(), array(string()));
6136
6669
  var stateFile = object({
@@ -6142,13 +6675,13 @@ var stateFile = object({
6142
6675
  });
6143
6676
  var emptyState = /* @__PURE__ */ __name(() => ({ paused: false, answered: [], sent: {} }), "emptyState");
6144
6677
  var answeredKey = /* @__PURE__ */ __name((message) => `${message.chatId}:${message.id}`, "answeredKey");
6145
- var repliesStatePathFor = /* @__PURE__ */ __name((app, profile, env = process.env) => join2(resolvePaths({ appName: app.appName, prefix: app.envPrefix, env }).state, `${profile}.replies-state.json`), "repliesStatePathFor");
6678
+ var repliesStatePathFor = /* @__PURE__ */ __name((app, profile, env = process.env) => join3(resolvePaths({ appName: app.appName, prefix: app.envPrefix, env }).state, `${profile}.replies-state.json`), "repliesStatePathFor");
6146
6679
  var readRepliesState = /* @__PURE__ */ __name((path) => {
6147
- if (!existsSync4(path))
6680
+ if (!existsSync6(path))
6148
6681
  return emptyState();
6149
6682
  let parsed;
6150
6683
  try {
6151
- parsed = JSON.parse(readFileSync2(path, "utf8"));
6684
+ parsed = JSON.parse(readFileSync3(path, "utf8"));
6152
6685
  } catch (error) {
6153
6686
  throw broken2(path, error instanceof Error ? error.message : String(error));
6154
6687
  }
@@ -6181,7 +6714,7 @@ var recordReply = /* @__PURE__ */ __name((state, rule2, message, now) => {
6181
6714
  }, "recordReply");
6182
6715
  var broken2 = /* @__PURE__ */ __name((path, why) => new CliError("configuration_error", `the reply state ${path} cannot be read (${why}) \u2014 fix or move the file`), "broken");
6183
6716
 
6184
- // node_modules/.pnpm/@wirecat+cli-core@0.566.0_@wirecat+cli-base@0.77.1_commander@15.0.0_esbuild@0.28.2_type_2c70ab84360472ff0036a7904a884c42/node_modules/@wirecat/cli-core/dist/replies/decide.js
6717
+ // node_modules/.pnpm/@wirecat+cli-core@0.604.0_@wirecat+cli-base@0.80.9_commander@15.0.0_esbuild@0.28.2_type_4b96f151b4ca40121094ad166c695991/node_modules/@wirecat/cli-core/dist/replies/decide.js
6185
6718
  var skip = /* @__PURE__ */ __name((why) => ({ skip: why }), "skip");
6186
6719
  var decide = /* @__PURE__ */ __name((rule2, incoming, state, now) => {
6187
6720
  const { message, chat, owner, sender } = incoming;
@@ -6287,7 +6820,7 @@ var filled = /* @__PURE__ */ __name((template2, senderName) => {
6287
6820
  return template2.replaceAll("{firstName}", name.split(/\s+/)[0] ?? name).replaceAll("{name}", name);
6288
6821
  }, "filled");
6289
6822
 
6290
- // node_modules/.pnpm/@wirecat+cli-core@0.566.0_@wirecat+cli-base@0.77.1_commander@15.0.0_esbuild@0.28.2_type_2c70ab84360472ff0036a7904a884c42/node_modules/@wirecat/cli-core/dist/replies/template.js
6823
+ // node_modules/.pnpm/@wirecat+cli-core@0.604.0_@wirecat+cli-base@0.80.9_commander@15.0.0_esbuild@0.28.2_type_4b96f151b4ca40121094ad166c695991/node_modules/@wirecat/cli-core/dist/replies/template.js
6291
6824
  var import_liquidjs = __toESM(require_liquid_node(), 1);
6292
6825
  var TEMPLATE_LIMITS = {
6293
6826
  parse: 32768,
@@ -6447,7 +6980,7 @@ var renderReplyTemplate = /* @__PURE__ */ __name(async (reply, input) => {
6447
6980
  }
6448
6981
  }, "renderReplyTemplate");
6449
6982
 
6450
- // node_modules/.pnpm/@wirecat+cli-core@0.566.0_@wirecat+cli-base@0.77.1_commander@15.0.0_esbuild@0.28.2_type_2c70ab84360472ff0036a7904a884c42/node_modules/@wirecat/cli-core/dist/replies/dry-run.js
6983
+ // node_modules/.pnpm/@wirecat+cli-core@0.604.0_@wirecat+cli-base@0.80.9_commander@15.0.0_esbuild@0.28.2_type_4b96f151b4ca40121094ad166c695991/node_modules/@wirecat/cli-core/dist/replies/dry-run.js
6451
6984
  var DRY_RUN_DAYS = 7;
6452
6985
  var PAGE = 500;
6453
6986
  var dryRun = /* @__PURE__ */ __name(async (store, account, rules, { since, until = Date.now(), only, audience, render }) => {
@@ -6561,7 +7094,7 @@ var storedSince = /* @__PURE__ */ __name(async (store, account, chat, since) =>
6561
7094
  }
6562
7095
  }, "storedSince");
6563
7096
 
6564
- // node_modules/.pnpm/@wirecat+cli-core@0.566.0_@wirecat+cli-base@0.77.1_commander@15.0.0_esbuild@0.28.2_type_2c70ab84360472ff0036a7904a884c42/node_modules/@wirecat/cli-core/dist/embeddings/keys.js
7097
+ // node_modules/.pnpm/@wirecat+cli-core@0.604.0_@wirecat+cli-base@0.80.9_commander@15.0.0_esbuild@0.28.2_type_4b96f151b4ca40121094ad166c695991/node_modules/@wirecat/cli-core/dist/embeddings/keys.js
6565
7098
  var endpointKeyName = /* @__PURE__ */ __name((baseUrl) => {
6566
7099
  const host = new URL(baseUrl).host;
6567
7100
  return ["openai", "anthropic"].includes(host) ? `endpoint:${host}` : host;
@@ -6592,7 +7125,7 @@ var embeddingKeys = /* @__PURE__ */ __name((app, env = process.env, keyring) =>
6592
7125
  };
6593
7126
  }, "embeddingKeys");
6594
7127
 
6595
- // node_modules/.pnpm/@wirecat+cli-core@0.566.0_@wirecat+cli-base@0.77.1_commander@15.0.0_esbuild@0.28.2_type_2c70ab84360472ff0036a7904a884c42/node_modules/@wirecat/cli-core/dist/models/openai.js
7128
+ // node_modules/.pnpm/@wirecat+cli-core@0.604.0_@wirecat+cli-base@0.80.9_commander@15.0.0_esbuild@0.28.2_type_4b96f151b4ca40121094ad166c695991/node_modules/@wirecat/cli-core/dist/models/openai.js
6596
7129
  var options = strictObject({
6597
7130
  temperature: range(0, 2),
6598
7131
  top_p: range(0, 1),
@@ -6606,7 +7139,7 @@ var openai = {
6606
7139
  images: true,
6607
7140
  baseUrl: "https://api.openai.com/v1",
6608
7141
  validate: /* @__PURE__ */ __name((given) => checkedOptions("openai", options, given), "validate"),
6609
- complete: /* @__PURE__ */ __name(async (target, request, checked, apiKey, fetcher) => {
7142
+ complete: /* @__PURE__ */ __name((target, request, checked, apiKey, fetcher) => withTimeLimit(12e4, async (deadline) => {
6610
7143
  const response = await fetcher(`${target.baseUrl.replace(/\/+$/, "")}/chat/completions`, {
6611
7144
  method: "POST",
6612
7145
  headers: { "Content-Type": "application/json", ...apiKey ? { Authorization: `Bearer ${apiKey}` } : {} },
@@ -6628,7 +7161,7 @@ var openai = {
6628
7161
  ],
6629
7162
  ...new URL(target.baseUrl).hostname === "api.openai.com" ? { max_completion_tokens: request.maxTokens } : { max_tokens: request.maxTokens }
6630
7163
  }),
6631
- signal: AbortSignal.timeout(12e4),
7164
+ signal: deadline,
6632
7165
  redirect: "error"
6633
7166
  });
6634
7167
  if (!response.ok)
@@ -6638,10 +7171,10 @@ var openai = {
6638
7171
  if (choice?.finish_reason !== "stop" || typeof choice.message?.content !== "string" || !Number.isInteger(body.usage?.total_tokens) || (body.usage?.total_tokens ?? 0) < 1)
6639
7172
  throw new Error("incomplete response");
6640
7173
  return { text: choice.message.content, tokens: body.usage?.total_tokens };
6641
- }, "complete")
7174
+ }), "complete")
6642
7175
  };
6643
7176
 
6644
- // node_modules/.pnpm/@wirecat+cli-core@0.566.0_@wirecat+cli-base@0.77.1_commander@15.0.0_esbuild@0.28.2_type_2c70ab84360472ff0036a7904a884c42/node_modules/@wirecat/cli-core/dist/models/index.js
7177
+ // node_modules/.pnpm/@wirecat+cli-core@0.604.0_@wirecat+cli-base@0.80.9_commander@15.0.0_esbuild@0.28.2_type_4b96f151b4ca40121094ad166c695991/node_modules/@wirecat/cli-core/dist/models/index.js
6645
7178
  var modelGateway = /* @__PURE__ */ __name((deps) => ({
6646
7179
  complete: /* @__PURE__ */ __name(async (request) => {
6647
7180
  if (deps.signal?.aborted)
@@ -6656,7 +7189,7 @@ var modelGateway = /* @__PURE__ */ __name((deps) => ({
6656
7189
  if (!adapter && target.provider === "openai")
6657
7190
  adapter = openai;
6658
7191
  if (!adapter && target.provider === "anthropic")
6659
- adapter = (await import("./anthropic-PPGFISVP.js")).anthropic;
7192
+ adapter = (await import("./anthropic-E3T4USLA.js")).anthropic;
6660
7193
  if (!adapter)
6661
7194
  throw new CliError("validation_error", `no model adapter for ${target.provider}`);
6662
7195
  if (request.images !== void 0 && adapter.images !== true)
@@ -6697,19 +7230,19 @@ var modelGateway = /* @__PURE__ */ __name((deps) => ({
6697
7230
  }, "complete")
6698
7231
  }), "modelGateway");
6699
7232
 
6700
- // node_modules/.pnpm/@wirecat+cli-core@0.566.0_@wirecat+cli-base@0.77.1_commander@15.0.0_esbuild@0.28.2_type_2c70ab84360472ff0036a7904a884c42/node_modules/@wirecat/cli-core/dist/replies/consents.js
6701
- import { existsSync as existsSync5, readFileSync as readFileSync3 } from "node:fs";
6702
- import { join as join3 } from "node:path";
7233
+ // node_modules/.pnpm/@wirecat+cli-core@0.604.0_@wirecat+cli-base@0.80.9_commander@15.0.0_esbuild@0.28.2_type_4b96f151b4ca40121094ad166c695991/node_modules/@wirecat/cli-core/dist/replies/consents.js
7234
+ import { existsSync as existsSync7, readFileSync as readFileSync4 } from "node:fs";
7235
+ import { join as join4 } from "node:path";
6703
7236
  var shape = strictObject({
6704
7237
  provider: nullable(pipe(string(), minLength(1))),
6705
7238
  deniedChats: array(pipe(string(), minLength(1)))
6706
7239
  });
6707
- var replyConsentPathFor = /* @__PURE__ */ __name((app, profile, env = process.env) => join3(resolvePaths({ appName: app.appName, prefix: app.envPrefix, env }).config, `${profile}.replies-consents.json`), "replyConsentPathFor");
7240
+ var replyConsentPathFor = /* @__PURE__ */ __name((app, profile, env = process.env) => join4(resolvePaths({ appName: app.appName, prefix: app.envPrefix, env }).config, `${profile}.replies-consents.json`), "replyConsentPathFor");
6708
7241
  var readReplyConsent = /* @__PURE__ */ __name((path) => {
6709
- if (!existsSync5(path))
7242
+ if (!existsSync7(path))
6710
7243
  return { provider: null, deniedChats: [] };
6711
7244
  try {
6712
- return parse(shape, JSON.parse(readFileSync3(path, "utf8")));
7245
+ return parse(shape, JSON.parse(readFileSync4(path, "utf8")));
6713
7246
  } catch {
6714
7247
  throw new CliError("configuration_error", "reply model consent is invalid; fix its file before granting consent");
6715
7248
  }
@@ -6722,7 +7255,7 @@ var mayModelReply = /* @__PURE__ */ __name((path, provider, chat) => {
6722
7255
  return consent.provider === provider && !consent.deniedChats.includes(chat);
6723
7256
  }, "mayModelReply");
6724
7257
 
6725
- // node_modules/.pnpm/@wirecat+cli-core@0.566.0_@wirecat+cli-base@0.77.1_commander@15.0.0_esbuild@0.28.2_type_2c70ab84360472ff0036a7904a884c42/node_modules/@wirecat/cli-core/dist/replies/rendering.js
7258
+ // node_modules/.pnpm/@wirecat+cli-core@0.604.0_@wirecat+cli-base@0.80.9_commander@15.0.0_esbuild@0.28.2_type_4b96f151b4ca40121094ad166c695991/node_modules/@wirecat/cli-core/dist/replies/rendering.js
6726
7259
  var replyRenderer = /* @__PURE__ */ __name((app, profile, settings, env, warn, options2 = {
6727
7260
  ai: true
6728
7261
  }) => async (rule2, message, chat, now) => {
@@ -6769,7 +7302,7 @@ var replyRenderer = /* @__PURE__ */ __name((app, profile, settings, env, warn, o
6769
7302
  return result2;
6770
7303
  }, "replyRenderer");
6771
7304
 
6772
- // node_modules/.pnpm/@wirecat+cli-core@0.566.0_@wirecat+cli-base@0.77.1_commander@15.0.0_esbuild@0.28.2_type_2c70ab84360472ff0036a7904a884c42/node_modules/@wirecat/cli-core/dist/replies/serve.js
7305
+ // node_modules/.pnpm/@wirecat+cli-core@0.604.0_@wirecat+cli-base@0.80.9_commander@15.0.0_esbuild@0.28.2_type_4b96f151b4ca40121094ad166c695991/node_modules/@wirecat/cli-core/dist/replies/serve.js
6773
7306
  var NOT_ALLOWED = "replies.send is not allow";
6774
7307
  var NO_RULES = "no rules";
6775
7308
  var ONLY_TASK = "opened a task, sent nothing";
@@ -6862,7 +7395,7 @@ var replyTo = /* @__PURE__ */ __name(async (deps, message) => {
6862
7395
  return { skip: why };
6863
7396
  }, "replyTo");
6864
7397
 
6865
- // node_modules/.pnpm/@wirecat+cli-core@0.566.0_@wirecat+cli-base@0.77.1_commander@15.0.0_esbuild@0.28.2_type_2c70ab84360472ff0036a7904a884c42/node_modules/@wirecat/cli-core/dist/cli/messenger/serve-catch-up.js
7398
+ // node_modules/.pnpm/@wirecat+cli-core@0.604.0_@wirecat+cli-base@0.80.9_commander@15.0.0_esbuild@0.28.2_type_4b96f151b4ca40121094ad166c695991/node_modules/@wirecat/cli-core/dist/cli/messenger/serve-catch-up.js
6866
7399
  var START_SYNC_DELAY_MS = 3e4;
6867
7400
  var START_SYNC_BUDGET_MS = 5 * 6e4;
6868
7401
  var START_SYNC_WINDOW_MS = 7 * 864e5;
@@ -6873,8 +7406,8 @@ var startSync = /* @__PURE__ */ __name(({ chats, newestHeld, fetch: fetch2, note
6873
7406
  let pass = Promise.resolve();
6874
7407
  let started = false;
6875
7408
  let done;
6876
- const run = /* @__PURE__ */ __name(async () => {
6877
- const stop = AbortSignal.any([controller.signal, AbortSignal.timeout(budgetMs)]);
7409
+ const run = /* @__PURE__ */ __name(() => withTimeLimit(budgetMs, (deadline) => catchUp(AbortSignal.any([controller.signal, deadline]))), "run");
7410
+ const catchUp = /* @__PURE__ */ __name(async (stop) => {
6878
7411
  const floor = now() - windowMs;
6879
7412
  const moved = [];
6880
7413
  for (const chat of await chats(stop)) {
@@ -6915,7 +7448,7 @@ var startSync = /* @__PURE__ */ __name(({ chats, newestHeld, fetch: fetch2, note
6915
7448
  code: "start_sync",
6916
7449
  text: `caught up ${summary.fetched} message(s) in ${summary.chats} chat(s) that moved while serve was down` + (summary.stopped ? ` \u2014 stopped at the time limit, ${behind.length - summary.chats - summary.failed} left` : "")
6917
7450
  });
6918
- }, "run");
7451
+ }, "catchUp");
6919
7452
  return {
6920
7453
  start: /* @__PURE__ */ __name(() => {
6921
7454
  if (started || controller.signal.aborted)
@@ -6939,7 +7472,7 @@ var startSync = /* @__PURE__ */ __name(({ chats, newestHeld, fetch: fetch2, note
6939
7472
  };
6940
7473
  }, "startSync");
6941
7474
 
6942
- // node_modules/.pnpm/@wirecat+cli-core@0.566.0_@wirecat+cli-base@0.77.1_commander@15.0.0_esbuild@0.28.2_type_2c70ab84360472ff0036a7904a884c42/node_modules/@wirecat/cli-core/dist/cli/messenger/serve-members.js
7475
+ // node_modules/.pnpm/@wirecat+cli-core@0.604.0_@wirecat+cli-base@0.80.9_commander@15.0.0_esbuild@0.28.2_type_4b96f151b4ca40121094ad166c695991/node_modules/@wirecat/cli-core/dist/cli/messenger/serve-members.js
6943
7476
  var FIRST_FETCH_MS = 6e4;
6944
7477
  var DAY_MS = 864e5;
6945
7478
  var memberFetches = /* @__PURE__ */ __name(({ withStore, fetch: fetch2, warn, firstMs = FIRST_FETCH_MS, everyMs = DAY_MS }) => {
@@ -6993,7 +7526,7 @@ var memberFetches = /* @__PURE__ */ __name(({ withStore, fetch: fetch2, warn, fi
6993
7526
  };
6994
7527
  }, "memberFetches");
6995
7528
 
6996
- // node_modules/.pnpm/@wirecat+cli-core@0.566.0_@wirecat+cli-base@0.77.1_commander@15.0.0_esbuild@0.28.2_type_2c70ab84360472ff0036a7904a884c42/node_modules/@wirecat/cli-core/dist/cli/messenger/serve-notice.js
7529
+ // node_modules/.pnpm/@wirecat+cli-core@0.604.0_@wirecat+cli-base@0.80.9_commander@15.0.0_esbuild@0.28.2_type_4b96f151b4ca40121094ad166c695991/node_modules/@wirecat/cli-core/dist/cli/messenger/serve-notice.js
6997
7530
  var record2 = /* @__PURE__ */ __name((context, app, severity, attributes) => recordLogFor(context.streams.diagnostic, app, { command: currentRun().command || "serve" })[severity](attributes), "record");
6998
7531
  var noticeFor = /* @__PURE__ */ __name((context, app, severity = "warn") => ({ text, ...attributes }) => {
6999
7532
  if (context.format === "pretty") {
@@ -7026,7 +7559,7 @@ var recordDiagnostics = /* @__PURE__ */ __name((context, app) => {
7026
7559
  return context;
7027
7560
  }, "recordDiagnostics");
7028
7561
 
7029
- // node_modules/.pnpm/@wirecat+cli-core@0.566.0_@wirecat+cli-base@0.77.1_commander@15.0.0_esbuild@0.28.2_type_2c70ab84360472ff0036a7904a884c42/node_modules/@wirecat/cli-core/dist/cli/messenger/serve-stems.js
7562
+ // node_modules/.pnpm/@wirecat+cli-core@0.604.0_@wirecat+cli-base@0.80.9_commander@15.0.0_esbuild@0.28.2_type_4b96f151b4ca40121094ad166c695991/node_modules/@wirecat/cli-core/dist/cli/messenger/serve-stems.js
7030
7563
  var STEMS_EVERY_MS = 3e4;
7031
7564
  var STEMS_SLICE_MS = 2e3;
7032
7565
  var stemFills = /* @__PURE__ */ __name(({ withStore, warn, everyMs = STEMS_EVERY_MS, sliceMs = STEMS_SLICE_MS }) => {
@@ -7066,7 +7599,7 @@ var stemFills = /* @__PURE__ */ __name(({ withStore, warn, everyMs = STEMS_EVERY
7066
7599
  };
7067
7600
  }, "stemFills");
7068
7601
 
7069
- // node_modules/.pnpm/@wirecat+cli-core@0.566.0_@wirecat+cli-base@0.77.1_commander@15.0.0_esbuild@0.28.2_type_2c70ab84360472ff0036a7904a884c42/node_modules/@wirecat/cli-core/dist/render/messages.js
7602
+ // node_modules/.pnpm/@wirecat+cli-core@0.604.0_@wirecat+cli-base@0.80.9_commander@15.0.0_esbuild@0.28.2_type_4b96f151b4ca40121094ad166c695991/node_modules/@wirecat/cli-core/dist/render/messages.js
7070
7603
  import { styleText } from "node:util";
7071
7604
  var TIME_WIDTH = 8;
7072
7605
  var INDENT = " ".repeat(TIME_WIDTH + 2);
@@ -7242,7 +7775,7 @@ var editedAt = /* @__PURE__ */ __name((message, options2) => {
7242
7775
  return day(edited) === day(message.timestamp) ? time : `${day(edited)} ${time}`;
7243
7776
  }, "editedAt");
7244
7777
 
7245
- // node_modules/.pnpm/@wirecat+cli-core@0.566.0_@wirecat+cli-base@0.77.1_commander@15.0.0_esbuild@0.28.2_type_2c70ab84360472ff0036a7904a884c42/node_modules/@wirecat/cli-core/dist/cli/messenger/message-items.js
7778
+ // node_modules/.pnpm/@wirecat+cli-core@0.604.0_@wirecat+cli-base@0.80.9_commander@15.0.0_esbuild@0.28.2_type_4b96f151b4ca40121094ad166c695991/node_modules/@wirecat/cli-core/dist/cli/messenger/message-items.js
7246
7779
  var defined = /* @__PURE__ */ __name((value) => Object.fromEntries(Object.entries(value).filter(([, one]) => one !== void 0)), "defined");
7247
7780
  var attachmentItem = /* @__PURE__ */ __name((attachment) => defined({
7248
7781
  kind: attachment.kind,
@@ -7337,7 +7870,7 @@ var viewOf = /* @__PURE__ */ __name((context, messenger) => ({
7337
7870
  locale: messenger.app.locale
7338
7871
  }), "viewOf");
7339
7872
 
7340
- // node_modules/.pnpm/@wirecat+cli-core@0.566.0_@wirecat+cli-base@0.77.1_commander@15.0.0_esbuild@0.28.2_type_2c70ab84360472ff0036a7904a884c42/node_modules/@wirecat/cli-core/dist/cli/messenger/watch-answers.js
7873
+ // node_modules/.pnpm/@wirecat+cli-core@0.604.0_@wirecat+cli-base@0.80.9_commander@15.0.0_esbuild@0.28.2_type_4b96f151b4ca40121094ad166c695991/node_modules/@wirecat/cli-core/dist/cli/messenger/watch-answers.js
7341
7874
  var observed = /* @__PURE__ */ __name((value) => ({
7342
7875
  value: value.value,
7343
7876
  observed_at: value.observedAt,
@@ -7404,7 +7937,7 @@ var watchEventItem = /* @__PURE__ */ __name((value, account) => {
7404
7937
  }
7405
7938
  }, "watchEventItem");
7406
7939
 
7407
- // node_modules/.pnpm/@wirecat+cli-core@0.566.0_@wirecat+cli-base@0.77.1_commander@15.0.0_esbuild@0.28.2_type_2c70ab84360472ff0036a7904a884c42/node_modules/@wirecat/cli-core/dist/cli/messenger/watch-command.js
7940
+ // node_modules/.pnpm/@wirecat+cli-core@0.604.0_@wirecat+cli-base@0.80.9_commander@15.0.0_esbuild@0.28.2_type_4b96f151b4ca40121094ad166c695991/node_modules/@wirecat/cli-core/dist/cli/messenger/watch-command.js
7408
7941
  var watchCommand = /* @__PURE__ */ __name((messenger) => annotate(new Command("watch"), {
7409
7942
  output: { entity: "watch_item" },
7410
7943
  effects: REMOTE_READ,
@@ -7559,7 +8092,7 @@ var describe = /* @__PURE__ */ __name((event, render) => {
7559
8092
  }
7560
8093
  }, "describe");
7561
8094
 
7562
- // node_modules/.pnpm/@wirecat+cli-core@0.566.0_@wirecat+cli-base@0.77.1_commander@15.0.0_esbuild@0.28.2_type_2c70ab84360472ff0036a7904a884c42/node_modules/@wirecat/cli-core/dist/cli/messenger/serve-command.js
8095
+ // node_modules/.pnpm/@wirecat+cli-core@0.604.0_@wirecat+cli-base@0.80.9_commander@15.0.0_esbuild@0.28.2_type_4b96f151b4ca40121094ad166c695991/node_modules/@wirecat/cli-core/dist/cli/messenger/serve-command.js
7563
8096
  var serveCommand = /* @__PURE__ */ __name((messenger) => {
7564
8097
  const command = annotate(new Command("serve"), {
7565
8098
  output: { entity: "serve_summary" },
@@ -7823,8 +8356,8 @@ var tasking = /* @__PURE__ */ __name((context, warn) => {
7823
8356
  };
7824
8357
  }, "tasking");
7825
8358
 
7826
- // node_modules/.pnpm/@wirecat+cli-core@0.566.0_@wirecat+cli-base@0.77.1_commander@15.0.0_esbuild@0.28.2_type_2c70ab84360472ff0036a7904a884c42/node_modules/@wirecat/cli-core/dist/cli/messenger/store-tables-command.js
7827
- import { existsSync as existsSync6 } from "node:fs";
8359
+ // node_modules/.pnpm/@wirecat+cli-core@0.604.0_@wirecat+cli-base@0.80.9_commander@15.0.0_esbuild@0.28.2_type_4b96f151b4ca40121094ad166c695991/node_modules/@wirecat/cli-core/dist/cli/messenger/store-tables-command.js
8360
+ import { existsSync as existsSync8 } from "node:fs";
7828
8361
  var PATH = "store tables list";
7829
8362
  var STORE_TABLES_QUERY = {
7830
8363
  entity: "store_table",
@@ -7853,7 +8386,7 @@ var storeTablesCommand = /* @__PURE__ */ __name((messenger) => {
7853
8386
  const filter = filterOf(words);
7854
8387
  const { full } = this.optsWithGlobals();
7855
8388
  const path = storePath(environmentOf(this).env ?? process.env);
7856
- if (!existsSync6(path))
8389
+ if (!existsSync8(path))
7857
8390
  throw new CliError("not_found", `no store at ${path}`);
7858
8391
  const items = await readStoreTables(path, { filter, sizes: full === true });
7859
8392
  renderAnswer(this, outputFor(this), listOf(PATH, {
@@ -7866,7 +8399,7 @@ var storeTablesCommand = /* @__PURE__ */ __name((messenger) => {
7866
8399
  return tables;
7867
8400
  }, "storeTablesCommand");
7868
8401
 
7869
- // node_modules/.pnpm/@wirecat+cli-core@0.566.0_@wirecat+cli-base@0.77.1_commander@15.0.0_esbuild@0.28.2_type_2c70ab84360472ff0036a7904a884c42/node_modules/@wirecat/cli-core/dist/cli/messenger/store-maintenance-command.js
8402
+ // node_modules/.pnpm/@wirecat+cli-core@0.604.0_@wirecat+cli-base@0.80.9_commander@15.0.0_esbuild@0.28.2_type_4b96f151b4ca40121094ad166c695991/node_modules/@wirecat/cli-core/dist/cli/messenger/store-maintenance-command.js
7870
8403
  var SEARCH_INDEXES = ["messages_fts", "chats_fts", "identities_fts"];
7871
8404
  var WORD_INDEX = "message_words";
7872
8405
  var schemaOf = /* @__PURE__ */ __name((database) => {
@@ -7875,7 +8408,7 @@ var schemaOf = /* @__PURE__ */ __name((database) => {
7875
8408
  }, "schemaOf");
7876
8409
  var count2 = /* @__PURE__ */ __name((database, table) => Number(database.prepare(`SELECT count(*) AS n FROM ${table}`).get()?.n ?? 0), "count");
7877
8410
  var pendingIfKnown2 = /* @__PURE__ */ __name((database) => database.prepare("SELECT 1 FROM pragma_table_info('messages') WHERE name = 'normalized_text'").get() ? pendingNormalization(database) : null, "pendingIfKnown");
7878
- var bytesOf2 = /* @__PURE__ */ __name((path) => existsSync7(path) ? statSync3(path).size : 0, "bytesOf");
8411
+ var bytesOf2 = /* @__PURE__ */ __name((path) => existsSync9(path) ? statSync4(path).size : 0, "bytesOf");
7879
8412
  var reading = /* @__PURE__ */ __name(async (path, read) => {
7880
8413
  const database = await openCache(path);
7881
8414
  try {
@@ -7892,10 +8425,23 @@ var readingOnly = /* @__PURE__ */ __name(async (path, read) => {
7892
8425
  database.close();
7893
8426
  }
7894
8427
  }, "readingOnly");
7895
- var storeSummary = /* @__PURE__ */ __name(async (env) => {
8428
+ var storeSummary = /* @__PURE__ */ __name(async (env, { deep = false, command } = {}) => {
7896
8429
  const path = storePath(env);
7897
- if (!existsSync7(path))
8430
+ if (!existsSync9(path))
7898
8431
  return { path, exists: false };
8432
+ const checked = await storeHealth(path, { deep });
8433
+ const health = {
8434
+ checked: checked.checked,
8435
+ covers: deep ? "every page and every search index" : QUICK_HEALTH_CHECKS,
8436
+ ok: checked.ok,
8437
+ ms: checked.ms,
8438
+ ...checked.problems ? { problems: checked.problems } : {},
8439
+ ...checked.damagedTables?.length ? { damagedTables: checked.damagedTables } : {},
8440
+ ...checked.invalidJson?.length ? { invalidJson: checked.invalidJson } : {},
8441
+ ...checked.searchIndexes?.some((index) => !index.ok) ? { damagedSearchIndexes: checked.searchIndexes.filter((index) => !index.ok).map((index) => index.name) } : {}
8442
+ };
8443
+ const damage = command ? explainDamage(checked, command) : null;
8444
+ const healthOf = { health, ...damage ? { damage } : {} };
7899
8445
  try {
7900
8446
  return await reading(path, (database) => {
7901
8447
  const { version, writable } = schemaOf(database);
@@ -7905,11 +8451,12 @@ var storeSummary = /* @__PURE__ */ __name(async (env) => {
7905
8451
  schema: version,
7906
8452
  speaks: SPEAKS,
7907
8453
  writable,
7908
- ...version > 0 ? { chats: count2(database, "chats"), messages: count2(database, "messages") } : {}
8454
+ ...version > 0 ? { chats: count2(database, "chats"), messages: count2(database, "messages") } : {},
8455
+ ...healthOf
7909
8456
  };
7910
8457
  });
7911
8458
  } catch (error) {
7912
- return { path, exists: true, error: messageOf2(error) };
8459
+ return { path, exists: true, error: messageOf2(error), ...healthOf };
7913
8460
  }
7914
8461
  }, "storeSummary");
7915
8462
  var result = /* @__PURE__ */ __name((command, value, next = []) => renderAnswer(command, outputFor(command), itemOf(snakeKeys(value), { next })), "result");
@@ -7924,7 +8471,8 @@ var storeMaintenanceCommands = /* @__PURE__ */ __name((messenger) => [
7924
8471
  repairCommand(messenger),
7925
8472
  resetCommand(messenger),
7926
8473
  copiesCommand(),
7927
- storeTablesCommand(messenger)
8474
+ storeTablesCommand(messenger),
8475
+ storeRecoverCommand({ command: messenger.app.command, version: messenger.app.version })
7928
8476
  ], "storeMaintenanceCommands");
7929
8477
  var refuseWhileServing = /* @__PURE__ */ __name((command, messenger) => {
7930
8478
  const serving = servingProfiles(messenger.app, environmentOf(command).env ?? process.env);
@@ -7936,7 +8484,7 @@ var repairCommand = /* @__PURE__ */ __name((messenger) => annotate(new Command("
7936
8484
  const { renderer, format } = outputFor(this);
7937
8485
  const { dryRun: dryRun2 } = this.opts();
7938
8486
  const path = storePath(environmentOf(this).env ?? process.env);
7939
- if (!existsSync7(path)) {
8487
+ if (!existsSync9(path)) {
7940
8488
  result(this, { path, exists: false });
7941
8489
  return;
7942
8490
  }
@@ -7976,7 +8524,7 @@ var notesOf = /* @__PURE__ */ __name((report, command) => {
7976
8524
  }, "notesOf");
7977
8525
  var copiesCommand = /* @__PURE__ */ __name(() => new Command("copies").description("the tables `store repair` kept as copies").addCommand(annotate(new Command("delete"), { output: { entity: "store_copy_removal" }, effects: LOCAL_WRITE }).description("delete one copy `store repair` kept, named exactly; refuses any other table").argument("<name>", "the copy's name, as `store repair` printed it").action(async function(name) {
7978
8526
  const path = storePath(environmentOf(this).env ?? process.env);
7979
- if (!existsSync7(path))
8527
+ if (!existsSync9(path))
7980
8528
  throw new CliError("not_found", `no store at ${path}`);
7981
8529
  const deleted = await reading(path, (database) => deleteCopy(database, name));
7982
8530
  result(this, { path, deleted });
@@ -7984,7 +8532,7 @@ var copiesCommand = /* @__PURE__ */ __name(() => new Command("copies").descripti
7984
8532
  var checkCommand = /* @__PURE__ */ __name((messenger) => annotate(new Command("check"), { output: { entity: "store_check" }, effects: LOCAL_READ }).summary("check the local archive for problems").description("whether the store is healthy \u2014 integrity, search indexes, disk, and which chats are behind").action(async function() {
7985
8533
  const { renderer } = outputFor(this);
7986
8534
  const path = storePath(environmentOf(this).env ?? process.env);
7987
- if (!existsSync7(path)) {
8535
+ if (!existsSync9(path)) {
7988
8536
  result(this, { path, exists: false, ok: true });
7989
8537
  return;
7990
8538
  }
@@ -8047,7 +8595,7 @@ var inspect = /* @__PURE__ */ __name((path) => reading(path, (database) => {
8047
8595
  ...schema.version > 0 ? [["attachment_words", indexIntegrity(database, "attachment_words", 0)]] : []
8048
8596
  ]);
8049
8597
  const size = bytesOf2(path) + bytesOf2(`${path}-wal`);
8050
- const { bavail, bsize } = statfsSync(dirname(path));
8598
+ const { bavail, bsize } = statfsSync2(dirname2(path));
8051
8599
  const free = Number(bavail) * Number(bsize);
8052
8600
  const behind = schema.version > 0 ? chatsBehind(database) : [];
8053
8601
  const vectorIndexes = schema.version >= 34 ? vectorIndexCounts(database) : [];
@@ -8135,14 +8683,18 @@ var chatsBehind = /* @__PURE__ */ __name((database) => database.prepare(`SELECT
8135
8683
  var migrateCommand = /* @__PURE__ */ __name((messenger) => annotate(new Command("migrate"), { output: { entity: "store_migration" }, effects: LOCAL_WRITE }).summary("migrate an older local archive").description("bring the store up to this build's schema, then normalize, index and stem the messages and notes stored before it").action(async function() {
8136
8684
  const { renderer } = outputFor(this);
8137
8685
  const path = storePath(environmentOf(this).env ?? process.env);
8138
- if (!existsSync7(path)) {
8686
+ if (!existsSync9(path)) {
8139
8687
  result(this, { path, exists: false });
8140
8688
  renderer.note(`no store yet \u2014 the first \`${messenger.app.command}\` command that reads a chat creates it`);
8141
8689
  return;
8142
8690
  }
8143
8691
  const answer = await reading(path, (database) => {
8144
8692
  const from = schemaOf(database).version;
8145
- migrate(database, { command: messenger.app.command, version: messenger.app.version });
8693
+ migrate(database, {
8694
+ command: messenger.app.command,
8695
+ version: messenger.app.version,
8696
+ rollback: { store: path, warn: /* @__PURE__ */ __name((line) => renderer.warn(line), "warn") }
8697
+ });
8146
8698
  const { normalized, indexed, terms } = buildWordIndex(database, (note) => renderer.note(note));
8147
8699
  const stemmed = buildStems(database, (note) => renderer.note(note));
8148
8700
  const notes = buildNoteIndex(database, (note) => renderer.note(note));
@@ -8195,7 +8747,7 @@ var buildNoteIndex = /* @__PURE__ */ __name((database, note, { reset = false } =
8195
8747
  var reindexCommand = /* @__PURE__ */ __name((messenger) => destroysNothing(annotate(new Command("rebuild"), { output: { entity: "store_reindex" }, effects: LOCAL_WRITE })).summary("rebuild the local archive's search indexes").description("rebuild the word index, its typo vocabulary, the stems, the files' word index, the notes' indexes and who took part in what, from what is stored, and drop the vectors no stored text uses; loses nothing").action(async function() {
8196
8748
  const { renderer } = outputFor(this);
8197
8749
  const path = storePath(environmentOf(this).env ?? process.env);
8198
- if (!existsSync7(path)) {
8750
+ if (!existsSync9(path)) {
8199
8751
  result(this, { path, exists: false });
8200
8752
  return;
8201
8753
  }
@@ -8224,11 +8776,11 @@ var reindexCommand = /* @__PURE__ */ __name((messenger) => destroysNothing(annot
8224
8776
  result(this, answer);
8225
8777
  }), "reindexCommand");
8226
8778
  var vacuumInto = /* @__PURE__ */ __name(async (path, target) => {
8227
- writeFileSync(target, "", { flag: "wx", mode: 384 });
8779
+ writeFileSync2(target, "", { flag: "wx", mode: 384 });
8228
8780
  try {
8229
8781
  await reading(path, (database) => database.prepare("VACUUM INTO ?").run(target));
8230
8782
  } catch (error) {
8231
- rmSync2(target, { force: true });
8783
+ rmSync3(target, { force: true });
8232
8784
  throw error;
8233
8785
  }
8234
8786
  }, "vacuumInto");
@@ -8237,9 +8789,9 @@ var backupCommand = /* @__PURE__ */ __name(() => destroysNothing(annotate(new Co
8237
8789
  const { encrypt } = this.opts();
8238
8790
  const path = storePath(environmentOf(this).env ?? process.env);
8239
8791
  const target = resolve(file2);
8240
- if (!existsSync7(path))
8792
+ if (!existsSync9(path))
8241
8793
  throw new CliError("not_found", `no store at ${path} to back up`);
8242
- if (existsSync7(target))
8794
+ if (existsSync9(target))
8243
8795
  throw new CliError("validation_error", `${target} exists \u2014 a backup never overwrites a file`);
8244
8796
  const password = encrypt ? await passwordOf(this, { twice: true }) : void 0;
8245
8797
  const copyAt = password === void 0 ? target : `${path}.backup-${process.pid}`;
@@ -8261,67 +8813,69 @@ var backupCommand = /* @__PURE__ */ __name(() => destroysNothing(annotate(new Co
8261
8813
  });
8262
8814
  } catch (error) {
8263
8815
  if (password === void 0)
8264
- rmSync2(target, { force: true });
8816
+ rmSync3(target, { force: true });
8265
8817
  throw error;
8266
8818
  } finally {
8267
8819
  if (password !== void 0)
8268
- rmSync2(copyAt, { force: true });
8820
+ rmSync3(copyAt, { force: true });
8269
8821
  }
8270
8822
  }), "backupCommand");
8271
8823
  var decryptCommand = /* @__PURE__ */ __name(() => annotate(new Command("decrypt"), { output: { entity: "store_decrypt" }, effects: LOCAL_WRITE }).description("open a file written with --encrypt into a new file; asks for its password").argument("<file>", "a file `store backup --encrypt` or `store export --encrypt` wrote").requiredOption("--output <file>", "the new file, readable only by you").action(async function(file2) {
8272
8824
  const { output } = this.opts();
8273
8825
  const from = resolve(file2);
8274
8826
  const to = resolve(output);
8275
- if (!existsSync7(from))
8827
+ if (!existsSync9(from))
8276
8828
  throw new CliError("not_found", `no file at ${from}`);
8277
8829
  if (!isSealed(from))
8278
8830
  throw new CliError("validation_error", `${from} was not written with --encrypt`);
8279
- if (existsSync7(to))
8831
+ if (existsSync9(to))
8280
8832
  throw new CliError("validation_error", `${to} exists \u2014 never overwritten`);
8281
8833
  await unsealFile(from, to, await passwordOf(this, { twice: false }));
8282
8834
  result(this, { path: to, from, bytes: bytesOf2(to) });
8283
8835
  }), "decryptCommand");
8284
- var restoreCommand = /* @__PURE__ */ __name((messenger) => annotate(new Command("restore"), { output: { entity: "store_restore" }, effects: LOCAL_WRITE }).summary("restore a backup while keeping the current store").description("put a backup in place of the store; the store it replaces is kept beside it, never deleted").argument("<file>", "a file `store backup` wrote; one written with --encrypt asks for its password").action(async function(file2) {
8836
+ var restoreCommand = /* @__PURE__ */ __name((messenger) => annotate(new Command("restore"), { output: { entity: "store_restore" }, effects: LOCAL_WRITE }).summary("restore a backup and keep the current store, or roll back a breaking upgrade").description("put a backup in place of the store; the store it replaces is kept beside it, never deleted. Given a rollback copy (backups/<store>-rollback-schema-<version>-<time>.db, kept for a day before an upgrade older tools cannot open), put its tables back in the store and return it to that version instead").argument("<file>", "a file `store backup` wrote, or a rollback copy; one written with --encrypt asks for its password").action(async function(file2) {
8285
8837
  const path = storePath(environmentOf(this).env ?? process.env);
8286
8838
  const given = resolve(file2);
8287
- if (!existsSync7(given))
8839
+ if (!existsSync9(given))
8288
8840
  throw new CliError("not_found", `no file at ${given}`);
8289
8841
  refuseWhileServing(this, messenger);
8290
8842
  if (!isSealed(given))
8291
8843
  return restoreFrom(this, messenger, given, given);
8292
8844
  const opened = `${path}.unsealing-${process.pid}`;
8293
- mkdirSync(dirname(path), { recursive: true, mode: 448 });
8845
+ mkdirSync(dirname2(path), { recursive: true, mode: 448 });
8294
8846
  try {
8295
8847
  await unsealFile(given, opened, await passwordOf(this, { twice: false }));
8296
8848
  await restoreFrom(this, messenger, opened, given);
8297
8849
  } finally {
8298
- rmSync2(opened, { force: true });
8850
+ rmSync3(opened, { force: true });
8299
8851
  }
8300
8852
  }), "restoreCommand");
8301
8853
  var restoreFrom = /* @__PURE__ */ __name(async (command, messenger, backup, given) => {
8302
8854
  const { renderer } = outputFor(command);
8303
8855
  const path = storePath(environmentOf(command).env ?? process.env);
8304
- if (existsSync7(path) && realpathSync(backup) === realpathSync(path)) {
8856
+ if (existsSync9(path) && realpathSync2(backup) === realpathSync2(path)) {
8305
8857
  throw new CliError("validation_error", `${backup} is the store itself`);
8306
8858
  }
8859
+ if (await isRollbackCopy(backup))
8860
+ return rollBackFrom(command, messenger, backup);
8307
8861
  const schema = await backupSchema(backup);
8308
8862
  const stamp = stampNow();
8309
- const kept = existsSync7(path) ? `${path}.before-restore-${stamp}` : null;
8863
+ const kept = existsSync9(path) ? `${path}.before-restore-${stamp}` : null;
8310
8864
  if (kept) {
8311
8865
  const waitMs = environmentOf(command).storeLockWaitMs;
8312
8866
  await quiesce(path, messenger, "restore", (message) => renderer.warn(message), waitMs);
8313
8867
  } else
8314
- mkdirSync(dirname(path), { recursive: true, mode: 448 });
8868
+ mkdirSync(dirname2(path), { recursive: true, mode: 448 });
8315
8869
  const incoming = `${path}.restoring-${stamp}`;
8316
8870
  copyFileSync(backup, incoming, constants.COPYFILE_EXCL);
8317
8871
  chmodSync(incoming, 384);
8318
8872
  if (kept) {
8319
- renameSync2(path, kept);
8873
+ renameSync3(path, kept);
8320
8874
  for (const suffix of ["-wal", "-shm"])
8321
- if (existsSync7(`${path}${suffix}`))
8322
- renameSync2(`${path}${suffix}`, `${kept}${suffix}`);
8875
+ if (existsSync9(`${path}${suffix}`))
8876
+ renameSync3(`${path}${suffix}`, `${kept}${suffix}`);
8323
8877
  }
8324
- renameSync2(incoming, path);
8878
+ renameSync3(incoming, path);
8325
8879
  result(command, { path, restoredFrom: given, keptAt: kept, schema: schema.version });
8326
8880
  if (kept)
8327
8881
  renderer.note(`the store it replaced is kept at ${kept}`);
@@ -8330,6 +8884,43 @@ var restoreFrom = /* @__PURE__ */ __name(async (command, messenger, backup, give
8330
8884
  renderer.note(`the backup is behind this build; the next command migrates it \u2014 \`${lineOf(command, "store migrate")}\` now`);
8331
8885
  }
8332
8886
  }, "restoreFrom");
8887
+ var isRollbackCopy = /* @__PURE__ */ __name(async (file2) => {
8888
+ try {
8889
+ return await readingOnly(file2, (database) => database.prepare("SELECT 1 FROM sqlite_master WHERE name = 'rollback_meta'").get() !== void 0);
8890
+ } catch {
8891
+ return false;
8892
+ }
8893
+ }, "isRollbackCopy");
8894
+ var rollBackFrom = /* @__PURE__ */ __name(async (command, messenger, copy) => {
8895
+ const { renderer } = outputFor(command);
8896
+ const path = storePath(environmentOf(command).env ?? process.env);
8897
+ if (!existsSync9(path))
8898
+ throw new CliError("not_found", `no store at ${path} to roll back`);
8899
+ const waitMs = environmentOf(command).storeLockWaitMs;
8900
+ await quiesce(path, messenger, "restore", (message) => renderer.warn(message), waitMs);
8901
+ const { database } = await openSqlite(path);
8902
+ let rolled;
8903
+ try {
8904
+ rolled = rollBack(database, copy);
8905
+ } finally {
8906
+ database.close();
8907
+ }
8908
+ result(command, {
8909
+ path,
8910
+ restoredFrom: copy,
8911
+ rolledBack: true,
8912
+ schema: rolled.from,
8913
+ was: rolled.was,
8914
+ tables: rolled.restored,
8915
+ rebuilt: rolled.rebuilt,
8916
+ foreignKeyViolations: rolled.foreignKeyViolations
8917
+ });
8918
+ const taken = new Date(rolled.createdAt).toISOString();
8919
+ renderer.note(`the store is back at schema ${rolled.from}; ${rolled.tables.length > 0 ? rolled.tables.join(", ") : "no table"} hold what they held at ${taken}, and what was written to them since is not kept`);
8920
+ renderer.note("open it with the older tool and run its `store rebuild`: the search indexes are behind the tables");
8921
+ renderer.note(`a tool that speaks schema ${rolled.to} or later migrates it again on its next run`);
8922
+ renderer.note("restart every serve and mcp of either CLI that was running, so they read the restored store");
8923
+ }, "rollBackFrom");
8333
8924
  var backupSchema = /* @__PURE__ */ __name(async (backup) => {
8334
8925
  let read;
8335
8926
  try {
@@ -8353,7 +8944,7 @@ var backupSchema = /* @__PURE__ */ __name(async (backup) => {
8353
8944
  var STORE_LOCK_WAIT_MS = 1e3;
8354
8945
  var quiesce = /* @__PURE__ */ __name(async (path, messenger, then, warn, waitMs = STORE_LOCK_WAIT_MS) => {
8355
8946
  const { command } = messenger.app;
8356
- const files = [path, `${path}-wal`, `${path}-shm`].filter((file2) => existsSync7(file2)).map((file2) => realpathSync(file2));
8947
+ const files = [path, `${path}-wal`, `${path}-shm`].filter((file2) => existsSync9(file2)).map((file2) => realpathSync2(file2));
8357
8948
  const holders = holdersOf(files);
8358
8949
  if (holders === void 0) {
8359
8950
  warn(`this system cannot say which processes have the store open \u2014 restart every running serve and mcp after this`);
@@ -8379,7 +8970,7 @@ var resetCommand = /* @__PURE__ */ __name((messenger) => annotate(new Command("r
8379
8970
  const { command } = messenger.app;
8380
8971
  const env = environmentOf(this).env ?? process.env;
8381
8972
  const path = storePath(env);
8382
- if (!existsSync7(path)) {
8973
+ if (!existsSync9(path)) {
8383
8974
  result(this, { path, exists: false, reset: false });
8384
8975
  renderer.note(`no store at ${path} \u2014 nothing to reset; the first \`${command}\` command that reads a chat creates it`);
8385
8976
  return;
@@ -8415,17 +9006,17 @@ var resetCommand = /* @__PURE__ */ __name((messenger) => annotate(new Command("r
8415
9006
  });
8416
9007
  renderer.note(`backed the store up to ${backup}`);
8417
9008
  }
8418
- for (const suffix of STORE_PARTS)
8419
- rmSync2(`${path}${suffix}`, { force: true });
9009
+ for (const suffix of STORE_PARTS2)
9010
+ rmSync3(`${path}${suffix}`, { force: true });
8420
9011
  await (await openStore({ path, command })).close();
8421
9012
  const schema = await reading(path, (database) => schemaOf(database).version);
8422
9013
  result(this, { path, exists: true, reset: true, backup, backedUp, schema });
8423
9014
  renderer.note(backup ? `the store is empty at schema ${schema}; \`${command} store restore ${backup}\` puts the old one back once a build can read it` : `the store is empty at schema ${schema}; there is no backup`);
8424
9015
  }), "resetCommand");
8425
- var STORE_PARTS = ["", "-wal", "-shm"];
9016
+ var STORE_PARTS2 = ["", "-wal", "-shm"];
8426
9017
  var resetPreview = /* @__PURE__ */ __name(async (path, messenger, env, keep) => {
8427
- const files = STORE_PARTS.map((suffix) => `${path}${suffix}`).filter((file2) => existsSync7(file2));
8428
- const holders = holdersOf(files.map((file2) => realpathSync(file2)));
9018
+ const files = STORE_PARTS2.map((suffix) => `${path}${suffix}`).filter((file2) => existsSync9(file2));
9019
+ const holders = holdersOf(files.map((file2) => realpathSync2(file2)));
8429
9020
  const serving = servingProfiles(messenger.app, env).length > 0;
8430
9021
  const read = await readingOnly(path, (database) => ({
8431
9022
  schema: schemaOf(database).version,