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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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 +161 -0
  36. package/test/sources-signals/smoke.test.ts +228 -0
  37. package/vitest.config.ts +11 -0
@@ -0,0 +1,356 @@
1
+ /**
2
+ * `hq sources` subcommand group (US-006).
3
+ *
4
+ * Read-side surface over the sources written by sources-pipeline. Each
5
+ * invocation resolves a Cognito access token (or honors HQ_ACCESS_TOKEN),
6
+ * vends STS-scoped credentials via vault-service for the requested entity,
7
+ * and delegates to hq-cloud's listSources/getSource primitives.
8
+ *
9
+ * Subcommands:
10
+ * hq sources list List sources of a given channel for an entity.
11
+ * hq sources get Fetch one source by id.
12
+ * hq sources channels Print the canonical SOURCE_CHANNELS enum.
13
+ * hq sources entities List entities the caller has access to.
14
+ *
15
+ * Defaults:
16
+ * --entity falls back to .hq/config.json activeCompany (per sync.ts).
17
+ * --format 'table' when stdout is a TTY, 'json' when piped.
18
+ * --limit 50.
19
+ */
20
+
21
+ import * as fs from "node:fs";
22
+ import * as path from "node:path";
23
+ import { Command } from "commander";
24
+ import chalk from "chalk";
25
+ import {
26
+ SOURCE_CHANNELS,
27
+ assertSourceChannel,
28
+ resolveEntity,
29
+ listAvailableEntities,
30
+ listSources,
31
+ getSource,
32
+ type SourceChannel,
33
+ type SourceSummary,
34
+ type SourceDocument,
35
+ type AvailableEntity,
36
+ type EntityContext,
37
+ } from "@indigoai-us/hq-cloud";
38
+ import {
39
+ ensureCognitoToken,
40
+ buildVaultConfig,
41
+ DEFAULT_HQ_ROOT,
42
+ } from "../utils/cognito-session.js";
43
+ import { Sentry } from "../sentry.js";
44
+
45
+ // ---------------------------------------------------------------------------
46
+ // Access token resolution — honors HQ_ACCESS_TOKEN for tests + CI smoke
47
+ // ---------------------------------------------------------------------------
48
+
49
+ /**
50
+ * Returns a usable access token. Tests and CI smoke scripts can set
51
+ * HQ_ACCESS_TOKEN to bypass the interactive Cognito flow; otherwise we fall
52
+ * back to the cached/refresh/browser-login pipeline in cognito-session.ts.
53
+ */
54
+ async function resolveAccessToken(): Promise<string> {
55
+ if (process.env.HQ_ACCESS_TOKEN) return process.env.HQ_ACCESS_TOKEN;
56
+ return ensureCognitoToken();
57
+ }
58
+
59
+ // ---------------------------------------------------------------------------
60
+ // Entity resolution — flag → .hq/config.json activeCompany fallback
61
+ // ---------------------------------------------------------------------------
62
+
63
+ /**
64
+ * Read the active company slug from .hq/config.json (mirrors sync.ts /
65
+ * cloud.ts behaviour). Returns undefined when the file is missing or the
66
+ * key isn't set; never throws.
67
+ */
68
+ function readActiveCompanySlug(hqRoot: string): string | undefined {
69
+ const configPath = path.join(hqRoot, ".hq", "config.json");
70
+ if (!fs.existsSync(configPath)) return undefined;
71
+ try {
72
+ const cfg = JSON.parse(fs.readFileSync(configPath, "utf-8"));
73
+ const slug = (cfg as { activeCompany?: unknown }).activeCompany;
74
+ return typeof slug === "string" && slug.length > 0 ? slug : undefined;
75
+ } catch {
76
+ return undefined;
77
+ }
78
+ }
79
+
80
+ function requireEntitySlug(flag: string | undefined, hqRoot: string): string {
81
+ const slug = flag ?? readActiveCompanySlug(hqRoot);
82
+ if (!slug) {
83
+ throw new Error(
84
+ "No entity specified. Pass --entity <slug> or run `hq sources entities` to see your options.",
85
+ );
86
+ }
87
+ return slug;
88
+ }
89
+
90
+ // ---------------------------------------------------------------------------
91
+ // Format defaults — TTY-aware (humans get table, agents get JSON)
92
+ // ---------------------------------------------------------------------------
93
+
94
+ type ListFormat = "table" | "json";
95
+ type GetFormat = "markdown" | "json";
96
+
97
+ function defaultListFormat(): ListFormat {
98
+ return process.stdout.isTTY ? "table" : "json";
99
+ }
100
+
101
+ function defaultGetFormat(): GetFormat {
102
+ return process.stdout.isTTY ? "markdown" : "json";
103
+ }
104
+
105
+ // ---------------------------------------------------------------------------
106
+ // Rendering helpers
107
+ // ---------------------------------------------------------------------------
108
+
109
+ function renderListTable(entries: SourceSummary[], includeFrontmatter: boolean): string {
110
+ if (entries.length === 0) return "(no sources)";
111
+ const rows = entries.map((e) => ({
112
+ sourceId: e.sourceId,
113
+ lastModified: e.lastModified.toISOString(),
114
+ size: String(e.size),
115
+ ...(includeFrontmatter
116
+ ? { title: typeof e.frontmatter?.title === "string" ? e.frontmatter.title : "" }
117
+ : {}),
118
+ }));
119
+ const headers = Object.keys(rows[0]);
120
+ const widths = headers.map((h) =>
121
+ Math.max(h.length, ...rows.map((r) => String((r as Record<string, string>)[h]).length)),
122
+ );
123
+ const pad = (s: string, w: number): string => s + " ".repeat(Math.max(0, w - s.length));
124
+ const headerLine = headers.map((h, i) => pad(h, widths[i])).join(" ");
125
+ const sep = widths.map((w) => "-".repeat(w)).join(" ");
126
+ const body = rows
127
+ .map((r) =>
128
+ headers.map((h, i) => pad(String((r as Record<string, string>)[h]), widths[i])).join(" "),
129
+ )
130
+ .join("\n");
131
+ return [headerLine, sep, body].join("\n");
132
+ }
133
+
134
+ // ---------------------------------------------------------------------------
135
+ // Subcommand: list
136
+ // ---------------------------------------------------------------------------
137
+
138
+ interface ListOptions {
139
+ entity?: string;
140
+ type?: string;
141
+ limit?: string;
142
+ pageToken?: string;
143
+ format?: ListFormat;
144
+ includeFrontmatter?: boolean;
145
+ hqRoot: string;
146
+ }
147
+
148
+ async function runList(options: ListOptions): Promise<void> {
149
+ if (!options.type) {
150
+ throw new Error(
151
+ `--type <channel> is required. Valid channels: ${SOURCE_CHANNELS.join(", ")}`,
152
+ );
153
+ }
154
+ // Throws InvalidSourceChannelError with the list of valid channels if not in enum.
155
+ assertSourceChannel(options.type);
156
+ const channel: SourceChannel = options.type;
157
+
158
+ const slug = requireEntitySlug(options.entity, options.hqRoot);
159
+ const limit = options.limit ? Number.parseInt(options.limit, 10) : 50;
160
+ if (!Number.isFinite(limit) || limit <= 0) {
161
+ throw new Error(`--limit must be a positive integer (got '${options.limit}')`);
162
+ }
163
+ const format = options.format ?? defaultListFormat();
164
+
165
+ const accessToken = await resolveAccessToken();
166
+ const vaultConfig = buildVaultConfig(accessToken);
167
+ const entity: EntityContext = await resolveEntity({ slug, vaultConfig });
168
+
169
+ const result = await listSources({
170
+ entity,
171
+ channel,
172
+ limit,
173
+ continuationToken: options.pageToken,
174
+ includeFrontmatter: options.includeFrontmatter,
175
+ });
176
+
177
+ if (format === "json") {
178
+ process.stdout.write(JSON.stringify(result, null, 2) + "\n");
179
+ return;
180
+ }
181
+
182
+ process.stdout.write(renderListTable(result.entries, !!options.includeFrontmatter) + "\n");
183
+ if (result.nextToken) {
184
+ process.stdout.write(`\nNext page token: ${result.nextToken}\n`);
185
+ }
186
+ }
187
+
188
+ // ---------------------------------------------------------------------------
189
+ // Subcommand: get
190
+ // ---------------------------------------------------------------------------
191
+
192
+ interface GetOptions {
193
+ entity?: string;
194
+ type?: string;
195
+ id?: string;
196
+ format?: GetFormat;
197
+ includeRaw?: boolean;
198
+ hqRoot: string;
199
+ }
200
+
201
+ async function runGet(options: GetOptions): Promise<void> {
202
+ if (!options.type) {
203
+ throw new Error(
204
+ `--type <channel> is required. Valid channels: ${SOURCE_CHANNELS.join(", ")}`,
205
+ );
206
+ }
207
+ if (!options.id) {
208
+ throw new Error("--id <sourceId> is required.");
209
+ }
210
+ assertSourceChannel(options.type);
211
+ const channel: SourceChannel = options.type;
212
+
213
+ const slug = requireEntitySlug(options.entity, options.hqRoot);
214
+ const format = options.format ?? defaultGetFormat();
215
+
216
+ const accessToken = await resolveAccessToken();
217
+ const vaultConfig = buildVaultConfig(accessToken);
218
+ const entity: EntityContext = await resolveEntity({ slug, vaultConfig });
219
+
220
+ const doc: SourceDocument = await getSource({
221
+ entity,
222
+ channel,
223
+ sourceId: options.id,
224
+ includeRaw: options.includeRaw,
225
+ });
226
+
227
+ if (format === "json") {
228
+ process.stdout.write(JSON.stringify(doc, null, 2) + "\n");
229
+ return;
230
+ }
231
+
232
+ // markdown: reconstruct frontmatter block + body so the output round-trips.
233
+ if (doc.frontmatter) {
234
+ const yamlLines = Object.entries(doc.frontmatter).map(
235
+ ([k, v]) => `${k}: ${typeof v === "string" ? v : JSON.stringify(v)}`,
236
+ );
237
+ process.stdout.write(`---\n${yamlLines.join("\n")}\n---\n\n${doc.body}\n`);
238
+ } else {
239
+ process.stdout.write(doc.body + "\n");
240
+ }
241
+ }
242
+
243
+ // ---------------------------------------------------------------------------
244
+ // Subcommand: channels
245
+ // ---------------------------------------------------------------------------
246
+
247
+ function runChannels(): void {
248
+ const sorted = [...SOURCE_CHANNELS].sort();
249
+ process.stdout.write(sorted.join("\n") + "\n");
250
+ }
251
+
252
+ // ---------------------------------------------------------------------------
253
+ // Subcommand: entities
254
+ // ---------------------------------------------------------------------------
255
+
256
+ async function runEntities(options: { format?: ListFormat }): Promise<void> {
257
+ const format = options.format ?? defaultListFormat();
258
+ const accessToken = await resolveAccessToken();
259
+ const vaultConfig = buildVaultConfig(accessToken);
260
+ const entities: AvailableEntity[] = await listAvailableEntities({ vaultConfig });
261
+
262
+ if (format === "json") {
263
+ process.stdout.write(JSON.stringify(entities, null, 2) + "\n");
264
+ return;
265
+ }
266
+
267
+ if (entities.length === 0) {
268
+ process.stdout.write("(no entities — your account has no active memberships)\n");
269
+ return;
270
+ }
271
+
272
+ const headers = ["slug", "role", "uid"];
273
+ const widths = headers.map((h, i) =>
274
+ Math.max(
275
+ h.length,
276
+ ...entities.map((e) => String([e.slug, e.role, e.uid][i]).length),
277
+ ),
278
+ );
279
+ const pad = (s: string, w: number): string => s + " ".repeat(Math.max(0, w - s.length));
280
+ const headerLine = headers.map((h, i) => pad(h, widths[i])).join(" ");
281
+ const sep = widths.map((w) => "-".repeat(w)).join(" ");
282
+ const body = entities
283
+ .map((e) =>
284
+ [e.slug, e.role, e.uid].map((cell, i) => pad(cell, widths[i])).join(" "),
285
+ )
286
+ .join("\n");
287
+ process.stdout.write([headerLine, sep, body].join("\n") + "\n");
288
+ }
289
+
290
+ // ---------------------------------------------------------------------------
291
+ // Registration
292
+ // ---------------------------------------------------------------------------
293
+
294
+ /** Wrap an action so caught errors print red + capture to Sentry + exit 1. */
295
+ function withErrorHandling<T extends unknown[]>(
296
+ fn: (...args: T) => Promise<void> | void,
297
+ ): (...args: T) => Promise<void> {
298
+ return async (...args: T) => {
299
+ try {
300
+ await fn(...args);
301
+ } catch (err) {
302
+ const message = err instanceof Error ? err.message : String(err);
303
+ process.stderr.write(chalk.red(`✗ ${message}\n`));
304
+ Sentry.captureException(err);
305
+ process.exit(1);
306
+ }
307
+ };
308
+ }
309
+
310
+ export function registerSourcesCommand(program: Command): void {
311
+ const sources = program
312
+ .command("sources")
313
+ .description("Read sources (meetings, emails, etc.) from a vault entity");
314
+
315
+ sources
316
+ .command("list")
317
+ .description("List sources of a given channel for an entity")
318
+ .option("--entity <slug>", "Entity slug (defaults to .hq/config.json activeCompany)")
319
+ .option("--type <channel>", `Source channel: ${SOURCE_CHANNELS.join(" | ")}`)
320
+ .option("--limit <n>", "Max entries per page (default 50)")
321
+ .option("--page-token <token>", "Continuation token from a prior page")
322
+ .option("--format <fmt>", "Output format: table | json (default: table for TTY, json piped)")
323
+ .option("--include-frontmatter", "Fetch + parse each entry's frontmatter (extra GETs)")
324
+ .option(
325
+ "--hq-root <path>",
326
+ `Local HQ tree root (for .hq/config.json lookup; default: ${DEFAULT_HQ_ROOT})`,
327
+ DEFAULT_HQ_ROOT,
328
+ )
329
+ .action(withErrorHandling(async (options: ListOptions) => runList(options)));
330
+
331
+ sources
332
+ .command("get")
333
+ .description("Fetch a single source by id")
334
+ .option("--entity <slug>", "Entity slug (defaults to .hq/config.json activeCompany)")
335
+ .option("--type <channel>", `Source channel: ${SOURCE_CHANNELS.join(" | ")}`)
336
+ .option("--id <sourceId>", "Source id (filename minus .md)")
337
+ .option("--format <fmt>", "Output format: markdown | json (default: markdown for TTY, json piped)")
338
+ .option("--include-raw", "Also fetch the .raw.json sibling")
339
+ .option(
340
+ "--hq-root <path>",
341
+ `Local HQ tree root (for .hq/config.json lookup; default: ${DEFAULT_HQ_ROOT})`,
342
+ DEFAULT_HQ_ROOT,
343
+ )
344
+ .action(withErrorHandling(async (options: GetOptions) => runGet(options)));
345
+
346
+ sources
347
+ .command("channels")
348
+ .description("Print the canonical source channels (one per line)")
349
+ .action(withErrorHandling(() => runChannels()));
350
+
351
+ sources
352
+ .command("entities")
353
+ .description("List entities (companies/personal) your account has access to")
354
+ .option("--format <fmt>", "Output format: table | json (default: table for TTY, json piped)")
355
+ .action(withErrorHandling(async (options: { format?: ListFormat }) => runEntities(options)));
356
+ }
package/src/index.ts CHANGED
@@ -30,6 +30,8 @@ import { registerFilesCommand } from "./commands/files.js";
30
30
  import { registerMembersCommand } from "./commands/members.js";
31
31
  import { registerFeedbackCommand } from "./commands/feedback.js";
32
32
  import { registerMeetingsCommand } from "./commands/meetings.js";
33
+ import { registerSourcesCommand } from "./commands/sources.js";
34
+ import { registerSignalsCommand } from "./commands/signals.js";
33
35
  import { sanitizeArgv } from "./utils/feedback-diagnostics.js";
34
36
  import {
35
37
  maybeWarnNewVersion,
@@ -134,6 +136,12 @@ registerFeedbackCommand(program);
134
136
  // Meetings (subcommand group — hq meetings list|get|search|transcript|notes)
135
137
  registerMeetingsCommand(program);
136
138
 
139
+ // Sources read surface (subcommand group — hq sources list|get|channels|entities)
140
+ registerSourcesCommand(program);
141
+
142
+ // Signals read surface (subcommand group — hq signals list|get|types|entities)
143
+ registerSignalsCommand(program);
144
+
137
145
  (async () => {
138
146
  try {
139
147
  Sentry.addBreadcrumb({
@@ -8,7 +8,12 @@ import { mkdtempSync, rmSync, writeFileSync, mkdirSync } from "node:fs";
8
8
  import { tmpdir } from "node:os";
9
9
  import { join } from "node:path";
10
10
 
11
- import { resolveDefaultHqRoot } from "./cognito-session.js";
11
+ import {
12
+ CLI_CLIENT_INFO,
13
+ buildVaultConfig,
14
+ resolveDefaultHqRoot,
15
+ } from "./cognito-session.js";
16
+ import { CLI_NAME, CLI_VERSION } from "../cli-version.js";
12
17
 
13
18
  describe("resolveDefaultHqRoot", () => {
14
19
  let tmpRoot: string;
@@ -110,3 +115,21 @@ describe("resolveDefaultHqRoot", () => {
110
115
  expect(resolveDefaultHqRoot()).toBe(explicit);
111
116
  });
112
117
  });
118
+
119
+ describe("CLI_CLIENT_INFO + buildVaultConfig", () => {
120
+ it("exposes the CLI's package name and version", () => {
121
+ expect(CLI_CLIENT_INFO.name).toBe(CLI_NAME);
122
+ expect(CLI_CLIENT_INFO.version).toBe(CLI_VERSION);
123
+ // Name should always be the @indigoai-us scoped slug — guard against accidental
124
+ // renames that would silently break server-side traffic attribution.
125
+ expect(CLI_NAME).toBe("@indigoai-us/hq-cli");
126
+ expect(CLI_VERSION).toMatch(/^\d+\.\d+\.\d+/);
127
+ });
128
+
129
+ it("buildVaultConfig stamps clientInfo onto the returned config", () => {
130
+ const cfg = buildVaultConfig("dummy-token");
131
+ expect(cfg.clientInfo).toBe(CLI_CLIENT_INFO);
132
+ expect(cfg.clientInfo?.name).toBe("@indigoai-us/hq-cli");
133
+ expect(cfg.clientInfo?.version).toBe(CLI_VERSION);
134
+ });
135
+ });
@@ -28,9 +28,12 @@ import {
28
28
  isExpiring,
29
29
  refreshTokens,
30
30
  browserLogin,
31
+ detectHqCoreVersion,
31
32
  type CognitoAuthConfig,
33
+ type ClientInfo,
32
34
  type VaultServiceConfig,
33
35
  } from "@indigoai-us/hq-cloud";
36
+ import { CLI_NAME, CLI_VERSION } from "../cli-version.js";
34
37
 
35
38
  export const DEFAULT_COGNITO: CognitoAuthConfig = {
36
39
  region: process.env.AWS_REGION ?? "us-east-1",
@@ -146,12 +149,27 @@ export async function ensureCognitoToken(options: {
146
149
  return tokens.accessToken;
147
150
  }
148
151
 
152
+ /**
153
+ * The CLI's own ClientInfo. Resolved once at module load so every VaultClient
154
+ * built in this process stamps the same name/version onto its requests.
155
+ *
156
+ * `hqCoreVersion` is filled in lazily by walking up from cwd to find
157
+ * `core/core.yaml` — present only when the CLI is invoked from inside an
158
+ * hq-core checkout, so the server can see scaffold-generation skew.
159
+ */
160
+ export const CLI_CLIENT_INFO: ClientInfo = {
161
+ name: CLI_NAME,
162
+ version: CLI_VERSION,
163
+ hqCoreVersion: detectHqCoreVersion(),
164
+ };
165
+
149
166
  /** Build a VaultServiceConfig with the given access token. */
150
167
  export function buildVaultConfig(authToken: string): VaultServiceConfig {
151
168
  return {
152
169
  apiUrl: DEFAULT_VAULT_API_URL,
153
170
  authToken,
154
171
  region: DEFAULT_COGNITO.region,
172
+ clientInfo: CLI_CLIENT_INFO,
155
173
  };
156
174
  }
157
175
 
@@ -0,0 +1,200 @@
1
+ /**
2
+ * signals.test.ts — E2E tests for `hq signals` (US-007).
3
+ *
4
+ * Drives the full CLI through `runCli` with `globalThis.fetch` stubbed
5
+ * (vault-service) and the hq-cloud signals S3 factory swapped to an
6
+ * in-memory stub. Covers the three e2e cases defined in the PRD:
7
+ *
8
+ * 1. `hq signals list --entity indigo --type action_item --format json`
9
+ * → exit 0, JSON entry with signalId='xyz'.
10
+ * 2. `hq signals list --entity indigo --type ramble`
11
+ * → exit 1, stderr lists the six canonical signal types.
12
+ * 3. `hq signals types`
13
+ * → exit 0, stdout equals "action_item\ncommitment\ndecision\nkey_point\nrisk\nsummary\n".
14
+ *
15
+ * HQ_ACCESS_TOKEN is set per-test so resolveAccessToken() short-circuits
16
+ * away from the interactive Cognito flow.
17
+ */
18
+
19
+ import { mkdtempSync, rmSync } from "node:fs";
20
+ import { tmpdir } from "node:os";
21
+ import { join } from "node:path";
22
+ import { afterEach, beforeEach, describe, expect, it } from "vitest";
23
+ import {
24
+ _setSignalsS3Factory,
25
+ _resetSignalsS3Factory,
26
+ } from "@indigoai-us/hq-cloud";
27
+ import { mockS3WithEntries } from "../helpers/s3-list-mock.js";
28
+ import { mockVaultService } from "../helpers/vault-service-mock.js";
29
+ import { runCli } from "../helpers/cli-runner.js";
30
+
31
+ // ---------------------------------------------------------------------------
32
+ // Fixture — action_item signal matching sources-pipeline output shape
33
+ // ---------------------------------------------------------------------------
34
+
35
+ const ACTION_ITEM_MD = `---
36
+ signal_id: xyz
37
+ signal_type: action_item
38
+ source_ref: abc-meeting-001
39
+ citations:
40
+ - "Stefan to review the sources pipeline implementation by end of week"
41
+ entity_refs:
42
+ - stefan@indigoai.us
43
+ created_at: "2026-03-15T15:00:00Z"
44
+ ---
45
+
46
+ Stefan will review the sources pipeline implementation and provide feedback by Friday.
47
+ `;
48
+
49
+ const BODY_SENTINEL = "Stefan will review the sources pipeline implementation";
50
+
51
+ // ---------------------------------------------------------------------------
52
+ // Per-test setup — vault + S3 mocks + isolated --hq-root
53
+ // ---------------------------------------------------------------------------
54
+
55
+ let restoreFetch: (() => void) | undefined;
56
+ let tmpHqRoot: string;
57
+ let savedEnv: { HQ_ACCESS_TOKEN: string | undefined };
58
+
59
+ beforeEach(() => {
60
+ savedEnv = { HQ_ACCESS_TOKEN: process.env.HQ_ACCESS_TOKEN };
61
+ process.env.HQ_ACCESS_TOKEN = "test-access-token";
62
+
63
+ tmpHqRoot = mkdtempSync(join(tmpdir(), "hq-signals-test-"));
64
+
65
+ const s3 = mockS3WithEntries({
66
+ entries: [
67
+ {
68
+ key: "signals/action_item/xyz.md",
69
+ content: ACTION_ITEM_MD,
70
+ lastModified: new Date("2026-03-15T15:00:00Z"),
71
+ },
72
+ ],
73
+ });
74
+ _setSignalsS3Factory(() => s3);
75
+
76
+ restoreFetch = mockVaultService({
77
+ entities: [{ uid: "cmp_indigo_001", slug: "indigo", bucketName: "hq-indigo-bucket" }],
78
+ });
79
+ });
80
+
81
+ afterEach(() => {
82
+ _resetSignalsS3Factory();
83
+ restoreFetch?.();
84
+ restoreFetch = undefined;
85
+ rmSync(tmpHqRoot, { recursive: true, force: true });
86
+
87
+ if (savedEnv.HQ_ACCESS_TOKEN === undefined) {
88
+ delete process.env.HQ_ACCESS_TOKEN;
89
+ } else {
90
+ process.env.HQ_ACCESS_TOKEN = savedEnv.HQ_ACCESS_TOKEN;
91
+ }
92
+ });
93
+
94
+ // ---------------------------------------------------------------------------
95
+ // Tests — PRD e2e cases
96
+ // ---------------------------------------------------------------------------
97
+
98
+ describe("hq signals (e2e)", () => {
99
+ it("list --entity indigo --type action_item --format json — exit 0 + signalId='xyz'", async () => {
100
+ const result = await runCli([
101
+ "hq",
102
+ "signals",
103
+ "list",
104
+ "--entity",
105
+ "indigo",
106
+ "--type",
107
+ "action_item",
108
+ "--format",
109
+ "json",
110
+ "--hq-root",
111
+ tmpHqRoot,
112
+ ]);
113
+
114
+ expect(result.exitCode, `stderr=${result.stderr}`).toBe(0);
115
+ expect(result.stderr).toBe("");
116
+
117
+ const parsed = JSON.parse(result.stdout) as {
118
+ entries: Array<{ signalId: string; signalType: string; key: string }>;
119
+ nextToken?: string;
120
+ };
121
+ expect(parsed.entries).toHaveLength(1);
122
+ expect(parsed.entries[0].signalId).toBe("xyz");
123
+ expect(parsed.entries[0].signalType).toBe("action_item");
124
+ expect(parsed.entries[0].key).toBe("signals/action_item/xyz.md");
125
+ });
126
+
127
+ it("list --entity indigo --type ramble — exit 1 + stderr lists six canonical types", async () => {
128
+ const result = await runCli([
129
+ "hq",
130
+ "signals",
131
+ "list",
132
+ "--entity",
133
+ "indigo",
134
+ "--type",
135
+ "ramble",
136
+ "--format",
137
+ "json",
138
+ "--hq-root",
139
+ tmpHqRoot,
140
+ ]);
141
+
142
+ expect(result.exitCode).toBe(1);
143
+ // Every canonical signal type must appear in the error message.
144
+ for (const t of [
145
+ "action_item",
146
+ "commitment",
147
+ "decision",
148
+ "key_point",
149
+ "risk",
150
+ "summary",
151
+ ]) {
152
+ expect(result.stderr).toContain(t);
153
+ }
154
+ });
155
+
156
+ it("types — exit 0 + stdout equals the sorted six types, one per line", async () => {
157
+ const result = await runCli(["hq", "signals", "types"]);
158
+ expect(result.exitCode).toBe(0);
159
+ // Sorted alphabetically — happens to match SIGNAL_TYPES insertion order.
160
+ expect(result.stdout).toBe(
161
+ "action_item\ncommitment\ndecision\nkey_point\nrisk\nsummary\n",
162
+ );
163
+ });
164
+ });
165
+
166
+ // ---------------------------------------------------------------------------
167
+ // Bonus coverage — get + wiring
168
+ // ---------------------------------------------------------------------------
169
+
170
+ describe("hq signals get", () => {
171
+ it("get --entity indigo --type action_item --id xyz --format markdown — body present", async () => {
172
+ const result = await runCli([
173
+ "hq",
174
+ "signals",
175
+ "get",
176
+ "--entity",
177
+ "indigo",
178
+ "--type",
179
+ "action_item",
180
+ "--id",
181
+ "xyz",
182
+ "--format",
183
+ "markdown",
184
+ "--hq-root",
185
+ tmpHqRoot,
186
+ ]);
187
+
188
+ expect(result.exitCode, `stderr=${result.stderr}`).toBe(0);
189
+ expect(result.stderr).toBe("");
190
+ expect(result.stdout).toContain(BODY_SENTINEL);
191
+ });
192
+ });
193
+
194
+ describe("hq --help wiring", () => {
195
+ it("mentions the signals subcommand", async () => {
196
+ const result = await runCli(["hq", "--help"]);
197
+ expect(result.exitCode).toBe(0);
198
+ expect(result.stdout).toContain("signals");
199
+ });
200
+ });