@indigoai-us/hq-cli 5.345.231 → 5.345.233

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 (107) hide show
  1. package/CHANGELOG.md +48 -0
  2. package/README.md +3 -2
  3. package/assets/lanes-reconcile/hq-lanes-reconcile.service +1 -1
  4. package/assets/scaffold/core/scripts/pipeline-conductor.sh +14 -14
  5. package/assets/scaffold/core/scripts/pipeline-driver.sh +7 -7
  6. package/assets/scaffold/core/scripts/session-project.sh +19 -4
  7. package/dist/command-catalog.generated.d.ts +213 -177
  8. package/dist/command-catalog.generated.js +263 -212
  9. package/dist/command-registration-plan.d.ts +6 -24
  10. package/dist/command-registration-plan.js +4 -8
  11. package/dist/commands/auth.js +3 -2
  12. package/dist/commands/core-handoff.d.ts +1 -0
  13. package/dist/commands/core-handoff.js +2 -28
  14. package/dist/commands/core-pipeline-conductor-command.js +1 -1
  15. package/dist/commands/core-pipeline-conductor-native.js +5 -5
  16. package/dist/commands/core-pipeline-driver-native.js +5 -5
  17. package/dist/commands/daemon.js +7 -36
  18. package/dist/commands/deploy-access.js +6 -13
  19. package/dist/commands/deploy-comments.js +5 -13
  20. package/dist/commands/deploy-domains.js +6 -13
  21. package/dist/commands/deploy-list.js +25 -11
  22. package/dist/commands/deploy-mutations.d.ts +3 -0
  23. package/dist/commands/deploy-mutations.js +147 -0
  24. package/dist/commands/link.js +29 -0
  25. package/dist/commands/mcp-serve-gate.d.ts +22 -0
  26. package/dist/commands/mcp-serve-gate.js +37 -0
  27. package/dist/commands/mcp-serve.js +2 -8
  28. package/dist/commands/mesh.js +3 -1
  29. package/dist/commands/report.js +8 -9
  30. package/dist/data/command-states.json +10 -7
  31. package/dist/hq-cloud-sync-runner/bin/sync-runner.js +257 -214
  32. package/dist/hq-cloud-sync-runner/package.json +1 -1
  33. package/dist/index.js +6 -1
  34. package/dist/lib/bot/fleet-bots-update-pass.d.ts +8 -0
  35. package/dist/lib/bot/fleet-bots-update-pass.js +40 -0
  36. package/dist/lib/bot/fleet-bots-update-task.d.ts +12 -0
  37. package/dist/lib/bot/fleet-bots-update-task.js +52 -0
  38. package/dist/lib/bot/fleet-bots-update-worker-v1.d.ts +2 -0
  39. package/dist/lib/bot/fleet-bots-update-worker-v1.js +5 -0
  40. package/dist/lib/daemon/catalog.d.ts +8 -5
  41. package/dist/lib/daemon/catalog.js +15 -8
  42. package/dist/lib/daemon/flag.d.ts +2 -0
  43. package/dist/lib/daemon/flag.js +6 -4
  44. package/dist/lib/daemon/lock.js +33 -37
  45. package/dist/lib/daemon/ops/skill-command.d.ts +99 -0
  46. package/dist/lib/daemon/ops/skill-command.js +260 -0
  47. package/dist/lib/daemon/protocol.d.ts +1 -1
  48. package/dist/lib/daemon/protocol.js +1 -0
  49. package/dist/lib/daemon/run.js +10 -18
  50. package/dist/lib/daemon/server.js +7 -0
  51. package/dist/lib/daemon/shared-flag-reads.d.ts +70 -0
  52. package/dist/lib/daemon/shared-flag-reads.js +173 -0
  53. package/dist/lib/daemon/supervisor.d.ts +5 -0
  54. package/dist/lib/daemon/supervisor.js +17 -2
  55. package/dist/lib/db/app-ref.js +10 -15
  56. package/dist/lib/deploy-apps.d.ts +29 -0
  57. package/dist/lib/deploy-apps.js +37 -0
  58. package/dist/lib/doctor/checks/search-index.d.ts +16 -0
  59. package/dist/lib/doctor/checks/search-index.js +61 -0
  60. package/dist/lib/doctor/checks/stranded-lanes.js +1 -1
  61. package/dist/lib/doctor/registry.js +4 -0
  62. package/dist/lib/flag-registry-worker-source.generated.d.ts +1 -1
  63. package/dist/lib/flag-registry-worker-source.generated.js +1 -1
  64. package/dist/lib/lanes/accounts.js +3 -3
  65. package/dist/lib/lanes/admission-host.js +1 -1
  66. package/dist/lib/lanes/admission.js +4 -4
  67. package/dist/lib/lanes/autopilot.js +2 -2
  68. package/dist/lib/lanes/blocker-freshness.js +1 -1
  69. package/dist/lib/lanes/compaction.js +5 -5
  70. package/dist/lib/lanes/delivery.js +1 -1
  71. package/dist/lib/lanes/depth-cap.js +1 -1
  72. package/dist/lib/lanes/disk-guard.js +1 -1
  73. package/dist/lib/lanes/dropbox.js +1 -1
  74. package/dist/lib/lanes/hooks-install.js +1 -1
  75. package/dist/lib/lanes/imported-question.js +1 -1
  76. package/dist/lib/lanes/keep-alive.d.ts +2 -2
  77. package/dist/lib/lanes/keep-alive.js +3 -3
  78. package/dist/lib/lanes/kr-freshness.js +1 -1
  79. package/dist/lib/lanes/links.js +4 -4
  80. package/dist/lib/lanes/loop.js +2 -2
  81. package/dist/lib/lanes/machine-identity.js +3 -3
  82. package/dist/lib/lanes/models.js +6 -6
  83. package/dist/lib/lanes/quota.js +1 -1
  84. package/dist/lib/lanes/reconcile-install.js +3 -3
  85. package/dist/lib/lanes/reconcile.js +16 -16
  86. package/dist/lib/lanes/remote-control-lane.js +6 -6
  87. package/dist/lib/lanes/reviews.js +2 -2
  88. package/dist/lib/lanes/spawn.js +24 -24
  89. package/dist/lib/lanes/status-fields.js +4 -4
  90. package/dist/lib/lanes/wait.js +4 -4
  91. package/dist/lib/lanes/watch.js +2 -2
  92. package/dist/lib/lanes/watcher-main.js +1 -1
  93. package/dist/lib/lanes/watcher.js +38 -38
  94. package/dist/lib/lanes/worker-process.js +5 -5
  95. package/dist/lib/mesh/live/daemon/pid-lock.d.ts +2 -4
  96. package/dist/lib/mesh/live/daemon/pid-lock.js +38 -55
  97. package/dist/utils/cognito-session.d.ts +2 -56
  98. package/dist/utils/cognito-session.js +6 -164
  99. package/dist/utils/exclusive-lock.d.ts +60 -0
  100. package/dist/utils/exclusive-lock.js +65 -0
  101. package/package.json +9 -8
  102. package/dist/commands/staff/listings.d.ts +0 -41
  103. package/dist/commands/staff/listings.js +0 -160
  104. package/dist/commands/staff/reset-test-account.d.ts +0 -121
  105. package/dist/commands/staff/reset-test-account.js +0 -285
  106. package/dist/commands/staff/test-account.d.ts +0 -51
  107. package/dist/commands/staff/test-account.js +0 -196
@@ -1,41 +0,0 @@
1
- import { Command } from "commander";
2
- /**
3
- * `hq staff listings {queue|approve|reject}` — marketplace moderation from the
4
- * CLI. Thin wrappers over the vault-service moderation routes:
5
- *
6
- * GET /v1/moderation/queue (queue)
7
- * POST /v1/moderation/listings/{id} (approve | reject, body { action, note? })
8
- *
9
- * Every `hq publish` lands as `pending_review` and stays off the public
10
- * marketplace until a staff member decides it. Before this command the only
11
- * way to decide was the GTM admin web page. The server owns authorization
12
- * (`isStaffEmail` on the id_token's email claim) and the state machine
13
- * (pending_review -> approved | rejected, optimistic lock, superseding older
14
- * approved versions). The moderation gate reads the `email` claim, which only
15
- * the id_token carries, so this file uses `ensureCognitoIdToken`.
16
- */
17
- export interface QueueItem {
18
- listingId: string;
19
- type?: string;
20
- status?: string;
21
- creatorHandle?: string;
22
- name?: string;
23
- slug?: string;
24
- version?: string;
25
- summary?: string;
26
- createdAt?: string;
27
- injectionScan?: {
28
- flagged?: boolean;
29
- flags?: unknown[];
30
- };
31
- }
32
- export declare function renderQueue(items: QueueItem[]): string;
33
- export declare function runListingsQueue(): Promise<void>;
34
- export interface RunDecisionParams {
35
- listingId: string;
36
- note?: string;
37
- }
38
- export declare function runApproveListing(params: RunDecisionParams): Promise<void>;
39
- export declare function runRejectListing(params: RunDecisionParams): Promise<void>;
40
- export declare function registerListingsCommand(staff: Command): Command;
41
- //# sourceMappingURL=listings.d.ts.map
@@ -1,160 +0,0 @@
1
- import chalk from "chalk";
2
- import { ensureCognitoIdToken } from "../../utils/cognito-session.js";
3
- import { vaultApiFetch } from "../../utils/vault-api.js";
4
- import { callerEmailFromToken, isStaffEmail } from "./reset-test-account.js";
5
- // ── Rendering ───────────────────────────────────────────────────────────────
6
- function renderQueueLine(item) {
7
- const pack = `${item.slug ?? item.name ?? "?"}@${item.version ?? "?"}`;
8
- const creator = item.creatorHandle ? `@${item.creatorHandle}` : chalk.dim("(no handle)");
9
- const flag = item.injectionScan?.flagged
10
- ? chalk.yellow(` flagged (${item.injectionScan.flags?.length ?? 0})`)
11
- : "";
12
- const when = item.createdAt ? chalk.dim(` ${item.createdAt}`) : "";
13
- return ` ${item.listingId} ${pack.padEnd(28)} ${(item.type ?? "").padEnd(6)} ${creator}${when}${flag}`;
14
- }
15
- export function renderQueue(items) {
16
- if (items.length === 0) {
17
- return chalk.dim("\n(no listings waiting for review)");
18
- }
19
- const lines = [chalk.bold(`\nListings waiting for review (${items.length}, oldest first)`)];
20
- for (const item of items)
21
- lines.push(renderQueueLine(item));
22
- lines.push(chalk.dim("\nApprove with `hq staff listings approve <id>`, reject with `hq staff listings reject <id> --note <reason>`."));
23
- return lines.join("\n");
24
- }
25
- // ── Shared helpers ──────────────────────────────────────────────────────────
26
- async function readBody(res) {
27
- try {
28
- return (await res.json());
29
- }
30
- catch {
31
- return {};
32
- }
33
- }
34
- function renderApiError(status, body) {
35
- const code = typeof body.code === "string" ? body.code : undefined;
36
- const message = typeof body.error === "string" ? body.error : `request failed (${status})`;
37
- return code ? `${code}: ${message}` : message;
38
- }
39
- /**
40
- * Local staff preflight so a non-staff caller stops before the round trip.
41
- * The server remains the authorization boundary.
42
- */
43
- async function requireStaffIdToken() {
44
- const token = await ensureCognitoIdToken();
45
- const callerEmail = callerEmailFromToken(token);
46
- if (!callerEmail || !isStaffEmail(callerEmail)) {
47
- throw new Error("hq staff listings requires a staff HQ session (@getindigo.ai, @hqforwork.com or @vyg.ai). " +
48
- "Sign in with a staff account and retry.");
49
- }
50
- return token;
51
- }
52
- const LISTING_ID_RE = /^lst_[0-9A-Za-z]+$/;
53
- function requireListingId(listingId) {
54
- const id = listingId.trim();
55
- if (!LISTING_ID_RE.test(id)) {
56
- throw new Error(`"${listingId}" is not a listing id (expected lst_…). Run \`hq staff listings queue\` to see ids.`);
57
- }
58
- return id;
59
- }
60
- // ── Runners ─────────────────────────────────────────────────────────────────
61
- export async function runListingsQueue() {
62
- const token = await requireStaffIdToken();
63
- const res = await vaultApiFetch({ token, path: "/v1/moderation/queue", method: "GET" });
64
- const parsed = await readBody(res);
65
- if (!res.ok)
66
- throw new Error(renderApiError(res.status, parsed));
67
- const queue = parsed.queue;
68
- if (!Array.isArray(queue))
69
- throw new Error("server did not return a moderation queue");
70
- console.log(renderQueue(queue));
71
- }
72
- async function decide(action, params) {
73
- const id = requireListingId(params.listingId);
74
- const token = await requireStaffIdToken();
75
- const body = { action };
76
- if (params.note !== undefined && params.note.trim().length > 0)
77
- body.note = params.note.trim();
78
- const res = await vaultApiFetch({
79
- token,
80
- path: `/v1/moderation/listings/${encodeURIComponent(id)}`,
81
- method: "POST",
82
- body,
83
- });
84
- const parsed = await readBody(res);
85
- if (!res.ok) {
86
- const msg = renderApiError(res.status, parsed);
87
- if (res.status === 409) {
88
- throw new Error(`${msg} (the listing is no longer pending, or someone decided it at the same time)`);
89
- }
90
- throw new Error(msg);
91
- }
92
- return parsed;
93
- }
94
- function labelOf(listing, fallbackId) {
95
- if (!listing)
96
- return fallbackId;
97
- return `${listing.slug ?? listing.name ?? fallbackId}@${listing.version ?? "?"} (${listing.listingId ?? fallbackId})`;
98
- }
99
- export async function runApproveListing(params) {
100
- const result = await decide("approve", params);
101
- console.log(chalk.green(`\n✓ approved ${labelOf(result.listing, params.listingId)}`));
102
- const superseded = result.superseded ?? [];
103
- if (superseded.length > 0) {
104
- console.log(chalk.dim(` superseded older versions: ${superseded.join(", ")}`));
105
- }
106
- console.log(chalk.dim(" It is now live in the marketplace (the public pack page refreshes within ~10 minutes)."));
107
- }
108
- export async function runRejectListing(params) {
109
- const result = await decide("reject", params);
110
- console.log(chalk.yellow(`\n✗ rejected ${labelOf(result.listing, params.listingId)}`));
111
- }
112
- // ── Commander wiring ────────────────────────────────────────────────────────
113
- function fail(err) {
114
- console.error(chalk.red(err instanceof Error ? err.message : String(err)));
115
- process.exit(1);
116
- }
117
- export function registerListingsCommand(staff) {
118
- const group = staff
119
- .command("listings")
120
- .description("Review marketplace listings waiting for approval (staff only). Wraps /v1/moderation.");
121
- group
122
- .command("queue")
123
- .description("List published packs waiting for review, oldest first.")
124
- .action(async () => {
125
- try {
126
- await runListingsQueue();
127
- }
128
- catch (err) {
129
- fail(err);
130
- }
131
- });
132
- group
133
- .command("approve")
134
- .description("Approve a pending listing so it goes live (older approved versions are superseded).")
135
- .argument("<listingId>", "Listing id from `hq staff listings queue` (lst_…)")
136
- .option("--note <text>", "Reviewer note recorded on the listing")
137
- .action(async (listingId, opts) => {
138
- try {
139
- await runApproveListing({ listingId, note: opts.note });
140
- }
141
- catch (err) {
142
- fail(err);
143
- }
144
- });
145
- group
146
- .command("reject")
147
- .description("Reject a pending listing.")
148
- .argument("<listingId>", "Listing id from `hq staff listings queue` (lst_…)")
149
- .requiredOption("--note <reason>", "Why it was rejected (recorded on the listing)")
150
- .action(async (listingId, opts) => {
151
- try {
152
- await runRejectListing({ listingId, note: opts.note });
153
- }
154
- catch (err) {
155
- fail(err);
156
- }
157
- });
158
- return group;
159
- }
160
- //# sourceMappingURL=listings.js.map
@@ -1,121 +0,0 @@
1
- import { Command } from "commander";
2
- /**
3
- * `hq staff reset-test-account <email>` — onboarding-test-accounts US-007.
4
- *
5
- * Thin CLI wrapper over `POST /v1/admin/test-account/reset` (US-003 dry-run +
6
- * US-006 execute). Server owns every safety gate; this file owns two operator
7
- * ergonomics the wire cannot: (1) a LOCAL staff-email preflight so a non-staff
8
- * caller stops here instead of paying a round trip for the same 403, and (2)
9
- * the typed-email confirmation prompt for `--execute`, whose value is what the
10
- * server matches against `plan.target.normalizedEmail` via `confirmEmailMatches`.
11
- *
12
- * OQ-003 recommendation: this ships as a subcommand of the existing hq CLI
13
- * (`hq staff …`) rather than a separate `hq-staff` binary — reuses auth,
14
- * distribution, and telemetry with zero new plumbing.
15
- */
16
- interface PlanCognitoUser {
17
- username: string;
18
- sub: string;
19
- provider: string;
20
- email: string;
21
- }
22
- interface PlanCompany {
23
- uid: string;
24
- slug: string;
25
- memberCount: number;
26
- }
27
- interface PlanCompanyHandoff {
28
- companyUid: string;
29
- companySlug: string;
30
- toPersonUid: string;
31
- toEmail: string;
32
- }
33
- interface Plan {
34
- target: {
35
- input: string;
36
- normalizedEmail: string;
37
- };
38
- personUid: string | null;
39
- cognitoUsers: PlanCognitoUser[];
40
- ownedCompanies: PlanCompany[];
41
- /** Present only when the request opted in to the handoff. */
42
- sharedCompanyHandoffs?: PlanCompanyHandoff[];
43
- personalVault: {
44
- bucketName: string | null;
45
- kmsKeyAlias: string | null;
46
- };
47
- stripe: {
48
- customerIds: string[];
49
- subscriptionState: unknown | null;
50
- };
51
- welcomeSeries: {
52
- present: boolean;
53
- };
54
- workMesh: {
55
- eventCount: number | null;
56
- note?: string;
57
- };
58
- }
59
- interface StepOutcome {
60
- ok: boolean;
61
- skipped?: boolean;
62
- reason?: string;
63
- error?: string;
64
- }
65
- interface ExecuteResult {
66
- ok: boolean;
67
- steps: Record<string, StepOutcome & Record<string, unknown>>;
68
- counts: {
69
- stripeDeleted: number;
70
- welcomeDeleted: number;
71
- rawTelemetryDeleted: number | null;
72
- workMeshDeleted: number | null;
73
- membershipsDeleted: number;
74
- companiesPurged: number;
75
- entitiesPurged: number;
76
- cognitoDeleted: number;
77
- kms: string;
78
- invitesDeleted: number;
79
- };
80
- }
81
- /**
82
- * Same predicate the server's admin gate applies at the FIRST layer
83
- * (`isStaffEmail` in the vault-service admin handler). Duplicated here so a
84
- * non-staff caller stops before the round trip; the server remains the
85
- * authorization boundary (this file could not enforce it if it wanted to).
86
- *
87
- * The domain list matches the server's `SUPER_ADMIN_DOMAINS` (getindigo.ai,
88
- * hqforwork.com, vyg.ai). Exact domain match: `foo@getindigo.ai.evil.test`
89
- * and `bar@xgetindigo.ai` do not qualify.
90
- */
91
- export declare function isStaffEmail(candidate: unknown): boolean;
92
- /** Pull the caller email out of a locally cached id_token. */
93
- export declare function callerEmailFromToken(token: string): string | undefined;
94
- export type ConfirmFn = (question: string) => Promise<string>;
95
- export interface RunResetTestAccountParams {
96
- email: string;
97
- execute: boolean;
98
- /** Skip the typed-confirmation prompt on --execute (for scripts). */
99
- yes?: boolean;
100
- /** Keep a company with real members and hand it to one, instead of refusing. */
101
- handoffSharedCompanies?: boolean;
102
- }
103
- export interface RunResetTestAccountDeps {
104
- prompt?: ConfirmFn;
105
- /** Whether to treat this session as an interactive TTY. Defaults to `process.stdin.isTTY`. */
106
- isTty?: boolean;
107
- }
108
- /**
109
- * Print a compact dry-run plan. Kept flat so the operator can eyeball what the
110
- * executor would touch without a JSON pretty-printer in the loop.
111
- */
112
- export declare function renderPlan(plan: Plan): string;
113
- /**
114
- * One-line-per-step summary of the executor's result. AC calls for "per-step
115
- * counts, ok/failed".
116
- */
117
- export declare function renderExecuteSummary(result: ExecuteResult): string;
118
- export declare function runResetTestAccount(params: RunResetTestAccountParams, deps?: RunResetTestAccountDeps): Promise<void>;
119
- export declare function registerResetTestAccountCommand(staff: Command, deps?: RunResetTestAccountDeps): Command;
120
- export {};
121
- //# sourceMappingURL=reset-test-account.d.ts.map
@@ -1,285 +0,0 @@
1
- import chalk from "chalk";
2
- import * as readline from "node:readline";
3
- import { ensureCognitoToken } from "../../utils/cognito-session.js";
4
- import { peekIdToken } from "../../utils/id-token.js";
5
- import { vaultApiFetch } from "../../utils/vault-api.js";
6
- // ── Local staff-email preflight ─────────────────────────────────────────────
7
- /**
8
- * Same predicate the server's admin gate applies at the FIRST layer
9
- * (`isStaffEmail` in the vault-service admin handler). Duplicated here so a
10
- * non-staff caller stops before the round trip; the server remains the
11
- * authorization boundary (this file could not enforce it if it wanted to).
12
- *
13
- * The domain list matches the server's `SUPER_ADMIN_DOMAINS` (getindigo.ai,
14
- * hqforwork.com, vyg.ai). Exact domain match: `foo@getindigo.ai.evil.test`
15
- * and `bar@xgetindigo.ai` do not qualify.
16
- */
17
- export function isStaffEmail(candidate) {
18
- if (typeof candidate !== "string")
19
- return false;
20
- const parts = candidate.trim().toLowerCase().split("@");
21
- if (parts.length !== 2 || parts[0].length === 0)
22
- return false;
23
- const domain = parts[1];
24
- return domain === "getindigo.ai" || domain === "hqforwork.com" || domain === "vyg.ai";
25
- }
26
- /** Pull the caller email out of a locally cached id_token. */
27
- export function callerEmailFromToken(token) {
28
- const claims = peekIdToken(token);
29
- const email = claims.email;
30
- return typeof email === "string" && email.trim().length > 0
31
- ? email.trim()
32
- : undefined;
33
- }
34
- /** Real readline prompt, used when stdin is a TTY. */
35
- function realPrompt(question) {
36
- const rl = readline.createInterface({
37
- input: process.stdin,
38
- output: process.stdout,
39
- });
40
- return new Promise((resolve) => {
41
- rl.question(question, (line) => {
42
- rl.close();
43
- resolve(line);
44
- });
45
- });
46
- }
47
- /**
48
- * Print a compact dry-run plan. Kept flat so the operator can eyeball what the
49
- * executor would touch without a JSON pretty-printer in the loop.
50
- */
51
- export function renderPlan(plan) {
52
- const lines = [];
53
- lines.push(chalk.bold(`\nReset plan for ${plan.target.normalizedEmail}`));
54
- if (plan.target.input !== plan.target.normalizedEmail) {
55
- lines.push(chalk.dim(` raw input: ${plan.target.input}`));
56
- }
57
- lines.push(` person uid: ${plan.personUid ?? chalk.dim("(none)")}`);
58
- lines.push("");
59
- lines.push(chalk.bold(" Cognito users"));
60
- if (plan.cognitoUsers.length === 0) {
61
- lines.push(chalk.dim(" (none)"));
62
- }
63
- else {
64
- for (const u of plan.cognitoUsers) {
65
- lines.push(` - ${u.username} [${u.provider}] ${u.email}`);
66
- }
67
- }
68
- lines.push("");
69
- lines.push(chalk.bold(" Owned companies"));
70
- if (plan.ownedCompanies.length === 0) {
71
- lines.push(chalk.dim(" (none)"));
72
- }
73
- else {
74
- for (const c of plan.ownedCompanies) {
75
- lines.push(` - ${c.slug} (${c.uid}) members: ${c.memberCount}`);
76
- }
77
- }
78
- lines.push("");
79
- if (plan.sharedCompanyHandoffs && plan.sharedCompanyHandoffs.length > 0) {
80
- lines.push(chalk.bold(" Companies kept and handed over"));
81
- for (const h of plan.sharedCompanyHandoffs) {
82
- lines.push(` handoff: ${h.companySlug} to ${h.toEmail}`);
83
- }
84
- lines.push("");
85
- }
86
- lines.push(chalk.bold(" Personal vault"));
87
- lines.push(` bucket: ${plan.personalVault.bucketName ?? chalk.dim("(none)")}`);
88
- lines.push(` kms alias: ${plan.personalVault.kmsKeyAlias ?? chalk.dim("(none)")}`);
89
- lines.push("");
90
- lines.push(chalk.bold(" Stripe"));
91
- if (plan.stripe.customerIds.length === 0) {
92
- lines.push(chalk.dim(" (no customer)"));
93
- }
94
- else {
95
- for (const id of plan.stripe.customerIds) {
96
- lines.push(` - ${id}`);
97
- }
98
- }
99
- if (plan.stripe.subscriptionState !== null && plan.stripe.subscriptionState !== undefined) {
100
- lines.push(` subscription: ${JSON.stringify(plan.stripe.subscriptionState)}`);
101
- }
102
- lines.push("");
103
- lines.push(chalk.bold(" Other"));
104
- lines.push(` welcome-series row: ${plan.welcomeSeries.present ? "yes" : "no"}`);
105
- const wm = plan.workMesh.eventCount === null
106
- ? plan.workMesh.note
107
- ? `not enumerated (${plan.workMesh.note})`
108
- : "not enumerated"
109
- : String(plan.workMesh.eventCount);
110
- lines.push(` work-mesh events: ${wm}`);
111
- return lines.join("\n");
112
- }
113
- /**
114
- * One-line-per-step summary of the executor's result. AC calls for "per-step
115
- * counts, ok/failed".
116
- */
117
- export function renderExecuteSummary(result) {
118
- const c = result.counts;
119
- const s = result.steps;
120
- const line = (label, step, count) => {
121
- const flag = step.skipped
122
- ? chalk.dim("skipped")
123
- : step.ok
124
- ? chalk.green("ok")
125
- : chalk.red("failed");
126
- const note = step.error ? ` ${chalk.red(step.error)}` : "";
127
- return ` ${label.padEnd(20)} ${flag.padEnd(10)} ${String(count)}${note}`;
128
- };
129
- const overall = result.ok ? chalk.green("ok") : chalk.yellow("partial");
130
- const rawTelemetry = c.rawTelemetryDeleted ?? "n/a";
131
- const workMesh = c.workMeshDeleted ?? "n/a";
132
- return [
133
- "",
134
- chalk.bold(`Reset result: ${overall}`),
135
- line("stripe", s.stripe ?? { ok: true }, c.stripeDeleted),
136
- line("welcome-series", s.welcomeSeries ?? { ok: true }, c.welcomeDeleted),
137
- line("raw-telemetry", s.rawTelemetry ?? { ok: true }, rawTelemetry),
138
- line("work-mesh", s.workMesh ?? { ok: true }, workMesh),
139
- line("memberships", s.memberships ?? { ok: true }, c.membershipsDeleted),
140
- line("companies", s.companies ?? { ok: true }, c.companiesPurged),
141
- line("entities", s.entity ?? { ok: true }, c.entitiesPurged),
142
- line("cognito", s.cognito ?? { ok: true }, c.cognitoDeleted),
143
- line("kms (personal)", s.kms ?? { ok: true }, c.kms),
144
- line("invites", s.invites ?? { ok: true }, c.invitesDeleted),
145
- ].join("\n");
146
- }
147
- /** Read a JSON body, tolerant of an empty body (returns `{}`). */
148
- async function readBody(res) {
149
- try {
150
- return (await res.json());
151
- }
152
- catch {
153
- return {};
154
- }
155
- }
156
- function renderApiError(status, body) {
157
- const code = typeof body.code === "string" ? body.code : undefined;
158
- const message = typeof body.error === "string" ? body.error : `reset failed (${status})`;
159
- const detail = body.details ? ` ${JSON.stringify(body.details)}` : "";
160
- return code ? `${code}: ${message}${detail}` : `${message}${detail}`;
161
- }
162
- export async function runResetTestAccount(params, deps = {}) {
163
- const email = params.email.trim();
164
- if (email.length === 0) {
165
- throw new Error("email argument is required");
166
- }
167
- const token = await ensureCognitoToken();
168
- // LOCAL preflight — a non-staff caller's Cognito token cannot pass the
169
- // server's admin gate anyway, so we surface the refusal immediately and
170
- // avoid a round trip.
171
- const callerEmail = callerEmailFromToken(token);
172
- if (!callerEmail || !isStaffEmail(callerEmail)) {
173
- throw new Error("reset-test-account requires a super-admin (staff) HQ session. " +
174
- "Sign in with an @getindigo.ai account and retry.");
175
- }
176
- // Absent unless asked for, so the server's refusal stays the default.
177
- const handoff = params.handoffSharedCompanies === true
178
- ? { handoffSharedCompanies: true }
179
- : {};
180
- // Dry-run first. The AC calls out "Without --execute, runs dry-run and
181
- // prints the plan" — so a bare invocation always ends here.
182
- const dryRunRes = await vaultApiFetch({
183
- token,
184
- path: "/v1/admin/test-account/reset",
185
- method: "POST",
186
- body: { email, dryRun: true, ...handoff },
187
- });
188
- const dryRunBody = await readBody(dryRunRes);
189
- if (!dryRunRes.ok) {
190
- throw new Error(renderApiError(dryRunRes.status, dryRunBody));
191
- }
192
- const plan = dryRunBody.plan;
193
- if (!plan) {
194
- throw new Error("server did not return a plan for the dry-run request");
195
- }
196
- console.log(renderPlan(plan));
197
- if (!params.execute) {
198
- console.log(chalk.dim("\n(dry-run — no writes occurred. Pass --execute after reviewing.)"));
199
- return;
200
- }
201
- // Execute path — require the operator to type the email back.
202
- console.log(chalk.yellow(`\nThis will DELETE every artifact above for ${plan.target.normalizedEmail}.`));
203
- let confirmEmail;
204
- if (params.yes === true) {
205
- // `--yes` is an explicit operator act. The server still requires a
206
- // matching `confirmEmail`, so we supply the normalized target on the
207
- // operator's behalf; the guard on the wire is unchanged.
208
- confirmEmail = plan.target.normalizedEmail;
209
- console.log(chalk.dim(` (--yes: sending confirmEmail=${confirmEmail})`));
210
- }
211
- else {
212
- const prompt = deps.prompt ?? realPrompt;
213
- const isTty = deps.isTty ?? Boolean(process.stdin.isTTY);
214
- if (!isTty && !params.yes) {
215
- throw new Error("--execute needs an interactive terminal for the typed-email " +
216
- "confirmation. Re-run in a TTY, or pass --yes to skip the prompt.");
217
- }
218
- const answer = await prompt(`Type the target email to confirm (${plan.target.normalizedEmail}): `);
219
- confirmEmail = (answer ?? "").trim();
220
- if (confirmEmail.length === 0) {
221
- throw new Error("Aborted — no confirmation entered.");
222
- }
223
- // Local pre-check so the operator gets the friendlier message than the
224
- // server's CONFIRM_EMAIL_MISMATCH. Server still enforces via
225
- // confirmEmailMatches, so a stale local check cannot bypass the wire gate.
226
- if (confirmEmail.toLowerCase() !== plan.target.normalizedEmail.toLowerCase()) {
227
- throw new Error(`Aborted — the typed email (${confirmEmail}) does not match the ` +
228
- `target (${plan.target.normalizedEmail}).`);
229
- }
230
- }
231
- const executeRes = await vaultApiFetch({
232
- token,
233
- path: "/v1/admin/test-account/reset",
234
- method: "POST",
235
- body: { email, dryRun: false, confirmEmail, ...handoff },
236
- });
237
- const executeBody = await readBody(executeRes);
238
- // The handler answers 200 (all-ok) and 207 (best-effort partial). Anything
239
- // else is a refusal from a safety gate and should surface as an error.
240
- if (executeRes.status !== 200 && executeRes.status !== 207) {
241
- throw new Error(renderApiError(executeRes.status, executeBody));
242
- }
243
- const result = executeBody.result;
244
- if (!result) {
245
- throw new Error("server did not return an execute result");
246
- }
247
- console.log(renderExecuteSummary(result));
248
- for (const h of plan.sharedCompanyHandoffs ?? []) {
249
- console.log(` handoff: ${h.companySlug} to ${h.toEmail}`);
250
- }
251
- if (!result.ok) {
252
- // Non-zero exit so a scripted caller can react. The summary line above
253
- // already shows which step failed.
254
- process.exitCode = 1;
255
- }
256
- }
257
- // ── Commander wiring ────────────────────────────────────────────────────────
258
- function fail(err) {
259
- console.error(chalk.red(err instanceof Error ? err.message : String(err)));
260
- process.exit(1);
261
- }
262
- export function registerResetTestAccountCommand(staff, deps = {}) {
263
- return staff
264
- .command("reset-test-account")
265
- .description("Reset a designated real-email test account (dry-run by default). " +
266
- "Wraps POST /v1/admin/test-account/reset — super-admin only.")
267
- .argument("<email>", "Designated test-account email (must be in the registry)")
268
- .option("--execute", "Actually delete artifacts. Prompts for a typed-email confirmation.")
269
- .option("-y, --yes", "Skip the typed-email confirmation prompt (still sends confirmEmail).")
270
- .option("--handoff-shared-companies", "Keep a company with real members and hand it to one, instead of refusing the reset.")
271
- .action(async (email, opts) => {
272
- try {
273
- await runResetTestAccount({
274
- email,
275
- execute: opts.execute === true,
276
- yes: opts.yes === true,
277
- handoffSharedCompanies: opts.handoffSharedCompanies === true,
278
- }, deps);
279
- }
280
- catch (err) {
281
- fail(err);
282
- }
283
- });
284
- }
285
- //# sourceMappingURL=reset-test-account.js.map
@@ -1,51 +0,0 @@
1
- import { Command } from "commander";
2
- /**
3
- * `hq staff test-account {add|remove|list}` — onboarding-test-accounts US-007
4
- * follow-up. Thin CLI wrappers over the vault-service registry routes:
5
- *
6
- * POST /v1/admin/test-account-registry (add)
7
- * DELETE /v1/admin/test-account-registry/{emailB64} (remove)
8
- * GET /v1/admin/test-account-registry (list)
9
- *
10
- * The runbook now points staff at these commands instead of the previous
11
- * hand-rolled `curl` + `~/.hq/cognito-tokens.json` pattern. Reusing
12
- * `ensureCognitoToken` + `vaultApiFetch` means the id_token is never printed,
13
- * never handed to the operator, and never lifted out of the CLI's secure state
14
- * directory. The server owns every write; this file's local staff-email
15
- * preflight only saves an already-refused round trip.
16
- */
17
- interface RegistryEntry {
18
- email: string;
19
- addedBy: string;
20
- addedAt: string;
21
- note: string | null;
22
- active: boolean;
23
- removedBy?: string;
24
- removedAt?: string;
25
- }
26
- /**
27
- * Encode an email as the base64url path segment the DELETE route expects. The
28
- * server decodes and normalizes (`decodeRegistryEmailKey` → `normalizeRegistryEmail`),
29
- * so the operator can type `Bohemian.HW@gmail.com` and hit the same row as
30
- * `bohemianhw@gmail.com`. Local encoding is a pure transform on the raw input;
31
- * we never persist or print a locally normalized value.
32
- */
33
- export declare function encodeEmailForPath(email: string): string;
34
- export declare function renderEntry(entry: RegistryEntry): string;
35
- export declare function renderList(entries: RegistryEntry[]): string;
36
- export interface RunAddParams {
37
- email: string;
38
- note?: string;
39
- }
40
- export declare function runAddTestAccount(params: RunAddParams): Promise<void>;
41
- export interface RunRemoveParams {
42
- email: string;
43
- }
44
- export declare function runRemoveTestAccount(params: RunRemoveParams): Promise<void>;
45
- export interface RunListParams {
46
- includeInactive?: boolean;
47
- }
48
- export declare function runListTestAccounts(params?: RunListParams): Promise<void>;
49
- export declare function registerTestAccountCommand(staff: Command): Command;
50
- export {};
51
- //# sourceMappingURL=test-account.d.ts.map