@indigoai-us/hq-cloud 5.1.0 → 5.1.9

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 (100) hide show
  1. package/dist/bin/sync-runner.d.ts +134 -0
  2. package/dist/bin/sync-runner.d.ts.map +1 -0
  3. package/dist/bin/sync-runner.js +360 -0
  4. package/dist/bin/sync-runner.js.map +1 -0
  5. package/dist/bin/sync-runner.test.d.ts +10 -0
  6. package/dist/bin/sync-runner.test.d.ts.map +1 -0
  7. package/dist/bin/sync-runner.test.js +648 -0
  8. package/dist/bin/sync-runner.test.js.map +1 -0
  9. package/dist/cli/index.d.ts +1 -1
  10. package/dist/cli/index.d.ts.map +1 -1
  11. package/dist/cli/share.js +2 -2
  12. package/dist/cli/share.js.map +1 -1
  13. package/dist/cli/share.test.js +9 -1
  14. package/dist/cli/share.test.js.map +1 -1
  15. package/dist/cli/sync.d.ts +28 -0
  16. package/dist/cli/sync.d.ts.map +1 -1
  17. package/dist/cli/sync.js +33 -10
  18. package/dist/cli/sync.js.map +1 -1
  19. package/dist/cli/sync.test.js +15 -4
  20. package/dist/cli/sync.test.js.map +1 -1
  21. package/dist/cognito-auth.d.ts.map +1 -1
  22. package/dist/cognito-auth.js +19 -1
  23. package/dist/cognito-auth.js.map +1 -1
  24. package/dist/cognito-auth.test.d.ts +9 -0
  25. package/dist/cognito-auth.test.d.ts.map +1 -0
  26. package/dist/cognito-auth.test.js +113 -0
  27. package/dist/cognito-auth.test.js.map +1 -0
  28. package/dist/context.d.ts.map +1 -1
  29. package/dist/context.js +1 -0
  30. package/dist/context.js.map +1 -1
  31. package/dist/daemon-worker.d.ts +6 -1
  32. package/dist/daemon-worker.d.ts.map +1 -1
  33. package/dist/daemon-worker.js +12 -16
  34. package/dist/daemon-worker.js.map +1 -1
  35. package/dist/daemon.d.ts +2 -0
  36. package/dist/daemon.d.ts.map +1 -1
  37. package/dist/daemon.js +2 -0
  38. package/dist/daemon.js.map +1 -1
  39. package/dist/ignore.d.ts +13 -2
  40. package/dist/ignore.d.ts.map +1 -1
  41. package/dist/ignore.js +69 -12
  42. package/dist/ignore.js.map +1 -1
  43. package/dist/index.d.ts +24 -28
  44. package/dist/index.d.ts.map +1 -1
  45. package/dist/index.js +19 -134
  46. package/dist/index.js.map +1 -1
  47. package/dist/journal.d.ts +20 -4
  48. package/dist/journal.d.ts.map +1 -1
  49. package/dist/journal.js +45 -8
  50. package/dist/journal.js.map +1 -1
  51. package/dist/journal.test.d.ts +9 -0
  52. package/dist/journal.test.d.ts.map +1 -0
  53. package/dist/journal.test.js +114 -0
  54. package/dist/journal.test.js.map +1 -0
  55. package/dist/s3.d.ts +18 -6
  56. package/dist/s3.d.ts.map +1 -1
  57. package/dist/s3.js +57 -56
  58. package/dist/s3.js.map +1 -1
  59. package/dist/types.d.ts +34 -0
  60. package/dist/types.d.ts.map +1 -1
  61. package/dist/vault-client.d.ts +59 -0
  62. package/dist/vault-client.d.ts.map +1 -1
  63. package/dist/vault-client.js +72 -0
  64. package/dist/vault-client.js.map +1 -1
  65. package/dist/vault-client.test.js +160 -0
  66. package/dist/vault-client.test.js.map +1 -1
  67. package/dist/watcher.d.ts +7 -1
  68. package/dist/watcher.d.ts.map +1 -1
  69. package/dist/watcher.js +11 -5
  70. package/dist/watcher.js.map +1 -1
  71. package/package.json +15 -3
  72. package/src/bin/sync-runner.test.ts +804 -0
  73. package/src/bin/sync-runner.ts +499 -0
  74. package/src/cli/accept.ts +97 -0
  75. package/src/cli/conflict.ts +119 -0
  76. package/src/cli/index.ts +25 -0
  77. package/src/cli/invite.test.ts +247 -0
  78. package/src/cli/invite.ts +180 -0
  79. package/src/cli/promote.ts +123 -0
  80. package/src/cli/share.test.ts +155 -0
  81. package/src/cli/share.ts +212 -0
  82. package/src/cli/sync.test.ts +225 -0
  83. package/src/cli/sync.ts +225 -0
  84. package/src/cognito-auth.test.ts +156 -0
  85. package/src/cognito-auth.ts +18 -1
  86. package/src/context.test.ts +202 -0
  87. package/src/context.ts +178 -0
  88. package/src/daemon-worker.ts +13 -19
  89. package/src/daemon.ts +2 -0
  90. package/src/ignore.ts +76 -12
  91. package/src/index.ts +94 -165
  92. package/src/journal.test.ts +146 -0
  93. package/src/journal.ts +53 -11
  94. package/src/s3.ts +76 -66
  95. package/src/types.ts +37 -0
  96. package/src/vault-client.test.ts +563 -0
  97. package/src/vault-client.ts +478 -0
  98. package/src/watcher.ts +12 -5
  99. package/test/invite-flow.integration.test.ts +244 -0
  100. package/test/share-sync.integration.test.ts +210 -0
@@ -0,0 +1,499 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * hq-sync-runner — machine-targeted entrypoint for `@indigoai-us/hq-cloud`
4
+ * (ADR-0001).
5
+ *
6
+ * The AppBar Sync menubar (Tauri + Rust) spawns this binary as a subprocess
7
+ * and reads ndjson events from stdout. The protocol is intentionally narrow
8
+ * and versioned-by-shape, not by tooling — no chalk, no colors, no human
9
+ * prose. If you want to invoke sync as a human, use `hq sync` in
10
+ * `@indigoai-us/hq-cli`.
11
+ *
12
+ * Flags:
13
+ * --companies Fan out across every membership the caller has
14
+ * --company <slug-or-uid> Sync a single company (alternative to --companies)
15
+ * --on-conflict <strategy> abort | overwrite | keep (default: abort)
16
+ * --hq-root <path> Local HQ directory (default: $HOME/hq)
17
+ * --json Ignored — ndjson on stdout is the default and
18
+ * only output mode. Accepted for symmetry with the
19
+ * AppBar's argv in case someone passes it.
20
+ *
21
+ * Event protocol (one JSON object per line on stdout):
22
+ * setup-needed — caller signed in but has no person entity yet
23
+ * auth-error — no valid token available (interactive login disabled)
24
+ * fanout-plan — list of companies we're about to sync
25
+ * progress — per-file download
26
+ * error — per-file or per-company error
27
+ * complete — per-company summary
28
+ * all-complete — aggregate summary after fanout
29
+ *
30
+ * Exit code:
31
+ * 0 — event stream describes the outcome (including setup-needed)
32
+ * 1 — argv parse error or unrecoverable pre-sync failure
33
+ */
34
+
35
+ import * as os from "os";
36
+ import * as path from "path";
37
+ import * as fs from "fs";
38
+ import { fileURLToPath } from "url";
39
+ import {
40
+ getValidAccessToken,
41
+ loadCachedTokens,
42
+ VaultClient,
43
+ VaultAuthError,
44
+ type CognitoAuthConfig,
45
+ type CognitoTokens,
46
+ type VaultServiceConfig,
47
+ type Membership,
48
+ type EntityInfo,
49
+ type PendingInviteByEmail,
50
+ } from "../index.js";
51
+ import { sync as defaultSync } from "../cli/sync.js";
52
+ import type {
53
+ SyncOptions,
54
+ SyncResult,
55
+ SyncProgressEvent,
56
+ } from "../cli/sync.js";
57
+ import type { ConflictStrategy } from "../cli/conflict.js";
58
+
59
+ // ---------------------------------------------------------------------------
60
+ // Defaults — mirror `hq-cli/src/utils/cognito-session.ts`. Inlined (not
61
+ // imported) to avoid a circular dep between hq-cli and hq-cloud. If these
62
+ // drift, the symptom is "runner talks to a different stage than hq sync"
63
+ // — keep both files lined up.
64
+ // ---------------------------------------------------------------------------
65
+
66
+ const DEFAULT_COGNITO: CognitoAuthConfig = {
67
+ region: process.env.AWS_REGION ?? "us-east-1",
68
+ userPoolDomain: process.env.HQ_COGNITO_DOMAIN ?? "hq-vault-dev",
69
+ clientId: process.env.HQ_COGNITO_CLIENT_ID ?? "4mmujmjq3srakdueg656b9m0mp",
70
+ port: process.env.HQ_COGNITO_CALLBACK_PORT
71
+ ? Number(process.env.HQ_COGNITO_CALLBACK_PORT)
72
+ : 8765,
73
+ };
74
+
75
+ const DEFAULT_VAULT_API_URL =
76
+ process.env.HQ_VAULT_API_URL ??
77
+ "https://tqdwdqxv75.execute-api.us-east-1.amazonaws.com";
78
+
79
+ const DEFAULT_HQ_ROOT = path.join(os.homedir(), "hq");
80
+
81
+ // ---------------------------------------------------------------------------
82
+ // Event protocol
83
+ // ---------------------------------------------------------------------------
84
+
85
+ /**
86
+ * Every event emitted on stdout. The `company` field is present on every
87
+ * event except `setup-needed` / `auth-error` / `fanout-plan` / `all-complete`
88
+ * (which describe the whole run) — consumers should treat its absence as
89
+ * "meta-event, not tied to a specific company".
90
+ */
91
+ export type RunnerEvent =
92
+ | { type: "setup-needed" }
93
+ | { type: "auth-error"; message: string }
94
+ | {
95
+ type: "fanout-plan";
96
+ companies: Array<{ uid: string; slug: string; name?: string }>;
97
+ }
98
+ | ({ type: "progress"; company: string } & Omit<Extract<SyncProgressEvent, { type: "progress" }>, "type">)
99
+ | ({ type: "error"; company?: string } & Omit<Extract<SyncProgressEvent, { type: "error" }>, "type">)
100
+ | ({ type: "complete"; company: string } & SyncResult)
101
+ | {
102
+ type: "all-complete";
103
+ companiesAttempted: number;
104
+ filesDownloaded: number;
105
+ bytesDownloaded: number;
106
+ errors: Array<{ company: string; message: string }>;
107
+ };
108
+
109
+ /**
110
+ * The narrow VaultClient surface the runner actually uses. Declared here (not
111
+ * `Pick<VaultClient, ...>`) because `Pick` preserves the *entire* `entity`
112
+ * accessor object — but the runner only needs `entity.get`, and forcing test
113
+ * stubs to also implement `findBySlug`/`create` would be dishonest about the
114
+ * real dependency. Keep this interface in sync with the real VaultClient
115
+ * method signatures (both return types come straight from the SDK).
116
+ */
117
+ export interface VaultClientSurface {
118
+ listMyMemberships: () => Promise<Membership[]>;
119
+ listMyPendingInvitesByEmail: () => Promise<PendingInviteByEmail[]>;
120
+ claimPendingInvitesByEmail: (personUid: string) => Promise<void>;
121
+ ensureMyPersonEntity: (hints: {
122
+ ownerSub: string;
123
+ displayName: string;
124
+ }) => Promise<EntityInfo>;
125
+ entity: {
126
+ get: (uid: string) => Promise<EntityInfo>;
127
+ };
128
+ }
129
+
130
+ /** Minimal shape of the claims we read off the Cognito idToken. */
131
+ interface IdTokenClaims {
132
+ sub?: string;
133
+ email?: string;
134
+ name?: string;
135
+ given_name?: string;
136
+ family_name?: string;
137
+ }
138
+
139
+ export interface RunnerDeps {
140
+ /** Where to write ndjson events. Defaults to `process.stdout`. */
141
+ stdout?: { write: (chunk: string) => boolean | void };
142
+ /** Where to write diagnostics. Defaults to `process.stderr`. */
143
+ stderr?: { write: (chunk: string) => boolean | void };
144
+ /** Resolve a valid access token. Defaults to `getValidAccessToken` non-interactive. */
145
+ getAccessToken?: () => Promise<string>;
146
+ /**
147
+ * Read the caller's identity claims (sub/email/name) off the cached Cognito
148
+ * idToken. Defaults to decoding `loadCachedTokens().idToken`. Returns `null`
149
+ * when no cached tokens exist — the runner will then skip the claim-dance
150
+ * and fall through to the usual listMyMemberships path.
151
+ */
152
+ getIdTokenClaims?: () => IdTokenClaims | null;
153
+ /**
154
+ * Produce a VaultClient-like object. Defaults to `new VaultClient(config)`.
155
+ * Tests inject a stub here — the runner only calls the methods listed in
156
+ * `VaultClientSurface`.
157
+ */
158
+ createVaultClient?: (config: VaultServiceConfig) => VaultClientSurface;
159
+ /** Sync function. Defaults to `cli/sync.sync`. */
160
+ sync?: (options: SyncOptions) => Promise<SyncResult>;
161
+ }
162
+
163
+ // ---------------------------------------------------------------------------
164
+ // JWT claim decoder — inlined to avoid pulling a dep just to read an idToken.
165
+ // We do NOT verify the signature here — Cognito already did that when it
166
+ // issued the token, and we only read the public claims (sub/email/name) to
167
+ // drive the claim-dance + create the person entity. If the token is tampered
168
+ // with, the downstream vault-service call will reject it (signature-verified
169
+ // there) long before any claimed value causes harm.
170
+ // ---------------------------------------------------------------------------
171
+
172
+ function decodeJwtClaims(jwt: string): IdTokenClaims | null {
173
+ const parts = jwt.split(".");
174
+ if (parts.length !== 3) return null;
175
+ try {
176
+ const payload = parts[1].replace(/-/g, "+").replace(/_/g, "/");
177
+ const padded = payload + "=".repeat((4 - (payload.length % 4)) % 4);
178
+ const json = Buffer.from(padded, "base64").toString("utf-8");
179
+ return JSON.parse(json) as IdTokenClaims;
180
+ } catch {
181
+ return null;
182
+ }
183
+ }
184
+
185
+ function defaultGetIdTokenClaims(): IdTokenClaims | null {
186
+ const tokens: CognitoTokens | null = loadCachedTokens();
187
+ if (!tokens?.idToken) return null;
188
+ return decodeJwtClaims(tokens.idToken);
189
+ }
190
+
191
+ /**
192
+ * Best-effort: claim any email-keyed pending invites that were sent before
193
+ * this user had a person entity. Mirrors the installer's vault-handoff flow.
194
+ *
195
+ * Silent on the happy path — only logs to stderr on soft failures (so a
196
+ * transient network blip doesn't block the sync). Never throws: a caller who
197
+ * can't list memberships despite an unclaimed invite is no worse off than the
198
+ * pre-claim-dance behavior (which was to emit setup-needed).
199
+ */
200
+ async function runClaimDance(
201
+ client: VaultClientSurface,
202
+ claims: IdTokenClaims,
203
+ stderr: { write: (chunk: string) => boolean | void },
204
+ ): Promise<void> {
205
+ try {
206
+ const pending = await client.listMyPendingInvitesByEmail();
207
+ if (pending.length === 0) return;
208
+
209
+ const displayName =
210
+ claims.name ??
211
+ [claims.given_name, claims.family_name].filter(Boolean).join(" ") ??
212
+ claims.email ??
213
+ "";
214
+ const ownerSub = claims.sub ?? "";
215
+ if (!ownerSub || !displayName) {
216
+ stderr.write(
217
+ "hq-sync-runner: skipping claim-dance — idToken missing sub/name\n",
218
+ );
219
+ return;
220
+ }
221
+
222
+ const person = await client.ensureMyPersonEntity({
223
+ ownerSub,
224
+ displayName,
225
+ });
226
+ await client.claimPendingInvitesByEmail(person.uid);
227
+ } catch (err) {
228
+ const msg = err instanceof Error ? err.message : String(err);
229
+ stderr.write(`hq-sync-runner: claim-dance skipped — ${msg}\n`);
230
+ }
231
+ }
232
+
233
+ // ---------------------------------------------------------------------------
234
+ // argv parser — intentionally minimal (no commander/yargs dep)
235
+ // ---------------------------------------------------------------------------
236
+
237
+ interface ParsedArgs {
238
+ companies: boolean;
239
+ company?: string;
240
+ onConflict: ConflictStrategy;
241
+ hqRoot: string;
242
+ }
243
+
244
+ function parseArgs(argv: string[]): ParsedArgs | { error: string } {
245
+ let companies = false;
246
+ let company: string | undefined;
247
+ let onConflict: ConflictStrategy = "abort";
248
+ let hqRoot = DEFAULT_HQ_ROOT;
249
+
250
+ for (let i = 0; i < argv.length; i++) {
251
+ const arg = argv[i];
252
+ switch (arg) {
253
+ case "--companies":
254
+ companies = true;
255
+ break;
256
+ case "--company":
257
+ company = argv[++i];
258
+ if (!company) return { error: "--company requires a value" };
259
+ break;
260
+ case "--on-conflict": {
261
+ const val = argv[++i];
262
+ if (val !== "abort" && val !== "overwrite" && val !== "keep") {
263
+ return {
264
+ error: `--on-conflict must be one of abort|overwrite|keep, got: ${val ?? "(missing)"}`,
265
+ };
266
+ }
267
+ onConflict = val;
268
+ break;
269
+ }
270
+ case "--hq-root":
271
+ hqRoot = argv[++i];
272
+ if (!hqRoot) return { error: "--hq-root requires a value" };
273
+ break;
274
+ case "--json":
275
+ // Accepted but ignored — ndjson is the only output mode.
276
+ break;
277
+ default:
278
+ return { error: `Unknown argument: ${arg}` };
279
+ }
280
+ }
281
+
282
+ if (companies && company) {
283
+ return { error: "Pass --companies OR --company <slug>, not both" };
284
+ }
285
+ if (!companies && !company) {
286
+ return { error: "Pass --companies or --company <slug>" };
287
+ }
288
+
289
+ return { companies, company, onConflict, hqRoot };
290
+ }
291
+
292
+ // ---------------------------------------------------------------------------
293
+ // runRunner — testable entrypoint
294
+ // ---------------------------------------------------------------------------
295
+
296
+ export async function runRunner(
297
+ argv: string[],
298
+ deps: RunnerDeps = {},
299
+ ): Promise<number> {
300
+ const stdout = deps.stdout ?? process.stdout;
301
+ const stderr = deps.stderr ?? process.stderr;
302
+
303
+ const emit = (event: RunnerEvent): void => {
304
+ stdout.write(`${JSON.stringify(event)}\n`);
305
+ };
306
+
307
+ // ---- argv -------------------------------------------------------------
308
+ const parsed = parseArgs(argv);
309
+ if ("error" in parsed) {
310
+ stderr.write(`hq-sync-runner: ${parsed.error}\n`);
311
+ return 1;
312
+ }
313
+
314
+ // ---- auth -------------------------------------------------------------
315
+ let accessToken: string;
316
+ try {
317
+ const getAccessToken =
318
+ deps.getAccessToken ??
319
+ (() => getValidAccessToken(DEFAULT_COGNITO, { interactive: false }));
320
+ accessToken = await getAccessToken();
321
+ } catch (err) {
322
+ emit({
323
+ type: "auth-error",
324
+ message: err instanceof Error ? err.message : String(err),
325
+ });
326
+ return 0;
327
+ }
328
+
329
+ // ---- vault client -----------------------------------------------------
330
+ const vaultConfig: VaultServiceConfig = {
331
+ apiUrl: DEFAULT_VAULT_API_URL,
332
+ authToken: accessToken,
333
+ region: DEFAULT_COGNITO.region,
334
+ };
335
+ const client =
336
+ deps.createVaultClient?.(vaultConfig) ?? new VaultClient(vaultConfig);
337
+
338
+ // ---- resolve targets --------------------------------------------------
339
+ let memberships: Pick<Membership, "companyUid">[];
340
+ try {
341
+ if (parsed.companies) {
342
+ // Before giving up on memberships, run the claim-dance: new users signed
343
+ // in via the tray may have email-keyed invites waiting for them. Without
344
+ // this, an invited user would see "setup-needed" on every tray click.
345
+ const getClaims = deps.getIdTokenClaims ?? defaultGetIdTokenClaims;
346
+ const claims = getClaims();
347
+ if (claims) {
348
+ await runClaimDance(client, claims, stderr);
349
+ }
350
+
351
+ memberships = await client.listMyMemberships();
352
+ if (memberships.length === 0) {
353
+ // Truly empty — still a valid state (no memberships = nothing to
354
+ // sync). The tray will show a friendly "create your first company"
355
+ // CTA rather than an alarm banner.
356
+ emit({ type: "setup-needed" });
357
+ return 0;
358
+ }
359
+ } else {
360
+ // Single-company mode: fabricate a minimal membership so the fanout
361
+ // loop below treats it uniformly. We don't need to hit
362
+ // /membership/me — the caller already told us which company.
363
+ memberships = [{ companyUid: parsed.company! }];
364
+ }
365
+ } catch (err) {
366
+ if (err instanceof VaultAuthError) {
367
+ emit({
368
+ type: "auth-error",
369
+ message: err.message,
370
+ });
371
+ return 0;
372
+ }
373
+ // Any other failure is unrecoverable — surface as an error event and
374
+ // exit non-zero so the spawner knows the runner didn't get far enough
375
+ // to emit a useful protocol stream.
376
+ emit({
377
+ type: "error",
378
+ message: err instanceof Error ? err.message : String(err),
379
+ path: "(discovery)",
380
+ });
381
+ return 1;
382
+ }
383
+
384
+ // ---- resolve slugs for the fanout plan --------------------------------
385
+ // The menubar wants "Syncing indigo" in its UI, not the raw cmp_* ULID.
386
+ // If the entity fetch fails for some row (entity deleted, scoping issue),
387
+ // degrade to using the UID as the slug rather than aborting the run.
388
+ const plan: Array<{ uid: string; slug: string; name?: string }> = [];
389
+ for (const m of memberships) {
390
+ let slug = m.companyUid;
391
+ let name: string | undefined;
392
+ try {
393
+ const info = await client.entity.get(m.companyUid);
394
+ slug = info.slug || m.companyUid;
395
+ name = info.name;
396
+ } catch {
397
+ // Best-effort — keep UID as the display identifier.
398
+ }
399
+ plan.push({ uid: m.companyUid, slug, ...(name ? { name } : {}) });
400
+ }
401
+ emit({ type: "fanout-plan", companies: plan });
402
+
403
+ // ---- fanout -----------------------------------------------------------
404
+ const syncFn = deps.sync ?? defaultSync;
405
+ let totalFiles = 0;
406
+ let totalBytes = 0;
407
+ const errors: Array<{ company: string; message: string }> = [];
408
+
409
+ for (const target of plan) {
410
+ const companyLabel = target.slug;
411
+ try {
412
+ const result = await syncFn({
413
+ company: target.uid,
414
+ vaultConfig,
415
+ hqRoot: parsed.hqRoot,
416
+ onConflict: parsed.onConflict,
417
+ onEvent: (event) => {
418
+ // Tag per-file events with the company they belong to so the
419
+ // menubar can route them to the right company's progress bar.
420
+ if (event.type === "progress") {
421
+ emit({
422
+ type: "progress",
423
+ company: companyLabel,
424
+ path: event.path,
425
+ bytes: event.bytes,
426
+ ...(event.message ? { message: event.message } : {}),
427
+ });
428
+ } else {
429
+ emit({
430
+ type: "error",
431
+ company: companyLabel,
432
+ path: event.path,
433
+ message: event.message,
434
+ });
435
+ }
436
+ },
437
+ });
438
+ emit({ type: "complete", company: companyLabel, ...result });
439
+ totalFiles += result.filesDownloaded;
440
+ totalBytes += result.bytesDownloaded;
441
+ } catch (err) {
442
+ const message = err instanceof Error ? err.message : String(err);
443
+ errors.push({ company: companyLabel, message });
444
+ emit({
445
+ type: "error",
446
+ company: companyLabel,
447
+ path: "(company)",
448
+ message,
449
+ });
450
+ // Continue — one company's failure shouldn't abort the whole fanout.
451
+ }
452
+ }
453
+
454
+ emit({
455
+ type: "all-complete",
456
+ companiesAttempted: plan.length,
457
+ filesDownloaded: totalFiles,
458
+ bytesDownloaded: totalBytes,
459
+ errors,
460
+ });
461
+ return 0;
462
+ }
463
+
464
+ // ---------------------------------------------------------------------------
465
+ // Entrypoint — only runs when invoked directly, not when imported for tests
466
+ // ---------------------------------------------------------------------------
467
+
468
+ // Detect whether this module is the entry point. The obvious check
469
+ // (`import.meta.url === file://${argv[1]}`) breaks for every real-world
470
+ // install shape: npm-link'd binaries, global installs via Homebrew, and
471
+ // pnpm's `node_modules/.bin` shims all leave `process.argv[1]` pointing
472
+ // at a symlink named `hq-sync-runner` (no `.js` suffix) while
473
+ // `import.meta.url` always resolves to the underlying `sync-runner.js`.
474
+ //
475
+ // Resolve both sides through realpath before comparing — that's the only
476
+ // way to handle all symlink layouts without false negatives. If realpath
477
+ // fails (argv[1] gone, permissions), fall through to `false` so we
478
+ // don't run twice when imported as a library.
479
+ const isDirectInvocation = (() => {
480
+ if (!process.argv[1]) return false;
481
+ try {
482
+ const modulePath = fs.realpathSync(fileURLToPath(import.meta.url));
483
+ const argvPath = fs.realpathSync(process.argv[1]);
484
+ return modulePath === argvPath;
485
+ } catch {
486
+ return false;
487
+ }
488
+ })();
489
+
490
+ if (isDirectInvocation) {
491
+ runRunner(process.argv.slice(2))
492
+ .then((code) => process.exit(code))
493
+ .catch((err) => {
494
+ process.stderr.write(
495
+ `hq-sync-runner: uncaught error — ${err instanceof Error ? err.stack ?? err.message : String(err)}\n`,
496
+ );
497
+ process.exit(1);
498
+ });
499
+ }
@@ -0,0 +1,97 @@
1
+ /**
2
+ * `hq accept` command — accept a membership invite (VLT-7 US-003).
3
+ *
4
+ * Parses magic links (hq://accept/<token> or raw tokens), resolves the
5
+ * caller's identity from Cognito, and calls VaultClient.acceptInvite().
6
+ */
7
+
8
+ import type { VaultServiceConfig } from "../types.js";
9
+ import {
10
+ VaultClient,
11
+ VaultAuthError,
12
+ VaultNotFoundError,
13
+ VaultConflictError,
14
+ VaultPermissionDeniedError,
15
+ } from "../vault-client.js";
16
+ import type { Membership } from "../vault-client.js";
17
+
18
+ export interface AcceptOptions {
19
+ /** Raw token or magic link (hq://accept/<token>) */
20
+ tokenOrLink: string;
21
+ /** Caller's person UID (from Cognito) */
22
+ callerUid: string;
23
+ /** Vault service config */
24
+ vaultConfig: VaultServiceConfig;
25
+ }
26
+
27
+ export interface AcceptResult {
28
+ membership: Membership;
29
+ companySlug?: string;
30
+ }
31
+
32
+ /**
33
+ * Parse a magic link or raw token into the raw invite token.
34
+ */
35
+ export function parseToken(tokenOrLink: string): string {
36
+ const trimmed = tokenOrLink.trim();
37
+
38
+ // hq://accept/<token>
39
+ if (trimmed.startsWith("hq://accept/")) {
40
+ return trimmed.slice("hq://accept/".length);
41
+ }
42
+
43
+ // https://hq.indigoai.com/accept/<token> (future web route)
44
+ const httpsPrefix = "https://hq.indigoai.com/accept/";
45
+ if (trimmed.startsWith(httpsPrefix)) {
46
+ return trimmed.slice(httpsPrefix.length);
47
+ }
48
+
49
+ // Raw token
50
+ return trimmed;
51
+ }
52
+
53
+ /**
54
+ * Accept a membership invite.
55
+ */
56
+ export async function accept(options: AcceptOptions): Promise<AcceptResult> {
57
+ const { tokenOrLink, callerUid, vaultConfig } = options;
58
+ const token = parseToken(tokenOrLink);
59
+
60
+ if (!token) {
61
+ throw new Error("No invite token provided. Usage: /accept <token-or-magic-link>");
62
+ }
63
+
64
+ const client = new VaultClient(vaultConfig);
65
+
66
+ try {
67
+ const result = await client.acceptInvite(token, callerUid);
68
+ const membership = result.membership;
69
+
70
+ // Try to resolve company slug for display
71
+ let companySlug: string | undefined;
72
+ if (membership.companyUid) {
73
+ try {
74
+ const entity = await client.entity.get(membership.companyUid);
75
+ companySlug = entity.slug;
76
+ } catch {
77
+ // Non-critical — just display UID instead
78
+ }
79
+ }
80
+
81
+ return { membership, companySlug };
82
+ } catch (err) {
83
+ if (err instanceof VaultAuthError) {
84
+ throw new Error("Authentication failed — run `hq auth` to refresh your session");
85
+ }
86
+ if (err instanceof VaultConflictError) {
87
+ throw new Error("This invite was already accepted");
88
+ }
89
+ if (err instanceof VaultNotFoundError) {
90
+ throw new Error("Invite not found or expired");
91
+ }
92
+ if (err instanceof VaultPermissionDeniedError) {
93
+ throw new Error("This invite was for a different person");
94
+ }
95
+ throw err;
96
+ }
97
+ }