Debug app

From microsoft/power-platform-skills · View interactive version

Debug app is an AI agent skill from the GitHub repository microsoft/power-platform-skills. 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/MSA

How to use this skill

Skill file

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:

  1. Parse quoted text as one symptom value and parse recognized flags wherever they appear.
  2. 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.
  3. After removing recognized options and their values, any remaining non-reserved text is the symptom and enables symptom mode.
  4. 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.
  5. 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.
  6. Initialize:

```text

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:

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

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.

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.

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:

compatibility, startup before loading, or QR/device opening; or

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

Compare the app's required native counter with the selected Player's actual

supported counters when that evidence is available. Report both on mismatch;

offer an approved /check-updates migration or a verified matching Player,

never a counter rewrite or first-party package patch. Package metadata alone

does not prove device execution or offline synchronization.

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.

  1. 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.
  2. Read <working_dir>/power.config.json when present. Capture environmentId, databaseReferences, and connectionReferences. power.config.json is the preferred environment source.
  3. 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.
  4. 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:

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:

```text

<project> β€” <platform> β€” port <port> β€” pid <pid> β€” started <startedAt>

```

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.

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:

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. |

Startup diagnosis does not authorize copying the newest template or host over

the app. Resolve native requirements against the app's package-owned contract

and route a necessary migration to /check-updates. Missing verified support

blocks native mutations, not read-only startup diagnosis.

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|failed |

| Dataverse 2xx/error for the affected operation | dataverse=healthy|failed |

| Connector resolution/call success or failure | connector=healthy|failed |

| No offline profile | offline=not-configured; offline activation/sync warning or failure β†’ degraded|failed |

| Confirmed route/navigation error | navigation=failed; repaired route confirmation β†’ healthy |

| Native wrapper success, permission denial, missing module, or native failure | nativeCapability=healthy|degraded|failed |

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:

  1. Convert project paths to paths relative to <working_dir>. Replace other absolute home-directory paths with [REDACTED_PATH].
  2. 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].
  3. 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].
  4. Replace email addresses with [REDACTED_EMAIL] and GUIDs/record identifiers with [REDACTED_ID] unless the identifier is a non-sensitive local PID/port.
  5. 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.
  6. 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:

> 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.

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:

```

[<HH:MM:SS>] Observed (already resolved, not fixed) β€” <error summary> β€” superseded by <evidence line>

```

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:


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 <screen> screen on the device/simulator, then reply ready."

Wait for the user to confirm before proceeding.

0.5.3 Inject diagnostic console.log statements and read terminal

Inject targeted console.log statements at the boundaries of the suspected data path so the Metro terminal reveals what's happening.

Injection sites β€” choose the minimum set that covers the symptom class:

| Symptom class | Inject at |

|---|---|

| empty-list | (a) entry point of the data-fetching hook, logging [TRACE items] the raw response length; (b) the screen component, logging [TRACE render] the items array length before the list renders |

| blank-screen | Entry point of the screen component, logging [TRACE mount] with a timestamp plus only booleans or counts that describe whether required auth/data props are present |

| wrong-data / stale-data | The hook that calls the generated service (NOT inside src/generated/), logging [TRACE service-response] with an allowlisted summary: result count, error presence, bounded error code/status, and expected-field presence booleans |

| unresponsive-control | The event handler (onPress, onSubmit, etc.) logging [TRACE handler-called] before any async work |

| crash | Skip injection β€” jump to the monitor loop (Step A), crash stacks appear in the terminal |

Console.log injection pattern β€” all injected lines MUST use this exact format:

console.log('[TRACE <tag>]', <value>); // [INJECTED-TRACE]

Record every injection in .powernative/debug-app/injected-logs.md:

[<HH:MM:SS>] Injected [INJECTED-TRACE] at <file>:<line> β€” tag=<tag>

Then tell the user:

"I've added diagnostic console.log statements. Fast Refresh should apply them automatically. Navigate to <screen> and trigger the symptom (for example, scroll the list or tap the button). If the app does not refresh, reload it from the native dev-client menu. Reply done when finished."

Wait for the user to reply, then run the Step A tail --cursor procedure, persist nextCursor, and filter the returned output for [TRACE lines.

0.5.4 Walk the data path from terminal output

Use the [TRACE lines to walk the chain:

  1. Screen TSX (app/<route>.tsx)
  1. Data hook (src/hooks/useListData.ts or sibling)
  1. Generated service (src/generated/services/<Name>Service.ts)
  1. Generated model (src/generated/models/<Name>Model.ts)
  1. power.config.json
  1. Auth state (src/playerConfig.ts, app.config.js, auth.config.json, useAuth() hook)

Classify the [TRACE output:

| Output | Meaning | Next step |

|---|---|---|

| [TRACE items] 0 or [] β€” no error field | Service returned empty β€” check filter/query or data not seeded | Fix the query; if no records exist, seed sample data |

| [TRACE items] undefined | Hook never received a response β€” likely service stub or missing datasource | Route to /add-connector or /add-dataverse |

| [TRACE service-response] shows an error status/code | Service threw β€” 401/403 = auth; 404 = wrong resource | Fix auth config or re-run pa app add data-source |

| [TRACE render] N > 0 but list looks empty | Field name mismatch between model and screen | Fix screen field references to match the model |

| [TRACE handler-called] never appears | onPress not wired or component not mounted | Read TSX, fix the event binding |

| No [TRACE lines at all | Metro may have cached the old bundle | Ask the user to stop Metro, rerun npm run dev -- --clear, then reload the native app |

Record the outcome in .powernative/debug-app/symptom-state (single line: resolved, flagged, or pending).

0.5.5 Clean up injected console.log statements

After the root cause is identified and a fix is applied (or Phase 0.5 concludes), remove ALL injected logs:

find app src -type f \( -name '*.js' -o -name '*.jsx' -o -name '*.ts' -o -name '*.tsx' \) \
   ! -path 'src/generated/*' -exec grep -nH 'INJECTED-TRACE' {} +

For each matching file, edit out the console.log(...); // [INJECTED-TRACE] lines. Verify with:

find app src -type f \( -name '*.js' -o -name '*.jsx' -o -name '*.ts' -o -name '*.tsx' \) \
   ! -path 'src/generated/*' -exec grep -nH 'INJECTED-TRACE' {} +  # must print zero matches

Clear the tracking file:

echo '' > .powernative/debug-app/injected-logs.md

Run npm run type-check once after cleanup.

Hard rule: Never leave [INJECTED-TRACE] lines in code. Clean up before marking the session done, even if the symptom is pending or flagged.

0.5.6 Re-enter the standard monitor loop

After Phase 0.5 completes, fall through to the monitor loop (Step A). Count clean cycles normally, but let Step C choose the exit from the single-line symptom-state: resolved may exit green, while flagged and pending use their non-green exits after targetCleanCycles. Never report a green result for a flagged or pending symptom.


Monitor Loop

Repeat until targetCleanCycles consecutive clean cycles, timeoutSeconds elapses, the user types stop, OR the escalation rule trips.

Before every collection cycle and immediately after any fix verification, compare the current time with monitorStartedAt. When elapsed time is greater than or equal to timeoutSeconds:

  1. Clean up all [INJECTED-TRACE] lines before exit.
  2. Append the elapsed time, cycle count, clean count, active session identity, and unresolved issue count to fixes.md.
  3. Exit without stopping Metro:

```text

⚠ Monitoring timeout reached after <duration>.

Session: <project> β€” <platform> β€” port <port> β€” pid <pid>

Clean checks: <clean>/<targetCleanCycles>

Details: .powernative/debug-app/fixes.md

```

Step A β€” Collect logs

Telemetry checkpoint: collect_runtime_logs

Read .powernative/debug-app/metro-cursor.json and rediscover all live .powernative sessions using Phase 0.0's validation logic.

Otherwise collect newly appended bytes from the pinned session. When no bytes are already waiting, this foreground collector watches the log directory until that file changes or a full 5-second observation interval completes:

node - "$LOG_PATH" <saved-cursor> 262144 5000 <<'NODE'
const fs = require('node:fs');
const path = require('node:path');
const [file, cursorText, maxText, observationText] = process.argv.slice(2);
const cursor = Number(cursorText);
const maxBytes = Number(maxText);
const observationMs = Number(observationText);
const observedAt = Date.now();
let watcher;
let timer;
let finished = false;

function snapshot(observation) {
   try {
      const size = fs.statSync(file).size;
      const start = Number.isInteger(cursor) && cursor >= 0 && cursor <= size ? cursor : 0;
      const fd = fs.openSync(file, 'r');
      const buffer = Buffer.alloc(Math.min(maxBytes, Math.max(0, size - start)));
      let bytesRead;
      try {
         bytesRead = fs.readSync(fd, buffer, 0, buffer.length, start);
      } finally {
         fs.closeSync(fd);
      }
      return {
         cursor: start,
         nextCursor: start + bytesRead,
         rotationLost: start !== cursor,
         truncated: start + bytesRead < size,
         fileMissing: false,
         readError: null,
         observation,
         observedMs: Date.now() - observedAt,
         output: buffer.subarray(0, bytesRead).toString('utf8'),
      };
   } catch (error) {
      return {
         cursor,
         nextCursor: cursor,
         rotationLost: false,
         truncated: false,
         fileMissing: error && error.code === 'ENOENT',
         readError: error && typeof error.code === 'string' ? error.code : 'UNKNOWN',
         observation,
         observedMs: Date.now() - observedAt,
         output: '',
      };
   }
}

function finish(observation) {
   if (finished) return;
   finished = true;
   if (watcher) watcher.close();
   if (timer) clearTimeout(timer);
   process.stdout.write(JSON.stringify(snapshot(observation), null, 2));
}

const initial = snapshot('initial');
if (initial.readError || initial.rotationLost || initial.truncated || initial.output) {
   process.stdout.write(JSON.stringify(initial, null, 2));
} else {
   try {
      watcher = fs.watch(path.dirname(file), (_event, changedFile) => {
         if (!changedFile || String(changedFile) === path.basename(file)) finish('change');
      });
      watcher.on('error', () => finish('watch-error'));
      timer = setTimeout(() => finish('interval'), observationMs);
   } catch {
      finish('watch-error');
   }
}
NODE

Use only the returned output for this cycle. fileMissing: true means the logger may have renamed port-unknown; rediscover sessions instead of advancing the cursor. Any other non-null readError, or observation: watch-error, is not a clean cycle: report the bounded error code and stop rather than polling rapidly. Otherwise immediately persist the current logPath, pid, port, nextCursor, and a new updatedAt to metro-cursor.json, even when output is empty or contains an error; this prevents duplicate processing after interruption and handles file replacement safely.

Count a clean cycle only when readError is null, observation: interval, observedMs >= 5000, and output is empty or contains no classifiable error. An early change observation with informational output is not yet a full clean interval; process it and start the next collection cycle. If the log file changes, the PID/port check becomes contradictory, or the cursor resets because the file shrank/rotated, never count that cycle as clean.

If truncated: true, never count the result as clean. Process any nonempty output, then issue at most three additional tail calls from the returned cursor in the same cycle. If rotationLost: true, record an explicit rotation warning in fixes.md and require a fresh full observation interval before incrementing the clean counter. If data remains truncated after four chunks, record a backlog warning and continue next cycle rather than consuming unbounded context.

In the new output, surface as classifiable signal and update the matching health.json domain:

Interpretation rule for host diagnostic lines:

Step B β€” Classify each new log entry

Telemetry checkpoint: classify_runtime_failures

Apply the 8-category table. Treat each unique stack trace / error message as one issue.

| Priority | Pattern | Category |

|---|---|---|

| Critical | Uncaught exception, unhandled promise rejection, app crash | JS Runtime |

| Critical | Unable to resolve module, Cannot find module | Import / Bundle |

| Critical | SyntaxError, Unexpected token, transform failed (multi-line block from Metro terminal, primary mode only) | Import / Bundle |

| Critical | Cannot read properties of undefined, is not a function | JS Runtime |

| High | NATIVE_MODULE_MISSING from pdfViewer or penInput wrapper | Native |

| High | NATIVE_MODULE_MISSING, PERMISSION_DENIED, or TRACKING_FAILED from geolocation wrapper | Native |

| High | INVALID_URL from pdfViewer, or logs mentioning content://, blob:, or http:// PDF viewer input | JS Runtime |

| High | VIEWER_FAILED or CAPTURE_FAILED from PDF/pen wrapper | Native |

| High | ERROR level runtime log | JS Runtime |

| High | HTTP 4xx / 5xx surfaced in logs | Network / API |

| High | Native module or bridge error | Native |

| Medium | React Warning: component error | React |

| Low | WARN level log that is not known noise | General |

Parsing the multi-line bundle/transform block (primary mode): Metro prints these as a banner (e.g., error: Bundling failed, iOS Bundling failed) followed by an indented block. Unlike runtime stacks, the file:line is on the first non-banner line of the block, formatted as <absolute or relative path>:<line>:<col>. There are usually no at <fn> stack frames. Example to recognize:

iOS Bundling failed 412ms
SyntaxError: /Users/.../app/(tabs)/todos.tsx: Unexpected token (47:12)
  45 |   return (
  46 |     <YStack>
> 47 |       <Text>{title</Text>
     |             ^
  48 |     </YStack>
  49 |   );

Take app/(tabs)/todos.tsx:47:12 as the fix site. The recipes in D3.1 below operate on this format.

Ignore known-noisy lines:

Step C β€” If NO issues found

Telemetry checkpoint: confirm_runtime_health

Increment the consecutive-clean-cycle counter.

Before exiting at targetCleanCycles, check the symptom guard. Read .powernative/debug-app/symptom-state and pick the matching exit path below. (If no symptom-driven mode was used this session, Phase 0.1 cleared the file at startup, so the "file missing" branch fires.)

Before every clean, flagged, pending, timeout, iteration-cap, or escalation exit, print this sanitized health table from health.json:

Health
Bundle             <status>  <summary>
Runtime            <status>  <summary>
Authentication     <status>  <summary>
Dataverse          <status>  <summary>
Connector          <status>  <summary>
Offline            <status>  <summary>
Navigation         <status>  <summary>
Native capability  <status>  <summary>

Keep unknown when no evidence was observed and not-configured only when configuration absence was positively detected. Apply the persistence redaction gate to every summary. A clean log interval does not make all unknown domains healthy.

resolved OR file missing (no symptom mode this session):

βœ“ App is running cleanly β€” no errors detected across <targetCleanCycles> consecutive log checks.
  Symptom verification: <PASS | n/a β€” no symptom provided>.
   Session summary written to .powernative/debug-app/fixes.md.

  To resume monitoring, run /debug-app again.

flagged (Phase 0.5 found a real problem that needs another skill):

⚠ Logs are clean BUT the symptom isn't fixed β€” it requires another skill.
  Symptom: <class> on <screen>
  Next step: <skill route recorded in unresolved.md by Phase 0.5> (e.g., run /add-connector)
   Details: .powernative/debug-app/unresolved.md

  Re-run /debug-app "<symptom>" after taking that step to verify the fix.

Do NOT print the green βœ“ β€” the app is technically log-clean but the user-visible problem persists, and the user needs to act before re-running.

pending (still active after targetCleanCycles clean log cycles):

Append to unresolved.md with the Phase 0.5 chain findings, then print:

"⚠ Symptom <class> on <screen> still active after <targetCleanCycles> clean log cycles. The runtime is quiet but the user-visible problem persists β€” likely a swallowed data-path error. See .powernative/debug-app/unresolved.md for the chain walk. Suggested next step: <derived from the walk>."


Exit the loop. Do NOT auto-resume.

Iteration cap (applies in both modes): independent of the clean-cycle counter and timeout, the loop exits after 50 total cycles. Track cycle: <N> at the top of fixes.md and increment per cycle. On cap-hit, exit with:

"⚠ Loop reached the iteration cap (50 cycles). Symptom may be intermittent OR a fix is regressing on every reload. See .powernative/debug-app/fixes.md for the per-cycle log. Suggested next step: review the last 3 fixes for circular regressions, or re-run with a more specific symptom."

If counter is below targetCleanCycles and the cap has not tripped, return to Step A. Its foreground file watcher provides the observation interval; do not add shell sleep, a host-specific wait command, or a rapid polling loop.

Step D β€” If issues ARE found

Telemetry checkpoint: repair_and_verify_runtime_issue

Reset the consecutive-clean counter to 0. For each issue, work through the sequence below one at a time before moving to the next.

D0. Watch-only branch (`--no-fix`)

When noFix=true, do not continue to D1–D4 for mutation:

  1. Record the category, a minimal sanitized error summary, the project-relative top user-code frame when available, and the fix recipe or handoff that would have been used. Apply the persistence redaction gate before writing.
  2. Append:

```text

[<HH:MM:SS>] Observed (no-fix) β€” <category> β€” <file:line|no user frame> β€” <summary>

Would do: <inline fix recipe | skill handoff | manual native action>

```

  1. Do not edit project source/configuration, inject traces, type-check, reload, install, regenerate, switch accounts, or invoke another skill. Updating .powernative/debug-app/ cursor, audit, and health files is allowed.
  2. Continue to the next issue, then return to Step A. New output is still monitored until the clean target, timeout, stop, or iteration cap is reached.
D1. Gather context

Use the current Step A output block. Note whether the log shows:

For JS Runtime / React errors, the stack trace in the terminal IS the context. Read the topmost user-code frame to locate the file.

For crashes or blank screens with no terminal output: ask the user:

"Do you see anything on screen β€” error boundary, blank white, or loading spinner? Please copy any visible error text."

D2. Root-cause analysis

Read the relevant source file(s). Identify:

Dataverse / Power Platform diagnostic sequence (before handoff):

  1. Read skills/add-dataverse/references/dataverse-reference.md. Use memory-bank.md and the relevant native-app-plan.md sections when present.
  2. Read power.config.json; take environmentId from it before any other source. Inspect the relevant generated service/model and connectorSchemas.ts.
  3. Resolve the environment read-only:

```bash

node "${PLUGIN_ROOT}/scripts/resolve-environment.js" "<environmentId-or-url>"

```

If resolution fails, run $PA auth status --json. Never switch accounts, log out, or open login from /debug-app without user confirmation.

  1. When environment resolution succeeds and live evidence is required, use only read-only GET requests through:

```bash

node "${PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> GET <apiPath> \

--tenant-id '<resolved-tenant-id>'

```

Start with WhoAmI when authentication/tenant identity is in question. Use bounded metadata/entity reads to confirm table and column names. Do not create, update, delete, publish, seed, flood, or intentionally invalidate credentials from /debug-app.

  1. App runtime data fixes must continue to use generated <Table>Service calls. Never replace them with direct fetch/axios Dataverse calls.
  2. If OData syntax, lookup behavior, choice/virtual/file/image fields, authentication, throttling, or error shape remains uncertain, query Microsoft Learn with the exact error/token before forming a fix.

Only after this sequence proves that a table/column/service/schema artifact is missing or incompatible should D3 route to /add-dataverse.

Expo / Expo Router / React Native diagnostic sequence:

  1. Read the cited app file plus package.json, app.json/app.config.js, and route layout only as relevant.
  2. Prefer installed package types/readmes for the exact version.
  3. If behavior remains uncertain, use a targeted WebFetch against official https://docs.expo.dev/ documentation (Expo Router pages for routing; SDK pages for native modules). Do not query Microsoft Learn for Expo/React Native behavior.

First-party native package ownership gate:

Apply this gate before D3 whenever the failing stack, module, or export involves an installed package whose name matches @microsoft/power-apps-native-*.

  1. Treat a node_modules/ frame as a lead only. Read the app call site, the installed package's public types/readme/exports, and the declared and lockfile-resolved package version. Check that the app uses a documented API with supported inputs and configuration.
  2. Classify the problem as customer code when correcting the caller, input, or supported configuration resolves the contract violation. Apply the normal D3 route in that case.
  3. Classify the problem as package-owned only when the supported app call is valid and the failure is caused by package-internal implementation, a missing/broken advertised export, or an internal package import. If ownership remains uncertain, do not patch either side; record the uncertainty and escalate.
  4. For a confirmed package-owned defect, stop automated fix attempts for that issue. Do not change app source, configuration, dependency resolution, or installed package contents to compensate. Capture only the package name, declared/resolved version, platform, minimal reproduction, expected/actual behavior, and a sanitized bounded stack/error summary. Then route the user to /report-issue; mention an official published fix or documented workaround when one is known, but do not apply it from /debug-app.
D3. Apply the fix

For Import / Bundle category errors, jump to D3.1 first β€” those have specific recipes that pre-empt the generic routing table below. For everything else (JS Runtime, Network/API, React, etc.), use the routing table:

| Error location / category | Action |

|---|---|

| app/ screen file, _layout.tsx, route segment | Inline edit via Edit tool |

| src/components/ | Inline edit via Edit tool |

| src/hooks/, src/services/ | Inline edit via Edit tool |

| src/generated/ | Do not edit. Hand off service/model repair to the owning data-source skill using CLI refresh; npm run generate-schemas only regenerates the runtime connector map. Do not re-add an intentionally retired source. |

| Dataverse schema (column/table missing) | Run D2's read-only Dataverse diagnostic sequence first. If live metadata/generated artifacts confirm the schema or service is missing, hand off to /add-dataverse. Do not mutate Dataverse or edit generated files from /debug-app. |

| Auth / MSAL (AADSTS65001, AADSTS50011) | Hand-off: route user to the Power Apps Wrap page via /set-app-registration-native. Do not auto-edit registrations. |

| Connection / connector reference missing | Hand-off: route user to /list-connections or /add-connector. |

| Confirmed defect inside @microsoft/power-apps-native-* | Do not fix in the customer project. Emit the package-defect report below and route to /report-issue. This route takes precedence over native, import/bundle, and unrecognized-error recipes. |

| Native module, app.config.js, app.plugin.js, Podfile, build.gradle | Inform the user. Do NOT auto-edit native config β€” print the error + suggested action and skip to next issue. |

| Unrecognized error pattern | Best-effort autonomous fix β€” see D3.2 below. The skill attempts a single named hypothesis instead of stopping; the existing 2-attempt escalation rule is the safety net. |

PDF/pen/geolocation-specific routing:

For inline edits, keep the change minimal and surgical. Do not refactor surrounding code, rename symbols, or change component contracts.

For a confirmed first-party native package defect, do not append a successful fix entry. Pass this report through the persistence redaction gate, append it to .powernative/debug-app/unresolved.md, clean up injected traces, and stop the loop so /report-issue can run:

Confirmed first-party native package defect β€” no customer-project workaround applied
Package: <@microsoft/power-apps-native-*>
Declared/resolved version: <declared> / <resolved>
Platform: <ios|android>
Reproduction: <minimal sanitized steps>
Expected: <bounded behavior>
Actual: <bounded error/status>
Ownership evidence: <why the documented caller contract is satisfied and the failure is package-internal>
Next step: /report-issue "<package>: <sanitized summary>"

Append to .powernative/debug-app/fixes.md:

[<HH:MM:SS>] <category> β€” <file>:<line> β€” <one-line description of fix>
D3.1 Bundle / transform error fix recipes (Import / Bundle category)

These recipes apply to errors classified as "Import / Bundle" in Step B. They are read from the persisted .powernative Metro log. Each recipe is opinionated: take the action listed if its precondition matches, otherwise fall through to the next.

Release-aware diagnosis. Read

release lifecycle and

resolve the app read-only before attributing native import/module/ABI failures:

cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
node "${PLUGIN_ROOT}/scripts/resolve-mobile-release.js" --project-root '<working_dir>'

This strict command is diagnostic evidence, not permission to stop diagnosis

or prevent the app from being tried. If Dev Player reports a missing/incorrect

native module or ABI mismatch, compare the actual Player runtime and installed

package versions, including any extra native packages. Correlate a resolver

failure with that observed symptom before proposing repair. Local workflows

may intentionally arrive here with unverified compatibility warnings.

Use only the sanitized tuple in diagnostic handoffs. The newest bundled

template is not this app's runtime allowlist. Unknown/missing records block

native mutations, not source-only diagnosis and fixes; mark native compatibility

unverified. User consent to a dependency install does not waive this gate.

Never install controls, a native leaf, Expo, or a newer host to fix an older

player/base; route verified-release migrations to /check-updates.

For controls, read the conditional contract:

the root is metadata, /pdf, /pen, and /geolocation are public runtime

subpaths, and there is no barcode subpath. Use a leaf only when its matching

version is in the resolved release. Native wrappers guard the platform before

lazy imports. A missing native module or OS declaration is not solved by a JS

fallback, runtime grant, or enableNativeControls on host 0.4.0 (unsupported).

Package inclusion, declarations, grants, and use are separate; disabling

controls does not remove default Android permissions.

Before applying any recipe, run the first-party native package ownership gate when the cited source/importer or failed internal import is under node_modules/@microsoft/power-apps-native-*. A confirmed package-owned defect routes to /report-issue; never repair it with a resolver alias, copied source, patch, postinstall rewrite, or replacement dependency.

| Error pattern | Precondition | Action |

|---|---|---|

| SyntaxError: <file>:<line>:<col> in app/, src/components/, src/hooks/, src/services/ | The cited line is in editable user code (NOT src/generated/, NOT node_modules/) | Read the file around the cited line (Β±10 lines), identify the syntactic issue (unclosed JSX tag, missing closing brace/paren, stray comma, missing from in import, unterminated string, missing semicolon between statements), apply a single minimal Edit. Do NOT reformat surrounding code. |

| SyntaxError in src/generated/ | Cited file is under src/generated/ | Do not edit. For connectorSchemas.ts, regenerate the runtime map. For services/models, resolve the existing registration and hand off to /add-connector or /add-dataverse with --refresh --data-source-name "<registered-name>", the absolute app root, and approved scope for targeted CLI refresh and validation. Check the approved plan first: a removed source needs consumer cleanup through /edit-app, not re-registration. Missing/ambiguous registrations block refresh; do not fall back to addition. |

| Unable to resolve module <name> from <importer> | <name> starts with . or .. (relative import) | Glob the importer's directory for files matching <name> with any extension (.ts, .tsx, .js, .jsx, .json). If found with a different extension β†’ fix the import to drop the extension OR match the actual one. If found with a typo (Levenshtein ≀ 2) β†’ fix the typo. If not found at all β†’ the file genuinely doesn't exist; surface to user and ask whether to create it or remove the import. |

| Unable to resolve module <name> | <name> is a bare package AND not present in package.json dependencies / devDependencies | Follow CODE5 to classify the published package by contents, not its name. If native-bound and absent from the app's verified runtime, report that a template/runtime update is required; unresolved classification also blocks installation. If verified pure JavaScript, ask consent for the exact version compatible with this app, install with npm install --save-exact, validate, and retry. Do NOT install without consent. |

| Unable to resolve module <name> | <name> IS in package.json but the bundle still fails | Run the targeted startup inspection before blaming cache: compare locked/installed versions, resolve the exact entry point, and check the app-matched release. Restore only with approval when installation is broken; unsupported exports, controls root/subpath mismatches or native build mismatches need different remedies. |

| transform failed referencing a babel plugin (e.g., [BABEL] ... unknown plugin "react-native-reanimated/plugin") | Error references babel.config.js | Hand-off. babel.config.js is project config (same constraint that protects app.config.js). Print the cited plugin and suggested fix order (e.g., "react-native-reanimated/plugin MUST be the LAST plugin in babel.config.js plugins array"); skip to next issue. |

| transform failed without a babel reference | Generic transform failure (often a TS feature Metro's transformer can't handle) | Read the cited file, look for syntax that requires a specific TS lib (e.g., decorators, top-level await). If the issue is a known-bad pattern, surface and ask before fixing. Otherwise hand-off. |

| predev script failure (e.g., npm run generate-schemas errored before expo start ran) | Output shows failure before Metro started | Use startup diagnostics to identify the failed stage (installation, config, schema generation, or type-check). Do not assume a connector problem or edit power.config.json directly. |

| [BABEL] ... You're trying to use the @babel/plugin-X plugin twice | Duplicate babel plugin entries | Hand-off for the same reason as above β€” babel.config.js is project config. Surface the duplicate; let the user dedupe. |

After applying any inline edit (rows 1, 3, 4 above), Metro auto-detects the file save and re-bundles. Skip directly to D4 β€” do NOT manually trigger a reload. The verify step picks up Metro's Bundling complete (or the next error block) automatically.

Append to .powernative/debug-app/fixes.md:

[<HH:MM:SS>] Import/Bundle β€” <file>:<line> β€” <recipe applied>
D3.2 Best-effort fix recipe for uncategorized errors

When an error falls through every row of Step B's classification table AND every row of D3.1's bundle recipes, the skill still attempts a fix instead of stopping. The discipline below keeps best-effort from degrading into wild guessing.

Step 1 β€” Locate the cite. Try in order; stop at the first that yields a file:line in editable user code:

  1. Stack trace top user-frame β€” walk the stack from the top, skip frames in node_modules/, src/generated/, and React/Hermes internals (react-native/, hermes-engine/, metro/). First remaining frame is the cite.
  2. Multi-line bundle block β€” see Step B's parsing note (file:line on the first non-banner line).
  3. Verbatim grep across the repo β€” Grep for the exact error message text (or its most distinctive 4–6 word phrase, with regex special chars escaped) across app/, src/components/, src/hooks/, src/services/. A match at a throw new Error('...') site IS the cite.
  4. Module + symbol grep β€” if the error mentions a function or component name (e.g., useFoo is not a function), Grep for the symbol; the unique declaration site is the cite.

If no cite can be located by step 4: log a structured note to .powernative/debug-app/unresolved.md (minimal sanitized error summary + which lookup attempts ran), surface to the user, advance to next issue. Do not guess at a file. Best-effort still requires a target.

Step 2 β€” Enrich understanding (do not skip).

Step 3 β€” Form ONE named hypothesis. Write it to .powernative/debug-app/fixes.md BEFORE editing, in this format:

[<HH:MM:SS>] Hypothesis (best-effort) β€” <file>:<line> β€” <one-sentence theory>
   Evidence: <sanitized error code/summary + what in the cited code led you here>
  Planned change: <what you'll edit, in 1 line>

Examples of acceptable hypotheses:

NOT acceptable (refuse to apply, escalate instead):

Step 4 β€” Apply a single minimal edit. One Edit call, smallest possible diff that implements the planned change. Do NOT change unrelated code, rename symbols, or refactor surrounding structure. Re-confirm the file path is in editable user code (NOT under src/generated/, node_modules/, or any path in the Constraints section's protected list).

Step 5 β€” Defer to D4 verify. The existing verify cycle (type-check + reload + re-poll) decides whether the hypothesis was right. Do NOT preemptively try a second hypothesis "just in case."

Step 6 β€” On verify failure, ONE alternative is allowed. If D4 shows the same error reappearing, you may form ONE alternative hypothesis (this counts as fix attempt #2 against the original error). If THAT also fails, the existing Escalation rule trips and the skill stops on this error β€” surface to the user, append to unresolved.md, advance to the next issue. Do NOT chain a third hypothesis.

Constraint reminder for best-effort mode (no exceptions):

Only the separately approved, bounded startup retry in the startup reference

may start/restart the selected app's Metro session.

D4. Verify the fix

After the fix is applied:

  1. Type-check:

```bash

npm run type-check

```

If TS errors exist, fix them before continuing. Do not advance until type-check exits 0.

  1. Wait for Metro to re-bundle (Import/Bundle fix only):

For inline edits applied via D3.1, Metro auto-watches the file and triggers a re-bundle on save. Re-run the Step A cursored tail procedure for a bounded set of checks, watching for one of:

  1. Reload the app (all other fixes β€” JS Runtime, Network/API, React, etc.):

Fast Refresh should apply most inline edits. If no new bundle/runtime activity appears, instruct the user:

> "Please reload the app from the native dev-client menu, then trigger the workflow again."

After the user confirms, run the Step A cursored tail procedure to check only new output.

  1. Confirm the fix via persisted output. If the previous error pattern is absent from newly appended log bytes and no new errors appear, the fix held. If any [INJECTED-TRACE] lines are relevant, use them to confirm the data path is healthy. After confirming, clean up injected logs (Phase 0.5.5).
  1. Reset clean-cycle counter to 0 and return to Step A.

Escalation

If the same error persists after 2 fix attempts, stop and report:

⚠ Unresolved after 2 attempts: <error summary>
  File:           <path>
   Log:            <sanitized bounded error summary>
  Last fix tried: <one-line description>
  Suggested next step: <manual action>

Pass the block through the persistence redaction gate, append only the verifier's output to .powernative/debug-app/unresolved.md, and clean up any [INJECTED-TRACE] logs before exiting (Phase 0.5.5 procedure).

Do NOT attempt a third automated fix for the same error. Wait for user guidance.


Constraints

installed public contracts. Do not mutate native dependencies/config or run

local native builds, even with consent to an unrelated JS fix. No newest

template allowlist, fabricated verified release, or runtime fallback for a

missing native package. Optional permission wrapping remains deferred.

Never rewrite app.json β†’ expo.extra.powerappsNative requirements to make

the resolver accept a mismatched installation.

and bounded Metro retry in the startup reference are allowed exceptions.

No blind upgrades, lockfile deletion, Node installation, or host/MSAL patches.

data-source skill uses CLI add/refresh/remove for models/services and config;

npm run generate-schemas only rebuilds the runtime map afterward. Preserve

the approved source inventory; do not resurrect retired sources during repair.

1. The fix requires a native config change.

2. The fix requires a tenant admin action (e.g., AAD consent).

3. You have attempted a fix twice and the same error persists (escalation).

4. The fix routes to another skill (/add-dataverse, /set-app-registration-native, /list-connections).

5. Startup restoration/restart needs explicit approval or device verification.


Failure Modes

| Symptom | Likely cause | Fix |

|---|---|---|

| Phase 0 reports not-started or stopped | No live .powernative Metro log exists | Run the bounded startup diagnosis; offer approved restoration/retry only when supported by evidence |

| Phase 0 sees recent failure lines | Expo/Metro exited during startup or runtime | If no live session remains, correlate the failed launch in startup diagnostics; otherwise use the runtime baseline/supersession check before fixing |

| Phase 0 reports "Metro running but no app connected" | Device/player/QR/network issue, or the user has not opened the app | Diagnose the opening symptom without reinstalling by default; require user retry and fresh evidence |

| Loop appears stuck | Fix taking longer than expected (e.g., type-check on large project) | Wait β€” log lines should still print as the fix runs. Type stop to exit. |

| Loop exits with "iteration cap reached" | Symptom is intermittent OR a fix is regressing on every reload | Inspect the last 3 entries in fixes.md for circularity; re-run with a more specific symptom or fix manually |

| Same error keeps recurring after fix | Fast Refresh didn't apply the change, or the fix targeted the wrong file | Verify with git status; reload from the native dev-client menu; re-run |

| Same error persists after fix AND git status shows the change saved AND type-check is clean | Stale Metro transform cache | Ask the user to stop Metro, rerun npm run dev -- --clear, reload, then rerun /debug-app |

| Escalation triggered immediately | Error pattern is in a category we hand-off (auth, schema, native) | Take the suggested manual action, then re-run /debug-app |

| .powernative/debug-app/fixes.md not appearing | Phase 0 didn't run / state directory not created | Run mkdir -p .powernative/debug-app manually, re-run skill |

| "App is running cleanly" but the user still sees the problem | Symptom-driven mode was not used β€” log polling alone is blind to silent failures | Re-run as /debug-app "<describe what you see>" to trigger Phase 0.5 (console.log injection) |

| Phase 0.5 reports screen=unknown | Symptom text didn't match any route filename | Re-run with a more specific symptom (/debug-app "todos screen empty" not "data is broken"), OR navigate to the broken screen first then re-run |

| No [TRACE lines after reload | Metro cached the old bundle | Ask the user to stop Metro, rerun npm run dev -- --clear, then reload the app |

| [INJECTED-TRACE] lines left in code after session | Cleanup step was skipped | Run the Phase 0.5.5 find scan and remove each matching line |


Notes

monitoring is still a bounded foreground loop. It does not wake an idle agent

when an unrelated terminal fails. Type stop to leave the monitor.

| Behavior | Upstream | This skill |

|---|---|---|

| Log-driven monitor loop | yes | yes β€” project-local sanitized Metro log is authoritative; host terminal APIs are optional only |

| 8-category classification | yes | yes |

| Verification cycle (type-check + reload + re-poll) | yes | yes |

| Escalation after 2 attempts | yes | yes |

| Bounded polling | yes | yes β€” durable byte cursor, bounded chunks |

| Configurable consecutive-clean exit | fixed at 3 | yes β€” default 3, configurable with --cycles, and gated on symptom resolution |

| Specialist agent delegation | yes | replaced with skill routing |

| Working-dir audit log | no | yes (additional β€” .powernative/debug-app/fixes.md, injected-logs.md) |

| MS Learn fallback for unknown errors | no | yes (additional) |

| Persisted Metro/app log source (bundler errors + Hermes console + HTTP request log) | no | yes β€” survives host restarts; no MCP fallback |

| Bundle / transform error fix recipes (D3.1) | no | yes (additional) |

| Bundle-aware verify (poll Metro for Bundling complete) | no | yes (additional) |

| Best-effort autonomous fix for uncategorized errors (D3.2) | no | yes (additional) |

| Symptom-driven mode β€” console.log injection + terminal read + data-path walk | no | yes (additional β€” catches silent failures invisible to log polling; injects [INJECTED-TRACE] logs, reads terminal, cleans up logs after root cause found) |

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.