@fabrika/cli 0.9.0-dev.4 → 0.9.0-dev.41

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.
@@ -0,0 +1,737 @@
1
+ // The `fabrika operations` command area: Operations' issues, releases and health, read through the console's
2
+ // `/operations/api/rpc`, the typed RPC the console's Operations pages call. It is read-only: every command is a read
3
+ // procedure of `OperationsRpcContract`, and the area reaches no write.
4
+
5
+ import { createRpcClient, type InferRpcClient, RpcError, type RpcFetch } from '@fabrika/app'
6
+ import type { ConsoleAccessDto, ControlRpcContract } from '@fabrika/control-contract'
7
+ import { OPERATIONS_ACTIONS } from '@fabrika/operations-contract/access'
8
+ import type { ActivityItem, DisplayFrame, EventBreadcrumb, EventDetail, EventException } from '@fabrika/operations-contract/operator'
9
+ import type {
10
+ OperationsEventDetailResponseDto,
11
+ OperationsHealthCheckDto,
12
+ OperationsHealthResponseDto,
13
+ OperationsIssueDetailResponseDto,
14
+ OperationsIssueListResponseDto,
15
+ OperationsIssueOccurrenceDto,
16
+ OperationsIssueSummaryDto,
17
+ OperationsReleaseListResponseDto,
18
+ OperationsReleaseSummaryDto,
19
+ OperationsSourceHealthDto,
20
+ OperationsSourceListResponseDto,
21
+ OperationsSourceSummaryDto,
22
+ } from '@fabrika/operations-contract/operator-api'
23
+ import type { OperationsIssueQuery, OperationsReleaseQuery, OperationsRpcContract } from '@fabrika/operations-contract/rpc'
24
+ import { z } from 'zod'
25
+ import { type ControlOAuthDependencies, CREDENTIAL_HELPER_VARIABLE } from './control-oauth.js'
26
+ import { controlTransport, MISSING_CONTROL_CREDENTIAL, withoutControlKey } from './control.js'
27
+ import { printable } from './data.js'
28
+
29
+ const USAGE = `fabrika operations — read Operations (errors, releases, health) from the command line
30
+
31
+ Usage:
32
+ fabrika operations issues [--app=<id>] [--env=<env>] [--service=<key>] [--status=<open|resolved|ignored>]
33
+ [--level=<fatal|error|warning|info>] [--since=<24h|7d|30d|all>] [--search=<text>]
34
+ [--sort=<recent|new|frequency>] [--limit=<1-100>] [--cursor=<cursor>] [--json]
35
+ fabrika operations issue <issueId> [--event=<occurrenceId>] [--json]
36
+ fabrika operations releases [--app=<id>] [--env=<env>] [--service=<key>] [--limit=<1-100>] [--cursor=<cursor>] [--json]
37
+ fabrika operations health [--app=<id>] [--env=<env>] [--service=<key>] [--json]
38
+
39
+ Every command is read-only. It reads what the console's Operations pages show, through the same API, with the
40
+ key's rights: a source (one service of an application environment) the key may not read is not listed, and an
41
+ issue of one answers \`not_found\`.
42
+
43
+ \`issues\` lists issues, the most recently seen first (\`--sort\` changes that), one row each:
44
+ <id> <status> <level> <events> <last seen> <app> <env> <service> <title>.
45
+ stderr carries the selection's counts by status (whatever \`--status\` says) and, when more issues match, the
46
+ \`--cursor\` that reads the next page with the same options.
47
+
48
+ \`issue\` prints one issue: its fields, its activity, its recent events (\`occurrence\` rows), and the latest
49
+ event in full: request, user, tags, each exception with its stack frames, and the breadcrumbs. \`--event\` shows
50
+ the event of another occurrence instead. The raw event is in \`--json\` only.
51
+
52
+ \`releases\` lists releases, newest first, one row each:
53
+ <id> <state> <artifacts> <release> <commit> <created at> <finished at> <new issues> <regressions> <app> <env> <service>.
54
+
55
+ \`health\` prints each source's telemetry health and its HTTP checks:
56
+ source <app> <env> <service> <telemetry state>
57
+ check <app> <env> <service> <path> <state> <observed at> <latency ms> <detail code> <consecutive failures>
58
+
59
+ \`--app\`, \`--env\` and \`--service\` select sources. On \`issues\` and \`releases\` they must select exactly one;
60
+ when they match several, the error lists them. Without them every source the key may read is included.
61
+
62
+ Issue titles, exception messages, breadcrumbs, tags and the raw event are text the application's users and code
63
+ wrote. They are printed as data with control characters removed; \`--json\` escapes them, C1 controls included,
64
+ as JSON strings.
65
+
66
+ stdout carries data only; notes and errors go to stderr. Times are ISO 8601 UTC, except a breadcrumb time the event
67
+ wrote as text. \`--json\` prints the parsed answer: of the procedure, or for \`issue\` \`{ issue, event }\`, the
68
+ issue and the event shown (\`null\` when none is stored).
69
+
70
+ Exit codes:
71
+ 0 the answer was printed (an empty list included)
72
+ 1 the call failed: Control or Operations unreachable, a server error, an unreadable answer, or a procedure this
73
+ installation's release does not offer
74
+ 2 usage: an unknown command or option, a bad value, or a selection that matches several sources
75
+ 3 the credential: neither FABRIKA_CONTROL_KEY nor FABRIKA_CONTROL_CREDENTIAL_HELPER is set, or it was refused,
76
+ or it does not hold \`operations.read\`
77
+ 4 not found: no such issue, event or source, or one the key may not read
78
+
79
+ The console origin takes either form:
80
+
81
+ --url=<origin> FABRIKA_CONTROL_URL
82
+
83
+ The credential is read from the ENVIRONMENT ONLY and has no flag; one of:
84
+
85
+ FABRIKA_CONTROL_KEY a \`px_\` key of the console app holding \`operations.read\`
86
+ FABRIKA_CONTROL_CREDENTIAL_HELPER the helper a \`fabrika control auth device\` grant is stored through
87
+ (any preset but \`create\` reads Operations; a list is empty where the
88
+ person who approved it holds no \`operations.read\`)
89
+
90
+ Mint a key narrowed to \`operations.read\` alone, with a short expiry: docs/reference/operations-errors.md,
91
+ "Reading Operations from the command line".
92
+ `
93
+
94
+ export const OPERATIONS_EXIT = { ok: 0, failed: 1, usage: 2, credential: 3, notFound: 4 } as const
95
+
96
+ type ExitCode = (typeof OPERATIONS_EXIT)[keyof typeof OPERATIONS_EXIT]
97
+
98
+ class OperationsCliError extends Error {
99
+ constructor(readonly exitCode: ExitCode, message: string) {
100
+ super(message)
101
+ }
102
+ }
103
+
104
+ type Environment = Readonly<Record<string, string | undefined>>
105
+
106
+ /** What the area reads and writes: the environment, the network, stdout and stderr. */
107
+ export interface OperationsIo {
108
+ readonly env: Environment
109
+ readonly fetch: RpcFetch
110
+ /** Replaces the credential helper, its lock and the clock; only a test passes it. */
111
+ readonly oauth?: ControlOAuthDependencies
112
+ readonly out: (text: string) => void
113
+ readonly err: (text: string) => void
114
+ }
115
+
116
+ const processIo = (): OperationsIo => ({
117
+ env: process.env,
118
+ fetch: (input, init) => fetch(input, init),
119
+ out: (text) => console.info(text),
120
+ err: (text) => console.warn(text),
121
+ })
122
+
123
+ // ── Arguments ─────────────────────────────────────────────────────────────────────────────────────────────────────
124
+
125
+ const COMMAND_OPTIONS: Readonly<Record<string, readonly string[]>> = {
126
+ issues: ['app', 'env', 'service', 'status', 'level', 'since', 'search', 'sort', 'limit', 'cursor'],
127
+ issue: ['event'],
128
+ releases: ['app', 'env', 'service', 'limit', 'cursor'],
129
+ health: ['app', 'env', 'service'],
130
+ }
131
+
132
+ interface Args {
133
+ readonly positional: readonly string[]
134
+ readonly options: ReadonlyMap<string, string>
135
+ readonly json: boolean
136
+ readonly url: string | undefined
137
+ }
138
+
139
+ const usageError = (message: string): OperationsCliError => new OperationsCliError(OPERATIONS_EXIT.usage, message)
140
+
141
+ const parseArgs = (command: string, argv: readonly string[]): Args => {
142
+ const allowed = COMMAND_OPTIONS[command] ?? []
143
+ const positional: string[] = []
144
+ const options = new Map<string, string>()
145
+ let json = false
146
+ let url: string | undefined
147
+ for (const arg of argv) {
148
+ if (arg === '--json') {
149
+ json = true
150
+ continue
151
+ }
152
+ if (!arg.startsWith('-')) {
153
+ positional.push(arg)
154
+ continue
155
+ }
156
+ const eq = arg.indexOf('=')
157
+ const name = eq === -1 ? arg.replace(/^-+/, '') : arg.slice(2, eq)
158
+ if (!arg.startsWith('--') || (name !== 'url' && !allowed.includes(name))) {
159
+ throw usageError(`Unknown option for \`operations ${command}\`: ${arg}`)
160
+ }
161
+ if (eq === -1 || arg.slice(eq + 1) === '') throw usageError(`Option --${name} needs a value: --${name}=<value>`)
162
+ if (name === 'url') url = arg.slice(eq + 1)
163
+ else options.set(name, arg.slice(eq + 1))
164
+ }
165
+ return { positional, options, json, url }
166
+ }
167
+
168
+ const oneOf = <T extends string>(args: Args, name: string, allowed: readonly T[]): T | undefined => {
169
+ const value = args.options.get(name)
170
+ if (value === undefined) return undefined
171
+ const match = allowed.find((candidate) => candidate === value)
172
+ if (match === undefined) throw usageError(`--${name} is one of ${allowed.join(', ')}, not "${value}"`)
173
+ return match
174
+ }
175
+
176
+ const pageLimit = (args: Args): number | undefined => {
177
+ const value = args.options.get('limit')
178
+ if (value === undefined) return undefined
179
+ const limit = Number(value)
180
+ if (!/^\d+$/.test(value) || limit < 1 || limit > 100) throw usageError(`--limit is a whole number from 1 to 100, not "${value}"`)
181
+ return limit
182
+ }
183
+
184
+ interface SourceFilter {
185
+ readonly app: string | undefined
186
+ readonly env: string | undefined
187
+ readonly service: string | undefined
188
+ }
189
+
190
+ const sourceFilter = (args: Args): SourceFilter => ({
191
+ app: args.options.get('app'),
192
+ env: args.options.get('env'),
193
+ service: args.options.get('service'),
194
+ })
195
+
196
+ const filters = (filter: SourceFilter): boolean => filter.app !== undefined || filter.env !== undefined || filter.service !== undefined
197
+
198
+ const selects = (filter: SourceFilter, source: OperationsSourceSummaryDto): boolean =>
199
+ (filter.app === undefined || source.appId === filter.app)
200
+ && (filter.env === undefined || source.environment === filter.env)
201
+ && (filter.service === undefined || source.serviceKey === filter.service)
202
+
203
+ const filterLabel = (filter: SourceFilter): string =>
204
+ [
205
+ filter.app === undefined ? null : `--app=${filter.app}`,
206
+ filter.env === undefined ? null : `--env=${filter.env}`,
207
+ filter.service === undefined
208
+ ? null
209
+ : `--service=${filter.service}`,
210
+ ]
211
+ .filter((part) => part !== null)
212
+ .join(' ')
213
+
214
+ const noPositional = (command: string, args: Args): void => {
215
+ if (args.positional.length > 0) throw usageError(`\`operations ${command}\` takes no argument: ${args.positional.join(' ')}`)
216
+ }
217
+
218
+ // ── Answers, parsed where they enter ──────────────────────────────────────────────────────────────────────────────
219
+ // Each schema projects the DTO's known fields: a field a newer Operations adds is dropped, never printed.
220
+
221
+ const unreadable = (what: string): OperationsCliError => new OperationsCliError(OPERATIONS_EXIT.failed, `Operations returned an unreadable ${what}`)
222
+
223
+ const parse = <T>(schema: z.ZodType<T, z.ZodTypeDef, unknown>, value: unknown, what: string): T => {
224
+ const parsed = schema.safeParse(value)
225
+ if (!parsed.success) throw unreadable(what)
226
+ return parsed.data
227
+ }
228
+
229
+ const time = z.number().finite()
230
+ const issueStatus = z.enum(['open', 'resolved', 'ignored'])
231
+
232
+ const sourceSchema: z.ZodType<OperationsSourceSummaryDto, z.ZodTypeDef, unknown> = z.object({
233
+ id: z.string(),
234
+ appId: z.string(),
235
+ environment: z.string(),
236
+ serviceKey: z.string(),
237
+ displayName: z.string(),
238
+ publicOrigin: z.string().nullable(),
239
+ enabled: z.boolean(),
240
+ })
241
+
242
+ const sourceListSchema: z.ZodType<OperationsSourceListResponseDto, z.ZodTypeDef, unknown> = z.object({ items: z.array(sourceSchema) })
243
+
244
+ const issueSummaryFields = {
245
+ id: z.string(),
246
+ source: sourceSchema,
247
+ title: z.string(),
248
+ culprit: z.string().nullable(),
249
+ level: z.string(),
250
+ status: issueStatus,
251
+ assignedTo: z.object({ id: z.string(), label: z.string().nullable() }).nullable(),
252
+ regressedAt: time.nullable(),
253
+ firstSeen: time,
254
+ lastSeen: time,
255
+ count: z.number().int().nonnegative(),
256
+ trend: z.array(z.number()),
257
+ }
258
+
259
+ const issueSummarySchema: z.ZodType<OperationsIssueSummaryDto, z.ZodTypeDef, unknown> = z.object(issueSummaryFields)
260
+
261
+ const issueListSchema: z.ZodType<OperationsIssueListResponseDto, z.ZodTypeDef, unknown> = z.object({
262
+ items: z.array(issueSummarySchema),
263
+ nextCursor: z.string().nullable(),
264
+ summary: z.object({
265
+ total: z.number().int().nonnegative(),
266
+ open: z.number().int().nonnegative(),
267
+ resolved: z.number().int().nonnegative(),
268
+ ignored: z.number().int().nonnegative(),
269
+ }),
270
+ })
271
+
272
+ const occurrenceSchema: z.ZodType<OperationsIssueOccurrenceDto, z.ZodTypeDef, unknown> = z.object({
273
+ id: z.string(),
274
+ eventId: z.string(),
275
+ receivedAt: time,
276
+ release: z.string().nullable(),
277
+ })
278
+
279
+ const activitySchema: z.ZodType<ActivityItem, z.ZodTypeDef, unknown> = z.object({
280
+ id: z.string(),
281
+ kind: z.enum(['comment', 'status', 'assigned', 'regressed', 'snoozed', 'unsnoozed', 'merged']),
282
+ actorLabel: z.string().nullable(),
283
+ data: z.record(z.unknown()).nullable(),
284
+ at: time,
285
+ })
286
+
287
+ const issueDetailSchema: z.ZodType<OperationsIssueDetailResponseDto, z.ZodTypeDef, unknown> = z.object({
288
+ issue: z.object({
289
+ ...issueSummaryFields,
290
+ snoozeUntil: time.nullable(),
291
+ snoozeUntilCount: z.number().nullable(),
292
+ resolvedInRelease: z.object({ id: z.string(), name: z.string() }).nullable(),
293
+ mergedIntoIssueId: z.string().nullable(),
294
+ activity: z.array(activitySchema),
295
+ latestOccurrence: occurrenceSchema.nullable(),
296
+ occurrences: z.array(occurrenceSchema),
297
+ occurrencesNextCursor: z.string().nullable(),
298
+ }),
299
+ })
300
+
301
+ const frameSchema: z.ZodType<DisplayFrame, z.ZodTypeDef, unknown> = z.object({
302
+ file: z.string(),
303
+ function: z.string().nullable(),
304
+ line: z.number().nullable(),
305
+ column: z.number().nullable(),
306
+ inApp: z.boolean(),
307
+ resolved: z.boolean(),
308
+ source: z.object({ lines: z.array(z.string()), errorIndex: z.number(), startLine: z.number() }).optional(),
309
+ })
310
+
311
+ const exceptionSchema: z.ZodType<EventException, z.ZodTypeDef, unknown> = z.object({
312
+ type: z.string().nullable(),
313
+ value: z.string().nullable(),
314
+ handled: z.boolean().nullable(),
315
+ frames: z.array(frameSchema),
316
+ })
317
+
318
+ const breadcrumbSchema: z.ZodType<EventBreadcrumb, z.ZodTypeDef, unknown> = z.object({
319
+ timestamp: z.union([z.number(), z.string()]).optional(),
320
+ type: z.string().optional(),
321
+ category: z.string().optional(),
322
+ level: z.string().optional(),
323
+ message: z.string().optional(),
324
+ })
325
+
326
+ const eventDetailSchema: z.ZodType<EventDetail, z.ZodTypeDef, unknown> = z.object({
327
+ eventId: z.string().nullable(),
328
+ platform: z.string().nullable(),
329
+ release: z.string().nullable(),
330
+ environment: z.string().nullable(),
331
+ tags: z.array(z.object({ key: z.string(), value: z.string() })),
332
+ request: z.object({ url: z.string().nullable(), method: z.string().nullable() }).nullable(),
333
+ user: z.object({ id: z.string().nullable(), email: z.string().nullable(), username: z.string().nullable() }).nullable(),
334
+ breadcrumbs: z.array(breadcrumbSchema),
335
+ runtime: z.string().nullable(),
336
+ os: z.string().nullable(),
337
+ serverName: z.string().nullable(),
338
+ traceId: z.string().nullable(),
339
+ exceptions: z.array(exceptionSchema),
340
+ rawEvent: z.string(),
341
+ })
342
+
343
+ const eventSchema: z.ZodType<OperationsEventDetailResponseDto, z.ZodTypeDef, unknown> = z.object({
344
+ occurrenceId: z.string(),
345
+ receivedAt: time,
346
+ detail: eventDetailSchema,
347
+ })
348
+
349
+ const releaseSchema: z.ZodType<OperationsReleaseSummaryDto, z.ZodTypeDef, unknown> = z.object({
350
+ id: z.string(),
351
+ source: sourceSchema,
352
+ runId: z.string(),
353
+ commitSha: z.string(),
354
+ state: z.string(),
355
+ artifactState: z.enum(['pending', 'complete', 'incomplete', 'not_applicable']),
356
+ releaseName: z.string(),
357
+ createdAt: time,
358
+ finishedAt: time.nullable(),
359
+ newIssueCount: z.number().int().nonnegative(),
360
+ regressionCount: z.number().int().nonnegative(),
361
+ })
362
+
363
+ const releaseListSchema: z.ZodType<OperationsReleaseListResponseDto, z.ZodTypeDef, unknown> = z.object({
364
+ items: z.array(releaseSchema),
365
+ nextCursor: z.string().nullable(),
366
+ })
367
+
368
+ const healthState = z.enum(['healthy', 'degraded', 'failed', 'stale', 'unavailable'])
369
+
370
+ const healthCheckSchema: z.ZodType<OperationsHealthCheckDto, z.ZodTypeDef, unknown> = z.object({
371
+ id: z.string(),
372
+ sourceId: z.string(),
373
+ path: z.string(),
374
+ enabled: z.boolean(),
375
+ intervalMs: z.number(),
376
+ timeoutMs: z.number(),
377
+ expectedStatus: z.number(),
378
+ failureThreshold: z.number(),
379
+ recoveryThreshold: z.number(),
380
+ staleAfterMs: z.number(),
381
+ current: z.object({
382
+ state: z.enum(['healthy', 'degraded', 'failed', 'stale']),
383
+ observedAt: time,
384
+ latencyMs: z.number().nullable(),
385
+ detailCode: z.string(),
386
+ consecutiveFailures: z.number().int().nonnegative(),
387
+ consecutiveSuccesses: z.number().int().nonnegative(),
388
+ }).nullable(),
389
+ history: z.array(z.object({
390
+ id: z.string(),
391
+ state: healthState,
392
+ observedAt: time,
393
+ latencyMs: z.number().nullable(),
394
+ detailCode: z.string().nullable(),
395
+ successful: z.boolean(),
396
+ statusCode: z.number().nullable(),
397
+ })),
398
+ })
399
+
400
+ const sourceHealthSchema: z.ZodType<OperationsSourceHealthDto, z.ZodTypeDef, unknown> = z.object({
401
+ source: sourceSchema,
402
+ httpChecks: z.array(healthCheckSchema),
403
+ telemetryState: healthState,
404
+ })
405
+
406
+ const healthSchema: z.ZodType<OperationsHealthResponseDto, z.ZodTypeDef, unknown> = z.object({ sources: z.array(sourceHealthSchema) })
407
+
408
+ const consoleAccessSchema: z.ZodType<ConsoleAccessDto, z.ZodTypeDef, unknown> = z.object({
409
+ principal: z.object({ id: z.string(), label: z.string() }).nullable(),
410
+ global: z.array(z.string()),
411
+ scopes: z.array(z.object({ type: z.string(), value: z.string(), actions: z.array(z.string()) })),
412
+ })
413
+
414
+ // ── Output ────────────────────────────────────────────────────────────────────────────────────────────────────────
415
+
416
+ /** Operations' times are Unix milliseconds. */
417
+ const iso = (milliseconds: number): string => new Date(milliseconds).toISOString()
418
+
419
+ const isoOrDash = (milliseconds: number | null): string => milliseconds === null ? '-' : iso(milliseconds)
420
+
421
+ /** One cell of a row: untrusted text loses its control characters, and a tab or line break would split the row. */
422
+ const cell = (value: string | number | boolean | null | undefined): string => {
423
+ if (value === null || value === undefined || value === '') return '-'
424
+ return printable(String(value)).replace(/[\t\n]+/g, ' ')
425
+ }
426
+
427
+ const row = (...cells: readonly (string | number | boolean | null | undefined)[]): string => cells.map(cell).join('\t')
428
+
429
+ const sourceCells = (source: OperationsSourceSummaryDto): string[] => [source.appId, source.environment, source.serviceKey]
430
+
431
+ const issueRow = (issue: OperationsIssueSummaryDto): string =>
432
+ row(issue.id, issue.status, issue.level, issue.count, iso(issue.lastSeen), ...sourceCells(issue.source), issue.title)
433
+
434
+ const releaseRow = (release: OperationsReleaseSummaryDto): string =>
435
+ row(
436
+ release.id,
437
+ release.state,
438
+ release.artifactState,
439
+ release.releaseName,
440
+ release.commitSha,
441
+ iso(release.createdAt),
442
+ isoOrDash(release.finishedAt),
443
+ release.newIssueCount,
444
+ release.regressionCount,
445
+ ...sourceCells(release.source),
446
+ )
447
+
448
+ const checkState = (check: OperationsHealthCheckDto): string => !check.enabled ? 'disabled' : check.current?.state ?? 'pending'
449
+
450
+ const healthLines = (health: OperationsSourceHealthDto): string[] => [
451
+ row('source', ...sourceCells(health.source), health.telemetryState),
452
+ ...health.httpChecks.map((check) =>
453
+ row(
454
+ 'check',
455
+ ...sourceCells(health.source),
456
+ check.path,
457
+ checkState(check),
458
+ isoOrDash(check.current?.observedAt ?? null),
459
+ check.current?.latencyMs,
460
+ check.current?.detailCode,
461
+ check.current?.consecutiveFailures ?? 0,
462
+ )
463
+ ),
464
+ ]
465
+
466
+ /** Sentry gives a breadcrumb's time as Unix seconds, or as text the event wrote, which prints as given. */
467
+ const breadcrumbTime = (crumb: EventBreadcrumb): string | undefined =>
468
+ typeof crumb.timestamp === 'number' && Number.isFinite(crumb.timestamp) ? iso(crumb.timestamp * 1000) : crumb.timestamp?.toString()
469
+
470
+ const frameLocation = (frame: DisplayFrame): string => [frame.file, frame.line, frame.column].filter((part) => part !== null).join(':')
471
+
472
+ const eventLines = (event: OperationsEventDetailResponseDto): string[] => {
473
+ const detail = event.detail
474
+ return [
475
+ row('event', event.occurrenceId, iso(event.receivedAt), detail.eventId),
476
+ row('release', detail.release),
477
+ row('environment', detail.environment),
478
+ row('platform', detail.platform),
479
+ row('runtime', detail.runtime),
480
+ row('os', detail.os),
481
+ row('server', detail.serverName),
482
+ row('trace', detail.traceId),
483
+ ...(detail.request === null ? [] : [row('request', detail.request.method, detail.request.url)]),
484
+ ...(detail.user === null ? [] : [row('user', detail.user.id, detail.user.username, detail.user.email)]),
485
+ ...detail.tags.map((tag) => row('tag', tag.key, tag.value)),
486
+ ...detail.exceptions.flatMap((exception) => [
487
+ row('exception', exception.type, exception.handled === null ? null : exception.handled ? 'handled' : 'unhandled', exception.value),
488
+ ...exception.frames.map((frame) => row('frame', frameLocation(frame), frame.function, frame.inApp ? 'app' : 'library')),
489
+ ]),
490
+ ...detail.breadcrumbs.map((crumb) => row('breadcrumb', breadcrumbTime(crumb), crumb.level, crumb.category ?? crumb.type, crumb.message)),
491
+ ]
492
+ }
493
+
494
+ const issueLines = (detail: OperationsIssueDetailResponseDto, event: OperationsEventDetailResponseDto | null): string[] => {
495
+ const issue = detail.issue
496
+ return [
497
+ row('id', issue.id),
498
+ row('title', issue.title),
499
+ row('culprit', issue.culprit),
500
+ row('status', issue.status),
501
+ row('level', issue.level),
502
+ row('source', ...sourceCells(issue.source)),
503
+ row('events', issue.count),
504
+ row('firstSeen', iso(issue.firstSeen)),
505
+ row('lastSeen', iso(issue.lastSeen)),
506
+ row('regressedAt', isoOrDash(issue.regressedAt)),
507
+ row('assignedTo', issue.assignedTo?.label ?? issue.assignedTo?.id),
508
+ row('snoozeUntil', isoOrDash(issue.snoozeUntil)),
509
+ row('snoozeUntilCount', issue.snoozeUntilCount),
510
+ row('resolvedInRelease', issue.resolvedInRelease?.name),
511
+ row('mergedInto', issue.mergedIntoIssueId),
512
+ ...issue.activity.map((item) => row('activity', iso(item.at), item.kind, item.actorLabel, item.data === null ? null : JSON.stringify(item.data))),
513
+ ...issue.occurrences.map((occurrence) => row('occurrence', occurrence.id, iso(occurrence.receivedAt), occurrence.eventId, occurrence.release)),
514
+ ...(event === null ? [] : eventLines(event)),
515
+ ]
516
+ }
517
+
518
+ // ── Calls ─────────────────────────────────────────────────────────────────────────────────────────────────────────
519
+
520
+ interface Clients {
521
+ readonly operations: InferRpcClient<OperationsRpcContract>
522
+ readonly control: InferRpcClient<ControlRpcContract>
523
+ /** The credential is a person's device grant, whose Operations token is its own. */
524
+ readonly grant: boolean
525
+ }
526
+
527
+ const connect = (args: Args, io: OperationsIo): Clients => {
528
+ const given = (name: string): boolean => (io.env[name]?.trim() ?? '') !== ''
529
+ if (!given('FABRIKA_CONTROL_KEY') && !given(CREDENTIAL_HELPER_VARIABLE)) {
530
+ throw new OperationsCliError(OPERATIONS_EXIT.credential, MISSING_CONTROL_CREDENTIAL)
531
+ }
532
+ let transport: ReturnType<typeof controlTransport>
533
+ try {
534
+ transport = controlTransport(args.url, io.env, io.fetch, io.oauth)
535
+ } catch (error) {
536
+ throw usageError(error instanceof Error ? error.message : String(error))
537
+ }
538
+ return {
539
+ operations: createRpcClient<OperationsRpcContract>({ baseUrl: `${transport.origin}/operations/api/rpc`, fetch: transport.fetch }),
540
+ control: createRpcClient<ControlRpcContract>({ baseUrl: `${transport.origin}/api/rpc`, fetch: transport.fetch }),
541
+ grant: transport.grant,
542
+ }
543
+ }
544
+
545
+ /**
546
+ * Operations answers a key without `operations.read` with empty lists, as it answers a key scoped elsewhere. The
547
+ * console's own navigation asks Control which actions the caller holds; so does this, to tell the two apart.
548
+ */
549
+ const requireRead = async (clients: Clients): Promise<void> => {
550
+ // A grant's token for Control holds no Operations action, so Control's answer cannot tell. Its Operations token holds
551
+ // `operations.read` where the person does; elsewhere a list is empty, as the help says.
552
+ if (clients.grant) return
553
+ const access = parse(consoleAccessSchema, await clients.control.consoleAccess(), 'console access')
554
+ const read = OPERATIONS_ACTIONS.READ
555
+ if (access.global.includes(read) || access.scopes.some((scope) => scope.actions.includes(read))) return
556
+ throw new OperationsCliError(
557
+ OPERATIONS_EXIT.credential,
558
+ `FABRIKA_CONTROL_KEY does not hold ${read} in any scope. Use a key of the console app narrowed to ${read}; see \`fabrika operations --help\`.`,
559
+ )
560
+ }
561
+
562
+ /** The one source `filter` selects, or none when it selects nothing in particular. */
563
+ const selectedSource = async (clients: Clients, filter: SourceFilter): Promise<OperationsSourceSummaryDto | undefined> => {
564
+ if (!filters(filter)) return undefined
565
+ const sources = parse(sourceListSchema, await clients.operations.sources(), 'source list').items.filter((source) => selects(filter, source))
566
+ const [only, ...others] = sources
567
+ if (only === undefined) {
568
+ throw new OperationsCliError(OPERATIONS_EXIT.notFound, `No Operations source matches ${filterLabel(filter)}, or the key may not read it`)
569
+ }
570
+ if (others.length > 0) {
571
+ const listed = sources.map((source) => ` ${row(...sourceCells(source))}`).join('\n')
572
+ throw usageError(`${filterLabel(filter)} matches ${sources.length} sources; add --env or --service to pick one:\n${listed}`)
573
+ }
574
+ return only
575
+ }
576
+
577
+ /**
578
+ * JSON whose text cannot drive a terminal: `JSON.stringify` escapes C0 controls only, so DEL, the C1 controls (U+009B
579
+ * opens a sequence like ESC [) and the line separators are escaped too. They can occur only inside strings.
580
+ */
581
+ const escapedJson = (value: unknown): string =>
582
+ JSON.stringify(value, null, 2).replace(/[\u007f-\u009f\u2028\u2029]/g, (char) => `\\u${char.charCodeAt(0).toString(16).padStart(4, '0')}`)
583
+
584
+ const emit = (args: Args, io: OperationsIo, result: unknown, lines: () => readonly string[]): void => {
585
+ if (args.json) {
586
+ io.out(escapedJson(result))
587
+ return
588
+ }
589
+ const text = lines()
590
+ if (text.length > 0) io.out(text.join('\n'))
591
+ }
592
+
593
+ const note = (io: OperationsIo, text: string): void => io.err(printable(text))
594
+
595
+ const runIssues = async (args: Args, io: OperationsIo): Promise<void> => {
596
+ noPositional('issues', args)
597
+ const status = oneOf(args, 'status', ['open', 'resolved', 'ignored'] as const)
598
+ const level = oneOf(args, 'level', ['fatal', 'error', 'warning', 'info'] as const)
599
+ const window = oneOf(args, 'since', ['24h', '7d', '30d', 'all'] as const)
600
+ const sort = oneOf(args, 'sort', ['recent', 'new', 'frequency'] as const)
601
+ const limit = pageLimit(args)
602
+ const search = args.options.get('search')
603
+ const cursor = args.options.get('cursor')
604
+ const clients = connect(args, io)
605
+ await requireRead(clients)
606
+ const source = await selectedSource(clients, sourceFilter(args))
607
+ const query: OperationsIssueQuery = {
608
+ ...(source === undefined ? {} : { sourceId: source.id }),
609
+ ...(status === undefined ? {} : { status }),
610
+ ...(level === undefined ? {} : { level }),
611
+ ...(window === undefined ? {} : { window }),
612
+ ...(search === undefined ? {} : { query: search }),
613
+ ...(sort === undefined ? {} : { sort }),
614
+ ...(cursor === undefined ? {} : { cursor }),
615
+ ...(limit === undefined ? {} : { limit }),
616
+ }
617
+ const page = parse(issueListSchema, await clients.operations.issues(query), 'issue list')
618
+ const { summary } = page
619
+ note(io, `${summary.total} issues in this selection, any status: ${summary.open} open, ${summary.resolved} resolved, ${summary.ignored} ignored`)
620
+ if (page.nextCursor !== null) note(io, `more issues match; the next page: the same options and --cursor=${page.nextCursor}`)
621
+ emit(args, io, page, () => page.items.map(issueRow))
622
+ }
623
+
624
+ const runIssue = async (args: Args, io: OperationsIo): Promise<void> => {
625
+ const [issueId, ...extra] = args.positional
626
+ if (issueId === undefined || issueId.trim() === '' || extra.length > 0) {
627
+ throw usageError('Usage: fabrika operations issue <issueId> [--event=<occurrenceId>] [--json]')
628
+ }
629
+ const occurrenceId = args.options.get('event')
630
+ const clients = connect(args, io)
631
+ await requireRead(clients)
632
+ const detail = parse(issueDetailSchema, await clients.operations.issue({ issueId }), 'issue')
633
+ let event: OperationsEventDetailResponseDto | null = null
634
+ if (occurrenceId !== undefined) {
635
+ event = parse(eventSchema, await clients.operations.event({ issueId, occurrenceId }), 'event')
636
+ } else if (detail.issue.latestOccurrence !== null) {
637
+ try {
638
+ event = parse(eventSchema, await clients.operations.latestEvent({ issueId }), 'event')
639
+ } catch (error) {
640
+ // The issue was readable a moment ago, so a missing latest event is a payload no longer stored.
641
+ if (!(error instanceof RpcError) || error.httpStatus !== 404) throw error
642
+ note(io, 'the latest event is no longer stored')
643
+ }
644
+ }
645
+ if (detail.issue.occurrencesNextCursor !== null) {
646
+ note(io, `showing the ${detail.issue.occurrences.length} most recent events of ${detail.issue.count}`)
647
+ }
648
+ emit(args, io, { ...detail, event }, () => issueLines(detail, event))
649
+ }
650
+
651
+ const runReleases = async (args: Args, io: OperationsIo): Promise<void> => {
652
+ noPositional('releases', args)
653
+ const limit = pageLimit(args)
654
+ const cursor = args.options.get('cursor')
655
+ const clients = connect(args, io)
656
+ await requireRead(clients)
657
+ const source = await selectedSource(clients, sourceFilter(args))
658
+ const query: OperationsReleaseQuery = {
659
+ ...(source === undefined ? {} : { sourceId: source.id }),
660
+ ...(cursor === undefined ? {} : { cursor }),
661
+ ...(limit === undefined ? {} : { limit }),
662
+ }
663
+ const page = parse(releaseListSchema, await clients.operations.releases(query), 'release list')
664
+ if (page.items.length === 0) note(io, 'no releases')
665
+ if (page.nextCursor !== null) note(io, `more releases exist; the next page: the same options and --cursor=${page.nextCursor}`)
666
+ emit(args, io, page, () => page.items.map(releaseRow))
667
+ }
668
+
669
+ const runHealth = async (args: Args, io: OperationsIo): Promise<void> => {
670
+ noPositional('health', args)
671
+ const filter = sourceFilter(args)
672
+ const clients = connect(args, io)
673
+ await requireRead(clients)
674
+ const health = parse(healthSchema, await clients.operations.health(), 'health answer')
675
+ const sources = health.sources.filter((entry) => selects(filter, entry.source))
676
+ if (sources.length === 0) {
677
+ if (filters(filter)) {
678
+ throw new OperationsCliError(OPERATIONS_EXIT.notFound, `No Operations source matches ${filterLabel(filter)}, or the key may not read it`)
679
+ }
680
+ note(io, 'no Operations source is visible to this key')
681
+ }
682
+ emit(args, io, { sources }, () => sources.flatMap(healthLines))
683
+ }
684
+
685
+ const COMMANDS: Readonly<Record<string, (args: Args, io: OperationsIo) => Promise<void>>> = {
686
+ issues: runIssues,
687
+ issue: runIssue,
688
+ releases: runReleases,
689
+ health: runHealth,
690
+ }
691
+
692
+ /** An RPC refusal mapped to its exit code; the type and message are the server's, cleaned before they print. */
693
+ const rpcFailure = (error: RpcError): OperationsCliError => {
694
+ const said = `${error.type}: ${error.message}`
695
+ // Not offered by this installation's release: a definite answer, not a missing record.
696
+ if (error.type === 'method_not_found') {
697
+ return new OperationsCliError(
698
+ OPERATIONS_EXIT.failed,
699
+ `This installation's release does not offer the call; retrying will not change that — ${said}`,
700
+ )
701
+ }
702
+ // The device grant's own refusal (no grant stored, expired, not covering Operations): its message says what to do.
703
+ if (error.type === 'credential') return new OperationsCliError(OPERATIONS_EXIT.credential, error.message)
704
+ if (error.httpStatus === 401) {
705
+ return new OperationsCliError(OPERATIONS_EXIT.credential, `The console refused FABRIKA_CONTROL_KEY (unknown, expired or revoked) — ${said}`)
706
+ }
707
+ if (error.httpStatus === 403) return new OperationsCliError(OPERATIONS_EXIT.credential, `FABRIKA_CONTROL_KEY may not make this call — ${said}`)
708
+ if (error.httpStatus === 404 || error.type === 'not_found') {
709
+ return new OperationsCliError(OPERATIONS_EXIT.notFound, `Not found, or the key may not read it — ${said}`)
710
+ }
711
+ if (error.httpStatus === 400) return usageError(said)
712
+ return new OperationsCliError(OPERATIONS_EXIT.failed, said)
713
+ }
714
+
715
+ /** Runs one command and returns its exit code; every diagnostic goes to stderr with the key cut out. */
716
+ export const runOperationsCli = async (command: string | undefined, argv: readonly string[], io: OperationsIo = processIo()): Promise<number> => {
717
+ if (command === undefined) {
718
+ io.out(USAGE)
719
+ return OPERATIONS_EXIT.ok
720
+ }
721
+ try {
722
+ const run = COMMANDS[command]
723
+ if (run === undefined) throw usageError(`Unknown operations command: ${command}\n\n${USAGE}`)
724
+ await run(parseArgs(command, argv), io)
725
+ return OPERATIONS_EXIT.ok
726
+ } catch (error) {
727
+ const failure = error instanceof OperationsCliError
728
+ ? error
729
+ : error instanceof RpcError
730
+ ? rpcFailure(error)
731
+ : new OperationsCliError(OPERATIONS_EXIT.failed, error instanceof Error ? error.message : String(error))
732
+ io.err(`fabrika: ${printable(withoutControlKey(failure.message, io.env))}`)
733
+ return failure.exitCode
734
+ }
735
+ }
736
+
737
+ export { USAGE as OPERATIONS_USAGE }