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/GUIDE.md CHANGED
@@ -12,6 +12,18 @@ 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 to register
16
+ the server when missing and set Codex's 4200-second tool timeout. From a
17
+ checkout, use `node bin/xcodebug-setup-codex.mjs`. This explicit command keeps
18
+ package installation from changing Codex configuration silently.
19
+
20
+ Native pi/omp `/xcodebug` dispatches directly to the loaded extension handler,
21
+ without skill/model selection for that dispatch. The package excludes its
22
+ bundled skill from native package discovery; Claude/Codex share `mcp/skills/xcodebug/SKILL.md`.
23
+ If a native host also discovers that user-level shared skill, it routes to the native tool
24
+ when available. Reading a skill alone never executes an action; model-selected
25
+ requests still require a tool call, while the native command runs its handler.
26
+
15
27
  Debug a real iOS device: build, install, launch, and read the app's console
16
28
  (stdout/stderr + os_log) inside the agent session. No jailbreak, no LLDB attach,
17
29
  no paid account.
@@ -89,6 +101,12 @@ for analysis.
89
101
  See [Claude Code live display](README.md#claude-code-live-display) for version
90
102
  requirements, upgrade/disable steps and missing-display troubleshooting.
91
103
 
104
+ For an optional footer in Codex CLI 0.171.0 or later, follow the
105
+ [Codex live display setup](README.md#codex-live-display-experimental). The
106
+ footer shows the current operation or one running capture and its
107
+ latest log line. It refreshes between tool calls and clears once no operation
108
+ or capture remains. Use `logs` or `wait` to bring log evidence into the conversation.
109
+
92
110
  ## Running a command alongside a capture
93
111
 
94
112
  ### What it is for
@@ -142,8 +160,12 @@ What happens after `command`:
142
160
  1. `/bin/sh -lc` runs the whole line, with the project root as the working
143
161
  directory (`pi.cwd` → `ctx.cwd` → process cwd).
144
162
  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
163
+ 3. It stops **the capture it targeted** and cancels its queued reconnect — other
164
+ apps' captures keep streaming.
165
+ 4. When collecting exit diagnostics, it waits for the owned console-launch
166
+ result and matching crash-report collection independently of the stopped
167
+ capture; caller cancellation still interrupts that wait.
168
+ 5. It hands back the exit code, elapsed time, how many new lines arrived, the
147
169
  log path, and the `logs` call (with the right `since`) for the app side.
148
170
 
149
171
  **Quote the whole line.** `command="cd /repo && npm run test"`. Unquoted, the
@@ -215,6 +237,7 @@ xcodebug action=restart # after editing: rebuild + relaunch +
215
237
  xcodebug action=logs limit=200
216
238
  xcodebug action=logs grep=MySDK
217
239
  xcodebug action=wait match="DataPacket" timeoutSeconds=30
240
+ xcodebug action=wait match="sync (done|failed)" regex=true # either outcome, one wait
218
241
 
219
242
  # wrap up
220
243
  xcodebug action=status
@@ -244,6 +267,16 @@ pending writes; a drain timeout can truncate logs. Neither memory nor disk is
244
267
  a lossless archive of the whole run. See [retention](README.md#reading-logs-from-a-cursor)
245
268
  and [disk files](README.md#files) for details and the `logFiles` path list.
246
269
 
270
+ A filtered read (`logs grep=`, `wait`) looks in those files for the lines memory
271
+ has dropped and says in its reply that it did. Logs are deleted 30 days after
272
+ their last write.
273
+
274
+ Console launch-result JSON is temporary metadata, not a log. Ordinary `stop`
275
+ preserves pending exit diagnostics; session exit instead cancels result reads
276
+ and bounds startup/result cleanup as well as log drainage. Incomplete cleanup
277
+ is reported. Ownership-checked stale-result reclamation and its conservative
278
+ exceptions are documented under [disk files](README.md#files).
279
+
247
280
  ## Three rules of use
248
281
 
249
282
  1. **Stop once the log has answered the question.** A capture left running keeps
@@ -251,5 +284,7 @@ and [disk files](README.md#files) for details and the `logFiles` path list.
251
284
  2. **Do not stop while the user has not acted yet.** Silence there means "not
252
285
  tried yet", not "finished" — say what to tap and keep listening.
253
286
  3. **A console capture ends when the app process is confirmed gone.** Its syslog
254
- companion is stopped too. A standalone `syslog` capture is not bound to the
255
- app's lifetime and keeps reconnecting; stop it explicitly when finished.
287
+ companion is stopped too, and `status` says why it ended and where the crash
288
+ report is, if the device wrote one. A standalone `syslog` capture is not
289
+ bound to the app's lifetime and keeps reconnecting; stop it explicitly when
290
+ finished.
package/README.md CHANGED
@@ -92,13 +92,81 @@ codex mcp list # xcodebug bun …
92
92
  claude mcp list # xcodebug: … ✔ Connected
93
93
  ```
94
94
 
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
+
98
+ ```bash
99
+ xcodebug-setup-codex
100
+ ```
101
+
102
+ From a checkout, use `node bin/xcodebug-setup-codex.mjs`. The command uses the
103
+ Codex app-server config API. It registers xcodebug with Bun if it is missing,
104
+ then writes `tool_timeout_sec = 4200`. It does not run automatically during npm
105
+ install because package installation should not silently modify a user's Codex
106
+ configuration. The equivalent manual setting is:
107
+
108
+ ```toml
109
+ [mcp_servers.xcodebug]
110
+ tool_timeout_sec = 4200
111
+ ```
112
+
113
+ The timeout leaves room for the default 15-minute pod install, 15-minute build
114
+ and 30-minute command budgets, plus device operations. Increase it if you pass
115
+ larger timeouts. This does not change xcodebug's stage deadlines or Codex's
116
+ separate status-line resource read deadline.
117
+
118
+ Claude Code needs no setting for this. Its default limit on a tool call is about
119
+ 28 hours. It also ends a call to a stdio server that has sent neither a reply
120
+ nor a progress notification for 30 minutes; this server sends progress once a
121
+ second to a client that asks for it.
122
+
123
+ Cancelling an MCP request aborts that request. On SIGINT, SIGTERM or detected
124
+ stdout loss, the server stops accepting work, cancels admitted requests and
125
+ then cleans up captures. Closing only stdin lets admitted requests finish and
126
+ sends their replies; a silent lost reader cannot be distinguished from this
127
+ until stdout closes or a write fails.
128
+
129
+ To run `npm test` from a checkout, use Node.js 22.18 or later and put Bun on PATH
130
+ for the stdio integration tests.
131
+
132
+ ### Codex live display (experimental)
133
+
134
+ With Codex CLI 0.171.0 or later, start Codex with
135
+ `codex --enable tui_extensions_statusline` and choose `xcodebug / xcodebug_ui`
136
+ under `/statusline`. Use a fresh Codex session after updating the xcodebug MCP
137
+ server. For persistent opt-in, set `features.tui_extensions_statusline = true`
138
+ in Codex's config (or set `tui_extensions_statusline = true` under `[features]`).
139
+ Codex 0.171.0 looks up status-line providers in the user configuration. If a
140
+ project config overrides the same MCP server name, remove the override or use
141
+ a distinct server name for the user registration.
142
+
143
+ The footer shows the current operation or capture and its latest log line. It
144
+ refreshes even between tool calls and clears when no operation or capture is
145
+ active. This is a display preview, not a log stream into the conversation; use
146
+ `action=logs` or `action=wait` for log evidence.
147
+ Long status text is shortened in the footer without changing the command or
148
+ its output.
149
+
95
150
  ### Install the manual entry point
96
151
 
97
152
  Connecting MCP makes the tool available to the model; it does not register a
98
153
  `/xcodebug` command in either client. The shared
99
- [xcodebug skill](skills/xcodebug/SKILL.md) adds an explicit entry point:
154
+ [xcodebug skill](mcp/skills/xcodebug/SKILL.md) adds an explicit entry point:
100
155
  `/xcodebug` in Claude Code, `$xcodebug` in Codex, or Codex's `/skills` picker.
101
156
 
157
+ Native pi/omp needs only the extension, not this skill or an MCP connection.
158
+ Both hosts register `extensions: ["./index.ts"]`; `pi.skills: []` disables pi's
159
+ package skill loading. The shared skill lives under `mcp/skills/`, outside the
160
+ root `skills/` directory that omp scans independently of manifest fields.
161
+ Native `/xcodebug` runs
162
+ the registered extension handler directly; it does not ask the model to select
163
+ a skill. A normal model tool call uses the registered native `xcodebug` tool.
164
+ If pi/omp also discovers the shared user-level skill through `.agents/skills`
165
+ or `.claude/skills`, its instructions select that native tool before MCP.
166
+ This shared-skill selection is model-driven, not a substitute for the native
167
+ command's deterministic dispatch. The extension must be installed, enabled and
168
+ loaded in the session; explicitly disabling it is not overridden.
169
+
102
170
  Both clients can read the same skill directory through user-level symlinks:
103
171
 
104
172
  ```bash
@@ -107,11 +175,12 @@ XCODEBUG_DIR="/absolute/path/to/xcodebug" # a checkout containing the skill
107
175
  # XCODEBUG_DIR="$(npm root -g)/xcodebug"
108
176
 
109
177
  (
110
- source="$XCODEBUG_DIR/skills/xcodebug"
178
+ source="$XCODEBUG_DIR/mcp/skills/xcodebug"
179
+ legacy="$XCODEBUG_DIR/skills/xcodebug"
111
180
  test -f "$source/SKILL.md" || { printf 'Skill not found: %s\n' "$source/SKILL.md" >&2; exit 1; }
112
181
  for dest in "$HOME/.agents/skills/xcodebug" "$HOME/.claude/skills/xcodebug"; do
113
182
  if test -e "$dest" || test -L "$dest"; then
114
- if ! test -L "$dest" || ! test "$dest" -ef "$source"; then
183
+ if ! test -L "$dest" || { ! test "$dest" -ef "$source" && ! test "$(readlink "$dest")" = "$legacy"; }; then
115
184
  printf 'Existing skill path: %s; inspect it before installing.\n' "$dest" >&2
116
185
  exit 1
117
186
  fi
@@ -119,22 +188,29 @@ XCODEBUG_DIR="/absolute/path/to/xcodebug" # a checkout containing the skill
119
188
  done
120
189
  mkdir -p "$HOME/.agents/skills" "$HOME/.claude/skills" || exit 1
121
190
  for dest in "$HOME/.agents/skills/xcodebug" "$HOME/.claude/skills/xcodebug"; do
191
+ if test -L "$dest" && test "$(readlink "$dest")" = "$legacy"; then
192
+ rm "$dest" || exit 1
193
+ fi
122
194
  test -L "$dest" || ln -s "$source" "$dest" || exit 1
123
195
  done
124
196
  )
125
197
  ```
126
198
 
127
- If the installed package does not contain `skills/xcodebug/SKILL.md`, use a
199
+ If the installed package does not contain `mcp/skills/xcodebug/SKILL.md`, use a
128
200
  checkout that contains it. The commands check both target paths before installing,
129
- skip symlinks already pointing to this skill, and stop on other existing files,
130
- directories or symlinks, including broken links.
131
- Keep the checkout or npm package at the linked path. Updating that source updates
132
- the shared skill for both clients.
201
+ skip symlinks already pointing to this skill, and migrate links to this checkout's
202
+ old `skills/xcodebug` source. They stop on other existing files, directories or
203
+ symlinks, including unrelated broken links. After updating an older checkout or
204
+ upgrading an npm package that used the old root `skills/` path, rerun these
205
+ commands to relink both clients; npm upgrade alone does not migrate those links.
206
+ Keep the checkout or npm package at the linked path. Once relinked, updates to
207
+ the maintained source update the shared skill for both clients.
133
208
 
134
209
  Start a new Claude Code or Codex session after installing. The skill uses the
135
- MCP connection already configured above; it does not start a separate server or
136
- replace the native pi command. Both manual and model-selected invocation remain
137
- available. See the clients' [Claude Code skill documentation](https://code.claude.com/docs/en/skills)
210
+ MCP connection already configured above in those clients; it does not start a
211
+ separate server. Native pi/omp uses its extension command and native tool instead.
212
+ Both manual and model-selected invocation remain available. See the clients'
213
+ [Claude Code skill documentation](https://code.claude.com/docs/en/skills)
138
214
  and [Codex skill documentation](https://learn.chatgpt.com/docs/build-skills).
139
215
 
140
216
  ### Use
@@ -340,18 +416,20 @@ remain available without the display.
340
416
  |---|---|---|
341
417
  | how the tool is exposed | registered in-process | MCP server process |
342
418
  | manual entry point | native `/xcodebug` | shared skill: `/xcodebug` in Claude, `$xcodebug` in Codex |
343
- | status line, widget | yes | Claude: optional live Mod above; otherwise request progress when rendered |
419
+ | status line, widget | yes | [Claude live Mod](#claude-code-live-display) or [Codex status line](#codex-live-display-experimental), both opt-in |
344
420
  | `push` | mirrors new lines into the session | `off` only; `context` and `wake` refused |
345
421
  | capture state | in the session | in the server process |
346
422
  | lifetime | the session | the client process |
347
423
 
348
424
  - **The adapter refuses `push=context` and `push=wake`.** It does not implement
349
425
  background log delivery into model context. Read with `action=logs` or
350
- `action=wait`; these pull reads are separate from the Claude Mod's user-visible
351
- display. Cursor reads exclude earlier indices, but a limited read can omit
426
+ `action=wait`; these pull reads are separate from both clients' live displays.
427
+ Cursor reads exclude earlier indices, but a limited read can omit
352
428
  lines; see [Reading logs from a cursor](#reading-logs-from-a-cursor).
353
- - **Captures end with the client.** The server is a child of Codex/Claude, so
354
- quitting the client stops the bridges. Relaunch next session.
429
+ - **Captures end with the client.** The server is a child of Codex/Claude. When
430
+ the client closes the connection, the server finishes the call in progress,
431
+ stops its captures and exits. On SIGINT or SIGTERM it stops at once, a build
432
+ still running included. Relaunch next session.
355
433
 
356
434
  Logs land in `~/.xcodebug/logs/xcodebug/`, or under `XCODEBUG_AGENT_DIR` when set.
357
435
  Every response also reports the exact path, so the model can read the file once a
@@ -452,13 +530,23 @@ rather than writing logs to a guessed path.
452
530
  `device` may be a name, UDID, ECID or CoreDevice uuid. With one physical device
453
531
  connected it can be omitted.
454
532
 
533
+ A file that is not valid JSON is an error, not an absent config: `doctor` reports
534
+ it, and every action that would read it refuses to run rather than use the
535
+ defaults the file was written to override. The actions that never read it -
536
+ `devices`, `logs`, `wait`, `status`, `stop` and `await` - still work.
537
+
455
538
  ## Change detection and pod install
456
539
 
457
540
  Every `build` and `launch` first inspects the working tree with
458
541
  `git status --porcelain -uall`:
459
542
 
460
- 1. **Any build-relevant change** (sources, resources, Podfile, podspec, project
461
- files) forces a rebuild + relaunch.
543
+ 1. **Any change git reports** forces a rebuild + relaunch, tracked or not and
544
+ whatever its type (`Podfile.rb`, an `.xcconfig`, a new image): a build that
545
+ is reused must not be older than what it was built from. The exceptions are
546
+ the types no build reads - notes, logs, crash reports and patches (`.md`,
547
+ `.log`, `.ips`, `.patch`, `.diff`) - so what a run leaves in the tree does
548
+ not trigger a build. A run that writes files of other types into the
549
+ repository, such as JSON results, does.
462
550
  2. **A new file inside a pod** forces `pod install --no-repo-update` first,
463
551
  because the generated Pods project enumerates pod sources and will not
464
552
  compile a file it has never seen. Pod membership comes from the repo's own
@@ -472,10 +560,24 @@ Every `build` and `launch` first inspects the working tree with
472
560
  `Podfile` (the workspace's parent). If there is none, the step is skipped and
473
561
  the reason is reported - it never searches elsewhere, because that could
474
562
  reinstall a different project's pods.
475
- 4. **No change** since the last successful build in this session reuses that
476
- build instead of rebuilding for minutes. Pass `force=true` to override.
563
+ 4. **No change** since this session last built the same scheme, configuration
564
+ and device reuses that build, for `launch` as well as `build`, instead of
565
+ rebuilding for minutes. The app is still installed and launched. Pass
566
+ `force=true` to rebuild. "No change" means all of:
567
+ - the same committed code and the same uncommitted changes. A commit, pull or
568
+ checkout rebuilds even though `git status` is clean again; `git add` alone
569
+ does not;
570
+ - the same files in every pod the workspace installs from a path outside the
571
+ repository (`:path` in `Podfile.lock`), which `git status` cannot see;
572
+ - the built `.app` is as that build left it. Xcode, or an `xcodebuild` in
573
+ another terminal, writes the same product path.
574
+
575
+ A build during which the tree changed is not reused, and its reply says so.
477
576
 
478
577
  Inspect the decision without building:
578
+ Use the same target and device options as the intended build. If the target
579
+ cannot be resolved, the report cannot identify a reusable build. If pod install
580
+ is needed, the preview assumes a rebuild until the updated tree is available.
479
581
 
480
582
  ```text
481
583
  xcodebug action=changes
@@ -485,6 +587,7 @@ xcodebug action=changes
485
587
  2 build-relevant change(s)
486
588
  M Packages/FeatureX/Classes/Weather/AddCityController.swift
487
589
  fingerprint: 963e92a4
590
+ last build for this target: (none)
488
591
  rebuild needed: yes
489
592
  pod install needed: no
490
593
  ```
@@ -501,8 +604,8 @@ run. Set `installPods=false` to skip it deliberately.
501
604
  Detects the workspace from the current directory (walking up, so a nested cwd
502
605
  works), rebuilds when the tree changed, installs, launches, and starts capturing.
503
606
  Native pi/omp can push logs into the conversation; Claude Code and Codex use
504
- `logs`/`wait` pull reads through MCP. The optional Claude Mod displays a console
505
- tail to the user, not to the model. The phrase is a goal, not a log filter.
607
+ `logs`/`wait` pull reads through MCP. Both clients offer an optional live preview
608
+ for the user. The phrase is a goal, not a log filter.
506
609
 
507
610
  - **CocoaPods vs plain project** is decided by `Podfile`/`Podfile.lock`: a
508
611
  CocoaPods project uses its `.xcworkspace`, a plain project its `.xcodeproj`.
@@ -632,7 +735,10 @@ nothing about any test framework. Two consequences worth knowing:
632
735
  What it reports: exit code, elapsed time, how many new lines the capture gained,
633
736
  the log path, and the `action=logs` call (with the right `since`) that returns
634
737
  the app side of that run. A non-zero exit is surfaced as an error, not as a
635
- successful "run finished".
738
+ successful "run finished". Two things about the capture are reported when they
739
+ happened, because either one changes what the log means: that it was no longer
740
+ capturing when the command finished (with the reason, or the last line logged),
741
+ and that a console reattach relaunched the app during the run.
636
742
 
637
743
  ### What the model does with it
638
744
 
@@ -685,8 +791,10 @@ Boundaries that keep it out of every other workflow:
685
791
  **Prerequisite when the command drives the UI:** the runner must not relaunch the
686
792
  app. Many UI-test fixtures terminate and relaunch the app before every test
687
793
  unless `autoAppLaunch: false` is set, which kills the very launch xcodebug is
688
- capturing. Set it in the config the run uses. A command that does not touch the
689
- app (a curl, a fixture import, a codegen step) has no such constraint.
794
+ capturing. Set it in the config the run uses. When it happens anyway, the capture
795
+ ends there and says the app was restarted outside it; it does not relaunch over
796
+ the runner's instance. A command that does not touch the app (a curl, a fixture
797
+ import, a codegen step) has no such constraint.
690
798
 
691
799
  ### Run semantics
692
800
 
@@ -701,11 +809,51 @@ session.
701
809
  - **Do not stop while the user has not acted yet.** Silence there means nothing
702
810
  has been tried, not that the run is over: say what to do on the phone and keep
703
811
  listening.
812
+ - When the initial process-table query succeeds, a dual-channel launch runs
813
+ console app-PID discovery before connecting the syslog companion. An explicit
814
+ stop during that step does not leave a new companion running.
704
815
  - A console capture ends when the app process is confirmed gone, and its syslog
705
- companion is stopped too. A standalone `syslog` capture is not bound to the
706
- app's lifetime and keeps reconnecting; stop it explicitly when finished.
707
- - A dropped console bridge otherwise reconnects indefinitely. An inconclusive
708
- probe (USB unplugged, `devicectl` timeout) is **not** treated as "the app exited".
816
+ companion is stopped too. It records why - `the app exited`, with the last
817
+ line logged, which is devicectl's own `App terminated due to signal 9.` when
818
+ the app was killed - in the log file, in `status`, and under later `logs`
819
+ reads. If the device wrote a crash report for the app, it is copied next to
820
+ the log and its path is reported the same way. A standalone `syslog` capture
821
+ is not bound to the app's lifetime and keeps reconnecting; stop it explicitly
822
+ when finished.
823
+ - An interrupted `wait`, `await`, or `launch` with `command` joins the existing
824
+ exit-diagnostic job (launch identity and report collection) before replying.
825
+ A matching report supplies its
826
+ system termination namespace, code and explanation, plus its local path, in
827
+ the reply and follow-up details (`terminationReason`, `crashReport`). The
828
+ report search can add time after the line-wait or command deadline; caller
829
+ cancellation still interrupts it. A missing report or missing termination
830
+ data is reported as unavailable, not replaced with a guessed cause. A verified
831
+ App PID is required before a report can supply termination evidence; unknown
832
+ identity is reported explicitly without promoting another instance's candidate
833
+ report. Reattach-generation checks prevent an older search from overwriting
834
+ the newly launched instance's report.
835
+ Natural process exit registers that job before pipe/writer drain. Identity is
836
+ taken from this console launch's own `--json-output` result
837
+ (`result.process.processIdentifier`), not a late same-name process-table
838
+ snapshot. Each bridge start owns a fresh result file, removed after reading;
839
+ result identity and reattach-generation checks keep old jobs out of new runs.
840
+ A missing, malformed or unsuccessful launch result remains unverified; an
841
+ automatic reattach will not terminate an unverified running instance.
842
+ `wait` joins both identity and report collection. When a command exits, its
843
+ capture and queued reconnect are stopped before awaiting that independent job;
844
+ confirmed termination likewise cancels reconnect without cancelling collection.
845
+ - A dropped console bridge whose app is still running is reattached, retrying
846
+ for as long as it takes. devicectl attaches a console only by launching, so
847
+ with the default `terminateExisting` **a reattach restarts the app** and its
848
+ state is gone: the log says so and `status` counts the relaunches. An
849
+ inconclusive probe (USB unplugged, `devicectl` timeout) is retried without
850
+ relaunching. If the current PID is known but capture ownership cannot be
851
+ verified, a reattach that would terminate the running app is skipped.
852
+ - If the instance running is not the one this capture launched - another
853
+ session, a test runner or the user relaunched the app - the capture ends and
854
+ leaves that instance alone. Reattaching would terminate it. The session that
855
+ did the relaunching is told as well: its `launch` reply notes that the app was
856
+ already running and not started by it.
709
857
  - `idevicesyslog` can go silent with its process still alive; a 30s watchdog kills
710
858
  it and the exit hook reattaches. Reattachment has exactly one owner, so the
711
859
  watchdog and the exit hook can never both assume the other is handling it.
@@ -715,9 +863,10 @@ session.
715
863
  e.g. `📖 xcodebug · capturing · 7895 lines · 42s · /xcodebug stop to end`, plus
716
864
  recent log lines and the number of streaming channels. Claude Code can instead
717
865
  load the [live display Mod](#claude-code-live-display).
866
+ Codex can enable the [experimental status line](#codex-live-display-experimental).
718
867
  - Native pushed log batches are **hidden from the transcript** (`display: false`)
719
868
  but delivered to the model, subject to the per-batch limit. MCP does not push
720
- batches; the Claude Mod's display does not add logs to model context.
869
+ batches; neither MCP live display adds logs to model context.
721
870
  - `/xcodebug stop` (or `action=stop`) without `captureId` closes **every running
722
871
  capture**. An ID scopes the stop to that target; a console primary's syslog
723
872
  companion is stopped too. Other apps' captures are unaffected by a targeted
@@ -746,7 +895,9 @@ xcodebug action=syslog processName=MyApp
746
895
  # incremental reads (cursor-based)
747
896
  xcodebug action=logs limit=200
748
897
  xcodebug action=logs grep=MySDK
898
+ xcodebug action=logs grep=MySDK times=true
749
899
  xcodebug action=wait match="DataPacket" timeoutSeconds=30
900
+ xcodebug action=wait match="sync (done|failed)" regex=true timeoutSeconds=30
750
901
 
751
902
  xcodebug action=status
752
903
  xcodebug action=stop keepApp=true
@@ -790,6 +941,19 @@ is written to disk and delivered to live subscribers but not retained for
790
941
  and captures reconnecting after a bridge failure are not evicted. Older capture
791
942
  IDs leave `logs`/`status`, while their retained disk segments remain available.
792
943
 
944
+ A busy app fills that buffer in seconds, so a filtered read does not stop at it.
945
+ `logs grep=...` and `wait` also search for lines missing from memory, including
946
+ oversized lines between retained entries. They wait for writes through the
947
+ scan's cursor before reading disk; cancellation interrupts that work. The reply
948
+ reports how many lines were searched on disk and how many are unavailable.
949
+ An unfiltered `logs` returns the newest lines as before and
950
+ names the log file for the rest.
951
+
952
+ `regex=true` makes `grep` and `match` regular expressions, so one `wait` can
953
+ cover both outcomes of a step: `match="sync (done|failed)"`. `times=true`
954
+ prefixes each returned line with the host time it arrived, for lining the log
955
+ up with a test runner's own output.
956
+
793
957
  ### `syslog`: attach without relaunching
794
958
 
795
959
  `launch` restarts the app because `devicectl --console` has to start it. When the
@@ -836,9 +1000,36 @@ writes to drain. If they remain blocked, it destroys the streams, reports a
836
1000
  drain-timeout error in capture status, and completes shutdown; pending logs may
837
1001
  be truncated.
838
1002
 
1003
+ Console launches also own a private `.xcodebug-launch-*` directory containing
1004
+ `launch.json` and an `owner.json` marker with this extension's format, host PID
1005
+ and creation time. The directory is mode `0700`; the marker is mode `0600`.
1006
+ Result cleanup follows reading; raw metadata never enters the console log stream.
1007
+ Ordinary `stop` leaves a pending result read available to exit diagnostics.
1008
+ Session shutdown separately cancels those reads, blocks new bridge starts, and
1009
+ allows up to three seconds per capture for pending startup, result cleanup and
1010
+ log drainage, including older reattach results and captures evicted from visible
1011
+ history. Blocked filesystem work or failed deletion is reported as incomplete
1012
+ cleanup, including failures from captures already evicted from history.
1013
+ Once cleanup settles, the session retains only the warning text for shutdown,
1014
+ not the finished capture or its log buffer.
1015
+ Residual result files may remain; task settlement alone is not proof of deletion.
1016
+
839
1017
  The bundle id separates apps, and the timestamp includes milliseconds to
840
- separate runs. Segment limits apply per capture: old runs are not automatically
841
- deleted from disk when their capture IDs leave the in-memory history.
1018
+ separate runs. Segment limits apply per capture. What xcodebug itself says while
1019
+ a bridge is down - why the capture ended, each reattach - is appended to the same
1020
+ file, so a log that stops also says why. A crash report copied from the device
1021
+ lands beside the logs as `crash-<unique-id>-<name>.ips`. When the app PID is
1022
+ known, a report without that PID is not retained.
1023
+
1024
+ Logs are kept for 30 days after their last write. The first `build`, `launch` or
1025
+ `syslog` of a session deletes older `build-`, `console-`, `syslog-` and
1026
+ `pod-install-` logs and `crash-*.ips` reports from this directory. The same
1027
+ retention window applies to residual launch-result directories, but only when
1028
+ the ownership marker is valid, the host PID is definitely absent, and the
1029
+ directory and all known files are old. Active or uncertain owners, unmarked
1030
+ legacy directories, malformed markers, symlinks and extra entries are retained.
1031
+ Pruning removes only validated `owner.json` / `launch.json` files and an empty
1032
+ directory, never recursively deleting a directory based on its prefix.
842
1033
 
843
1034
  A successful build clears `<agentDir>/logs/xcodebug/archive/` first, so snapshots
844
1035
  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
 
@@ -61,6 +62,105 @@ export async function clearArchives(workDir: string): Promise<{ removed: number;
61
62
  return { removed, freedBytes };
62
63
  }
63
64
 
65
+ /** The files this extension writes: build, capture and pod install logs, and pulled crash reports. */
66
+ const OWN_LOG = /^(?:build|console|syslog|pod-install|crash)-.+\.(?:log(?:\.\d+)?|ips)$/;
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
+
134
+ /**
135
+ * Delete this extension's logs that nothing has written to for `maxAgeMs`.
136
+ *
137
+ * Nothing else ever removes them, and they add up to hundreds of megabytes in
138
+ * a few weeks. Age since the last write is the whole test: a capture still
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.
142
+ */
143
+ export async function pruneLogs(logDir: string, maxAgeMs: number): Promise<void> {
144
+ let entries: string[];
145
+ try {
146
+ entries = await readdir(logDir);
147
+ } catch {
148
+ return;
149
+ }
150
+ const cutoff = Date.now() - maxAgeMs;
151
+ for (const name of entries) {
152
+ const launchResult = name.startsWith(".xcodebug-launch-") && name.length > ".xcodebug-launch-".length;
153
+ if (!OWN_LOG.test(name) && !launchResult) continue;
154
+ const path = join(logDir, name);
155
+ try {
156
+ if (launchResult) await pruneLaunchResult(path, cutoff);
157
+ else if ((await stat(path)).mtimeMs < cutoff) await rm(path, { force: true });
158
+ } catch {
159
+ // A log or owned result that cannot be removed is not worth failing a run over.
160
+ }
161
+ }
162
+ }
163
+
64
164
  /** Recursive size of a file or directory, in bytes. */
65
165
  async function sizeOf(path: string): Promise<number> {
66
166
  const info = await stat(path);