@indigoai-us/hq-cli 5.15.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 (41) 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/cloud-provision.d.ts +25 -0
  6. package/dist/commands/cloud-provision.js +75 -9
  7. package/dist/commands/groups.js +6 -6
  8. package/dist/commands/meetings.js +8 -8
  9. package/dist/commands/members.d.ts +4 -2
  10. package/dist/commands/members.js +30 -14
  11. package/dist/commands/signals.d.ts +24 -0
  12. package/dist/commands/signals.js +240 -0
  13. package/dist/commands/sources.d.ts +22 -0
  14. package/dist/commands/sources.js +250 -0
  15. package/dist/index.js +8 -2
  16. package/dist/utils/cognito-session.d.ts +10 -1
  17. package/dist/utils/cognito-session.js +18 -3
  18. package/package.json +5 -4
  19. package/scripts/smoke-sources-signals.sh +103 -0
  20. package/src/cli-version.ts +5 -1
  21. package/src/commands/cloud-provision.test.ts +27 -2
  22. package/src/commands/cloud-provision.ts +122 -7
  23. package/src/commands/groups.ts +4 -4
  24. package/src/commands/meetings.ts +6 -6
  25. package/src/commands/members.test.ts +56 -0
  26. package/src/commands/members.ts +44 -13
  27. package/src/commands/signals.ts +345 -0
  28. package/src/commands/sources.ts +356 -0
  29. package/src/index.ts +8 -0
  30. package/src/utils/cognito-session.test.ts +24 -1
  31. package/src/utils/cognito-session.ts +18 -0
  32. package/test/commands/signals.test.ts +200 -0
  33. package/test/commands/sources.test.ts +225 -0
  34. package/test/fixtures/signals/action_item/sample.md +16 -0
  35. package/test/fixtures/signals/summary/sample.md +12 -0
  36. package/test/fixtures/sources/meetings/sample.md +25 -0
  37. package/test/helpers/cli-runner.ts +150 -0
  38. package/test/helpers/s3-list-mock.ts +79 -0
  39. package/test/helpers/vault-service-mock.ts +160 -0
  40. package/test/sources-signals/smoke.test.ts +226 -0
  41. package/vitest.config.ts +11 -0
@@ -0,0 +1,345 @@
1
+ /**
2
+ * `hq signals` subcommand group (US-007).
3
+ *
4
+ * Read-side surface over the signals written by sources-pipeline (and any
5
+ * future signal producer). Each invocation resolves a Cognito access
6
+ * token (or honors HQ_ACCESS_TOKEN), vends STS-scoped credentials via
7
+ * vault-service for the requested entity, and delegates to hq-cloud's
8
+ * listSignals/getSignal primitives.
9
+ *
10
+ * Subcommands:
11
+ * hq signals list List signals of a given type for an entity.
12
+ * hq signals get Fetch one signal by id.
13
+ * hq signals types Print the canonical SIGNAL_TYPES enum.
14
+ * hq signals entities List entities the caller has access to.
15
+ *
16
+ * Mirrors `hq sources` exactly — same flags, same TTY-aware defaults,
17
+ * same error/Sentry plumbing. Defense-in-depth signal-type validation
18
+ * (assertSignalType) runs at the CLI layer as well as in hq-cloud, so
19
+ * agents can't fabricate a signal type even if they bypass the CLI's
20
+ * --type flag parsing.
21
+ */
22
+
23
+ import * as fs from "node:fs";
24
+ import * as path from "node:path";
25
+ import { Command } from "commander";
26
+ import chalk from "chalk";
27
+ import {
28
+ SIGNAL_TYPES,
29
+ assertSignalType,
30
+ resolveEntity,
31
+ listAvailableEntities,
32
+ listSignals,
33
+ getSignal,
34
+ type SignalType,
35
+ type SignalSummary,
36
+ type SignalDocument,
37
+ type AvailableEntity,
38
+ type EntityContext,
39
+ } from "@indigoai-us/hq-cloud";
40
+ import {
41
+ ensureCognitoToken,
42
+ buildVaultConfig,
43
+ DEFAULT_HQ_ROOT,
44
+ } from "../utils/cognito-session.js";
45
+ import { Sentry } from "../sentry.js";
46
+
47
+ // ---------------------------------------------------------------------------
48
+ // Access token resolution — honors HQ_ACCESS_TOKEN for tests + CI smoke
49
+ // ---------------------------------------------------------------------------
50
+
51
+ async function resolveAccessToken(): Promise<string> {
52
+ if (process.env.HQ_ACCESS_TOKEN) return process.env.HQ_ACCESS_TOKEN;
53
+ return ensureCognitoToken();
54
+ }
55
+
56
+ // ---------------------------------------------------------------------------
57
+ // Entity resolution — flag → .hq/config.json activeCompany fallback
58
+ // ---------------------------------------------------------------------------
59
+
60
+ function readActiveCompanySlug(hqRoot: string): string | undefined {
61
+ const configPath = path.join(hqRoot, ".hq", "config.json");
62
+ if (!fs.existsSync(configPath)) return undefined;
63
+ try {
64
+ const cfg = JSON.parse(fs.readFileSync(configPath, "utf-8"));
65
+ const slug = (cfg as { activeCompany?: unknown }).activeCompany;
66
+ return typeof slug === "string" && slug.length > 0 ? slug : undefined;
67
+ } catch {
68
+ return undefined;
69
+ }
70
+ }
71
+
72
+ function requireEntitySlug(flag: string | undefined, hqRoot: string): string {
73
+ const slug = flag ?? readActiveCompanySlug(hqRoot);
74
+ if (!slug) {
75
+ throw new Error(
76
+ "No entity specified. Pass --entity <slug> or run `hq signals entities` to see your options.",
77
+ );
78
+ }
79
+ return slug;
80
+ }
81
+
82
+ // ---------------------------------------------------------------------------
83
+ // Format defaults — TTY-aware (humans get table, agents get JSON)
84
+ // ---------------------------------------------------------------------------
85
+
86
+ type ListFormat = "table" | "json";
87
+ type GetFormat = "markdown" | "json";
88
+
89
+ function defaultListFormat(): ListFormat {
90
+ return process.stdout.isTTY ? "table" : "json";
91
+ }
92
+
93
+ function defaultGetFormat(): GetFormat {
94
+ return process.stdout.isTTY ? "markdown" : "json";
95
+ }
96
+
97
+ // ---------------------------------------------------------------------------
98
+ // Rendering helpers
99
+ // ---------------------------------------------------------------------------
100
+
101
+ function renderListTable(entries: SignalSummary[], includeFrontmatter: boolean): string {
102
+ if (entries.length === 0) return "(no signals)";
103
+ // sourceRef column is only meaningful when --include-frontmatter was passed;
104
+ // omit it otherwise so the table doesn't lie with empty cells.
105
+ const rows = entries.map((e) => ({
106
+ signalId: e.signalId,
107
+ ...(includeFrontmatter ? { sourceRef: e.sourceRef ?? "" } : {}),
108
+ lastModified: e.lastModified.toISOString(),
109
+ size: String(e.size),
110
+ }));
111
+ const headers = Object.keys(rows[0]);
112
+ const widths = headers.map((h) =>
113
+ Math.max(h.length, ...rows.map((r) => String((r as Record<string, string>)[h]).length)),
114
+ );
115
+ const pad = (s: string, w: number): string => s + " ".repeat(Math.max(0, w - s.length));
116
+ const headerLine = headers.map((h, i) => pad(h, widths[i])).join(" ");
117
+ const sep = widths.map((w) => "-".repeat(w)).join(" ");
118
+ const body = rows
119
+ .map((r) =>
120
+ headers.map((h, i) => pad(String((r as Record<string, string>)[h]), widths[i])).join(" "),
121
+ )
122
+ .join("\n");
123
+ return [headerLine, sep, body].join("\n");
124
+ }
125
+
126
+ // ---------------------------------------------------------------------------
127
+ // Subcommand: list
128
+ // ---------------------------------------------------------------------------
129
+
130
+ interface ListOptions {
131
+ entity?: string;
132
+ type?: string;
133
+ limit?: string;
134
+ pageToken?: string;
135
+ format?: ListFormat;
136
+ includeFrontmatter?: boolean;
137
+ hqRoot: string;
138
+ }
139
+
140
+ async function runList(options: ListOptions): Promise<void> {
141
+ if (!options.type) {
142
+ throw new Error(
143
+ `--type <signalType> is required. Valid types: ${SIGNAL_TYPES.join(", ")}`,
144
+ );
145
+ }
146
+ // Throws InvalidSignalTypeError with the list of valid types if not in enum.
147
+ assertSignalType(options.type);
148
+ const signalType: SignalType = options.type;
149
+
150
+ const slug = requireEntitySlug(options.entity, options.hqRoot);
151
+ const limit = options.limit ? Number.parseInt(options.limit, 10) : 50;
152
+ if (!Number.isFinite(limit) || limit <= 0) {
153
+ throw new Error(`--limit must be a positive integer (got '${options.limit}')`);
154
+ }
155
+ const format = options.format ?? defaultListFormat();
156
+
157
+ const accessToken = await resolveAccessToken();
158
+ const vaultConfig = buildVaultConfig(accessToken);
159
+ const entity: EntityContext = await resolveEntity({ slug, vaultConfig });
160
+
161
+ const result = await listSignals({
162
+ entity,
163
+ signalType,
164
+ limit,
165
+ continuationToken: options.pageToken,
166
+ includeFrontmatter: options.includeFrontmatter,
167
+ });
168
+
169
+ if (format === "json") {
170
+ process.stdout.write(JSON.stringify(result, null, 2) + "\n");
171
+ return;
172
+ }
173
+
174
+ process.stdout.write(renderListTable(result.entries, !!options.includeFrontmatter) + "\n");
175
+ if (result.nextToken) {
176
+ process.stdout.write(`\nNext page token: ${result.nextToken}\n`);
177
+ }
178
+ }
179
+
180
+ // ---------------------------------------------------------------------------
181
+ // Subcommand: get
182
+ // ---------------------------------------------------------------------------
183
+
184
+ interface GetOptions {
185
+ entity?: string;
186
+ type?: string;
187
+ id?: string;
188
+ format?: GetFormat;
189
+ hqRoot: string;
190
+ }
191
+
192
+ async function runGet(options: GetOptions): Promise<void> {
193
+ if (!options.type) {
194
+ throw new Error(
195
+ `--type <signalType> is required. Valid types: ${SIGNAL_TYPES.join(", ")}`,
196
+ );
197
+ }
198
+ if (!options.id) {
199
+ throw new Error("--id <signalId> is required.");
200
+ }
201
+ assertSignalType(options.type);
202
+ const signalType: SignalType = options.type;
203
+
204
+ const slug = requireEntitySlug(options.entity, options.hqRoot);
205
+ const format = options.format ?? defaultGetFormat();
206
+
207
+ const accessToken = await resolveAccessToken();
208
+ const vaultConfig = buildVaultConfig(accessToken);
209
+ const entity: EntityContext = await resolveEntity({ slug, vaultConfig });
210
+
211
+ const doc: SignalDocument = await getSignal({
212
+ entity,
213
+ signalType,
214
+ signalId: options.id,
215
+ });
216
+
217
+ if (format === "json") {
218
+ process.stdout.write(JSON.stringify(doc, null, 2) + "\n");
219
+ return;
220
+ }
221
+
222
+ // markdown: reconstruct frontmatter block + body so the output round-trips.
223
+ if (doc.frontmatter) {
224
+ const yamlLines = Object.entries(doc.frontmatter).map(
225
+ ([k, v]) => `${k}: ${typeof v === "string" ? v : JSON.stringify(v)}`,
226
+ );
227
+ process.stdout.write(`---\n${yamlLines.join("\n")}\n---\n\n${doc.body}\n`);
228
+ } else {
229
+ process.stdout.write(doc.body + "\n");
230
+ }
231
+ }
232
+
233
+ // ---------------------------------------------------------------------------
234
+ // Subcommand: types
235
+ // ---------------------------------------------------------------------------
236
+
237
+ function runTypes(): void {
238
+ const sorted = [...SIGNAL_TYPES].sort();
239
+ process.stdout.write(sorted.join("\n") + "\n");
240
+ }
241
+
242
+ // ---------------------------------------------------------------------------
243
+ // Subcommand: entities (alias — identical to `hq sources entities`)
244
+ // ---------------------------------------------------------------------------
245
+
246
+ async function runEntities(options: { format?: ListFormat }): Promise<void> {
247
+ const format = options.format ?? defaultListFormat();
248
+ const accessToken = await resolveAccessToken();
249
+ const vaultConfig = buildVaultConfig(accessToken);
250
+ const entities: AvailableEntity[] = await listAvailableEntities({ vaultConfig });
251
+
252
+ if (format === "json") {
253
+ process.stdout.write(JSON.stringify(entities, null, 2) + "\n");
254
+ return;
255
+ }
256
+
257
+ if (entities.length === 0) {
258
+ process.stdout.write("(no entities — your account has no active memberships)\n");
259
+ return;
260
+ }
261
+
262
+ const headers = ["slug", "role", "uid"];
263
+ const widths = headers.map((h, i) =>
264
+ Math.max(
265
+ h.length,
266
+ ...entities.map((e) => String([e.slug, e.role, e.uid][i]).length),
267
+ ),
268
+ );
269
+ const pad = (s: string, w: number): string => s + " ".repeat(Math.max(0, w - s.length));
270
+ const headerLine = headers.map((h, i) => pad(h, widths[i])).join(" ");
271
+ const sep = widths.map((w) => "-".repeat(w)).join(" ");
272
+ const body = entities
273
+ .map((e) =>
274
+ [e.slug, e.role, e.uid].map((cell, i) => pad(cell, widths[i])).join(" "),
275
+ )
276
+ .join("\n");
277
+ process.stdout.write([headerLine, sep, body].join("\n") + "\n");
278
+ }
279
+
280
+ // ---------------------------------------------------------------------------
281
+ // Registration
282
+ // ---------------------------------------------------------------------------
283
+
284
+ /** Wrap an action so caught errors print red + capture to Sentry + exit 1. */
285
+ function withErrorHandling<T extends unknown[]>(
286
+ fn: (...args: T) => Promise<void> | void,
287
+ ): (...args: T) => Promise<void> {
288
+ return async (...args: T) => {
289
+ try {
290
+ await fn(...args);
291
+ } catch (err) {
292
+ const message = err instanceof Error ? err.message : String(err);
293
+ process.stderr.write(chalk.red(`✗ ${message}\n`));
294
+ Sentry.captureException(err);
295
+ process.exit(1);
296
+ }
297
+ };
298
+ }
299
+
300
+ export function registerSignalsCommand(program: Command): void {
301
+ const signals = program
302
+ .command("signals")
303
+ .description("Read signals (action_items, decisions, etc.) from a vault entity");
304
+
305
+ signals
306
+ .command("list")
307
+ .description("List signals of a given type for an entity")
308
+ .option("--entity <slug>", "Entity slug (defaults to .hq/config.json activeCompany)")
309
+ .option("--type <signalType>", `Signal type: ${SIGNAL_TYPES.join(" | ")}`)
310
+ .option("--limit <n>", "Max entries per page (default 50)")
311
+ .option("--page-token <token>", "Continuation token from a prior page")
312
+ .option("--format <fmt>", "Output format: table | json (default: table for TTY, json piped)")
313
+ .option("--include-frontmatter", "Fetch + parse each entry's frontmatter (extra GETs)")
314
+ .option(
315
+ "--hq-root <path>",
316
+ `Local HQ tree root (for .hq/config.json lookup; default: ${DEFAULT_HQ_ROOT})`,
317
+ DEFAULT_HQ_ROOT,
318
+ )
319
+ .action(withErrorHandling(async (options: ListOptions) => runList(options)));
320
+
321
+ signals
322
+ .command("get")
323
+ .description("Fetch a single signal by id")
324
+ .option("--entity <slug>", "Entity slug (defaults to .hq/config.json activeCompany)")
325
+ .option("--type <signalType>", `Signal type: ${SIGNAL_TYPES.join(" | ")}`)
326
+ .option("--id <signalId>", "Signal id (filename minus .md)")
327
+ .option("--format <fmt>", "Output format: markdown | json (default: markdown for TTY, json piped)")
328
+ .option(
329
+ "--hq-root <path>",
330
+ `Local HQ tree root (for .hq/config.json lookup; default: ${DEFAULT_HQ_ROOT})`,
331
+ DEFAULT_HQ_ROOT,
332
+ )
333
+ .action(withErrorHandling(async (options: GetOptions) => runGet(options)));
334
+
335
+ signals
336
+ .command("types")
337
+ .description("Print the canonical signal types (one per line)")
338
+ .action(withErrorHandling(() => runTypes()));
339
+
340
+ signals
341
+ .command("entities")
342
+ .description("List entities (companies/personal) your account has access to")
343
+ .option("--format <fmt>", "Output format: table | json (default: table for TTY, json piped)")
344
+ .action(withErrorHandling(async (options: { format?: ListFormat }) => runEntities(options)));
345
+ }
@@ -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
+ }