@sentry/warden 0.20.0 → 0.22.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 (77) hide show
  1. package/CHANGELOG.md +353 -0
  2. package/README.md +3 -3
  3. package/dist/cli/args.d.ts +7 -5
  4. package/dist/cli/args.d.ts.map +1 -1
  5. package/dist/cli/args.js +31 -17
  6. package/dist/cli/args.js.map +1 -1
  7. package/dist/cli/commands/runs.d.ts +26 -0
  8. package/dist/cli/commands/runs.d.ts.map +1 -0
  9. package/dist/cli/commands/runs.js +726 -0
  10. package/dist/cli/commands/runs.js.map +1 -0
  11. package/dist/cli/log-cleanup.d.ts.map +1 -1
  12. package/dist/cli/log-cleanup.js +4 -0
  13. package/dist/cli/log-cleanup.js.map +1 -1
  14. package/dist/cli/main.d.ts +15 -0
  15. package/dist/cli/main.d.ts.map +1 -1
  16. package/dist/cli/main.js +428 -128
  17. package/dist/cli/main.js.map +1 -1
  18. package/dist/cli/output/index.d.ts +1 -1
  19. package/dist/cli/output/index.d.ts.map +1 -1
  20. package/dist/cli/output/index.js +1 -1
  21. package/dist/cli/output/index.js.map +1 -1
  22. package/dist/cli/output/ink-runner.d.ts.map +1 -1
  23. package/dist/cli/output/ink-runner.js +50 -14
  24. package/dist/cli/output/ink-runner.js.map +1 -1
  25. package/dist/cli/output/jsonl-schema-gen.d.ts +16 -0
  26. package/dist/cli/output/jsonl-schema-gen.d.ts.map +1 -0
  27. package/dist/cli/output/jsonl-schema-gen.js +65 -0
  28. package/dist/cli/output/jsonl-schema-gen.js.map +1 -0
  29. package/dist/cli/output/jsonl.d.ts +266 -26
  30. package/dist/cli/output/jsonl.d.ts.map +1 -1
  31. package/dist/cli/output/jsonl.js +377 -139
  32. package/dist/cli/output/jsonl.js.map +1 -1
  33. package/dist/cli/output/tasks.d.ts +6 -1
  34. package/dist/cli/output/tasks.d.ts.map +1 -1
  35. package/dist/cli/output/tasks.js +183 -27
  36. package/dist/cli/output/tasks.js.map +1 -1
  37. package/dist/cli/terminal.d.ts.map +1 -1
  38. package/dist/cli/terminal.js +20 -0
  39. package/dist/cli/terminal.js.map +1 -1
  40. package/dist/index.d.ts +2 -2
  41. package/dist/index.d.ts.map +1 -1
  42. package/dist/index.js +2 -0
  43. package/dist/index.js.map +1 -1
  44. package/dist/sdk/analyze.d.ts.map +1 -1
  45. package/dist/sdk/analyze.js +103 -10
  46. package/dist/sdk/analyze.js.map +1 -1
  47. package/dist/sdk/errors.d.ts +11 -0
  48. package/dist/sdk/errors.d.ts.map +1 -1
  49. package/dist/sdk/errors.js +50 -0
  50. package/dist/sdk/errors.js.map +1 -1
  51. package/dist/sdk/runner.d.ts +1 -1
  52. package/dist/sdk/runner.d.ts.map +1 -1
  53. package/dist/sdk/types.d.ts +28 -1
  54. package/dist/sdk/types.d.ts.map +1 -1
  55. package/dist/types/index.d.ts +130 -6
  56. package/dist/types/index.d.ts.map +1 -1
  57. package/dist/types/index.js +72 -3
  58. package/dist/types/index.js.map +1 -1
  59. package/package.json +2 -1
  60. package/skills/warden/SKILL.md +5 -5
  61. package/skills/warden/SOURCES.md +39 -0
  62. package/skills/warden/references/cli-reference.md +11 -4
  63. package/skills/warden/references/config-schema.md +9 -0
  64. package/skills/warden/references/configuration.md +9 -0
  65. package/skills/warden-sweep/SKILL.md +43 -365
  66. package/skills/warden-sweep/SOURCES.md +43 -0
  67. package/skills/warden-sweep/references/issue-phase.md +24 -0
  68. package/skills/warden-sweep/references/organize-phase.md +31 -0
  69. package/skills/warden-sweep/references/patch-phase.md +142 -0
  70. package/skills/warden-sweep/references/resume-and-artifacts.md +51 -0
  71. package/skills/warden-sweep/references/scan-phase.md +46 -0
  72. package/skills/warden-sweep/references/script-interfaces.md +127 -0
  73. package/skills/warden-sweep/references/verify-phase.md +69 -0
  74. package/dist/cli/commands/logs.d.ts +0 -19
  75. package/dist/cli/commands/logs.d.ts.map +0 -1
  76. package/dist/cli/commands/logs.js +0 -412
  77. package/dist/cli/commands/logs.js.map +0 -1
@@ -0,0 +1,726 @@
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 { isExtractionErrorCode } from '../../types/index.js';
6
+ import { getRepoRoot } from '../git.js';
7
+ import { findExpiredArtifacts } from '../log-cleanup.js';
8
+ import { renderTerminalReport, filterReports } from '../terminal.js';
9
+ import { pluralize, formatDuration, formatCost, shortRunId, parseJsonlReports, parseLogMetadata, renderJsonlString, JsonlChunkRecordSchema, JsonlRecordSchema, JsonlSummaryRecordSchema, } from '../output/index.js';
10
+ /**
11
+ * Resolve a log directory path from the repo root.
12
+ */
13
+ function resolveLogDir() {
14
+ const cwd = process.cwd();
15
+ let repoPath;
16
+ try {
17
+ repoPath = getRepoRoot(cwd);
18
+ }
19
+ catch {
20
+ return undefined;
21
+ }
22
+ return { logDir: join(repoPath, '.warden', 'logs'), repoPath };
23
+ }
24
+ /**
25
+ * Recover an ISO timestamp from `{runId8}-{ISO-datetime}.jsonl`.
26
+ * Used as the list sort key for in-progress runs (no summary yet).
27
+ */
28
+ function filenameTimestamp(filename) {
29
+ const match = filename.match(/-(\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}-\d{3}Z)\.jsonl$/);
30
+ const stamp = match?.[1];
31
+ if (!stamp)
32
+ return '';
33
+ return stamp.replace(/^(\d{4}-\d{2}-\d{2}T\d{2})-(\d{2})-(\d{2})-(\d{3})Z$/, '$1:$2:$3.$4Z');
34
+ }
35
+ /**
36
+ * Resolve a file argument to a full path.
37
+ * If the argument looks like a run ID (no `/` or `.`), look up matching files in .warden/logs/.
38
+ */
39
+ function resolveFileArg(arg, logDir) {
40
+ // If it contains path separators or dots, treat as a file path
41
+ if (arg.includes('/') || arg.includes('.')) {
42
+ return [resolve(process.cwd(), arg)];
43
+ }
44
+ // Treat as a short run ID — glob for matching files
45
+ try {
46
+ const entries = readdirSync(logDir);
47
+ const matches = entries
48
+ .filter((e) => e.endsWith('.jsonl') && e.startsWith(arg))
49
+ .map((e) => join(logDir, e));
50
+ return matches;
51
+ }
52
+ catch {
53
+ return [];
54
+ }
55
+ }
56
+ // eslint-disable-next-line no-control-regex
57
+ const ANSI_RE = /\x1b\[[0-9;]*m/g;
58
+ /**
59
+ * Get the visual width of a string (ignoring ANSI escape codes).
60
+ */
61
+ function visualWidth(str) {
62
+ return str.replace(ANSI_RE, '').length;
63
+ }
64
+ /**
65
+ * Pad a string to a visual width, accounting for ANSI codes.
66
+ */
67
+ function padToWidth(str, width) {
68
+ const pad = width - visualWidth(str);
69
+ return pad > 0 ? str + ' '.repeat(pad) : str;
70
+ }
71
+ /**
72
+ * Right-align a string to a visual width, accounting for ANSI codes.
73
+ */
74
+ function rightAlign(str, width) {
75
+ const pad = width - visualWidth(str);
76
+ return pad > 0 ? ' '.repeat(pad) + str : str;
77
+ }
78
+ /**
79
+ * Format a date as a human-friendly relative or short absolute string.
80
+ */
81
+ function formatRelativeTime(date) {
82
+ const now = Date.now();
83
+ const diffMs = now - date.getTime();
84
+ const diffSec = Math.floor(diffMs / 1000);
85
+ const diffMin = Math.floor(diffSec / 60);
86
+ const diffHr = Math.floor(diffMin / 60);
87
+ const diffDays = Math.floor(diffHr / 24);
88
+ if (diffSec < 60)
89
+ return 'just now';
90
+ if (diffMin < 60)
91
+ return `${diffMin}m ago`;
92
+ if (diffHr < 24)
93
+ return `${diffHr}h ago`;
94
+ if (diffDays === 1)
95
+ return 'yesterday';
96
+ if (diffDays < 7)
97
+ return `${diffDays}d ago`;
98
+ // Older than a week: show short date
99
+ const month = date.toLocaleString('en-US', { month: 'short' });
100
+ const day = date.getDate();
101
+ const year = date.getFullYear();
102
+ const currentYear = new Date().getFullYear();
103
+ return year === currentYear ? `${month} ${day}` : `${month} ${day}, ${year}`;
104
+ }
105
+ const SEVERITY_COLORS = {
106
+ high: chalk.red,
107
+ medium: chalk.yellow,
108
+ low: chalk.green,
109
+ };
110
+ /**
111
+ * Format a severity breakdown as colored counts.
112
+ */
113
+ function formatSeverityBreakdown(bySeverity) {
114
+ const severities = ['high', 'medium', 'low'];
115
+ const parts = severities.map((sev) => {
116
+ const count = bySeverity[sev] ?? 0;
117
+ return count > 0 ? SEVERITY_COLORS[sev](String(count)) : chalk.dim('0');
118
+ });
119
+ return parts.join(chalk.dim(' / '));
120
+ }
121
+ /**
122
+ * List sessions in `.warden/logs/`. Empty (no-file, no-skill) runs
123
+ * are hidden unless `all` is set.
124
+ */
125
+ export async function runRunsList(options, reporter, listOptions = {}) {
126
+ const resolved = resolveLogDir();
127
+ if (!resolved) {
128
+ reporter.error('Not a git repository');
129
+ return 1;
130
+ }
131
+ const { logDir } = resolved;
132
+ let entries;
133
+ try {
134
+ entries = readdirSync(logDir)
135
+ .filter((e) => e.endsWith('.jsonl'))
136
+ .sort((a, b) => filenameTimestamp(b).localeCompare(filenameTimestamp(a)));
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
+ try {
441
+ unlinkSync(`${filePath}.done`);
442
+ }
443
+ catch { /* sidecar may not exist */ }
444
+ deleted++;
445
+ }
446
+ catch {
447
+ // Skip files we can't delete
448
+ }
449
+ }
450
+ reporter.success(`Removed ${deleted} expired ${pluralize(deleted, 'log file')}`);
451
+ return 0;
452
+ }
453
+ /**
454
+ * Resolve a follow target. With no arg, picks the newest session whose
455
+ * file lacks a trailing `summary` record — a reliable proxy for "the
456
+ * run currently happening in another terminal."
457
+ */
458
+ function resolveFollowTarget(arg, logDir) {
459
+ if (arg) {
460
+ if (arg.includes('/') || arg.includes('.')) {
461
+ const path = resolve(process.cwd(), arg);
462
+ return existsSync(path) ? path : undefined;
463
+ }
464
+ return resolveFileArg(arg, logDir)[0];
465
+ }
466
+ let entries;
467
+ try {
468
+ entries = readdirSync(logDir)
469
+ .filter((e) => e.endsWith('.jsonl'))
470
+ .sort((a, b) => filenameTimestamp(b).localeCompare(filenameTimestamp(a)));
471
+ }
472
+ catch {
473
+ return undefined;
474
+ }
475
+ for (const entry of entries) {
476
+ const filePath = join(logDir, entry);
477
+ if (!arg && existsSync(`${filePath}.done`))
478
+ continue;
479
+ let content;
480
+ try {
481
+ content = readFileSync(filePath, 'utf-8');
482
+ }
483
+ catch {
484
+ continue;
485
+ }
486
+ const lines = content.trim().split('\n').filter((l) => l.trim());
487
+ const last = lines[lines.length - 1];
488
+ if (!last)
489
+ return filePath;
490
+ let parsed;
491
+ try {
492
+ parsed = JSON.parse(last);
493
+ }
494
+ catch {
495
+ // Corrupt tail — treating this as in-progress would hang forever.
496
+ continue;
497
+ }
498
+ if (parsed?.type !== 'summary') {
499
+ return filePath;
500
+ }
501
+ }
502
+ return undefined;
503
+ }
504
+ /** Render one JSONL line for the human follower. Stops on the summary record. */
505
+ function renderFollowLine(line, reporter) {
506
+ let parsed;
507
+ try {
508
+ parsed = JSON.parse(line);
509
+ }
510
+ catch {
511
+ reporter.warning(`Skipping malformed line: ${line.slice(0, 80)}`);
512
+ return { stop: false };
513
+ }
514
+ const obj = parsed;
515
+ if (obj.type === 'summary') {
516
+ const summary = JsonlSummaryRecordSchema.safeParse(obj);
517
+ if (summary.success) {
518
+ const { totalFindings, bySeverity } = summary.data;
519
+ reporter.blank();
520
+ reporter.text(chalk.dim(`Run finished — ${totalFindings} ${pluralize(totalFindings, 'finding')} `) +
521
+ formatSeverityBreakdown(bySeverity));
522
+ }
523
+ return { stop: true };
524
+ }
525
+ if (obj.type === 'fix-evaluation')
526
+ return { stop: false };
527
+ const chunkResult = JsonlChunkRecordSchema.safeParse(obj);
528
+ if (chunkResult.success) {
529
+ const chunk = chunkResult.data;
530
+ if (chunk.findings.length === 0 && !chunk.error)
531
+ return { stop: false };
532
+ console.log(renderTerminalReport([{
533
+ skill: chunk.skill,
534
+ summary: chunk.findings.length > 0
535
+ ? `${chunk.skill}: Found ${chunk.findings.length} ${pluralize(chunk.findings.length, 'issue')}`
536
+ : `${chunk.skill}: chunk failed`,
537
+ findings: chunk.findings,
538
+ durationMs: chunk.durationMs,
539
+ usage: chunk.usage,
540
+ model: chunk.model,
541
+ files: [{
542
+ filename: chunk.chunk.file,
543
+ findings: chunk.findings.length,
544
+ durationMs: chunk.durationMs,
545
+ usage: chunk.usage,
546
+ }],
547
+ error: chunk.error,
548
+ hunkFailures: chunk.error
549
+ ? [{
550
+ type: isExtractionErrorCode(chunk.error.code) ? 'extraction' : 'analysis',
551
+ filename: chunk.chunk.file,
552
+ lineRange: chunk.chunk.lineRange,
553
+ code: chunk.error.code,
554
+ message: chunk.error.message,
555
+ }]
556
+ : undefined,
557
+ }], reporter.mode, { verbosity: reporter.verbosity }));
558
+ return { stop: false };
559
+ }
560
+ const skillResult = JsonlRecordSchema.safeParse(obj);
561
+ if (!skillResult.success) {
562
+ reporter.warning(`Skipping unrecognized record`);
563
+ return { stop: false };
564
+ }
565
+ const { run: _run, ...report } = skillResult.data;
566
+ console.log(renderTerminalReport([report], reporter.mode, { verbosity: reporter.verbosity }));
567
+ return { stop: false };
568
+ }
569
+ /** `--json` mode: pass the raw line through unmodified for downstream tools. */
570
+ function passthroughFollowLine(line) {
571
+ // One write keeps the line + newline atomic for piped consumers.
572
+ process.stdout.write(line + '\n');
573
+ try {
574
+ const parsed = JSON.parse(line);
575
+ if (parsed?.type === 'summary')
576
+ return { stop: true };
577
+ }
578
+ catch {
579
+ // partial / invalid line; keep waiting for a valid summary
580
+ }
581
+ return { stop: false };
582
+ }
583
+ /**
584
+ * Tail a JSONL session file, rendering each appended record live.
585
+ * Exits 0 on summary record or Ctrl-C — never on findings; this is a
586
+ * viewer, not a build gate.
587
+ */
588
+ export async function runRunsFollow(runsOptions, options, reporter) {
589
+ const resolved = resolveLogDir();
590
+ if (!resolved) {
591
+ reporter.error('Not a git repository');
592
+ return 1;
593
+ }
594
+ const { logDir } = resolved;
595
+ const target = resolveFollowTarget(runsOptions.files[0], logDir);
596
+ if (!target) {
597
+ if (runsOptions.files[0]) {
598
+ reporter.error(`No matching session for ${runsOptions.files[0]}`);
599
+ }
600
+ else {
601
+ reporter.error('No active session to follow');
602
+ reporter.tip('Start a run in another terminal, or pass an explicit run id.');
603
+ }
604
+ return 1;
605
+ }
606
+ if (!options.json) {
607
+ reporter.dim(`Following: ${target}`);
608
+ reporter.blank();
609
+ }
610
+ // Render anything already on disk and remember where we left off.
611
+ let offset = 0;
612
+ let buffer = '';
613
+ let fileIdentity;
614
+ let stopped = false;
615
+ const emittedJsonLines = new Set();
616
+ const targetComplete = () => existsSync(`${target}.done`);
617
+ const drainFile = () => {
618
+ let fd;
619
+ try {
620
+ fd = openSync(target, 'r');
621
+ }
622
+ catch {
623
+ return;
624
+ }
625
+ try {
626
+ const stat = fstatSync(fd);
627
+ const identity = `${stat.dev}:${stat.ino}`;
628
+ if (fileIdentity && identity !== fileIdentity) {
629
+ fileIdentity = identity;
630
+ buffer = '';
631
+ if (offset > 0 && !options.json) {
632
+ offset = stat.size;
633
+ return;
634
+ }
635
+ offset = 0;
636
+ }
637
+ fileIdentity = identity;
638
+ if (stat.size < offset) {
639
+ buffer = '';
640
+ offset = 0;
641
+ }
642
+ if (stat.size <= offset)
643
+ return;
644
+ const len = stat.size - offset;
645
+ const buf = Buffer.alloc(len);
646
+ readSync(fd, buf, 0, len, offset);
647
+ offset = stat.size;
648
+ buffer += buf.toString('utf-8');
649
+ let nl;
650
+ while ((nl = buffer.indexOf('\n')) >= 0) {
651
+ const line = buffer.slice(0, nl);
652
+ buffer = buffer.slice(nl + 1);
653
+ if (!line.trim())
654
+ continue;
655
+ if (options.json && emittedJsonLines.has(line))
656
+ continue;
657
+ if (options.json)
658
+ emittedJsonLines.add(line);
659
+ const result = options.json ? passthroughFollowLine(line) : renderFollowLine(line, reporter);
660
+ if (result.stop) {
661
+ stopped = true;
662
+ return;
663
+ }
664
+ }
665
+ }
666
+ finally {
667
+ try {
668
+ closeSync(fd);
669
+ }
670
+ catch { /* ignore */ }
671
+ }
672
+ };
673
+ drainFile();
674
+ if (stopped || targetComplete())
675
+ return 0;
676
+ return new Promise((resolvePromise) => {
677
+ let watcher;
678
+ const tick = () => {
679
+ drainFile();
680
+ if (stopped || targetComplete())
681
+ finish(0);
682
+ };
683
+ // fs.watch is best-effort across platforms; the 1s poll below is the
684
+ // real correctness guarantee.
685
+ try {
686
+ watcher = watch(target, { persistent: true }, () => tick());
687
+ // FSWatcher 'error' would crash the process otherwise (file deleted, inotify limit, ...).
688
+ watcher.on('error', () => {
689
+ try {
690
+ watcher?.close();
691
+ }
692
+ catch { /* ignore */ }
693
+ watcher = undefined;
694
+ });
695
+ }
696
+ catch { /* polling alone is fine */ }
697
+ const pollTimer = setInterval(tick, 1000);
698
+ const finish = (code) => {
699
+ if (watcher) {
700
+ try {
701
+ watcher.close();
702
+ }
703
+ catch { /* ignore */ }
704
+ }
705
+ clearInterval(pollTimer);
706
+ process.off('SIGINT', onSigint);
707
+ resolvePromise(code);
708
+ };
709
+ const onSigint = () => finish(0);
710
+ process.on('SIGINT', onSigint);
711
+ });
712
+ }
713
+ /** Dispatch to the appropriate `runs` subcommand. */
714
+ export async function runRuns(runsOptions, options, reporter) {
715
+ switch (runsOptions.subcommand) {
716
+ case 'list':
717
+ return runRunsList(options, reporter, { all: runsOptions.all });
718
+ case 'show':
719
+ return runRunsShow(runsOptions, options, reporter);
720
+ case 'gc':
721
+ return runRunsGc(options, reporter);
722
+ case 'follow':
723
+ return runRunsFollow(runsOptions, options, reporter);
724
+ }
725
+ }
726
+ //# sourceMappingURL=runs.js.map