mobile-debug-mcp 0.35.0 → 0.36.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (112) hide show
  1. package/.cursor-plugin/marketplace.json +1 -1
  2. package/.github/workflows/ci.yml +1 -1
  3. package/README.md +86 -24
  4. package/agent-plugin/.antigravity-plugin/README.md +48 -0
  5. package/agent-plugin/.antigravity-plugin/plugin.json +18 -0
  6. package/agent-plugin/.claude-plugin/plugin.json +2 -2
  7. package/agent-plugin/.codex-plugin/plugin.json +1 -1
  8. package/agent-plugin/.cursor-plugin/plugin.json +2 -2
  9. package/agent-plugin/.mcp.json +1 -1
  10. package/agent-plugin/README.md +37 -8
  11. package/agent-plugin/cursor/.cursor-plugin/plugin.json +23 -0
  12. package/agent-plugin/cursor/LICENSE +201 -0
  13. package/agent-plugin/cursor/README.md +9 -0
  14. package/agent-plugin/cursor/skills/mobile-debug-mcp/SKILL.md +253 -0
  15. package/agent-plugin/mcp.json +1 -1
  16. package/agent-plugin/mcp_config.json +13 -0
  17. package/agent-plugin/plugin.json +1 -1
  18. package/agent-plugin/skills/mobile-debug-mcp/SKILL.md +36 -16
  19. package/dist/debugger/guard.js +4 -4
  20. package/dist/debugger/ios-worker.js +62 -0
  21. package/dist/debugger/ios.js +57 -0
  22. package/dist/debugger/sessions.js +33 -16
  23. package/dist/debugger/worker.js +6 -4
  24. package/dist/interact/index.js +12 -2
  25. package/dist/manage/ios.js +2 -0
  26. package/dist/observe/ios-trace/artifact.js +63 -0
  27. package/dist/observe/ios-trace/capabilities.js +86 -0
  28. package/dist/observe/ios-trace/native.js +93 -0
  29. package/dist/observe/ios-trace/notification.js +35 -0
  30. package/dist/observe/ios-trace/process.js +98 -0
  31. package/dist/observe/ios-trace/sessions.js +244 -0
  32. package/dist/observe/readiness-service.js +1 -1
  33. package/dist/observe/readiness.js +4 -4
  34. package/dist/observe/system-trace-error.js +7 -0
  35. package/dist/observe/system-trace-router.js +81 -0
  36. package/dist/observe/system-trace.js +4 -8
  37. package/dist/server/handlers/debugger-handlers.js +27 -8
  38. package/dist/server/handlers/diagnostic.js +12 -4
  39. package/dist/server/handlers/tool-handlers.js +19 -9
  40. package/dist/server/schemas/debugger-schema.js +10 -7
  41. package/dist/server/schemas/system-trace-schema.js +14 -9
  42. package/dist/server-core.js +1 -1
  43. package/dist/server.js +4 -4
  44. package/dist/utils/ios/utils.js +3 -0
  45. package/docs/CHANGELOG.md +23 -1
  46. package/docs/agent-plugin-installation-verification.md +39 -0
  47. package/docs/code-structure.md +3 -1
  48. package/docs/specs/031-ios-system-traces/intent.md +38 -0
  49. package/docs/specs/031-ios-system-traces/investigation.md +92 -0
  50. package/docs/specs/031-ios-system-traces/late-run-failure-evidence.json +32 -0
  51. package/docs/specs/031-ios-system-traces/plan.md +138 -0
  52. package/docs/specs/031-ios-system-traces/pr102-monitor-evidence.json +22 -0
  53. package/docs/specs/031-ios-system-traces/simulator-evidence.json +47 -0
  54. package/docs/specs/031-ios-system-traces/spec.md +135 -0
  55. package/docs/specs/032-ios-runtime-debugger/evidence.json +176 -0
  56. package/docs/specs/032-ios-runtime-debugger/intent.md +38 -0
  57. package/docs/specs/032-ios-runtime-debugger/plan.md +95 -0
  58. package/docs/specs/032-ios-runtime-debugger/report.md +205 -0
  59. package/docs/specs/032-ios-runtime-debugger/spec.md +153 -0
  60. package/docs/tools/TOOLS.md +2 -2
  61. package/docs/tools/debugger.md +45 -5
  62. package/docs/tools/system-traces.md +81 -14
  63. package/package.json +2 -1
  64. package/scripts/agent-plugin.mjs +55 -5
  65. package/src/debugger/android.ts +1 -1
  66. package/src/debugger/guard.ts +5 -5
  67. package/src/debugger/ios-worker.ts +49 -0
  68. package/src/debugger/ios.ts +45 -0
  69. package/src/debugger/lldb/breakpoints.py +51 -0
  70. package/src/debugger/lldb/inspection.py +109 -0
  71. package/src/debugger/lldb/worker.py +203 -0
  72. package/src/debugger/sessions.ts +24 -12
  73. package/src/debugger/worker.ts +7 -4
  74. package/src/interact/index.ts +13 -2
  75. package/src/manage/ios.ts +2 -0
  76. package/src/observe/ios-trace/artifact.ts +55 -0
  77. package/src/observe/ios-trace/capabilities.ts +74 -0
  78. package/src/observe/ios-trace/native.ts +72 -0
  79. package/src/observe/ios-trace/notification.ts +30 -0
  80. package/src/observe/ios-trace/process.ts +82 -0
  81. package/src/observe/ios-trace/sessions.ts +204 -0
  82. package/src/observe/readiness-service.ts +1 -1
  83. package/src/observe/readiness.ts +4 -4
  84. package/src/observe/system-trace-error.ts +3 -0
  85. package/src/observe/system-trace-router.ts +61 -0
  86. package/src/observe/system-trace.ts +4 -4
  87. package/src/server/handlers/debugger-handlers.ts +28 -9
  88. package/src/server/handlers/diagnostic.ts +11 -4
  89. package/src/server/handlers/tool-handlers.ts +20 -9
  90. package/src/server/schemas/debugger-schema.ts +10 -7
  91. package/src/server/schemas/system-trace-schema.ts +15 -9
  92. package/src/server-core.ts +1 -1
  93. package/src/server.ts +3 -3
  94. package/src/utils/ios/utils.ts +3 -0
  95. package/test/device/automated/debugger/runtime.ios.test.ts +221 -0
  96. package/test/device/automated/observe/ios-system-trace.smoke.ts +119 -0
  97. package/test/fixtures/contracts/tool-definitions.json +192 -32
  98. package/test/fixtures/ios-debugger-app/Main.swift +95 -0
  99. package/test/fixtures/ios-debugger-app/README.md +27 -0
  100. package/test/fixtures/ios-debugger-app/build.ts +21 -0
  101. package/test/helpers/ios-trace-shutdown.ts +29 -0
  102. package/test/unit/debugger/handle-guards.test.ts +88 -0
  103. package/test/unit/debugger/ios-preparation.test.ts +57 -0
  104. package/test/unit/debugger/ios.test.ts +104 -0
  105. package/test/unit/debugger/lldb-worker.py +166 -0
  106. package/test/unit/debugger/lldb-worker.test.ts +10 -0
  107. package/test/unit/observe/ios-trace-native.test.ts +90 -0
  108. package/test/unit/observe/ios-trace-sessions.test.ts +131 -0
  109. package/test/unit/observe/readiness.test.ts +1 -1
  110. package/test/unit/observe/system-trace-router.test.ts +49 -0
  111. package/test/unit/quality/agent-plugin-export.test.ts +38 -0
  112. package/test/unit/server/system-trace.test.ts +12 -3
@@ -0,0 +1,88 @@
1
+ import assert from 'node:assert/strict'
2
+ import { debuggerSessions, iosDebuggerSessions } from '../../../src/debugger/sessions.js'
3
+ import { handleToolCall } from '../../../src/server-core.js'
4
+ import { ToolsObserve } from '../../../src/observe/index.js'
5
+ import { ToolsInteract } from '../../../src/interact/index.js'
6
+ import { markDispatchStarted } from '../../../src/utils/operation-budget.js'
7
+ import { _setDeviceListersForTests, _resetDeviceListersForTests } from '../../../src/utils/resolve-device.js'
8
+
9
+ const original = {
10
+ androidPaused: debuggerSessions.paused, androidActive: debuggerSessions.hasActiveSessions,
11
+ iosPaused: iosDebuggerSessions.paused, iosActive: iosDebuggerSessions.hasActiveSessions,
12
+ tree: ToolsObserve.getUITreeHandler, tap: ToolsInteract.tapHandler
13
+ }
14
+ let iosPaused = false, androidPaused = false, racePause = false, reads = 0, androidResolutions = 0
15
+ const inputs: { platform?: string; deviceId?: string }[] = []
16
+ const pause: any = { debug_session_id: 'ios-session', target: { app_id: 'test.app', pid: 1 }, state: 'paused', captured_at_ms: 1 }
17
+ const tree = (platform: string, id: string): any => ({ device: { platform, id }, resolution: { width: 100, height: 100 },
18
+ elements: [{ text: 'Target', resourceId: 'target', bounds: [0, 0, 40, 40], visible: true, enabled: true, clickable: true }] })
19
+ const payload = (response: any) => JSON.parse(response.content.find((item: any) => item.type === 'text').text)
20
+ const call = async (elementId: string, hints: Record<string, unknown> = {}) => payload(await handleToolCall('tap_element', {
21
+ elementId, verificationMode: 'none', responseMode: 'compact', ...hints
22
+ }))
23
+ _setDeviceListersForTests({
24
+ listAndroidDevices: async () => { androidResolutions++; return [{ id: 'android', platform: 'android' } as any] },
25
+ listIOSDevices: async () => ['ios-a', 'ios-b'].map(id => ({ id, platform: 'ios', booted: true } as any))
26
+ })
27
+ debuggerSessions.hasActiveSessions = () => true
28
+ iosDebuggerSessions.hasActiveSessions = () => true
29
+ debuggerSessions.paused = id => androidPaused && id === 'android' ? { ...pause, debug_session_id: 'android-session' } : null
30
+ iosDebuggerSessions.paused = id => iosPaused && id === 'ios-a' ? pause : null
31
+ ToolsInteract._resetResolvedUiElementsForTests()
32
+ try {
33
+ ToolsObserve.getUITreeHandler = async ({ platform, deviceId }) => {
34
+ reads++
35
+ if (racePause) iosPaused = true
36
+ return tree(platform!, deviceId!)
37
+ }
38
+ ToolsInteract.tapHandler = async ({ platform, deviceId, x, y }) => {
39
+ markDispatchStarted()
40
+ inputs.push({ platform, deviceId })
41
+ return { success: true, device: { platform, id: deviceId }, x, y } as any
42
+ }
43
+ const handle = async (platform: 'android' | 'ios', deviceId: string) => {
44
+ const result = await ToolsInteract.waitForUIHandler({ platform, deviceId, selector: { text: 'Target' }, condition: 'exists', timeout_ms: 1000 })
45
+ assert.equal(result.status, 'success')
46
+ return result.element.elementId
47
+ }
48
+ const ios = await handle('ios', 'ios-a')
49
+ const otherIOS = await handle('ios', 'ios-b')
50
+ const android = await handle('android', 'android')
51
+ reads = 0; androidResolutions = 0; iosPaused = true
52
+ for (const hints of [{}, { deviceId: 'ios-a' }, { platform: 'ios' }]) {
53
+ const blocked = await call(ios, hints)
54
+ assert.equal(blocked.failure_code, 'DEBUGGER_PAUSED')
55
+ assert.equal(blocked.debugger.debug_session_id, 'ios-session')
56
+ assert.equal(blocked.delivery_status, 'not_delivered'); assert.equal(blocked.dispatch_started, false)
57
+ }
58
+ assert.equal(reads, 0, 'A known pause must block before hierarchy reads')
59
+ assert.equal(inputs.length, 0); assert.equal(androidResolutions, 0, 'An iOS handle must not resolve an Android device')
60
+
61
+ iosPaused = false
62
+ assert.equal((await call(ios)).success, true)
63
+ assert.deepEqual(inputs.pop(), { platform: 'ios', deviceId: 'ios-a' })
64
+ racePause = true
65
+ const raced = await call(ios)
66
+ assert.equal(raced.failure_code, 'DEBUGGER_PAUSED')
67
+ assert.equal(raced.delivery_status, 'not_delivered'); assert.equal(inputs.length, 0, 'A pause during target refresh must block native dispatch')
68
+ racePause = false
69
+
70
+ assert.equal((await call(android)).success, true, 'An unrelated iOS pause must not block Android')
71
+ assert.deepEqual(inputs.pop(), { platform: 'android', deviceId: 'android' })
72
+ androidPaused = true
73
+ assert.equal((await call(android)).failure_code, 'DEBUGGER_PAUSED')
74
+ assert.equal((await call(otherIOS)).success, true, 'Other iOS devices must remain usable')
75
+ assert.deepEqual(inputs.pop(), { platform: 'ios', deviceId: 'ios-b' })
76
+ androidPaused = false; reads = 0
77
+ for (const hints of [{ platform: 'android', deviceId: 'android' }, { platform: 'ios', deviceId: 'ios-b' }]) {
78
+ assert.equal((await call(ios, hints)).failure_code, 'STALE_REFERENCE', 'Explicit mismatches retain handle validation')
79
+ }
80
+ assert.equal((await call('unknown', { platform: 'ios', deviceId: 'ios-b' })).failure_code, 'STALE_REFERENCE')
81
+ assert.equal(reads, 0); assert.equal(inputs.length, 0)
82
+ console.log('PASS stored-handle debugger guards: omitted target, no observation/input while paused, racing pause, platform/device isolation and mismatches')
83
+ } finally {
84
+ debuggerSessions.paused = original.androidPaused; debuggerSessions.hasActiveSessions = original.androidActive
85
+ iosDebuggerSessions.paused = original.iosPaused; iosDebuggerSessions.hasActiveSessions = original.iosActive
86
+ ToolsObserve.getUITreeHandler = original.tree; ToolsInteract.tapHandler = original.tap
87
+ ToolsInteract._resetResolvedUiElementsForTests(); _resetDeviceListersForTests()
88
+ }
@@ -0,0 +1,57 @@
1
+ import { execFile } from 'node:child_process'
2
+ import { promisify } from 'node:util'
3
+ import { mkdtemp, writeFile, rm } from 'node:fs/promises'
4
+ import os from 'node:os'
5
+ import path from 'node:path'
6
+ const exec = promisify(execFile)
7
+ const directory = await mkdtemp(path.join(os.tmpdir(), 'debugger-fake-lldb-'))
8
+ const python = path.join(directory, 'python')
9
+ const xcrun = path.join(directory, 'xcrun')
10
+ const log = path.join(directory, 'calls')
11
+ const failed = path.join(directory, 'failed')
12
+ try {
13
+ await writeFile(xcrun, `#!${process.execPath}
14
+ const fs=require('node:fs');fs.appendFileSync(${JSON.stringify(log)},'xcrun\\n');
15
+ console.log(process.argv[2]==='lldb'?'/fake/lldb-python':${JSON.stringify(python)});
16
+ `, { mode: 0o700 })
17
+ await writeFile(python, `#!${process.execPath}
18
+ const fs=require('node:fs');
19
+ if(process.argv.includes('-c')) {
20
+ fs.appendFileSync(${JSON.stringify(log)},'probe\\n');
21
+ if(!fs.existsSync(${JSON.stringify(failed)})){fs.writeFileSync(${JSON.stringify(failed)},'');process.exit(1)}
22
+ console.log('ready');
23
+ } else {
24
+ fs.appendFileSync(${JSON.stringify(log)},'worker\\n');
25
+ require('node:readline').createInterface({input:process.stdin}).on('line',line=>{
26
+ const request=JSON.parse(line);console.log(JSON.stringify({id:request.id,result:{detached:true}}));
27
+ });
28
+ }
29
+ `, { mode: 0o700 })
30
+ const code = `
31
+ import assert from 'node:assert/strict';import {readFileSync} from 'node:fs';
32
+ // Load the TypeScript toolchain before emulating macOS so Linux selects its own esbuild.
33
+ const {prepareIOSWorker,createIOSWorker}=await import('./src/debugger/ios-worker.ts');
34
+ // Isolate platform emulation and native binaries from the unit runner process.
35
+ Object.defineProperty(process,'platform',{value:'darwin'});
36
+ const first=prepareIOSWorker();assert.strictEqual(first,prepareIOSWorker());
37
+ const failed=await Promise.allSettled([first,prepareIOSWorker()]);
38
+ assert.ok(failed.every(result=>result.status==='rejected'));
39
+ const retry=prepareIOSWorker();assert.notStrictEqual(first,retry);
40
+ assert.strictEqual(retry,prepareIOSWorker());
41
+ const configuration=await retry;
42
+ assert.equal(configuration.python,${JSON.stringify(python)});
43
+ assert.equal(configuration.env.PYTHONPATH,'/fake/lldb-python');
44
+ assert.equal(configuration.env.PYTHONNOUSERSITE,'1');
45
+ assert.strictEqual(await prepareIOSWorker(),configuration);
46
+ const worker=await createIOSWorker(()=>{});await worker.close();
47
+ const calls=readFileSync(${JSON.stringify(log)},'utf8').trim().split('\\n');
48
+ assert.equal(calls.filter(call=>call==='xcrun').length,4);
49
+ assert.equal(calls.filter(call=>call==='probe').length,2);
50
+ assert.equal(calls.filter(call=>call==='worker').length,1);
51
+ console.log('PASS shared iOS preparation, failed-probe retry, configuration and worker cache reuse');
52
+ `
53
+ const result = await exec(process.execPath, ['--import', 'tsx', '--input-type=module', '-e', code], {
54
+ env: { ...process.env, XCRUN_PATH: xcrun }, timeout: 15000
55
+ })
56
+ console.log(result.stdout.trim())
57
+ } finally { await rm(directory, { recursive: true, force: true }) }
@@ -0,0 +1,104 @@
1
+ import assert from 'node:assert/strict'
2
+ import { mkdtemp, writeFile, rm, realpath } from 'node:fs/promises'
3
+ import os from 'node:os'
4
+ import path from 'node:path'
5
+ import { IOSDebugNative } from '../../../src/debugger/ios.js'
6
+ import { DebuggerSessions, iosDebuggerSessions, debuggerSessions } from '../../../src/debugger/sessions.js'
7
+ import { iosCapabilities, iosLimitations } from '../../../src/debugger/ios-worker.js'
8
+ import { debuggerContracts, debuggerTools } from '../../../src/server/schemas/debugger-schema.js'
9
+ import { withDebuggerGuard, checkDebuggerGuard, pausedReadiness } from '../../../src/debugger/guard.js'
10
+ import { execCommandWithDiagnostics } from '../../../src/utils/ios/utils.js'
11
+ import { handleDebugger } from '../../../src/server/handlers/debugger-handlers.js'
12
+ import { DebuggerError, type WorkerEvent } from '../../../src/debugger/worker.js'
13
+ const directory = await mkdtemp(path.join(os.tmpdir(), 'ios-debugger-unit-'))
14
+ await writeFile(path.join(directory, 'App'), '')
15
+ const executable = await realpath(path.join(directory, 'App'))
16
+ const device = 'F9243BAF-62A8-4990-8A99-17F527F56FDA'
17
+ let processPath = executable, started = 'Mon Nov 4 12:00:00 2026', services = '123\t0\tUIKitApplication:dev.fixture.app[uuid]'
18
+ const calls: string[][] = []
19
+ const native = new IOSDebugNative(async (file, args) => {
20
+ calls.push([file, ...args])
21
+ if (args[0] === 'simctl' && args[1] === 'list') return JSON.stringify({ devices: { runtime: [{ udid: device, state: 'Booted' }] } })
22
+ if (args.includes('get_app_container')) return directory
23
+ if (file === '/usr/bin/plutil') return 'App'
24
+ if (args.includes('launchctl')) return services
25
+ if (args.includes('comm=')) return processPath
26
+ if (args.includes('lstart=')) return started
27
+ throw new Error('unexpected native command')
28
+ })
29
+ const base = { debugSessionId: 's', line: 1 }
30
+ for (const selector of [{}, { className: 'dev.App', sourceFile: '/tmp/App.swift' }, { sourceFile: 'App.swift' }]) {
31
+ assert.equal(debuggerContracts.set_debugger_breakpoint.schema.safeParse({ ...base, ...selector }).success, false)
32
+ }
33
+ for (const selector of [{ className: 'dev.App' }, { sourceFile: '/tmp/App.swift' }]) {
34
+ assert.equal(debuggerContracts.set_debugger_breakpoint.schema.safeParse({ ...base, ...selector }).success, true)
35
+ }
36
+ assert.ok(debuggerTools.find(t => t.name === 'attach_debugger')!.inputSchema.properties.platform)
37
+ let emit: (event: WorkerEvent) => void = () => {}
38
+ let closed = 0
39
+ const sessions = new DebuggerSessions(native, async onEvent => {
40
+ emit = onEvent
41
+ return { call: async (command, args) => {
42
+ if (command === 'step' && args?.threadId === 'foreign') throw new DebuggerError('DEBUGGER_STALE_REFERENCE')
43
+ if (command === 'attach') { assert.equal(args?.pid, 123); assert.equal(args?.executablePath, executable); emit({ event: 'stopped', stop_id: 'racing-stop', thread_id: 't' }) }
44
+ return { breakpoints: [] }
45
+ }, close: async () => { closed++ } }
46
+ }, async () => {}, { platform: 'ios', capabilities: iosCapabilities, limitations: iosLimitations })
47
+ const androidPause = debuggerSessions.paused, iosPause = iosDebuggerSessions.paused
48
+ try {
49
+ const candidates = await native.candidates(device, 'dev.fixture.app')
50
+ assert.equal(candidates[0].pid, 123); assert.equal(candidates[0].executable_path, executable)
51
+ assert.equal(candidates[0].uid, null)
52
+ await assert.rejects(native.candidates('booted', 'dev.fixture.app'), /INVALID_ARGUMENT/)
53
+ await assert.rejects(native.candidates('00000000-0000-0000-0000-000000000000', 'dev.fixture.app'), /DEBUGGER_UNSUPPORTED/)
54
+ processPath = '/tmp/foreign-process'
55
+ await assert.rejects(native.identity(device, candidates[0]), /PROCESS_CHANGED/)
56
+ processPath = executable; started = 'new process'
57
+ await assert.rejects(native.identity(device, candidates[0]), /PROCESS_CHANGED/)
58
+ started = candidates[0].start_identity
59
+ services = '999\t0\tUIKitApplication:dev.fixture.other[uuid]'
60
+ await assert.rejects(native.identity(device, candidates[0]), /PROCESS_CHANGED/)
61
+ services = '123\t0\tUIKitApplication:dev.fixture.app[uuid]'
62
+ const attached = await sessions.attach(device, 'dev.fixture.app')
63
+ assert.equal(attached.device.platform, 'ios'); assert.equal(attached.state, 'paused', 'racing attach stop is preserved')
64
+ assert.deepEqual(attached.cleanup.remaining_resources, ['lldb_worker'])
65
+ await assert.rejects(sessions.command(attached.debug_session_id, 'set', { className: 'Wrong', line: 1 }), /INVALID_ARGUMENT/)
66
+ emit({ event: 'stopped', stop_id: 'fresh', thread_id: 't' })
67
+ await assert.rejects(sessions.command(attached.debug_session_id, 'step', { stopId: 'fresh', threadId: 'foreign', kind: 'into' }), /DEBUGGER_STALE_REFERENCE/)
68
+ assert.equal(sessions.paused(device)?.stop?.stop_id, 'fresh', 'Rejected step preserves known suspension and guard')
69
+ await assert.rejects(sessions.command(attached.debug_session_id, 'locals', { stopId: 'racing-stop' }), /DEBUGGER_STALE_REFERENCE/)
70
+ iosDebuggerSessions.paused = id => id === 'same-id' ? { ...attached, debug_session_id: 'ios' } : null
71
+ debuggerSessions.paused = id => id === 'same-id' ? { ...attached, debug_session_id: 'android' } : null
72
+ assert.equal(pausedReadiness('same-id', 'ios')?.debug_session_id, 'ios')
73
+ assert.equal(pausedReadiness('same-id', 'android')?.debug_session_id, 'android')
74
+ await assert.rejects(withDebuggerGuard('ios', 'same-id', async () => checkDebuggerGuard(true)), /DEBUGGER_PAUSED/)
75
+ await withDebuggerGuard('ios', 'other', async () => checkDebuggerGuard())
76
+ await assert.rejects(withDebuggerGuard('ios', 'same-id', async () => execCommandWithDiagnostics(['simctl', 'launch', 'same-id', 'dev.fixture.app'])), /DEBUGGER_PAUSED/, 'Diagnostic fallback cannot resend a paused lifecycle command')
77
+ assert.equal((await sessions.command(attached.debug_session_id, 'detach')).cleanup.status, 'complete')
78
+ assert.equal(closed, 1)
79
+ assert.ok(!calls.some(call => call.includes('forward')), 'iOS must not allocate or remove ADB forwards')
80
+ const original = iosDebuggerSessions.capabilities
81
+ try {
82
+ iosDebuggerSessions.capabilities = async () => { throw new DebuggerError('DEBUGGER_UNSUPPORTED') }
83
+ const response = await handleDebugger('get_debugger_capabilities', { platform: 'ios', deviceId: device, appId: 'dev.fixture.app' })
84
+ const payload = JSON.parse(response.content[0].text)
85
+ assert.equal(payload.device.platform, 'ios'); assert.equal(payload.capabilities.coroutines, false)
86
+ assert.ok(!/JDK|Java worker|ADB/.test(payload.error.diagnostic.recovery))
87
+ } finally { iosDebuggerSessions.capabilities = original }
88
+ console.log('PASS iOS target membership, process identity, contracts, session routing, racing stops and platform guards')
89
+ } finally {
90
+ debuggerSessions.paused = androidPause; iosDebuggerSessions.paused = iosPause
91
+ await sessions.shutdown(); await rm(directory, { recursive: true, force: true })
92
+ }
93
+
94
+ // Confirmed detach and process-exit evidence are required for cleanup success.
95
+ const { IOSWorker } = await import('../../../src/debugger/ios-worker.js')
96
+ let transportClosed = 0
97
+ const disconnected = new IOSWorker({ call: async () => { throw new Error('transport lost') }, close: async () => { transportClosed++ } }, () => false)
98
+ await assert.rejects(disconnected.close(), /DEBUGGER_CLEANUP_FAILED/)
99
+ assert.equal(transportClosed, 1)
100
+ const exited = new IOSWorker({ call: async () => { throw new Error('must not need detach') }, close: async () => {} }, () => true)
101
+ await exited.close()
102
+ const confirmed = new IOSWorker({ call: async () => ({ detached: true }), close: async () => {} }, () => false)
103
+ await confirmed.close()
104
+ console.log('PASS iOS cleanup requires confirmed release; worker exit alone is insufficient')
@@ -0,0 +1,166 @@
1
+ """Platform-independent regression checks for the optional LLDB worker."""
2
+ import pathlib
3
+ import sys
4
+ import types
5
+
6
+ root = pathlib.Path(__file__).resolve().parents[3] / 'src/debugger/lldb'
7
+ sys.path.insert(0, str(root))
8
+ lldb = types.SimpleNamespace(eStateInvalid=0, eStateStopped=5, eStateExited=10, eStateDetached=9,
9
+ eStopReasonNone=1, eStopReasonInvalid=0, eStopReasonBreakpoint=3)
10
+ sys.modules['lldb'] = lldb
11
+ import worker
12
+ from inspection import Inspection
13
+ from breakpoints import Breakpoints
14
+
15
+ # Independent pause, idle and absolute expiry cannot be extended by heartbeats.
16
+ w = object.__new__(worker.Worker)
17
+ clock = [100.0]
18
+ worker.time.monotonic = lambda: clock[0]
19
+ w.created, w.activity, w.paused_at = 0, 100, 40
20
+ assert w.expired() == 'pause_limit'
21
+ w.paused_at = None
22
+ clock[0] = 400
23
+ assert w.expired() == 'idle_limit'
24
+ w.activity = 1800
25
+ clock[0] = 1800
26
+ assert w.expired() == 'session_limit'
27
+
28
+ # An internal transition with an empty thread list must not create a pause epoch.
29
+ i = Inspection()
30
+ p = types.SimpleNamespace(GetNumThreads=lambda: 0, GetState=lambda: 5, GetSelectedThread=lambda: types.SimpleNamespace(IsValid=lambda: False))
31
+ assert i.stopped(p) is None
32
+ assert i.stop_id is None
33
+ for method, args in [(i.thread, {'stopId': 'old', 'threadId': 'old'}),
34
+ (i.locals, {'stopId': 'old', 'frameId': 'old'})]:
35
+ try:
36
+ method(args)
37
+ raise AssertionError('Stale reference accepted')
38
+ except ValueError as error:
39
+ assert str(error) == 'DEBUGGER_STALE_REFERENCE'
40
+
41
+ # Exact source-line resolver must never request nearest-code relocation.
42
+ class Entry:
43
+ def IsValid(self): return True
44
+ def GetFileSpec(self): return '/tmp/App.swift'
45
+ def GetLine(self): return 13
46
+ class Location:
47
+ def GetAddress(self): return types.SimpleNamespace(GetLineEntry=lambda: Entry())
48
+ def SetEnabled(self, enabled): self.enabled = enabled
49
+ class Breakpoint:
50
+ def __init__(self): self.location = Location()
51
+ def __iter__(self): return iter([self.location])
52
+ def GetID(self): return 1
53
+ class Target:
54
+ def __init__(self): self.deleted = False; self.bp = Breakpoint()
55
+ def BreakpointCreateByLocation(self, *args):
56
+ assert args[-1] is False
57
+ return self.bp
58
+ def BreakpointDelete(self, identity): self.deleted = True
59
+ def FindCompileUnits(self, source): return types.SimpleNamespace(GetSize=lambda: 1)
60
+ lldb.SBFileSpec = lambda source: source
61
+ lldb.SBFileSpecList = list
62
+ t = Target()
63
+ b = Breakpoints(t)
64
+ r = b.set({'sourceFile': '/tmp/App.swift', 'line': 12})
65
+ assert r['status'] == 'rejected'
66
+ assert t.bp.location.enabled is False and t.deleted
67
+
68
+ # Polling must consume events before reading the process snapshot.
69
+ trace = []
70
+ class Listener:
71
+ def GetNextEvent(self, event): trace.append('consume'); return False
72
+ class Process:
73
+ def GetState(self): trace.append('state'); return 6
74
+ w.debugger = types.SimpleNamespace(GetListener=lambda: Listener())
75
+ w.process, w.terminal = Process(), False
76
+ lldb.SBEvent = object
77
+ w.poll()
78
+ assert trace == ['consume', 'state']
79
+
80
+ # EOF cleanup must release an actual target, never call Kill or expression APIs.
81
+ w.attached = True
82
+ w.inspection = Inspection()
83
+ w.breakpoints = types.SimpleNamespace(clear=lambda: None)
84
+ w.process = types.SimpleNamespace(IsValid=lambda: True, GetState=lambda: 5,
85
+ Detach=lambda: types.SimpleNamespace(Success=lambda: True))
86
+ assert w.detach() == {'detached': True}
87
+ assert w.terminal
88
+ print('PASS LLDB worker expiry, transient stops, stale references, exact lines, events and detach')
89
+
90
+ # Static Swift bool decoding must preserve boolean meaning without formatters.
91
+ lldb.eNoDynamicValues, lldb.eTypeIsScalar, lldb.eTypeIsInteger, lldb.eTypeIsFloat = 0, 1, 2, 4
92
+ class BoolValue:
93
+ def GetNonSyntheticValue(self): return self
94
+ def GetName(self): return 'cancelled'
95
+ def GetTypeName(self): return 'Swift.Bool'
96
+ def GetError(self): return types.SimpleNamespace(Success=lambda: True)
97
+ def GetType(self): return types.SimpleNamespace(GetTypeFlags=lambda: 0)
98
+ def GetValue(self): return '1'
99
+ def GetChildMemberWithName(self, name):
100
+ assert name == '_value'
101
+ return types.SimpleNamespace(GetNonSyntheticValue=lambda: self)
102
+ def IsValid(self): return True
103
+ values = types.SimpleNamespace(GetSize=lambda: 1, GetValueAtIndex=lambda index: BoolValue())
104
+ i.stop_id = '00000000-0000-0000-0000-000000000001'
105
+ i.frames['frame'] = types.SimpleNamespace(GetVariables=lambda *args: values)
106
+ assert i.locals({'stopId': i.stop_id, 'frameId': 'frame'})['locals'][0]['value'] == 'true'
107
+
108
+ # Reference summaries are stable within a stop and never expose the pointer.
109
+ pointer = types.SimpleNamespace(GetValue=lambda: '0x1234')
110
+ first = i.object_identity(pointer, 'Controller')
111
+ assert first == i.object_identity(pointer, 'Controller') and '1234' not in first
112
+ i.stop_id = '00000000-0000-0000-0000-000000000002'
113
+ assert first != i.object_identity(pointer, 'Controller')
114
+
115
+ # Repeated stack pages reuse references and cannot grow beyond the stop cap.
116
+ import inspection
117
+ original_location = inspection.location
118
+ inspection.location = lambda frame: {'source_file': '/tmp/App.swift', 'line': 1}
119
+ try:
120
+ i.invalidate()
121
+ i.stop_id = '00000000-0000-0000-0000-000000000001'
122
+ i.threads['thread'] = types.SimpleNamespace(GetNumFrames=lambda: 1001, GetFrameAtIndex=lambda index: object())
123
+ args = {'stopId': i.stop_id, 'threadId': 'thread', 'limit': 100}
124
+ assert i.stack(args)['frames'][0]['frame_id'] == i.stack(args)['frames'][0]['frame_id']
125
+ for offset in range(0, 1000, 100): i.stack({**args, 'offset': offset})
126
+ assert len(i.frames) == 1000
127
+ i.threads['other'] = i.threads['thread']
128
+ result = i.stack({**args, 'threadId': 'other'})
129
+ assert result['frames'] == [] and result['truncated']
130
+ finally:
131
+ inspection.location = original_location
132
+ print('PASS static bool decoding, opaque identities and bounded stable frame references')
133
+
134
+ # Error-reporting StepInto requires LLDB's UINT32_MAX sentinel, not line zero.
135
+ lldb.LLDB_INVALID_LINE_NUMBER, lldb.eOnlyDuringStepping = 4294967295, 0
136
+ lldb.SBError = lambda: types.SimpleNamespace(Success=lambda: True)
137
+ class StepThread:
138
+ def StepInto(self, target, end_line, error, run_mode):
139
+ assert target is None and end_line == 4294967295
140
+ w.terminal = False
141
+ w.inspection = Inspection()
142
+ w.inspection.stop_id = 'stop'
143
+ w.inspection.threads['thread'] = StepThread()
144
+ w.process = types.SimpleNamespace(GetState=lambda: 5)
145
+ assert w.command({'command': 'step', 'stopId': 'stop', 'threadId': 'thread', 'kind': 'into'}) == {'resumed': True}
146
+ assert w.inspection.stop_id is None
147
+ print('PASS LLDB step error overload uses the documented invalid-line sentinel')
148
+
149
+ # Signals and exceptions must not be misrepresented as completed source steps.
150
+ lldb.eStopReasonPlanComplete, lldb.eStopReasonSignal, lldb.eStopReasonException = 8, 5, 6
151
+ lldb.eStopReasonWatchpoint, lldb.eStopReasonExec = 4, 7
152
+ assert inspection.stop_reason(types.SimpleNamespace(GetStopReason=lambda: 5)) == 'signal'
153
+ assert inspection.stop_reason(types.SimpleNamespace(GetStopReason=lambda: 6)) == 'exception'
154
+ assert inspection.stop_reason(types.SimpleNamespace(GetStopReason=lambda: 8)) == 'step'
155
+ assert inspection.stop_reason(types.SimpleNamespace(GetStopReason=lambda: 99)) == 'unknown'
156
+ print('PASS LLDB stop reasons preserve signal/exception versus step evidence')
157
+
158
+ # Losing a previously owned process handle cannot prove detach or resume.
159
+ w.attached = True
160
+ w.process = types.SimpleNamespace(IsValid=lambda: False)
161
+ try:
162
+ w.detach()
163
+ raise AssertionError('Lost process handle incorrectly confirmed detach')
164
+ except ValueError as error:
165
+ assert str(error) == 'DEBUGGER_WORKER_FAILED'
166
+ print('PASS lost process handles preserve cleanup uncertainty')
@@ -0,0 +1,10 @@
1
+ import assert from 'node:assert/strict'
2
+ import { spawnSync } from 'node:child_process'
3
+ import { fileURLToPath } from 'node:url'
4
+ const result = spawnSync('python3', ['-B', fileURLToPath(new URL('./lldb-worker.py', import.meta.url))], { encoding: 'utf8', timeout: 15000 })
5
+ if ((result.error as NodeJS.ErrnoException | undefined)?.code === 'ENOENT') {
6
+ console.log('UNRUN optional LLDB Python worker checks: python3 is unavailable')
7
+ } else {
8
+ assert.equal(result.status, 0, result.stderr || result.error?.message)
9
+ console.log(result.stdout.trim())
10
+ }
@@ -0,0 +1,90 @@
1
+ import assert from 'node:assert/strict'
2
+ import { promises as fs } from 'node:fs'
3
+ import os from 'node:os'
4
+ import path from 'node:path'
5
+ import { iosCapabilities, resolveIosApp } from '../../../src/observe/ios-trace/capabilities.js'
6
+ import { validateArtifact, validateToc, traceSize, IOS_TRACE_MAX_BYTES } from '../../../src/observe/ios-trace/artifact.js'
7
+ import { IosTraceNative } from '../../../src/observe/ios-trace/native.js'
8
+ import { spawnTrace, stopTraceChild, classifyTraceFailure, type TraceSpawn, type TraceCommandResult } from '../../../src/observe/ios-trace/process.js'
9
+ const app={app_id:'fixture',pid:123,executable:'/Fixture.app/Fixture',started_at:'Wed Nov 4 10:00:00 2026'}
10
+ const toc=(id='sim',pid=123,template='Time Profiler')=>`<trace-toc><run><info><target><device uuid="${id}"/><process pid="${pid}"/></target><summary><template-name>${template}</template-name></summary></info><processes><process pid="${pid}" path="/Fixture.app/Fixture"/></processes><data><table schema="time-sample"/></data></run></trace-toc>`
11
+ function fake(){
12
+ const calls:{command:string;args:string[];signals:NodeJS.Signals[]}[]=[],lines:string[]=[]
13
+ let mismatch=false,failExport=false,failReady=false
14
+ const spawn:TraceSpawn=(command,args)=>{
15
+ const call={command,args,signals:[] as NodeJS.Signals[]};calls.push(call)
16
+ const recording=args.includes('record'),listener=command.endsWith('/notification'),pending=recording||listener
17
+ let alive=pending,resolve!:(r:TraceCommandResult)=>void
18
+ const done=new Promise<TraceCommandResult>(r=>{resolve=r})
19
+ const execute=async()=>{
20
+ let output=''
21
+ if(args.includes('get_app_container'))output='/Fixture.app'
22
+ else if(args.includes('launchctl'))output='123 0 UIKitApplication:fixture[abc]'
23
+ else if(command==='/bin/ps')output=args.includes('lstart=')?app.started_at:mismatch?'/Other.app/Other':app.executable
24
+ else if(args.includes('clang'))await fs.writeFile(args[args.indexOf('-o')+1],'binary')
25
+ else if(args.includes('xcodebuild'))output='Xcode 27.2'
26
+ else if(args.includes('templates'))output='== Standard Templates ==\nTime Profiler\nSystem Trace\nAnimation Hitches'
27
+ else if(args.includes('xctrace')&&args.includes('devices'))output='fixture (sim)'
28
+ else if(args.includes('devices'))output=JSON.stringify({devices:{'iOS-26-4':[{udid:'sim',state:'Booted',name:'fixture',isAvailable:true}]}})
29
+ else if(args.includes('export')){
30
+ if(failExport){resolve({code:2,output:'private stderr',timedOut:false});return}
31
+ const file=args[args.indexOf('--output')+1]
32
+ await fs.writeFile(file,args.includes('--toc')?toc():'<trace-query-result><node><schema name="time-sample"/><row><sample-time>1</sample-time></row></node></trace-query-result>')
33
+ }
34
+ if(!pending)resolve({code:0,output,timedOut:false})
35
+ }
36
+ void execute()
37
+ return {done,alive:()=>alive,signal:s=>{call.signals.push(s);alive=false;resolve({code:0,output:'Stopped',timedOut:false})},line:async(line)=>{lines.push(line);if(failReady&&line==='READY')throw new Error('READINESS_TIMEOUT')}}
38
+ }
39
+ return {spawn,calls,lines,flags:(v:{mismatch?:boolean;export?:boolean;ready?:boolean})=>{mismatch=v.mismatch??false;failExport=v.export??false;failReady=v.ready??false}}
40
+ }
41
+ async function run(){
42
+ const f=fake(),directory=await fs.mkdtemp(path.join(os.tmpdir(),'ios-trace-unit-'))
43
+ try{
44
+ assert.deepEqual(await resolveIosApp('sim','fixture',f.spawn),app)
45
+ f.flags({mismatch:true});await assert.rejects(()=>resolveIosApp('sim','fixture',f.spawn),/APP_IDENTITY_UNAVAILABLE/);f.flags({})
46
+ const cap=await iosCapabilities('sim','fixture','Time Profiler',f.spawn,'darwin')
47
+ assert.equal(cap.supported,true);assert.equal(cap.prerequisites.permissions,'unknown');assert.equal(cap.templates.filter(t=>t.supported).length,1)
48
+ assert.equal((await iosCapabilities('sim',undefined,'System Trace',f.spawn,'darwin')).supported,false)
49
+ assert.equal((await iosCapabilities('physical',undefined,'Time Profiler',f.spawn,'darwin')).supported,false)
50
+ assert.equal((await iosCapabilities('sim',undefined,'Time Profiler',f.spawn,'linux')).reasons[0],'MACOS_REQUIRED')
51
+ assert.ok(!f.calls.some(c=>c.args.includes('record')),'Discovery must not record')
52
+ validateToc(toc(),'sim',app)
53
+ assert.throws(()=>validateToc(toc(),'sim',{...app,executable:'/Other.app/Other'}),/ARTIFACT_APP_MISMATCH/)
54
+ assert.equal(classifyTraceFailure({code:1,output:'secret path: permission denied',timedOut:false}),'PROFILING_PERMISSION_REQUIRED')
55
+ assert.equal(classifyTraceFailure({code:1,output:'Cannot find process for provided pid: 123',timedOut:false}),'APP_NOT_RUNNING')
56
+ for(const xml of [toc('other'),toc('sim',456),toc('sim',123,'System Trace'),'<invalid>'])assert.throws(()=>validateToc(xml,'sim',app))
57
+ const file=path.join(directory,'capture.trace');await fs.mkdir(file);await fs.writeFile(path.join(file,'data'),'samples')
58
+ const artifact=await validateArtifact(file,'sim',app,f.spawn)
59
+ assert.equal(artifact.validation.sample_rows,1);assert.equal(artifact.kind,'directory');assert.equal((await fs.stat(path.join(file,'data'))).mode&0o777,0o600)
60
+ await assert.rejects(()=>fs.stat(path.join(directory,'samples.xml')),{code:'ENOENT'})
61
+ f.flags({export:true});await assert.rejects(()=>validateArtifact(file,'sim',app,f.spawn));f.flags({})
62
+ const outside=path.join(directory,'link');await fs.symlink(file,outside);await assert.rejects(()=>traceSize(outside),/UNSAFE_ARTIFACT/)
63
+ const huge=path.join(directory,'huge');await fs.writeFile(huge,'');await fs.truncate(huge,IOS_TRACE_MAX_BYTES+1)
64
+ assert.ok(await traceSize(huge)>IOS_TRACE_MAX_BYTES)
65
+ const native=new IosTraceNative(f.spawn)
66
+ const recording=await native.start('sim',app,directory,30000,()=>{})
67
+ assert.deepEqual(f.lines,['ARMED','READY'])
68
+ const recorder=f.calls.find(c=>c.args.includes('record'))!,listener=f.calls.find(c=>c.command.endsWith('/notification'))!
69
+ assert.equal(recorder.args[recorder.args.indexOf('--device')+1],'sim')
70
+ assert.equal(recorder.args[recorder.args.indexOf('--attach')+1],'123')
71
+ assert.equal(recorder.args[recorder.args.indexOf('--notify-tracing-started')+1],listener.args[0])
72
+ assert.ok(!recorder.args.includes('--no-prompt'));await native.stop(recording);assert.deepEqual(recorder.signals,['SIGINT'])
73
+ const failed=fake();failed.flags({ready:true});const other=new IosTraceNative(failed.spawn)
74
+ await assert.rejects(()=>other.start('sim',app,directory,30000,()=>{}),/READINESS_TIMEOUT/)
75
+ assert.ok(failed.calls.find(c=>c.args.includes('record'))?.signals.includes('SIGINT'))
76
+ native.shutdown();other.shutdown()
77
+ const child=spawnTrace(process.execPath,['-e','process.stdout.write("READY\\n");setInterval(()=>{},1000)'],2000)
78
+ await child.line('READY',1000);await stopTraceChild(child,1000);assert.equal(child.alive(),false)
79
+ const signals:NodeJS.Signals[]=[]
80
+ const stuck={done:new Promise<TraceCommandResult>(()=>{}),alive:()=>true,line:async()=>{},signal:(s:NodeJS.Signals)=>{signals.push(s)}}
81
+ await assert.rejects(()=>stopTraceChild(stuck,1),/ACTION_TIMEOUT/)
82
+ assert.deepEqual(signals,['SIGINT','SIGKILL'])
83
+ const noisy=await spawnTrace(process.execPath,['-e','process.stdout.write("x".repeat(100000))'],2000).done
84
+ assert.equal(noisy.output.length,65536)
85
+ const timeout=await spawnTrace(process.execPath,['-e','setInterval(()=>{},1000)'],30).done
86
+ assert.equal(timeout.timedOut,true)
87
+ console.log('PASS iOS native discovery, notification, ownership, artifact schemas and bounded children')
88
+ }finally{await fs.rm(directory,{recursive:true,force:true})}
89
+ }
90
+ run().catch(error=>{console.error(error);process.exitCode=1})