@indigoai-us/hq-cli 5.5.5 → 5.6.1

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.
@@ -0,0 +1,207 @@
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 missing from manifest, or company dir missing
24
+ * 3 — sync failure after entity provisioned (cloud_uid in JSON;
25
+ * `initial_sync.ok=false`). Manifest + config may have been written.
26
+ */
27
+ import { Command } from "commander";
28
+ /** Vault entity shape (subset we consume). Mirrors hq-pro entity types. */
29
+ export interface VaultEntity {
30
+ uid: string;
31
+ type: string;
32
+ slug: string;
33
+ name: string;
34
+ bucketName?: string;
35
+ kmsKeyId?: string | null;
36
+ status?: string;
37
+ ownerUid?: string;
38
+ }
39
+ /** Per-company `.hq/config.json` schema (matches AppBar `provision.rs::CompanyConfig`). */
40
+ export interface CompanyConfig {
41
+ companyUid: string;
42
+ companySlug: string;
43
+ bucketName: string;
44
+ vaultApiUrl: string;
45
+ }
46
+ /** Final stdout JSON shape. Consumers (designate-team, AppBar) parse this. */
47
+ export interface ProvisionResult {
48
+ ok: boolean;
49
+ company_slug: string;
50
+ cloud_uid: string;
51
+ bucket_name: string;
52
+ vault_api_url: string;
53
+ kms_key_id: string | null;
54
+ created_entity: boolean;
55
+ manifest_patched: boolean;
56
+ config_written: boolean;
57
+ initial_sync: {
58
+ ok?: boolean;
59
+ files_uploaded?: number;
60
+ bytes_uploaded?: number;
61
+ error?: string;
62
+ /** True if the caller passed --skip-initial-sync; ok/files/bytes will be absent. */
63
+ skipped?: boolean;
64
+ };
65
+ }
66
+ /** Options for the high-level `provisionCompany` orchestrator. */
67
+ export interface ProvisionCompanyOptions {
68
+ slug: string;
69
+ name?: string;
70
+ ownerUid?: string;
71
+ hqRoot: string;
72
+ vaultApiUrl: string;
73
+ /**
74
+ * Skip the initial-sync step. The vault entity, manifest patch, and
75
+ * `.hq/config.json` write still happen; the post-provision `share()` call
76
+ * is no-op'd. Use this when the caller has its own upload pipeline (e.g.
77
+ * AppBar HQ Sync's `first_push_company` with STS-vended credentials and
78
+ * Tauri progress events) and would otherwise double-upload the same files.
79
+ * When true, `initial_sync` in the result is `{ skipped: true }`.
80
+ */
81
+ skipInitialSync?: boolean;
82
+ /** Injected vault HTTP client (override for tests). */
83
+ vaultClient?: VaultClient;
84
+ /** Injected access-token resolver (override for tests). */
85
+ resolveAccessToken?: () => Promise<string>;
86
+ /** Injected sync runner (override for tests). */
87
+ runInitialSync?: (args: InitialSyncArgs) => Promise<{
88
+ filesUploaded: number;
89
+ bytesUploaded: number;
90
+ }>;
91
+ /** Optional progress logger; defaults to stderr-prefixed `[hq cloud provision]`. */
92
+ log?: (msg: string) => void;
93
+ }
94
+ interface InitialSyncArgs {
95
+ slug: string;
96
+ hqRoot: string;
97
+ accessToken: string;
98
+ vaultApiUrl: string;
99
+ }
100
+ /** Vault HTTP client interface — minimal surface for entity ops. */
101
+ export interface VaultClient {
102
+ findCompanyBySlug(slug: string): Promise<VaultEntity | null>;
103
+ createCompanyEntity(input: {
104
+ slug: string;
105
+ name: string;
106
+ ownerUid?: string;
107
+ }): Promise<VaultEntity>;
108
+ }
109
+ /** Custom error class so the CLI runner can map to exit codes. */
110
+ export declare class ProvisionError extends Error {
111
+ readonly code: 1 | 2 | 3;
112
+ readonly partial?: Partial<ProvisionResult> | undefined;
113
+ constructor(code: 1 | 2 | 3, message: string, partial?: Partial<ProvisionResult> | undefined);
114
+ }
115
+ /**
116
+ * Validate a company slug per the contract: alphanumeric / dot / dash / underscore,
117
+ * non-empty, and never `"personal"` (which is auto-provisioned per-user, not
118
+ * promoted via this subcommand).
119
+ *
120
+ * Throws ProvisionError with code=2 on failure.
121
+ */
122
+ export declare function validateSlug(slug: string): void;
123
+ /** Path to the top-level companies manifest file. */
124
+ export declare function manifestPath(hqRoot: string): string;
125
+ /** Path to a company's directory inside the HQ tree. */
126
+ export declare function companyDirPath(hqRoot: string, slug: string): string;
127
+ /** Path to a company's `.hq/config.json`. */
128
+ export declare function companyConfigPath(hqRoot: string, slug: string): string;
129
+ /**
130
+ * Validate that the company exists in the manifest and on disk.
131
+ *
132
+ * Throws ProvisionError with code=2 if:
133
+ * - manifest file missing
134
+ * - manifest is malformed (no `companies` map)
135
+ * - slug not present under `.companies`
136
+ * - company is `status: archived`
137
+ * - `companies/<slug>/` does not exist
138
+ *
139
+ * Returns the parsed manifest (so the caller can re-use it for the patch step).
140
+ */
141
+ export declare function validateManifestAndDir(hqRoot: string, slug: string): {
142
+ manifest: ManifestDoc;
143
+ };
144
+ /**
145
+ * Top-level manifest shape we touch. We preserve all unknown fields — only
146
+ * `cloud_uid` and `bucket_name` under the target slug are mutated.
147
+ */
148
+ export interface ManifestDoc {
149
+ companies?: Record<string, ManifestCompanyEntry | null>;
150
+ [k: string]: unknown;
151
+ }
152
+ export interface ManifestCompanyEntry {
153
+ cloud_uid?: string;
154
+ bucket_name?: string;
155
+ status?: string;
156
+ [k: string]: unknown;
157
+ }
158
+ /**
159
+ * Atomically patch `companies/manifest.yaml` to set `cloud_uid` + `bucket_name`
160
+ * under the target slug. Read → mutate → temp-write → rename so concurrent
161
+ * readers never see a partially-written file.
162
+ *
163
+ * Idempotent: if the values already match, this is a no-op (still rewrites
164
+ * the file to canonical YAML, but the mutation is identical).
165
+ *
166
+ * Returns true if the file was written (always true in current impl —
167
+ * reserved for future "skip if unchanged" optimization).
168
+ */
169
+ export declare function patchManifest(hqRoot: string, slug: string, cloudUid: string, bucketName: string): boolean;
170
+ /**
171
+ * Atomically write `companies/<slug>/.hq/config.json` with the cloud-promotion
172
+ * config. Creates the parent `.hq/` directory if needed. Temp-write + rename
173
+ * so concurrent readers never see a partial file.
174
+ *
175
+ * Idempotent: a re-run with the same inputs writes byte-identical output.
176
+ */
177
+ export declare function writeCompanyConfig(hqRoot: string, slug: string, config: CompanyConfig): boolean;
178
+ /**
179
+ * Default vault HTTP client backed by global `fetch`. Uses the `/v1/entities`
180
+ * route surface (matches AppBar `vault_client.rs` and hq-pro handler routes).
181
+ *
182
+ * Note: the hq-pro handler.ts uses `/entity` (singular, no `/v1/`); the API
183
+ * Gateway in front of it exposes the same handlers under `/v1/entities/*`
184
+ * (plural) — the deployed surface is the prefixed form, which is what
185
+ * AppBar (`vault_client.rs`) and the architecture audit document. We use
186
+ * the deployed `/v1/entities/*` form here.
187
+ */
188
+ export declare function createDefaultVaultClient(apiUrl: string, accessToken: string): VaultClient;
189
+ /**
190
+ * Run the full 9-step provision flow. Returns a `ProvisionResult` on success
191
+ * (including partial success — sync failure after entity provisioned).
192
+ *
193
+ * Throws `ProvisionError` for terminal failures with the right exit code.
194
+ *
195
+ * All side effects (HTTP calls, file writes, sync) flow through injected
196
+ * helpers so unit tests can fully exercise the flow without network or disk.
197
+ */
198
+ export declare function provisionCompany(options: ProvisionCompanyOptions): Promise<ProvisionResult>;
199
+ /**
200
+ * Register `provision company <slug>` under a `cloud` subcommand group.
201
+ *
202
+ * Wired in `src/index.ts` via `registerCloudProvisionCommands(cloudCmd)` where
203
+ * `cloudCmd` is the top-level `hq cloud` command group.
204
+ */
205
+ export declare function registerCloudProvisionCommands(program: Command): void;
206
+ export {};
207
+ //# sourceMappingURL=cloud-provision.d.ts.map
@@ -0,0 +1,429 @@
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 missing from manifest, or company dir missing
24
+ * 3 — sync failure after entity provisioned (cloud_uid in JSON;
25
+ * `initial_sync.ok=false`). Manifest + config may have been written.
26
+ */
27
+
28
+ !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="325d7bbf-c44d-5bba-a156-072302ab1536")}catch(e){}}();
29
+ import chalk from "chalk";
30
+ import * as fs from "node:fs";
31
+ import * as path from "node:path";
32
+ import * as yaml from "js-yaml";
33
+ import { share } from "@indigoai-us/hq-cloud";
34
+ import { DEFAULT_HQ_ROOT, DEFAULT_VAULT_API_URL, ensureCognitoToken, buildVaultConfig, } from "../utils/cognito-session.js";
35
+ /** Custom error class so the CLI runner can map to exit codes. */
36
+ export class ProvisionError extends Error {
37
+ code;
38
+ partial;
39
+ constructor(code, message, partial) {
40
+ super(message);
41
+ this.code = code;
42
+ this.partial = partial;
43
+ this.name = "ProvisionError";
44
+ }
45
+ }
46
+ // ── Validation ───────────────────────────────────────────────────────────────
47
+ const SLUG_REGEX = /^[A-Za-z0-9._-]+$/;
48
+ const FORBIDDEN_SLUGS = new Set(["personal"]);
49
+ /**
50
+ * Validate a company slug per the contract: alphanumeric / dot / dash / underscore,
51
+ * non-empty, and never `"personal"` (which is auto-provisioned per-user, not
52
+ * promoted via this subcommand).
53
+ *
54
+ * Throws ProvisionError with code=2 on failure.
55
+ */
56
+ export function validateSlug(slug) {
57
+ if (!slug || slug.trim() === "") {
58
+ throw new ProvisionError(2, "Slug is required");
59
+ }
60
+ if (!SLUG_REGEX.test(slug)) {
61
+ throw new ProvisionError(2, `Invalid slug "${slug}" — must match ${SLUG_REGEX.source}`);
62
+ }
63
+ if (FORBIDDEN_SLUGS.has(slug)) {
64
+ throw new ProvisionError(2, `Slug "${slug}" is reserved (auto-provisioned per-user, not eligible for cloud promotion)`);
65
+ }
66
+ }
67
+ /** Path to the top-level companies manifest file. */
68
+ export function manifestPath(hqRoot) {
69
+ return path.join(hqRoot, "companies", "manifest.yaml");
70
+ }
71
+ /** Path to a company's directory inside the HQ tree. */
72
+ export function companyDirPath(hqRoot, slug) {
73
+ return path.join(hqRoot, "companies", slug);
74
+ }
75
+ /** Path to a company's `.hq/config.json`. */
76
+ export function companyConfigPath(hqRoot, slug) {
77
+ return path.join(companyDirPath(hqRoot, slug), ".hq", "config.json");
78
+ }
79
+ /**
80
+ * Validate that the company exists in the manifest and on disk.
81
+ *
82
+ * Throws ProvisionError with code=2 if:
83
+ * - manifest file missing
84
+ * - manifest is malformed (no `companies` map)
85
+ * - slug not present under `.companies`
86
+ * - company is `status: archived`
87
+ * - `companies/<slug>/` does not exist
88
+ *
89
+ * Returns the parsed manifest (so the caller can re-use it for the patch step).
90
+ */
91
+ export function validateManifestAndDir(hqRoot, slug) {
92
+ const mPath = manifestPath(hqRoot);
93
+ if (!fs.existsSync(mPath)) {
94
+ throw new ProvisionError(2, `companies/manifest.yaml not found at ${mPath}`);
95
+ }
96
+ const raw = fs.readFileSync(mPath, "utf-8");
97
+ const parsed = yaml.load(raw);
98
+ if (!parsed ||
99
+ typeof parsed !== "object" ||
100
+ !("companies" in parsed) ||
101
+ typeof parsed.companies !== "object") {
102
+ throw new ProvisionError(2, `companies/manifest.yaml is malformed — missing top-level .companies map`);
103
+ }
104
+ const manifest = parsed;
105
+ const entry = manifest.companies?.[slug];
106
+ if (entry === undefined) {
107
+ throw new ProvisionError(2, `Company "${slug}" not found under .companies in manifest.yaml`);
108
+ }
109
+ if (entry && typeof entry === "object" && entry.status === "archived") {
110
+ throw new ProvisionError(2, `Company "${slug}" is status=archived — refusing to promote`);
111
+ }
112
+ const dir = companyDirPath(hqRoot, slug);
113
+ if (!fs.existsSync(dir)) {
114
+ throw new ProvisionError(2, `Company directory ${dir} does not exist`);
115
+ }
116
+ return { manifest };
117
+ }
118
+ /**
119
+ * Atomically patch `companies/manifest.yaml` to set `cloud_uid` + `bucket_name`
120
+ * under the target slug. Read → mutate → temp-write → rename so concurrent
121
+ * readers never see a partially-written file.
122
+ *
123
+ * Idempotent: if the values already match, this is a no-op (still rewrites
124
+ * the file to canonical YAML, but the mutation is identical).
125
+ *
126
+ * Returns true if the file was written (always true in current impl —
127
+ * reserved for future "skip if unchanged" optimization).
128
+ */
129
+ export function patchManifest(hqRoot, slug, cloudUid, bucketName) {
130
+ const mPath = manifestPath(hqRoot);
131
+ const raw = fs.readFileSync(mPath, "utf-8");
132
+ const parsed = yaml.load(raw) ?? { companies: {} };
133
+ if (!parsed.companies)
134
+ parsed.companies = {};
135
+ const existing = parsed.companies[slug];
136
+ // Preserve null / object / unknown — promote null → {} so we can write keys.
137
+ const entry = existing && typeof existing === "object" ? { ...existing } : {};
138
+ entry.cloud_uid = cloudUid;
139
+ entry.bucket_name = bucketName;
140
+ parsed.companies[slug] = entry;
141
+ const dump = yaml.dump(parsed, { lineWidth: -1, noRefs: true });
142
+ const tmp = `${mPath}.tmp.${process.pid}`;
143
+ fs.writeFileSync(tmp, dump);
144
+ fs.renameSync(tmp, mPath);
145
+ return true;
146
+ }
147
+ // ── .hq/config.json writing (atomic) ─────────────────────────────────────────
148
+ /**
149
+ * Atomically write `companies/<slug>/.hq/config.json` with the cloud-promotion
150
+ * config. Creates the parent `.hq/` directory if needed. Temp-write + rename
151
+ * so concurrent readers never see a partial file.
152
+ *
153
+ * Idempotent: a re-run with the same inputs writes byte-identical output.
154
+ */
155
+ export function writeCompanyConfig(hqRoot, slug, config) {
156
+ const cPath = companyConfigPath(hqRoot, slug);
157
+ const dir = path.dirname(cPath);
158
+ fs.mkdirSync(dir, { recursive: true });
159
+ const body = JSON.stringify(config, null, 2) + "\n";
160
+ const tmp = `${cPath}.tmp.${process.pid}`;
161
+ fs.writeFileSync(tmp, body);
162
+ fs.renameSync(tmp, cPath);
163
+ return true;
164
+ }
165
+ // ── Vault HTTP client (real impl) ────────────────────────────────────────────
166
+ /**
167
+ * Default vault HTTP client backed by global `fetch`. Uses the `/v1/entities`
168
+ * route surface (matches AppBar `vault_client.rs` and hq-pro handler routes).
169
+ *
170
+ * Note: the hq-pro handler.ts uses `/entity` (singular, no `/v1/`); the API
171
+ * Gateway in front of it exposes the same handlers under `/v1/entities/*`
172
+ * (plural) — the deployed surface is the prefixed form, which is what
173
+ * AppBar (`vault_client.rs`) and the architecture audit document. We use
174
+ * the deployed `/v1/entities/*` form here.
175
+ */
176
+ export function createDefaultVaultClient(apiUrl, accessToken) {
177
+ const headers = {
178
+ "Content-Type": "application/json",
179
+ Authorization: `Bearer ${accessToken}`,
180
+ };
181
+ return {
182
+ async findCompanyBySlug(slug) {
183
+ const url = `${apiUrl.replace(/\/$/, "")}/v1/entities/by-slug/company/${encodeURIComponent(slug)}`;
184
+ const res = await fetch(url, { method: "GET", headers });
185
+ if (res.status === 404)
186
+ return null;
187
+ if (!res.ok) {
188
+ const body = await safeBody(res);
189
+ throw new ProvisionError(1, `Vault GET by-slug failed: ${res.status} ${res.statusText} — ${body}`);
190
+ }
191
+ const data = (await res.json());
192
+ if (!data.entity) {
193
+ throw new ProvisionError(1, `Vault GET by-slug returned 200 with no entity body`);
194
+ }
195
+ return data.entity;
196
+ },
197
+ async createCompanyEntity(input) {
198
+ const url = `${apiUrl.replace(/\/$/, "")}/v1/entities`;
199
+ const body = {
200
+ type: "company",
201
+ slug: input.slug,
202
+ name: input.name,
203
+ };
204
+ if (input.ownerUid)
205
+ body.ownerUid = input.ownerUid;
206
+ const res = await fetch(url, {
207
+ method: "POST",
208
+ headers,
209
+ body: JSON.stringify(body),
210
+ });
211
+ if (!res.ok) {
212
+ const text = await safeBody(res);
213
+ // 409 means a concurrent client created it between our GET and POST —
214
+ // surface it as a vault error. The orchestrator is responsible for
215
+ // retrying GET if it wants idempotency on collisions.
216
+ throw new ProvisionError(1, `Vault POST /v1/entities failed: ${res.status} ${res.statusText} — ${text}`);
217
+ }
218
+ const data = (await res.json());
219
+ if (!data.entity) {
220
+ throw new ProvisionError(1, `Vault POST /v1/entities returned ${res.status} with no entity body`);
221
+ }
222
+ return data.entity;
223
+ },
224
+ };
225
+ }
226
+ async function safeBody(res) {
227
+ try {
228
+ return await res.text();
229
+ }
230
+ catch {
231
+ return "<no body>";
232
+ }
233
+ }
234
+ // ── Default initial-sync runner (wraps share()) ──────────────────────────────
235
+ async function defaultRunInitialSync(args) {
236
+ const result = await share({
237
+ paths: [companyDirPath(args.hqRoot, args.slug)],
238
+ company: args.slug,
239
+ message: `hq cloud provision:${args.slug}`,
240
+ onConflict: "keep",
241
+ vaultConfig: buildVaultConfig(args.accessToken),
242
+ hqRoot: args.hqRoot,
243
+ });
244
+ return {
245
+ filesUploaded: result.filesUploaded,
246
+ bytesUploaded: result.bytesUploaded,
247
+ };
248
+ }
249
+ // ── Orchestrator ─────────────────────────────────────────────────────────────
250
+ /**
251
+ * Run the full 9-step provision flow. Returns a `ProvisionResult` on success
252
+ * (including partial success — sync failure after entity provisioned).
253
+ *
254
+ * Throws `ProvisionError` for terminal failures with the right exit code.
255
+ *
256
+ * All side effects (HTTP calls, file writes, sync) flow through injected
257
+ * helpers so unit tests can fully exercise the flow without network or disk.
258
+ */
259
+ export async function provisionCompany(options) {
260
+ const log = options.log ?? ((msg) => process.stderr.write(`[hq cloud provision] ${msg}\n`));
261
+ // Step 1+2+3: validate slug, manifest, dir
262
+ validateSlug(options.slug);
263
+ validateManifestAndDir(options.hqRoot, options.slug);
264
+ log(`validated slug=${options.slug}`);
265
+ // Step 4: auth — defer to injected resolver (default: ensureCognitoToken)
266
+ const accessToken = options.resolveAccessToken
267
+ ? await options.resolveAccessToken()
268
+ : await ensureCognitoToken();
269
+ log(`acquired Cognito access token`);
270
+ // Step 5: GET-then-POST for idempotency
271
+ const vaultClient = options.vaultClient ??
272
+ createDefaultVaultClient(options.vaultApiUrl, accessToken);
273
+ let entity = await vaultClient.findCompanyBySlug(options.slug);
274
+ let createdEntity = false;
275
+ if (entity) {
276
+ log(`reusing existing vault entity uid=${entity.uid}`);
277
+ }
278
+ else {
279
+ log(`vault entity not found — creating`);
280
+ entity = await vaultClient.createCompanyEntity({
281
+ slug: options.slug,
282
+ name: options.name ?? options.slug,
283
+ ownerUid: options.ownerUid,
284
+ });
285
+ createdEntity = true;
286
+ log(`created vault entity uid=${entity.uid}`);
287
+ }
288
+ if (!entity.bucketName) {
289
+ // Vault returned an entity without a bucket — this would happen if the
290
+ // provisioning Lambda asynchronously failed. We have a `cloud_uid` but
291
+ // no `bucket_name` to write to disk. Surface as a vault error since the
292
+ // entity exists but is incomplete.
293
+ throw new ProvisionError(1, `Vault entity ${entity.uid} has no bucketName — provisioning incomplete`, {
294
+ ok: false,
295
+ company_slug: options.slug,
296
+ cloud_uid: entity.uid,
297
+ bucket_name: "",
298
+ vault_api_url: options.vaultApiUrl,
299
+ kms_key_id: entity.kmsKeyId ?? null,
300
+ created_entity: createdEntity,
301
+ manifest_patched: false,
302
+ config_written: false,
303
+ initial_sync: { ok: false, error: "entity has no bucketName" },
304
+ });
305
+ }
306
+ const cloudUid = entity.uid;
307
+ const bucketName = entity.bucketName;
308
+ const kmsKeyId = entity.kmsKeyId ?? null;
309
+ // Step 6: patch manifest atomically
310
+ patchManifest(options.hqRoot, options.slug, cloudUid, bucketName);
311
+ log(`patched companies/manifest.yaml`);
312
+ // Step 7: write .hq/config.json atomically
313
+ writeCompanyConfig(options.hqRoot, options.slug, {
314
+ companyUid: cloudUid,
315
+ companySlug: options.slug,
316
+ bucketName,
317
+ vaultApiUrl: options.vaultApiUrl,
318
+ });
319
+ log(`wrote companies/${options.slug}/.hq/config.json`);
320
+ // Step 8: trigger initial sync (failure ⇒ exit 3 with cloud_uid populated).
321
+ // Skipped when caller passed --skip-initial-sync (e.g. AppBar HQ Sync, which
322
+ // owns its own STS-credentialed upload pipeline + Tauri progress events).
323
+ let initialSync;
324
+ if (options.skipInitialSync) {
325
+ log(`skipping initial sync (--skip-initial-sync)`);
326
+ initialSync = { skipped: true };
327
+ }
328
+ else {
329
+ const runner = options.runInitialSync ?? defaultRunInitialSync;
330
+ try {
331
+ log(`triggering initial sync via share()`);
332
+ const sync = await runner({
333
+ slug: options.slug,
334
+ hqRoot: options.hqRoot,
335
+ accessToken,
336
+ vaultApiUrl: options.vaultApiUrl,
337
+ });
338
+ initialSync = {
339
+ ok: true,
340
+ files_uploaded: sync.filesUploaded,
341
+ bytes_uploaded: sync.bytesUploaded,
342
+ };
343
+ log(`initial sync complete — files=${sync.filesUploaded} bytes=${sync.bytesUploaded}`);
344
+ }
345
+ catch (err) {
346
+ const msg = err instanceof Error ? err.message : String(err);
347
+ log(`initial sync failed: ${msg}`);
348
+ throw new ProvisionError(3, `Initial sync failed: ${msg}`, {
349
+ ok: false,
350
+ company_slug: options.slug,
351
+ cloud_uid: cloudUid,
352
+ bucket_name: bucketName,
353
+ vault_api_url: options.vaultApiUrl,
354
+ kms_key_id: kmsKeyId,
355
+ created_entity: createdEntity,
356
+ manifest_patched: true,
357
+ config_written: true,
358
+ initial_sync: { ok: false, error: msg },
359
+ });
360
+ }
361
+ }
362
+ return {
363
+ ok: true,
364
+ company_slug: options.slug,
365
+ cloud_uid: cloudUid,
366
+ bucket_name: bucketName,
367
+ vault_api_url: options.vaultApiUrl,
368
+ kms_key_id: kmsKeyId,
369
+ created_entity: createdEntity,
370
+ manifest_patched: true,
371
+ config_written: true,
372
+ initial_sync: initialSync,
373
+ };
374
+ }
375
+ // ── Commander wiring ─────────────────────────────────────────────────────────
376
+ /**
377
+ * Register `provision company <slug>` under a `cloud` subcommand group.
378
+ *
379
+ * Wired in `src/index.ts` via `registerCloudProvisionCommands(cloudCmd)` where
380
+ * `cloudCmd` is the top-level `hq cloud` command group.
381
+ */
382
+ export function registerCloudProvisionCommands(program) {
383
+ const provisionCmd = program
384
+ .command("provision")
385
+ .description("Provision a cloud-backed entity (entity + bucket + initial sync)");
386
+ provisionCmd
387
+ .command("company")
388
+ .description("Promote a local company to a cloud-backed entity (idempotent). " +
389
+ "Provisions the vault entity if missing, patches manifest.yaml, " +
390
+ "writes .hq/config.json, and triggers an initial sync.")
391
+ .argument("<slug>", "Company slug (must match a top-level key in companies/manifest.yaml)")
392
+ .option("--name <name>", "Display name for the entity (default: slug)")
393
+ .option("--owner <uid>", "Owner person UID (default: current Cognito user sub)")
394
+ .option("--hq-root <path>", `Local HQ tree root (default: ${DEFAULT_HQ_ROOT})`, DEFAULT_HQ_ROOT)
395
+ .option("--vault-api-url <url>", `Vault API URL (default: ${DEFAULT_VAULT_API_URL})`, DEFAULT_VAULT_API_URL)
396
+ .option("--skip-initial-sync", "Skip the post-provision share() initial sync. Use when the caller " +
397
+ "(e.g. AppBar HQ Sync) has its own upload pipeline. Result includes " +
398
+ "{ initial_sync: { skipped: true } } when set.")
399
+ .action(async (slug, options) => {
400
+ try {
401
+ const result = await provisionCompany({
402
+ slug,
403
+ name: options.name,
404
+ ownerUid: options.owner,
405
+ hqRoot: options.hqRoot,
406
+ vaultApiUrl: options.vaultApiUrl,
407
+ skipInitialSync: options.skipInitialSync,
408
+ });
409
+ // Final stdout line — single JSON document for downstream consumers
410
+ process.stdout.write(JSON.stringify(result) + "\n");
411
+ process.exit(0);
412
+ }
413
+ catch (err) {
414
+ if (err instanceof ProvisionError) {
415
+ // Partial-success path (code 3): cloud_uid is known; emit JSON to stdout
416
+ // so downstream consumers can capture it for retry.
417
+ if (err.partial) {
418
+ process.stdout.write(JSON.stringify(err.partial) + "\n");
419
+ }
420
+ process.stderr.write(chalk.red(`[hq cloud provision] ${err.message}\n`));
421
+ process.exit(err.code);
422
+ }
423
+ process.stderr.write(chalk.red(`[hq cloud provision] Unexpected error: ${err instanceof Error ? err.message : String(err)}\n`));
424
+ process.exit(1);
425
+ }
426
+ });
427
+ }
428
+ //# sourceMappingURL=cloud-provision.js.map
429
+ //# debugId=325d7bbf-c44d-5bba-a156-072302ab1536
package/dist/index.js CHANGED
@@ -3,7 +3,7 @@
3
3
  * HQ CLI - Module management, package management, and cloud sync for HQ
4
4
  */
5
5
 
6
- !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="47414e28-81ab-5d6e-b37e-5988b2866f47")}catch(e){}}();
6
+ !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="8abd3fa1-9f1a-53b3-9d1c-cf764db1f670")}catch(e){}}();
7
7
  import { Command } from "commander";
8
8
  import { initSentry, Sentry } from "./sentry.js";
9
9
  import { registerAddCommand } from "./commands/add.js";
@@ -11,6 +11,7 @@ import { registerSyncCommand } from "./commands/sync.js";
11
11
  import { registerListCommand } from "./commands/list.js";
12
12
  import { registerUpdateCommand } from "./commands/update.js";
13
13
  import { registerCloudCommands } from "./commands/cloud.js";
14
+ import { registerCloudProvisionCommands } from "./commands/cloud-provision.js";
14
15
  import { registerLoginCommand } from "./commands/login.js";
15
16
  import { registerLogoutCommand } from "./commands/logout.js";
16
17
  import { registerWhoamiCommand } from "./commands/whoami.js";
@@ -55,6 +56,12 @@ const syncCmd = program
55
56
  .command("sync")
56
57
  .description("Cloud sync commands — sync HQ to S3 for mobile access");
57
58
  registerCloudCommands(syncCmd);
59
+ // Cloud provisioning subcommand group (entity + bucket + initial sync)
60
+ // Distinct from `hq sync` which assumes provisioning has already happened.
61
+ const cloudCmd = program
62
+ .command("cloud")
63
+ .description("Cloud commands — provision entities and manage cloud-backed companies");
64
+ registerCloudProvisionCommands(cloudCmd);
58
65
  // Team commands (top-level)
59
66
  registerTeamSyncCommand(program);
60
67
  // Auth commands (top-level — Cognito OAuth)
@@ -81,4 +88,4 @@ registerOnboardCommand(program);
81
88
  }
82
89
  })();
83
90
  //# sourceMappingURL=index.js.map
84
- //# debugId=47414e28-81ab-5d6e-b37e-5988b2866f47
91
+ //# debugId=8abd3fa1-9f1a-53b3-9d1c-cf764db1f670
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@indigoai-us/hq-cli",
3
- "version": "5.5.5",
3
+ "version": "5.6.1",
4
4
  "description": "HQ by Indigo management CLI — modules and cloud sync",
5
5
  "main": "dist/index.js",
6
6
  "bin": {