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