xcodebug 1.2.1 → 1.2.3

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.
package/capture.ts CHANGED
@@ -4,9 +4,9 @@
4
4
  * back through a cursor so the agent can fetch only what is new.
5
5
  */
6
6
  import { spawn, type ChildProcess } from "node:child_process";
7
- import { createWriteStream, type WriteStream } from "node:fs";
8
- import { mkdir } from "node:fs/promises";
9
- import { dirname } from "node:path";
7
+ import { appendFileSync, createReadStream, createWriteStream, statSync, type WriteStream } from "node:fs";
8
+ import { lstat, mkdir, mkdtemp, readFile, readdir, rmdir, unlink, writeFile } from "node:fs/promises";
9
+ import { dirname, join } from "node:path";
10
10
  import { finished } from "node:stream/promises";
11
11
  import { timestamp } from "./exec.ts";
12
12
 
@@ -26,6 +26,9 @@ export interface LogLine {
26
26
  text: string;
27
27
  }
28
28
 
29
+ /** A line as a search returns it: one read back from disk has no stream. */
30
+ export type FoundLine = Pick<LogLine, "index" | "at" | "text"> & Partial<Pick<LogLine, "stream">>;
31
+
29
32
  export interface CaptureInit {
30
33
  mode: CaptureMode;
31
34
  deviceId: string;
@@ -37,6 +40,8 @@ export interface CaptureInit {
37
40
  logDir: string;
38
41
  command: string;
39
42
  args: string[];
43
+ /** Collect the native console launch's raw command result, outside the log stream. */
44
+ collectLaunchResult?: boolean;
40
45
  /** Reuse an existing log file (used when auto-reconnecting a dropped bridge). */
41
46
  logFile?: string;
42
47
  /** How new lines are mirrored into the session; the reconnect path restarts it. */
@@ -65,12 +70,59 @@ export interface CaptureStatus {
65
70
  logFiles: string[];
66
71
  commandLine: string;
67
72
  error?: string;
73
+ relaunches: number;
74
+ endReason?: string;
75
+ crashReport?: string;
76
+ terminationReason?: string;
68
77
  }
69
78
 
70
79
  function clean(text: string): string {
71
80
  return text.replace(ANSI, "").replace(/\r/g, "");
72
81
  }
73
82
 
83
+ function clampLimit(limit: number | undefined): number {
84
+ return Math.trunc(Math.min(Math.max(1, limit ?? 200), 5_000));
85
+ }
86
+
87
+ /** A filter is a substring, or a pattern when the caller asked for one. */
88
+ export function matchesFilter(text: string, filter: string | RegExp): boolean {
89
+ return typeof filter === "string" ? text.includes(filter) : filter.test(text);
90
+ }
91
+
92
+ function sizeOnDisk(path: string): number {
93
+ try {
94
+ return statSync(path).size;
95
+ } catch {
96
+ return 0;
97
+ }
98
+ }
99
+
100
+ async function removeLaunchResultDirectory(path: string): Promise<void> {
101
+ const directory = await lstat(path);
102
+ if (!directory.isDirectory()) throw new Error("owned result path is not a real directory");
103
+ const entries = (await readdir(path)).sort();
104
+ if (entries.some(name => name !== "owner.json" && name !== "launch.json")) {
105
+ throw new Error("owned result directory contains an unexpected entry");
106
+ }
107
+ const files = [];
108
+ for (const name of entries) {
109
+ const filePath = join(path, name);
110
+ const file = await lstat(filePath);
111
+ if (!file.isFile()) throw new Error("owned result payload is not a real file");
112
+ files.push({ path: filePath, stat: file });
113
+ }
114
+ for (const file of files) {
115
+ const currentDirectory = await lstat(path);
116
+ const currentFile = await lstat(file.path);
117
+ if (!currentDirectory.isDirectory() || currentDirectory.dev !== directory.dev || currentDirectory.ino !== directory.ino ||
118
+ !currentFile.isFile() || currentFile.dev !== file.stat.dev || currentFile.ino !== file.stat.ino) {
119
+ throw new Error("owned result path changed during cleanup");
120
+ }
121
+ await unlink(file.path);
122
+ }
123
+ await rmdir(path);
124
+ }
125
+
74
126
  export class Capture {
75
127
  readonly id: string;
76
128
  readonly mode: CaptureMode;
@@ -78,13 +130,22 @@ export class Capture {
78
130
  readonly deviceLabel: string;
79
131
  readonly bundleId: string;
80
132
  readonly processName?: string;
81
- /** App pid on the device; filled in once discovery succeeds, never the bridge pid. */
133
+ /** Operational live PID; exit diagnosis replaces it with the owned launch result's PID. */
82
134
  appPid?: number;
83
135
  readonly startedAt = Date.now();
84
136
  readonly logFile: string;
85
137
 
86
138
  readonly command: string;
87
139
  readonly launchArgs: string[];
140
+ /** One owned native command result per bridge start; absent for generic captures. */
141
+ launchResult?: Promise<string | undefined>;
142
+ private readonly collectLaunchResult: boolean;
143
+ private spawnedArgs: string[];
144
+ private shuttingDown = false;
145
+ private readonly startups = new Set<Promise<void>>();
146
+ private readonly resultJobs = new Set<{ done: Promise<void>; cancel: () => void }>();
147
+ /** Failed result removals survive reattachment and history eviction until session shutdown reports them. */
148
+ launchResultCleanupErrors?: string[];
88
149
  /** Set when the user explicitly stops this capture, so auto-reconnect stays off. */
89
150
  stoppedByUser = false;
90
151
  /**
@@ -103,6 +164,18 @@ export class Capture {
103
164
  * emits anything still ages from a sane starting point.
104
165
  */
105
166
  lastLineAt = Date.now();
167
+ /**
168
+ * Times the console bridge was reattached. devicectl attaches a console only
169
+ * by launching, so each one restarted the app and dropped its state.
170
+ */
171
+ relaunches = 0;
172
+ /** Why the capture ended without being asked to. */
173
+ endReason?: string;
174
+ /** The crash report pulled from the device after the app died, if it left one. */
175
+ crashReport?: string;
176
+ terminationReason?: string;
177
+ /** Bridge exit time before any stop, retained through drain and report collection. */
178
+ naturalExitAt?: number;
106
179
  /**
107
180
  * Aborted when this capture is stopped, so an in-flight device probe returns
108
181
  * at once instead of running out its own timeout first.
@@ -124,9 +197,24 @@ export class Capture {
124
197
  private fileNumber = 0;
125
198
  private fileOrder = 0;
126
199
  private readonly logFiles = new Map<string, number>();
200
+ /** Only overwriting an existing segment invalidates an in-flight disk scan. */
201
+ private readonly fileVersions = new Map<string, number>();
202
+ /**
203
+ * Where each run of consecutively indexed lines starts on disk. The files
204
+ * carry no index and have holes - a rotated segment is overwritten, and a
205
+ * write that fails takes its lines with it - so a line's index is only
206
+ * recoverable per run.
207
+ */
208
+ private runs: Array<{ path: string; offset: number; index: number }> = [];
209
+ /** The segment being written, and where its next run starts once a line arrives. */
210
+ private segment = "";
211
+ private opened: { path: string; offset: number } | undefined;
212
+ /** True while lines are appended with the bridge down, which is one run. */
213
+ private appending = false;
127
214
  private readonly files = new Set<WriteStream>();
128
215
  private readonly blockedFiles = new Set<WriteStream>();
129
216
  private readonly exitListeners = new Set<(code: number | undefined, signal: string | undefined) => void>();
217
+ private readonly processExitListeners = new Set<(code: number | undefined, signal: string | undefined) => void>();
130
218
  private readonly lineListeners = new Set<(line: LogLine) => void>();
131
219
 
132
220
  constructor(init: CaptureInit) {
@@ -140,6 +228,8 @@ export class Capture {
140
228
  this.pushMode = init.pushMode;
141
229
  this.command = init.command;
142
230
  this.launchArgs = init.args;
231
+ this.collectLaunchResult = init.mode === "console" && init.collectLaunchResult === true;
232
+ this.spawnedArgs = this.launchArgs;
143
233
  this.logFile =
144
234
  init.logFile ?? `${init.logDir}/${init.mode}-${init.bundleId}-${timestamp()}.log`;
145
235
  }
@@ -149,17 +239,37 @@ export class Capture {
149
239
  return this.child !== undefined;
150
240
  }
151
241
 
242
+ get starting(): boolean {
243
+ return this.startups.size > 0;
244
+ }
245
+
246
+ get processExited(): boolean {
247
+ return this.child
248
+ ? this.child.exitCode !== null || this.child.signalCode !== null
249
+ : this.exitCode !== undefined || this.exitSignal !== undefined;
250
+ }
251
+
152
252
  /** Clear the terminal state so start() can attach a fresh bridge. */
153
253
  resetForReconnect(): void {
154
254
  this.exitCode = undefined;
155
255
  this.exitSignal = undefined;
156
256
  this.error = undefined;
257
+ this.endReason = undefined;
258
+ this.crashReport = undefined;
259
+ this.terminationReason = undefined;
260
+ this.naturalExitAt = undefined;
157
261
  this.buffered = { out: "", err: "" };
158
262
  // A fresh bridge starts its silence clock now, or the watchdog would see the
159
263
  // gap it just repaired and immediately restart the new bridge too.
160
264
  this.lastLineAt = Date.now();
161
265
  }
162
266
 
267
+ /** Observe process exit before the pipes and writers finish draining. */
268
+ onProcessExit(listener: (code: number | undefined, signal: string | undefined) => void): () => void {
269
+ this.processExitListeners.add(listener);
270
+ return () => this.processExitListeners.delete(listener);
271
+ }
272
+
163
273
  get pid(): number | undefined {
164
274
  return this.child?.pid;
165
275
  }
@@ -175,12 +285,98 @@ export class Capture {
175
285
  return () => this.lineListeners.delete(listener);
176
286
  }
177
287
 
178
- async start(): Promise<void> {
179
- await mkdir(dirname(this.logFile), { recursive: true });
180
- this.openFile(true);
288
+ start(signal?: AbortSignal): Promise<void> {
289
+ if (this.shuttingDown) return Promise.resolve();
290
+ let resolveStartup!: () => void;
291
+ const startup = new Promise<void>(resolve => { resolveStartup = resolve; });
292
+ this.startups.add(startup);
293
+ const operation = this.startRun(signal);
294
+ const complete = (): void => {
295
+ this.startups.delete(startup);
296
+ resolveStartup();
297
+ };
298
+ void operation.then(complete, complete);
299
+ return operation;
300
+ }
181
301
 
182
- const child = spawn(this.command, this.launchArgs, { stdio: ["ignore", "pipe", "pipe"] });
183
- this.child = child;
302
+ private async startRun(signal?: AbortSignal): Promise<void> {
303
+ let resultDir: string | undefined;
304
+ let resolveResult: ((raw: string | undefined) => void) | undefined;
305
+ let resolveCleanup: (() => void) | undefined;
306
+ let resultJob: { done: Promise<void>; cancel: () => void } | undefined;
307
+ let collecting = false;
308
+ const resultAbort = this.collectLaunchResult ? new AbortController() : undefined;
309
+ if (resultAbort) {
310
+ // Node 20's Promise API requires an executor; it has no withResolvers().
311
+ this.launchResult = new Promise((resolve) => { resolveResult = resolve; });
312
+ resultJob = {
313
+ done: new Promise(resolve => { resolveCleanup = resolve; }),
314
+ cancel: () => resultAbort.abort(),
315
+ };
316
+ this.resultJobs.add(resultJob);
317
+ }
318
+ const result = this.launchResult;
319
+ // Exit diagnosis outlives stop/reconnect; only session shutdown cancels its read.
320
+ const collectResult = async (): Promise<void> => {
321
+ if (!resolveResult || !resultAbort || collecting) return;
322
+ collecting = true;
323
+ let raw: string | undefined;
324
+ let onAbort: (() => void) | undefined;
325
+ try {
326
+ if (resultDir && !resultAbort.signal.aborted) {
327
+ raw = await Promise.race([
328
+ readFile(join(resultDir, "launch.json"), { encoding: "utf8", signal: resultAbort.signal }).catch(() => undefined),
329
+ new Promise<undefined>(resolve => {
330
+ onAbort = () => resolve(undefined);
331
+ resultAbort.signal.addEventListener("abort", onAbort, { once: true });
332
+ if (resultAbort.signal.aborted) onAbort();
333
+ }),
334
+ ]);
335
+ }
336
+ } catch {
337
+ // A killed console or failed spawn may never produce a command result.
338
+ } finally {
339
+ if (onAbort) resultAbort.signal.removeEventListener("abort", onAbort);
340
+ if (resultDir) await removeLaunchResultDirectory(resultDir).catch(error => {
341
+ const detail = `launch result cleanup failed: ${resultDir}: ${error instanceof Error ? error.message : String(error)}`;
342
+ (this.launchResultCleanupErrors ??= []).push(detail);
343
+ if (this.launchResult !== result) return;
344
+ this.error = this.error ? `${this.error}; ${detail}` : detail;
345
+ });
346
+ resolveResult(resultAbort.signal.aborted ? undefined : raw);
347
+ if (resultJob) this.resultJobs.delete(resultJob);
348
+ resolveCleanup?.();
349
+ }
350
+ };
351
+ let child: ChildProcess;
352
+ try {
353
+ await mkdir(dirname(this.logFile), { recursive: true });
354
+ signal?.throwIfAborted();
355
+ if (this.stoppedByUser || this.shuttingDown) { await collectResult(); return; }
356
+ let args = this.launchArgs;
357
+ if (this.collectLaunchResult) {
358
+ resultDir = await mkdtemp(join(dirname(this.logFile), ".xcodebug-launch-"));
359
+ signal?.throwIfAborted();
360
+ if (this.stoppedByUser || this.shuttingDown) { await collectResult(); return; }
361
+ await writeFile(join(resultDir, "owner.json"), JSON.stringify({
362
+ kind: "xcodebug.launch-result", version: 1, pid: process.pid, createdAt: Date.now(),
363
+ }), { mode: 0o600, flag: "wx" });
364
+ signal?.throwIfAborted();
365
+ if (this.stoppedByUser || this.shuttingDown) { await collectResult(); return; }
366
+ const consoleIndex = args.indexOf("--console");
367
+ const separatorIndex = args.indexOf("--");
368
+ const index = consoleIndex >= 0 ? consoleIndex : separatorIndex >= 0 ? separatorIndex : args.length;
369
+ args = args.slice();
370
+ args.splice(index, 0, "--json-output", join(resultDir, "launch.json"));
371
+ }
372
+ this.openFile(true);
373
+ this.spawnedArgs = args;
374
+ child = spawn(this.command, args, { stdio: ["ignore", "pipe", "pipe"] });
375
+ this.child = child;
376
+ } catch (error) {
377
+ await collectResult();
378
+ throw error;
379
+ }
184
380
  let finishing = false;
185
381
  let drainTimer: NodeJS.Timeout | undefined;
186
382
  const drainAbort = new AbortController();
@@ -236,13 +432,24 @@ export class Capture {
236
432
  if (this.child === child) this.consume("err", chunk);
237
433
  });
238
434
  child.on("error", (error: Error) => {
435
+ void collectResult();
239
436
  if (this.child !== child) return;
240
437
  this.error = error.message;
241
438
  this.pushLine("err", `[xcodebug] failed to start: ${error.message}`);
242
439
  finish(undefined, undefined);
243
440
  });
244
441
  // `close` can itself wait forever while a backed-up writer pauses the pipes.
245
- child.on("exit", (code, signal) => beginDrain(code ?? undefined, signal ?? undefined));
442
+ child.on("exit", (code, signal) => {
443
+ void collectResult();
444
+ if (this.child !== child) return;
445
+ if (!this.stoppedByUser) this.naturalExitAt = Date.now();
446
+ beginDrain(code ?? undefined, signal ?? undefined);
447
+ for (const listener of this.processExitListeners) {
448
+ try { listener(code ?? undefined, signal ?? undefined); } catch {
449
+ // A listener must never break capture teardown.
450
+ }
451
+ }
452
+ });
246
453
  child.on("close", (code: number | null, signal: NodeJS.Signals | null) => {
247
454
  if (this.child !== child) return;
248
455
  this.flush("out");
@@ -253,6 +460,13 @@ export class Capture {
253
460
 
254
461
  private openFile(append: boolean): void {
255
462
  const path = this.fileNumber === 0 ? this.logFile : `${this.logFile}.${this.fileNumber}`;
463
+ if (!append && this.runs.some((run) => run.path === path)) {
464
+ this.runs = this.runs.filter((run) => run.path !== path);
465
+ this.fileVersions.set(path, (this.fileVersions.get(path) ?? 0) + 1);
466
+ }
467
+ this.segment = path;
468
+ this.opened = { path, offset: append ? sizeOnDisk(path) : 0 };
469
+ this.appending = false;
256
470
  const file = createWriteStream(path, { flags: append ? "a" : "w" });
257
471
  this.file = file;
258
472
  this.files.add(file);
@@ -321,15 +535,8 @@ export class Capture {
321
535
  // Still deliver and write an oversized line, without retaining it in memory.
322
536
  this.droppedLines += 1;
323
537
  }
324
- for (const listener of this.lineListeners) {
325
- try {
326
- listener(line);
327
- } catch {
328
- // A listener must never break capture.
329
- }
330
- }
538
+ const encoded = `${new Date(line.at).toISOString()} ${line.text}\n`;
331
539
  if (this.file) {
332
- const encoded = `${new Date(line.at).toISOString()} ${line.text}\n`;
333
540
  const size = Buffer.byteLength(encoded);
334
541
  if (this.fileBytes > 0 && this.fileBytes + size > MAX_FILE_BYTES) {
335
542
  this.file.end();
@@ -337,6 +544,10 @@ export class Capture {
337
544
  this.fileBytes = 0;
338
545
  this.openFile(false);
339
546
  }
547
+ if (this.opened) {
548
+ this.runs.push({ ...this.opened, index: line.index });
549
+ this.opened = undefined;
550
+ }
340
551
  this.fileBytes += size;
341
552
  const file = this.file;
342
553
  if (!file.write(encoded)) {
@@ -344,6 +555,26 @@ export class Capture {
344
555
  this.child?.stdout?.pause();
345
556
  this.child?.stderr?.pause();
346
557
  }
558
+ } else if (!this.child && this.segment) {
559
+ // The bridge is down and its file is closed. What is said meanwhile - why
560
+ // it ended, each reattach - is what explains the rest of the log, so it
561
+ // goes to disk too. Only a few lines arrive in this state.
562
+ try {
563
+ const offset = this.appending ? undefined : sizeOnDisk(this.segment);
564
+ appendFileSync(this.segment, encoded);
565
+ if (offset !== undefined) this.runs.push({ path: this.segment, offset, index: line.index });
566
+ this.appending = true;
567
+ } catch {
568
+ // The log could not be written before either; the line is still in memory.
569
+ this.appending = false;
570
+ }
571
+ }
572
+ for (const listener of this.lineListeners) {
573
+ try {
574
+ listener(line);
575
+ } catch {
576
+ // A listener must never break capture.
577
+ }
347
578
  }
348
579
  }
349
580
 
@@ -360,6 +591,39 @@ export class Capture {
360
591
  }
361
592
  }
362
593
 
594
+ /** Join every retained per-start result task, including old reconnect results. */
595
+ async waitForLaunchResults(): Promise<void> {
596
+ await Promise.all([...this.resultJobs].map(job => job.done));
597
+ }
598
+
599
+ /** Session exit cancels diagnostics as well as the bridge, unlike ordinary stop. */
600
+ shutdown(timeoutMs = 3_000): Promise<boolean> {
601
+ this.shuttingDown = true;
602
+ this.stop(false);
603
+ for (const job of this.resultJobs) job.cancel();
604
+ return new Promise(resolve => {
605
+ let settled = false;
606
+ let unsubscribe = (): void => {};
607
+ const done = (cleaned: boolean): void => {
608
+ if (settled) return;
609
+ settled = true;
610
+ clearTimeout(timer);
611
+ unsubscribe();
612
+ if (!cleaned) {
613
+ const detail = `capture shutdown timed out after ${timeoutMs}ms; resource cleanup remains pending`;
614
+ this.error = this.error ? `${this.error}; ${detail}` : detail;
615
+ }
616
+ resolve(cleaned);
617
+ };
618
+ const timer = setTimeout(() => done(false), Math.max(0, timeoutMs));
619
+ timer.unref();
620
+ const drained = this.running
621
+ ? new Promise<void>(resolve => { unsubscribe = this.onExit(() => resolve()); })
622
+ : Promise.resolve();
623
+ void Promise.all([Promise.all([...this.startups]), this.waitForLaunchResults(), drained]).then(() => done(true));
624
+ });
625
+ }
626
+
363
627
  /**
364
628
  * Kill the bridge for a restart, without touching `stoppedByUser`.
365
629
  *
@@ -394,14 +658,16 @@ export class Capture {
394
658
  });
395
659
  }
396
660
 
397
- read(options: { since?: number; limit?: number; grep?: string; streams?: Array<"out" | "err"> }): {
661
+ read(options: { since?: number; limit?: number; grep?: string | RegExp; streams?: Array<"out" | "err"> }): {
398
662
  lines: LogLine[];
399
663
  cursor: number;
400
664
  total: number;
665
+ /** Lines after `since` that the buffer has already dropped. */
666
+ evicted: number;
401
667
  } {
402
668
  const since = Math.max(0, options.since ?? 0);
403
- const limit = Math.trunc(Math.min(Math.max(1, options.limit ?? 200), 5_000));
404
- const grep = options.grep?.trim();
669
+ const limit = clampLimit(options.limit);
670
+ const grep = typeof options.grep === "string" ? options.grep.trim() : options.grep;
405
671
  const streams = options.streams;
406
672
  // Locate the first eligible index without scanning or copying the buffer.
407
673
  let first = 0;
@@ -411,23 +677,142 @@ export class Capture {
411
677
  if (this.lines[(this.head + middle) % MAX_BUFFER_LINES]!.index <= since) first = middle + 1;
412
678
  else end = middle;
413
679
  }
680
+ // Oversized lines can leave holes inside the ring, not just before it.
681
+ const evicted = Math.max(0, this.cursor - since - (this.lineCount - first));
414
682
  const lines: LogLine[] = [];
415
683
  if (!grep && (!streams || streams.length === 0)) {
416
684
  for (let i = Math.max(first, this.lineCount - limit); i < this.lineCount; i++) {
417
685
  lines.push(this.lines[(this.head + i) % MAX_BUFFER_LINES]!);
418
686
  }
419
- return { lines, cursor: this.cursor, total: this.lineCount - first };
687
+ return { lines, cursor: this.cursor, total: this.lineCount - first, evicted };
420
688
  }
421
689
  let total = 0;
422
690
  for (let i = this.lineCount - 1; i >= first; i--) {
423
691
  const line = this.lines[(this.head + i) % MAX_BUFFER_LINES]!;
424
692
  if (streams && streams.length > 0 && !streams.includes(line.stream)) continue;
425
- if (grep && !line.text.includes(grep)) continue;
693
+ if (grep && !matchesFilter(line.text, grep)) continue;
426
694
  total += 1;
427
695
  if (lines.length < limit) lines.push(line);
428
696
  }
429
697
  lines.reverse();
430
- return { lines, cursor: this.cursor, total };
698
+ return { lines, cursor: this.cursor, total, evicted };
699
+ }
700
+
701
+ /**
702
+ * `read` with a filter, extended to disk for every hole in the ring, including
703
+ * oversized lines between retained entries. `missing` counts lines neither
704
+ * memory nor any retained file holds any more.
705
+ */
706
+ async search(options: { since?: number; limit?: number; grep: string | RegExp; signal?: AbortSignal }, retry = true): Promise<{
707
+ lines: FoundLine[];
708
+ cursor: number;
709
+ total: number;
710
+ evicted: number;
711
+ missing: number;
712
+ }> {
713
+ const signal = options.signal;
714
+ signal?.throwIfAborted();
715
+ const read = this.read(options);
716
+ if (read.evicted === 0) return { ...read, missing: 0 };
717
+ const since = Math.max(0, options.since ?? 0);
718
+ const holes: Array<{ first: number; last: number }> = [];
719
+ let first = since + 1;
720
+ for (let i = 0; i < this.lineCount; i++) {
721
+ const index = this.lines[(this.head + i) % MAX_BUFFER_LINES]!.index;
722
+ if (index <= since) continue;
723
+ if (index > first) holes.push({ first, last: index - 1 });
724
+ first = index + 1;
725
+ }
726
+ if (first <= read.cursor) holes.push({ first, last: read.cursor });
727
+ const grep = typeof options.grep === "string" ? options.grep.trim() : options.grep;
728
+ const limit = clampLimit(options.limit);
729
+ let older: FoundLine[] = [];
730
+ let total = read.total;
731
+ let covered = 0;
732
+ const runs = [...this.runs];
733
+ const versions = new Map(runs.map((run) => [run.path, this.fileVersions.get(run.path) ?? 0]));
734
+ // A reader reaching EOF before queued writes finish must not advance the
735
+ // cursor past those matches. Flush a barrier after this snapshot's writes;
736
+ // later producer output does not extend the snapshot or delay the barrier.
737
+ const clearBarriers: Array<() => void> = [];
738
+ const writes = [...this.files].map((file) => {
739
+ if (file.destroyed || file.writableFinished) return Promise.resolve();
740
+ if (file.writableEnded) return finished(file, { cleanup: true, signal }).catch(() => {});
741
+ return new Promise<void>((resolve) => {
742
+ const done = (): void => { file.off("close", done); resolve(); };
743
+ file.once("close", done);
744
+ clearBarriers.push(() => { file.off("close", done); });
745
+ file.write("", done);
746
+ });
747
+ });
748
+ let onAbort: (() => void) | undefined;
749
+ try {
750
+ await Promise.race([
751
+ Promise.all(writes),
752
+ new Promise<never>((_, reject) => {
753
+ if (!signal) return;
754
+ onAbort = () => reject(signal.reason);
755
+ signal.addEventListener("abort", onAbort, { once: true });
756
+ if (signal.aborted) onAbort();
757
+ }),
758
+ ]);
759
+ } finally {
760
+ if (onAbort) signal!.removeEventListener("abort", onAbort);
761
+ for (const clear of clearBarriers) clear();
762
+ }
763
+ let hole = 0;
764
+ for (const [position, run] of runs.entries()) {
765
+ signal?.throwIfAborted();
766
+ if (run.index > read.cursor) break;
767
+ const next = runs[position + 1];
768
+ let index = run.index;
769
+ let pending = "";
770
+ try {
771
+ const stream = createReadStream(run.path, {
772
+ encoding: "utf8",
773
+ start: run.offset,
774
+ ...(next?.path === run.path ? { end: next.offset - 1 } : {}),
775
+ signal,
776
+ });
777
+ for await (const chunk of stream) {
778
+ signal?.throwIfAborted();
779
+ const parts = (pending + chunk).split("\n");
780
+ pending = parts.pop() ?? "";
781
+ for (const raw of parts) {
782
+ if (index > read.cursor) break;
783
+ while (hole < holes.length && holes[hole].last < index) hole++;
784
+ if (hole < holes.length && index >= holes[hole].first) {
785
+ covered += 1;
786
+ const space = raw.indexOf(" ");
787
+ const text = raw.slice(space + 1);
788
+ if (matchesFilter(text, grep)) {
789
+ total += 1;
790
+ older.push({ index, at: Date.parse(raw.slice(0, space)), text });
791
+ if (older.length >= limit * 2 + 64) older = older.slice(-limit);
792
+ }
793
+ }
794
+ index += 1;
795
+ }
796
+ if (index > read.cursor || hole === holes.length) break;
797
+ }
798
+ } catch {
799
+ signal?.throwIfAborted();
800
+ // A run that cannot be read back stays counted in `missing`.
801
+ }
802
+ }
803
+ signal?.throwIfAborted();
804
+ // Opening a new segment is harmless; only replacement of a file actually
805
+ // included in this snapshot can relabel bytes with the wrong indices.
806
+ if ([...versions].some(([path, version]) => (this.fileVersions.get(path) ?? 0) !== version)) {
807
+ return retry ? this.search(options, false) : { ...read, missing: read.evicted };
808
+ }
809
+ return {
810
+ lines: [...older, ...read.lines].sort((a, b) => a.index - b.index).slice(-limit),
811
+ cursor: read.cursor,
812
+ total,
813
+ evicted: read.evicted,
814
+ missing: read.evicted - covered,
815
+ };
431
816
  }
432
817
 
433
818
  status(): CaptureStatus {
@@ -448,8 +833,12 @@ export class Capture {
448
833
  cursor: this.cursor,
449
834
  logFile: this.logFile,
450
835
  logFiles: [...this.logFiles].sort((a, b) => a[1] - b[1]).map(([path]) => path),
451
- commandLine: [this.command, ...this.launchArgs].join(" "),
836
+ commandLine: [this.command, ...this.spawnedArgs].join(" "),
452
837
  error: this.error,
838
+ relaunches: this.relaunches,
839
+ endReason: this.endReason,
840
+ crashReport: this.crashReport,
841
+ terminationReason: this.terminationReason,
453
842
  };
454
843
  }
455
844
  }