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.

fix(mobile-apps): orchestrate scoped app feature edits (#596)

Shubham Agarwal8c4b4477d21e
diff --git a/plugins/mobile-apps/AGENTS.md b/plugins/mobile-apps/AGENTS.md
index f0f90bba5..a83431d60 100644
--- a/plugins/mobile-apps/AGENTS.md
+++ b/plugins/mobile-apps/AGENTS.md
@@ -98,7 +98,7 @@ Do not add preparation rewrites for `scheme`, `package`, `bundleIdentifier`, `sr
consumer edits, use the supported removal command to update registrations,
schemas, and generated models/services, then regenerate the runtime schema
map. Never turn a removed plan row into server-table deletion. Follow
- [data-source-removal.md](shared/references/data-source-removal.md)
+ [`shared/references/data-source-removal.md`](shared/references/data-source-removal.md)
for shared-reference safety, inventory/offline reconciliation, and no-op
detection; successful exit alone is insufficient.
20. **Seed scope is not the schema inventory** — Orchestrated `/add-sample-data`
@@ -109,15 +109,28 @@ Do not add preparation rewrites for `scheme`, `package`, `bundleIdentifier`, `sr
`offlineRetirement` outcomes in leaf results and memory-bank. Addition-only
`in-sync` never clears a pending profile decision/migration. App-binding
approval is not permission to delete offline profile items or server data.
-22. **Data-only planning shares creation's helpers, not its gates** —
- Setup/standalone proposals use compact hash-bound evidence, snapshot-only
- architect context, and decision validation before the existing approval.
+22. **Dataverse change planning shares creation's helpers, not its gates** —
+ Setup/edit/standalone proposals use compact hash-bound evidence, required
+ snapshot-only architect context, and decision validation before the owner's existing approval.
The same checks apply to diagrams and inline fallbacks. Preapproval
environment resolution uses `--no-cache --require-tenant`; never downgrade
to the persistent resolver. Follow
[scoped Dataverse planning](shared/references/dataverse-change-planning.md).
- Do not fabricate the four-approval create-only execution receipt for a
- data-only change.
+ Accepted contract/plan hashes travel in the existing scoped context; do not
+ fabricate the four-approval create-only execution receipt for an edit.
+23. **Feature entry points share one edit owner** — Direct native, connector,
+ data-model, and design requests on existing apps choose implementation-only,
+ full integration, or cancellation before costly work. Approved children
+ reuse their current owner/root/phase/scope and never recurse into another
+ edit. Follow [app-edit-routing.md](shared/references/app-edit-routing.md);
+ the choice enters a workflow, not permission to mutate.
+24. **Shared entry policy is not copied into every skill** — Every new public
+ app workflow starts with a read-first link to `shared/shared-instructions.md`
+ and allows `Read`. The shared preflight classifies feature work before
+ operational commands; leaves only link to it. Invocation discovery tests
+ cover newly added skills automatically. These static checks verify the
+ instruction contract, not model compliance; do not claim smaller-model or
+ host reliability without agent-run evidence.
## Telemetry
diff --git a/plugins/mobile-apps/README.md b/plugins/mobile-apps/README.md
index a9bed701c..e3e9097de 100644
--- a/plugins/mobile-apps/README.md
+++ b/plugins/mobile-apps/README.md
@@ -196,7 +196,11 @@ End state: a working app you can iterate on with hot reload. ~5–12 minutes for
> /add-dataverse I need an Asset table with name, serial number, and a lookup to an existing Account
```
-Or paste an ER diagram (image / Mermaid / text). The data-model-architect agent discovers what already exists in your environment, scores reuse vs extend vs create, walks through approval, then creates the tables in dependency order and regenerates `src/generated/services/`.
+Or paste an ER diagram (image / Mermaid / text). For an existing app, this first
+asks whether to integrate through `/edit-app`, do data-only work, or cancel.
+Full integration approves the schema delta and affected screens together.
+The data-model-architect checks reuse vs extend vs create before the Dataverse
+leaf applies approved operations and regenerates services.
### 3. Add a native capability
@@ -204,7 +208,13 @@ Or paste an ER diagram (image / Mermaid / text). The data-model-architect agent
> /add-native camera
```
-Generates `src/native/camera.ts` (typed wrapper around `expo-camera` + `expo-image-picker`) and — if Dataverse image columns exist — a `cameraUpload.ts` helper that bridges to `Service.upload()`. The Expo modules are already in the upstream template; no `package.json` or `app.config.js` edits.
+On an existing app, `/add-native` first asks whether to do implementation-only
+work, full app integration, or cancel. Only full integration invokes `/edit-app`,
+which resolves how the camera will be used, updates the Native Capabilities and
+Screens plan, and asks about retention only when needed. It then generates the supported
+wrappers/helpers and integrates the approved screen flow. Dataverse schema
+changes are conditional, not required for every capture. Native modules must
+already ship in the template; no native dependency or permission-config edits.
For other capabilities (only those actually shipped by the template):
```text
@@ -224,14 +234,28 @@ Native modules are allowlist-bound by the current template `package.json`. If th
> /add-connector # any other Power Platform connector
```
-Runs `pa app add data-source` under the hood, regenerates services, prints how to import in your screens.
+On an existing app, these entry points ask before invoking the fuller, more
+costly `/edit-app` workflow. Choose implementation-only work, full integration,
+or cancel. Full integration clarifies the operation and consuming screens,
+approves the Connectors delta, generates services with `pa app add data-source`,
+and wires the intended behavior. Teams/email actions and profile lookups
+do not automatically create a Dataverse model. SQL/Excel/SharePoint tables
+also stay in the connector plan unless Dataverse storage is separately required.
+
+Choose implementation-only in that question, or use `--implementation-only` (for example,
+`/add-native secure-store --implementation-only`) or explicitly request only a
+wrapper/service registration. The skill keeps applicable plan entries current,
+but leaves screens unchanged and reports that integration was not performed.
+When the change is already part of an approved creation/edit workflow, the
+extra entry question is skipped. This choice runs before costly app scans or
+planners and does not replace mutation/removal approval.
### Data-source planning, refresh, and retirement
Use `/setup-datamodel` or `/add-dataverse` to review and approve a data change.
Add `--plan-only` to preview it without changing the app or its data.
-For an existing binding, use the dedicated operation instead of adding it again:
+For existing sources, use the dedicated refresh/removal operation:
```text
> /add-dataverse --refresh --data-source-name <registered-name>
@@ -241,8 +265,9 @@ For an existing binding, use the dedicated operation instead of adding it again:
Refresh updates an existing source without adding it again. Removal stops if
app code still uses the source and never deletes server tables, records, lists,
-or connections. These commands update the data layer; request screen changes
-separately through `/edit-app`. Cloud-flow integration is not supported.
+or connections. For a fully integrated removal, `/edit-app` updates the approved
+consumers before retiring their data sources. Offline-profile changes require
+separate approval. Cloud-flow integration is not supported.
### 5. Iterate on the generated app after the fact
@@ -289,7 +314,7 @@ Example edit flows:
| `/create-mobile-app` | ✅ v0 | Orchestrator — starts from a fresh installed `expo-app-standalone` template folder, gates planning, runs `pa app init`, resolves the selected environment tenant, discovers tenant-visible app registrations and checks the complete required permission profile, lets the user select or create one (or skip auth), then applies data/native/connectors, builds screens, starts dev server |
| `/set-app-registration-native` | ✅ v0 | Auth helper — discovers tenant-visible app registrations, checks the applicable native runtime permission profile, opens the environment-specific Wrap page for creation or repair, and writes the selected client ID to `auth.config.json`. |
| `/add-dataverse` | ✅ v0 | Add Dataverse — connect to existing tables, or create / extend tables in Tier 0 → N order via the Dataverse Web API, then generate TS services. Accepts ER diagrams via image / Mermaid / text, or spawns the data-model-architect agent. |
-| `/setup-datamodel` | ✅ v0 | Plan and approve a scoped Dataverse/connector change, apply only accepted data operations, refresh retained bindings, or retire app-local bindings after consumer checks. `--plan-only` returns before saving or applying. |
+| `/setup-datamodel` | ✅ v0 | Plan and approve a scoped Dataverse/connector change. Choose data-only work or full `/edit-app` integration; `--plan-only` returns a proposal without applying it. |
| `/add-connector` | ✅ v0 | Generic connector — runs `pa app add data-source` for any first-party or custom connector |
| `/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, haptics, 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 `pa app add data-source`. Use when adding non-Dataverse connectors or re-binding after a 401. |
@@ -303,7 +328,7 @@ Example edit flows:
| `/telemetry` | ✅ v0 | Enable, disable, or show the per-user Mobile Apps telemetry transmission preference. |
| `/design-system` | ✅ v0 | End-to-end design system — collects brand inputs (logo, brand doc, website, free text, canvas app, code app, Figma), runs a 3-style visual picker, writes `brand/design-system.md` + `brand/tokens.ts`, renders branded screen previews. Auto-invoked at Step 6.75 of `/create-mobile-app`; also standalone. |
| `/preview-screens` | ✅ v0 | Renders generated TSX screens as a browser-viewable HTML preview (no Metro needed). Uses Tamagui → HTML mapping. |
-| `/add-datasource` | ✅ v0 | Alias for `/add-connector` — discoverable name for "how do I connect to X?" |
+| `/add-datasource` | ✅ v0 | Intent-aware entry point for data/action integrations; asks full `/edit-app` integration vs implementation-only, then uses the approved Dataverse/SharePoint/connector leaf. |
| `/add-sharepoint`, `/add-teams`, `/add-office365`, `/add-excel`, `/add-onedrive`, `/add-azuredevops` | 🟡 v1 | Pre-filled wrappers around `/add-connector` |
| `/setup-offline-profile` | 🟡 v0.1 | Create a Dataverse Mobile Offline Profile for the app's tables. One consolidated configuration questionnaire (no per-step approval clicks), schema+screen-aware architect proposal, single `accept` confirm. Writes `offline-profile.json`; never mutates `power.config.json`. The bundled offline package is consumed by the native host for local storage, queued synchronization, reconnect handling, and status UX, so the skill configures the host runtime instead of generating duplicate app-owned offline infrastructure. Offered explicitly by `/create-mobile-app` after Dataverse materialization; connectivity wording in the initial prompt does not auto-enable it. Also runs standalone on existing apps. |
| `/enable-tables-offline` | 🟡 v0.1 | Pre-flight pass — flip `IsAvailableOffline` + `ChangeTrackingEnabled` on selected tables' EntityMetadata, then `PublishAllXml`. Idempotent. Mostly a no-op for fresh scaffolds since `/add-dataverse` Step 5b now sets these flags at create time; primary use case is fixing legacy / imported tables. |
diff --git a/plugins/mobile-apps/agents/data-model-architect.md b/plugins/mobile-apps/agents/data-model-architect.md
index b9ddbf1c4..a23a6cb0a 100644
--- a/plugins/mobile-apps/agents/data-model-architect.md
+++ b/plugins/mobile-apps/agents/data-model-architect.md
@@ -31,7 +31,7 @@ or standalone `/add-dataverse` with a prompt that includes:
- Wizard answers (target users, aesthetic, features)
- The working directory
- The plugin root
-- **Scoped change context** (setup/standalone) — current delta, retained
+- **Scoped change context** (setup/edit/standalone) — current delta, retained
native/connector constraints, `phase: planning`, and the proposal-only mode.
Existing plan rows are context, not permission to recreate unrelated tables.
- **Normalized Dataverse foreground planning snapshot path (validation only)** —
@@ -53,7 +53,7 @@ or standalone `/add-dataverse` with a prompt that includes:
## Hard Rules
- **Read-only.** You MUST NOT run `pa app add data-source --connector dataverse --org-url <env-url> --table <table>`, table-creation HTTP calls, or any mutating PowerShell. Mutation happens later in `/add-dataverse` after user approval.
-- **Scoped proposals preserve the owner.** For setup/standalone change
+- **Scoped proposals preserve the owner.** For setup/edit/standalone change
planning, use [dataverse-change-planning.md](../shared/references/dataverse-change-planning.md).
Return the proposed delta and required dependencies in `_dm_section.md` and
the normalized contract; do not copy unrelated historical creation rows into
@@ -188,9 +188,9 @@ If validation succeeds, this path is mandatory:
If either required artifact is missing, invalid, or mismatched, return
`NEEDS_CONTEXT: matching-dataverse-snapshot-and-evidence`. Do not fall back to
live discovery from `required` mode. The legacy live path below remains only
-for callers that omit the new planning mode entirely (including the existing
-`/edit-app` path). Setup/standalone data planning must not omit `required` to
-bypass missing evidence. The `cross-entity-audit` short circuit remains separate.
+for older external callers that omit the planning mode entirely. Bundled
+setup/edit/standalone planning must not omit `required` to bypass missing
+evidence. The `cross-entity-audit` short circuit remains separate.
## Step 1 — Resolve Target Environment
diff --git a/plugins/mobile-apps/agents/native-app-planner.md b/plugins/mobile-apps/agents/native-app-planner.md
index 84a5674a5..60f9e7798 100644
--- a/plugins/mobile-apps/agents/native-app-planner.md
+++ b/plugins/mobile-apps/agents/native-app-planner.md
@@ -107,7 +107,7 @@ Do NOT attempt to read `app.config.js` from the working directory — scaffoldin
From the planner prompt extract:
- **Target platforms** — always iOS + Android. The foreground does not ask the user to choose a subset; retain platform-specific fallback behavior for both.
-- **Native capability hints** — words like "scan", "photo", "camera" -> `expo-camera`; "pick file", "upload PDF", "import document", "attach file" -> `expo-document-picker`; "generate PDF", "export report", "print report", "evidence packet" -> `pdf-report` (`expo-print` plus optional `expo-sharing`); "view PDF", "open PDF", "preview PDF" -> `native-pdf-viewer` for HTTPS URLs or local `file://` URIs with `@microsoft/power-apps-native-pdf-viewer` 0.2.9+; "signature", "sign off", "approval", "pen", "ink", "draw" -> `pen-input` with `@microsoft/power-apps-native-pen-input`; "track location", "background location", "GPS tracking", "follow my route", "breadcrumb", "field worker location" -> `geolocation` with `@microsoft/power-apps-native-bglocation` (continuous/background tracking + Dataverse sync); "where am I", "current location", "one-shot location", "tag this with my coordinates" -> one-shot `location` with `expo-location`; "save token", "credentials" -> `expo-secure-store`; "share / send" -> `expo-sharing`; "save file / download" -> `expo-file-system`. **Capability hints that the template does NOT ship** (including PDF viewer, PDF report, sharing, pen, or geolocation packages when absent) are surfaced to the user as transparency notes per Step 3 - never silently promoted into the plan. If the request is generated-report-shaped and the Power Apps PDF viewer package is absent, fall back to `pdf-report` only when `expo-print` is present; otherwise drop the PDF capability.
+- **Native capability hints** — words like "photo", "camera" -> `camera` with `expo-image-picker`; "scan", "barcode", "QR" -> `barcode-scanner` with `expo-camera`; "pick file", "upload PDF", "import document", "attach file" -> `expo-document-picker`; "generate PDF", "export report", "print report", "evidence packet" -> `pdf-report` (`expo-print` plus optional `expo-sharing`); "view PDF", "open PDF", "preview PDF" -> `native-pdf-viewer` for HTTPS URLs or local `file://` URIs with `@microsoft/power-apps-native-pdf-viewer` 0.2.9+; "signature", "sign off", "approval", "pen", "ink", "draw" -> `pen-input` with `@microsoft/power-apps-native-pen-input`; "track location", "background location", "GPS tracking", "follow my route", "breadcrumb", "field worker location" -> `geolocation` with `@microsoft/power-apps-native-bglocation` (continuous/background tracking + Dataverse sync); "where am I", "current location", "one-shot location", "tag this with my coordinates" -> one-shot `location` with `expo-location`; "save token", "credentials" -> `expo-secure-store`; "share / send" -> `expo-sharing`; "save file / download" -> `expo-file-system`. **Capability hints that the template does NOT ship** (including PDF viewer, PDF report, sharing, pen, or geolocation packages when absent) are surfaced to the user as transparency notes per Step 3 - never silently promoted into the plan. If the request is generated-report-shaped and the Power Apps PDF viewer package is absent, fall back to `pdf-report` only when `expo-print` is present; otherwise drop the PDF capability.
- **Pure-JavaScript dependency hints** — pass any explicit JavaScript-library request, or any feature that may benefit from an established JS-only package instead of custom code, to `screen-planner`. These are app dependencies, not native capabilities. The screen planner reuses suitable installed packages first; otherwise it follows the canonical candidate-selection workflow and records the selected package with an exact version under `## Screens → ### JavaScript Dependencies`.
- **Industry confirmed** — if the prompt contains a line `Industry confirmed: <slug>`, the orchestrator already ran the industry-confidence check (see Step 3c). Treat that slug as the locked industry for Step 3c — skip detection, skip the confidence check, jump straight to mapping the industry to aesthetic direction / palette / tone.
@@ -155,8 +155,9 @@ Map each shipped module to a user-facing capability slug. Use this known mapping
| Capability | Module | Add via |
|---|---|---|
-| `camera` | `expo-camera` | `/add-native camera` |
+| `camera` | `expo-image-picker` | `/add-native camera` |
| `image-picker` | `expo-image-picker` | `/add-native image-picker` |
+| `barcode-scanner` | `expo-camera` | `/add-native barcode-scanner` |
| `document-picker` | `expo-document-picker` | `/add-native document-picker` |
| `pdf-report` | `expo-print` (+ `expo-sharing` when local share is needed and present) | `/add-native pdf-report` |
| `native-pdf-viewer` | `@microsoft/power-apps-native-pdf-viewer` | `/add-native pdf-viewer` |
@@ -224,7 +225,7 @@ For each capability the app needs **AND is in the allowlist**:
| Field | Example |
|---|---|
| Capability | `camera` |
-| Expo module | `expo-camera` |
+| Expo module | `expo-image-picker` |
| Required by workflow | `Capture receipts`, `Update profile photo` |
| Justification | One-sentence rationale tied to a user need ("Capture receipts attached to expense reports") |
| Storage/output target | `n/a`, `Dataverse Image`, `Dataverse File`, `child Evidence table`, `connector-owned storage` (connector + operation + destination), `on-device/share-only`, `local file URI`, or `HTTPS URL` |
diff --git a/plugins/mobile-apps/agents/screen-planner.md b/plugins/mobile-apps/agents/screen-planner.md
index 4707d16ca..25ace9e71 100644
--- a/plugins/mobile-apps/agents/screen-planner.md
+++ b/plugins/mobile-apps/agents/screen-planner.md
@@ -487,7 +487,7 @@ This is the target shape for every spec. ~120 words, ~450 tokens. No inlined cat
- **Audit:** On zone Save: event 100000001 (Zone Step Completed); payload: zoneIndex, zoneName, completedAt, evidenceCount, defectCount.
- **Lookup writes:** exact generated-model key, for example `'[email protected]': '/cr3e9_inspections(<id>)'`, on every zone-progress upsert.
- **Pagination:** `none` (6-row bounded set).
-- **Native capabilities:** `expo-camera`, `expo-image-picker` (capture tiles).
+- **Native capabilities:** `expo-image-picker` (capture tiles).
- **Navigation:** from inspection detail; pushes to defect form; pops back to inspection summary on last zone Save.
- **State delta:** empty defects = `"No defects logged"` + add CTA; error = `"Couldn't load this zone, retry"`.
- **Key user actions:** capture photo, add defect, navigate prev/next, save zone.
@@ -568,7 +568,7 @@ Section format (emit only the subsections owned by the current phase):
| Inspections list | `/(app)/inspections` | `app/(app)/inspections/index.tsx` | default | List + filter | `cr123_inspectionService.getAll` | — | new |
| Inspection detail | `/(app)/inspections/[id]` | `app/(app)/inspections/[id]/index.tsx` | default | View + edit one | `getById`, `update` | — | new |
| New inspection | `/(app)/inspections/new` | `app/(app)/inspections/new.tsx` | modal | Create form, slides up from list | `create` | — | new |
-| Capture photo | `/(app)/inspections/[id]/photo` | `app/(app)/inspections/[id]/photo.tsx` | modal | Take or pick photo | `update` (photo column) | `expo-camera`, `expo-image-picker` | new |
+| Capture photo | `/(app)/inspections/[id]/photo` | `app/(app)/inspections/[id]/photo.tsx` | modal | Take or pick photo | `update` (photo column) | `expo-image-picker` | new |
| Profile | `/(app)/profile` | `app/(app)/profile.tsx` | default | User info + sign out | `useAuth()` only | — | new |
> **Why the File column matters:** the orchestrator's Step 10b walks this column to (1) compute top-level tab/drawer entries (one per unique `app/(app)/<name>` — folder OR flat file) and (2) emit per-folder `_layout.tsx` files with the right modal options. Each builder reads its own row's File path as `target_file`. Without this column, the orchestrator falls back to flat `app/(app)/<screen-name>.tsx` for every screen — phantom tabs return.
diff --git a/plugins/mobile-apps/scripts/tests/app-edit-routing-contract.test.js b/plugins/mobile-apps/scripts/tests/app-edit-routing-contract.test.js
index 8a9117424..9ee13400b 100644
--- a/plugins/mobile-apps/scripts/tests/app-edit-routing-contract.test.js
+++ b/plugins/mobile-apps/scripts/tests/app-edit-routing-contract.test.js
@@ -4,23 +4,18 @@ const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const test = require('node:test');
+const { isInvocable, readInvocationMetadata } = require('../lib/mobileapp-hook-utils');
const pluginRoot = path.resolve(__dirname, '../..');
// Windows checkouts can use CRLF; the prose contracts should not depend on Git's EOL setting.
const read = (file) => fs.readFileSync(path.join(pluginRoot, file), 'utf8').replace(/\r\n?/g, '\n');
const skill = (name) => read(`skills/${name}/SKILL.md`);
const shared = read('shared/shared-instructions.md');
+const routing = read('shared/references/app-edit-routing.md');
const removal = read('shared/references/data-source-removal.md');
+const edit = skill('edit-app');
const create = skill('create-mobile-app');
const pluginCheck = '> **Plugin check**: Run `node "${PLUGIN_ROOT}/scripts/check-version.js"` - if it outputs a message, show it to the user before proceeding.';
-const dataSkills = [
- 'add-datasource',
- 'setup-datamodel',
- 'add-dataverse',
- 'add-connector',
- 'add-sharepoint',
- 'add-sample-data',
-];
function section(text, start, end) {
const startIndex = text.indexOf(start);
@@ -31,9 +26,9 @@ function section(text, start, end) {
}
for (const [name, ending] of [['LF', '\n'], ['CRLF', '\r\n']]) {
- test(`Markdown reader preserves the same data contracts with ${name} line endings`, (t) => {
- const file = 'shared/shared-instructions.md';
- const content = '# Shared Instructions\n\n## Data-source invocation scope\nfirst\nsecond\n\n## Version Check\n';
+ test(`Markdown reader preserves the same contracts with ${name} line endings`, (t) => {
+ const file = 'shared/references/app-edit-routing.md';
+ const content = '# Routing\n\n## Direct requests\nfirst\nsecond\n\n## Orchestrated calls\n';
t.mock.method(fs, 'readFileSync', (filePath, encoding) => {
assert.equal(filePath, path.join(pluginRoot, file));
assert.equal(encoding, 'utf8');
@@ -41,7 +36,7 @@ for (const [name, ending] of [['LF', '\n'], ['CRLF', '\r\n']]) {
});
const actual = read(file);
assert.equal(actual, content);
- assert.match(section(actual, '## Data-source invocation scope', '## Version Check'), /first\nsecond/);
+ assert.match(section(actual, '## Direct requests', '## Orchestrated calls'), /first\nsecond/);
});
}
@@ -54,18 +49,34 @@ function assertSharedEntry(content, name) {
assert.match(content.match(/^allowed-tools: (.+)$/m)?.[1] || '', /\bRead\b/, `${name}: allow reading policy`);
}
-for (const name of dataSkills) {
- test(`${name} starts with the shared data-scope preflight`, () => {
+// Discover invocable skills instead of allowing new entry points to escape a
+// fixed list. This verifies instructions, not whether a model obeys them.
+const invocableSkills = fs.readdirSync(path.join(pluginRoot, 'skills'), { withFileTypes: true })
+ .filter((entry) => entry.isDirectory() && isInvocable(readInvocationMetadata(
+ path.join(pluginRoot, 'skills', entry.name, 'SKILL.md'),
+ )))
+ .map((entry) => entry.name)
+ .sort();
+
+for (const name of invocableSkills) {
+ test(`${name} starts with the shared entry preflight`, () => {
const content = skill(name);
+ // The cross-plugin telemetry preference wrapper has no app workflow.
+ if (name === 'telemetry') {
+ assert.match(content, /\*\*Workflow:.*telemetry-workflow\.md/);
+ return;
+ }
assertSharedEntry(content, name);
- const entry = section(content, '**Invocation scope:**', '\n\n');
- assert.match(entry, /shared-instructions\.md#data-source-invocation-scope/);
- assert.ok(content.indexOf('**Invocation scope:**') < content.indexOf('## Workflow'));
- assert.doesNotMatch(content, /#app-feature-entry-points|(?:app-edit-routing|native-artifact-compatibility)\.md/);
+ if (content.includes('**Entry routing:**')) {
+ const entry = content.split('**Entry routing:**')[1].split('\n\n')[0];
+ assert.match(entry, /shared-instructions\.md#app-feature-entry-points/);
+ assert.doesNotMatch(entry, /Offer|implementation-only|full integration|cancel/);
+ assert.ok(content.indexOf('**Entry routing:**') < content.indexOf('**Telemetry checkpoint:'));
+ }
});
}
-test('data workflows cannot omit, defer, or disable reading shared policy', () => {
+test('a future skill cannot omit, defer, or disable reading shared policy', () => {
const valid = '---\nallowed-tools: Read, Bash\n---\n\n**Shared instructions: [shared-instructions.md](../../shared/shared-instructions.md)** - read first.\n\n## Workflow\n';
assert.doesNotThrow(() => assertSharedEntry(valid, 'data-workflow'));
assert.doesNotThrow(() => assertSharedEntry(valid.replace('**Shared instructions:', `${pluginCheck}\n\n**Shared instructions:`), 'data-workflow'));
@@ -76,69 +87,112 @@ test('data workflows cannot omit, defer, or disable reading shared policy', () =
assert.throws(() => assertSharedEntry(valid.replace('Read, Bash', 'Bash'), 'data-workflow'));
});
-test('shared data scope precedes operational work and does not turn caller markers into approval', () => {
- const scope = section(shared, '## Data-source invocation scope', '## Version Check');
- assert.match(scope, /before any workflow commands or app\/cloud writes/);
- assert.match(scope, /cannot be loaded, STOP/);
- assert.match(scope, /Resolve the current requested operation before discovery or mutation/);
- assert.match(scope, /An existing plan or inventory is context, not permission to replay every row/);
- assert.match(scope, /Standalone calls keep the data workflow's own approval and validation gates/);
- assert.match(scope, /MOBILE_APP_ORCHESTRATING=1/);
- for (const field of ['orchestrator', 'working_dir', 'phase', 'approved_scope']) {
- assert.ok(scope.includes(`\`${field}\``));
+test('shared policy classifies future feature skills before operational commands', () => {
+ const shared = read('shared/shared-instructions.md');
+ const preflight = section(shared, '## App feature entry points', '## Version Check');
+ assert.match(preflight, /before any workflow commands or app\/cloud writes/);
+ assert.match(preflight, /cannot be loaded, STOP/);
+ assert.match(preflight, /applies to new skills too/);
+ assert.match(preflight, /read and execute \[app-edit-routing\.md\]/);
+ assert.match(preflight, /Do not repeat or narrow the\n\s+choices in individual skills/);
+ assert.match(preflight, /Pure operational\/configuration requests/);
+ assert.match(preflight, /`--plan-only` or a planning-phase handoff never authorizes mutating leaves/);
+ assert.match(routing, /includes future feature skills/);
+});
+
+test('direct requests preserve intent and do not infer implementation-only work', () => {
+ assert.match(routing, /original request,\nall arguments, supplied answers/);
+ assert.match(routing, /Naming a capability, connector, table, or package does not establish/);
+ assert.match(routing, /Do not infer this mode merely because the user did not mention screens/);
+ assert.match(routing, /Do not re-scaffold over the app/);
+ assert.match(routing, /UI integration was intentionally\nnot performed/);
+});
+
+test('the entry choice precedes costly work and requires explicit integration consent', () => {
+ const direct = section(routing, '## Direct requests', '## Orchestrated calls');
+ assert.match(direct, /before loading\nor invoking `\/edit-app`/);
+ assert.match(direct, /Do not run health\/type checks, scan\nall screens\/services/);
+ assert.match(direct, /precedes operational toolchain\/auth checks/);
+ assert.match(direct, /standard plugin-update notification still runs first/);
+ for (const choice of ['Implementation only', 'Full app integration', 'Cancel']) {
+ assert.ok(direct.includes(`| ${choice} |`));
}
- assert.match(scope, /including routers and retries/);
- assert.match(scope, /do not persist it, rely on a prior shell export, or infer\napproval from a flag alone/);
- assert.match(scope, /expanded or conflicting scope returns `NEEDS_CONTEXT`/);
- assert.match(scope, /Older callers without a complete approved handoff must establish current scope\nthrough the leaf's approval gate/);
- assert.match(scope, /`--plan-only` or a planning-phase handoff never authorizes mutating leaves/);
- assert.match(scope, /Propagate the mode and current scoped context through routers/);
+ assert.match(direct, /costs more than implementation-only work/);
+ assert.match(direct, /Silence, dismissal, or an ambiguous answer is not\nconsent/);
+ assert.match(direct, /Only after \*\*Full app integration\*\* is selected/);
+ assert.match(direct, /Stop without invoking `\/edit-app`, running implementation commands, or changing files/);
});
-test('shared prompt defaults cannot override explicit data approval gates', () => {
- const policy = section(shared, '## Execution Style', '## Inline Shell');
+test('shared prompt defaults cannot override explicit consent gates', () => {
+ const policy = section(
+ read('shared/shared-instructions.md'),
+ '## Execution Style',
+ '## Inline Shell',
+ );
assert.match(policy, /Explicit approval gates take precedence/);
- assert.match(policy, /plan\/mutation, data-source removal, and deployment/);
+ assert.match(policy, /entry-choice, plan\/mutation, data-source removal, and deployment/);
assert.match(policy, /Cancellation or dismissal stops the pending operation/);
assert.match(policy, /empty or ambiguous answer requires clarification/);
assert.match(policy, /already-approved scoped child calls do not repeat approvals/);
- assert.match(policy, /expanded scope returns to the owner for a new decision/);
assert.doesNotMatch(policy, /empty\/cancel answer auto-proceeds|empty answer proceeds|default-yes/);
});
-test('shared connector setup requires approved implementation and preserves supplied bindings', () => {
- const connector = section(shared, '## Connector Reference', '## Safety Guardrails');
+test('shared connector setup follows entry consent and approved implementation', () => {
+ const connector = section(
+ read('shared/shared-instructions.md'),
+ '## Connector Reference',
+ '## Safety Guardrails',
+ );
assert.doesNotMatch(connector, /Always run `\/list-connections` first/);
+ assert.match(connector, /entry-choice gate precedes `\/list-connections`/);
assert.match(connector, /only in the approved implementation phase/);
assert.match(connector, /Reuse a supplied connection ID or reference/);
assert.match(connector, /Do not invoke it during planning, `--plan-only`, cancellation, or removal-only work/);
- assert.match(connector, /Approved data child calls reuse their scoped handoff without repeating\napproval/);
assert.match(connector, /Direct operational `\/list-connections` requests keep their own workflow/);
});
-test('data routers preserve the current request and proposal-only context without granting approval', () => {
- const router = skill('add-datasource');
- assert.match(router, /Forward the absolute `working_dir`, current request, owner\/phase\/scope,\n\s+supplied answers, and `--plan-only` or planning-phase status unchanged on every\n\s+handoff/);
- assert.match(router, /a saved plan or router choice is not consent to mutate/);
- assert.match(router, /Conflicting add\/refresh\/remove scopes return to the owner for separate calls/);
- const connector = skill('add-connector');
- assert.match(connector, /same `\$ARGUMENTS`, absolute `working_dir`,\ncurrent request, owner\/phase\/scope, and proposal-only mode/);
- assert.match(connector, /Do not continue this\nskill's workflow.*or infer execution approval from this routing decision/);
+test('implementation-only choice is forwarded rather than silently escalated', () => {
+ const direct = section(routing, '## Direct requests', '## Orchestrated calls');
+ assert.match(direct, /forward\n`--implementation-only` through any router/);
+ assert.match(direct, /Do not silently escalate\nto `\/edit-app`/);
+ assert.match(direct, /entry choice approves entering that workflow, not its mutations/);
+ assert.match(direct, /explicit approval for data-source removals/);
+});
+
+test('current approved create and edit handoffs do not repeat the entry question', () => {
+ const orchestrated = section(routing, '## Orchestrated calls', '## Conditional impact');
+ assert.match(orchestrated, /Check valid caller context before the entry-choice gate/);
+ assert.match(orchestrated, /approved\n`\/create-mobile-app` or `\/edit-app` child call skips the entry question/);
+ assert.match(orchestrated, /Do not add a second integration\/cost question/);
+ assert.match(edit, /Reuse\n`entry_choice: full-integration`/);
+ assert.match(edit, /direct `\/edit-app` invocation also needs no entry-choice menu/);
+});
+
+test('orchestration context is scoped, forwarded, and not an approval bypass', () => {
+ assert.match(routing, /MOBILE_APP_ORCHESTRATING=1/);
+ for (const field of ['orchestrator', 'working_dir', 'phase', 'approved_scope']) {
+ assert.ok(routing.includes(`\`${field}\``));
+ }
+ assert.match(routing, /Routers forward the same context/);
+ assert.match(routing, /internal\nnative helpers inherit it/);
+ assert.match(routing, /never\ndelegates back to `\/edit-app`/);
+ assert.match(routing, /A bare\/stale environment value or `--skip-planning` without a matching current/);
+ assert.match(routing, /Do not persist the marker/);
});
-test('creation passes scoped approval and the app root to data leaves', () => {
+test('create calls native and data leaves without routing its partial app into edit', () => {
for (const [start, end, expected] of [
+ ['Invoke skill: /add-native', 'Run sequentially.', /approved capability row/],
['Invoke skill: /add-dataverse', '`/add-dataverse` validates', /bound operation-manifest artifacts/],
['### Step 10 — Add connectors', '### Step 10b', /connector row and supplied/],
]) {
const handoff = section(create, start, end);
assert.match(handoff, /MOBILE_APP_ORCHESTRATING=1/);
assert.match(handoff, /orchestrator: create-mobile-app/);
- assert.match(handoff, /working_dir: <working_dir>|`working_dir`/);
- assert.match(handoff, /--working-dir "?<working_dir>"?/);
assert.match(handoff, /phase: implementation/);
assert.match(handoff, expected);
}
+ assert.match(create, /children must use this context rather than mistake creation for a standalone\nedit/);
});
test('connector-owned actions and SharePoint schemas do not imply Dataverse schema', () => {
@@ -146,6 +200,70 @@ test('connector-owned actions and SharePoint schemas do not imply Dataverse sche
assert.match(skill('add-sharepoint'), /Keep SharePoint list\/library schemas in Connectors, not the Dataverse\nData Model/);
});
+test('edit planning defers connector and design execution until approval', () => {
+ const planning = section(edit, '### Step 2 — Re-plan', '### Step 3 — Gate');
+ const design = section(edit, '**If the user picks (d) Design:**', '### Step 2 — Re-plan');
+ assert.match(planning, /Do not execute connector skills, create connections, or generate services/);
+ assert.doesNotMatch(planning, /read and execute `\/add-/);
+ assert.match(design, /Steps 2-4 before executing `\/design-system` in Step 5/);
+ assert.match(design, /during `--plan-only`/);
+ assert.match(edit, /inspection-only gate/);
+ assert.match(edit, /Run only operations in the approved delta/);
+ assert.match(edit, /If `--plan-only` is present, do not invoke the configuration skill/);
+});
+
+test('edit validates scoped Dataverse planning before its existing gate and preserves docs-only approval', () => {
+ const planning = section(edit, '### Step 2 — Re-plan', '### Step 3 — Gate');
+ const gate = section(edit, '### Step 3 — Gate', '### Step 4 — Write');
+ const save = section(edit, '### Step 4 — Write', '### Step 5 — Apply');
+ assert.ok(planning.indexOf('dataverse-change-planning.md') < planning.indexOf('Spawn agent:'));
+ assert.match(planning, /structured Dataverse context\/revision signals[\s\S]*before generic retry limits/);
+ assert.match(planning, /Every Data Model result, including inline output, must pass[\s\S]*`DONE` alone never authorizes Step 3/);
+ assert.match(gate, /require exit `0` from\n`validate-dataverse-planning-decisions\.js`[\s\S]*before showing this gate/);
+ assert.ok(gate.indexOf('validate-dataverse-planning-decisions.js') < gate.indexOf('Show the user'));
+ assert.match(gate, /no extra create-flow approval gate/);
+ assert.match(gate, /If cancel → STOP, leave the plan and app untouched/);
+ assert.match(gate, /`--plan-only`[\s\S]*"Approve and save plan only"[\s\S]*stop after Step 4/);
+ assert.match(save, /preserve all other sections verbatim/);
+ assert.match(save, /`--plan-only`[\s\S]*`plan_only: true`[\s\S]*and stop/);
+ assert.match(save, /A plan-only save does not create this implementation approval context/);
+ assert.ok(save.indexOf('and stop') < save.indexOf('freeze the shared workflow'));
+ assert.doesNotMatch(planning, /Invoke skill: \/add-dataverse|--approval-receipt|--operation-manifest/);
+});
+
+test('planning-phase edit children return to their owner before the direct docs-only approval path', () => {
+ const gate = section(edit, '### Step 3 — Gate', '### Step 4 — Write');
+ const childReturn = section(gate, 'If this is a planning-phase handoff from another owner', 'Show the user');
+ const directGate = gate.slice(gate.indexOf('Show the user'));
+ assert.match(childReturn, /return the validated\nproposal and concerns to that owner now/);
+ assert.match(childReturn, /without saving the live plan or\nopening an implementation gate/);
+ assert.match(childReturn, /Do not turn the caller's planning consent\ninto approval to apply the edit/);
+ assert.match(childReturn, /A direct `--plan-only` request retains the\nexplicit plan-document approval below/);
+ assert.doesNotMatch(childReturn, /Approve and apply|Approve and save plan only|Invoke skill:|--skip-planning/);
+ const validation = gate.indexOf('validate-dataverse-planning-decisions.js');
+ const returnToOwner = gate.indexOf('If this is a planning-phase handoff');
+ const localGate = gate.indexOf('Show the user');
+ assert.ok(validation >= 0 && validation < returnToOwner && returnToOwner < localGate);
+ assert.match(directGate, /If cancel → STOP, leave the plan and app untouched/);
+ assert.match(directGate, /If `\$ARGUMENTS` includes `--plan-only`, change option \(a\) to "Approve and save plan only" and stop after Step 4/);
+ assert.ok(directGate.indexOf('Approve this edit') < directGate.indexOf('Approve and save plan only'));
+});
+
+test('connector and native intent do not unconditionally create Dataverse schema', () => {
+ for (const expected of [
+ /Teams\/email action or profile lookup/,
+ /SQL\/Excel\/SharePoint data/,
+ /not automatically Dataverse/,
+ /missing generated services/,
+ /Ask about retention rather than assuming/,
+ ]) {
+ assert.match(routing, expected);
+ }
+ assert.match(edit, /\*\*Data Model is conditional\.\*\*/);
+ assert.match(edit, /Preserve unaffected Data Model content verbatim/);
+ assert.match(edit, /ask about retention, then update Data Model only if/);
+});
+
test('setup-datamodel saves every approved path and passes scope to its leaves', () => {
const setup = skill('setup-datamodel');
const planning = section(setup, '### Phase 2', '### Phase 4');
@@ -180,7 +298,6 @@ test('setup validates all Dataverse proposal paths before the one combined appro
assert.ok(validate >= 0 && validate < proposalExit && proposalExit < approval && approval < save);
assert.match(gate, /Connector-only, retirement-only, and refresh-only proposals[\s\S]*must not reuse stale schema-planning artifacts/);
assert.match(gate, /Revisions repeat validation, not broad discovery or another\napproval ceremony/);
- assert.match(gate, /A saved plan or `--skip-planning` alone is not approval/);
assert.doesNotMatch(planning, /EnterPlanMode|ExitPlanMode|--approval-receipt/);
});
@@ -191,7 +308,7 @@ test('connector aliases and operations preserve dedicated routing and dependency
assert.match(connector, /actions\/functions follow the discovery-only branch/);
assert.doesNotMatch(connector, /npx expo install <missing-package>/);
assert.match(connector, /Do not install\nnative packages absent from the template/);
- assert.match(connector, /Standalone removal must stop if\nit would leave broken consumers/);
+ assert.match(connector, /Standalone removal must stop if\s+it would leave broken consumers/);
});
test('Dataverse discovery executes before connector setup and ends the leaf', () => {
@@ -205,6 +322,56 @@ test('Dataverse discovery executes before connector setup and ends the leaf', ()
assert.doesNotMatch(setup, /find-dataverse-api/);
});
+test('connector discovery examples use the canonical local CLI resolver', () => {
+ const connector = skill('add-connector');
+ for (const verb of ['list-datasets', 'list-tables', 'list-procedures']) {
+ assert.match(connector, new RegExp(`^\\$PA connection ${verb}\\b`, 'm'));
+ }
+ assert.doesNotMatch(connector, /^npx (?:--no-install )?power-apps /m);
+});
+
+for (const [label, discoveryVerb, addCommand, approval, proposalOnly] of [
+ ['table', 'list-datasets', '$PA app add data-source --connector <apiId> --connection-id <connectionId> --dataset',
+ /Approve\s+the exact selected bindings before generation, or reuse matching current owner\s+approval/, /proposal-only discovery returns without adding sources/],
+ ['procedure', 'list-procedures', '$PA app add data-source --connector shared_sql',
+ /Approve the exact procedure binding before generation if it was not already in\s+the current approved scope/, /proposal-only discovery returns without adding it/],
+]) {
+ test(`connector ${label} discovery returns through approval before a separate guarded mutation`, () => {
+ const connector = skill('add-connector');
+ const blocks = [...connector.matchAll(/^```bash\n([\s\S]*?)\n```/gm)];
+ const discovery = blocks.find((block) => block[1].includes(`$PA connection ${discoveryVerb}`));
+ const addition = blocks.find((block) => block[1].includes(addCommand));
+ assert.ok(discovery, `${label}: documented discovery block`);
+ assert.ok(addition, `${label}: documented registration block`);
+ assert.ok(addition.index > discovery.index, 'Discovery and mutation must be separate, ordered calls');
+ const guard = "cd -- '<working_dir>' || { echo \"BLOCKED: cannot enter working_dir\" >&2; exit 1; }";
+ assert.ok(discovery[1].startsWith(`${guard}\n`));
+ assert.ok(addition[1].startsWith(`${guard}\n`));
+ assert.doesNotMatch(discovery[1], /^\$PA app add\b/m);
+ const gate = connector.slice(discovery.index + discovery[0].length, addition.index);
+ assert.match(gate, approval);
+ assert.match(gate, proposalOnly);
+ });
+}
+
+test('SharePoint proposal and binding approvals precede implementation', () => {
+ const sharepoint = skill('add-sharepoint');
+ const plan = section(sharepoint, '### Step 2:', '### Step 3:');
+ assert.match(plan, /For `--plan-only` or a planning-phase handoff/);
+ assert.match(plan, /bindings, any schema changes, and unresolved choices, then STOP before\s+implementation/);
+ assert.match(plan, /Do not create connections\/lists, generate services, or update\s+the app plan or memory-bank/);
+ assert.match(plan, /Missing discovery access is not permission to\s+create a connection/);
+ assert.ok(plan.indexOf('For `--plan-only`') < plan.indexOf('**If lists already exist:**'));
+ const binding = section(sharepoint, '### Step 6:', '### Step 7:');
+ assert.match(binding, /obtain explicit approval to create a connection with the\s+command below/);
+ assert.ok(binding.indexOf('obtain explicit approval') < binding.indexOf('```bash'));
+ const add = section(sharepoint, '### Step 9:', '### Step 10:');
+ assert.match(add, /Confirm approval covers this environment, connection\s+ID\/reference, site, and list\/library before registration/);
+ assert.match(add, /approve any newly resolved binding; return a changed child scope to its\s+owner/);
+ assert.match(add, /A picker\s+selection alone is not execution approval/);
+ assert.ok(add.indexOf('Confirm approval') < add.indexOf('```bash'));
+});
+
test('generic connector preserves supplied IDs and references before resolving a missing binding', () => {
const setup = section(skill('add-connector'), '### Step 3', '**Classify the connector');
assert.match(setup, /Supplied `--connection-id`[\s\S]*reuse that exact/);
@@ -233,6 +400,17 @@ test('SharePoint reuses supplied bindings and emits the matching registration fo
assert.match(section(sharepoint, '### Step 8:', '### Step 9:'), /Skip this picker/);
});
+test('every explicit create/edit child context includes its working directory', () => {
+ for (const [name, content] of [['create-mobile-app', create], ['edit-app', edit]]) {
+ const contexts = [...content.matchAll(/(?:Context|Environment):\n([\s\S]*?)\nArguments:\n([\s\S]*?)\n```/g)];
+ assert.ok(contexts.length > 0, `${name} handoff coverage`);
+ for (const [, context, args] of contexts) {
+ assert.match(context, /working_dir: <working_dir>/, name);
+ assert.match(args, /--working-dir ['"]?<working_dir>['"]?/, name);
+ }
+ }
+});
+
test('connector-only summary does not claim a nonexistent Dataverse manifest', () => {
const summary = section(skill('setup-datamodel'), '### Phase 7', '## Reference');
assert.match(summary, /Manifest as `not applicable`/);
@@ -240,17 +418,34 @@ test('connector-only summary does not claim a nonexistent Dataverse manifest', (
assert.doesNotMatch(summary, /Manifest\s+:\s+\.datamodel-manifest\.json/);
});
-test('existing Dataverse plans are checked against the requested delta rather than replayed', () => {
+test('existing native wrappers and Dataverse plans are checked against the requested delta', () => {
+ assert.match(skill('add-native'), /inspect its exports against the approved capability\ncontract/);
+ assert.doesNotMatch(skill('add-native'), /regeneration skipped — wrapper already exists/);
const dataverse = skill('add-dataverse');
assert.match(dataverse, /restrict schema writes to the exact `approved_scope` delta/);
assert.match(dataverse, /flag alone must not suppress standalone reconciliation/);
- assert.match(dataverse, /If the request adds nothing, verify the existing outcome and report a no-op/);
assert.doesNotMatch(dataverse, /empty\/cancel input auto-proceeds/);
});
+test('design changes return screen impact and use the existing host theme integration', () => {
+ const design = skill('design-system');
+ const refresh = read('skills/design-system/references/refresh-flow.md');
+ assert.doesNotMatch(design, /\/tweak-screen|src\/theme\/ThemeProvider\.tsx/);
+ assert.match(design, /runtime wiring, affected screen changes, and final verification/);
+ assert.match(design, /Drift detection \(Mode A\/B/);
+ assert.match(refresh, /before either spec or token write/i);
+ assert.match(refresh, /Cancellation leaves both artifacts unchanged/);
+ assert.match(refresh, /paired pre-write snapshot/);
+ assert.match(refresh, /screen constraints/);
+});
+
+test('configuration-only workflows retain their own approvals and return to their caller', () => {
+ assert.match(routing, /Do not route a\npure operational request through app planning/);
+ assert.match(skill('setup-app-insights'), /MOBILE_APP_ORCHESTRATING=1 AND explicit edit-app caller context/);
+ assert.match(skill('setup-app-insights'), /Configuration approval remains owned by Step 3/);
+});
+
test('data-source removal is an explicit app-only retirement, not server deletion', () => {
- assert.match(removal, /shared-instructions\.md#data-source-invocation-scope/);
- assert.doesNotMatch(removal, /#app-feature-entry-points|(?:app-edit-routing|native-artifact-compatibility)\.md/);
assert.match(removal, /does not authorize deleting the server table,\s+its columns\/records/);
assert.match(removal, /A missing row in a planner's output is a candidate, not consent/);
assert.match(removal, /lookup\/identity reads, and offline requirements/);
@@ -258,14 +453,16 @@ test('data-source removal is an explicit app-only retirement, not server deletio
assert.match(removal, /Never mutate\s+configuration\/generated files during\s+planning or `--plan-only`/);
});
-test('data-source retirement requires consumers to be retired before unregistering', () => {
- const consumers = section(removal, '## 2.', '## 3.');
- assert.match(consumers, /responsible app workflow adds\/refreshes replacement sources first/);
- assert.match(consumers, /updates or removes the approved consumers and verifies they no longer depend\s+on the retiring source/);
- assert.match(consumers, /Keep the old binding available until those source edits are complete/);
- assert.match(consumers, /Only then call the appropriate leaf in removal mode/);
- assert.match(consumers, /removal must stop if consumers remain/);
- assert.match(consumers, /cannot be staged safely,\nreturn the conflict to the owner for an explicit migration plan/);
+test('retired consumers are updated before the edit unregisters their sources', () => {
+ const mutations = section(edit, '### Step 5 — Apply app mutations', '### Step 6 — Rebuild');
+ const consumers = section(edit, '### Step 6 — Rebuild', '### Step 6.5 — Unregister');
+ const retirement = section(edit, '### Step 6.5 — Unregister', '### Step 7 — Verify');
+ assert.match(mutations, /Step 5 applies additions\/refreshes, not removals/);
+ assert.match(mutations, /Never add a retiring table to the offline profile/);
+ assert.match(consumers, /Pass the approved retiring service\/source list/);
+ assert.match(retirement, /After Step 6 updates\/removes the\nconsumers/);
+ assert.match(retirement, /Refresh the Generated Services snapshot again/);
+ assert.match(retirement, /no-op, partial cleanup, or remaining consumer blocks completion/);
});
for (const name of ['add-connector', 'add-dataverse', 'add-sharepoint']) {
@@ -299,6 +496,8 @@ test('refresh preserves registration identity and never falls back to an add', (
assert.match(refresh, /preserve unrelated registration identities/);
assert.match(refresh, /do not repair generator output by hand or retry through addition/);
assert.match(skill('add-datasource'), /--refresh --data-source-name "<registered-name>"/);
+ assert.match(skill('debug-app'), /--refresh --data-source-name "<registered-name>"/);
+ assert.match(edit, /do not route refreshes through addition/);
});
test('the router and data-only orchestrator retain the removal operation', () => {
@@ -327,6 +526,8 @@ test('schema-map generation is distinct from service refresh and removal', () =>
assert.match(removal, /\$PA app refresh data-source --name '<registered-name>'/);
assert.match(removal, /npm run generate-schemas\nnpx --no-install tsc --noEmit/);
assert.match(removal, /including when the\nlast source was removed/);
+ assert.match(skill('debug-app'), /do not resurrect retired sources during repair/i);
+ assert.doesNotMatch(skill('debug-app'), /tell the user to re-run `npm run generate-schemas`; if the error reproduces/);
});
test('verified removal reconciles the app inventory without faking offline cleanup', () => {
@@ -382,3 +583,15 @@ test('README explains data-source commands without internal execution mechanics'
assert.match(examples, /never deletes server tables/);
assert.doesNotMatch(examples, /compact live-metadata|working_dir|PowerShell|Bash|schema map|allowlist|offline-profile-delta/);
});
+
+test('scoped feature context preserves the separate upstream browser suppression flag', () => {
+ assert.match(routing, /MOBILE_APP_ORCHESTRATING=1/);
+ assert.match(routing, /CODE_APPS_NATIVE_ORCHESTRATING=1/);
+ assert.match(routing, /suppresses browser openers/);
+ const creation = section(create, '### Step 6.75', '#### Branch A');
+ assert.match(creation, /Environment:\s+CODE_APPS_NATIVE_ORCHESTRATING=1/);
+ assert.match(creation, /Context:\s+MOBILE_APP_ORCHESTRATING=1/);
+ assert.match(edit, /CODE_APPS_NATIVE_ORCHESTRATING=1[\s\S]*suppress intermediate browser tabs/);
+ assert.match(skill('design-system'), /CODE_APPS_NATIVE_ORCHESTRATING=1/);
+ assert.match(read('skills/design-system/references/vibe/style-picker.md'), /CODE_APPS_NATIVE_ORCHESTRATING=1/);
+});
diff --git a/plugins/mobile-apps/scripts/tests/app-working-directory-contract.test.js b/plugins/mobile-apps/scripts/tests/app-working-directory-contract.test.js
index 274cfba20..787b8dfd6 100644
--- a/plugins/mobile-apps/scripts/tests/app-working-directory-contract.test.js
+++ b/plugins/mobile-apps/scripts/tests/app-working-directory-contract.test.js
@@ -9,13 +9,23 @@ const test = require('node:test');
const { shellBlocks } = require('./helpers/markdown-shell-blocks');
const pluginRoot = path.resolve(__dirname, '../..');
+const nativeRoot = path.join(pluginRoot, 'skills/add-native');
const normalize = (text) => text.replace(/\r\n?/g, '\n');
const read = (file) => normalize(fs.readFileSync(file, 'utf8'));
+const reference = read(path.join(pluginRoot, 'shared/references/native-artifact-compatibility.md'));
+const rootLink = '[native-artifact-compatibility.md Step 0](${PLUGIN_ROOT}/shared/references/native-artifact-compatibility.md#0-bind-every-operation-to-the-app-root)';
const appRootReference = read(path.join(pluginRoot, 'shared/references/app-working-directory.md'));
const appRootLink = '[app-working-directory.md](${PLUGIN_ROOT}/shared/references/app-working-directory.md)';
const guard = "cd -- '<working_dir>' || { echo \"BLOCKED: cannot enter working_dir\" >&2; exit 1; }";
const powershellGuard = "Set-Location -LiteralPath '<working_dir>' -ErrorAction Stop";
const quotedFileArgument = /--(?:working-dir|project-root|approval-receipt|contract|file|output|publish-checkpoint|reconciliation|snapshot|validate)\s+"[^"\n]*<[^>\n]+>[^"\n]*"/;
+const files = [
+ path.join(nativeRoot, 'SKILL.md'),
+ ...fs.readdirSync(nativeRoot, { withFileTypes: true })
+ .filter((entry) => entry.isDirectory())
+ .map((entry) => path.join(nativeRoot, entry.name, 'SKILL.md'))
+ .filter((file) => fs.existsSync(file)),
+];
function unsafePathLiteral(line) {
if (quotedFileArgument.test(line)) return true;
@@ -35,11 +45,11 @@ for (const prefix of ['', ' ', '> ', '> ']) {
}
}
-function assertRootBinding(text) {
+function assertRootBinding(text, link = appRootLink) {
text = normalize(text);
assert.match(text, /before any project read or command, execute/);
- assert.ok(text.includes(appRootLink));
- assert.ok(text.indexOf(appRootLink) < text.indexOf('```bash'), 'Bind root before the first gate');
+ assert.ok(text.includes(link));
+ assert.ok(text.indexOf(link) < text.indexOf('```bash'), 'Bind root before the first gate');
assert.match(text, /every shell call and\s+file tool/);
const blocks = shellBlocks(text);
assert.ok(blocks.length > 0);
@@ -52,11 +62,11 @@ function assertRootBinding(text) {
}
}
-function assertEveryGuardIsRequired(content, command, language = 'bash') {
+function assertEveryGuardIsRequired(content, command, language = 'bash', link = appRootLink) {
let count = 0;
// Use source offsets: extracted list/blockquote snippets have already been dedented.
for (let index = content.indexOf(command); index !== -1; index = content.indexOf(command, index + command.length)) {
- assert.throws(() => assertRootBinding(content.slice(0, index) + content.slice(index + command.length)));
+ assert.throws(() => assertRootBinding(content.slice(0, index) + content.slice(index + command.length), link));
count++;
}
assert.equal(count, shellBlocks(content, language).length);
@@ -68,6 +78,15 @@ const bashPaths = process.platform === 'win32'
: [];
const bash = bashPaths.find((entry) => /[\\/]Git[\\/]/i.test(entry)) || 'bash';
const shellLiteralContents = (value) => value.replaceAll('\\', '/').replaceAll("'", "'\\''");
+const shellQuote = (value) => `'${value.replaceAll("'", "'\\''")}'`;
+const dependencies = {
+ 'expo-camera': '1.0.0',
+ 'expo-secure-store': '1.0.0',
+ 'expo-print': '1.0.0',
+ '@microsoft/power-apps-native-pdf-viewer': '0.2.9',
+ '@microsoft/power-apps-native-pen-input': '1.0.0',
+ '@microsoft/power-apps-native-bglocation': '1.0.0',
+};
function fixture(t) {
const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'app-working-dir-'));
@@ -75,7 +94,7 @@ function fixture(t) {
const owner = path.join(directory, "owner's app [test] $root $(printf expanded) `printf backtick`");
const caller = path.join(directory, 'different app');
for (const root of [owner, caller]) {
- fs.mkdirSync(root, { recursive: true });
+ fs.mkdirSync(path.join(root, 'src/native'), { recursive: true });
fs.writeFileSync(path.join(root, 'app.config.js'), 'module.exports = {};');
fs.writeFileSync(path.join(root, 'power.config.json'), JSON.stringify({ environmentId: root === owner ? 'owner' : 'caller' }));
fs.writeFileSync(path.join(root, 'native-app-plan.md'), '# Plan\n');
@@ -83,13 +102,21 @@ function fixture(t) {
for (const name of ['dataverse-operation-all.json', 'dataverse-operation-phase-fixture.json']) {
fs.writeFileSync(path.join(root, '.tmp', name), '[]');
}
- fs.writeFileSync(path.join(root, 'package.json'), '{"dependencies":{}}');
+ fs.writeFileSync(path.join(root, 'package.json'), JSON.stringify({
+ dependencies: root === owner ? dependencies : {},
+ }));
+ const installed = path.join(root, 'node_modules/@microsoft/power-apps-native-pdf-viewer');
+ fs.mkdirSync(installed, { recursive: true });
+ fs.writeFileSync(path.join(installed, 'package.json'), JSON.stringify({ version: '0.2.9' }));
}
return { directory, owner, caller };
}
function run(block, owner, caller) {
- const command = block.replaceAll('<working_dir>', shellLiteralContents(owner));
+ const command = block
+ .replaceAll('<working_dir>', shellLiteralContents(owner))
+ .replaceAll('<approved-artifact-keys-json>', '["scanner"]')
+ .replaceAll('<expo-module-name>', 'expo-secure-store');
// Use the current Node executable; mutation tests supply local CLI probes.
const result = spawnSync(bash, ['-s'], {
input: `node() { "$REAL_NODE" "$@"; }\nPA="npx --no-install pa"\nPA_KIND=pa\n${command}`,
@@ -110,17 +137,16 @@ function run(block, owner, caller) {
test('shared root contract distinguishes direct defaults from required child context and file-tool scope', () => {
const scope = appRootReference;
const shared = read(path.join(pluginRoot, 'shared/shared-instructions.md'));
- const heading = '## Data-source invocation scope';
- const start = shared.indexOf(heading);
- assert.ok(start >= 0, 'Data-source invocations must have a shared scope preflight');
- const end = shared.indexOf('\n---', start);
- assert.ok(end > start);
- const invocation = shared.slice(start, end);
const binding = '[app-working-directory.md](references/app-working-directory.md)';
- assert.ok(invocation.includes(binding));
- assert.match(invocation, /before (?:reading|any project read)/);
- assert.ok(invocation.indexOf(binding) < invocation.indexOf('`power.config.json`'),
- 'Bind the owner root before reading the selected app environment');
+ assert.ok(shared.includes(binding));
+ assert.ok(shared.indexOf(binding) < shared.search(/Classify the current\s+request/));
+ const dataScopeStart = shared.indexOf('## Data-source invocation scope');
+ assert.ok(dataScopeStart > 0, 'Existing data callers keep their canonical scope anchor');
+ const dataScope = shared.slice(dataScopeStart, shared.indexOf('## Version Check', dataScopeStart));
+ assert.ok(dataScope.includes(binding));
+ assert.match(dataScope, /Resolve the current requested operation before discovery or mutation/);
+ assert.match(dataScope, /expanded or conflicting scope returns `NEEDS_CONTEXT`/);
+ assert.match(reference, /## 0\. Bind every operation to the app root[\s\S]*\[app-working-directory\.md\]\(app-working-directory\.md\)/);
assert.match(scope, /Child invocation[\s\S]*owner's absolute\s+`working_dir`/);
assert.match(scope, /Never fall back to the process cwd/);
assert.match(scope, /Missing or\s+relative owner context returns `NEEDS_CONTEXT` before project access/);
@@ -363,29 +389,88 @@ test('shared connector command examples retain the same per-call root guard', ()
}
});
-const sampleData = read(path.join(pluginRoot, 'skills/add-sample-data/SKILL.md'));
-for (const [eolName, eol] of [['LF', '\n'], ['CRLF', '\r\n']]) {
- test(`sample-data discovery, insertion, and retry commands re-enter the app root (${eolName})`, () => {
- assert.match(sampleData, /before any project read or command\. Bind the absolute `working_dir` first/);
- assert.match(sampleData, /reuse it for every shell call, file tool, media path, and retry/);
- // Numbered instructions indent some command fences by three spaces.
- const content = sampleData.replace(/\n/g, eol);
- const blocks = shellBlocks(content.replace(/^ {3}/gm, ''));
- assert.ok(blocks.length > 0);
- assert.equal(blocks.length, [...sampleData.matchAll(/^ {0,3}```bash$/gm)].length);
- for (const block of blocks) {
- assert.ok(block.startsWith(`${guard}\n`), 'Each seed command needs a fail-closed root guard');
- }
- });
+for (const name of ['add-dataverse', 'add-sample-data']) {
+ const content = read(path.join(pluginRoot, 'skills', name, 'SKILL.md')).replace(/^> ?/gm, '');
+ for (const [eolName, eol] of [['LF', '\n'], ['CRLF', '\r\n']]) {
+ test(`${name} roots all Bash commands, including indented recipes (${eolName})`, () => {
+ // Numbered instructions indent command fences by two or three spaces.
+ const source = content.replace(/\n/g, eol).replace(/^ {1,3}/gm, '');
+ const blocks = shellBlocks(source);
+ assert.equal(blocks.length, [...content.matchAll(/^ {0,3}```bash$/gm)].length);
+ assertRootBinding(source, appRootLink);
+ assertEveryGuardIsRequired(normalize(source), guard);
+ });
+ }
}
+test('Dataverse nested metadata and generated-file paths stay literal and app-rooted', () => {
+ const content = read(path.join(pluginRoot, 'skills/add-dataverse/SKILL.md'));
+ assert.match(content, /--operations "\$\(cat '<working_dir>\/\.tmp\/derived-metadata-operations\.json'\)"/);
+ assert.match(content, /Glob: <working_dir>\/src\/generated\/services\/\*Service\.ts/);
+ assert.match(content, /Glob: <working_dir>\/src\/generated\/models\/\*Model\.ts/);
+});
+
+test('documented seed commands block missing roots before any script or CLI call', (t) => {
+ const { directory, owner, caller } = fixture(t);
+ const content = read(path.join(pluginRoot, 'skills/add-sample-data/SKILL.md')).replace(/^> ?/gm, '');
+ const blocks = shellBlocks(content.replace(/^ {1,3}/gm, ''));
+ assert.equal(blocks.length, 11);
+ const trace = path.join(owner, 'seed-root-commands.jsonl');
+ const callerTrace = path.join(caller, 'seed-root-commands.jsonl');
+ const ownerConfig = fs.readFileSync(path.join(owner, 'power.config.json'));
+ const callerConfig = fs.readFileSync(path.join(caller, 'power.config.json'));
+ fs.writeFileSync(path.join(owner, '.datamodel-manifest.json'), '{"tables":[]}');
+ // Script/cloud commands are recorders; only the fixed local logger uses real Node.
+ const probes = `
+record_call() {
+ "$REAL_NODE" -e 'require("node:fs").appendFileSync("seed-root-commands.jsonl", JSON.stringify({ cwd: process.cwd(), args: process.argv.slice(1) }) + "\\n")' "$@"
+}
+node() {
+ record_call node "$@"
+ if [ "$1" = "-p" ]; then printf 'owner\\n'; else printf '{}\\n'; fi
+}
+az() { record_call az "$@"; printf 'fixture-account\\n'; }
+npx() { record_call npx "$@"; }
+npm() { record_call npm "$@"; }
+`;
+ const prepare = (block, root) => {
+ const command = block
+ .replaceAll('<working_dir>', shellLiteralContents(root))
+ .replaceAll(/<[^>]+>/g, 'fixture');
+ assert.doesNotMatch(command, /<[^>]+>/);
+ return `${probes}\nPLUGIN_ROOT=${shellQuote(pluginRoot.replaceAll('\\', '/'))}\n${command}`;
+ };
+ for (const block of blocks) {
+ const valid = run(prepare(block, owner), owner, caller);
+ assert.equal(valid.status, 0, `${block}\n${valid.stderr}`);
+ assert.equal(valid.stderr, '');
+ const before = fs.existsSync(trace) ? fs.readFileSync(trace, 'utf8') : '';
+ const missing = run(prepare(block, path.join(directory, 'missing seed app')), owner, caller);
+ assert.equal(missing.status, 1, missing.stderr);
+ assert.match(missing.stderr, /BLOCKED: cannot enter working_dir/);
+ assert.doesNotMatch(missing.stderr, /syntax error|unexpected token|unexpected EOF/);
+ assert.equal(fs.existsSync(trace) ? fs.readFileSync(trace, 'utf8') : '', before, 'Failed cd must invoke no script or CLI');
+ assert.equal(fs.existsSync(callerTrace), false);
+ }
+ const calls = fs.readFileSync(trace, 'utf8').trim().split('\n').map(JSON.parse);
+ assert.equal(calls.length, 11);
+ for (const call of calls) {
+ assert.equal(fs.realpathSync.native(call.cwd), fs.realpathSync.native(owner));
+ }
+ assert.ok(calls.some((call) => call.args[0] === 'az'));
+ assert.ok(calls.some((call) => call.args.includes('BATCH-RECORDS')));
+ assert.ok(calls.some((call) => call.args.some((arg) => arg.endsWith('/resolve-environment.js')) && call.args.includes('owner')));
+ assert.deepEqual(fs.readFileSync(path.join(owner, 'power.config.json')), ownerConfig);
+ assert.deepEqual(fs.readFileSync(path.join(caller, 'power.config.json')), callerConfig);
+});
+
for (const file of dataFiles) {
const name = path.basename(path.dirname(file));
const content = read(file).replace(/^> ?/gm, '');
const blocks = shellBlocks(content);
for (const [eolName, eol] of [['LF', '\n'], ['CRLF', '\r\n']]) {
test(`${name} binds addition, discovery, and verification to the app root (${eolName})`, () => {
- assertRootBinding(content.replace(/\n/g, eol));
+ assertRootBinding(content.replace(/\n/g, eol), appRootLink);
});
}
test(`${name} rejects missing or deferred root guards`, () => {
@@ -532,6 +617,31 @@ const previewOpeners = [
['skills/preview-screens/SKILL.md', 'preview.html'],
];
+test('design previews and runtime checks use the approved root in fresh shells', (t) => {
+ const { directory, owner, caller } = fixture(t);
+ const design = read(path.join(pluginRoot, 'skills/design-system/SKILL.md'));
+ assert.match(design, /bind `working_dir` through\s+\[app-working-directory\.md\]/);
+ assert.match(design, /every shell call and absolute file-tool path/);
+ assert.match(design, /Check the resolved working_dir for app.config.js/);
+ for (const file of [
+ 'skills/design-system/SKILL.md',
+ 'skills/design-system/references/tamagui-integration.md',
+ ]) {
+ const blocks = shellBlocks(read(path.join(pluginRoot, file)));
+ assert.ok(blocks.length > 0);
+ for (const block of blocks) {
+ assert.ok(block.startsWith(`${guard}\n`), file);
+ const probe = `${block.split('\n')[0]}\nnode -p "process.cwd()"`;
+ const result = run(probe, owner, caller);
+ assert.equal(result.status, 0, result.stderr);
+ assert.equal(fs.realpathSync.native(result.stdout.trim()), fs.realpathSync.native(owner));
+ const missing = run(probe, path.join(directory, 'missing design app'), caller);
+ assert.equal(missing.status, 1);
+ assert.match(missing.stderr, /BLOCKED: cannot enter working_dir/);
+ }
+ }
+});
+
function captureWindowsOpener(t, file, filename) {
const { owner, caller } = fixture(t);
const block = shellBlocks(read(path.join(pluginRoot, file)))
@@ -609,3 +719,57 @@ test('PowerShell root guards and preview openers preserve literal paths', {
assert.equal(JSON.parse(result.stdout).path, call.path);
}
});
+
+for (const file of files) {
+ const name = path.relative(nativeRoot, file);
+ const content = read(file);
+ const blocks = shellBlocks(content);
+
+ for (const [eolName, eol] of [['LF', '\n'], ['CRLF', '\r\n']]) {
+ test(`${name} binds every shell call and file tool before project access (${eolName})`, () => {
+ assertRootBinding(content.replace(/\n/g, eol), rootLink);
+ });
+ }
+
+ test(`${name} rejects a deferred root preflight or a missing later cd`, () => {
+ assert.throws(() => assertRootBinding(content.replace(rootLink, '') + `\n${rootLink}`, rootLink));
+ assertEveryGuardIsRequired(content, guard, 'bash', rootLink);
+ });
+
+ test(`${name} executes project and package gates against the owner, not the launch directory`, (t) => {
+ const { owner, caller } = fixture(t);
+ const projectGate = blocks[0];
+ const packageGate = blocks.find((block) => block.includes("require('./package.json')"));
+ assert.ok(packageGate);
+ for (const gate of new Set([projectGate, packageGate])) {
+ const result = run(gate, owner, caller);
+ assert.equal(result.status, 0, result.stderr);
+ }
+
+ fs.unlinkSync(path.join(owner, 'app.config.js'));
+ const invalidProject = run(projectGate, owner, caller);
+ assert.equal(invalidProject.status, 1);
+ assert.match(invalidProject.stderr, /BLOCKED: working_dir is not an initialized app/);
+ fs.writeFileSync(path.join(owner, 'app.config.js'), 'module.exports = {};');
+
+ fs.writeFileSync(path.join(owner, 'package.json'), '{"dependencies":{}}');
+ fs.writeFileSync(path.join(caller, 'package.json'), JSON.stringify({ dependencies }));
+ const missingPackage = run(packageGate, owner, caller);
+ assert.equal(missingPackage.status, 1);
+ assert.match(missingPackage.stderr, /MISSING/);
+ });
+
+ test(`${name} roots relative write probes and stops before writes when cd fails`, (t) => {
+ const { directory, owner, caller } = fixture(t);
+ const probe = "node -e \"require('node:fs').writeFileSync('src/native/root-probe.txt', 'scoped')\"";
+ // Probe the actual per-call guard without executing network or type-check commands.
+ const command = `${blocks[0].split('\n')[0]}\n${probe}`;
+ assert.equal(run(command, owner, caller).status, 0);
+ assert.equal(fs.readFileSync(path.join(owner, 'src/native/root-probe.txt'), 'utf8'), 'scoped');
+ assert.equal(fs.existsSync(path.join(caller, 'src/native/root-probe.txt')), false);
+ const missingRoot = run(command, path.join(directory, 'missing app'), caller);
+ assert.equal(missingRoot.status, 1);
+ assert.match(missingRoot.stderr, /BLOCKED: cannot enter working_dir/);
+ assert.equal(fs.existsSync(path.join(caller, 'src/native/root-probe.txt')), false);
+ });
+}
diff --git a/plugins/mobile-apps/scripts/tests/camera-helper-example.test.js b/plugins/mobile-apps/scripts/tests/camera-helper-example.test.js
new file mode 100644
index 000000000..379277b91
--- /dev/null
+++ b/plugins/mobile-apps/scripts/tests/camera-helper-example.test.js
@@ -0,0 +1,207 @@
+'use strict';
+
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const path = require('node:path');
+const test = require('node:test');
+const vm = require('node:vm');
+
+const camera = fs.readFileSync(
+ path.resolve(__dirname, '../../skills/add-native/add-camera/SKILL.md'),
+ 'utf8',
+).replace(/\r\n?/g, '\n');
+
+const example = /```typescript\n(\/\/ src\/native\/camera\.ts[\s\S]*?)\n```/.exec(camera)?.[1];
+assert.ok(example, 'Expected the actual camera.ts example');
+
+function cameraFunctions(ImagePicker, warnings) {
+ // Only signatures/type declarations are omitted. Execute the actual JS bodies
+ // so assertions catch rejected permissions in the prescribed example, not just prose.
+ const functions = [
+ ['requestPermission', 'request', 'PermissionResult'],
+ ['permissionGranted', 'request', 'boolean'],
+ ['requestCameraPermission', '', 'boolean'],
+ ['requestMediaLibraryPermission', '', 'boolean'],
+ ['takePhoto', 'options', 'PhotoResult'],
+ ['pickImage', 'options', 'PhotoResult'],
+ ].map(([name, parameters, result]) => {
+ const pattern = new RegExp(
+ `(?:export )?async function ${name}\\([\\s\\S]*?\\): Promise<${result}> \\{\\n([\\s\\S]*?)\\n\\}`,
+ );
+ const match = pattern.exec(example);
+ assert.ok(match, `Missing function body: ${name}`);
+ return `async function ${name}(${parameters}) {\n${match[1]}\n}`;
+ });
+ return vm.runInNewContext(`${functions.join('\n')}\n({
+ requestCameraPermission, requestMediaLibraryPermission, takePhoto, pickImage
+ })`, {
+ ImagePicker,
+ Error,
+ console: { warn: (message) => warnings.push(message) },
+ });
+}
+
+for (const [operation, publicPermission, permissionApi, launchApi] of [
+ ['takePhoto', 'requestCameraPermission', 'requestCameraPermissionsAsync', 'launchCameraAsync'],
+ ['pickImage', 'requestMediaLibraryPermission', 'requestMediaLibraryPermissionsAsync', 'launchImageLibraryAsync'],
+]) {
+ function harness(request, launch) {
+ let launches = 0;
+ const warnings = [];
+ const api = {
+ [permissionApi]: request,
+ [launchApi]: launch && (async (...args) => {
+ launches += 1;
+ return launch(...args);
+ }),
+ };
+ return { functions: cameraFunctions(api, warnings), warnings, launches: () => launches };
+ }
+
+ test(`${operation} maps permission rejection without launching or throwing`, async () => {
+ const h = harness(
+ async () => { throw new Error('native permission unavailable'); },
+ async () => ({ canceled: true }),
+ );
+ const result = await h.functions[operation]();
+ assert.equal(result.ok, false);
+ assert.equal(result.reason, 'error');
+ assert.equal(result.message, 'native permission unavailable');
+ assert.equal(h.launches(), 0);
+ assert.equal(await h.functions[publicPermission](), false);
+ assert.deepEqual(h.warnings, ['Device permission request failed (error).']);
+ });
+
+ test(`${operation} distinguishes denied permission from failed or missing APIs`, async () => {
+ const denied = harness(async () => ({ status: 'denied' }), async () => ({ canceled: true }));
+ assert.equal((await denied.functions[operation]()).reason, 'permission-denied');
+ assert.equal(await denied.functions[publicPermission](), false);
+ assert.equal(denied.launches(), 0);
+ assert.deepEqual(denied.warnings, []);
+
+ const missing = harness(undefined, async () => ({ canceled: true }));
+ assert.equal((await missing.functions[operation]()).reason, 'unsupported');
+ assert.equal(await missing.functions[publicPermission](), false);
+ assert.equal(missing.launches(), 0);
+ assert.deepEqual(missing.warnings, ['Device permission request failed (unsupported).']);
+ });
+
+ test(`${operation} preserves successful output and cancellation behavior`, async () => {
+ const granted = async () => ({ status: 'granted' });
+ const h = harness(granted, async (options) => {
+ assert.equal(options.quality, 0.6);
+ return { canceled: false, assets: [{ uri: 'file:///photo.jpg', width: 100, height: 80 }] };
+ });
+ const result = await h.functions[operation]({ quality: 0.6 });
+ assert.equal(result.ok, true);
+ assert.equal(result.uri, 'file:///photo.jpg');
+ assert.equal(result.width, 100);
+ assert.equal(await h.functions[publicPermission](), true);
+ assert.deepEqual(h.warnings, []);
+
+ const cancelled = harness(granted, async () => ({ canceled: true }));
+ assert.equal((await cancelled.functions[operation]()).reason, 'cancelled');
+ });
+
+ test(`${operation} maps missing or rejecting launch APIs to failure results`, async () => {
+ const granted = async () => ({ status: 'granted' });
+ const missing = harness(granted, undefined);
+ assert.equal((await missing.functions[operation]()).reason, 'unsupported');
+ const rejected = harness(granted, async () => { throw new Error('launch failed'); });
+ assert.equal((await rejected.functions[operation]()).reason, 'error');
+ });
+}
+
+const packageCheck = /node - '<approved-artifact-keys-json>' <<'NODE'\n([\s\S]*?)\nNODE/.exec(camera)?.[1];
+assert.ok(packageCheck, 'Expected artifact-scoped package prerequisite script');
+
+function checkPackages(artifacts, dependencies) {
+ return vm.runInNewContext(packageCheck, {
+ require: (name) => {
+ assert.equal(name, './package.json');
+ return { dependencies };
+ },
+ process: {
+ argv: ['node', '-', JSON.stringify(artifacts)],
+ exit: (code) => { throw new Error(`exit ${code}`); },
+ },
+ console: { log: () => {}, error: () => {} },
+ });
+}
+
+test('scanner-only and upload-only prerequisites do not require capture packages', () => {
+ assert.doesNotThrow(() => checkPackages(['scanner'], { 'expo-camera': 'installed' }));
+ assert.doesNotThrow(() => checkPackages(['upload'], { 'expo-file-system': 'installed' }));
+ assert.doesNotThrow(() => checkPackages(['photo', 'gallery'], { 'expo-image-picker': 'installed' }));
+});
+
+test('public camera capabilities map to canonical artifact keys before the check', () => {
+ const mappings = [...camera.matchAll(/^\| `(camera|image-picker|barcode-scanner|qr-scanner)` \| `(\[[^\n]+\])` \|$/gm)];
+ assert.equal(mappings.length, 4);
+ const expected = {
+ camera: ['photo'],
+ 'image-picker': ['gallery'],
+ 'barcode-scanner': ['scanner'],
+ 'qr-scanner': ['scanner'],
+ };
+ for (const [row, capability, json] of mappings) {
+ const keys = JSON.parse(json);
+ assert.deepEqual(keys, expected[capability]);
+ assert.ok(camera.indexOf(row) < camera.indexOf("node - '<approved-artifact-keys-json>'"));
+ assert.doesNotThrow(() => checkPackages(keys, {
+ [keys[0] === 'scanner' ? 'expo-camera' : 'expo-image-picker']: 'installed',
+ }));
+ }
+ assert.match(camera, /Add `upload` only for an\nexplicitly approved custom Dataverse Image-upload helper/);
+ assert.match(camera, /not raw `\$ARGUMENTS`/);
+});
+
+test('combined artifact prerequisites require the union and reject invalid scope', () => {
+ assert.throws(() => checkPackages(['photo', 'scanner'], { 'expo-camera': 'installed' }), /exit 1/);
+ assert.doesNotThrow(() => checkPackages(['photo', 'scanner'], {
+ 'expo-camera': 'installed',
+ 'expo-image-picker': 'installed',
+ }));
+ for (const invalid of [[], ['unknown'], ['__proto__'], [1], 'scanner']) {
+ assert.throws(() => checkPackages(invalid, {}), /Expected a nonempty approved artifact list/);
+ }
+});
+
+test('public and planner capability tables agree with artifact package prerequisites', () => {
+ const publicSkill = fs.readFileSync(path.resolve(__dirname, '../../skills/add-native/SKILL.md'), 'utf8');
+ const planner = fs.readFileSync(path.resolve(__dirname, '../../agents/native-app-planner.md'), 'utf8');
+ for (const [capability, artifact, module] of [
+ ['camera', 'photo', 'expo-image-picker'],
+ ['image-picker', 'gallery', 'expo-image-picker'],
+ ['barcode-scanner', 'scanner', 'expo-camera'],
+ ]) {
+ const row = publicSkill.split('\n').find(line =>
+ line.startsWith(`| \`${capability}\``) && line.includes('| `src/native/'));
+ assert.ok(row, `Missing supported capability: ${capability}`);
+ assert.equal(row.split('|')[2].trim(), `\`${module}\``);
+ assert.ok(planner.includes(`| \`${capability}\` | \`${module}\` | \`/add-native ${capability}\` |`));
+ assert.doesNotThrow(() => checkPackages([artifact], { [module]: 'installed' }));
+ const otherModule = module === 'expo-camera' ? 'expo-image-picker' : 'expo-camera';
+ assert.throws(() => checkPackages([artifact], { [otherModule]: 'installed' }), /exit 1/);
+ }
+});
+
+test('scanner permission failures are handled and rendered, not left as rejected effects', () => {
+ const scanner = /```tsx\n(\/\/ src\/native\/barcodeScanner\.tsx[\s\S]*?)\n```/.exec(camera)?.[1];
+ assert.ok(scanner);
+ assert.match(scanner, /async function requestScannerPermission\(\)[\s\S]*try[\s\S]*await requestPermission\(\);[\s\S]*catch[\s\S]*setPermissionError/);
+ assert.match(scanner, /if \(permissionError\)[\s\S]*<Text>\{permissionError\}<\/Text>/);
+ assert.match(scanner, /!permissionAttemptedRef\.current/);
+ assert.doesNotMatch(scanner, /^\s+requestPermission\(\);$/m);
+});
+
+test('camera summary reports only fulfilled requested artifacts and conditional examples', () => {
+ const summary = camera.slice(camera.indexOf('### Step 7 — Summary'), camera.indexOf('## Notes'));
+ assert.match(summary, /<fulfilled requested capabilities only>/);
+ assert.match(summary, /<one row per requested path: created \/ updated \/ reused>/);
+ assert.match(summary, /Do not list `camera\.ts` for scanner-only or upload-only results/);
+ assert.doesNotMatch(summary, /Camera \+ image picker wrappers generated|Camera wrapper\s+: src\/native\/camera\.ts/);
+ for (const capability of ['capture and custom Image upload', 'gallery picking', 'scanner support']) {
+ assert.ok(summary.includes(`Include this usage only when ${capability} `));
+ }
+});
diff --git a/plugins/mobile-apps/scripts/tests/data-model-edit-scope-contract.test.js b/plugins/mobile-apps/scripts/tests/data-model-edit-scope-contract.test.js
index 56a57c8bc..4cf47028b 100644
--- a/plugins/mobile-apps/scripts/tests/data-model-edit-scope-contract.test.js
+++ b/plugins/mobile-apps/scripts/tests/data-model-edit-scope-contract.test.js
@@ -10,6 +10,7 @@ const read = (file) => fs.readFileSync(path.join(pluginRoot, file), 'utf8').repl
const skill = (name) => read(`skills/${name}/SKILL.md`);
const setup = skill('setup-datamodel');
const seed = skill('add-sample-data');
+const edit = skill('edit-app');
const create = skill('create-mobile-app');
for (const [eolName, eol] of [['LF', '\n'], ['CRLF', '\r\n']]) {
@@ -149,6 +150,11 @@ test('data-model proposals and actual inventory keep separate lifecycle ownershi
assert.match(setup, /verified materialized\nmanifest is updated after execution\/verification/);
assert.match(setup, /return a non-success status rather than claiming the plan is fully applied/);
assert.match(setup, /Connector-only work without Dataverse does\nnot require or create a Dataverse manifest/);
+ const plan = section(edit, '### Step 4', '### Step 5');
+ assert.match(plan, /saved plan describes approved intent, not successful application/);
+ assert.match(plan, /never replay stale scratch output for an unrelated edit/);
+ assert.match(plan, /manifest\.json` only from verified schema\/service outcomes/);
+ assert.match(plan, /Record any failure and\nremaining operations in memory-bank/);
});
test('setup plan-only exits before saving or applying every proposal path', () => {
@@ -231,6 +237,9 @@ test('offline retirement survives no-op addition checks, summaries, and resume',
assert.match(offline, /existing `offlineRetirement` outcomes unchanged/);
assert.match(summary, /`pending` returns `DONE_WITH_CONCERNS`, not a clean `DONE`/);
assert.match(summary, /whether to retain or remove that coverage is pending/);
+ assert.match(edit, /Carry each leaf's `offlineRetirement` status into Step 8/);
+ assert.match(edit, /If any `offlineRetirement` outcome is `pending`, return `DONE_WITH_CONCERNS`/);
+ assert.match(edit, /Never remove profile entries automatically/);
});
test('sample seeding resolves a required explicit scope before auth or discovery', () => {
@@ -243,13 +252,6 @@ test('sample seeding resolves a required explicit scope before auth or discovery
assert.match(scope, /return without cloud calls or writes/);
assert.match(scope, /overlaps `retiringTables`, stop/);
assert.match(scope, /Do not silently drop unknown\nnames/);
- assert.match(scope, /For `--plan-only` or a planning-phase handoff/);
- assert.match(scope, /media policy before Step 5\. Planning approval is not insertion approval/);
- assert.match(scope, /Do not generate media files, insert\/update\/upload records, or change the app\nplan, manifest, or seeded-data history on this path/);
- const discovery = section(seed, '### Step 1', '### Step 2');
- assert.match(discovery, /^node "\$\{PLUGIN_ROOT\}\/scripts\/resolve-environment\.js" "\$environment_id" --no-cache --require-tenant$/m);
- assert.match(discovery, /Incomplete or conflicting identity returns `NEEDS_CONTEXT`/);
- assert.match(discovery, /Do not remove the safety flags, select another\nenvironment, or persist resolver output to recover/);
assert.ok(seed.indexOf('### Step 0') < seed.indexOf('### Step 1'));
});
@@ -274,8 +276,6 @@ test('lookup dependencies never implicitly expand seed scope', () => {
test('seed preview does not treat row counts or cancellation as insertion approval', () => {
const preview = section(seed, '#### Step 4d', '### Step 5');
- assert.match(preview, /For `--plan-only` or a planning-phase handoff, return the preview and STOP here/);
- assert.match(preview, /neither an earlier approval nor a populated manifest overrides that boundary/);
assert.match(preview, /exact seed tables\/count policy and\nany media writes are already approved/);
assert.match(preview, /Otherwise obtain explicit approval/);
assert.match(preview, /Row counts prevent duplicate volume; they are not consent/);
@@ -283,6 +283,26 @@ test('seed preview does not treat row counts or cancellation as insertion approv
assert.doesNotMatch(preview, /No confirmation prompt/);
});
+test('seed proposal-only calls stop before media generation, insertion, and history writes', () => {
+ const scope = section(seed, '### Step 0', '## Prototype Seed Reuse');
+ const preview = section(seed, '#### Step 4d', '### Step 5');
+ assert.match(scope, /For `--plan-only` or a planning-phase handoff/);
+ assert.match(scope, /media policy before Step 5\. Planning approval is not insertion approval/);
+ assert.match(scope, /Do not generate media files, insert\/update\/upload records, or change the app\nplan, manifest, or seeded-data history on this path/);
+ assert.match(preview, /For `--plan-only` or a planning-phase handoff, return the preview and STOP here/);
+ assert.match(preview, /neither an earlier approval nor a populated manifest overrides that boundary/);
+});
+
+test('seed environment discovery stays non-persisting and bound to the selected app', () => {
+ const discovery = section(seed, '### Step 1', '### Step 2');
+ assert.match(discovery, /node -p "require\('\.\/power\.config\.json'\)\.environmentId \|\| ''"/);
+ assert.match(discovery, /^node "\$\{PLUGIN_ROOT\}\/scripts\/resolve-environment\.js" "\$environment_id" --no-cache --require-tenant$/m);
+ assert.match(discovery, /Capture the \*\*environment URL\*\*, \*\*environment ID\*\*, and \*\*tenant ID\*\*/);
+ assert.match(discovery, /require a match with the selected app and any supplied\s+owner context/);
+ assert.match(discovery, /Incomplete or conflicting identity returns `NEEDS_CONTEXT`/);
+ assert.match(discovery, /Do not remove the safety flags, select another\nenvironment, or persist resolver output to recover/);
+});
+
test('batches, prototype seeds, media, and retries all honor the same allowlist', () => {
const prototype = section(seed, '## Prototype Seed Reuse', '### Step 1');
const batches = section(seed, '#### Step 5b', '#### Step 5c');
@@ -297,6 +317,20 @@ test('batches, prototype seeds, media, and retries all honor the same allowlist'
assert.match(resume, /never retry a retiring table/);
});
+test('edit passes a seed allowlist and excludes the approved retirement set', () => {
+ const approval = section(edit, '### Step 3', '### Step 4');
+ const execution = section(edit, '### Step 5', '#### Step 5.5');
+ assert.match(approval, /Exact sample-data table allowlist and count\/media policy/);
+ assert.match(execution, /Distinguish `createdThisEdit` from historical\n\s+manifest `status: new`/);
+ assert.match(execution, /empty scope means skip seeding/);
+ const handoff = execution.slice(execution.indexOf('Invoke skill: /add-sample-data'));
+ assert.match(handoff, /MOBILE_APP_ORCHESTRATING=1/);
+ assert.match(handoff, /working_dir: <working_dir>/);
+ assert.match(handoff, /--tables "<approved-seed-table-logical-names>"/);
+ assert.match(handoff, /--exclude-tables "<retiring-table-logical-names-or-empty>"/);
+ assert.match(handoff, /required parent outside\nthe allowlist returns `NEEDS_CONTEXT`/);
+});
+
test('creation supplies a bounded sample-data handoff too', () => {
const seeding = section(create, '### Step 8.5', '### Offline profile');
assert.match(seeding, /excluding standard system tables by default/);
diff --git a/plugins/mobile-apps/scripts/tests/design-dark-palette-contract.test.js b/plugins/mobile-apps/scripts/tests/design-dark-palette-contract.test.js
new file mode 100644
index 000000000..23de707d5
--- /dev/null
+++ b/plugins/mobile-apps/scripts/tests/design-dark-palette-contract.test.js
@@ -0,0 +1,325 @@
+'use strict';
+
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const path = require('node:path');
+const test = require('node:test');
+const vm = require('node:vm');
+
+const root = path.resolve(__dirname, '../..');
+const read = (file) => fs.readFileSync(path.join(root, file), 'utf8').replace(/\r\n?/g, '\n');
+const integration = read('skills/design-system/references/tamagui-integration.md');
+const design = read('skills/design-system/SKILL.md');
+const refresh = read('skills/design-system/references/refresh-flow.md');
+const inputs = read('skills/design-system/references/input-modes.md');
+const schema = read('skills/design-system/references/design-system-schema.md');
+const create = read('skills/create-mobile-app/SKILL.md');
+const branch = integration.slice(
+ integration.indexOf('## Approved dark palette (conditional)'),
+ integration.indexOf('## Restored dark state'),
+);
+const history = refresh.slice(refresh.indexOf('## Snapshot contract'), refresh.indexOf('## Allowed dimensions'));
+const rollback = refresh.slice(refresh.indexOf('### `/design-system --rollback'));
+const prewrite = design.slice(
+ design.indexOf('## Sub-step 3.5 —'),
+ design.indexOf('## Sub-step 4 —'),
+);
+const generation = design.slice(
+ design.indexOf('## Sub-step 4 —'),
+ design.indexOf('## Sub-step 5 —'),
+);
+const confirmation = design.slice(
+ design.indexOf('## Sub-step 6 —'),
+ design.indexOf('## Sub-step 6.5 —'),
+);
+
+function inOrder(text, ...instructions) {
+ let previous = -1;
+ for (const instruction of instructions) {
+ const position = text.indexOf(instruction);
+ assert.ok(position > previous, `Missing or out-of-order instruction: ${instruction}`);
+ previous = position;
+ }
+}
+
+// These contracts check workflow instructions and documented snippets, not history execution or native rendering.
+
+test('direct design entry uses the authoritative shared routing preflight', () => {
+ const entry = design.slice(design.indexOf('**Entry routing:**'), design.indexOf('Source of truth'));
+ assert.match(entry, /\[App feature entry points\]\(\.\.\/\.\.\/shared\/shared-instructions\.md#app-feature-entry-points\)/);
+ assert.match(entry, /preflight before the workflow below/);
+});
+
+test('custom dark artifacts have one named export and a complete non-literal color contract', () => {
+ assert.match(branch, /export const darkTokens =/);
+ assert.match(branch, /satisfies \{ color: \{ \[K in keyof BrandTokens\['color'\]\]: string \} \}/);
+ for (const key of ['bg', 'surface', 'primary', 'accent', 'text', 'textMuted', 'border',
+ 'statusSuccess', 'statusWarning', 'statusDanger', 'statusInfo']) {
+ assert.match(branch, new RegExp(`\\b${key}: '\\{\\{approved-dark-`));
+ }
+ assert.match(branch, /import \{ darkTokens \} from '\.\/brand\/tokens\.dark'/);
+ assert.match(branch, /Missing files, missing exports\/keys, or unresolved placeholder values block/);
+ assert.match(design, /Write `brand\/tokens\.dark\.ts` using the named `darkTokens` export/);
+});
+
+test('ordinary brand integration keeps its prior defaults without requiring a dark file', () => {
+ const base = integration.slice(integration.indexOf('## Brand Import'), integration.indexOf('## Approved dark palette'));
+ assert.doesNotMatch(base, /tokens\.dark/);
+ assert.match(base, /defaultConfig\.themes\.dark/);
+ assert.match(base, /accent: brandTokens\.color\.accent/);
+ assert.match(branch, /keep the Brand Import example above unchanged and do not import a nonexistent\ndark file/);
+ assert.match(branch, /unapproved file's presence alone does not authorize wiring it/);
+});
+
+test('both creation and edit apply custom-dark wiring before using the resolved provider theme', () => {
+ const edit = read('skills/edit-app/SKILL.md');
+ assert.match(create, /\*\*Approved dark palette\*\* branch first: import `darkTokens`/);
+ assert.match(create, /derive `appDarkTheme` from\n`darkTokens\.color`/);
+ assert.match(edit, /\*\*Approved dark\n\s+palette\*\* branch: wire `darkTokens\.color` into `appDarkTheme`/);
+ assert.match(edit, /provider's `brandedDarkTheme`/);
+ assert.match(integration, /darkTheme=\{brandedDarkTheme\}/);
+});
+
+test('history instructions capture dark presence and approval before any mutation', () => {
+ assert.match(history, /refresh, reskin, `--add-dark-mode`, changing or\nremoving a custom dark palette, and rollback/);
+ assert.match(history, /After approval and \*\*before the\nfirst write or deletion\*\*, including drift resolution/);
+ for (const member of ['<id>.md', '<id>.tokens.ts', '<id>.tokens.dark.ts', '<id>.state.json']) {
+ assert.ok(history.includes(`| \`${member}\` |`), `Missing snapshot member: ${member}`);
+ }
+ assert.match(history, /Exact current `brand\/tokens\.dark\.ts`, only when present/);
+ assert.match(history, /Never derive this copy from the light palette/);
+ const examples = [...history.matchAll(/```json\n([\s\S]*?)\n```/g)].map((match) => JSON.parse(match[1]));
+ assert.deepEqual(examples, [
+ { darkTokens: 'present', darkPalette: 'approved' },
+ { darkTokens: 'absent', darkPalette: 'default' },
+ ]);
+ assert.match(history, /Presence is not approval/);
+ assert.match(history, /"darkTokens": "present", "darkPalette": "default"/);
+ assert.match(history, /failed or incomplete\nbackup blocks the change/);
+ assert.match(history, /Keep the pre-write snapshot unchanged afterward/);
+ assert.match(refresh, /Cancellation leaves both artifacts unchanged and preserves the dark artifact's\npresence, contents, and approved selection/);
+});
+
+test('rollback instructions restore exact saved dark contents when both versions have a palette', () => {
+ const action = /^\s*\| present \| present \| (.+) \|$/m.exec(rollback)?.[1];
+ assert.ok(action, 'Expected the present-to-present rollback instruction');
+ assert.match(action, /Replace `brand\/tokens\.dark\.ts` with the exact saved target contents/);
+ assert.match(action, /Do not regenerate from light tokens or keep the newer dark values/);
+ assert.match(rollback, /\| absent \| present \| Restore `brand\/tokens\.dark\.ts` from the exact saved target contents/);
+ const confirmation = rollback.indexOf('Obtain confirmation before any write');
+ const backup = rollback.indexOf('Snapshot current state to `.history/`');
+ const restore = rollback.indexOf('Restore the approved spec and saved light tokens exactly');
+ assert.ok(confirmation >= 0 && confirmation < backup && backup < restore);
+ assert.match(rollback, /verify the safety backup before any restore or deletion/);
+});
+
+test('rollback instructions remove only an approved target-absent dark artifact', () => {
+ const action = /^\s*\| present \| absent \| (.+) \|$/m.exec(rollback)?.[1];
+ assert.ok(action, 'Expected the present-to-absent rollback instruction');
+ assert.match(action, /Remove only the current `brand\/tokens\.dark\.ts`/);
+ assert.match(action, /after explicit approval of that removal and a verified safety backup/);
+ assert.match(action, /Do not delete any unrelated files/);
+ assert.match(rollback, /\| absent \| absent \| Leave `brand\/tokens\.dark\.ts` absent; do not generate or import it/);
+ assert.match(history, /Legacy snapshots without `\.state\.json` have \*\*unknown\*\*, not absent, dark state/);
+ assert.match(history, /do not infer\npermission to delete a dark file from a missing history member/);
+ assert.match(history, /without its saved payload blocks rollback rather than\nre-deriving colors/);
+});
+
+test('refresh and read-only history instructions preserve the no-dark default', () => {
+ assert.match(refresh, /If absent and default dark is selected → keep it absent; no dark file is required/);
+ assert.match(refresh, /dark-only change does not rewrite light tokens/);
+ assert.match(refresh, /If dark state is not in scope, leave `brand\/tokens\.dark\.ts` unchanged when\n\s+present and absent when absent/);
+ assert.match(refresh, /Default dark mode still works without it/);
+ assert.match(refresh, /Removing a custom palette deletes only `brand\/tokens\.dark\.ts` after the\n\s+explicit removal approval and verified safety snapshot/);
+ assert.match(refresh, /including `brand\/tokens\.dark\.ts` contents or its creation\/removal/);
+ assert.match(refresh, /`--history` and `--diff` are\nread-only; do not materialize missing artifacts/);
+ assert.match(refresh, /prune only the oldest snapshot's known\nmembers together/);
+});
+
+test('restored approved state drives both runtime dark branches and the provider', () => {
+ const restored = integration.slice(
+ integration.indexOf('## Restored dark state'),
+ integration.indexOf('## Root Provider Wiring'),
+ );
+ assert.match(rollback, /Return the restored approved selection to the owner/);
+ assert.match(rollback, /reapply\n\s+\[Tamagui integration\]\(\.\/tamagui-integration\.md#restored-dark-state\)/);
+ assert.match(restored, /Do not choose a branch from the\nmere presence of `brand\/tokens\.dark\.ts` or the abandoned newer plan/);
+ assert.match(restored, /`appDarkTheme` consumes\n\s+the restored `darkTokens\.color`, not the previous palette/);
+ assert.match(restored, /remove only stale\n\s+`tokens\.dark` imports and custom-dark overrides/);
+ assert.match(restored, /unchanged Brand Import default dark declaration, retaining Config v5\n\s+dark surfaces\/text/);
+ assert.match(restored, /Do not import or\n\s+create an absent dark file/);
+ assert.match(restored, /rebuild `brandedDarkTheme` from the same resolved\n\s+`appDarkTheme`/);
+ assert.match(rollback, /Artifact-only\n\s+rollback reports this outstanding runtime work/);
+});
+
+test('schema and creation guidance defer to the authoritative default and approved-custom branches', () => {
+ assert.match(schema, /tokens\.dark\.ts\s+← optional approved custom-dark palette/);
+ assert.match(schema, /`brand\/tokens\.dark\.ts` is optional, not a prerequisite for default dark mode/);
+ assert.match(schema, /\[snapshot contract\]\(\.\/refresh-flow\.md#snapshot-contract\)/);
+ for (const anchor of ['brand-import', 'approved-dark-palette-conditional', 'root-provider-wiring']) {
+ assert.ok(schema.includes(`./tamagui-integration.md#${anchor}`), `Missing integration branch: ${anchor}`);
+ }
+ assert.match(schema, /After rollback, choose the\n\s+branch from the restored approved state/);
+ assert.doesNotMatch(schema, /export const appDarkTheme|createPowerAppsTamaguiConfig\(/);
+ const explanation = create.slice(
+ create.indexOf('Without an approved custom dark palette, the exported dark app theme'),
+ create.indexOf('### Step 10 — Add connectors'),
+ );
+ assert.match(explanation, /Without an approved custom dark palette/);
+ assert.match(explanation, /Config v5 dark surfaces and text/);
+ assert.match(explanation, /With an approved custom dark palette, `appDarkTheme` instead resolves the full\n`darkTokens\.color` palette, including its surfaces and text/);
+ assert.doesNotMatch(create, /The generated schema has one brand palette, so the exported dark app theme/);
+ assert.match(integration, /This default dark branch keeps Config v5/);
+ assert.match(integration, /When custom dark is approved, apply the conditional branch below instead/);
+});
+
+test('generation and dark-mode writes use the same pre-write snapshot contract', () => {
+ assert.match(prewrite, /After approval and before the first write or deletion/);
+ assert.match(prewrite, /refresh-flow\.md#snapshot-contract/);
+ assert.match(prewrite, /optional `brand\/tokens\.dark\.ts` and explicit absence/);
+ assert.match(generation, /write only the candidate approved in Sub-step 3\.5, after its verified\npre-write backup/);
+ const dark = design.slice(
+ design.indexOf('## Dark mode —'),
+ design.indexOf('## Version history'),
+ );
+ assert.match(dark, /After approval, capture the pre-write \[snapshot contract\]/);
+ assert.ok(dark.indexOf('capture the pre-write') < dark.indexOf('4. Write'));
+ assert.match(dark, /7\. Retain the pre-write snapshot/);
+ assert.doesNotMatch(dark, /7\. Snapshot \+ history/);
+});
+
+test('full-design rerun instructions approve the concrete delta and verify backup before writing', () => {
+ const paths = design.slice(design.indexOf('**Branches:**'), design.indexOf('**On ANY input failure'));
+ for (const option of ['a', 'b']) {
+ const line = paths.split('\n').find((value) => value.startsWith(`- **(${option})**`));
+ assert.ok(line, `Missing full-design branch (${option})`);
+ assert.match(line, /Sub-step 3\.5 before Sub-steps 4–7/);
+ }
+ inOrder(prewrite,
+ '1. Prepare the complete candidate without live writes.',
+ 'before/after delta: palette values, typography, component/density/negative',
+ '2. Obtain explicit approval of that concrete delta',
+ '4. After approval and before the first write or deletion',
+ 'Verify every',
+ 'expected backup member; a failed or incomplete backup blocks all live writes.',
+ '5. Apply only the approved candidate',
+ );
+ inOrder(design, '## Sub-step 3.5 —', '## Sub-step 4 —', '## Sub-step 5 —', '## Sub-step 6 —');
+ assert.match(prewrite, /refresh-flow\.md#step-5--update-the-spec/);
+ assert.match(confirmation, /review of the already approved delta, not the first\nauthorization to write/);
+});
+
+test('rerun approval reuses only matching current owner scope without duplicate prompts', () => {
+ assert.match(prewrite, /owner's matching approved scope \*\*without another prompt\*\*/);
+ assert.match(prewrite, /owner,\n\s+absolute working directory, implementation phase \(or explicitly delegated\n\s+design gate\), and exact proposed changes must match/);
+ assert.match(prewrite, /A cost choice, style\n\s+pick, input flag, stale Design record, or orchestration marker alone is not\n\s+approval/);
+ assert.match(prewrite, /Changed or missing caller scope\n\s+returns `NEEDS_CONTEXT` to the owner/);
+ assert.match(confirmation, /continue without another confirmation prompt/);
+ assert.match(prewrite, /If the candidate or\n\s+current baseline changes after approval, return to this boundary/);
+});
+
+test('cancelled or ambiguous rerun approval forbids live writes, snapshots, and approval records', () => {
+ const cancelled = prewrite.slice(prewrite.indexOf('3. Cancellation'), prewrite.indexOf('4. After approval'));
+ assert.match(cancelled, /Cancellation, dismissal, silence, or an ambiguous answer means \*\*no live\n\s+writes\*\*: stop or clarify/);
+ assert.match(cancelled, /Do not create a history snapshot, overwrite spec,\n\s+tokens, galleries\/previews, persist pending memory-bank notes, change the\n\s+approved dark selection/);
+ assert.match(cancelled, /or report the candidate as applied\/locked/);
+ assert.match(design, /Keep `visual_companion: <yes\|no\|skip>` pending/);
+ assert.match(design, /Keep selection\/rejection notes pending on reruns/);
+ assert.match(design, /do not repair drift during detection/);
+ assert.match(prewrite, /scope, preserve its exact contents, presence\/absence, and approved selection/);
+ assert.match(prewrite, /default dark never requires creating a dark file/);
+});
+
+test('minimal defaults, brand previews, and imported specs cannot bypass the rerun write boundary', () => {
+ const paths = design.slice(design.indexOf('**Branches:**'), design.indexOf('**On ANY input failure'));
+ assert.match(paths, /\*\*\(c\) Brand preview\*\*[^\n]*Sub-step 3\.5 before applying it/);
+ assert.match(paths, /\*\*\(c\) Apply defaults \/ \(d\)[\s\S]*\*\*Minimal Sub-step 4\*\*[^\n]*Sub-step 3\.5 before writing it/);
+ assert.match(paths, /prior full design exists[^\n]*concrete token delta and corresponding spec-section updates together, or preserve both unchanged/);
+ assert.match(paths, /Cancellation or missing approval never authorizes a write/);
+ assert.doesNotMatch(paths, /Never return DONE without writing/);
+ const passthrough = paths.slice(paths.indexOf('**`--design-spec` passthrough:**'));
+ inOrder(passthrough, 'without copying into `brand/`', 'Run Sub-step 3.5', 'apply only the', 'continue to Sub-steps 5–7');
+ const importMode = inputs.slice(inputs.indexOf('### `--design-spec'), inputs.indexOf('### `--stylesheet'));
+ inOrder(importMode, 'without copying into brand/', "Sub-step 3.5's approval + backup boundary", 'Apply the approved replacement');
+ assert.doesNotMatch(inputs, /SKIP Sub-steps 3 AND 4|skips Sub-steps 3\+4/);
+});
+
+test('planning and partial prior state cannot fall through to first-time writes', () => {
+ const setup = design.slice(design.indexOf('**Write boundary (all paths):**'), design.indexOf('## Sub-step 1 —'));
+ assert.match(setup, /`--plan-only` or a planning-phase handoff returns\nonly a proposal; do not write brand artifacts, previews, history, or memory-bank/);
+ assert.match(setup, /existing spec, light or\ndark token file, gallery, history, or record of a previously applied design makes\nthis a rerun/);
+ assert.match(setup, /A new creation plan alone is not prior\nbrand state/);
+ assert.match(setup, /first-time drafts generated in this invocation remain drafts during\nedit\/regeneration/);
+ assert.match(setup, /Every generation\/reskin rerun uses \*\*Sub-step 3\.5\*\* before its first live write/);
+ assert.match(setup, /Dedicated refresh,\ndark-mode, and rollback commands retain their own equivalent approval\/backup\nflows; do not add a second gate/);
+ assert.match(prewrite, /Partial or unknown prior state is not first-time generation/);
+ assert.match(prewrite, /stop and resolve it with the owner rather\n\s+than inventing an initial snapshot/);
+});
+
+test('edits and regeneration reapprove new deltas before replacing an existing design', () => {
+ const edits = confirmation.slice(confirmation.indexOf('**On [edit X]:**'), confirmation.indexOf('**On [confirm]:**'));
+ inOrder(edits, 'without live writes', 'return to Sub-step 3.5', 'verified backup before updating anything', 'Apply only that approved section');
+ assert.match(edits, /An earlier approval does not cover changed values or expanded scope/);
+ const regeneration = confirmation.slice(confirmation.indexOf('**On [regenerate]:**'), confirmation.indexOf('**On [skip'));
+ assert.match(regeneration, /new direction invalidates\nthe previous candidate approval/);
+ assert.match(regeneration, /reruns must pass Sub-step 3\.5 again before any\nreplacement/);
+ assert.match(regeneration, /First-time regenerated drafts still wait for confirmation/);
+});
+
+test('first-time generation records complete history only after confirmation, never for drafts', () => {
+ const completion = confirmation.slice(confirmation.indexOf('**History completion (after confirmation):**'));
+ inOrder(design, '## Sub-step 4 —', '## Sub-step 5 —', '## Sub-step 6 —',
+ '**On [confirm]:**', '**History completion (after confirmation):**', '## Sub-step 6.5 —');
+ assert.match(generation, /History completion occurs after confirmation in Sub-step 6, not here/);
+ assert.match(confirmation, /In either approved case, complete history below before continuing to Sub-step 6\.5/);
+ assert.doesNotMatch(generation, /\*\*History completion|record one complete|approved initial snapshot/);
+ assert.match(prewrite, /Do not create an approved initial snapshot before that confirmation/);
+ assert.match(completion, /If a pre-write snapshot was captured, retain it unchanged/);
+ assert.match(completion, /Do not create a\n\s+second post-write `-initial` snapshot/);
+ assert.match(completion, /Only for first-time generation with no prior brand state/);
+ assert.match(completion, /record one complete\n\s+approved initial snapshot after generation/);
+ assert.match(completion, /after generation \*\*and explicit confirmation\*\* of\n\s+that candidate/);
+ assert.match(completion, /light tokens, optional dark-token payload, and explicit presence\/approval\n\s+state/);
+ assert.match(completion, /Verify every expected member before reporting success/);
+ assert.match(completion, /failed or incomplete\n\s+snapshot is a visible failure/);
+ assert.match(confirmation, /as draft, without\nan approved initial snapshot or a locked-design record/);
+ assert.match(confirmation, /cancel, dismissal, silence, or ambiguity[\s\S]*without further writes, history creation, or approval\/lock/);
+ assert.match(history, /after generation and explicit confirmation of that\ncandidate/);
+ assert.match(history, /never before confirmation\nor for an unconfirmed draft/);
+ assert.doesNotMatch(generation, /cp brand\/design-system\.md|2>\/dev\/null|\|\| true/);
+});
+
+test('the conditional example forwards approved dark surfaces and text to provider values', () => {
+ const theme = /export const appDarkTheme = (withPowerAppsSemanticAliases\([\s\S]*?\n\));/.exec(branch)?.[1];
+ const provider = /const brandedDarkTheme: ThemeTokens = (\{[\s\S]*?\n\});/.exec(integration)?.[1];
+ assert.ok(theme, 'Expected the concrete conditional dark-theme declaration');
+ assert.ok(provider, 'Expected the concrete host provider mapping');
+ const colors = { bg: '#121212', surface: '#202020', text: '#eeeeee', accent: '#77aaff' };
+ let calls = 0;
+ const result = vm.runInNewContext(
+ `const appDarkTheme = ${theme}; const brandedDarkTheme = ${provider}; brandedDarkTheme;`,
+ {
+ darkTokens: { color: colors },
+ defaultConfig: { themes: { dark: { baseline: true } } },
+ hostDarkTheme: { preservedHostValue: 'keep' },
+ // Stub host color resolution; this tests the documented data path, not host implementation.
+ withPowerAppsSemanticAliases: (base, palette) => {
+ calls += 1;
+ assert.equal(base.baseline, true);
+ assert.equal(palette, colors);
+ return {
+ surface0: palette.bg,
+ surface1: palette.surface,
+ text0: palette.text,
+ accentBase: palette.accent,
+ };
+ },
+ },
+ );
+ assert.equal(calls, 1);
+ assert.equal(result.surface0, colors.bg);
+ assert.equal(result.surface1, colors.surface);
+ assert.equal(result.text0, colors.text);
+ assert.equal(result.accentBase, colors.accent);
+ assert.equal(result.preservedHostValue, 'keep');
+});
diff --git a/plugins/mobile-apps/scripts/tests/native-helper-reuse-contract.test.js b/plugins/mobile-apps/scripts/tests/native-helper-reuse-contract.test.js
new file mode 100644
index 000000000..f72b6d04d
--- /dev/null
+++ b/plugins/mobile-apps/scripts/tests/native-helper-reuse-contract.test.js
@@ -0,0 +1,357 @@
+'use strict';
+
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const path = require('node:path');
+const test = require('node:test');
+
+const pluginRoot = path.resolve(__dirname, '../..');
+// Contracts are prose, so Git's LF/CRLF checkout setting must not change their meaning.
+const normalize = (text) => text.replace(/\r\n?/g, '\n');
+const read = (file) => normalize(fs.readFileSync(path.join(pluginRoot, file), 'utf8'));
+const referencePath = 'shared/references/native-artifact-compatibility.md';
+const reference = read(referencePath);
+const native = read('skills/add-native/SKILL.md');
+const helpers = [
+ {
+ name: 'add-camera',
+ reconcile: '### Step 2a — Reconcile requested artifacts',
+ writes: [
+ '### Step 3 — Write camera wrapper',
+ '### Step 3b — Write barcode/QR scanner control when requested',
+ '### Step 5 — Write image upload helper',
+ ],
+ verify: '### Step 6 — Type-check',
+ summary: '### Step 7 — Summary',
+ files: ['camera.ts', 'barcodeScanner.tsx', 'cameraUpload.ts'],
+ },
+ ...[
+ ['add-pdf-report', 'pdfReport.ts', 6, 8],
+ ['add-pdf-viewer', 'pdfViewer.ts', 5, 8],
+ ['add-pen-input', 'penInput.ts', 6, 9],
+ ].map(([name, file, verify, summary]) => ({
+ name,
+ reconcile: '### 2a. Reconcile requested artifacts',
+ writes: [`### 3. Write or verify \`src/native/${file}\``],
+ verify: `### ${verify}. Type-check`,
+ summary: `### ${summary}. Summary`,
+ files: [file],
+ })),
+ {
+ name: 'add-geolocation',
+ reconcile: '## 2a. Reconcile requested artifacts',
+ writes: ['## 3. Write `src/native/geolocation.ts`'],
+ verify: '## 5. Type-check and summary',
+ files: ['geolocation.ts'],
+ },
+];
+const skill = (name) => read(`skills/add-native/${name}/SKILL.md`);
+
+function section(text, heading) {
+ const start = text.indexOf(`${heading}\n`);
+ assert.ok(start >= 0, `Missing section: ${heading}`);
+ const rest = text.slice(start + heading.length + 1);
+ const next = rest.search(/^#{2,3} /m);
+ return next < 0 ? rest : rest.slice(0, next);
+}
+
+function prose(text) {
+ return text.replace(/^```[^\n]*\n[\s\S]*?^```[ \t]*$/gm, '');
+}
+
+// These are instruction-contract regressions, not model runs or native-runtime tests.
+// Check the invoked preflight, each actual write branch, and the postflight together:
+// a correct outer paragraph must not mask an unchecked nested implementation.
+function assertHelperContract(raw, helper) {
+ const text = normalize(raw);
+ const gate = section(text, helper.reconcile);
+ assert.match(gate, /Read and execute \[native-artifact-compatibility\.md\]/);
+ assert.ok(gate.includes(`(\${PLUGIN_ROOT}/${referencePath})`));
+ assert.match(gate, /Steps 1–3/);
+ assert.match(gate, /before any writes or reuse/);
+ assert.match(gate, /do not repeat a valid scoped approval/);
+ assert.match(gate, /`NEEDS_CONTEXT` to\s+the owner/);
+ assert.match(gate, /asks standalone/);
+ for (const file of helper.files) {
+ assert.ok(gate.includes(`src/native/${file}`), `${helper.name} must inventory ${file}`);
+ }
+ for (const heading of helper.writes) {
+ assert.ok(text.indexOf(helper.reconcile) < text.indexOf(heading), 'Reconcile before each write');
+ const write = prose(section(text, heading));
+ assert.match(write, /Apply Step 2a's (?:independent )?decision/);
+ assert.match(write, /reuse unchanged only if compatible/);
+ assert.match(write, /approved scoped\s+update/);
+ }
+ assert.doesNotMatch(
+ prose(text),
+ /If (?:the (?:file|wrapper)|it) (?:already )?exists[^\n]*(?:skip|do not overwrite|do NOT overwrite|patch only if)/i,
+ );
+ assert.doesNotMatch(prose(text), /append a comment noting|Create or patch `src\/native\//);
+ const verification = section(text, helper.verify);
+ assert.match(verification, /shared compatibility contract's\s+Step 4/);
+ assert.match(verification, /Type-check success alone is insufficient/);
+ assert.match(verification, /do not fix screen\/generated\s+files/i);
+ const result = helper.summary ? section(text, helper.summary) : verification;
+ assert.match(result, /shared compatibility result/);
+ assert.match(result, /created\/updated\/reused paths/);
+}
+
+for (const helper of helpers) {
+ const content = skill(helper.name);
+ for (const [name, eol] of [['LF', '\n'], ['CRLF', '\r\n']]) {
+ test(`${helper.name} reconciles every output before writes and success (${name})`, () => {
+ assertHelperContract(content.replace(/\n/g, eol), helper);
+ });
+ }
+
+ test(`${helper.name} rejects bypasses and restored existence-only branches`, () => {
+ assert.throws(() => assertHelperContract(
+ content.replace('Read and execute [native-artifact-compatibility.md]', 'Optionally read the reference'),
+ helper,
+ ));
+ const gate = `${helper.reconcile}\n${section(content, helper.reconcile)}`;
+ assert.throws(() => assertHelperContract(
+ content.replace(gate, '') + `\n${gate}`,
+ helper,
+ ), 'A check moved after generation must not count as preflight');
+ for (const write of helper.writes) {
+ assert.throws(() => assertHelperContract(
+ content.replace(`${write}\n`, `${write}\nIf the file already exists, skip this step.\n`),
+ helper,
+ ), `Existence-only reuse in ${write} must be rejected`);
+ assert.throws(() => assertHelperContract(
+ content.replace(section(content, write), 'Create or patch the file.\n\n'),
+ helper,
+ ), `The actual ${write} branch must apply reconciliation`);
+ }
+ assert.throws(() => assertHelperContract(
+ content.replace("shared compatibility contract's Step 4", 'type-check only')
+ .replace("shared compatibility contract's\nStep 4", 'type-check only'),
+ helper,
+ ), 'Compilation alone must not satisfy the result gate');
+ });
+}
+
+test('dedicated dispatch forwards scope and returns failures instead of falling through', () => {
+ const dispatch = section(native, '### Step 3 — Route to nested helpers or inline wrappers');
+ assert.match(dispatch, /working_dir.*arguments, supplied answers, mode flags/s);
+ assert.match(dispatch, /current owner\/phase\/`approved_scope`/);
+ assert.match(dispatch, /Each helper must execute/);
+ assert.match(dispatch, /before its writes\/reuse and before its success summary/);
+ assert.match(dispatch, /outer Step 5 is not\s+reached/);
+ assert.match(dispatch, /Propagate `NEEDS_CONTEXT`\/`BLOCKED`/);
+ assert.match(dispatch, /STOP this leaf, not the owning workflow/);
+ assert.match(dispatch, /Do not\s+fall through to inline generation or report success for a partial helper result/);
+ const inline = section(native, '### Step 5 — Write wrapper');
+ assert.match(inline, /Read and execute \[native-artifact-compatibility\.md\]/);
+ assert.match(inline, /scoped update without re-asking when already approved/);
+ assert.match(inline, /`NEEDS_CONTEXT` to the owner \(or ask standalone\)/);
+});
+
+function decision(text, label) {
+ const decisions = section(text, '## 3. Apply the reconciliation decisions');
+ const start = decisions.indexOf(`- **${label}:**`);
+ assert.ok(start >= 0, `Missing decision: ${label}`);
+ const rest = decisions.slice(start);
+ const end = rest.indexOf('\n- **', 1);
+ return end < 0 ? rest : rest.slice(0, end);
+}
+
+function assertDecisions(text) {
+ const compatible = decision(text, 'Compatible');
+ assert.match(compatible, /reuse unchanged, including custom code/);
+ assert.match(compatible, /do not append a\s+regeneration comment or rewrite/);
+ const missing = decision(text, 'Missing and in scope');
+ assert.match(missing, /create only that requested artifact/);
+ assert.match(missing, /partial set,\s+keep compatible siblings unchanged/);
+ assert.match(missing, /missing scanner\/upload helper does not\s+authorize regenerating/);
+ const approved = decision(text, 'Incompatible and update already approved');
+ assert.match(approved, /smallest scoped update/);
+ assert.match(approved, /preserving unrelated custom behavior, exports, and callers/);
+ assert.match(approved, /Proceed without another approval question/);
+ const unresolved = decision(text, 'Incompatible/unknown and not safely covered by approval');
+ assert.match(unresolved, /stop before writes/);
+ assert.match(unresolved, /`NEEDS_CONTEXT: <artifact, mismatch, required scoped decision>`/);
+ assert.match(unresolved, /owner, or ask standalone/);
+ assert.match(unresolved, /caller changes,[\s\S]*replacement of custom code, unapproved storage, or a new capability/);
+ assert.match(unresolved, /Do not\s+delete, rename, replace wholesale, or silently skip/);
+ assert.match(decision(text, 'Unrequested'), /leave untouched/);
+}
+
+for (const [name, eol] of [['LF', '\n'], ['CRLF', '\r\n']]) {
+ test(`reconciliation branches preserve scoped approval and partial sets (${name})`, () => {
+ assertDecisions(normalize(reference.replace(/\n/g, eol)));
+ });
+}
+
+test('decision regressions cannot silently widen scope, overwrite, skip, or re-prompt', () => {
+ const heading = '## 3. Apply the reconciliation decisions';
+ const decisions = section(reference, heading);
+ for (const [before, after] of [
+ ['reuse unchanged, including custom code', 'overwrite from the example'],
+ ['keep compatible siblings unchanged', 'regenerate all siblings'],
+ ['Proceed without another approval question', 'Ask again before any approved update'],
+ ['stop before writes', 'continue and report success'],
+ ['owner, or ask standalone', 'start /edit-app automatically'],
+ ['leave untouched', 'generate every optional companion'],
+ ]) {
+ assert.ok(decisions.includes(before));
+ assert.throws(() => assertDecisions(`${heading}\n${decisions.replace(before, after)}`), before);
+ }
+});
+
+test('full versus implementation-only and planning paths retain current request boundaries', () => {
+ const context = section(reference, '## 1. Resolve the current request');
+ for (const field of ['working_dir', 'orchestrator', 'phase', 'approved_scope', '--implementation-only', '--plan-only']) {
+ assert.ok(context.includes(`\`${field}\``));
+ }
+ assert.match(context, /existing plan, memory-bank entry, environment\s+flag, or filename alone is not approval/);
+ assert.match(context, /never start `\/edit-app` from a helper/);
+ assert.match(context, /bounded request, not every capability\s+in an older plan/);
+ assert.match(context, /Cancellation\/dismissal stops without writes/);
+ assert.match(context, /ambiguous answer is not approval/);
+ assert.match(context, /Planning \/ `--plan-only`.*proposal only, without writes/);
+ assert.match(context, /memory-bank entry marked complete must pass this reconciliation/);
+});
+
+function row(name) {
+ const value = reference.split('\n').find((line) => line.startsWith(`| ${name} |`));
+ assert.ok(value, `Missing artifact contract: ${name}`);
+ return value;
+}
+
+test('camera inventory covers the actual gallery export and independent scanner/upload artifacts', () => {
+ const camera = row('Camera / gallery / scanner');
+ for (const api of ['camera.ts', 'pickImage', 'PhotoResult', 'barcodeScanner.tsx',
+ 'BarcodeScannerView', 'BarcodeScannerViewProps', 'ScannerResult', 'onScanned',
+ 'paused', 'resetKey', 'barcodeTypes', 'cameraUpload.ts',
+ 'uploadPhotoToImageColumn', 'ImageUpdateService', 'UploadResult']) {
+ assert.ok(camera.includes(api), api);
+ }
+ assert.match(camera, /one-shot lock, permission fallback, and sibling overlay/);
+ assert.match(camera, /installed `expo-file-system` API \(or `\/legacy`\)/);
+ assert.match(camera, /truthy generated-service `success`/);
+ assert.match(camera, /Image `update\(\)` helper is not a File upload implementation/);
+ const galleryRow = native.split('\n').find((line) => line.startsWith('| `image-picker`, `gallery`'));
+ assert.match(galleryRow, /src\/native\/camera\.ts` \(`pickImage`\)/);
+ assert.doesNotMatch(galleryRow, /src\/native\/imagePicker\.ts/);
+});
+
+test('camera does not turn missing requested storage into capture-only success', () => {
+ const camera = skill('add-camera');
+ const storage = section(camera, '### Step 4 — Detect Dataverse image/file columns');
+ assert.match(storage, /requested Dataverse Image target is missing\/unverified/);
+ assert.match(storage, /`NEEDS_CONTEXT` to the owner/);
+ assert.match(storage, /blocker applies only to\nthe Dataverse Image-helper branch/);
+ assert.match(storage, /File target is not supported by the Image\s+`update\(\)` example/);
+ assert.match(storage, /Mere presence of generated columns does\s+not authorize an upload helper/);
+ assert.doesNotMatch(prose(camera), /If no matches[^\n]*skip Step 5\./);
+ const gate = section(camera, helpers[0].reconcile);
+ assert.match(gate, /current approved request\/scope/);
+ assert.match(gate, /not unrelated\s+matches in an older plan/);
+ assert.match(section(camera, helpers[0].writes[2]),
+ /explicit implementation-only upload-helper request; a screen plan is not required/);
+});
+
+test('approved connector retention does not require Dataverse columns or an Image helper', () => {
+ const camera = skill('add-camera');
+ const storage = section(camera, '### Step 4 — Detect Dataverse image/file columns');
+ const connector = storage.split('\n').find((line) => line.startsWith('| Non-Dataverse retention'));
+ assert.ok(connector);
+ assert.match(connector, /SharePoint document library/);
+ assert.match(connector, /Skip the Dataverse search and Step 5/);
+ assert.match(connector, /Missing Dataverse columns are not an error/);
+ assert.match(connector, /return the connector\/local persistence work to the owner/);
+ assert.match(connector, /Do not generate `cameraUpload\.ts`/);
+ assert.doesNotMatch(connector, /NEEDS_CONTEXT/);
+ assert.doesNotMatch(storage, /If retention is required, return `NEEDS_CONTEXT`/);
+ assert.ok(storage.indexOf('| Non-Dataverse retention') < storage.indexOf('Grep pattern='));
+ assert.match(section(camera, helpers[0].reconcile), /non-Dataverse retention must not\nrequire Dataverse columns/);
+ assert.match(reference, /known approved\nconnector\/local destination does not require Dataverse columns/);
+ assert.match(reference, /For approved Dataverse retention, inspect the actual generated target column/);
+});
+
+test('PDF generation does not mistake generate-only output or package presence for share/upload support', () => {
+ const pdf = row('PDF report');
+ for (const api of ['createPdfReport', 'wrapPdfDocument', 'escapePdfHtml',
+ 'PdfReportResult', 'includeBase64', 'sharePdfReport', 'PdfShareResult']) {
+ assert.ok(pdf.includes(api), api);
+ }
+ assert.match(pdf, /Package presence alone does not authorize adding sharing/);
+ const report = skill('add-pdf-report');
+ assert.match(section(report, '### 2. Verify packages are already present'),
+ /requirement specifically includes sharing, STOP/);
+ assert.match(section(report, helpers[1].reconcile), /Generate-only\s+compatibility does not satisfy a share\/upload request/);
+ assert.match(section(report, helpers[1].writes[0]), /Do not\s+remove compatible existing share exports/);
+ assert.match(section(report, '### 5. Optional Dataverse upload'), /Optional means unrequested, not skippable/);
+});
+
+test('PDF viewer compares URI behavior and installed version, not just an export name', () => {
+ const viewer = row('PDF viewer');
+ for (const input of ['openHttpsPdf', 'PdfViewerResult', '0.2.9+', 'file://',
+ 'https://', 'content://', 'blob:', 'http://', 'INVALID_URL',
+ 'NATIVE_MODULE_MISSING', 'VIEWER_FAILED']) {
+ assert.ok(viewer.includes(input), input);
+ }
+ assert.match(viewer, /HTTPS-only old wrapper is incompatible with a local PDF request/);
+ const versionGate = section(skill('add-pdf-viewer'), '### 2. Verify package is already present');
+ assert.match(versionGate, /node_modules/);
+ assert.match(versionGate, /UNSUPPORTED_VERSION/);
+ assert.match(versionGate, /If the check fails, STOP/);
+});
+
+test('pen capture-only reuse cannot conceal required Image/File normalization', () => {
+ const pen = row('Pen input');
+ for (const api of ['captureSignature', 'stripDataUriPrefix', 'PenInputResult',
+ 'data:image/png;base64,', 'USER_CANCELLED', 'NATIVE_MODULE_MISSING', 'CAPTURE_FAILED']) {
+ assert.ok(pen.includes(api), api);
+ }
+ assert.match(pen, /capture-only wrapper is insufficient.*storage contract.*prefix normalization/);
+ assert.match(section(skill('add-pen-input'), '### 5. Optional Dataverse save'),
+ /Optional means unrequested, not skippable/);
+});
+
+test('geolocation rejects one-shot or unverified storage substitutes', () => {
+ const geo = row('Geolocation');
+ for (const api of ['startTracking', 'stopTracking', 'isTracking', 'getPermissionStatus',
+ 'getCurrentLocation', 'GeoTrackingTarget', 'GeoResult', 'LocationData', 'PermissionStatus',
+ 'geoService', 'BgLocationClient', 'connectionUrl', 'trackInBackground', 'persistAcrossRestarts']) {
+ assert.ok(geo.includes(api), api);
+ }
+ assert.match(geo, /MSAL-only/);
+ assert.match(geo, /one-shot `expo-location` wrapper is not equivalent/);
+ assert.match(geo, /msdyn_locationrecords.*every default `msdyn_\*` mapped column/);
+ const verification = section(skill('add-geolocation'), '## 2. Verify the Dataverse target table first');
+ assert.match(verification, /Empty `value: \[\]`: stop.*BLOCKED/);
+ assert.match(verification, /Auth\/environment error: stop.*UNVERIFIED/);
+ assert.match(verification, /If any active `fieldMap` column is missing, stop/);
+ assert.match(verification, /Do not create the table, do not route to `\/add-dataverse`/);
+});
+
+test('storage comparison protects generated outputs and does not implement owner-side screens', () => {
+ const inventory = section(reference, '## 2. Inventory and compare the actual output set');
+ assert.match(inventory, /Follow re-exports to their implementation/);
+ assert.match(inventory, /Do not create a duplicate wrapper/);
+ assert.match(inventory, /Image.*supported image\s+payload/);
+ assert.match(inventory, /File.*parent row, verifies success and its ID/);
+ assert.match(inventory, /Never put File bytes in create\/update JSON or assume an upload accepts\s+a URI/);
+ assert.match(inventory, /screen-side save examples are integration guidance, not helper-owned\s+upload implementations/);
+ assert.match(inventory, /Missing\/unknown required storage targets, generated signatures, or payload\s+support are unresolved requirements/);
+ assert.match(inventory, /Do not create\s+schema, refresh services, or hand-edit `src\/generated\/`/);
+ const decisions = section(reference, '## 3. Apply the reconciliation decisions');
+ assert.match(decisions, /No branch permits installs, dependency\s+or native-config edits, native builds, screen edits, or hand-editing generator-owned\s+output/);
+});
+
+test('success requires fulfilled requested artifacts, not type-checks or one compatible sibling', () => {
+ const result = section(reference, '## 4. Verify and return');
+ assert.match(result, /After scoped edits \(or a reuse-only run\), recheck every requested artifact and\s+storage requirement/);
+ assert.match(result, /negative\s+paths when native execution is unavailable and report that limitation/);
+ assert.match(result, /Type-check success alone is insufficient/);
+ assert.match(result, /one\s+compatible sibling cannot stand in for an unfulfilled requested artifact/);
+ assert.match(result, /Return `DONE` only when all requested helper-owned artifacts and their API\/behavior\/\s+storage obligations are fulfilled/);
+ assert.match(result, /Otherwise return `NEEDS_CONTEXT` or `BLOCKED`/);
+ assert.match(result, /not a success summary or completed memory-bank entry/);
+ assert.match(result, /`writtenFiles` \(only actual helper-owned edits\)/);
+ assert.match(result, /Report no generator-owned changes/);
+ assert.match(result, /implementation-only\s+reports that UI integration was intentionally not performed/);
+});
diff --git a/plugins/mobile-apps/scripts/tests/scoped-dataverse-planning-contract.test.js b/plugins/mobile-apps/scripts/tests/scoped-dataverse-planning-contract.test.js
index 80ad0963c..26c9d8bf3 100644
--- a/plugins/mobile-apps/scripts/tests/scoped-dataverse-planning-contract.test.js
+++ b/plugins/mobile-apps/scripts/tests/scoped-dataverse-planning-contract.test.js
@@ -14,6 +14,7 @@ const skill = (name) => read(`skills/${name}/SKILL.md`);
const planningPath = 'shared/references/dataverse-change-planning.md';
const planning = read(planningPath);
const setup = skill('setup-datamodel');
+const edit = skill('edit-app');
const dataverse = skill('add-dataverse');
const create = skill('create-mobile-app');
@@ -114,7 +115,7 @@ test('scope and selected environment are established before compact discovery',
assert.match(scope, /do not copy historical creation rows from the full plan/);
assert.match(scope, /Preserve unrelated services outside this contract/);
assert.match(scope, /missing dependency[\s\S]*additional mutations goes into the proposal for approval/);
- assert.match(scope, /Connector-only,[\s\S]*removal-only, and retained-service-only\n\s+refresh requests skip/);
+ assert.match(scope, /Connector-only, native\/design-only, removal-only, and retained-service-only\n\s+refresh requests skip/);
assert.match(scope, /do not create empty Dataverse artifacts or require a data-model receipt/);
assert.match(scope, /environment ID, HTTPS URL, and tenant to match/);
assert.match(scope, /`NEEDS_CONTEXT` to the owner before discovery/);
@@ -159,17 +160,20 @@ test('all scoped proposal sources share required snapshot-only architect inputs
assert.match(proposal, /do not replace its unaffected sections with the scoped contract/);
const setupPlanner = section(setup, '#### Path B', '#### Path C');
- assert.match(setupPlanner, /Dataverse planning mode: required/);
- assert.match(setupPlanner, /snapshot \(validator input only\): <SNAPSHOT_PATH>/);
- assert.match(setupPlanner, /Compact Dataverse architect evidence: <ARCHITECT_EVIDENCE_PATH>/);
- assert.match(setupPlanner, /Structured schema contract output: <working_dir>\/\.tmp\/dataverse-schema-contract\.json/);
- assert.doesNotMatch(setupPlanner, /Dataverse planning mode: (?:default|optional|legacy)/);
+ const editPlanner = section(edit, 'For the Data Model handoff', 'For Native Capabilities (no separate agent)');
+ for (const handoff of [setupPlanner, editPlanner]) {
+ assert.match(handoff, /Dataverse planning mode: required/);
+ assert.match(handoff, /snapshot \(validator input only\): <SNAPSHOT_PATH>/);
+ assert.match(handoff, /Compact Dataverse architect evidence: <ARCHITECT_EVIDENCE_PATH>/);
+ assert.match(handoff, /Structured schema contract output: <working_dir>\/\.tmp\/dataverse-schema-contract\.json/);
+ assert.doesNotMatch(handoff, /Dataverse planning mode: (?:default|optional|legacy)/);
+ }
assert.match(section(setup, '#### Path A', '#### Path B'), /same decision validation as Path B before[\s\S]*Phase 4 approval/);
assert.match(section(dataverse, '### Step 2.5', '### Step 2.6'), /decision validation for the diagram just as for\nan architect result/);
assert.match(section(dataverse, '### Step 2.6', '### Step 2.7'), /If the host cannot spawn agents, produce both inline from that same evidence/);
});
-test('the architect fails closed in required mode and preserves non-persisting legacy planning', () => {
+test('the architect refuses live-discovery fallback when required compact evidence is missing', () => {
const architect = read('agents/data-model-architect.md');
const snapshotOnly = section(architect, '## Snapshot-only', '## Step 1');
inOrder(snapshotOnly, 'render-dataverse-architect-evidence.js', '--validate-only', 'Read the compact architect evidence once');
@@ -177,12 +181,7 @@ test('the architect fails closed in required mode and preserves non-persisting l
assert.match(snapshotOnly, /Do \*\*not\*\* run Bash discovery or call `resolve-environment\.js`/);
assert.match(snapshotOnly, /`NEEDS_CONTEXT: matching-dataverse-snapshot-and-evidence`/);
assert.match(snapshotOnly, /Do not fall back to\nlive discovery from `required` mode/);
- assert.match(snapshotOnly, /Setup\/standalone data planning must not omit `required`/);
- assert.match(snapshotOnly, /legacy live path below remains only\nfor callers that omit the new planning mode entirely/);
- const legacy = section(architect, '## Step 1', '## Step 2');
- assert.match(legacy, /Legacy live path only\. Skip entirely in the validated snapshot-only path/);
- assert.match(legacy, /^node "\$\{PLUGIN_ROOT\}\/scripts\/resolve-environment\.js" <environment-id-or-url> --no-cache --require-tenant$/m);
- assert.match(legacy, /do not remove these flags or\nredirect output into app\/auth configuration/);
+ assert.match(snapshotOnly, /Bundled\nsetup\/edit\/standalone planning must not omit `required`/);
});
test('normalization and decision validation precede approval, including successful agent returns', () => {
@@ -223,11 +222,12 @@ test('structured metadata expansion and deterministic revision precede generic r
assert.match(canonical, /If it is empty, do not issue another network request/);
for (const owner of [
section(setup, '#### Path B', '#### Path C'),
+ section(edit, 'For the Data Model handoff', 'For Native Capabilities (no separate agent)'),
section(dataverse, '### Step 2.6', '### Step 2.7'),
]) assert.match(owner, /(?:shared planning recovery before|recovery before generic retry limits|shared structured-signal recovery before generic retries)/);
});
-test('accepted data scopes bind evidence and exact hashes without create-only artifact flags', () => {
+test('accepted setup/edit scopes bind evidence and exact hashes without create-only artifact flags', () => {
const accepted = planning.slice(planning.indexOf('## 5.'));
inOrder(accepted, 'existing gate approves implementation', 'save only the accepted plan', '`contract_sha256`', '`plan_sha256`', 'Before execution');
assert.match(accepted, /exact accepted operations\/dependencies/);
@@ -235,16 +235,18 @@ test('accepted data scopes bind evidence and exact hashes without create-only ar
assert.match(accepted, /never recalculate these approval hashes after discovering a mismatch/);
assert.match(accepted, /not a new\nreceipt format/);
assert.match(accepted, /receipt requires `workflow: create-mobile-app`\nand four approvals/);
- assert.match(accepted, /Do not fabricate those approvals[\s\S]*weaken\nreceipt validation, or pass a partially populated fast-path argument set/);
- const handoff = section(setup, 'Invoke skill: /add-dataverse', '\n```');
- assert.match(handoff, /orchestrator: setup-datamodel/);
- assert.match(handoff, /phase: implementation/);
- assert.match(handoff, /planning_snapshot: <SNAPSHOT_PATH>/);
- assert.match(handoff, /architect_evidence: <ARCHITECT_EVIDENCE_PATH>/);
- assert.match(handoff, /schema_contract: <working_dir>\/\.tmp\/dataverse-schema-contract\.json/);
- assert.match(handoff, /approved_scope: <[^\n]*delta[^\n]*contract_sha256, plan_sha256>/);
- assert.match(handoff, /--skip-planning/);
- assert.doesNotMatch(handoff, /--(?:schema-contract|approval-receipt|execution-reconciliation|operation-manifest|publish-checkpoint)\b/);
+ assert.match(accepted, /Do not fabricate those approvals for setup\/edit, weaken\nreceipt validation, or pass a partially populated fast-path argument set/);
+ for (const [owner, content] of [['setup-datamodel', setup], ['edit-app', edit]]) {
+ const handoff = section(content, 'Invoke skill: /add-dataverse', '\n```');
+ assert.match(handoff, new RegExp(`orchestrator: ${owner}`));
+ assert.match(handoff, /phase: implementation/);
+ assert.match(handoff, /planning_snapshot: <SNAPSHOT_PATH>/);
+ assert.match(handoff, /architect_evidence: <ARCHITECT_EVIDENCE_PATH>/);
+ assert.match(handoff, /schema_contract: <working_dir>\/\.tmp\/dataverse-schema-contract\.json/);
+ assert.match(handoff, /approved_scope: <[^\n]*delta[^\n]*contract_sha256, plan_sha256>/);
+ assert.match(handoff, /--skip-planning/);
+ assert.doesNotMatch(handoff, /--(?:schema-contract|approval-receipt|execution-reconciliation|operation-manifest|publish-checkpoint)\b/);
+ }
});
test('Step 2b verifies approval before fresh bounded reconciliation, not whole-plan replay', () => {
@@ -272,14 +274,15 @@ test('Step 2b verifies approval before fresh bounded reconciliation, not whole-p
});
test('legacy child handoffs require current approval and cannot bypass invalid compact artifacts', () => {
- const legacy = section(dataverse, 'Older callers,', 'For the shared scoped path');
- assert.match(legacy, /Do not assume compact evidence or complete approval from the caller's\nname/);
- assert.match(legacy, /Without a complete approved handoff, resolve the current requested delta\nand use this leaf's normal proposal and Step 2\.7 approval path before execution/);
- assert.match(legacy, /missing or conflicting child root\nstill returns `NEEDS_CONTEXT` before project access/);
- assert.match(legacy, /Never silently replay the\nsaved plan or treat `--skip-planning` as consent/);
+ const legacy = section(dataverse, 'Older callers', 'For the shared scoped path');
+ assert.match(legacy, /Do not assume compact\s+evidence or complete approval from the caller's name/);
+ assert.match(legacy, /Without a complete approved\s+handoff, resolve the current requested delta/);
+ assert.match(legacy, /Step 2\.7 approval path before execution/);
+ assert.match(legacy, /missing or conflicting child root still returns `NEEDS_CONTEXT`/);
+ assert.match(legacy, /Never silently replay the saved plan or treat `--skip-planning`\s+as consent/);
assert.match(legacy, /An approved legacy child without compact-planning artifacts keeps the supported\nMarkdown\/live-reconciliation path/);
assert.match(legacy, /current request, absolute\nroot, implementation phase, and exact approved delta are all established/);
- assert.match(legacy, /Never use this legacy path to bypass a partial or invalid compact-planning\nhandoff, or to skip setup\/standalone proposal validation/);
+ assert.match(legacy, /Never use this legacy path to bypass a partial or invalid compact-planning\nhandoff/);
assert.match(legacy, /Only the current approved\ndelta and its necessary dependencies enter live schema reconciliation/);
assert.match(legacy, /complete approved legacy handoff, proceed to Step 3 after this initialization/);
assert.match(legacy, /do not repeat proposal Steps 2\.5–2\.7 or require new compact artifacts/);
diff --git a/plugins/mobile-apps/shared/memory-bank.md b/plugins/mobile-apps/shared/memory-bank.md
index 9f398c276..d62210074 100644
--- a/plugins/mobile-apps/shared/memory-bank.md
+++ b/plugins/mobile-apps/shared/memory-bank.md
@@ -74,7 +74,7 @@ associationsCount: # number of mobileofflineprofileitemassociation rows
| Capability | Module | Wrapper file | When added | Justification |
|---|---|---|---|---|
-| _e.g. camera_ | _expo-camera_ | _src/native/camera.ts_ | _ISO date_ | _from plan_ |
+| _e.g. camera_ | _expo-image-picker_ | _src/native/camera.ts_ | _ISO date_ | _from plan_ |
## Connectors
diff --git a/plugins/mobile-apps/shared/references/app-edit-routing.md b/plugins/mobile-apps/shared/references/app-edit-routing.md
new file mode 100644
index 000000000..6ba9aadf6
--- /dev/null
+++ b/plugins/mobile-apps/shared/references/app-edit-routing.md
@@ -0,0 +1,165 @@
+# App edit routing
+
+Use this contract for every native, connector/data-source, data-model, or
+mutating design feature request classified by the shared entry preflight.
+This includes future feature skills; it is not an allowlist of current names.
+Adding a wrapper or registering a service is not the same as delivering the
+feature that uses it.
+
+Use [app-working-directory.md](app-working-directory.md) for root binding and
+the canonical [data-source invocation scope](../shared-instructions.md#data-source-invocation-scope)
+for data operations; this reference adds entry choice and feature ownership,
+not another environment resolver or data lifecycle.
+
+Cloud-flow integration remains unsupported. Report
+`BLOCKED: cloud-flow integration is not supported` before offering integration
+or starting a planner; do not broaden the available CLI surface.
+
+## Direct requests
+
+For an existing mobile app, use a lightweight **entry-choice gate** before loading
+or invoking `/edit-app`. Check only the supplied request/caller context and local
+project markers needed to identify the app. Do not run health/type checks, scan
+all screens/services, discover cloud metadata, start planners, or generate previews
+just to ask this question. This gate precedes operational toolchain/auth checks;
+the standard plugin-update notification still runs first.
+
+Ask one question through the host's question tool: "How far should I take this change?"
+
+| Choice | Work authorized by the choice |
+|---|---|
+| Implementation only | Generate/register the requested wrapper, service, or bounded artifact; no screen integration, broad replanning, or preview |
+| Full app integration | Invoke `/edit-app` to inspect intent and propose the affected plan/data/screens changes; explain that this costs more than implementation-only work |
+| Cancel | Stop without invoking `/edit-app`, running implementation commands, or changing files |
+
+Wait for an explicit selection. Silence, dismissal, or an ambiguous answer is not
+consent; stop or clarify, never default to full integration. Naming a screen or
+giving a detailed feature request does not bypass this gate.
+
+Only after **Full app integration** is selected, delegate the complete request
+to `/edit-app`. Forward `entry_choice: full-integration` for this request, the
+absolute `working_dir`, original request,
+all arguments, supplied answers, and entry skill name, then stop this invocation.
+Naming a capability, connector, table, or package does not establish its intended
+screen behavior or authorize a wrapper-only/data-only change.
+
+For **Implementation only**, continue the bounded leaf workflow and forward
+`--implementation-only` through any router so the next leaf does not ask again.
+Retain that operation's own approval and validation gates. Do not silently escalate
+to `/edit-app` when implementation-only work is insufficient; explain the missing
+integration and ask before broadening scope.
+
+Reuse a mode choice already supplied for this same request. An explicit
+`--implementation-only` request needs no entry question. A direct `/edit-app`
+invocation already selects the integration workflow; do not send it through this
+menu again. Honor `--plan-only` in either mode: return only the proposal, never
+execute app/cloud mutations.
+
+`/edit-app` inspects the app and asks only for unresolved intent: what job the
+feature supports, where it is used, and whether its output must be retained.
+It owns the approved plan delta, affected screens, verification, preview, and
+memory-bank update. Do not ask the user to run a second command themselves.
+The entry choice approves entering that workflow, not its mutations: preserve
+its impact/plan approval and explicit approval for data-source removals.
+
+If full integration was selected but the app's plan is missing, report that
+prerequisite and ask whether to restore it or choose a limited implementation-only
+operation. Implementation-only work does not require a complete app plan.
+Do not re-scaffold over the app or fabricate a complete plan from one request.
+Outside an existing app, retain the skill's project prerequisites and standalone
+planning behavior; brand-only design generation need not create an app.
+
+## Orchestrated calls
+
+`MOBILE_APP_ORCHESTRATING=1` is an invocation-scoped context marker, not approval.
+`/create-mobile-app` and `/edit-app` pass it explicitly with every child handoff,
+together with:
+
+- `orchestrator`: the owning skill;
+- `working_dir`: the absolute app directory;
+- `phase`: planning or implementation, or an explicitly delegated design/configuration gate;
+- `approved_scope`: the exact approved plan sections/operations and supplied answers
+ for implementation, or the read-only planning task.
+
+Keep the upstream `CODE_APPS_NATIVE_ORCHESTRATING=1` environment flag for
+nested design/browser workflows that require it. It suppresses browser openers;
+it is not a substitute for this scoped `MOBILE_APP_ORCHESTRATING=1` handoff.
+
+Check valid caller context before the entry-choice gate. A current approved
+`/create-mobile-app` or `/edit-app` child call skips the entry question and executes
+only its approved scope. Do not add a second integration/cost question inside
+creation, edit, or their routed leaf calls.
+
+`/setup-datamodel` may also pass this context when applying its standalone approved
+data-only plan. Routers forward the same context to their selected leaf; internal
+native helpers inherit it from `/add-native`. A child returns to its owner, never
+delegates back to `/edit-app`, and never starts another orchestration.
+
+Do not persist the marker in project files, shell profiles, or memory-bank.
+A shell `export` in one tool call does not propagate reliably to later skill
+calls: include the context in each invocation even if the environment is set.
+A bare/stale environment value or `--skip-planning` without a matching current
+handoff is not an orchestration guard or consent. Ask for the missing scope.
+
+Planning is read-only: no connection creation, schema/service generation, native
+wrapper writes, brand/token writes, or dependency installation. Implementation
+starts only after the owner approves and saves the plan delta. Reuse approved
+answers; if a new choice expands the scope, return `NEEDS_CONTEXT` to the owner
+instead of independently approving or silently broadening the change.
+
+During fresh creation, the design child may own its brand-selection gate after
+the app architecture is approved. Configuration-only children such as
+`setup-app-insights` also retain their own mutation approval. Identify that gate
+explicitly in the handoff; these exceptions do not authorize feature leaves to
+mutate during planning.
+
+## Conditional impact
+
+| Requirement | Affected plan surfaces |
+|---|---|
+| Device capture, scan, view, or local export | Native Capabilities; Screens when used by UI |
+| Teams/email action or profile lookup | Connectors and the consuming Screens; no Dataverse Data Model by default |
+| SQL/Excel/SharePoint data | Connectors, including external tables/list schemas, and consuming Screens; not automatically Dataverse |
+| New/changed Dataverse tables, columns, relationships, or retained artifacts | Data Model; Screens when they consume the change |
+| Existing Dataverse schema with missing generated services | Refresh services and Generated Services snapshot; do not invent schema changes |
+| Brand refresh/reskin | Design; inspect affected Screens and runtime token/provider wiring |
+
+Ask about retention rather than assuming every photo/signature/PDF needs Dataverse.
+Reuse the approved storage platform and existing columns. Update Dataverse schema
+only when the feature actually requires new/changed Dataverse storage.
+
+For removed/replaced requirements, apply
+[data-source-removal.md](data-source-removal.md). The owner approves retirement,
+updates consumers first, then uses the CLI to unregister the source and reconcile
+generated/config output. A shortened plan or unused screen is not permission to
+delete a server table or manually prune generated files.
+
+## Explicit implementation-only requests
+
+Honor the implementation-only entry choice, `--implementation-only`, or an explicit instruction such as "generate only
+the wrapper" or "register the connector without changing screens." Confirm the
+bounded operation if it is not already clear; retain the leaf's approval and
+validation gates. This is not permission to execute an unrelated existing plan.
+Do not infer this mode merely because the user did not mention screens.
+
+After success, reconcile only the affected Native Capabilities, Connectors,
+Data Model, Design, and Generated Services entries that actually changed, if an
+existing plan is available. Update memory-bank without secrets. Leave screen
+specifications/code unchanged and state that UI integration was intentionally
+not performed. Do not claim the user-visible feature is complete.
+
+## Returning from implementation
+
+Return the standard first-line status plus implemented operations, existing
+skill/helper-owned `writtenFiles`, generator-owned outputs, validation results,
+and unresolved integration needs. In orchestrated mode the parent owns the final
+plan/service snapshot, screen work, and completion summary; a leaf's `DONE` or
+`STOP` returns control to that parent, not completion of the entire feature.
+
+Connection discovery/re-authentication, auth configuration, Application Insights
+configuration, telemetry preferences, sample seeding, offline-profile
+configuration, dependency maintenance, diagnostics, previews, deployment, and
+issue reporting retain their dedicated workflows and approvals. Do not route a
+pure operational request through app planning. If it also requests new screen
+behavior or schema, hand that feature delta to `/edit-app` rather than implementing
+it as an unplanned side effect.
diff --git a/plugins/mobile-apps/shared/references/connector-planning.md b/plugins/mobile-apps/shared/references/connector-planning.md
index a3f1c203d..dcaa40404 100644
--- a/plugins/mobile-apps/shared/references/connector-planning.md
+++ b/plugins/mobile-apps/shared/references/connector-planning.md
@@ -1,8 +1,8 @@
# Connector Planning Reference
Shared logic for inferring and confirming Power Platform connectors from app
-requirements. Used by `native-app-planner` and `setup-datamodel`.
-Discovery and proposal are not implementation.
+requirements. Used by `native-app-planner`, `setup-datamodel`, and the read-only
+planning phase of `/edit-app`. Discovery and proposal are not implementation.
---
@@ -115,5 +115,4 @@ At execution time, each confirmed connector maps to a skill invocation:
Invoke these skills only in the implementation phase with
`MOBILE_APP_ORCHESTRATING=1` and the explicit approved context from
-[Data-source invocation scope](../shared-instructions.md#data-source-invocation-scope).
-Forward it when a router delegates.
+[app-edit-routing.md](app-edit-routing.md). Forward it when a router delegates.
diff --git a/plugins/mobile-apps/shared/references/dataverse-change-planning.md b/plugins/mobile-apps/shared/references/dataverse-change-planning.md
index b6afda79d..2cd4c0d1f 100644
--- a/plugins/mobile-apps/shared/references/dataverse-change-planning.md
+++ b/plugins/mobile-apps/shared/references/dataverse-change-planning.md
@@ -1,6 +1,6 @@
# Dataverse planning for scoped changes
-Use this contract from `setup-datamodel` and standalone
+Use this contract from `setup-datamodel`, `edit-app`, and standalone
`add-dataverse` when proposing Dataverse schema or a new table binding. It
adapts the existing create-flow planning helpers to the owner's current delta;
it does not invoke `/create-mobile-app` or add another approval gate.
@@ -9,8 +9,8 @@ it does not invoke `/create-mobile-app` or add another approval gate.
Retain one absolute `working_dir`, the current request, the existing plan, and
the owner's planning/implementation mode across every call and retry.
-Planning is not implementation approval, including after a request to inspect
-or propose a data-model change.
+Planning is not implementation approval, including after an entry-mode choice
+or an edit-impact preview.
- Connector-only, native/design-only, removal-only, and retained-service-only
refresh requests skip this workflow. Use their existing scoped workflows;
@@ -160,8 +160,9 @@ Never import creation's Gate 1/2 prompts into this owner.
For `--plan-only`, return the validated proposal (or explicit blocker) at the
owner's proposal boundary. `setup-datamodel` and `add-dataverse` do not save the
-live plan. None of these modes grants implementation approval or mints an
-execution receipt.
+live plan; `edit-app` may save plan documents only after its explicit
+plan-document approval. None of these modes grants implementation approval or
+mints an execution receipt.
## 5. Carry the accepted scope into implementation
@@ -176,9 +177,9 @@ never recalculate these approval hashes after discovering a mismatch.
The existing five-artifact operation-manifest fast path remains
creation-receipt-owned. Its receipt requires `workflow: create-mobile-app`
-and four approvals. Do not fabricate those approvals for data-only changes, weaken
+and four approvals. Do not fabricate those approvals for setup/edit, weaken
receipt validation, or pass a partially populated fast-path argument set.
-Data-only changes use the scoped standalone execution path with their real approval.
+Setup/edit use the scoped standalone execution path with their real approval.
On resume without matching approval context, return `NEEDS_CONTEXT`; an old
plan or scratch artifact does not grant permission.
diff --git a/plugins/mobile-apps/shared/references/native-artifact-compatibility.md b/plugins/mobile-apps/shared/references/native-artifact-compatibility.md
new file mode 100644
index 000000000..d48488908
--- /dev/null
+++ b/plugins/mobile-apps/shared/references/native-artifact-compatibility.md
@@ -0,0 +1,141 @@
+# Native artifact compatibility
+
+Apply this contract inside `/add-native` and every nested native helper before
+writing or reusing output. Dedicated helpers return before the outer Step 5;
+checking only that step leaves their actual artifacts unchecked.
+
+## 0. Bind every operation to the app root
+
+Before any project read or command, execute
+[app-working-directory.md](app-working-directory.md). It owns absolute-root
+resolution, per-call Bash/PowerShell guards, and absolute file-tool paths for
+native work as well as data-source workflows. Apply it to package/installed-version
+checks and every nested helper, not just the first project gate.
+
+## 1. Resolve the current request
+
+Inherit the absolute `working_dir`, original arguments, supplied answers,
+`--implementation-only`, `--plan-only`, and current orchestration context from
+`/add-native`. Apply [app-edit-routing.md](app-edit-routing.md): valid
+`MOBILE_APP_ORCHESTRATING=1`, `orchestrator`, `phase`, and `approved_scope` identify
+the owner and approved operation. An existing plan, memory-bank entry, environment
+flag, or filename alone is not approval.
+Even a memory-bank entry marked complete must pass this reconciliation; do not
+skip inspection or ask a redundant redo question for the current approved request.
+
+- **Orchestrated implementation:** use the approved capability and storage delta.
+ Do not repeat entry-choice or mutation questions for an already-approved scoped
+ update. Missing context or an expanded operation returns `NEEDS_CONTEXT` to the
+ owner; never start `/edit-app` from a helper.
+- **Standalone implementation-only:** use the bounded request, not every capability
+ in an older plan. Ask only for unresolved requirements or an update outside the
+ current approval, then wait. Cancellation/dismissal stops without writes; an
+ ambiguous answer is not approval. Do not silently escalate to full integration.
+- **Planning / `--plan-only`:** inspect and return a proposal only, without writes.
+
+## 2. Inventory and compare the actual output set
+
+Before any writes, list every requested artifact as **missing**, **compatible**,
+or **incompatible/unknown**, with the required exports, behavior, storage contract,
+and scoped action. Inspect each existing file and relevant consumers read-only,
+including `.tsx`, upload helpers, and app-owned re-exports; do not treat one
+existing wrapper as proof that a partial output set is complete.
+
+Use the helper's actual output paths and public APIs below, not a guessed
+capability-to-filename conversion. Follow re-exports to their implementation;
+a renamed/custom API is compatible only if the approved consumers can use it
+without unapproved changes. Preserve existing public exports and call signatures.
+Do not create a duplicate wrapper to bypass an incompatible existing artifact.
+
+| Helper | Actual helper-owned outputs and compatibility checks |
+|---|---|
+| Camera / gallery / scanner | `src/native/camera.ts` exports `takePhoto`, `pickImage`, `requestCameraPermission`, `requestMediaLibraryPermission`, and `PhotoResult`; gallery uses `pickImage` here, not a required `imagePicker.ts`. Check the requested capture/picker methods, options, URI/metadata, and permission/cancel/unsupported/error results. Requested scanning independently needs `src/native/barcodeScanner.tsx`: `BarcodeScannerView`, `BarcodeScannerViewProps`, `ScannerResult`, `onScanned`, `paused`, `resetKey`, requested `barcodeTypes`, one-shot lock, permission fallback, and sibling overlay rendering. Custom Image retention additionally needs `src/native/cameraUpload.ts`: `uploadPhotoToImageColumn`, `ImageUpdateService`, `UploadResult`, native URI-to-base64 reading supported by the installed `expo-file-system` API (or `/legacy`), and a truthy generated-service `success` check. An Image `update()` helper is not a File upload implementation. |
+| PDF report | `src/native/pdfReport.ts`: `createPdfReport`, `wrapPdfDocument`, `escapePdfHtml`, `PdfReportResult`; verify requested options, deterministic app-owned HTML, local `file://` output, and `includeBase64`/returned base64 when required for retention. Requested sharing additionally needs `sharePdfReport` and `PdfShareResult`, local URI validation, availability/error handling, and installed `expo-sharing`. Package presence alone does not authorize adding sharing. No direct native-viewer import or remote HTML fetch. |
+| PDF viewer | `src/native/pdfViewer.ts`: `openHttpsPdf`, `PdfViewerResult`, requested title/size/cache options and native actions. Verify installed `@microsoft/power-apps-native-pdf-viewer` version 0.2.9+; an HTTPS-only old wrapper is incompatible with a local PDF request. Accept `https://` and non-empty `file://`; reject `content://`, `blob:`, `http://`, empty/malformed inputs. Check `INVALID_URL`, `NATIVE_MODULE_MISSING`, and `VIEWER_FAILED` paths, not just the function name. |
+| Pen input | `src/native/penInput.ts`: `captureSignature`, `stripDataUriPrefix`, `PenInputResult`, requested stroke/background options, PNG `data:image/png;base64,...` output, non-error `USER_CANCELLED`, `NATIVE_MODULE_MISSING`, and `CAPTURE_FAILED`. A capture-only wrapper is insufficient when the requested storage contract also needs prefix normalization; check the Image/File payload distinction below. |
+| Geolocation | `src/native/geolocation.ts`: `startTracking`, `stopTracking`, `isTracking`, `getPermissionStatus`, `getCurrentLocation`, `GeoTrackingTarget`, `GeoResult`, and the `LocationData`/`PermissionStatus` type exports. Verify `geoService`/`BgLocationClient`, MSAL-only auth, required `connectionUrl`, `trackInBackground`, `persistAcrossRestarts`, and native durable storage/Dataverse sync. A one-shot `expo-location` wrapper is not equivalent. Verify `msdyn_locationrecords` and every default `msdyn_*` mapped column as required by the helper; do not substitute another target or silently drop retention/tracking flags. |
+| Inline capability | The actual `src/native/<wrapper>.ts` and the requested domain/permission methods from the supported-capabilities table. Check arguments, result shape, platform guards, and storage behavior against the installed module API. |
+
+For all rows, inspect implementation behavior as well as names/types: requested
+methods must handle failure/cancellation/platform states without throwing
+(including permission calls). Compare with the installed package APIs/version;
+an import that type-checks is not proof the native build supports the operation.
+Keep each helper's missing-package, runtime-ban, and native-version gates.
+Camera permission rejection must become an `error` result, not an unhandled
+promise or a false permission-denied result. Missing APIs return `unsupported`;
+public boolean permission helpers report the failure and return false. Scanner
+permission rejection renders a failure state instead of escaping its effect.
+
+**Storage is part of compatibility when requested.** Resolve the approved local-only
+or retained-artifact behavior and storage platform before judging reuse. Do not
+infer uploads from unrelated generated columns or an old plan. A known approved
+connector/local destination does not require Dataverse columns. Validate the
+native output against that destination's payload contract and return persistence
+integration to the owner; do not create a Dataverse upload helper or claim the
+whole retained-artifact feature is complete. Only genuinely unknown required
+destination/payload information returns `NEEDS_CONTEXT`.
+
+For approved Dataverse retention, inspect the actual generated target column
+type and service signature read-only:
+
+- Custom camera/pen **Image** updates use the generated service's supported image
+ payload; strip the PNG data URI prefix when raw base64 is expected. Camera's
+ native Image helper reads URI bytes as base64, not browser `File`/`Blob`.
+- **File** retention saves/updates the parent row, verifies success and its ID,
+ then uploads compatible bytes/File/picked-file payload through the generated
+ service. Never put File bytes in create/update JSON or assume an upload accepts
+ a URI. Verify truthy `success` on writes, not merely absence of an error.
+- Host `FilePicker` / `ImagePicker` still own normal Dataverse form fields.
+ PDF/pen screen-side save examples are integration guidance, not helper-owned
+ upload implementations. Do not claim they were implemented by writing a
+ capture wrapper. Identify any approved owner-side adapter/screen work explicitly.
+- Missing/unknown required storage targets, generated signatures, or payload
+ support are unresolved requirements, not permission to skip retention. Return
+ `NEEDS_CONTEXT` to the owner, or ask standalone before proceeding. Do not create
+ schema, refresh services, or hand-edit `src/generated/` to make the check pass.
+ Geolocation retains its stricter missing-table/column `BLOCKED` gate.
+
+## 3. Apply the reconciliation decisions
+
+Decide the entire requested set before applying writes in the helper's output steps.
+
+- **Compatible:** reuse unchanged, including custom code; do not append a
+ regeneration comment or rewrite the file to match the example.
+- **Missing and in scope:** create only that requested artifact. In a partial set,
+ keep compatible siblings unchanged; a missing scanner/upload helper does not
+ authorize regenerating the camera wrapper.
+- **Incompatible and update already approved:** make the smallest scoped update
+ to helper-owned code, preserving unrelated custom behavior, exports, and callers.
+ Proceed without another approval question. Examples are starting points, not
+ overwrite templates; adapt them to the live API and the approved contract.
+- **Incompatible/unknown and not safely covered by approval:** stop before writes;
+ return `NEEDS_CONTEXT: <artifact, mismatch, required scoped decision>` to the
+ owner, or ask standalone. This includes a repair needing caller changes,
+ replacement of custom code, unapproved storage, or a new capability. Do not
+ delete, rename, replace wholesale, or silently skip it.
+- **Unrequested:** leave untouched. Do not generate an optional companion merely
+ because a package, plan row, or generated column exists.
+
+Recheck if files changed since inspection. No branch permits installs, dependency
+or native-config edits, native builds, screen edits, or hand-editing generator-owned
+output. Full integration remains the owner's job; implementation-only does not
+authorize those changes.
+
+## 4. Verify and return
+
+After scoped edits (or a reuse-only run), recheck every requested artifact and
+storage requirement against the inventory. Run the helper's type-check and changed-file
+validation, plus available focused behavior checks; review the relevant negative
+paths when native execution is unavailable and report that limitation.
+Type-check success alone is insufficient: existence, compilation, or one
+compatible sibling cannot stand in for an unfulfilled requested artifact.
+
+Return `DONE` only when all requested helper-owned artifacts and their API/behavior/
+storage obligations are fulfilled. Otherwise return `NEEDS_CONTEXT` or `BLOCKED`
+as applicable, not a success summary or completed memory-bank entry.
+List created/updated/reused files, preserved exports, compatibility evidence,
+`writtenFiles` (only actual helper-owned edits), validation, and unresolved
+owner-side integration. Report no generator-owned changes. In orchestrated mode,
+return to the owner for screens and final plan/memory updates; implementation-only
+reports that UI integration was intentionally not performed. Never equate helper
+success with a completed end-to-end retained-artifact feature.
diff --git a/plugins/mobile-apps/shared/shared-instructions.md b/plugins/mobile-apps/shared/shared-instructions.md
index 11db6f083..15ee5136c 100644
--- a/plugins/mobile-apps/shared/shared-instructions.md
+++ b/plugins/mobile-apps/shared/shared-instructions.md
@@ -4,19 +4,50 @@
All skills reference this single file. When new shared instructions are added, update this file only — no changes needed to individual skills.
-## Data-source invocation scope
+## App feature entry points
Read this shared file before any workflow commands or app/cloud writes. If it
cannot be loaded, STOP and report the missing prerequisite; do not proceed from
-a remembered or copied fragment. Before data-source work, bind the invocation through
+a remembered or copied fragment. This preflight applies to new skills too, not
+only the currently named feature leaves.
+
+For native or data-source feature work, bind the invocation through
+[app-working-directory.md](references/app-working-directory.md) before reading
+even the minimal local app markers. A child's launch directory is not its app root.
+
+The standard plugin-update notification remains first. Classify the current
+request from supplied intent, caller context, and minimal local app markers
+before operational toolchain/auth checks, metadata discovery, or planners:
+
+- Native capability, connector/data-source, data-model, or design feature work:
+ read and execute [app-edit-routing.md](references/app-edit-routing.md).
+ It alone owns the implementation-only/full-integration/cancel entry-choice
+ gate, forwarding, and approved-child exceptions. Do not repeat or narrow the
+ choices in individual skills.
+- Direct `/edit-app` and fresh creation keep their own approval workflows.
+ Approved child calls carry `MOBILE_APP_ORCHESTRATING=1` and matching owner,
+ absolute working directory, phase, and scope; a marker alone is not approval.
+- Pure operational/configuration requests (connection management, diagnostics,
+ publishing, telemetry, sample seeding, offline administration) keep their own
+ scoped approvals; they do not authorize an unrelated feature integration.
+
+For data work, continue with the canonical invocation scope below after the
+entry choice or approved-child routing. Native and design workflows retain
+their own operation-specific gates.
+
+---
+
+## Data-source invocation scope
+
+Before data-source work, bind the invocation through
[app-working-directory.md](references/app-working-directory.md) before reading
even the minimal local app markers. A child's launch directory is not its app root.
Resolve the current requested operation before discovery or mutation: schema
change/new binding, retained-source refresh, retirement, or sample seeding.
An existing plan or inventory is context, not permission to replay every row.
-Standalone calls keep the data workflow's own approval and validation gates.
-They do not start a full-app integration wizard or automatically edit screens.
+Standalone implementation-only calls keep the data workflow's own approval and
+validation gates; the full-integration entry choice delegates to `/edit-app`.
For every data child handoff, including routers and retries, pass
`MOBILE_APP_ORCHESTRATING=1`, the owning `orchestrator`, absolute `working_dir`,
@@ -28,8 +59,8 @@ Older callers without a complete approved handoff must establish current scope
through the leaf's approval gate rather than silently applying the saved plan.
`--plan-only` or a planning-phase handoff never authorizes mutating leaves,
-connection creation, generated services, seeding, or schema writes.
-Return the proposal before implementation; only a
+connection creation, generated services, seeding, schema writes, native wrappers, brand tokens, or
+dependency installation. Return the proposal before implementation; only a
workflow's explicit plan-document approval may save planning documents.
Propagate the mode and current scoped context through routers; missing or
conflicting context returns `NEEDS_CONTEXT` before mutation.
@@ -50,7 +81,7 @@ to recover a planning failure. Scratch planning artifacts are allowed.
For scoped Dataverse proposals, follow
[dataverse-change-planning.md](references/dataverse-change-planning.md).
It reuses creation's compact-evidence helpers without importing the create
-wizard or its approval gates into setup/standalone data planning.
+wizard or its approval gates into setup/edit.
---
@@ -58,7 +89,10 @@ wizard or its approval gates into setup/standalone data planning.
**📋 [version-check.md](./version-check.md)**
-Run at the start of every skill execution (at most once per day). Notifies the user if a tool version is below the supported minimum (Node 22+, npm 10+, Expo SDK 55+, etc.).
+Run at the start of operational skill work (at most once per day). For direct
+feature requests, first capture the lightweight entry choice below; do not run
+version/auth checks before the user chooses to proceed. Notifies the user if a
+tool version is below the supported minimum (Node 22+, npm 10+, Expo SDK 55+, etc.).
---
@@ -247,14 +281,17 @@ All non-Dataverse connectors require a connection ID or connection reference
before `pa app add data-source`. Read this reference before implementing
any `/add-*` connector operation.
-Resolve connections only in the approved implementation phase, before adding
-the data source.
+For feature requests, the entry-choice gate precedes `/list-connections` and
+all connection discovery/creation. After the mode is selected, resolve connections
+only in the approved implementation phase, before adding the data source.
Reuse a supplied connection ID or reference for the confirmed connector/environment;
invoke `/list-connections` only when lookup or creation is needed.
Do not invoke it during planning, `--plan-only`, cancellation, or removal-only work.
-Approved data child calls reuse their scoped handoff without repeating
-approval. Direct operational `/list-connections` requests keep their own workflow;
-they do not authorize unrelated app changes.
+Selecting full integration alone does not approve connection creation.
+
+Approved creation/edit child calls reuse their scoped handoff without repeating
+the entry question. Direct operational `/list-connections` requests keep their own workflow;
+they do not require full app integration or authorize unrelated feature changes.
## Safety Guardrails
@@ -462,14 +499,14 @@ When a skill is invoked from another skill (e.g., `/create-mobile-app` calls `/a
- Do not announce steps before executing them. Proceed directly through the workflow.
- Within the current approved phase, do not ask separately for read-only operations
(Glob, Grep, Read, `node scripts/resolve-environment.js <environment-id-or-url>`).
- This does not authorize mutation or discovery outside the current data scope.
+ This does not authorize discovery or costly scans before the entry-choice gate.
- For multi-step operations, use `manage_todo_list` to give the user visibility.
- After completing each step, update the memory bank — don't batch updates at the end.
### When to use `AskUserQuestion` — and when NOT to
**Explicit approval gates take precedence** over the efficiency rules below:
-plan/mutation, data-source removal, and deployment gates require
+entry-choice, plan/mutation, data-source removal, and deployment gates require
the user's explicit selection or approval. A recommended option, one viable
path, stored preference, or deterministic recovery is not consent. Reuse approval
only for the same current operation: already-approved scoped child calls do not repeat approvals,
diff --git a/plugins/mobile-apps/skills/add-connector/SKILL.md b/plugins/mobile-apps/skills/add-connector/SKILL.md
index b7955271a..74ed3ce55 100644
--- a/plugins/mobile-apps/skills/add-connector/SKILL.md
+++ b/plugins/mobile-apps/skills/add-connector/SKILL.md
@@ -17,6 +17,9 @@ model: sonnet
Use its resolved absolute `working_dir` for every shell call and file tool,
including referenced commands and delegated skills; never inherit a prior `cd`.
+**Entry routing:** use the shared [App feature entry points](../../shared/shared-instructions.md#app-feature-entry-points)
+preflight before the workflow below.
+
**Invocation scope:** follow [Data-source invocation scope](../../shared/shared-instructions.md#data-source-invocation-scope)
before the workflow below. This skill owns connector bindings and generated
services, not a full-app plan or screen implementation.
diff --git a/plugins/mobile-apps/skills/add-datasource/SKILL.md b/plugins/mobile-apps/skills/add-datasource/SKILL.md
index a23dd92db..79fa6f3ef 100644
--- a/plugins/mobile-apps/skills/add-datasource/SKILL.md
+++ b/plugins/mobile-apps/skills/add-datasource/SKILL.md
@@ -12,6 +12,9 @@ model: sonnet
# Add Data Source
+**Entry routing:** use the shared [App feature entry points](../../shared/shared-instructions.md#app-feature-entry-points)
+preflight before the workflow below.
+
**Invocation scope:** follow [Data-source invocation scope](../../shared/shared-instructions.md#data-source-invocation-scope)
before any project read or the workflow below. Resolve the absolute app root
before reading memory-bank. Routing selects a data workflow, not implementation
diff --git a/plugins/mobile-apps/skills/add-dataverse/SKILL.md b/plugins/mobile-apps/skills/add-dataverse/SKILL.md
index 1a66a8f32..a7844b7e1 100644
--- a/plugins/mobile-apps/skills/add-dataverse/SKILL.md
+++ b/plugins/mobile-apps/skills/add-dataverse/SKILL.md
@@ -17,6 +17,9 @@ model: opus
Use its resolved absolute `working_dir` for every shell call and file tool,
including referenced commands and delegated skills; never inherit a prior `cd`.
+**Entry routing:** use the shared [App feature entry points](../../shared/shared-instructions.md#app-feature-entry-points)
+preflight before the workflow below.
+
**Invocation scope:** follow [Data-source invocation scope](../../shared/shared-instructions.md#data-source-invocation-scope)
before the workflow below. Standalone calls use this skill's own data-delta
approval and verification; do not start a full-app plan or screen workflow.
@@ -101,8 +104,8 @@ artifact flags in Step 2a. When all are present, only confirm
`native-app-plan.md` exists for hash validation; do not parse its Data Model
section or build operations/service lists from Markdown.
-For all non-fast-path Dataverse proposals from `/setup-datamodel` or a standalone
-request, including an existing-plan delta, read and execute
+For all non-fast-path Dataverse proposals from `/setup-datamodel`, `/edit-app`, or
+a standalone request, including an existing-plan delta, read and execute
[dataverse-change-planning.md](../../shared/references/dataverse-change-planning.md).
Use its scoped evidence/contract for the diagram, architect, or inline path.
An approved child with `planning_snapshot`, `architect_evidence`, and
@@ -110,13 +113,13 @@ An approved child with `planning_snapshot`, `architect_evidence`, and
not rediscover or re-approve it. New-binding requests use this planning path;
service-only refreshes and retirements have already returned from their branches.
-Older callers, including existing `/edit-app`, may not supply the new structured
-handoff. Do not assume compact evidence or complete approval from the caller's
-name. Without a complete approved handoff, resolve the current requested delta
-and use this leaf's normal proposal and Step 2.7 approval path before execution.
-Resolve required invocation context first; a missing or conflicting child root
-still returns `NEEDS_CONTEXT` before project access. Never silently replay the
-saved plan or treat `--skip-planning` as consent.
+Older callers may not supply the new structured handoff. Do not assume compact
+evidence or complete approval from the caller's name. Without a complete approved
+handoff, resolve the current requested delta and use this leaf's normal proposal
+and Step 2.7 approval path before execution. Resolve required invocation context
+first; a missing or conflicting child root still returns `NEEDS_CONTEXT` before
+project access. Never silently replay the saved plan or treat `--skip-planning`
+as consent.
An approved legacy child without compact-planning artifacts keeps the supported
Markdown/live-reconciliation path below only when its current request, absolute
diff --git a/plugins/mobile-apps/skills/add-native/SKILL.md b/plugins/mobile-apps/skills/add-native/SKILL.md
index a6b1bdb69..701b04096 100644
--- a/plugins/mobile-apps/skills/add-native/SKILL.md
+++ b/plugins/mobile-apps/skills/add-native/SKILL.md
@@ -2,7 +2,7 @@
name: add-native
description: Public entry point for native device capabilities and native controls — camera, image picker, barcode/QR scanner, document picker, file picker, secure storage, file system, sharing, haptic feedback, PDF generation/viewing, pen/signature capture, background GPS/geolocation tracking, or supported local file workflows — in a Power Apps mobile app. Also owns routing to internal camera/PDF/pen/geolocation implementation helpers and the guidance boundary between native wrappers and Dataverse File/Image host controls.
user-invocable: true
-allowed-tools: Read, Edit, Write, Grep, Glob, Bash, AskUserQuestion
+allowed-tools: Read, Edit, Write, Grep, Glob, Bash, AskUserQuestion, Skill
model: sonnet
---
@@ -10,9 +10,19 @@ model: sonnet
**📋 Shared instructions: [shared-instructions.md](${PLUGIN_ROOT}/shared/shared-instructions.md)** — read first.
+**Working directory:** before any project read or command, execute
+[native-artifact-compatibility.md Step 0](${PLUGIN_ROOT}/shared/references/native-artifact-compatibility.md#0-bind-every-operation-to-the-app-root).
+Resolve `--working-dir` / owner context there; use the resolved absolute root for
+every shell call and file tool, not a previous shell's cwd.
+
# Add Native Capability
-Generate a one-file typed wrapper under `src/native/` for a native device capability that the upstream template already ships. Screens import the wrapper instead of touching Expo modules directly, so the discriminated-union result contract stays consistent across the app.
+**Entry routing:** use the shared [App feature entry points](../../shared/shared-instructions.md#app-feature-entry-points)
+preflight before the workflow below.
+
+The leaf generates typed wrappers under `src/native/` for native capabilities that
+the upstream template already ships. Screens import the wrapper instead of touching
+Expo modules directly, so the discriminated-union result contract stays consistent.
## Hard rules — do NOT cross these lines
@@ -47,7 +57,7 @@ Before adding any native control or wrapper, apply every gate: classify the inte
|---|---|---|---|
| Form field bound to a Dataverse File column | Host `<FilePicker>` in screen JSX | `@microsoft/power-apps-native-host` host control | Do not generate document-picker/file-system/sharing wrappers for this field |
| Form field bound to a Dataverse Image column | Host `<ImagePicker>` in screen JSX | `@microsoft/power-apps-native-host` host control | Do not use camera/image-picker wrappers for normal form-bound image fields |
-| Dedicated photo/gallery/scanner workflow | `/add-native camera`, `image-picker`, or `barcode-scanner` | `expo-camera` and/or `expo-image-picker` present | If packages are absent, stop with missing-package guidance |
+| Dedicated photo/gallery/scanner workflow | `/add-native camera`, `image-picker`, or `barcode-scanner` | `expo-image-picker` for photo/gallery; `expo-camera` for scanner; both for combined requests | If packages are absent, stop with missing-package guidance |
| Pick/import/upload a user-selected PDF/document | `/add-native document-picker`, or host `<FilePicker>` for Dataverse File fields | `expo-document-picker` present, or host File control | Do not treat this as `pdf-report` or native PDF viewer |
| Generate/export/print an app-owned report PDF | `/add-native pdf-report` | `expo-print` present | If `expo-print` is absent, do not add PDF report capability |
| Share a generated local PDF | `pdfReport.ts` share helper | `expo-sharing` present | If `expo-sharing` is absent, do not render sharing UI |
@@ -129,8 +139,8 @@ Apply the Native capability gate above. This table is a known capability-to-pack
| Capability | Module | Wrapper to generate | Notes |
|---|---|---|---|
-| `camera`, `take-photo`, `photo`, `expo-camera` | `expo-camera` | `src/native/camera.ts` | `/add-native` routes internally to `add-camera` |
-| `image-picker`, `gallery`, `expo-image-picker` | `expo-image-picker` | `src/native/imagePicker.ts` | `/add-native` routes internally to `add-camera` |
+| `camera`, `take-photo`, `photo`, `expo-camera` | `expo-image-picker` | `src/native/camera.ts` | `/add-native` routes internally to `add-camera` for the `photo` artifact; `expo-camera` is a capability alias, not its required package |
+| `image-picker`, `gallery`, `expo-image-picker` | `expo-image-picker` | `src/native/camera.ts` (`pickImage`) | `/add-native` routes internally to `add-camera`; preserve compatible existing re-exports |
| `barcode-scanner`, `qr-scanner`, `scanner`, `barcode`, `qr` | `expo-camera` | `src/native/barcodeScanner.tsx` | `/add-native` routes internally to `add-camera` |
| `document-picker` | `expo-document-picker` | `src/native/documentPicker.ts` | Picks/imports user-selected files (PDF, docs, etc.) from the device |
| `pdf-viewer`, `native-pdf-viewer`, `pdf-control`, `open-pdf`, `@microsoft/power-apps-native-pdf-viewer` | `@microsoft/power-apps-native-pdf-viewer` | `src/native/pdfViewer.ts` | `/add-native` routes internally to `add-pdf-viewer`; 0.2.9+ opens HTTPS URLs and file URIs |
@@ -185,7 +195,8 @@ For custom workflows outside Dataverse File/Image form fields, use the `image-pi
### Step 1 — Verify project
```bash
-test -f app.config.js && test -f power.config.json && test -f package.json
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
+test -f app.config.js && test -f power.config.json && test -f package.json || { echo "BLOCKED: working_dir is not an initialized app" >&2; exit 1; }
```
### Step 2 — Resolve capability
@@ -207,6 +218,7 @@ If the user names something not in the supported table, apply the Native capabil
For normalized `camera`, `image-picker`, `barcode-scanner`, `qr-scanner`, `pdf-report`, `pdf-viewer`, `pen-input`, or `geolocation`, do not fall through to the generic wrapper flow and do not tell the user to run another slash command. Read the nested helper and follow its steps inside this `/add-native` invocation:
```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
case "<capability>" in
camera|image-picker|barcode-scanner|qr-scanner) test -f "${PLUGIN_ROOT}/skills/add-native/add-camera/SKILL.md" && echo "INTERNAL_HELPER:add-camera" ;;
pdf-report) test -f "${PLUGIN_ROOT}/skills/add-native/add-pdf-report/SKILL.md" && echo "INTERNAL_HELPER:add-pdf-report" ;;
@@ -217,7 +229,16 @@ case "<capability>" in
esac
```
-- **INTERNAL_HELPER:** read the printed helper file, execute its workflow with the same `--working-dir` and forwarded arguments, then STOP. `/add-native` remains the only user-facing command for these controls.
+- **INTERNAL_HELPER:** read the printed helper file and execute its workflow with
+ the same absolute `working_dir`, arguments, supplied answers, mode flags, and
+ current owner/phase/`approved_scope`. The helper must bind every operation to
+ that root using Step 0, even if launched from another directory. Each helper must execute
+ [native-artifact-compatibility.md](${PLUGIN_ROOT}/shared/references/native-artifact-compatibility.md)
+ before its writes/reuse and before its success summary; outer Step 5 is not
+ reached on this branch. Propagate `NEEDS_CONTEXT`/`BLOCKED` and the artifact
+ result to the owner, then STOP this leaf, not the owning workflow. Do not
+ fall through to inline generation or report success for a partial helper result.
+ `/add-native` remains the only user-facing command for these controls.
- **INLINE:** continue to Step 4.
### Step 4 — Verify module is template-shipped
@@ -225,6 +246,7 @@ esac
Confirm the underlying native-capability package is actually present in the project's `package.json` (catches the case where the user hand-removed it or the template version is older than expected):
```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
node -e "const p = require('./package.json'); const m = '<expo-module-name>'; if (!p.dependencies?.[m]) { console.error('MISSING: ' + m + ' is not in package.json. The template should ship it. Re-scaffold via /create-mobile-app, restore it from upstream, or wait for the template release that adds it — this skill will not install it.'); process.exit(1); }"
```
@@ -237,7 +259,14 @@ If the check fails, STOP. Do not run `npx expo install`. Print the error verbati
**Print before starting:**
> "→ Writing src/native/<wrapper>.ts (typed wrapper with discriminated-union result + iOS/Android platform guards)…"
-Create `src/native/<wrapper-filename>.ts` (per the supported-capabilities table). If the file already exists, **do NOT overwrite** — append a comment noting "regeneration skipped — wrapper already exists" and skip to Step 6.
+Read and execute [native-artifact-compatibility.md](${PLUGIN_ROOT}/shared/references/native-artifact-compatibility.md)
+Steps 1–3 for the inline capability row before writing or reusing output.
+Create `src/native/<wrapper-filename>.ts` only when missing and in scope. If the
+file already exists, inspect its exports against the approved capability
+contract, including behavior and storage. Reuse it unchanged when compatible;
+make a scoped update without re-asking when already approved. Otherwise return
+`NEEDS_CONTEXT` to the owner (or ask standalone) before updating; never silently
+skip the feature or overwrite custom code.
Each wrapper exports:
@@ -382,13 +411,24 @@ export async function setSecret(key: string, value: string): Promise<SecureResul
> "→ Running tsc to verify wrapper compiles (~10–20 seconds)."
```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
npx --no-install tsc --noEmit
```
-Fix any wrapper-side errors. Do not run platform-specific native build commands during normal `/add-native` use because the module is already part of the current template binary. When a template/base maintainer first adds `expo-haptics` or changes its version, that release must rebuild the Android and iOS base binaries so Expo autolinking includes the module.
+Fix only in-scope wrapper-side errors. Execute the shared compatibility contract's
+Step 4 after type-checking: recheck all requested artifacts, API/behavior, and
+storage obligations before returning success. Type-check success alone is
+insufficient. Do not run platform-specific native build commands during normal
+`/add-native` use because the module is already part of the current template binary.
+When a template/base maintainer first adds `expo-haptics` or changes its version,
+that release must rebuild the Android and iOS base binaries so Expo autolinking
+includes the module.
### Step 7 — Summary
+Return the shared compatibility result before the summary; use the actual
+created/updated/reused paths and do not claim completion for unresolved artifacts.
+
```
✅ Native wrapper generated: <capability>
─────────────────────────────────────────────
diff --git a/plugins/mobile-apps/skills/add-native/add-camera/SKILL.md b/plugins/mobile-apps/skills/add-native/add-camera/SKILL.md
index 27aebecce..402ef6061 100644
--- a/plugins/mobile-apps/skills/add-native/add-camera/SKILL.md
+++ b/plugins/mobile-apps/skills/add-native/add-camera/SKILL.md
@@ -9,6 +9,11 @@ model: sonnet
**Shared instructions: [shared-instructions.md](${PLUGIN_ROOT}/shared/shared-instructions.md)** — read first.
+**Working directory:** before any project read or command, execute
+[native-artifact-compatibility.md Step 0](${PLUGIN_ROOT}/shared/references/native-artifact-compatibility.md#0-bind-every-operation-to-the-app-root).
+Inherit `/add-native`'s resolved absolute `working_dir`; bind every shell call and
+file tool to it, even when this helper starts from another directory.
+
**References:**
- [dataverse-reference.md](${PLUGIN_ROOT}/skills/add-dataverse/references/dataverse-reference.md) — File/image column upload patterns (Step 7–8)
@@ -19,13 +24,26 @@ model: sonnet
Generate typed camera + image-picker wrappers, an optional barcode/QR scanner control, and optional custom-upload guidance for Dataverse image/file workflows.
-This skill **only writes JS files under `src/native/`**. It does not install modules and does not touch `package.json` or `app.config.js` — the underlying Expo modules (`expo-camera`, `expo-image-picker`) and their config plugins must already be shipped by the `microsoft/power-platform-skills/plugins/mobile-apps/template#main` template. If they're missing, STOP and tell the user the template doesn't ship them yet.
+This skill **only writes JS files under `src/native/`**. It does not install
+modules or touch `package.json` / `app.config.js`. Only the modules required by
+the approved artifact set below must already ship in the template/native build;
+if a required module is missing, STOP. Do not require unrelated capture packages
+for a scanner-only or upload-only request.
Why: customer binaries are built from a pre-built rewrap base, not from the customer's `package.json`. Adding a native module here would compile against modules the binary doesn't actually contain, causing runtime crashes after rewrap. See [`/add-native`](../SKILL.md) for the same hard rules.
-Two modules are required (must already be in `package.json`):
-- **`expo-camera`** — live viewfinder, barcode scanning
-- **`expo-image-picker`** — gallery selection + quick camera capture (simpler API, no viewfinder)
+Required modules depend on the approved artifact set (all must already be in
+`package.json`):
+
+| Requested artifact key | Required module | Output |
+|---|---|---|
+| `photo` / `gallery` | `expo-image-picker` | `camera.ts` capture/picker APIs |
+| `scanner` | `expo-camera` | `barcodeScanner.tsx` live scanner |
+| `upload` | `expo-file-system` | `cameraUpload.ts` custom Image helper |
+
+Use the union for combined requests. A scanner-only request does not require
+`expo-image-picker` or `camera.ts`; an upload-only request does not require a
+capture/scanner package.
**Dataverse File/Image boundary:** for normal Dataverse File/Image form fields, screens should use `FilePicker` / `ImagePicker` from `@microsoft/power-apps-native-host` (see [`/add-native` File/Image Picker Ownership](../SKILL.md#fileimage-picker-ownership)). `/add-native camera` owns custom camera/gallery/scanner workflows, such as a dedicated evidence-capture screen, barcode/QR scan gate, or gallery-selected image that is transformed before saving.
@@ -33,50 +51,102 @@ Two modules are required (must already be in `package.json`):
## Workflow
-1. Verify project → 2. Verify modules are template-shipped → 3. Write camera wrapper → 3b. Write scanner control if requested → 4. Detect Dataverse columns → 5. Write upload helper only for custom capture flows → 6. Type-check → 7. Summary
+1. Verify project → 2. Verify modules are template-shipped → 2a. Reconcile requested artifacts → 3. Apply camera decision → 3b. Apply scanner decision → 4. Confirm storage decision → 5. Apply upload decision → 6. Verify → 7. Summary
---
### Step 1 — Verify project
```bash
-test -f app.config.js && test -f power.config.json && test -f package.json
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
+test -f app.config.js && test -f power.config.json && test -f package.json || { echo "BLOCKED: working_dir is not an initialized app" >&2; exit 1; }
```
If any file is missing, report and STOP — this skill requires an initialized Power Apps mobile app.
### Step 2 — Verify modules are template-shipped
-Both `expo-camera` and `expo-image-picker` must already be in `package.json`. Do **not** install them — if they're missing, the upstream template hasn't shipped them yet, and this skill STOPs.
+Resolve the approved artifact keys before this check. Missing/ambiguous intent
+returns to the owner (ask standalone); do not assume all artifacts. Substitute
+the exact JSON list, e.g. `["scanner"]` or `["photo","upload"]`, below:
-```bash
-node -e "const p = require('./package.json'); const need = ['expo-camera','expo-image-picker']; const missing = need.filter(m => !p.dependencies?.[m]); if (missing.length) { console.error('MISSING from package.json: ' + missing.join(', ') + '. The upstream template must ship these for /add-native camera to run. Do NOT install them yourself — file an issue at the template repo (plugins/mobile-apps/template) instead.'); process.exit(1); } console.log('OK: both modules present');"
-```
+Use the owner's normalized public capability to resolve those keys:
-If the check fails, STOP. Print the error verbatim. Do not run `npx expo install`. Do not edit `app.config.js`. Tell the user the template version they scaffolded from doesn't include the camera modules — they need to wait for a newer template release or open a request upstream.
+| Public capability | Artifact keys |
+|---|---|
+| `camera` | `["photo"]` |
+| `image-picker` | `["gallery"]` |
+| `barcode-scanner` | `["scanner"]` |
+| `qr-scanner` | `["scanner"]` |
-Also check if the wrapper already exists:
+For combined approved capabilities use the union. Add `upload` only for an
+explicitly approved custom Dataverse Image-upload helper, not automatically for
+capture or scanning. The checker accepts artifact-key JSON, not raw `$ARGUMENTS`
+or a public capability string. Missing/ambiguous intent still returns to the owner.
```bash
-test -f src/native/camera.ts && echo "exists" || echo "missing"
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
+node - '<approved-artifact-keys-json>' <<'NODE'
+const p = require('./package.json');
+const modules = {
+ photo: 'expo-image-picker',
+ gallery: 'expo-image-picker',
+ scanner: 'expo-camera',
+ upload: 'expo-file-system',
+};
+const artifacts = JSON.parse(process.argv[2]);
+if (!Array.isArray(artifacts) || artifacts.length === 0
+ || artifacts.some(key => typeof key !== 'string' || !Object.hasOwn(modules, key))) {
+ throw new Error('Expected a nonempty approved artifact list: photo, gallery, scanner, upload');
+}
+const need = [...new Set(artifacts.map(key => modules[key]))];
+const missing = need.filter(name => !p.dependencies?.[name]);
+if (missing.length) {
+ console.error('MISSING from package.json: ' + missing.join(', ') + '. Do not install native modules.');
+ process.exit(1);
+}
+console.log('OK: requested modules present');
+NODE
```
-If the wrapper exists, skip Step 3 — do NOT overwrite. Continue to Step 3b / Step 4 as needed.
+If the check fails, STOP. Print the error verbatim. Do not run `npx expo install`. Do not edit `app.config.js`. Tell the user which requested modules the template lacks; they need template support, not an app-local native-package install.
+
+### Step 2a — Reconcile requested artifacts
+
+Read and execute [native-artifact-compatibility.md](${PLUGIN_ROOT}/shared/references/native-artifact-compatibility.md)
+Steps 1–3 for the camera/gallery/scanner row before any writes or reuse. Inherit
+the current approval/mode from `/add-native`; do not repeat a valid scoped approval.
-Detect whether barcode/QR scanning is requested by checking `$ARGUMENTS` and `native-app-plan.md` for `barcode`, `bar code`, `QR`, `scanner`, `scan gate`, `SKU scan`, or `inventory scan`. If present, set `SCANNER_NEEDED=yes`; otherwise skip Step 3b unless the user explicitly asks for scanner support.
+Inventory `src/native/camera.ts` (including gallery `pickImage`, not a required
+`imagePicker.ts`), requested `src/native/barcodeScanner.tsx`, and requested
+`src/native/cameraUpload.ts` independently. Check requested exports, options,
+failure paths, scanner lock/reset/overlay behavior, and any requested Dataverse
+Image-upload payload semantics. Resolve the approved storage platform and Step 4
+requirements read-only now, before writes; non-Dataverse retention must not
+require Dataverse columns or `cameraUpload.ts`.
+Missing required storage or an incompatible artifact outside approval returns
+`NEEDS_CONTEXT` to the owner, or asks standalone; it is not a successful skip.
+
+Set `SCANNER_NEEDED=yes` only for scanning in the current approved request/scope
+(`barcode`, `QR`, scanner, or a supplied scan-gate requirement), not unrelated
+matches in an older plan. A compatible camera file cannot satisfy a missing
+scanner or upload helper. Preserve compatible files unchanged in partial sets.
### Step 3 — Write camera wrapper
-**Print before starting:**
+**Print only when creating/updating the requested camera wrapper:**
> "→ Writing src/native/camera.ts wrapper (takePhoto + pickImage with discriminated-union results)…"
-Create `src/native/camera.ts`. If the file already exists, **do NOT overwrite** — append a comment noting "regenerated by /add-native camera" and STOP this step.
+Apply Step 2a's decision for `src/native/camera.ts`: create if requested and
+missing, reuse unchanged only if compatible, or make only the approved scoped
+update. Scanner-only requests do not require this file. Preserve custom code and
+existing exports; do not append regeneration comments or replace it with the example.
```typescript
// src/native/camera.ts
// Camera capture and image picker wrapper for Power Apps mobile apps.
// Uses expo-image-picker for both camera capture and gallery selection.
-// All functions return discriminated-union results — never throw.
+// Capture/pick functions return discriminated results; permission helpers retain boolean APIs.
import * as ImagePicker from 'expo-image-picker';
@@ -88,30 +158,66 @@ export type PhotoResult =
// --- Permission ---
+type PermissionResult =
+ | { ok: true }
+ | { ok: false; reason: 'permission-denied' | 'unsupported' | 'error'; message?: string };
+
+async function requestPermission(
+ request?: () => Promise<{ status: string }>,
+): Promise<PermissionResult> {
+ if (typeof request !== 'function') {
+ return { ok: false, reason: 'unsupported', message: 'Permission API is unavailable.' };
+ }
+ try {
+ const { status } = await request();
+ return status === 'granted'
+ ? { ok: true }
+ : { ok: false, reason: 'permission-denied' };
+ } catch (error) {
+ return {
+ ok: false,
+ reason: 'error',
+ message: error instanceof Error ? error.message : 'Permission request failed.',
+ };
+ }
+}
+
+async function permissionGranted(
+ request?: () => Promise<{ status: string }>,
+): Promise<boolean> {
+ const permission = await requestPermission(request);
+ if (!permission.ok && permission.reason !== 'permission-denied') {
+ // Preserve the public boolean API without silently hiding a failed native request.
+ console.warn(`Device permission request failed (${permission.reason}).`);
+ }
+ return permission.ok;
+}
+
export async function requestCameraPermission(): Promise<boolean> {
- const { status } = await ImagePicker.requestCameraPermissionsAsync();
- return status === 'granted';
+ return permissionGranted(ImagePicker.requestCameraPermissionsAsync);
}
export async function requestMediaLibraryPermission(): Promise<boolean> {
- const { status } = await ImagePicker.requestMediaLibraryPermissionsAsync();
- return status === 'granted';
+ return permissionGranted(ImagePicker.requestMediaLibraryPermissionsAsync);
}
// --- Capture ---
/**
* Launch the device camera and capture a photo.
- * Returns `{ ok: false, reason: 'unsupported' }` when native camera capture is unavailable.
+ * Missing APIs return 'unsupported'; rejected native calls return 'error'.
*/
export async function takePhoto(options?: {
quality?: number;
allowsEditing?: boolean;
}): Promise<PhotoResult> {
- const granted = await requestCameraPermission();
- if (!granted) return { ok: false, reason: 'permission-denied' };
-
try {
+ if (typeof ImagePicker.launchCameraAsync !== 'function') {
+ return { ok: false, reason: 'unsupported', message: 'Camera API is unavailable.' };
+ }
+ const permission = await requestPermission(ImagePicker.requestCameraPermissionsAsync);
+ if (!permission.ok) return permission;
+
const result = await ImagePicker.launchCameraAsync({
mediaTypes: ['images'],
quality: options?.quality ?? 0.8,
@@ -130,8 +236,8 @@ export async function takePhoto(options?: {
mimeType: asset.mimeType ?? undefined,
fileSize: asset.fileSize ?? undefined,
};
- } catch (e: any) {
- return { ok: false, reason: 'error', message: e?.message };
+ } catch (error) {
+ return { ok: false, reason: 'error', message: error instanceof Error ? error.message : 'Camera capture failed.' };
}
}
@@ -144,10 +250,13 @@ export async function pickImage(options?: {
allowsEditing?: boolean;
allowsMultipleSelection?: boolean;
}): Promise<PhotoResult> {
- const granted = await requestMediaLibraryPermission();
- if (!granted) return { ok: false, reason: 'permission-denied' };
-
try {
+ if (typeof ImagePicker.launchImageLibraryAsync !== 'function') {
+ return { ok: false, reason: 'unsupported', message: 'Image picker API is unavailable.' };
+ }
+ const permission = await requestPermission(ImagePicker.requestMediaLibraryPermissionsAsync);
+ if (!permission.ok) return permission;
+
const result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ['images'],
quality: options?.quality ?? 0.8,
@@ -167,8 +276,8 @@ export async function pickImage(options?: {
mimeType: asset.mimeType ?? undefined,
fileSize: asset.fileSize ?? undefined,
};
- } catch (e: any) {
- return { ok: false, reason: 'error', message: e?.message };
+ } catch (error) {
+ return { ok: false, reason: 'error', message: error instanceof Error ? error.message : 'Image selection failed.' };
}
}
```
@@ -180,7 +289,10 @@ export async function pickImage(options?: {
**Print before starting:**
> "→ Writing src/native/barcodeScanner.tsx (CameraView barcode/QR scanner control)…"
-Create `src/native/barcodeScanner.tsx`. If it already exists, do not overwrite.
+Apply Step 2a's independent decision for `src/native/barcodeScanner.tsx`: create
+when requested and missing, reuse unchanged only if compatible, or make only the
+approved scoped update. Existence alone does not verify `BarcodeScannerView`,
+`onScanned`, `paused`, `resetKey`, or the requested barcode types.
```tsx
// src/native/barcodeScanner.tsx
@@ -235,11 +347,21 @@ export function BarcodeScannerView({
children,
}: BarcodeScannerViewProps) {
const [permission, requestPermission] = useCameraPermissions();
+ const [permissionError, setPermissionError] = React.useState<string | null>(null);
+ const permissionAttemptedRef = React.useRef(false);
const scanLockedRef = React.useRef(false);
React.useEffect(() => {
- if (permission && !permission.granted && permission.canAskAgain) {
- requestPermission();
+ if (permission && !permission.granted && permission.canAskAgain && !permissionAttemptedRef.current) {
+ permissionAttemptedRef.current = true;
+ async function requestScannerPermission() {
+ try {
+ await requestPermission();
+ } catch {
+ setPermissionError('Camera permission request failed. Check device settings and reopen the scanner.');
+ }
+ }
+ void requestScannerPermission();
}
}, [permission, requestPermission]);
@@ -255,6 +377,10 @@ export function BarcodeScannerView({
onScanned({ ok: true, data: event.data, type: event.type, raw: event });
}, [onScanned, paused]);
+ if (permissionError) {
+ return <View style={[styles.fallback, style]}><Text>{permissionError}</Text></View>;
+ }
+
if (!permission) {
return <View style={[styles.fallback, style]}><Text>Checking camera permission...</Text></View>;
}
@@ -294,26 +420,53 @@ Scanner loading UI rule: when scan processing takes time (lookup/create mutation
### Step 4 — Detect Dataverse image/file columns
-Check if the project has generated services with file or image upload support:
+Reuse Step 2a's read-only storage findings; repeat the check only if those files
+changed. Classify the approved storage destination before searching Dataverse:
+
+| Approved storage scope | Helper action |
+|---|---|
+| No retention / local preview only | Skip the Dataverse search and Step 5; fulfill the requested capture/scanner artifacts. |
+| Non-Dataverse retention (for example an existing SharePoint document library) or approved local-file retention | Skip the Dataverse search and Step 5. Validate the required capture output/payload against the approved destination contract, then return the connector/local persistence work to the owner. Missing Dataverse columns are not an error on this path. Do not generate `cameraUpload.ts` or claim persistence is implemented by capture alone. |
+| Dataverse File retention or a normal host File/Image field | Apply the shared storage checks and return the File/host-control integration to the owner; do not use the custom Image `update()` helper. A File target is not supported by the Image `update()` example. |
+| Custom Dataverse Image upload helper requested | Inspect the actual approved Image column and generated service signature below, then apply Step 5. |
+| Destination or required payload contract is unknown | Return `NEEDS_CONTEXT` to the owner (ask standalone); do not assume Dataverse or silently drop retention. |
+
+Only the custom Dataverse Image-helper branch requires this column search:
```text
Grep pattern="ImageColumnName|FileColumnName|UploadColumnName" path="src/generated/"
```
-**If matches found:** note the table names and column types. Continue to Step 5 only when the plan explicitly requires a custom camera/gallery capture flow outside the host `ImagePicker` / `FilePicker` controls.
+**If matches found:** verify the approved target, column type, payload, and write
+result contract. Continue to Step 5 only for requested custom camera/gallery
+**Image** retention outside host controls. Mere presence of generated columns does
+not authorize an upload helper. If the matched target is File rather than the
+approved Image target, return the mismatch to the owner without generating an
+Image helper or claiming File persistence is implemented.
File/Image host-control safety: this skill does not replace normal Dataverse form controls. Keep host `ImagePicker` / `FilePicker` for standard Dataverse form-bound Image/File fields.
-**If no matches (or `src/generated/` doesn't exist):** skip Step 5. The camera wrapper (Step 3) and scanner control (Step 3b, when requested) are still useful standalone — screens can display photos or scan codes without uploading to Dataverse. Mention in the summary that Dataverse file/image form fields should use host controls after running `/add-dataverse` with image/file columns.
+**If the requested Dataverse Image target is missing/unverified:** return
+`NEEDS_CONTEXT` to the owner, or ask standalone; do not silently deliver a
+capture-only success for that requested helper. This blocker applies only to
+the Dataverse Image-helper branch, not an approved connector/local destination.
+Do not generate schema/services or hand-edit `src/generated/`.
### Step 5 — Write image upload helper
**Print before starting:**
> "→ Writing src/native/cameraUpload.ts (Dataverse image column base64 patch helper)…"
-Create `src/native/cameraUpload.ts`. If the file already exists, **do NOT overwrite**.
+Apply Step 2a's independent decision for `src/native/cameraUpload.ts`: create
+when requested and missing, reuse unchanged only if compatible with the approved
+Image target and installed file API, or make only the approved scoped update.
+An existing Image helper cannot satisfy File retention.
-Do **not** generate this helper for normal Dataverse File/Image form fields. Those use host `FilePicker` / `ImagePicker` controls. Generate it only when the approved screen plan needs a custom camera/gallery capture flow.
+Do **not** generate this helper for normal Dataverse File/Image form fields. Those
+use host `FilePicker` / `ImagePicker` controls. Generate it only when the current
+approved scope requests custom camera/gallery Image retention, including an
+explicit implementation-only upload-helper request; a screen plan is not required
+for that bounded operation.
This helper does not change host `ImagePicker` / `FilePicker` behavior. It only covers custom photo-capture flows where the app receives a camera URI and then updates a Dataverse Image column explicitly.
@@ -403,32 +556,49 @@ async function readUriAsBase64(uri: string): Promise<string | null> {
### Step 6 — Type-check
**Print before starting:**
-> "→ Running tsc to verify camera + upload helper compile (~10–20 seconds)."
+> "→ Running tsc to verify the requested native artifacts compile (~10–20 seconds)."
```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
npx --no-install tsc --noEmit
```
-Fix any errors. Common issues:
+Fix only in-scope helper errors. Common issues:
- `readAsStringAsync` not found on `expo-file-system` — switch import to `expo-file-system/legacy` for this helper.
- Import path mismatches — verify `src/native/` is reachable from screen components.
+Execute the shared compatibility contract's Step 4 after type-checking. Recheck
+every requested camera/scanner/upload artifact and storage obligation, including
+permission failures, repeated scan callbacks, URI reads, and false write results.
+Type-check success alone is insufficient; return unresolved requirements rather
+than marking a partial output set complete. Do not fix screen/generated files.
+
### Step 7 — Summary
+Return the shared compatibility result and actual created/updated/reused paths.
+Show only applicable usage examples; no upload success claim when retention is
+unresolved, and no full-feature claim for implementation-only work.
+
```
-Camera + image picker wrappers generated
+Requested native artifacts ready
---
-Modules (template-shipped) : expo-camera, expo-image-picker
+Capabilities : <fulfilled requested capabilities only>
+Modules (template-shipped) : <required modules for those capabilities only>
package.json : unchanged ✓
app.config.js : unchanged ✓
-Camera wrapper : src/native/camera.ts
-Scanner control : src/native/barcodeScanner.tsx (or "skipped — no barcode/QR workflow requested")
-Upload helper : src/native/cameraUpload.ts (or "skipped — no Dataverse image columns found")
+Artifacts : <one row per requested path: created / updated / reused>
+
+Type-check : <actual result>
+UI integration : <returned to owner / intentionally not performed>
+---
+```
-Type-check: PASS
+Do not list `camera.ts` for scanner-only or upload-only results. Do not list
+unrequested companion paths as generated, even if they already existed.
-Sample usage (capture + upload to Dataverse):
+**Include this usage only when capture and custom Image upload were fulfilled:**
+```text
import { takePhoto } from '../native/camera';
import { uploadPhotoToImageColumn } from '../native/cameraUpload';
import { Cr123_inspectionService } from '../generated/services/Cr123_inspectionService';
@@ -445,18 +615,22 @@ Sample usage (capture + upload to Dataverse):
showToast('Photo attached to record');
}
}
+```
-Sample usage (gallery pick, no Dataverse):
+**Include this usage only when gallery picking was fulfilled:**
+```text
import { pickImage } from '../native/camera';
const result = await pickImage();
if (result.ok) {
setPreviewUri(result.uri);
}
+```
-Sample usage (QR/barcode scan gate):
+**Include this usage only when scanner support was fulfilled:**
+```text
import { BarcodeScannerView } from '../native/barcodeScanner';
import { useFocusEffect } from 'expo-router';
@@ -486,17 +660,15 @@ Sample usage (QR/barcode scan gate):
handleCode(data, type);
}}
/>
-
-Note: Camera changes need a native rebuild to take effect:
- run the platform-specific native command for your target device/simulator
- Metro hot-reload alone is not enough for permission changes.
----
```
+No native rebuild or permission/config change is performed. These are JS
+wrapper/control changes over template-shipped native modules.
+
## Notes
- This skill never modifies `src/playerConfig.ts`, `src/generated/`, or any screen file.
-- `takePhoto()` returns `{ ok: false, reason: 'unsupported' }` when native camera capture is unavailable.
+- `takePhoto()` returns `unsupported` for missing APIs and `error` for rejected native calls; neither rejects its promise.
- Barcode/QR scanning is handled here via `src/native/barcodeScanner.tsx` when requested. Use it for scan gates and lookup flows; do not use it as a replacement for Dataverse File/Image host controls.
- `cameraUpload.ts` in this skill targets custom Dataverse Image-column capture flows only. It does not replace host `ImagePicker` / `FilePicker` controls for standard Dataverse forms.
-- If Dataverse tables are added later (via `/add-dataverse`), re-run `/add-native camera` — it will skip module install and wrapper creation, and only write `cameraUpload.ts` when image columns are detected for custom capture flows.
+- If Dataverse tables are added later (via `/add-dataverse`), re-run `/add-native camera` with the approved custom Image-retention requirement. Reconcile all requested artifacts again, reuse compatible wrappers unchanged, and create/update `cameraUpload.ts` only within that scope. This never installs modules.
diff --git a/plugins/mobile-apps/skills/add-native/add-geolocation/SKILL.md b/plugins/mobile-apps/skills/add-native/add-geolocation/SKILL.md
index 17f144f3d..58281a76e 100644
--- a/plugins/mobile-apps/skills/add-native/add-geolocation/SKILL.md
+++ b/plugins/mobile-apps/skills/add-native/add-geolocation/SKILL.md
@@ -9,6 +9,11 @@ model: sonnet
**Shared instructions: [shared-instructions.md](${PLUGIN_ROOT}/shared/shared-instructions.md)** - read first.
+**Working directory:** before any project read or command, execute
+[native-artifact-compatibility.md Step 0](${PLUGIN_ROOT}/shared/references/native-artifact-compatibility.md#0-bind-every-operation-to-the-app-root).
+Inherit `/add-native`'s resolved absolute `working_dir`; bind every shell call and
+file tool to it, even when this helper starts from another directory.
+
# Add Geolocation
Internal helper for `/add-native geolocation`, `/add-native location-tracking`, `/add-native background-location`, `/add-native gps-tracking`, and `/add-native @microsoft/power-apps-native-bglocation`.
@@ -25,7 +30,8 @@ Hard rules:
## 1. Verify app and package
```bash
-test -f app.config.js && test -f power.config.json && test -f package.json && test -d src
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
+test -f app.config.js && test -f power.config.json && test -f package.json && test -d src || { echo "BLOCKED: working_dir is not an initialized app" >&2; exit 1; }
node -e "const p=require('./package.json'); const m='@microsoft/power-apps-native-bglocation'; if (!p.dependencies?.[m]) { console.error('MISSING: ' + m); process.exit(1); } console.log('OK: geolocation package present');"
```
@@ -42,6 +48,7 @@ msdyn_locationrecords
Do not ask the user for a table name and do not invent a custom table. `msdyn_locationrecords` must already exist before the control can be used.
```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
ENV_JSON=$(node "${PLUGIN_ROOT}/scripts/resolve-environment.js" "$(node -e "console.log(require('./power.config.json').environmentId)")")
ENV_URL=$(node -e "const j=JSON.parse(process.argv[1]); process.stdout.write(j.environmentUrl || '')" "$ENV_JSON")
@@ -58,6 +65,7 @@ Required result:
When the table exists, verify every mapped column exists:
```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
node "${PLUGIN_ROOT}/scripts/dataverse-request.js" "$ENV_URL" GET \
"EntityDefinitions(LogicalName='<logicalName>')/Attributes?\$select=LogicalName,AttributeType"
```
@@ -71,9 +79,25 @@ msdyn_altitude, msdyn_accuracy, msdyn_heading, msdyn_speed, msdyn_timestamp
If any active `fieldMap` column is missing, stop. Mark `BLOCKED (target columns missing)` and tell the user to fix the control table through the geolocation-control table provisioning/setup mechanism.
+## 2a. Reconcile requested artifacts
+
+Read and execute [native-artifact-compatibility.md](${PLUGIN_ROOT}/shared/references/native-artifact-compatibility.md)
+Steps 1–3 for the geolocation row before any writes or reuse. Inherit the current
+approval/mode from `/add-native`; do not repeat a valid scoped approval.
+Inspect `src/native/geolocation.ts` for all requested tracking/status/location
+exports, `GeoTrackingTarget`, MSAL-only `geoService`/`BgLocationClient`, required
+`connectionUrl`/`trackInBackground`/`persistAcrossRestarts`, durable storage, and
+Dataverse sync. Reuse Step 2's verified `msdyn_locationrecords` columns; one-shot
+location or a wrapper targeting another table is not compatible. An incompatible
+artifact outside approval returns `NEEDS_CONTEXT` to the owner, or asks standalone;
+missing table/columns remain `BLOCKED`, never a usable-control success.
+
## 3. Write `src/native/geolocation.ts`
-Create or patch `src/native/geolocation.ts` so screens import this wrapper, not the package directly.
+Apply Step 2a's decision for `src/native/geolocation.ts`: create when requested
+and missing, reuse unchanged only if compatible, or make only the approved scoped
+update. Preserve custom code, exports, and callers; do not overwrite from the
+example. Screens import this wrapper, not the package directly.
The target config must require the README's two tracking flags:
- `trackInBackground: boolean`
@@ -181,6 +205,8 @@ export async function getCurrentLocation(): Promise<GeoResult<LocationData>> {
## 4. Usage shape
+Integration guidance for the owner; do not edit screens in this helper.
+
Screens must pass `connectionUrl`, `trackInBackground`, and `persistAcrossRestarts`. Do not pass `tableName` or `fieldMap`; the control uses the default `msdyn_locationrecords` table and default `msdyn_*` field map. `intervalMs`, `distanceFilterMeters`, and `notification` are optional.
```ts
@@ -196,10 +222,16 @@ await startTracking('my-wrap-app', target);
## 5. Type-check and summary
```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
npx --no-install tsc --noEmit
```
-Only after table + columns are verified and TypeScript passes, report:
+Execute the shared compatibility contract's Step 4 after type-checking. Recheck
+all requested tracking APIs/flags, MSAL auth, durable storage/sync, and failure
+paths. Type-check success alone is insufficient; do not fix screen/generated
+files. Only after the requested artifact contract, table + columns, and
+TypeScript all pass, return the shared compatibility result and actual
+created/updated/reused paths before reporting:
```text
Geolocation status : READY
diff --git a/plugins/mobile-apps/skills/add-native/add-pdf-report/SKILL.md b/plugins/mobile-apps/skills/add-native/add-pdf-report/SKILL.md
index 0759702aa..df9b1d5dd 100644
--- a/plugins/mobile-apps/skills/add-native/add-pdf-report/SKILL.md
+++ b/plugins/mobile-apps/skills/add-native/add-pdf-report/SKILL.md
@@ -9,6 +9,11 @@ model: sonnet
**Shared instructions: [shared-instructions.md](${PLUGIN_ROOT}/shared/shared-instructions.md)** - read first.
+**Working directory:** before any project read or command, execute
+[native-artifact-compatibility.md Step 0](${PLUGIN_ROOT}/shared/references/native-artifact-compatibility.md#0-bind-every-operation-to-the-app-root).
+Inherit `/add-native`'s resolved absolute `working_dir`; bind every shell call and
+file tool to it, even when this helper starts from another directory.
+
# Add PDF Report
**Internal helper.** Users should invoke `/add-native pdf-report`, `/add-native generate-pdf`, or `/add-native pdf-export`; `/add-native` routes here after resolving the capability.
@@ -32,7 +37,8 @@ Local generated PDFs are usually `file://` URIs and can be passed to `openHttpsP
### 1. Verify app
```bash
-test -f app.config.js && test -f power.config.json && test -f package.json && test -d src
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
+test -f app.config.js && test -f power.config.json && test -f package.json && test -d src || { echo "BLOCKED: working_dir is not an initialized app" >&2; exit 1; }
```
If this fails, tell the user to run `/create-mobile-app` first and STOP.
@@ -42,6 +48,7 @@ If this fails, tell the user to run `/create-mobile-app` first and STOP.
`expo-print` is required. `expo-sharing` is optional unless the plan specifically needs sharing behavior.
```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
node -e "const p=require('./package.json'); const deps={...p.dependencies,...p.devDependencies}; const required='expo-print'; if (!deps[required]) { console.error('MISSING: expo-print is not in package.json. The template/app must already ship it for /add-native pdf-report. This skill will not install it or edit native config. Capability not added.'); process.exit(1); } console.log('OK: expo-print package present'); console.log(deps['expo-sharing'] ? 'OK: expo-sharing package present' : 'OPTIONAL_MISSING: expo-sharing is not in package.json; generated PDFs can be created/viewed/uploaded, but sharing helpers must not be generated.');"
```
@@ -54,9 +61,25 @@ If `expo-sharing` is missing:
- Do not generate `sharePdfReport(...)`.
- If the user's requirement specifically includes sharing, STOP and say sharing is not supported by this template.
+### 2a. Reconcile requested artifacts
+
+Read and execute [native-artifact-compatibility.md](${PLUGIN_ROOT}/shared/references/native-artifact-compatibility.md)
+Steps 1–3 for the PDF report row before any writes or reuse. Inherit the current
+approval/mode from `/add-native`; do not repeat a valid scoped approval.
+Inspect `src/native/pdfReport.ts` for the full requested API: `createPdfReport`,
+`wrapPdfDocument`, `escapePdfHtml`, requested `includeBase64` output for retention,
+and `sharePdfReport`/`PdfShareResult` when sharing is approved. Generate-only
+compatibility does not satisfy a share/upload request. Verify local-file and
+generated File-service payload requirements; missing required storage or an
+incompatible artifact outside approval returns `NEEDS_CONTEXT` to the owner, or
+asks standalone.
+
### 3. Write or verify `src/native/pdfReport.ts`
-Create `src/native/pdfReport.ts` if it does not exist. If it already exists, inspect it and patch only if it throws instead of returning a result, imports missing packages, or routes local URIs to the native PDF viewer.
+Apply Step 2a's decision for `src/native/pdfReport.ts`: create when requested and
+missing, reuse unchanged only if compatible, or make only the approved scoped
+update. Preserve custom HTML logic and existing exports; the example is not an
+overwrite template.
The wrapper MUST:
@@ -67,7 +90,7 @@ The wrapper MUST:
- Never import `@microsoft/power-apps-native-pdf-viewer` directly from this wrapper.
- Keep HTML generation deterministic and app-owned; do not fetch remote HTML inside the wrapper.
-Base wrapper when `expo-sharing` is present:
+Base wrapper when sharing is requested and `expo-sharing` is present:
```ts
// src/native/pdfReport.ts
@@ -160,11 +183,17 @@ export async function sharePdfReport(uri: string, options?: { dialogTitle?: stri
}
```
-When `expo-sharing` is absent, generate the same file without the `expo-sharing` import, without `PdfShareResult`, and without `sharePdfReport(...)`. Keep `createPdfReport(...)`, `wrapPdfDocument(...)`, and `escapePdfHtml(...)`.
+For a new generate-only wrapper (or when `expo-sharing` is absent), omit the
+`expo-sharing` import, `PdfShareResult`, and `sharePdfReport(...)`. Keep
+`createPdfReport(...)`, `wrapPdfDocument(...)`, and `escapePdfHtml(...)`. Do not
+remove compatible existing share exports merely because sharing is not requested
+this time; any incompatible existing import follows Step 2a's scoped-update gate.
### 4. Use the wrapper
-Screens import the wrapper, not Expo modules directly:
+Integration guidance for the owner, not instructions to edit screens here.
+Screens import the wrapper, not Expo modules directly. This example includes
+sharing only when approved and available:
```ts
import { createPdfReport, escapePdfHtml, sharePdfReport, wrapPdfDocument } from '@/native/pdfReport';
@@ -190,6 +219,11 @@ If `expo-sharing` is absent, screens may still call `createPdfReport(...)`, prev
### 5. Optional Dataverse upload
+Optional means unrequested, not skippable when retention is approved. Step 2a
+verifies wrapper payload support and the generated signature; the owner supplies
+the app-specific adapter/screen integration below. Return missing helper-owned
+support or unknown required storage as `NEEDS_CONTEXT`, not a capture-only success.
+
Retained PDFs use Dataverse File columns. Save or update the parent row first, verify `success`, then upload a payload compatible with the generated service's `upload(id, columnName, file, fileDisplayName?)` signature. Never put File column bytes in create/update JSON.
```ts
@@ -233,10 +267,14 @@ if (!upload.success) {
### 6. Type-check
```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
npx --no-install tsc --noEmit
```
-Fix any TypeScript errors before rebuilding.
+Fix only in-scope helper errors, then execute the shared compatibility contract's
+Step 4. Recheck requested generation, sharing, and retention payloads, including
+empty HTML, unavailable sharing, print/share failures, and absent required base64.
+Type-check success alone is insufficient; do not fix screen/generated files.
### 7. Native rebuild note
@@ -244,6 +282,10 @@ This skill does not install native code. If `expo-print` or `expo-sharing` was j
### 8. Summary
+Return the shared compatibility result and actual created/updated/reused paths
+before this summary. Report owner-side upload/integration separately; update
+memory-bank only after success, and leave final updates to the owner when orchestrated.
+
Tell the user:
```text
diff --git a/plugins/mobile-apps/skills/add-native/add-pdf-viewer/SKILL.md b/plugins/mobile-apps/skills/add-native/add-pdf-viewer/SKILL.md
index 3a0a68839..f62fd90f1 100644
--- a/plugins/mobile-apps/skills/add-native/add-pdf-viewer/SKILL.md
+++ b/plugins/mobile-apps/skills/add-native/add-pdf-viewer/SKILL.md
@@ -9,6 +9,11 @@ model: sonnet
**📋 Shared instructions: [shared-instructions.md](${PLUGIN_ROOT}/shared/shared-instructions.md)** — read first.
+**Working directory:** before any project read or command, execute
+[native-artifact-compatibility.md Step 0](${PLUGIN_ROOT}/shared/references/native-artifact-compatibility.md#0-bind-every-operation-to-the-app-root).
+Inherit `/add-native`'s resolved absolute `working_dir`; bind every shell call and
+file tool to it, even when this helper starts from another directory.
+
# Add PDF Viewer
**Internal helper.** Users should invoke `/add-native pdf-viewer`, `/add-native pdf-control`, or `/add-native @microsoft/power-apps-native-pdf-viewer`; `/add-native` routes here after resolving the capability.
@@ -20,7 +25,8 @@ Generate or verify the native PDF viewer wrapper and show how to call its **nati
### 1. Verify app
```bash
-test -f app.config.js && test -f power.config.json && test -f package.json && test -d src
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
+test -f app.config.js && test -f power.config.json && test -f package.json && test -d src || { echo "BLOCKED: working_dir is not an initialized app" >&2; exit 1; }
```
If this fails, tell the user to run `/create-mobile-app` first and STOP.
@@ -28,14 +34,29 @@ If this fails, tell the user to run `/create-mobile-app` first and STOP.
### 2. Verify package is already present
```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
node -e "const p=require('./package.json'); const m='@microsoft/power-apps-native-pdf-viewer'; if (!p.dependencies?.[m]) { console.error('MISSING: ' + m + ' is not in package.json. The template/app must already ship this native extension. This skill will not install it or edit native config.'); process.exit(1); } let v; try { v=require('./node_modules/' + m + '/package.json').version; } catch { console.error('MISSING_INSTALL: cannot verify the installed ' + m + ' version. Run the project package install first.'); process.exit(1); } const [major,minor,patch]=v.split('.').map(Number); if (!(major > 0 || minor > 2 || (minor === 2 && patch >= 9))) { console.error('UNSUPPORTED_VERSION: ' + m + ' ' + v + ' does not support file:// URIs. Version 0.2.9+ is required.'); process.exit(1); } console.log('OK: native PDF viewer ' + v + ' supports https:// and file://');"
```
If the check fails, STOP. Do not run `npm install`, `npx expo install`, `pod install`, or edit `app.config.js`. Version 0.2.9+ must already be part of the app's native build.
+### 2a. Reconcile requested artifacts
+
+Read and execute [native-artifact-compatibility.md](${PLUGIN_ROOT}/shared/references/native-artifact-compatibility.md)
+Steps 1–3 for the PDF viewer row before any writes or reuse. Inherit the current
+approval/mode from `/add-native`; do not repeat a valid scoped approval.
+Inspect `src/native/pdfViewer.ts` for `openHttpsPdf`, `PdfViewerResult`, requested
+options/actions, and the actual HTTPS/local-file behavior against installed
+version 0.2.9+. An HTTPS-only implementation cannot satisfy a requested local
+`file://` preview. Check invalid URI and missing-native-module paths, not just
+exports; an incompatible artifact outside approval returns `NEEDS_CONTEXT` to
+the owner, or asks standalone.
+
### 3. Write or verify `src/native/pdfViewer.ts`
-Create `src/native/pdfViewer.ts` if it does not exist. If it already exists, inspect it and patch only if it violates the supported URI rules or throws instead of returning a result.
+Apply Step 2a's decision for `src/native/pdfViewer.ts`: create when requested and
+missing, reuse unchanged only if compatible, or make only the approved scoped
+update. Preserve custom code, exports, and callers; do not overwrite from the example.
The wrapper MUST:
@@ -95,6 +116,8 @@ export async function openHttpsPdf(
### 4. Use the wrapper
+Integration guidance for the owner; do not edit screens in this helper.
+
Screens import the wrapper, not the native package directly:
```ts
@@ -133,10 +156,14 @@ Notes:
### 5. Type-check
```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
npx --no-install tsc --noEmit
```
-Fix any TypeScript errors before rebuilding.
+Fix only in-scope helper errors, then execute the shared compatibility contract's
+Step 4. Recheck requested inputs/options/actions, invalid URI rejection, missing
+native module, and viewer failures. Type-check success alone is insufficient;
+do not fix screen/generated files.
### 6. Native rebuild note
@@ -154,6 +181,10 @@ Do not wire Companion PCF or `NativePdfViewerExtension`. In Power Apps native co
### 8. Summary
+Return the shared compatibility result and actual created/updated/reused paths
+before this summary. Update memory-bank only after success, and leave final
+updates to the owner when orchestrated.
+
Tell the user:
```text
diff --git a/plugins/mobile-apps/skills/add-native/add-pen-input/SKILL.md b/plugins/mobile-apps/skills/add-native/add-pen-input/SKILL.md
index 12f1d2d82..541ed2bf7 100644
--- a/plugins/mobile-apps/skills/add-native/add-pen-input/SKILL.md
+++ b/plugins/mobile-apps/skills/add-native/add-pen-input/SKILL.md
@@ -9,6 +9,11 @@ model: sonnet
**📋 Shared instructions: [shared-instructions.md](${PLUGIN_ROOT}/shared/shared-instructions.md)** — read first.
+**Working directory:** before any project read or command, execute
+[native-artifact-compatibility.md Step 0](${PLUGIN_ROOT}/shared/references/native-artifact-compatibility.md#0-bind-every-operation-to-the-app-root).
+Inherit `/add-native`'s resolved absolute `working_dir`; bind every shell call and
+file tool to it, even when this helper starts from another directory.
+
# Add Pen Input
**Internal helper.** Users should invoke `/add-native pen-input`, `/add-native signature`, or `/add-native @microsoft/power-apps-native-pen-input`; `/add-native` routes here after resolving the capability.
@@ -20,7 +25,8 @@ Generate or verify the native pen input wrapper and show how to call its **nativ
### 1. Verify app
```bash
-test -f app.config.js && test -f power.config.json && test -f package.json && test -d src
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
+test -f app.config.js && test -f power.config.json && test -f package.json && test -d src || { echo "BLOCKED: working_dir is not an initialized app" >&2; exit 1; }
```
If this fails, tell the user to run `/create-mobile-app` first and STOP.
@@ -28,14 +34,29 @@ If this fails, tell the user to run `/create-mobile-app` first and STOP.
### 2. Verify package is already present
```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
node -e "const p=require('./package.json'); const m='@microsoft/power-apps-native-pen-input'; if (!p.dependencies?.[m]) { console.error('MISSING: ' + m + ' is not in package.json. The template/app must already ship this native extension. This skill will not install it or edit native config.'); process.exit(1); } console.log('OK: pen input package present');"
```
If the check fails, STOP. Do not run `npm install`, `npx expo install`, `pod install`, or edit `app.config.js`. This package contains native iOS/Android code and must already be part of the app's native build.
+### 2a. Reconcile requested artifacts
+
+Read and execute [native-artifact-compatibility.md](${PLUGIN_ROOT}/shared/references/native-artifact-compatibility.md)
+Steps 1–3 for the pen input row before any writes or reuse. Inherit the current
+approval/mode from `/add-native`; do not repeat a valid scoped approval.
+Inspect `src/native/penInput.ts` for `captureSignature`, `stripDataUriPrefix`,
+`PenInputResult`, requested options, PNG data URI output, and non-error
+`USER_CANCELLED`. Check approved Image/File payload requirements as well as
+capture: a missing normalizer or unknown required generated service signature
+cannot be ignored. Missing required storage or an incompatible artifact outside
+approval returns `NEEDS_CONTEXT` to the owner, or asks standalone.
+
### 3. Write or verify `src/native/penInput.ts`
-Create `src/native/penInput.ts` if it does not exist. If it already exists, inspect it and patch only if cancellation is treated as an error or the wrapper can throw.
+Apply Step 2a's decision for `src/native/penInput.ts`: create when requested and
+missing, reuse unchanged only if compatible, or make only the approved scoped
+update. Preserve custom code, exports, and callers; do not overwrite from the example.
The wrapper MUST:
@@ -94,6 +115,8 @@ export function stripDataUriPrefix(dataUri: string): string {
### 4. Use the wrapper
+Integration guidance for the owner; do not edit screens in this helper.
+
Screens import the wrapper, not the native package directly:
```ts
@@ -134,6 +157,11 @@ Notes:
### 5. Optional Dataverse save
+Optional means unrequested, not skippable when retention is approved. Step 2a
+verifies wrapper payload support and the generated signature; the owner supplies
+the screen-side save/upload below. Return missing helper-owned support or unknown
+required storage as `NEEDS_CONTEXT`, not a capture-only success.
+
If the user wants to save the signature to a Dataverse Image/File column, use generated services only. Do not write direct Dataverse Web API calls.
Image column pattern: normalize the data URI to the generated service's expected image payload. If raw base64 is required, strip the prefix.
@@ -158,10 +186,14 @@ File column pattern: save or update the parent row first, then upload the PNG by
### 6. Type-check
```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
npx --no-install tsc --noEmit
```
-Fix any TypeScript errors before rebuilding.
+Fix only in-scope helper errors, then execute the shared compatibility contract's
+Step 4. Recheck requested capture/normalization/storage behavior, including user
+cancellation, missing native module, capture failure, and Image versus File payloads.
+Type-check success alone is insufficient; do not fix screen/generated files.
### 7. Native rebuild note
@@ -179,6 +211,10 @@ Do not wire Companion PCF or `PenInputExtension`. In Power Apps native code apps
### 9. Summary
+Return the shared compatibility result and actual created/updated/reused paths
+before this summary. Report owner-side save/integration separately; update
+memory-bank only after success, and leave final updates to the owner when orchestrated.
+
Tell the user:
```text
diff --git a/plugins/mobile-apps/skills/add-sample-data/SKILL.md b/plugins/mobile-apps/skills/add-sample-data/SKILL.md
index 0bbc4867c..34a458116 100644
--- a/plugins/mobile-apps/skills/add-sample-data/SKILL.md
+++ b/plugins/mobile-apps/skills/add-sample-data/SKILL.md
@@ -12,10 +12,10 @@ model: sonnet
# Add Sample Data
-**Invocation scope:** follow [Data-source invocation scope](../../shared/shared-instructions.md#data-source-invocation-scope)
-before any project read or command. Bind the absolute `working_dir` first and
-reuse it for every shell call, file tool, media path, and retry. This data-only
-workflow does not require creating a full app plan or changing screens.
+**App root:** before any project read or command, execute
+[app-working-directory.md](${PLUGIN_ROOT}/shared/references/app-working-directory.md).
+Use its resolved absolute `working_dir` for every shell call and file tool,
+including media paths and retries; never inherit a prior `cd`.
Populate Dataverse tables with realistic sample records so a freshly-scaffolded code app shows real-looking data on first launch. Generates rows from each table's schema and inserts them in dependency order. Use after `/add-dataverse` (or `/setup-datamodel`) has created the tables.
@@ -253,7 +253,7 @@ For the selected tables, build a dependency graph from lookup columns:
If a selected table references an UNSELECTED parent, reuse a verified existing
parent record through a bounded read when that lookup is within the approved
-data scope. Reading a lookup parent is not permission to insert/update it. If no
+feature. Reading a lookup parent is not permission to insert/update it. If no
suitable record exists, return `NEEDS_CONTEXT` to the owner (or ask standalone)
to extend the seed scope or explicitly omit an optional lookup. Never auto-add
a parent to `seedTables`, create a retiring parent, or omit a required lookup.
diff --git a/plugins/mobile-apps/skills/add-sharepoint/SKILL.md b/plugins/mobile-apps/skills/add-sharepoint/SKILL.md
index feea830fe..c3f200597 100644
--- a/plugins/mobile-apps/skills/add-sharepoint/SKILL.md
+++ b/plugins/mobile-apps/skills/add-sharepoint/SKILL.md
@@ -23,6 +23,9 @@ model: sonnet
Use its resolved absolute `working_dir` for every shell call and file tool,
including referenced commands and delegated skills; never inherit a prior `cd`.
+**Entry routing:** use the shared [App feature entry points](../../shared/shared-instructions.md#app-feature-entry-points)
+preflight before the workflow below.
+
**Invocation scope:** follow [Data-source invocation scope](../../shared/shared-instructions.md#data-source-invocation-scope)
before the workflow below. Standalone calls approve only their SharePoint
schema/binding delta and verify it here; they do not start a full-app workflow.
diff --git a/plugins/mobile-apps/skills/check-updates/SKILL.md b/plugins/mobile-apps/skills/check-updates/SKILL.md
index 346ce1ac1..677b026e4 100644
--- a/plugins/mobile-apps/skills/check-updates/SKILL.md
+++ b/plugins/mobile-apps/skills/check-updates/SKILL.md
@@ -6,7 +6,7 @@ allowed-tools: Read, Write, Edit, Glob, Grep, Bash, WebFetch, AskUserQuestion
model: opus
---
-**Shared instructions: [shared-instructions.md](../../shared/shared-instructions.md)** - skip its version check and `memory-bank.md` handling because this skill performs its own plugin check and must not create unrelated project state.
+**Shared instructions: [shared-instructions.md](../../shared/shared-instructions.md)** - read first, then skip its version check and `memory-bank.md` handling because this skill performs its own plugin check and must not create unrelated project state.
# Check Updates (`/check-updates`)
diff --git a/plugins/mobile-apps/skills/create-mobile-app/SKILL.md b/plugins/mobile-apps/skills/create-mobile-app/SKILL.md
index 91597c3e4..bfe93e301 100644
--- a/plugins/mobile-apps/skills/create-mobile-app/SKILL.md
+++ b/plugins/mobile-apps/skills/create-mobile-app/SKILL.md
@@ -14,6 +14,16 @@ model: opus
Top-level orchestrator. Owns the user-visible flow; delegates planning to the `native-app-planner` agent and per-domain mutation to dedicated `/add-*` skills.
+For every child skill handoff, pass the invocation-scoped
+[app-edit-routing.md](../../shared/references/app-edit-routing.md) context:
+`MOBILE_APP_ORCHESTRATING=1`, `orchestrator: create-mobile-app`, the absolute
+`working_dir`, current `phase`, and the exact approved scope/answers for
+implementation. Forward it through routers and native helpers; do not persist it
+or rely on an earlier shell export. The plan exists before the app is fully built,
+so children must use this context rather than mistake creation for a standalone
+edit. Design/configuration children still own any approval explicitly delegated
+to their phase; this marker never skips those gates.
+
## Workflow
Resume/template checks → prerequisites → requirements (iOS + Android fixed) →
@@ -1741,15 +1751,26 @@ Invoke skill: /design-system
Environment:
CODE_APPS_NATIVE_ORCHESTRATING=1
+Context:
+ MOBILE_APP_ORCHESTRATING=1
+ orchestrator: create-mobile-app
+ working_dir: <working_dir>
+ phase: design
+ approved_scope: <confirmed app intent; design-system owns its design approval>
+
Arguments:
- --working-dir <working_dir>
+ --working-dir '<working_dir>'
```
The `Environment` block is load-bearing, and follows the nested-skill handoff `/edit-app` already
uses. `/design-system` and its style picker gate every browser opener on that variable; without it
they detect a standalone run and open tabs over the build plan.
-The skill detects orchestrator mode (`CODE_APPS_NATIVE_ORCHESTRATING=1`), collects brand inputs, presents the cost picker (a/b/c/d), runs the internal style picker, writes `brand/design-system.md` + `brand/tokens.ts`, renders `brand/design-system.html`, and returns with status.
+The scoped `MOBILE_APP_ORCHESTRATING=1` context identifies the owner and approval
+boundary; `CODE_APPS_NATIVE_ORCHESTRATING=1` separately suppresses nested browser
+openers. The skill collects brand inputs, presents the cost picker (a/b/c/d),
+runs the internal style picker, writes approved brand artifacts, and returns
+with status.
As soon as `/design-system` returns, replace the note — the user has answered and the run is
working again:
@@ -2356,6 +2377,13 @@ Read the `## Native Capabilities` section from `native-app-plan.md`. For each ca
```
Invoke skill: /add-native
+Context:
+ MOBILE_APP_ORCHESTRATING=1
+ orchestrator: create-mobile-app
+ working_dir: <working_dir>
+ phase: implementation
+ approved_scope: <approved capability row, storage target, and screen requirements>
+
Arguments:
--working-dir <working_dir>
--capability <name>
@@ -2398,6 +2426,12 @@ summary. Re-run `npx --no-install tsc --noEmit` after Tamagui config changes.
exports `appLightTheme` and `appDarkTheme`. Map those resolved semantic values
into the host themes so `useTheme()` and `useThemeTokens()` cannot drift:
+If the approved design includes a custom dark palette, apply the reference's
+**Approved dark palette** branch first: import `darkTokens` from
+`brand/tokens.dark.ts` in `tamagui.config.ts` and derive `appDarkTheme` from
+`darkTokens.color`. The provider mapping below then consumes that resolved theme;
+do not leave the base accent-only dark declaration in place.
+
```tsx
import {
PowerAppsProvider,
@@ -2447,9 +2481,11 @@ const brandedDarkTheme: ThemeTokens = {
<PowerAppsProvider ... theme={brandedLightTheme} darkTheme={brandedDarkTheme}>
```
-The generated schema has one brand palette, so the exported dark app theme
-retains Config v5 dark surfaces and text while carrying brand accents and
-statuses. For runtime theme switching, use `useThemeControl()` from
+Without an approved custom dark palette, the exported dark app theme retains
+Config v5 dark surfaces and text while carrying brand accents and statuses.
+With an approved custom dark palette, `appDarkTheme` instead resolves the full
+`darkTokens.color` palette, including its surfaces and text, and the provider
+mapping above uses that same resolved theme. For runtime theme switching, use `useThemeControl()` from
`@microsoft/power-apps-native-host`.
### Step 10 — Add connectors
diff --git a/plugins/mobile-apps/skills/debug-app/SKILL.md b/plugins/mobile-apps/skills/debug-app/SKILL.md
index f74bdd3ba..65e195913 100644
--- a/plugins/mobile-apps/skills/debug-app/SKILL.md
+++ b/plugins/mobile-apps/skills/debug-app/SKILL.md
@@ -879,7 +879,7 @@ Apply this gate before D3 whenever the failing stack, module, or export involves
| `app/` screen file, `_layout.tsx`, route segment | Inline edit via `Edit` tool |
| `src/components/` | Inline edit via `Edit` tool |
| `src/hooks/`, `src/services/` | Inline edit via `Edit` tool |
-| `src/generated/` | **Do not edit.** Fix the upstream query or schema and run `npm run generate-schemas` |
+| `src/generated/` | **Do not edit.** Hand off service/model repair to the owning data-source skill using CLI refresh; `npm run generate-schemas` only regenerates the runtime connector map. Do not re-add an intentionally retired source. |
| Dataverse schema (column/table missing) | Run D2's read-only Dataverse diagnostic sequence first. If live metadata/generated artifacts confirm the schema or service is missing, **hand off** to `/add-dataverse`. Do not mutate Dataverse or edit generated files from `/debug-app`. |
| Auth / MSAL (`AADSTS65001`, `AADSTS50011`) | **Hand-off:** route user to the Power Apps Wrap page via `/set-app-registration-native`. Do not auto-edit registrations. |
| Connection / connector reference missing | **Hand-off:** route user to `/list-connections` or `/add-connector`. |
@@ -925,7 +925,7 @@ Before applying any recipe, run the first-party native package ownership gate wh
| Error pattern | Precondition | Action |
|---|---|---|
| `SyntaxError: <file>:<line>:<col>` in `app/`, `src/components/`, `src/hooks/`, `src/services/` | The cited line is in editable user code (NOT `src/generated/`, NOT `node_modules/`) | `Read` the file around the cited line (±10 lines), identify the syntactic issue (unclosed JSX tag, missing closing brace/paren, stray comma, missing `from` in import, unterminated string, missing semicolon between statements), apply a single minimal `Edit`. Do NOT reformat surrounding code. |
-| `SyntaxError` in `src/generated/` | Cited file is under `src/generated/` | **Do not edit.** 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. |
+| `SyntaxError` in `src/generated/` | Cited file is under `src/generated/` | **Do not edit.** For `connectorSchemas.ts`, regenerate the runtime map. For services/models, resolve the existing registration and hand off to `/add-connector` or `/add-dataverse` with `--refresh --data-source-name "<registered-name>"`, the absolute app root, and approved scope for targeted CLI refresh and validation. Check the approved plan first: a removed source needs consumer cleanup through `/edit-app`, not re-registration. Missing/ambiguous registrations block refresh; do not fall back to addition. |
| `Unable to resolve module <name>` from `<importer>` | `<name>` starts with `.` or `..` (relative import) | `Glob` the importer's directory for files matching `<name>` with any extension (`.ts`, `.tsx`, `.js`, `.jsx`, `.json`). If found with a different extension → fix the import to drop the extension OR match the actual one. If found with a typo (Levenshtein ≤ 2) → fix the typo. If not found at all → the file genuinely doesn't exist; surface to user and ask whether to create it or remove the import. |
| `Unable to resolve module <name>` | `<name>` is a bare package AND not present in `package.json` `dependencies` / `devDependencies` | Follow [`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: ask the user to stop Metro, rerun `npm run dev -- --clear`, then reload. Never kill an unowned process. |
@@ -1042,7 +1042,10 @@ Do NOT attempt a third automated fix for the same error. Wait for user guidance.
## Constraints
- **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 modify `src/generated/`** — these files are auto-generated. The owning
+ data-source skill uses CLI add/refresh/remove for models/services and config;
+ `npm run generate-schemas` only rebuilds the runtime map afterward. Preserve
+ the approved source inventory; do not resurrect retired sources during repair.
- **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:
diff --git a/plugins/mobile-apps/skills/design-system/SKILL.md b/plugins/mobile-apps/skills/design-system/SKILL.md
index d8fd0d5cc..d5a21820a 100644
--- a/plugins/mobile-apps/skills/design-system/SKILL.md
+++ b/plugins/mobile-apps/skills/design-system/SKILL.md
@@ -2,7 +2,7 @@
name: design-system
description: Creates the Tamagui brand system for an Expo/React Native Power Apps mobile app, including design-system.md, tokens.ts, and an HTML gallery.
user-invocable: true
-allowed-tools: Read, Write, Edit, Glob, Grep, Bash, AskUserQuestion, Task, WebFetch
+allowed-tools: Read, Write, Edit, Glob, Grep, Bash, AskUserQuestion, Task, WebFetch, Skill
model: opus
---
@@ -12,6 +12,17 @@ model: opus
# Design System
+**Entry routing:** use the shared [App feature entry points](../../shared/shared-instructions.md#app-feature-entry-points)
+preflight before the workflow below.
+
+Before reading brand state, bind `working_dir` through
+[app-working-directory.md](../../shared/references/app-working-directory.md).
+Use that root for every shell call and absolute file-tool path, including
+history, rollback, previews, and runtime wiring in the referenced workflows.
+
+Read-only `--history` / `--diff` and standalone brand generation without an app
+remain here.
+
Source of truth for every screen built in a Power Apps mobile app. Produces three artifacts:
1. `brand/design-system.md` — full spec (palette, typography, spacing, components, negatives)
@@ -30,7 +41,7 @@ Design-system and Tamagui integration are complementary, not alternatives. `/des
## When NOT to use
-- Screen-level visual tweaks → use `/tweak-screen` (deterministic, 0 tokens)
+- Screen-level visual tweaks → use `/edit-app`
- Plan-level screen changes → use `/edit-app screens`
- Data model changes → use `/add-dataverse` or `/setup-datamodel`
@@ -63,20 +74,36 @@ Design-system and Tamagui integration are complementary, not alternatives. `/des
Detect invocation mode:
```
-1. Check env var CODE_APPS_NATIVE_ORCHESTRATING=1
- → Mode A (folded into /create-mobile-app Step 6.5)
+1. Check MOBILE_APP_ORCHESTRATING=1 AND matching explicit caller context
+ → Mode A (folded into /create-mobile-app or approved /edit-app work)
-2. Check cwd for app.config.js + tamagui.config.ts + package.json with expo deps
+2. Check the resolved working_dir for app.config.js + tamagui.config.ts + package.json with expo deps
→ Mode B (standalone in existing project)
3. Else
→ Mode C (standalone, no project)
- → Ask: "No native project detected. Write brand/ to current directory? [y/N]"
+ → Ask: "No native project detected. Write brand/ to <working_dir>? [y/N]"
```
-For Mode A/B, set `working_dir` to cwd. For Mode C, confirm with user.
-
-**Drift detection (Mode B only — existing brand/ present):**
+All modes retain the already resolved `working_dir`; do not resolve another root
+from the launch directory. Mode C still requires user confirmation before writes.
+
+**Write boundary (all paths):** `--plan-only` or a planning-phase handoff returns
+only a proposal; do not write brand artifacts, previews, history, or memory-bank.
+Detect prior brand state before generating anything: an existing spec, light or
+dark token file, gallery, history, or record of a previously applied design makes
+this a rerun, not first-time generation. A new creation plan alone is not prior
+brand state; first-time drafts generated in this invocation remain drafts during
+edit/regeneration, not pre-existing approved designs. Keep proposed choices and
+memory-bank notes pending until approval. On reruns, do not overwrite live
+artifacts or existing previews during input/style selection; any comparison
+preview must be proposal-only.
+Every generation/reskin rerun uses **Sub-step 3.5** before its first live write,
+even if its cost path or input flag skips other sub-steps. Dedicated refresh,
+dark-mode, and rollback commands retain their own equivalent approval/backup
+flows; do not add a second gate to them.
+
+**Drift detection (Mode A/B — existing brand/ present):**
If `brand/design-system.md` AND `brand/tokens.ts` both exist:
1. Parse current tokens.ts palette + typography tokens
@@ -84,6 +111,9 @@ If `brand/design-system.md` AND `brand/tokens.ts` both exist:
3. Compute diff
4. If divergent → surface drift, ask user to resolve before proceeding (see [refresh-flow.md](./references/refresh-flow.md) § Drift)
+Treat that resolution as a proposal until the concrete approval and backup
+boundary (Sub-step 3.5 for generation reruns); do not repair drift during detection.
+
---
## Sub-step 1 — Brand inputs
@@ -93,7 +123,10 @@ If `brand/design-system.md` AND `brand/tokens.ts` both exist:
**Print:**
> "→ [design-system] Checking for brand inputs…"
-**MUST stop and wait for user response.** Do NOT skip this step.
+Reuse brand inputs and decisions in the approved caller scope. Ask only for
+missing inputs; return scope-changing choices to `/edit-app` rather than
+reopening an independent design flow. Fresh creation still owns the interactive
+brand selection below when those choices have not yet been made.
Ask user for optional brand input. See [`references/input-modes.md`](./references/input-modes.md) for full processing details.
@@ -134,7 +167,7 @@ If flag was passed on invocation, skip asking — process directly.
**On skip:** Continue with no brand context.
**Priority order** when multiple inputs given:
-1. `--design-spec` (highest — skips Sub-steps 3 AND 4)
+1. `--design-spec` (highest — skips style/spec generation, not Sub-step 3.5 or confirmation)
2. `--brand-doc` (locks direction, skips Sub-step 3)
3. `--from-figma` (locks palette + typography + components)
4. `--from-code-app` (highest fidelity sibling)
@@ -177,25 +210,32 @@ Show the cost picker, adapting the intro and option set to brand input.
**Note:** Option (c) "Brand preview" only appears when brand input was provided (there's nothing to preview without brand tokens).
-Persist choice to `memory-bank.md`: `visual_companion: <yes|no|skip>`
+Keep `visual_companion: <yes|no|skip>` pending; persist it to `memory-bank.md`
+only after the applicable approval.
**Branches:**
-- **(a)** → continue all sub-steps (Sub-steps 3–7) (~3 min)
-- **(b)** → skip Sub-step 3 (style picker), run Sub-steps 4–7 (spec + gallery + confirmation)
-- **(c) Brand preview** → skip Sub-steps 3–6, render key screen mockups (List + Form + Detail) with brand tokens applied, open browser (standalone runs only; otherwise print the path), proceed to Sub-step 7. No extra question about how many screens — always shows 3 key screens.
+- **(a)** → style picker (Sub-step 3), then Sub-step 3.5 before Sub-steps 4–7 (~3 min)
+- **(b)** → skip Sub-step 3 (style picker), run Sub-step 3.5 before Sub-steps 4–7 (spec + gallery + review)
+- **(c) Brand preview** → prepare the brand-token candidate, run Sub-step 3.5 before applying it, then render key screen mockups (List + Form + Detail), open browser on standalone runs only (otherwise print the path), and proceed to Sub-step 7. Skip style picking and full-spec generation, not the write boundary. No extra question about how many screens — always shows 3 key screens.
- **(c) Apply defaults / (d) — no-brand path** → skip Sub-steps 3, 5. Run these in order:
- 1. **Minimal Sub-step 4** — write `brand/tokens.ts` from the industry's direction preset.
+ 1. **Minimal Sub-step 4** — prepare `brand/tokens.ts` from the industry's direction preset, then run Sub-step 3.5 before writing it.
**Source-of-truth lookup order for the preset bundle:**
1. If the user passed `--direction <name>` (e.g. `inspection`, `saas`, `product`), load `${PLUGIN_ROOT}/skills/design-system/references/vibe/direction-<name>.md` and use its tokens.
- 2. **Airline / aviation / commercial-flight carve-out (HARD RULE).** If the brief contains any of `airline`, `aviation`, `flight`, `aircraft`, `carrier`, `pilot`, `cabin crew`, `boarding`, `departure`, `tarmac`, `turnaround`, `ground ops`, OR the app name contains those tokens, DO NOT load the `signature` preset (safety-orange would clash with airline brand expectations). Instead **load [`${PLUGIN_ROOT}/skills/design-system/references/vibe/direction-airline.md`](./references/vibe/direction-airline.md)** — deep aviation blue (`#0A4F8F`), white surfaces, hi-vis status pills, hairline borders. Token bundle is the canonical FlightCheck tokens (proven in production). Record in `memory-bank.md` as `direction: airline`.
+ 2. **Airline / aviation / commercial-flight carve-out (HARD RULE).** If the brief contains any of `airline`, `aviation`, `flight`, `aircraft`, `carrier`, `pilot`, `cabin crew`, `boarding`, `departure`, `tarmac`, `turnaround`, `ground ops`, OR the app name contains those tokens, DO NOT load the `signature` preset (safety-orange would clash with airline brand expectations). Instead **load [`${PLUGIN_ROOT}/skills/design-system/references/vibe/direction-airline.md`](./references/vibe/direction-airline.md)** — deep aviation blue (`#0A4F8F`), white surfaces, hi-vis status pills, hairline borders. Token bundle is the canonical FlightCheck tokens (proven in production). After approval, record in `memory-bank.md` as `direction: airline`.
3. **Else (true "all defaults" path) → load [`${PLUGIN_ROOT}/skills/design-system/references/vibe/direction-polished-inspection.md`](./references/vibe/direction-polished-inspection.md) as the canonical `polished-inspection` preset** — white surface, Power-Platform green `#007d48` accent (Power Platform–aligned default), status-stripe cards, soft-tinted status pills, large tap targets. This is the polished MVP default that fits any inspection / field-ops / asset-tracking app (~70% of mobile-app traffic) AND demos cleanly to enterprise stakeholders. The previous `signature` preset (slate dark + safety orange, sourced from `uber-design.md`) is now opt-in via `--direction inspection` for true outdoor-only field apps.
4. As a last fallback, if the source file is unreadable, use the inspection direction inlined in [`references/design-system-schema.md`](./references/design-system-schema.md).
- Skip the full `brand/design-system.md` write — only `brand/tokens.ts` is needed. Record the chosen source in `memory-bank.md` under `## Design`: `direction: polished-inspection (default — white + Power-Platform green, demo-friendly enterprise polish)` so future runs know what was picked.
+ For first-time defaults, skip the full `brand/design-system.md` write — only `brand/tokens.ts` is needed. If a prior full design exists, do not silently replace its tokens with defaults: Sub-step 3.5 must approve the concrete token delta and corresponding spec-section updates together, or preserve both unchanged. Record the chosen source in `memory-bank.md` only after approval under `## Design`: `direction: polished-inspection (default — white + Power-Platform green, demo-friendly enterprise polish)` so future runs know what was picked.
2. **Mini-preview (Sub-step 6.5 lite)** — render exactly 3 screens (List + Form + Detail archetypes from the plan's `## Screens`; if fewer exist, render whichever do) using the same HTML preview template + Tamagui-to-HTML mapping as `screen-planner`, with `brand/tokens.ts` values substituted. Write to `<working_dir>/_plan_preview.html` — the canonical filename. `/create-mobile-app` takes its screen carousel from that file and the build plan links it, so writing anything else leaves both empty on this path. Open it in the browser on standalone runs only; in orchestrator mode print the path, because the build plan already links it. Print: `"→ Polished-inspection preview ready at file://<working_dir>/_plan_preview.html — confirm the look (or re-run /design-system --direction <inspection|saas|product> to switch)."`
3. **Return DONE** so Step 9b of the orchestrator picks up `brand/tokens.ts` and applies [`references/tamagui-integration.md`](./references/tamagui-integration.md) in brand-import mode.
- **Never return DONE without writing `brand/tokens.ts`.** The label promises "applied defaults"; the implementation must deliver tokens AND a preview, otherwise the user has no way to verify the look short of waiting for full screen-builders + emulator boot. The preview is fast (HTML, no JS execution) and uses the same renderer Sub-step 6.5 uses for paths (a)/(b).
+ **Return DONE only after the approved tokens are available** (written after the boundary, or unchanged existing tokens reused). Cancellation or missing approval never authorizes a write to satisfy this requirement. The label promises "applied defaults"; the implementation must deliver tokens AND a preview, otherwise the user has no way to verify the look short of waiting for full screen-builders + emulator boot. The preview is fast (HTML, no JS execution) and uses the same renderer Sub-step 6.5 uses for paths (a)/(b).
+
+**`--design-spec` passthrough:** Validate and prepare the imported spec and matching
+light tokens without copying into `brand/`. Run Sub-step 3.5, apply only the
+approved replacement (or first-time draft), then continue to Sub-steps 5–7.
+Skipping generation is not permission to bypass approval, backup, or first-time
+confirmation.
**On ANY input failure during Sub-step 1**, after printing "BLOCKED: {{input}} — {{reason}}":
@@ -250,6 +290,58 @@ If brand_notes or --logo palette exist, prepend banner showing inferred recommen
- Retry cap: max 2 regenerates
Store result as `picked_direction` with all resolved dimensions.
+Keep selection/rejection notes pending on reruns rather than letting the folded
+picker persist them before Sub-step 3.5.
+
+---
+
+## Sub-step 3.5 — Approve the concrete delta + verify backup
+
+**Mandatory generation write boundary for reruns:** paths (a), (b), both (c) paths,
+(d), `--design-spec`, reskin, edits, and regeneration. Reuse the approval rule in
+[refresh-flow.md Step 5](./references/refresh-flow.md#step-5--update-the-spec);
+the dedicated refresh flow remains the owner of single-dimension refreshes.
+
+1. Prepare the complete candidate without live writes. Show the concrete
+ before/after delta: palette values, typography, component/density/negative
+ changes, affected spec sections and token files, and any gallery/preview or
+ Design-record updates. Include any dark-file creation, replacement, or
+ removal and the resulting default/custom selection. If dark state is out of
+ scope, preserve its exact contents, presence/absence, and approved selection;
+ default dark never requires creating a dark file. For minimal/brand-preview
+ paths with a prior full spec, include matching spec-section updates rather
+ than leaving the spec and tokens divergent.
+2. Obtain explicit approval of that concrete delta, or reuse the current
+ owner's matching approved scope **without another prompt**. The owner,
+ absolute working directory, implementation phase (or explicitly delegated
+ design gate), and exact proposed changes must match. A cost choice, style
+ pick, input flag, stale Design record, or orchestration marker alone is not
+ approval to replace an existing design. Changed or missing caller scope
+ returns `NEEDS_CONTEXT` to the owner; do not independently widen its approval.
+3. Cancellation, dismissal, silence, or an ambiguous answer means **no live
+ writes**: stop or clarify. Do not create a history snapshot, overwrite spec,
+ tokens, galleries/previews, persist pending memory-bank notes, change the
+ approved dark selection, or report the candidate as applied/locked.
+4. After approval and before the first write or deletion, capture the existing
+ state using the [snapshot contract](./references/refresh-flow.md#snapshot-contract).
+ Include optional `brand/tokens.dark.ts` and explicit absence. Verify every
+ expected backup member; a failed or incomplete backup blocks all live writes.
+ Partial or unknown prior state is not first-time generation: if it cannot be
+ captured safely under that contract, stop and resolve it with the owner rather
+ than inventing an initial snapshot. Retain the pre-write snapshot unchanged.
+5. Apply only the approved candidate via Sub-step 4, the minimal/brand-preview
+ path, or validated spec passthrough, then render/review. If the candidate or
+ current baseline changes after approval, return to this boundary for the new
+ delta and a verified backup before further writes. An unchanged candidate
+ needs no duplicate approval or snapshot.
+
+**First-time generation with no prior brand state:** keep the existing
+generation-then-review flow; there is no pre-edit state to back up. Full designs
+and imported specs stay drafts through Sub-steps 4–5 and become approved only at
+Sub-step 6 (or through an owner's exact approval of the generated candidate).
+Do not create an approved initial snapshot before that confirmation. Minimal
+defaults/brand previews keep their existing lightweight path; they do not
+invent a confirmed full spec or an approved full-design history entry.
---
@@ -260,7 +352,12 @@ Store result as `picked_direction` with all resolved dimensions.
**Print:**
> "→ [design-system] Writing brand/design-system.md…"
-Generate the full spec deterministically from the locked direction. Follow the schema in [`references/design-system-schema.md`](./references/design-system-schema.md).
+On reruns, write only the candidate approved in Sub-step 3.5, after its verified
+pre-write backup. Do not generate a different design after obtaining approval.
+For first-time generation, write the draft spec deterministically from the
+selected direction. Follow the schema in
+[`references/design-system-schema.md`](./references/design-system-schema.md).
+History completion occurs after confirmation in Sub-step 6, not here.
**Sections (required):**
@@ -369,13 +466,6 @@ export const tokens = {
export type BrandTokens = typeof tokens;
```
-**Snapshot to history:**
-
-```bash
-mkdir -p brand/.history
-cp brand/design-system.md "brand/.history/$(date -u +%Y-%m-%dT%H-%M-%SZ)-initial.md" 2>/dev/null || true
-```
-
---
## Sub-step 5 — Render brand/design-system.html (paths (a) and (b))
@@ -406,6 +496,7 @@ Write to `brand/design-system.html`.
**Open in browser — standalone runs only:**
```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
open "brand/design-system.html" 2>/dev/null \
|| xdg-open "brand/design-system.html" 2>/dev/null \
|| echo "Preview at: file://$(pwd)/brand/design-system.html"
@@ -426,6 +517,13 @@ interrupts rather than informs. Run standalone, open as usual — there is no pl
**Print:**
> "→ [design-system] Design system ready for review."
+For reruns, this is review of the already approved delta, not the first
+authorization to write. If it matches the approved candidate and no revision is
+requested, continue without another confirmation prompt, including matching
+owner-approved calls. First-time full designs/imports require confirmation of
+the generated candidate unless the owner already approved that exact candidate.
+In either approved case, complete history below before continuing to Sub-step 6.5.
+
```
Summary
─────────────────────────────────────────────
@@ -453,17 +551,45 @@ What now?
If user says "change palette AND typography" → refuse, ask which first.
**On [edit X]:**
-1. Prompt for the specific change
-2. Update ONLY that section of `brand/design-system.md`
-3. Regenerate `brand/tokens.ts` from updated spec
-4. Re-render `brand/design-system.html`
-5. Show summary again
+1. Resolve the specific change as a candidate without live writes.
+2. On reruns or edits to an already confirmed design, return to Sub-step 3.5
+ for concrete-delta approval and a verified backup before updating anything.
+ An earlier approval does not cover changed values or expanded scope.
+3. Apply only that approved section and its corresponding token changes,
+ then re-render and show the summary again. Unconfirmed first-time drafts
+ may be revised before confirmation; do not snapshot them as approved.
**On [confirm]:**
-Continue to Sub-step 6.5.
+Accept the generated candidate, complete history below, then continue to Sub-step 6.5.
**On [regenerate]:**
-Go back to Sub-step 3 (counts against retry cap of 2).
+Go back to Sub-step 3 (counts against retry cap of 2). A new direction invalidates
+the previous candidate approval; reruns must pass Sub-step 3.5 again before any
+replacement. First-time regenerated drafts still wait for confirmation.
+
+**On [skip — use as draft]:**
+Only first-time unconfirmed output can proceed to Sub-step 7 as draft, without
+an approved initial snapshot or a locked-design record. This is not a bypass
+for replacing an existing design; leave the previously approved live state
+unchanged.
+
+**On cancel, dismissal, silence, or ambiguity:**
+Stop or clarify without further writes, history creation, or approval/lock
+updates. Do not treat an unconfirmed first-time draft as an approved design.
+
+**History completion (after confirmation):**
+
+- If a pre-write snapshot was captured, retain it unchanged. Do not create a
+ second post-write `-initial` snapshot on refresh, reskin, or regeneration.
+- Only for first-time generation with no prior brand state, record one complete
+ approved initial snapshot after generation **and explicit confirmation** of
+ that candidate (or the owner's matching exact approval), using the same
+ [snapshot contract](./references/refresh-flow.md#snapshot-contract): spec,
+ light tokens, optional dark-token payload, and explicit presence/approval
+ state. Do not save only the Markdown spec or snapshot an unconfirmed draft.
+- Verify every expected member before reporting success. A failed or incomplete
+ snapshot is a visible failure, not a suppressed copy error or a valid
+ rollback target.
---
@@ -509,6 +635,10 @@ interrupts rather than informs. Run standalone, open as usual — there is no pl
**Telemetry checkpoint: `persist_design_system`**
+Persist only the applied state and approved notes. For an explicitly accepted
+first-time draft, label the summary/return as draft and omit `design_system_locked`;
+the locked messages below apply only to confirmed designs.
+
**Print:**
> "→ [design-system] Done. Design system locked."
@@ -557,9 +687,10 @@ See [`references/refresh-flow.md`](./references/refresh-flow.md) for full detail
4. Prompt for the specific change to the named dimension
5. Update ONLY that section (refuse bundled changes)
6. Regenerate `brand/tokens.ts`
-7. Snapshot to `brand/.history/`
+7. Retain the pre-write snapshot captured before steps 5-6 in `brand/.history/`,
+ including dark-token presence/absence per the shared snapshot contract
8. Re-render `brand/design-system.html`
-9. Confirmation gate
+9. Review the applied diff (approval must precede steps 5-6)
10. Append to `## Design history` in memory-bank
**Allowed dimensions:** `palette`, `typography`, `components`, `density`, `negatives`, `motion`
@@ -571,9 +702,9 @@ See [`references/refresh-flow.md`](./references/refresh-flow.md) for full detail
| `--refresh palette` | ~3k | ~30 sec | no (tokens swap) |
| `--refresh typography` | ~3k | ~30 sec | no (tokens swap) |
| `--refresh components` | ~5k | ~45 sec | yes (primitives regenerate) |
-| `--refresh density` | ~3k | ~30 sec | no |
-| `--refresh negatives` | ~2k | ~20 sec | no |
-| `--refresh motion` | ~3k | ~30 sec | no |
+| `--refresh density` | ~3k | ~30 sec | inspect affected layouts |
+| `--refresh negatives` | ~2k | ~20 sec | inspect screens for newly forbidden patterns |
+| `--refresh motion` | ~3k | ~30 sec | inspect consumers |
| `--reskin` | ~50-80k | ~5-10 min | YES (every screen) |
| `--add-dark-mode` | ~5-8k | ~1 min | yes (ThemeProvider wired) |
@@ -596,16 +727,25 @@ See [`references/refresh-flow.md`](./references/refresh-flow.md) for full detail
3. User approval gate (show derived palette, allow [y/N/edit])
-4. Write `brand/tokens.dark.ts`
+ After approval, capture the pre-write [snapshot contract](./references/refresh-flow.md#snapshot-contract),
+ including whether `brand/tokens.dark.ts` exists, before Step 4 writes it.
+
+4. Write `brand/tokens.dark.ts` using the named `darkTokens` export and complete
+ `color` shape in
+ [Approved dark palette](./references/tamagui-integration.md#approved-dark-palette-conditional).
+ Use the approved dark values, not copies of the light surfaces/text.
-5. Generate theme infrastructure:
- - `src/theme/index.ts` — themes registry
- - `src/theme/ThemeProvider.tsx` — system-follow + manual override
- - `src/theme/useTheme.ts` — convenience hooks
+5. Return the dark palette and required wiring to the owning create/edit
+ orchestrator. It applies [tamagui-integration.md](./references/tamagui-integration.md)
+ to the existing light/dark themes and `PowerAppsProvider`; do not generate an
+ app-owned theme provider or a second theme registry.
-6. Patch `app/_layout.tsx` to wrap with ThemeProvider
+6. Let the owner update any approved theme-switching UI and verify it. In
+ implementation-only mode, report the unwired runtime dependency rather than
+ claiming dark mode is active.
-7. Snapshot + history
+7. Retain the pre-write snapshot and record the approved dark palette in design
+ history; do not overwrite the rollback target with the newly generated file.
---
@@ -618,6 +758,8 @@ See [`references/refresh-flow.md`](./references/refresh-flow.md) for full detail
```
History stored in `brand/.history/`, capped at 50 entries (oldest auto-pruned).
+Follow the [snapshot contract and rollback flow](./references/refresh-flow.md#snapshot-contract)
+for light/dark artifacts, explicit absence, and restoration of runtime wiring.
---
@@ -626,9 +768,9 @@ History stored in `brand/.history/`, capped at 50 entries (oldest auto-pruned).
| Consumer | Reads from brand/ | Behavior |
|---|---|---|
| `screen-builder` | `brand/design-system.md` (MANDATORY) | Negatives = HARD RULES. Token references required. |
-| Tamagui integration reference | `brand/tokens.ts` | Applied through native-host theme helpers by `/create-mobile-app` Step 9b |
+| Tamagui integration reference | `brand/tokens.ts` and approved dark palette | Applied through native-host theme helpers by `/create-mobile-app` Step 9b or `/edit-app` Step 5 |
| `preview-screens` | `visual_companion` flag | Renders previews with brand tokens |
-| `/edit-app` | Routes visual changes here | Non-visual schema and screen-plan changes stay in `/edit-app` |
+| `/edit-app` | Routes approved visual changes here | Owns Design plan, runtime wiring, affected screen changes, and final verification |
| `/deploy` | `brand/` shipped in bundle | No special handling |
---
@@ -663,6 +805,6 @@ All external inputs MUST follow the policies in [`references/input-modes.md`](./
## Notes
- **Read-only with respect to app source code.** This skill writes only to `brand/`, `_design_vibe.html`, `memory-bank.md`, and `_plan_preview.html`. Never touches TSX, services, or generated code.
-- **Re-runnable.** Each run overwrites brand/ files (with snapshot to .history/). Memory bank entries accumulate.
+- **Re-runnable.** Approved reruns replace only the agreed brand/ files after a verified pre-write snapshot. Memory bank entries accumulate only for applied changes.
- **One-major-change-per-prompt.** Refuse bundled dimension changes. Ask which first.
- **Retry cap.** Max 2 direction regenerates per session.
diff --git a/plugins/mobile-apps/skills/design-system/references/design-system-schema.md b/plugins/mobile-apps/skills/design-system/references/design-system-schema.md
index e0351dd32..bf803548a 100644
--- a/plugins/mobile-apps/skills/design-system/references/design-system-schema.md
+++ b/plugins/mobile-apps/skills/design-system/references/design-system-schema.md
@@ -9,10 +9,19 @@ This file documents the exact shape of `brand/design-system.md` that `/design-sy
├── brand/
│ ├── design-system.md ← this schema
│ ├── tokens.ts ← importable Tamagui tokens
+│ ├── tokens.dark.ts ← optional approved custom-dark palette
│ ├── design-system.html ← visual gallery (optional)
│ └── .history/ ← version snapshots
```
+`brand/tokens.dark.ts` is optional, not a prerequisite for default dark mode.
+When custom dark is approved, use the named `darkTokens` export and complete
+color contract in
+[Approved dark palette](./tamagui-integration.md#approved-dark-palette-conditional).
+Its presence alone does not authorize wiring it. Refresh and rollback use the
+[snapshot contract](./refresh-flow.md#snapshot-contract) to retain exact spec and
+token contents plus dark artifact presence/absence and approved selection.
+
## Full schema
```markdown
@@ -238,52 +247,19 @@ Missing sections → skill surfaces error, asks user to re-run.
## How Tamagui Integration Uses tokens.ts
-`brand/tokens.ts` is a plain TypeScript export. `/create-mobile-app` Step 9b
-imports it into `tamagui.config.ts` using
-[`tamagui-integration.md`](./tamagui-integration.md) and the native host's
-`withPowerAppsSemanticAliases` helper:
-
-```ts
-import { createTokens } from '@tamagui/core';
-import { defaultConfig } from '@tamagui/config/v5';
-import {
- createPowerAppsTamaguiConfig,
- withPowerAppsSemanticAliases,
-} from '@microsoft/power-apps-native-host/config/tamaguiConfig';
-import { tokens as brandTokens } from './brand/tokens';
-
-const tokens = createTokens({
- ...defaultConfig.tokens,
- space: { ...defaultConfig.tokens.space, ...brandTokens.space },
- size: { ...defaultConfig.tokens.size, ...brandTokens.size },
- radius: { ...defaultConfig.tokens.radius, ...brandTokens.radius },
-});
-
-export const appLightTheme = withPowerAppsSemanticAliases(
- defaultConfig.themes.light,
- brandTokens.color,
-);
-
-export const appDarkTheme = withPowerAppsSemanticAliases(
- defaultConfig.themes.dark,
- {
- primary: brandTokens.color.primary,
- accent: brandTokens.color.accent,
- statusSuccess: brandTokens.color.statusSuccess,
- statusWarning: brandTokens.color.statusWarning,
- statusDanger: brandTokens.color.statusDanger,
- statusInfo: brandTokens.color.statusInfo,
- },
-);
-
-const customConfig = {
- tokens,
- themes: {
- ...defaultConfig.themes,
- light: appLightTheme,
- dark: appDarkTheme,
- },
-};
-
-export const tamaguiConfig = createPowerAppsTamaguiConfig(customConfig);
-```
+`brand/tokens.ts` is a plain TypeScript export. `/create-mobile-app` Step 9b and
+`/edit-app` Step 5 must follow the authoritative
+[`tamagui-integration.md`](./tamagui-integration.md) implementation rather than
+maintaining a second config example here:
+
+- **Default dark:** use [Brand Import](./tamagui-integration.md#brand-import).
+ Keep Config v5 dark surfaces/text with brand accents/statuses; no dark artifact
+ or import is required.
+- **Approved custom dark:** also apply
+ [Approved dark palette](./tamagui-integration.md#approved-dark-palette-conditional).
+ `appDarkTheme` consumes `darkTokens.color`, including approved surfaces/text,
+ instead of the base accent-only override.
+- **Both branches:** apply
+ [Root Provider Wiring](./tamagui-integration.md#root-provider-wiring), mapping
+ the resolved `appDarkTheme` into `brandedDarkTheme`. After rollback, choose the
+ branch from the restored approved state, not a newer plan or file presence.
diff --git a/plugins/mobile-apps/skills/design-system/references/input-modes.md b/plugins/mobile-apps/skills/design-system/references/input-modes.md
index 77a1598b7..badc0faf7 100644
--- a/plugins/mobile-apps/skills/design-system/references/input-modes.md
+++ b/plugins/mobile-apps/skills/design-system/references/input-modes.md
@@ -87,7 +87,9 @@ Input: pre-structured design spec (Claude Design, Tokens Studio, Style Dictionar
Processing:
1. Validate: ≤200 KB, .md/.mdx/.json
2. Auto-detect format by markers
- 3. Near-direct passthrough → SKIP Sub-steps 3 AND 4
+ 3. Prepare spec + matching token candidate without copying into brand/
+ 4. Skip style/spec generation, not Sub-step 3.5's approval + backup boundary
+ 5. Apply the approved replacement (or first-time draft), then Sub-steps 5–7 (confirmation before initial history)
Cost: ~0-2k tokens (mostly deterministic)
```
@@ -296,7 +298,7 @@ Token values masked. Failures logged with reason.
When multiple flags are passed, apply in priority order:
```
-1. --design-spec (highest — near-direct passthrough, skips Sub-steps 3+4)
+1. --design-spec (highest — near-direct passthrough, never skips Sub-step 3.5's write boundary)
2. --brand-doc (locks direction, skips Sub-step 3)
3. --from-figma (locks palette + typography + components)
4. --from-code-app (highest fidelity sibling)
diff --git a/plugins/mobile-apps/skills/design-system/references/refresh-flow.md b/plugins/mobile-apps/skills/design-system/references/refresh-flow.md
index 5bdf47830..a13b668a4 100644
--- a/plugins/mobile-apps/skills/design-system/references/refresh-flow.md
+++ b/plugins/mobile-apps/skills/design-system/references/refresh-flow.md
@@ -1,17 +1,73 @@
# Refresh Flow — `/design-system --refresh <dimension>`
-Single-dimension edit to an existing design system. Changes one section of `brand/design-system.md`, regenerates `brand/tokens.ts`, optionally re-renders the HTML gallery.
+Single-dimension edit to an existing design system. Changes the approved section of `brand/design-system.md` and its token artifact (`brand/tokens.ts` or the optional `brand/tokens.dark.ts`), optionally re-renders the HTML gallery.
+
+Apply [app-edit-routing.md](../../../shared/references/app-edit-routing.md) first.
+An approved create/edit child call reuses the supplied change and approval rather
+than rerunning intent selection. Return any scope-changing drift resolution to
+the owner. A token refresh still requires the owner's runtime wiring and
+affected-screen verification; a gallery is not proof of app integration.
+
+All `brand/` paths below belong to the already resolved `working_dir`. Use
+absolute file-tool paths and the shared app-root guard for any shell call.
+
+## Snapshot contract
+
+Use one history contract for refresh, reskin, `--add-dark-mode`, changing or
+removing a custom dark palette, and rollback. After approval and **before the
+first write or deletion**, including drift resolution, capture the current state
+under one collision-free `<timestamp>-<command>` ID in `brand/.history/`:
+
+| Snapshot member | Contents |
+|---|---|
+| `<id>.md` | Exact current `brand/design-system.md`. |
+| `<id>.tokens.ts` | Exact current `brand/tokens.ts`, when present. |
+| `<id>.tokens.dark.ts` | Exact current `brand/tokens.dark.ts`, only when present. Never derive this copy from the light palette. |
+| `<id>.state.json` | Explicit dark artifact presence (`"darkTokens": "present"` or `"absent"`) and the current approved selection (`"darkPalette": "approved"` or `"default"`). |
+
+For example, a design using an approved custom dark palette records:
+
+```json
+{ "darkTokens": "present", "darkPalette": "approved" }
+```
+
+A default-dark design with no dark artifact records:
+
+```json
+{ "darkTokens": "absent", "darkPalette": "default" }
+```
+
+Presence is not approval: preserve an existing unapproved dark file in the
+snapshot with `"darkTokens": "present", "darkPalette": "default"` and do not wire
+it. Derive the approved selection from the current Design/approval record, not
+the filename. If that selection is unknown or an approved dark palette lacks its
+artifact, STOP and resolve the mismatch with the owner before mutating anything.
+
+Verify every expected snapshot member before proceeding; a failed or incomplete
+backup blocks the change. Keep the pre-write snapshot unchanged afterward. For
+first-time generation with no prior design, record the complete approved initial
+state using this same format after generation and explicit confirmation of that
+candidate (or the owner's matching exact approval), never before confirmation
+or for an unconfirmed draft. Do not replace a pre-edit backup with that initial
+snapshot on a rerun.
+
+Legacy snapshots without `.state.json` have **unknown**, not absent, dark state.
+Resolve and explicitly approve that target state before rollback; do not infer
+permission to delete a dark file from a missing history member. A target requiring
+a custom dark palette without its saved payload blocks rollback rather than
+re-deriving colors. A missing legacy light-token copy may be regenerated from the
+saved spec with approval, but never from the current spec.
## Allowed dimensions
| Dimension | What changes | Tokens affected | Affects screens? |
|-----------|-------------|-----------------|------------------|
-| `palette` | ## Palette + ## Status palette | color.* | no (tokens swap automatically) |
+| `palette` | Approved light or custom-dark palette; name the target in the delta | color.* in the selected artifact | inspect dark wiring and affected screens |
| `typography` | ## Typography | typography.* | no (tokens swap) |
| `components` | ## Components | size.*, radius.* | yes (primitives regenerate) |
-| `density` | ## Spacing + ## Components heights | space.*, size.* | no |
-| `negatives` | ## Negatives | none (advisory) | no |
-| `motion` | ## Motion | motion.* | no |
+| `density` | ## Spacing + ## Components heights | space.*, size.* | inspect affected layouts |
+| `negatives` | ## Negatives | none (screen constraints) | inspect screens for newly forbidden patterns |
+| `motion` | ## Motion | motion.* | inspect consumers |
## Flow
@@ -23,6 +79,10 @@ If missing → STOP: "No design system found. Run /design-system first."
Read brand/tokens.ts
If missing → WARN: "tokens.ts missing — will regenerate from spec."
+
+Read brand/tokens.dark.ts if present, and the current approved dark selection.
+If absent and default dark is selected → keep it absent; no dark file is required.
+If an approved custom dark palette is missing → STOP and return the mismatch to the owner.
```
### Step 2 — Drift detection
@@ -68,6 +128,12 @@ How do you want to resolve?
**Why drift detection matters:** without it, `--refresh palette` overwrites hand-edits silently. Drift detection turns this into a conscious choice.
+Also compare an existing `brand/tokens.dark.ts` with the approved dark palette
+record before overwriting or removing it. Missing approval or hand-edited dark
+values require the same explicit resolution; file presence alone is not approval.
+Every resolution uses the pre-write snapshot contract above, including an
+otherwise light-only refresh.
+
### Step 3 — Cost preview (mandatory)
```
@@ -75,13 +141,13 @@ How do you want to resolve?
This will:
- Re-run palette extraction with new input
- - Update brand/tokens.ts (1 file)
+ - Update the approved light or dark token artifact (name it in the delta)
- Re-render brand/design-system.html (~25k tokens, optional)
- Snapshot current to brand/.history/
Estimated cost: ~3k tokens (refresh-only) OR ~28k (with HTML preview)
Estimated time: ~30 sec OR ~2 min
-Affects screens: NO — primitives auto-pick up tokens
+Affects screens: inspect dark runtime wiring and affected screens
Render HTML preview after? [y/N]
Continue? [y/N]
@@ -91,12 +157,12 @@ Continue? [y/N]
| Command | Tokens | Wall time | Affects screens? |
|---------|--------|-----------|------------------|
-| `--refresh palette` | ~3k | ~30 sec | no |
+| `--refresh palette` | ~3k | ~30 sec | inspect dark wiring and affected screens |
| `--refresh typography` | ~3k | ~30 sec | no |
| `--refresh components` | ~5k | ~45 sec | yes (primitives regenerate) |
-| `--refresh density` | ~3k | ~30 sec | no |
-| `--refresh negatives` | ~2k | ~20 sec | no |
-| `--refresh motion` | ~3k | ~30 sec | no |
+| `--refresh density` | ~3k | ~30 sec | inspect layouts |
+| `--refresh negatives` | ~2k | ~20 sec | inspect screen constraints |
+| `--refresh motion` | ~3k | ~30 sec | inspect consumers |
| HTML preview render | +25k | +90 sec | no |
### Step 4 — Prompt for specific change
@@ -116,6 +182,11 @@ What do you want to change?
(Enter specific changes, e.g. "accent to forest green, more saturated")
```
+Name whether the approved palette change targets light values, custom-dark
+values, or removal of the custom-dark override. If dark state is outside the
+approved scope, preserve its file presence and contents exactly; do not
+auto-derive, replace, or remove it when refreshing the light palette.
+
**Typography:**
```
Current typography:
@@ -149,25 +220,39 @@ Which first? [palette / typography]
### Step 5 — Update the spec
+Before either spec or token write, show the concrete proposed delta and obtain
+approval unless it exactly matches the current owner's approved scope. Include
+any dark-file creation, replacement, or removal and the resulting default/custom
+selection in that delta. Capture the current spec/tokens as a paired history
+snapshot plus the optional dark artifact and explicit state, following the
+[snapshot contract](#snapshot-contract), so rollback restores the pre-edit state.
+Cancellation leaves both artifacts unchanged and preserves the dark artifact's
+presence, contents, and approved selection.
+
1. Read full `brand/design-system.md`
2. Find the relevant section (e.g. `## Palette`)
3. Replace ONLY that section with updated content
4. Leave all other sections untouched
5. Update `## Provenance` timestamp and note
-### Step 6 — Regenerate tokens.ts
+### Step 6 — Update the approved token artifacts
-1. Re-derive `brand/tokens.ts` from the updated `brand/design-system.md`
-2. Write new tokens.ts
+1. For a light-spec change, re-derive `brand/tokens.ts` from the updated
+ `brand/design-system.md`; a dark-only change does not rewrite light tokens.
+2. Only if approved, create or replace `brand/tokens.dark.ts` with the named
+ `darkTokens` export and complete color shape in
+ [Approved dark palette](./tamagui-integration.md#approved-dark-palette-conditional).
+ Removing a custom palette deletes only `brand/tokens.dark.ts` after the
+ explicit removal approval and verified safety snapshot; never delete other
+ brand artifacts or unrelated files.
+3. If dark state is not in scope, leave `brand/tokens.dark.ts` unchanged when
+ present and absent when absent. Default dark mode still works without it.
### Step 7 — Snapshot to history
-```bash
-mkdir -p brand/.history
-ts=$(date -u +%Y-%m-%dT%H-%M-%SZ)
-cp brand/design-system.md "brand/.history/${ts}-refresh-${dimension}.md"
-cp brand/tokens.ts "brand/.history/${ts}-refresh-${dimension}.tokens.ts"
-```
+Retain the paired pre-write snapshot from Step 5, including the dark artifact
+presence/absence and approved selection. Do not replace it with copies of the new
+artifacts: that would make rollback restore the edited state.
### Step 8 — Re-render HTML (if requested)
@@ -177,6 +262,11 @@ If user said yes to HTML preview:
### Step 9 — Confirmation gate
+Review the applied diff; this is not the first approval. Revisions return to the
+pre-write gate. Return changed files, the resulting approved dark selection, and
+screen-impact notes to the owning orchestrator before it performs runtime
+verification using [Tamagui integration](./tamagui-integration.md).
+
```
Updated: ## {{dimension}}
@@ -198,18 +288,22 @@ Confirm? [y/N/edit again]
### `/design-system --history`
-List all snapshots:
+List all logical snapshots, including their saved default/custom dark selection
+and dark artifact presence/absence:
```
Brand design system history:
- 1. 2026-05-01T14:23:00Z initial Inspection direction, Inter typography
- 2. 2026-05-08T09:15:00Z refresh-palette Changed accent from orange to slate-blue
- 3. 2026-05-12T16:44:00Z add-dark-mode Auto-derived dark palette
+ 1. 2026-05-01T14:23:00Z initial Initial design; default dark, artifact absent
+ 2. 2026-05-08T09:15:00Z refresh-palette Before accent change; default dark, artifact absent
+ 3. 2026-05-12T16:44:00Z add-dark-mode Before adding custom dark; default dark, artifact absent
```
### `/design-system --diff <timestamp>`
-Show diff between current spec and the named snapshot:
+Show diff between the current spec/token artifacts and the named snapshot,
+including `brand/tokens.dark.ts` contents or its creation/removal, and the
+saved versus current approved dark selection. `--history` and `--diff` are
+read-only; do not materialize missing artifacts.
```
diff brand/design-system.md vs brand/.history/2026-05-01T14-23-00Z-initial.md
@@ -223,18 +317,42 @@ diff brand/design-system.md vs brand/.history/2026-05-01T14-23-00Z-initial.md
### `/design-system --rollback <timestamp>`
-1. Snapshot current state to `.history/` first (safety net)
-2. Copy the target snapshot to `brand/design-system.md`
-3. Regenerate `brand/tokens.ts` from restored spec
-4. Confirmation gate before write
+1. Resolve and validate every target snapshot member and its explicit dark state
+ using the [snapshot contract](#snapshot-contract). Preview the exact spec,
+ token, dark-file, and default/custom selection delta without writing.
+2. Obtain confirmation before any write (or reuse the owner's exact approval).
+3. Snapshot current state to `.history/`, including dark presence/absence and
+ approval, and verify the safety backup before any restore or deletion.
+4. Restore the approved spec and saved light tokens exactly (only a missing light
+ copy uses the saved-spec fallback above). Restore dark state as follows:
+
+ | Current dark artifact | Target dark artifact | Approved restore action |
+ |---|---|---|
+ | present | present | Replace `brand/tokens.dark.ts` with the exact saved target contents, even when current and target both use custom dark palettes. Do not regenerate from light tokens or keep the newer dark values. |
+ | absent | present | Restore `brand/tokens.dark.ts` from the exact saved target contents. |
+ | present | absent | Remove only the current `brand/tokens.dark.ts` after explicit approval of that removal and a verified safety backup. Do not delete any unrelated files. |
+ | absent | absent | Leave `brand/tokens.dark.ts` absent; do not generate or import it. |
+
+5. Return the restored approved selection to the owner. Reconcile the Design plan
+ to that target, not the abandoned newer palette, then reapply
+ [Tamagui integration](./tamagui-integration.md#restored-dark-state) and verify
+ affected screens. For approved custom dark, `appDarkTheme` must consume the
+ restored `darkTokens.color`; for default dark, remove stale custom-dark
+ imports/overrides and use the base dark branch. In either case the provider's
+ `brandedDarkTheme` must map the same resolved `appDarkTheme`. Artifact-only
+ rollback reports this outstanding runtime work rather than claiming the app
+ has been restored.
```
Rolling back to 2026-05-01T14:23:00Z (initial):
- Current state will be saved to .history/ as safety backup
- brand/design-system.md will be restored
- - brand/tokens.ts will be regenerated
+ - brand/tokens.ts will be restored (or regenerated from the saved spec if missing)
+ - brand/tokens.dark.ts will match the target's recorded presence and exact contents
+ - The target's approved default/custom dark selection will drive runtime reconciliation
-This will undo all changes since that snapshot. Continue? [y/N]
+This restores the listed brand state, not unrelated app changes. Continue? [y/N]
```
-History capped at 50 entries — oldest auto-pruned with notice.
+History capped at 50 logical snapshots — prune only the oldest snapshot's known
+members together, with notice; never prune unrelated files.
diff --git a/plugins/mobile-apps/skills/design-system/references/tamagui-integration.md b/plugins/mobile-apps/skills/design-system/references/tamagui-integration.md
index 3083cd11d..c1d35f276 100644
--- a/plugins/mobile-apps/skills/design-system/references/tamagui-integration.md
+++ b/plugins/mobile-apps/skills/design-system/references/tamagui-integration.md
@@ -1,7 +1,8 @@
# Tamagui Integration
-Internal reference used by `/create-mobile-app` Step 9b after `/design-system`
-writes `brand/tokens.ts`. This is not a user-invocable skill.
+Internal reference used by `/create-mobile-app` Step 9b and `/edit-app` Step 5
+after `/design-system` writes approved brand artifacts. This is not a
+user-invocable skill.
The native host owns the baseline Tamagui contract. Generated applications
must extend that contract rather than copying its semantic aliases, color
@@ -22,6 +23,7 @@ parsing, contrast selection, animations, or font fallback into each app.
| Condition | Action |
|---|---|
+| Approved design includes a custom dark palette | Apply brand-import mode plus the conditional dark-palette branch below; require its approved artifact and export shape. |
| `brand/tokens.ts` exists | Apply the brand-import implementation below. |
| `## Design` requires custom tokens but `brand/tokens.ts` is missing | Materialize the approved tokens first, then use brand-import mode. |
| No custom design tokens exist | Verify the template calls `createPowerAppsTamaguiConfig({})`; make no config edit. |
@@ -112,9 +114,10 @@ declare module 'tamagui' {
}
```
-The generated schema has one palette. Light mode receives its approved
-surfaces, text, accents, and statuses. Dark mode keeps Config v5 dark surfaces
-and text while carrying the approved accent and status colors.
+Without an approved custom dark palette, light mode receives the brand palette's
+surfaces, text, accents, and statuses. This default dark branch keeps Config v5
+dark surfaces and text while carrying the approved accent and status colors.
+When custom dark is approved, apply the conditional branch below instead.
Never copy `parseColorChannels`, `readableForeground`, or
`withSemanticAliases` into the app. The host helper owns those rules.
@@ -122,6 +125,81 @@ Never copy `parseColorChannels`, `readableForeground`, or
Never remap brand space keys (`xs`, `sm`, `md`, `lg`, `xl`, `2xl`, `3xl`,
`4xl`) onto Tamagui numeric keys. Preserve the default numeric scale.
+## Approved dark palette (conditional)
+
+This branch is required for both `/create-mobile-app` Step 9b and `/edit-app`
+Step 5 when the approved design includes a custom dark palette. Without one,
+keep the Brand Import example above unchanged and do not import a nonexistent
+dark file. An unapproved file's presence alone does not authorize wiring it.
+
+`/design-system` writes `brand/tokens.dark.ts` with this exact named export.
+The color keys match `BrandTokens['color']`, but their values are the approved
+dark palette, not the light palette's literal types:
+
+```ts
+import type { BrandTokens } from './tokens';
+
+export const darkTokens = {
+ color: {
+ bg: '{{approved-dark-bg}}',
+ surface: '{{approved-dark-surface}}',
+ primary: '{{approved-dark-primary}}',
+ accent: '{{approved-dark-accent}}',
+ text: '{{approved-dark-text}}',
+ textMuted: '{{approved-dark-text-muted}}',
+ border: '{{approved-dark-border}}',
+ statusSuccess: '{{approved-dark-success}}',
+ statusWarning: '{{approved-dark-warning}}',
+ statusDanger: '{{approved-dark-danger}}',
+ statusInfo: '{{approved-dark-info}}',
+ },
+} as const satisfies { color: { [K in keyof BrandTokens['color']]: string } };
+```
+
+After verifying that artifact, add this import in `tamagui.config.ts` and
+**replace**, do not duplicate, the Brand Import example's `appDarkTheme` declaration:
+
+```ts
+import { darkTokens } from './brand/tokens.dark';
+
+export const appDarkTheme = withPowerAppsSemanticAliases(
+ defaultConfig.themes.dark,
+ darkTokens.color,
+);
+```
+
+The full dark palette supplies surfaces/text as well as accents/statuses.
+Keep `appLightTheme` sourced from `brandTokens.color`, and keep
+`customConfig.themes.dark: appDarkTheme`. The Root Provider Wiring below must
+map that same resolved `appDarkTheme` into `brandedDarkTheme` and pass it through
+`PowerAppsProvider darkTheme={brandedDarkTheme}`; do not map light tokens there or
+introduce a parallel theme registry/provider. Include any requested switch UI in
+the owner's approved screen scope.
+
+Missing files, missing exports/keys, or unresolved placeholder values block
+custom-dark integration. Do not silently fall back to default dark surfaces
+and report the approved palette as applied. Return the mismatch to the owner.
+
+## Restored dark state
+
+For refresh or rollback, first follow
+[the snapshot contract](./refresh-flow.md#snapshot-contract) and reconcile the
+Design plan with the resulting approved state. Do not choose a branch from the
+mere presence of `brand/tokens.dark.ts` or the abandoned newer plan.
+
+- **Approved custom dark restored:** verify the exact restored `darkTokens`
+ artifact, then apply the conditional branch above so `appDarkTheme` consumes
+ the restored `darkTokens.color`, not the previous palette.
+- **Default dark restored or custom dark removed:** remove only stale
+ `tokens.dark` imports and custom-dark overrides from the theme configuration.
+ Use the unchanged Brand Import default dark declaration, retaining Config v5
+ dark surfaces/text and approved light-brand accents/statuses. Do not import or
+ create an absent dark file, and do not delete unrelated theme customizations.
+- **Both branches:** rebuild `brandedDarkTheme` from the same resolved
+ `appDarkTheme` using Root Provider Wiring below, preserving unrelated provider
+ props, and perform the validation below. Artifact-only callers must return
+ this runtime dependency to their owner, not claim the app already uses it.
+
## Root Provider Wiring
Tamagui components read the themes above through `useTheme()`. Shared host
@@ -197,9 +275,18 @@ and custom provider props when applying this change.
After Tamagui or provider changes:
```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
npx --no-install tsc --noEmit
```
Also verify that `tamagui.config.ts` contains no local color parser or semantic
alias implementation and that both provider themes map every
surface/text/accent value from `appLightTheme` / `appDarkTheme`.
+For the custom-dark branch, also verify the `darkTokens` import, that
+`appDarkTheme` consumes `darkTokens.color`, and that the resolved dark
+surface/text values reflect the approved palette rather than the light/default
+palette. A generated dark file alone does not satisfy this integration check.
+After restoring default dark, verify there is no stale `tokens.dark` import or
+custom-dark override and the provider reflects the base dark branch. Runtime
+verification belongs to the owning create/edit flow; instruction-contract tests
+alone are not native rendering evidence.
diff --git a/plugins/mobile-apps/skills/edit-app/SKILL.md b/plugins/mobile-apps/skills/edit-app/SKILL.md
index 4d1d81d06..178ad5da0 100644
--- a/plugins/mobile-apps/skills/edit-app/SKILL.md
+++ b/plugins/mobile-apps/skills/edit-app/SKILL.md
@@ -39,13 +39,32 @@ Use `--plan-only` only when the user explicitly asks to update planning docs wit
## When NOT to use
- Brand-new project → `/create-mobile-app`
-- Just adding one connector with no screen changes → `/add-connector` directly
-- Just adding a single native wrapper with no screen changes → `/add-native` directly
-- The plan file is missing → re-run `/create-mobile-app` (don't try to reconstruct)
+- Explicit implementation-only request → the matching leaf skill under
+ [app-edit-routing.md](../../shared/references/app-edit-routing.md); do not infer
+ this from a short request or the absence of screen details.
+- The plan file is missing → stop and ask to restore it or confirm a bounded
+ implementation-only operation; never re-scaffold over the existing app.
## Workflow
-0. Locate app + health/drift probe → 0.5 Application Insights fast path when applicable → 1. Discover intent + inspect existing app → 1.5 Impact preview → 2. Re-plan affected sections → 3. Gate intent, plan + mutation preview → 4. Write plan diff → 5. Apply app mutations → 6. Rebuild affected screens → 7. Verify + quality sweep → 8. Preview + memory-bank update + optional debug handoff
+This skill owns direct feature requests forwarded by native, connector,
+data-model, and design entry points. Reuse the forwarded original request,
+arguments, and answers; do not ask the user to repeat them.
+
+Those entry points ask permission before invoking this full workflow. Reuse
+`entry_choice: full-integration` for the current request without repeating the
+mode question. A direct `/edit-app` invocation also needs no entry-choice menu.
+Neither authorizes mutations: keep the impact/plan gates below. Approved child
+calls skip the entry question and return here; do not create a recursive menu.
+
+For each child skill invocation, explicitly pass the
+[app-edit-routing.md](../../shared/references/app-edit-routing.md) context:
+`MOBILE_APP_ORCHESTRATING=1`, `orchestrator: edit-app`, `working_dir`, `phase`,
+and `approved_scope`. Planning uses read-only proposals; Step 5 implementation
+uses the scope approved in Step 3 and saved in Step 4. The marker is not approval
+and must not be persisted or relied on via a previous shell export.
+
+0. Locate app + health/drift probe → 0.5 Application Insights fast path when applicable → 1. Discover intent + inspect existing app → 1.5 Impact preview → 2. Re-plan affected sections → 3. Gate intent, plan + mutation preview → 4. Write plan diff → 5. Apply additions/refreshes → 6. Rebuild affected screens → 6.5 Unregister approved retired sources → 7. Verify + quality sweep → 8. Preview + memory-bank update + optional debug handoff
---
@@ -96,7 +115,9 @@ test -f memory-bank.md && echo "OK: memory bank found" || echo "WARN: no memory
git status --short
```
-If `native-app-plan.md` is missing → STOP. Tell the user this skill edits an existing generated app; they should re-run `/create-mobile-app` on a fresh template or manually recreate the plan before using this editor.
+If `native-app-plan.md` is missing → STOP. Ask to restore the existing plan or
+explicitly limit the request to implementation-only work. Do not reconstruct the
+full app plan from one feature request or run `/create-mobile-app` over this app.
Read if present:
@@ -107,6 +128,10 @@ Read if present:
Run these existing-app health checks before any mutation:
+This is an inspection-only gate. Include required scaffold/provider/service
+repairs in the proposed mutation scope; do not apply them before Step 3 approval.
+`--plan-only` never authorizes these repairs or any other app/cloud mutation.
+
| Check | Action if unhealthy |
|---|---|
| `memory-bank.md` exists and has expected headings | If missing/corrupt, ask whether to proceed with reduced resume safety; create/update only after approval |
@@ -122,6 +147,11 @@ If the app already fails `npx --no-install tsc --noEmit`, capture the errors onc
### Step 0.5 — Application Insights configuration fast path
+If `--plan-only` is present, do not invoke the configuration skill or change
+Application Insights. For a configuration-only request, report that it has no
+plan section and stop unchanged; for a mixed request, continue with only the
+requested plan proposal.
+
Use this fast path when the request is only to enable Application Insights, change its resource, or disable it. Application Insights is host/runtime configuration, not a connector or plan section, so do not run the planner, data-model, native, design, screen, or preview flows.
If the request also adds or changes custom events in app screens, configure Application Insights here first, then continue through the normal edit workflow for those source changes.
@@ -132,7 +162,11 @@ All Application Insights logic lives in the dedicated `/setup-app-insights` skil
Invoke skill: /setup-app-insights
Environment:
- CODE_APPS_NATIVE_ORCHESTRATING=1
+ MOBILE_APP_ORCHESTRATING=1
+ orchestrator: edit-app
+ working_dir: <working_dir>
+ phase: configuration
+ approved_scope: <requested configuration action; setup-app-insights owns approval>
Arguments:
--working-dir <working_dir>
@@ -184,7 +218,7 @@ Build an edit brief before Step 2:
If the edit brief is incomplete after inspection, ask scenario-specific questions before continuing.
-Ask via `AskUserQuestion`:
+Only if the requested change is still unknown after inspection, ask via `AskUserQuestion`:
> "What should this app edit change?
> (a) Data model — add/extend/reuse Dataverse tables
@@ -196,7 +230,8 @@ Ask via `AskUserQuestion`:
> (g) Preview only
> (h) Cancel"
-Then ask: "Briefly describe the change you want."
+Ask for a brief description only if the original request and supplied answers
+still do not explain it. Ask one unresolved question at a time.
Scenario-specific questions to ask only when the answer is not already obvious:
@@ -209,7 +244,9 @@ Scenario-specific questions to ask only when the answer is not already obvious:
| Dataverse create form | Which Dataverse table? Existing table or new table? Which fields are required/editable? Where should the form launch from? What happens after save (back, detail, add another)? Are there lookup/file/image fields? |
| Barcode/QR scan search | Where should scanning live (new scanner screen, existing search screen action, form field)? What does the scanned value represent (record ID, serial number, asset tag, SKU, custom field)? Which table/service/field should it search? What happens on no match or multiple matches? |
| New requirement + screen | What user workflow is being added? Who uses it? What data/native/connectors does it need? Where does it sit in navigation? What is success/failure behavior? |
-| New data source | What job does the data source support? Is it structured business data (Dataverse), SharePoint list/library, cloud flow/action, or another connector? Which screen(s), if any, should use it now? |
+| New data source | What job does the data source support? Is it structured business data (Dataverse), SharePoint list/library, a connector action, or another connector? Which screen(s), if any, should use it now? |
+| Remove/replace a table or integration | Remove it only from this app, or is server deletion separately intended? Which remaining screens, lookup/identity helpers, native sync, or offline behavior still require it? Preserve server data by default. |
+| Native capability without a workflow | What should the capability do, where should users invoke it, and should the result stay local or be retained in an existing data source? |
| Preview only | Preview all screens or only changed/key screens? Should Visual Companion auto-open behavior be honored? |
Existing-state checks before deciding to add vs edit:
@@ -234,16 +271,28 @@ Use this scenario coverage matrix for common follow-ups. The goal is one user pr
| Add a full calendar, agenda, or scheduling view | Screens → JavaScript Dependencies | Add exact `react-native-calendars` version to the approved table, then `npm install --save-exact` before builders | Build the calendar screen with the approved pattern; no `/add-native` or Android/iOS rebuild |
| Add a new requirement with a new screen | Usually Screens plus whichever of Data Model, Connector, Native, Design the requirement implies | Decompose into one coherent feature; apply data/connector/native/design first, then screens | Generate/refresh service snapshot, layouts, skeletons/shared code, then build affected screens |
| Add a new data source but no screen | Connector/Data Source; sometimes Data Model | `/add-datasource` when ambiguous; `/add-sharepoint`, `/add-connector`, or `/add-dataverse` when clear | Refresh generated services and memory bank; no screen rebuild unless the user asked for UI |
+| Add Teams/email action or profile lookup | Connectors; Screens when consumed | `/add-connector` after approval | Wire the action/read and its loading/error/success behavior; no Dataverse schema by default |
+| Add SQL/Excel/SharePoint data | Connectors, including external table/list schema; Screens when consumed | Matching connector leaf after approval | Do not add a Dataverse model just because the connector supplies tabular data |
| Add a new table/entity but no screen | Data Model | `mobile-app:data-model-architect` -> `/add-dataverse --skip-planning` | Refresh generated services; optionally seed sample data; no preview unless UI changed |
+| Stop using a table/connector/flow or replace its data source | Data Model/Connectors and affected Screens | Approved retirement via the matching leaf after consumer updates in Step 6 | CLI removes the app registration and regenerates services/config; Step 6.5 verifies remaining sources and refreshes the schema map |
| Remove, rename, reorder, or change a screen archetype | Screens | `mobile-app:screen-planner` edit pass | Update route files/layouts/navigation contracts; delete only approved files; run route check |
| Generate a new static preview | None unless source is stale | `/preview-screens` | No source edits; do not run data/native/design work |
One user-visible feature may require multiple plan sections. That is allowed and expected. Multiple unrelated features in one prompt should be split: list the features, ask which to run first, and do not bundle their mutations.
+**Data Model is conditional.** A connector/action/native capability does not
+automatically require Dataverse. Reuse existing storage and schema. Plan Dataverse
+changes only for new/changed Dataverse tables, columns, or relationships actually
+required by the feature; missing generated services alone require regeneration,
+not new schema. Keep connector operations and external table/list schemas in
+`## Connectors`. Preserve unaffected Data Model content verbatim.
+
Loophole checks before continuing:
- If the request adds UI that reads or writes data, confirm the generated service exists or add the data source before screen work. Never let screen-builders invent services.
-- If the request is ambiguous about Dataverse vs SharePoint vs another connector, route through `/add-datasource` rather than guessing.
+- If the request is ambiguous about Dataverse vs SharePoint vs another connector,
+ consult the `/add-datasource` routing table read-only and resolve the choice
+ before approval. Execute the selected leaf only in Step 5.
- If a screen requires a native wrapper, run `/add-native` before screen-builders import `src/native/*`.
- If a native capability is not shipped by the template, stop with a clear block; do not install native packages or fake support.
- If a screen requires a pure-JavaScript library, add it with an exact version to `## Screens → ### JavaScript Dependencies`, include it in the mutation preview, and install it before screen builders run. Determine JS-only status from shipped contents, not from a package-name prefix.
@@ -255,7 +304,7 @@ For PDF/signature requests, map the change to every affected section instead of
| User request | Required plan updates |
|---|---|
-| Add signature capture, sign-off, pen, ink, drawing | Native Capabilities: `pen-input`; Data Model: Image/File column or child Evidence/Signature table; Screens: capture action, preview state, cancelled state, upload failed state |
+| Add signature capture, sign-off, pen, ink, drawing | Native Capabilities: `pen-input`; Screens: capture, preview, cancellation, and applicable failure states; ask about retention, then update Data Model only if new/changed Dataverse storage is required |
| Store signed approval as Dataverse image | Data Model: Image column; Screens: normalize `data:image/png;base64,...` before update; Native Capabilities: `pen-input` if capture is in-app |
| Generate/export/print evidence PDF | Native Capabilities: `pdf-report` only when `expo-print` is present, plus `sharing` only when local share is needed and `expo-sharing` is present; Data Model: File column only if retained; Screens: generation pending/failed/success states |
| Persist generated PDFs | Data Model: Dataverse File column or child Attachment table; Screens: create/update row first, then upload File bytes; Native Capabilities: `pdf-report` |
@@ -301,7 +350,8 @@ If the user chooses **edit**, return to Step 1 and refine the edit brief. If can
**If the user picks (d) Design:**
-Read and execute the `/design-system` skill instead of spawning a planner agent. Determine the dimension from the user's description:
+Read the `/design-system` references to propose the Design delta without executing
+the skill yet. Determine the dimension from the user's description:
| User says | Route to |
|---|---|
@@ -315,15 +365,10 @@ Read and execute the `/design-system` skill instead of spawning a planner agent.
**One-major-change-per-prompt enforced.** If the user asks to change palette AND typography → refuse, ask which first. This matches `/design-system`'s own behavior.
-After `/design-system --refresh` returns, print:
-
-```
-✅ Design system updated. brand/design-system.md + brand/tokens.ts refreshed.
-
-Continuing with verification and preview. Rebuilding screens only if component shapes, density, navigation, or screen-specific design rules changed.
-```
-
-Do not stop after design refresh. Continue to Step 7 verification and Step 8 preview. If the refresh changed component shapes, density, negatives, or a full reskin requires TSX adjustments, include Screens in the affected sections and rebuild those screens.
+Include runtime token/provider wiring and any affected screens in the proposal.
+Continue through Steps 2-4 before executing `/design-system` in Step 5.
+Do not write brand artifacts before approval or during `--plan-only`, and do not
+jump from design refresh straight to verification if screen changes are needed.
### Step 2 — Re-plan affected sections
@@ -346,20 +391,32 @@ Reuse the same planning primitives as `/create-mobile-app`, but only for the aff
Read each affected section verbatim from `native-app-plan.md` and pass it as input to the relevant read-only agent. Use the plugin namespace for every `Task` invocation.
+For Dataverse schema/new-binding work, first read and execute
+[dataverse-change-planning.md](../../shared/references/dataverse-change-planning.md).
+Use the requested delta and necessary dependencies, not all historical plan
+rows. The foreground obtains and validates compact evidence; the architect
+uses `Dataverse planning mode: required`, not legacy live discovery.
+Native/design/connector-only edits, app-binding removals, and retained-service
+refreshes skip this planning path and never reuse its old artifacts.
+
Before the first `Task`, run a silent preflight for the leaf agent you need (`mobile-app:data-model-architect`, `mobile-app:screen-planner`, or `mobile-app:screen-builder` preflight later). If the host cannot spawn agents, print once:
> "→ Planner agents unavailable in this host — running inline planning. (No action needed; this is automatic.)"
Inline fallback rules:
-- Data Model: draft the section inline from the existing plan, `.datamodel-manifest.json`, generated models, and the user's edit brief; then gate it exactly like an agent result.
+- Data Model: use the existing plan, manifest, models, and edit brief as context,
+ but ground decisions in the shared workflow's validated compact evidence.
+ Produce `_dm_section.md` and the normalized schema contract and run the same
+ decision validator as for an agent result; local files alone are not proof
+ of current server schema.
- Screens: draft Screen Map / Navigation Contracts / per-screen spec changes inline using `agents/screen-planner.md`, `shared/references/screen-templates.md`, and the existing screen TSX; then gate it exactly like an agent result.
- Native Capabilities and Connectors: already handled inline by this skill.
- Never skip approval just because a leaf agent is unavailable.
| Section | Agent (read-only) | Output file |
|---|---|---|
-| Data Model | `mobile-app:data-model-architect` | `_dm_section.md` |
+| Data Model | `mobile-app:data-model-architect` | `_dm_section.md` + `.tmp/dataverse-schema-contract.json` |
| Native Capabilities | (handled inline — no separate agent) | `_native_section.md` |
| Screens | `mobile-app:screen-planner` | `_screens_section.md` |
@@ -373,13 +430,32 @@ Prompt:
Current section content: <verbatim>
Working directory: <absolute path>
Plugin root: ${PLUGIN_ROOT}
+ Phase: planning
+ Proposal only: <true for --plan-only or a planning-phase caller>
Mode: edit (preserve existing decisions where the change doesn't affect them).
Existing generated app must be updated after approval, so include enough detail for builders to mutate code without guessing.
Return the updated section as a markdown file.
```
-Parse the first line of every agent result using the return-status protocol in `AGENTS.md`. `DONE` continues, `DONE_WITH_CONCERNS:` must be surfaced and recorded, `NEEDS_CONTEXT:` gets one clarified retry, `BLOCKED:` stops before any file mutation, and unknown first lines are treated as `BLOCKED: malformed agent return`.
+For the Data Model handoff, also include these fields verbatim:
+
+```text
+Dataverse planning mode: required
+Normalized Dataverse foreground planning snapshot (validator input only): <SNAPSHOT_PATH>
+Compact Dataverse architect evidence: <ARCHITECT_EVIDENCE_PATH>
+Structured schema contract output: <working_dir>/.tmp/dataverse-schema-contract.json
+Scope: <requested delta and necessary dependencies; preserve unrelated rows>
+Native capabilities and connector ownership: <retained approved constraints>
+```
+
+Handle structured Dataverse context/revision signals with the shared planning
+recovery before generic retry limits. For other signals, use `AGENTS.md`:
+`DONE` continues to output validation, `DONE_WITH_CONCERNS:` must be surfaced
+and recorded, `NEEDS_CONTEXT:` gets one clarified retry, `BLOCKED:` stops before
+app mutation, and unknown first lines are `BLOCKED: malformed agent return`.
+Every Data Model result, including inline output, must pass the shared decision
+validator; `DONE` alone never authorizes Step 3.
For Native Capabilities (no separate agent), do it inline: read the current capability table, apply the change, regenerate the table. For PDF/pen rows, include storage/output notes in the table or immediately below it:
@@ -387,18 +463,44 @@ For Native Capabilities (no separate agent), do it inline: read the current capa
- `pdf-report` generates a local PDF only when `expo-print` is present; local output may be opened by `native-pdf-viewer` 0.2.9+, shared with `expo-sharing` when present, or uploaded to Dataverse File storage.
- `pen-input` returns a PNG data URI; cancellation is a non-error state; Dataverse target must be Image, File, or child Evidence/Signature row.
-For connector/data-source edits, read and execute `/add-datasource` when the source type is unclear; use `/add-sharepoint`, `/add-connector`, or `/add-dataverse` directly only when the source type is clear. Pass the data handoff context from Step 5 with `phase: planning`, the proposed scope, and `--plan-only --working-dir '<working_dir>'`; return a proposal, not mutations. If the connector drives new screens or forms, update the Screens section too before applying code.
+For connector/data-source edits, read
+[connector-planning.md](../../shared/references/connector-planning.md) and the
+`/add-datasource` routing table as reference only. Propose the `## Connectors`
+delta with operations, external tables/list schemas, and consuming screens.
+Do not execute connector skills, create connections, or generate services in
+Step 2. Update Screens when the connector drives new screens/forms; defer the
+selected leaf to Step 5 after approval.
+
+For removals/replacements, follow
+[data-source-removal.md](../../shared/references/data-source-removal.md).
+Before changing the plan, capture the current registration inventory and propose
+retain/add/refresh/removal sets. Do not interpret an omitted table as permission
+to delete it. Include non-screen consumers and offline dependencies, preserve
+server tables/records, and carry the approved removal set through Step 6.5.
### Step 3 — Gate intent, plan + app mutation preview
**Telemetry checkpoint: `approve_app_mutation_plan`**
+For Dataverse planning, require exit `0` from
+`validate-dataverse-planning-decisions.js` for the current normalized contract
+and snapshot before showing this gate. Revisions repeat that check. There is
+no extra create-flow approval gate; preserve this edit's existing UX.
+
+If this is a planning-phase handoff from another owner, return the validated
+proposal and concerns to that owner now, without saving the live plan or
+opening an implementation gate. Do not turn the caller's planning consent
+into approval to apply the edit. A direct `--plan-only` request retains the
+explicit plan-document approval below.
+
Show the user a side-by-side diff (or before/after) for every changed plan section. Also show an app mutation preview:
- Edit brief: intent, target screens/routes, data/native/JavaScript/design dependencies, and assumptions
- Data/schema operations to run (`/add-dataverse --skip-planning`, connector add, native wrapper add)
-- Proposed seed table allowlist, count/media policy, and any lookup dependencies
- requiring new records; no seed writes are authorized when this set is empty
+- Exact app data-source removals, consumer updates, and server data that will be preserved
+- Exact sample-data table allowlist and count/media policy, if requested; exclude
+ retiring tables and include required seed parents only with explicit approval.
+ An empty approved set authorizes no seed writes.
- Screen files to create, rewrite, rename, or delete
- Navigation/layout files to update
- Verification commands to run
@@ -430,31 +532,117 @@ diff --git native-app-plan.md native-app-plan.md
If this is `--plan-only`, update `memory-bank.md` with `plan_only: true`, print the exact follow-up commands, and stop. Otherwise continue immediately.
+The saved plan describes approved intent, not successful application. When the
+Data Model changed, merge its newly accepted `_dm_section.md` proposal here;
+never replay stale scratch output for an unrelated edit. Preserve unrelated
+sections and do not reuse execution artifacts/approval receipts bound to an older plan. The leaf
+updates `.datamodel-manifest.json` only from verified schema/service outcomes;
+pending retirements stay transitional until Step 6.5. Record any failure and
+remaining operations in memory-bank rather than claiming this plan is applied.
+For approved Dataverse implementation, freeze the shared workflow's
+`contract_sha256` and final saved `plan_sha256` in `approved_scope`, and retain
+the absolute `planning_snapshot`, `architect_evidence`, and `schema_contract`
+paths. A plan-only save does not create this implementation approval context.
+
### Step 5 — Apply app mutations
**Telemetry checkpoint: `apply_app_mutations`**
Apply sections in dependency order so screens always build against the current data/native surface:
-For every data child (including connector routers), pass invocation-scoped
-`MOBILE_APP_ORCHESTRATING=1`, `orchestrator: edit-app`, absolute
-`working_dir: <working_dir>`, `phase: implementation`, and only the current
-Step 3-approved delta as `approved_scope`. Also pass the argument
-`--working-dir '<working_dir>'`. Forward this through nested data helpers.
-This legacy editor does not supply compact artifacts; keep the supported
-approved Markdown/live-reconciliation path rather than fabricating them.
-The marker is not consent and cannot turn a planning-phase call into a write.
+Run only operations in the approved delta, not every section of the existing
+plan. Pass `MOBILE_APP_ORCHESTRATING=1` and the explicit implementation context
+above on each handoff, including through routers and on retries. Reuse supplied
+answers, and return to the approval gate if an unresolved choice changes scope.
0. **Environment drift gate for data edits** — before Dataverse, SharePoint, connector, or sample-data work, compare `memory-bank.md`, `power.config.json`, and `.resolved-environment.json`. If they disagree, show the values and ask the user which environment is intended. Do not create tables or connections until confirmed.
-1. **Data Model** — read and execute `/add-dataverse --skip-planning --working-dir '<working_dir>'` with the data child context above, the approved Data Model delta, and `offline_reconciliation_owner: edit-app`. Step 5.6 owns offline reconciliation; the leaf returns its verified created/extended/reused table results without running its own offline check. It must create/extend only the approved delta, refresh generated services/models, update `.datamodel-manifest.json`, and leave generated services compiling. After it returns, run `npm run generate-schemas` and `npx --no-install tsc --noEmit`; do not continue to screens until clean.
-2. **Sample Data** — intersect the Step 3-approved seed set with the leaf's verified newly created tables used by changed screens. Never derive the allowlist from the whole manifest or pass an empty/missing `--tables` to discovery. If the intersection is empty, skip seeding. Otherwise read and execute `/add-sample-data --working-dir '<working_dir>' --tables "<comma-separated approved logical names>"` with the data child context, the exact approved count/media policy in `approved_scope`, and `retiring_tables: <explicit exclusions or []>`. Newly needed seed dependencies require approval; do not silently expand the set. If seeding fails, record a concern and continue only if the app handles empty states.
-3. **Connector/Data Source** — read and execute `/add-datasource` when ambiguous, or `/add-sharepoint` / `/add-connector` for approved connector changes. Regenerate services and record connection notes in `memory-bank.md`.
+1. **Data Model** — invoke `/add-dataverse --skip-planning` with the approved
+ delta and the scoped planning context below, not every row in the plan.
+ The leaf verifies the evidence/approval hashes and performs fresh live
+ reconciliation before scoped mutations; no partial create-only fast-path
+ flags or fabricated create receipt. It refreshes the affected services,
+ updates verified inventory, and leaves generated services compiling.
+ Pass `offline_reconciliation_owner: edit-app`; Step 5.6 owns the offline
+ check, so the leaf returns its verified delta without prompting twice.
+ After it returns, run `npm run generate-schemas` and `npx --no-install tsc --noEmit`;
+ do not continue to screens until clean.
+2. **Sample Data** — seed only the explicit table allowlist approved in Step 3.
+ Propose newly created Dataverse tables used by changed screens as candidates,
+ not the entire project manifest. Distinguish `createdThisEdit` from historical
+ manifest `status: new`; existing/reused parent tables need explicit inclusion.
+ Validate the approved names against verified output and the retirement set.
+ An empty scope means skip seeding. Missing/unverified/retiring targets return to the owner
+ for correction, not a fallback to project-wide seeding. Pass the handoff below.
+ If insertion fails, record the partial result and continue only if the app
+ handles empty states; never report complete seed coverage.
+3. **Connector/Data Source** — read and execute `/add-datasource` when ambiguous, or `/add-sharepoint` / `/add-connector` for approved connector changes. For a retained source refresh, pass skill-only `--refresh --data-source-name "<registered-name>"` with its verified identity in `approved_scope`; do not route refreshes through addition. Use the same refresh branch for service-only Dataverse repairs without schema changes. Regenerate services and record connection notes in `memory-bank.md`.
4. **Pure-JavaScript Dependencies** — execute the Installation Contract in [`shared/references/javascript-dependency-planning.md`](${PLUGIN_ROOT}/shared/references/javascript-dependency-planning.md) for new or changed rows in the approved `## Screens → ### JavaScript Dependencies` table. Approval is consent for those exact packages and versions. Install and validate before screen work; if final inspection finds native code/config or incompatible runtime dependencies, remove only the newly added package and stop with the exact failed criterion.
5. **Native Capabilities** — read and execute `/add-native <capability>` for every new capability. Do not install missing native packages or fake wrappers. If a capability is unsupported by the current template, stop before rebuilding screens that import it, record the block, and tell the user what upstream template support is missing.
-6. **Design** — read and execute `/design-system --refresh <dimension>` or `/design-system --reskin` for design edits. Token-only changes usually do not require TSX rewrites; component/density/negative-rule changes may.
+6. **Design** — read and execute the approved `/design-system` operation (refresh,
+ reskin, theme, or rollback). Include `CODE_APPS_NATIVE_ORCHESTRATING=1` in
+ the child environment to suppress intermediate browser tabs, alongside the
+ scoped `MOBILE_APP_ORCHESTRATING=1` context above. Apply its Tamagui integration reference to changed
+ tokens/themes and provider wiring before verification; a brand artifact alone
+ does not prove runtime integration. Token-only changes usually do not require
+ screen TSX rewrites; component/density/negative-rule changes may. Rebuild
+ affected screens in Step 6 rather than returning early.
+ For an approved custom dark palette, execute the reference's **Approved dark
+ palette** branch: wire `darkTokens.color` into `appDarkTheme`, then into the
+ provider's `brandedDarkTheme`. Verify the export/keys and resolved dark
+ surface/text values; writing `brand/tokens.dark.ts` alone is not completion.
+
+Step 5 applies additions/refreshes, not removals. If the Data Model change is
+removal-only, do not run `/add-dataverse`'s add workflow against the shortened
+plan: it would neither unregister the old source nor safely update its consumers.
+Defer approved retirements until Step 6.5, after source consumers are updated.
After any Data Model, Connector/Data Source, JavaScript Dependency, or Native Capabilities mutation, rerun the generated-service/dependency/native-wrapper probe before screen work. Screen prompts must reflect what exists on disk now, not what the earlier plan expected.
+Dataverse handoff (only for approved schema/new-binding work):
+
+```text
+Invoke skill: /add-dataverse
+
+Context:
+ MOBILE_APP_ORCHESTRATING=1
+ orchestrator: edit-app
+ working_dir: <working_dir>
+ phase: implementation
+ offline_reconciliation_owner: edit-app
+ planning_snapshot: <SNAPSHOT_PATH>
+ architect_evidence: <ARCHITECT_EVIDENCE_PATH>
+ schema_contract: <working_dir>/.tmp/dataverse-schema-contract.json
+ approved_scope: <accepted delta and dependencies, contract_sha256, plan_sha256>
+
+Arguments:
+ --working-dir '<working_dir>'
+ --plan-section '<working_dir>/native-app-plan.md#data-model'
+ --skip-planning
+```
+
+Sample-data handoff (only for a nonempty approved seed scope):
+
+```text
+Invoke skill: /add-sample-data
+
+Context:
+ MOBILE_APP_ORCHESTRATING=1
+ orchestrator: edit-app
+ working_dir: <working_dir>
+ phase: implementation
+ approved_scope: <approved seed tables, count/media policy, and lookup decisions>
+ retiring_tables: <approved retirement list, or empty>
+
+Arguments:
+ --working-dir '<working_dir>'
+ --tables "<approved-seed-table-logical-names>"
+ --exclude-tables "<retiring-table-logical-names-or-empty>"
+```
+
+These are skill arguments, not Dataverse CLI flags. A required parent outside
+the allowlist returns `NEEDS_CONTEXT`; the seeding leaf must not expand scope
+or seed a transitional retiring table to satisfy its coverage rules.
+
#### Step 5.5 — Refresh generated service snapshot
Run this after any data-source/schema/connector mutation and before any screen-builder prompt:
@@ -471,11 +659,20 @@ done
Replace or create the `## Generated Services (snapshot at <ISO timestamp>)` section in `native-app-plan.md` immediately after `## Screens`. If there are no services, write an empty table and a note. Screen-builders must treat this table as authoritative.
+Mark still-present services in the approved removal set as retiring: builders
+must not introduce or retain dependencies on them. Refresh this snapshot again
+after Step 6.5 so it describes the actual remaining output.
+
Do not ask the user to run these follow-up skills manually. This skill is the orchestrator.
#### Step 5.6 — Offline profile reconciliation
-If Step 5 created or extended Dataverse tables, an existing Mobile Offline Profile may now be missing those tables/columns (new tables never sync to devices; new columns arrive blank). Step 5's `/add-dataverse --skip-planning` suppresses that skill's own Step 8.5 reconciliation, so this orchestrator owns the check. Skip when no Data Model mutation occurred in this edit.
+If Step 5 created or extended Dataverse tables, an existing Mobile Offline Profile may now be missing those tables/columns (new tables never sync to devices; new columns arrive blank). Step 5's complete scoped `/add-dataverse --skip-planning` handoff names `offline_reconciliation_owner: edit-app`, so this orchestrator owns the check instead of the leaf's Step 8.5. The flag alone is not enough. Skip when no Data Model mutation occurred in this edit.
+
+For mixed addition/removal edits, intersect any returned additions with the
+approved retained/added Dataverse set before offering/applying profile changes.
+Never add a retiring table to the offline profile merely because its transitional
+manifest entry remains until Step 6.5.
Run the local, no-network delta check:
@@ -498,6 +695,10 @@ and column arguments, then re-check through the same failure dispatch.
Record the outcome in the Step 8 memory-bank entry without clearing pending
`offlineRetirement` outcomes.
+These statuses concern additions only. Preserve any `offlineRetirement` outcomes
+from earlier attempts, and collect the removal leaf's updated outcomes in
+Step 6.5; an `in-sync` result never resolves a pending retirement.
+
### Step 6 — Rebuild affected screens
**Telemetry checkpoint: `rebuild_affected_screens`**
@@ -511,11 +712,15 @@ Use the plan diff plus the user's request to build the affected screen set:
| New create/edit form | The form screen plus parent list/detail screens that launch it and refresh on focus |
| New scanner/camera/PDF/pen workflow | The capability screen plus any result/detail/form screens it routes to |
| Data-model field added for visible UI | Every screen that displays or writes the field |
+| Data source removed/replaced | Every approved consumer, including shared hooks/helpers and native upload/sync code; retain the old registration until these edits are complete |
| Navigation pattern changed | Every tab/root screen and any route whose contract changed |
| Design component/density/reskin changed | All screens whose layout grammar is affected; for full reskin, run a broad screen wave or controlled style sweep |
Before spawning builders:
+- Pass the approved retiring service/source list to every affected builder.
+ Still-present generated files are transitional dependencies, not permission
+ to keep or introduce usages that the edit is meant to remove.
- Update route layout files using the `/create-mobile-app` Step 10b layout rules if navigation changed.
- Create missing route folders for new screens.
- Refresh the `## Generated Services` table using `/create-mobile-app` Step 10.7 rules if any data source/schema changed.
@@ -582,6 +787,27 @@ current_file: <paste current file content if the file exists>
Preserve unaffected behavior from the existing screen. Apply the approved plan diff. If this is an existing screen and no skeleton marker is present, update the screen from current_file instead of falling back to sample layout.
```
+### Step 6.5 — Unregister retired data sources
+
+Skip when the approved removal set is empty. After Step 6 updates/removes the
+consumers, re-check that no retained source depends on a retiring registration.
+Execute [data-source-removal.md](../../shared/references/data-source-removal.md)
+through `/add-dataverse` for Dataverse bindings, `/add-sharepoint` for SharePoint,
+or `/add-connector` for other connectors/procedures/flows, passing removal mode,
+the exact registered identities, and the current approved orchestration context.
+Select removal mode with the skill-only `--remove` argument; never pass it to CLI.
+
+The leaf bypasses its add workflow and uses the supported CLI removal command,
+which owns `.power/schemas/`, `src/generated/`, and `power.config.json` cleanup.
+Then regenerate the runtime schema map, verify absent/retained registrations
+and generated output, and reconcile the app manifest and offline impact.
+Refresh the Generated Services snapshot again before final validation.
+A no-op, partial cleanup, or remaining consumer blocks completion; do not mark
+the new plan as fully applied or manually patch generated/config files.
+Carry each leaf's `offlineRetirement` status into Step 8, including intentionally
+retained coverage and pending decisions/migrations. Do not replace those statuses
+with Step 5.6's addition-only result.
+
### Step 7 — Verify
**Telemetry checkpoint: `validate_edited_app`**
@@ -654,10 +880,16 @@ Append an edit entry to `memory-bank.md`:
- Verification: <commands/gates + pass/fail/skipped with reason>
- Preview: <preview.html path or not generated>
- Debug handoff: <not requested / /debug-app "<symptom>" invoked>
+- Offline retirement: <per-table not-applicable / retained with reason / pending / reconciled with verification>
- Blocks/concerns: <none or list>
```
Final summary must say what changed in the app, what verification ran, where the preview is, and whether a symptom-debug handoff was requested. Do not end by saying the codebase was not changed unless this was explicitly `--plan-only`.
+If any `offlineRetirement` outcome is `pending`, return `DONE_WITH_CONCERNS` and
+state the unfinished decision separately: "App changes completed. The offline
+profile still includes Orders; deciding whether to retain or remove that coverage
+is pending." Substitute the actual table and only claim app completion when its
+verification passed. Never remove profile entries automatically to clear this note.
## Notes
diff --git a/plugins/mobile-apps/skills/list-connections/SKILL.md b/plugins/mobile-apps/skills/list-connections/SKILL.md
index 4504df1cb..4a56dd80a 100644
--- a/plugins/mobile-apps/skills/list-connections/SKILL.md
+++ b/plugins/mobile-apps/skills/list-connections/SKILL.md
@@ -8,7 +8,7 @@ model: haiku
> **Plugin check**: Run `node "${PLUGIN_ROOT}/scripts/check-version.js"` - if it outputs a message, show it to the user before proceeding.
-**📋 Shared instructions: [shared-instructions.md](${PLUGIN_ROOT}/shared/shared-instructions.md)** — cross-cutting concerns (Windows CLI compatibility, memory bank, etc.).
+**📋 Shared instructions: [shared-instructions.md](${PLUGIN_ROOT}/shared/shared-instructions.md)** — read first for cross-cutting concerns (Windows CLI compatibility, memory bank, etc.).
# List Connections
diff --git a/plugins/mobile-apps/skills/open-wrap-url/SKILL.md b/plugins/mobile-apps/skills/open-wrap-url/SKILL.md
index 9fb99916a..50371b015 100644
--- a/plugins/mobile-apps/skills/open-wrap-url/SKILL.md
+++ b/plugins/mobile-apps/skills/open-wrap-url/SKILL.md
@@ -2,7 +2,7 @@
name: open-wrap-url
description: Use when the user wants to open the Power Apps Wrap page for an app ID in the active environment.
user-invocable: true
-allowed-tools: Bash
+allowed-tools: Read, Bash
model: haiku
---
diff --git a/plugins/mobile-apps/skills/setup-app-insights/SKILL.md b/plugins/mobile-apps/skills/setup-app-insights/SKILL.md
index 16e3fea8e..7222203e6 100644
--- a/plugins/mobile-apps/skills/setup-app-insights/SKILL.md
+++ b/plugins/mobile-apps/skills/setup-app-insights/SKILL.md
@@ -38,13 +38,17 @@ Application Insights is **off by default**. Invoking this skill (or approving it
**Telemetry checkpoint: `resolve_app_insights_mode`**
```
-1. Check env var CODE_APPS_NATIVE_ORCHESTRATING=1
+1. Check MOBILE_APP_ORCHESTRATING=1 AND explicit edit-app caller context
→ Mode A (invoked by /edit-app). Use the passed --working-dir. Return a status block.
2. Else resolve working_dir from cwd (must contain app.json with an expo object)
→ Mode B (standalone). Return a human summary.
```
+Use the invocation-scoped context from
+[app-edit-routing.md](../../shared/references/app-edit-routing.md), not a stale
+shell value. Configuration approval remains owned by Step 3 in either mode.
+
## Step 2 — Inspect and determine the action
**Telemetry checkpoint: `determine_app_insights_action`**
diff --git a/plugins/mobile-apps/skills/setup-datamodel/SKILL.md b/plugins/mobile-apps/skills/setup-datamodel/SKILL.md
index 532e5ea9b..e668165ad 100644
--- a/plugins/mobile-apps/skills/setup-datamodel/SKILL.md
+++ b/plugins/mobile-apps/skills/setup-datamodel/SKILL.md
@@ -12,6 +12,9 @@ model: opus
# Set Up Data Model + Connectors
+**Entry routing:** use the shared [App feature entry points](../../shared/shared-instructions.md#app-feature-entry-points)
+preflight before the workflow below.
+
**Invocation scope:** follow [Data-source invocation scope](../../shared/shared-instructions.md#data-source-invocation-scope)
before any project read or the workflow below.