@raidiant/notifai 0.3.0 → 0.4.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 (80) hide show
  1. package/README.md +20 -4
  2. package/dist/atomic-file.d.ts +4 -0
  3. package/dist/atomic-file.js +60 -10
  4. package/dist/atomic-file.js.map +1 -1
  5. package/dist/client.d.ts +25 -2
  6. package/dist/client.js +45 -1
  7. package/dist/client.js.map +1 -1
  8. package/dist/commands.d.ts +56 -7
  9. package/dist/commands.js +980 -318
  10. package/dist/commands.js.map +1 -1
  11. package/dist/config-schema.d.ts +1 -1
  12. package/dist/config-schema.js +46 -8
  13. package/dist/config-schema.js.map +1 -1
  14. package/dist/config.d.ts +38 -3
  15. package/dist/config.js +61 -14
  16. package/dist/config.js.map +1 -1
  17. package/dist/file-lock.d.ts +26 -0
  18. package/dist/file-lock.js +268 -0
  19. package/dist/file-lock.js.map +1 -0
  20. package/dist/harnesses.d.ts +28 -0
  21. package/dist/harnesses.js +40 -0
  22. package/dist/harnesses.js.map +1 -0
  23. package/dist/hook-adapter.d.ts +27 -0
  24. package/dist/hook-adapter.js +188 -0
  25. package/dist/hook-adapter.js.map +1 -0
  26. package/dist/hook-input.d.ts +10 -0
  27. package/dist/hook-input.js +64 -0
  28. package/dist/hook-input.js.map +1 -0
  29. package/dist/hooks.d.ts +66 -10
  30. package/dist/hooks.js +751 -276
  31. package/dist/hooks.js.map +1 -1
  32. package/dist/install-hooks.d.ts +40 -16
  33. package/dist/install-hooks.js +217 -73
  34. package/dist/install-hooks.js.map +1 -1
  35. package/dist/interactive.d.ts +1 -1
  36. package/dist/interactive.js +3 -3
  37. package/dist/interactive.js.map +1 -1
  38. package/dist/logging.d.ts +142 -0
  39. package/dist/logging.js +533 -0
  40. package/dist/logging.js.map +1 -0
  41. package/dist/main.js +97 -36
  42. package/dist/main.js.map +1 -1
  43. package/dist/opencode-plugin.d.ts +7 -7
  44. package/dist/opencode-plugin.js +12 -13
  45. package/dist/opencode-plugin.js.map +1 -1
  46. package/dist/ui/config-view.js +3 -0
  47. package/dist/ui/config-view.js.map +1 -1
  48. package/dist/ui/theme.d.ts +1 -1
  49. package/package.json +3 -2
  50. package/src/atomic-file.ts +86 -7
  51. package/src/client.test.ts +12 -0
  52. package/src/client.ts +72 -4
  53. package/src/commands.test.ts +891 -43
  54. package/src/commands.ts +1133 -332
  55. package/src/config-schema.ts +51 -9
  56. package/src/config.test.ts +6 -5
  57. package/src/config.ts +85 -16
  58. package/src/file-lock-process-worker.test.ts +64 -0
  59. package/src/file-lock.test.ts +279 -0
  60. package/src/file-lock.ts +318 -0
  61. package/src/harnesses.test.ts +48 -0
  62. package/src/harnesses.ts +59 -0
  63. package/src/hook-adapter.test.ts +187 -0
  64. package/src/hook-adapter.ts +212 -0
  65. package/src/hook-input.test.ts +39 -0
  66. package/src/hook-input.ts +72 -0
  67. package/src/hooks.test.ts +1318 -240
  68. package/src/hooks.ts +1046 -296
  69. package/src/install-hooks.test.ts +90 -41
  70. package/src/install-hooks.ts +259 -74
  71. package/src/interactive.ts +3 -3
  72. package/src/logging-process-worker.test.ts +39 -0
  73. package/src/logging.test.ts +453 -0
  74. package/src/logging.ts +639 -0
  75. package/src/main.ts +113 -32
  76. package/src/opencode-plugin.ts +15 -16
  77. package/src/session-end-log-lock-worker.test.ts +35 -0
  78. package/src/skill.test.ts +11 -0
  79. package/src/ui/config-view.test.ts +4 -2
  80. package/src/ui/config-view.ts +3 -0
package/src/logging.ts ADDED
@@ -0,0 +1,639 @@
1
+ /**
2
+ * Local, agent-facing logs.
3
+ *
4
+ * Most of what this CLI does happens where nobody is looking. A harness hook
5
+ * runs headless in front of every prompt; its stderr is swallowed by the
6
+ * harness, and its most consequential act is usually a decision to do nothing —
7
+ * the question stayed in the terminal, and no line anywhere says why. An agent
8
+ * asked afterwards "did my question reach the phone?" has had no way to find
9
+ * out. This is the record that answers that.
10
+ *
11
+ * Written for an agent to read, which is a different job from writing for a
12
+ * person:
13
+ *
14
+ * - One JSON object per line, so `grep`, `jq`, and a plain read all work
15
+ * without a parser and without reading the file whole.
16
+ * - A closed event vocabulary, so a filter written once keeps matching.
17
+ * - A run id stamped on every line of one invocation, so "what happened
18
+ * during that command" is a single query rather than a reconstruction.
19
+ * - Retrieval bounded by default (`notifai logs`), because an unbounded dump
20
+ * into a context window is worse than no log at all.
21
+ *
22
+ * Local only. Nothing here is uploaded, and nothing in the record is shaped for
23
+ * a server. If submitting a log for debugging is ever added it will be an
24
+ * explicit, separate act by the user.
25
+ *
26
+ * ## Concurrency
27
+ *
28
+ * Several processes share one file: the hook fires per turn, `send` and `ask`
29
+ * fire whenever an agent calls them, and worktrees run in parallel. Every write
30
+ * takes one short cross-process lock around the shared size check, any rotation,
31
+ * and the append. Without that transaction, several writers can all observe the
32
+ * same remaining budget and independently push the file past its configured cap.
33
+ *
34
+ * The record itself still lands in one `O_APPEND` write. That keeps a line whole
35
+ * if an uncooperating process touches the file, while the lock makes cooperating
36
+ * Notifai processes agree which inode owns the record and when it must rotate.
37
+ *
38
+ * ## Failure
39
+ *
40
+ * Logging may never break the CLI. A read-only home, a full disk, or a
41
+ * directory someone replaced with a file all end the same way: logging switches
42
+ * itself off for the rest of the process and the command carries on. A
43
+ * diagnostic that can take down the thing it observes is not a diagnostic.
44
+ */
45
+ import { randomBytes } from 'node:crypto'
46
+ import { appendFileSync, mkdirSync, readFileSync, readdirSync, renameSync, statSync, unlinkSync } from 'node:fs'
47
+ import path from 'node:path'
48
+ import {
49
+ CONFIG_KEYS,
50
+ LOG_LEVELS,
51
+ loadConfig,
52
+ stateDir,
53
+ type CliConfig,
54
+ type LogLevel,
55
+ } from './config.js'
56
+ import { withFileLock } from './file-lock.js'
57
+
58
+ /** Bumped when the record shape changes in a way a reader must notice. */
59
+ export const LOG_SCHEMA_VERSION = 1
60
+
61
+ export { LOG_LEVELS, type LogLevel }
62
+ export type RecordLevel = Exclude<LogLevel, 'off'>
63
+
64
+ const LEVEL_RANK: Record<LogLevel, number> = { off: 0, error: 1, info: 2, debug: 3 }
65
+
66
+ /**
67
+ * The closed vocabulary. A filter is only worth writing if it keeps matching,
68
+ * so these names are a contract: add to the list rather than rephrasing an
69
+ * existing one, and keep each event answering exactly one question.
70
+ */
71
+ export const LOG_EVENTS = [
72
+ /** A CLI invocation began: which command, which arguments, which version. */
73
+ 'cli.start',
74
+ /** It ended: exit code and how long it took. */
75
+ 'cli.end',
76
+ /** A command failed. Carries the server's own code and rejected paths. */
77
+ 'cli.error',
78
+ /** Which config layer won, for the keys that changed the outcome. */
79
+ 'config.resolved',
80
+ /** One HTTP call to the service: method, path, status, duration. */
81
+ 'http.call',
82
+ /** A notification was accepted by the service. */
83
+ 'send.submitted',
84
+ /** What became of it per device. */
85
+ 'send.outcome',
86
+ /** `notifai ask` registered a question for the turn-end hook. */
87
+ 'ask.registered',
88
+ /** An answer came back from a device. */
89
+ 'reply.received',
90
+ /** A harness hook started. */
91
+ 'hook.start',
92
+ /** A hook decided whether a question may leave the terminal, and why. */
93
+ 'hook.gate',
94
+ /** A question reached the user's devices. */
95
+ 'hook.pushed',
96
+ /** The hook handed an answer back to the agent. */
97
+ 'hook.answer',
98
+ /** The hook finished, with or without a decision. */
99
+ 'hook.end',
100
+ /** The active file was rotated. Explains a gap to anyone reading backwards. */
101
+ 'log.rotated',
102
+ ] as const
103
+ export type LogEvent = (typeof LOG_EVENTS)[number]
104
+
105
+ export interface LogRecord {
106
+ /** Schema version. On every line, so a line pulled out by grep still parses. */
107
+ v: number
108
+ /** ISO 8601, UTC. */
109
+ ts: string
110
+ level: RecordLevel
111
+ event: LogEvent
112
+ /** Correlation id for one CLI invocation. */
113
+ run: string
114
+ /** The command path, e.g. `send` or `config set`. */
115
+ cmd: string
116
+ pid: number
117
+ project?: string
118
+ session?: string
119
+ data?: Record<string, unknown>
120
+ }
121
+
122
+ // ---------------------------------------------------------------------------
123
+ // Limits
124
+ // ---------------------------------------------------------------------------
125
+
126
+ /**
127
+ * A record must fit in one write to stay atomic against other processes, and
128
+ * must fit in a reader's context window to be worth writing at all. Both point
129
+ * at the same answer: keep them small and truncate loudly.
130
+ */
131
+ const MAX_RECORD_BYTES = 8_000
132
+ const MAX_STRING_CHARS = 400
133
+ const MAX_ARRAY_ITEMS = 20
134
+ const MAX_DEPTH = 4
135
+
136
+ /**
137
+ * Redaction is unconditional, not a level. A log is the artefact most likely to
138
+ * be pasted into a conversation, an issue, or a future upload, and a bearer
139
+ * token that only leaks at `debug` still leaks.
140
+ */
141
+ const SECRET_KEY_PATTERN = /secret|token|password|authorization|credential|verifier|api[_-]?key/i
142
+ const MACHINE_TOKEN_PATTERN = /nfm_[A-Za-z0-9._-]{6,}/g
143
+
144
+ export const REDACTED = '[redacted]'
145
+
146
+ // ---------------------------------------------------------------------------
147
+ // Paths
148
+ // ---------------------------------------------------------------------------
149
+
150
+ export function logsDir(env: NodeJS.ProcessEnv = process.env): string {
151
+ return path.join(stateDir(env), 'logs')
152
+ }
153
+
154
+ export function activeLogPath(env: NodeJS.ProcessEnv = process.env): string {
155
+ return path.join(logsDir(env), 'notifai.jsonl')
156
+ }
157
+
158
+ /**
159
+ * Archives are timestamp-named so lexical order is chronological order — the
160
+ * reader needs no `stat` to walk them, and two processes rotating at once
161
+ * cannot collide on a name.
162
+ */
163
+ const ARCHIVE_PATTERN = /^notifai-\d{8}T\d{9}Z-[0-9a-f]{4}\.jsonl$/
164
+
165
+ function archiveName(now: number): string {
166
+ const stamp = new Date(now).toISOString().replace(/[-:.]/g, '')
167
+ return `notifai-${stamp}-${randomBytes(2).toString('hex')}.jsonl`
168
+ }
169
+
170
+ /** Archives, oldest first. */
171
+ export function archiveLogPaths(env: NodeJS.ProcessEnv = process.env): string[] {
172
+ const dir = logsDir(env)
173
+ let entries: string[]
174
+ try {
175
+ entries = readdirSync(dir)
176
+ } catch {
177
+ return []
178
+ }
179
+ return entries
180
+ .filter((name) => ARCHIVE_PATTERN.test(name))
181
+ .sort()
182
+ .map((name) => path.join(dir, name))
183
+ }
184
+
185
+ // ---------------------------------------------------------------------------
186
+ // Redaction and shaping
187
+ // ---------------------------------------------------------------------------
188
+
189
+ function redactString(value: string): string {
190
+ const scrubbed = value.replace(MACHINE_TOKEN_PATTERN, 'nfm_[redacted]')
191
+ if (scrubbed.length <= MAX_STRING_CHARS) return scrubbed
192
+ return `${scrubbed.slice(0, MAX_STRING_CHARS)}…(+${scrubbed.length - MAX_STRING_CHARS} chars)`
193
+ }
194
+
195
+ /**
196
+ * Shape a value for the record: drop what must never be written, truncate what
197
+ * would flood a reader, and refuse to recurse for ever into a cyclic object.
198
+ */
199
+ export function shape(value: unknown, depth = 0): unknown {
200
+ if (value === null || value === undefined) return value
201
+ if (typeof value === 'string') return redactString(value)
202
+ if (typeof value === 'number' || typeof value === 'boolean') return value
203
+ if (typeof value === 'bigint') return String(value)
204
+ if (value instanceof Error) return redactString(`${value.name}: ${value.message}`)
205
+ if (depth >= MAX_DEPTH) return '[deep]'
206
+ if (Array.isArray(value)) {
207
+ const items = value.slice(0, MAX_ARRAY_ITEMS).map((item) => shape(item, depth + 1))
208
+ return value.length > MAX_ARRAY_ITEMS ? [...items, `…(+${value.length - MAX_ARRAY_ITEMS} more)`] : items
209
+ }
210
+ if (typeof value === 'object') {
211
+ const out: Record<string, unknown> = {}
212
+ for (const [key, nested] of Object.entries(value as Record<string, unknown>)) {
213
+ if (nested === undefined) continue
214
+ out[key] = SECRET_KEY_PATTERN.test(key) ? REDACTED : shape(nested, depth + 1)
215
+ }
216
+ return out
217
+ }
218
+ return String(value)
219
+ }
220
+
221
+ /**
222
+ * A record as one line, guaranteed to fit a single write. An oversized payload
223
+ * loses its data rather than its line: knowing an event happened and that its
224
+ * detail was too large beats losing the event.
225
+ */
226
+ export function serialize(record: LogRecord): string {
227
+ const line = `${JSON.stringify(record)}\n`
228
+ if (Buffer.byteLength(line) <= MAX_RECORD_BYTES) return line
229
+ const trimmed: LogRecord = {
230
+ ...record,
231
+ data: { dropped: 'record exceeded the per-line cap', bytes: Buffer.byteLength(line) },
232
+ }
233
+ return `${JSON.stringify(trimmed)}\n`
234
+ }
235
+
236
+ // ---------------------------------------------------------------------------
237
+ // The logger
238
+ // ---------------------------------------------------------------------------
239
+
240
+ export interface LogSettings {
241
+ level: LogLevel
242
+ maxBytes: number
243
+ /** Files kept in total, active included. */
244
+ maxFiles: number
245
+ }
246
+
247
+ export interface LoggerBindings {
248
+ cmd?: string
249
+ project?: string | null
250
+ session?: string | null
251
+ }
252
+
253
+ export interface Logger {
254
+ /** Correlation id for this invocation; print it in error messages. */
255
+ readonly runId: string
256
+ /** False when the level is `off` or the sink has failed. */
257
+ readonly enabled: boolean
258
+ error(event: LogEvent, data?: Record<string, unknown>): void
259
+ info(event: LogEvent, data?: Record<string, unknown>): void
260
+ debug(event: LogEvent, data?: Record<string, unknown>): void
261
+ /** Attach fields to every later record: command, project, session. */
262
+ bind(fields: LoggerBindings): void
263
+ /** Adopt settings from a config resolved later (a hook's project, not ours). */
264
+ adopt(settings: Partial<LogSettings>): void
265
+ }
266
+
267
+ /** Everything the sink needs, so tests can drive it without a clock or a disk. */
268
+ export interface LoggerOptions {
269
+ env?: NodeJS.ProcessEnv
270
+ settings?: Partial<LogSettings>
271
+ now?: () => number
272
+ cmd?: string
273
+ runId?: string
274
+ }
275
+
276
+ export const DEFAULT_LOG_SETTINGS: LogSettings = {
277
+ level: 'info',
278
+ maxBytes: 2_000_000,
279
+ maxFiles: 3,
280
+ }
281
+
282
+ /** A logger that records nothing, for tests and for `log_level = off`. */
283
+ export function nullLogger(runId = 'r_none'): Logger {
284
+ return {
285
+ runId,
286
+ enabled: false,
287
+ error: () => undefined,
288
+ info: () => undefined,
289
+ debug: () => undefined,
290
+ bind: () => undefined,
291
+ adopt: () => undefined,
292
+ }
293
+ }
294
+
295
+ export function newRunId(): string {
296
+ return `r_${randomBytes(6).toString('hex')}`
297
+ }
298
+
299
+ export function createLogger(options: LoggerOptions = {}): Logger {
300
+ const env = options.env ?? process.env
301
+ const now = options.now ?? Date.now
302
+ const runId = options.runId ?? newRunId()
303
+ const settings: LogSettings = { ...DEFAULT_LOG_SETTINGS, ...options.settings }
304
+ const bindings: LoggerBindings = { cmd: options.cmd ?? 'notifai' }
305
+
306
+ const dir = logsDir(env)
307
+ const active = activeLogPath(env)
308
+ const lock = `${active}.lock`
309
+ let broken = false
310
+
311
+ function currentSize(): number {
312
+ try {
313
+ return statSync(active).size
314
+ } catch {
315
+ return 0
316
+ }
317
+ }
318
+
319
+ /**
320
+ * Keep the inode handoff and retention prune inside the caller's byte-budget
321
+ * transaction, so every writer agrees which history the fresh file replaces.
322
+ */
323
+ function rotate(): string | null {
324
+ const target = path.join(dir, archiveName(now()))
325
+ try {
326
+ renameSync(active, target)
327
+ } catch (err) {
328
+ const code = (err as NodeJS.ErrnoException).code
329
+ if (code !== 'ENOENT') throw err
330
+ return null
331
+ }
332
+ const keep = Math.max(0, settings.maxFiles - 1)
333
+ const archives = archiveLogPaths(env)
334
+ for (const stale of archives.slice(0, Math.max(0, archives.length - keep))) {
335
+ try {
336
+ unlinkSync(stale)
337
+ } catch {
338
+ // An external cleaner removed it; the retained-file bound still holds.
339
+ }
340
+ }
341
+ return path.basename(target)
342
+ }
343
+
344
+ function write(level: RecordLevel, event: LogEvent, data?: Record<string, unknown>): void {
345
+ if (broken || LEVEL_RANK[settings.level] < LEVEL_RANK[level]) return
346
+ try {
347
+ const record: LogRecord = {
348
+ v: LOG_SCHEMA_VERSION,
349
+ ts: new Date(now()).toISOString(),
350
+ level,
351
+ event,
352
+ run: runId,
353
+ cmd: bindings.cmd ?? 'notifai',
354
+ pid: process.pid,
355
+ ...(bindings.project ? { project: bindings.project } : {}),
356
+ ...(bindings.session ? { session: bindings.session } : {}),
357
+ ...(data === undefined ? {} : { data: shape(data) as Record<string, unknown> }),
358
+ }
359
+ const line = serialize(record)
360
+ const bytes = Buffer.byteLength(line)
361
+ mkdirSync(dir, { recursive: true, mode: 0o700 })
362
+ withFileLock(lock, () => {
363
+ let payload = line
364
+ if (currentSize() + bytes > settings.maxBytes) {
365
+ const rotated = rotate()
366
+ if (rotated !== null) {
367
+ const marker = serialize({
368
+ ...record,
369
+ event: 'log.rotated',
370
+ data: { archived_to: rotated },
371
+ })
372
+ // A marker is diagnostic, not permission to violate the cap. The
373
+ // product configuration cannot make this branch drop it — maxBytes
374
+ // is at least 64 KB and each line is at most 8 KB — but tiny injected
375
+ // test settings may not have room for both atomic records.
376
+ if (Buffer.byteLength(marker) + bytes <= settings.maxBytes) payload = marker + line
377
+ }
378
+ }
379
+ // One record cannot be split without corrupting JSONL. If an internal
380
+ // caller injects maxBytes below that record's size, this one-record file
381
+ // is the only unavoidable overshoot. Valid CLI configuration makes the
382
+ // invariant unreachable (64 KB minimum versus an 8 KB record cap).
383
+ appendFileSync(active, payload, { mode: 0o600, flag: 'a' })
384
+ })
385
+ } catch {
386
+ // One failure is enough: a sink that cannot write will not start working
387
+ // mid-command, and retrying it on every event would cost the hook path
388
+ // real time for nothing.
389
+ broken = true
390
+ }
391
+ }
392
+
393
+ return {
394
+ runId,
395
+ get enabled() {
396
+ return !broken && settings.level !== 'off'
397
+ },
398
+ error: (event, data) => write('error', event, data),
399
+ info: (event, data) => write('info', event, data),
400
+ debug: (event, data) => write('debug', event, data),
401
+ bind: (fields) => Object.assign(bindings, fields),
402
+ adopt: (next) => Object.assign(settings, next),
403
+ }
404
+ }
405
+
406
+ /** Log settings as the layered config resolved them. */
407
+ export function logSettingsFrom(config: CliConfig): LogSettings {
408
+ return {
409
+ level: config.log_level.value,
410
+ maxBytes: config.log_max_bytes.value,
411
+ maxFiles: config.log_max_files.value,
412
+ }
413
+ }
414
+
415
+ const lastResolvedConfig = new WeakMap<Logger, string>()
416
+
417
+ /** Record each distinct resolution once per invocation when debug logging is on. */
418
+ export function logConfigResolved(logger: Logger, config: CliConfig): void {
419
+ const values = Object.fromEntries(
420
+ CONFIG_KEYS.map((key) => [
421
+ key,
422
+ { value: config[key].value, source: config[key].source },
423
+ ]),
424
+ )
425
+ const fingerprint = JSON.stringify(values)
426
+ if (lastResolvedConfig.get(logger) === fingerprint) return
427
+ lastResolvedConfig.set(logger, fingerprint)
428
+ logger.debug('config.resolved', { values })
429
+ }
430
+
431
+ /**
432
+ * The logger for a CLI invocation, configured from disk.
433
+ *
434
+ * It loads config itself rather than being handed one, because the earliest
435
+ * thing worth logging is the command starting — which is before any command has
436
+ * resolved anything, and sometimes before a config file that fails to parse has
437
+ * been discovered. A config that throws leaves the defaults in place; it is
438
+ * reported by the command that needed it, not silently swallowed here.
439
+ */
440
+ export function bootstrapLogger(options: { env?: NodeJS.ProcessEnv; cwd?: string } = {}): Logger {
441
+ const env = options.env ?? process.env
442
+ let settings: Partial<LogSettings> = {}
443
+ let project: string | null = null
444
+ try {
445
+ const config = loadConfig({ cwd: options.cwd ?? process.cwd(), env })
446
+ settings = logSettingsFrom(config)
447
+ project = config.project.value
448
+ } catch {
449
+ // Defaults, and the command reports the parse failure in its own words.
450
+ }
451
+ // Keep a real, mutable logger even when this bootstrap directory says off.
452
+ // Harness payloads can resolve a more-specific project or session later and
453
+ // adopt settings that legitimately re-enable the same invocation.
454
+ const logger = createLogger({ env, settings })
455
+ if (project !== null) logger.bind({ project })
456
+ return logger
457
+ }
458
+
459
+ // ---------------------------------------------------------------------------
460
+ // Reading
461
+ // ---------------------------------------------------------------------------
462
+
463
+ export interface LogQuery {
464
+ /** Newest N matching records. Bounded on purpose. */
465
+ limit?: number
466
+ /** Epoch milliseconds; records older than this are not returned. */
467
+ since?: number
468
+ /** Minimum severity, e.g. `error` for failures only. */
469
+ level?: LogLevel
470
+ event?: readonly string[]
471
+ run?: string
472
+ session?: string
473
+ project?: string
474
+ /** Matches a notification request id exactly in structured event data. */
475
+ request?: string
476
+ /** Free-text match over the serialized record. */
477
+ contains?: string
478
+ }
479
+
480
+ export interface LogReadResult {
481
+ /** Oldest first, so the result reads as a narrative and ends with `tail`. */
482
+ records: LogRecord[]
483
+ /** Files consulted, newest first. */
484
+ files: string[]
485
+ /** True when the limit cut the result short — there is more history behind it. */
486
+ more: boolean
487
+ }
488
+
489
+ function containsExactString(value: unknown, expected: string): boolean {
490
+ if (typeof value === 'string') return value === expected
491
+ if (Array.isArray(value)) return value.some((item) => containsExactString(item, expected))
492
+ return false
493
+ }
494
+
495
+ const REQUEST_ID_KEYS = new Set(['request_id', 'request_ids', 'retires_request_id'])
496
+
497
+ /** Match identity fields, never prose that happens to mention the same token. */
498
+ function containsRequestIdentity(value: unknown, expected: string): boolean {
499
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) return false
500
+ for (const [key, nested] of Object.entries(value as Record<string, unknown>)) {
501
+ if (REQUEST_ID_KEYS.has(key) && containsExactString(nested, expected)) return true
502
+ if (containsRequestIdentity(nested, expected)) return true
503
+ }
504
+ return false
505
+ }
506
+
507
+ function matches(record: LogRecord, raw: string, query: LogQuery): boolean {
508
+ if (query.level !== undefined && LEVEL_RANK[record.level] > LEVEL_RANK[query.level]) return false
509
+ if (query.event !== undefined && query.event.length > 0 && !query.event.includes(record.event)) return false
510
+ if (query.run !== undefined && record.run !== query.run) return false
511
+ if (query.session !== undefined && record.session !== query.session) return false
512
+ if (query.project !== undefined && record.project !== query.project) return false
513
+ if (query.request !== undefined && !containsRequestIdentity(record.data, query.request)) return false
514
+ if (query.contains !== undefined && !raw.toLowerCase().includes(query.contains.toLowerCase())) return false
515
+ return true
516
+ }
517
+
518
+ function isRecord(parsed: unknown): parsed is LogRecord {
519
+ return (
520
+ typeof parsed === 'object' &&
521
+ parsed !== null &&
522
+ typeof (parsed as { event?: unknown }).event === 'string' &&
523
+ typeof (parsed as { ts?: unknown }).ts === 'string'
524
+ )
525
+ }
526
+
527
+ /**
528
+ * Newest matching records, walking the active file and then the archives
529
+ * backwards and stopping as soon as the limit is met.
530
+ *
531
+ * A partially written or corrupt line is skipped rather than fatal. The point
532
+ * of a line-oriented log is that damage stays on its own line, and a reader
533
+ * that throws on one bad byte throws away everything else that was fine.
534
+ */
535
+ export function readLogRecords(
536
+ env: NodeJS.ProcessEnv = process.env,
537
+ query: LogQuery = {},
538
+ ): LogReadResult {
539
+ const limit = query.limit ?? 50
540
+ const files = [activeLogPath(env), ...archiveLogPaths(env).reverse()]
541
+ const collected: LogRecord[] = []
542
+ const consulted: string[] = []
543
+ let more = false
544
+
545
+ for (const file of files) {
546
+ if (collected.length >= limit) {
547
+ more = true
548
+ break
549
+ }
550
+ let contents: string
551
+ try {
552
+ contents = readFileSync(file, 'utf8')
553
+ } catch {
554
+ continue
555
+ }
556
+ consulted.push(file)
557
+ const lines = contents.split('\n')
558
+ let reachedFloor = false
559
+ for (let index = lines.length - 1; index >= 0; index -= 1) {
560
+ const raw = lines[index]
561
+ if (raw === undefined || raw.trim() === '') continue
562
+ let parsed: unknown
563
+ try {
564
+ parsed = JSON.parse(raw)
565
+ } catch {
566
+ continue
567
+ }
568
+ if (!isRecord(parsed)) continue
569
+ if (query.since !== undefined && Date.parse(parsed.ts) < query.since) {
570
+ // Files are chronological, so everything behind this is older too.
571
+ reachedFloor = true
572
+ break
573
+ }
574
+ if (!matches(parsed, raw, query)) continue
575
+ if (collected.length >= limit) {
576
+ more = true
577
+ break
578
+ }
579
+ collected.push(parsed)
580
+ }
581
+ if (reachedFloor) break
582
+ }
583
+
584
+ return { records: collected.reverse(), files: consulted, more }
585
+ }
586
+
587
+ /** Bytes currently held by the logs, for `doctor` and for `logs --path`. */
588
+ export function logsDiskUsage(env: NodeJS.ProcessEnv = process.env): { files: number; bytes: number } {
589
+ let bytes = 0
590
+ let files = 0
591
+ for (const file of [activeLogPath(env), ...archiveLogPaths(env)]) {
592
+ try {
593
+ bytes += statSync(file).size
594
+ files += 1
595
+ } catch {
596
+ // Not there; it simply does not count.
597
+ }
598
+ }
599
+ return { files, bytes }
600
+ }
601
+
602
+ // ---------------------------------------------------------------------------
603
+ // Rendering
604
+ // ---------------------------------------------------------------------------
605
+
606
+ const LEVEL_MARK: Record<RecordLevel, string> = { error: '!', info: ' ', debug: '·' }
607
+
608
+ /** `key=value` pairs for the parts of `data` worth a glance, bounded in width. */
609
+ function summarize(data: Record<string, unknown> | undefined, width: number): string {
610
+ if (data === undefined) return ''
611
+ const parts: string[] = []
612
+ let used = 0
613
+ for (const [key, value] of Object.entries(data)) {
614
+ if (value === null || value === undefined) continue
615
+ const rendered =
616
+ typeof value === 'object' ? JSON.stringify(value) : String(value)
617
+ const flattened = rendered.replace(/\s+/g, ' ')
618
+ const piece = `${key}=${flattened.length > 60 ? `${flattened.slice(0, 60)}…` : flattened}`
619
+ if (used + piece.length > width) {
620
+ parts.push('…')
621
+ break
622
+ }
623
+ parts.push(piece)
624
+ used += piece.length + 1
625
+ }
626
+ return parts.join(' ')
627
+ }
628
+
629
+ /**
630
+ * One record, one line. The fixed left columns matter more than they look:
631
+ * aligned columns are what let a reader — human or model — scan for the one
632
+ * line that differs instead of reading every line.
633
+ */
634
+ export function renderRecord(record: LogRecord): string {
635
+ const when = record.ts.replace('T', ' ').replace(/\.\d+Z$/, '')
636
+ const event = record.event.padEnd(15)
637
+ const summary = summarize(record.data, 110)
638
+ return `${when} ${LEVEL_MARK[record.level]} ${event} ${summary}`.trimEnd()
639
+ }