@fabrika/cli 0.9.0-dev.2 → 0.9.0-dev.20

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