xcodebug 1.2.2 → 1.2.4

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 CHANGED
@@ -12,6 +12,29 @@ Enter these commands in the client's chat input. A bare `/xcodebug` (`$xcodebug`
12
12
  in Codex) builds as needed, installs, launches and starts capturing with defaults.
13
13
  Use `/xcodebug status` (`$xcodebug status` in Codex) to inspect current captures.
14
14
 
15
+ After installing the MCP server, run `xcodebug-setup-codex` once. It registers
16
+ the server when missing, adds the 4200-second timeout only when no custom
17
+ timeout exists, enables the statusline feature on Codex CLI 0.171.0+, and selects
18
+ the xcodebug provider when the user selection is missing or `default`. Other
19
+ custom providers are preserved with a warning.
20
+ It also checks the running app-server version; both CLI and service must support
21
+ the feature. An old or unverifiable service gets a warning, not an automatic
22
+ upgrade or restart that could interrupt active tasks and captures.
23
+ From a checkout, use `node bin/xcodebug-setup-codex.mjs`. Open a new Codex session
24
+ after setup. If another custom provider was preserved, select `xcodebug_ui`
25
+ (`xcodebug / xcodebug_ui`) through `/statusline` → **Choose a status line provider**
26
+ or set `tui.status_line_provider` explicitly. If another process changes the
27
+ configuration while setup runs, the stale write is rejected; rerun setup.
28
+ See [README.md § Codex live display](README.md#codex-live-display-experimental)
29
+ for the configuration and global inventory discovery timeout details.
30
+
31
+ Native pi/omp `/xcodebug` dispatches directly to the loaded extension handler,
32
+ without skill/model selection for that dispatch. The package excludes its
33
+ bundled skill from native package discovery; Claude/Codex share `mcp/skills/xcodebug/SKILL.md`.
34
+ If a native host also discovers that user-level shared skill, it routes to the native tool
35
+ when available. Reading a skill alone never executes an action; model-selected
36
+ requests still require a tool call, while the native command runs its handler.
37
+
15
38
  Debug a real iOS device: build, install, launch, and read the app's console
16
39
  (stdout/stderr + os_log) inside the agent session. No jailbreak, no LLDB attach,
17
40
  no paid account.
@@ -89,6 +112,12 @@ for analysis.
89
112
  See [Claude Code live display](README.md#claude-code-live-display) for version
90
113
  requirements, upgrade/disable steps and missing-display troubleshooting.
91
114
 
115
+ For an optional footer in Codex CLI 0.171.0 or later, follow the
116
+ [Codex live display setup](README.md#codex-live-display-experimental). The
117
+ footer shows the current operation or one running capture and its
118
+ latest log line. It refreshes between tool calls and clears once no operation
119
+ or capture remains. Use `logs` or `wait` to bring log evidence into the conversation.
120
+
92
121
  ## Running a command alongside a capture
93
122
 
94
123
  ### What it is for
@@ -142,8 +171,12 @@ What happens after `command`:
142
171
  1. `/bin/sh -lc` runs the whole line, with the project root as the working
143
172
  directory (`pi.cwd` → `ctx.cwd` → process cwd).
144
173
  2. It waits for the process to exit.
145
- 3. It stops **the capture it targeted** — other apps' captures keep streaming.
146
- 4. It hands back the exit code, elapsed time, how many new lines arrived, the
174
+ 3. It stops **the capture it targeted** and cancels its queued reconnect — other
175
+ apps' captures keep streaming.
176
+ 4. When collecting exit diagnostics, it waits for the owned console-launch
177
+ result and matching crash-report collection independently of the stopped
178
+ capture; caller cancellation still interrupts that wait.
179
+ 5. It hands back the exit code, elapsed time, how many new lines arrived, the
147
180
  log path, and the `logs` call (with the right `since`) for the app side.
148
181
 
149
182
  **Quote the whole line.** `command="cd /repo && npm run test"`. Unquoted, the
@@ -249,6 +282,12 @@ A filtered read (`logs grep=`, `wait`) looks in those files for the lines memory
249
282
  has dropped and says in its reply that it did. Logs are deleted 30 days after
250
283
  their last write.
251
284
 
285
+ Console launch-result JSON is temporary metadata, not a log. Ordinary `stop`
286
+ preserves pending exit diagnostics; session exit instead cancels result reads
287
+ and bounds startup/result cleanup as well as log drainage. Incomplete cleanup
288
+ is reported. Ownership-checked stale-result reclamation and its conservative
289
+ exceptions are documented under [disk files](README.md#files).
290
+
252
291
  ## Three rules of use
253
292
 
254
293
  1. **Stop once the log has answered the question.** A capture left running keeps
package/README.md CHANGED
@@ -92,16 +92,53 @@ codex mcp list # xcodebug bun …
92
92
  claude mcp list # xcodebug: … ✔ Connected
93
93
  ```
94
94
 
95
- Set Codex's MCP timeout high enough for the stages your calls use. For example,
96
- 4200 seconds leaves room for the default 15-minute pod install, 15-minute build
97
- and 30-minute command budgets, plus device operations. Increase it if you pass
98
- larger timeouts; the client can still cancel before xcodebug's own deadline.
95
+ After installing the package, run the setup command once to register the MCP
96
+ server when missing and add the timeout without replacing an existing xcodebug
97
+ command or argument list:
98
+
99
+ ```bash
100
+ xcodebug-setup-codex
101
+ ```
102
+
103
+ From a checkout, use `node bin/xcodebug-setup-codex.mjs`. The command uses the
104
+ Codex app-server config API available in current Codex releases. It registers
105
+ xcodebug with Bun if it is missing, writes `tool_timeout_sec = 4200` only when
106
+ that field is absent, and preserves an existing custom timeout. On Codex CLI
107
+ `0.171.0` or later it also enables `features.tui_extensions_statusline = true`
108
+ and selects the xcodebug statusline provider when the user selection is missing
109
+ or `default`. Existing custom providers are preserved with a warning. Older or
110
+ unrecognized CLI versions receive a warning instead. It checks the
111
+ running service with `codex app-server daemon version` and warns if its
112
+ `appServerVersion` is too old or cannot be verified. Saving configuration does
113
+ not upgrade the service; setup never updates or restarts a daemon automatically.
114
+ The command warns about project-level xcodebug overrides and existing server
115
+ paths pointing elsewhere, but preserves the registration and project files.
116
+ Setup saves these fields together with one version-checked `config/batchWrite`
117
+ request.
118
+ If another process edits the user configuration during setup, Codex rejects
119
+ stale writes; rerun setup after that edit rather than overwrite a new selection.
120
+ It does not run automatically during npm install because package installation
121
+ should not silently modify a user's Codex configuration. See the live display
122
+ section below for provider selection. For manual setup on supported CLI and
123
+ app-server versions, merge these fields into existing tables rather than add
124
+ duplicate table headers:
99
125
 
100
126
  ```toml
127
+ [features]
128
+ tui_extensions_statusline = true
129
+
130
+ [tui]
131
+ status_line_provider = { server = "xcodebug", tool = "xcodebug_ui" }
132
+
101
133
  [mcp_servers.xcodebug]
102
134
  tool_timeout_sec = 4200
103
135
  ```
104
136
 
137
+ The timeout leaves room for the default 15-minute pod install, 15-minute build
138
+ and 30-minute command budgets, plus device operations. Increase it if you pass
139
+ larger timeouts. This does not change xcodebug's stage deadlines or Codex's
140
+ separate status-line resource read deadline.
141
+
105
142
  Claude Code needs no setting for this. Its default limit on a tool call is about
106
143
  28 hours. It also ends a call to a stdio server that has sent neither a reply
107
144
  nor a progress notification for 30 minutes; this server sends progress once a
@@ -116,13 +153,65 @@ until stdout closes or a write fails.
116
153
  To run `npm test` from a checkout, use Node.js 22.18 or later and put Bun on PATH
117
154
  for the stdio integration tests.
118
155
 
156
+ ### Codex live display (experimental)
157
+
158
+ Both Codex CLI and the connected app server must be `0.171.0` or later. Setup
159
+ enables the feature persistently and selects xcodebug for a missing or default
160
+ provider. Alternatively start Codex with `codex --enable tui_extensions_statusline`.
161
+ If setup reports an older running
162
+ service, finish active Codex tasks and captures before running
163
+ `codex app-server daemon update --from-cli --yes`, then
164
+ `codex app-server daemon restart`. Opening a new TUI alone does not upgrade it.
165
+
166
+ Start a new Codex session after setup or after updating the service or MCP
167
+ server. If setup preserved another custom provider, open `/statusline`, enter
168
+ **Choose a status line provider**, then select `xcodebug_ui`
169
+ (`xcodebug / xcodebug_ui`). Codex 0.171.0 discovers providers from
170
+ the user configuration. A project-level override of the same MCP server name
171
+ can make the provider unavailable; remove the override or use a distinct name.
172
+
173
+ Codex 0.171.0 has a five-second provider discovery deadline. If the global MCP
174
+ inventory stalls, the picker can show only the default provider even though
175
+ xcodebug itself is available. Specify the provider directly for one session:
176
+
177
+ ```bash
178
+ codex -c 'tui.status_line_provider={server="xcodebug",tool="xcodebug_ui"}'
179
+ ```
180
+
181
+ Setup persists the provider selection for missing/default user settings. To
182
+ replace another custom provider explicitly, use the manual settings above.
183
+ Provider selection is supported configuration, not an MCP server setting.
184
+ See Codex's
185
+ [provider configuration](https://github.com/openai/codex/blob/rust-v0.171.0/codex-rs/tui/src/app/status_line_settings.rs)
186
+ and [discovery deadline](https://github.com/openai/codex/blob/rust-v0.171.0/codex-rs/tui/src/statusline_provider.rs).
187
+
188
+ The footer shows the current operation or capture and its latest log line. It
189
+ refreshes even between tool calls and clears when no operation or capture is
190
+ active. This is a display preview, not a log stream into the conversation; use
191
+ `action=logs` or `action=wait` for log evidence.
192
+ Long status text is shortened in the footer without changing the command or
193
+ its output.
194
+
119
195
  ### Install the manual entry point
120
196
 
121
197
  Connecting MCP makes the tool available to the model; it does not register a
122
198
  `/xcodebug` command in either client. The shared
123
- [xcodebug skill](skills/xcodebug/SKILL.md) adds an explicit entry point:
199
+ [xcodebug skill](mcp/skills/xcodebug/SKILL.md) adds an explicit entry point:
124
200
  `/xcodebug` in Claude Code, `$xcodebug` in Codex, or Codex's `/skills` picker.
125
201
 
202
+ Native pi/omp needs only the extension, not this skill or an MCP connection.
203
+ Both hosts register `extensions: ["./index.ts"]`; `pi.skills: []` disables pi's
204
+ package skill loading. The shared skill lives under `mcp/skills/`, outside the
205
+ root `skills/` directory that omp scans independently of manifest fields.
206
+ Native `/xcodebug` runs
207
+ the registered extension handler directly; it does not ask the model to select
208
+ a skill. A normal model tool call uses the registered native `xcodebug` tool.
209
+ If pi/omp also discovers the shared user-level skill through `.agents/skills`
210
+ or `.claude/skills`, its instructions select that native tool before MCP.
211
+ This shared-skill selection is model-driven, not a substitute for the native
212
+ command's deterministic dispatch. The extension must be installed, enabled and
213
+ loaded in the session; explicitly disabling it is not overridden.
214
+
126
215
  Both clients can read the same skill directory through user-level symlinks:
127
216
 
128
217
  ```bash
@@ -131,11 +220,12 @@ XCODEBUG_DIR="/absolute/path/to/xcodebug" # a checkout containing the skill
131
220
  # XCODEBUG_DIR="$(npm root -g)/xcodebug"
132
221
 
133
222
  (
134
- source="$XCODEBUG_DIR/skills/xcodebug"
223
+ source="$XCODEBUG_DIR/mcp/skills/xcodebug"
224
+ legacy="$XCODEBUG_DIR/skills/xcodebug"
135
225
  test -f "$source/SKILL.md" || { printf 'Skill not found: %s\n' "$source/SKILL.md" >&2; exit 1; }
136
226
  for dest in "$HOME/.agents/skills/xcodebug" "$HOME/.claude/skills/xcodebug"; do
137
227
  if test -e "$dest" || test -L "$dest"; then
138
- if ! test -L "$dest" || ! test "$dest" -ef "$source"; then
228
+ if ! test -L "$dest" || { ! test "$dest" -ef "$source" && ! test "$(readlink "$dest")" = "$legacy"; }; then
139
229
  printf 'Existing skill path: %s; inspect it before installing.\n' "$dest" >&2
140
230
  exit 1
141
231
  fi
@@ -143,22 +233,29 @@ XCODEBUG_DIR="/absolute/path/to/xcodebug" # a checkout containing the skill
143
233
  done
144
234
  mkdir -p "$HOME/.agents/skills" "$HOME/.claude/skills" || exit 1
145
235
  for dest in "$HOME/.agents/skills/xcodebug" "$HOME/.claude/skills/xcodebug"; do
236
+ if test -L "$dest" && test "$(readlink "$dest")" = "$legacy"; then
237
+ rm "$dest" || exit 1
238
+ fi
146
239
  test -L "$dest" || ln -s "$source" "$dest" || exit 1
147
240
  done
148
241
  )
149
242
  ```
150
243
 
151
- If the installed package does not contain `skills/xcodebug/SKILL.md`, use a
244
+ If the installed package does not contain `mcp/skills/xcodebug/SKILL.md`, use a
152
245
  checkout that contains it. The commands check both target paths before installing,
153
- skip symlinks already pointing to this skill, and stop on other existing files,
154
- directories or symlinks, including broken links.
155
- Keep the checkout or npm package at the linked path. Updating that source updates
156
- the shared skill for both clients.
246
+ skip symlinks already pointing to this skill, and migrate links to this checkout's
247
+ old `skills/xcodebug` source. They stop on other existing files, directories or
248
+ symlinks, including unrelated broken links. After updating an older checkout or
249
+ upgrading an npm package that used the old root `skills/` path, rerun these
250
+ commands to relink both clients; npm upgrade alone does not migrate those links.
251
+ Keep the checkout or npm package at the linked path. Once relinked, updates to
252
+ the maintained source update the shared skill for both clients.
157
253
 
158
254
  Start a new Claude Code or Codex session after installing. The skill uses the
159
- MCP connection already configured above; it does not start a separate server or
160
- replace the native pi command. Both manual and model-selected invocation remain
161
- available. See the clients' [Claude Code skill documentation](https://code.claude.com/docs/en/skills)
255
+ MCP connection already configured above in those clients; it does not start a
256
+ separate server. Native pi/omp uses its extension command and native tool instead.
257
+ Both manual and model-selected invocation remain available. See the clients'
258
+ [Claude Code skill documentation](https://code.claude.com/docs/en/skills)
162
259
  and [Codex skill documentation](https://learn.chatgpt.com/docs/build-skills).
163
260
 
164
261
  ### Use
@@ -364,15 +461,15 @@ remain available without the display.
364
461
  |---|---|---|
365
462
  | how the tool is exposed | registered in-process | MCP server process |
366
463
  | manual entry point | native `/xcodebug` | shared skill: `/xcodebug` in Claude, `$xcodebug` in Codex |
367
- | status line, widget | yes | Claude: optional live Mod above; otherwise request progress when rendered |
464
+ | status line, widget | yes | [Claude live Mod](#claude-code-live-display) or [Codex status line](#codex-live-display-experimental), both opt-in |
368
465
  | `push` | mirrors new lines into the session | `off` only; `context` and `wake` refused |
369
466
  | capture state | in the session | in the server process |
370
467
  | lifetime | the session | the client process |
371
468
 
372
469
  - **The adapter refuses `push=context` and `push=wake`.** It does not implement
373
470
  background log delivery into model context. Read with `action=logs` or
374
- `action=wait`; these pull reads are separate from the Claude Mod's user-visible
375
- display. Cursor reads exclude earlier indices, but a limited read can omit
471
+ `action=wait`; these pull reads are separate from both clients' live displays.
472
+ Cursor reads exclude earlier indices, but a limited read can omit
376
473
  lines; see [Reading logs from a cursor](#reading-logs-from-a-cursor).
377
474
  - **Captures end with the client.** The server is a child of Codex/Claude. When
378
475
  the client closes the connection, the server finishes the call in progress,
@@ -552,8 +649,8 @@ run. Set `installPods=false` to skip it deliberately.
552
649
  Detects the workspace from the current directory (walking up, so a nested cwd
553
650
  works), rebuilds when the tree changed, installs, launches, and starts capturing.
554
651
  Native pi/omp can push logs into the conversation; Claude Code and Codex use
555
- `logs`/`wait` pull reads through MCP. The optional Claude Mod displays a console
556
- tail to the user, not to the model. The phrase is a goal, not a log filter.
652
+ `logs`/`wait` pull reads through MCP. Both clients offer an optional live preview
653
+ for the user. The phrase is a goal, not a log filter.
557
654
 
558
655
  - **CocoaPods vs plain project** is decided by `Podfile`/`Podfile.lock`: a
559
656
  CocoaPods project uses its `.xcworkspace`, a plain project its `.xcodeproj`.
@@ -757,6 +854,9 @@ session.
757
854
  - **Do not stop while the user has not acted yet.** Silence there means nothing
758
855
  has been tried, not that the run is over: say what to do on the phone and keep
759
856
  listening.
857
+ - When the initial process-table query succeeds, a dual-channel launch runs
858
+ console app-PID discovery before connecting the syslog companion. An explicit
859
+ stop during that step does not leave a new companion running.
760
860
  - A console capture ends when the app process is confirmed gone, and its syslog
761
861
  companion is stopped too. It records why - `the app exited`, with the last
762
862
  line logged, which is devicectl's own `App terminated due to signal 9.` when
@@ -765,6 +865,28 @@ session.
765
865
  the log and its path is reported the same way. A standalone `syslog` capture
766
866
  is not bound to the app's lifetime and keeps reconnecting; stop it explicitly
767
867
  when finished.
868
+ - An interrupted `wait`, `await`, or `launch` with `command` joins the existing
869
+ exit-diagnostic job (launch identity and report collection) before replying.
870
+ A matching report supplies its
871
+ system termination namespace, code and explanation, plus its local path, in
872
+ the reply and follow-up details (`terminationReason`, `crashReport`). The
873
+ report search can add time after the line-wait or command deadline; caller
874
+ cancellation still interrupts it. A missing report or missing termination
875
+ data is reported as unavailable, not replaced with a guessed cause. A verified
876
+ App PID is required before a report can supply termination evidence; unknown
877
+ identity is reported explicitly without promoting another instance's candidate
878
+ report. Reattach-generation checks prevent an older search from overwriting
879
+ the newly launched instance's report.
880
+ Natural process exit registers that job before pipe/writer drain. Identity is
881
+ taken from this console launch's own `--json-output` result
882
+ (`result.process.processIdentifier`), not a late same-name process-table
883
+ snapshot. Each bridge start owns a fresh result file, removed after reading;
884
+ result identity and reattach-generation checks keep old jobs out of new runs.
885
+ A missing, malformed or unsuccessful launch result remains unverified; an
886
+ automatic reattach will not terminate an unverified running instance.
887
+ `wait` joins both identity and report collection. When a command exits, its
888
+ capture and queued reconnect are stopped before awaiting that independent job;
889
+ confirmed termination likewise cancels reconnect without cancelling collection.
768
890
  - A dropped console bridge whose app is still running is reattached, retrying
769
891
  for as long as it takes. devicectl attaches a console only by launching, so
770
892
  with the default `terminateExisting` **a reattach restarts the app** and its
@@ -786,9 +908,10 @@ session.
786
908
  e.g. `📖 xcodebug · capturing · 7895 lines · 42s · /xcodebug stop to end`, plus
787
909
  recent log lines and the number of streaming channels. Claude Code can instead
788
910
  load the [live display Mod](#claude-code-live-display).
911
+ Codex can enable the [experimental status line](#codex-live-display-experimental).
789
912
  - Native pushed log batches are **hidden from the transcript** (`display: false`)
790
913
  but delivered to the model, subject to the per-batch limit. MCP does not push
791
- batches; the Claude Mod's display does not add logs to model context.
914
+ batches; neither MCP live display adds logs to model context.
792
915
  - `/xcodebug stop` (or `action=stop`) without `captureId` closes **every running
793
916
  capture**. An ID scopes the stop to that target; a console primary's syslog
794
917
  companion is stopped too. Other apps' captures are unaffected by a targeted
@@ -922,6 +1045,20 @@ writes to drain. If they remain blocked, it destroys the streams, reports a
922
1045
  drain-timeout error in capture status, and completes shutdown; pending logs may
923
1046
  be truncated.
924
1047
 
1048
+ Console launches also own a private `.xcodebug-launch-*` directory containing
1049
+ `launch.json` and an `owner.json` marker with this extension's format, host PID
1050
+ and creation time. The directory is mode `0700`; the marker is mode `0600`.
1051
+ Result cleanup follows reading; raw metadata never enters the console log stream.
1052
+ Ordinary `stop` leaves a pending result read available to exit diagnostics.
1053
+ Session shutdown separately cancels those reads, blocks new bridge starts, and
1054
+ allows up to three seconds per capture for pending startup, result cleanup and
1055
+ log drainage, including older reattach results and captures evicted from visible
1056
+ history. Blocked filesystem work or failed deletion is reported as incomplete
1057
+ cleanup, including failures from captures already evicted from history.
1058
+ Once cleanup settles, the session retains only the warning text for shutdown,
1059
+ not the finished capture or its log buffer.
1060
+ Residual result files may remain; task settlement alone is not proof of deletion.
1061
+
925
1062
  The bundle id separates apps, and the timestamp includes milliseconds to
926
1063
  separate runs. Segment limits apply per capture. What xcodebug itself says while
927
1064
  a bridge is down - why the capture ended, each reattach - is appended to the same
@@ -931,8 +1068,13 @@ known, a report without that PID is not retained.
931
1068
 
932
1069
  Logs are kept for 30 days after their last write. The first `build`, `launch` or
933
1070
  `syslog` of a session deletes older `build-`, `console-`, `syslog-` and
934
- `pod-install-` logs and `crash-*.ips` reports from this directory, and nothing
935
- else in it.
1071
+ `pod-install-` logs and `crash-*.ips` reports from this directory. The same
1072
+ retention window applies to residual launch-result directories, but only when
1073
+ the ownership marker is valid, the host PID is definitely absent, and the
1074
+ directory and all known files are old. Active or uncertain owners, unmarked
1075
+ legacy directories, malformed markers, symlinks and extra entries are retained.
1076
+ Pruning removes only validated `owner.json` / `launch.json` files and an empty
1077
+ directory, never recursively deleting a directory based on its prefix.
936
1078
 
937
1079
  A successful build clears `<agentDir>/logs/xcodebug/archive/` first, so snapshots
938
1080
  from a previous binary cannot be mistaken for the run that is starting.
package/archive.ts CHANGED
@@ -14,7 +14,8 @@
14
14
  * device archive - os_log only (framework/system messages, errors)
15
15
  * MySDK-style NSLog lines appear only in the live channel.
16
16
  */
17
- import { mkdir, readdir, rm, stat } from "node:fs/promises";
17
+ import { constants, type Stats } from "node:fs";
18
+ import { lstat, mkdir, open, readdir, rm, rmdir, stat, unlink } from "node:fs/promises";
18
19
  import { dirname, join } from "node:path";
19
20
  import { runCommand, timestamp } from "./exec.ts";
20
21
 
@@ -64,12 +65,80 @@ export async function clearArchives(workDir: string): Promise<{ removed: number;
64
65
  /** The files this extension writes: build, capture and pod install logs, and pulled crash reports. */
65
66
  const OWN_LOG = /^(?:build|console|syslog|pod-install|crash)-.+\.(?:log(?:\.\d+)?|ips)$/;
66
67
 
68
+ /** Reclaim only expired, marked launch results whose owning process is definitely gone. */
69
+ async function pruneLaunchResult(path: string, cutoff: number): Promise<void> {
70
+ const same = (a: Stats, b: Stats) => a.dev === b.dev && a.ino === b.ino
71
+ && a.size === b.size && a.mtimeMs === b.mtimeMs && a.ctimeMs === b.ctimeMs;
72
+ const inspect = async (expectedDirectory?: Stats) => {
73
+ const directory = await lstat(path);
74
+ if (!directory.isDirectory() || (expectedDirectory
75
+ ? !same(directory, expectedDirectory) : !(directory.mtimeMs < cutoff))) return;
76
+ const names = (await readdir(path)).sort();
77
+ if (!names.includes("owner.json") || names.some(name => name !== "owner.json" && name !== "launch.json")) return;
78
+ const files: { name: string; info: Stats }[] = [];
79
+ for (const name of names) {
80
+ const info = await lstat(join(path, name));
81
+ if (!info.isFile() || !(info.mtimeMs < cutoff)) return;
82
+ files.push({ name, info });
83
+ }
84
+ const ownerInfo = files.find(file => file.name === "owner.json")!.info;
85
+ // Refuse links and oversized unknown content before reading an ownership marker.
86
+ if (ownerInfo.size > 1_024) return;
87
+ const handle = await open(join(path, "owner.json"), constants.O_RDONLY | constants.O_NOFOLLOW);
88
+ let ownerText: string;
89
+ try {
90
+ if (!same(await handle.stat(), ownerInfo)) return;
91
+ ownerText = await handle.readFile({ encoding: "utf8" });
92
+ if (!same(await handle.stat(), ownerInfo)) return;
93
+ } finally {
94
+ await handle.close();
95
+ }
96
+ const owner = JSON.parse(ownerText);
97
+ if (!owner || typeof owner !== "object" || Array.isArray(owner) || Object.keys(owner).length !== 4
98
+ || owner.kind !== "xcodebug.launch-result" || owner.version !== 1
99
+ || !Number.isSafeInteger(owner.pid) || owner.pid <= 0
100
+ || !Number.isSafeInteger(owner.createdAt) || owner.createdAt < 0 || !(owner.createdAt < cutoff)) return;
101
+ try {
102
+ process.kill(owner.pid, 0);
103
+ return;
104
+ } catch (error) {
105
+ if ((error as NodeJS.ErrnoException).code !== "ESRCH") return;
106
+ }
107
+ for (const file of files) {
108
+ if (!same(await lstat(join(path, file.name)), file.info)) return;
109
+ }
110
+ if (!same(await lstat(path), directory)) return;
111
+ return { directory, files, ownerText };
112
+ };
113
+
114
+ const initial = await inspect();
115
+ if (!initial) return;
116
+ let expectedDirectory = initial.directory;
117
+ let removed = 0;
118
+ // Sorted entries remove launch.json first, retaining proof of ownership if cleanup fails.
119
+ for (const file of initial.files) {
120
+ const current = await inspect(expectedDirectory);
121
+ if (!current || current.ownerText !== initial.ownerText || current.files.length !== initial.files.length - removed
122
+ || current.files.some((entry, index) => entry.name !== initial.files[index + removed].name
123
+ || !same(entry.info, initial.files[index + removed].info))) return;
124
+ await unlink(join(path, file.name));
125
+ removed++;
126
+ // Only our successful unlink may make an otherwise-expired directory fresh.
127
+ expectedDirectory = await lstat(path);
128
+ if (!expectedDirectory.isDirectory() || expectedDirectory.dev !== initial.directory.dev
129
+ || expectedDirectory.ino !== initial.directory.ino) return;
130
+ }
131
+ if ((await readdir(path)).length === 0 && same(await lstat(path), expectedDirectory)) await rmdir(path);
132
+ }
133
+
67
134
  /**
68
135
  * Delete this extension's logs that nothing has written to for `maxAgeMs`.
69
136
  *
70
137
  * Nothing else ever removes them, and they add up to hundreds of megabytes in
71
138
  * a few weeks. Age since the last write is the whole test: a capture still
72
139
  * running keeps its log fresh, and a file xcodebug did not name is left alone.
140
+ * Owned launch-result leftovers additionally require an expired marker and a
141
+ * definitely absent owner; unmarked or uncertain directories are left alone.
73
142
  */
74
143
  export async function pruneLogs(logDir: string, maxAgeMs: number): Promise<void> {
75
144
  let entries: string[];
@@ -80,12 +149,14 @@ export async function pruneLogs(logDir: string, maxAgeMs: number): Promise<void>
80
149
  }
81
150
  const cutoff = Date.now() - maxAgeMs;
82
151
  for (const name of entries) {
83
- if (!OWN_LOG.test(name)) continue;
152
+ const launchResult = name.startsWith(".xcodebug-launch-") && name.length > ".xcodebug-launch-".length;
153
+ if (!OWN_LOG.test(name) && !launchResult) continue;
84
154
  const path = join(logDir, name);
85
155
  try {
86
- if ((await stat(path)).mtimeMs < cutoff) await rm(path, { force: true });
156
+ if (launchResult) await pruneLaunchResult(path, cutoff);
157
+ else if ((await stat(path)).mtimeMs < cutoff) await rm(path, { force: true });
87
158
  } catch {
88
- // A log that cannot be removed is not worth failing a run over.
159
+ // A log or owned result that cannot be removed is not worth failing a run over.
89
160
  }
90
161
  }
91
162
  }