@indigoai-us/hq-cloud 6.15.0 → 6.15.2

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 (329) hide show
  1. package/dist/bin/sync-mutation.d.ts +16 -0
  2. package/dist/bin/sync-mutation.d.ts.map +1 -0
  3. package/dist/bin/sync-mutation.js +60 -0
  4. package/dist/bin/sync-mutation.js.map +1 -0
  5. package/dist/bin/sync-mutation.test.d.ts +2 -0
  6. package/dist/bin/sync-mutation.test.d.ts.map +1 -0
  7. package/dist/bin/sync-mutation.test.js +165 -0
  8. package/dist/bin/sync-mutation.test.js.map +1 -0
  9. package/dist/bin/sync-runner-company.d.ts +8 -0
  10. package/dist/bin/sync-runner-company.d.ts.map +1 -1
  11. package/dist/bin/sync-runner-company.js +16 -0
  12. package/dist/bin/sync-runner-company.js.map +1 -1
  13. package/dist/bin/sync-runner-company.test.d.ts +2 -0
  14. package/dist/bin/sync-runner-company.test.d.ts.map +1 -0
  15. package/dist/bin/sync-runner-company.test.js +36 -0
  16. package/dist/bin/sync-runner-company.test.js.map +1 -0
  17. package/dist/bin/sync-runner-watch-loop.d.ts.map +1 -1
  18. package/dist/bin/sync-runner-watch-loop.js +98 -8
  19. package/dist/bin/sync-runner-watch-loop.js.map +1 -1
  20. package/dist/bin/sync-runner.d.ts +17 -0
  21. package/dist/bin/sync-runner.d.ts.map +1 -1
  22. package/dist/bin/sync-runner.js.map +1 -1
  23. package/dist/bin/sync-runner.test.js +109 -0
  24. package/dist/bin/sync-runner.test.js.map +1 -1
  25. package/dist/cli/conflict-recovery.test.d.ts +2 -0
  26. package/dist/cli/conflict-recovery.test.d.ts.map +1 -0
  27. package/dist/cli/conflict-recovery.test.js +201 -0
  28. package/dist/cli/conflict-recovery.test.js.map +1 -0
  29. package/dist/cli/conflict.d.ts +60 -0
  30. package/dist/cli/conflict.d.ts.map +1 -1
  31. package/dist/cli/conflict.js +333 -0
  32. package/dist/cli/conflict.js.map +1 -1
  33. package/dist/cli/sync.d.ts +35 -0
  34. package/dist/cli/sync.d.ts.map +1 -1
  35. package/dist/cli/sync.js +100 -0
  36. package/dist/cli/sync.js.map +1 -1
  37. package/dist/cli/sync.test.js +85 -1
  38. package/dist/cli/sync.test.js.map +1 -1
  39. package/dist/index.d.ts +2 -0
  40. package/dist/index.d.ts.map +1 -1
  41. package/dist/index.js +1 -0
  42. package/dist/index.js.map +1 -1
  43. package/dist/skill-telemetry.d.ts +6 -0
  44. package/dist/skill-telemetry.d.ts.map +1 -1
  45. package/dist/skill-telemetry.js +14 -2
  46. package/dist/skill-telemetry.js.map +1 -1
  47. package/dist/skill-telemetry.test.js +79 -0
  48. package/dist/skill-telemetry.test.js.map +1 -1
  49. package/dist/sync/candidate-uploader.d.ts +88 -0
  50. package/dist/sync/candidate-uploader.d.ts.map +1 -0
  51. package/dist/sync/candidate-uploader.js +212 -0
  52. package/dist/sync/candidate-uploader.js.map +1 -0
  53. package/dist/sync/candidate-uploader.test.d.ts +2 -0
  54. package/dist/sync/candidate-uploader.test.d.ts.map +1 -0
  55. package/dist/sync/candidate-uploader.test.js +132 -0
  56. package/dist/sync/candidate-uploader.test.js.map +1 -0
  57. package/dist/sync/delta-client.d.ts +73 -0
  58. package/dist/sync/delta-client.d.ts.map +1 -0
  59. package/dist/sync/delta-client.js +201 -0
  60. package/dist/sync/delta-client.js.map +1 -0
  61. package/dist/sync/delta-client.test.d.ts +2 -0
  62. package/dist/sync/delta-client.test.d.ts.map +1 -0
  63. package/dist/sync/delta-client.test.js +97 -0
  64. package/dist/sync/delta-client.test.js.map +1 -0
  65. package/dist/sync/durable-apply.d.ts +76 -0
  66. package/dist/sync/durable-apply.d.ts.map +1 -0
  67. package/dist/sync/durable-apply.js +530 -0
  68. package/dist/sync/durable-apply.js.map +1 -0
  69. package/dist/sync/durable-apply.test.d.ts +2 -0
  70. package/dist/sync/durable-apply.test.d.ts.map +1 -0
  71. package/dist/sync/durable-apply.test.js +180 -0
  72. package/dist/sync/durable-apply.test.js.map +1 -0
  73. package/dist/sync/event-sync.d.ts +33 -1
  74. package/dist/sync/event-sync.d.ts.map +1 -1
  75. package/dist/sync/event-sync.js +149 -1
  76. package/dist/sync/event-sync.js.map +1 -1
  77. package/dist/sync/event-sync.test.js +142 -1
  78. package/dist/sync/event-sync.test.js.map +1 -1
  79. package/dist/sync/index.d.ts +2 -0
  80. package/dist/sync/index.d.ts.map +1 -1
  81. package/dist/sync/index.js +1 -0
  82. package/dist/sync/index.js.map +1 -1
  83. package/dist/sync/multipart-uploader.d.ts +99 -0
  84. package/dist/sync/multipart-uploader.d.ts.map +1 -0
  85. package/dist/sync/multipart-uploader.js +447 -0
  86. package/dist/sync/multipart-uploader.js.map +1 -0
  87. package/dist/sync/multipart-uploader.test.d.ts +2 -0
  88. package/dist/sync/multipart-uploader.test.d.ts.map +1 -0
  89. package/dist/sync/multipart-uploader.test.js +119 -0
  90. package/dist/sync/multipart-uploader.test.js.map +1 -0
  91. package/dist/sync/mutation-client.d.ts +85 -0
  92. package/dist/sync/mutation-client.d.ts.map +1 -0
  93. package/dist/sync/mutation-client.js +245 -0
  94. package/dist/sync/mutation-client.js.map +1 -0
  95. package/dist/sync/mutation-client.test.d.ts +2 -0
  96. package/dist/sync/mutation-client.test.d.ts.map +1 -0
  97. package/dist/sync/mutation-client.test.js +51 -0
  98. package/dist/sync/mutation-client.test.js.map +1 -0
  99. package/dist/sync/push-receiver.d.ts +45 -0
  100. package/dist/sync/push-receiver.d.ts.map +1 -1
  101. package/dist/sync/push-receiver.js +101 -0
  102. package/dist/sync/push-receiver.js.map +1 -1
  103. package/dist/sync/push-receiver.test.js +54 -2
  104. package/dist/sync/push-receiver.test.js.map +1 -1
  105. package/dist/sync/scope-inventory-client.d.ts +69 -0
  106. package/dist/sync/scope-inventory-client.d.ts.map +1 -0
  107. package/dist/sync/scope-inventory-client.js +210 -0
  108. package/dist/sync/scope-inventory-client.js.map +1 -0
  109. package/dist/sync/scope-inventory-client.test.d.ts +2 -0
  110. package/dist/sync/scope-inventory-client.test.d.ts.map +1 -0
  111. package/dist/sync/scope-inventory-client.test.js +94 -0
  112. package/dist/sync/scope-inventory-client.test.js.map +1 -0
  113. package/dist/sync/snapshot-client.d.ts +98 -0
  114. package/dist/sync/snapshot-client.d.ts.map +1 -0
  115. package/dist/sync/snapshot-client.js +402 -0
  116. package/dist/sync/snapshot-client.js.map +1 -0
  117. package/dist/sync/snapshot-client.test.d.ts +2 -0
  118. package/dist/sync/snapshot-client.test.d.ts.map +1 -0
  119. package/dist/sync/snapshot-client.test.js +169 -0
  120. package/dist/sync/snapshot-client.test.js.map +1 -0
  121. package/dist/sync/uploader-finalization.d.ts +97 -0
  122. package/dist/sync/uploader-finalization.d.ts.map +1 -0
  123. package/dist/sync/uploader-finalization.js +273 -0
  124. package/dist/sync/uploader-finalization.js.map +1 -0
  125. package/dist/sync/uploader-finalization.test.d.ts +2 -0
  126. package/dist/sync/uploader-finalization.test.d.ts.map +1 -0
  127. package/dist/sync/uploader-finalization.test.js +92 -0
  128. package/dist/sync/uploader-finalization.test.js.map +1 -0
  129. package/dist/telemetry.d.ts +11 -1
  130. package/dist/telemetry.d.ts.map +1 -1
  131. package/dist/telemetry.js +21 -2
  132. package/dist/telemetry.js.map +1 -1
  133. package/dist/telemetry.test.js +80 -0
  134. package/dist/telemetry.test.js.map +1 -1
  135. package/package.json +6 -1
  136. package/.claude/policies/hq-cloud-esm-cannot-spy-fs-builtins.md +0 -30
  137. package/.claude/policies/hq-cloud-strip-types-no-parameter-properties.md +0 -22
  138. package/.github/workflows/ci.yml +0 -84
  139. package/.github/workflows/publish.yml +0 -56
  140. package/.github/workflows/unreleased-commits-nag.yml +0 -256
  141. package/eslint.config.js +0 -67
  142. package/pnpm-workspace.yaml +0 -2
  143. package/scripts/presign-transport-e2e.mjs +0 -250
  144. package/scripts/vault-rebaseline.sh +0 -323
  145. package/scripts/vault-rescue.sh +0 -332
  146. package/src/active-company.test.ts +0 -188
  147. package/src/active-company.ts +0 -168
  148. package/src/agent-codex-instructions.test.ts +0 -332
  149. package/src/agent-codex-instructions.ts +0 -309
  150. package/src/auth.ts +0 -146
  151. package/src/backup-prune.test.ts +0 -98
  152. package/src/backup-prune.ts +0 -182
  153. package/src/bin/backup-prune-runner.ts +0 -33
  154. package/src/bin/rescue-runner.ts +0 -25
  155. package/src/bin/sync-runner-company.ts +0 -695
  156. package/src/bin/sync-runner-events.test.ts +0 -143
  157. package/src/bin/sync-runner-events.ts +0 -55
  158. package/src/bin/sync-runner-planning.test.ts +0 -311
  159. package/src/bin/sync-runner-planning.ts +0 -258
  160. package/src/bin/sync-runner-rollup.test.ts +0 -37
  161. package/src/bin/sync-runner-rollup.ts +0 -97
  162. package/src/bin/sync-runner-telemetry.ts +0 -15
  163. package/src/bin/sync-runner-watch-loop.ts +0 -1235
  164. package/src/bin/sync-runner-watch-routes.test.ts +0 -71
  165. package/src/bin/sync-runner-watch-routes.ts +0 -184
  166. package/src/bin/sync-runner.test.ts +0 -8767
  167. package/src/bin/sync-runner.ts +0 -2190
  168. package/src/cli/accept.ts +0 -124
  169. package/src/cli/conflict.ts +0 -119
  170. package/src/cli/doctor.test.ts +0 -581
  171. package/src/cli/doctor.ts +0 -642
  172. package/src/cli/index.ts +0 -49
  173. package/src/cli/invite.test.ts +0 -250
  174. package/src/cli/invite.ts +0 -214
  175. package/src/cli/promote.ts +0 -157
  176. package/src/cli/reindex-knowledge.test.ts +0 -307
  177. package/src/cli/reindex-knowledge.ts +0 -450
  178. package/src/cli/reindex.test.ts +0 -957
  179. package/src/cli/reindex.ts +0 -979
  180. package/src/cli/rescue-classify-ordering.test.ts +0 -548
  181. package/src/cli/rescue-clone-diagnostics.test.ts +0 -120
  182. package/src/cli/rescue-core.ts +0 -3011
  183. package/src/cli/rescue-drift-reconcile.test.ts +0 -179
  184. package/src/cli/rescue-drop-dir-symlink.test.ts +0 -224
  185. package/src/cli/rescue-exec-bit-preserve.test.ts +0 -187
  186. package/src/cli/rescue-hq-root-guard.test.ts +0 -232
  187. package/src/cli/rescue-journal-reconcile.test.ts +0 -215
  188. package/src/cli/rescue-mtime-preserve.test.ts +0 -203
  189. package/src/cli/rescue-settings-reconcile.test.ts +0 -637
  190. package/src/cli/rescue-snapshot.test.ts +0 -57
  191. package/src/cli/rescue-snapshot.ts +0 -51
  192. package/src/cli/rescue.reindex.test.ts +0 -63
  193. package/src/cli/rescue.test.ts +0 -131
  194. package/src/cli/rescue.ts +0 -182
  195. package/src/cli/share.test.ts +0 -7843
  196. package/src/cli/share.ts +0 -3663
  197. package/src/cli/sync-scope.test.ts +0 -652
  198. package/src/cli/sync.test.ts +0 -5207
  199. package/src/cli/sync.ts +0 -3470
  200. package/src/cli/tombstones.ts +0 -106
  201. package/src/cli/watch-event-push-conflict.test.ts +0 -234
  202. package/src/client-info.test.ts +0 -214
  203. package/src/client-info.ts +0 -121
  204. package/src/cognito-auth.test.ts +0 -712
  205. package/src/cognito-auth.ts +0 -1422
  206. package/src/company-resolver.test.ts +0 -618
  207. package/src/company-resolver.ts +0 -521
  208. package/src/context.test.ts +0 -583
  209. package/src/context.ts +0 -378
  210. package/src/daemon-worker.ts +0 -26
  211. package/src/daemon.ts +0 -99
  212. package/src/entity-resolver.test.ts +0 -315
  213. package/src/entity-resolver.ts +0 -180
  214. package/src/ignore.test.ts +0 -466
  215. package/src/ignore.ts +0 -469
  216. package/src/index.ts +0 -439
  217. package/src/journal.test.ts +0 -968
  218. package/src/journal.ts +0 -765
  219. package/src/lib/cloud-authoritative.test.ts +0 -45
  220. package/src/lib/cloud-authoritative.ts +0 -59
  221. package/src/lib/conflict-file.ts +0 -86
  222. package/src/lib/conflict-index.ts +0 -289
  223. package/src/lib/conflict.test.ts +0 -348
  224. package/src/lib/describe-error.test.ts +0 -100
  225. package/src/lib/describe-error.ts +0 -58
  226. package/src/lib/exit-codes.ts +0 -24
  227. package/src/lib/machine-id.test.ts +0 -231
  228. package/src/lib/machine-id.ts +0 -175
  229. package/src/lib/net-errors.test.ts +0 -65
  230. package/src/lib/net-errors.ts +0 -86
  231. package/src/lib/readlink-safe.test.ts +0 -43
  232. package/src/lib/readlink-safe.ts +0 -29
  233. package/src/local-path-codec.test.ts +0 -138
  234. package/src/local-path-codec.ts +0 -161
  235. package/src/machine-auth.test.ts +0 -1323
  236. package/src/manifest-reconcile.test.ts +0 -1123
  237. package/src/manifest-reconcile.ts +0 -518
  238. package/src/object-io.test.ts +0 -1221
  239. package/src/object-io.ts +0 -1306
  240. package/src/operation-lock.test.ts +0 -484
  241. package/src/operation-lock.ts +0 -680
  242. package/src/outcome-telemetry.test.ts +0 -498
  243. package/src/outcome-telemetry.ts +0 -639
  244. package/src/personal-vault-exclusions.test.ts +0 -308
  245. package/src/personal-vault-exclusions.ts +0 -354
  246. package/src/personal-vault.test.ts +0 -756
  247. package/src/personal-vault.ts +0 -496
  248. package/src/prefix-coalesce.test.ts +0 -240
  249. package/src/prefix-coalesce.ts +0 -273
  250. package/src/public-surface.test.ts +0 -117
  251. package/src/qmd-reindex.test.ts +0 -877
  252. package/src/qmd-reindex.ts +0 -842
  253. package/src/read-only-state-dir.test.ts +0 -188
  254. package/src/remote-pull.test.ts +0 -1130
  255. package/src/remote-pull.ts +0 -618
  256. package/src/s3.symlink-materialize.test.ts +0 -492
  257. package/src/s3.test.ts +0 -1789
  258. package/src/s3.ts +0 -1532
  259. package/src/schemas/signal-types.test.ts +0 -82
  260. package/src/schemas/signal-types.ts +0 -38
  261. package/src/schemas/source-channels.test.ts +0 -82
  262. package/src/schemas/source-channels.ts +0 -53
  263. package/src/scope-shrink.test.ts +0 -633
  264. package/src/scope-shrink.ts +0 -481
  265. package/src/signals/get.test.ts +0 -310
  266. package/src/signals/get.ts +0 -75
  267. package/src/signals/internals.ts +0 -195
  268. package/src/signals/list.test.ts +0 -420
  269. package/src/signals/list.ts +0 -79
  270. package/src/signals/parse.ts +0 -8
  271. package/src/signals/types.ts +0 -91
  272. package/src/skill-telemetry.test.ts +0 -1825
  273. package/src/skill-telemetry.ts +0 -1439
  274. package/src/sources/get.test.ts +0 -293
  275. package/src/sources/get.ts +0 -66
  276. package/src/sources/internals.ts +0 -198
  277. package/src/sources/list.test.ts +0 -402
  278. package/src/sources/list.ts +0 -84
  279. package/src/sources/parse.ts +0 -43
  280. package/src/sources/types.ts +0 -84
  281. package/src/sync/event-sync.test.ts +0 -594
  282. package/src/sync/event-sync.ts +0 -545
  283. package/src/sync/feature-flags.test.ts +0 -378
  284. package/src/sync/feature-flags.ts +0 -62
  285. package/src/sync/index.ts +0 -76
  286. package/src/sync/lease-client.test.ts +0 -128
  287. package/src/sync/lease-client.ts +0 -207
  288. package/src/sync/logger.test.ts +0 -242
  289. package/src/sync/logger.ts +0 -79
  290. package/src/sync/metrics.test.ts +0 -462
  291. package/src/sync/metrics.ts +0 -213
  292. package/src/sync/pull-scope.ts +0 -265
  293. package/src/sync/push-event.test.ts +0 -266
  294. package/src/sync/push-event.ts +0 -224
  295. package/src/sync/push-receiver.test.ts +0 -566
  296. package/src/sync/push-receiver.ts +0 -1048
  297. package/src/sync/push-transport.ts +0 -231
  298. package/src/sync/realtime-rollout.test.ts +0 -86
  299. package/src/sync/realtime-rollout.ts +0 -262
  300. package/src/sync/state-store.test.ts +0 -194
  301. package/src/sync/state-store.ts +0 -727
  302. package/src/sync-core.ts +0 -58
  303. package/src/sync-progress.test.ts +0 -94
  304. package/src/sync-progress.ts +0 -140
  305. package/src/telemetry-events.test.ts +0 -88
  306. package/src/telemetry-events.ts +0 -205
  307. package/src/telemetry.test.ts +0 -1280
  308. package/src/telemetry.ts +0 -1109
  309. package/src/types.ts +0 -314
  310. package/src/vault-client.test.ts +0 -1380
  311. package/src/vault-client.ts +0 -1694
  312. package/src/version.ts +0 -24
  313. package/src/watch-roots.test.ts +0 -278
  314. package/src/watch-roots.ts +0 -162
  315. package/src/watcher-event-gate.test.ts +0 -212
  316. package/src/watcher.test.ts +0 -1079
  317. package/src/watcher.ts +0 -1741
  318. package/test/e2e/sync/cross-tenant-isolation.test.ts +0 -630
  319. package/test/e2e/sync/skill-telemetry-oversized-transcript.test.ts +0 -124
  320. package/test/e2e/sync/transient-company-leg.test.ts +0 -384
  321. package/test/e2e/sync/windows-unreadable-link-leg.test.ts +0 -191
  322. package/test/e2e/watcher-real-chokidar.test.ts +0 -165
  323. package/test/e2e/watcher-recursive-backend.test.ts +0 -181
  324. package/test/e2e/watcher-scoped-coverage.test.ts +0 -381
  325. package/test/invite-flow.integration.test.ts +0 -244
  326. package/test/joiner-manifest-reconcile.integration.test.ts +0 -322
  327. package/test/share-sync.integration.test.ts +0 -213
  328. package/tsconfig.json +0 -19
  329. package/vitest.config.ts +0 -22
@@ -1,877 +0,0 @@
1
- /**
2
- * Unit tests for reindexAfterSync.
3
- *
4
- * The function shells out to the global `qmd` binary, so every test injects a
5
- * fake `exec` that records the calls and returns canned results — no real qmd
6
- * is invoked. We assert on the *sequence of qmd commands* the function would
7
- * run, which is the contract that keeps a teammate's index fresh after sync.
8
- *
9
- * Corruption-safety tests pin feedback_b9a369ff + feedback_332c7ccc (resolved
10
- * index path, dual-lock, honest quarantine). Path-drift tests pin
11
- * feedback_f8e233c6 (detect-only by default; opt-in repair).
12
- */
13
-
14
- import { describe, it, expect } from "vitest";
15
- import * as fs from "fs";
16
- import * as os from "os";
17
- import * as path from "path";
18
- import {
19
- reindexAfterSync,
20
- looksCorrupt,
21
- resolveExecTimeoutMs,
22
- DEFAULT_QMD_EXEC_TIMEOUT_MS,
23
- parseIndexDirFromStatus,
24
- parseCollectionPathFromShow,
25
- pathsEquivalent,
26
- repairPathDriftEnabled,
27
- acquireDualReindexLocks,
28
- type QmdExec,
29
- type QmdExecResult,
30
- type AcquireReindexLock,
31
- type QuarantineCorruptIndex,
32
- } from "./qmd-reindex.js";
33
-
34
- /** A lock acquirer that always succeeds — keeps command-sequence tests pure. */
35
- const noLock: AcquireReindexLock = () => ({ release() {} });
36
-
37
- /** Identity realpath so path-drift comparisons stay deterministic in fakes. */
38
- const identityRealpath = (p: string) => path.resolve(p);
39
-
40
- /** Build a fake exec that returns status 0 for everything and logs calls. */
41
- function fakeExec(opts?: {
42
- listStdout?: string;
43
- statusStdout?: string;
44
- failOn?: string;
45
- resultFor?: (args: string[]) => Partial<QmdExecResult> | undefined;
46
- }): {
47
- exec: QmdExec;
48
- calls: string[][];
49
- } {
50
- const calls: string[][] = [];
51
- const exec: QmdExec = (args) => {
52
- calls.push(args);
53
- const override = opts?.resultFor?.(args);
54
- if (override) return { status: 0, stdout: "", ...override };
55
- if (opts?.failOn && args[0] === opts.failOn) return { status: 1, stdout: "" };
56
- if (args[0] === "status") {
57
- return { status: 0, stdout: opts?.statusStdout ?? "" };
58
- }
59
- if (args[0] === "collection" && args[1] === "list") {
60
- return { status: 0, stdout: opts?.listStdout ?? "" };
61
- }
62
- if (args[0] === "collection" && args[1] === "show") {
63
- const name = args[2] ?? "unknown";
64
- const registered = path.join("/hq", "companies", name, "knowledge");
65
- return {
66
- status: 0,
67
- stdout: `Collection: ${name}\n Path: ${registered}\n Pattern: **/*.md\n`,
68
- };
69
- }
70
- return { status: 0, stdout: "" };
71
- };
72
- return { exec, calls };
73
- }
74
-
75
- describe("reindexAfterSync", () => {
76
- it("no-ops when the path is not an HQ root", () => {
77
- const { exec, calls } = fakeExec();
78
- const r = reindexAfterSync("/tmp/not-hq", {
79
- exec,
80
- acquireReindexLock: noLock,
81
- existsSync: () => false, // core/core.yaml absent
82
- });
83
- expect(r.qmdAvailable).toBe(false);
84
- expect(calls).toHaveLength(0);
85
- });
86
-
87
- it("no-ops when qmd is unavailable (collection list errors)", () => {
88
- const { exec, calls } = fakeExec({ failOn: "collection" });
89
- const r = reindexAfterSync("/hq", {
90
- exec,
91
- acquireReindexLock: noLock,
92
- existsSync: () => true, // core.yaml present
93
- });
94
- expect(r.qmdAvailable).toBe(false);
95
- expect(r.updated).toBe(false);
96
- expect(calls).toEqual([["status"], ["collection", "list"]]);
97
- });
98
-
99
- it("registers a missing company collection then runs an incremental update", () => {
100
- const { exec, calls } = fakeExec({ listStdout: "Collections (1):\n\nHQ (qmd://HQ/)\n" });
101
- const r = reindexAfterSync("/hq", {
102
- exec,
103
- acquireReindexLock: noLock,
104
- existsSync: () => true,
105
- readCompanies: () => ["acme"],
106
- hasIndexableMarkdown: (p) => p === path.join("/hq", "companies", "acme", "knowledge"),
107
- });
108
- expect(r.qmdAvailable).toBe(true);
109
- expect(r.collectionsAdded).toEqual(["acme"]);
110
- expect(r.updated).toBe(true);
111
- expect(r.embedded).toBe(false);
112
-
113
- expect(calls).toEqual([
114
- ["status"],
115
- ["collection", "list"],
116
- ["collection", "add", path.join("/hq", "companies", "acme", "knowledge"), "--name", "acme", "--mask", "**/*.md"],
117
- ["context", "add", "qmd://acme", "Knowledge base for acme."],
118
- ["update"],
119
- ]);
120
- });
121
-
122
- it("skips collections that already exist at the desired path", () => {
123
- const { exec, calls } = fakeExec({ listStdout: "acme (qmd://acme/)\n" });
124
- const r = reindexAfterSync("/hq", {
125
- exec,
126
- acquireReindexLock: noLock,
127
- existsSync: () => true,
128
- readCompanies: () => ["acme"],
129
- hasIndexableMarkdown: (p) => p === path.join("/hq", "companies", "acme", "knowledge"),
130
- realpathSync: identityRealpath,
131
- });
132
- expect(r.collectionsAdded).toEqual([]);
133
- expect(r.pathDriftDetected).toEqual([]);
134
- expect(calls).toEqual([
135
- ["status"],
136
- ["collection", "list"],
137
- ["collection", "show", "acme"],
138
- ["update"],
139
- ]);
140
- });
141
-
142
- it("detects path drift without repairing when HQ_QMD_REPAIR_PATH_DRIFT is off", () => {
143
- const drifted = path.join("/mirror", "knowledge-acme");
144
- const { exec, calls } = fakeExec({
145
- listStdout: "acme (qmd://acme/)\n",
146
- resultFor: (args) =>
147
- args[0] === "collection" && args[1] === "show"
148
- ? {
149
- status: 0,
150
- stdout: `Collection: acme\n Path: ${drifted}\n`,
151
- }
152
- : undefined,
153
- });
154
- const r = reindexAfterSync("/hq", {
155
- exec,
156
- acquireReindexLock: noLock,
157
- existsSync: () => true,
158
- readCompanies: () => ["acme"],
159
- hasIndexableMarkdown: (p) => p === path.join("/hq", "companies", "acme", "knowledge"),
160
- realpathSync: identityRealpath,
161
- env: {},
162
- embed: true,
163
- });
164
- expect(r.pathDriftDetected).toEqual(["acme"]);
165
- expect(r.collectionsRepaired).toEqual([]);
166
- expect(calls.some((c) => c[0] === "collection" && c[1] === "remove")).toBe(false);
167
- // Detect-only must still allow embed (no repair this cycle).
168
- expect(r.embedded).toBe(true);
169
- });
170
-
171
- it("repairs path drift when HQ_QMD_REPAIR_PATH_DRIFT=1 and skips embed", () => {
172
- const drifted = path.join("/mirror", "knowledge-acme");
173
- const desired = path.join("/hq", "companies", "acme", "knowledge");
174
- const { exec, calls } = fakeExec({
175
- listStdout: "acme (qmd://acme/)\n",
176
- resultFor: (args) =>
177
- args[0] === "collection" && args[1] === "show"
178
- ? { status: 0, stdout: `Collection: acme\n Path: ${drifted}\n` }
179
- : undefined,
180
- });
181
- const r = reindexAfterSync("/hq", {
182
- exec,
183
- acquireReindexLock: noLock,
184
- existsSync: () => true,
185
- readCompanies: () => ["acme"],
186
- hasIndexableMarkdown: (p) => p === path.join("/hq", "companies", "acme", "knowledge"),
187
- realpathSync: identityRealpath,
188
- env: { HQ_QMD_REPAIR_PATH_DRIFT: "1" },
189
- embed: true,
190
- });
191
- expect(r.pathDriftDetected).toEqual(["acme"]);
192
- expect(r.collectionsRepaired).toEqual(["acme"]);
193
- expect(r.embedded).toBe(false);
194
- expect(calls).toEqual([
195
- ["status"],
196
- ["collection", "list"],
197
- ["collection", "show", "acme"],
198
- ["collection", "remove", "acme"],
199
- ["collection", "add", desired, "--name", "acme", "--mask", "**/*.md"],
200
- ["context", "add", "qmd://acme", "Knowledge base for acme."],
201
- ["update"],
202
- ]);
203
- });
204
-
205
- it("does not remove a drifted collection when desired path has no indexable markdown", () => {
206
- const drifted = path.join("/mirror", "knowledge-acme");
207
- const { exec, calls } = fakeExec({
208
- listStdout: "acme (qmd://acme/)\n",
209
- resultFor: (args) =>
210
- args[0] === "collection" && args[1] === "show"
211
- ? { status: 0, stdout: `Collection: acme\n Path: ${drifted}\n` }
212
- : undefined,
213
- });
214
- // hasIndexableMarkdown false → skipped before show/repair (desired empty).
215
- const r = reindexAfterSync("/hq", {
216
- exec,
217
- acquireReindexLock: noLock,
218
- existsSync: () => true,
219
- readCompanies: () => ["acme"],
220
- hasIndexableMarkdown: () => false,
221
- env: { HQ_QMD_REPAIR_PATH_DRIFT: "1" },
222
- });
223
- expect(r.pathDriftDetected).toEqual([]);
224
- expect(r.collectionsRepaired).toEqual([]);
225
- expect(calls.some((c) => c[1] === "remove")).toBe(false);
226
- });
227
-
228
- it("skips company dirs with no indexable markdown", () => {
229
- const { exec, calls } = fakeExec({ listStdout: "" });
230
- const r = reindexAfterSync("/hq", {
231
- exec,
232
- acquireReindexLock: noLock,
233
- existsSync: () => true,
234
- readCompanies: () => ["empty"],
235
- hasIndexableMarkdown: () => false,
236
- });
237
- expect(r.collectionsAdded).toEqual([]);
238
- expect(calls).toEqual([["status"], ["collection", "list"], ["update"]]);
239
- });
240
-
241
- it("registers populated company projects with the shell name and mask", () => {
242
- const { exec, calls } = fakeExec({ listStdout: "" });
243
- const r = reindexAfterSync("/hq", {
244
- exec,
245
- acquireReindexLock: noLock,
246
- existsSync: () => true,
247
- readCompanies: () => ["acme"],
248
- hasIndexableMarkdown: () => false,
249
- hasIndexableProjectContent: () => true,
250
- });
251
-
252
- expect(r.collectionsAdded).toEqual(["acme-projects"]);
253
- expect(calls).toEqual([
254
- ["status"],
255
- ["collection", "list"],
256
- [
257
- "collection",
258
- "add",
259
- path.join("/hq", "companies", "acme", "projects"),
260
- "--name",
261
- "acme-projects",
262
- "--mask",
263
- "**/*.{md,json}",
264
- ],
265
- ["context", "add", "qmd://acme-projects", "Project PRDs and documentation for acme."],
266
- ["update"],
267
- ]);
268
- });
269
-
270
- it("skips missing and empty company projects dirs", () => {
271
- const { exec, calls } = fakeExec({ listStdout: "" });
272
- const emptyProjects = path.join("/hq", "companies", "empty", "projects");
273
- const r = reindexAfterSync("/hq", {
274
- exec,
275
- acquireReindexLock: noLock,
276
- existsSync: (p) => p !== path.join("/hq", "companies", "missing", "projects"),
277
- readCompanies: () => ["missing", "empty"],
278
- hasIndexableMarkdown: () => false,
279
- hasIndexableProjectContent: (p) => p !== emptyProjects,
280
- });
281
-
282
- expect(r.collectionsAdded).toEqual([]);
283
- expect(calls).toEqual([["status"], ["collection", "list"], ["update"]]);
284
- });
285
-
286
- it("registers populated personal knowledge with the shell name and mask", () => {
287
- const { exec, calls } = fakeExec({ listStdout: "" });
288
- const personalKnowledge = path.join("/hq", "personal", "knowledge");
289
- const r = reindexAfterSync("/hq", {
290
- exec,
291
- acquireReindexLock: noLock,
292
- existsSync: () => true,
293
- readCompanies: () => [],
294
- hasIndexableMarkdown: (p) => p === personalKnowledge,
295
- });
296
-
297
- expect(r.collectionsAdded).toEqual(["personal-knowledge"]);
298
- expect(calls).toEqual([
299
- ["status"],
300
- ["collection", "list"],
301
- [
302
- "collection",
303
- "add",
304
- personalKnowledge,
305
- "--name",
306
- "personal-knowledge",
307
- "--mask",
308
- "**/*.md",
309
- ],
310
- ["context", "add", "qmd://personal-knowledge", "Personal knowledge base (owner overlay)."],
311
- ["update"],
312
- ]);
313
- });
314
-
315
- it("skips absent and empty personal knowledge", () => {
316
- const absent = fakeExec({ listStdout: "" });
317
- const absentResult = reindexAfterSync("/hq", {
318
- exec: absent.exec,
319
- acquireReindexLock: noLock,
320
- existsSync: (p) => p !== path.join("/hq", "personal", "knowledge"),
321
- readCompanies: () => [],
322
- });
323
- expect(absentResult.collectionsAdded).toEqual([]);
324
- expect(absent.calls).toEqual([["status"], ["collection", "list"], ["update"]]);
325
-
326
- const empty = fakeExec({ listStdout: "" });
327
- const emptyResult = reindexAfterSync("/hq", {
328
- exec: empty.exec,
329
- acquireReindexLock: noLock,
330
- existsSync: () => true,
331
- readCompanies: () => [],
332
- hasIndexableMarkdown: () => false,
333
- });
334
- expect(emptyResult.collectionsAdded).toEqual([]);
335
- expect(empty.calls).toEqual([["status"], ["collection", "list"], ["update"]]);
336
- });
337
-
338
- it("does not add projects or personal knowledge a second time", () => {
339
- let listCount = 0;
340
- const { exec, calls } = fakeExec({
341
- resultFor: (args) => {
342
- if (args[0] !== "collection" || args[1] !== "list") return undefined;
343
- listCount++;
344
- return {
345
- status: 0,
346
- stdout:
347
- listCount === 1
348
- ? ""
349
- : "acme (qmd://acme/)\nacme-projects (qmd://acme-projects/)\npersonal-knowledge (qmd://personal-knowledge/)\n",
350
- };
351
- },
352
- });
353
- const options = {
354
- exec,
355
- acquireReindexLock: noLock,
356
- existsSync: () => true,
357
- readCompanies: () => ["acme"],
358
- hasIndexableMarkdown: () => true,
359
- hasIndexableProjectContent: () => true,
360
- realpathSync: identityRealpath,
361
- };
362
-
363
- expect(reindexAfterSync("/hq", options).collectionsAdded).toEqual([
364
- "acme",
365
- "acme-projects",
366
- "personal-knowledge",
367
- ]);
368
- expect(reindexAfterSync("/hq", options).collectionsAdded).toEqual([]);
369
- expect(calls.filter((c) => c[0] === "collection" && c[1] === "add")).toHaveLength(3);
370
- });
371
-
372
- it("emits the same collection-add commands as the shell for a fixture tree", () => {
373
- const dir = fs.mkdtempSync(path.join(os.tmpdir(), "hq-qmd-parity-"));
374
- try {
375
- const hq = path.join(dir, "hq");
376
- const acmeKnowledge = path.join(hq, "companies", "acme", "knowledge");
377
- const acmeProjects = path.join(hq, "companies", "acme", "projects");
378
- const emptyProjects = path.join(hq, "companies", "empty", "projects");
379
- const personalKnowledge = path.join(hq, "personal", "knowledge");
380
- fs.mkdirSync(path.join(hq, "core"), { recursive: true });
381
- fs.mkdirSync(acmeKnowledge, { recursive: true });
382
- fs.mkdirSync(acmeProjects, { recursive: true });
383
- fs.mkdirSync(emptyProjects, { recursive: true });
384
- fs.mkdirSync(personalKnowledge, { recursive: true });
385
- fs.writeFileSync(path.join(hq, "core", "core.yaml"), "hqVersion: 1\n");
386
- fs.writeFileSync(path.join(acmeKnowledge, "note.md"), "# knowledge\n");
387
- fs.writeFileSync(path.join(acmeProjects, "prd.json"), "{}\n");
388
- fs.writeFileSync(path.join(personalKnowledge, "note.md"), "# personal\n");
389
-
390
- const { exec, calls } = fakeExec({ listStdout: "" });
391
- reindexAfterSync(hq, { exec, acquireReindexLock: noLock });
392
-
393
- expect(calls.filter((c) => c[0] === "collection" && c[1] === "add")).toEqual([
394
- ["collection", "add", acmeKnowledge, "--name", "acme", "--mask", "**/*.md"],
395
- [
396
- "collection",
397
- "add",
398
- acmeProjects,
399
- "--name",
400
- "acme-projects",
401
- "--mask",
402
- "**/*.{md,json}",
403
- ],
404
- [
405
- "collection",
406
- "add",
407
- personalKnowledge,
408
- "--name",
409
- "personal-knowledge",
410
- "--mask",
411
- "**/*.md",
412
- ],
413
- ]);
414
- } finally {
415
- fs.rmSync(dir, { recursive: true, force: true });
416
- }
417
- });
418
-
419
- it("skips qmd entirely when provided changed paths do not touch knowledge markdown", () => {
420
- const { exec, calls } = fakeExec({ listStdout: "" });
421
- const r = reindexAfterSync("/hq", {
422
- exec,
423
- acquireReindexLock: noLock,
424
- existsSync: () => true,
425
- changedPaths: ["companies/acme/docs/readme.txt"],
426
- });
427
- expect(r.qmdAvailable).toBe(false);
428
- expect(r.updated).toBe(false);
429
- expect(calls).toEqual([]);
430
- });
431
-
432
- it("debounces dirty updates with a pending marker and flushes the final update later", () => {
433
- const dir = fs.mkdtempSync(path.join(os.tmpdir(), "hq-qmd-debounce-"));
434
- try {
435
- const statePath = path.join(dir, "qmd-state.json");
436
- const { exec, calls } = fakeExec({ listStdout: "acme (qmd://acme/)\n" });
437
-
438
- const first = reindexAfterSync("/hq", {
439
- exec,
440
- acquireReindexLock: noLock,
441
- existsSync: () => true,
442
- readCompanies: () => ["acme"],
443
- hasIndexableMarkdown: (p) => p === path.join("/hq", "companies", "acme", "knowledge"),
444
- changedPaths: ["companies/acme/knowledge/note.md"],
445
- debounceMs: 60_000,
446
- nowMs: 100_000,
447
- statePath,
448
- realpathSync: identityRealpath,
449
- });
450
- expect(first.updated).toBe(false);
451
- expect(first.pendingDirty).toBe(true);
452
- expect(calls).toEqual([
453
- ["status"],
454
- ["collection", "list"],
455
- ["collection", "show", "acme"],
456
- ]);
457
-
458
- const second = reindexAfterSync("/hq", {
459
- exec,
460
- acquireReindexLock: noLock,
461
- existsSync: () => true,
462
- changedPaths: [],
463
- debounceMs: 60_000,
464
- nowMs: 161_000,
465
- statePath,
466
- });
467
- expect(second.updated).toBe(true);
468
- expect(second.pendingDirty).toBe(false);
469
- expect(calls).toEqual([
470
- ["status"],
471
- ["collection", "list"],
472
- ["collection", "show", "acme"],
473
- ["status"],
474
- ["collection", "list"],
475
- ["update"],
476
- ]);
477
- } finally {
478
- fs.rmSync(dir, { recursive: true, force: true });
479
- }
480
- });
481
-
482
- it("runs embed only when embed:true", () => {
483
- const { exec, calls } = fakeExec({ listStdout: "" });
484
- const r = reindexAfterSync("/hq", {
485
- exec,
486
- acquireReindexLock: noLock,
487
- existsSync: () => true,
488
- readCompanies: () => [],
489
- embed: true,
490
- });
491
- expect(r.embedded).toBe(true);
492
- expect(calls).toEqual([["status"], ["collection", "list"], ["update"], ["embed"]]);
493
- });
494
-
495
- it("never throws even if exec misbehaves", () => {
496
- const exec: QmdExec = () => {
497
- throw new Error("boom");
498
- };
499
- expect(() =>
500
- reindexAfterSync("/hq", { exec, acquireReindexLock: noLock, existsSync: () => true }),
501
- ).not.toThrow();
502
- });
503
-
504
- it("hasIndexableMarkdown finds a real .md and ignores INDEX.md", () => {
505
- const dir = fs.mkdtempSync(path.join(os.tmpdir(), "hq-qmd-test-"));
506
- try {
507
- const hq = path.join(dir, "hq");
508
- const kdir = path.join(hq, "companies", "acme", "knowledge");
509
- fs.mkdirSync(kdir, { recursive: true });
510
- fs.mkdirSync(path.join(hq, "core"), { recursive: true });
511
- fs.writeFileSync(path.join(hq, "core", "core.yaml"), "hqVersion: 1\n");
512
- fs.writeFileSync(path.join(kdir, "INDEX.md"), "# index\n");
513
- fs.writeFileSync(path.join(kdir, "note.md"), "# real\n");
514
-
515
- const { exec, calls } = fakeExec({ listStdout: "" });
516
- const r = reindexAfterSync(hq, { exec, acquireReindexLock: noLock }); // real fs walk
517
- expect(r.collectionsAdded).toEqual(["acme"]);
518
- expect(calls.some((c) => c[0] === "collection" && c[1] === "add")).toBe(true);
519
- } finally {
520
- fs.rmSync(dir, { recursive: true, force: true });
521
- }
522
- });
523
-
524
- // ── Corruption safety: lock serialization (feedback_b9a369ff) ──────────────
525
-
526
- it("skips the cycle after status when another writer holds the lock", () => {
527
- const dir = fs.mkdtempSync(path.join(os.tmpdir(), "hq-qmd-lockbusy-"));
528
- try {
529
- const statePath = path.join(dir, "qmd-state.json");
530
- const { exec, calls } = fakeExec({ listStdout: "" });
531
- const r = reindexAfterSync("/hq", {
532
- exec,
533
- existsSync: () => true,
534
- statePath,
535
- // Simulate a concurrent qmd writer already holding the lock.
536
- acquireReindexLock: () => null,
537
- });
538
- // status is read-only and runs before lock; no write commands follow.
539
- expect(calls).toEqual([["status"]]);
540
- expect(r.lockBusy).toBe(true);
541
- expect(r.pendingDirty).toBe(true);
542
- expect(r.updated).toBe(false);
543
- const persisted = JSON.parse(fs.readFileSync(statePath, "utf8"));
544
- expect(persisted.pendingDirty).toBe(true);
545
- } finally {
546
- fs.rmSync(dir, { recursive: true, force: true });
547
- }
548
- });
549
-
550
- it("always releases the lock, even when a qmd command throws after status", () => {
551
- let released = false;
552
- const exec: QmdExec = (args) => {
553
- if (args[0] === "status") return { status: 0, stdout: "" };
554
- throw new Error("boom");
555
- };
556
- reindexAfterSync("/hq", {
557
- exec,
558
- existsSync: () => true,
559
- acquireReindexLock: () => ({
560
- release() {
561
- released = true;
562
- },
563
- }),
564
- });
565
- expect(released).toBe(true);
566
- });
567
-
568
- // ── Corruption safety: timeout-kill handling ───────────────────────────────
569
-
570
- it("treats a timed-out update as not-done, marks dirty, and does NOT embed", () => {
571
- const dir = fs.mkdtempSync(path.join(os.tmpdir(), "hq-qmd-timeout-"));
572
- try {
573
- const statePath = path.join(dir, "qmd-state.json");
574
- const { exec, calls } = fakeExec({
575
- listStdout: "",
576
- resultFor: (args) =>
577
- args[0] === "update" ? { status: null, timedOut: true } : undefined,
578
- });
579
- const r = reindexAfterSync("/hq", {
580
- exec,
581
- acquireReindexLock: noLock,
582
- existsSync: () => true,
583
- readCompanies: () => [],
584
- embed: true,
585
- statePath,
586
- });
587
- expect(r.timedOut).toBe(true);
588
- expect(r.updated).toBe(false);
589
- expect(r.embedded).toBe(false);
590
- expect(r.pendingDirty).toBe(true);
591
- expect(calls).toEqual([["status"], ["collection", "list"], ["update"]]);
592
- const persisted = JSON.parse(fs.readFileSync(statePath, "utf8"));
593
- expect(persisted.pendingDirty).toBe(true);
594
- } finally {
595
- fs.rmSync(dir, { recursive: true, force: true });
596
- }
597
- });
598
-
599
- it("treats a timed-out embed as not-embedded and marks dirty", () => {
600
- const { exec } = fakeExec({
601
- listStdout: "",
602
- resultFor: (args) =>
603
- args[0] === "embed" ? { status: null, timedOut: true } : undefined,
604
- });
605
- const r = reindexAfterSync("/hq", {
606
- exec,
607
- acquireReindexLock: noLock,
608
- existsSync: () => true,
609
- readCompanies: () => [],
610
- embed: true,
611
- });
612
- expect(r.updated).toBe(true);
613
- expect(r.embedded).toBe(false);
614
- expect(r.timedOut).toBe(true);
615
- expect(r.pendingDirty).toBe(true);
616
- });
617
-
618
- // ── Corruption safety: SQLITE_CORRUPT detection + quarantine ────────────────
619
-
620
- it("quarantines the resolved index dir when update reports SQLITE_CORRUPT", () => {
621
- const dir = fs.mkdtempSync(path.join(os.tmpdir(), "hq-qmd-corrupt-"));
622
- try {
623
- const statePath = path.join(dir, "qmd-state.json");
624
- const cacheDir = path.join(dir, "cache-qmd");
625
- const quarantined: Array<{ qmdDir: string; suffix: string }> = [];
626
- const quarantine: QuarantineCorruptIndex = (qmdDir, suffix) => {
627
- quarantined.push({ qmdDir, suffix });
628
- return path.join(qmdDir, `index.sqlite.corrupt-${suffix}`);
629
- };
630
- const { exec, calls } = fakeExec({
631
- listStdout: "",
632
- statusStdout: `Index: ${path.join(cacheDir, "index.sqlite")}\nSize: 1 GB\n`,
633
- resultFor: (args) =>
634
- args[0] === "update"
635
- ? { status: 1, stderr: "SqliteError: database disk image is malformed (SQLITE_CORRUPT)" }
636
- : undefined,
637
- });
638
- const r = reindexAfterSync("/hq", {
639
- exec,
640
- acquireReindexLock: noLock,
641
- existsSync: () => true,
642
- readCompanies: () => [],
643
- embed: true,
644
- statePath,
645
- quarantineCorruptIndex: quarantine,
646
- });
647
- expect(r.corruptionQuarantined).toBe(true);
648
- expect(r.corruptionQuarantineFailed).toBe(false);
649
- expect(r.embedded).toBe(false);
650
- expect(r.pendingDirty).toBe(true);
651
- expect(calls).toEqual([["status"], ["collection", "list"], ["update"]]);
652
- expect(quarantined).toHaveLength(1);
653
- expect(quarantined[0].qmdDir).toBe(cacheDir);
654
- expect(r.indexDir).toBe(cacheDir);
655
- } finally {
656
- fs.rmSync(dir, { recursive: true, force: true });
657
- }
658
- });
659
-
660
- it("reports quarantine failure when corruption is detected but nothing moves", () => {
661
- const quarantined: string[] = [];
662
- const { exec, calls } = fakeExec({
663
- resultFor: (args) =>
664
- args[0] === "collection" && args[1] === "list"
665
- ? { status: 0, stdout: "database disk image is malformed" }
666
- : undefined,
667
- });
668
- const r = reindexAfterSync("/hq", {
669
- exec,
670
- acquireReindexLock: noLock,
671
- existsSync: () => true,
672
- quarantineCorruptIndex: (qmdDir) => {
673
- quarantined.push(qmdDir);
674
- return null;
675
- },
676
- });
677
- expect(r.corruptionQuarantined).toBe(false);
678
- expect(r.corruptionQuarantineFailed).toBe(true);
679
- expect(r.updated).toBe(false);
680
- expect(calls).toEqual([["status"], ["collection", "list"]]);
681
- expect(quarantined).toEqual([path.join("/hq", ".qmd")]);
682
- });
683
-
684
- it("quarantines when embed reports SQLITE_CORRUPT", () => {
685
- const quarantined: string[] = [];
686
- const { exec, calls } = fakeExec({
687
- listStdout: "",
688
- resultFor: (args) =>
689
- args[0] === "embed"
690
- ? { status: 1, stderr: "code SQLITE_CORRUPT at store.js:1546" }
691
- : undefined,
692
- });
693
- const r = reindexAfterSync("/hq", {
694
- exec,
695
- acquireReindexLock: noLock,
696
- existsSync: () => true,
697
- readCompanies: () => [],
698
- embed: true,
699
- quarantineCorruptIndex: (qmdDir) => {
700
- quarantined.push(qmdDir);
701
- return path.join(qmdDir, "index.sqlite.corrupt-x");
702
- },
703
- });
704
- expect(r.corruptionQuarantined).toBe(true);
705
- expect(r.embedded).toBe(false);
706
- expect(calls).toEqual([["status"], ["collection", "list"], ["update"], ["embed"]]);
707
- expect(quarantined).toEqual([path.join("/hq", ".qmd")]);
708
- });
709
- });
710
-
711
- // ── The default reindex lock (real filesystem) ───────────────────────────────
712
-
713
- describe("default reindex lock", () => {
714
- it("holds the lock for the duration of the cycle and releases it after", () => {
715
- const dir = fs.mkdtempSync(path.join(os.tmpdir(), "hq-qmd-lock-"));
716
- try {
717
- const hq = path.join(dir, "hq");
718
- const kdir = path.join(hq, "companies", "acme", "knowledge");
719
- fs.mkdirSync(kdir, { recursive: true });
720
- fs.mkdirSync(path.join(hq, "core"), { recursive: true });
721
- fs.writeFileSync(path.join(hq, "core", "core.yaml"), "v: 1\n");
722
- fs.writeFileSync(path.join(kdir, "note.md"), "# real\n");
723
-
724
- const lockPath = path.join(hq, ".qmd", ".reindex.lock");
725
- let reAcquireBlockedWhileHeld = false;
726
- const { exec } = fakeExec({ listStdout: "" });
727
- const observingExec: QmdExec = (args) => {
728
- if (args[0] === "update") {
729
- try {
730
- fs.closeSync(fs.openSync(lockPath, "wx"));
731
- fs.unlinkSync(lockPath);
732
- } catch (err) {
733
- reAcquireBlockedWhileHeld =
734
- (err as NodeJS.ErrnoException).code === "EEXIST";
735
- }
736
- }
737
- return exec(args);
738
- };
739
-
740
- const r = reindexAfterSync(hq, { exec: observingExec });
741
- expect(r.updated).toBe(true);
742
- expect(reAcquireBlockedWhileHeld).toBe(true);
743
- expect(fs.existsSync(lockPath)).toBe(false);
744
- } finally {
745
- fs.rmSync(dir, { recursive: true, force: true });
746
- }
747
- });
748
-
749
- it("reclaims a lock held by a dead PID (stale takeover)", () => {
750
- const dir = fs.mkdtempSync(path.join(os.tmpdir(), "hq-qmd-lock-stale-"));
751
- try {
752
- const hq = path.join(dir, "hq");
753
- const kdir = path.join(hq, "companies", "acme", "knowledge");
754
- fs.mkdirSync(kdir, { recursive: true });
755
- fs.mkdirSync(path.join(hq, "core"), { recursive: true });
756
- fs.writeFileSync(path.join(hq, "core", "core.yaml"), "v: 1\n");
757
- fs.writeFileSync(path.join(kdir, "note.md"), "# real\n");
758
-
759
- const lockPath = path.join(hq, ".qmd", ".reindex.lock");
760
- fs.mkdirSync(path.dirname(lockPath), { recursive: true });
761
- fs.writeFileSync(
762
- lockPath,
763
- JSON.stringify({ pid: 2147483646, startedAt: "2000-01-01T00:00:00.000Z", command: "dead" }),
764
- );
765
-
766
- const { exec, calls } = fakeExec({ listStdout: "" });
767
- const r = reindexAfterSync(hq, { exec });
768
- expect(r.updated).toBe(true);
769
- expect(r.lockBusy).toBe(false);
770
- expect(calls.some((c) => c[0] === "update")).toBe(true);
771
- } finally {
772
- fs.rmSync(dir, { recursive: true, force: true });
773
- }
774
- });
775
- });
776
-
777
- describe("acquireDualReindexLocks", () => {
778
- it("dedupes identical paths so a process cannot lock itself out", () => {
779
- let acquires = 0;
780
- const acquire: AcquireReindexLock = () => {
781
- acquires++;
782
- return { release() {} };
783
- };
784
- const same = path.join("/hq", ".qmd", ".reindex.lock");
785
- const { locks, busy } = acquireDualReindexLocks(acquire, [same, same]);
786
- expect(busy).toBe(false);
787
- expect(locks).toHaveLength(1);
788
- expect(acquires).toBe(1);
789
- });
790
-
791
- it("releases the first lock when the second is busy", () => {
792
- const released: string[] = [];
793
- let n = 0;
794
- const acquire: AcquireReindexLock = (lockPath) => {
795
- n++;
796
- if (n === 2) return null;
797
- return {
798
- release() {
799
- released.push(lockPath);
800
- },
801
- };
802
- };
803
- const { locks, busy } = acquireDualReindexLocks(acquire, [
804
- "/a/.reindex.lock",
805
- "/b/.reindex.lock",
806
- ]);
807
- expect(busy).toBe(true);
808
- expect(locks).toHaveLength(0);
809
- expect(released).toEqual(["/a/.reindex.lock"]);
810
- });
811
- });
812
-
813
- // ── Pure helpers ─────────────────────────────────────────────────────────────
814
-
815
- describe("resolveExecTimeoutMs", () => {
816
- it("defaults to a generous bound, not the old 120s that killed writes", () => {
817
- expect(resolveExecTimeoutMs({})).toBe(DEFAULT_QMD_EXEC_TIMEOUT_MS);
818
- expect(DEFAULT_QMD_EXEC_TIMEOUT_MS).toBeGreaterThan(120_000);
819
- });
820
-
821
- it("honors a valid HQ_QMD_EXEC_TIMEOUT_MS override", () => {
822
- expect(resolveExecTimeoutMs({ HQ_QMD_EXEC_TIMEOUT_MS: "300000" })).toBe(300_000);
823
- });
824
-
825
- it("ignores an invalid override", () => {
826
- expect(resolveExecTimeoutMs({ HQ_QMD_EXEC_TIMEOUT_MS: "nope" })).toBe(DEFAULT_QMD_EXEC_TIMEOUT_MS);
827
- expect(resolveExecTimeoutMs({ HQ_QMD_EXEC_TIMEOUT_MS: "-5" })).toBe(DEFAULT_QMD_EXEC_TIMEOUT_MS);
828
- expect(resolveExecTimeoutMs({ HQ_QMD_EXEC_TIMEOUT_MS: "0" })).toBe(DEFAULT_QMD_EXEC_TIMEOUT_MS);
829
- });
830
- });
831
-
832
- describe("looksCorrupt", () => {
833
- it("matches the SQLITE_CORRUPT signature on stdout or stderr", () => {
834
- expect(looksCorrupt({ stderr: "SqliteError: ... code SQLITE_CORRUPT" })).toBe(true);
835
- expect(looksCorrupt({ stdout: "database disk image is malformed" })).toBe(true);
836
- expect(looksCorrupt({ stdout: "Database disk image IS MALFORMED" })).toBe(true);
837
- });
838
-
839
- it("does not match clean output", () => {
840
- expect(looksCorrupt({ stdout: "Updated 688 documents", stderr: "" })).toBe(false);
841
- expect(looksCorrupt({})).toBe(false);
842
- });
843
- });
844
-
845
- describe("parseIndexDirFromStatus / parseCollectionPathFromShow", () => {
846
- it("parses Index file path into its directory", () => {
847
- expect(
848
- parseIndexDirFromStatus("Index: C:/Users/me/.cache/qmd/index.sqlite\nSize: 1.3 GB\n"),
849
- ).toBe(path.dirname("C:/Users/me/.cache/qmd/index.sqlite"));
850
- });
851
-
852
- it("returns null when Index line is missing", () => {
853
- expect(parseIndexDirFromStatus("Collections: 2\n")).toBeNull();
854
- });
855
-
856
- it("parses Path from collection show", () => {
857
- expect(
858
- parseCollectionPathFromShow("Collection: indigo\n Path: /hq/companies/indigo/knowledge\n"),
859
- ).toBe("/hq/companies/indigo/knowledge");
860
- });
861
- });
862
-
863
- describe("pathsEquivalent / repairPathDriftEnabled", () => {
864
- it("treats case and trailing separators as equal", () => {
865
- expect(
866
- pathsEquivalent("/HQ/Companies/Acme/knowledge/", "/hq/companies/acme/knowledge", (p) => p),
867
- ).toBe(true);
868
- });
869
-
870
- it("enables repair only for 1/true/yes", () => {
871
- expect(repairPathDriftEnabled({})).toBe(false);
872
- expect(repairPathDriftEnabled({ HQ_QMD_REPAIR_PATH_DRIFT: "1" })).toBe(true);
873
- expect(repairPathDriftEnabled({ HQ_QMD_REPAIR_PATH_DRIFT: "true" })).toBe(true);
874
- expect(repairPathDriftEnabled({ HQ_QMD_REPAIR_PATH_DRIFT: "yes" })).toBe(true);
875
- expect(repairPathDriftEnabled({ HQ_QMD_REPAIR_PATH_DRIFT: "0" })).toBe(false);
876
- });
877
- });