@indigoai-us/hq-cli 5.16.0 → 5.17.0-sources-rc.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/.github/workflows/ci.yml +8 -4
  2. package/.github/workflows/publish.yml +8 -3
  3. package/dist/cli-version.d.ts +1 -0
  4. package/dist/cli-version.js +3 -2
  5. package/dist/commands/groups.js +6 -6
  6. package/dist/commands/meetings.js +8 -8
  7. package/dist/commands/members.d.ts +4 -2
  8. package/dist/commands/members.js +30 -14
  9. package/dist/commands/signals.d.ts +24 -0
  10. package/dist/commands/signals.js +240 -0
  11. package/dist/commands/sources.d.ts +22 -0
  12. package/dist/commands/sources.js +250 -0
  13. package/dist/index.js +8 -2
  14. package/dist/utils/cognito-session.d.ts +10 -1
  15. package/dist/utils/cognito-session.js +18 -3
  16. package/package.json +5 -4
  17. package/scripts/smoke-sources-signals.sh +103 -0
  18. package/src/cli-version.ts +5 -1
  19. package/src/commands/groups.ts +4 -4
  20. package/src/commands/meetings.ts +6 -6
  21. package/src/commands/members.test.ts +56 -0
  22. package/src/commands/members.ts +44 -13
  23. package/src/commands/signals.ts +345 -0
  24. package/src/commands/sources.ts +356 -0
  25. package/src/index.ts +8 -0
  26. package/src/utils/cognito-session.test.ts +24 -1
  27. package/src/utils/cognito-session.ts +18 -0
  28. package/test/commands/signals.test.ts +200 -0
  29. package/test/commands/sources.test.ts +225 -0
  30. package/test/fixtures/signals/action_item/sample.md +16 -0
  31. package/test/fixtures/signals/summary/sample.md +12 -0
  32. package/test/fixtures/sources/meetings/sample.md +25 -0
  33. package/test/helpers/cli-runner.ts +150 -0
  34. package/test/helpers/s3-list-mock.ts +79 -0
  35. package/test/helpers/vault-service-mock.ts +160 -0
  36. package/test/sources-signals/smoke.test.ts +226 -0
  37. package/vitest.config.ts +11 -0
@@ -0,0 +1,225 @@
1
+ /**
2
+ * sources.test.ts — E2E tests for `hq sources` (US-006).
3
+ *
4
+ * Drives the full CLI through `runCli` with `globalThis.fetch` stubbed
5
+ * (vault-service) and the hq-cloud sources S3 factory swapped to an
6
+ * in-memory stub. Tests the four e2e cases defined in the PRD:
7
+ *
8
+ * 1. `hq sources list --entity indigo --type meeting --format json`
9
+ * → exit 0, JSON entry with sourceId='abc'.
10
+ * 2. `hq sources get --entity indigo --type meeting --id abc`
11
+ * → exit 0, body text present in stdout.
12
+ * 3. `hq sources list --type meeting` (no --entity, no config)
13
+ * → exit 1, stderr mentions --entity.
14
+ * 4. `hq sources list --entity indigo --type pigeon`
15
+ * → exit 1, stderr lists valid channels.
16
+ *
17
+ * HQ_ACCESS_TOKEN is set per-test so resolveAccessToken() short-circuits
18
+ * away from the interactive Cognito flow.
19
+ */
20
+
21
+ import { mkdtempSync, rmSync } from "node:fs";
22
+ import { tmpdir } from "node:os";
23
+ import { join } from "node:path";
24
+ import { afterEach, beforeEach, describe, expect, it } from "vitest";
25
+ import {
26
+ _setSourcesS3Factory,
27
+ _resetSourcesS3Factory,
28
+ } from "@indigoai-us/hq-cloud";
29
+ import { mockS3WithEntries } from "../helpers/s3-list-mock.js";
30
+ import { mockVaultService } from "../helpers/vault-service-mock.js";
31
+ import { runCli } from "../helpers/cli-runner.js";
32
+
33
+ // ---------------------------------------------------------------------------
34
+ // Fixtures
35
+ // ---------------------------------------------------------------------------
36
+
37
+ /**
38
+ * Markdown source matching sources-pipeline output shape.
39
+ * NOTE: stored at `sources/meeting/abc.md` (singular `meeting/`) because
40
+ * listSources prefixes with `sources/${channel}/` and channel is the
41
+ * singular SOURCE_CHANNELS member.
42
+ */
43
+ const MEETING_MD = `---
44
+ source_id: abc
45
+ source_type: meeting
46
+ channel: meeting
47
+ title: Q1 Planning Meeting
48
+ ---
49
+
50
+ [Stefan 00:00:05]: Body text goes here for the e2e test.
51
+ [Corey 00:00:12]: Acknowledged.
52
+ `;
53
+
54
+ // Sentinel string used to assert body presence in `hq sources get` output.
55
+ const BODY_SENTINEL = "Body text goes here for the e2e test.";
56
+
57
+ // ---------------------------------------------------------------------------
58
+ // Per-test setup — vault + S3 mocks + isolated --hq-root
59
+ // ---------------------------------------------------------------------------
60
+
61
+ let restoreFetch: (() => void) | undefined;
62
+ let tmpHqRoot: string;
63
+ let savedEnv: { HQ_ACCESS_TOKEN: string | undefined };
64
+
65
+ beforeEach(() => {
66
+ // Sidestep Cognito interactive flow.
67
+ savedEnv = { HQ_ACCESS_TOKEN: process.env.HQ_ACCESS_TOKEN };
68
+ process.env.HQ_ACCESS_TOKEN = "test-access-token";
69
+
70
+ // Empty .hq tree so `readActiveCompanySlug` returns undefined unless a
71
+ // test writes config.json into it.
72
+ tmpHqRoot = mkdtempSync(join(tmpdir(), "hq-sources-test-"));
73
+
74
+ // Default S3 stub returns the one meeting source.
75
+ const s3 = mockS3WithEntries({
76
+ entries: [
77
+ {
78
+ key: "sources/meeting/abc.md",
79
+ content: MEETING_MD,
80
+ lastModified: new Date("2026-03-15T14:00:00Z"),
81
+ },
82
+ ],
83
+ });
84
+ _setSourcesS3Factory(() => s3);
85
+
86
+ // Default vault-service mock with one entity 'indigo'.
87
+ restoreFetch = mockVaultService({
88
+ entities: [{ uid: "cmp_indigo_001", slug: "indigo", bucketName: "hq-indigo-bucket" }],
89
+ });
90
+ });
91
+
92
+ afterEach(() => {
93
+ _resetSourcesS3Factory();
94
+ restoreFetch?.();
95
+ restoreFetch = undefined;
96
+ rmSync(tmpHqRoot, { recursive: true, force: true });
97
+
98
+ if (savedEnv.HQ_ACCESS_TOKEN === undefined) {
99
+ delete process.env.HQ_ACCESS_TOKEN;
100
+ } else {
101
+ process.env.HQ_ACCESS_TOKEN = savedEnv.HQ_ACCESS_TOKEN;
102
+ }
103
+ });
104
+
105
+ // ---------------------------------------------------------------------------
106
+ // Tests — PRD e2e cases
107
+ // ---------------------------------------------------------------------------
108
+
109
+ describe("hq sources (e2e)", () => {
110
+ it("list --entity indigo --type meeting --format json — exit 0 + JSON with sourceId='abc'", async () => {
111
+ const result = await runCli([
112
+ "hq",
113
+ "sources",
114
+ "list",
115
+ "--entity",
116
+ "indigo",
117
+ "--type",
118
+ "meeting",
119
+ "--format",
120
+ "json",
121
+ "--hq-root",
122
+ tmpHqRoot,
123
+ ]);
124
+
125
+ expect(result.exitCode, `stderr=${result.stderr}`).toBe(0);
126
+ expect(result.stderr).toBe("");
127
+
128
+ const parsed = JSON.parse(result.stdout) as {
129
+ entries: Array<{ sourceId: string; channel: string; key: string }>;
130
+ nextToken?: string;
131
+ };
132
+ expect(parsed.entries).toHaveLength(1);
133
+ expect(parsed.entries[0].sourceId).toBe("abc");
134
+ expect(parsed.entries[0].channel).toBe("meeting");
135
+ expect(parsed.entries[0].key).toBe("sources/meeting/abc.md");
136
+ });
137
+
138
+ it("get --entity indigo --type meeting --id abc — exit 0 + stdout contains body text", async () => {
139
+ const result = await runCli([
140
+ "hq",
141
+ "sources",
142
+ "get",
143
+ "--entity",
144
+ "indigo",
145
+ "--type",
146
+ "meeting",
147
+ "--id",
148
+ "abc",
149
+ "--format",
150
+ "markdown",
151
+ "--hq-root",
152
+ tmpHqRoot,
153
+ ]);
154
+
155
+ expect(result.exitCode).toBe(0);
156
+ expect(result.stderr).toBe("");
157
+ expect(result.stdout).toContain(BODY_SENTINEL);
158
+ });
159
+
160
+ it("list --type meeting (no --entity, no config) — exit 1 + stderr mentions --entity", async () => {
161
+ // tmpHqRoot has no .hq/config.json, so readActiveCompanySlug returns undefined.
162
+ const result = await runCli([
163
+ "hq",
164
+ "sources",
165
+ "list",
166
+ "--type",
167
+ "meeting",
168
+ "--format",
169
+ "json",
170
+ "--hq-root",
171
+ tmpHqRoot,
172
+ ]);
173
+
174
+ expect(result.exitCode).toBe(1);
175
+ expect(result.stderr).toMatch(/--entity/);
176
+ // Also surfaces the discovery affordance.
177
+ expect(result.stderr).toMatch(/hq sources entities/);
178
+ });
179
+
180
+ it("list --entity indigo --type pigeon — exit 1 + stderr lists valid channels", async () => {
181
+ const result = await runCli([
182
+ "hq",
183
+ "sources",
184
+ "list",
185
+ "--entity",
186
+ "indigo",
187
+ "--type",
188
+ "pigeon",
189
+ "--format",
190
+ "json",
191
+ "--hq-root",
192
+ tmpHqRoot,
193
+ ]);
194
+
195
+ expect(result.exitCode).toBe(1);
196
+ // Every canonical channel must appear in the error message.
197
+ expect(result.stderr).toContain("meeting");
198
+ expect(result.stderr).toContain("email");
199
+ expect(result.stderr).toContain("slack");
200
+ expect(result.stderr).toContain("linear");
201
+ expect(result.stderr).toContain("notion");
202
+ });
203
+ });
204
+
205
+ // ---------------------------------------------------------------------------
206
+ // Bonus coverage — channels + wiring
207
+ // ---------------------------------------------------------------------------
208
+
209
+ describe("hq sources channels", () => {
210
+ it("prints SOURCE_CHANNELS sorted, one per line, exit 0", async () => {
211
+ const result = await runCli(["hq", "sources", "channels"]);
212
+ expect(result.exitCode).toBe(0);
213
+ const lines = result.stdout.trim().split("\n");
214
+ // Sorted alphabetically: email, linear, meeting, notion, slack
215
+ expect(lines).toEqual(["email", "linear", "meeting", "notion", "slack"]);
216
+ });
217
+ });
218
+
219
+ describe("hq --help wiring", () => {
220
+ it("mentions the sources subcommand", async () => {
221
+ const result = await runCli(["hq", "--help"]);
222
+ expect(result.exitCode).toBe(0);
223
+ expect(result.stdout).toContain("sources");
224
+ });
225
+ });
@@ -0,0 +1,16 @@
1
+ ---
2
+ signal_id: sig_action_001
3
+ signal_type: action_item
4
+ source_ref: abc-meeting-001
5
+ citations:
6
+ - "Stefan to review the sources pipeline implementation by end of week"
7
+ - "Corey to prepare roadmap slides for the next planning session"
8
+ entity_refs:
9
+ - stefan@indigoai.us
10
+ - corey@indigoai.us
11
+ created_at: "2026-03-15T15:00:00Z"
12
+ ---
13
+
14
+ Stefan will review the sources pipeline implementation and provide feedback by Friday 2026-03-20.
15
+
16
+ Corey will prepare updated roadmap slides covering the CLI read surface and signal type validation for the follow-up planning session.
@@ -0,0 +1,12 @@
1
+ ---
2
+ signal_id: sig_summary_001
3
+ signal_type: summary
4
+ source_ref: abc-meeting-001
5
+ citations: []
6
+ entity_refs:
7
+ - stefan@indigoai.us
8
+ - corey@indigoai.us
9
+ created_at: "2026-03-15T15:00:00Z"
10
+ ---
11
+
12
+ The Q1 planning meeting covered roadmap priorities for the sources pipeline and CLI tooling. Key decisions included implementing the `hq sources` and `hq signals` commands in hq-cli, enforcing a closed signal-type enum to prevent agents from inventing new types, and using STS-scoped credentials via vault-service for tenant isolation. The team agreed to ship a read-only CLI surface first before tackling S3 Vectors search in Phase 2.
@@ -0,0 +1,25 @@
1
+ ---
2
+ source_id: abc-meeting-001
3
+ source_type: meeting
4
+ channel: meeting
5
+ title: Q1 Planning Meeting
6
+ date: "2026-03-15"
7
+ participants:
8
+ - name: Stefan Johnson
9
+ email: stefan@indigoai.us
10
+ - name: Corey Smith
11
+ email: corey@indigoai.us
12
+ duration_seconds: 3600
13
+ entity_ref: cmp_indigo_001
14
+ created_at: "2026-03-15T14:00:00Z"
15
+ ---
16
+
17
+ [Stefan Johnson 00:00:05]: Good morning everyone. Let's get started with the Q1 planning session.
18
+
19
+ [Corey Smith 00:00:12]: Morning! I have the roadmap slides ready to share.
20
+
21
+ [Stefan Johnson 00:00:18]: Perfect. First item on the agenda is the sources pipeline work. We need to add a read surface to the CLI so agents and users can browse sources and signals without writing AWS code.
22
+
23
+ [Corey Smith 00:00:35]: Makes sense. The S3 layout is already defined by the pipeline — sources/{channel}/{sourceId}.md. We just need the listing and fetch commands.
24
+
25
+ [Stefan Johnson 00:00:48]: Exactly. And we should enforce signal type validation at the CLI layer too. No invented signal types from agents.
@@ -0,0 +1,150 @@
1
+ /**
2
+ * cli-runner.ts — in-process Commander test harness.
3
+ *
4
+ * Builds a minimal Commander program and runs it with the given argv,
5
+ * capturing stdout/stderr without forking a child process.
6
+ *
7
+ * The program starts with only the core hq metadata (name, description,
8
+ * version). As new top-level command registrars are added to the CLI
9
+ * (US-006: sources, US-007: signals, etc.), import and register them here
10
+ * so tests that need the full command tree can use the same runner.
11
+ *
12
+ * NOTE: Some existing commands (pkg-install, pack-install) use semver deep
13
+ * subpath imports (semver/functions/satisfies.js) that are not resolvable in
14
+ * the pnpm test context. Those commands are excluded from the test program;
15
+ * add them here only if/when the semver resolution is fixed in devDeps.
16
+ *
17
+ * Usage:
18
+ * const { exitCode, stdout, stderr } = await runCli(['hq', '--help']);
19
+ */
20
+
21
+ import { Command } from "commander";
22
+ import { registerLoginCommand } from "../../src/commands/login.js";
23
+ import { registerLogoutCommand } from "../../src/commands/logout.js";
24
+ import { registerWhoamiCommand } from "../../src/commands/whoami.js";
25
+ import { registerSecretsCommand } from "../../src/commands/secrets.js";
26
+ import { registerGroupsCommand } from "../../src/commands/groups.js";
27
+ import { registerSourcesCommand } from "../../src/commands/sources.js";
28
+ import { registerSignalsCommand } from "../../src/commands/signals.js";
29
+
30
+ export interface CliRunResult {
31
+ exitCode: number;
32
+ stdout: string;
33
+ stderr: string;
34
+ }
35
+
36
+ /**
37
+ * Builds a test-only Commander program using exitOverride() so Commander
38
+ * throws CommanderError instead of calling process.exit().
39
+ */
40
+ function buildProgram(): Command {
41
+ const program = new Command();
42
+
43
+ program
44
+ .name("hq")
45
+ .description("HQ management CLI — modules, packages, and cloud sync")
46
+ .version("0.0.0-test")
47
+ .exitOverride();
48
+
49
+ // Auth commands (no semver deep imports)
50
+ registerLoginCommand(program);
51
+ registerLogoutCommand(program);
52
+ registerWhoamiCommand(program);
53
+
54
+ // Secrets / groups (no semver deep imports)
55
+ registerSecretsCommand(program);
56
+ registerGroupsCommand(program);
57
+
58
+ // Sources read surface (US-006)
59
+ registerSourcesCommand(program);
60
+
61
+ // Signals read surface (US-007)
62
+ registerSignalsCommand(program);
63
+
64
+ return program;
65
+ }
66
+
67
+ /**
68
+ * Runs the hq CLI in-process with the given argv.
69
+ *
70
+ * stdout/stderr are intercepted for the duration of the call and restored
71
+ * afterward. Not safe to call concurrently (share process streams).
72
+ */
73
+ export async function runCli(argv: string[]): Promise<CliRunResult> {
74
+ const stdoutChunks: string[] = [];
75
+ const stderrChunks: string[] = [];
76
+ let exitCode = 0;
77
+
78
+ const origStdoutWrite = process.stdout.write.bind(process.stdout);
79
+ const origStderrWrite = process.stderr.write.bind(process.stderr);
80
+ const origExit = process.exit.bind(process);
81
+
82
+ const captureWrite =
83
+ (chunks: string[]) =>
84
+ (
85
+ chunk: string | Uint8Array,
86
+ encodingOrCb?: unknown,
87
+ cb?: unknown,
88
+ ): boolean => {
89
+ chunks.push(typeof chunk === "string" ? chunk : Buffer.from(chunk).toString("utf-8"));
90
+ if (typeof encodingOrCb === "function") (encodingOrCb as () => void)();
91
+ else if (typeof cb === "function") (cb as () => void)();
92
+ return true;
93
+ };
94
+
95
+ (process.stdout as { write: unknown }).write = captureWrite(stdoutChunks);
96
+ (process.stderr as { write: unknown }).write = captureWrite(stderrChunks);
97
+
98
+ // Stub process.exit so action-handler exit(code) becomes a thrown error
99
+ // caught by parseAsync(). Otherwise it would tear down the vitest worker.
100
+ class ProcessExitError extends Error {
101
+ code: number;
102
+ constructor(code: number) {
103
+ super(`process.exit(${code})`);
104
+ this.name = "ProcessExitError";
105
+ this.code = code;
106
+ }
107
+ }
108
+ (process as { exit: unknown }).exit = ((code?: number) => {
109
+ throw new ProcessExitError(code ?? 0);
110
+ }) as typeof process.exit;
111
+
112
+ try {
113
+ const program = buildProgram();
114
+ // Commander's default strips 2 elements (node + script).
115
+ // Our argv convention is ['hq', ...userArgs], so strip the program name
116
+ // and use { from: 'user' } so Commander treats the rest as user args.
117
+ const userArgs = argv[0] === "hq" ? argv.slice(1) : argv;
118
+ await program.parseAsync(userArgs, { from: "user" });
119
+ exitCode = 0;
120
+ } catch (err: unknown) {
121
+ if (err instanceof ProcessExitError) {
122
+ // hq command threw via stubbed process.exit (withErrorHandling pattern).
123
+ // stderr was already written by the action handler.
124
+ exitCode = err.code;
125
+ } else if (err && typeof err === "object" && "code" in err) {
126
+ // Commander error from exitOverride()
127
+ const ce = err as { code: string; exitCode?: number };
128
+ if (ce.code === "commander.helpDisplayed" || ce.code === "commander.version") {
129
+ exitCode = 0;
130
+ } else {
131
+ exitCode = ce.exitCode ?? 1;
132
+ }
133
+ } else if (err instanceof Error) {
134
+ stderrChunks.push(err.message + "\n");
135
+ exitCode = 1;
136
+ } else {
137
+ exitCode = 1;
138
+ }
139
+ } finally {
140
+ process.stdout.write = origStdoutWrite;
141
+ process.stderr.write = origStderrWrite;
142
+ (process as { exit: unknown }).exit = origExit;
143
+ }
144
+
145
+ return {
146
+ exitCode,
147
+ stdout: stdoutChunks.join(""),
148
+ stderr: stderrChunks.join(""),
149
+ };
150
+ }
@@ -0,0 +1,79 @@
1
+ /**
2
+ * s3-list-mock.ts — in-memory stub for @aws-sdk/client-s3 S3Client.
3
+ *
4
+ * Used by sources/signals tests that need ListObjectsV2 and GetObject behaviour
5
+ * without real AWS credentials or network I/O.
6
+ */
7
+
8
+ import type { S3Client } from "@aws-sdk/client-s3";
9
+ // NOTE: We intentionally do NOT use `instanceof ListObjectsV2Command` for
10
+ // dispatch. When this stub is consumed by code in a sibling package
11
+ // (@indigoai-us/hq-cloud's compiled dist), that code's @aws-sdk/client-s3
12
+ // resolution can produce a distinct constructor instance from the one we
13
+ // import here, breaking instanceof. Dispatching on `command.constructor.name`
14
+ // is identity-free and works across package boundaries.
15
+
16
+ export interface MockEntry {
17
+ /** S3 object key (e.g. "sources/meetings/abc.md") */
18
+ key: string;
19
+ /** Full file content as UTF-8 string */
20
+ content: string;
21
+ /** Optional override; defaults to 2026-01-01T00:00:00Z */
22
+ lastModified?: Date;
23
+ }
24
+
25
+ export interface MockS3Options {
26
+ entries: MockEntry[];
27
+ }
28
+
29
+ /**
30
+ * Returns a stub S3Client whose `send` method handles:
31
+ * - ListObjectsV2Command — filters entries by Prefix, no pagination
32
+ * - GetObjectCommand — returns a streaming Body for the matching entry
33
+ *
34
+ * Throws `NoSuchKey` (matching AWS SDK error shape) for GetObject misses.
35
+ */
36
+ export function mockS3WithEntries(opts: MockS3Options): S3Client {
37
+ const { entries } = opts;
38
+ const defaultDate = new Date("2026-01-01T00:00:00Z");
39
+
40
+ async function send(command: unknown): Promise<unknown> {
41
+ const cmdName = (command as { constructor?: { name?: string } }).constructor?.name ?? "";
42
+
43
+ if (cmdName === "ListObjectsV2Command") {
44
+ const { Prefix } = (command as { input: { Bucket: string; Prefix?: string } }).input;
45
+ const prefix = Prefix ?? "";
46
+ const filtered = entries.filter((e) => e.key.startsWith(prefix));
47
+ return {
48
+ Contents: filtered.map((e) => ({
49
+ Key: e.key,
50
+ Size: Buffer.byteLength(e.content, "utf-8"),
51
+ LastModified: e.lastModified ?? defaultDate,
52
+ ETag: `"mock-etag"`,
53
+ })),
54
+ IsTruncated: false,
55
+ NextContinuationToken: undefined,
56
+ $metadata: {},
57
+ };
58
+ }
59
+
60
+ if (cmdName === "GetObjectCommand") {
61
+ const { Key } = (command as { input: { Bucket: string; Key: string } }).input;
62
+ const entry = entries.find((e) => e.key === Key);
63
+ if (!entry) {
64
+ const err = new Error(`The specified key does not exist: ${Key}`);
65
+ (err as NodeJS.ErrnoException).name = "NoSuchKey";
66
+ throw err;
67
+ }
68
+ const content = entry.content;
69
+ async function* bodyStream(): AsyncIterable<Uint8Array> {
70
+ yield Buffer.from(content, "utf-8");
71
+ }
72
+ return { Body: bodyStream(), $metadata: {} };
73
+ }
74
+
75
+ throw new Error(`mockS3WithEntries: unhandled command type "${cmdName || "unknown"}"`);
76
+ }
77
+
78
+ return { send } as unknown as S3Client;
79
+ }
@@ -0,0 +1,160 @@
1
+ /**
2
+ * vault-service-mock.ts — fetch stub for vault-service HTTP endpoints.
3
+ *
4
+ * Intercepts globalThis.fetch and handles the subset of vault-service routes
5
+ * needed by entity-resolver and STS tests. Returns the original fetch restore
6
+ * function so callers can clean up in afterEach/finally.
7
+ *
8
+ * Handled endpoints (URL path suffixes):
9
+ * GET .../membership/me returns { memberships: [...] }
10
+ * GET .../entity/by-slug/{type}/{slug} returns { entity: {...} }
11
+ * POST .../entities/{uid}/sts returns { credentials, expiresAt, bucketName, region }
12
+ */
13
+
14
+ import type { Membership, EntityInfo } from "@indigoai-us/hq-cloud";
15
+
16
+ export interface MockEntity {
17
+ /** Entity UID (e.g. "cmp_indigo_001") */
18
+ uid: string;
19
+ /** Human-readable stable slug (e.g. "indigo", "personal") */
20
+ slug: string;
21
+ /** S3 bucket name for this entity */
22
+ bucketName: string;
23
+ /** AWS region; defaults to "us-east-1" */
24
+ region?: string;
25
+ /** Entity role in this membership; defaults to "owner" */
26
+ role?: "owner" | "admin" | "member" | "guest";
27
+ }
28
+
29
+ export interface MockStsCredentials {
30
+ accessKeyId: string;
31
+ secretAccessKey: string;
32
+ sessionToken: string;
33
+ }
34
+
35
+ export interface MockVaultOptions {
36
+ entities: MockEntity[];
37
+ /** STS credentials returned for every POST /entities/{uid}/sts; defaults to test creds */
38
+ stsCredentials?: MockStsCredentials;
39
+ }
40
+
41
+ const DEFAULT_STS: MockStsCredentials = {
42
+ accessKeyId: "ASIAMOCK000000000001",
43
+ secretAccessKey: "mockSecretAccessKey",
44
+ sessionToken: "mockSessionToken",
45
+ };
46
+
47
+ /**
48
+ * Installs a fetch stub for vault-service endpoints.
49
+ *
50
+ * @returns A restore function — call it in afterEach to un-install the stub.
51
+ */
52
+ export function mockVaultService(opts: MockVaultOptions): () => void {
53
+ const { entities, stsCredentials = DEFAULT_STS } = opts;
54
+ const originalFetch = globalThis.fetch as typeof fetch | undefined;
55
+
56
+ globalThis.fetch = async (
57
+ input: RequestInfo | URL,
58
+ init?: RequestInit,
59
+ ): Promise<Response> => {
60
+ const url =
61
+ typeof input === "string"
62
+ ? input
63
+ : input instanceof URL
64
+ ? input.toString()
65
+ : (input as Request).url;
66
+ const method =
67
+ (init?.method ?? (input instanceof Request ? input.method : "GET")).toUpperCase();
68
+
69
+ // GET /membership/me
70
+ if (method === "GET" && /\/membership\/me(\?.*)?$/.test(url)) {
71
+ const memberships: Partial<Membership>[] = entities.map((e) => ({
72
+ membershipKey: `mbr_${e.uid}`,
73
+ personUid: "prs_test_person_001",
74
+ companyUid: e.uid,
75
+ role: e.role ?? "owner",
76
+ status: "active",
77
+ invitedBy: "system",
78
+ invitedAt: "2026-01-01T00:00:00Z",
79
+ createdAt: "2026-01-01T00:00:00Z",
80
+ updatedAt: "2026-01-01T00:00:00Z",
81
+ }));
82
+ return json({ memberships });
83
+ }
84
+
85
+ // GET /entity/by-slug/{type}/{slug}
86
+ const bySlugMatch = /\/entity\/by-slug\/[^/]+\/([^/?]+)/.exec(url);
87
+ if (method === "GET" && bySlugMatch) {
88
+ const slug = decodeURIComponent(bySlugMatch[1]);
89
+ const entity = entities.find((e) => e.slug === slug);
90
+ if (!entity) {
91
+ return json({ error: "Not found" }, 404);
92
+ }
93
+ const info: Partial<EntityInfo> = {
94
+ uid: entity.uid,
95
+ slug: entity.slug,
96
+ type: "company",
97
+ name: entity.slug,
98
+ bucketName: entity.bucketName,
99
+ status: "active",
100
+ };
101
+ return json({ entity: info });
102
+ }
103
+
104
+ // GET /entity/{uid} (direct UID lookup — used by entity-resolver)
105
+ const entityUidMatch = /\/entity\/([^/?]+)$/.exec(url);
106
+ if (method === "GET" && entityUidMatch) {
107
+ const uid = decodeURIComponent(entityUidMatch[1]);
108
+ const entity = entities.find((e) => e.uid === uid);
109
+ if (!entity) {
110
+ return json({ error: `Entity '${uid}' not found` }, 404);
111
+ }
112
+ const info: Partial<EntityInfo> = {
113
+ uid: entity.uid,
114
+ slug: entity.slug,
115
+ type: "company",
116
+ name: entity.slug,
117
+ bucketName: entity.bucketName,
118
+ status: "active",
119
+ };
120
+ return json({ entity: info });
121
+ }
122
+
123
+ // POST /entities/{uid}/sts
124
+ const entityStsMatch = /\/entities\/([^/]+)\/sts/.exec(url);
125
+ if (method === "POST" && entityStsMatch) {
126
+ const uid = decodeURIComponent(entityStsMatch[1]);
127
+ const entity = entities.find((e) => e.uid === uid);
128
+ if (!entity) {
129
+ return json({ error: `Entity '${uid}' not found` }, 404);
130
+ }
131
+ return json({
132
+ credentials: stsCredentials,
133
+ expiresAt: new Date(Date.now() + 3600 * 1000).toISOString(),
134
+ bucketName: entity.bucketName,
135
+ region: entity.region ?? "us-east-1",
136
+ });
137
+ }
138
+
139
+ // Unhandled — pass through if original fetch exists, else 500
140
+ if (originalFetch) {
141
+ return originalFetch(input, init);
142
+ }
143
+ return json({ error: `mockVaultService: unhandled request ${method} ${url}` }, 500);
144
+ };
145
+
146
+ return () => {
147
+ if (originalFetch) {
148
+ globalThis.fetch = originalFetch;
149
+ } else {
150
+ delete (globalThis as Record<string, unknown>).fetch;
151
+ }
152
+ };
153
+ }
154
+
155
+ function json(body: unknown, status = 200): Response {
156
+ return new Response(JSON.stringify(body), {
157
+ status,
158
+ headers: { "Content-Type": "application/json" },
159
+ });
160
+ }