xcodebug 1.2.0 → 1.2.2
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/GUIDE.md +65 -16
- package/README.md +364 -47
- package/archive.ts +29 -0
- package/capture.ts +212 -16
- package/changes.ts +113 -15
- package/claude/.claude-plugin/plugin.json +6 -0
- package/claude/hooks/hooks.json +3 -0
- package/claude/hooks/register.js +113 -0
- package/claude/tests/live.test.ts +321 -0
- package/devices.ts +74 -3
- package/index.ts +518 -113
- package/mcp/server.ts +141 -17
- package/package.json +6 -1
- package/skills/xcodebug/SKILL.md +89 -0
- package/xcode.ts +84 -4
package/capture.ts
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
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";
|
|
7
|
+
import { appendFileSync, createReadStream, createWriteStream, statSync, type WriteStream } from "node:fs";
|
|
8
8
|
import { mkdir } from "node:fs/promises";
|
|
9
9
|
import { dirname } from "node:path";
|
|
10
10
|
import { finished } from "node:stream/promises";
|
|
@@ -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;
|
|
@@ -65,12 +68,32 @@ export interface CaptureStatus {
|
|
|
65
68
|
logFiles: string[];
|
|
66
69
|
commandLine: string;
|
|
67
70
|
error?: string;
|
|
71
|
+
relaunches: number;
|
|
72
|
+
endReason?: string;
|
|
73
|
+
crashReport?: string;
|
|
68
74
|
}
|
|
69
75
|
|
|
70
76
|
function clean(text: string): string {
|
|
71
77
|
return text.replace(ANSI, "").replace(/\r/g, "");
|
|
72
78
|
}
|
|
73
79
|
|
|
80
|
+
function clampLimit(limit: number | undefined): number {
|
|
81
|
+
return Math.trunc(Math.min(Math.max(1, limit ?? 200), 5_000));
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** A filter is a substring, or a pattern when the caller asked for one. */
|
|
85
|
+
export function matchesFilter(text: string, filter: string | RegExp): boolean {
|
|
86
|
+
return typeof filter === "string" ? text.includes(filter) : filter.test(text);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function sizeOnDisk(path: string): number {
|
|
90
|
+
try {
|
|
91
|
+
return statSync(path).size;
|
|
92
|
+
} catch {
|
|
93
|
+
return 0;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
|
|
74
97
|
export class Capture {
|
|
75
98
|
readonly id: string;
|
|
76
99
|
readonly mode: CaptureMode;
|
|
@@ -103,6 +126,15 @@ export class Capture {
|
|
|
103
126
|
* emits anything still ages from a sane starting point.
|
|
104
127
|
*/
|
|
105
128
|
lastLineAt = Date.now();
|
|
129
|
+
/**
|
|
130
|
+
* Times the console bridge was reattached. devicectl attaches a console only
|
|
131
|
+
* by launching, so each one restarted the app and dropped its state.
|
|
132
|
+
*/
|
|
133
|
+
relaunches = 0;
|
|
134
|
+
/** Why the capture ended without being asked to. */
|
|
135
|
+
endReason?: string;
|
|
136
|
+
/** The crash report pulled from the device after the app died, if it left one. */
|
|
137
|
+
crashReport?: string;
|
|
106
138
|
/**
|
|
107
139
|
* Aborted when this capture is stopped, so an in-flight device probe returns
|
|
108
140
|
* at once instead of running out its own timeout first.
|
|
@@ -124,6 +156,20 @@ export class Capture {
|
|
|
124
156
|
private fileNumber = 0;
|
|
125
157
|
private fileOrder = 0;
|
|
126
158
|
private readonly logFiles = new Map<string, number>();
|
|
159
|
+
/** Only overwriting an existing segment invalidates an in-flight disk scan. */
|
|
160
|
+
private readonly fileVersions = new Map<string, number>();
|
|
161
|
+
/**
|
|
162
|
+
* Where each run of consecutively indexed lines starts on disk. The files
|
|
163
|
+
* carry no index and have holes - a rotated segment is overwritten, and a
|
|
164
|
+
* write that fails takes its lines with it - so a line's index is only
|
|
165
|
+
* recoverable per run.
|
|
166
|
+
*/
|
|
167
|
+
private runs: Array<{ path: string; offset: number; index: number }> = [];
|
|
168
|
+
/** The segment being written, and where its next run starts once a line arrives. */
|
|
169
|
+
private segment = "";
|
|
170
|
+
private opened: { path: string; offset: number } | undefined;
|
|
171
|
+
/** True while lines are appended with the bridge down, which is one run. */
|
|
172
|
+
private appending = false;
|
|
127
173
|
private readonly files = new Set<WriteStream>();
|
|
128
174
|
private readonly blockedFiles = new Set<WriteStream>();
|
|
129
175
|
private readonly exitListeners = new Set<(code: number | undefined, signal: string | undefined) => void>();
|
|
@@ -175,8 +221,10 @@ export class Capture {
|
|
|
175
221
|
return () => this.lineListeners.delete(listener);
|
|
176
222
|
}
|
|
177
223
|
|
|
178
|
-
async start(): Promise<void> {
|
|
224
|
+
async start(signal?: AbortSignal): Promise<void> {
|
|
179
225
|
await mkdir(dirname(this.logFile), { recursive: true });
|
|
226
|
+
signal?.throwIfAborted();
|
|
227
|
+
if (this.stoppedByUser) return;
|
|
180
228
|
this.openFile(true);
|
|
181
229
|
|
|
182
230
|
const child = spawn(this.command, this.launchArgs, { stdio: ["ignore", "pipe", "pipe"] });
|
|
@@ -253,6 +301,13 @@ export class Capture {
|
|
|
253
301
|
|
|
254
302
|
private openFile(append: boolean): void {
|
|
255
303
|
const path = this.fileNumber === 0 ? this.logFile : `${this.logFile}.${this.fileNumber}`;
|
|
304
|
+
if (!append && this.runs.some((run) => run.path === path)) {
|
|
305
|
+
this.runs = this.runs.filter((run) => run.path !== path);
|
|
306
|
+
this.fileVersions.set(path, (this.fileVersions.get(path) ?? 0) + 1);
|
|
307
|
+
}
|
|
308
|
+
this.segment = path;
|
|
309
|
+
this.opened = { path, offset: append ? sizeOnDisk(path) : 0 };
|
|
310
|
+
this.appending = false;
|
|
256
311
|
const file = createWriteStream(path, { flags: append ? "a" : "w" });
|
|
257
312
|
this.file = file;
|
|
258
313
|
this.files.add(file);
|
|
@@ -321,15 +376,8 @@ export class Capture {
|
|
|
321
376
|
// Still deliver and write an oversized line, without retaining it in memory.
|
|
322
377
|
this.droppedLines += 1;
|
|
323
378
|
}
|
|
324
|
-
|
|
325
|
-
try {
|
|
326
|
-
listener(line);
|
|
327
|
-
} catch {
|
|
328
|
-
// A listener must never break capture.
|
|
329
|
-
}
|
|
330
|
-
}
|
|
379
|
+
const encoded = `${new Date(line.at).toISOString()} ${line.text}\n`;
|
|
331
380
|
if (this.file) {
|
|
332
|
-
const encoded = `${new Date(line.at).toISOString()} ${line.text}\n`;
|
|
333
381
|
const size = Buffer.byteLength(encoded);
|
|
334
382
|
if (this.fileBytes > 0 && this.fileBytes + size > MAX_FILE_BYTES) {
|
|
335
383
|
this.file.end();
|
|
@@ -337,6 +385,10 @@ export class Capture {
|
|
|
337
385
|
this.fileBytes = 0;
|
|
338
386
|
this.openFile(false);
|
|
339
387
|
}
|
|
388
|
+
if (this.opened) {
|
|
389
|
+
this.runs.push({ ...this.opened, index: line.index });
|
|
390
|
+
this.opened = undefined;
|
|
391
|
+
}
|
|
340
392
|
this.fileBytes += size;
|
|
341
393
|
const file = this.file;
|
|
342
394
|
if (!file.write(encoded)) {
|
|
@@ -344,6 +396,26 @@ export class Capture {
|
|
|
344
396
|
this.child?.stdout?.pause();
|
|
345
397
|
this.child?.stderr?.pause();
|
|
346
398
|
}
|
|
399
|
+
} else if (!this.child && this.segment) {
|
|
400
|
+
// The bridge is down and its file is closed. What is said meanwhile - why
|
|
401
|
+
// it ended, each reattach - is what explains the rest of the log, so it
|
|
402
|
+
// goes to disk too. Only a few lines arrive in this state.
|
|
403
|
+
try {
|
|
404
|
+
const offset = this.appending ? undefined : sizeOnDisk(this.segment);
|
|
405
|
+
appendFileSync(this.segment, encoded);
|
|
406
|
+
if (offset !== undefined) this.runs.push({ path: this.segment, offset, index: line.index });
|
|
407
|
+
this.appending = true;
|
|
408
|
+
} catch {
|
|
409
|
+
// The log could not be written before either; the line is still in memory.
|
|
410
|
+
this.appending = false;
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
for (const listener of this.lineListeners) {
|
|
414
|
+
try {
|
|
415
|
+
listener(line);
|
|
416
|
+
} catch {
|
|
417
|
+
// A listener must never break capture.
|
|
418
|
+
}
|
|
347
419
|
}
|
|
348
420
|
}
|
|
349
421
|
|
|
@@ -394,14 +466,16 @@ export class Capture {
|
|
|
394
466
|
});
|
|
395
467
|
}
|
|
396
468
|
|
|
397
|
-
read(options: { since?: number; limit?: number; grep?: string; streams?: Array<"out" | "err"> }): {
|
|
469
|
+
read(options: { since?: number; limit?: number; grep?: string | RegExp; streams?: Array<"out" | "err"> }): {
|
|
398
470
|
lines: LogLine[];
|
|
399
471
|
cursor: number;
|
|
400
472
|
total: number;
|
|
473
|
+
/** Lines after `since` that the buffer has already dropped. */
|
|
474
|
+
evicted: number;
|
|
401
475
|
} {
|
|
402
476
|
const since = Math.max(0, options.since ?? 0);
|
|
403
|
-
const limit =
|
|
404
|
-
const grep = options.grep
|
|
477
|
+
const limit = clampLimit(options.limit);
|
|
478
|
+
const grep = typeof options.grep === "string" ? options.grep.trim() : options.grep;
|
|
405
479
|
const streams = options.streams;
|
|
406
480
|
// Locate the first eligible index without scanning or copying the buffer.
|
|
407
481
|
let first = 0;
|
|
@@ -411,23 +485,142 @@ export class Capture {
|
|
|
411
485
|
if (this.lines[(this.head + middle) % MAX_BUFFER_LINES]!.index <= since) first = middle + 1;
|
|
412
486
|
else end = middle;
|
|
413
487
|
}
|
|
488
|
+
// Oversized lines can leave holes inside the ring, not just before it.
|
|
489
|
+
const evicted = Math.max(0, this.cursor - since - (this.lineCount - first));
|
|
414
490
|
const lines: LogLine[] = [];
|
|
415
491
|
if (!grep && (!streams || streams.length === 0)) {
|
|
416
492
|
for (let i = Math.max(first, this.lineCount - limit); i < this.lineCount; i++) {
|
|
417
493
|
lines.push(this.lines[(this.head + i) % MAX_BUFFER_LINES]!);
|
|
418
494
|
}
|
|
419
|
-
return { lines, cursor: this.cursor, total: this.lineCount - first };
|
|
495
|
+
return { lines, cursor: this.cursor, total: this.lineCount - first, evicted };
|
|
420
496
|
}
|
|
421
497
|
let total = 0;
|
|
422
498
|
for (let i = this.lineCount - 1; i >= first; i--) {
|
|
423
499
|
const line = this.lines[(this.head + i) % MAX_BUFFER_LINES]!;
|
|
424
500
|
if (streams && streams.length > 0 && !streams.includes(line.stream)) continue;
|
|
425
|
-
if (grep && !line.text
|
|
501
|
+
if (grep && !matchesFilter(line.text, grep)) continue;
|
|
426
502
|
total += 1;
|
|
427
503
|
if (lines.length < limit) lines.push(line);
|
|
428
504
|
}
|
|
429
505
|
lines.reverse();
|
|
430
|
-
return { lines, cursor: this.cursor, total };
|
|
506
|
+
return { lines, cursor: this.cursor, total, evicted };
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
/**
|
|
510
|
+
* `read` with a filter, extended to disk for every hole in the ring, including
|
|
511
|
+
* oversized lines between retained entries. `missing` counts lines neither
|
|
512
|
+
* memory nor any retained file holds any more.
|
|
513
|
+
*/
|
|
514
|
+
async search(options: { since?: number; limit?: number; grep: string | RegExp; signal?: AbortSignal }, retry = true): Promise<{
|
|
515
|
+
lines: FoundLine[];
|
|
516
|
+
cursor: number;
|
|
517
|
+
total: number;
|
|
518
|
+
evicted: number;
|
|
519
|
+
missing: number;
|
|
520
|
+
}> {
|
|
521
|
+
const signal = options.signal;
|
|
522
|
+
signal?.throwIfAborted();
|
|
523
|
+
const read = this.read(options);
|
|
524
|
+
if (read.evicted === 0) return { ...read, missing: 0 };
|
|
525
|
+
const since = Math.max(0, options.since ?? 0);
|
|
526
|
+
const holes: Array<{ first: number; last: number }> = [];
|
|
527
|
+
let first = since + 1;
|
|
528
|
+
for (let i = 0; i < this.lineCount; i++) {
|
|
529
|
+
const index = this.lines[(this.head + i) % MAX_BUFFER_LINES]!.index;
|
|
530
|
+
if (index <= since) continue;
|
|
531
|
+
if (index > first) holes.push({ first, last: index - 1 });
|
|
532
|
+
first = index + 1;
|
|
533
|
+
}
|
|
534
|
+
if (first <= read.cursor) holes.push({ first, last: read.cursor });
|
|
535
|
+
const grep = typeof options.grep === "string" ? options.grep.trim() : options.grep;
|
|
536
|
+
const limit = clampLimit(options.limit);
|
|
537
|
+
let older: FoundLine[] = [];
|
|
538
|
+
let total = read.total;
|
|
539
|
+
let covered = 0;
|
|
540
|
+
const runs = [...this.runs];
|
|
541
|
+
const versions = new Map(runs.map((run) => [run.path, this.fileVersions.get(run.path) ?? 0]));
|
|
542
|
+
// A reader reaching EOF before queued writes finish must not advance the
|
|
543
|
+
// cursor past those matches. Flush a barrier after this snapshot's writes;
|
|
544
|
+
// later producer output does not extend the snapshot or delay the barrier.
|
|
545
|
+
const clearBarriers: Array<() => void> = [];
|
|
546
|
+
const writes = [...this.files].map((file) => {
|
|
547
|
+
if (file.destroyed || file.writableFinished) return Promise.resolve();
|
|
548
|
+
if (file.writableEnded) return finished(file, { cleanup: true, signal }).catch(() => {});
|
|
549
|
+
return new Promise<void>((resolve) => {
|
|
550
|
+
const done = (): void => { file.off("close", done); resolve(); };
|
|
551
|
+
file.once("close", done);
|
|
552
|
+
clearBarriers.push(() => { file.off("close", done); });
|
|
553
|
+
file.write("", done);
|
|
554
|
+
});
|
|
555
|
+
});
|
|
556
|
+
let onAbort: (() => void) | undefined;
|
|
557
|
+
try {
|
|
558
|
+
await Promise.race([
|
|
559
|
+
Promise.all(writes),
|
|
560
|
+
new Promise<never>((_, reject) => {
|
|
561
|
+
if (!signal) return;
|
|
562
|
+
onAbort = () => reject(signal.reason);
|
|
563
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
564
|
+
if (signal.aborted) onAbort();
|
|
565
|
+
}),
|
|
566
|
+
]);
|
|
567
|
+
} finally {
|
|
568
|
+
if (onAbort) signal!.removeEventListener("abort", onAbort);
|
|
569
|
+
for (const clear of clearBarriers) clear();
|
|
570
|
+
}
|
|
571
|
+
let hole = 0;
|
|
572
|
+
for (const [position, run] of runs.entries()) {
|
|
573
|
+
signal?.throwIfAborted();
|
|
574
|
+
if (run.index > read.cursor) break;
|
|
575
|
+
const next = runs[position + 1];
|
|
576
|
+
let index = run.index;
|
|
577
|
+
let pending = "";
|
|
578
|
+
try {
|
|
579
|
+
const stream = createReadStream(run.path, {
|
|
580
|
+
encoding: "utf8",
|
|
581
|
+
start: run.offset,
|
|
582
|
+
...(next?.path === run.path ? { end: next.offset - 1 } : {}),
|
|
583
|
+
signal,
|
|
584
|
+
});
|
|
585
|
+
for await (const chunk of stream) {
|
|
586
|
+
signal?.throwIfAborted();
|
|
587
|
+
const parts = (pending + chunk).split("\n");
|
|
588
|
+
pending = parts.pop() ?? "";
|
|
589
|
+
for (const raw of parts) {
|
|
590
|
+
if (index > read.cursor) break;
|
|
591
|
+
while (hole < holes.length && holes[hole].last < index) hole++;
|
|
592
|
+
if (hole < holes.length && index >= holes[hole].first) {
|
|
593
|
+
covered += 1;
|
|
594
|
+
const space = raw.indexOf(" ");
|
|
595
|
+
const text = raw.slice(space + 1);
|
|
596
|
+
if (matchesFilter(text, grep)) {
|
|
597
|
+
total += 1;
|
|
598
|
+
older.push({ index, at: Date.parse(raw.slice(0, space)), text });
|
|
599
|
+
if (older.length >= limit * 2 + 64) older = older.slice(-limit);
|
|
600
|
+
}
|
|
601
|
+
}
|
|
602
|
+
index += 1;
|
|
603
|
+
}
|
|
604
|
+
if (index > read.cursor || hole === holes.length) break;
|
|
605
|
+
}
|
|
606
|
+
} catch {
|
|
607
|
+
signal?.throwIfAborted();
|
|
608
|
+
// A run that cannot be read back stays counted in `missing`.
|
|
609
|
+
}
|
|
610
|
+
}
|
|
611
|
+
signal?.throwIfAborted();
|
|
612
|
+
// Opening a new segment is harmless; only replacement of a file actually
|
|
613
|
+
// included in this snapshot can relabel bytes with the wrong indices.
|
|
614
|
+
if ([...versions].some(([path, version]) => (this.fileVersions.get(path) ?? 0) !== version)) {
|
|
615
|
+
return retry ? this.search(options, false) : { ...read, missing: read.evicted };
|
|
616
|
+
}
|
|
617
|
+
return {
|
|
618
|
+
lines: [...older, ...read.lines].sort((a, b) => a.index - b.index).slice(-limit),
|
|
619
|
+
cursor: read.cursor,
|
|
620
|
+
total,
|
|
621
|
+
evicted: read.evicted,
|
|
622
|
+
missing: read.evicted - covered,
|
|
623
|
+
};
|
|
431
624
|
}
|
|
432
625
|
|
|
433
626
|
status(): CaptureStatus {
|
|
@@ -450,6 +643,9 @@ export class Capture {
|
|
|
450
643
|
logFiles: [...this.logFiles].sort((a, b) => a[1] - b[1]).map(([path]) => path),
|
|
451
644
|
commandLine: [this.command, ...this.launchArgs].join(" "),
|
|
452
645
|
error: this.error,
|
|
646
|
+
relaunches: this.relaunches,
|
|
647
|
+
endReason: this.endReason,
|
|
648
|
+
crashReport: this.crashReport,
|
|
453
649
|
};
|
|
454
650
|
}
|
|
455
651
|
}
|
package/changes.ts
CHANGED
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
* Pod membership is derived from the repo's own podspecs (`source_files`
|
|
11
11
|
* globs), so it follows whatever layout the podspec declares.
|
|
12
12
|
*/
|
|
13
|
-
import { mkdir, readdir, readFile, stat, writeFile } from "node:fs/promises";
|
|
13
|
+
import { lstat, mkdir, readdir, readFile, realpath, stat, writeFile } from "node:fs/promises";
|
|
14
14
|
import { dirname, join, relative, resolve } from "node:path";
|
|
15
15
|
import { runCommand } from "./exec.ts";
|
|
16
16
|
|
|
@@ -61,17 +61,36 @@ export interface ChangeReport {
|
|
|
61
61
|
needsBuild: boolean;
|
|
62
62
|
}
|
|
63
63
|
|
|
64
|
+
/**
|
|
65
|
+
* Is this of a type a project compiles as soon as it sees the file? A new one
|
|
66
|
+
* in a pod then needs `pod install`, which is the only question this answers.
|
|
67
|
+
*/
|
|
68
|
+
function isSource(path: string): boolean {
|
|
69
|
+
const lower = path.toLowerCase();
|
|
70
|
+
if (lower.endsWith("podfile") || lower.endsWith("podfile.lock") || lower.endsWith(".podspec")) return true;
|
|
71
|
+
if (lower.includes(".xcodeproj/") || lower.includes(".xcworkspace/")) return true;
|
|
72
|
+
const dot = lower.lastIndexOf(".");
|
|
73
|
+
return dot >= 0 && SOURCE_EXTENSIONS.has(lower.slice(dot));
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Types no build reads, though a working session writes them into a repository:
|
|
78
|
+
* notes, logs, crash reports, patches.
|
|
79
|
+
*/
|
|
80
|
+
const NEVER_BUILT = new Set([".md", ".log", ".ips", ".patch", ".diff"]);
|
|
81
|
+
|
|
64
82
|
function isRelevant(path: string): boolean {
|
|
65
83
|
const normalized = `/${path.replace(/\\/g, "/")}`;
|
|
66
84
|
if (IGNORED_SEGMENTS.some((segment) => normalized.includes(segment))) return false;
|
|
67
85
|
// Agent state is not app source: a session file or skill under a config dir
|
|
68
86
|
// must not trigger a device build.
|
|
69
87
|
if (AGENT_STATE_DIRS.some((dir) => normalized.includes(`/${dir}/`))) return false;
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
88
|
+
// Anything else git reports can feed the build: a Podfile.rb, an .xcconfig,
|
|
89
|
+
// an image dropped into a folder the project takes whole. A build that is
|
|
90
|
+
// reused must not be older than its inputs, so the list is of what is known
|
|
91
|
+
// not to be one, and an unknown type costs a rebuild instead of a stale app.
|
|
92
|
+
const dot = path.lastIndexOf(".");
|
|
93
|
+
return dot < 0 || !NEVER_BUILT.has(path.slice(dot).toLowerCase());
|
|
75
94
|
}
|
|
76
95
|
|
|
77
96
|
/** Expand one glob (braces, **, *) into a RegExp over repo-relative paths. */
|
|
@@ -157,16 +176,78 @@ function podsForPath(path: string, pods: PodEntry[]): string[] {
|
|
|
157
176
|
*
|
|
158
177
|
* `git status` keeps reporting the same path after a second edit, so hashing
|
|
159
178
|
* paths alone would silently skip a rebuild. mtime + size changes on every
|
|
160
|
-
* write and costs one stat per changed file.
|
|
179
|
+
* write and costs one stat per changed file. Whether the change is staged is
|
|
180
|
+
* left out: `git add` does not alter what gets built.
|
|
161
181
|
*/
|
|
162
182
|
async function fileSignature(repoRoot: string, file: ChangedFile): Promise<string> {
|
|
163
|
-
if (file.deleted) return `${file.
|
|
183
|
+
if (file.deleted) return `${file.path}:deleted`;
|
|
184
|
+
try {
|
|
185
|
+
const path = join(repoRoot, file.path);
|
|
186
|
+
const info = await stat(path);
|
|
187
|
+
// A directory here is a submodule: one entry however much changed inside
|
|
188
|
+
// it, and nothing on the entry itself tells two of its states apart.
|
|
189
|
+
if (info.isDirectory()) return `${file.path}:${(await directorySignature(path, "source")) ?? "unreadable"}`;
|
|
190
|
+
return `${file.path}:${info.mtimeMs}:${info.size}`;
|
|
191
|
+
} catch {
|
|
192
|
+
return `${file.path}:missing`;
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/**
|
|
197
|
+
* Fingerprint every file's path, time and size in a built product or source tree.
|
|
198
|
+
*
|
|
199
|
+
* Products include all directories: even a resource called `build` is installed
|
|
200
|
+
* app content. Source trees omit generated/build directories and git metadata
|
|
201
|
+
* so a local pod's build output does not invalidate its own inputs.
|
|
202
|
+
* Undefined when the directory is missing or changes under the walk, which is
|
|
203
|
+
* never "the same as before".
|
|
204
|
+
*/
|
|
205
|
+
export async function directorySignature(root: string, kind: "product" | "source" = "product"): Promise<string | undefined> {
|
|
206
|
+
const files: string[] = [];
|
|
207
|
+
const pending = [root];
|
|
208
|
+
for (let dir = pending.pop(); dir !== undefined; dir = pending.pop()) {
|
|
209
|
+
try {
|
|
210
|
+
for (const entry of await readdir(dir, { withFileTypes: true })) {
|
|
211
|
+
const path = join(dir, entry.name);
|
|
212
|
+
if (entry.isDirectory()) {
|
|
213
|
+
if (kind === "product" || !IGNORED_SEGMENTS.includes(`/${entry.name}/`)) pending.push(path);
|
|
214
|
+
continue;
|
|
215
|
+
}
|
|
216
|
+
// Not followed: a link is recorded as itself, so one that points at a
|
|
217
|
+
// directory, or at nothing, does not make the whole tree unreadable.
|
|
218
|
+
const info = await lstat(path);
|
|
219
|
+
files.push(`${path}:${info.mtimeMs}:${info.size}`);
|
|
220
|
+
}
|
|
221
|
+
} catch {
|
|
222
|
+
return undefined;
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
return hashString(files.sort().join("\n"));
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/**
|
|
229
|
+
* The directories outside the repository that a container's Podfile.lock
|
|
230
|
+
* installs pods from (`:path` entries). An edit there changes what gets built
|
|
231
|
+
* and leaves `git status` exactly as it was.
|
|
232
|
+
*/
|
|
233
|
+
async function outsidePodDirs(containerPath: string, repoRoot: string, cwd: string): Promise<string[]> {
|
|
234
|
+
const dir = dirname(resolve(cwd, containerPath));
|
|
235
|
+
let lock: string;
|
|
164
236
|
try {
|
|
165
|
-
|
|
166
|
-
return `${file.status}:${file.path}:${info.mtimeMs}:${info.size}`;
|
|
237
|
+
lock = await readFile(join(dir, "Podfile.lock"), "utf8");
|
|
167
238
|
} catch {
|
|
168
|
-
return
|
|
239
|
+
return [];
|
|
169
240
|
}
|
|
241
|
+
// Compared as real paths: git reports the repository's, and a path reached
|
|
242
|
+
// through a link (/tmp, /var) would otherwise always look like another place.
|
|
243
|
+
const root = await realpath(repoRoot).catch(() => repoRoot);
|
|
244
|
+
const dirs = new Set<string>();
|
|
245
|
+
for (const match of lock.matchAll(/^\s+:path:\s*"?([^"\n]+?)"?\s*$/gm)) {
|
|
246
|
+
const path = resolve(dir, match[1]);
|
|
247
|
+
const real = await realpath(path).catch(() => path);
|
|
248
|
+
if (real !== root && !real.startsWith(`${root}/`)) dirs.add(real);
|
|
249
|
+
}
|
|
250
|
+
return [...dirs].sort();
|
|
170
251
|
}
|
|
171
252
|
|
|
172
253
|
export function hashString(value: string): string {
|
|
@@ -242,7 +323,12 @@ export async function checkPodLockSync(
|
|
|
242
323
|
return { synced: false, podfileDir: dir, reason: "Podfile.lock differs from Pods/Manifest.lock" };
|
|
243
324
|
}
|
|
244
325
|
|
|
245
|
-
|
|
326
|
+
/**
|
|
327
|
+
* `containerPath` is the .xcworkspace/.xcodeproj the run targets, resolved from
|
|
328
|
+
* `cwd` when relative. With it, the fingerprint also covers pods that container
|
|
329
|
+
* installs from outside the repository; without it, only what git can see.
|
|
330
|
+
*/
|
|
331
|
+
export async function detectChanges(cwd: string, containerPath?: string): Promise<ChangeReport> {
|
|
246
332
|
const root = await runCommand("git", ["rev-parse", "--show-toplevel"], { cwd, timeoutMs: 30_000 });
|
|
247
333
|
if (root.code !== 0) {
|
|
248
334
|
return {
|
|
@@ -294,15 +380,27 @@ export async function detectChanges(cwd: string): Promise<ChangeReport> {
|
|
|
294
380
|
for (const file of changed) {
|
|
295
381
|
if (file.deleted) continue;
|
|
296
382
|
const isNew = file.untracked || file.status.includes("A");
|
|
297
|
-
|
|
383
|
+
// Only a file the generated Pods project would compile needs it regenerated.
|
|
384
|
+
if (!isNew || !isSource(file.path)) continue;
|
|
298
385
|
const matched = podsForPath(file.path, pods);
|
|
299
386
|
if (matched.length === 0) continue;
|
|
300
387
|
newComponentFiles.push({ ...file, pods: matched });
|
|
301
388
|
for (const pod of matched) podsNeedingInstall.add(pod);
|
|
302
389
|
}
|
|
303
390
|
|
|
391
|
+
// The committed tree is part of the identity: after a commit, a pull or a
|
|
392
|
+
// checkout the working tree can be clean again while holding other code than
|
|
393
|
+
// was last built. The tree rather than the commit, so that rewording a commit
|
|
394
|
+
// or switching to a branch with the same content costs no rebuild.
|
|
395
|
+
const head = await runCommand("git", ["rev-parse", "HEAD^{tree}"], { cwd: repoRoot, timeoutMs: 30_000 });
|
|
304
396
|
const signatures = await Promise.all(changed.map((file) => fileSignature(repoRoot, file)));
|
|
305
|
-
const
|
|
397
|
+
const outside = containerPath ? await outsidePodDirs(containerPath, repoRoot, cwd) : [];
|
|
398
|
+
const outsideSignatures = await Promise.all(
|
|
399
|
+
outside.map(async (dir) => `${dir}:${(await directorySignature(dir, "source")) ?? "unreadable"}`),
|
|
400
|
+
);
|
|
401
|
+
const fingerprint = hashString(
|
|
402
|
+
[head.code === 0 ? head.stdout.trim() : "no commit", ...signatures.sort(), ...outsideSignatures].join("\n"),
|
|
403
|
+
);
|
|
306
404
|
|
|
307
405
|
return {
|
|
308
406
|
repoRoot,
|
|
@@ -358,7 +456,7 @@ export function describeChanges(report: ChangeReport): string {
|
|
|
358
456
|
if (report.unavailable) {
|
|
359
457
|
return `change detection unavailable (${report.reason ?? "unknown"}); assuming a rebuild is needed`;
|
|
360
458
|
}
|
|
361
|
-
if (report.changed.length === 0) return "no build-relevant changes";
|
|
459
|
+
if (report.changed.length === 0) return "no uncommitted build-relevant changes";
|
|
362
460
|
const lines = [`${report.changed.length} build-relevant change(s)`];
|
|
363
461
|
for (const file of report.changed.slice(0, 15)) {
|
|
364
462
|
lines.push(` ${file.status} ${file.path}`);
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
// Poll the existing connection, not a second server with different captures.
|
|
2
|
+
const SERVER = 'xcodebug';
|
|
3
|
+
// A literal, not built from SERVER: `claude plugin validate` reads the matcher statically.
|
|
4
|
+
const ACTION_TOOL = 'mcp__xcodebug__xcodebug';
|
|
5
|
+
const UI_TOOL = 'xcodebug_ui';
|
|
6
|
+
const POLL_MS = 1000;
|
|
7
|
+
// One failed read may be a blip; a server that stays down is not polled forever.
|
|
8
|
+
const MAX_FAILURES = 3;
|
|
9
|
+
const MAX_ERROR_CHARS = 160;
|
|
10
|
+
// The server repaints once a second while it shows anything, so a file whose
|
|
11
|
+
// `seq` stands still this many reads running belongs to a server that is gone.
|
|
12
|
+
const MAX_STALE_READS = 5;
|
|
13
|
+
// Actions that neither build nor start a capture, so they paint nothing new
|
|
14
|
+
// unless they carry a `command`, which runs as a phase of its own.
|
|
15
|
+
// Listed as exclusions so that an action added later shows by default.
|
|
16
|
+
const QUIET_ACTIONS = new Set(['doctor', 'devices', 'changes', 'status', 'logs', 'wait', 'stop', 'terminate']);
|
|
17
|
+
|
|
18
|
+
let rows = [];
|
|
19
|
+
let polling = false;
|
|
20
|
+
let timer;
|
|
21
|
+
let calls = 0;
|
|
22
|
+
let failures = 0;
|
|
23
|
+
let file;
|
|
24
|
+
let seq;
|
|
25
|
+
let stale = 0;
|
|
26
|
+
|
|
27
|
+
// A tool call runs the session's tool hooks, so only the first read of an
|
|
28
|
+
// activity asks the server; it names the file the server keeps the same
|
|
29
|
+
// snapshot in, and the reads after that come from there.
|
|
30
|
+
async function readServer($) {
|
|
31
|
+
const result = await $.mcp.call(SERVER, UI_TOOL, {});
|
|
32
|
+
if (result.isError) throw new Error(result.content.find(c => c.type === 'text')?.text ?? 'UI read failed');
|
|
33
|
+
const snapshot = JSON.parse(result.content.find(c => c.type === 'text')?.text ?? '{}');
|
|
34
|
+
// A server from before the file existed names none, and is asked every time.
|
|
35
|
+
file = snapshot.file;
|
|
36
|
+
seq = snapshot.seq;
|
|
37
|
+
stale = 0;
|
|
38
|
+
return snapshot;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
async function readFile($) {
|
|
42
|
+
if (!file) return undefined;
|
|
43
|
+
try {
|
|
44
|
+
const snapshot = JSON.parse(await $.fs.read(file));
|
|
45
|
+
stale = snapshot.seq === seq ? stale + 1 : 0;
|
|
46
|
+
seq = snapshot.seq;
|
|
47
|
+
if (stale < MAX_STALE_READS) return snapshot;
|
|
48
|
+
} catch {
|
|
49
|
+
// Removed when its server exited; the server is asked instead, below.
|
|
50
|
+
}
|
|
51
|
+
file = undefined;
|
|
52
|
+
return undefined;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
// The timer lives only while there is something to show: it ends once the
|
|
56
|
+
// server empties its snapshot (no build, no capture) or keeps failing.
|
|
57
|
+
function watch($) {
|
|
58
|
+
timer ??= $.clock.every(POLL_MS, async () => {
|
|
59
|
+
if (polling) return;
|
|
60
|
+
polling = true;
|
|
61
|
+
try {
|
|
62
|
+
const snapshot = await readFile($) ?? await readServer($);
|
|
63
|
+
rows = snapshot.rows?.length ? snapshot.rows : snapshot.status ? [snapshot.status] : [];
|
|
64
|
+
failures = 0;
|
|
65
|
+
} catch (error) {
|
|
66
|
+
rows = ['Xcodebug · live display unavailable', String(error.message ?? error).slice(0, MAX_ERROR_CHARS)];
|
|
67
|
+
failures += 1;
|
|
68
|
+
} finally {
|
|
69
|
+
polling = false;
|
|
70
|
+
}
|
|
71
|
+
// A call still in flight may not have painted its first status yet.
|
|
72
|
+
if (calls === 0 && (rows.length === 0 || failures >= MAX_FAILURES)) {
|
|
73
|
+
timer?.cancel();
|
|
74
|
+
timer = undefined;
|
|
75
|
+
rows = [];
|
|
76
|
+
failures = 0;
|
|
77
|
+
// The next activity may meet a restarted server, with a file of its own.
|
|
78
|
+
file = undefined;
|
|
79
|
+
}
|
|
80
|
+
$.ui.invalidate('ui.render');
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export function register(on) {
|
|
85
|
+
// A capture outlives the module: a reload or a resumed session finds it here.
|
|
86
|
+
on('session.start', async ($, e, next) => {
|
|
87
|
+
watch($);
|
|
88
|
+
return next(e);
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
on('tool.call', { tool: ACTION_TOOL }, async ($, e, next) => {
|
|
92
|
+
if (QUIET_ACTIONS.has(e.action) && !e.command) return next(e);
|
|
93
|
+
// The server may have been replaced since the file was named; one killed
|
|
94
|
+
// while it showed something leaves that file behind, still naming it.
|
|
95
|
+
file = undefined;
|
|
96
|
+
watch($);
|
|
97
|
+
calls += 1;
|
|
98
|
+
try {
|
|
99
|
+
return await next(e);
|
|
100
|
+
} finally {
|
|
101
|
+
calls -= 1;
|
|
102
|
+
}
|
|
103
|
+
});
|
|
104
|
+
|
|
105
|
+
on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
|
|
106
|
+
if (rows.length === 0) return next(e);
|
|
107
|
+
const { Box, Text } = $.ui.resolve(e);
|
|
108
|
+
return Box({
|
|
109
|
+
flexDirection: 'column',
|
|
110
|
+
children: rows.map(text => Text({ children: [text] })),
|
|
111
|
+
});
|
|
112
|
+
});
|
|
113
|
+
}
|