Skip to content

A plugin marketplace for GitHub Copilot and other AI agents that provides Power Platform development plugins, including reusable skills, agents, and commands for building and deploying solutions.

refactor(mobile-app): make Metro debug logs project-local (#272)

Shubham Agarwal088e6e7e6d78
diff --git a/.github/workflows/mobile-apps-script-tests.yml b/.github/workflows/mobile-apps-script-tests.yml
index 6cfa2314c..d57e228ad 100644
--- a/.github/workflows/mobile-apps-script-tests.yml
+++ b/.github/workflows/mobile-apps-script-tests.yml
@@ -36,6 +36,10 @@ jobs:
with:
node-version: ${{ matrix.node }}
+ - name: syntax-check-mobile-template
+ shell: bash
+ run: node --check plugins/mobile-apps/template/metro.config.js
+
- name: run-mobile-apps-script-tests
shell: bash
working-directory: plugins/mobile-apps
@@ -82,6 +86,13 @@ jobs:
node - <<'NODE'
const fs = require('fs');
const files = {
+ 'power.config.json': `${JSON.stringify({
+ environmentId: '',
+ appId: '',
+ appDisplayName: 'Template Quality Probe',
+ databaseReferences: {},
+ connectionReferences: {},
+ }, null, 2)}\n`,
'src/components/AliasProbe.ts': 'export const componentAliasProbe = 1;\n',
'src/native/aliasProbe.ts': 'export const nativeAliasProbe = 2;\n',
'src/generated/services/AliasProbe.ts': 'export const generatedAliasProbe = 3;\n',
@@ -98,7 +109,7 @@ jobs:
fs.writeFileSync(file, content);
}
NODE
- npx tsc --noEmit
+ npm run predev
node ../scripts/validate-mobile-files.js \
--project-root . \
--all-source
diff --git a/plugins/mobile-apps/AGENTS.md b/plugins/mobile-apps/AGENTS.md
index 04a9ec115..51a0c4832 100644
--- a/plugins/mobile-apps/AGENTS.md
+++ b/plugins/mobile-apps/AGENTS.md
@@ -36,8 +36,8 @@ The Expo template snapshot ships bundled inside this plugin at `template/`. It i
| Edit | Purpose |
|---|---|
-| `app.config.js`: `name`, `slug` | Replace `'Power Apps Dev Player'` / `'powerapps-dev-player'` with wizard answers |
-| `package.json`: `name` | Replace `'powerapps-dev-app'` with the app slug |
+| `app.config.js`: `name`, `slug` | Replace `'Power Apps Standalone App'` / `'powerapps-standalone-app'` with wizard answers |
+| `package.json`: `name` | Replace `'powerapps-standalone-app'` with the app slug |
| Remove an empty placeholder `power.config.json` | Preserve populated environment configuration; `npx power-apps init` creates a missing file |
| Remove legacy example hooks and query-client files | Preserve every artifact under `src/generated/` |
| `app/_layout.tsx`: add `tamaguiConfig` + `defaultTheme` | Use host light/dark defaults until generated brand themes are explicitly wired |
@@ -73,6 +73,9 @@ Do not add preparation rewrites for `scheme`, `package`, `bundleIdentifier`, `sr
- `DONE_WITH_CONCERNS` requires at least one concern. If none, use `DONE`.
- Special early-return signals (`INDUSTRY_CONFIRM_REQUESTED:`, `DESIGN_VIBE_REQUESTED:`) pre-date this protocol and remain in effect — they are special-cased "ask the user one question and re-spawn me" handoffs, not terminal returns.
- The canonical orchestrator handler lives in [`skills/create-mobile-app/SKILL.md`](./skills/create-mobile-app/SKILL.md) Step 3.0. Future skills that spawn agents should reference it rather than duplicating the switch.
+13. **Metro lifecycle is project-local** — template `metro.config.js` delegates to `createPowerAppsMetroConfig`, whose host implementation writes sanitized `.powernative/metro-logs/` output during normal `npm run dev`; `/debug-app` locates and tails those files directly, with its cursor, health, and audit state under `.powernative/debug-app/`. Do not restore required `BashOutput`/terminal-ID behavior or host-specific project state directories. Host terminal APIs may be optional conveniences only. Never write unsanitized Metro output to disk, and never diagnose a log unless the logged PID/port still look live.
+14. **First-party native package defects are reported, not patched in customer projects** — a `node_modules/@microsoft/power-apps-native-*` frame alone is not proof of package ownership; first rule out invalid app usage against the package's public contract. Once a defect is confirmed inside one of these packages, do not edit `node_modules/`, generate `patch-package` or postinstall rewrites, vendor or fork the package, replace it with a git/tarball/local dependency, or shadow it through resolver aliases. Capture sanitized reproduction evidence and route to `/report-issue`.
+
## Telemetry
Mobile Apps bundles the canonical stdlib-only telemetry helpers from the repo-root `shared/telemetry/lib` at `scripts/lib/telemetry/lib`. Edit the shared source first, then refresh this physical copy in the same change; never copy another plugin's `ikey.json` or resolver.
@@ -93,6 +96,7 @@ Mobile Apps bundles the canonical stdlib-only telemetry helpers from the repo-ro
- ✅ Connection model: per-environment connections, with platform-specific auth (`expo-msal-intune` on native, `expo-auth-session` on web)
- ✅ Auth: `/create-mobile-app` resolves the tenant from the selected Power Platform environment (`scripts/resolve-environment.js`), writes that tenant to `auth.config.json`, then lets the user paste an app registration client ID, create one from the Power Apps Wrap page and paste it, or skip auth for later. `/set-app-registration-native` is a manual helper for the same Wrap-page + pasted-client-ID flow.
- ✅ `/add-native` v0 scope: camera, location, push, biometrics, secure-store (already in template)
+- ✅ Cross-host Metro diagnostics: user-owned `npm run dev`, port-probe liveness and stale-PID protection, sanitized project-local logs, a durable debug cursor, and read-only `status` plus foreground-loop `stop` commands
- ✅ Template is supplied as a fresh `microsoft/power-platform-skills/plugins/mobile-apps/template#main` folder before `/create-mobile-app` runs; users materialize it with `degit`, run `npm install`, then invoke the skill from that folder. The skill validates/prepares the folder and runs `npx power-apps init`.
- ✅ `brand/` directory convention: `/design-system` (Step 6.75) writes `brand/design-system.md` (spec), `brand/tokens.ts` (importable Tamagui tokens), and `brand/design-system.html` (visual gallery). Screen-builders MUST read `brand/design-system.md` if present; `## Negatives` = HARD RULES. `/create-mobile-app` Step 9b imports `brand/tokens.ts` via `skills/design-system/references/tamagui-integration.md`. Projects without `brand/` fall back to `## Design Direction` only — no breakage.
- ✅ Offline profile creation is **author-only in v0.1** — `/setup-offline-profile` and `/enable-tables-offline` POST `mobileofflineprofile` / `mobileofflineprofileitem` / `mobileofflineprofileitemassociation` to Dataverse and write `offline-profile.json` to the project, but do NOT scaffold offline runtime code (SQLite store, sync engine, write queue) into the generated app. Runtime support is gated on upstream `@microsoft/power-apps-native-host` confirmation.
diff --git a/plugins/mobile-apps/README.md b/plugins/mobile-apps/README.md
index 4fc4ec243..d75ee6054 100644
--- a/plugins/mobile-apps/README.md
+++ b/plugins/mobile-apps/README.md
@@ -92,12 +92,22 @@ connector wiring.
5. Start mobile app:
- Run the below command in a new terminal from the app directory.
+ `/create-mobile-app` starts Metro with `npm run dev`; its `predev` lifecycle
+ runs schema generation and type-checking before Expo starts.
+ The template's Metro config delegates sanitized logging to the native host package, which writes `.powernative/metro-logs/`,
+ so `/debug-app` works after switching between VS Code, Copilot CLI, and
+ Claude Code without asking for a terminal ID.
+
+ To start Metro manually instead, run the command below from the app directory.
+ Manual starts and `/debug-app` use the same `.powernative` log source.
```bash
npm run dev
```
+ The Metro config removes sensitive lines before writing logs. The complete
+ `.powernative/` folder is ignored by the template's `.gitignore`.
+
6. Preview the app by scanning the QR code with the Power Apps Developer app
- App store: https://apps.apple.com/us/app/power-apps-developer/id6753083462
@@ -145,7 +155,7 @@ After the prereq sanity check passes:
> /create-mobile-app build me a small notes app
```
-Expected: ~6 prompts (wizard + gates), then ~5 minutes of scaffolding, table creation, and parallel screen builds. End state: a working Notes app with `npm run dev` ready to go. If anything fails, the [memory bank](#glossary) remembers where you left off — re-run the same command and it resumes.
+Expected: ~6 prompts (wizard + gates), then ~5 minutes of scaffolding, table creation, and parallel screen builds. End state: a working Notes app with a project-local Metro session ready to scan and debug. If anything fails, the [memory bank](#glossary) remembers where you left off — re-run the same command and it resumes.
## Quick examples
@@ -164,7 +174,7 @@ What happens:
4. **4 approval gates** — data model → native capabilities → connectors → screens (with a visual `_plan_preview.html` of every screen before any code is written)
5. **Design system** — brand inputs (logo, brand doc, website, or free-text) → cost picker → style picker → component reference sheet → branded screen previews
6. **Scaffold + build** — validates the prepared template folder, runs `npx power-apps init`, verifies installed dependencies, generates schemas, builds Dataverse tables, wires connectors, spawns N parallel screen-builders for the TSX
-7. **Dev server** — `npm run dev` starts Metro; scan the QR with your native dev client on a device
+7. **Dev server** — the plugin starts a portable Metro session; scan the QR with your native dev client and use `/debug-app` against its persisted sanitized log
End state: a working app you can iterate on with hot reload. ~5–12 minutes for the planning gates, then scaffolding runs.
@@ -253,6 +263,7 @@ Example edit flows:
| `/add-native` | ✅ v0 | Add a supported native capability/control (camera, image-picker, barcode/QR scanner, document-picker, PDF viewer/report, pen/signature, secure-store, file-system, sharing, etc.) — verifies the module already ships in the template and writes typed wrappers under `src/native/` without installing native packages or editing `app.config.js` |
| `/list-connections` | ✅ v0 | Finds or creates a Power Platform connection ID, or resolves a solution connection reference, for `npx power-apps add-data-source`. Use when adding non-Dataverse connectors or re-binding after a 401. |
| `/edit-app` | ✅ v0 | Post-generation app editor — updates affected sections of `native-app-plan.md`, applies Dataverse/native/design/connector changes, rebuilds affected screens, runs verification, updates `memory-bank.md`, and regenerates `preview.html` when UI changed. `--plan-only` preserves the old docs-only behavior. |
+| `/debug-app` | ✅ v0 | Monitors live `.powernative/metro-logs/` files with a durable byte cursor, stores host-neutral cursor/audit/health state under `.powernative/debug-app/`, diagnoses runtime and silent data-path failures, and verifies bounded fixes without depending on host terminal IDs. |
| `/check-updates` | ✅ v0 | Standalone dependency maintenance — checks for a plugin update and restart first, then presents, approves, updates, and validates direct packages one at a time in host, other `@microsoft/*`, and remaining npm package order. |
| `/deploy` | ✅ v0 | Build + push — `npm run build` then `npx power-apps push` to the env in `power.config.json`. **Does not** drive `expo run:ios` or `expo run:android` (out of scope for v0). |
| `/open-wrap-url` | ✅ v0 | Opens the Wrap URL in browser for an app ID using `https://make.powerapps.com/environments/<envID>/wrap?appID=<appID>`. Requires both `--app-id` and `--env-id`. |
diff --git a/plugins/mobile-apps/scripts/redact-debug-diagnostic.js b/plugins/mobile-apps/scripts/redact-debug-diagnostic.js
new file mode 100644
index 000000000..011b0c59c
--- /dev/null
+++ b/plugins/mobile-apps/scripts/redact-debug-diagnostic.js
@@ -0,0 +1,71 @@
+'use strict';
+
+const os = require('node:os');
+const path = require('node:path');
+
+const MAX_OUTPUT_LENGTH = 4096;
+const headerPattern = /^(\s*)(authorization|proxy-authorization|cookie|set-cookie|x-api-key|api-key|client-secret|x-ms-token[^:\r\n]*)[ \t]*:[^\r\n]*$/gim;
+const bearerPattern = /\bBearer\s+[A-Za-z0-9._~+/-]+=*/gi;
+const jwtPattern = /\beyJ[A-Za-z0-9_-]*\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\b/g;
+const querySecretPattern = /([?&;](?:sig|se|sp|sv|code|token|access_token|refresh_token|id_token|client_secret)=)[^&#;\s]+/gi;
+const assignedSecretPattern = /(^|[^\w])((?:[\w.-]*?(?:access[_-]?token|refresh[_-]?token|id[_-]?token|token|client[_-]?secret|password|api[_-]?key|accountkey|sharedaccesskey))\s*[:=]\s*)("[^"]*"|'[^']*'|[^\s,;}]+)/gim;
+const emailPattern = /\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b/gi;
+const guidPattern = /\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b/gi;
+const providerSecretPattern = /\b(?:AKIA[0-9A-Z]{16}|ghp_[A-Za-z0-9]{30,}|sk-[A-Za-z0-9]{20,})\b/g;
+const residualPattern = /\bBearer\s+(?!\[REDACTED_SECRET\])\S+|\beyJ[A-Za-z0-9_-]*\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\b|[?&;](?:sig|se|sp|sv|code|token|access_token|refresh_token|id_token|client_secret)=(?!\[REDACTED_SECRET\])[^&#;\s]+|(?:^|[^\w])(?:[\w.-]*?(?:access[_-]?token|refresh[_-]?token|id[_-]?token|token|client[_-]?secret|password|api[_-]?key|accountkey|sharedaccesskey))\s*[:=]\s*(?!\[REDACTED_SECRET\])("[^"]*"|'[^']*'|[^\s,;}]+)/im;
+
+function argumentValue(name) {
+ const index = process.argv.indexOf(name);
+ return index >= 0 ? process.argv[index + 1] : undefined;
+}
+
+function escapeRegExp(value) {
+ return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
+}
+
+function redact(input, workingDir) {
+ let output = String(input);
+ const resolvedWorkingDir = workingDir ? path.resolve(workingDir) : process.cwd();
+ const homeDir = os.homedir();
+
+ output = output.replace(new RegExp(`${escapeRegExp(resolvedWorkingDir)}(?:[/\\\\]|$)`, 'g'), '');
+ if (homeDir && path.resolve(homeDir) !== resolvedWorkingDir) {
+ output = output.replace(
+ new RegExp(`${escapeRegExp(path.resolve(homeDir))}[/\\\\][^\\r\\n:()'"]+`, 'g'),
+ '[REDACTED_PATH]',
+ );
+ }
+
+ output = output
+ .replace(headerPattern, '$1$2: [REDACTED_HEADER]')
+ .replace(bearerPattern, 'Bearer [REDACTED_SECRET]')
+ .replace(jwtPattern, '[REDACTED_SECRET]')
+ .replace(querySecretPattern, '$1[REDACTED_SECRET]')
+ .replace(assignedSecretPattern, '$1$2[REDACTED_SECRET]')
+ .replace(providerSecretPattern, '[REDACTED_SECRET]')
+ .replace(emailPattern, '[REDACTED_EMAIL]')
+ .replace(guidPattern, '[REDACTED_ID]');
+
+ if (residualPattern.test(output)) {
+ return '[REDACTION_BLOCKED: diagnostic omitted]';
+ }
+
+ if (output.length > MAX_OUTPUT_LENGTH) {
+ output = `${output.slice(0, MAX_OUTPUT_LENGTH)}\n[TRUNCATED]`;
+ }
+
+ return output;
+}
+
+if (require.main === module) {
+ let input = '';
+ process.stdin.setEncoding('utf8');
+ process.stdin.on('data', (chunk) => {
+ input += chunk;
+ });
+ process.stdin.on('end', () => {
+ process.stdout.write(redact(input, argumentValue('--working-dir')));
+ });
+}
+
+module.exports = { redact };
diff --git a/plugins/mobile-apps/scripts/tests/metro-logging-contract.test.js b/plugins/mobile-apps/scripts/tests/metro-logging-contract.test.js
new file mode 100644
index 000000000..4254f68ed
--- /dev/null
+++ b/plugins/mobile-apps/scripts/tests/metro-logging-contract.test.js
@@ -0,0 +1,175 @@
+'use strict';
+
+const assert = require('node:assert/strict');
+const { spawnSync } = require('node:child_process');
+const fs = require('node:fs');
+const os = require('node:os');
+const path = require('node:path');
+const test = require('node:test');
+const vm = require('node:vm');
+
+function caretVersionAtLeast(value, minimum) {
+ const match = /^\^(\d+)\.(\d+)\.(\d+)$/.exec(value);
+ assert.ok(match, `expected a caret semver range, received ${value}`);
+ const actual = match.slice(1).map(Number);
+ for (let index = 0; index < minimum.length; index += 1) {
+ if (actual[index] !== minimum[index]) return actual[index] > minimum[index];
+ }
+ return true;
+}
+
+function extractMetroCollector(debugSkill) {
+ const normalizedSkill = debugSkill.replace(/\r\n?/g, '\n');
+ const collector = /node - "\$LOG_PATH" <saved-cursor> 262144 5000 <<'NODE'\n([\s\S]*?)\nNODE/.exec(normalizedSkill);
+ assert.ok(collector, 'expected the foreground Metro log collector snippet');
+ return collector[1];
+}
+
+function metroCollectorSource() {
+ const pluginRoot = path.resolve(__dirname, '..', '..');
+ const debugSkill = fs.readFileSync(path.join(pluginRoot, 'skills', 'debug-app', 'SKILL.md'), 'utf8');
+ return extractMetroCollector(debugSkill);
+}
+
+function runMetroCollector(source, logPath, cursor, observationMs) {
+ const result = spawnSync(
+ process.execPath,
+ ['-', logPath, String(cursor), '262144', String(observationMs)],
+ { input: source, encoding: 'utf8', timeout: 2000 },
+ );
+ assert.equal(result.status, 0, result.stderr || result.error?.message);
+ return JSON.parse(result.stdout);
+}
+
+test('template uses the host Metro factory that installs project-local logging', () => {
+ const pluginRoot = path.resolve(__dirname, '..', '..');
+ const workflow = fs.readFileSync(
+ path.resolve(pluginRoot, '..', '..', '.github', 'workflows', 'mobile-apps-script-tests.yml'),
+ 'utf8',
+ );
+ const metroConfig = fs.readFileSync(path.join(pluginRoot, 'template', 'metro.config.js'), 'utf8');
+ const gitignore = fs.readFileSync(path.join(pluginRoot, 'template', '.gitignore'), 'utf8');
+ const packageJson = JSON.parse(fs.readFileSync(path.join(pluginRoot, 'template', 'package.json'), 'utf8'));
+
+ assert.match(
+ metroConfig,
+ /const \{ createPowerAppsMetroConfig \} = require\('@microsoft\/power-apps-native-host\/config\/metroConfig'\);/,
+ );
+ assert.doesNotMatch(
+ metroConfig,
+ /power-apps-native-host\/metro-logger|SENSITIVE_LINE_PATTERN|appendMetroLog|process\.stdout\.write/,
+ );
+ assert.ok(
+ caretVersionAtLeast(packageJson.dependencies['@microsoft/power-apps-native-host'], [0, 2, 26]),
+ 'the host package must include the Metro logger introduced in 0.2.26',
+ );
+ assert.match(gitignore, /^\.powernative\//m);
+ assert.equal(packageJson.scripts.dev, 'expo start');
+ assert.equal(packageJson.scripts.predev, 'npm run generate-schemas && npm run type-check');
+ const workflowCoversMobileApps = /plugins\/mobile-apps\/\*\*/.test(workflow);
+ assert.ok(workflowCoversMobileApps || /plugins\/mobile-apps\/template\/metro\.config\.js/.test(workflow));
+ assert.ok(workflowCoversMobileApps || /plugins\/mobile-apps\/template\/package\.json/.test(workflow));
+ assert.match(workflow, /appDisplayName: 'Template Quality Probe'/);
+ assert.match(workflow, /npm run predev/);
+});
+
+test('skill contracts read logs and persist host-neutral state under .powernative', () => {
+ const pluginRoot = path.resolve(__dirname, '..', '..');
+ const createSkill = fs.readFileSync(path.join(pluginRoot, 'skills', 'create-mobile-app', 'SKILL.md'), 'utf8');
+ const debugSkill = fs.readFileSync(path.join(pluginRoot, 'skills', 'debug-app', 'SKILL.md'), 'utf8');
+ const deploySkill = fs.readFileSync(path.join(pluginRoot, 'skills', 'deploy', 'SKILL.md'), 'utf8');
+ const reportIssueSkill = fs.readFileSync(path.join(pluginRoot, 'skills', 'report-issue', 'SKILL.md'), 'utf8');
+ const agentsGuide = fs.readFileSync(path.join(pluginRoot, 'AGENTS.md'), 'utf8');
+
+ const createFrontmatter = createSkill.split('---', 3)[1];
+ assert.match(createFrontmatter, /allowed-tools:.*\bSkill\b/);
+ assert.match(createSkill, /\.powernative\/metro-logs/);
+ assert.match(createSkill, /npm run dev/);
+ assert.match(createSkill, /12\. Start Metro \(`npm run dev`\)/);
+ assert.match(createSkill, /createPowerAppsMetroConfig/);
+ assert.match(createSkill, /npm does not launch `expo start` when either gate fails/);
+ assert.match(createSkill, /always receives a scannable code even when Metro runs in a background terminal/);
+ assert.match(createSkill, /Do not rely on Expo's terminal-rendered QR as the only presentation path/);
+ assert.match(createSkill, /continue through the optional Step 12\.5 debug handoff and print the Step 13 summary/);
+ assert.doesNotMatch(createSkill, /stops after Step 12/);
+ assert.doesNotMatch(createSkill, /npx expo start|without rerunning the `predev` schema hook/);
+ assert.doesNotMatch(createSkill, /delegates Metro terminal output.*power-apps-native-host\/metro-logger/);
+ assert.doesNotMatch(createSkill, /scripts\/metro-session\.js|dev:expo|copy the plugin wrapper/i);
+ assert.match(debugSkill, /\.powernative\/metro-logs/);
+ assert.match(debugSkill, /\.powernative\/debug-app/);
+ assert.doesNotMatch(debugSkill, /\.claude\/debug-app/);
+ assert.match(debugSkill, /--working-dir <path>/);
+ assert.match(debugSkill, /Use `workingDir` from argument parsing as `<working_dir>`/);
+ assert.match(debugSkill, /every relative project path and command below runs from that directory/);
+ assert.match(debugSkill, /Early-return subcommands/);
+ assert.match(debugSkill, /execute only Phase 0\.0 discovery through the status branch/);
+ assert.match(debugSkill, /read `\.powernative\/debug-app\/metro-cursor\.json` only when it is nonempty valid JSON/);
+ assert.match(debugSkill, /process\.kill\(pid, 0\)/);
+ assert.match(debugSkill, /Treat a missing, empty, malformed, or shape-invalid file as no saved cursor/);
+ assert.match(debugSkill, /discover valid project-local Metro sessions/i);
+ assert.match(debugSkill, /"logPath":/);
+ assert.match(debugSkill, /"pid":/);
+ assert.match(debugSkill, /predates project-local Metro logging/);
+ assert.match(debugSkill, /createPowerAppsMetroConfig/);
+ assert.match(debugSkill, /factory installs project-local logging internally/);
+ assert.match(debugSkill, /exact subpath resolves from the project's installed dependencies/);
+ assert.match(debugSkill, /dependency version string alone does not prove/);
+ assert.doesNotMatch(debugSkill, /raw return value|any auth\/data props passed in|JSON\.stringify\(value\) for objects/);
+ assert.match(debugSkill, /Never log raw records, response bodies, arbitrary objects/);
+ assert.doesNotMatch(debugSkill, /recorded as `NEEDS ATTENTION`/);
+ assert.doesNotMatch(debugSkill, /status\.running|verbatim error|<exact error line>/);
+ assert.match(debugSkill, /Output contains only the logger startup line/);
+ assert.match(debugSkill, /append only the verifier's output/);
+ assert.match(debugSkill, /logging instrumentation failed/);
+ assert.match(debugSkill, /baseline read gets `ENOENT`/);
+ assert.match(debugSkill, /watcher = fs\.watch/);
+ assert.match(debugSkill, /observation: interval/);
+ assert.match(debugSkill, /a frame under `node_modules\/@microsoft\/power-apps-native-\*` is evidence, not proof/i);
+ assert.match(debugSkill, /confirmed package-owned defect routes to `\/report-issue`/i);
+ assert.match(debugSkill, /do not edit `node_modules\/`, generate `patch-package` artifacts or postinstall rewrites/i);
+ assert.match(debugSkill, /replace the dependency with a git\/tarball\/local path/i);
+ assert.match(reportIssueSkill, /collect its declared and lockfile-resolved versions from `package\.json` and `package-lock\.json`/);
+ assert.match(reportIssueSkill, /Do not read package source or metadata from `node_modules\/`/);
+ assert.match(reportIssueSkill, /### Affected native package/);
+ assert.match(agentsGuide, /First-party native package defects are reported, not patched in customer projects/);
+ assert.doesNotMatch(debugSkill, /ordinary tool execution provides the cadence/);
+ assert.doesNotThrow(() => new vm.Script(metroCollectorSource()));
+ assert.doesNotThrow(() => new vm.Script(extractMetroCollector(debugSkill.replace(/\n/g, '\r\n'))));
+ const traceScanCount = (debugSkill.match(/find app src -type f/g) || []).length;
+ const generatedExclusionCount = (debugSkill.match(/! -path 'src\/generated\/\*'/g) || []).length;
+ assert.ok(traceScanCount >= 2, 'expected trace discovery and verification scans');
+ assert.equal(generatedExclusionCount, traceScanCount, 'every trace scan must exclude generated code');
+ assert.doesNotMatch(debugSkill, /tail -n 500 "\$LOG_PATH"/);
+ assert.doesNotMatch(debugSkill, /BashOutput|METRO_TERMINAL_ID|metro-session\.js|start --project-root/);
+ assert.match(deploySkill, /\.powernative/);
+ assert.match(agentsGuide, /user-owned `npm run dev`/);
+ assert.doesNotMatch(agentsGuide, /detached project-local process|start\/status\/tail\/stop/);
+});
+
+test('Metro collector returns already-appended bytes without waiting', (context) => {
+ const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'metro-collector-backlog-'));
+ context.after(() => fs.rmSync(directory, { recursive: true, force: true }));
+ const logPath = path.join(directory, 'metro.log');
+ fs.writeFileSync(logPath, 'new output');
+
+ const result = runMetroCollector(metroCollectorSource(), logPath, 0, 1000);
+
+ assert.equal(result.observation, 'initial');
+ assert.equal(result.output, 'new output');
+ assert.equal(result.nextCursor, 10);
+ assert.equal(result.readError, null);
+});
+
+test('Metro collector waits for a complete idle observation interval', (context) => {
+ const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'metro-collector-idle-'));
+ context.after(() => fs.rmSync(directory, { recursive: true, force: true }));
+ const logPath = path.join(directory, 'metro.log');
+ fs.writeFileSync(logPath, 'existing');
+
+ const result = runMetroCollector(metroCollectorSource(), logPath, 8, 50);
+
+ assert.equal(result.observation, 'interval');
+ assert.equal(result.output, '');
+ assert.ok(result.observedMs >= 40, `expected an idle wait, received ${result.observedMs}ms`);
+ assert.equal(result.readError, null);
+});
diff --git a/plugins/mobile-apps/scripts/tests/redact-debug-diagnostic.test.js b/plugins/mobile-apps/scripts/tests/redact-debug-diagnostic.test.js
new file mode 100644
index 000000000..e9a658b50
--- /dev/null
+++ b/plugins/mobile-apps/scripts/tests/redact-debug-diagnostic.test.js
@@ -0,0 +1,71 @@
+'use strict';
+
+const assert = require('node:assert/strict');
+const os = require('node:os');
+const path = require('node:path');
+const { spawnSync } = require('node:child_process');
+const test = require('node:test');
+
+const scriptPath = path.resolve(__dirname, '..', 'redact-debug-diagnostic.js');
+const { redact } = require(scriptPath);
+
+test('keeps project paths relative and removes complete home paths with spaces', () => {
+ const workingDir = path.join(os.tmpdir(), 'debug-redaction-project');
+ const projectFile = path.join(workingDir, 'app', 'orders.tsx');
+ const homeFile = path.join(os.homedir(), 'Other Project', 'customer export.ts');
+
+ const output = redact(`${projectFile}:12:3\n${homeFile}:8:1`, workingDir);
+
+ assert.equal(output, `${path.join('app', 'orders.tsx')}:12:3\n[REDACTED_PATH]:8:1`);
+ assert.doesNotMatch(output, /Other Project|customer export/);
+});
+
+test('does not relativize a sibling path that only shares the project prefix', () => {
+ const workingDir = path.join(os.homedir(), 'app');
+ const siblingFile = path.join(os.homedir(), 'application-secrets', 'token.txt');
+
+ assert.equal(redact(`${siblingFile}:3:1`, workingDir), '[REDACTED_PATH]:3:1');
+});
+
+test('redacts headers, secrets, emails, and record identifiers', () => {
+ const output = redact([
+ 'Authorization: Bearer abc.def.ghi',
+ 'Proxy-Authorization \t: Basic dXNlcjpwYXNz',
+ 'transport failed for Bearer standalone-token',
+ 'claim=eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjMifQ.signature',
+ 'request?sig=secret&se=expiry&sp=read&sv=version&code=oauth;token=other',
+ 'my_password=hunter2 _token=token-value authToken=auth-value api_key=key-value',
+ '[email protected] 11111111-1111-1111-1111-111111111111',
+ `ghp_${'a'.repeat(30)}`,
+ ].join('\n'), path.join(os.tmpdir(), 'project'));
+
+ assert.match(output, /Authorization: \[REDACTED_HEADER\]/);
+ assert.match(output, /Proxy-Authorization: \[REDACTED_HEADER\]/);
+ assert.match(output, /transport failed for Bearer \[REDACTED_SECRET\]/);
+ assert.match(output, /claim=\[REDACTED_SECRET\]/);
+ assert.match(output, /sig=\[REDACTED_SECRET\]&se=\[REDACTED_SECRET\]&sp=\[REDACTED_SECRET\]&sv=\[REDACTED_SECRET\]&code=\[REDACTED_SECRET\];token=\[REDACTED_SECRET\]/);
+ assert.match(output, /my_password=\[REDACTED_SECRET\] _token=\[REDACTED_SECRET\] authToken=\[REDACTED_SECRET\] api_key=\[REDACTED_SECRET\]/);
+ assert.match(output, /\[REDACTED_EMAIL\] \[REDACTED_ID\]/);
+ assert.doesNotMatch(output, /dXNlcjpwYXNz|secret|expiry|read|version|oauth|other|hunter2|token-value|auth-value|key-value|owner@example\.com|11111111|ghp_/);
+});
+
+test('bounds persisted diagnostics after redaction', () => {
+ const output = redact('x'.repeat(5000), path.join(os.tmpdir(), 'project'));
+
+ assert.equal(output, `${'x'.repeat(4096)}\n[TRUNCATED]`);
+});
+
+test('CLI applies the same redaction contract', () => {
+ const workingDir = path.join(os.tmpdir(), 'debug-redaction-cli');
+ const result = spawnSync(
+ process.execPath,
+ [scriptPath, '--working-dir', workingDir],
+ {
+ input: `${path.join(workingDir, 'src', 'screen.tsx')}:4 token=secret`,
+ encoding: 'utf8',
+ },
+ );
+
+ assert.equal(result.status, 0, result.stderr);
+ assert.equal(result.stdout, `${path.join('src', 'screen.tsx')}:4 token=[REDACTED_SECRET]`);
+});
\ No newline at end of file
diff --git a/plugins/mobile-apps/scripts/tests/template-quality-contract.test.js b/plugins/mobile-apps/scripts/tests/template-quality-contract.test.js
index 2ea190eea..083a2e3fb 100644
--- a/plugins/mobile-apps/scripts/tests/template-quality-contract.test.js
+++ b/plugins/mobile-apps/scripts/tests/template-quality-contract.test.js
@@ -87,6 +87,8 @@ test('Babel and Metro configuration are delegated to native-host factories', ()
test('bundled dependencies match the current host-factory template boundary', () => {
const packageJson = JSON.parse(read('template/package.json'));
assert.strictEqual(packageJson.dependencies['@microsoft/power-apps-native-host'], '^0.3.3');
+ assert.strictEqual(packageJson.scripts.dev, 'expo start');
+ assert.strictEqual(packageJson.scripts.predev, 'npm run generate-schemas && npm run type-check');
assert.strictEqual(packageJson.dependencies['expo-media-library'], undefined);
assert.strictEqual(packageJson.dependencies['expo-modules-core'], undefined);
assert.strictEqual(packageJson.devDependencies['@microsoft/power-apps-cli'], '0.15.3');
diff --git a/plugins/mobile-apps/shared/connector-reference.md b/plugins/mobile-apps/shared/connector-reference.md
index 9a5eaa29f..70ef3fd21 100644
--- a/plugins/mobile-apps/shared/connector-reference.md
+++ b/plugins/mobile-apps/shared/connector-reference.md
@@ -101,7 +101,7 @@ npx power-apps add-flow --flow-id <flow-guid> --non-interactive
npx power-apps remove-flow --flow-id <flow-guid> --non-interactive
```
-Do not use local Expo web-player testing from mobile-app skills. Mobile-app runtime diagnosis uses the native dev-client flow and `/debug-app` reading Metro terminal output.
+Do not use local Expo web-player testing from mobile-app skills. Mobile-app runtime diagnosis uses the native dev-client flow and `/debug-app` reading the sanitized `.powernative/metro-logs/` files.
## Inspecting large generated files
diff --git a/plugins/mobile-apps/shared/memory-bank.md b/plugins/mobile-apps/shared/memory-bank.md
index e22a74f70..4a7740106 100644
--- a/plugins/mobile-apps/shared/memory-bank.md
+++ b/plugins/mobile-apps/shared/memory-bank.md
@@ -18,8 +18,8 @@ This file is the per-project notebook the agent maintains across `/create-mobile
| Working directory | |
| Plugin version that created the project | |
| Created | _<ISO date>_ |
-| Metro terminal id | _<background-shell id from Step 12 — `/debug-app` reads this terminal's output for symptom-driven native debugging only. If empty/dead, re-launch with `cd <working_dir> && npm run dev` and update this field._ |
-| Metro launch command | _e.g. `cd <working_dir> && npm run dev`_ |
+| Metro logs | `.powernative/metro-logs/` — sanitized source used by `/debug-app`; do not copy ephemeral values from log filenames into this file |
+| Metro launch command | `npm run dev` |
## Power Platform context
diff --git a/plugins/mobile-apps/shared/shared-instructions.md b/plugins/mobile-apps/shared/shared-instructions.md
index f2ebc5f9a..6dc9cfcc4 100644
--- a/plugins/mobile-apps/shared/shared-instructions.md
+++ b/plugins/mobile-apps/shared/shared-instructions.md
@@ -142,7 +142,7 @@ Never pass a directory or the whole project. Files with common text extensions (
- MUST NOT install Expo modules with `npm install <pkg>` — use `npx expo install <pkg>` so versions stay Expo-SDK-compatible.
- MUST NOT add packages with native source, podspecs, codegen configuration, Expo modules/config plugins, or platform projects unless they already exist in the template `package.json`. The wrapped binary only contains the template's native modules.
- A package name is not evidence of native code. For explicit package requests or approved use cases, pure-JavaScript libraries, including JS-only `react-native-*` packages, may be selected and added at an exact version to app runtime `dependencies`; no Android/iOS rebuild is needed. Follow the selection, approval, and install gates in [`references/javascript-dependency-planning.md`](references/javascript-dependency-planning.md).
-- MUST NOT add browser-based runtime verification steps, React Native Web setup, screen-by-screen runtime checks, route crawling, or direct Metro/localhost HTTP probes to mobile-app skills. Runtime diagnosis, when requested, uses `/debug-app` against the captured Metro terminal output.
+- MUST NOT add browser-based runtime verification steps, React Native Web setup, screen-by-screen runtime checks, route crawling, or direct Metro/localhost HTTP probes to mobile-app skills. Runtime diagnosis, when requested, uses `/debug-app` against sanitized `.powernative/metro-logs/` files.
- MUST NOT add `react-native-reanimated/plugin` anywhere except as the **last** entry in `babel.config.js` `plugins` array. Wrong order silently breaks animations.
- MUST NOT modify `app/_layout.tsx`'s provider wrapping order without re-running `npx tsc --noEmit`.
- MUST NOT make changes outside the project root without user confirmation.
diff --git a/plugins/mobile-apps/skills/create-mobile-app/SKILL.md b/plugins/mobile-apps/skills/create-mobile-app/SKILL.md
index 21f7609bf..7a5074344 100644
--- a/plugins/mobile-apps/skills/create-mobile-app/SKILL.md
+++ b/plugins/mobile-apps/skills/create-mobile-app/SKILL.md
@@ -2,7 +2,7 @@
name: create-mobile-app
description: Use when the user wants to start a new Power Apps mobile app (Expo / React Native / TypeScript, targeting iOS and Android) from scratch.
user-invocable: true
-allowed-tools: Read, Write, Edit, Bash, Glob, Grep, AskUserQuestion, Task, EnterPlanMode, ExitPlanMode
+allowed-tools: Read, Write, Edit, Bash, Glob, Grep, AskUserQuestion, Skill, Task, EnterPlanMode, ExitPlanMode
model: opus
---
@@ -14,7 +14,7 @@ Top-level orchestrator. Owns the user-visible flow; delegates planning to the `n
## Workflow
-0. Resume check + fresh-template gate → 1. Prerequisites → 2. Gather requirements → 2b. Requirements discovery → 2c. Plan preview (rough cost + abort gate) → 3. Plan (planner agent + 4 gates) → 4. Auth & environment → 5. Prepare existing template → 6. `npx power-apps init` → 6.5 verify `npm install` → **6.5b SafeAreaProvider gate (always runs, idempotent)** → 6.6 scaffold `tsc` smoke check → 6.7 seed memory bank → **6.85 Offline profile (always asked)** → 7. Auth config → 8. Apply data model → 9. Apply native capabilities → 9a. Install planned JavaScript dependencies → 9b. Design system → 10. Add connectors → 10b. Wire navigation layout → 11. Build screens (parallel) → 11.4 Stylistic fix sweep → 12. Start Metro (`npx expo start`) → 12.5 Optional debug handoff → 13. Summary
+0. Resume check + fresh-template gate → 1. Prerequisites → 2. Gather requirements → 2b. Requirements discovery → 2c. Plan preview (rough cost + abort gate) → 3. Plan (planner agent + 4 gates) → 4. Auth & environment → 5. Prepare existing template → 6. `npx power-apps init` → 6.5 verify `npm install` → **6.5b SafeAreaProvider gate (always runs, idempotent)** → 6.6 scaffold `tsc` smoke check → 6.7 seed memory bank → **6.85 Offline profile (always asked)** → 7. Auth config → 8. Apply data model → 9. Apply native capabilities → 9a. Install planned JavaScript dependencies → 9b. Design system → 10. Add connectors → 10b. Wire navigation layout → 11. Build screens (parallel) → 11.4 Stylistic fix sweep → 12. Start Metro (`npm run dev`) → 12.5 Optional debug handoff → 13. Summary
---
@@ -954,6 +954,26 @@ Substitute the hardcoded template values with wizard answers from Step 2:
Bundle ID and scheme are left as template defaults — they are fixed across all dev builds and patched by the wrap pipeline at release time.
+**Fix 1b — Verify captured dev logging path**
+
+Manual `npm run dev` must remain the normal Expo entry point. The template's `metro.config.js` delegates to `createPowerAppsMetroConfig` from `@microsoft/power-apps-native-host/config/metroConfig`; that factory installs sanitized Metro terminal and HTTP bundle-failure logging under `.powernative/metro-logs/`. Manual starts and `/debug-app` use the same log source without a process-owning wrapper. Verify these script entries only; do not add wrapper-specific scripts:
+
+```bash
+node - "<working_dir>" <<'NODE'
+const fs = require('node:fs');
+const path = require('node:path');
+const root = process.argv[2];
+const packagePath = path.join(root, 'package.json');
+const pkg = JSON.parse(fs.readFileSync(packagePath, 'utf8'));
+if (!pkg.scripts || pkg.scripts.dev !== 'expo start') {
+ throw new Error('Expected package.json scripts.dev to be "expo start". Do not route dev through a wrapper.');
+}
+if (pkg.scripts.predev !== 'npm run generate-schemas && npm run type-check') {
+ throw new Error('Expected predev to run schema generation followed by type-checking.');
+}
+NODE
+```
+
**Fix 2 — Remove only an empty placeholder `power.config.json`**
The preparation script parses `power.config.json` and removes it only when
@@ -2228,70 +2248,78 @@ After `tsc` passes, offer a static HTML preview. The dev server starts next (Ste
---
-### Step 12 — Start dev server (background)
+### Step 12 — Start dev server (Metro writes project-local logs)
**Telemetry checkpoint: `launch_metro_dev_server`**
**Print before starting:**
-> "→ [Step 12/13] Launching Metro dev server in the background so you can scan the QR."
+> "→ [Step 12/13] Launching Metro so you can scan the QR; logs will be written under .powernative/."
-This skill **launches** Metro in an async/background terminal so:
+This skill launches the template's canonical `npm run dev` command. Its `predev` lifecycle runs schema generation followed by the final TypeScript gate before Expo starts, and logging is configured in `metro.config.js`.
-1. The QR code prints in the terminal — the user can scan with their dev client immediately.
+1. Expo prints the native Metro URL and may also render a QR in its terminal. Capture the URL and generate the QR PNG below so the user always receives a scannable code even when Metro runs in a background terminal or the host does not expose terminal rendering.
2. Hot-reload works on file edits — no restart needed for screen tweaks.
-3. **The agent owns the terminal** — when the user says "the screen is blank" / "data isn't showing" / "it crashed", the agent can read Metro's `console.log`, BUNDLE errors, and red-box stack traces directly via `BashOutput` (or its equivalent terminal-output tool) without asking the user to copy-paste.
+3. `/debug-app` reads project-local `.powernative` logs regardless of whether the user or the agent started Metro. It never needs an opaque terminal ID.
+
+The native host Metro logger stores runtime-only logs under `<working_dir>/.powernative/metro-logs/`:
-**Launch commands:**
+- `metro-<timestamp>-pid-<pid>-port-<port>.log` — ANSI-free Metro output and HTTP bundle failures, with sensitive lines removed before persistence
+
+The **port** is the log identity: it is what the QR encodes, what the device dials, and what `/debug-app` probes to pick the latest live log. Expo rolls to the next free port when 8081 is taken, so always report the port discovered from the log/helper rather than assuming 8081.
+
+`.powernative/` is gitignored by the template. Do not copy these files into `memory-bank.md` or commit them.
+
+**Launch command:**
```bash
-cd <working_dir>
-npm run generate-schemas # refresh schema map for any data sources added since last run (idempotent)
-npx tsc --noEmit # final gate — dev server starts only from a clean TypeScript state
+cd "<working_dir>"
+npm run dev
```
-Run the schema regen and final `tsc` synchronously and check both exits. If either fails, do not launch Metro. Capture the full output once, batch-fix by root cause, rerun the final gate, and continue only when clean. Then launch Metro async:
+`npm run dev` runs `predev` first: `npm run generate-schemas && npm run type-check`. npm does not launch `expo start` when either gate fails. Capture the full failing gate output once, batch-fix by root cause, then rerun `npm run dev`; continue only when `predev` passes and Expo prints its Metro URL.
+
+This is a long-running dev server. In hosts that support background terminals, run it as a background/async terminal only for process lifetime; do not persist or depend on the terminal ID. `/debug-app` discovers logs from `.powernative/metro-logs/`, not from terminal output.
+
+Read the initial terminal output and locate the generated `.powernative` log directly:
```bash
-# Async / background — DO NOT block on this. Capture the terminal id.
-npx expo start
+ls -t "<working_dir>/.powernative/metro-logs"/metro-*-pid-*-port-*.log 2>/dev/null | head -1
```
-Use `npx expo start` here instead of `npm run dev` because the orchestrator has already run `npm run generate-schemas` for the final gate. The template keeps `predev: npm run generate-schemas` as a safety net for humans running `npm run dev` manually, but the orchestrated path should not regenerate schemas twice.
+Branch as follows:
-When invoking the Bash tool: set `run_in_background: true` (or the equivalent async flag in your tool surface). Capture the returned terminal/shell id as `$METRO_TERMINAL_ID`.
+| State | Action |
+|---|---|
+| Latest log exists and Expo printed a Metro URL | Continue with QR handling. Report the port from the URL/log filename to the user. |
+| No log exists yet | Wait for Expo's `Waiting on ...` line, then check the log directory once more. If still absent, print the terminal output and stop without guessing a URL. |
+| A stale log exists but no current Metro output appears | Tell the user to stop stale Metro processes and rerun `npm run dev`; do not diagnose from that log. |
-**After launch, wait ≤8s for the "Metro waiting on" line, then:**
+**When Expo prints a Metro URL:** Do not rely on Expo's terminal-rendered QR as the only presentation path.
-1. Read the terminal output once (`BashOutput` with the captured id).
-2. **Extract the native Metro URL** from the terminal output:
- - Locate the line beginning `› Metro:` — it has the form `exp+<scheme>://expo-development-client/?url=<encoded-http-url>`. Capture the full Metro URL.
-3. **Generate QR code PNG and present it to the user** (chat-first, deterministic fallback):
- - Run `npx --yes qrcode -o <working_dir>/.expo/metro-qr.png "<metro-url>"` to generate the PNG. If the project's npm config requires auth and the fetch fails with `E401`, retry once with `npm_config_registry=https://registry.npmjs.org/ npm_config_always_auth=false` prefixed.
- - Verify the PNG was created: `test -f <working_dir>/.expo/metro-qr.png` (exit code 0 = success). If it fails, print the qrcode error and continue to step 4.
- - **Chat-first render (best effort):** read and base64-encode the file (`base64 <working_dir>/.expo/metro-qr.png`) and embed in markdown as a data URI (`![QR](data:image/png;base64,<data>)`) so hosts that support inline image markdown show the QR directly in chat.
- - **Guaranteed visible fallback:** if inline chat image rendering is unavailable in the host UI, open the PNG directly in the default system image viewer/browser (`open <working_dir>/.expo/metro-qr.png` on macOS, `xdg-open ...` on Linux, `start "" ...` on Windows). This fallback is required whenever chat image rendering is unavailable.
+1. **Generate QR code PNG and present it to the user** (chat-first, deterministic fallback):
+ - Define `METRO_QR="<working_dir>/.expo/metro-qr.png"` and run `npx --yes qrcode -o "$METRO_QR" "<metro-url>"`. If the project's npm config requires auth and the fetch fails with `E401`, retry once with `npm_config_registry=https://registry.npmjs.org/ npm_config_always_auth=false` prefixed.
+ - Verify the PNG with a host-neutral Node check: `node -e "const fs=require('node:fs'); process.exit(fs.existsSync(process.argv[1]) ? 0 : 1)" "$METRO_QR"`. If it fails, print the qrcode error and continue without the image.
+ - **Chat-first render (best effort):** read and base64-encode the file with Node (`node -e "process.stdout.write(require('node:fs').readFileSync(process.argv[1]).toString('base64'))" "$METRO_QR"`) and embed in markdown as a data URI (`![QR](data:image/png;base64,<data>)`) so hosts that support inline image markdown show the QR directly in chat.
+ - **Guaranteed visible fallback:** if inline chat image rendering is unavailable, use the host's file-open tool when present. Otherwise use the quoted OS command (`open "$METRO_QR"` on macOS, `xdg-open "$METRO_QR"` on Linux, or `cmd /c start "" "$METRO_QR"` on Windows). If opening fails, print the quoted path. Never interpolate an unquoted project path.
- Surface only the native Metro URL immediately after the image/fallback message.
-4. **Optional: ASCII terminal QR for power users.** Extract and print the terminal's ASCII QR banner as a secondary/backup option:
- - Locate the first line composed of unicode block glyphs (`▀ ▄ █`) — that is the top of the QR.
- - Print every line from that line through the `› Metro:` line.
- - Cap at 30 lines as a safety net. Print as-is inside a fenced code block so terminal renderers preserve glyph alignment.
- - If the ASCII QR banner is not yet in the output, re-read `BashOutput` once more after another 4s before giving up. If still absent, skip the ASCII QR — PNG delivery from step 3 is the primary path.
-5. Follow with:
-
- > "✓ Metro is running in background terminal `<id>`.
+2. Follow with:
+
+ > "✓ Metro is running on port `<port>`.
> 📱 Scan the QR code shown above (or opened from `<working_dir>/.expo/metro-qr.png`) with your native dev client to load the app. Metro URL: `<metro-url>`
- > 🔄 Edits hot-reload automatically."
+ > 🔄 Edits hot-reload automatically. Debug logs: `<working_dir>/.powernative/metro-logs/`."
-**Persist the terminal id to memory bank** so resumed sessions and downstream skills (`/preview-screens`, `/edit-app`, `/add-*`) can find it:
+**Persist only stable discovery paths to memory bank** so resumed sessions and downstream skills can find the session without coupling to a host terminal:
```markdown
## Project facts
...
-- Metro terminal id: <id> (started <ISO date>)
-- Metro launch cmd: cd <working_dir> && npx expo start
+- Metro logs: .powernative/metro-logs/
+- Metro launch cmd: npm run dev
```
-This skill stops after Step 12 so the user can iterate locally. Production build + tenant push is a separate, explicit user action via the `/deploy` skill.
+Do not persist PIDs, ports, or Metro URLs to the memory bank. They are ephemeral and are resolved from the latest `.powernative` log when needed.
+
+After Step 12 starts the long-running server, continue through the optional Step 12.5 debug handoff and print the Step 13 summary, then return so the user can iterate locally. Production build + tenant push remains a separate, explicit user action via the `/deploy` skill.
### Step 12.5 — Optional debug handoff
@@ -2299,9 +2327,9 @@ Do not perform screen-by-screen runtime verification. Do not crawl routes, open
After Metro is running and the QR has been presented, offer a single optional debug handoff:
-> "If the app shows an error or a workflow looks wrong after you load it in the native dev client, tell me the symptom and I can run `/debug-app "<symptom>"` using the Metro terminal logs."
+> "If the app shows an error or a workflow looks wrong after you load it in the native dev client, tell me the symptom and I can run `/debug-app "<symptom>"` using the project-local Metro log."
-Only invoke `/debug-app` if the user asks for debugging or gives a concrete symptom. `/debug-app` must use the captured Metro terminal output as its diagnostic source; it must not probe `localhost`, request a bundle URL, or run any React Native Web setup. If the user gives no symptom, proceed directly to Step 13.
+Only invoke `/debug-app` if the user asks for debugging or gives a concrete symptom. `/debug-app` uses `.powernative/metro-logs/` as its primary diagnostic source; it must not request a bundle URL or run any React Native Web setup. If the user gives no symptom, proceed directly to Step 13.
When the user is ready to deploy:
@@ -2323,8 +2351,8 @@ Data model : <N tables — M reuse, K extend, L create>
Native caps : <list>
Connectors : <list>
Screens : <N total — M from template, K built in parallel>
-Dev server : npx expo start — running in background terminal <id>
- (scan QR there when you want to run locally)
+Dev server : Metro running on port <port>
+Debug logs : .powernative/metro-logs/
─────────────────────────────────────────────
```
diff --git a/plugins/mobile-apps/skills/debug-app/SKILL.md b/plugins/mobile-apps/skills/debug-app/SKILL.md
index 38f419846..7396aab35 100644
--- a/plugins/mobile-apps/skills/debug-app/SKILL.md
+++ b/plugins/mobile-apps/skills/debug-app/SKILL.md
@@ -1,8 +1,8 @@
---
name: debug-app
-description: Use when the user has finished building a mobile app, started it with `npm run dev`, and wants the running app monitored for runtime errors AND silent failures (empty lists, blank screens, swallowed network errors) and fixed autonomously. Accepts a free-text symptom (e.g., `/debug-app "todos not appearing on home screen"`) to drive terminal-log diagnostics — injects temporary console.log statements at data-path boundaries, reads Metro terminal output, and cleans up logs after the root cause is fixed. Otherwise polls the Metro terminal every 5s, classifies errors using an 8-category table, fixes inline or routes to the right skill, verifies each fix from terminal output, and exits after 3 consecutive clean polls. Foreground loop — blocks the conversation while running. Run only after the app is loaded.
+description: Use when the user has finished building a mobile app, started Metro with `npm run dev`, and wants the running app monitored for runtime errors AND silent failures (empty lists, blank screens, swallowed network errors) and fixed autonomously. Accepts a free-text symptom (e.g., `/debug-app "todos not appearing on home screen"`) to drive persisted-log diagnostics — injects temporary console.log statements at data-path boundaries, reads the sanitized `.powernative/metro-logs/` log, and cleans up logs after the root cause is fixed. Supports port/platform filtering, configurable clean-cycle and timeout limits, and watch-only `--no-fix` mode. Otherwise polls with a durable byte cursor, fixes inline or routes appropriately, verifies each fix from new output, and exits after the configured clean checks (default 3). Foreground loop — blocks the conversation while running. Run only after the app is loaded.
user-invocable: true
-allowed-tools: Read, Edit, Write, Grep, Glob, Bash, AskUserQuestion, WebFetch
+allowed-tools: Read, Edit, Write, Grep, Glob, Bash, AskUserQuestion, WebFetch, mcp__plugin_mobile-app_microsoft-learn__microsoft_docs_search
model: sonnet
---
@@ -10,46 +10,101 @@ model: sonnet
# Debug App — Monitor & Fix
-Monitor the running app by reading the Metro dev-server terminal output, 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 the Metro terminal for output, then clean them up after the root cause is fixed. Modeled on the upstream `app-debugger.agent.md` pattern — foreground loop, 5-second cadence, exit on 3 consecutive clean polls.
+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.
-> **Dev-client limitation:** the standalone dev client outputs app/runtime logs, React errors, and Metro bundler output to the terminal running `npm run dev`. This includes host runtime diagnostics that use 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:`. There is no separate device log stream. All diagnosis happens by reading that terminal and, where needed, injecting strategic trace statements into source files.
+> **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 — terminal log-driven mode.** Run Phase 0 (startup check), enter monitor loop. Log source is the Metro terminal (`BashOutput` on the `$METRO_TERMINAL_ID` recorded in `memory-bank.md` by `/create-mobile-app` Step 12). One read covers Metro bundler errors, app/runtime log lines (including host diagnostics), and red-box stack traces. If the terminal ID is not in `memory-bank.md`, ask the user which terminal is running `npm run dev` before starting. |
+| `/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 status` | Print current state (last poll, fixes applied this session, unresolved errors). Do NOT enter loop. |
-| `/debug-app stop` | If a loop is in progress, the user can type "stop" or this command to exit. State files preserved at `.claude/debug-app/`. |
+| `/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. |
-**Dispatch rule:** if `$ARGUMENTS` is non-empty and is not one of the reserved subcommand tokens (`status`, `stop`, `help`, `--help`, `-h`, `version`, `--version`), treat the entire string (everything after the command name; outer quotes optional) as the symptom and use symptom-driven mode. For `help` / `--help` / `-h`, print the subcommands table above and exit.
+### Monitoring options
-**Tip — "play around then debug":** in primary mode, `BashOutput($METRO_TERMINAL_ID)` returns Metro output accumulated since the last read. So if something weird just happened, keep using the app the way you would normally — then run `/debug-app` (or `/debug-app "<what you saw>"`) and the very first cycle will see the entire history of your session, not just what arrives after the skill starts. No need to reproduce the bug under the agent's eye.
+Options may follow the default command, a symptom, or `status`:
+
+| Option | Meaning | Default |
+|---|---|---|
+| `--working-dir <path>` | App root containing `package.json` and `metro.config.js`. 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` | Watch-only mode: classify and report, but never edit project source/config, inject traces, install dependencies, regenerate files, or invoke a mutating handoff. Debug cursor/audit/health state still advances. | Fix enabled |
+
+Examples:
+
+```text
+/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
+```
+
+**Argument parsing:**
+
+1. Parse quoted text as one symptom value and parse recognized flags wherever they appear.
+2. The first reserved token (`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`, and `--no-fix` because it does not enter the loop.
+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`. For monitoring and `status`, resolve `workingDir` to an absolute path from `--working-dir` or the current shell directory. Do not search parent directories. Require `package.json` and `metro.config.js` at that root; otherwise print the invalid path and stop before reading or writing project state. After validation, `cd` to `workingDir` once and reset it from the resulting absolute `$PWD`; 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>
+ monitorStartedAt=<current ISO timestamp>
+ ```
+
+For `help` / `--help` / `-h`, print the subcommands and monitoring-options tables and exit.
+
+**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.
+
+**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 3 consecutive clean polls confirm the app is healthy, the user types `stop`, or the escalation rule trips. **Do not run other skills concurrently** — they'll queue behind the loop.
-- **Run AFTER the app is loaded** — `npm run dev` must be running and the simulator/device must have the app open. Phase 0 verifies this; the skill stops cleanly if no app is detected.
-- **Native-only runtime target** — The app must be loaded in a native dev client on a device or simulator; Metro terminal output is the 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 Metro terminal and source files.
+- **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.
+- **Run AFTER the app is loaded** — Metro must be running through `npm run dev` and the simulator/device must have the app open. Phase 0 verifies that a live `.powernative` log exists; the skill stops cleanly if no app is detected.
+- **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** — All session state lives in `.claude/debug-app/` (gitignored): `fixes.md` for audit log, `unresolved.md` for escalations, `injected-logs.md` for tracking injected console.log statements. Survives across runs.
-- **Reference resolution order** — For unfamiliar errors: in-repo references first ([skills/add-dataverse/references/dataverse-reference.md](${PLUGIN_ROOT}/skills/add-dataverse/references/dataverse-reference.md), etc.), then `mcp__microsoft-learn__microsoft_docs_search`, then general web search.
+- **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 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 terminal APIs are optional only** — If the current host already exposes Metro terminal output, it may be consulted as a low-latency convenience. Never ask the user for a terminal ID, never persist one, and never make a diagnosis from host output without advancing the authoritative `.powernative` log cursor too.
+- **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](${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.
## Workflow — Task List First
Before entering the monitor loop, write a task list and keep it up to date:
```
-- [ ] Verify dev server is running (BashOutput on Metro terminal — expect Metro banner)
-- [ ] Capture baseline terminal state (read BashOutput, note most recent activity)
-- [ ] (Symptom mode only) Phase 0.5: parse symptom → ask user to navigate → inject console.logs → read terminal → walk data path → clean up logs
+- [ ] Discover valid `.powernative` Metro sessions and select one when needed
+- [ ] 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; stop after 3 consecutive clean cycles AND symptom resolved/flagged)
+ (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)
```
@@ -61,29 +116,96 @@ Mark each cycle complete (clean OR fixed) before starting the next.
Before entering the loop:
-### 0.0 Resolve the Metro terminal
+### 0.preflight Read project context
+
+Follow the shared instructions before diagnosing logs:
-The Metro terminal is the **only** log source. The dev-player routes all JS output there.
+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. Read `memory-bank.md` for the `Metro terminal id:` line (written by `/create-mobile-app` Step 12).
-2. If found, call `BashOutput` against that id once. If it returns any Metro output (even just the banner), set `$METRO_TERMINAL_ID` and continue.
-3. If `memory-bank.md` has no terminal id, or `BashOutput` returns "shell not found" / "no such background shell": ask the user:
- > "Which terminal is running `npm run dev`? I need its terminal ID to read Metro logs. If you started it in VS Code, look for the active terminal tab name."
- Wait for the user to provide the ID, then retry `BashOutput` against the provided id. Set `$METRO_TERMINAL_ID` and continue.
+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.
-Record the resolved id in `fixes.md`:
+Append a compact context line to `fixes.md` after Phase 0.1 creates it:
+
+```text
+[<HH:MM:SS>] Context — memory-bank=<present|absent> native-plan=<present|absent|not-needed> environment=<environmentId|none> dataverse-tables=<N> connectors=<N>
```
-[<HH:MM:SS>] Log source — Metro terminal $METRO_TERMINAL_ID
+
+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:
+
+```bash
+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:
+
+- 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`.
+- **One valid session** — select it automatically.
+- **Multiple valid sessions** — show one choice per session in this exact shape, then ask which to monitor:
+ ```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.
+- **No valid sessions** — apply the failure branches below. Stale or contradictory logs are evidence for the report, never selectable choices.
+
+**`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. Stop and report the missing config form, dependency declaration, or resolvable export. Do not enter a restart loop or edit customer-owned config from `/debug-app`; the user must adopt the current template's Metro config and host dependency first. |
+| No log exists and the current factory or legacy direct logging form resolves | If available host output contains `[powernative] Metro logging instrumentation failed`, report its phase and project-relative log path; the host deliberately fails open, so Metro can remain live without a file. Otherwise tell the user Metro is not running or has not emitted `.powernative` logs. Ask them to run `npm run dev`, open the native app, then rerun `/debug-app`. |
+
+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, that output may explain what is running, but do not ask for or store its terminal ID and do not enter the continuous monitor loop against it. Ask the user to restart with `npm run dev` so Metro config creates the log.
+
+Record the stable source in `fixes.md`:
+
+```text
+[<HH:MM:SS>] Log source — <project> <platform> — <logPath> (pid <pid>, port <port>, started <startedAt>)
```
### 0.1 Ensure state directory
```bash
-mkdir -p .claude/debug-app
-touch .claude/debug-app/fixes.md
-touch .claude/debug-app/unresolved.md
-touch .claude/debug-app/injected-logs.md
-rm -f .claude/debug-app/symptom-state # per-session — Phase 0.5 rewrites it if symptom mode is active
+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:
@@ -92,44 +214,191 @@ If `fixes.md` is empty, write a session header:
```
+Append the effective invocation settings:
+
+```text
+[<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:
+
+```json
+{
+ "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:
+
+```bash
+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`**
-Branch on the source resolved in 0.0.
+Read a bounded baseline window and return a real byte cursor:
+
+```bash
+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
+```
-**If `$METRO_TERMINAL_ID` is set (primary path):**
+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.
-Call `BashOutput` on it once and scan the captured Metro output:
+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`) but no native `Bundled` / `bundling` lines yet → Metro is up but no native client has connected. Tell the user:
+- 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.** Open the app on a device or simulator, then re-run `/debug-app`.
Stop here.
-- Output is empty, OR contains no Metro banner at all → the recorded shell is alive but Metro isn't running in it (the user repurposed the terminal). Tell the user:
- > **Metro not detected in the recorded terminal.** Restart with `npm run dev` and re-run `/debug-app` — the new terminal id will be picked up from `memory-bank.md`.
- Stop here.
+- 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:
-**If `$METRO_TERMINAL_ID` is NOT set:**
+- **Superseded** → do NOT fix. Record it and move on:
+ ```
+ [<HH:MM:SS>] Observed (already resolved, not fixed) — <error summary> — superseded by <evidence line>
+ ```
+- **Not superseded** → the error is live. Fix it normally through Step D.
+- **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.
-Ask the user:
-> "Which terminal is running `npm run dev`? Please provide the terminal ID so I can read Metro output."
+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.
-Wait for the user to reply. Set `$METRO_TERMINAL_ID` to the provided ID, call `BashOutput($METRO_TERMINAL_ID)` once, and continue with the checks above.
+**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`**
-Read the latest output from `BashOutput($METRO_TERMINAL_ID)`. Note the most recently bundled native platform (iOS / Android) and any recent runtime log lines. Append to `fixes.md`:
+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 cursor
+### 0.4 Initialize the durable byte cursor
+
+Write `.powernative/debug-app/metro-cursor.json` using structured JSON:
+
+```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.
-`BashOutput` maintains an internal stream cursor against `$METRO_TERMINAL_ID` — each call returns only output produced since the previous call. No separate cursor file is needed. The `.claude/debug-app/cursor` file is no longer used and can be ignored if present from a previous session.
+- 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`.
---
@@ -137,6 +406,8 @@ Read the latest output from `BashOutput($METRO_TERMINAL_ID)`. Note the most rece
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:
@@ -170,8 +441,8 @@ Inject targeted `console.log` statements at the boundaries of the suspected data
| 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]` a timestamp and any auth/data props passed in |
-| `wrong-data` / `stale-data` | The hook that calls the generated service (NOT inside `src/generated/`), logging `[TRACE service-response]` the raw return value |
+| `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 |
@@ -183,18 +454,19 @@ console.log('[TRACE <tag>]', <value>); // [INJECTED-TRACE]
- `<tag>` — short unique label for this site (e.g., `items`, `render`, `service-response`)
- `// [INJECTED-TRACE]` trailing comment on the SAME LINE — this is the cleanup grep key
-- Log the smallest useful value; use `JSON.stringify(value)` for objects
+- Log only primitives or a newly constructed allowlisted summary of counts, booleans, bounded error/status codes, and configured table/column names. `JSON.stringify` is allowed only for that constructed summary.
+- Never log raw records, response bodies, arbitrary objects, field values, user-entered text, auth/data prop values, identifiers, URLs, headers, or credentials. The host logger removes credential-like lines, but it cannot prove arbitrary app data is free of sensitive information.
- **Never inject inside `src/generated/`** — inject in the hook/screen that calls into it
-Record every injection in `.claude/debug-app/injected-logs.md`:
+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. Please reload the app (press `r` in the Metro terminal), navigate to `<screen>`, and trigger the symptom (e.g., scroll the list, tap the button). Reply `done` when finished."
+> "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 call `BashOutput($METRO_TERMINAL_ID)` and filter for `[TRACE` lines.
+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
@@ -214,7 +486,7 @@ Use the `[TRACE` lines to walk the chain:
3. **Generated service** (`src/generated/services/<Name>Service.ts`)
- If a TODO stub or file missing → route to `/add-connector` or `/add-dataverse`. Do NOT edit `src/generated/`.
- - If it exists and the `[TRACE service-response]` log shows an error field → read that error; 401/403 = auth issue; 404 = wrong resource name.
+ - If it exists and the `[TRACE service-response]` summary shows an error → use its bounded status/error code; 401/403 = auth issue; 404 = wrong resource name. Use separately emitted, already-sanitized host diagnostics for message context; do not add a raw error trace.
4. **Generated model** (`src/generated/models/<Name>Model.ts`)
- Confirm field names match what the screen references. `item.title` vs `cr3e9_title` produces blank rows.
@@ -223,7 +495,7 @@ Use the `[TRACE` lines to walk the chain:
- Confirm the `datasources` array contains the suspected entity / connector. If absent, `npx power-apps add-data-source` was never run for it.
6. **Auth state** (`src/playerConfig.ts`, `app.config.js`, `auth.config.json`, `useAuth()` hook)
- - 401 from the service wrapped as `{ error }` — the `[TRACE service-response]` log surfaces the error string.
+ - 401 from the service wrapped as `{ error }` — the `[TRACE service-response]` summary surfaces the status without persisting the error object or message.
- **OAuth deeplink handoff**: verify `app.config.js` → `expo.scheme` matches `src/playerConfig.ts` → `connectorOAuthRedirectUri`, AND the same redirect URI is in `auth.config.json` and the Entra ID registration. If the app registration is missing, route the user to the Power Apps Wrap page via `/set-app-registration-native`.
**Classify the `[TRACE` output:**
@@ -232,12 +504,12 @@ Use the `[TRACE` lines to walk the chain:
|---|---|---|
| `[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 error string | Service threw — read the error; 401/403 = auth; 404 = wrong resource | Fix auth config or re-run `add-data-source` |
+| `[TRACE service-response]` shows an error status/code | Service threw — 401/403 = auth; 404 = wrong resource | Fix auth config or re-run `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 user: stop Metro, run `npx expo start --clear`, reload |
+| 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 `.claude/debug-app/symptom-state` (single line: `resolved`, `flagged`, or `pending`).
+Record the outcome in `.powernative/debug-app/symptom-state` (single line: `resolved`, `flagged`, or `pending`).
- **Fix is clear and local** → apply via Step D3 + D4 (type-check + reload + re-poll). After the fix, ask the user to interact with the screen again and read the terminal. If the `[TRACE items]` line shows N > 0, write `resolved`.
- **Fix routes to another skill** → tell the user, log to `unresolved.md`. Write `flagged`.
@@ -248,17 +520,19 @@ Record the outcome in `.claude/debug-app/symptom-state` (single line: `resolved`
After the root cause is identified and a fix is applied (or Phase 0.5 concludes), remove ALL injected logs:
```bash
-grep -rn 'INJECTED-TRACE' app/ src/hooks/ src/services/
+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:
```bash
-grep -rn 'INJECTED-TRACE' app/ src/hooks/ src/services/ # must return zero results
+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:
```bash
-echo '' > .claude/debug-app/injected-logs.md
+echo '' > .powernative/debug-app/injected-logs.md
```
Run `npm run type-check` once after cleanup.
@@ -267,25 +541,122 @@ Run `npm run type-check` once after cleanup.
### 0.5.6 Re-enter the standard monitor loop
-After Phase 0.5 completes, fall through to the monitor loop (Step A). The "3 consecutive clean cycles" exit condition is **suspended** until the symptom is either marked resolved or recorded as `NEEDS ATTENTION` in `unresolved.md`. After that, the loop exits per the standard rule.
+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 **3 consecutive clean cycles**, OR the user types `stop`, OR the escalation rule trips.
+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`**
-```
-BashOutput(bash_id=$METRO_TERMINAL_ID)
+Read `.powernative/debug-app/metro-cursor.json` and rediscover all live `.powernative` sessions using Phase 0.0's validation logic.
+
+- If the saved `logPath` + `pid` + `port` is still valid, keep monitoring it even when a newer valid session has appeared. Do not interrupt the current run or jump ports.
+- If the saved session is no longer valid and exactly one valid session remains, select that session and return to Phase 0.2 for a new baseline.
+- If the saved session is no longer valid and multiple valid sessions remain, show the session choices and ask which one to monitor, then return to Phase 0.2.
+- If no valid session remains, stop with the applicable Phase 0.0 failure instead of reading a stale log.
+
+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:
+
+```bash
+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
```
-`BashOutput` returns only output produced since the previous call against the same shell — its built-in stream cursor IS the cursor.
+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.
-In the new output, surface as classifiable signal:
+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:
- Runtime ` ERROR ` / ` WARN ` / ` LOG ` prefixes
- Host diagnostic lines with prefixes like `[PAHost]`, `[bridge]`, `[AuthProvider]`, `[AuthContext]`, `[useConnectionRefs]`, `[useConnectionSetup]`, `[addAadAppToConnectionAcl]`, `[PAHost][ErrorBoundary]`
- Stack frames (`at <fn> (<file>:<line>:<col>)`)
@@ -366,14 +737,30 @@ Take `app/(tabs)/todos.tsx:47:12` as the fix site. The recipes in D3.1 below ope
Increment the consecutive-clean-cycle counter.
-**Before exiting at 3 clean cycles, check the symptom guard.** Read `.claude/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 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`:
+
+```text
+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 3 consecutive log checks.
+✓ App is running cleanly — no errors detected across <targetCleanCycles> consecutive log checks.
Symptom verification: <PASS | n/a — no symptom provided>.
- Session summary written to .claude/debug-app/fixes.md.
+ Session summary written to .powernative/debug-app/fixes.md.
To resume monitoring, run /debug-app again.
```
@@ -384,28 +771,28 @@ Increment the consecutive-clean-cycle counter.
⚠ 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: .claude/debug-app/unresolved.md
+ 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 3 clean log cycles):
+**`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 3 clean log cycles. The runtime is quiet but the user-visible problem persists — likely a swallowed data-path error. See `.claude/debug-app/unresolved.md` for the chain walk. Suggested next step: <derived from the walk>."
+> "⚠ 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, the loop exits after **50 total cycles** (≈5 min wall clock on a clean loop, longer when fixes are running). Track `cycle: <N>` at the top of `fixes.md` and increment per cycle. On cap-hit, exit with:
+**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 `.claude/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."
+> "⚠ 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 < 3 AND the cap hasn't tripped, pause 5 seconds (`sleep 5` via Bash; on Windows without bash, `Start-Sleep -Seconds 5` via `pwsh -NoProfile -Command`), then return to Step A.
+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
@@ -413,9 +800,22 @@ If counter is < 3 AND the cap hasn't tripped, pause 5 seconds (`sleep 5` via Bas
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>
+ ```
+3. 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.
+4. 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
-Read the most recent output from `BashOutput($METRO_TERMINAL_ID)`. Note whether the log shows:
+Use the current Step A `output` block. Note whether the log shows:
- A crash with a full stack trace (app is crashing)
- A React error boundary message (component threw)
- A network error or HTTP status (API/connector failure)
@@ -433,6 +833,41 @@ Read the relevant source file(s). Identify:
- Whether the fix touches the data layer, UI layer, routing, or schema.
- Whether the fix could regress other screens.
+**Dataverse / Power Platform diagnostic sequence (before handoff):**
+
+1. Read [skills/add-dataverse/references/dataverse-reference.md](../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 `npx power-apps auth-status --json`. Never switch accounts, log out, or open login from `/debug-app` without user confirmation.
+4. 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`.
+5. App runtime data fixes must continue to use generated `<Table>Service` calls. Never replace them with direct `fetch`/`axios` Dataverse calls.
+6. 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:
@@ -443,9 +878,10 @@ Read the relevant source file(s). Identify:
| `src/components/` | Inline edit via `Edit` tool |
| `src/hooks/`, `src/services/` | Inline edit via `Edit` tool |
| `src/generated/` | **Do not edit.** Fix the upstream query or schema and run `npm run generate-schemas` |
-| Dataverse schema (column/table missing) | **Hand-off:** route user to `/add-dataverse`. Do not auto-edit. Read [skills/add-dataverse/references/dataverse-reference.md](${PLUGIN_ROOT}/skills/add-dataverse/references/dataverse-reference.md) before suggesting changes. |
+| 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. |
@@ -459,14 +895,30 @@ 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.
-Append to `.claude/debug-app/fixes.md`:
+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:
+
+```text
+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 only visible in the Metro terminal (`BashOutput($METRO_TERMINAL_ID)`). Each recipe is opinionated: take the action listed if its precondition matches, otherwise fall through to the next.
+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.
+
+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 |
|---|---|---|
@@ -474,7 +926,7 @@ These recipes apply to errors classified as "Import / Bundle" in Step B. They ar
| `SyntaxError` in `src/generated/` | Cited file is under `src/generated/` | **Do not edit.** Schema regen produced bad output. Hand-off: tell the user to re-run `npm run generate-schemas`; if the error reproduces, route to `/add-connector` or `/add-dataverse` to re-add the affected datasource. |
| `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 [`shared/references/javascript-dependency-planning.md`](${PLUGIN_ROOT}/shared/references/javascript-dependency-planning.md) to classify the published package by contents, not its name. If native-bound and absent from the template, report that a template/runtime update is required. If verified pure JavaScript, ask consent for the exact version, 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 | Likely cache: instruct the user to stop the Metro terminal and re-run with `npx expo start --clear`. Do NOT auto-restart Metro from the skill — it owns Metro's lifecycle (see Constraints). |
+| `Unable to resolve module <name>` | `<name>` IS in `package.json` but the bundle still fails | Likely cache: ask the user to stop Metro, rerun `npm run dev -- --clear`, then reload. Never kill an unowned process. |
| `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) | Bundle output shows the failure happened during the `predev` lifecycle hook | This is not a code edit — `power.config.json` or the connector setup is broken. **Hand-off:** route user to `/add-connector` (for Power Platform connectors) or `/add-dataverse` (for Dataverse). Do NOT edit `power.config.json` directly. |
@@ -482,7 +934,7 @@ These recipes apply to errors classified as "Import / Bundle" in Step B. They ar
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 `.claude/debug-app/fixes.md`:
+Append to `.powernative/debug-app/fixes.md`:
```
[<HH:MM:SS>] Import/Bundle — <file>:<line> — <recipe applied>
```
@@ -498,19 +950,21 @@ When an error falls through every row of Step B's classification table AND every
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 `.claude/debug-app/unresolved.md` (verbatim error + which lookup attempts ran), surface to the user, advance to next issue. **Do not guess at a file.** Best-effort still requires a target.
+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).**
-- If the error contains a Microsoft-stack token (`AADSTS\d+`, `Dataverse`, `Power Platform`, `MSAL`, `Entra`, `Graph API`): query `mcp__microsoft-learn__microsoft_docs_search` with the exact code or token. A matching doc usually pins the fix exactly.
+- If the error contains a Microsoft-stack token (`AADSTS\d+`, `Dataverse`, `Power Platform`, `MSAL`, `Entra`, `Graph API`): first run D2's project/reference/read-only diagnostic sequence, then query `mcp__plugin_mobile-app_microsoft-learn__microsoft_docs_search` with the exact code or token when behavior remains uncertain.
+- If the error concerns Expo, Expo Router, an Expo SDK module, or React Native behavior: inspect the installed version and local package documentation, then use targeted `WebFetch` against `https://docs.expo.dev/`. Do not use Microsoft Learn for these errors.
+- If the error involves `@microsoft/power-apps-native-*`, run D2's first-party native package ownership gate. A confirmed package-owned defect is not eligible for best-effort editing.
- Read the cited file ±15 lines for surrounding context. Note recent imports, the function signature, and any nearby `try/catch` or `useEffect` deps.
- If the error mentions a third-party module (anything in `node_modules/` from the stack), one targeted `WebFetch` against the module's npm page or GitHub README is acceptable; do NOT do open-ended web searches in the loop.
-**Step 3 — Form ONE named hypothesis.** Write it to `.claude/debug-app/fixes.md` BEFORE editing, in this format:
+**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: <what in the error message + cited code led you here>
+ Evidence: <sanitized error code/summary + what in the cited code led you here>
Planned change: <what you'll edit, in 1 line>
```
@@ -547,19 +1001,19 @@ After the fix is applied:
If TS errors exist, fix them before continuing. Do not advance until type-check exits 0.
2. **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 — no manual reload needed. Poll `BashOutput($METRO_TERMINAL_ID)` every 2s for up to 30s, watching for one of:
+ 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:
- `Bundling complete` / `iOS Bundled` / `Android Bundled` → success, proceed to step 4.
- A new bundle error block (different file:line, or different message) → treat as a NEW issue and return to Step B.
- Same error repeats → the fix didn't take. Treat as fix attempt #2 against the same error (Escalation rule applies after 2).
- 30s elapsed with no bundling activity → Metro may be paused/wedged; surface to user, do NOT auto-restart Metro (Constraints).
3. **Reload the app (all other fixes — JS Runtime, Network/API, React, etc.):**
- Inline edits to runtime code require an app reload. Instruct the user:
- > "Please press `r` in the Metro terminal to reload the app."
+ 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."
- Wait ~5 seconds, then call `BashOutput($METRO_TERMINAL_ID)` to confirm the specific error line is gone from the new output.
+ After the user confirms, run the Step A cursored tail procedure to check only new output.
-4. **Confirm the fix via terminal output.** After reload, re-read `BashOutput($METRO_TERMINAL_ID)`. If the previous error pattern is absent and no new errors appear, the fix held. If any `[INJECTED-TRACE]` lines are still present and relevant, read them to confirm the data path is now healthy. After confirming, clean up any injected logs (Phase 0.5.5 procedure).
+4. **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).
5. **Reset clean-cycle counter to 0** and return to Step A.
@@ -572,12 +1026,12 @@ If the same error persists after **2 fix attempts**, stop and report:
```
⚠ Unresolved after 2 attempts: <error summary>
File: <path>
- Log: <exact error line>
+ Log: <sanitized bounded error summary>
Last fix tried: <one-line description>
Suggested next step: <manual action>
```
-Append the same block to `.claude/debug-app/unresolved.md`. Clean up any `[INJECTED-TRACE]` logs before exiting (Phase 0.5.5 procedure).
+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.
@@ -587,15 +1041,17 @@ Do NOT attempt a third automated fix for the same error. Wait for user guidance.
- **Never fix native config files** (`app.config.js`, `app.plugin.js`, `Podfile`, `build.gradle`, `gradle.properties`) — report the error to the user with the exact line and a suggested manual action.
- **Never modify `src/generated/`** — these files are auto-generated. Fix the upstream query / service / schema instead, then run `npm run generate-schemas`.
+- **Never patch or fork first-party native packages in a customer project** — for confirmed defects in `@microsoft/power-apps-native-*`, do not edit `node_modules/`, generate `patch-package` artifacts or postinstall rewrites, vendor/copy package source, generate or install a fork, replace the dependency with a git/tarball/local path, or add resolver aliases/shims that shadow the package. Route the sanitized evidence to `/report-issue`.
+- **Dataverse diagnosis is read-only** — `/debug-app` may resolve the configured environment and issue bounded Dataverse `GET` requests through the bundled scripts. It must never perform metadata/data writes, publish, seed records, intentionally trigger throttling, invalidate tokens, switch CLI accounts, or replace generated services with direct HTTP.
- **Do not ask the user about errors mid-cycle** — investigate autonomously using the tools above. Only surface to the user when:
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`).
- **One fix at a time** — fully resolve one issue (including type-check + reload + log verification) before starting the next.
-- **Always clean up injected logs** — any `// [INJECTED-TRACE]` line added during a session MUST be removed before the session ends, even if the symptom is `pending` or `flagged`. Use `grep -rn 'INJECTED-TRACE' app/ src/hooks/ src/services/` to find them.
+- **Always clean up injected logs** — any `// [INJECTED-TRACE]` line added during a session MUST be removed before the session ends, even if the symptom is `pending` or `flagged`. Use the Phase 0.5.5 `find` scan across editable `app/` and `src/` files, excluding `src/generated/`, to find them.
- **Preserve existing behavior** — fixes must be minimal and surgical. Do not refactor, rename, or change component contracts as a side effect of a bug fix.
-- **5-second pause between polls** — do not busy-loop.
+- **Bounded polling** — do not busy-loop. Every poll advances a persisted byte cursor and each cycle processes at most four 256 KiB chunks.
- **Log every action** — before each tool call, print a one-line description of what you're about to do and why, so the user can follow along.
---
@@ -604,25 +1060,25 @@ Do NOT attempt a third automated fix for the same error. Wait for user guidance.
| Symptom | Likely cause | Fix |
|---|---|---|
-| Phase 0 reports "Metro not detected" | `npm run dev` not running in the recorded terminal | Start `npm run dev` in a new terminal; the skill will ask for the terminal ID |
-| `BashOutput` returns "shell not found" for `$METRO_TERMINAL_ID` | The Metro terminal was killed or repurposed since `memory-bank.md` was written | Restart `npm run dev`; provide the new terminal ID when the skill asks |
+| Phase 0 reports `not-started` or `stopped` | No live `.powernative` Metro log exists | Run `npm run dev`, open the native app, then rerun `/debug-app` |
+| Phase 0 sees recent failure lines | Expo/Metro exited during startup or runtime | Read the latest log tail, fix the sanitized error, then ask the user to restart `npm run dev` |
| Phase 0 reports "Metro running but no app connected" | Simulator/device hasn't loaded the app yet | Open the app on the simulator/device, then re-run `/debug-app` |
| 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 | Reload didn't pick up the change, or the fix targeted the wrong file | Verify with `git status`; manually reload Metro (press `r`); re-run |
-| Same error persists after fix AND `git status` shows the change saved AND type-check is clean | Stale Metro transform cache | Stop the dev server, restart with `npx expo start --clear` to drop the cache, reload, re-run `/debug-app` |
+| 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` |
-| `.claude/debug-app/fixes.md` not appearing | Phase 0 didn't run / state directory not created | Run `mkdir -p .claude/debug-app` manually, re-run skill |
+| `.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 in terminal after reload | Metro cached the old bundle | Stop Metro, run `npx expo start --clear`, reload the app |
-| `[INJECTED-TRACE]` lines left in code after session | Cleanup step was skipped | Run `grep -rn 'INJECTED-TRACE' app/ src/hooks/ src/services/` and remove each matching line |
+| 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
-- **Designed to be re-run** — every invocation is idempotent. State files in `.claude/debug-app/` carry forward, but the cursor advances past previously-seen logs so you don't re-process old errors.
+- **Designed to be re-run** — every invocation is idempotent. `.powernative/debug-app/metro-cursor.json` advances past previously seen bytes and resets safely when a new Metro session or rotated log is detected.
- **Honest about limits** — this is a foreground loop. While it's running, you can't run other skills. By design — the model is "build first, debug second." If you need to pause, type `stop` and resume later.
- **No specialist agents** — upstream's `app-debugger.agent.md` delegates to `screen-builder`, `component-author`, `api-integration`, `dataverse-data-modeler` agents. We don't have all those agents in this plugin, so this skill fixes inline OR routes to skills (`/add-dataverse`, `/set-app-registration-native`, `/list-connections`, `/add-connector`). Behavior is equivalent for the categories we cover.
- **Host diagnostics caveat** — host-prefixed diagnostics (`[PAHost]`, `[bridge]`, `[AuthProvider]`, etc.) are expected in dev-player sessions and should be treated as first-class telemetry. If these lines are absent in non-dev-player builds, that is expected and not itself a bug.
@@ -630,16 +1086,16 @@ Do NOT attempt a third automated fix for the same error. Wait for user guidance.
| Behavior | Upstream | This skill |
|---|---|---|
- | Log-driven monitor loop | yes | yes — Metro terminal (`BashOutput($METRO_TERMINAL_ID)`) is the sole source |
+ | 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 |
- | 5s pause between polls | yes | yes |
- | Exit on 3 consecutive clean cycles | yes | yes (gated on symptom resolution when symptom-driven mode is in use) |
+ | 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 — `.claude/debug-app/fixes.md`, `injected-logs.md`) |
+ | Working-dir audit log | no | yes (additional — `.powernative/debug-app/fixes.md`, `injected-logs.md`) |
| MS Learn fallback for unknown errors | no | yes (additional) |
- | Metro terminal as log source (sees bundler errors + Hermes console + HTTP request log) | no | yes — only source; no MCP fallback |
+ | 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) |
diff --git a/plugins/mobile-apps/skills/deploy/SKILL.md b/plugins/mobile-apps/skills/deploy/SKILL.md
index c69c2d762..663fbab2c 100644
--- a/plugins/mobile-apps/skills/deploy/SKILL.md
+++ b/plugins/mobile-apps/skills/deploy/SKILL.md
@@ -18,7 +18,7 @@ This skill uses the standard 4-step deployment flow for this plugin: check memor
- `expo run:ios` / `expo run:android` — local native compile is the user's choice; run your platform-specific native command directly when ready.
- OTA updates and store distribution — out of scope for v0.
-- Starting Metro for local dev — run `npm run dev` (= `expo start`) directly.
+- Starting Metro for local dev — created apps use `npm run dev`; template Metro config writes `.powernative` logs for `/debug-app`.
## Workflow
@@ -166,7 +166,7 @@ Environment : <env-name>
App URL : <url or "see make.powerapps.com">
Bundle path : dist/
-Local dev: npm run dev (= expo start, QR for native dev clients)
+Local dev: npm run dev (writes .powernative logs for /debug-app)
Re-deploy: /deploy
List conns: /list-connections
─────────────────────────────────────────────
@@ -176,18 +176,18 @@ List conns: /list-connections
## Local dev (out of scope for this skill — for reference only)
-When the user wants to iterate locally, they run **directly**:
+When the user wants normal Expo iteration with portable monitoring, they can run:
```bash
-npm run dev # = expo start → Metro + QR for native dev clients
+npm run dev # Metro + QR + .powernative log
```
-This launches Metro and prints a QR code. They can:
+This launches Metro, prints a QR code, and writes sanitized output to `.powernative/metro-logs/` so `/debug-app` can reattach after a host/session restart. They can:
- Scan the QR with the installed native dev client
-- Press `r` to reload, `j` to open the debugger, `m` for the dev menu
+- Reload from the native dev-client menu
-Runtime debugging for this plugin uses `/debug-app` with native dev-client sessions and Metro terminal logs. Do not use React Native Web, browser automation, direct Metro/localhost HTTP probes, or screen-by-screen runtime checks.
+Do not use React Native Web, browser automation, direct Metro/localhost HTTP probes, or screen-by-screen runtime checks.
If they want to compile a native binary locally, they run the platform-specific native command directly. Local native compile and manual device testing are user-owned and are not deployment gates for this skill.
diff --git a/plugins/mobile-apps/skills/preview-screens/SKILL.md b/plugins/mobile-apps/skills/preview-screens/SKILL.md
index 7e9f04bbb..caf02ad10 100644
--- a/plugins/mobile-apps/skills/preview-screens/SKILL.md
+++ b/plugins/mobile-apps/skills/preview-screens/SKILL.md
@@ -20,7 +20,7 @@ Generates a self-contained HTML file that renders every screen in the app as a p
## When NOT to use
-- To run the actual app → use `npx expo start`
+- To run the actual app → use `npm run dev`
- To modify screens → use `/edit-app`; `screen-builder` is an internal agent invoked by orchestrator skills
## Workflow
diff --git a/plugins/mobile-apps/skills/report-issue/SKILL.md b/plugins/mobile-apps/skills/report-issue/SKILL.md
index e4fa795b9..fabb2d192 100644
--- a/plugins/mobile-apps/skills/report-issue/SKILL.md
+++ b/plugins/mobile-apps/skills/report-issue/SKILL.md
@@ -67,6 +67,24 @@ test -f native-app-plan.md && echo "plan=present"
ls src/generated/services/ 2>/dev/null | head -10
```
+If the description names a package matching `@microsoft/power-apps-native-*`, collect its declared and lockfile-resolved versions from `package.json` and `package-lock.json`. Do not read package source or metadata from `node_modules/`.
+
+```bash
+node - <<'NODE'
+const fs = require('node:fs');
+const manifest = JSON.parse(fs.readFileSync('package.json', 'utf8'));
+const lockfile = fs.existsSync('package-lock.json')
+ ? JSON.parse(fs.readFileSync('package-lock.json', 'utf8'))
+ : null;
+const dependencies = { ...manifest.dependencies, ...manifest.devDependencies };
+for (const [name, declared] of Object.entries(dependencies)) {
+ if (!name.startsWith('@microsoft/power-apps-native-')) continue;
+ const resolved = lockfile?.packages?.[`node_modules/${name}`]?.version ?? 'unknown';
+ console.log(`${name}\tdeclared=${declared}\tresolved=${resolved}`);
+}
+NODE
+```
+
For native-build issues also capture:
```bash
@@ -93,6 +111,7 @@ If the user pasted an error, capture verbatim. Otherwise look for recent failure
- Contents of `.env` or any file matching `.env*`
- Connection IDs unless the user explicitly opted in (PII / can map to tenant)
- Anything under `node_modules/`
+- Package source excerpts, patched package contents, or proposed fork code
### Step 4 — Render issue body
@@ -142,6 +161,15 @@ Print this block — user copies into a new issue:
Not run inside a mobile-app project.
</if>
+### Affected native package
+
+<include only when the issue concerns @microsoft/power-apps-native-*>
+- Package: `<package name>`
+- Declared version: `<package.json range>`
+- Resolved version: `<package-lock.json version or unknown>`
+- Platform: `<iOS / Android>`
+- Ownership evidence: <why the documented caller contract is satisfied and the failure is package-internal>
+
### Reproduction steps
1.
diff --git a/plugins/mobile-apps/template/.gitignore b/plugins/mobile-apps/template/.gitignore
index 031c286e4..038aacbc4 100644
--- a/plugins/mobile-apps/template/.gitignore
+++ b/plugins/mobile-apps/template/.gitignore
@@ -10,6 +10,7 @@ node_modules/
# ── Expo / Metro ─────────────────────────────────────────────────────────────
.expo/
+.powernative/
dist/
dist-web/
web-build/
diff --git a/plugins/mobile-apps/template/README.md b/plugins/mobile-apps/template/README.md
index d21e52402..32ce141d7 100644
--- a/plugins/mobile-apps/template/README.md
+++ b/plugins/mobile-apps/template/README.md
@@ -97,12 +97,20 @@ connector wiring.
5. Start mobile app:
- Run the below command in a new terminal from the app directory.
+ `/create-mobile-app` starts Metro with `npm run dev`; its `predev` lifecycle
+ runs schema generation and type-checking before Expo starts.
+ The template's Metro config delegates sanitized logging to the native host package, which writes `.powernative/metro-logs/`,
+ allowing `/debug-app` to work across VS Code, Copilot CLI, and Claude Code
+ without a terminal ID.
+
+ To start Metro manually instead, run the command below from the app directory.
+ Manual starts and `/debug-app` use the same `.powernative` log source.
```bash
npm run dev
```
+
6. Preview the app by scanning the QR code with the Power Apps Developer app
- App store: https://apps.apple.com/us/app/power-apps-developer/id6753083462
diff --git a/plugins/mobile-apps/template/package.json b/plugins/mobile-apps/template/package.json
index 6358b7f96..fcd4bb972 100644
--- a/plugins/mobile-apps/template/package.json
+++ b/plugins/mobile-apps/template/package.json
@@ -6,7 +6,7 @@
"dev": "expo start",
"web": "power-apps-web",
"generate-schemas": "generate-connector-schemas",
- "predev": "npm run generate-schemas",
+ "predev": "npm run generate-schemas && npm run type-check",
"type-check": "tsc --noEmit",
"build:android": "wrap android",
"build:ios": "wrap ios",