Plugin check: Run node "${PLUGIN_ROOT}/scripts/check-version.js" - if it outputs a message, show it to the user before proceeding.
📋 Shared instructions: shared-instructions.md — read first.
Startup diagnosis uses the targeted compatibility inspection below instead of
the shared blanket version check; missing dependencies must not prevent diagnosis.
It does not check for updates. Explicit startup repair/restart approval overrides
shared auto-proceed/default-answer guidance.
Debug App — Monitor & Fix
Monitor the running app through the project-local .powernative/metro-logs/ files written by metro.config.js, detect runtime and bundle errors, and fix them autonomously by editing the affected files (or routing to the right skill when the fix belongs in a domain like Dataverse schema or auth registration). For silent failures, inject temporary console.log statements at data-path boundaries, read only newly appended log bytes, then clean the traces after the root cause is fixed. Modeled on the upstream app-debugger.agent.md pattern — foreground loop, bounded polling, configurable clean-check/timeout exits, and optional watch-only operation.
When setup/startup or device opening is failing, first execute
startup-diagnostics.md. This bounded phase
can run without Metro logs or a loaded app and returns to the runtime path only
when its prerequisites actually hold. Running npm run dev alone does not
activate an agent, and this skill installs no background watcher.
Dev-client limitation: the standalone dev client sends app/runtime logs, React errors, host diagnostics, and Metro bundler output through Metro. The template's metro.config.js writes Metro terminal output and HTTP bundle failures into .powernative/metro-logs/; there is no separate device log source. Host diagnostics include strings such as [AuthProvider] MSAL init failed:, [bridge] fetch THREW for, [bridge] HTTP <status> for, [addAadAppToConnectionAcl] failed HTTP <status> for connection, [useConnectionRefs] could not verify connection ACLs; treating existing connections as setup-required, and [PAHost][ErrorBoundary] Unhandled JS error:.
Subcommands (parsed from $ARGUMENTS)
| Form |
Behavior |
/debug-app (no args) |
Default — project-log-driven mode. Run Phase 0, discover valid project-local Metro sessions, select automatically when one is live or ask when several are live, then monitor the selected log. No host terminal ID is required. |
/debug-app "<symptom text>" |
Symptom-driven mode (recommended when there's a user-visible problem). Free-text symptom such as "todos not appearing on home screen", "login button does nothing", "list empty after refresh". Run Phase 0 → Phase 0.5 (parse symptom → ask the user to reproduce/navigate → walk the likely data path from terminal traces) → enter monitor loop. Catches silent failures (empty lists, blank screens, swallowed errors) that pure log polling misses. |
/debug-app startup ["<symptom text>"] [--tunnel] [--tunnel-tenant <tenant-guid>] |
Startup-only diagnosis. Inspect install/startup/QR failures, offer bounded approved repair, and verify the original symptom. Preserve explicitly selected authenticated tunnel options for an approved retry. Return without the runtime monitor; also used by creation-time failure handoffs. |
/debug-app status |
Discover all project-local Metro logs and print each valid session's project, platform, PID, port, start time, and log path. Mark the session referenced by the saved cursor when present, then print fixes and unresolved errors. Do NOT ask for a selection or enter the loop. |
/debug-app stop |
Stop only the foreground debug loop and preserve .powernative/debug-app/ state. It does not stop Metro; the user owns the npm run dev process. |
/debug-app version |
Print the installed mobile-app plugin name and version from ${PLUGIN_ROOT}/.plugin/plugin.json, then exit. |
Monitoring options
Options may follow the default command, a symptom, or status:
| Option |
Meaning |
Default |
--working-dir <path> |
App root containing package.json. Startup diagnosis accepts missing Metro config or dependencies; runtime monitoring requires a configured, live Metro session. Relative paths resolve from the current shell directory. |
Current shell directory |
--port <1-65535> |
Monitor only the valid Metro session on this port. |
Any port |
--platform <ios|android> |
Consider only sessions whose recent log identifies this platform. |
Any platform |
--cycles <1-50> |
Exit after this many consecutive clean observation intervals. |
3 |
--timeout <duration> |
Maximum wall-clock monitoring time. Accept 30s–60m using s, m, or h. |
5m |
--no-fix |
Inspect/watch-only: never edit project source/config, inject traces, install, regenerate, start/stop/restart Metro, open the device app, or invoke a mutating handoff. Debug cursor/audit/health state may still advance. |
Fix enabled |
--tunnel |
Startup only: preserve --tunnel when an approved retry invokes npm run dev. Never switch a LAN launch to a tunnel automatically. |
Disabled |
--tunnel-tenant <tenant-guid> |
Startup only: preserve the Entra tenant used to authenticate the dev tunnel. Requires --tunnel. |
Active Azure CLI tenant |
Examples:
/debug-app --port 8082 --platform ios
/debug-app "orders screen is empty" --cycles 10 --timeout 15m
/debug-app --no-fix --timeout 30m
/debug-app status --platform android
/debug-app status --working-dir ../my-mobile-app
/debug-app startup "npm run dev exits before the QR appears"
/debug-app startup "tunnel launch fails" --tunnel --tunnel-tenant 11111111-1111-1111-1111-111111111111
/debug-app "QR won't open the app" --no-fix
Argument parsing:
- Parse quoted text as one symptom value and parse recognized flags wherever they appear.
- The first reserved token (
startup, status, stop, help, --help, -h, version, --version) selects the subcommand. stop, help, and version do not accept monitoring options. status accepts only --working-dir, --port, and --platform; reject symptoms, --cycles, --timeout, --no-fix, and tunnel options because it does not enter the loop. startup accepts one symptom and all options except --cycles, because it never enters the runtime monitor. Reject --tunnel and --tunnel-tenant on every other subcommand.
- After removing recognized options and their values, any remaining non-reserved text is the symptom and enables symptom mode.
- Reject unknown flags, duplicate flags, missing values, invalid numbers, unsupported platforms, or more than one free-text symptom. Print the valid forms and exit without monitoring.
- Normalize
platform to lowercase. Convert timeout to timeoutSeconds; require 30 <= timeoutSeconds <= 3600. Validate --tunnel-tenant as a GUID and require --tunnel; never derive either option from symptom text or untrusted diagnostic context. Resolve workingDir from explicit --working-dir, or inherit the caller's absolute root; use the current shell directory only for a direct invocation without either. Reject conflicting explicit/inherited roots and do not search parent directories. Require package.json at that root; missing metro.config.js, configuration, or installed dependencies routes to startup inspection, not runtime monitoring. An unreadable/malformed manifest is a blocked diagnostic, not permission to initialize a new app. Every shell call must explicitly enter the selected absolute workingDir; every relative project path and command below runs from that directory.
- Initialize:
workingDir=<absolute app root>
portFilter=<number|none>
platformFilter=<ios|android|none>
targetCleanCycles=<number, default 3>
timeoutSeconds=<number, default 300>
noFix=<true|false, default false>
devArgs=<[]|["--tunnel"]|["--tunnel","--tunnel-tenant","<tenant-guid>"]>
monitorStartedAt=<current ISO timestamp>
For help / --help / -h, print the subcommands and monitoring-options tables and exit.
Set startupStartedAt only when entering startup diagnostics. Its timeout and
attempt budget include caller-supplied prior attempts. After a verified live app
continues into monitoring, reset monitorStartedAt for that separate bounded loop.
Early-return subcommands:
stop: if received while this foreground loop owns the conversation, clean up any injected traces using Phase 0.5.5 and exit at the next safe boundary. For a standalone stop invocation, report that no loop is active. Never stop Metro or delete .powernative/debug-app/ state.
version / --version: read ${PLUGIN_ROOT}/.plugin/plugin.json, print <name> <version>, and exit without resolving a project or writing state. If the manifest is missing or malformed, report that the plugin version is unavailable and exit.
status: validate workingDir, then execute only Phase 0.0 discovery through the status branch below. Do not run project preflight, create state files, ask for a session, initialize a baseline, or enter the monitor loop.
If stop arrives during startup diagnosis, cancel upcoming diagnostic/repair
steps and report any in-flight approved command accurately. Do not automatically
kill an installation or Metro process, or claim a partly restored install is complete.
Tip — "play around then debug": Metro persists recent app output in .powernative/metro-logs/ even across chat/editor restarts. If something weird just happened, keep using the app normally, then run /debug-app or /debug-app "<what you saw>". The first cycle reads the latest persisted log window; subsequent cycles read only bytes appended after the saved cursor.
Core Principles
- Foreground autonomous loop — Once started, this skill owns the conversation until
targetCleanCycles consecutive clean polls confirm the app is healthy, timeoutSeconds elapses, the user types stop, or the escalation rule trips. Do not run other skills concurrently — they'll queue behind the loop.
- Watch-only means no project mutation — With
--no-fix, do not edit project source/configuration, inject diagnostic logs, install packages, regenerate schemas, switch accounts, or invoke a mutating skill. Continue to advance .powernative/debug-app/ cursor/audit/health state, classify errors, and provide the fix/handoff that would have been used.
- Runtime monitoring requires a live app; startup diagnosis does not. First
classify install/startup/opening failures through the bounded startup reference.
Do not enter the runtime monitor or claim healthy runtime without a verified
live native session.
- Native-only runtime target — The app must be loaded in a native dev client on a device or simulator;
.powernative/metro-logs/ is the authoritative log source for that native session.
- No web or direct Metro probes — Do not use React Native Web, browser automation,
curl, fetch, WebFetch, or any direct request to a Metro/localhost endpoint for runtime diagnosis. Read only the .powernative log and source files.
- No screen-by-screen verification — Do not crawl routes or validate every screen. In symptom mode, focus only on the user-reported workflow and the terminal/source evidence needed to diagnose it.
- One fix at a time — Fully resolve one issue (context → fix → type-check → reload → re-poll) before starting the next. No batching.
- Working-dir state — Debug audit state lives in
.powernative/debug-app/: fixes.md, unresolved.md, injected-logs.md, health.json, and metro-cursor.json. Metro logs live in the already-ignored .powernative/metro-logs/. Both survive chat/editor restarts without binding state to a specific agent host.
- Defense-in-depth redaction — The Metro logger removes credential-like lines before writing
.powernative, but /debug-app must independently minimize and sanitize every value before persisting it to .powernative/debug-app/. Never copy raw response bodies, record objects, tokens, headers, trace payloads, or absolute home-directory paths into debugger state.
- The port is the log identity — the dev-server port is the number the QR encodes, the device dials, and this skill verifies. Liveness is a socket probe (does the log's PID still hold that port?), never terminal scrollback. A
port-taken status means the log belongs to a dead session and must not be diagnosed.
- Never fix history — the log is a record of the past, so an error in it is not proof of a current problem. Errors found in the baseline window must pass the Phase 0.2.1 supersession check before any code is edited. Editing working code to chase an already-resolved error is a worse outcome than reporting nothing.
- First-party native packages are an immutable boundary — a frame under
node_modules/@microsoft/power-apps-native-* is evidence, not proof, of package ownership. First rule out broken installation, Node/native compatibility, invalid app inputs, unsupported configuration, and misuse of the package's documented API. Once the evidence confirms a defect inside an installed @microsoft/power-apps-native-* package, do not apply a customer-project workaround: do not edit node_modules/, create a patch-package patch or postinstall rewrite, vendor or fork package source, redirect the package through Metro/Babel/TypeScript aliases, or replace its dependency with a git, tarball, or local fork. Record a sanitized package-defect report and route the user to /report-issue. Host/MSAL source patches remain prohibited; approved same-lock installation restoration is not a source patch or upgrade.
- Host terminal APIs are optional only — Never ask for or persist a terminal
ID. During runtime monitoring, available host output is only a convenience and
diagnosis still advances the authoritative
.powernative cursor. Before a log
exists, the bounded startup phase may use the current failed command's sanitized
terminal output; it must not fabricate a cursor or treat that output as a live
runtime session.
- Context-first diagnosis — Read
memory-bank.md when present. Read power.config.json for environment, Dataverse, and connector context. Consult native-app-plan.md only when the failure concerns a planned screen, data model, connector, offline profile, or native capability; do not parse it for unrelated syntax/runtime errors.
- Reference resolution order — For Dataverse/Power Platform errors: read skills/add-dataverse/references/dataverse-reference.md first, inspect generated services/models and project context, then query
mcp__plugin_mobile-app_microsoft-learn__microsoft_docs_search when behavior remains uncertain. For Expo/Expo Router/React Native errors: inspect installed versions and project code first, then use targeted WebFetch against official https://docs.expo.dev/ documentation. Use package documentation next and general web search only as a last resort.
Workflow — Task List First
Before entering the monitor loop, write a task list and keep it up to date:
- [ ] Discover valid `.powernative` Metro sessions and select one when needed
- [ ] If startup/install/QR failure or no live session: inspect and classify; repair only with approval; verify original symptom or return pending/blocked
- [ ] Capture baseline log state from the selected session and save its byte cursor
- [ ] (Symptom mode only) Phase 0.5: parse symptom → ask user to navigate → inject console.logs → read new log bytes → walk data path → clean up logs
- [ ] Monitoring cycle 1: collect → classify → fix if needed
- [ ] Monitoring cycle 2: collect → classify → fix if needed
- [ ] Monitoring cycle 3: collect → classify → fix if needed
(add cycles as needed; after <targetCleanCycles> consecutive clean cycles, use the resolved/flagged/pending symptom outcome)
- [ ] Fix: <error summary> → <inline edit | skill route> (one task per error found)
Mark each cycle complete (clean OR fixed) before starting the next.
Phase 0 — Startup Check
Before entering the loop:
0.setup Startup/setup diagnostic dispatch
After the early-return subcommands, run
startup-diagnostics.md when:
- the subcommand is
startup;
- the supplied symptom concerns installation,
npm run dev, Node/package
compatibility, startup before loading, or QR/device opening; or
- Phase 0.0 finds no valid live session (not merely a mismatched port/platform
filter when another session is live), or Phase 0.2 finds no connected client.
For a healthy live app with a runtime symptom, skip setup and use the existing
runtime path. On startup or a creation handoff, return the structured startup
outcome without entering the monitor. Otherwise a verified live app re-enters
Phase 0.preflight, session discovery, and state initialization (0.1) before
Phase 0.2; pending/blocked/cancelled returns without a green runtime result.
Record startupOutcome in invocation context so this return does not re-enter
setup just because the original symptom mentioned startup. If only installation
or Metro startup is verified but no native app is connected, report runtime
verification pending and return instead of repeatedly dispatching setup.
No unbounded redispatch: repeated setup failures consume the same attempt budget.
0.preflight Read project context
Follow the shared instructions before diagnosing logs:
Use workingDir from argument parsing as <working_dir> throughout this workflow. It is already validated as an app root; do not derive it again from a later phase or silently switch projects.
- If
<working_dir>/memory-bank.md exists, read its Project facts, Power Platform context, Data model, Connectors, Screens, Native capabilities, and Build history. Do not create a memory bank from /debug-app; absence is valid.
- Read
<working_dir>/power.config.json when present. Capture environmentId, databaseReferences, and connectionReferences. power.config.json is the preferred environment source.
- Read
<working_dir>/native-app-plan.md only when the supplied symptom or a classified error concerns a planned screen, Dataverse entity/column, connector, offline behavior, navigation contract, or native capability. Treat the plan as intended design, not proof of live schema/runtime state.
- Inspect
src/generated/services/, src/generated/models/, and src/generated/connectorSchemas.ts only when the affected data path uses them. Never edit generated files.
Append a compact context line to fixes.md after Phase 0.1 creates it:
[<HH:MM:SS>] Context — memory-bank=<present|absent> native-plan=<present|absent|not-needed> environment=<environmentId|none> dataverse-tables=<N> connectors=<N>
Do not resolve the environment or call Dataverse during ordinary bundle, React, or local JavaScript failures. When a current symptom/error is Dataverse or Power Platform related, perform the read-only Dataverse diagnostic sequence in D2 before handing off.
0.0 Discover and select the project-local Metro session
Use the validated <working_dir> from argument parsing. Enumerate all matching logs, newest first:
LOG_DIR='<working_dir>/.powernative/metro-logs'
ls -t "$LOG_DIR"/metro-*-pid-*-port-*.log 2>/dev/null
For every candidate, parse:
pid and port from metro-<timestamp>-pid-<pid>-port-<port>.log;
startedAt from the filename timestamp;
project from power.config.json.appDisplayName, falling back to the basename of <working_dir>;
platform by scanning only the latest 64 KiB for the most recent iOS ... Bundled / iOS Bundling or Android ... Bundled / Android Bundling line; use unknown when neither appears.
Check every recorded PID with a cross-platform Node probe: process.kill(pid, 0) means alive; treat EPERM as alive and other errors as gone. When port is numeric, verify ownership with lsof -nP -iTCP:<port> -sTCP:LISTEN -t on macOS/Linux when available, or netstat.exe -ano -p tcp on Git Bash/Windows. On Linux without lsof, use ss -ltnp when available. A candidate is valid/live only when its PID is alive and either owns the recorded port, has port=unknown, or no supported port-ownership probe exists. A probe that runs and reports a different PID is a contradiction, not an unavailable probe. Do not persist terminal IDs or depend on terminal output.
Selection rules:
status branch — return before selection: After filtering and liveness checks, read .powernative/debug-app/metro-cursor.json only when it is nonempty valid JSON with string logPath, numeric pid, and numeric-or-unknown port. Treat a missing, empty, malformed, or shape-invalid cursor as absent and print a warning; never overwrite it from status. Print every valid session newest-first using the normal session display shape, marking [saved] only when logPath + pid + port match the valid cursor. Then print at most the last 20 nonempty lines from fixes.md and unresolved.md, passing the displayed text through the persistence redactor first. Print stale/contradictory candidate counts without diagnosing their log content, then exit. When no valid session exists, print that result plus the applicable no-log/stale reason and exit.
For monitoring modes only, select a session using the rules above. After selection, set LOG_PATH, pid, port, project, platform, and startedAt from the chosen candidate. This selection is sticky for the current monitor run.
When no log exists, inspect metro.config.js and resolve the logging module from <working_dir> before choosing a failure branch:
- Current factory form: the config uses
createPowerAppsMetroConfig from @microsoft/power-apps-native-host/config/metroConfig, and that exact subpath resolves from the project's installed dependencies. The factory installs project-local logging internally.
- Legacy direct form: the config directly imports
@microsoft/power-apps-native-host/metro-logger, and that exact subpath resolves from the project's installed dependencies.
- Unavailable: neither configured subpath resolves, the referenced form is absent, or
@microsoft/power-apps-native-host is missing from package.json. A dependency version string alone does not prove that the configured export exists.
Branch as follows:
| Status |
Meaning |
Action |
| Exactly one valid log exists, PID is alive, and either port is unknown or the port probe is unavailable |
Select it. Capture project, platform, startedAt, port, pid, and logPath, then continue. |
|
| Exactly one valid log exists and PID still owns the logged port |
Select it. Capture project, platform, startedAt, port, pid, and logPath, then continue. |
|
| Multiple valid logs exist |
Show every valid session and ask which one to monitor. Do not select by recency alone. |
|
| Log exists, PID is gone, and another process owns the logged port |
Do NOT diagnose from this log. Tell the user which PID holds the port and ask them to restart npm run dev. |
|
| Log exists but PID/port contradict each other |
The device may be talking to the wrong server. Ask the user to stop stale Metro processes and rerun npm run dev. |
|
| No log exists and the logging form is unavailable |
This project predates project-local Metro logging or has incomplete dependencies. Enter startup diagnostics to distinguish broken install, unsupported export, and config mismatch; do not edit native/Metro config or loop on restarts. |
|
| No log exists and the current factory or legacy direct logging form resolves |
If available host output contains [powernative] Metro logging instrumentation failed, preserve that bounded evidence. Enter startup diagnostics rather than assume a package defect or require the app to load first. |
|
The PID/port check prevents stale-log diagnosis: a log file can outlive its Metro process, so only the socket probe reveals that the log stopped belonging to the app under test. The explicit choice prevents a valid session on one port from being confused with another valid session in the same project.
If no .powernative log exists but the host exposes a live Metro terminal, use
its bounded output only as startup evidence. Do not ask for or store its terminal
ID or enter the continuous monitor against it. The startup phase owns any
approved retry; runtime monitoring still requires a valid project-local log.
Record the stable source in fixes.md:
[<HH:MM:SS>] Log source — <project> <platform> — <logPath> (pid <pid>, port <port>, started <startedAt>)
0.1 Ensure state directory
mkdir -p .powernative/debug-app
touch .powernative/debug-app/fixes.md
touch .powernative/debug-app/unresolved.md
touch .powernative/debug-app/injected-logs.md
touch .powernative/debug-app/health.json
touch .powernative/debug-app/metro-cursor.json
rm -f .powernative/debug-app/symptom-state # per-session — Phase 0.5 rewrites it if symptom mode is active
If fixes.md is empty, write a session header:
# Debug session — <date>
Append the effective invocation settings:
[<HH:MM:SS>] Monitor config — port=<any|port> platform=<any|ios|android> clean-cycles=<targetCleanCycles> timeout=<timeoutSeconds>s no-fix=<true|false>
0.1.1 Initialize health state
Write .powernative/debug-app/health.json without raw log content:
{
"bundle": { "status": "unknown", "summary": "No evidence yet" },
"runtime": { "status": "unknown", "summary": "No evidence yet" },
"authentication": { "status": "unknown", "summary": "No evidence yet" },
"dataverse": { "status": "unknown", "summary": "No evidence yet" },
"connector": { "status": "unknown", "summary": "No evidence yet" },
"offline": { "status": "unknown", "summary": "No evidence yet" },
"navigation": { "status": "unknown", "summary": "No evidence yet" },
"nativeCapability": { "status": "unknown", "summary": "No evidence yet" },
"updatedAt": "<ISO timestamp>"
}
Allowed statuses are healthy, degraded, failed, unknown, and not-configured. Update only the affected domain after each classified signal:
| Signal |
Health update |
| Successful native bundle after the latest bundle error |
bundle=healthy |
| Bundle/transform/import failure |
bundle=failed |
| Uncaught JS/React error |
runtime=failed; set healthy after the repaired workflow produces clean new output |
| Auth success/failure host diagnostics |
`authentication=healthy |
| Dataverse 2xx/error for the affected operation |
`dataverse=healthy |
| Connector resolution/call success or failure |
`connector=healthy |
| No offline profile |
offline=not-configured; offline activation/sync warning or failure → `degraded |
| Confirmed route/navigation error |
navigation=failed; repaired route confirmation → healthy |
| Native wrapper success, permission denial, missing module, or native failure |
`nativeCapability=healthy |
Absence of evidence remains unknown; never convert an unobserved domain to healthy.
0.1.2 Persistence redaction gate
Before appending diagnostic text to fixes.md or unresolved.md, or storing a health summary, sanitize it:
- Convert project paths to paths relative to
<working_dir>. Replace other absolute home-directory paths with [REDACTED_PATH].
- Replace complete authorization/cookie/secret headers (
Authorization, Proxy-Authorization, Cookie, Set-Cookie, x-api-key, api-key, client-secret, and token headers) with [REDACTED_HEADER].
- Replace Bearer values, JWT-like three-segment values, SAS/query secrets (
sig, se, sp, sv, code, token, access_token, refresh_token, id_token, client_secret), passwords, and API keys with [REDACTED_SECRET].
- Replace email addresses with
[REDACTED_EMAIL] and GUIDs/record identifiers with [REDACTED_ID] unless the identifier is a non-sensitive local PID/port.
- Never persist Dataverse/connector response bodies or arbitrary
[TRACE] object values. Persist only status, source/config table or column names, counts, error codes, and a bounded error message.
- Scan the sanitized result again. If any sensitive pattern remains, persist
[REDACTION_BLOCKED: diagnostic omitted] instead.
Run the bundled verifier for every candidate diagnostic before writing:
printf '%s' "$DIAGNOSTIC_SUMMARY" | node \
"${PLUGIN_ROOT}/scripts/redact-debug-diagnostic.js" \
--working-dir '<working_dir>'
Persist only the verifier's stdout. Build DIAGNOSTIC_SUMMARY from minimal fields first; do not pass a full Metro window or response body and rely on redaction to make it safe.
Store logPath in metro-cursor.json relative to <working_dir> and resolve it against <working_dir> when reading. This gate is required even though .powernative logs are already sanitized.
0.2 Verify Metro bundled and the app is running
Telemetry checkpoint: validate_metro_session
Read a bounded baseline window and return a real byte cursor:
node - "$LOG_PATH" 262144 <<'NODE'
const fs = require('node:fs');
const [file, maxText] = process.argv.slice(2);
const maxBytes = Number(maxText);
const size = fs.statSync(file).size;
const start = Math.max(0, size - maxBytes);
const fd = fs.openSync(file, 'r');
const buffer = Buffer.alloc(size - start);
const bytesRead = fs.readSync(fd, buffer, 0, buffer.length, start);
fs.closeSync(fd);
process.stdout.write(JSON.stringify({
cursor: start,
nextCursor: start + bytesRead,
truncated: start > 0,
output: buffer.subarray(0, bytesRead).toString('utf8')
}, null, 2));
NODE
The logger initially writes port-unknown and may atomically rename that file to the numeric port. If the baseline read gets ENOENT, rediscover once before reporting failure. When the same filename timestamp and PID now exist with a numeric port, update LOG_PATH and port to that file and retry the bounded read once; do not process both names as separate sessions.
Parse output, cursor, nextCursor, and truncated; use the pid, port, and logPath resolved in Phase 0.0. Scan output:
- Most recent error-class line is
SyntaxError, Unable to resolve module, transform failed, or error: Bundling failed → bundle is broken. Treat as a Step B "Import / Bundle" critical error and route through Step D immediately. Do NOT enter the steady-state loop until the bundle is healthy.
- Output contains
Bundling complete / iOS Bundled / Android Bundled with no later error-class line → Metro is healthy. Proceed.
- Output contains a Metro banner (
Metro waiting on, Logs for your project, or › Metro:) but no native Bundled / bundling lines yet → Metro is up but no native client has connected. Tell the user:
Metro is running but no app is connected yet.
Enter startup diagnostics for a reported QR/opening problem, or ask the user
to open the native client. If they cannot verify it now, return
verification-pending; no reinstall merely because the client has not connected.
- Output contains only the logger startup line while the selected PID/port session remains live → Metro has not emitted enough state yet. Tell the user to wait for the native URL, then re-run
/debug-app; do not guess readiness.
If truncated: true, the baseline covers only the latest 256 KiB. Record that older history was omitted; do not claim the full session history was inspected.
Before initializing the cursor, pass all classifiable entries in this initial
window through Step B, including JS runtime errors, React warnings, network/API
failures, native errors, and host diagnostics. Do not advance past a prior error
just because it is not a bundle error. This preserves the promise that users can
"play around, then debug" after a symptom already occurred.
0.2.1 Supersession — never re-fix an error the log already shows resolved
The baseline window is history, not current state. It can contain errors that
were already fixed, that the user resolved themselves, or that were transient.
Fixing those is worse than doing nothing: it edits working code to chase a
symptom that no longer exists, and the "fix" is unverifiable because the error
cannot reproduce.
So every error found in the baseline window only (not in later polls) is
treated as unconfirmed until checked for supersession. Scan forward from the
error line to the end of the window:
| Error class |
Superseded when a later line shows |
| Import / Bundle |
Bundling complete, iOS Bundled, or Android Bundled |
| Network / API |
a 2xx for the same route/resource that previously failed |
| JS runtime / React |
a later app reload or successful bundle, and the error does not reappear after it |
Host diagnostic ([AuthProvider], [bridge], …) |
a later success from the same subsystem (e.g. a token acquired after acquireTokenSilent failed) |
Then:
This applies to the baseline window only. Anything appearing in a later
tail --cursor poll is by definition new output and needs no supersession check.
Symptom mode overrides this. If the user supplied a symptom, that is
first-hand evidence the problem is current, so a matching baseline error is
treated as live even when a later line would otherwise look like supersession.
0.3 Capture baseline
Telemetry checkpoint: capture_runtime_baseline
Use the output from Phase 0.2. Note the most recently bundled native platform (iOS / Android) and any recent runtime log lines. Append to fixes.md:
[<HH:MM:SS>] Baseline — last Metro activity: <1-line summary of most recent lines>
0.4 Initialize the durable byte cursor
Write .powernative/debug-app/metro-cursor.json using structured JSON:
{
"logPath": ".powernative/metro-logs/metro-<timestamp>-pid-12345-port-8081.log",
"pid": 12345,
"port": 8081,
"project": "My Mobile App",
"platform": "ios",
"startedAt": "2026-08-27T12:41:32.050Z",
"monitorStartedAt": "<ISO timestamp>",
"monitorConfig": {
"port": null,
"platform": null,
"targetCleanCycles": 3,
"timeoutSeconds": 300,
"noFix": false
},
"cursor": 12345,
"updatedAt": "<ISO timestamp>"
}
Set project-relative logPath, plus pid, port, project, platform, and startedAt from Phase 0.0. Set monitorStartedAt and monitorConfig from the current invocation, and set cursor to nextCursor from Phase 0.2. Resolve logPath against <working_dir> before file access. A new invocation always replaces the prior monitoring configuration and start time. On later invocations:
Parse an existing cursor only when it is nonempty valid JSON with the expected field types. Treat a missing, empty, malformed, or shape-invalid file as no saved cursor, append a sanitized reset warning to fixes.md, and initialize from the selected session's bounded baseline. Never fail startup solely because prior debug state is partial.
Same logPath, pid, and port, with the process still owning the port → reuse the saved cursor so old errors are not processed again.
Multiple valid sessions → ask which session to monitor. Default to the saved session when it remains valid.
A different session is explicitly selected, or the saved session is no longer valid → discard the old cursor and initialize from the selected session's latest log window.
rotationLost: true from Step A → accept the returned reset cursor and record the file shrink/replacement in fixes.md.
Phase 0.5 — Symptom-driven setup (only when $ARGUMENTS is a symptom string)
Skip this entire phase if no symptom was provided. The standard log-polling loop alone is good at visible errors but blind to silent ones: an empty list because the connector wasn't added, a blank screen because useFocusEffect wasn't wired, blank rows because column names don't match the model. Phase 0.5 closes that gap.
--no-fix behavior: Parse the symptom and ask the user to reproduce it, but do not inject [INJECTED-TRACE] logs or edit any file. Read only new Metro output. If the symptom is silent and produces no classifiable output, write pending to symptom-state, append watch-only: traces not injected to unresolved.md, then enter the standard loop.
0.5.1 Parse the symptom
Extract three signals from the user's text:
| Signal |
How to derive |
| Affected screen |
Match keywords against route filenames in app/ (e.g., "todos" → app/(tabs)/todos.tsx, app/todos/index.tsx, app/(tabs)/index.tsx). Use Glob to enumerate app/**/*.tsx; pick the closest substring match. If multiple, ask once. |
| Affected entity / service |
Same keyword against src/generated/services/*Service.ts and src/generated/models/*Model.ts (e.g., "todos" → TodosService, Todo model). Use Glob. |
| Symptom class |
Map the text to one of: empty-list, blank-screen, wrong-data, unresponsive-control, stale-data, wrong-navigation, crash, pdf-viewer, pdf-report, pen-input, geolocation, dataverse-upload. Default for "PDF won't open / preview PDF fails": pdf-viewer. Default for "report PDF not generated / print report fails": pdf-report. Default for "signature / pen / ink fails": pen-input. Default for "location not tracking / GPS not updating / background location stopped / breadcrumb gaps / route not consistent": geolocation. Default for "signature/report saved but missing", or "location rows not reaching Dataverse": dataverse-upload. Default for "not appearing / not showing / nothing here / missing": empty-list. Default for "doesn't load / freezes / spinner forever": blank-screen. |
Append to fixes.md:
[<HH:MM:SS>] Symptom — class=<class> screen=<path> entity=<service>
If no screen/entity match: keep screen=unknown / entity=unknown and proceed — Phase 0.5 still injects diagnostic logs and reads the terminal from whatever data path is most likely based on the symptom text.
0.5.2 Ask the user to navigate to the affected screen
The dev-player has no automation API for navigation. Ask the user:
"Please open the `
…(truncated)
1---2name: debug-app3description: Diagnose Power Apps mobile install/startup failures, npm run dev errors, missing package entry points, or QR/device-opening problems even before an app is loaded. Inspect locally first; restore locked dependencies or restart Metro only with explicit approval, never upgrade packages or patch host/MSAL source. For a running native app, monitor sanitized project-local Metro logs and diagnose runtime errors or silent failures such as empty lists and blank screens. Supports startup-only diagnosis, symptoms, port/platform filters, bounded monitoring, and non-mutating --no-fix mode. Verify the original symptom, not merely installation or quiet logs.4---56> **Plugin check**: Run `node "${PLUGIN_ROOT}/scripts/check-version.js"` - if it outputs a message, show it to the user before proceeding.78**📋 Shared instructions: [shared-instructions.md](${PLUGIN_ROOT}/shared/shared-instructions.md)** — read first.910Startup diagnosis uses the targeted compatibility inspection below instead of11the shared blanket version check; missing dependencies must not prevent diagnosis.12It does not check for updates. Explicit startup repair/restart approval overrides13shared auto-proceed/default-answer guidance.1415# Debug App — Monitor & Fix1617Monitor the running app through the project-local `.powernative/metro-logs/` files written by `metro.config.js`, detect runtime and bundle errors, and fix them autonomously by editing the affected files (or routing to the right skill when the fix belongs in a domain like Dataverse schema or auth registration). For silent failures, inject temporary `console.log` statements at data-path boundaries, read only newly appended log bytes, then clean the traces after the root cause is fixed. Modeled on the upstream `app-debugger.agent.md` pattern — foreground loop, bounded polling, configurable clean-check/timeout exits, and optional watch-only operation.1819When setup/startup or device opening is failing, first execute20[startup-diagnostics.md](references/startup-diagnostics.md). This bounded phase21can run without Metro logs or a loaded app and returns to the runtime path only22when its prerequisites actually hold. Running `npm run dev` alone does not23activate an agent, and this skill installs no background watcher.2425> **Dev-client limitation:** the standalone dev client sends app/runtime logs, React errors, host diagnostics, and Metro bundler output through Metro. The template's `metro.config.js` writes Metro terminal output and HTTP bundle failures into `.powernative/metro-logs/`; there is no separate device log source. Host diagnostics include strings such as `[AuthProvider] MSAL init failed:`, `[bridge] fetch THREW for`, `[bridge] HTTP <status> for`, `[addAadAppToConnectionAcl] failed HTTP <status> for connection`, `[useConnectionRefs] could not verify connection ACLs; treating existing connections as setup-required`, and `[PAHost][ErrorBoundary] Unhandled JS error:`.2627## Subcommands (parsed from `$ARGUMENTS`)2829| Form | Behavior |30|---|---|31| `/debug-app` (no args) | **Default — project-log-driven mode.** Run Phase 0, discover valid project-local Metro sessions, select automatically when one is live or ask when several are live, then monitor the selected log. No host terminal ID is required. |32| `/debug-app "<symptom text>"` | **Symptom-driven mode** (recommended when there's a user-visible problem). Free-text symptom such as `"todos not appearing on home screen"`, `"login button does nothing"`, `"list empty after refresh"`. Run Phase 0 → Phase 0.5 (parse symptom → ask the user to reproduce/navigate → walk the likely data path from terminal traces) → enter monitor loop. Catches silent failures (empty lists, blank screens, swallowed errors) that pure log polling misses. |33| `/debug-app startup ["<symptom text>"] [--tunnel] [--tunnel-tenant <tenant-guid>]` | **Startup-only diagnosis.** Inspect install/startup/QR failures, offer bounded approved repair, and verify the original symptom. Preserve explicitly selected authenticated tunnel options for an approved retry. Return without the runtime monitor; also used by creation-time failure handoffs. |34| `/debug-app status` | Discover all project-local Metro logs and print each valid session's project, platform, PID, port, start time, and log path. Mark the session referenced by the saved cursor when present, then print fixes and unresolved errors. Do NOT ask for a selection or enter the loop. |35| `/debug-app stop` | Stop only the foreground debug loop and preserve `.powernative/debug-app/` state. It does not stop Metro; the user owns the `npm run dev` process. |36| `/debug-app version` | Print the installed `mobile-app` plugin name and version from `${PLUGIN_ROOT}/.plugin/plugin.json`, then exit. |3738### Monitoring options3940Options may follow the default command, a symptom, or `status`:4142| Option | Meaning | Default |43|---|---|---|44| `--working-dir <path>` | App root containing `package.json`. Startup diagnosis accepts missing Metro config or dependencies; runtime monitoring requires a configured, live Metro session. Relative paths resolve from the current shell directory. | Current shell directory |45| `--port <1-65535>` | Monitor only the valid Metro session on this port. | Any port |46| `--platform <ios\|android>` | Consider only sessions whose recent log identifies this platform. | Any platform |47| `--cycles <1-50>` | Exit after this many consecutive clean observation intervals. | `3` |48| `--timeout <duration>` | Maximum wall-clock monitoring time. Accept `30s`–`60m` using `s`, `m`, or `h`. | `5m` |49| `--no-fix` | Inspect/watch-only: never edit project source/config, inject traces, install, regenerate, start/stop/restart Metro, open the device app, or invoke a mutating handoff. Debug cursor/audit/health state may still advance. | Fix enabled |50| `--tunnel` | Startup only: preserve `--tunnel` when an approved retry invokes `npm run dev`. Never switch a LAN launch to a tunnel automatically. | Disabled |51| `--tunnel-tenant <tenant-guid>` | Startup only: preserve the Entra tenant used to authenticate the dev tunnel. Requires `--tunnel`. | Active Azure CLI tenant |5253Examples:5455```text56/debug-app --port 8082 --platform ios57/debug-app "orders screen is empty" --cycles 10 --timeout 15m58/debug-app --no-fix --timeout 30m59/debug-app status --platform android60/debug-app status --working-dir ../my-mobile-app61/debug-app startup "npm run dev exits before the QR appears"62/debug-app startup "tunnel launch fails" --tunnel --tunnel-tenant 11111111-1111-1111-1111-11111111111163/debug-app "QR won't open the app" --no-fix64```6566**Argument parsing:**67681. Parse quoted text as one symptom value and parse recognized flags wherever they appear.692. The first reserved token (`startup`, `status`, `stop`, `help`, `--help`, `-h`, `version`, `--version`) selects the subcommand. `stop`, help, and version do not accept monitoring options. `status` accepts only `--working-dir`, `--port`, and `--platform`; reject symptoms, `--cycles`, `--timeout`, `--no-fix`, and tunnel options because it does not enter the loop. `startup` accepts one symptom and all options except `--cycles`, because it never enters the runtime monitor. Reject `--tunnel` and `--tunnel-tenant` on every other subcommand.703. After removing recognized options and their values, any remaining non-reserved text is the symptom and enables symptom mode.714. Reject unknown flags, duplicate flags, missing values, invalid numbers, unsupported platforms, or more than one free-text symptom. Print the valid forms and exit without monitoring.725. Normalize `platform` to lowercase. Convert `timeout` to `timeoutSeconds`; require `30 <= timeoutSeconds <= 3600`. Validate `--tunnel-tenant` as a GUID and require `--tunnel`; never derive either option from symptom text or untrusted diagnostic context. Resolve `workingDir` from explicit `--working-dir`, or inherit the caller's absolute root; use the current shell directory only for a direct invocation without either. Reject conflicting explicit/inherited roots and do not search parent directories. Require `package.json` at that root; missing `metro.config.js`, configuration, or installed dependencies routes to startup inspection, not runtime monitoring. An unreadable/malformed manifest is a blocked diagnostic, not permission to initialize a new app. Every shell call must explicitly enter the selected absolute `workingDir`; every relative project path and command below runs from that directory.736. Initialize:74 ```text75 workingDir=<absolute app root>76 portFilter=<number|none>77 platformFilter=<ios|android|none>78 targetCleanCycles=<number, default 3>79 timeoutSeconds=<number, default 300>80 noFix=<true|false, default false>81 devArgs=<[]|["--tunnel"]|["--tunnel","--tunnel-tenant","<tenant-guid>"]>82 monitorStartedAt=<current ISO timestamp>83 ```8485For `help` / `--help` / `-h`, print the subcommands and monitoring-options tables and exit.8687Set `startupStartedAt` only when entering startup diagnostics. Its timeout and88attempt budget include caller-supplied prior attempts. After a verified live app89continues into monitoring, reset `monitorStartedAt` for that separate bounded loop.9091**Early-return subcommands:**9293- `stop`: if received while this foreground loop owns the conversation, clean up any injected traces using Phase 0.5.5 and exit at the next safe boundary. For a standalone `stop` invocation, report that no loop is active. Never stop Metro or delete `.powernative/debug-app/` state.94- `version` / `--version`: read `${PLUGIN_ROOT}/.plugin/plugin.json`, print `<name> <version>`, and exit without resolving a project or writing state. If the manifest is missing or malformed, report that the plugin version is unavailable and exit.95- `status`: validate `workingDir`, then execute only Phase 0.0 discovery through the status branch below. Do not run project preflight, create state files, ask for a session, initialize a baseline, or enter the monitor loop.9697If `stop` arrives during startup diagnosis, cancel upcoming diagnostic/repair98steps and report any in-flight approved command accurately. Do not automatically99kill an installation or Metro process, or claim a partly restored install is complete.100101**Tip — "play around then debug":** Metro persists recent app output in `.powernative/metro-logs/` even across chat/editor restarts. If something weird just happened, keep using the app normally, then run `/debug-app` or `/debug-app "<what you saw>"`. The first cycle reads the latest persisted log window; subsequent cycles read only bytes appended after the saved cursor.102103## Core Principles104105- **Foreground autonomous loop** — Once started, this skill owns the conversation until `targetCleanCycles` consecutive clean polls confirm the app is healthy, `timeoutSeconds` elapses, the user types `stop`, or the escalation rule trips. **Do not run other skills concurrently** — they'll queue behind the loop.106- **Watch-only means no project mutation** — With `--no-fix`, do not edit project source/configuration, inject diagnostic logs, install packages, regenerate schemas, switch accounts, or invoke a mutating skill. Continue to advance `.powernative/debug-app/` cursor/audit/health state, classify errors, and provide the fix/handoff that would have been used.107- **Runtime monitoring requires a live app; startup diagnosis does not.** First108 classify install/startup/opening failures through the bounded startup reference.109 Do not enter the runtime monitor or claim healthy runtime without a verified110 live native session.111- **Native-only runtime target** — The app must be loaded in a native dev client on a device or simulator; `.powernative/metro-logs/` is the authoritative log source for that native session.112- **No web or direct Metro probes** — Do not use React Native Web, browser automation, `curl`, `fetch`, `WebFetch`, or any direct request to a Metro/localhost endpoint for runtime diagnosis. Read only the `.powernative` log and source files.113- **No screen-by-screen verification** — Do not crawl routes or validate every screen. In symptom mode, focus only on the user-reported workflow and the terminal/source evidence needed to diagnose it.114- **One fix at a time** — Fully resolve one issue (context → fix → type-check → reload → re-poll) before starting the next. No batching.115- **Working-dir state** — Debug audit state lives in `.powernative/debug-app/`: `fixes.md`, `unresolved.md`, `injected-logs.md`, `health.json`, and `metro-cursor.json`. Metro logs live in the already-ignored `.powernative/metro-logs/`. Both survive chat/editor restarts without binding state to a specific agent host.116- **Defense-in-depth redaction** — The Metro logger removes credential-like lines before writing `.powernative`, but `/debug-app` must independently minimize and sanitize every value before persisting it to `.powernative/debug-app/`. Never copy raw response bodies, record objects, tokens, headers, trace payloads, or absolute home-directory paths into debugger state.117- **The port is the log identity** — the dev-server port is the number the QR encodes, the device dials, and this skill verifies. Liveness is a socket probe (does the log's PID still hold that port?), never terminal scrollback. A `port-taken` status means the log belongs to a dead session and must not be diagnosed.118- **Never fix history** — the log is a record of the past, so an error in it is not proof of a current problem. Errors found in the baseline window must pass the Phase 0.2.1 supersession check before any code is edited. Editing working code to chase an already-resolved error is a worse outcome than reporting nothing.119- **First-party native packages are an immutable boundary** — a frame under `node_modules/@microsoft/power-apps-native-*` is evidence, not proof, of package ownership. First rule out broken installation, Node/native compatibility, invalid app inputs, unsupported configuration, and misuse of the package's documented API. Once the evidence confirms a defect inside an installed `@microsoft/power-apps-native-*` package, do not apply a customer-project workaround: do not edit `node_modules/`, create a `patch-package` patch or postinstall rewrite, vendor or fork package source, redirect the package through Metro/Babel/TypeScript aliases, or replace its dependency with a git, tarball, or local fork. Record a sanitized package-defect report and route the user to `/report-issue`. Host/MSAL source patches remain prohibited; approved same-lock installation restoration is not a source patch or upgrade.120- **Host terminal APIs are optional only** — Never ask for or persist a terminal121 ID. During runtime monitoring, available host output is only a convenience and122 diagnosis still advances the authoritative `.powernative` cursor. Before a log123 exists, the bounded startup phase may use the current failed command's sanitized124 terminal output; it must not fabricate a cursor or treat that output as a live125 runtime session.126- **Context-first diagnosis** — Read `memory-bank.md` when present. Read `power.config.json` for environment, Dataverse, and connector context. Consult `native-app-plan.md` only when the failure concerns a planned screen, data model, connector, offline profile, or native capability; do not parse it for unrelated syntax/runtime errors.127- **Reference resolution order** — For Dataverse/Power Platform errors: read [skills/add-dataverse/references/dataverse-reference.md](${PLUGIN_ROOT}/skills/add-dataverse/references/dataverse-reference.md) first, inspect generated services/models and project context, then query `mcp__plugin_mobile-app_microsoft-learn__microsoft_docs_search` when behavior remains uncertain. For Expo/Expo Router/React Native errors: inspect installed versions and project code first, then use targeted `WebFetch` against official `https://docs.expo.dev/` documentation. Use package documentation next and general web search only as a last resort.128129## Workflow — Task List First130131Before entering the monitor loop, write a task list and keep it up to date:132133```134- [ ] Discover valid `.powernative` Metro sessions and select one when needed135- [ ] If startup/install/QR failure or no live session: inspect and classify; repair only with approval; verify original symptom or return pending/blocked136- [ ] Capture baseline log state from the selected session and save its byte cursor137- [ ] (Symptom mode only) Phase 0.5: parse symptom → ask user to navigate → inject console.logs → read new log bytes → walk data path → clean up logs138- [ ] Monitoring cycle 1: collect → classify → fix if needed139- [ ] Monitoring cycle 2: collect → classify → fix if needed140- [ ] Monitoring cycle 3: collect → classify → fix if needed141 (add cycles as needed; after <targetCleanCycles> consecutive clean cycles, use the resolved/flagged/pending symptom outcome)142- [ ] Fix: <error summary> → <inline edit | skill route> (one task per error found)143```144145Mark each cycle complete (clean OR fixed) before starting the next.146147---148149## Phase 0 — Startup Check150151Before entering the loop:152153### 0.setup Startup/setup diagnostic dispatch154155After the early-return subcommands, run156[startup-diagnostics.md](references/startup-diagnostics.md) when:157158- the subcommand is `startup`;159- the supplied symptom concerns installation, `npm run dev`, Node/package160 compatibility, startup before loading, or QR/device opening; or161- Phase 0.0 finds no valid live session (not merely a mismatched port/platform162 filter when another session is live), or Phase 0.2 finds no connected client.163164For a healthy live app with a runtime symptom, skip setup and use the existing165runtime path. On `startup` or a creation handoff, return the structured startup166outcome without entering the monitor. Otherwise a verified live app re-enters167Phase 0.preflight, session discovery, and state initialization (0.1) before168Phase 0.2; pending/blocked/cancelled returns without a green runtime result.169Record `startupOutcome` in invocation context so this return does not re-enter170setup just because the original symptom mentioned startup. If only installation171or Metro startup is verified but no native app is connected, report runtime172verification pending and return instead of repeatedly dispatching setup.173No unbounded redispatch: repeated setup failures consume the same attempt budget.174175### 0.preflight Read project context176177Follow the shared instructions before diagnosing logs:178179Use `workingDir` from argument parsing as `<working_dir>` throughout this workflow. It is already validated as an app root; do not derive it again from a later phase or silently switch projects.1801811. If `<working_dir>/memory-bank.md` exists, read its Project facts, Power Platform context, Data model, Connectors, Screens, Native capabilities, and Build history. Do not create a memory bank from `/debug-app`; absence is valid.1822. Read `<working_dir>/power.config.json` when present. Capture `environmentId`, `databaseReferences`, and `connectionReferences`. `power.config.json` is the preferred environment source.1833. Read `<working_dir>/native-app-plan.md` only when the supplied symptom or a classified error concerns a planned screen, Dataverse entity/column, connector, offline behavior, navigation contract, or native capability. Treat the plan as intended design, not proof of live schema/runtime state.1844. Inspect `src/generated/services/`, `src/generated/models/`, and `src/generated/connectorSchemas.ts` only when the affected data path uses them. Never edit generated files.185186Append a compact context line to `fixes.md` after Phase 0.1 creates it:187188```text189[<HH:MM:SS>] Context — memory-bank=<present|absent> native-plan=<present|absent|not-needed> environment=<environmentId|none> dataverse-tables=<N> connectors=<N>190```191192Do not resolve the environment or call Dataverse during ordinary bundle, React, or local JavaScript failures. When a current symptom/error is Dataverse or Power Platform related, perform the read-only Dataverse diagnostic sequence in D2 before handing off.193194### 0.0 Discover and select the project-local Metro session195196Use the validated `<working_dir>` from argument parsing. Enumerate **all** matching logs, newest first:197198```bash199LOG_DIR='<working_dir>/.powernative/metro-logs'200ls -t "$LOG_DIR"/metro-*-pid-*-port-*.log 2>/dev/null201```202203For every candidate, parse:204205- `pid` and `port` from `metro-<timestamp>-pid-<pid>-port-<port>.log`;206- `startedAt` from the filename timestamp;207- `project` from `power.config.json.appDisplayName`, falling back to the basename of `<working_dir>`;208- `platform` by scanning only the latest 64 KiB for the most recent `iOS ... Bundled` / `iOS Bundling` or `Android ... Bundled` / `Android Bundling` line; use `unknown` when neither appears.209210Check every recorded PID with a cross-platform Node probe: `process.kill(pid, 0)` means alive; treat `EPERM` as alive and other errors as gone. When `port` is numeric, verify ownership with `lsof -nP -iTCP:<port> -sTCP:LISTEN -t` on macOS/Linux when available, or `netstat.exe -ano -p tcp` on Git Bash/Windows. On Linux without `lsof`, use `ss -ltnp` when available. A candidate is **valid/live** only when its PID is alive and either owns the recorded port, has `port=unknown`, or no supported port-ownership probe exists. A probe that runs and reports a different PID is a contradiction, not an unavailable probe. Do not persist terminal IDs or depend on terminal output.211212Selection rules:213214- Apply `portFilter` and `platformFilter` to the valid/live candidates before selection. When no valid session matches, print the filters plus the available valid sessions and stop. If a platform-filtered candidate is `unknown`, do not guess; tell the user to use `--port` or omit `--platform`.215- **One valid session** — select it automatically.216- **Multiple valid sessions** — show one choice per session in this exact shape, then ask which to monitor:217 ```text218 <project> — <platform> — port <port> — pid <pid> — started <startedAt>219 ```220 Use `AskUserQuestion`; identify choices internally by the complete `logPath` + `pid` + `port`, not by port alone. If `metro-cursor.json` points to one of the valid sessions, make that session the default choice but still ask. Never silently choose the newest session when more than one is live.221- **No valid sessions** — apply the failure branches below. Stale or contradictory logs are evidence for the report, never selectable choices.222223**`status` branch — return before selection:** After filtering and liveness checks, read `.powernative/debug-app/metro-cursor.json` only when it is nonempty valid JSON with string `logPath`, numeric `pid`, and numeric-or-`unknown` `port`. Treat a missing, empty, malformed, or shape-invalid cursor as absent and print a warning; never overwrite it from `status`. Print every valid session newest-first using the normal session display shape, marking `[saved]` only when `logPath` + `pid` + `port` match the valid cursor. Then print at most the last 20 nonempty lines from `fixes.md` and `unresolved.md`, passing the displayed text through the persistence redactor first. Print stale/contradictory candidate counts without diagnosing their log content, then exit. When no valid session exists, print that result plus the applicable no-log/stale reason and exit.224225For monitoring modes only, select a session using the rules above. After selection, set `LOG_PATH`, `pid`, `port`, `project`, `platform`, and `startedAt` from the chosen candidate. This selection is sticky for the current monitor run.226227When no log exists, inspect `metro.config.js` and resolve the logging module from `<working_dir>` before choosing a failure branch:228229- **Current factory form:** the config uses `createPowerAppsMetroConfig` from `@microsoft/power-apps-native-host/config/metroConfig`, and that exact subpath resolves from the project's installed dependencies. The factory installs project-local logging internally.230- **Legacy direct form:** the config directly imports `@microsoft/power-apps-native-host/metro-logger`, and that exact subpath resolves from the project's installed dependencies.231- **Unavailable:** neither configured subpath resolves, the referenced form is absent, or `@microsoft/power-apps-native-host` is missing from `package.json`. A dependency version string alone does not prove that the configured export exists.232233Branch as follows:234235| Status | Meaning | Action |236|---|---|---|237| Exactly one valid log exists, PID is alive, and either port is unknown or the port probe is unavailable | Select it. Capture `project`, `platform`, `startedAt`, `port`, `pid`, and `logPath`, then continue. |238| Exactly one valid log exists and PID still owns the logged port | Select it. Capture `project`, `platform`, `startedAt`, `port`, `pid`, and `logPath`, then continue. |239| Multiple valid logs exist | Show every valid session and ask which one to monitor. Do not select by recency alone. |240| Log exists, PID is gone, and another process owns the logged port | Do NOT diagnose from this log. Tell the user which PID holds the port and ask them to restart `npm run dev`. |241| Log exists but PID/port contradict each other | The device may be talking to the wrong server. Ask the user to stop stale Metro processes and rerun `npm run dev`. |242| No log exists and the logging form is unavailable | This project predates project-local Metro logging or has incomplete dependencies. Enter startup diagnostics to distinguish broken install, unsupported export, and config mismatch; do not edit native/Metro config or loop on restarts. |243| No log exists and the current factory or legacy direct logging form resolves | If available host output contains `[powernative] Metro logging instrumentation failed`, preserve that bounded evidence. Enter startup diagnostics rather than assume a package defect or require the app to load first. |244245The PID/port check prevents stale-log diagnosis: a log file can outlive its Metro process, so only the socket probe reveals that the log stopped belonging to the app under test. The explicit choice prevents a valid session on one port from being confused with another valid session in the same project.246247If no `.powernative` log exists but the host exposes a live Metro terminal, use248its bounded output only as startup evidence. Do not ask for or store its terminal249ID or enter the continuous monitor against it. The startup phase owns any250approved retry; runtime monitoring still requires a valid project-local log.251252Record the stable source in `fixes.md`:253254```text255[<HH:MM:SS>] Log source — <project> <platform> — <logPath> (pid <pid>, port <port>, started <startedAt>)256```257258### 0.1 Ensure state directory259260```bash261mkdir -p .powernative/debug-app262touch .powernative/debug-app/fixes.md263touch .powernative/debug-app/unresolved.md264touch .powernative/debug-app/injected-logs.md265touch .powernative/debug-app/health.json266touch .powernative/debug-app/metro-cursor.json267rm -f .powernative/debug-app/symptom-state # per-session — Phase 0.5 rewrites it if symptom mode is active268```269270If `fixes.md` is empty, write a session header:271```272# Debug session — <date>273274```275276Append the effective invocation settings:277278```text279[<HH:MM:SS>] Monitor config — port=<any|port> platform=<any|ios|android> clean-cycles=<targetCleanCycles> timeout=<timeoutSeconds>s no-fix=<true|false>280```281282### 0.1.1 Initialize health state283284Write `.powernative/debug-app/health.json` without raw log content:285286```json287{288 "bundle": { "status": "unknown", "summary": "No evidence yet" },289 "runtime": { "status": "unknown", "summary": "No evidence yet" },290 "authentication": { "status": "unknown", "summary": "No evidence yet" },291 "dataverse": { "status": "unknown", "summary": "No evidence yet" },292 "connector": { "status": "unknown", "summary": "No evidence yet" },293 "offline": { "status": "unknown", "summary": "No evidence yet" },294 "navigation": { "status": "unknown", "summary": "No evidence yet" },295 "nativeCapability": { "status": "unknown", "summary": "No evidence yet" },296 "updatedAt": "<ISO timestamp>"297}298```299300Allowed statuses are `healthy`, `degraded`, `failed`, `unknown`, and `not-configured`. Update only the affected domain after each classified signal:301302| Signal | Health update |303|---|---|304| Successful native bundle after the latest bundle error | `bundle=healthy` |305| Bundle/transform/import failure | `bundle=failed` |306| Uncaught JS/React error | `runtime=failed`; set `healthy` after the repaired workflow produces clean new output |307| Auth success/failure host diagnostics | `authentication=healthy|failed` |308| Dataverse 2xx/error for the affected operation | `dataverse=healthy|failed` |309| Connector resolution/call success or failure | `connector=healthy|failed` |310| No offline profile | `offline=not-configured`; offline activation/sync warning or failure → `degraded|failed` |311| Confirmed route/navigation error | `navigation=failed`; repaired route confirmation → `healthy` |312| Native wrapper success, permission denial, missing module, or native failure | `nativeCapability=healthy|degraded|failed` |313314Absence of evidence remains `unknown`; never convert an unobserved domain to `healthy`.315316### 0.1.2 Persistence redaction gate317318Before appending diagnostic text to `fixes.md` or `unresolved.md`, or storing a health `summary`, sanitize it:3193201. Convert project paths to paths relative to `<working_dir>`. Replace other absolute home-directory paths with `[REDACTED_PATH]`.3212. Replace complete authorization/cookie/secret headers (`Authorization`, `Proxy-Authorization`, `Cookie`, `Set-Cookie`, `x-api-key`, `api-key`, `client-secret`, and token headers) with `[REDACTED_HEADER]`.3223. Replace Bearer values, JWT-like three-segment values, SAS/query secrets (`sig`, `se`, `sp`, `sv`, `code`, `token`, `access_token`, `refresh_token`, `id_token`, `client_secret`), passwords, and API keys with `[REDACTED_SECRET]`.3234. Replace email addresses with `[REDACTED_EMAIL]` and GUIDs/record identifiers with `[REDACTED_ID]` unless the identifier is a non-sensitive local PID/port.3245. Never persist Dataverse/connector response bodies or arbitrary `[TRACE]` object values. Persist only status, source/config table or column names, counts, error codes, and a bounded error message.3256. Scan the sanitized result again. If any sensitive pattern remains, persist `[REDACTION_BLOCKED: diagnostic omitted]` instead.326327Run the bundled verifier for every candidate diagnostic before writing:328329```bash330printf '%s' "$DIAGNOSTIC_SUMMARY" | node \331 "${PLUGIN_ROOT}/scripts/redact-debug-diagnostic.js" \332 --working-dir '<working_dir>'333```334335Persist only the verifier's stdout. Build `DIAGNOSTIC_SUMMARY` from minimal fields first; do not pass a full Metro window or response body and rely on redaction to make it safe.336337Store `logPath` in `metro-cursor.json` relative to `<working_dir>` and resolve it against `<working_dir>` when reading. This gate is required even though `.powernative` logs are already sanitized.338339### 0.2 Verify Metro bundled and the app is running340341**Telemetry checkpoint: `validate_metro_session`**342343Read a bounded baseline window and return a real byte cursor:344345```bash346node - "$LOG_PATH" 262144 <<'NODE'347const fs = require('node:fs');348const [file, maxText] = process.argv.slice(2);349const maxBytes = Number(maxText);350const size = fs.statSync(file).size;351const start = Math.max(0, size - maxBytes);352const fd = fs.openSync(file, 'r');353const buffer = Buffer.alloc(size - start);354const bytesRead = fs.readSync(fd, buffer, 0, buffer.length, start);355fs.closeSync(fd);356process.stdout.write(JSON.stringify({357 cursor: start,358 nextCursor: start + bytesRead,359 truncated: start > 0,360 output: buffer.subarray(0, bytesRead).toString('utf8')361}, null, 2));362NODE363```364365The logger initially writes `port-unknown` and may atomically rename that file to the numeric port. If the baseline read gets `ENOENT`, rediscover once before reporting failure. When the same filename timestamp and PID now exist with a numeric port, update `LOG_PATH` and `port` to that file and retry the bounded read once; do not process both names as separate sessions.366367Parse `output`, `cursor`, `nextCursor`, and `truncated`; use the `pid`, `port`, and `logPath` resolved in Phase 0.0. Scan `output`:368369- Most recent error-class line is `SyntaxError`, `Unable to resolve module`, `transform failed`, or `error: Bundling failed` → bundle is broken. Treat as a Step B "Import / Bundle" critical error and route through Step D immediately. Do NOT enter the steady-state loop until the bundle is healthy.370- Output contains `Bundling complete` / `iOS Bundled` / `Android Bundled` with no later error-class line → Metro is healthy. Proceed.371- Output contains a Metro banner (`Metro waiting on`, `Logs for your project`, or `› Metro:`) but no native `Bundled` / `bundling` lines yet → Metro is up but no native client has connected. Tell the user:372 > **Metro is running but no app is connected yet.**373 Enter startup diagnostics for a reported QR/opening problem, or ask the user374 to open the native client. If they cannot verify it now, return375 `verification-pending`; no reinstall merely because the client has not connected.376- Output contains only the logger startup line while the selected PID/port session remains live → Metro has not emitted enough state yet. Tell the user to wait for the native URL, then re-run `/debug-app`; do not guess readiness.377378If `truncated: true`, the baseline covers only the latest 256 KiB. Record that older history was omitted; do not claim the full session history was inspected.379380Before initializing the cursor, pass **all** classifiable entries in this initial381window through Step B, including JS runtime errors, React warnings, network/API382failures, native errors, and host diagnostics. Do not advance past a prior error383just because it is not a bundle error. This preserves the promise that users can384"play around, then debug" after a symptom already occurred.385386### 0.2.1 Supersession — never re-fix an error the log already shows resolved387388The baseline window is **history, not current state**. It can contain errors that389were already fixed, that the user resolved themselves, or that were transient.390Fixing those is worse than doing nothing: it edits working code to chase a391symptom that no longer exists, and the "fix" is unverifiable because the error392cannot reproduce.393394So every error found in the **baseline window only** (not in later polls) is395treated as *unconfirmed* until checked for supersession. Scan forward from the396error line to the end of the window:397398| Error class | Superseded when a later line shows |399|---|---|400| Import / Bundle | `Bundling complete`, `iOS Bundled`, or `Android Bundled` |401| Network / API | a 2xx for the same route/resource that previously failed |402| JS runtime / React | a later app reload or successful bundle, and the error does not reappear after it |403| Host diagnostic (`[AuthProvider]`, `[bridge]`, …) | a later success from the same subsystem (e.g. a token acquired after `acquireTokenSilent failed`) |404405Then:406407- **Superseded** → do NOT fix. Record it and move on:408 ```409 [<HH:MM:SS>] Observed (already resolved, not fixed) — <error summary> — superseded by <evidence line>410 ```411- **Not superseded** → the error is live. Fix it normally through Step D.412- **Ambiguous** (no clear supersession evidence either way) → do NOT edit code yet. Ask the user whether they still see it, or wait for it to reappear in the next poll. An error that recurs after the cursor advances is confirmed live.413414This applies to the baseline window only. Anything appearing in a later415`tail --cursor` poll is by definition new output and needs no supersession check.416417**Symptom mode overrides this.** If the user supplied a symptom, that is418first-hand evidence the problem is current, so a matching baseline error is419treated as live even when a later line would otherwise look like supersession.420421### 0.3 Capture baseline422423**Telemetry checkpoint: `capture_runtime_baseline`**424425Use the output from Phase 0.2. Note the most recently bundled native platform (iOS / Android) and any recent runtime log lines. Append to `fixes.md`:426```427[<HH:MM:SS>] Baseline — last Metro activity: <1-line summary of most recent lines>428```429430### 0.4 Initialize the durable byte cursor431432Write `.powernative/debug-app/metro-cursor.json` using structured JSON:433434```json435{436 "logPath": ".powernative/metro-logs/metro-<timestamp>-pid-12345-port-8081.log",437 "pid": 12345,438 "port": 8081,439 "project": "My Mobile App",440 "platform": "ios",441 "startedAt": "2026-08-27T12:41:32.050Z",442 "monitorStartedAt": "<ISO timestamp>",443 "monitorConfig": {444 "port": null,445 "platform": null,446 "targetCleanCycles": 3,447 "timeoutSeconds": 300,448 "noFix": false449 },450 "cursor": 12345,451 "updatedAt": "<ISO timestamp>"452}453```454455Set project-relative `logPath`, plus `pid`, `port`, `project`, `platform`, and `startedAt` from Phase 0.0. Set `monitorStartedAt` and `monitorConfig` from the current invocation, and set `cursor` to `nextCursor` from Phase 0.2. Resolve `logPath` against `<working_dir>` before file access. A new invocation always replaces the prior monitoring configuration and start time. On later invocations:456457- Parse an existing cursor only when it is nonempty valid JSON with the expected field types. Treat a missing, empty, malformed, or shape-invalid file as no saved cursor, append a sanitized reset warning to `fixes.md`, and initialize from the selected session's bounded baseline. Never fail startup solely because prior debug state is partial.458459- Same `logPath`, `pid`, and `port`, with the process still owning the port → reuse the saved cursor so old errors are not processed again.460- Multiple valid sessions → ask which session to monitor. Default to the saved session when it remains valid.461- A different session is explicitly selected, or the saved session is no longer valid → discard the old cursor and initialize from the selected session's latest log window.462- `rotationLost: true` from Step A → accept the returned reset cursor and record the file shrink/replacement in `fixes.md`.463464---465466## Phase 0.5 — Symptom-driven setup (only when `$ARGUMENTS` is a symptom string)467468Skip this entire phase if no symptom was provided. The standard log-polling loop alone is good at *visible* errors but blind to *silent* ones: an empty list because the connector wasn't added, a blank screen because `useFocusEffect` wasn't wired, blank rows because column names don't match the model. Phase 0.5 closes that gap.469470**`--no-fix` behavior:** Parse the symptom and ask the user to reproduce it, but do not inject `[INJECTED-TRACE]` logs or edit any file. Read only new Metro output. If the symptom is silent and produces no classifiable output, write `pending` to `symptom-state`, append `watch-only: traces not injected` to `unresolved.md`, then enter the standard loop.471472### 0.5.1 Parse the symptom473474Extract three signals from the user's text:475476| Signal | How to derive |477|---|---|478| **Affected screen** | Match keywords against route filenames in `app/` (e.g., `"todos"` → `app/(tabs)/todos.tsx`, `app/todos/index.tsx`, `app/(tabs)/index.tsx`). Use `Glob` to enumerate `app/**/*.tsx`; pick the closest substring match. If multiple, ask once. |479| **Affected entity / service** | Same keyword against `src/generated/services/*Service.ts` and `src/generated/models/*Model.ts` (e.g., `"todos"` → `TodosService`, `Todo` model). Use `Glob`. |480| **Symptom class** | Map the text to one of: `empty-list`, `blank-screen`, `wrong-data`, `unresponsive-control`, `stale-data`, `wrong-navigation`, `crash`, `pdf-viewer`, `pdf-report`, `pen-input`, `geolocation`, `dataverse-upload`. Default for "PDF won't open / preview PDF fails": `pdf-viewer`. Default for "report PDF not generated / print report fails": `pdf-report`. Default for "signature / pen / ink fails": `pen-input`. Default for "location not tracking / GPS not updating / background location stopped / breadcrumb gaps / route not consistent": `geolocation`. Default for "signature/report saved but missing", or "location rows not reaching Dataverse": `dataverse-upload`. Default for "not appearing / not showing / nothing here / missing": `empty-list`. Default for "doesn't load / freezes / spinner forever": `blank-screen`. |481482Append to `fixes.md`:483```484[<HH:MM:SS>] Symptom — class=<class> screen=<path> entity=<service>485```486487If no screen/entity match: keep `screen=unknown` / `entity=unknown` and proceed — Phase 0.5 still injects diagnostic logs and reads the terminal from whatever data path is most likely based on the symptom text.488489### 0.5.2 Ask the user to navigate to the affected screen490491The dev-player has no automation API for navigation. Ask the user:492> "Please open the `<screen>493494…(truncated)