@sentry/warden 0.20.0 → 0.21.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 (57) hide show
  1. package/CHANGELOG.md +173 -0
  2. package/dist/cli/args.d.ts +7 -5
  3. package/dist/cli/args.d.ts.map +1 -1
  4. package/dist/cli/args.js +31 -17
  5. package/dist/cli/args.js.map +1 -1
  6. package/dist/cli/commands/runs.d.ts +26 -0
  7. package/dist/cli/commands/runs.d.ts.map +1 -0
  8. package/dist/cli/commands/runs.js +668 -0
  9. package/dist/cli/commands/runs.js.map +1 -0
  10. package/dist/cli/main.d.ts +15 -0
  11. package/dist/cli/main.d.ts.map +1 -1
  12. package/dist/cli/main.js +236 -128
  13. package/dist/cli/main.js.map +1 -1
  14. package/dist/cli/output/index.d.ts +1 -1
  15. package/dist/cli/output/index.d.ts.map +1 -1
  16. package/dist/cli/output/index.js +1 -1
  17. package/dist/cli/output/index.js.map +1 -1
  18. package/dist/cli/output/ink-runner.d.ts.map +1 -1
  19. package/dist/cli/output/ink-runner.js +32 -14
  20. package/dist/cli/output/ink-runner.js.map +1 -1
  21. package/dist/cli/output/jsonl-schema-gen.d.ts +16 -0
  22. package/dist/cli/output/jsonl-schema-gen.d.ts.map +1 -0
  23. package/dist/cli/output/jsonl-schema-gen.js +63 -0
  24. package/dist/cli/output/jsonl-schema-gen.js.map +1 -0
  25. package/dist/cli/output/jsonl.d.ts +168 -34
  26. package/dist/cli/output/jsonl.d.ts.map +1 -1
  27. package/dist/cli/output/jsonl.js +212 -144
  28. package/dist/cli/output/jsonl.js.map +1 -1
  29. package/dist/cli/output/tasks.d.ts +2 -0
  30. package/dist/cli/output/tasks.d.ts.map +1 -1
  31. package/dist/cli/output/tasks.js +167 -27
  32. package/dist/cli/output/tasks.js.map +1 -1
  33. package/dist/cli/terminal.d.ts.map +1 -1
  34. package/dist/cli/terminal.js +20 -0
  35. package/dist/cli/terminal.js.map +1 -1
  36. package/dist/index.d.ts +2 -2
  37. package/dist/index.d.ts.map +1 -1
  38. package/dist/index.js +2 -0
  39. package/dist/index.js.map +1 -1
  40. package/dist/sdk/analyze.d.ts.map +1 -1
  41. package/dist/sdk/analyze.js +83 -10
  42. package/dist/sdk/analyze.js.map +1 -1
  43. package/dist/sdk/errors.d.ts +11 -0
  44. package/dist/sdk/errors.d.ts.map +1 -1
  45. package/dist/sdk/errors.js +50 -0
  46. package/dist/sdk/errors.js.map +1 -1
  47. package/dist/sdk/types.d.ts +9 -1
  48. package/dist/sdk/types.d.ts.map +1 -1
  49. package/dist/types/index.d.ts +129 -6
  50. package/dist/types/index.d.ts.map +1 -1
  51. package/dist/types/index.js +59 -3
  52. package/dist/types/index.js.map +1 -1
  53. package/package.json +2 -1
  54. package/dist/cli/commands/logs.d.ts +0 -19
  55. package/dist/cli/commands/logs.d.ts.map +0 -1
  56. package/dist/cli/commands/logs.js +0 -412
  57. package/dist/cli/commands/logs.js.map +0 -1
@@ -0,0 +1,668 @@
1
+ import { existsSync, openSync, closeSync, fstatSync, readSync, readdirSync, readFileSync, unlinkSync, watch } from 'node:fs';
2
+ import { dirname, join, resolve } from 'node:path';
3
+ import chalk from 'chalk';
4
+ import { loadWardenConfig } from '../../config/loader.js';
5
+ import { getRepoRoot } from '../git.js';
6
+ import { findExpiredArtifacts } from '../log-cleanup.js';
7
+ import { renderTerminalReport, filterReports } from '../terminal.js';
8
+ import { pluralize, formatDuration, formatCost, shortRunId, parseJsonlReports, parseLogMetadata, renderJsonlString, JsonlRecordSchema, JsonlSummaryRecordSchema, } from '../output/index.js';
9
+ /**
10
+ * Resolve a log directory path from the repo root.
11
+ */
12
+ function resolveLogDir() {
13
+ const cwd = process.cwd();
14
+ let repoPath;
15
+ try {
16
+ repoPath = getRepoRoot(cwd);
17
+ }
18
+ catch {
19
+ return undefined;
20
+ }
21
+ return { logDir: join(repoPath, '.warden', 'logs'), repoPath };
22
+ }
23
+ /**
24
+ * Recover an ISO timestamp from `{runId8}-{ISO-datetime}.jsonl`.
25
+ * Used as the list sort key for in-progress runs (no summary yet).
26
+ */
27
+ function filenameTimestamp(filename) {
28
+ const match = filename.match(/-(\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}-\d{3}Z)\.jsonl$/);
29
+ const stamp = match?.[1];
30
+ if (!stamp)
31
+ return '';
32
+ return stamp.replace(/^(\d{4}-\d{2}-\d{2}T\d{2})-(\d{2})-(\d{2})-(\d{3})Z$/, '$1:$2:$3.$4Z');
33
+ }
34
+ /**
35
+ * Resolve a file argument to a full path.
36
+ * If the argument looks like a run ID (no `/` or `.`), look up matching files in .warden/logs/.
37
+ */
38
+ function resolveFileArg(arg, logDir) {
39
+ // If it contains path separators or dots, treat as a file path
40
+ if (arg.includes('/') || arg.includes('.')) {
41
+ return [resolve(process.cwd(), arg)];
42
+ }
43
+ // Treat as a short run ID — glob for matching files
44
+ try {
45
+ const entries = readdirSync(logDir);
46
+ const matches = entries
47
+ .filter((e) => e.endsWith('.jsonl') && e.startsWith(arg))
48
+ .map((e) => join(logDir, e));
49
+ return matches;
50
+ }
51
+ catch {
52
+ return [];
53
+ }
54
+ }
55
+ // eslint-disable-next-line no-control-regex
56
+ const ANSI_RE = /\x1b\[[0-9;]*m/g;
57
+ /**
58
+ * Get the visual width of a string (ignoring ANSI escape codes).
59
+ */
60
+ function visualWidth(str) {
61
+ return str.replace(ANSI_RE, '').length;
62
+ }
63
+ /**
64
+ * Pad a string to a visual width, accounting for ANSI codes.
65
+ */
66
+ function padToWidth(str, width) {
67
+ const pad = width - visualWidth(str);
68
+ return pad > 0 ? str + ' '.repeat(pad) : str;
69
+ }
70
+ /**
71
+ * Right-align a string to a visual width, accounting for ANSI codes.
72
+ */
73
+ function rightAlign(str, width) {
74
+ const pad = width - visualWidth(str);
75
+ return pad > 0 ? ' '.repeat(pad) + str : str;
76
+ }
77
+ /**
78
+ * Format a date as a human-friendly relative or short absolute string.
79
+ */
80
+ function formatRelativeTime(date) {
81
+ const now = Date.now();
82
+ const diffMs = now - date.getTime();
83
+ const diffSec = Math.floor(diffMs / 1000);
84
+ const diffMin = Math.floor(diffSec / 60);
85
+ const diffHr = Math.floor(diffMin / 60);
86
+ const diffDays = Math.floor(diffHr / 24);
87
+ if (diffSec < 60)
88
+ return 'just now';
89
+ if (diffMin < 60)
90
+ return `${diffMin}m ago`;
91
+ if (diffHr < 24)
92
+ return `${diffHr}h ago`;
93
+ if (diffDays === 1)
94
+ return 'yesterday';
95
+ if (diffDays < 7)
96
+ return `${diffDays}d ago`;
97
+ // Older than a week: show short date
98
+ const month = date.toLocaleString('en-US', { month: 'short' });
99
+ const day = date.getDate();
100
+ const year = date.getFullYear();
101
+ const currentYear = new Date().getFullYear();
102
+ return year === currentYear ? `${month} ${day}` : `${month} ${day}, ${year}`;
103
+ }
104
+ const SEVERITY_COLORS = {
105
+ high: chalk.red,
106
+ medium: chalk.yellow,
107
+ low: chalk.green,
108
+ };
109
+ /**
110
+ * Format a severity breakdown as colored counts.
111
+ */
112
+ function formatSeverityBreakdown(bySeverity) {
113
+ const severities = ['high', 'medium', 'low'];
114
+ const parts = severities.map((sev) => {
115
+ const count = bySeverity[sev] ?? 0;
116
+ return count > 0 ? SEVERITY_COLORS[sev](String(count)) : chalk.dim('0');
117
+ });
118
+ return parts.join(chalk.dim(' / '));
119
+ }
120
+ /**
121
+ * List sessions in `.warden/logs/`. Empty (no-file, no-skill) runs
122
+ * are hidden unless `all` is set.
123
+ */
124
+ export async function runRunsList(options, reporter, listOptions = {}) {
125
+ const resolved = resolveLogDir();
126
+ if (!resolved) {
127
+ reporter.error('Not a git repository');
128
+ return 1;
129
+ }
130
+ const { logDir } = resolved;
131
+ let entries;
132
+ try {
133
+ entries = readdirSync(logDir)
134
+ .filter((e) => e.endsWith('.jsonl'))
135
+ .sort()
136
+ .reverse(); // newest first (filenames embed timestamps)
137
+ }
138
+ catch {
139
+ entries = [];
140
+ }
141
+ if (entries.length === 0) {
142
+ reporter.warning('No saved sessions found');
143
+ reporter.tip('Run warden to generate sessions in .warden/logs/');
144
+ return 0;
145
+ }
146
+ const allLogData = [];
147
+ for (const entry of entries) {
148
+ const filePath = join(logDir, entry);
149
+ allLogData.push({ entry, meta: parseLogMetadata(filePath) });
150
+ }
151
+ // In-progress runs have no summary; fall back to the run record's
152
+ // timestamp, then to the filename, so they sort to the top.
153
+ const sortKey = (entry) => entry.meta?.summary?.run.timestamp ??
154
+ entry.meta?.runMetadata?.timestamp ??
155
+ filenameTimestamp(entry.entry);
156
+ allLogData.sort((a, b) => sortKey(b).localeCompare(sortKey(a)));
157
+ // Run-level errors (auth, config) stay visible even with zero files —
158
+ // the error is the point of keeping the record. In-progress runs also
159
+ // stay visible so users can find the active session.
160
+ const isEmptyRun = (entry) => {
161
+ const meta = entry.meta;
162
+ if (!meta || meta.inProgress)
163
+ return false;
164
+ if (meta.summary?.error)
165
+ return false;
166
+ return meta.totalFiles === 0 && meta.skills.length === 0;
167
+ };
168
+ const showAll = listOptions.all ?? false;
169
+ const logData = showAll ? allLogData : allLogData.filter((e) => !isEmptyRun(e));
170
+ const hiddenCount = allLogData.length - logData.length;
171
+ if (options.json) {
172
+ const results = logData.map(({ entry, meta }) => ({
173
+ file: entry,
174
+ runId: meta?.runMetadata?.runId,
175
+ timestamp: meta?.runMetadata?.timestamp,
176
+ model: meta?.model,
177
+ headSha: meta?.headSha,
178
+ files: meta?.totalFiles,
179
+ findings: meta?.summary?.totalFindings,
180
+ bySeverity: meta?.summary?.bySeverity,
181
+ durationMs: meta?.summary?.run.durationMs,
182
+ costUSD: meta?.summary?.usage?.costUSD,
183
+ skills: meta?.skills,
184
+ inProgress: meta?.inProgress ?? false,
185
+ }));
186
+ process.stdout.write(JSON.stringify(results, null, 2) + '\n');
187
+ return 0;
188
+ }
189
+ const rows = [];
190
+ // Aggregate totals across all runs
191
+ const totals = {
192
+ findings: 0,
193
+ bySeverity: { high: 0, medium: 0, low: 0 },
194
+ costUSD: 0,
195
+ durationMs: 0,
196
+ skills: new Set(),
197
+ };
198
+ for (const { entry, meta } of logData) {
199
+ if (!meta) {
200
+ rows.push({
201
+ runId: entry.slice(0, 8),
202
+ date: '',
203
+ files: '',
204
+ findings: chalk.dim('parse error'),
205
+ time: '',
206
+ cost: '',
207
+ sha: '',
208
+ model: '-',
209
+ skills: '',
210
+ });
211
+ continue;
212
+ }
213
+ const { summary, runMetadata, skills, inProgress } = meta;
214
+ if (inProgress) {
215
+ const ts = runMetadata?.timestamp ?? filenameTimestamp(entry);
216
+ const runId = runMetadata?.runId
217
+ ? shortRunId(runMetadata.runId)
218
+ : entry.slice(0, 8);
219
+ rows.push({
220
+ runId,
221
+ date: ts ? formatRelativeTime(new Date(ts)) : '',
222
+ files: meta.totalFiles > 0 ? String(meta.totalFiles) : '',
223
+ findings: chalk.yellow('running'),
224
+ time: '',
225
+ cost: '',
226
+ sha: meta.headSha ? meta.headSha.slice(0, 7) : '',
227
+ model: meta.model ?? '-',
228
+ skills: skills.join(', '),
229
+ });
230
+ for (const skill of skills)
231
+ totals.skills.add(skill);
232
+ continue;
233
+ }
234
+ if (summary) {
235
+ totals.findings += summary.totalFindings;
236
+ totals.durationMs += summary.run.durationMs;
237
+ if (summary.usage)
238
+ totals.costUSD += summary.usage.costUSD;
239
+ for (const [sev, count] of Object.entries(summary.bySeverity)) {
240
+ totals.bySeverity[sev] += count;
241
+ }
242
+ for (const skill of skills)
243
+ totals.skills.add(skill);
244
+ rows.push({
245
+ runId: shortRunId(summary.run.runId),
246
+ date: formatRelativeTime(new Date(summary.run.timestamp)),
247
+ files: meta.totalFiles > 0 ? String(meta.totalFiles) : '',
248
+ findings: formatSeverityBreakdown(summary.bySeverity),
249
+ time: formatDuration(summary.run.durationMs),
250
+ cost: summary.usage ? formatCost(summary.usage.costUSD) : '',
251
+ sha: meta.headSha ? meta.headSha.slice(0, 7) : '',
252
+ model: meta.model ?? '-',
253
+ skills: skills.join(', '),
254
+ });
255
+ }
256
+ }
257
+ // Calculate column widths
258
+ const headers = {
259
+ runId: 'RUN',
260
+ date: 'DATE',
261
+ files: 'FILES',
262
+ findings: 'FINDINGS',
263
+ time: 'TIME',
264
+ cost: 'COST',
265
+ sha: 'SHA',
266
+ model: 'MODEL',
267
+ skills: 'SKILLS',
268
+ };
269
+ const widths = Object.fromEntries(Object.keys(headers).map((key) => {
270
+ const col = key;
271
+ return [col, Math.max(headers[col].length, ...rows.map((r) => visualWidth(r[col])))];
272
+ }));
273
+ // Header row
274
+ const headerLine = ` ${padToWidth(headers.runId, widths.runId)} ` +
275
+ `${padToWidth(headers.date, widths.date)} ` +
276
+ `${rightAlign(headers.files, widths.files)} ` +
277
+ `${padToWidth(headers.findings, widths.findings)} ` +
278
+ `${rightAlign(headers.time, widths.time)} ` +
279
+ `${rightAlign(headers.cost, widths.cost)} ` +
280
+ `${padToWidth(headers.sha, widths.sha)} ` +
281
+ `${padToWidth(headers.model, widths.model)} ` +
282
+ `${headers.skills}`;
283
+ reporter.text(chalk.dim(headerLine));
284
+ // Data rows
285
+ for (const row of rows) {
286
+ const line = ` ${padToWidth(chalk.bold(row.runId), widths.runId)} ` +
287
+ `${padToWidth(chalk.dim(row.date), widths.date)} ` +
288
+ `${rightAlign(chalk.dim(row.files), widths.files)} ` +
289
+ `${padToWidth(row.findings, widths.findings)} ` +
290
+ `${rightAlign(chalk.dim(row.time), widths.time)} ` +
291
+ `${rightAlign(chalk.dim(row.cost), widths.cost)} ` +
292
+ `${padToWidth(chalk.dim(row.sha), widths.sha)} ` +
293
+ `${padToWidth(chalk.dim(row.model), widths.model)} ` +
294
+ `${chalk.dim(row.skills)}`;
295
+ reporter.text(line);
296
+ }
297
+ // Summary footer
298
+ reporter.blank();
299
+ reporter.text(chalk.dim(`${rows.length} ${pluralize(rows.length, 'run')} · ` +
300
+ `${totals.findings} ${pluralize(totals.findings, 'finding')} `) +
301
+ formatSeverityBreakdown(totals.bySeverity) +
302
+ chalk.dim(` · ${formatDuration(totals.durationMs)}` +
303
+ ` · ${formatCost(totals.costUSD)}` +
304
+ ` · ${totals.skills.size} ${pluralize(totals.skills.size, 'skill')}`));
305
+ if (hiddenCount > 0) {
306
+ reporter.text(chalk.dim(`${hiddenCount} empty ${pluralize(hiddenCount, 'session')} hidden — pass --all to show`));
307
+ }
308
+ return 0;
309
+ }
310
+ /**
311
+ * Show results from JSONL log files (replaces `warden replay`).
312
+ */
313
+ export async function runRunsShow(runsOptions, options, reporter) {
314
+ const { files: fileArgs } = runsOptions;
315
+ if (fileArgs.length === 0) {
316
+ reporter.error('No log files specified');
317
+ reporter.tip('Usage: warden runs show <file.jsonl> [file2.jsonl ...]');
318
+ return 1;
319
+ }
320
+ // Resolve file arguments (may be paths or run IDs)
321
+ const resolved = resolveLogDir();
322
+ const logDir = resolved?.logDir;
323
+ const resolvedFiles = [];
324
+ for (const arg of fileArgs) {
325
+ if (logDir) {
326
+ const matches = resolveFileArg(arg, logDir);
327
+ if (matches.length > 0) {
328
+ resolvedFiles.push(...matches);
329
+ continue;
330
+ }
331
+ }
332
+ // Fall back to treating as a direct path
333
+ resolvedFiles.push(resolve(process.cwd(), arg));
334
+ }
335
+ // Validate all files exist
336
+ const missingFiles = [];
337
+ for (const file of resolvedFiles) {
338
+ if (!existsSync(file)) {
339
+ missingFiles.push(file);
340
+ }
341
+ }
342
+ if (missingFiles.length > 0) {
343
+ reporter.error(`Log ${pluralize(missingFiles.length, 'file')} not found: ${missingFiles.join(', ')}`);
344
+ return 1;
345
+ }
346
+ // Parse and merge reports from all files
347
+ const allReports = [];
348
+ let totalDurationMs = 0;
349
+ let lastRunMetadata;
350
+ for (const file of resolvedFiles) {
351
+ try {
352
+ const content = readFileSync(file, 'utf-8');
353
+ const parsed = parseJsonlReports(content);
354
+ allReports.push(...parsed.reports);
355
+ totalDurationMs += parsed.totalDurationMs;
356
+ if (parsed.runMetadata) {
357
+ lastRunMetadata = parsed.runMetadata;
358
+ reporter.debug(`Loaded ${parsed.reports.length} ${pluralize(parsed.reports.length, 'skill')} from ${file}`);
359
+ reporter.debug(` Run ID: ${parsed.runMetadata.runId}`);
360
+ reporter.debug(` Timestamp: ${parsed.runMetadata.timestamp}`);
361
+ }
362
+ }
363
+ catch (err) {
364
+ reporter.error(`Failed to parse ${file}: ${err instanceof Error ? err.message : String(err)}`);
365
+ return 1;
366
+ }
367
+ }
368
+ if (allReports.length === 0) {
369
+ reporter.warning('No skill reports found in log files');
370
+ return 0;
371
+ }
372
+ // Load config for minConfidence default (matches main run flow)
373
+ let configMinConfidence;
374
+ if (resolved) {
375
+ try {
376
+ const configPath = resolve(resolved.repoPath, 'warden.toml');
377
+ if (existsSync(configPath)) {
378
+ const config = loadWardenConfig(dirname(configPath));
379
+ configMinConfidence = config.defaults?.minConfidence;
380
+ }
381
+ }
382
+ catch {
383
+ // Use default
384
+ }
385
+ }
386
+ // Apply filtering
387
+ const filteredReports = filterReports(allReports, options.reportOn, options.minConfidence ?? configMinConfidence ?? 'medium');
388
+ // Output results
389
+ reporter.blank();
390
+ if (options.json) {
391
+ const jsonlContent = renderJsonlString(filteredReports, totalDurationMs, lastRunMetadata ? {
392
+ runId: lastRunMetadata.runId,
393
+ traceId: lastRunMetadata.traceId,
394
+ timestamp: new Date(lastRunMetadata.timestamp),
395
+ model: lastRunMetadata.model,
396
+ headSha: lastRunMetadata.headSha,
397
+ cwd: lastRunMetadata.cwd,
398
+ } : undefined);
399
+ process.stdout.write(jsonlContent);
400
+ }
401
+ else {
402
+ console.log(renderTerminalReport(filteredReports, reporter.mode, { verbosity: reporter.verbosity }));
403
+ }
404
+ // Show summary
405
+ reporter.blank();
406
+ reporter.renderSummary(filteredReports, totalDurationMs);
407
+ return 0;
408
+ }
409
+ /**
410
+ * Garbage-collect expired log files.
411
+ */
412
+ export async function runRunsGc(options, reporter) {
413
+ const resolved = resolveLogDir();
414
+ if (!resolved) {
415
+ reporter.error('Not a git repository');
416
+ return 1;
417
+ }
418
+ const { logDir, repoPath } = resolved;
419
+ // Load config for retentionDays
420
+ let retentionDays = 30;
421
+ try {
422
+ const configPath = resolve(repoPath, 'warden.toml');
423
+ if (existsSync(configPath)) {
424
+ const config = loadWardenConfig(dirname(configPath));
425
+ retentionDays = config.logs?.retentionDays ?? 30;
426
+ }
427
+ }
428
+ catch {
429
+ // Use default
430
+ }
431
+ const expired = findExpiredArtifacts(logDir, retentionDays);
432
+ if (expired.length === 0) {
433
+ reporter.success('Nothing to clean up');
434
+ return 0;
435
+ }
436
+ let deleted = 0;
437
+ for (const filePath of expired) {
438
+ try {
439
+ unlinkSync(filePath);
440
+ deleted++;
441
+ }
442
+ catch {
443
+ // Skip files we can't delete
444
+ }
445
+ }
446
+ reporter.success(`Removed ${deleted} expired ${pluralize(deleted, 'log file')}`);
447
+ return 0;
448
+ }
449
+ /**
450
+ * Resolve a follow target. With no arg, picks the newest session whose
451
+ * file lacks a trailing `summary` record — a reliable proxy for "the
452
+ * run currently happening in another terminal."
453
+ */
454
+ function resolveFollowTarget(arg, logDir) {
455
+ if (arg) {
456
+ if (arg.includes('/') || arg.includes('.')) {
457
+ const path = resolve(process.cwd(), arg);
458
+ return existsSync(path) ? path : undefined;
459
+ }
460
+ return resolveFileArg(arg, logDir)[0];
461
+ }
462
+ let entries;
463
+ try {
464
+ entries = readdirSync(logDir)
465
+ .filter((e) => e.endsWith('.jsonl'))
466
+ .sort()
467
+ .reverse();
468
+ }
469
+ catch {
470
+ return undefined;
471
+ }
472
+ for (const entry of entries) {
473
+ const filePath = join(logDir, entry);
474
+ let content;
475
+ try {
476
+ content = readFileSync(filePath, 'utf-8');
477
+ }
478
+ catch {
479
+ continue;
480
+ }
481
+ const lines = content.trim().split('\n').filter((l) => l.trim());
482
+ const last = lines[lines.length - 1];
483
+ if (!last)
484
+ return filePath;
485
+ let parsed;
486
+ try {
487
+ parsed = JSON.parse(last);
488
+ }
489
+ catch {
490
+ // Corrupt tail — treating this as in-progress would hang forever.
491
+ continue;
492
+ }
493
+ if (parsed?.type !== 'summary') {
494
+ return filePath;
495
+ }
496
+ }
497
+ return undefined;
498
+ }
499
+ /** Render one JSONL line for the human follower. Stops on the summary record. */
500
+ function renderFollowLine(line, reporter) {
501
+ let parsed;
502
+ try {
503
+ parsed = JSON.parse(line);
504
+ }
505
+ catch {
506
+ reporter.warning(`Skipping malformed line: ${line.slice(0, 80)}`);
507
+ return { stop: false };
508
+ }
509
+ const obj = parsed;
510
+ if (obj.type === 'summary') {
511
+ const summary = JsonlSummaryRecordSchema.safeParse(obj);
512
+ if (summary.success) {
513
+ const { totalFindings, bySeverity } = summary.data;
514
+ reporter.blank();
515
+ reporter.text(chalk.dim(`Run finished — ${totalFindings} ${pluralize(totalFindings, 'finding')} `) +
516
+ formatSeverityBreakdown(bySeverity));
517
+ }
518
+ return { stop: true };
519
+ }
520
+ if (obj.type === 'fix-evaluation')
521
+ return { stop: false };
522
+ const skillResult = JsonlRecordSchema.safeParse(obj);
523
+ if (!skillResult.success) {
524
+ reporter.warning(`Skipping unrecognized record`);
525
+ return { stop: false };
526
+ }
527
+ const { run: _run, ...report } = skillResult.data;
528
+ console.log(renderTerminalReport([report], reporter.mode, { verbosity: reporter.verbosity }));
529
+ return { stop: false };
530
+ }
531
+ /** `--json` mode: pass the raw line through unmodified for downstream tools. */
532
+ function passthroughFollowLine(line) {
533
+ // One write keeps the line + newline atomic for piped consumers.
534
+ process.stdout.write(line + '\n');
535
+ try {
536
+ const parsed = JSON.parse(line);
537
+ if (parsed?.type === 'summary')
538
+ return { stop: true };
539
+ }
540
+ catch {
541
+ // partial / invalid line; keep waiting for a valid summary
542
+ }
543
+ return { stop: false };
544
+ }
545
+ /**
546
+ * Tail a JSONL session file, rendering each appended record live.
547
+ * Exits 0 on summary record or Ctrl-C — never on findings; this is a
548
+ * viewer, not a build gate.
549
+ */
550
+ export async function runRunsFollow(runsOptions, options, reporter) {
551
+ const resolved = resolveLogDir();
552
+ if (!resolved) {
553
+ reporter.error('Not a git repository');
554
+ return 1;
555
+ }
556
+ const { logDir } = resolved;
557
+ const target = resolveFollowTarget(runsOptions.files[0], logDir);
558
+ if (!target) {
559
+ if (runsOptions.files[0]) {
560
+ reporter.error(`No matching session for ${runsOptions.files[0]}`);
561
+ }
562
+ else {
563
+ reporter.error('No active session to follow');
564
+ reporter.tip('Start a run in another terminal, or pass an explicit run id.');
565
+ }
566
+ return 1;
567
+ }
568
+ if (!options.json) {
569
+ reporter.dim(`Following: ${target}`);
570
+ reporter.blank();
571
+ }
572
+ // Render anything already on disk and remember where we left off.
573
+ let offset = 0;
574
+ let buffer = '';
575
+ let stopped = false;
576
+ const drainFile = () => {
577
+ let fd;
578
+ try {
579
+ fd = openSync(target, 'r');
580
+ }
581
+ catch {
582
+ return;
583
+ }
584
+ try {
585
+ const stat = fstatSync(fd);
586
+ if (stat.size <= offset)
587
+ return;
588
+ const len = stat.size - offset;
589
+ const buf = Buffer.alloc(len);
590
+ readSync(fd, buf, 0, len, offset);
591
+ offset = stat.size;
592
+ buffer += buf.toString('utf-8');
593
+ let nl;
594
+ while ((nl = buffer.indexOf('\n')) >= 0) {
595
+ const line = buffer.slice(0, nl);
596
+ buffer = buffer.slice(nl + 1);
597
+ if (!line.trim())
598
+ continue;
599
+ const result = options.json
600
+ ? passthroughFollowLine(line)
601
+ : renderFollowLine(line, reporter);
602
+ if (result.stop) {
603
+ stopped = true;
604
+ return;
605
+ }
606
+ }
607
+ }
608
+ finally {
609
+ try {
610
+ closeSync(fd);
611
+ }
612
+ catch { /* ignore */ }
613
+ }
614
+ };
615
+ drainFile();
616
+ if (stopped)
617
+ return 0;
618
+ return new Promise((resolvePromise) => {
619
+ let watcher;
620
+ const tick = () => {
621
+ drainFile();
622
+ if (stopped)
623
+ finish(0);
624
+ };
625
+ // fs.watch is best-effort across platforms; the 1s poll below is the
626
+ // real correctness guarantee.
627
+ try {
628
+ watcher = watch(target, { persistent: true }, () => tick());
629
+ // FSWatcher 'error' would crash the process otherwise (file deleted, inotify limit, ...).
630
+ watcher.on('error', () => {
631
+ try {
632
+ watcher?.close();
633
+ }
634
+ catch { /* ignore */ }
635
+ watcher = undefined;
636
+ });
637
+ }
638
+ catch { /* polling alone is fine */ }
639
+ const pollTimer = setInterval(tick, 1000);
640
+ const finish = (code) => {
641
+ if (watcher) {
642
+ try {
643
+ watcher.close();
644
+ }
645
+ catch { /* ignore */ }
646
+ }
647
+ clearInterval(pollTimer);
648
+ process.off('SIGINT', onSigint);
649
+ resolvePromise(code);
650
+ };
651
+ const onSigint = () => finish(0);
652
+ process.on('SIGINT', onSigint);
653
+ });
654
+ }
655
+ /** Dispatch to the appropriate `runs` subcommand. */
656
+ export async function runRuns(runsOptions, options, reporter) {
657
+ switch (runsOptions.subcommand) {
658
+ case 'list':
659
+ return runRunsList(options, reporter, { all: runsOptions.all });
660
+ case 'show':
661
+ return runRunsShow(runsOptions, options, reporter);
662
+ case 'gc':
663
+ return runRunsGc(options, reporter);
664
+ case 'follow':
665
+ return runRunsFollow(runsOptions, options, reporter);
666
+ }
667
+ }
668
+ //# sourceMappingURL=runs.js.map