@raidiant/notifai 0.2.1 → 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 (94) 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 +85 -6
  9. package/dist/commands.js +1133 -322
  10. package/dist/commands.js.map +1 -1
  11. package/dist/config-schema.d.ts +62 -0
  12. package/dist/config-schema.js +312 -0
  13. package/dist/config-schema.js.map +1 -0
  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 +4 -0
  36. package/dist/interactive.js +604 -0
  37. package/dist/interactive.js.map +1 -0
  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 +201 -51
  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/banner.d.ts +22 -0
  47. package/dist/ui/banner.js +87 -0
  48. package/dist/ui/banner.js.map +1 -0
  49. package/dist/ui/config-view.d.ts +32 -0
  50. package/dist/ui/config-view.js +108 -0
  51. package/dist/ui/config-view.js.map +1 -0
  52. package/dist/ui/help.d.ts +46 -0
  53. package/dist/ui/help.js +105 -0
  54. package/dist/ui/help.js.map +1 -0
  55. package/dist/ui/theme.d.ts +108 -0
  56. package/dist/ui/theme.js +261 -0
  57. package/dist/ui/theme.js.map +1 -0
  58. package/package.json +11 -9
  59. package/src/atomic-file.ts +86 -7
  60. package/src/client.test.ts +12 -0
  61. package/src/client.ts +72 -4
  62. package/src/commands.test.ts +971 -44
  63. package/src/commands.ts +1323 -337
  64. package/src/config-schema.test.ts +152 -0
  65. package/src/config-schema.ts +363 -0
  66. package/src/config.test.ts +6 -5
  67. package/src/config.ts +85 -16
  68. package/src/file-lock-process-worker.test.ts +64 -0
  69. package/src/file-lock.test.ts +279 -0
  70. package/src/file-lock.ts +318 -0
  71. package/src/harnesses.test.ts +48 -0
  72. package/src/harnesses.ts +59 -0
  73. package/src/hook-adapter.test.ts +187 -0
  74. package/src/hook-adapter.ts +212 -0
  75. package/src/hook-input.test.ts +39 -0
  76. package/src/hook-input.ts +72 -0
  77. package/src/hooks.test.ts +1318 -240
  78. package/src/hooks.ts +1046 -296
  79. package/src/install-hooks.test.ts +90 -41
  80. package/src/install-hooks.ts +259 -74
  81. package/src/interactive.ts +692 -0
  82. package/src/logging-process-worker.test.ts +39 -0
  83. package/src/logging.test.ts +453 -0
  84. package/src/logging.ts +639 -0
  85. package/src/main.ts +220 -48
  86. package/src/opencode-plugin.ts +15 -16
  87. package/src/session-end-log-lock-worker.test.ts +35 -0
  88. package/src/skill.test.ts +11 -0
  89. package/src/ui/banner.ts +95 -0
  90. package/src/ui/config-view.test.ts +88 -0
  91. package/src/ui/config-view.ts +138 -0
  92. package/src/ui/help.ts +124 -0
  93. package/src/ui/theme.test.ts +92 -0
  94. package/src/ui/theme.ts +279 -0
@@ -0,0 +1,39 @@
1
+ import { existsSync, writeFileSync } from 'node:fs'
2
+ import { describe, expect, it } from 'vitest'
3
+ import { createLogger } from './logging.js'
4
+
5
+ const worker = process.env['NOTIFAI_ROTATION_WORKER']
6
+
7
+ if (worker === undefined) {
8
+ describe('rotation process worker', () => {
9
+ it('stays dormant outside the concurrency regression', () => {
10
+ expect(worker).toBeUndefined()
11
+ })
12
+ })
13
+ } else {
14
+ describe('rotation process worker', () => {
15
+ it('writes one share of an overlapping log stream', async () => {
16
+ const readyPath = process.env['NOTIFAI_ROTATION_READY']!
17
+ const startPath = process.env['NOTIFAI_ROTATION_START']!
18
+ const records = Number(process.env['NOTIFAI_ROTATION_RECORDS'])
19
+ const maxBytes = Number(process.env['NOTIFAI_ROTATION_MAX_BYTES'])
20
+ const maxFiles = Number(process.env['NOTIFAI_ROTATION_MAX_FILES'])
21
+ writeFileSync(readyPath, 'ready')
22
+ const startDeadline = Date.now() + 10_000
23
+ while (!existsSync(startPath)) {
24
+ if (Date.now() >= startDeadline) throw new Error('rotation parent never released the barrier')
25
+ await new Promise((resolve) => setTimeout(resolve, 2))
26
+ }
27
+
28
+ const logger = createLogger({
29
+ runId: `r_worker_${worker}`,
30
+ settings: { maxBytes, maxFiles },
31
+ })
32
+ for (let sequence = 0; sequence < records; sequence += 1) {
33
+ logger.info('cli.end', { worker, sequence, pad: 'p'.repeat(140) })
34
+ await new Promise((resolve) => setTimeout(resolve, 1))
35
+ }
36
+ expect(logger.enabled).toBe(true)
37
+ })
38
+ })
39
+ }
@@ -0,0 +1,453 @@
1
+ import { spawn } from 'node:child_process'
2
+ import {
3
+ appendFileSync,
4
+ existsSync,
5
+ mkdtempSync,
6
+ readFileSync,
7
+ statSync,
8
+ writeFileSync,
9
+ } from 'node:fs'
10
+ import os from 'node:os'
11
+ import path from 'node:path'
12
+ import { describe, expect, it } from 'vitest'
13
+ import {
14
+ LOG_SCHEMA_VERSION,
15
+ activeLogPath,
16
+ archiveLogPaths,
17
+ createLogger,
18
+ logsDiskUsage,
19
+ nullLogger,
20
+ readLogRecords,
21
+ renderRecord,
22
+ serialize,
23
+ shape,
24
+ type LogRecord,
25
+ } from './logging.js'
26
+
27
+ function sandbox(): NodeJS.ProcessEnv {
28
+ return { XDG_STATE_HOME: mkdtempSync(path.join(os.tmpdir(), 'notifai-logs-')) }
29
+ }
30
+
31
+ function lines(env: NodeJS.ProcessEnv): LogRecord[] {
32
+ return readFileSync(activeLogPath(env), 'utf8')
33
+ .split('\n')
34
+ .filter((line) => line.trim() !== '')
35
+ .map((line) => JSON.parse(line) as LogRecord)
36
+ }
37
+
38
+ async function waitUntil(predicate: () => boolean, timeoutMs = 10_000): Promise<void> {
39
+ const deadline = Date.now() + timeoutMs
40
+ while (!predicate()) {
41
+ if (Date.now() >= deadline) throw new Error('timed out waiting for rotation workers')
42
+ await new Promise((resolve) => setTimeout(resolve, 5))
43
+ }
44
+ }
45
+
46
+ function rotationWorker(
47
+ env: NodeJS.ProcessEnv,
48
+ worker: number,
49
+ records: number,
50
+ maxBytes: number,
51
+ maxFiles: number,
52
+ startPath: string,
53
+ ): { readyPath: string; done: Promise<void> } {
54
+ const readyPath = path.join(env['XDG_STATE_HOME']!, `rotation-ready-${worker}`)
55
+ const vitest = path.join(process.cwd(), 'node_modules', 'vitest', 'vitest.mjs')
56
+ const child = spawn(
57
+ process.execPath,
58
+ [vitest, 'run', 'src/logging-process-worker.test.ts', '--reporter=dot', '--maxWorkers=1'],
59
+ {
60
+ cwd: process.cwd(),
61
+ env: {
62
+ ...process.env,
63
+ ...env,
64
+ NOTIFAI_ROTATION_WORKER: String(worker),
65
+ NOTIFAI_ROTATION_RECORDS: String(records),
66
+ NOTIFAI_ROTATION_MAX_BYTES: String(maxBytes),
67
+ NOTIFAI_ROTATION_MAX_FILES: String(maxFiles),
68
+ NOTIFAI_ROTATION_READY: readyPath,
69
+ NOTIFAI_ROTATION_START: startPath,
70
+ },
71
+ stdio: ['ignore', 'pipe', 'pipe'],
72
+ },
73
+ )
74
+ const stdout: Buffer[] = []
75
+ const stderr: Buffer[] = []
76
+ child.stdout.on('data', (chunk: Buffer) => stdout.push(chunk))
77
+ child.stderr.on('data', (chunk: Buffer) => stderr.push(chunk))
78
+ const done = new Promise<void>((resolve, reject) => {
79
+ child.once('error', reject)
80
+ child.once('exit', (code) => {
81
+ if (code === 0) resolve()
82
+ else {
83
+ reject(
84
+ new Error(
85
+ `rotation worker ${worker} exited ${String(code)}\n${Buffer.concat(stdout).toString()}\n${Buffer.concat(stderr).toString()}`,
86
+ ),
87
+ )
88
+ }
89
+ })
90
+ })
91
+ return { readyPath, done }
92
+ }
93
+
94
+ describe('the record', () => {
95
+ it('is one self-describing JSON object per line', () => {
96
+ const env = sandbox()
97
+ const logger = createLogger({ env, cmd: 'send', runId: 'r_test' })
98
+ logger.info('send.submitted', { request_id: 'req_1' })
99
+ logger.info('send.outcome', { request_id: 'req_1' })
100
+
101
+ const written = lines(env)
102
+ expect(written).toHaveLength(2)
103
+ // Every line stands alone: a line pulled out by grep, with no header and no
104
+ // neighbours, still says what it is and which run it belongs to.
105
+ for (const record of written) {
106
+ expect(record.v).toBe(LOG_SCHEMA_VERSION)
107
+ expect(record.run).toBe('r_test')
108
+ expect(record.cmd).toBe('send')
109
+ expect(record.pid).toBe(process.pid)
110
+ expect(() => new Date(record.ts).toISOString()).not.toThrow()
111
+ }
112
+ })
113
+
114
+ it('carries the project and session once bound', () => {
115
+ const env = sandbox()
116
+ const logger = createLogger({ env })
117
+ logger.bind({ project: 'notifai', session: 'sess-1' })
118
+ logger.info('hook.start', {})
119
+ expect(lines(env)[0]).toMatchObject({ project: 'notifai', session: 'sess-1' })
120
+ })
121
+ })
122
+
123
+ describe('level', () => {
124
+ it('records nothing at off', () => {
125
+ const env = sandbox()
126
+ const logger = createLogger({ env, settings: { level: 'off' } })
127
+ logger.error('cli.error', {})
128
+ expect(logsDiskUsage(env).files).toBe(0)
129
+ expect(logger.enabled).toBe(false)
130
+ })
131
+
132
+ it('drops debug below debug, and keeps it at debug', () => {
133
+ const quiet = sandbox()
134
+ createLogger({ env: quiet, settings: { level: 'info' } }).debug('http.call', {})
135
+ expect(logsDiskUsage(quiet).files).toBe(0)
136
+
137
+ const loud = sandbox()
138
+ createLogger({ env: loud, settings: { level: 'debug' } }).debug('http.call', {})
139
+ expect(lines(loud)).toHaveLength(1)
140
+ })
141
+
142
+ it('keeps errors at the error level and nothing else', () => {
143
+ const env = sandbox()
144
+ const logger = createLogger({ env, settings: { level: 'error' } })
145
+ logger.info('cli.end', {})
146
+ logger.error('cli.error', {})
147
+ expect(lines(env).map((record) => record.event)).toEqual(['cli.error'])
148
+ })
149
+ })
150
+
151
+ describe('redaction', () => {
152
+ it('never writes a machine token, wherever it appears', () => {
153
+ const env = sandbox()
154
+ const logger = createLogger({ env })
155
+ logger.info('http.call', {
156
+ authorization: 'Bearer nfm_abc123.supersecretvalue',
157
+ message: 'rejected credential nfm_abc123.supersecretvalue for this machine',
158
+ nested: { poll_verifier: 'v_secret', fine: 'kept' },
159
+ })
160
+
161
+ const raw = readFileSync(activeLogPath(env), 'utf8')
162
+ expect(raw).not.toContain('supersecretvalue')
163
+ expect(raw).not.toContain('v_secret')
164
+ expect(raw).toContain('kept')
165
+ })
166
+
167
+ it('redacts by key name regardless of the value', () => {
168
+ expect(shape({ api_key: 12345, token: null, other: 'ok' })).toEqual({
169
+ api_key: '[redacted]',
170
+ token: '[redacted]',
171
+ other: 'ok',
172
+ })
173
+ })
174
+
175
+ it('truncates a long string instead of carrying it whole', () => {
176
+ const shaped = shape({ body: 'x'.repeat(1000) }) as { body: string }
177
+ expect(shaped.body.length).toBeLessThan(500)
178
+ expect(shaped.body).toContain('+600 chars')
179
+ })
180
+
181
+ it('refuses to recurse for ever into a cyclic object', () => {
182
+ const cyclic: Record<string, unknown> = {}
183
+ cyclic['self'] = cyclic
184
+ expect(() => JSON.stringify(shape(cyclic))).not.toThrow()
185
+ })
186
+ })
187
+
188
+ describe('record size', () => {
189
+ it('drops an oversized payload rather than the event', () => {
190
+ const record: LogRecord = {
191
+ v: LOG_SCHEMA_VERSION,
192
+ ts: new Date(0).toISOString(),
193
+ level: 'info',
194
+ event: 'send.submitted',
195
+ run: 'r_1',
196
+ cmd: 'send',
197
+ pid: 1,
198
+ data: Object.fromEntries(Array.from({ length: 400 }, (_, i) => [`k${i}`, 'y'.repeat(300)])),
199
+ }
200
+ const line = serialize(record)
201
+ // Small enough to land in one write, which is what makes concurrent
202
+ // appends safe — and the event survives even though its detail did not.
203
+ expect(Buffer.byteLength(line)).toBeLessThan(8_000)
204
+ const parsed = JSON.parse(line) as LogRecord
205
+ expect(parsed.event).toBe('send.submitted')
206
+ expect(parsed.data).toMatchObject({ dropped: expect.any(String) })
207
+ })
208
+ })
209
+
210
+ describe('rotation', () => {
211
+ it('rotates at the byte cap and keeps only the configured files', () => {
212
+ const env = sandbox()
213
+ const logger = createLogger({ env, settings: { maxBytes: 700, maxFiles: 3 } })
214
+ for (let i = 0; i < 60; i += 1) logger.info('cli.end', { i, pad: 'p'.repeat(50) })
215
+
216
+ const usage = logsDiskUsage(env)
217
+ expect(usage.files).toBe(3)
218
+ expect(archiveLogPaths(env)).toHaveLength(2)
219
+ // The whole point: bounded. Every retained file obeys the configured cap,
220
+ // however long the agent runs.
221
+ expect(usage.bytes).toBeLessThanOrEqual(3 * 700)
222
+ for (const file of [activeLogPath(env), ...archiveLogPaths(env)]) {
223
+ expect(statSync(file).size).toBeLessThanOrEqual(700)
224
+ }
225
+ })
226
+
227
+ it('leaves a marker in the fresh file so a gap is explained, not inferred', () => {
228
+ const env = sandbox()
229
+ const logger = createLogger({ env, settings: { maxBytes: 700, maxFiles: 3 } })
230
+ for (let i = 0; i < 20; i += 1) logger.info('cli.end', { i, pad: 'p'.repeat(40) })
231
+ expect(lines(env).some((record) => record.event === 'log.rotated')).toBe(true)
232
+ })
233
+
234
+ it('keeps only the active file when asked for one', () => {
235
+ const env = sandbox()
236
+ const logger = createLogger({ env, settings: { maxBytes: 300, maxFiles: 1 } })
237
+ for (let i = 0; i < 30; i += 1) logger.info('cli.end', { i, pad: 'p'.repeat(40) })
238
+ expect(archiveLogPaths(env)).toHaveLength(0)
239
+ expect(logsDiskUsage(env).files).toBe(1)
240
+ expect(statSync(activeLogPath(env)).size).toBeLessThanOrEqual(300)
241
+ })
242
+
243
+ it('keeps an indivisible record whole when an internal test injects an impossible cap', () => {
244
+ const env = sandbox()
245
+ const logger = createLogger({ env, settings: { maxBytes: 64, maxFiles: 3 } })
246
+ logger.info('cli.end', { sequence: 1 })
247
+ logger.info('cli.end', { sequence: 2 })
248
+
249
+ const files = [activeLogPath(env), ...archiveLogPaths(env)]
250
+ expect(files).toHaveLength(2)
251
+ for (const file of files) {
252
+ const records = readFileSync(file, 'utf8').split('\n').filter((line) => line !== '')
253
+ expect(records).toHaveLength(1)
254
+ expect(() => JSON.parse(records[0]!) as unknown).not.toThrow()
255
+ expect(statSync(file).size).toBeGreaterThan(64)
256
+ }
257
+ })
258
+
259
+ it('enforces the byte cap and preserves each record across overlapping processes', async () => {
260
+ const env = sandbox()
261
+ const workers = 4
262
+ const recordsPerWorker = 50
263
+ const maxBytes = 4_000
264
+ const maxFiles = 100
265
+ const startPath = path.join(env['XDG_STATE_HOME']!, 'rotation-start')
266
+ const children = Array.from({ length: workers }, (_, worker) =>
267
+ rotationWorker(env, worker, recordsPerWorker, maxBytes, maxFiles, startPath),
268
+ )
269
+
270
+ await waitUntil(() => children.every(({ readyPath }) => existsSync(readyPath)))
271
+ writeFileSync(startPath, 'go')
272
+ await Promise.all(children.map(({ done }) => done))
273
+
274
+ const files = [activeLogPath(env), ...archiveLogPaths(env)]
275
+ expect(files.length).toBeGreaterThan(1)
276
+ // The stat/rotate/append transaction is cross-process: no writer gets to
277
+ // consume budget another writer already claimed.
278
+ for (const file of files) expect(statSync(file).size).toBeLessThanOrEqual(maxBytes)
279
+
280
+ const seen = new Map<string, number>()
281
+ let retainedRecords = 0
282
+ for (const file of files) {
283
+ for (const line of readFileSync(file, 'utf8').split('\n')) {
284
+ if (line.trim() === '') continue
285
+ const record = JSON.parse(line) as LogRecord
286
+ if (record.event !== 'cli.end') continue
287
+ retainedRecords += 1
288
+ const key = `${String(record.data?.['worker'])}:${String(record.data?.['sequence'])}`
289
+ seen.set(key, (seen.get(key) ?? 0) + 1)
290
+ }
291
+ }
292
+ // Retention has room for every record, so neither a rotation nor an archive
293
+ // name race may lose or duplicate one.
294
+ expect(retainedRecords).toBe(workers * recordsPerWorker)
295
+ expect(seen.size).toBe(workers * recordsPerWorker)
296
+ expect([...seen.values()].every((count) => count === 1)).toBe(true)
297
+ })
298
+ })
299
+
300
+ describe('failure isolation', () => {
301
+ it('a sink that cannot write never throws at the caller', () => {
302
+ const env = sandbox()
303
+ // The logs directory's place is taken by a regular file, so every write
304
+ // below fails. A command must not care.
305
+ writeFileSync(path.join(env['XDG_STATE_HOME']!, 'notifai'), 'in the way')
306
+ const logger = createLogger({ env })
307
+ expect(() => logger.info('cli.end', { exit: 0 })).not.toThrow()
308
+ expect(logger.enabled).toBe(false)
309
+ })
310
+
311
+ it('the null logger accepts everything and records nothing', () => {
312
+ const logger = nullLogger()
313
+ expect(() => {
314
+ logger.info('cli.end', {})
315
+ logger.bind({ cmd: 'x' })
316
+ logger.adopt({ level: 'debug' })
317
+ }).not.toThrow()
318
+ expect(logger.enabled).toBe(false)
319
+ })
320
+ })
321
+
322
+ describe('reading', () => {
323
+ function seed(env: NodeJS.ProcessEnv): void {
324
+ const logger = createLogger({ env, runId: 'r_1', cmd: 'send' })
325
+ logger.bind({ project: 'alpha' })
326
+ logger.info('send.submitted', { request_id: 'req_alpha' })
327
+ logger.error('cli.error', { message: 'boom' })
328
+ const other = createLogger({ env, runId: 'r_2', cmd: 'ask' })
329
+ other.bind({ project: 'beta' })
330
+ other.info('ask.registered', { request_id: 'req_beta' })
331
+ }
332
+
333
+ it('returns records oldest first, so the result reads forwards', () => {
334
+ const env = sandbox()
335
+ seed(env)
336
+ const { records } = readLogRecords(env)
337
+ expect(records.map((record) => record.event)).toEqual([
338
+ 'send.submitted',
339
+ 'cli.error',
340
+ 'ask.registered',
341
+ ])
342
+ })
343
+
344
+ it('is bounded, and says when there is more behind it', () => {
345
+ const env = sandbox()
346
+ seed(env)
347
+ const { records, more } = readLogRecords(env, { limit: 1 })
348
+ // The newest, not the oldest: a limit exists to answer "what just
349
+ // happened", so cutting the recent end would defeat it.
350
+ expect(records.map((record) => record.event)).toEqual(['ask.registered'])
351
+ expect(more).toBe(true)
352
+ })
353
+
354
+ it('filters by run, project, event, and severity', () => {
355
+ const env = sandbox()
356
+ seed(env)
357
+ expect(readLogRecords(env, { run: 'r_1' }).records).toHaveLength(2)
358
+ expect(readLogRecords(env, { project: 'beta' }).records).toHaveLength(1)
359
+ expect(readLogRecords(env, { event: ['cli.error'] }).records).toHaveLength(1)
360
+ expect(readLogRecords(env, { level: 'error' }).records.map((r) => r.event)).toEqual(['cli.error'])
361
+ })
362
+
363
+ it('finds every record touching one notification request', () => {
364
+ const env = sandbox()
365
+ seed(env)
366
+ const { records } = readLogRecords(env, { request: 'req_alpha' })
367
+ expect(records).toHaveLength(1)
368
+ expect(records[0]!.event).toBe('send.submitted')
369
+ })
370
+
371
+ it('matches every structured request identity without prefix false positives', () => {
372
+ const env = sandbox()
373
+ const logger = createLogger({ env })
374
+ logger.info('send.submitted', { request_id: 'req_1' })
375
+ logger.info('send.submitted', { request_id: 'req_10' })
376
+ logger.info('hook.answer', { request_ids: ['req_1', 'req_10'], answered: false })
377
+ logger.error('cli.error', { request_ids: ['req_10'], message: 'req_1' })
378
+
379
+ const { records } = readLogRecords(env, { request: 'req_1' })
380
+ expect(records).toHaveLength(2)
381
+ expect(records.map((record) => record.event)).toEqual(['send.submitted', 'hook.answer'])
382
+ })
383
+
384
+ it('honours a time floor', () => {
385
+ const env = sandbox()
386
+ const early = createLogger({ env, now: () => Date.parse('2026-08-01T00:00:00Z') })
387
+ early.info('cli.end', { when: 'old' })
388
+ const late = createLogger({ env, now: () => Date.parse('2026-08-11T00:00:00Z') })
389
+ late.info('cli.end', { when: 'new' })
390
+
391
+ const { records } = readLogRecords(env, { since: Date.parse('2026-08-10T00:00:00Z') })
392
+ expect(records).toHaveLength(1)
393
+ expect(records[0]!.data).toMatchObject({ when: 'new' })
394
+ })
395
+
396
+ it('reads across archives when the active file is not enough', () => {
397
+ const env = sandbox()
398
+ const logger = createLogger({ env, settings: { maxBytes: 500, maxFiles: 5 } })
399
+ for (let i = 0; i < 30; i += 1) logger.info('cli.end', { i })
400
+ expect(archiveLogPaths(env).length).toBeGreaterThan(0)
401
+ const { records, files } = readLogRecords(env, { limit: 30, event: ['cli.end'] })
402
+ expect(files.length).toBeGreaterThan(1)
403
+ expect(records.length).toBeGreaterThan(lines(env).filter((r) => r.event === 'cli.end').length)
404
+ })
405
+
406
+ it('skips a damaged line instead of throwing away the file', () => {
407
+ const env = sandbox()
408
+ seed(env)
409
+ // A half-written line is what a crashed process leaves behind, and a
410
+ // reader that dies on it loses every good record around it.
411
+ appendFileSync(activeLogPath(env), '{"v":1,"ts":"2026-0\n')
412
+ appendFileSync(activeLogPath(env), 'not json at all\n')
413
+ expect(readLogRecords(env).records).toHaveLength(3)
414
+ })
415
+
416
+ it('reports nothing at all rather than failing when there is no log', () => {
417
+ expect(readLogRecords(sandbox())).toMatchObject({ records: [], more: false })
418
+ })
419
+ })
420
+
421
+ describe('rendering', () => {
422
+ it('puts the fixed columns first so lines can be scanned, not read', () => {
423
+ const line = renderRecord({
424
+ v: 1,
425
+ ts: '2026-08-11T12:04:31.123Z',
426
+ level: 'info',
427
+ event: 'hook.gate',
428
+ run: 'r_1',
429
+ cmd: 'hook stop',
430
+ pid: 1,
431
+ data: { verdict: 'held', reason: 'user-present', idle_seconds: 4 },
432
+ })
433
+ expect(line).toContain('2026-08-11 12:04:31')
434
+ expect(line).toContain('hook.gate')
435
+ expect(line).toContain('reason=user-present')
436
+ expect(line).toContain('idle_seconds=4')
437
+ })
438
+
439
+ it('stays on one line whatever the payload', () => {
440
+ const line = renderRecord({
441
+ v: 1,
442
+ ts: '2026-08-11T12:04:31.123Z',
443
+ level: 'error',
444
+ event: 'cli.error',
445
+ run: 'r_1',
446
+ cmd: 'send',
447
+ pid: 1,
448
+ data: { message: 'first\nsecond\nthird', big: 'z'.repeat(300) },
449
+ })
450
+ expect(line).not.toContain('\n')
451
+ expect(line.length).toBeLessThan(200)
452
+ })
453
+ })