@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,942 +0,0 @@
1
- /**
2
- * `hq cloud provision company <slug>` — canonical cloud-promotion subcommand.
3
- *
4
- * Promotes a local company directory (`companies/<slug>/`) to a cloud-backed
5
- * entity by:
6
- * 1. Validating the slug, manifest membership, and local company directory
7
- * 2. Resolving a Cognito access token (refresh as needed)
8
- * 3. Idempotently provisioning the vault entity:
9
- * GET /v1/entities/by-slug/company/<slug> → 200 reuse, 404 → POST /v1/entities
10
- * 4. Atomically patching `companies/manifest.yaml` with `cloud_uid` + `bucket_name`
11
- * 5. Atomically writing `companies/<slug>/.hq/config.json`
12
- * 6. Triggering an initial sync via `share()` from `@indigoai-us/hq-cloud`
13
- * 7. Emitting one structured JSON line to stdout (machine-readable result)
14
- *
15
- * Replaces three ad-hoc implementations:
16
- * - `designate-team` bash script (hq-core-staging)
17
- * - AppBar `provision.rs` (hq-sync, auto-provision on first sync)
18
- * - AppBar `workspaces.rs` Connect flow (hq-sync, manual Connect)
19
- *
20
- * Exit codes:
21
- * 0 — success (and `initial_sync.ok=true`)
22
- * 1 — vault auth/network/API error (no entity provisioned)
23
- * 2 — invalid slug, company dir missing, or company is status=archived.
24
- * Folder-only states (companies/<slug>/ exists on disk but no manifest
25
- * entry) self-heal via ensureManifestEntryForProvision before
26
- * validation runs, so a missing manifest entry alone is NOT an exit-2.
27
- * 3 — sync failure after entity provisioned (cloud_uid in JSON;
28
- * `initial_sync.ok=false`). Manifest + config may have been written.
29
- */
30
-
31
- import { Command } from "commander";
32
- import chalk from "chalk";
33
- import * as fs from "node:fs";
34
- import * as path from "node:path";
35
- import * as yaml from "js-yaml";
36
- import { parseUserYaml } from "../utils/user-yaml-error.js";
37
-
38
- import { share } from "@indigoai-us/hq-cloud";
39
-
40
- import {
41
- DEFAULT_HQ_ROOT,
42
- DEFAULT_VAULT_API_URL,
43
- ensureCognitoToken,
44
- buildVaultConfig,
45
- } from "../utils/cognito-session.js";
46
-
47
- // ── Types ────────────────────────────────────────────────────────────────────
48
-
49
- /** Vault entity shape (subset we consume). Mirrors hq-pro entity types. */
50
- export interface VaultEntity {
51
- uid: string;
52
- type: string;
53
- slug: string;
54
- name: string;
55
- bucketName?: string;
56
- kmsKeyId?: string | null;
57
- status?: string;
58
- ownerUid?: string;
59
- }
60
-
61
- /** Per-company `.hq/config.json` schema (matches AppBar `provision.rs::CompanyConfig`). */
62
- export interface CompanyConfig {
63
- companyUid: string;
64
- companySlug: string;
65
- bucketName: string;
66
- vaultApiUrl: string;
67
- }
68
-
69
- /** Final stdout JSON shape. Consumers (designate-team, AppBar) parse this. */
70
- export interface ProvisionResult {
71
- ok: boolean;
72
- company_slug: string;
73
- cloud_uid: string;
74
- bucket_name: string;
75
- vault_api_url: string;
76
- kms_key_id: string | null;
77
- created_entity: boolean;
78
- manifest_patched: boolean;
79
- config_written: boolean;
80
- initial_sync: {
81
- ok?: boolean;
82
- files_uploaded?: number;
83
- bytes_uploaded?: number;
84
- error?: string;
85
- /** True if the caller passed --skip-initial-sync; ok/files/bytes will be absent. */
86
- skipped?: boolean;
87
- };
88
- }
89
-
90
- /** Options for the high-level `provisionCompany` orchestrator. */
91
- export interface ProvisionCompanyOptions {
92
- slug: string;
93
- name?: string;
94
- ownerUid?: string;
95
- hqRoot: string;
96
- vaultApiUrl: string;
97
- /**
98
- * Skip the initial-sync step. The vault entity, manifest patch, and
99
- * `.hq/config.json` write still happen; the post-provision `share()` call
100
- * is no-op'd. Use this when the caller has its own upload pipeline (e.g.
101
- * AppBar HQ Sync's `first_push_company` with STS-vended credentials and
102
- * Tauri progress events) and would otherwise double-upload the same files.
103
- * When true, `initial_sync` in the result is `{ skipped: true }`.
104
- */
105
- skipInitialSync?: boolean;
106
- /** Injected vault HTTP client (override for tests). */
107
- vaultClient?: VaultClient;
108
- /** Injected access-token resolver (override for tests). */
109
- resolveAccessToken?: () => Promise<string>;
110
- /** Injected sync runner (override for tests). */
111
- runInitialSync?: (args: InitialSyncArgs) => Promise<{
112
- filesUploaded: number;
113
- bytesUploaded: number;
114
- }>;
115
- /** Optional progress logger; defaults to stderr-prefixed `[hq cloud provision]`. */
116
- log?: (msg: string) => void;
117
- }
118
-
119
- interface InitialSyncArgs {
120
- slug: string;
121
- hqRoot: string;
122
- accessToken: string;
123
- vaultApiUrl: string;
124
- }
125
-
126
- /** Vault HTTP client interface — minimal surface for entity ops. */
127
- export interface VaultClient {
128
- /**
129
- * List every person entity visible to the caller (scoped server-side by the
130
- * caller's Cognito identity). Used by `provisionCompany` as a pre-flight
131
- * to verify the caller has been onboarded before mutating any cloud-side
132
- * resources — the initial-sync step at the end of provision needs to vend
133
- * STS credentials, which the server only does for callers with a person
134
- * entity.
135
- */
136
- listMyPersonEntities(): Promise<VaultEntity[]>;
137
- /**
138
- * Legacy global-uniqueness lookup. Under the per-user-namespace model
139
- * (hq-pro 2026-05-15) this can return any tenant's entity when more
140
- * than one user holds the same slug, OR `null` when the caller doesn't
141
- * have it but a different user does. Kept on the interface for any
142
- * remaining callers, but `provisionCompany` now uses
143
- * `checkSlugInMyNamespace` instead — same-slug-different-owner is
144
- * legitimate and should NOT trigger reuse of the stranger's entity.
145
- */
146
- findCompanyBySlug(slug: string): Promise<VaultEntity | null>;
147
- /**
148
- * Caller-scoped slug availability check via
149
- * `GET /entity/check-slug/me?type=company&slug=...`. Returns
150
- * `{available: true}` when the caller's namespace
151
- * (owned ∪ active-member-of, soft-deleted excluded) doesn't hold the
152
- * slug, or `{available: false, conflictingCompanyUid}` when it does
153
- * — `provisionCompany` reuses the `conflictingCompanyUid` as the
154
- * idempotent entity instead of creating a duplicate.
155
- */
156
- checkSlugInMyNamespace(slug: string): Promise<{
157
- available: boolean;
158
- conflictingCompanyUid?: string;
159
- }>;
160
- /** Fetch a company entity by uid. Used to materialize the entity
161
- * after `checkSlugInMyNamespace` reports a same-namespace collision. */
162
- getCompanyByUid(uid: string): Promise<VaultEntity>;
163
- createCompanyEntity(input: {
164
- slug: string;
165
- name: string;
166
- ownerUid?: string;
167
- }): Promise<VaultEntity>;
168
- }
169
-
170
- /** Custom error class so the CLI runner can map to exit codes. */
171
- export class ProvisionError extends Error {
172
- constructor(
173
- public readonly code: 1 | 2 | 3,
174
- message: string,
175
- public readonly partial?: Partial<ProvisionResult>,
176
- ) {
177
- super(message);
178
- this.name = "ProvisionError";
179
- }
180
- }
181
-
182
- // ── Validation ───────────────────────────────────────────────────────────────
183
-
184
- const SLUG_REGEX = /^[A-Za-z0-9._-]+$/;
185
- const FORBIDDEN_SLUGS = new Set(["personal", ".", ".."]);
186
-
187
- /**
188
- * Validate a company slug per the contract: alphanumeric / dot / dash / underscore,
189
- * non-empty, never `"."` or `".."` (path-traversal — would resolve to
190
- * `companies/` itself or `<hqRoot>` and write outside the intended company
191
- * directory), and never `"personal"` (auto-provisioned per-user, not promoted
192
- * via this subcommand).
193
- *
194
- * Throws ProvisionError with code=2 on failure.
195
- */
196
- export function validateSlug(slug: string): void {
197
- if (!slug || slug.trim() === "") {
198
- throw new ProvisionError(2, "Slug is required");
199
- }
200
- if (!SLUG_REGEX.test(slug)) {
201
- throw new ProvisionError(
202
- 2,
203
- `Invalid slug "${slug}" — must match ${SLUG_REGEX.source}`,
204
- );
205
- }
206
- if (FORBIDDEN_SLUGS.has(slug)) {
207
- const reason =
208
- slug === "personal"
209
- ? "auto-provisioned per-user, not eligible for cloud promotion"
210
- : "path-traversal slug (would resolve to a directory outside the intended company folder)";
211
- throw new ProvisionError(2, `Slug "${slug}" is reserved (${reason})`);
212
- }
213
- }
214
-
215
- /** Path to the top-level companies manifest file. */
216
- export function manifestPath(hqRoot: string): string {
217
- return path.join(hqRoot, "companies", "manifest.yaml");
218
- }
219
-
220
- /** Path to a company's directory inside the HQ tree. */
221
- export function companyDirPath(hqRoot: string, slug: string): string {
222
- return path.join(hqRoot, "companies", slug);
223
- }
224
-
225
- /** Path to a company's `.hq/config.json`. */
226
- export function companyConfigPath(hqRoot: string, slug: string): string {
227
- return path.join(companyDirPath(hqRoot, slug), ".hq", "config.json");
228
- }
229
-
230
- /**
231
- * Validate that the company exists in the manifest and on disk.
232
- *
233
- * Throws ProvisionError with code=2 if:
234
- * - manifest file missing
235
- * - manifest is malformed (no `companies` map)
236
- * - slug not present under `.companies`
237
- * - company is `status: archived`
238
- * - `companies/<slug>/` does not exist
239
- *
240
- * Strict on purpose — callers that want the "auto-insert a missing entry when
241
- * the local folder exists" affordance (cloud-provision's fault-tolerant flow)
242
- * MUST call `ensureManifestEntryForProvision` first. cloud-demote and other
243
- * sensitive callers depend on this strict failure for typo-catching.
244
- *
245
- * Returns the parsed manifest (so the caller can re-use it for the patch step).
246
- */
247
- export function validateManifestAndDir(
248
- hqRoot: string,
249
- slug: string,
250
- ): { manifest: ManifestDoc } {
251
- const mPath = manifestPath(hqRoot);
252
- if (!fs.existsSync(mPath)) {
253
- throw new ProvisionError(
254
- 2,
255
- `companies/manifest.yaml not found at ${mPath}`,
256
- );
257
- }
258
- const raw = fs.readFileSync(mPath, "utf-8");
259
- const parsed = parseUserYaml<unknown>(raw, mPath);
260
- if (
261
- !parsed ||
262
- typeof parsed !== "object" ||
263
- !("companies" in parsed) ||
264
- typeof (parsed as ManifestDoc).companies !== "object"
265
- ) {
266
- throw new ProvisionError(
267
- 2,
268
- `companies/manifest.yaml is malformed — missing top-level .companies map`,
269
- );
270
- }
271
- const manifest = parsed as ManifestDoc;
272
- const entry = manifest.companies?.[slug];
273
- if (entry === undefined) {
274
- throw new ProvisionError(
275
- 2,
276
- `Company "${slug}" not found under .companies in manifest.yaml`,
277
- );
278
- }
279
- if (entry && typeof entry === "object" && entry.status === "archived") {
280
- throw new ProvisionError(
281
- 2,
282
- `Company "${slug}" is status=archived — refusing to promote`,
283
- );
284
- }
285
- const dir = companyDirPath(hqRoot, slug);
286
- if (!fs.existsSync(dir)) {
287
- throw new ProvisionError(
288
- 2,
289
- `Company directory ${dir} does not exist`,
290
- );
291
- }
292
- return { manifest };
293
- }
294
-
295
- /**
296
- * Provision-only pre-step. If `companies/<slug>/` exists on disk but the slug
297
- * is absent from `manifest.yaml`, atomically insert an empty entry
298
- * (`<slug>: {}`) so the downstream `validateManifestAndDir` + `patchManifest`
299
- * flow has something to operate on. Heals the common folder-only state
300
- * (manual mkdir, or older tools that didn't patch manifest.yaml) that hq-sync's
301
- * Connect button used to dead-end on with exit 2.
302
- *
303
- * No-op in every other case:
304
- * - manifest file missing / malformed (validation will surface)
305
- * - slug already present (any value, including null — preserved as-is)
306
- * - `companies/<slug>/` does not exist (validation will surface as a typo)
307
- *
308
- * This affordance is provision-specific. `cloud-demote` and other strict
309
- * callers MUST NOT call this — their typo-catching contract depends on
310
- * `validateManifestAndDir` throwing on missing-slug.
311
- */
312
- export function ensureManifestEntryForProvision(
313
- hqRoot: string,
314
- slug: string,
315
- ): void {
316
- const mPath = manifestPath(hqRoot);
317
- if (!fs.existsSync(mPath)) return;
318
- // Defense-in-depth against path-traversal slugs (`.`, `..`, anything that
319
- // resolves outside companies/). validateSlug rejects these upstream, but
320
- // this helper is exported and might be called directly by future code —
321
- // never auto-insert based on a path that isn't a literal direct child of
322
- // `companies/`. fs.realpathSync would also catch symlink-escapes, but the
323
- // directory may legitimately not exist yet on disk; path.resolve gives us
324
- // the canonical lexical form without a stat call.
325
- const companiesDir = path.resolve(hqRoot, "companies");
326
- const expected = path.resolve(companiesDir, slug);
327
- const expectedParent = path.dirname(expected);
328
- if (expectedParent !== companiesDir) return;
329
- if (path.basename(expected) !== slug) return;
330
- const dir = companyDirPath(hqRoot, slug);
331
- // Must be an actual directory, not a stray file. fs.existsSync returns true
332
- // for regular files too — without this guard, auto-insert would fire on a
333
- // file at `companies/<slug>`, provisionCompany would then create the vault
334
- // entity and patch manifest.yaml before writeCompanyConfig's `mkdir -p .hq`
335
- // exploded with ENOTDIR. statSync swallows the not-found case so a missing
336
- // path is treated the same as before (no auto-insert).
337
- let dirStat: fs.Stats;
338
- try {
339
- dirStat = fs.statSync(dir);
340
- } catch {
341
- return;
342
- }
343
- if (!dirStat.isDirectory()) return;
344
- const raw = fs.readFileSync(mPath, "utf-8");
345
- let parsed: unknown;
346
- try {
347
- parsed = yaml.load(raw);
348
- } catch {
349
- return;
350
- }
351
- if (
352
- !parsed ||
353
- typeof parsed !== "object" ||
354
- !("companies" in parsed) ||
355
- typeof (parsed as ManifestDoc).companies !== "object"
356
- ) {
357
- return;
358
- }
359
- const doc = parsed as ManifestDoc;
360
- if (!doc.companies) doc.companies = {};
361
- if (doc.companies[slug] !== undefined) return;
362
- doc.companies[slug] = {};
363
- const dump = yaml.dump(doc, { lineWidth: -1, noRefs: true });
364
- const tmp = `${mPath}.tmp.${process.pid}`;
365
- fs.writeFileSync(tmp, dump);
366
- fs.renameSync(tmp, mPath);
367
- }
368
-
369
- // ── Manifest patching (atomic) ───────────────────────────────────────────────
370
-
371
- /**
372
- * Top-level manifest shape we touch. We preserve all unknown fields — only
373
- * `cloud_uid` and `bucket_name` under the target slug are mutated.
374
- */
375
- export interface ManifestDoc {
376
- companies?: Record<string, ManifestCompanyEntry | null>;
377
- [k: string]: unknown;
378
- }
379
-
380
- export interface ManifestCompanyEntry {
381
- cloud_uid?: string;
382
- bucket_name?: string;
383
- status?: string;
384
- [k: string]: unknown;
385
- }
386
-
387
- /**
388
- * Atomically patch `companies/manifest.yaml` to set `cloud_uid` + `bucket_name`
389
- * under the target slug. Read → mutate → temp-write → rename so concurrent
390
- * readers never see a partially-written file.
391
- *
392
- * Skip-if-unchanged: if the target slug already carries the exact
393
- * `cloud_uid` + `bucket_name`, this is a true no-op — the file is left
394
- * byte-for-byte intact (comments, ordering, and formatting preserved) and
395
- * we return `false`. This matters because `yaml.dump` does NOT round-trip
396
- * comments or the original layout: an unconditional rewrite re-canonicalises
397
- * the manifest (stripping the `/newcompany` header comment, reflowing keys)
398
- * on EVERY provision/Connect, even when nothing semantically changed. Each
399
- * such rewrite is then pushed by the initial-sync step, so the
400
- * comment-stripped local form perpetually diverges from any peer/cloud copy
401
- * that still holds the commented form — manifesting as a recurring HQ Sync
402
- * conflict loop on `companies/manifest.yaml` that re-fires every sync. Only
403
- * writing when a value actually changes lets the two forms converge.
404
- *
405
- * Returns true if the file was written, false if it was already current.
406
- */
407
- export function patchManifest(
408
- hqRoot: string,
409
- slug: string,
410
- cloudUid: string,
411
- bucketName: string,
412
- ): boolean {
413
- const mPath = manifestPath(hqRoot);
414
- const raw = fs.readFileSync(mPath, "utf-8");
415
- const parsed = parseUserYaml<ManifestDoc | null>(raw, mPath) ?? { companies: {} };
416
- if (!parsed.companies) parsed.companies = {};
417
- const existing = parsed.companies[slug];
418
- // Preserve null / object / unknown — promote null → {} so we can write keys.
419
- const entry: ManifestCompanyEntry =
420
- existing && typeof existing === "object" ? { ...existing } : {};
421
-
422
- // No-op guard: both fields already match → leave the on-disk file (and its
423
- // comments) untouched so a re-provision can't churn the manifest and seed a
424
- // sync conflict loop.
425
- if (entry.cloud_uid === cloudUid && entry.bucket_name === bucketName) {
426
- return false;
427
- }
428
-
429
- entry.cloud_uid = cloudUid;
430
- entry.bucket_name = bucketName;
431
- parsed.companies[slug] = entry;
432
-
433
- const dump = yaml.dump(parsed, { lineWidth: -1, noRefs: true });
434
- const tmp = `${mPath}.tmp.${process.pid}`;
435
- fs.writeFileSync(tmp, dump);
436
- fs.renameSync(tmp, mPath);
437
- return true;
438
- }
439
-
440
- // ── .hq/config.json writing (atomic) ─────────────────────────────────────────
441
-
442
- /**
443
- * Atomically write `companies/<slug>/.hq/config.json` with the cloud-promotion
444
- * config. Creates the parent `.hq/` directory if needed. Temp-write + rename
445
- * so concurrent readers never see a partial file.
446
- *
447
- * Idempotent: a re-run with the same inputs writes byte-identical output.
448
- */
449
- export function writeCompanyConfig(
450
- hqRoot: string,
451
- slug: string,
452
- config: CompanyConfig,
453
- ): boolean {
454
- const cPath = companyConfigPath(hqRoot, slug);
455
- const dir = path.dirname(cPath);
456
- fs.mkdirSync(dir, { recursive: true });
457
- const body = JSON.stringify(config, null, 2) + "\n";
458
- const tmp = `${cPath}.tmp.${process.pid}`;
459
- fs.writeFileSync(tmp, body);
460
- fs.renameSync(tmp, cPath);
461
- return true;
462
- }
463
-
464
- // ── Vault HTTP client (real impl) ────────────────────────────────────────────
465
-
466
- /**
467
- * Default vault HTTP client backed by global `fetch`. Uses the `/v1/entities`
468
- * route surface (matches AppBar `vault_client.rs` and hq-pro handler routes).
469
- *
470
- * Note: the hq-pro handler.ts uses `/entity` (singular, no `/v1/`); the API
471
- * Gateway in front of it exposes the same handlers under `/v1/entities/*`
472
- * (plural) — the deployed surface is the prefixed form, which is what
473
- * AppBar (`vault_client.rs`) and the architecture audit document. We use
474
- * the deployed `/v1/entities/*` form here.
475
- */
476
- export function createDefaultVaultClient(
477
- apiUrl: string,
478
- accessToken: string,
479
- ): VaultClient {
480
- const headers: Record<string, string> = {
481
- "Content-Type": "application/json",
482
- Authorization: `Bearer ${accessToken}`,
483
- };
484
- return {
485
- async listMyPersonEntities(): Promise<VaultEntity[]> {
486
- const url = `${apiUrl.replace(/\/$/, "")}/entity/by-type/person`;
487
- const res = await fetch(url, { method: "GET", headers });
488
- if (res.status === 404) return [];
489
- if (!res.ok) {
490
- const body = await safeBody(res);
491
- throw new ProvisionError(
492
- 1,
493
- `Vault GET /entity/by-type/person failed: ${res.status} ${res.statusText} — ${body}`,
494
- );
495
- }
496
- const data = (await res.json()) as { entities?: VaultEntity[] };
497
- return data.entities ?? [];
498
- },
499
- async findCompanyBySlug(slug: string): Promise<VaultEntity | null> {
500
- const url = `${apiUrl.replace(/\/$/, "")}/entity/by-slug/company/${encodeURIComponent(
501
- slug,
502
- )}`;
503
- const res = await fetch(url, { method: "GET", headers });
504
- if (res.status === 404) return null;
505
- if (!res.ok) {
506
- const body = await safeBody(res);
507
- throw new ProvisionError(
508
- 1,
509
- `Vault GET by-slug failed: ${res.status} ${res.statusText} — ${body}`,
510
- );
511
- }
512
- const data = (await res.json()) as { entity?: VaultEntity };
513
- if (!data.entity) {
514
- throw new ProvisionError(
515
- 1,
516
- `Vault GET by-slug returned 200 with no entity body`,
517
- );
518
- }
519
- return data.entity;
520
- },
521
- async checkSlugInMyNamespace(slug: string): Promise<{
522
- available: boolean;
523
- conflictingCompanyUid?: string;
524
- }> {
525
- const url = `${apiUrl.replace(/\/$/, "")}/entity/check-slug/me?type=company&slug=${encodeURIComponent(
526
- slug,
527
- )}`;
528
- const res = await fetch(url, { method: "GET", headers });
529
- if (!res.ok) {
530
- const body = await safeBody(res);
531
- throw new ProvisionError(
532
- 1,
533
- `Vault GET /entity/check-slug/me failed: ${res.status} ${res.statusText} — ${body}`,
534
- );
535
- }
536
- return (await res.json()) as {
537
- available: boolean;
538
- conflictingCompanyUid?: string;
539
- };
540
- },
541
- async getCompanyByUid(uid: string): Promise<VaultEntity> {
542
- const url = `${apiUrl.replace(/\/$/, "")}/entity/${encodeURIComponent(uid)}`;
543
- const res = await fetch(url, { method: "GET", headers });
544
- if (!res.ok) {
545
- const body = await safeBody(res);
546
- throw new ProvisionError(
547
- 1,
548
- `Vault GET /entity/${uid} failed: ${res.status} ${res.statusText} — ${body}`,
549
- );
550
- }
551
- const data = (await res.json()) as { entity?: VaultEntity };
552
- if (!data.entity) {
553
- throw new ProvisionError(
554
- 1,
555
- `Vault GET /entity/${uid} returned 200 with no entity body`,
556
- );
557
- }
558
- return data.entity;
559
- },
560
- async createCompanyEntity(input: {
561
- slug: string;
562
- name: string;
563
- ownerUid?: string;
564
- }): Promise<VaultEntity> {
565
- const url = `${apiUrl.replace(/\/$/, "")}/entity`;
566
- const body: Record<string, unknown> = {
567
- type: "company",
568
- slug: input.slug,
569
- name: input.name,
570
- };
571
- if (input.ownerUid) body.ownerUid = input.ownerUid;
572
- const res = await fetch(url, {
573
- method: "POST",
574
- headers,
575
- body: JSON.stringify(body),
576
- });
577
- if (!res.ok) {
578
- const text = await safeBody(res);
579
- // 409 SLUG_IN_USE_FOR_PERSON: the caller already has the slug
580
- // in their namespace (owned ∪ active-member-of). Under the
581
- // per-user-namespace model this is the new same-user-collision
582
- // signal — distinct from the legacy global EntityAlreadyExists.
583
- // The CLI normally reaches `createCompanyEntity` only after
584
- // `checkSlugInMyNamespace` reported `available: true`, so a
585
- // 409 here means a race between the pre-check and the POST.
586
- // Surface the response body verbatim so the caller can see the
587
- // `code` + `conflictingCompanyUid` and resolve / retry.
588
- throw new ProvisionError(
589
- 1,
590
- `Vault POST /entity failed: ${res.status} ${res.statusText} — ${text}`,
591
- );
592
- }
593
- const data = (await res.json()) as { entity?: VaultEntity };
594
- if (!data.entity) {
595
- throw new ProvisionError(
596
- 1,
597
- `Vault POST /entity returned ${res.status} with no entity body`,
598
- );
599
- }
600
- return data.entity;
601
- },
602
- };
603
- }
604
-
605
- async function safeBody(res: Response): Promise<string> {
606
- try {
607
- return await res.text();
608
- } catch {
609
- return "<no body>";
610
- }
611
- }
612
-
613
- // ── Default initial-sync runner (wraps share()) ──────────────────────────────
614
-
615
- async function defaultRunInitialSync(args: InitialSyncArgs): Promise<{
616
- filesUploaded: number;
617
- bytesUploaded: number;
618
- }> {
619
- const result = await share({
620
- paths: [companyDirPath(args.hqRoot, args.slug)],
621
- company: args.slug,
622
- message: `hq cloud provision:${args.slug}`,
623
- onConflict: "keep",
624
- vaultConfig: buildVaultConfig(args.accessToken),
625
- hqRoot: args.hqRoot,
626
- });
627
- return {
628
- filesUploaded: result.filesUploaded,
629
- bytesUploaded: result.bytesUploaded,
630
- };
631
- }
632
-
633
- // ── Orchestrator ─────────────────────────────────────────────────────────────
634
-
635
- /**
636
- * Run the full 9-step provision flow. Returns a `ProvisionResult` on success
637
- * (including partial success — sync failure after entity provisioned).
638
- *
639
- * Throws `ProvisionError` for terminal failures with the right exit code.
640
- *
641
- * All side effects (HTTP calls, file writes, sync) flow through injected
642
- * helpers so unit tests can fully exercise the flow without network or disk.
643
- */
644
- export async function provisionCompany(
645
- options: ProvisionCompanyOptions,
646
- ): Promise<ProvisionResult> {
647
- const log = options.log ?? ((msg: string) => process.stderr.write(`[hq cloud provision] ${msg}\n`));
648
-
649
- // Step 1+2+3: validate slug, auto-heal a folder-only manifest, then validate
650
- // the resulting manifest + dir. The auto-heal is provision-specific: it
651
- // inserts an empty entry when companies/<slug>/ exists on disk but the slug
652
- // is missing from manifest.yaml. validateManifestAndDir stays strict so
653
- // other callers (cloud-demote) keep their typo-catching guard.
654
- validateSlug(options.slug);
655
- ensureManifestEntryForProvision(options.hqRoot, options.slug);
656
- validateManifestAndDir(options.hqRoot, options.slug);
657
- log(`validated slug=${options.slug}`);
658
-
659
- // Step 4: auth — defer to injected resolver (default: ensureCognitoToken)
660
- const accessToken = options.resolveAccessToken
661
- ? await options.resolveAccessToken()
662
- : await ensureCognitoToken();
663
- log(`acquired Cognito access token`);
664
-
665
- // Step 5: GET-then-POST for idempotency
666
- const vaultClient =
667
- options.vaultClient ??
668
- createDefaultVaultClient(options.vaultApiUrl, accessToken);
669
-
670
- // Pre-flight: caller MUST have a registered person entity. Without one,
671
- // the initial-sync step at the end of this flow (STS /sts/vend) returns
672
- // 403 "no person entity" and leaves the operator with a half-built cloud
673
- // company — vault entity created, S3 bucket provisioned, manifest patched,
674
- // .hq/config.json written, but nothing actually syncing. This was the
675
- // primary failure mode in the 2026-05-14 setup-session deep dive
676
- // (Joey Muller / sum-digital).
677
- //
678
- // Failing here, BEFORE any cloud-side resource creation, leaves the operator
679
- // with no cleanup work — they fix the underlying onboarding gap (run
680
- // `hq onboard` / sign in with the correct federated identity) and re-run
681
- // `hq cloud provision company <slug>` cleanly.
682
- const persons = await vaultClient.listMyPersonEntities();
683
- if (persons.length === 0) {
684
- throw new ProvisionError(
685
- 2,
686
- 'No person entity found for this Cognito identity. Run `hq onboard` first to create your HQ identity, then re-run `hq cloud provision company`. (Provision was halted before any cloud-side resources were created.)',
687
- );
688
- }
689
- log(`pre-flight ok — caller has ${persons.length} person entity(ies)`);
690
-
691
- // Per-user-namespace-aware reuse-or-create. Replaces the legacy
692
- // global `findCompanyBySlug` lookup, which under the per-user model
693
- // (hq-pro 2026-05-15) returns ANY tenant's entity when more than one
694
- // user holds the same slug, OR null when a different user has it —
695
- // both wrong for the CLI's "reuse mine, or create" intent.
696
- //
697
- // `--owner` override: `options.ownerUid`, when set, lets a caller
698
- // create the entity under a DIFFERENT person's ownership (e.g. an
699
- // admin provisioning on behalf of someone). `/entity/check-slug/me`
700
- // answers about the CALLER's namespace, not the target owner's, so
701
- // the pre-check is meaningless in that case. Codex P2 on PR 7
702
- // flagged this. The gate: only run the namespace check when the
703
- // owner is the caller (or defaulted to the caller — i.e. no
704
- // --owner supplied). On override, fall through to
705
- // `createCompanyEntity` and let the server's authoritative 409
706
- // (which IS scoped to the target's namespace, per the
707
- // callerIsOwner gate on POST /entity in hq-pro PR 67) surface any
708
- // real conflict.
709
- //
710
- // `callerIsOwner` is `true` whenever `options.ownerUid` is unset
711
- // (defaults to caller server-side) OR — when set — happens to
712
- // match the caller's own person UID(s) from `listMyPersonEntities`.
713
- const callerOwnedUids = new Set(persons.map((p) => p.uid));
714
- const callerIsOwner =
715
- !options.ownerUid || callerOwnedUids.has(options.ownerUid);
716
-
717
- let entity: VaultEntity;
718
- let createdEntity = false;
719
- if (callerIsOwner) {
720
- const slugCheck = await vaultClient.checkSlugInMyNamespace(options.slug);
721
- if (!slugCheck.available && slugCheck.conflictingCompanyUid) {
722
- log(
723
- `reusing existing vault entity uid=${slugCheck.conflictingCompanyUid} (slug already in caller's namespace)`,
724
- );
725
- entity = await vaultClient.getCompanyByUid(
726
- slugCheck.conflictingCompanyUid,
727
- );
728
- } else {
729
- log(`slug available in caller's namespace — creating vault entity`);
730
- entity = await vaultClient.createCompanyEntity({
731
- slug: options.slug,
732
- name: options.name ?? options.slug,
733
- ownerUid: options.ownerUid,
734
- });
735
- createdEntity = true;
736
- log(`created vault entity uid=${entity.uid}`);
737
- }
738
- } else {
739
- log(
740
- `--owner ${options.ownerUid} differs from caller's person(s); skipping namespace pre-check (server authoritatively gates per-target-namespace)`,
741
- );
742
- entity = await vaultClient.createCompanyEntity({
743
- slug: options.slug,
744
- name: options.name ?? options.slug,
745
- ownerUid: options.ownerUid,
746
- });
747
- createdEntity = true;
748
- log(`created vault entity uid=${entity.uid}`);
749
- }
750
-
751
- if (!entity.bucketName) {
752
- // Vault returned an entity without a bucket — this would happen if the
753
- // provisioning Lambda asynchronously failed. We have a `cloud_uid` but
754
- // no `bucket_name` to write to disk. Surface as a vault error since the
755
- // entity exists but is incomplete.
756
- throw new ProvisionError(
757
- 1,
758
- `Vault entity ${entity.uid} has no bucketName — provisioning incomplete`,
759
- {
760
- ok: false,
761
- company_slug: options.slug,
762
- cloud_uid: entity.uid,
763
- bucket_name: "",
764
- vault_api_url: options.vaultApiUrl,
765
- kms_key_id: entity.kmsKeyId ?? null,
766
- created_entity: createdEntity,
767
- manifest_patched: false,
768
- config_written: false,
769
- initial_sync: { ok: false, error: "entity has no bucketName" },
770
- },
771
- );
772
- }
773
-
774
- const cloudUid = entity.uid;
775
- const bucketName = entity.bucketName;
776
- const kmsKeyId = entity.kmsKeyId ?? null;
777
-
778
- // Step 6: patch manifest atomically. Skip-if-unchanged returns false when
779
- // the manifest already carries this slug's cloud_uid + bucket_name, so we
780
- // report the honest outcome rather than always claiming a patch.
781
- const manifestPatched = patchManifest(
782
- options.hqRoot,
783
- options.slug,
784
- cloudUid,
785
- bucketName,
786
- );
787
- log(
788
- manifestPatched
789
- ? `patched companies/manifest.yaml`
790
- : `companies/manifest.yaml already current — left untouched`,
791
- );
792
-
793
- // Step 7: write .hq/config.json atomically
794
- writeCompanyConfig(options.hqRoot, options.slug, {
795
- companyUid: cloudUid,
796
- companySlug: options.slug,
797
- bucketName,
798
- vaultApiUrl: options.vaultApiUrl,
799
- });
800
- log(`wrote companies/${options.slug}/.hq/config.json`);
801
-
802
- // Step 8: trigger initial sync (failure ⇒ exit 3 with cloud_uid populated).
803
- // Skipped when caller passed --skip-initial-sync (e.g. AppBar HQ Sync, which
804
- // owns its own STS-credentialed upload pipeline + Tauri progress events).
805
- let initialSync: ProvisionResult["initial_sync"];
806
- if (options.skipInitialSync) {
807
- log(`skipping initial sync (--skip-initial-sync)`);
808
- initialSync = { skipped: true };
809
- } else {
810
- const runner = options.runInitialSync ?? defaultRunInitialSync;
811
- try {
812
- log(`triggering initial sync via share()`);
813
- const sync = await runner({
814
- slug: options.slug,
815
- hqRoot: options.hqRoot,
816
- accessToken,
817
- vaultApiUrl: options.vaultApiUrl,
818
- });
819
- initialSync = {
820
- ok: true,
821
- files_uploaded: sync.filesUploaded,
822
- bytes_uploaded: sync.bytesUploaded,
823
- };
824
- log(
825
- `initial sync complete — files=${sync.filesUploaded} bytes=${sync.bytesUploaded}`,
826
- );
827
- } catch (err) {
828
- const msg = err instanceof Error ? err.message : String(err);
829
- log(`initial sync failed: ${msg}`);
830
- throw new ProvisionError(3, `Initial sync failed: ${msg}`, {
831
- ok: false,
832
- company_slug: options.slug,
833
- cloud_uid: cloudUid,
834
- bucket_name: bucketName,
835
- vault_api_url: options.vaultApiUrl,
836
- kms_key_id: kmsKeyId,
837
- created_entity: createdEntity,
838
- manifest_patched: true,
839
- config_written: true,
840
- initial_sync: { ok: false, error: msg },
841
- });
842
- }
843
- }
844
-
845
- return {
846
- ok: true,
847
- company_slug: options.slug,
848
- cloud_uid: cloudUid,
849
- bucket_name: bucketName,
850
- vault_api_url: options.vaultApiUrl,
851
- kms_key_id: kmsKeyId,
852
- created_entity: createdEntity,
853
- manifest_patched: manifestPatched,
854
- config_written: true,
855
- initial_sync: initialSync,
856
- };
857
- }
858
-
859
- // ── Commander wiring ─────────────────────────────────────────────────────────
860
-
861
- /**
862
- * Register `provision company <slug>` under a `cloud` subcommand group.
863
- *
864
- * Wired in `src/index.ts` via `registerCloudProvisionCommands(cloudCmd)` where
865
- * `cloudCmd` is the top-level `hq cloud` command group.
866
- */
867
- export function registerCloudProvisionCommands(program: Command): void {
868
- const provisionCmd = program
869
- .command("provision")
870
- .description("Provision a cloud-backed entity (entity + bucket + initial sync)");
871
-
872
- provisionCmd
873
- .command("company")
874
- .description(
875
- "Promote a local company to a cloud-backed entity (idempotent). " +
876
- "Provisions the vault entity if missing, patches manifest.yaml, " +
877
- "writes .hq/config.json, and triggers an initial sync.",
878
- )
879
- .argument("<slug>", "Company slug (must match a top-level key in companies/manifest.yaml)")
880
- .option("--name <name>", "Display name for the entity (default: slug)")
881
- .option("--owner <uid>", "Owner person UID (default: current Cognito user sub)")
882
- .option(
883
- "--hq-root <path>",
884
- `Local HQ tree root (default: ${DEFAULT_HQ_ROOT})`,
885
- DEFAULT_HQ_ROOT,
886
- )
887
- .option(
888
- "--vault-api-url <url>",
889
- `Vault API URL (default: ${DEFAULT_VAULT_API_URL})`,
890
- DEFAULT_VAULT_API_URL,
891
- )
892
- .option(
893
- "--skip-initial-sync",
894
- "Skip the post-provision share() initial sync. Use when the caller " +
895
- "(e.g. AppBar HQ Sync) has its own upload pipeline. Result includes " +
896
- "{ initial_sync: { skipped: true } } when set.",
897
- )
898
- .action(
899
- async (
900
- slug: string,
901
- options: {
902
- name?: string;
903
- owner?: string;
904
- hqRoot: string;
905
- vaultApiUrl: string;
906
- skipInitialSync?: boolean;
907
- },
908
- ) => {
909
- try {
910
- const result = await provisionCompany({
911
- slug,
912
- name: options.name,
913
- ownerUid: options.owner,
914
- hqRoot: options.hqRoot,
915
- vaultApiUrl: options.vaultApiUrl,
916
- skipInitialSync: options.skipInitialSync,
917
- });
918
- // Final stdout line — single JSON document for downstream consumers
919
- process.stdout.write(JSON.stringify(result) + "\n");
920
- process.exit(0);
921
- } catch (err) {
922
- if (err instanceof ProvisionError) {
923
- // Partial-success path (code 3): cloud_uid is known; emit JSON to stdout
924
- // so downstream consumers can capture it for retry.
925
- if (err.partial) {
926
- process.stdout.write(JSON.stringify(err.partial) + "\n");
927
- }
928
- process.stderr.write(
929
- chalk.red(`[hq cloud provision] ${err.message}\n`),
930
- );
931
- process.exit(err.code);
932
- }
933
- process.stderr.write(
934
- chalk.red(
935
- `[hq cloud provision] Unexpected error: ${err instanceof Error ? err.message : String(err)}\n`,
936
- ),
937
- );
938
- process.exit(1);
939
- }
940
- },
941
- );
942
- }