@indigoai-us/hq-cli 5.77.13 → 5.78.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 (307) hide show
  1. package/CHANGELOG.md +34 -0
  2. package/assets/scaffold/core/scripts/archive-old-threads.sh +86 -0
  3. package/assets/scaffold/core/scripts/backfill-company-skill-mirrors.sh +73 -0
  4. package/assets/scaffold/core/scripts/backfill-workspace-mirror.sh +51 -0
  5. package/assets/scaffold/core/scripts/codex-skill-bridge.sh +550 -0
  6. package/assets/scaffold/core/scripts/detect-stale-core-policy-mirror.sh +185 -0
  7. package/assets/scaffold/core/scripts/hq-status-summary.sh +187 -0
  8. package/assets/scaffold/core/scripts/ontology-readme-drift.sh +264 -0
  9. package/assets/scaffold/core/scripts/qmd-reindex-after-sync.sh +93 -0
  10. package/assets/scaffold/core/scripts/rebuild-all-indexes.sh +69 -0
  11. package/assets/scaffold/core/scripts/rebuild-companies-index.sh +206 -0
  12. package/assets/scaffold/core/scripts/rebuild-company-knowledge-index.sh +127 -0
  13. package/assets/scaffold/core/scripts/rebuild-orchestrator-index.sh +86 -0
  14. package/assets/scaffold/core/scripts/rebuild-projects-index.sh +105 -0
  15. package/assets/scaffold/core/scripts/rebuild-public-knowledge-index.sh +83 -0
  16. package/assets/scaffold/core/scripts/rebuild-reports-index.sh +114 -0
  17. package/assets/scaffold/core/scripts/rebuild-social-drafts-index.sh +135 -0
  18. package/assets/scaffold/core/scripts/rebuild-threads-index.sh +82 -0
  19. package/assets/scaffold/core/scripts/rebuild-workers-index.sh +97 -0
  20. package/assets/scaffold/core/scripts/resize-screenshot.sh +47 -0
  21. package/assets/scaffold/core/scripts/token-usage-report.sh +254 -0
  22. package/assets/scaffold/core/scripts/worktree.sh +136 -0
  23. package/dist/commands/agents.js +28 -12
  24. package/dist/commands/api-keys.js +100 -20
  25. package/dist/commands/core.d.ts +90 -0
  26. package/dist/commands/core.js +279 -0
  27. package/dist/commands/files-browse.d.ts +21 -0
  28. package/dist/commands/files-browse.js +145 -24
  29. package/dist/commands/files.js +33 -7
  30. package/dist/commands/members.js +16 -5
  31. package/dist/commands/pack-install.d.ts +14 -0
  32. package/dist/commands/pack-install.js +51 -2
  33. package/dist/commands/pkg-install.js +43 -0
  34. package/dist/commands/run.js +8 -0
  35. package/dist/commands/secrets.js +125 -65
  36. package/dist/main.js +6 -0
  37. package/dist/utils/api-key-command-gate.d.ts +45 -0
  38. package/dist/utils/api-key-command-gate.js +51 -0
  39. package/dist/utils/hq-roots.d.ts +91 -0
  40. package/dist/utils/hq-roots.js +212 -0
  41. package/dist/utils/resolve-vault-credential.d.ts +63 -3
  42. package/dist/utils/resolve-vault-credential.js +152 -6
  43. package/dist/utils/run-bundled-script.d.ts +66 -0
  44. package/dist/utils/run-bundled-script.js +80 -0
  45. package/dist/utils/vault-api.d.ts +21 -0
  46. package/dist/utils/vault-api.js +74 -3
  47. package/package.json +7 -1
  48. package/.claude/policies/hq-cli-interactive-reads-use-sts-vend.md +0 -49
  49. package/.github/workflows/ci.yml +0 -46
  50. package/.github/workflows/publish.yml +0 -36
  51. package/.github/workflows/scripts/smoke-test-pkg.sh +0 -97
  52. package/e2e/cli.test.ts +0 -128
  53. package/eslint.config.js +0 -37
  54. package/pnpm-workspace.yaml +0 -4
  55. package/scripts/chmod-bins.mjs +0 -49
  56. package/scripts/generate-dsn.mjs +0 -26
  57. package/scripts/generate-scan-packages-table.mjs +0 -113
  58. package/scripts/smoke-sources-signals.sh +0 -103
  59. package/src/bin/hq-auth-refresh.ts +0 -43
  60. package/src/cli-version.ts +0 -13
  61. package/src/commands/__fixtures__/make-tar.ts +0 -126
  62. package/src/commands/_patterns.ts +0 -10
  63. package/src/commands/add.ts +0 -75
  64. package/src/commands/agents.test.ts +0 -527
  65. package/src/commands/agents.ts +0 -923
  66. package/src/commands/api-keys.test.ts +0 -291
  67. package/src/commands/api-keys.ts +0 -382
  68. package/src/commands/artifact-verify.test.ts +0 -177
  69. package/src/commands/auth.test.ts +0 -82
  70. package/src/commands/auth.ts +0 -213
  71. package/src/commands/billing.test.ts +0 -158
  72. package/src/commands/billing.ts +0 -146
  73. package/src/commands/channels.test.ts +0 -74
  74. package/src/commands/channels.ts +0 -91
  75. package/src/commands/cloud-demote.test.ts +0 -401
  76. package/src/commands/cloud-demote.ts +0 -278
  77. package/src/commands/cloud-provision.test.ts +0 -1117
  78. package/src/commands/cloud-provision.ts +0 -942
  79. package/src/commands/cloud.pull-all.test.ts +0 -711
  80. package/src/commands/cloud.pull-per-company.test.ts +0 -188
  81. package/src/commands/cloud.push-all.test.ts +0 -485
  82. package/src/commands/cloud.scope-excluded-warning.test.ts +0 -22
  83. package/src/commands/cloud.selectors.test.ts +0 -208
  84. package/src/commands/cloud.status.test.ts +0 -160
  85. package/src/commands/cloud.test.ts +0 -41
  86. package/src/commands/cloud.ts +0 -2130
  87. package/src/commands/company.test.ts +0 -202
  88. package/src/commands/company.ts +0 -148
  89. package/src/commands/creators.test.ts +0 -60
  90. package/src/commands/creators.ts +0 -117
  91. package/src/commands/crm.test.ts +0 -179
  92. package/src/commands/crm.ts +0 -236
  93. package/src/commands/db-migrate.ts +0 -55
  94. package/src/commands/db-provision.ts +0 -114
  95. package/src/commands/db-sql.ts +0 -124
  96. package/src/commands/db-status.ts +0 -108
  97. package/src/commands/db.ts +0 -26
  98. package/src/commands/dm.test.ts +0 -748
  99. package/src/commands/dm.ts +0 -1226
  100. package/src/commands/feedback.test.ts +0 -413
  101. package/src/commands/feedback.ts +0 -169
  102. package/src/commands/files-browse.test.ts +0 -1249
  103. package/src/commands/files-browse.ts +0 -1506
  104. package/src/commands/files-delete.test.ts +0 -484
  105. package/src/commands/files-recovery.test.ts +0 -370
  106. package/src/commands/files.test.ts +0 -722
  107. package/src/commands/files.ts +0 -1446
  108. package/src/commands/group-grants.test.ts +0 -330
  109. package/src/commands/group-grants.ts +0 -455
  110. package/src/commands/groups.test.ts +0 -44
  111. package/src/commands/groups.ts +0 -368
  112. package/src/commands/integrations.test.ts +0 -633
  113. package/src/commands/integrations.ts +0 -507
  114. package/src/commands/list.ts +0 -85
  115. package/src/commands/login.ts +0 -52
  116. package/src/commands/logout.ts +0 -30
  117. package/src/commands/marketplace-install.test.ts +0 -543
  118. package/src/commands/marketplace-security.test.ts +0 -646
  119. package/src/commands/mcp-registration.test.ts +0 -2787
  120. package/src/commands/mcp-registration.ts +0 -2612
  121. package/src/commands/mcp-status.test.ts +0 -483
  122. package/src/commands/mcp-status.ts +0 -575
  123. package/src/commands/mcp-status.us011.test.ts +0 -243
  124. package/src/commands/meetings.test.ts +0 -522
  125. package/src/commands/meetings.ts +0 -789
  126. package/src/commands/members.test.ts +0 -1474
  127. package/src/commands/members.ts +0 -1181
  128. package/src/commands/onboard-identity-guard.test.ts +0 -99
  129. package/src/commands/onboard-identity-guard.ts +0 -103
  130. package/src/commands/onboard-join.test.ts +0 -96
  131. package/src/commands/onboard-join.ts +0 -101
  132. package/src/commands/onboard-warning.test.ts +0 -26
  133. package/src/commands/onboard-warning.ts +0 -12
  134. package/src/commands/onboard.ts +0 -267
  135. package/src/commands/outposts-heartbeat.test.ts +0 -299
  136. package/src/commands/outposts-heartbeat.ts +0 -310
  137. package/src/commands/outposts-replica-sync.test.ts +0 -272
  138. package/src/commands/outposts-self-deploy.test.ts +0 -243
  139. package/src/commands/outposts.test.ts +0 -1039
  140. package/src/commands/outposts.ts +0 -1935
  141. package/src/commands/pack-install-secret-authorization.test.ts +0 -115
  142. package/src/commands/pack-install.test.ts +0 -1469
  143. package/src/commands/pack-install.ts +0 -2247
  144. package/src/commands/pack-update-cache.test.ts +0 -149
  145. package/src/commands/packs.test.ts +0 -88
  146. package/src/commands/packs.ts +0 -622
  147. package/src/commands/people.test.ts +0 -807
  148. package/src/commands/people.ts +0 -422
  149. package/src/commands/pkg-install.dispatch.test.ts +0 -71
  150. package/src/commands/pkg-install.ts +0 -215
  151. package/src/commands/pkg-list.test.ts +0 -79
  152. package/src/commands/pkg-list.ts +0 -13
  153. package/src/commands/pkg-remove.ts +0 -71
  154. package/src/commands/pkg-update.ts +0 -189
  155. package/src/commands/publish.test.ts +0 -650
  156. package/src/commands/publish.ts +0 -580
  157. package/src/commands/reindex.test.ts +0 -259
  158. package/src/commands/reindex.ts +0 -274
  159. package/src/commands/rescue.test.ts +0 -39
  160. package/src/commands/rescue.ts +0 -210
  161. package/src/commands/run.env-local.test.ts +0 -88
  162. package/src/commands/run.test.ts +0 -45
  163. package/src/commands/run.ts +0 -184
  164. package/src/commands/safe-extract.test.ts +0 -459
  165. package/src/commands/safe-extract.ts +0 -444
  166. package/src/commands/secrets-scope.test.ts +0 -56
  167. package/src/commands/secrets-scope.ts +0 -32
  168. package/src/commands/secrets.parse-destination.test.ts +0 -38
  169. package/src/commands/secrets.test.ts +0 -2037
  170. package/src/commands/secrets.ts +0 -2240
  171. package/src/commands/signals.ts +0 -351
  172. package/src/commands/skill.test.ts +0 -770
  173. package/src/commands/skill.ts +0 -796
  174. package/src/commands/sources.ts +0 -362
  175. package/src/commands/sync-mode.test.ts +0 -366
  176. package/src/commands/sync-mode.ts +0 -387
  177. package/src/commands/sync-narrow.test.ts +0 -633
  178. package/src/commands/sync-narrow.ts +0 -555
  179. package/src/commands/sync.ts +0 -165
  180. package/src/commands/team-sync.ts +0 -628
  181. package/src/commands/update.ts +0 -71
  182. package/src/commands/whoami.ts +0 -83
  183. package/src/commands/workers.test.ts +0 -158
  184. package/src/commands/workers.ts +0 -301
  185. package/src/index.test.ts +0 -32
  186. package/src/index.ts +0 -20
  187. package/src/lib/db/control-plane.test.ts +0 -59
  188. package/src/lib/db/control-plane.ts +0 -113
  189. package/src/lib/db/local.test.ts +0 -81
  190. package/src/lib/db/local.ts +0 -148
  191. package/src/lib/db/migrate.test.ts +0 -133
  192. package/src/lib/db/migrate.ts +0 -137
  193. package/src/lib/db/paths.test.ts +0 -112
  194. package/src/lib/db/paths.ts +0 -128
  195. package/src/lib/db/remote-engine.test.ts +0 -44
  196. package/src/lib/db/remote-engine.ts +0 -148
  197. package/src/lib/db/remote-sql.test.ts +0 -32
  198. package/src/lib/db/remote-sql.ts +0 -62
  199. package/src/lib/db/sql.test.ts +0 -106
  200. package/src/lib/db/sql.ts +0 -192
  201. package/src/lib/hq-cloud-dep.smoke.test.ts +0 -75
  202. package/src/lib/local-tree-diff.test.ts +0 -301
  203. package/src/lib/local-tree-diff.ts +0 -362
  204. package/src/lib/narrow-hint-banner.test.ts +0 -235
  205. package/src/lib/narrow-hint-banner.ts +0 -212
  206. package/src/lib/plan-limit-nag.test.ts +0 -317
  207. package/src/lib/plan-limit-nag.ts +0 -264
  208. package/src/main.ts +0 -371
  209. package/src/node-preflight.test.ts +0 -60
  210. package/src/node-preflight.ts +0 -67
  211. package/src/outpost/session-heartbeat-bounds.test.ts +0 -195
  212. package/src/outpost/session-heartbeat-guard.test.ts +0 -105
  213. package/src/outpost/session-heartbeat-publisher.test.ts +0 -178
  214. package/src/outpost/session-heartbeat-publisher.ts +0 -186
  215. package/src/outpost/session-heartbeat-retain-guard.test.ts +0 -126
  216. package/src/outpost/session-heartbeat.test.ts +0 -459
  217. package/src/outpost/session-heartbeat.ts +0 -877
  218. package/src/packaging.test.ts +0 -109
  219. package/src/run/__fixtures__/discover-schemas/example.env.schema +0 -4
  220. package/src/run/discover-schemas.test.ts +0 -153
  221. package/src/run/discover-schemas.ts +0 -79
  222. package/src/run/hq-plugin.test.ts +0 -371
  223. package/src/run/hq-plugin.ts +0 -277
  224. package/src/run/varlock-shape.test.ts +0 -57
  225. package/src/schemas/hq-package.schema.json +0 -155
  226. package/src/sentry-before-send.test.ts +0 -359
  227. package/src/sentry-before-send.ts +0 -221
  228. package/src/sentry-epipe.test.ts +0 -37
  229. package/src/sentry-release.test.ts +0 -54
  230. package/src/sentry.test.ts +0 -24
  231. package/src/sentry.ts +0 -54
  232. package/src/strategies/link.ts +0 -62
  233. package/src/strategies/merge.ts +0 -142
  234. package/src/types.ts +0 -146
  235. package/src/utils/__fixtures__/scan-packages.generated-block.sh +0 -23
  236. package/src/utils/auth-error.test.ts +0 -40
  237. package/src/utils/auth-error.ts +0 -42
  238. package/src/utils/billing-gate.test.ts +0 -95
  239. package/src/utils/billing-gate.ts +0 -228
  240. package/src/utils/breadcrumb-buffer.ts +0 -18
  241. package/src/utils/cli-telemetry.test.ts +0 -153
  242. package/src/utils/cli-telemetry.ts +0 -61
  243. package/src/utils/cognito-session.machine.test.ts +0 -109
  244. package/src/utils/cognito-session.refresh.test.ts +0 -84
  245. package/src/utils/cognito-session.test.ts +0 -328
  246. package/src/utils/cognito-session.ts +0 -448
  247. package/src/utils/company-selection-error.test.ts +0 -42
  248. package/src/utils/company-selection-error.ts +0 -45
  249. package/src/utils/contribution-table.ts +0 -83
  250. package/src/utils/environmental-error.test.ts +0 -45
  251. package/src/utils/environmental-error.ts +0 -39
  252. package/src/utils/epipe.test.ts +0 -28
  253. package/src/utils/epipe.ts +0 -29
  254. package/src/utils/expected-cli-error.test.ts +0 -28
  255. package/src/utils/expected-cli-error.ts +0 -39
  256. package/src/utils/feedback-diagnostics.test.ts +0 -183
  257. package/src/utils/feedback-diagnostics.ts +0 -123
  258. package/src/utils/feedback-screenshots.test.ts +0 -134
  259. package/src/utils/feedback-screenshots.ts +0 -124
  260. package/src/utils/feedback-versions.test.ts +0 -98
  261. package/src/utils/feedback-versions.ts +0 -68
  262. package/src/utils/git.ts +0 -74
  263. package/src/utils/integrity.ts +0 -59
  264. package/src/utils/intercepted-process-exit.test.ts +0 -37
  265. package/src/utils/intercepted-process-exit.ts +0 -36
  266. package/src/utils/login-provider.test.ts +0 -42
  267. package/src/utils/login-provider.ts +0 -30
  268. package/src/utils/manifest.test.ts +0 -167
  269. package/src/utils/manifest.ts +0 -131
  270. package/src/utils/pack-contributions.test.ts +0 -603
  271. package/src/utils/pack-contributions.ts +0 -450
  272. package/src/utils/people.ts +0 -215
  273. package/src/utils/registry-client.ts +0 -204
  274. package/src/utils/registry.ts +0 -90
  275. package/src/utils/resolve-vault-credential.test.ts +0 -69
  276. package/src/utils/resolve-vault-credential.ts +0 -60
  277. package/src/utils/sandbox-runner-client.test.ts +0 -279
  278. package/src/utils/sandbox-runner-client.ts +0 -260
  279. package/src/utils/secrets-cache.ts +0 -183
  280. package/src/utils/sentry-identity.ts +0 -45
  281. package/src/utils/settle-with-timeout.test.ts +0 -21
  282. package/src/utils/settle-with-timeout.ts +0 -22
  283. package/src/utils/user-yaml-error.test.ts +0 -24
  284. package/src/utils/user-yaml-error.ts +0 -30
  285. package/src/utils/vault-api.test.ts +0 -536
  286. package/src/utils/vault-api.ts +0 -382
  287. package/src/utils/version-check.test.ts +0 -176
  288. package/src/utils/version-check.ts +0 -155
  289. package/src/utils/version-gate.test.ts +0 -1024
  290. package/src/utils/version-gate.ts +0 -702
  291. package/test/commands/db-tenant-isolation.test.ts +0 -94
  292. package/test/commands/db.test.ts +0 -85
  293. package/test/commands/signals.test.ts +0 -207
  294. package/test/commands/sources.test.ts +0 -231
  295. package/test/e2e/smoke-install-mcp.sh +0 -113
  296. package/test/fixtures/hq-pack-smoke-mcp/mcp/smoke-http.json +0 -1
  297. package/test/fixtures/hq-pack-smoke-mcp/package.yaml +0 -11
  298. package/test/fixtures/signals/action_item/sample.md +0 -16
  299. package/test/fixtures/signals/summary/sample.md +0 -12
  300. package/test/fixtures/sources/meetings/sample.md +0 -25
  301. package/test/helpers/cli-runner.ts +0 -150
  302. package/test/helpers/s3-list-mock.ts +0 -79
  303. package/test/helpers/vault-service-mock.ts +0 -295
  304. package/test/sources-signals/smoke.test.ts +0 -228
  305. package/tsconfig.json +0 -20
  306. package/vitest.config.ts +0 -11
  307. package/vitest.e2e.config.ts +0 -7
@@ -1,113 +0,0 @@
1
- /**
2
- * Control-plane client for remote vault DB (US-009).
3
- * Injectable fetch for tests — never logs response bodies that might hold secrets.
4
- */
5
-
6
- export interface RemoteProvisionResponse {
7
- ok: boolean;
8
- companyUid: string;
9
- companySlug: string;
10
- engineId: string;
11
- resourceArn: string;
12
- region: string;
13
- status: string;
14
- secretRef: string;
15
- idempotent: boolean;
16
- }
17
-
18
- export interface RemoteStatusResponse {
19
- companyUid: string;
20
- companySlug?: string;
21
- remote: {
22
- engineId: string;
23
- resourceArn: string;
24
- region: string;
25
- status: string;
26
- secretRef: string;
27
- } | null;
28
- }
29
-
30
- export interface ControlPlaneClientOptions {
31
- baseUrl: string;
32
- /** Bearer access token */
33
- getAccessToken: () => Promise<string>;
34
- fetchImpl?: typeof fetch;
35
- }
36
-
37
- function assertNoPostgresUrl(label: string, text: string): void {
38
- if (/postgres:\/\//i.test(text) || /postgresql:\/\//i.test(text)) {
39
- throw new Error(
40
- `${label}: control plane returned a connection string (refusing to surface)`,
41
- );
42
- }
43
- }
44
-
45
- export class ControlPlaneDbClient {
46
- private readonly baseUrl: string;
47
- private readonly getAccessToken: () => Promise<string>;
48
- private readonly fetchImpl: typeof fetch;
49
-
50
- constructor(opts: ControlPlaneClientOptions) {
51
- this.baseUrl = opts.baseUrl.replace(/\/$/, "");
52
- this.getAccessToken = opts.getAccessToken;
53
- this.fetchImpl = opts.fetchImpl ?? fetch;
54
- }
55
-
56
- async provision(input: {
57
- companyUid: string;
58
- companySlug: string;
59
- region?: string;
60
- }): Promise<RemoteProvisionResponse> {
61
- const token = await this.getAccessToken();
62
- const res = await this.fetchImpl(`${this.baseUrl}/v1/db/provision`, {
63
- method: "POST",
64
- headers: {
65
- Authorization: `Bearer ${token}`,
66
- "Content-Type": "application/json",
67
- },
68
- body: JSON.stringify(input),
69
- });
70
- const text = await res.text();
71
- assertNoPostgresUrl("provision", text);
72
- if (!res.ok) {
73
- let msg = `provision failed (${res.status})`;
74
- let code: string | undefined;
75
- try {
76
- const j = JSON.parse(text) as { error?: string; code?: string };
77
- if (j.error) msg = j.error;
78
- if (j.code) code = j.code;
79
- } catch {
80
- /* keep */
81
- }
82
- const err = new Error(msg) as Error & { status?: number; code?: string };
83
- err.status = res.status;
84
- if (code) err.code = code;
85
- throw err;
86
- }
87
- return JSON.parse(text) as RemoteProvisionResponse;
88
- }
89
-
90
- async status(companyUid: string): Promise<RemoteStatusResponse> {
91
- const token = await this.getAccessToken();
92
- const url = `${this.baseUrl}/v1/db/status?companyUid=${encodeURIComponent(companyUid)}`;
93
- const res = await this.fetchImpl(url, {
94
- method: "GET",
95
- headers: { Authorization: `Bearer ${token}` },
96
- });
97
- const text = await res.text();
98
- assertNoPostgresUrl("status", text);
99
- if (!res.ok) {
100
- let msg = `status failed (${res.status})`;
101
- try {
102
- const j = JSON.parse(text) as { error?: string };
103
- if (j.error) msg = j.error;
104
- } catch {
105
- /* keep */
106
- }
107
- const err = new Error(msg) as Error & { status?: number };
108
- err.status = res.status;
109
- throw err;
110
- }
111
- return JSON.parse(text) as RemoteStatusResponse;
112
- }
113
- }
@@ -1,81 +0,0 @@
1
- /**
2
- * Local vault SQLite open/status tests (vault-databases US-003).
3
- */
4
-
5
- import fs from "node:fs";
6
- import os from "node:os";
7
- import path from "node:path";
8
-
9
- import { afterEach, describe, expect, it } from "vitest";
10
-
11
- import {
12
- ensureAndStatusLocalDb,
13
- openLocalDb,
14
- readMigrationHead,
15
- } from "./local.js";
16
- import { resolveLocalDbPath } from "./paths.js";
17
-
18
- const tempHomes: string[] = [];
19
-
20
- function makeTempHome(): string {
21
- const dir = fs.mkdtempSync(path.join(os.tmpdir(), "hq-db-local-"));
22
- tempHomes.push(dir);
23
- return dir;
24
- }
25
-
26
- afterEach(() => {
27
- while (tempHomes.length > 0) {
28
- const dir = tempHomes.pop();
29
- if (dir) fs.rmSync(dir, { recursive: true, force: true });
30
- }
31
- });
32
-
33
- describe("openLocalDb / ensureAndStatusLocalDb", () => {
34
- it("creates SQLite at canonical path with WAL on first open", () => {
35
- const home = makeTempHome();
36
- const status = ensureAndStatusLocalDb("fixture-co", { home });
37
- const dbPath = resolveLocalDbPath("fixture-co", { home });
38
-
39
- expect(status.healthy).toBe(true);
40
- expect(status.tier).toBe("local");
41
- expect(status.company).toBe("fixture-co");
42
- expect(status.path).toBe(dbPath);
43
- expect(status.journalMode?.toLowerCase()).toBe("wal");
44
- expect(fs.existsSync(dbPath)).toBe(true);
45
- expect(status.schemaVersion).toBeNull();
46
- // Never a remote URL
47
- expect(JSON.stringify(status)).not.toMatch(/postgres:\/\//i);
48
- });
49
-
50
- it("second open is idempotent (file survives, no wipe)", () => {
51
- const home = makeTempHome();
52
- const dbPath = resolveLocalDbPath("idem", { home });
53
-
54
- const db1 = openLocalDb("idem", { home });
55
- db1.exec("CREATE TABLE smoke (id INTEGER PRIMARY KEY, v TEXT)");
56
- db1.prepare("INSERT INTO smoke (v) VALUES (?)").run("keep-me");
57
- db1.close();
58
-
59
- const stat1 = fs.statSync(dbPath);
60
- const status2 = ensureAndStatusLocalDb("idem", { home });
61
- expect(status2.healthy).toBe(true);
62
-
63
- const db2 = openLocalDb("idem", { home });
64
- const row = db2.prepare("SELECT v FROM smoke WHERE id = 1").get() as {
65
- v: string;
66
- };
67
- expect(row.v).toBe("keep-me");
68
- db2.close();
69
-
70
- const stat2 = fs.statSync(dbPath);
71
- // Size should not collapse (recreate would lose data / shrink oddly)
72
- expect(stat2.size).toBeGreaterThanOrEqual(stat1.size);
73
- });
74
-
75
- it("readMigrationHead returns null without ledger table", () => {
76
- const home = makeTempHome();
77
- const db = openLocalDb("noleger", { home });
78
- expect(readMigrationHead(db)).toBeNull();
79
- db.close();
80
- });
81
- });
@@ -1,148 +0,0 @@
1
- /**
2
- * Local vault SQLite open/create (C1).
3
- *
4
- * File lives at ~/.hq/db/{company}/vault.db with WAL journal mode.
5
- * Never returns or logs remote connection strings.
6
- */
7
-
8
- import fs from "node:fs";
9
-
10
- import Database from "better-sqlite3";
11
-
12
- import {
13
- ensureLocalDbDir,
14
- resolveLocalDbPath,
15
- type LocalDbPathEnv,
16
- } from "./paths.js";
17
-
18
- export type LocalDb = Database.Database;
19
-
20
- export interface OpenLocalDbOptions extends LocalDbPathEnv {
21
- /** When true, do not create the file if missing (throws). Default false. */
22
- readonly?: boolean;
23
- }
24
-
25
- export interface LocalDbStatus {
26
- company: string;
27
- tier: "local";
28
- path: string;
29
- exists: boolean;
30
- healthy: boolean;
31
- journalMode: string | null;
32
- /** Migration ledger head when present; null if ledger not initialized. */
33
- schemaVersion: string | null;
34
- /** Fingerprint of path for logs that prefer not to echo full home paths. */
35
- pathFingerprint: string;
36
- }
37
-
38
- const MIGRATIONS_TABLE = "hq_schema_migrations";
39
-
40
- /**
41
- * Short non-reversible fingerprint of a path (for status display).
42
- * Not a secret — just avoids dumping full home paths when preferred.
43
- */
44
- export function fingerprintPath(filePath: string): string {
45
- let h = 2166136261;
46
- for (let i = 0; i < filePath.length; i++) {
47
- h ^= filePath.charCodeAt(i);
48
- h = Math.imul(h, 16777619);
49
- }
50
- return `fp_${(h >>> 0).toString(16).padStart(8, "0")}`;
51
- }
52
-
53
- /**
54
- * Open (and create if missing) the company local vault DB with WAL mode.
55
- * Idempotent: reopening an existing file does not recreate or wipe it.
56
- */
57
- export function openLocalDb(
58
- companySlug: string,
59
- opts?: OpenLocalDbOptions,
60
- ): LocalDb {
61
- const dbPath = resolveLocalDbPath(companySlug, opts);
62
- const exists = fs.existsSync(dbPath);
63
-
64
- if (!exists) {
65
- if (opts?.readonly) {
66
- throw new Error(
67
- `local vault DB not found for company ${JSON.stringify(companySlug)} at ${dbPath}`,
68
- );
69
- }
70
- ensureLocalDbDir(companySlug, opts);
71
- }
72
-
73
- const db = new Database(dbPath);
74
- // WAL for concurrent readers; safe for agent/CLI workloads.
75
- db.pragma("journal_mode = WAL");
76
- db.pragma("foreign_keys = ON");
77
- return db;
78
- }
79
-
80
- /**
81
- * Read migration head from platform ledger if the table exists.
82
- */
83
- export function readMigrationHead(db: LocalDb): string | null {
84
- try {
85
- const row = db
86
- .prepare(
87
- `SELECT name FROM sqlite_master WHERE type='table' AND name=?`,
88
- )
89
- .get(MIGRATIONS_TABLE) as { name?: string } | undefined;
90
- if (!row?.name) return null;
91
-
92
- const head = db
93
- .prepare(
94
- `SELECT version FROM ${MIGRATIONS_TABLE} ORDER BY version DESC LIMIT 1`,
95
- )
96
- .get() as { version?: string } | undefined;
97
- return head?.version ?? null;
98
- } catch {
99
- return null;
100
- }
101
- }
102
-
103
- /**
104
- * Ensure local DB exists (create if needed), report status, close handle.
105
- * Safe for CLI status: never includes connection strings.
106
- */
107
- export function ensureAndStatusLocalDb(
108
- companySlug: string,
109
- opts?: LocalDbPathEnv,
110
- ): LocalDbStatus {
111
- const dbPath = resolveLocalDbPath(companySlug, opts);
112
- const db = openLocalDb(companySlug, opts);
113
- try {
114
- const journalMode = String(db.pragma("journal_mode", { simple: true }));
115
- const schemaVersion = readMigrationHead(db);
116
- // Touch a trivial query to prove the handle is healthy.
117
- db.prepare("SELECT 1 AS ok").get();
118
-
119
- return {
120
- company: companySlug.trim().toLowerCase(),
121
- tier: "local",
122
- path: dbPath,
123
- exists: true,
124
- healthy: true,
125
- journalMode,
126
- schemaVersion,
127
- pathFingerprint: fingerprintPath(dbPath),
128
- };
129
- } finally {
130
- db.close();
131
- }
132
- }
133
-
134
- /**
135
- * Format status for CLI stdout (no secrets).
136
- */
137
- export function formatLocalDbStatus(status: LocalDbStatus): string {
138
- const lines = [
139
- `company: ${status.company}`,
140
- `tier: ${status.tier}`,
141
- `healthy: ${status.healthy ? "yes" : "no"}`,
142
- `path: ${status.path}`,
143
- `pathFingerprint: ${status.pathFingerprint}`,
144
- `journalMode: ${status.journalMode ?? "unknown"}`,
145
- `schemaVersion: ${status.schemaVersion ?? "(none)"}`,
146
- ];
147
- return lines.join("\n");
148
- }
@@ -1,133 +0,0 @@
1
- /**
2
- * Migration apply/idempotent/failure tests (vault-databases US-005).
3
- */
4
-
5
- import fs from "node:fs";
6
- import os from "node:os";
7
- import path from "node:path";
8
-
9
- import { afterEach, describe, expect, it } from "vitest";
10
-
11
- import { openLocalDb } from "./local.js";
12
- import { migrateLocalDb, resolveMigrationsDir } from "./migrate.js";
13
-
14
- const tempRoots: string[] = [];
15
-
16
- function makeFixture(): { home: string; hqRoot: string } {
17
- const root = fs.mkdtempSync(path.join(os.tmpdir(), "hq-db-migrate-"));
18
- tempRoots.push(root);
19
- const home = path.join(root, "home");
20
- const hqRoot = path.join(root, "hq");
21
- fs.mkdirSync(home, { recursive: true });
22
- fs.mkdirSync(hqRoot, { recursive: true });
23
- return { home, hqRoot };
24
- }
25
-
26
- function writeMigration(
27
- hqRoot: string,
28
- company: string,
29
- name: string,
30
- sql: string,
31
- ): void {
32
- const dir = resolveMigrationsDir(hqRoot, company);
33
- fs.mkdirSync(dir, { recursive: true });
34
- fs.writeFileSync(path.join(dir, name), sql, "utf8");
35
- }
36
-
37
- afterEach(() => {
38
- while (tempRoots.length > 0) {
39
- const dir = tempRoots.pop();
40
- if (dir) fs.rmSync(dir, { recursive: true, force: true });
41
- }
42
- });
43
-
44
- describe("migrateLocalDb", () => {
45
- it("applies one migration and records ledger", () => {
46
- const { home, hqRoot } = makeFixture();
47
- writeMigration(
48
- hqRoot,
49
- "indigo",
50
- "001_create_t.sql",
51
- "CREATE TABLE t (id INTEGER PRIMARY KEY);",
52
- );
53
-
54
- const result = migrateLocalDb({ company: "indigo", home, hqRoot });
55
- expect(result.applied).toEqual(["001_create_t.sql"]);
56
- expect(result.head).toBe("001_create_t");
57
-
58
- const db = openLocalDb("indigo", { home });
59
- const row = db
60
- .prepare(
61
- "SELECT name FROM sqlite_master WHERE type='table' AND name='t'",
62
- )
63
- .get() as { name: string };
64
- expect(row.name).toBe("t");
65
- db.close();
66
- });
67
-
68
- it("applies two migrations in order", () => {
69
- const { home, hqRoot } = makeFixture();
70
- writeMigration(
71
- hqRoot,
72
- "indigo",
73
- "001_a.sql",
74
- "CREATE TABLE a (id INTEGER PRIMARY KEY);",
75
- );
76
- writeMigration(
77
- hqRoot,
78
- "indigo",
79
- "002_b.sql",
80
- "CREATE TABLE b (id INTEGER PRIMARY KEY);",
81
- );
82
-
83
- const result = migrateLocalDb({ company: "indigo", home, hqRoot });
84
- expect(result.applied).toEqual(["001_a.sql", "002_b.sql"]);
85
- expect(result.head).toBe("002_b");
86
- });
87
-
88
- it("re-run is idempotent", () => {
89
- const { home, hqRoot } = makeFixture();
90
- writeMigration(
91
- hqRoot,
92
- "indigo",
93
- "001_t.sql",
94
- "CREATE TABLE t (id INTEGER PRIMARY KEY);",
95
- );
96
-
97
- migrateLocalDb({ company: "indigo", home, hqRoot });
98
- const second = migrateLocalDb({ company: "indigo", home, hqRoot });
99
- expect(second.applied).toEqual([]);
100
- expect(second.skipped).toContain("001_t.sql");
101
- expect(second.head).toBe("001_t");
102
- });
103
-
104
- it("failed migration is not marked applied", () => {
105
- const { home, hqRoot } = makeFixture();
106
- writeMigration(
107
- hqRoot,
108
- "indigo",
109
- "001_ok.sql",
110
- "CREATE TABLE ok (id INTEGER PRIMARY KEY);",
111
- );
112
- writeMigration(
113
- hqRoot,
114
- "indigo",
115
- "002_bad.sql",
116
- "CREATE TABLE ok (id INTEGER PRIMARY KEY);", // duplicate → fail
117
- );
118
-
119
- expect(() =>
120
- migrateLocalDb({ company: "indigo", home, hqRoot }),
121
- ).toThrow(/002_bad\.sql/);
122
-
123
- const db = openLocalDb("indigo", { home });
124
- const versions = db
125
- .prepare("SELECT version FROM hq_schema_migrations ORDER BY version")
126
- .all() as { version: string }[];
127
- expect(versions.map((v) => v.version)).toEqual(["001_ok"]);
128
- expect(
129
- versions.map((v) => v.version).includes("002_bad"),
130
- ).toBe(false);
131
- db.close();
132
- });
133
- });
@@ -1,137 +0,0 @@
1
- /**
2
- * Vault text migrations for local SQLite (vault-databases US-005).
3
- *
4
- * Migrations live as reviewable text under:
5
- * companies/{company}/db/migrations/*.sql
6
- * Applied versions are recorded in hq_schema_migrations inside the local DB.
7
- */
8
-
9
- import fs from "node:fs";
10
- import path from "node:path";
11
-
12
- import type { LocalDb } from "./local.js";
13
- import { openLocalDb, readMigrationHead } from "./local.js";
14
- import type { LocalDbPathEnv } from "./paths.js";
15
- import { normalizeCompanySlugForLocalDb } from "./paths.js";
16
-
17
- export const MIGRATIONS_TABLE = "hq_schema_migrations";
18
-
19
- export interface MigrateOptions extends LocalDbPathEnv {
20
- company: string;
21
- /**
22
- * Absolute path to HQ root containing companies/{co}/db/migrations.
23
- * Required for vault-relative migrations.
24
- */
25
- hqRoot: string;
26
- }
27
-
28
- export interface MigrateResult {
29
- company: string;
30
- migrationsDir: string;
31
- applied: string[];
32
- skipped: string[];
33
- head: string | null;
34
- }
35
-
36
- export function resolveMigrationsDir(hqRoot: string, companySlug: string): string {
37
- const slug = normalizeCompanySlugForLocalDb(companySlug);
38
- return path.join(hqRoot, "companies", slug, "db", "migrations");
39
- }
40
-
41
- /**
42
- * Ensure migrations directory exists (creates empty dir on first migrate).
43
- */
44
- export function ensureMigrationsDir(hqRoot: string, companySlug: string): string {
45
- const dir = resolveMigrationsDir(hqRoot, companySlug);
46
- fs.mkdirSync(dir, { recursive: true });
47
- return dir;
48
- }
49
-
50
- /**
51
- * List pending migration files in lexical/version order (filename sort).
52
- */
53
- export function listMigrationFiles(migrationsDir: string): string[] {
54
- if (!fs.existsSync(migrationsDir)) return [];
55
- return fs
56
- .readdirSync(migrationsDir)
57
- .filter((f) => f.endsWith(".sql"))
58
- .sort((a, b) => a.localeCompare(b, "en"));
59
- }
60
-
61
- export function ensureMigrationsLedger(db: LocalDb): void {
62
- db.exec(`
63
- CREATE TABLE IF NOT EXISTS ${MIGRATIONS_TABLE} (
64
- version TEXT PRIMARY KEY NOT NULL,
65
- applied_at TEXT NOT NULL DEFAULT (datetime('now'))
66
- );
67
- `);
68
- }
69
-
70
- export function listAppliedVersions(db: LocalDb): Set<string> {
71
- ensureMigrationsLedger(db);
72
- const rows = db
73
- .prepare(`SELECT version FROM ${MIGRATIONS_TABLE} ORDER BY version`)
74
- .all() as { version: string }[];
75
- return new Set(rows.map((r) => r.version));
76
- }
77
-
78
- /**
79
- * Apply pending migrations. On failure, does not mark the failed file applied.
80
- */
81
- export function migrateLocalDb(opts: MigrateOptions): MigrateResult {
82
- const company = normalizeCompanySlugForLocalDb(opts.company);
83
- if (!opts.hqRoot?.trim()) {
84
- throw new Error("hqRoot is required for vault migrations");
85
- }
86
-
87
- const migrationsDir = ensureMigrationsDir(opts.hqRoot, company);
88
- const files = listMigrationFiles(migrationsDir);
89
-
90
- const db = openLocalDb(company, opts);
91
- const applied: string[] = [];
92
- const skipped: string[] = [];
93
-
94
- try {
95
- ensureMigrationsLedger(db);
96
- const already = listAppliedVersions(db);
97
-
98
- for (const file of files) {
99
- const version = file.replace(/\.sql$/i, "");
100
- if (already.has(version) || already.has(file)) {
101
- skipped.push(file);
102
- continue;
103
- }
104
-
105
- const fullPath = path.join(migrationsDir, file);
106
- const sql = fs.readFileSync(fullPath, "utf8");
107
-
108
- const run = db.transaction(() => {
109
- db.exec(sql);
110
- db.prepare(
111
- `INSERT INTO ${MIGRATIONS_TABLE} (version) VALUES (?)`,
112
- ).run(version);
113
- });
114
-
115
- try {
116
- run();
117
- applied.push(file);
118
- already.add(version);
119
- } catch (err) {
120
- const msg = err instanceof Error ? err.message : String(err);
121
- throw new Error(
122
- `migration failed: ${file} — ${msg} (not marked applied)`,
123
- );
124
- }
125
- }
126
-
127
- return {
128
- company,
129
- migrationsDir,
130
- applied,
131
- skipped,
132
- head: readMigrationHead(db),
133
- };
134
- } finally {
135
- db.close();
136
- }
137
- }