@indigoai-us/hq-cli 5.5.0 → 5.5.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (103) hide show
  1. package/dist/bin/hq-auth-refresh.js +0 -0
  2. package/dist/commands/add.d.ts.map +1 -1
  3. package/dist/commands/add.js +2 -1
  4. package/dist/commands/add.js.map +1 -1
  5. package/dist/commands/auth.d.ts +0 -3
  6. package/dist/commands/auth.d.ts.map +1 -1
  7. package/dist/commands/auth.js +0 -3
  8. package/dist/commands/auth.js.map +1 -1
  9. package/dist/commands/cloud.d.ts +12 -2
  10. package/dist/commands/cloud.d.ts.map +1 -1
  11. package/dist/commands/cloud.js +112 -80
  12. package/dist/commands/cloud.js.map +1 -1
  13. package/dist/commands/list.d.ts.map +1 -1
  14. package/dist/commands/list.js +18 -1
  15. package/dist/commands/list.js.map +1 -1
  16. package/dist/commands/login.d.ts +1 -1
  17. package/dist/commands/login.d.ts.map +1 -1
  18. package/dist/commands/login.js +28 -9
  19. package/dist/commands/login.js.map +1 -1
  20. package/dist/commands/logout.d.ts +1 -1
  21. package/dist/commands/logout.d.ts.map +1 -1
  22. package/dist/commands/logout.js +8 -3
  23. package/dist/commands/logout.js.map +1 -1
  24. package/dist/commands/onboard.d.ts +23 -0
  25. package/dist/commands/onboard.d.ts.map +1 -0
  26. package/dist/commands/onboard.js +142 -0
  27. package/dist/commands/onboard.js.map +1 -0
  28. package/dist/commands/pack-install.d.ts +44 -0
  29. package/dist/commands/pack-install.d.ts.map +1 -0
  30. package/dist/commands/pack-install.js +513 -0
  31. package/dist/commands/pack-install.js.map +1 -0
  32. package/dist/commands/pkg-install.d.ts.map +1 -1
  33. package/dist/commands/pkg-install.js +20 -8
  34. package/dist/commands/pkg-install.js.map +1 -1
  35. package/dist/commands/pkg-list.js +4 -4
  36. package/dist/commands/pkg-list.js.map +1 -1
  37. package/dist/commands/pkg-update.js +3 -3
  38. package/dist/commands/pkg-update.js.map +1 -1
  39. package/dist/commands/secrets.d.ts +3 -0
  40. package/dist/commands/secrets.d.ts.map +1 -0
  41. package/dist/commands/secrets.js +521 -0
  42. package/dist/commands/secrets.js.map +1 -0
  43. package/dist/commands/sync.d.ts.map +1 -1
  44. package/dist/commands/sync.js +10 -2
  45. package/dist/commands/sync.js.map +1 -1
  46. package/dist/commands/team-sync.d.ts.map +1 -1
  47. package/dist/commands/team-sync.js +6 -6
  48. package/dist/commands/team-sync.js.map +1 -1
  49. package/dist/commands/whoami.d.ts +1 -1
  50. package/dist/commands/whoami.d.ts.map +1 -1
  51. package/dist/commands/whoami.js +23 -7
  52. package/dist/commands/whoami.js.map +1 -1
  53. package/dist/index.js +7 -1
  54. package/dist/index.js.map +1 -1
  55. package/dist/strategies/link.d.ts +2 -2
  56. package/dist/strategies/link.d.ts.map +1 -1
  57. package/dist/strategies/link.js.map +1 -1
  58. package/dist/strategies/merge.d.ts +2 -2
  59. package/dist/strategies/merge.d.ts.map +1 -1
  60. package/dist/strategies/merge.js.map +1 -1
  61. package/dist/types.d.ts +37 -3
  62. package/dist/types.d.ts.map +1 -1
  63. package/dist/types.js +6 -0
  64. package/dist/types.js.map +1 -1
  65. package/dist/utils/cognito-session.d.ts +18 -7
  66. package/dist/utils/cognito-session.d.ts.map +1 -1
  67. package/dist/utils/cognito-session.js +35 -8
  68. package/dist/utils/cognito-session.js.map +1 -1
  69. package/dist/utils/manifest.d.ts +13 -0
  70. package/dist/utils/manifest.d.ts.map +1 -1
  71. package/dist/utils/manifest.js +24 -1
  72. package/dist/utils/manifest.js.map +1 -1
  73. package/dist/utils/secrets-cache.d.ts +7 -0
  74. package/dist/utils/secrets-cache.d.ts.map +1 -0
  75. package/dist/utils/secrets-cache.js +134 -0
  76. package/dist/utils/secrets-cache.js.map +1 -0
  77. package/package.json +15 -5
  78. package/src/commands/add.ts +7 -6
  79. package/src/commands/auth.ts +0 -3
  80. package/src/commands/cloud.ts +214 -101
  81. package/src/commands/list.ts +20 -1
  82. package/src/commands/login.ts +28 -9
  83. package/src/commands/logout.ts +8 -3
  84. package/src/commands/onboard.ts +193 -0
  85. package/src/commands/pack-install.ts +667 -0
  86. package/src/commands/pkg-install.ts +34 -16
  87. package/src/commands/pkg-list.ts +4 -4
  88. package/src/commands/pkg-update.ts +3 -3
  89. package/src/commands/secrets.ts +670 -0
  90. package/src/commands/sync.ts +20 -4
  91. package/src/commands/team-sync.ts +7 -8
  92. package/src/commands/whoami.ts +22 -7
  93. package/src/index.ts +9 -1
  94. package/src/strategies/link.ts +2 -2
  95. package/src/strategies/merge.ts +2 -2
  96. package/src/types.ts +54 -4
  97. package/src/utils/cognito-session.ts +46 -14
  98. package/src/utils/manifest.test.ts +148 -0
  99. package/src/utils/manifest.ts +22 -1
  100. package/src/utils/secrets-cache.ts +129 -0
  101. package/tsconfig.json +2 -1
  102. package/src/utils/auth.ts +0 -193
  103. package/src/utils/token-store.ts +0 -83
@@ -1,125 +1,238 @@
1
1
  /**
2
- * hq sync commands — cloud sync management
3
- * Bridges hq-cli to @indigoai-us/hq-cloud
2
+ * `hq sync` commands — push/pull files between the local HQ tree and the
3
+ * company's S3 vault bucket.
4
+ *
5
+ * VLT-5 model: each command resolves a Cognito access token, asks
6
+ * vault-service for the company's bucket + STS-vended credentials, and
7
+ * runs the operation. No daemon, no init step (handled by `hq onboard`),
8
+ * no long-lived background process — every invocation is self-contained.
9
+ *
10
+ * Subcommands:
11
+ * hq sync push [paths...] — broadcast local file(s) to the vault
12
+ * hq sync pull — pull all permitted files from the vault
13
+ * hq sync status — show local journal summary
4
14
  */
5
15
 
6
16
  import { Command } from "commander";
7
- import { findHqRoot } from "../utils/manifest.js";
17
+ import chalk from "chalk";
18
+ import * as fs from "fs";
19
+ import * as path from "path";
20
+
21
+ import {
22
+ share,
23
+ sync,
24
+ readJournal,
25
+ getJournalPath,
26
+ type ConflictStrategy,
27
+ } from "@indigoai-us/hq-cloud";
28
+
29
+ import {
30
+ DEFAULT_HQ_ROOT,
31
+ ensureCognitoToken,
32
+ buildVaultConfig,
33
+ } from "../utils/cognito-session.js";
34
+
35
+ interface CommonSyncOptions {
36
+ hqRoot: string;
37
+ company?: string;
38
+ }
8
39
 
9
40
  export function registerCloudCommands(program: Command): void {
10
41
  program
11
- .command("init")
12
- .description("Authenticate with IndigoAI and set up cloud sync")
13
- .action(async () => {
14
- try {
15
- const hqRoot = findHqRoot();
16
- const { initSync } = await import("@indigoai-us/hq-cloud");
17
- await initSync(hqRoot);
18
- } catch (error) {
19
- console.error(
20
- "Error:",
21
- error instanceof Error ? error.message : error
22
- );
23
- process.exit(1);
24
- }
25
- });
42
+ .command("push")
43
+ .description("Push local file(s) to the company vault on S3")
44
+ .argument("[paths...]", "Paths to push (defaults to current directory)")
45
+ .option(
46
+ "--hq-root <path>",
47
+ `Local HQ tree root (default: ${DEFAULT_HQ_ROOT})`,
48
+ DEFAULT_HQ_ROOT,
49
+ )
50
+ .option(
51
+ "--company <slug>",
52
+ "Company slug or UID (defaults to active company in .hq/config.json)",
53
+ )
54
+ .option(
55
+ "--message <msg>",
56
+ "Optional message attached to journal entries for these uploads",
57
+ )
58
+ .option(
59
+ "--on-conflict <strategy>",
60
+ "Conflict strategy: overwrite | keep | abort (omit for interactive)",
61
+ )
62
+ .action(
63
+ async (
64
+ paths: string[],
65
+ options: CommonSyncOptions & {
66
+ message?: string;
67
+ onConflict?: ConflictStrategy;
68
+ },
69
+ ) => {
70
+ try {
71
+ const targetPaths =
72
+ paths && paths.length > 0 ? paths : [process.cwd()];
26
73
 
27
- program
28
- .command("start")
29
- .description("Start the background sync daemon")
30
- .action(async () => {
31
- try {
32
- const hqRoot = findHqRoot();
33
- const { startDaemon } = await import("@indigoai-us/hq-cloud");
34
- await startDaemon(hqRoot);
35
- console.log("Sync daemon started. Use 'hq sync status' to check.");
36
- } catch (error) {
37
- console.error(
38
- "Error:",
39
- error instanceof Error ? error.message : error
40
- );
41
- process.exit(1);
42
- }
43
- });
74
+ console.log(chalk.bold("\nHQ Sync — Push"));
75
+ console.log(` HQ root: ${options.hqRoot}`);
76
+ console.log(` Company: ${options.company ?? "(from .hq/config.json)"}`);
77
+ console.log(` Paths: ${targetPaths.join(", ")}\n`);
44
78
 
45
- program
46
- .command("stop")
47
- .description("Stop the sync daemon")
48
- .action(async () => {
49
- try {
50
- const hqRoot = findHqRoot();
51
- const { stopDaemon } = await import("@indigoai-us/hq-cloud");
52
- await stopDaemon(hqRoot);
53
- console.log("Sync daemon stopped.");
54
- } catch (error) {
55
- console.error(
56
- "Error:",
57
- error instanceof Error ? error.message : error
58
- );
59
- process.exit(1);
60
- }
61
- });
79
+ const accessToken = await ensureCognitoToken();
80
+ const result = await share({
81
+ paths: targetPaths,
82
+ company: options.company,
83
+ message: options.message,
84
+ onConflict: options.onConflict,
85
+ vaultConfig: buildVaultConfig(accessToken),
86
+ hqRoot: options.hqRoot,
87
+ });
88
+
89
+ if (result.aborted) {
90
+ console.log(
91
+ chalk.yellow(
92
+ `\n⚠ Push aborted (${result.filesUploaded} uploaded, ${result.filesSkipped} skipped)`,
93
+ ),
94
+ );
95
+ process.exit(1);
96
+ }
97
+
98
+ console.log(
99
+ chalk.green(
100
+ `\n✓ Pushed ${result.filesUploaded} file(s) (${formatBytes(result.bytesUploaded)}, ${result.filesSkipped} skipped)`,
101
+ ),
102
+ );
103
+ } catch (err) {
104
+ console.error(
105
+ chalk.red("\n✗ Push failed:"),
106
+ err instanceof Error ? err.message : String(err),
107
+ );
108
+ process.exit(1);
109
+ }
110
+ },
111
+ );
62
112
 
63
113
  program
64
- .command("status")
65
- .description("Show sync status")
66
- .action(async () => {
67
- try {
68
- const hqRoot = findHqRoot();
69
- const { getStatus } = await import("@indigoai-us/hq-cloud");
70
- const status = await getStatus(hqRoot);
71
- console.log(` State: ${status.running ? "running" : "stopped"}`);
72
- console.log(` Last sync: ${status.lastSync || "never"}`);
73
- console.log(` Files: ${status.fileCount} tracked`);
74
- console.log(` Bucket: ${status.bucket || "not configured"}`);
75
- if (status.errors.length > 0) {
76
- console.log(` Errors: ${status.errors.length}`);
77
- for (const err of status.errors.slice(0, 5)) {
78
- console.log(` - ${err}`);
114
+ .command("pull")
115
+ .description("Pull permitted files from the company vault to local HQ")
116
+ .option(
117
+ "--hq-root <path>",
118
+ `Local HQ tree root (default: ${DEFAULT_HQ_ROOT})`,
119
+ DEFAULT_HQ_ROOT,
120
+ )
121
+ .option(
122
+ "--company <slug>",
123
+ "Company slug or UID (defaults to active company in .hq/config.json)",
124
+ )
125
+ .option(
126
+ "--on-conflict <strategy>",
127
+ "Conflict strategy: overwrite | keep | abort (omit for interactive)",
128
+ )
129
+ .action(
130
+ async (
131
+ options: CommonSyncOptions & {
132
+ onConflict?: ConflictStrategy;
133
+ },
134
+ ) => {
135
+ try {
136
+ console.log(chalk.bold("\nHQ Sync — Pull"));
137
+ console.log(` HQ root: ${options.hqRoot}`);
138
+ console.log(` Company: ${options.company ?? "(from .hq/config.json)"}\n`);
139
+
140
+ const accessToken = await ensureCognitoToken();
141
+ const result = await sync({
142
+ company: options.company,
143
+ onConflict: options.onConflict,
144
+ vaultConfig: buildVaultConfig(accessToken),
145
+ hqRoot: options.hqRoot,
146
+ });
147
+
148
+ if (result.aborted) {
149
+ console.log(
150
+ chalk.yellow(
151
+ `\n⚠ Pull aborted (${result.filesDownloaded} downloaded, ${result.filesSkipped} skipped, ${result.conflicts} conflicts)`,
152
+ ),
153
+ );
154
+ process.exit(1);
79
155
  }
156
+
157
+ console.log(
158
+ chalk.green(
159
+ `\n✓ Pulled ${result.filesDownloaded} file(s) (${formatBytes(result.bytesDownloaded)}, ${result.filesSkipped} skipped, ${result.conflicts} conflicts)`,
160
+ ),
161
+ );
162
+ } catch (err) {
163
+ console.error(
164
+ chalk.red("\n✗ Pull failed:"),
165
+ err instanceof Error ? err.message : String(err),
166
+ );
167
+ process.exit(1);
80
168
  }
81
- } catch (error) {
82
- console.error(
83
- "Error:",
84
- error instanceof Error ? error.message : error
85
- );
86
- process.exit(1);
87
- }
88
- });
169
+ },
170
+ );
89
171
 
90
172
  program
91
- .command("push")
92
- .description("Force push all local changes to cloud")
93
- .action(async () => {
173
+ .command("status")
174
+ .description("Show local sync journal summary")
175
+ .option(
176
+ "--hq-root <path>",
177
+ `Local HQ tree root (default: ${DEFAULT_HQ_ROOT})`,
178
+ DEFAULT_HQ_ROOT,
179
+ )
180
+ .action((options: { hqRoot: string }) => {
94
181
  try {
95
- const hqRoot = findHqRoot();
96
- const { pushAll } = await import("@indigoai-us/hq-cloud");
97
- const result = await pushAll(hqRoot);
98
- console.log(`Pushed ${result.filesUploaded} files to cloud.`);
99
- } catch (error) {
100
- console.error(
101
- "Error:",
102
- error instanceof Error ? error.message : error
182
+ const journalPath = getJournalPath(options.hqRoot);
183
+ if (!fs.existsSync(journalPath)) {
184
+ console.log(chalk.dim("No sync journal yet — run `hq sync push` or `hq sync pull` to create one."));
185
+ console.log(chalk.dim(` Expected at: ${journalPath}`));
186
+ return;
187
+ }
188
+
189
+ const journal = readJournal(options.hqRoot);
190
+ const entries = Object.entries(journal.files ?? {});
191
+ const lastSyncTimes = entries
192
+ .map(([, entry]) => entry.syncedAt)
193
+ .filter((t): t is string => typeof t === "string")
194
+ .sort();
195
+ const lastSync = lastSyncTimes.at(-1) ?? "never";
196
+ const totalBytes = entries.reduce(
197
+ (acc, [, entry]) => acc + (entry.size ?? 0),
198
+ 0,
103
199
  );
104
- process.exit(1);
105
- }
106
- });
107
200
 
108
- program
109
- .command("pull")
110
- .description("Force pull all cloud changes to local")
111
- .action(async () => {
112
- try {
113
- const hqRoot = findHqRoot();
114
- const { pullAll } = await import("@indigoai-us/hq-cloud");
115
- const result = await pullAll(hqRoot);
116
- console.log(`Pulled ${result.filesDownloaded} files from cloud.`);
117
- } catch (error) {
201
+ const configPath = path.join(options.hqRoot, ".hq", "config.json");
202
+ let activeCompany: string | undefined;
203
+ if (fs.existsSync(configPath)) {
204
+ try {
205
+ const cfg = JSON.parse(fs.readFileSync(configPath, "utf-8"));
206
+ activeCompany = cfg.activeCompany;
207
+ } catch {
208
+ // ignore
209
+ }
210
+ }
211
+
212
+ console.log(chalk.bold("\nHQ Sync — Status"));
213
+ console.log(` HQ root: ${options.hqRoot}`);
214
+ console.log(` Active company: ${activeCompany ?? chalk.dim("(none)")}`);
215
+ console.log(` Tracked files: ${entries.length}`);
216
+ console.log(` Total size: ${formatBytes(totalBytes)}`);
217
+ console.log(` Last sync: ${lastSync}`);
218
+ console.log(` Journal: ${journalPath}`);
219
+ } catch (err) {
118
220
  console.error(
119
- "Error:",
120
- error instanceof Error ? error.message : error
221
+ chalk.red("✗ Status failed:"),
222
+ err instanceof Error ? err.message : String(err),
121
223
  );
122
224
  process.exit(1);
123
225
  }
124
226
  });
125
227
  }
228
+
229
+ function formatBytes(bytes: number): string {
230
+ if (bytes === 0) return "0 B";
231
+ const units = ["B", "KB", "MB", "GB"];
232
+ const exponent = Math.min(
233
+ Math.floor(Math.log(bytes) / Math.log(1024)),
234
+ units.length - 1,
235
+ );
236
+ const value = bytes / Math.pow(1024, exponent);
237
+ return `${value.toFixed(value >= 100 || exponent === 0 ? 0 : 1)} ${units[exponent]}`;
238
+ }
@@ -29,10 +29,29 @@ export function registerListCommand(program: Command): void {
29
29
  console.log('Modules:\n');
30
30
 
31
31
  for (const module of manifest.modules) {
32
+ console.log(` ${module.name}`);
33
+
34
+ if (module.strategy === 'package') {
35
+ // hq-pack content pack — wired by scripts/scan-packages.sh
36
+ console.log(` Strategy: package`);
37
+ console.log(` Source: ${module.source}`);
38
+ if (module.version) {
39
+ console.log(` Version: ${module.version}`);
40
+ }
41
+ if (module.installed_at) {
42
+ console.log(` Path: ${module.installed_at}`);
43
+ }
44
+ if (module.resolved_sha) {
45
+ console.log(` SHA: ${module.resolved_sha}`);
46
+ }
47
+ console.log();
48
+ continue;
49
+ }
50
+
51
+ // legacy git-repo module
32
52
  const moduleDir = path.join(modulesDir, module.name);
33
53
  const installed = await isRepo(moduleDir);
34
54
 
35
- console.log(` ${module.name}`);
36
55
  console.log(` Repo: ${module.repo}`);
37
56
  console.log(` Branch: ${module.branch || 'main'}`);
38
57
  console.log(` Strategy: ${module.strategy}`);
@@ -1,23 +1,42 @@
1
1
  /**
2
- * hq login — opens browser for Clerk auth, caches token (US-004)
2
+ * hq login — opens browser for Cognito auth via Google OAuth
3
3
  */
4
4
 
5
5
  import { Command } from 'commander';
6
6
  import chalk from 'chalk';
7
- import { startAuthFlow } from '../utils/auth.js';
8
- import { saveToken } from '../utils/token-store.js';
9
- import { getRegistryUrl } from '../utils/registry-client.js';
7
+ import { browserLogin, loadCachedTokens, isExpiring } from '@indigoai-us/hq-cloud';
8
+ import { DEFAULT_COGNITO } from '../utils/cognito-session.js';
9
+
10
+ function peekIdToken(idToken: string): { email?: string; sub?: string } {
11
+ try {
12
+ const payload = idToken.split('.')[1];
13
+ if (!payload) return {};
14
+ const pad = payload.length % 4 === 0 ? '' : '='.repeat(4 - (payload.length % 4));
15
+ const normalized = payload.replace(/-/g, '+').replace(/_/g, '/') + pad;
16
+ const decoded = JSON.parse(Buffer.from(normalized, 'base64').toString('utf-8'));
17
+ return { email: decoded.email, sub: decoded.sub };
18
+ } catch {
19
+ return {};
20
+ }
21
+ }
10
22
 
11
23
  export function registerLoginCommand(program: Command): void {
12
24
  program
13
25
  .command('login')
14
- .description('Authenticate with the HQ package registry')
26
+ .description('Authenticate with HQ via Cognito (Google OAuth)')
15
27
  .action(async () => {
16
28
  try {
17
- const registryUrl = getRegistryUrl();
18
- const token = await startAuthFlow(registryUrl);
19
- await saveToken(token);
20
- console.log(chalk.green(`Logged in as ${token.email}`));
29
+ const existing = loadCachedTokens();
30
+ if (existing && !isExpiring(existing, 120)) {
31
+ const who = peekIdToken(existing.idToken).email ?? 'cached session';
32
+ console.log(chalk.green(`Already logged in as ${who}. Run \`hq logout\` to switch accounts.`));
33
+ return;
34
+ }
35
+
36
+ console.log('Opening browser for authentication...');
37
+ const tokens = await browserLogin(DEFAULT_COGNITO);
38
+ const who = peekIdToken(tokens.idToken).email ?? 'HQ';
39
+ console.log(chalk.green(`Logged in as ${who}`));
21
40
  } catch (error) {
22
41
  console.error(
23
42
  chalk.red('Login failed:'),
@@ -1,10 +1,10 @@
1
1
  /**
2
- * hq logout — clears cached session (US-004)
2
+ * hq logout — clears cached Cognito session
3
3
  */
4
4
 
5
5
  import { Command } from 'commander';
6
6
  import chalk from 'chalk';
7
- import { clearToken } from '../utils/token-store.js';
7
+ import { clearCachedTokens, loadCachedTokens } from '@indigoai-us/hq-cloud';
8
8
 
9
9
  export function registerLogoutCommand(program: Command): void {
10
10
  program
@@ -12,7 +12,12 @@ export function registerLogoutCommand(program: Command): void {
12
12
  .description('Log out and clear cached credentials')
13
13
  .action(async () => {
14
14
  try {
15
- await clearToken();
15
+ const existing = loadCachedTokens();
16
+ if (!existing) {
17
+ console.log(chalk.yellow('No cached HQ session'));
18
+ return;
19
+ }
20
+ clearCachedTokens();
16
21
  console.log(chalk.green('Logged out successfully'));
17
22
  } catch (error) {
18
23
  console.error(
@@ -0,0 +1,193 @@
1
+ /**
2
+ * `hq onboard` — bootstrap an HQ vault: sign in to Cognito + provision
3
+ * the company entity, S3 bucket, KMS key, owner membership, and STS-vended
4
+ * credentials in one flow.
5
+ *
6
+ * This is the "the entire flow" entry point that VLT-9 was building toward:
7
+ * a real user can install hq-cli and run `hq onboard create-company` once
8
+ * to land in a fully provisioned vault, then use `hq sync push|pull` to
9
+ * round-trip files against S3.
10
+ *
11
+ * Subcommands:
12
+ * hq onboard create-company — provision a brand new company
13
+ * hq onboard join — accept an invite from another user
14
+ * hq onboard resume — resume a partially-completed flow from checkpoint
15
+ * hq onboard dry-run — show what create-company would do, without doing it
16
+ *
17
+ * Auth: we cache the Cognito access + refresh tokens at ~/.hq/cognito-tokens.json.
18
+ * If the cached token is missing or expired beyond the refresh window, the
19
+ * browser-OAuth flow opens automatically.
20
+ */
21
+
22
+ import { Command } from "commander";
23
+ import chalk from "chalk";
24
+
25
+ import { runOnboardCli } from "@indigoai-us/hq-onboarding";
26
+ import {
27
+ DEFAULT_HQ_ROOT,
28
+ ensureCognitoToken,
29
+ buildVaultConfig,
30
+ } from "../utils/cognito-session.js";
31
+
32
+ // ---------------------------------------------------------------------------
33
+ // Command registration
34
+ // ---------------------------------------------------------------------------
35
+
36
+ export function registerOnboardCommand(program: Command): void {
37
+ const onboard = program
38
+ .command("onboard")
39
+ .description("Provision an HQ vault: sign in, create company, S3 bucket, STS, sync");
40
+
41
+ onboard
42
+ .command("create-company")
43
+ .description("Sign in and provision a brand new HQ vault for a company")
44
+ .requiredOption("--slug <slug>", "Company slug (used as bucket name suffix)")
45
+ .requiredOption("--name <name>", "Company display name")
46
+ .requiredOption("--email <email>", "Your email (must match Cognito sign-in)")
47
+ .requiredOption("--person-name <name>", "Your display name")
48
+ .option(
49
+ "--hq-root <path>",
50
+ `Local HQ tree root (default: ${DEFAULT_HQ_ROOT})`,
51
+ DEFAULT_HQ_ROOT,
52
+ )
53
+ .action(async (options: {
54
+ slug: string;
55
+ name: string;
56
+ email: string;
57
+ personName: string;
58
+ hqRoot: string;
59
+ }) => {
60
+ try {
61
+ console.log(chalk.bold(`\nHQ Onboard — Create Company`));
62
+ console.log(` Company: ${options.name} (${options.slug})`);
63
+ console.log(` Person: ${options.personName} <${options.email}>`);
64
+ console.log(` HQ root: ${options.hqRoot}\n`);
65
+
66
+ const accessToken = await ensureCognitoToken();
67
+ const result = await runOnboardCli({
68
+ mode: "create-company",
69
+ personName: options.personName,
70
+ personEmail: options.email,
71
+ companyName: options.name,
72
+ companySlug: options.slug,
73
+ vaultConfig: buildVaultConfig(accessToken),
74
+ hqRoot: options.hqRoot,
75
+ });
76
+
77
+ if (!result.success) {
78
+ console.error(chalk.red(`\n✗ Onboarding failed: ${result.error}`));
79
+ process.exit(1);
80
+ }
81
+ } catch (err) {
82
+ console.error(
83
+ chalk.red("\n✗ Error:"),
84
+ err instanceof Error ? err.message : String(err),
85
+ );
86
+ process.exit(1);
87
+ }
88
+ });
89
+
90
+ onboard
91
+ .command("join")
92
+ .description("Accept an invite and join an existing company")
93
+ .requiredOption("--invite-token <token>", "Magic link token from your invite email")
94
+ .requiredOption("--email <email>", "Your email (must match Cognito sign-in)")
95
+ .requiredOption("--person-name <name>", "Your display name")
96
+ .option(
97
+ "--hq-root <path>",
98
+ `Local HQ tree root (default: ${DEFAULT_HQ_ROOT})`,
99
+ DEFAULT_HQ_ROOT,
100
+ )
101
+ .action(async (options: {
102
+ inviteToken: string;
103
+ email: string;
104
+ personName: string;
105
+ hqRoot: string;
106
+ }) => {
107
+ try {
108
+ console.log(chalk.bold(`\nHQ Onboard — Join Company`));
109
+ console.log(` Person: ${options.personName} <${options.email}>`);
110
+ console.log(` HQ root: ${options.hqRoot}\n`);
111
+
112
+ const accessToken = await ensureCognitoToken();
113
+ const result = await runOnboardCli({
114
+ mode: "join-company",
115
+ personName: options.personName,
116
+ personEmail: options.email,
117
+ inviteToken: options.inviteToken,
118
+ vaultConfig: buildVaultConfig(accessToken),
119
+ hqRoot: options.hqRoot,
120
+ });
121
+
122
+ if (!result.success) {
123
+ console.error(chalk.red(`\n✗ Join failed: ${result.error}`));
124
+ process.exit(1);
125
+ }
126
+ } catch (err) {
127
+ console.error(
128
+ chalk.red("\n✗ Error:"),
129
+ err instanceof Error ? err.message : String(err),
130
+ );
131
+ process.exit(1);
132
+ }
133
+ });
134
+
135
+ onboard
136
+ .command("resume")
137
+ .description("Resume a partially-completed onboarding flow from local checkpoint")
138
+ .option(
139
+ "--hq-root <path>",
140
+ `Local HQ tree root (default: ${DEFAULT_HQ_ROOT})`,
141
+ DEFAULT_HQ_ROOT,
142
+ )
143
+ .action(async (options: { hqRoot: string }) => {
144
+ try {
145
+ const accessToken = await ensureCognitoToken();
146
+ const result = await runOnboardCli({
147
+ mode: "resume",
148
+ vaultConfig: buildVaultConfig(accessToken),
149
+ hqRoot: options.hqRoot,
150
+ });
151
+ if (!result.success) {
152
+ console.error(chalk.red(`\n✗ Resume failed: ${result.error}`));
153
+ process.exit(1);
154
+ }
155
+ } catch (err) {
156
+ console.error(
157
+ chalk.red("\n✗ Error:"),
158
+ err instanceof Error ? err.message : String(err),
159
+ );
160
+ process.exit(1);
161
+ }
162
+ });
163
+
164
+ onboard
165
+ .command("dry-run")
166
+ .description("Show what create-company would do, without provisioning anything")
167
+ .option(
168
+ "--hq-root <path>",
169
+ `Local HQ tree root (default: ${DEFAULT_HQ_ROOT})`,
170
+ DEFAULT_HQ_ROOT,
171
+ )
172
+ .action(async (options: { hqRoot: string }) => {
173
+ try {
174
+ // No auth needed for dry-run — runOnboardCli handles this branch
175
+ // without touching the vault-service.
176
+ const result = await runOnboardCli({
177
+ mode: "dry-run",
178
+ vaultConfig: buildVaultConfig("dry-run-no-token"),
179
+ hqRoot: options.hqRoot,
180
+ });
181
+ if (!result.success) {
182
+ console.error(chalk.red(`\n✗ Dry-run failed: ${result.error}`));
183
+ process.exit(1);
184
+ }
185
+ } catch (err) {
186
+ console.error(
187
+ chalk.red("\n✗ Error:"),
188
+ err instanceof Error ? err.message : String(err),
189
+ );
190
+ process.exit(1);
191
+ }
192
+ });
193
+ }