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): reorder planning and offline setup (#502)

Shubham Agarwal75e72559d77c
diff --git a/plugins/mobile-apps/AGENTS.md b/plugins/mobile-apps/AGENTS.md
index 8943cb837..21e29abd0 100644
--- a/plugins/mobile-apps/AGENTS.md
+++ b/plugins/mobile-apps/AGENTS.md
@@ -53,7 +53,10 @@ Do not add preparation rewrites for `scheme`, `package`, `bundleIdentifier`, `sr
3. **Fresh-template mode** — `/create-mobile-app` validates and prepares an existing fresh Expo standalone template working directory. Do not silently copy the bundled `template/` snapshot over the user's folder.
4. **Safety guardrails** — Confirm before deploys, before global installs, before edits outside the project root.
5. **Memory bank** — Persist `memory-bank.md` in the project root.
-6. **Plan mode** — Enter plan mode before multi-file work; per-section approval gates (data model → native APIs → screen plan).
+6. **Plan mode** — Confirm requirements first. Gate 1 then presents native
+ capabilities, connectors, and the data-platform choice before conditional
+ Dataverse modeling; later gates approve the applicable data model and screen
+ plan.
7. **Persisted plan** — Write `native-app-plan.md` (Mermaid ER + per-screen specs + native capabilities matrix) as the source of truth that sub-skills `Read`.
8. **CLI compatibility** — Use `npx power-apps ...` for code-app lifecycle and data-source commands. Use `scripts/resolve-environment.js` plus `az` tokens for Dataverse environment URL/tenant discovery and Azure/Entra operations. See [`shared/shared-instructions.md`](./shared/shared-instructions.md).
9. **Agent invocation namespace** — All `Task` invocations of agents in this plugin MUST use the fully-qualified `mobile-app:<agent-name>` form (e.g. `mobile-app:native-app-planner`, `mobile-app:screen-builder`). Bare names like `native-app-planner` return `Agent type 'native-app-planner' not found` because Claude Code namespaces all plugin agents by plugin name.
@@ -72,6 +75,7 @@ Do not add preparation rewrites for `scheme`, `package`, `bundleIdentifier`, `sr
- Status code is the literal first line — no `Status:` prefix, no backticks, no preamble. After it, blank line, then the agent's normal summary.
- Agents MUST NOT downgrade `BLOCKED` to `DONE_WITH_CONCERNS` to keep the workflow moving — the orchestrator's job is to handle the block, not the agent's.
- `DONE_WITH_CONCERNS` requires at least one concern. If none, use `DONE`.
+ - In `/create-mobile-app` only, `NEEDS_CONTEXT: dataverse-planning-mode:<required|connector-only>` from the `gate-only` architecture pass is a phase-completion signal, not a retry. The canonical handler validates the approved architecture before continuing; other phases cannot use it to change the data platform.
- Special early-return signals (`INDUSTRY_CONFIRM_REQUESTED:`, `DESIGN_VIBE_REQUESTED:`) pre-date this protocol and remain in effect — they are special-cased "ask the user one question and re-spawn me" handoffs, not terminal returns.
- The canonical orchestrator handler lives in [`skills/create-mobile-app/SKILL.md`](./skills/create-mobile-app/SKILL.md) Step 3.0. Future skills that spawn agents should reference it rather than duplicating the switch.
13. **Metro lifecycle is project-local** — template `metro.config.js` delegates to `createPowerAppsMetroConfig`, whose host implementation writes sanitized `.powernative/metro-logs/` output during normal `npm run dev`; `/debug-app` locates and tails those files directly, with its cursor, health, and audit state under `.powernative/debug-app/`. Do not restore required `BashOutput`/terminal-ID behavior or host-specific project state directories. Host terminal APIs may be optional conveniences only. Never write unsanitized Metro output to disk, and never diagnose a log unless the logged PID/port still look live.
@@ -92,7 +96,7 @@ Mobile Apps bundles the canonical stdlib-only telemetry helpers from the repo-ro
## Decisions made
- ✅ Markdown plan with Mermaid (no HTML rendering)
-- ✅ **Per-section approval gates** in the planner (data model → native APIs → screen plan)
+- ✅ **Architecture-first approval gates** in the planner (data platform + native APIs + connectors → conditional Dataverse model → screen plan)
- ✅ `/edit-app` skill for post-generation app iteration: updates the approved plan delta, applies Dataverse/native/design/screen mutations, verifies, and refreshes preview output. `--plan-only` is the explicit docs-only escape hatch.
- ✅ Single `/deploy` skill — `npm run build` + `npx power-apps push`; no local native compile, no OTA in v0
- ✅ Connection model: per-environment connections, with platform-specific auth (`expo-msal-intune` on native, `expo-auth-session` on web)
@@ -101,7 +105,16 @@ Mobile Apps bundles the canonical stdlib-only telemetry helpers from the repo-ro
- ✅ Cross-host Metro diagnostics: user-owned `npm run dev`, port-probe liveness and stale-PID protection, sanitized project-local logs, a durable debug cursor, and read-only `status` plus foreground-loop `stop` commands
- ✅ Template is supplied as a fresh `microsoft/power-platform-skills/plugins/mobile-apps/template#main` folder before `/create-mobile-app` runs; users materialize it with `degit`, run `npm install`, then invoke the skill from that folder. The skill validates/prepares the folder and runs `npx power-apps init`.
- ✅ `brand/` directory convention: `/design-system` (Step 6.75) writes `brand/design-system.md` (spec), `brand/tokens.ts` (importable Tamagui tokens), and `brand/design-system.html` (visual gallery). Screen-builders MUST read `brand/design-system.md` if present; `## Negatives` = HARD RULES. `/create-mobile-app` Step 9b imports `brand/tokens.ts` via `skills/design-system/references/tamagui-integration.md`. Projects without `brand/` fall back to `## Design Direction` only — no breakage.
-- ✅ Offline profile creation is **author-only in v0.1** — `/setup-offline-profile` and `/enable-tables-offline` POST `mobileofflineprofile` / `mobileofflineprofileitem` / `mobileofflineprofileitemassociation` to Dataverse and write `offline-profile.json` to the project, but do NOT scaffold offline runtime code (SQLite store, sync engine, write queue) into the generated app. Runtime support is gated on upstream `@microsoft/power-apps-native-host` confirmation.
+- ✅ Offline profile creation is **configuration-only in v0.1** —
+ `/setup-offline-profile` and `/enable-tables-offline` POST
+ `mobileofflineprofile` / `mobileofflineprofileitem` /
+ `mobileofflineprofileitemassociation` to Dataverse and write
+ `offline-profile.json`. The template already bundles
+ `@microsoft/power-apps-native-offline`, and
+ `@microsoft/power-apps-native-host` consumes it for local SQLite access,
+ queued synchronization, reconnect handling, and its status overlay. Skills
+ configure that host runtime; they do not scaffold a second app-owned store,
+ sync engine, queue, or duplicate offline UX.
- ✅ Custom filter mode (`recorddistributioncriteria=3`, `profileitemrule` → `savedquery`) is **deferred to v0.5**. v0.1 supports Related-rows-only / All-records / Organization-rows radio options only.
- ✅ `offline-profile-architect` agent follows the existing `mobile-app:` namespace + status-code protocol (`DONE` / `DONE_WITH_CONCERNS:` / `NEEDS_CONTEXT:` / `BLOCKED:`). Read-only — proposes scope; never mutates Dataverse. Mutation lives in `/setup-offline-profile` after the 3 gates.
- ✅ **Offline profile ↔ schema reconciliation across the lifecycle.** Any schema change (`/add-dataverse`, `/setup-datamodel`, `/edit-app`) reconciles an existing offline profile, and `/deploy` gates the final push on offline coverage. Mechanism: `scripts/offline-profile-delta.js` — a purely LOCAL, no-network diff of `.datamodel-manifest.json` (schema) vs `offline-profile.json` (offline coverage) reporting `missingTables` + new columns; `status` ∈ `no-manifest`/`no-profile`/`in-sync`/`delta`/`error` (exit 0 = ran, 1 = fatal). It is distinct from `verify-offline-profile.js`, which is a Dataverse-network drift check of the snapshot vs the live published profile. Column delta is computed against a per-table `schemaColumns` baseline (all schema columns present at reconciliation time), written by `/setup-offline-profile`, `/add-table-to-offline-profile`, and refreshed by `/edit-offline-profile` — NOT against the curated `selectedColumns`, so deliberate exclusions aren't false-flagged; legacy snapshots without it degrade to table-only delta. The one canonical flow (prompt wording, reconcile ordering, deploy gate/override) lives in [`shared/references/offline-profile-reconciliation.md`](shared/references/offline-profile-reconciliation.md); the four skills reference it rather than duplicating it. Orchestrator-invoked `/add-dataverse` (`--skip-planning`) suppresses its own Step 8.5 so the orchestrator owns reconciliation once.
diff --git a/plugins/mobile-apps/README.md b/plugins/mobile-apps/README.md
index fbf19adcf..b0483e510 100644
--- a/plugins/mobile-apps/README.md
+++ b/plugins/mobile-apps/README.md
@@ -171,7 +171,7 @@ What happens:
1. **Wizard** (~30s) — confirms device class / aesthetic
2. **Requirements brief** — the orchestrator infers features (data entry, camera, location), pre-checks them, asks you to confirm or adjust
3. **Industry confirmation** — only fires if the inference is shaky (your description matched multiple industries, or none)
-4. **4 approval gates** — data model → native capabilities → connectors → screens (with a visual `_plan_preview.html` of every screen before any code is written)
+4. **Up to 4 approval gates** — data platform + native capabilities + connectors → Dataverse model when selected → screen graph → screen specs (reviewed in markdown before code is written)
5. **Design system** — brand inputs (logo, brand doc, website, or free-text) → cost picker → style picker → component reference sheet → branded screen previews
6. **Scaffold + build** — validates the prepared template folder, runs `npx power-apps init`, verifies installed dependencies, generates schemas, builds Dataverse tables, wires connectors, spawns N parallel screen-builders for the TSX
7. **Dev server** — the plugin starts a portable Metro session; scan the QR with your native dev client and use `/debug-app` against its persisted sanitized log
@@ -274,7 +274,7 @@ Example edit flows:
| `/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-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`. Author-only — no runtime stubs in the generated app yet; runtime support is deferred until upstream host support is confirmed. Auto-proposed by `/create-mobile-app` Step 6.85 for offline-relevant apps; also runs standalone on existing apps. |
+| `/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. |
| `/assign-offline-profile` | 🟡 v0.1 | Bind users / teams to a Mobile Offline Profile via `usermobileofflineprofilemembership` / `teammobileofflineprofilemembership` rows. Without this, the profile exists but no one's app uses it. Accepts `--user <upn>`, `--team <name>`, `--me`, `--all-app-users`, `--unassign-*` flags. |
| `/edit-offline-profile` | 🟡 v0.1 | Change ONE aspect of an existing profile (table scope, sync frequency, column list, name/description) without re-running the full wizard. Mirrors the `/edit-app` gated edit pattern. Accepts `--rename`, `--table X --scope`, `--table X --sync`, `--table X --columns add:/remove:/reset` flags. |
@@ -285,7 +285,7 @@ Example edit flows:
| Agent | Role |
| --- | --- |
-| `native-app-planner` | Orchestrator — coordinates the data-model + screen-planner architects, plans native capabilities + connectors inline, runs 4 approval gates |
+| `native-app-planner` | Orchestrator — approves data platform + native capabilities + connectors, conditionally coordinates the data-model architect, coordinates screen planning, and runs up to 4 approval gates |
| `data-model-architect` | Read-only — discovers Dataverse, scores reuse / extend / create, returns an ER section |
| `screen-planner` | Read-only — picks navigation pattern, designs per-screen specs |
| `screen-builder` | Mutation — writes ONE TSX file per assigned screen, runs N in parallel |
diff --git a/plugins/mobile-apps/agents/data-model-architect.md b/plugins/mobile-apps/agents/data-model-architect.md
index 6fd9a5bfd..19b7bd947 100644
--- a/plugins/mobile-apps/agents/data-model-architect.md
+++ b/plugins/mobile-apps/agents/data-model-architect.md
@@ -26,8 +26,13 @@ You will be invoked by `native-app-planner` or `/edit-app` with a prompt that in
`<working_dir>/.tmp/dataverse-foreground-planning-snapshot.json`.
- **Planning evidence path (preferred)** — an absolute path to the deterministic
Markdown appendix rendered from that same foreground planning snapshot.
-- **Dataverse planning mode** — `required` or `connector-only`.
- `connector-only` intentionally has no snapshot/evidence paths.
+- **Dataverse planning mode** — `required`. Connector-only planning is owned by
+ `native-app-planner` and must not dispatch this agent.
+- **Approved native capabilities** (create flow, when supplied) — the exact
+ Gate 1-approved capability matrix, including capture/output and retention
+ targets.
+- **Approved connectors** (create flow, when supplied) — the exact Gate
+ 1-approved connector list and each external system's ownership boundary.
- **Publisher prefix (detected from env)** — e.g. `cr8142a` (no trailing underscore). Use this literally when constructing logical names: `<prefix>_<entity>` → `cr8142a_inspection`. If the prefix is empty / `NOT DETECTED`, fall back to the placeholder `cr` and add a `DONE_WITH_CONCERNS` note that the actual prefix will be assigned by Dataverse at create time. **Do not invent or assume `cr_` if a real prefix was supplied.**
- **`mode` (optional)** — one of `default` (full Steps 1–7, the original flow) or `cross-entity-audit` (the addendum pass spawned AFTER `screen-planner` returns; runs ONLY Step 6a + writes a `### Cross-entity Reads` addendum to `_dm_section.md`, skipping discovery and re-scoring). When omitted, treat as `default`.
@@ -41,9 +46,16 @@ You will be invoked by `native-app-planner` or `/edit-app` with a prompt that in
foreground planning snapshot. Don't propose a `cr123_customer` table if a verified
target `contact` table fits.
- **Never invent existing schema.** Never propose recreating or imitating a missing standard, managed, or solution-owned table/column. If discovery cannot run, you may still draft a plan from requirements, but mark it `Discovery skipped` so every decision remains unverified and non-executable. Step 8 verifies approved decisions against fresh bounded metadata; it never invents `Adapt` or `Defer`.
-- **Mode fidelity.** `connector-only` means zero Dataverse tables and zero
- Dataverse discovery. A Dataverse-required run with unreadable metadata is
- blocked by the foreground orchestrator before this agent is dispatched.
+- **Mode fidelity.** This agent runs only for Dataverse-required planning. A
+ run with unreadable metadata is blocked by the foreground orchestrator before
+ dispatch.
+- **Connectivity intent ownership.** Follow
+ [`shared/references/connectivity-intent-ownership.md`](../shared/references/connectivity-intent-ownership.md)
+ when deriving schema.
+- **Approved architecture is authoritative when supplied.** Account for
+ approved native capture and retention targets when selecting Image, File,
+ location, or child evidence storage. Do not create a Dataverse duplicate of a connector-owned entity;
+ model only app-owned data or explicit Dataverse projections approved at Gate 1.
- **No automatic replacement.** This agent classifies schema as `Reuse`, `Extend`, `Create`, `Adapt` (create beside a conflicting object under a new name), `Defer` (leave out of this run), or `Unverified` (target metadata could not be read). Replacing an existing table/column requires a separately approved migration with dependency analysis and data movement; it is outside this workflow. A data-modelling conflict is never a blocker — it is an `Adapt` or a `Defer` with a recorded reason.
- **Return a section, not a separate doc.** Output is a markdown `## Data Model` section the planner embeds verbatim.
- **No JSON request bodies in the output.** Your `_dm_section.md` describes *what* to create (tables, columns, relationships) using the Mermaid ER + reuse/extend/create table + tier list. **Do NOT include POST body JSON** for `EntityDefinitions` or `RelationshipDefinitions` — `/add-dataverse` constructs those from its own canonical templates in [skills/add-dataverse/SKILL.md](../skills/add-dataverse/SKILL.md) Step 5b. JSON in your output is read as authoritative and will leak invented/wrong fields (e.g. `ReferencingAttribute` on a lookup) into the actual POST.
@@ -76,18 +88,18 @@ You will be invoked by `native-app-planner` or `/edit-app` with a prompt that in
6a. Cross-entity Read Audit (when `_screens_section.md` exists OR `mode: cross-entity-audit`)
7. Produce the `## Data Model` section
-**`mode: cross-entity-audit` short-circuit** — when invoked with `mode: cross-entity-audit`, skip Steps 1–6 entirely (the data model is already in `_dm_section.md` from the prior round) and run ONLY Step 6a + a slim Step 7-addendum that writes a `### Cross-entity Reads` block. The orchestrator presents this addendum to the user as an addendum to Gate 1 (or rolls it into the Gate 1 view if Gate 1 has not yet been presented).
+**`mode: cross-entity-audit` short-circuit** — when invoked with `mode: cross-entity-audit`, skip Steps 1–6 entirely (the data model is already in `_dm_section.md` from the prior round) and run ONLY Step 6a + a slim Step 7-addendum that writes a `### Cross-entity Reads` block. The orchestrator presents this addendum to the user as an addendum to Gate 2 (the Dataverse data-model gate), not the architecture gate.
---
## Planning-mode short circuits
-When `Dataverse planning mode: connector-only` is supplied, do not resolve an
-environment, read metadata, or request snapshot artifacts. Write
-`_dm_section.md` with an explicit zero-table `## Data Model` section (all
-summary counts zero, no ER entities or dependency tiers, and a note that the
-confirmed systems of record are the approved connectors), update the normal
-artifact milestone, and return `DONE`.
+When `Dataverse planning mode: connector-only` is supplied, return:
+
+`BLOCKED: This step only applies when Dataverse is selected. Continue the connector-based app plan without data-model planning.`
+
+Do not read metadata or write planning artifacts. The native app planner owns
+the explicit zero-table connector-only section.
## Snapshot-only fast path
@@ -332,7 +344,7 @@ dependency-tier counts.
**Print before starting:**
> "→ Auditing planned screens for supported cross-entity read paths…"
-**Run condition:** execute this step when EITHER (a) `<working_dir>/_screens_section.md` exists at this point in the workflow OR (b) you were invoked with `mode: cross-entity-audit`. **Skip silently otherwise** (default-mode first-pass run, before screen-planner has produced its section) — the orchestrator will re-spawn you in `mode: cross-entity-audit` after Gate 4a/4b lands.
+**Run condition:** execute this step when EITHER (a) `<working_dir>/_screens_section.md` exists at this point in the workflow OR (b) you were invoked with `mode: cross-entity-audit`. **Skip silently otherwise** (default-mode first-pass run, before screen-planner has produced its section) — the orchestrator will re-spawn you in `mode: cross-entity-audit` after Gates 3 and 4 land.
When `mode: cross-entity-audit`, the orchestrator's prompt also includes the path to the existing `_dm_section.md` so you can append (do NOT regenerate it from scratch — Steps 1–6 are skipped in this mode).
@@ -343,7 +355,15 @@ code, so this audit never proposes generated formula metadata.
**Algorithm:**
-1. **Read the screen plan.** Look for `<working_dir>/_screens_section.md` first (graph-only mode after Gate 4a). If absent, parse `<working_dir>/native-app-plan.md` and extract the `## Screens` section. Walk every per-screen spec and collect every `related_entity_fields` block.
+1. **Read the screen plan.** In `mode: cross-entity-audit`, read `plan_path`
+ (default `<working_dir>/native-app-plan.md`) and extract `## Screens`.
+ `_screens_section.md` is graph-only scratch after Gate 3 and is not a substitute
+ for the final per-screen specs. If the canonical plan or completed specs are
+ missing, return `NEEDS_CONTEXT: canonical-screen-specs` so the foreground
+ restores that handoff; do not report zero related fields from a graph alone.
+ Only legacy default-mode callers may use `_screens_section.md` when it
+ actually contains per-screen specs. Walk every spec and collect every
+ `related_entity_fields` block.
2. **Per entry, branch on `recommends`:**
diff --git a/plugins/mobile-apps/agents/native-app-planner.md b/plugins/mobile-apps/agents/native-app-planner.md
index 1a583fdc2..dc32cd018 100644
--- a/plugins/mobile-apps/agents/native-app-planner.md
+++ b/plugins/mobile-apps/agents/native-app-planner.md
@@ -1,6 +1,6 @@
---
name: native-app-planner
-description: Use when the orchestrator needs a full plan + four approval gates (data model → native capabilities → connectors → screens) for a Power Apps mobile app. Read-only — proposes everything, mutates nothing. Called by /create-mobile-app; not invoked directly by users.
+description: Use when the orchestrator needs architecture approval before conditional Dataverse modeling and screen planning for a Power Apps mobile app. Read-only — proposes everything, mutates nothing. Called by /create-mobile-app; not invoked directly by users.
user-invocable: false
color: cyan
tools:
@@ -22,12 +22,14 @@ You are the planning orchestrator for a Power Apps mobile app. Your job is to co
You will be invoked by `/create-mobile-app` with a prompt that includes:
- The user's app requirements (`$ARGUMENTS`)
-- Wizard answers collected by the skill (target users + device, target platforms, aesthetic, features)
+- Wizard answers collected by the skill (target users + device, aesthetic, features); target platforms are always iOS and Android
- The working directory where `native-app-plan.md` should be written
- The plugin root directory (`${PLUGIN_ROOT}`)
- The foreground-generated normalized Dataverse planning snapshot path, when available
- The deterministic Dataverse planning evidence appendix path, when available
-- Dataverse planning mode: `required` or `connector-only`
+- Dataverse planning mode: `required` or `connector-only` in `complete` phase
+- Architecture phase: `gate-only` or `complete`
+- Approved architecture artifact path for `complete` phase
## Hard Rules
@@ -40,14 +42,19 @@ You will be invoked by `/create-mobile-app` with a prompt that includes:
human plan or a source
for free-form Markdown parsing. No HTML or other per-domain plan files.
Mermaid for diagrams.
-- **Per-section approval gates.** You enter plan mode four times — once per section. A rejection on any section means revise that section only and re-enter plan mode for it. Do not move on until each section is explicitly approved.
-- **Sequential then parallel.** Spawn `data-model-architect` first (alone). Plan native capabilities and connectors inline. Only then spawn `screen-planner` — it needs the connector list to write correct per-screen service references.
+- **Architecture-first approval.** Gate 1 approves native capabilities,
+ connectors, and the data platform in that order. Only then may a `required`
+ run dispatch `data-model-architect` and enter Gate 2. A `connector-only` run
+ has no Dataverse contract or data-model approval interaction.
+- **Sequential then parallel.** Resolve and approve native capabilities,
+ connectors, and persistence in `gate-only` phase. In `complete` phase, build
+ the Dataverse model only when required, then spawn `screen-planner` with every
+ approved dependency.
- **Application Insights is outside the plan gates.** Treat requests to enable telemetry for the generated app as host/runtime configuration owned by the `/setup-app-insights` skill (standalone or via `/edit-app`). Do not model Application Insights in the data model, native-capability matrix, connector list, or as a telemetry-specific screen. In particular, never propose the deprecated Azure Application Insights connector or a custom connector for telemetry ingestion. When the user explicitly names custom events, preserve them as `Custom events` annotations on the corresponding normal business-screen specs; this records behavior without turning telemetry into a planning gate or data source.
-
-- **Dataverse planning forwarding is verbatim.** Pass the planning mode to every
- default-mode `data-model-architect` dispatch and revision. In `required`,
- pass both planning-snapshot/evidence absolute paths unchanged. In `connector-only`,
- state that both paths are not supplied. Never invent placeholder artifact
+- **Dataverse planning forwarding is verbatim.** In `complete` phase, for every `required`
+ `data-model-architect` dispatch and revision, pass the planning mode and both
+ planning-snapshot/evidence absolute paths unchanged. Never dispatch the
+ architect in `connector-only` mode and never invent placeholder artifact
paths. Do not
resolve the environment, verify Dataverse access, run broad discovery, or
issue any live Dataverse
@@ -57,6 +64,9 @@ You will be invoked by `/create-mobile-app` with a prompt that includes:
rationale, ER diagram, tiers, and risks verbatim. Keep the appendix as a
referenced artifact; do not paste candidate rankings, raw columns, or timing
tables into `native-app-plan.md`.
+- **Connectivity intent ownership.** Follow
+ [`shared/references/connectivity-intent-ownership.md`](../shared/references/connectivity-intent-ownership.md)
+ throughout planning.
- **MANDATORY progress reporting.** Every step in the workflow has a `**Print before starting:**` block. You MUST emit that exact line as a plain text message to the user before doing the step's work. Do not skip, do not paraphrase, do not batch them. The user has no other visibility into what you're doing — silence between gates looks like the agent has hung. If you finish a step without having printed its line, you violated this rule.
## Step 0 — Tool-surface preflight (MANDATORY — first thing you do)
@@ -65,7 +75,7 @@ Before reading anything or drafting any plan content, verify your invocation con
Required tool surface:
- `Task` — spawn `data-model-architect` and `screen-planner`
-- `EnterPlanMode` / `ExitPlanMode` — run the four approval gates
+- `EnterPlanMode` / `ExitPlanMode` — run up to four applicable approval gates
- `AskUserQuestion` — industry-confirm and style-picker handoffs
- `Read` / `Write` — read references, write `native-app-plan.md`
- `Bash` / `Grep` / `Glob` — working-dir checks and legacy discovery only;
@@ -76,7 +86,7 @@ Required tool surface:
**On missing tools, return as your final message** (literal first line):
```
-BLOCKED: tool surface missing <comma-separated tool names>. Re-spawn from a context with Task + EnterPlanMode + ExitPlanMode + AskUserQuestion + Read + Write + Bash. Do NOT draft a plan from this context — the orchestrator cannot run the four gates without these tools, and a draft without gates wastes tokens.
+BLOCKED: tool surface missing <comma-separated tool names>. Re-spawn from a context with Task + EnterPlanMode + ExitPlanMode + AskUserQuestion + Read + Write + Bash. Do NOT draft a plan from this context — the orchestrator cannot run the applicable gates without these tools, and a draft without gates wastes tokens.
```
The orchestrator's Step 3 has a documented inline-gate fallback for exactly this case (it owns the right tool surface itself). Returning `BLOCKED` here is the correct handoff — do not silently degrade to "write a draft plan and hope someone gates it later."
@@ -87,72 +97,44 @@ Read these references once before doing anything else:
- `${PLUGIN_ROOT}/AGENTS.md` — plugin conventions
- `${PLUGIN_ROOT}/template/package.json` — **the native-code allowlist**. The set of modules with native code/config is fixed by the rewrap pipeline; you may NEVER propose a native capability whose module is not present here. Pure-JavaScript app dependencies are planned separately by `screen-planner` under `## Screens` and need not be bundled in this template.
+- `${PLUGIN_ROOT}/shared/references/connectivity-intent-ownership.md` — owns
+ how offline and connectivity wording is handled during creation.
Do NOT attempt to read `app.config.js` from the working directory — scaffolding has not run yet. Reading `template/package.json` from `${PLUGIN_ROOT}` IS allowed and IS required.
From the planner prompt extract:
-- **Target platforms** — iOS + Android by default. If the user picked just one platform, native modules need `Platform.OS` branching notes in the screen plan.
+- **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.
- **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.
Carry each input into its owning planning step: native hints into `## Native Capabilities`, pure-JavaScript dependency hints into the `screen-planner` prompt, and the confirmed industry into design planning.
-## Step 2 — Spawn `data-model-architect` + inline planning in parallel
+## Step 2 — Prepare Architecture Inputs
-**Print before spawning** (so the orchestrator user sees progress):
-> "→ [1/4] Spawning data-model-architect. Running native caps + design + connector inference in parallel while it works…"
+**Print before starting:**
+> "→ Preparing native capabilities and connector inputs before any data-model work…"
-**Spawn `mobile-app:data-model-architect` via `Task` and immediately continue** — do NOT wait for it to return before doing Steps 3, 3b, 3c. Those three steps only need the requirements brief, which you already have. Native caps, design direction, and connectors are independent of the Dataverse schema.
+If `Architecture phase: complete`, read the approved architecture artifact,
+restore its exact data-platform choice, native-capability section, and
+connector section, then continue at Step 5. Do not re-run or re-present Gate 1.
-While the architect runs, complete Steps 3, 3b, and 3c inline. By the time you finish connector inference, the architect is usually done or nearly done. This cuts ~1–2 min of dead-wait off the plan phase.
+For `Architecture phase: gate-only`, continue below. No Dataverse snapshot,
+evidence, publisher prefix, or schema contract is required in this phase.
-### Prompt for `data-model-architect`
+Complete native-capability planning, then connector planning, then run Gate 1.
+The data architect must receive the exact approved native
+capabilities and connectors because capture, file, location, identity, and
+external-system decisions can change schema and storage requirements.
-> You are the data-model-architect agent. Design a Dataverse data model for the following mobile app.
->
-> Requirements: [paste $ARGUMENTS]
-> Wizard answers: [target users & device, aesthetic, features]
-> Target environment: use the foreground-resolved environment URL and tenant.
-> When planning-snapshot/evidence paths are supplied, do not read `power.config.json` or
-> call `scripts/resolve-environment.js`.
-> Working directory: [absolute path]
-> Plugin root: ${PLUGIN_ROOT}
-> Dataverse planning mode: [required | connector-only]
-> Dataverse planning failure reason: none
-> Normalized Dataverse foreground planning snapshot: [absolute path supplied by foreground verbatim, or NOT SUPPLIED]
-> Dataverse planning evidence: [absolute path supplied by foreground verbatim, or NOT SUPPLIED]
-> Structured schema contract output: [absolute
-> `<working_dir>/.tmp/dataverse-schema-contract.json` in required mode, or NOT
-> SUPPLIED in connector-only mode]
->
-> Follow the instructions in your agent file. You are read-only — do NOT create tables. In required mode, return a markdown `## Data Model` section ready to embed in native-app-plan.md and write/normalize the structured schema contract sidecar covering every table, column, relationship, and alternate key. Include a Mermaid ER diagram, a reuse/extend/create table, and dependency-tier ordering. Return per AGENTS.md rule #10: literal first line is `DONE` / `DONE_WITH_CONCERNS:` / `NEEDS_CONTEXT:` / `BLOCKED:`, then a blank line, then your summary.
-> If requirements mention generated PDFs, report exports, evidence packets, signatures, sign-off, pen/ink, drawings, or uploaded PDFs/documents, include the artifact storage target in the data model: on-device/share-only, Dataverse Image column, Dataverse File column, or child Evidence/Attachment table. Retained PDF content must use a File column, not long text/base64.
-
-After spawning, proceed immediately to Step 3 without waiting. Then, before writing the plan doc (Step 4), check the architect's result and parse its first line per AGENTS.md rule #10:
-
-- `DONE` → in `required` mode, verify both `_dm_section.md` and the normalized
- `.tmp/dataverse-schema-contract.json` exist; then embed the section and
- continue. A missing sidecar is `BLOCKED`, not a Markdown-parsing fallback.
-- `DONE_WITH_CONCERNS: <list>` → apply the same sidecar check, embed section,
- and propagate concerns.
-- `NEEDS_CONTEXT: detailed-dataverse-metadata:<logical names>` → return that
- exact first line to the foreground orchestrator. Do not expand the foreground planning snapshot
- or re-run discovery here.
-- `NEEDS_CONTEXT: proposed-dataverse-names:<logical names>` → return that exact
- first line to the foreground orchestrator for collision-only expansion. Do
- not infer absence or rewrite the proposed names here.
-- `NEEDS_CONTEXT: <missing>` → re-spawn once with missing non-Dataverse context,
- forwarding the same planning-snapshot/evidence paths unchanged. If the second return
- is also `NEEDS_CONTEXT`, return `BLOCKED`.
-- `BLOCKED: <reason>` → return `BLOCKED: data-model-architect returned BLOCKED: <reason>` to orchestrator.
-
-## Step 3 — Plan Native Capabilities Inline (Gate 2)
+## Step 3 — Plan Native Capabilities Inline (Gate 1 input)
**Print before starting:**
> "→ [2/4] Building native capabilities matrix from requirements (allowlist-bounded against template/package.json)…"
-Build the native capabilities matrix yourself (this is a small enough surface to keep in-house). Cross-reference the screen-planner output to know which screens use which capability.
+Build the native capabilities matrix yourself (this is a small enough surface
+to keep in-house). Screen planning has not run yet, so tie each capability to
+the confirmed workflow or use case that requires it.
**Important:** the upstream template owns iOS Info.plist keys, Android permissions, and config plugins for every shipped module. Do NOT specify those here — the planner does not pick permission strings, and downstream `/add-native` helpers do not edit `app.config.js` or `package.json`. The matrix only records *which* capabilities the app uses and *why*.
@@ -203,15 +185,16 @@ PDF fallback order:
Control planning gate:
- Classify the intent, resolve the exact package/control from the allowlist, confirm it is not runtime-banned, and record storage/output plus add path (`/add-native <capability>` or host File/Image control).
-- If any required gate is false — missing package/control, runtime-banned package, unsupported URL/output type, or missing Dataverse storage for a persisted artifact — do not propose that native capability; write a transparency note instead.
+- If any required gate is false — missing package/control, runtime-banned package, unsupported URL/output type, or no supported storage/output target — flag the capability and resolve its requirement at Gate 1 before approval.
+- For a persisted artifact, record either an appropriate Dataverse target when Dataverse is selected or connector-owned storage with the exact connector, supported upload/write operation, and target library/container/field. Verify that the operation accepts the captured file or image representation; a connector name alone is not a storage implementation. On-device/share-only output is valid only when the confirmed requirement does not need server retention.
- Do not use Power Apps extensions as generic replacements: PDF viewer opens HTTPS and local file PDFs, pen input is ink/signature capture, generated reports are `expo-print`.
- The table is not closed. For unlisted native hints, use the exact relevant package when present and safe; otherwise drop the capability. Multi-part asks must update every affected surface.
PDF/pen inference rules:
- `document-picker` means user-selected local files only: pick/import/upload PDF/document/attachment.
-- `pdf-report` means app-generated PDFs. Local output is shared with `expo-sharing` only when that package is present, or uploaded to a Dataverse File column if retained.
+- `pdf-report` means app-generated PDFs. Local output is shared with `expo-sharing` only when that package is present. Retention uses an approved Dataverse File column or a supported connector-owned storage operation; do not force a Dataverse model for a connector-owned PDF.
- `native-pdf-viewer` means opening an HTTPS PDF URL or local `file://` URI with `@microsoft/power-apps-native-pdf-viewer` 0.2.9+. It does not support `content://`, `blob:`, or `http://`.
-- `pen-input` means signature/ink capture with `@microsoft/power-apps-native-pen-input`. It returns PNG data URI and needs a Dataverse Image/File/child-row target when persisted.
+- `pen-input` means signature/ink capture with `@microsoft/power-apps-native-pen-input`. It returns a PNG data URI. When retained, use an approved Dataverse Image/File/child-row target or a supported connector-owned storage operation with an explicit conversion/upload path; use on-device/share-only only when retention is not required.
- `geolocation` means continuous/background GPS tracking with durable storage and inline Dataverse sync via `@microsoft/power-apps-native-bglocation`. Auth is MSAL-only; native uploads each fix to an existing Dataverse table (default entity set `msdyn_locationrecords`). It is distinct from one-shot `location` (`expo-location`). Plan it only for continuous tracking or durable upload, require `/add-native geolocation` to verify the target table exists before use, and never propose the `GeolocationExtension`/HostingSDK path.
- The Power Apps extensions are use-case-specific, not generic replacements for Expo modules. For other native needs, choose the relevant Expo module or dependency already present in `template/package.json` and still enforce the allowlist.
@@ -237,76 +220,177 @@ For each capability the app needs **AND is in the allowlist**:
|---|---|
| Capability | `camera` |
| Expo module | `expo-camera` |
-| Used by screens | `CaptureReceipt`, `ProfilePhoto` |
+| 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`, `on-device/share-only`, `local file URI`, or `HTTPS URL` |
+| 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` |
| Add via | `/add-native camera` |
If the app needs zero allowlisted native capabilities, include a `## Native Capabilities` section that says "None — this app uses only standard React Native components and Power Platform connectors." Transparency notes for dropped caps still appear under this header — "None proposed" is not the same as "nothing was considered."
-## Step 3c — Plan Design Inline
+## Step 4 — Plan Connectors Inline (Gate 1 input)
**Print before starting:**
-> "→ Inferring design direction from industry signals (no gate — design is reviewed visually at Gate 4)…"
+> "→ [3/4] Inferring connector needs from requirements…"
-Follow [`shared/references/design-planning.md`](${PLUGIN_ROOT}/shared/references/design-planning.md) exactly. The three steps are:
+Follow [`shared/references/connector-planning.md`](${PLUGIN_ROOT}/shared/references/connector-planning.md)
+only for Step 1 inference, Step 3 section formatting, and connector metadata.
+Skip its Step 2 standalone confirmation in this workflow. Gate 1 owns the only
+user interaction; the shared reference's confirmation remains unchanged for
+other callers:
-1. **Detect** — scan requirements and wizard aesthetic answer for design keywords. Detect the industry and build a list of design decisions (even if all of them match the default stack).
-2. **Decide** — map the detected industry to its aesthetic direction, palette, copy tone, and visual language using the tables in `design-planning.md`. Always produce a full `## Design` section — never write just "default (Clean + Professional)".
-3. **Summarise** — do NOT ask a question here. Write the `## Design` section into the plan doc and move on. Design confirmation happens visually at Gate 4 when the user sees `_plan_preview.html` — not via a text question upfront.
+1. **Infer** — scan requirements and wizard answers for connector keywords.
+2. **Draft** — build the candidate `## Connectors` section (table or "None"
+ line) without asking a separate question.
+3. **Approve in Gate 1** — let the user add, remove, or confirm connectors while
+ reviewing the complete architecture.
-Store the design decision — you will pass it to `screen-planner` in Step 5b so per-screen specs use the right tokens.
+**Key rule:** Dataverse is NOT a connector. If requirements mention custom business data / tables, that belongs in `## Data Model`, not `## Connectors`.
-**Key rule:** Always describe the design with industry rationale, even when every decision matches the default. The user needs to see *why* — e.g. "Refined Minimal — standard for productivity/enterprise apps: neutral palette, dense layout, professional copy tone" — not just a label. Design approval happens at Gate 4 via the preview, not here.
+Application Insights telemetry is also NOT a connector. Exclude it from Gate 1 and allow planning to proceed with the actual business connectors. The customer-owned Application Insights resource is configured separately through the `/setup-app-insights` skill (standalone or via `/edit-app`).
-### Industry inference confidence
+Store the Gate 1-approved connector list for the data-model and screen planners.
-After detection, classify the inference confidence and emit a signal so the orchestrator can ask the user only when the guess is shaky. **Skip this entirely when `Design vibe opt-in: yes` or `done`** — in those cases the user already drove the direction explicitly.
+### Gate 1 — Data Platform + Device Capabilities + Integrations
-| Confidence | When | Action |
-|---|---|---|
-| `high` | Wizard aesthetic answer was non-default OR user mentioned a hex color / brand / explicit aesthetic word ("warm", "playful", "minimal") OR exactly one industry keyword family matched | No signal. Proceed silently. |
-| `low` | Zero industry keywords matched (defaulted to Productivity) OR two or more industry families matched (ambiguity, e.g. "field inspections at car dealerships" hits Field/Ops + E-commerce) OR the wizard aesthetic conflicts with the inferred industry (e.g. wizard says "Warm+Organic" but keywords say Field/Ops) | Emit `INDUSTRY_CONFIRM_REQUESTED:` signal and STOP — do NOT continue to Step 3b yet |
+Always present this gate before any data-model architect dispatch. Present the
+foreground's provisional Dataverse recommendation, but let this gate make the
+first user-visible data-platform decision:
+
+```markdown
+## Gate 1 of 4 — Architecture
-**When confidence is `low`**, return early with this single line as your final message (no prose, no preamble):
+### Native Capabilities
+<capability matrix, or "None">
-```
-INDUSTRY_CONFIRM_REQUESTED: <inferred-industry>|<reason-code>|<top-3-alternatives-comma-sep>
-```
+### Connectors
+<connector table, or "None">
-Where:
-- `<inferred-industry>` — what you would have picked (e.g. `productivity`, `field-ops`)
-- `<reason-code>` — one of `no-keywords` / `ambiguous-match` / `wizard-conflict`
-- `<top-3-alternatives-comma-sep>` — the most plausible 3 other industries from the [`design-planning.md`](${PLUGIN_ROOT}/shared/references/design-planning.md) table, ordered by relevance (e.g. `field-ops,healthcare,e-commerce`)
+### Data platform
+<Dataverse | No Dataverse — connectors own data | No Dataverse — no persistent business records>
-Example signals:
-```
-INDUSTRY_CONFIRM_REQUESTED: productivity|no-keywords|field-ops,healthcare,e-commerce
-INDUSTRY_CONFIRM_REQUESTED: field-ops|ambiguous-match|e-commerce,productivity,tech-iot
+Approve this architecture before data modeling?
```
-The orchestrator will surface a one-question picker, write the chosen industry into the working dir as a hint file, and re-spawn this planner with `Industry confirmed: <industry>` added to the prompt. On the re-spawn, treat that as the locked industry — skip detection, skip the confidence check, jump straight to mapping the industry to aesthetic direction / palette / tone.
-
-## Step 3b — Plan Connectors Inline (Gate 3)
+**Before accepting Gate 1**, revalidate every native capability and storage/output
+target against the final data-platform choice and connector list. Repeat this
+check whenever either choice changes, before writing the approved artifact:
+
+- `geolocation` requires Dataverse for its durable background upload contract
+ and an existing target verified later by `/add-native geolocation`. A
+ connector-only selection cannot satisfy that contract. Resolve the choice
+ with the user in Gate 1: retain Dataverse or explicitly revise the tracking
+ requirement. One-shot `location` is not an automatic replacement.
+- For retained photos, signatures, documents, and generated PDFs without
+ Dataverse, require a supported write path in an approved connector and record
+ its storage destination. Do not substitute transient local output for required
+ persistence. Local viewing, generation, or sharing alone does not require
+ Dataverse.
+- Do not silently remove capabilities, change data platforms, or discard a
+ persistence requirement. Keep incompatible rows pending, explain the specific
+ mismatch, revise the affected architecture with the user, and revalidate.
+ Write the approved artifact only after the compatible combination is accepted.
+
+- **Approved:** write the exact selected mode, native-capability section, and
+ connector section to `<working_dir>/.tmp/approved-architecture.md`, then
+ return `NEEDS_CONTEXT: dataverse-planning-mode:<required|connector-only>`.
+ Include the selected data-platform label, `Dataverse planning mode: required`
+ or `Dataverse planning mode: connector-only`, the unchanged
+ `## Native Capabilities` and `## Connectors` sections, and the actual user
+ acceptance as `Approved by: user` plus `Approved at: <ISO timestamp>`.
+ The foreground creates Dataverse evidence only for `required` and
+ re-dispatches with `Architecture phase: complete`.
+- **Rejected capabilities:** revise only the capability matrix and re-present
+ Gate 1.
+- **Rejected connectors:** revise only the connector list and re-present Gate 1.
+- **Changed data platform or connector list during review:** update the selection
+ in the same gate, rerun the capability/storage checks above, and obtain
+ acceptance of the resulting compatible architecture before writing the artifact.
+
+## Step 5 — Build Data Model
+
+Branch on the Gate 1-approved data platform:
+
+### Connector-only
+
+Do not dispatch `mobile-app:data-model-architect`. Write an explicit
+`## Data Model` section stating that Dataverse is not used, there are zero
+Dataverse tables, and the approved connectors own persistence (or that the app
+has no persistent business records). Do not create
+`.tmp/dataverse-schema-contract.json` or a data-model approval receipt. Gate 2
+is auto-skipped as not applicable.
+
+### Dataverse required
+
+Only now dispatch `mobile-app:data-model-architect` with the locked
+architecture inputs:
+
+> Requirements: [paste confirmed requirements]
+> Wizard answers: [target users & device, aesthetic, features]
+> Target platforms: iOS and Android
+> Approved native capabilities: [paste the exact approved `## Native Capabilities` section]
+> Approved connectors: [paste the exact approved `## Connectors` section]
+> Connectivity intent policy: follow `${PLUGIN_ROOT}/shared/references/connectivity-intent-ownership.md`
+> Target environment: use the foreground-resolved environment URL and tenant
+> Working directory: [absolute path]
+> Plugin root: ${PLUGIN_ROOT}
+> Dataverse planning mode: required
+> Normalized Dataverse foreground planning snapshot: [absolute path supplied by foreground verbatim]
+> Dataverse planning evidence: [absolute path supplied by foreground verbatim]
+> Structured schema contract output: `<working_dir>/.tmp/dataverse-schema-contract.json`
+
+The architect must account for approved capture/storage targets and avoid
+duplicating entities owned by approved connectors. Wait for its return and
+apply the standard status switch:
+
+- `DONE` or `DONE_WITH_CONCERNS:` — require `_dm_section.md` and the normalized
+ schema contract, then continue.
+- `NEEDS_CONTEXT: detailed-dataverse-metadata:<logical names>` or
+ `NEEDS_CONTEXT: proposed-dataverse-names:<logical names>` — return the exact
+ signal to the foreground for one bounded expansion.
+- Other `NEEDS_CONTEXT:` — re-dispatch once with the missing context and the
+ same approved architecture sections.
+- `BLOCKED:` — propagate as a substantive planner block.
+
+## Design Planning
**Print before starting:**
-> "→ [3/4] Inferring connector needs from requirements…"
+> "→ Inferring design context for the later design-system phase…"
-Follow [`shared/references/connector-planning.md`](${PLUGIN_ROOT}/shared/references/connector-planning.md) exactly. The three steps are:
+Follow [`shared/references/design-planning.md`](${PLUGIN_ROOT}/shared/references/design-planning.md) exactly:
-1. **Infer** — scan requirements and wizard answers for connector keywords. Build a candidate list without asking the user yet.
-2. **Confirm** — present the inferred list via `AskUserQuestion`. Let the user add, remove, or confirm. If nothing was inferred, ask cold ("Does your app need any external services?").
-3. **Record** — build the `## Connectors` section (table or "None" line).
+1. **Detect** — scan requirements and the wizard aesthetic answer for design
+ keywords and industry signals.
+2. **Decide** — map the industry to aesthetic direction, palette, copy tone,
+ and visual language. Always produce a complete `## Design` section.
+3. **Summarise** — write the section without another confirmation. The
+ foreground design-system phase owns user-facing visual selection.
-**Key rule:** Dataverse is NOT a connector. If requirements mention custom business data / tables, that belongs in `## Data Model`, not `## Connectors`.
+Store the design decision for `screen-planner`.
+
+### Industry inference confidence
+
+After detection, classify confidence. Skip this check when
+`Design vibe opt-in` is `yes`, `done`, `deferred`, or `skip`.
-Application Insights telemetry is also NOT a connector. Exclude it from Gate 3 and allow planning to proceed with the actual business connectors. The customer-owned Application Insights resource is configured separately through the `/setup-app-insights` skill (standalone or via `/edit-app`).
+| Confidence | When | Action |
+|---|---|---|
+| `high` | The user supplied a non-default aesthetic, brand/color cue, or exactly one industry family matched | Proceed silently |
+| `low` | No industry matched, multiple industries matched, or the wizard aesthetic conflicts with the inferred industry | Return `INDUSTRY_CONFIRM_REQUESTED:` |
-Store the confirmed connector list — you will pass it to `screen-planner` in Step 4.
+For low confidence, return only:
+
+```
+INDUSTRY_CONFIRM_REQUESTED: <inferred-industry>|<no-keywords|ambiguous-match|wizard-conflict>|<top-3-alternatives-comma-sep>
+```
-## Step 4 — Assemble `native-app-plan.md`
+The foreground asks one industry question and re-dispatches with
+`Industry confirmed: <industry>`. Treat that value as locked.
-Write `<working_dir>/native-app-plan.md` with this structure. Use the architects' output verbatim for their sections. Leave `## Screens` empty for now — it is filled after Gate 3 approval (Step 5, screen-planner).
+## Step 6 — Assemble `native-app-plan.md`
+
+Write `<working_dir>/native-app-plan.md` with this structure. Use the
+architects' output verbatim for their sections. Leave `## Screens` empty for
+the later screen-planning gates.
**HARD RULES — plan structure (read before writing):**
1. **Top-level headings are EXACTLY the eight below.** Do NOT invent a `## Brief` super-section that nests the data model, discovery notes, or sample notes under it. Each section is its own `## ` heading.
@@ -328,27 +412,27 @@ Write `<working_dir>/native-app-plan.md` with this structure. Use the architects
<verbatim $ARGUMENTS>
## Data Model
-<verbatim from data-model-architect>
+<verbatim from data-model-architect, or the explicit zero-table connector-only section>
## Native Capabilities
<your matrix from Step 3>
## Design
-<your ## Design section from Step 3c — always a full block with all 8 decision fields; never just a label>
+<your ## Design section from Design Planning — always a full block with all 8 decision fields; never just a label>
## Connectors
-<your table from Step 3b — or "None">
+<your table from Step 4 — or "None">
## Screens
<!-- populated after Gate 3 approval -->
-## Approval Status
+## Approvals
- [ ] Data model approved
- [ ] Native capabilities approved
-- [ ] Design approved (via screen preview at Gate 4)
+- [ ] Design approved (during `/design-system`, or at Gate 4 only when HTML preview rendering is enabled)
- [ ] Connectors approved
- [ ] Screen plan approved
-- [ ] Cross-entity reads approved (Gate 1 addendum — auto-skipped if no `related_entity_fields` in plan)
+- [ ] Cross-entity reads approved (Gate 2 addendum — auto-skipped for connector-only or when no `related_entity_fields` exist)
## Plan Provenance
- Generated by: native-app-planner
@@ -356,16 +440,23 @@ Write `<working_dir>/native-app-plan.md` with this structure. Use the architects
- Date: <today>
```
-## Step 5 — Four Approval Gates
+## Step 7 — Remaining Approval Gates
+
+Gate 1 already locked the data platform, native capabilities, and connectors.
+Run Gate 2 only for Dataverse-backed apps, then continue to the screen graph and
+screen-spec gates. A rejection changes only its owning section.
-Enter plan mode four times. **Each gate is independent.** A rejection on one gate means revise that section only and re-enter plan mode for it. Do not move on until each section is explicitly approved.
+### Gate 2 — Data Model
-### Gate 1 — Data Model
+**Auto-skip rule:** in `connector-only` mode, do not enter plan mode, do not
+dispatch or re-dispatch `data-model-architect`, and do not create a schema
+contract or data-model approval receipt. Mark the Data Model section
+`not applicable — no Dataverse` and continue to screen planning.
-Call `EnterPlanMode` and present:
+For `required` mode, call `EnterPlanMode` and present:
```
-## Gate 1 of 3 — Data Model
+## Gate 2 of 4 — Data Model
[reuse/extend/create table]
[Mermaid ER diagram]
@@ -380,51 +471,26 @@ Call `ExitPlanMode` to request approval.
initialize/update `<working_dir>/.tmp/mobile-plan-status.json` with the
normalized contract's exact content/hash and a `dataModel` approval record.
This receipt is written by this gate-owning planner, never by the Step 8
- manifest builder. Continue to Gate 2.
+ manifest builder. Continue to screen planning.
- **Rejected:** re-spawn `data-model-architect` with the user's feedback and
the original planning-snapshot/evidence paths verbatim, regenerate that section, and
regenerate/normalize the structured sidecar, then re-enter plan mode. Loop
- until approved; do not run discovery during a revision.
-
-### Gate 2 — Native Capabilities + Connectors (combined)
-
-**Auto-skip rule:** if native capabilities = "None" AND connectors = "None", mark both approved without entering plan mode. Print:
-> "→ Gate 2 auto-approved — no native capabilities or external connectors. Proceeding to screen planning."
-
-Then continue directly to Step 5b.
-
-**Otherwise**, present a single combined gate (one `EnterPlanMode` cycle instead of two):
+ until approved; do not run discovery during a revision. Every revision must
+ retain the Gate 1-approved native capabilities and connectors as architect
+ inputs.
-```
-## Gate 2 of 3 — Device Capabilities + Integrations
-
-### Native Capabilities
-[capability matrix, or "None"]
-
-### Connectors
-[connector table, or "None"]
-
-Approve both? (Reject capabilities → revise matrix only. Reject connectors → revise connector list only.)
-```
+### Gates 3 and 4 — Screen Plan
-- **Approved:** mark `[x] Native capabilities approved` + `[x] Connectors approved` in plan doc. Continue to Step 5b.
-- **Rejected (capabilities only):** revise matrix, re-present combined gate.
-- **Rejected (connectors only):** re-run connector inference with feedback, re-present combined gate.
+Gate 3 locks the graph; Gate 4 approves its expanded specs.
-> **Why combined:** native caps and connectors are reviewed together in practice — they are both "what external systems does this app touch?" questions. Merging eliminates one full `EnterPlanMode`/`ExitPlanMode` cycle (~1–2 min) with zero information loss.
-
-### Gate 3 → renamed to Screen Plan (was Gate 4)
-
-See Step 5b + Step 5 Gate 4 below. Numbering shifts by one because Gates 2+3 are now merged.
-
-### Step 5b — Spawn `screen-planner` (two-phase: graph → specs)
+### Screen planning — spawn `screen-planner` in two phases
**Print before spawning:**
> "→ [4/4] Spawning screen-planner (phase 1/2: screen graph + shared conventions)…"
-Only run after Gate 3 is approved. Gate 4 is split into two cheaper gates:
-- **Gate 4a (graph)** — user approves the screen list, navigation, and shared conventions BEFORE any per-screen spec text is generated. Catches missing/extra screens cheaply.
-- **Gate 4b (specs)** — user approves expanded per-screen specs + Open Questions + (optional) HTML preview. Re-uses the locked graph; never regenerates it.
+Only run after Gate 2 is approved or auto-skipped. Screen planning has two bounded approvals:
+- **Gate 3 (graph)** — user approves the screen list, navigation, and shared conventions BEFORE any per-screen spec text is generated. Catches missing/extra screens cheaply.
+- **Gate 4 (specs)** — user approves expanded per-screen specs + Open Questions. Re-uses the locked graph; never regenerates it.
This cuts the cost of a screen-list rejection from "regenerate everything" to "regenerate just the specs."
@@ -436,6 +502,8 @@ Pass the data model + connectors + design + an explicit `phase: graph`:
You are the screen-planner agent. PHASE 1 OF 2 — graph only.
phase: graph
+plan_path: <working_dir>/native-app-plan.md
+skip_preview: true
Requirements: [paste $ARGUMENTS]
Wizard answers: [target users & device, target platforms, aesthetic, features]
@@ -445,6 +513,9 @@ Plugin root: ${PLUGIN_ROOT}
Approved data model:
[paste ## Data Model section verbatim]
+Approved native capabilities:
+[paste ## Native Capabilities section verbatim]
+
Approved design:
[paste ## Design section verbatim]
@@ -456,21 +527,21 @@ Follow your agent file. In `phase: graph`, you write ONLY:
- Screen Map (table)
- Navigation Contracts (table)
- Shared Conventions (Step 3.5)
-Do NOT write per-screen specs, Open Questions, Standard Imports, or any preview. Stop after Step 3.5 and return.
+Do NOT write per-screen specs, Open Questions, Standard Imports, or any preview. Run Step 5b's graph-only completeness repair after Step 3.5 and before Step 5 writes the graph; only then return for Gate 3 approval.
Return per AGENTS.md rule #10: literal first line is `DONE` / `DONE_WITH_CONCERNS:` / `NEEDS_CONTEXT:` / `BLOCKED:`, then a blank line, then your one-line summary.
```
Wait for return; apply the Step 3.0 status switch. Embed the partial output verbatim into `## Screens` in `native-app-plan.md`.
-#### Gate 4a — Screen Graph (structural)
+#### Gate 3 — Screen Graph (structural)
**Print before entering plan mode:**
-> "→ Gate 4a of 4 — Screen graph review. This is the cheap gate — catch missing or extra screens NOW, before specs are written."
+> "→ Gate 3 of 4 — Screen graph review. This is the cheap gate — catch missing or extra screens NOW, before specs are written."
EnterPlanMode with the locked graph (Navigation + Screen Map + Navigation Contracts + Shared Conventions) prefixed with:
-> "This is a graph-only review. Add/remove screens, change archetypes, rename routes, or revise shared conventions here. Per-screen specs (layouts, fields, animations, states) come at Gate 4b after this is locked. Approve when the screen list and conventions are right."
+> "This is a graph-only review. Add/remove screens, change archetypes, rename routes, or revise shared conventions here. Per-screen specs (layouts, fields, animations, states) come at Gate 4 after this is locked. Approve when the screen list and conventions are right."
Reject loop = re-spawn with `phase: graph` and the user's feedback. Approve = proceed to 5b.2.
@@ -479,19 +550,25 @@ Reject loop = re-spawn with `phase: graph` and the user's feedback. Approve = pr
**Print before spawning:**
> "→ [4/4] Spawning screen-planner (phase 2/2: per-screen specs)…"
-Re-spawn the planner. The locked graph is already in `_screens_section.md`; the planner reads it as input and only appends:
+Re-spawn the planner with the canonical `native-app-plan.md`; read its `## Screens` section
+as the locked graph. `_screens_section.md` remains graph-only scratch and is
+not the specs input or output.
```
You are the screen-planner agent. PHASE 2 OF 2 — specs only.
phase: specs
+plan_path: <working_dir>/native-app-plan.md
+skip_preview: <true for deferred/skip design; false only for the explicitly selected legacy preview mode>
-The screen graph + shared conventions are already locked in <working_dir>/_screens_section.md — read them and treat them as immutable. Do NOT add, remove, or rename screens. Do NOT change shared conventions.
+The screen graph + shared conventions are already locked in plan_path's ## Screens section. Read that section and treat it as immutable. Do NOT add, remove, or rename screens, change routes, or change shared conventions. Run the read-only completeness check before writing; missing graph requirements return NEEDS_CONTEXT: graph missing <thing>. Replace only the phase-owned subsections in plan_path using screen-planner Step 5, including any Step 6 summary in the same update. On retries remove stale owned sections rather than appending duplicates; do not update _screens_section.md.
Requirements: [paste $ARGUMENTS]
Approved data model: [paste ## Data Model section verbatim]
+Approved native capabilities: [paste ## Native Capabilities section verbatim]
Approved design: [paste ## Design section verbatim]
Approved connectors: [paste ## Connectors section verbatim]
+Connectivity intent policy: follow `${PLUGIN_ROOT}/shared/references/connectivity-intent-ownership.md`
Working directory: [absolute path]
Plugin root: ${PLUGIN_ROOT}
@@ -504,19 +581,33 @@ Style-picker + preview rules unchanged — honour the same `skip_preview` policy
Return per AGENTS.md rule #10.
```
-Wait for return; apply the Step 3.0 status switch. The planner appends specs + (optional) markdown screen-graph or HTML preview to `_screens_section.md` and `native-app-plan.md`.
+On `NEEDS_CONTEXT: graph missing <thing>`, handle graph recovery before the generic
+Step 3.0 retry: mark the screen graph and specs approvals pending, preserving the
+other approved sections. Re-dispatch `phase: graph` with the previous graph, approved
+requirements, and missing items. Reopen Gate 3 and require fresh user approval;
+merge the newly approved graph, then re-dispatch `phase: specs` and review Gate 4.
+Do not retry specs against the unchanged incomplete graph or reuse the old screen
+approval records for a changed graph.
+
+For other returns, apply the Step 3.0 status switch. The planner writes specs only into `plan_path`.
+Keep the approved graph and `_screens_section.md` unchanged. Any explicitly
+selected legacy HTML preview is a separate preview artifact, never a reason
+to write specifications to the graph scratch file.
-#### Gate 4b — Screen Specs (visual + spec review)
+#### Gate 4 — Screen Specs
-Proceed to the existing Gate 4 logic below (preview-path emission, plan-mode entry, reject loop). The only difference is the gate's name in the user-facing prompt: print `## Gate 4b of 4 — Screen specs` instead of `## Gate 3 of 3 — Screens`. Reject loop in 4b re-spawns with `phase: specs` only; the locked graph from 4a is preserved unless the user explicitly asks to revise screens (in which case bounce back to 4a).
+Proceed to the Gate 4 review logic below. Print `## Gate 4 of 4 — Screen specs`.
+Its reject loop re-spawns with `phase: specs` only; preserve the Gate 3 graph
+unless the user explicitly asks to revise destinations, routes, or shared
+conventions, in which case return to Gate 3.
-### Gate 4 — Screen Plan (structural review, no HTML preview)
+### Gate 4 — Screen Specs Review (no HTML preview)
-**Step 0 — Design context.** Design vibe selection has moved to `/design-system` (Step 6.75 of the orchestrator), which runs AFTER planning completes. **Gate 3 (screen plan) is a STRUCTURAL review only — no HTML preview.** The visual preview lives at Step 6.75 after brand tokens are locked, so the user only ever sees one render with the right colors instead of a default-tokens render here that gets overwritten in 5 minutes.
+**Step 0 — Design context.** Design vibe selection has moved to `/design-system` (Step 6.75 of the orchestrator), which runs AFTER planning completes. **Gates 3 and 4 review structure and specs only — no HTML preview.** The visual preview lives at Step 6.75 after brand tokens are locked, so the user only ever sees one render with the right colors instead of a default-tokens render here that gets overwritten in 5 minutes.
Branch on the orchestrator's `Design vibe opt-in:` value:
-- **`Design vibe opt-in: deferred`** (default — `/design-system` handles design at Step 6.75) — spawn `screen-planner` with **`skip_preview: true`**. It writes only `_screens_section.md` (specs + markdown screen-graph) — no `_plan_preview.html`. The orchestrator's Step 6.75 will spawn screen-planner again WITHOUT `skip_preview` after `/design-system` locks the brand, so the single HTML preview gets rendered with real tokens. Skip Step A below entirely (no `PLAN_PREVIEW_PATH:` emission); jump to Step B.
+- **`Design vibe opt-in: deferred`** (default — `/design-system` handles design at Step 6.75) — pass **`skip_preview: true`** to the specs dispatch above. It replaces only specs-owned content in `native-app-plan.md`; the approved graph scratch remains unchanged and no `_plan_preview.html` is written. Do not dispatch the completed specs phase a second time merely to review it. The foreground design-system phase owns the later visual preview. Skip Step A below entirely (no `PLAN_PREVIEW_PATH:` emission); jump to Step B.
- **`Design vibe opt-in: done`** — the orchestrator has already written `## Design Direction` into the plan via the legacy text picker (only happens when `/design-system` is NOT installed). Spawn `screen-planner` WITHOUT `skip_preview`. It generates the HTML preview as before. Continue to Step A.
@@ -534,7 +625,7 @@ PLAN_PREVIEW_PATH: file://<absolute-working-dir>/_plan_preview.html
The orchestrator greps for the `PLAN_PREVIEW_PATH:` prefix in the planner's return value to know which file to open. **Skip this emission entirely when `skip_preview: true` was passed** — the orchestrator's Step 3b is wired to short-circuit on no-token-emitted; emitting a path that doesn't exist would cause the open to fail with a confusing 404.
-**Step B — Enter plan mode** with the screen table + per-screen specs prefixed with `## Gate 3 of 3 — Screens`. Note text differs by mode:
+**Step B — Enter plan mode** with the screen table + per-screen specs prefixed with `## Gate 4 of 4 — Screen Specs`. Note text differs by mode:
- **`skip_preview` mode (deferred / skip)**: Use this note at the top:
@@ -548,14 +639,17 @@ The orchestrator greps for the `PLAN_PREVIEW_PATH:` prefix in the planner's retu
In `skip_preview` mode, this gate covers **screen plan only** — design is approved separately at Step 6.75. In HTML-preview mode, this gate covers **both** (legacy combined gate).
-Reject loop = re-spawn `screen-planner` with the user's feedback (layout, screen names, navigation, and — in HTML-preview mode — design). Re-emit the `PLAN_PREVIEW_PATH:` line before re-entering plan mode if you generated HTML; skip the emission if `skip_preview` was set. If the user requests data-model or connector changes via screen feedback, re-approve those gates first — never silently revise an already-approved section. **After re-approving an earlier gate, MUST re-spawn `screen-planner` with the updated data model/connector sections before re-entering Gate 4** — otherwise screen specs are stale and reference the old service list.
+Reject loop = re-spawn `screen-planner` with the user's feedback (layout, screen names, navigation, and — in HTML-preview mode — design). Re-emit the `PLAN_PREVIEW_PATH:` line before re-entering plan mode if you generated HTML; skip the emission if `skip_preview` was set. If the user requests data-model or connector changes via screen feedback, re-approve those gates first — never silently revise an already-approved section. **After re-approving an earlier gate, MUST re-spawn `screen-planner` with the updated data model/connector sections before re-entering Gate 4** — otherwise screen specs are stale and reference the old service list. Return to Gate 3 first when the change alters destinations, routes, or shared conventions.
### Step 5c — Cross-entity Read Audit (Round 2 data-model pass)
**Print before spawning:**
> "→ Auditing the locked screen plan for supported cross-entity read paths…"
-**Run condition:** execute this step ONLY after Gate 4b has been approved AND the screen-planner's per-screen specs include at least one `related_entity_fields` block. Skip silently otherwise.
+**Run condition:** execute this step ONLY in `required` mode, after Gate 4 has
+been approved, and when the screen-planner specs include at least one
+`related_entity_fields` block. In `connector-only`, skip this step and never
+dispatch `data-model-architect`. Skip silently when no related fields exist.
**Detection (cheap):** before spawning, `Grep` the locked plan for `related_entity_fields:` in `<working_dir>/native-app-plan.md`. Zero matches → skip Step 5c entirely, mark `[x]` and proceed to Step 6. One or more matches → spawn the audit pass below.
@@ -572,7 +666,7 @@ You are the data-model-architect agent. ROUND 2 — cross-entity audit only.
mode: cross-entity-audit
-The data model from Round 1 is already locked at <working_dir>/_dm_section.md (and embedded in <working_dir>/native-app-plan.md → ## Data Model). The screen plan from Gate 4b is at <working_dir>/native-app-plan.md → ## Screens. Read both. Run ONLY Step 6a (Cross-entity Read Audit) — skip Steps 1–6 (the data model is already done) and skip Step 7 (the section is already written; you append a new ### Cross-entity Reads subsection to it instead).
+The data model from Round 1 is already locked at <working_dir>/_dm_section.md (and embedded in <working_dir>/native-app-plan.md → ## Data Model). The screen plan from Gate 4 is at <working_dir>/native-app-plan.md → ## Screens. Read both. Run ONLY Step 6a (Cross-entity Read Audit) — skip Steps 1–6 (the data model is already done) and skip Step 7 (the section is already written; you append a new ### Cross-entity Reads subsection to it instead).
Working directory: [absolute path]
Plugin root: ${PLUGIN_ROOT}
@@ -585,16 +679,16 @@ Return per AGENTS.md rule #10.
Wait for return; apply the Step 3.0 status switch:
- `DONE` (no cross-entity reads) → mark Step 5c done, proceed to Step 6.
-- `DONE` with addendum written → re-mirror the updated `## Data Model` section into `native-app-plan.md` (architect writes `_dm_section.md`; you embed it). Continue to Gate 1 addendum below.
+- `DONE` with addendum written → re-mirror the updated `## Data Model` section into `native-app-plan.md` (architect writes `_dm_section.md`; you embed it). Continue to Gate 2 addendum below.
- `DONE_WITH_CONCERNS: <list>` → embed addendum, propagate concerns into your own final `DONE_WITH_CONCERNS:`.
- `NEEDS_CONTEXT:` / `BLOCKED:` — propagate up per the standard switch.
-#### 5c.2 — Gate 1 addendum (cross-entity read paths)
+#### 5c.2 — Gate 2 addendum (cross-entity read paths)
-If 5c.1 wrote a `### Cross-entity Reads` addendum, present it to the user as a Gate 1 addendum (NOT a fresh Gate 1 — the original schema is already approved and unchanged):
+If 5c.1 wrote a `### Cross-entity Reads` addendum, present it to the user as a Gate 2 addendum (not a fresh Gate 2 — the original schema is already approved and unchanged):
```
-## Gate 1 — Addendum: Cross-entity Reads
+## Gate 2 — Addendum: Cross-entity Reads
The screen plan reads N fields from related entities. The generated SDK has no
$expand, so each field must use a formatted lookup, a bounded chained fetch, or
@@ -608,10 +702,10 @@ Approve these read paths? Any `external-projection-required` row remains a
blocker until the user supplies that projection outside this workflow.
```
-Reject loop = re-spawn data-model-architect in `mode: cross-entity-audit` with the user's feedback (e.g. "drop cr3e9_tailnumber_calc, the list doesn't actually show it"). Approve = mark `[x]` Gate 1 addendum approved, proceed to Step 6.
+Reject loop = re-spawn data-model-architect in `mode: cross-entity-audit` with the user's feedback (e.g. "drop cr3e9_tailnumber_calc, the list doesn't actually show it"). Approve = mark `[x]` Gate 2 addendum approved, proceed to Step 6.
-**Auto-skip rule:** if Step 5c.1 returned "no cross-entity reads required" (zero `related_entity_fields` blocks across all screens), skip Gate 1 addendum entirely. Print:
-> "→ Gate 1 addendum auto-skipped — no cross-entity reads in the screen plan."
+**Auto-skip rule:** if Step 5c.1 returned "no cross-entity reads required" (zero `related_entity_fields` blocks across all screens), skip Gate 2 addendum entirely. Print:
+> "→ Gate 2 addendum auto-skipped — no cross-entity reads in the screen plan."
## Step 6 — Validate written artifacts
@@ -644,7 +738,7 @@ deterministic shape:
"approvals": {
"dataModel": {
"status": "approved",
- "approvedAt": "<ISO timestamp from Gate 1 acceptance>",
+ "approvedAt": "<ISO timestamp from Gate 2 acceptance>",
"approvedContractSha256": "<sha256 of stable normalized contract content>"
},
"nativeCapabilities": {
@@ -679,9 +773,10 @@ intersect declarations in the normalized schema contract. If the final screen
plan introduces a service not present there, revise and re-approve the affected
earlier section rather than silently changing the contract.
-Initialize the receipt when Gate 1 is accepted, then advance its other approval
-records, current plan hash, and final service dependencies only when this same
-planner accepts the corresponding existing gates. Before revising an approved
+In `required` mode, initialize the receipt when Gate 2 is accepted, including
+the already approved Gate 1 native-capability and connector records. Advance
+the current plan hash and final service dependencies only when this same
+planner accepts the corresponding later gates. Before revising an approved
section, mark that section and dependent later sections non-approved; refresh
the receipt only after the existing approval loop accepts the revision.
Do not call the manifest builder to create or restamp this receipt. The local
@@ -702,7 +797,7 @@ You MUST return your final message to `/create-mobile-app` with one of these fou
| Code | When to use | Example first line |
|---|---|---|
-| `DONE` | All 4 gates passed cleanly, plan written, no caveats | `DONE` |
+| `DONE` | All applicable gates passed cleanly, plan written, no caveats | `DONE` |
| `DONE_WITH_CONCERNS: <comma-separated concerns>` | Plan written and gates approved, but a sub-architect returned `DONE_WITH_CONCERNS` you propagated, or the user approved with explicit reservations | `DONE_WITH_CONCERNS: data-model-architect could not verify contact reuse, screen-planner used Tamagui default tokens` |
| `NEEDS_CONTEXT: <what is missing>` | Cannot complete the plan without more info from the orchestrator — e.g. industry confidence is `low` (use the existing `INDUSTRY_CONFIRM_REQUESTED:` signal instead, this code is for cases not covered by an existing signal) | `NEEDS_CONTEXT: data-model-architect returned NEEDS_CONTEXT, requirements brief lacks entity nouns` |
| `BLOCKED: <reason>` | Hit a hard wall — sub-architect returned `BLOCKED`, plan file cannot be written, user rejected the same gate 3 times in a row, or any pre-condition (working dir, plugin root) is missing. The orchestrator MUST escalate, never silently retry | `BLOCKED: data-model-architect returned BLOCKED: cannot write _dm_section.md` |
@@ -723,7 +818,7 @@ Dataverse schema contract: <absolute path, or "not applicable">
Mobile plan approval receipt: <absolute path, or "not applicable">
Sections approved:
- ✓ Data model — <N tables: M reuse, K extend, L create>
+ ✓ Data model — <N tables: M reuse, K extend, L create; or "not applicable — no Dataverse">
✓ Native caps — <list capability names, or "none">
✓ Design — <"default" | font + brand token + theme + animation>
✓ Connectors — <list connector API names, or "none">
@@ -733,7 +828,7 @@ Next steps for the orchestrator:
1. Auth + environment selection
2. Use the user-prepared fresh template folder materialized from `microsoft/power-platform-skills/plugins/mobile-apps/template#main` with `degit`
3. npx power-apps init -t MobileApp --display-name <name> --environment-id <environment-id> --non-interactive
- 4. Apply data model via /add-dataverse using the plan
+ 4. If Dataverse was approved, apply data model via /add-dataverse using the plan
5. Apply native capabilities via /add-native using the plan
6. Apply connectors via /add-connector per connector using the plan
7. Spawn N screen-builder agents in parallel using the plan
@@ -741,6 +836,22 @@ Next steps for the orchestrator:
## Tool Permissions
-You have `Bash` only to run read-only file/HTTP/helper checks such as `node scripts/resolve-environment.js <environment-id-or-url>` when needed for context. You MUST NOT run mutating Power Apps CLI commands such as `npx power-apps init -t MobileApp --display-name <name> --environment-id <environment-id> --non-interactive`, `npx power-apps add-data-source ...`, `npx power-apps add-flow --flow-id <flow-guid> --non-interactive`, `npx power-apps push --non-interactive`, `npm install`, or any other mutation command.
-
-You have `Write` only to create `native-app-plan.md`. You MUST NOT write any other file in the project.
+Use `Bash` for the documented read-only checks and local planning-artifact
+normalization/validation only. Dataverse discovery stays foreground-owned;
+`gate-only` never performs it. Do not run app initialization, data-source or
+flow generation, dependency installation, deployment, or tenant mutations.
+
+`Write` permissions are phase-scoped beneath `<working_dir>`:
+
+- `gate-only`: write `.tmp/approved-architecture.md` only after actual Gate 1
+ acceptance, using the artifact contract above. Do not write a schema contract,
+ data-model receipt, or completed plan in this phase.
+- `complete`: write `native-app-plan.md` and update `.tmp/mobile-plan-status.json`
+ only from the corresponding user approvals. The documented normalization
+ helper may rewrite the architect-produced `.tmp/dataverse-schema-contract.json`;
+ validation scratch is limited to `.tmp/`. Leaf agents retain ownership of
+ their section outputs under their own contracts.
+
+No app source, app configuration, generated services, memory-bank, dependency,
+or out-of-project writes are allowed. A planning-artifact permission never
+grants approval or authorizes tenant mutation.
diff --git a/plugins/mobile-apps/agents/screen-builder.md b/plugins/mobile-apps/agents/screen-builder.md
index c83841d11..7313ae42d 100644
--- a/plugins/mobile-apps/agents/screen-builder.md
+++ b/plugins/mobile-apps/agents/screen-builder.md
@@ -1119,31 +1119,10 @@ Follow these whenever the spec touches navigation, list rows, or modals. Recipes
The large title collapses on scroll (iOS Settings / Mail / App Store). On Android it degrades to a standard toolbar. Pass `contentInsetAdjustmentBehavior="automatic"` to your `ScrollView` or `FlatList` so content scrolls under the collapsing header. Detail and Form screens pushed onto the stack do NOT use large title — they use `headerShown: true` with standard height.
-41. **Connectivity banner — use `@react-native-community/netinfo` (already in template).** Every app MUST show a persistent "No connection" banner when the device loses connectivity. Do NOT build this per-screen — it lives in `app/(app)/_layout.tsx` (or `src/components/ConnectivityBanner.tsx` if the orchestrator created it). If the banner primitive exists, do nothing. If your screen is the protected layout (`_layout.tsx`), wire it:
-
- ```tsx
- import NetInfo from '@react-native-community/netinfo';
- import { useTheme } from 'tamagui';
-
- const [isConnected, setIsConnected] = React.useState(true);
- const theme = useTheme();
- React.useEffect(() => {
- const unsub = NetInfo.addEventListener(state => {
- setIsConnected(state.isConnected ?? true);
- });
- return () => unsub();
- }, []);
-
- // Render above the slot/navigator:
- {!isConnected && (
- <XStack bg="$red4" px="$4" py="$2" items="center" justify="center" gap="$2">
- <Ionicons name="cloud-offline-outline" size={16} color={theme.red10.val} />
- <Text fontSize="$2" fontWeight="600" color="$red10">No connection</Text>
- </XStack>
- )}
- ```
-
- This is different from the offline *sync* bar (which tracks pending local writes). The connectivity banner is binary: connected or not. Field apps lose signal constantly — users must know before they tap Save and get a silent failure.
+41. **Connectivity UI follows the approved specification.** Apply
+ [`shared/references/connectivity-intent-ownership.md`](../shared/references/connectivity-intent-ownership.md).
+ Implement connectivity diagnostics or app-owned sync UI only when the
+ approved per-screen specification names that product feature.
42. **Layout animations on list add/remove.** Every `FlatList` that supports create or delete MUST animate insertions and removals. Wrap `renderItem` content in Reanimated `Animated.View` with `entering`, `exiting`, and `layout` props:
diff --git a/plugins/mobile-apps/agents/screen-planner.md b/plugins/mobile-apps/agents/screen-planner.md
index d7701d98b..a33a2c358 100644
--- a/plugins/mobile-apps/agents/screen-planner.md
+++ b/plugins/mobile-apps/agents/screen-planner.md
@@ -24,6 +24,9 @@ You will be invoked by `native-app-planner` in parallel with `data-model-archite
- **Read-only.** You MUST NOT write TSX, install packages, or modify any project files except your output section file.
- **Power Apps CLI failure refresh.** Follow [shared-instructions.md](../shared/shared-instructions.md) command-failure handling for any failed `npx power-apps *` command; retry the original command once after auth is corrected.
- **No questions.** The planner runs the approval gate. Make confident decisions from the inputs provided. If a detail is genuinely ambiguous, list it under "Open Questions" in your output for the planner to surface.
+- **Connectivity intent ownership.** Follow
+ [`shared/references/connectivity-intent-ownership.md`](../shared/references/connectivity-intent-ownership.md)
+ when deriving the screen graph and specifications.
- **Return a section, not a doc.** Output is a markdown `## Screens` section the planner embeds verbatim.
- **Screens only.** Do not design shared components, hooks, or services. The `screen-builder` writes shared UI inline first; refactoring happens later.
- **MANDATORY progress reporting.** Every step in the workflow below has a `**Print before starting:**` block. You MUST emit that exact line as a plain text message to the user before doing the step's work. Do not skip, do not paraphrase, do not batch them. The user has no other visibility into what you're doing — silence looks like the agent has hung. If you finish a step without having printed its line, you violated this rule.
@@ -38,19 +41,19 @@ The planner gives you:
- Features the user listed
- **`phase`** — one of `graph` | `specs` | unset (back-compat = full run, equivalent to `specs` after an inline graph)
-## Two-phase mode (Gate 4 split — PREFERRED)
+## Two-phase mode (Gates 3 and 4 — PREFERRED)
-The orchestrator splits Gate 4 into two cheaper gates so the user can edit the screen *list* before any per-screen specs are generated. Behaviour by phase:
+The orchestrator uses separate graph and specs gates so the user can edit the screen *list* before any per-screen specs are generated. Behaviour by phase:
| `phase` | What you do | What you write | What you skip | Gate that follows |
|---|---|---|---|---|
-| `graph` | Steps 0, 0b, 1, 2, 3 + Step 3.5 (Shared Conventions) only | `_screens_section.md` containing **Navigation Pattern + Screen Map + Navigation Contracts + Shared Conventions** ONLY | Steps 4, 5, 5b, 6 | Gate 4a (graph approval) |
-| `specs` | Steps 4, 5, 5b, 6 | **Append per-screen specs + Open Questions directly into `plan_path` (the `## Screens` section of `native-app-plan.md`).** Do NOT touch `_screens_section.md` — it is scratch from `phase: graph` and not read by anyone after Gate 4a. | Steps 1–3 if the locked graph is already present in `plan_path`'s `## Screens` section | Gate 4b (specs approval) |
+| `graph` | Steps 0, 0b, 1, 2, 3, 3.5, then Step 5b (repair) before Step 5 writes the graph | `_screens_section.md` containing **Navigation Pattern + Screen Map + Navigation Contracts + Shared Conventions** ONLY | Steps 4 and 6 | Gate 3 (graph approval) |
+| `specs` | Steps 0, 0b, then Step 5b (read-only preflight), followed by Steps 4, 5, 6 | **Replace the phase-owned subsections in `plan_path` once, following Step 5.** Preserve the approved graph; do NOT touch `_screens_section.md`. | Steps 1–3 and 3.5; a missing locked graph requires `NEEDS_CONTEXT`, never inline regeneration | Gate 4 (specs approval) |
| unset / legacy | All steps end-to-end | Full `_screens_section.md` in one pass | nothing | single Gate 4 (back-compat) |
-**`phase: specs` MUST read the locked graph from `plan_path` (the `## Screens` section already merged in by the orchestrator after Gate 4a).** The orchestrator may have edited screens, conventions, or routes between phases. Treat the locked graph as immutable input. Do NOT add or remove screens during `phase: specs`; if you find the graph incomplete, return `NEEDS_CONTEXT: graph missing <thing>` so the orchestrator re-runs `phase: graph`.
+**`phase: specs` MUST read the locked graph from `plan_path` (the `## Screens` section already merged in by the orchestrator after Gate 3).** The orchestrator may have edited screens, conventions, or routes between phases. Treat the locked graph as immutable input. Do NOT add, remove, or rename screens or change routes, navigation contracts, or shared conventions during `phase: specs`. If the graph is incomplete, return `NEEDS_CONTEXT: graph missing <thing>` before writing the plan or preview so the orchestrator re-runs `phase: graph` and obtains fresh Gate 3 approval before retrying specs.
-**Hard rule — single-write in `phase: specs`.** The previous behaviour of writing both `plan_path` and `_screens_section.md` doubles wall-clock time on Gate 4b (full file rewrite of a ~12 KB plan happens twice for an 8-screen app). The duplicate `_screens_section.md` write is forbidden in `phase: specs` — only the append into `plan_path` is allowed.
+**Hard rule — single-write in `phase: specs`.** Assemble the complete replacement, including the Step 6 markdown summary when requested, before one update to `plan_path`. A retry replaces the previous specs-owned output; it never adds a second copy. Do not write `_screens_section.md` or delete old sections in a separate operation before inserting their replacements.
**The scaffolded project IS available at `<working_dir>/`.** The orchestrator's Step 2d background pipeline finishes the full template scaffold (clone → fixes → npm install → `npx power-apps init -t MobileApp --display-name <name> --environment-id <environment-id> --non-interactive` → schemas → tsc smoke) in parallel with your run. By the time you start, `<working_dir>/` is populated with the complete template tree. Safe to `Glob` and `Read`:
@@ -61,7 +64,7 @@ The orchestrator splits Gate 4 into two cheaper gates so the user can edit the s
**Hard rule — read-only on the scaffolded files.** You may NEVER write to anything outside this allow-list:
-- `<working_dir>/native-app-plan.md` (your `phase: specs` append target)
+- `<working_dir>/native-app-plan.md` (your `phase: specs` replacement target)
- `<working_dir>/_screens_section.md` (your `phase: graph` write target)
- `<working_dir>/_plan_preview.html` (only when `skip_preview` is unset/false)
- `<working_dir>/.tmp/*` (scratch)
@@ -89,7 +92,7 @@ Specifically — `memory-bank.md` is OFF-LIMITS during `phase: graph` and `phase
| After Step 0 + 0b loaded | `echo "→ [screen-planner] loaded patterns + design direction"` |
| Before Step 2 (graph) or before Step 4 (specs) | `echo "→ [screen-planner] phase=<phase>, N=<screen_count> screens, est ~$((N * 60))s"` |
| Per screen during Step 4 (specs phase only) | `echo "→ [screen-planner] spec <i>/<N>: <screen_name>"` |
-| Before Step 5 write | `echo "→ [screen-planner] writing ${phase == 'graph' ? '_screens_section.md' : 'plan.md ## Screens append'}"` |
+| Before Step 5 write | `echo "→ [screen-planner] writing ${phase == 'graph' ? '_screens_section.md' : 'plan.md ## Screens replacement'}"` |
| Before Step 6 preview (if not skipped) | `echo "→ [screen-planner] rendering _plan_preview.html"` |
These are pure progress signals — never block on or check echo output. Use a single `Bash` call per milestone, not batched at the end (defeats the point).
@@ -98,7 +101,7 @@ These are pure progress signals — never block on or check echo output. Use a s
### Step 0 — Load Industry Patterns
-If the planner's prompt includes an industry (from `## Design`), read `${PLUGIN_ROOT}/shared/references/universal-patterns.md` and note which sections apply per the "When to Use This Document" table at the bottom. Incorporate relevant patterns into per-screen specs in Step 5 (e.g., sparklines in finance stat cards, offline sync bar for field apps, circular progress for health goals). Do NOT add patterns that don't match the app's purpose — only use what the industry mapping recommends.
+If the planner's prompt includes an industry (from `## Design`), read `${PLUGIN_ROOT}/shared/references/universal-patterns.md` and note which sections apply per the "When to Use This Document" table at the bottom. Incorporate relevant patterns into per-screen specs in Step 5 (e.g., sparklines in finance stat cards or circular progress for health goals). Do NOT add patterns that don't match the app's purpose — only use what the industry mapping recommends.
### Step 0b — Load Design Direction (if present)
@@ -251,7 +254,7 @@ Every generated signed-in app MUST include a Profile screen and place sign-out t
**Print before starting:**
> "→ Locking shared conventions (row style, field order, hero treatments) before specs…"
-Before any per-screen spec is written, decide and lock the cross-screen conventions. These travel with the graph through Gate 4a so the user reviews them ONCE — every spec then expands within these locked rails.
+Before any per-screen spec is written, decide and lock the cross-screen conventions. These travel with the graph through Gate 3 so the user reviews them ONCE — every spec then expands within these locked rails.
Write a **Shared Conventions** subsection into `_screens_section.md` (immediately after Navigation Contracts):
@@ -459,7 +462,7 @@ For each screen the user adds, provide this compact shape:
- **Restrained or expressive** (override only) — omit unless the screen is one of the 1–2 designated expressive screens (completion states, empty onboarding). Default is `restrained` for everything else; do not emit it.
- **Refresh trigger** (override only) — List screens default to `useFocusEffect` (hard rule in screen-builder). Omit unless the screen needs a different refresh strategy (timer, websocket, manual-only).
-**Differentiation check (mandatory before writing the section):** read back your per-screen specs. If 3+ screens have identical domain decisions, row/hero overrides, and visual emphasis descriptions — the specs are too generic. Revise the domain decisions or Shared Conventions overrides until each screen has at least one layout decision that is domain-specific and different from its siblings. Do not fix this by adding repeated design boilerplate.
+**Differentiation check (mandatory before writing the section):** read back your per-screen specs. If 3+ screens have identical domain decisions, row/hero overrides, and visual emphasis descriptions — the specs are too generic. Revise the per-screen domain decisions or permitted per-screen overrides until each screen has at least one layout decision that is domain-specific and different from its siblings. In `phase: specs`, do not rewrite the locked Shared Conventions; a required graph-level change returns `NEEDS_CONTEXT: graph missing <thing>`. Do not fix this by adding repeated design boilerplate.
---
@@ -522,11 +525,31 @@ Reference data-model entities by name as the data architect proposed them — do
> "→ Assembling the ## Screens markdown section…"
**Write target by phase:**
-- `phase: specs` — read `plan_path`, locate the existing `## Screens` section (the locked graph from Gate 4a), and append the **Per-Screen Specs** + **Open Questions** subsections immediately before `## Approvals`. **Do NOT also write `_screens_section.md`** — single-write rule (see phase table above). Use one `Edit` (insert before `## Approvals`) or one `Write` of the full updated `plan_path`. Pick whichever is one operation.
-- `phase: graph` — write to `<working_dir>/_screens_section.md` as scratch for Gate 4a; orchestrator merges the approved graph into `plan_path` after Gate 4a passes.
+- `phase: specs` — read the complete `plan_path` and replace the phase-owned subsections inside its existing `## Screens` section as described below. Do not regenerate the approved graph or write `_screens_section.md`.
+- `phase: graph` — write to `<working_dir>/_screens_section.md` as scratch for Gate 3; orchestrator merges the approved graph into `plan_path` after Gate 3 passes.
- legacy / unset — write to `<working_dir>/_screens_section.md` as before.
-Section format (same in all phases):
+**Idempotent specs replacement:** prepare the final content in memory before writing.
+Remove all prior copies of the phase-owned `### Per-Screen Specs`,
+`### Open Questions` (including `### Open Questions for the User`),
+`### JavaScript Dependencies`, and the Step 6-generated `### Screen Graph` summary
+inside `## Screens`, then insert their regenerated content immediately before `## Approvals`.
+If the new pass omits an optional subsection, remove its old copy too. Match real
+Markdown headings outside fenced code blocks; each subsection ends at the next
+heading of the same or higher level. Preserve all other content, including the
+approved Navigation Pattern, Screen Map, Navigation Contracts, and Shared
+Conventions, unchanged. The derived `### Screen Graph` summary is not the locked
+Screen Map and must be regenerated from that approved map, not used to revise it.
+
+Complete Step 5b and prepare any Step 6 markdown summary before this update. Use
+one `Edit` replacing the old owned content with the final result, or one `Write`
+of the complete updated plan; never delete and insert in separate operations.
+Before committing, verify exactly one Per-Screen Specs subsection and at most one
+of each optional phase-owned subsection (the Open Questions names are alternatives),
+with the approved graph and everything outside these owned subsections unchanged.
+On a malformed or ambiguous section boundary, return `NEEDS_CONTEXT` without writing.
+
+Section format (emit only the subsections owned by the current phase):
```markdown
## Screens
@@ -667,26 +690,42 @@ Do NOT write `### Standard Imports` or `#### Resolved Imports` blocks. The orche
What you DO emit per screen: the `**Data**` field listing service+method calls (e.g. cursor list: `Cr3e9_inspectionsService.getAll({ maxPageSize: 50, orderBy: ['createdon desc', 'cr3e9_inspectionid asc'], select: [...] })`; bounded lookup: `Cr3e9_categoriesService.getAll({ top: 50, orderBy: ['name asc'], select: ['name'] })`). For cursor screens, also mark `Pagination: cursor` so the orchestrator generates the cursor skeleton.
-### Step 5b — Gate 4 completeness check (MANDATORY before return)
+### Step 5b — Phase-aware completeness check (MANDATORY before writing)
-Before writing the section (to `plan_path` in `phase: specs`, or to `_screens_section.md` in `phase: graph` / legacy) and returning to the planner, verify the screen graph is complete. Build a coverage matrix in your head (or scratch buffer):
+**`phase: specs`: read-only validation before any plan or preview write.** Check the
+approved graph before generating specs and again before committing the Step 5
+replacement. If a required screen, route, navigation contract, or shared convention
+is missing or needs changing, leave the canonical plan and graph scratch unchanged
+and return `NEEDS_CONTEXT: graph missing <thing>`. Do not repair the graph in this
+phase. The orchestrator must obtain fresh Gate 3 approval before specs resume.
-1. **Features** — every feature listed in the requirements brief MUST map to at least one screen (or to a documented exception under "Open Questions"). Walk the brief feature-by-feature and confirm.
+**`phase: graph`: repair before Gate 3.** Run this check after Step 3.5 and before
+Step 5 writes graph scratch. Add missing screens and reconcile routes, navigation
+contracts, and shared conventions within the approved requirements. The repaired
+graph is still a proposal until the user accepts Gate 3. Legacy/unset mode keeps
+its full-run completeness repair before its single screen-plan approval gate.
+
+Build a coverage matrix in memory or scratch, respecting documented user-approved
+exceptions rather than silently restoring intentionally excluded screens:
+
+1. **Features** — every feature listed in the requirements brief MUST map to at least one screen (or to a documented exception in Screen Map notes, or Open Questions in legacy mode). Walk the brief feature-by-feature and confirm.
2. **Primary entities** — every entity from the data-model architect's `## Data Model` section MUST have at least a List + Detail pair (or a documented exception, e.g. lookup-only entities like `User`, `Status`, `Category`).
3. **User actions** — every verb in the brief (create, edit, assign, approve, capture, export, …) MUST have a target screen or a Form/Sheet that hosts it. A verb with no host = a missing screen.
-If the matrix has gaps, add the missing screens NOW — do not return a partial plan and let Gate 4 catch it (the iteration loop after Gate 4 rejection is the most expensive in the whole flow). Only after the matrix is fully covered (or every gap is justified under Open Questions) may you proceed to Step 6.
+Only a complete graph (including documented exceptions) may proceed to specs output.
+Unresolved gaps return `NEEDS_CONTEXT`; they do not authorize silently changing an
+approved graph, accepting an exception on the user's behalf, or skipping approval.
Emit a one-line confirmation in your final summary so the orchestrator can verify:
> "Coverage: <F> features / <E> entities / <V> actions all mapped to screens."
## Step 6 — Generate Plan-Time Preview
-**If the planner passed `skip_preview: true` in your prompt, do NOT generate `_plan_preview.html`** — instead, append a markdown **Screen Graph** subsection to the same write target as Step 5 (`plan_path` in `phase: specs`, `_screens_section.md` otherwise) so the planner has structural content to show at Gate 4. Then jump to Return.
+**If the planner passed `skip_preview: true` in your prompt, do NOT generate `_plan_preview.html`.** In `phase: specs`, prepare a markdown **Screen Graph** summary from the locked graph and include it in the same single Step 5 replacement as the specs and Open Questions. Do not perform a later append. In legacy mode, include it in the full scratch section write. `phase: graph` skips this step entirely. Then jump to Return.
The markdown screen graph replaces the HTML preview's role at Gate 4 in `skip_preview` mode. It communicates *structure* (screen list, archetype, navigation hierarchy) without misleading visuals — the real branded HTML preview gets rendered later at Step 6.75 by the orchestrator after `/design-system` locks the brand tokens.
-**Markdown screen-graph format** (append after the per-screen specs in the same write target as Step 5):
+**Markdown screen-graph format** (include after the per-screen specs in the staged Step 5 output):
```markdown
### Screen Graph
@@ -716,7 +755,7 @@ The Hierarchy block should reflect the actual nav pattern — for `Stack`, rende
**Print before starting (`skip_preview: true` branch):**
> "→ Skipping HTML preview (Step 6.75 will render it with locked brand). Writing markdown screen-graph for Gate 4 structural review."
-Then append the markdown block to the Step 5 write target (`plan_path` in `phase: specs`, `_screens_section.md` otherwise — NEVER both) and **return — do NOT generate any HTML**.
+Commit the complete Step 5 output once (`plan_path` in `phase: specs`, `_screens_section.md` in legacy mode — NEVER both) and **return — do NOT generate any HTML**. If Step 5 already committed this composed output, do not write it again.
---
@@ -725,7 +764,7 @@ Then append the markdown block to the Step 5 write target (`plan_path` in `phase
**Print before starting:**
> "→ Generating _plan_preview.html so you can see each screen visually before code is written…"
-After writing `_screens_section.md`, generate a `preview.html` from the plan specs — before any TSX exists. This gives the planner a visual to show the user at Gate 4.
+After committing the Step 5 output, generate the HTML from the current plan specs (`plan_path` in `phase: specs`, `_screens_section.md` in legacy mode) before any TSX exists. This gives the planner a visual to show the user at Gate 4 without reading stale graph scratch in specs mode.
Load the phone frame template from `${PLUGIN_ROOT}/shared/references/tamagui-html-mapping.md` Section 4. Then for each screen in the Screen Map (excluding baseline screens marked "keep"), synthesize representative HTML using the per-screen spec:
@@ -772,4 +811,4 @@ If `skip_preview: true` was set, write instead:
If `phase: specs` was set, write instead (note: target is `plan_path`, not `_screens_section.md`):
-> Per-screen specs appended to `<plan_path>` (`## Screens` section, before `## Approvals`). `_screens_section.md` left untouched per single-write rule. Navigation: <pattern>. Total screens: <N> (<M> baseline kept from template, <K> new).
+> Per-screen specs replaced in `<plan_path>` (`## Screens` section, before `## Approvals`). Approved graph preserved; no duplicate specs-owned sections. `_screens_section.md` left untouched per single-write rule. Navigation: <pattern>. Total screens: <N> (<M> baseline kept from template, <K> new).
diff --git a/plugins/mobile-apps/scripts/lib/mobile-telemetry-dispatcher.js b/plugins/mobile-apps/scripts/lib/mobile-telemetry-dispatcher.js
index f3abecd54..8a24d7787 100644
--- a/plugins/mobile-apps/scripts/lib/mobile-telemetry-dispatcher.js
+++ b/plugins/mobile-apps/scripts/lib/mobile-telemetry-dispatcher.js
@@ -81,7 +81,11 @@ function fireAndForget(event, opts = {}) {
const optOutValue = optOutName ? env[optOutName] || '' : '';
try {
- const child = spawn(process.execPath, [__filename], {
+ const spawnProcess = opts.spawn || spawn;
+ const child = spawnProcess(process.execPath, [__filename], {
+ // Detached dispatch can outlive checkpoint CLIs. Inheriting the project
+ // cwd would keep that directory locked against deletion on Windows.
+ cwd: os.tmpdir(),
detached: true,
stdio: ['pipe', 'ignore', 'ignore'],
env: {
diff --git a/plugins/mobile-apps/scripts/tests/create-mobile-app-planning-order.test.js b/plugins/mobile-apps/scripts/tests/create-mobile-app-planning-order.test.js
new file mode 100644
index 000000000..3d0461394
--- /dev/null
+++ b/plugins/mobile-apps/scripts/tests/create-mobile-app-planning-order.test.js
@@ -0,0 +1,369 @@
+'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, '..', '..');
+const createSkill = fs.readFileSync(
+ path.join(pluginRoot, 'skills', 'create-mobile-app', 'SKILL.md'),
+ 'utf8',
+);
+const planner = fs.readFileSync(
+ path.join(pluginRoot, 'agents', 'native-app-planner.md'),
+ 'utf8',
+);
+const architect = fs.readFileSync(
+ path.join(pluginRoot, 'agents', 'data-model-architect.md'),
+ 'utf8',
+);
+const screenPlanner = fs.readFileSync(
+ path.join(pluginRoot, 'agents', 'screen-planner.md'),
+ 'utf8',
+);
+const screenBuilder = fs.readFileSync(
+ path.join(pluginRoot, 'agents', 'screen-builder.md'),
+ 'utf8',
+);
+const universalPatterns = fs.readFileSync(
+ path.join(pluginRoot, 'shared', 'references', 'universal-patterns.md'),
+ 'utf8',
+);
+const requirementsDiscovery = fs.readFileSync(
+ path.join(pluginRoot, 'skills', 'create-mobile-app', 'references', 'requirements-discovery.md'),
+ 'utf8',
+);
+const connectivityOwnership = fs.readFileSync(
+ path.join(pluginRoot, 'shared', 'references', 'connectivity-intent-ownership.md'),
+ 'utf8',
+);
+const templatePackage = JSON.parse(
+ fs.readFileSync(path.join(pluginRoot, 'template', 'package.json'), 'utf8'),
+);
+
+function section(source, start, end) {
+ const startIndex = source.indexOf(start);
+ assert.notEqual(startIndex, -1, `missing section: ${start}`);
+ const endIndex = source.indexOf(end, startIndex + start.length);
+ assert.notEqual(endIndex, -1, `missing section boundary: ${end}`);
+ return source.slice(startIndex, endIndex);
+}
+
+test('planning contracts contain no unresolved merge markers', () => {
+ for (const source of [createSkill, planner, architect, screenPlanner, screenBuilder]) {
+ assert.doesNotMatch(source, /^(?:<{7}|={7}|>{7})(?: |$)/m);
+ }
+});
+
+test('connectivity wording is owned by the post-materialization offline flow', () => {
+ const classification = section(
+ createSkill,
+ 'Infer a provisional Dataverse planning mode before Step 2c',
+ '**Design decisions are deferred to Step 6.75**',
+ );
+ assert.match(classification, /connectivity-intent-ownership\.md/i);
+ assert.doesNotMatch(classification, /Dataverse offline data/);
+ for (const source of [planner, architect, screenPlanner, screenBuilder, requirementsDiscovery]) {
+ assert.match(source, /connectivity-intent-ownership\.md/i);
+ }
+ assert.match(
+ connectivityOwnership,
+ /offline-first[\s\S]*limited or[\s\S]*intermittent connectivity[\s\S]*no connectivity/i,
+ );
+ assert.match(connectivityOwnership, /operating\s+context only/i);
+ assert.match(
+ connectivityOwnership,
+ /must not add offline-specific business tables[\s\S]*services[\s\S]*stores[\s\S]*routes[\s\S]*screens/i,
+ );
+ assert.equal(
+ typeof templatePackage.dependencies['@microsoft/power-apps-native-offline'],
+ 'string',
+ );
+ assert.match(
+ connectivityOwnership,
+ /power-apps-native-host[\s\S]*local SQLite[\s\S]*status overlay/i,
+ );
+ assert.match(universalPatterns, /approved product requirement.*app-owned sync queue/is);
+ assert.doesNotMatch(requirementsDiscovery, /Camera capability \+ image column/);
+});
+
+test('the wizard targets iOS and Android without asking a platform question', () => {
+ const gatherRequirements = section(
+ createSkill,
+ '### Step 2 — Gather requirements',
+ '### Step 2b — Requirements discovery',
+ );
+ assert.doesNotMatch(gatherRequirements, /\| Target platforms \|/);
+ assert.match(gatherRequirements, /<target_platforms> = "ios, android"/i);
+ assert.match(gatherRequirements, /do not ask.*iOS.*Android/is);
+});
+
+test('data platform and integrations are approved before Dataverse modeling', () => {
+ const modeQuestion = createSkill.indexOf('**Question header:** `Data platform`');
+ const architecturePass = createSkill.indexOf('### Architecture gate');
+ const prefixDetection = createSkill.indexOf('Now execute the deferred Step 1.7');
+ const snapshot = createSkill.indexOf('### Foreground Dataverse planning snapshot');
+ assert.equal(modeQuestion, -1);
+ assert.ok(architecturePass > 0 && architecturePass < prefixDetection);
+ assert.ok(prefixDetection < snapshot);
+ assert.match(
+ section(createSkill, '### Architecture gate', '### Foreground Dataverse planning snapshot'),
+ /Dataverse planning snapshot: NOT SUPPLIED[\s\S]*approved-architecture\.md/i,
+ );
+ assert.match(
+ section(createSkill, '### Foreground Dataverse planning snapshot', '**Hard rule — planner writes'),
+ /Gate 1-approved[\s\S]*<dataverse_planning_mode>/i,
+ );
+
+ const architectureGate = planner.indexOf(
+ '### Gate 1 — Data Platform + Device Capabilities + Integrations',
+ );
+ const nativePlanning = planner.indexOf('## Step 3 — Plan Native Capabilities Inline');
+ const connectorPlanning = planner.indexOf('## Step 4 — Plan Connectors Inline');
+ const architectDispatch = planner.indexOf('## Step 5 — Build Data Model');
+ const dataModelGate = planner.indexOf('### Gate 2 — Data Model');
+ const screenGraphGate = planner.indexOf('#### Gate 3 — Screen Graph');
+ const screenSpecsGate = planner.indexOf('### Gate 4 — Screen Specs Review');
+ assert.ok(nativePlanning > 0 && nativePlanning < connectorPlanning);
+ assert.ok(connectorPlanning < architectureGate);
+ const connectorSection = planner.slice(connectorPlanning, architectureGate);
+ assert.doesNotMatch(connectorSection, /AskUserQuestion|ask cold/i);
+ assert.match(connectorSection, /Approve in Gate 1/i);
+ assert.ok(architectureGate > 0 && architectureGate < architectDispatch);
+ assert.ok(architectDispatch < dataModelGate);
+ assert.ok(dataModelGate < screenGraphGate && screenGraphGate < screenSpecsGate);
+ assert.match(
+ planner,
+ /connector-only[\s\S]*data-model-architect/i,
+ );
+ assert.match(planner, /Approved native capabilities:[\s\S]*Approved connectors:/i);
+ assert.match(architect, /approved native capabilities/i);
+ assert.match(architect, /approved connectors/i);
+ assert.match(architect, /do not create a Dataverse duplicate of a connector-owned entity/i);
+ assert.match(
+ createSkill,
+ /architecture-only pass[\s\S]*NEEDS_CONTEXT: dataverse-planning-mode:<required\|connector-only>/i,
+ );
+ assert.match(
+ planner,
+ /Run condition:[\s\S]*ONLY in `required` mode[\s\S]*In `connector-only`[\s\S]*never[\s\S]*dispatch `data-model-architect`/i,
+ );
+ assert.doesNotMatch(`${planner}\n${architect}\n${screenPlanner}`, /Gate 4a|Gate 4b/);
+ assert.match(
+ architect,
+ /BLOCKED: This step only applies when Dataverse is selected/i,
+ );
+});
+
+test('screen specs use the canonical approvals heading as their insertion anchor', () => {
+ assert.match(planner, /^## Approvals$/m);
+ assert.doesNotMatch(planner, /^## Approval Status$/m);
+ assert.match(screenPlanner, /immediately before `## Approvals`/);
+});
+
+test('deferred design does not create an extra industry question', () => {
+ assert.match(planner, /Design vibe opt-in` is `yes`, `done`, `deferred`, or `skip`/i);
+ assert.doesNotMatch(planner, /design is reviewed visually at Gate 4/i);
+});
+
+test('preview preferences keep deferred Gate 4 markdown-only', () => {
+ const preferences = section(createSkill, 'Set tentative defaults', '**`--no-design` escape hatch.**');
+ assert.match(preferences, /<visual_companion> = yes[^\r\n]*Step 6\.75/);
+ assert.match(preferences, /Gate 4 remains markdown-only/);
+ assert.doesNotMatch(preferences, /open[^\r\n]*at Gate 4/i);
+ assert.doesNotMatch(createSkill, /The planner emits[^\r\n]*before each Gate 4 plan-mode entry/);
+ const handoff = section(createSkill, '#### Step 3b', '#### 3.9');
+ assert.match(handoff, /legacy planner emits `PLAN_PREVIEW_PATH:[\s\S]*ignore that early preview output/);
+ assert.match(handoff, /Do not open it[\s\S]*at Gate 4/);
+ assert.match(handoff, /With `--no-design`, Step 6\.75 and its HTML preview are both skipped/);
+ assert.doesNotMatch(handoff, /open "|xdg-open|Start-Process/);
+ const design = section(createSkill, '### Step 6.75', 'Offline profile setup is intentionally deferred');
+ assert.match(design, /legacy[\s\S]*Gate 4 remains markdown-only/i);
+ assert.match(design, /visual_companion: no` disables automatic\s+browser opening, not rendering/);
+ assert.match(design, /`--no-design` skips this stage and its HTML preview/);
+ assert.doesNotMatch(design, /Step 6\.85|every path through the flow gets at least one visual preview/);
+ const brandedPreview = section(design, '#### Branch A', '#### Branch B');
+ assert.match(brandedPreview, /\/design-system` owns rendering of `_plan_preview\.html`/);
+ const skippedDesign = section(design, '#### Branch B', '**Preview timing:**');
+ assert.match(skippedDesign, /\*\*Render `_plan_preview\.html`\*\*/);
+ assert.match(skippedDesign, /Print the preview path; open in browser only if `<visual_companion> = yes`/);
+});
+
+test('offline completion summary reflects the bundled native host runtime', () => {
+ const offlineSkill = fs.readFileSync(
+ path.join(pluginRoot, 'skills/setup-offline-profile/SKILL.md'), 'utf8',
+ );
+ const summary = section(offlineSkill, '### Step 10 — Summary', '## Status code');
+ assert.match(summary, /@microsoft\/power-apps-native-host[\s\S]*consumes the profile/);
+ assert.match(summary, /SQLite[\s\S]*queued synchronization[\s\S]*reconnect[\s\S]*status/);
+ assert.doesNotMatch(summary, /does not yet consume|Native runtime support remains deferred/i);
+});
+
+test('inline fallback preserves architecture-first conditional modeling', () => {
+ const fallback = section(
+ createSkill,
+ '#### 3.0a — Inline-gate fallback',
+ '#### 3.0 — Sub-agent return-status switch',
+ );
+ const architecture = fallback.indexOf('.tmp/approved-architecture.md');
+ const architect = fallback.indexOf('spawn `mobile-app:data-model-architect`');
+ assert.ok(architecture > 0 && architecture < architect);
+ assert.match(fallback, /connector-only[\s\S]*zero-table\/no-Dataverse/i);
+ assert.match(fallback, /Approved native capabilities:[\s\S]*Approved connectors:/i);
+});
+
+test('inline screen planning persists the approved graph before requesting specs', () => {
+ const fallback = section(createSkill, '#### 3.0a — Inline-gate fallback',
+ '#### 3.0 — Sub-agent return-status switch');
+ const skeleton = fallback.indexOf('Create the `native-app-plan.md` skeleton');
+ const graph = fallback.indexOf('`phase: graph`');
+ const embedded = fallback.indexOf('Embed the approved graph');
+ const specs = fallback.indexOf('`phase: specs`');
+ assert.ok(skeleton >= 0 && skeleton < graph);
+ assert.ok(graph < embedded && embedded < specs);
+ assert.match(fallback, /plan_path: <working_dir>\/native-app-plan\.md/);
+ assert.match(fallback, /both screen dispatches[\s\S]*skip_preview: true/);
+ assert.match(fallback, /missing or malformed, return to the Architecture gate/);
+});
+
+test('screen specs use the canonical plan and never rewrite graph scratch', () => {
+ const specs = section(planner, '#### 5b.2 — Spawn planner', '#### Gate 4 — Screen Specs');
+ assert.match(specs, /plan_path: <working_dir>\/native-app-plan\.md/);
+ assert.match(specs, /read its `## Screens` section/);
+ assert.match(specs, /writes specs only into `plan_path`/);
+ assert.doesNotMatch(specs, /locked[^.\n]*_screens_section\.md/);
+ const deferred = section(planner, '- **`Design vibe opt-in: deferred`',
+ '- **`Design vibe opt-in: done`');
+ assert.match(deferred, /native-app-plan\.md/);
+ assert.doesNotMatch(deferred, /writes only `_screens_section\.md`/i);
+});
+
+test('screen completeness repair belongs to graph planning before approval', () => {
+ const phases = section(screenPlanner, '## Two-phase mode', '**The scaffolded project');
+ const graphRow = phases.split(/\r?\n/).find((line) => line.startsWith('| `graph` |'));
+ assert.match(graphRow, /Step 5b \(repair\)/);
+ const audit = section(screenPlanner, '### Step 5b', '## Step 6');
+ assert.match(audit, /`phase: specs`[\s\S]*read-only[\s\S]*before any[\s\S]*write/);
+ assert.match(audit, /NEEDS_CONTEXT: graph missing <thing>/);
+ assert.match(audit, /`phase: graph`[\s\S]*repair[\s\S]*Gate 3/);
+ assert.doesNotMatch(audit, /add the missing screens NOW/);
+ const graphDispatch = section(planner, '#### 5b.1', '#### Gate 3');
+ assert.match(graphDispatch, /Step 5b[\s\S]*before[\s\S]*return/);
+ assert.doesNotMatch(graphDispatch, /Stop after Step 3\.5 and return/);
+});
+
+test('missing screen graph context returns to approval instead of retrying specs', () => {
+ const specsDispatch = section(planner, '#### 5b.2', '#### Gate 4');
+ assert.match(specsDispatch, /NEEDS_CONTEXT: graph missing[\s\S]*before the generic/);
+ assert.match(specsDispatch, /phase: graph[\s\S]*Gate 3[\s\S]*user approval/);
+ const fallback = section(createSkill, '#### 3.0a', '#### 3.0 —');
+ assert.match(fallback, /NEEDS_CONTEXT: graph missing[\s\S]*Gate 3[\s\S]*user approval/);
+});
+
+test('screen specs retries replace owned sections without changing the approved graph', () => {
+ const write = section(screenPlanner, '**Write target by phase:**', 'Section format');
+ assert.match(write, /replace[\s\S]*all prior copies/i);
+ for (const heading of ['Per-Screen Specs', 'Open Questions', 'Open Questions for the User', 'Screen Graph', 'JavaScript Dependencies']) {
+ assert.ok(write.includes(`### ${heading}`), `missing owned subsection: ${heading}`);
+ }
+ assert.match(write, /Navigation Pattern[\s\S]*Screen Map[\s\S]*Navigation Contracts[\s\S]*Shared\s+Conventions[\s\S]*unchanged/);
+ assert.match(write, /one[\s\S]*Edit[\s\S]*Write/);
+ assert.match(write, /omits an optional subsection[\s\S]*remove/i);
+ assert.match(write, /at most one[\s\S]*outside[\s\S]*unchanged/);
+ const preview = section(screenPlanner, '## Step 6', '**Otherwise (`skip_preview`');
+ assert.match(preview, /same single[\s\S]*replacement/);
+ assert.doesNotMatch(preview, /Then append the markdown block/);
+ assert.doesNotMatch(screenPlanner, /only the append into `plan_path` is allowed/);
+ const specsDispatch = section(planner, '#### 5b.2', '#### Gate 4');
+ assert.match(specsDispatch, /replace[\s\S]*phase-owned/i);
+ assert.doesNotMatch(specsDispatch, /Append per-screen specs and Open Questions only/);
+});
+
+test('architecture result is validated before generic missing-context retry routing', () => {
+ const routing = section(createSkill, '#### 3.0 — Sub-agent return-status switch',
+ '**Data-model exact-name expansion:**');
+ const special = routing.indexOf('**Architecture-gate result');
+ const generic = routing.indexOf('For all other first lines');
+ assert.ok(special >= 0 && generic > special);
+ assert.match(routing, /Architecture phase: gate-only/);
+ assert.match(routing, /approved-architecture\.md/);
+ assert.match(routing, /does not consume the generic retry budget/);
+ assert.match(routing, /mode must match/);
+});
+
+test('planner permissions allow required planning artifacts only in their owning phase', () => {
+ const permissions = planner.slice(planner.indexOf('## Tool Permissions'));
+ assert.match(permissions, /`gate-only`: write `\.tmp\/approved-architecture\.md` only after actual Gate 1/);
+ assert.match(permissions, /`complete`: write `native-app-plan\.md`[\s\S]*\.tmp\/mobile-plan-status\.json/);
+ assert.match(permissions, /normalization[\s\S]*\.tmp\/dataverse-schema-contract\.json/);
+ assert.match(permissions, /No app source, app configuration, generated services/);
+ assert.doesNotMatch(permissions, /`Write` only to create `native-app-plan\.md`/);
+});
+
+test('post-specs cross-entity audit reads the canonical plan and belongs to Gate 2', () => {
+ const audit = section(architect, '## Step 6a — Cross-entity Read Audit',
+ '2. **Per entry, branch on');
+ assert.match(audit, /mode: cross-entity-audit[\s\S]*native-app-plan\.md/);
+ assert.match(audit, /graph-only scratch[\s\S]*not a substitute/);
+ assert.doesNotMatch(architect, /addendum to Gate 1|Gate 1 view/);
+});
+
+test('architecture revalidates storage and native dependencies without silently dropping requirements', () => {
+ const gate = section(planner, '### Gate 1 — Data Platform', '## Step 5 — Build Data Model');
+ assert.match(gate, /Before accepting Gate 1[\s\S]*revalidate every native capability/);
+ assert.match(gate, /whenever either choice changes/);
+ assert.match(gate, /`geolocation` requires Dataverse/);
+ assert.match(gate, /One-shot `location` is not an automatic replacement/);
+ assert.match(gate, /Do not silently remove capabilities/);
+ assert.match(gate, /Write the approved artifact only after the compatible combination is accepted/);
+ const capabilities = section(planner, 'Control planning gate:', '## Step 4 — Plan Connectors');
+ assert.match(capabilities, /connector-owned storage[\s\S]*supported upload\/write operation/);
+ assert.match(capabilities, /connector name alone is not a storage implementation/);
+ assert.doesNotMatch(capabilities, /missing Dataverse storage for a persisted artifact/);
+});
+
+test('architecture owns connector confirmation without changing the shared standalone workflow', () => {
+ const connectors = section(planner, '## Step 4 — Plan Connectors', '### Gate 1 — Data Platform');
+ assert.match(connectors, /Skip its Step 2 standalone confirmation/);
+ const shared = fs.readFileSync(path.join(pluginRoot, 'shared/references/connector-planning.md'), 'utf8');
+ assert.match(shared, /## Step 2 — Present to User for Confirmation/);
+ assert.match(shared, /present using `AskUserQuestion`/);
+});
+
+test('reuse-only apps retain a verified materialized inventory without replaying schema writes', () => {
+ const addDataverse = fs.readFileSync(path.join(pluginRoot, 'skills/add-dataverse/SKILL.md'), 'utf8');
+ const verification = section(addDataverse, '### Step 6c — Verify tables exist', '### Step 6d — Write');
+ const materialized = section(addDataverse, '### Step 6d — Write', '### Step 7 — Inspect generated files');
+ assert.match(verification, /every table in `SERVICE_REQUIRED_TABLES`, including reused-as-is tables/);
+ assert.match(materialized, /reuse-only app must still have a populated manifest/);
+ assert.match(materialized, /Include every service-required table[\s\S]*status: "reused"/);
+ assert.match(materialized, /Exclude deferred or unverified tables/);
+ assert.match(materialized, /not by replaying successful schema writes/);
+ assert.match(materialized, /standard-system-table exclusions still apply/);
+ assert.doesNotMatch(materialized, /Do NOT include tables reused/);
+
+ const seeding = section(createSkill, '### Step 8.5 — Seed sample data', '### Offline profile');
+ assert.ok(seeding.indexOf('Rebuild the local manifest') < seeding.indexOf('Invoke skill: /add-sample-data'));
+ assert.match(seeding, /Zero schema writes is a valid reuse-only result/);
+ assert.match(seeding, /service.requiredTables/);
+ assert.match(seeding, /verify-dataverse-services\.js/);
+ const offline = section(createSkill, '### Offline profile', '### Step 9 — Apply native capabilities');
+ assert.match(offline, /including reused tables/);
+ assert.match(offline, /read-only manifest\s+recovery in Step 8\.5/);
+});
+
+test('offline profile opt-in runs after Dataverse materialization and before native wiring', () => {
+ assert.equal(createSkill.indexOf('### Step 6.85 — Offline profile'), -1);
+ const sampleData = createSkill.indexOf('### Step 8.5 — Seed sample data');
+ const offline = createSkill.indexOf('### Offline profile');
+ const native = createSkill.indexOf('### Step 9 — Apply native capabilities');
+ assert.ok(sampleData > 0 && sampleData < offline);
+ assert.ok(offline < native);
+ assert.match(createSkill, /→ \[Offline profile\] Asking whether/i);
+ assert.doesNotMatch(createSkill, /Step 8\.6 — Offline profile/);
+ assert.match(
+ createSkill,
+ /missing, malformed, or contains no Dataverse[\s\S]*BLOCKED: Dataverse materialization/i,
+ );
+});
diff --git a/plugins/mobile-apps/scripts/tests/metro-logging-contract.test.js b/plugins/mobile-apps/scripts/tests/metro-logging-contract.test.js
index 4254f68ed..4f2d93776 100644
--- a/plugins/mobile-apps/scripts/tests/metro-logging-contract.test.js
+++ b/plugins/mobile-apps/scripts/tests/metro-logging-contract.test.js
@@ -85,7 +85,7 @@ test('skill contracts read logs and persist host-neutral state under .powernativ
assert.match(createFrontmatter, /allowed-tools:.*\bSkill\b/);
assert.match(createSkill, /\.powernative\/metro-logs/);
assert.match(createSkill, /npm run dev/);
- assert.match(createSkill, /12\. Start Metro \(`npm run dev`\)/);
+ assert.match(createSkill, /^### Step 12 [^\r\n]*Metro writes project-local logs/m);
assert.match(createSkill, /createPowerAppsMetroConfig/);
assert.match(createSkill, /npm does not launch `expo start` when either gate fails/);
assert.match(createSkill, /always receives a scannable code even when Metro runs in a background terminal/);
diff --git a/plugins/mobile-apps/scripts/tests/mobile-telemetry-hooks.test.js b/plugins/mobile-apps/scripts/tests/mobile-telemetry-hooks.test.js
index f60769215..819714ad2 100644
--- a/plugins/mobile-apps/scripts/tests/mobile-telemetry-hooks.test.js
+++ b/plugins/mobile-apps/scripts/tests/mobile-telemetry-hooks.test.js
@@ -8,6 +8,7 @@ const path = require('node:path');
const { spawnSync } = require('node:child_process');
const { TRACKED_SKILL_NAMES } = require('../lib/mobileapp-hook-utils');
const { withStableDispatchCwd } = require('../../hooks/run-telemetry');
+const { fireAndForget } = require('../lib/mobile-telemetry-dispatcher');
const PLUGIN_ROOT = path.resolve(__dirname, '..', '..');
const PLUGIN_VERSION = JSON.parse(
@@ -116,6 +117,35 @@ test('hook dispatch runs outside the caller project and restores its cwd', () =>
assert.equal(process.cwd(), originalCwd);
});
+test('detached telemetry dispatch uses a stable cwd without changing the caller', (testContext) => {
+ const context = fixture(testContext);
+ const originalCwd = process.cwd();
+ const spawnStub = testContext.mock.fn(() => ({
+ on() {},
+ stdin: { on() {}, end() {} },
+ unref() {},
+ }));
+
+ try {
+ process.chdir(context.projectRoot);
+ fireAndForget({ data: { pluginName: 'mobile-app' } }, {
+ projectRoot: context.projectRoot,
+ env: { POWER_PLATFORM_SKILLS_TELEMETRY_MOBILE_APP_OPTOUT: '1' },
+ spawn: spawnStub,
+ });
+ assert.equal(fs.realpathSync(process.cwd()), fs.realpathSync(context.projectRoot));
+ } finally {
+ process.chdir(originalCwd);
+ }
+
+ assert.equal(spawnStub.mock.callCount(), 1);
+ const spawnOptions = spawnStub.mock.calls[0].arguments[2];
+ assert.equal(spawnOptions.cwd, os.tmpdir());
+ assert.equal(spawnOptions.detached, true);
+ assert.equal(spawnOptions.env.POWER_PLATFORM_SKILLS_PROJECT_ROOT, context.projectRoot);
+ assert.equal(spawnOptions.env.POWER_PLATFORM_SKILLS_TELEMETRY_MOBILE_APP_OPTOUT, '1');
+});
+
test('interactive Copilot invocation creates identity and logs before environment resolution', (t) => {
const context = fixture(t);
const appPath = path.join(context.projectRoot, 'app.json');
diff --git a/plugins/mobile-apps/shared/references/connectivity-intent-ownership.md b/plugins/mobile-apps/shared/references/connectivity-intent-ownership.md
new file mode 100644
index 000000000..1966ca9ba
--- /dev/null
+++ b/plugins/mobile-apps/shared/references/connectivity-intent-ownership.md
@@ -0,0 +1,25 @@
+# Connectivity Intent Ownership
+
+During `/create-mobile-app`, wording such as offline, offline-first, limited or
+intermittent connectivity, disconnected use, or no connectivity is operating
+context only. Requirements discovery and planning continue from the user's
+independently stated workflows, data, device capabilities, integrations, and
+explicit connectivity-diagnostic features.
+
+Planning and generation must not add offline-specific business tables, columns,
+status fields, services, hooks, stores, queues, routes, or screens solely from
+that connectivity wording. Offline storage and synchronization are runtime
+concerns owned by the bundled offline package and native host.
+
+After a Dataverse model is materialized, the create flow offers
+`/setup-offline-profile`. That skill owns which Dataverse tables and columns
+are available offline. The bundled `@microsoft/power-apps-native-offline`
+package is consumed by `@microsoft/power-apps-native-host`: a valid
+`offline-profile.json` activates local SQLite reads/writes, queued
+synchronization, reconnect behavior, and the host-rendered status overlay.
+Mobile Offline Profile setup therefore does not add duplicate generated
+screens, routes, sync controls, queues, banners, or record-status UI.
+
+An explicit product requirement for a custom connectivity diagnostic or an
+app-owned sync queue is separate from Mobile Offline Profile setup and must be
+named as such in the approved requirements and screen specifications.
diff --git a/plugins/mobile-apps/shared/references/screen-templates.md b/plugins/mobile-apps/shared/references/screen-templates.md
index 1493fc182..808ae8d11 100644
--- a/plugins/mobile-apps/shared/references/screen-templates.md
+++ b/plugins/mobile-apps/shared/references/screen-templates.md
@@ -325,7 +325,7 @@ Every empty state should have a visual element beyond just text. In priority ord
| No people/team | `people-outline` | `@expo/vector-icons` |
| Error state | `alert-circle` | `@expo/vector-icons` |
| Success/complete | `checkmark-circle` | `@expo/vector-icons` |
-| Offline | `cloud-offline-outline` | `@expo/vector-icons` |
+| Connectivity diagnostic | `cloud-offline-outline` | `@expo/vector-icons` |
| No permissions | `shield-outline` | `@expo/vector-icons` |
| Onboarding welcome | `sparkles` | `@expo/vector-icons` |
diff --git a/plugins/mobile-apps/shared/references/universal-patterns.md b/plugins/mobile-apps/shared/references/universal-patterns.md
index bec2ebf1d..70dd9a54c 100644
--- a/plugins/mobile-apps/shared/references/universal-patterns.md
+++ b/plugins/mobile-apps/shared/references/universal-patterns.md
@@ -279,9 +279,11 @@ Used for: finance, enterprise, health — any app with auth sessions.
---
-## 8. Offline Sync Queue UI
+## 8. App-Owned Sync Queue UI
-Used for: field apps, any app that works without connectivity.
+Use this pattern only for an approved product requirement backed by a real
+app-owned sync queue API. Mobile Offline Profile configuration is governed by
+[`connectivity-intent-ownership.md`](connectivity-intent-ownership.md).
```tsx
// Sync status bar — sticky at top of list screens
diff --git a/plugins/mobile-apps/skills/add-dataverse/SKILL.md b/plugins/mobile-apps/skills/add-dataverse/SKILL.md
index 9cb8f0f9b..097d88b6c 100644
--- a/plugins/mobile-apps/skills/add-dataverse/SKILL.md
+++ b/plugins/mobile-apps/skills/add-dataverse/SKILL.md
@@ -1086,7 +1086,11 @@ If the publish call returns a non-2xx status, report the error and stop — do n
**Telemetry checkpoint: `verify_dataverse_schema`**
-Confirm every created or extended table is queryable after publish with **one** filtered query, not one request per table:
+Confirm every table in `SERVICE_REQUIRED_TABLES`, including reused-as-is tables,
+plus any created or extended table, is queryable after publication when needed.
+Use the resolved effective names from the approved operation manifest or the
+standalone path's verified service list, not Creation Order alone. Use **one**
+filtered query for the bounded set, not one request per table:
```bash
node "${PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> GET \
@@ -1095,11 +1099,16 @@ node "${PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> GET \
```
- **Every expected name present in `value[]`** → confirmed.
-- **Any expected name missing** → that table did not survive publish — report which ones and stop.
+- **Any expected name missing** → schema/service verification is incomplete.
+ Return to the owning reconciliation step; do not mark that table materialized
+ or invent a new table to replace a missing reuse target.
### Step 6d — Write `.datamodel-manifest.json`
-After all tables are verified, write the manifest to the project root using the `Write` tool:
+After schema verification in Step 6c and generated-service verification in
+Step 6 both pass, write the manifest to the project root using the `Write`
+tool. This is the application's verified table inventory, not a schema-write
+log; a reuse-only app must still have a populated manifest:
```json
{
@@ -1123,7 +1132,19 @@ After all tables are verified, write the manifest to the project root using the
`metadataId` and `solution` are required for `status: "new"` or `"extended"` entries — they're how Step 5a distinguishes "we own this on a re-run" from "name collision." Reused tables can omit both.
-Include only tables confirmed in Step 6c. Do NOT include tables reused with no schema changes.
+Include every service-required table confirmed in Step 6c, including tables
+reused with no schema changes, plus verified new/extended tables. Use
+`status: "reused"` for unchanged existing tables; retain `"new"` and
+`"extended"` only for their actual outcomes. Preserve effective adapted names,
+entity-set names, and verified column/relationship/key facts from reconciliation
+and any post-write metadata reads. Exclude deferred or unverified tables.
+
+Before returning, check that every `SERVICE_REQUIRED_TABLES` name occurs in the
+manifest and has verified generated service output. A partial or empty manifest
+from an earlier run is repaired by repeating Step 6's read-only service verifier
+and Steps 6c–6d, not by replaying successful schema writes. Recording a reused
+table does not authorize a metadata POST or republish; the existing sample-data
+record-count checks and standard-system-table exclusions still apply.
### Step 7 — Inspect generated files
diff --git a/plugins/mobile-apps/skills/create-mobile-app/SKILL.md b/plugins/mobile-apps/skills/create-mobile-app/SKILL.md
index 00f9622e0..ec945c460 100644
--- a/plugins/mobile-apps/skills/create-mobile-app/SKILL.md
+++ b/plugins/mobile-apps/skills/create-mobile-app/SKILL.md
@@ -14,7 +14,14 @@ Top-level orchestrator. Owns the user-visible flow; delegates planning to the `n
## Workflow
-0. Resume check + fresh-template gate → 1. Prerequisites → 2. Gather requirements → 2b. Requirements discovery → 2c. Plan preview (rough cost + abort gate) → 3. Plan (planner agent + 4 gates) → 4. Auth & environment → 5. Prepare existing template → 6. `npx power-apps init` → 6.5 verify `npm install` → **6.5b SafeAreaProvider gate (always runs, idempotent)** → 6.6 scaffold `tsc` smoke check → 6.7 seed memory bank → 6.75 design system → **6.85 Offline profile (always asked)** → 7. Auth config → 8. Apply data model → 9. Apply native capabilities → 9a. Install planned JavaScript dependencies → 9b. Design system → 10. Add connectors → 10b. Wire navigation layout → 11. Build screens (parallel) → 11.4 Stylistic fix sweep → 12. Start Metro (`npm run dev`) → 12.5 Optional debug handoff → 13. Summary
+Resume/template checks → prerequisites → requirements (iOS + Android fixed) →
+rough plan preview → Gate 1 architecture (native capabilities, connectors,
+then data platform) → Gate 2 Dataverse model when selected → Gates 3 and 4
+screen graph/specifications → environment and template preparation → app
+initialization → design system → conditional Dataverse materialization and
+sample data → Mobile Offline Profile offer for Dataverse apps → native
+capabilities and connectors → navigation and screens → validation, preview,
+and summary.
---
@@ -162,9 +169,9 @@ If `resolve-environment.js` cannot get tokens, run `az login --tenant <env-tenan
Detect the publisher prefix for the env's Default solution so the planner uses the correct prefix rather than assuming `cr_`.
-**Deferred execution:** do not run the query at this point. Step 2b.4 first
-classifies the run as `required` or `connector-only`; only `required` runs
-execute the block below. Connector-only runs set
+**Deferred execution:** do not run the query at this point. The architecture
+gate first selects `required` or `connector-only`; only `required` runs execute
+the block below. Connector-only runs set
`$DETECTED_PUBLISHER_PREFIX = ""` and make no Dataverse prefix query.
```bash
@@ -211,10 +218,13 @@ Then collect with `AskUserQuestion` (batch where possible):
| Question | Default |
|---|---|
| App display name | derived from description |
-| Target platforms | `ios`, `android` (multi-select, default both) |
| Aesthetic | minimal / playful / professional / matches existing brand |
| Target environment | Confirm `<ACTIVE_ENV_URL>` / `<ACTIVE_ENV_ID>` from Step 1.6, or choose "use a different environment" and provide another environment ID |
+Set `<target_platforms> = "ios, android"` for every new app. Do not ask the
+user to choose between iOS and Android; the mobile template targets both and
+downstream planning must retain platform-specific behavior for each.
+
**App slug is auto-derived** from the display name (`slugify(displayName)` — kebab-case, ASCII-only, strip non-alphanumerics). Do NOT ask the user; the derived slug is correct >95% of the time. Show the resolved slug as part of Step 2c's plan preview so the user can override via `edit` if needed.
**Environment override branch:** If the user picks "use a different environment", ask for the Power Platform environment ID via `AskUserQuestion`, then run `scripts/resolve-environment.js` again and refresh `$ACTIVE_ENV_ID` / `$ACTIVE_ENV_URL` / `$ACTIVE_TENANT_ID`.
@@ -318,33 +328,35 @@ Do not ask for confirmation here — the user agreed to this when their prompt s
**Auto-proceed after `yes` (or after auto-plan transparency log).** Fall through directly to Step 2c (plan preview). Do NOT add a separate "Proceed to planning?" prompt — the brief confirmation IS the planning go-ahead. The only abort gate after this is Step 2c's `proceed/edit/abort` block, which is intentionally distinct because it shows the rough cost estimate.
-Classify Dataverse planning before Step 2c and stash
-`<dataverse_planning_mode>`:
+Infer a provisional Dataverse planning mode before Step 2c:
- `connector-only` only when every record source and write target is an
explicit non-Dataverse connector/system of record, and the app needs no
- app-owned persistent rows, Dataverse offline data, retained File/Image
+ app-owned persistent rows, retained File/Image
artifact, existing Dataverse table, or Dataverse-backed native capability.
- `required` for every other case, including ambiguity. Do not infer
connector-only merely because the brief names a connector.
+Apply
+[`shared/references/connectivity-intent-ownership.md`](${PLUGIN_ROOT}/shared/references/connectivity-intent-ownership.md)
+while classifying the brief.
+
+Store the recommendation as `<recommended_dataverse_planning_mode>`. The first
+user-visible data-platform choice happens in the planner's architecture gate
+after native capabilities and connectors have been presented. Dataverse
+discovery does not run before that gate.
+
Also stash `<exact_target_facts_required> = yes` when planning depends on any
existing/standard/managed table, reuse or extension decision, proposed-name
collision decision, relationship target, computed column, or target
customizability fact. Otherwise set it to `no`. This flag controls only safe
planning degradation; it never relaxes `/add-dataverse` reconciliation.
-Now execute the deferred Step 1.7 publisher-prefix detection only when
-`<dataverse_planning_mode> = required`. For `connector-only`, set
-`$DETECTED_PUBLISHER_PREFIX = ""`, print
-`↷ Publisher-prefix discovery skipped — connector-only planning.`, and do not
-call `detect-publisher-prefix.js`.
-
**Design decisions are deferred to Step 6.75** — `/design-system` (ships with this plugin) handles brand inputs, the style picker, and visual companion preference in one flow after the project is scaffolded. Do NOT ask design questions here.
-Set tentative defaults (used by Step 3b before `/design-system` runs):
+Set tentative defaults (the preview preference applies at Step 6.75):
-- `<visual_companion> = yes` — open `_plan_preview.html` in browser at Gate 4 by default. `/design-system` at Step 6.75 may downgrade this to `no` (path (d) in its cost picker), persisted to memory-bank for future runs.
+- `<visual_companion> = yes` — automatically open `_plan_preview.html` in the browser at Step 6.75, after the design choice. Gate 4 remains markdown-only regardless of this preference. `/design-system` may change it to `no`; persist the final value to memory-bank for future runs.
- `<design_vibe_opt_in> = deferred` — Step 6.75 sets the real value. While `deferred`, the planner does NOT prompt for a direction; it writes a placeholder `## Design Direction: <deferred — set by /design-system>` block so screen-planner can still run.
**`--no-design` escape hatch.** For headless / token-constrained runs, set `--no-design` in `$ARGUMENTS`. It forces `<visual_companion> = no`, skips the style-picker handoff at Step 3a entirely, and short-circuits Step 6.75 to a no-op (placeholder block stays in `native-app-plan.md`; screen-builders fall back to industry-inferred defaults).
@@ -360,7 +372,7 @@ Set tentative defaults (used by Step 3b before `/design-system` runs):
| Output | Input proxy | Computation | Confidence |
|---|---|---|---|
| Tables | Distinct nouns in confirmed brief | `count(unique_nouns) × [0.7, 1.3]` rounded | low — architect may merge or split |
-| Connectors | Step 2b inferred connector list | `len(inferred)` (already exact) | high |
+| Connectors | Connector keywords in the confirmed brief | `len(candidates)` | low — Gate 1 confirms the actual list |
| Screens | Confirmed features in brief | `count(features) × [2, 3]` | low — depends on navigation choice |
| Planning min | Tables + screens | lower bound `max(10, tables × 0.3 + screens × 0.4 + 2)`; upper bound `max(15, computed upper)` | low — protects the quality-first Gate 1 budget |
| Scaffold min | Fixed | `1-2` (template preparation + npm install already happened before skill invocation) | high |
@@ -375,9 +387,9 @@ Based on your confirmed brief, before any agent runs:
Scope (proxy estimates — actual numbers come from architects):
Tables ~<low>-<high> ← from <N> nouns in brief; architect may merge/split
- Connectors <N> inferred ← <comma-separated names> (confirm at Gate 3)
+ Connectors <N> inferred ← <comma-separated names> (confirm at Gate 1)
Screens ~<low>-<high> ← from <N> features × ~2-3 screens each
- Approval gates 4 ← fixed (data model, native, connectors, screen plan)
+ Approval gates 4 ← architecture, data model when applicable, screen graph, screen specs
Time (rough — agent time only, excludes your approval latency at gates):
Planning ~<low>-<high> min ← includes the quality-first 10–15 min data-model target; approvals add latency
@@ -388,7 +400,7 @@ Token tier: Opus everywhere in v0 (model routing not yet shipped).
⚠ These are proxies, not measurements:
• Table count is "noun count in brief" — architect may collapse or split
- • Time excludes your approval latency at the 4 gates
+ • Time excludes your approval latency at up to 4 applicable gates
• If industry inference is low-confidence, +1 picker prompt
• If you opted into the design vibe picker, +1 prompt + planner re-spawn
• If any gate is rejected, that section regenerates (~2-3 min each)
@@ -412,11 +424,11 @@ Proceed, edit brief, or abort? [proceed/edit/abort]
- Forced calibration: every run produces the `<estimate, actual>` data we need for v0.x model routing decisions. Skipping drops calibration data.
**Set expectations before handing off to the planner:**
-> "Brief locked in. Planning surfaces 4 approval prompts (data model → native capabilities → connectors → screens). Data-model readiness is quality-first, with a 10–15 minute target:
-> • Gate 1 (data model) — budget 10–15 min for verified reuse/extend/create decisions, ER columns, relationships, tiers, and risks
-> • Gate 2 (native capabilities) — ~10s (quick)
-> • Gate 3 (connectors) — ~30–60s
-> • Gate 4 (screens + design) — **3–8 minutes** (this is the heavy one: design vibe picker if opted in, then per-screen specs and HTML preview generation)
+> "Brief locked in. Planning surfaces up to 4 approval prompts (data platform + native capabilities + connectors → data model when Dataverse is selected → screen graph → screen specs). Data-model readiness is quality-first, with a 10–15 minute target:
+> • Gate 1 (architecture) — confirm Dataverse choice, native capabilities, and connectors before schema work
+> • Gate 2 (data model, Dataverse only) — budget 10–15 min for verified reuse/extend/create decisions, ER columns, relationships, tiers, and risks; auto-skipped for no-Dataverse apps
+> • Gate 3 (screen graph) — approve destinations, navigation, and shared conventions
+> • Gate 4 (screen specs) — **3–8 minutes** for detailed screen contracts
>
> For Dataverse-required apps, factual foreground milestones will show
> environment, inventory, candidate, detail, and timing counts within 30
@@ -430,7 +442,7 @@ Proceed, edit brief, or abort? [proceed/edit/abort]
No background scaffold pipeline is used. The template is already present in `<working_dir>` and dependencies are expected to be installed before this skill starts (`npm install`). Continue directly to Step 3.
-### Step 3 — Plan (planner agent + 4 approval gates)
+### Step 3 — Plan (planner agent + up to 4 applicable approval gates)
**Telemetry checkpoint: `plan_app_architecture`**
@@ -440,9 +452,49 @@ First, create the working and planning-artifact directories:
mkdir -p <working_dir> <working_dir>/.tmp
```
-### Step 3.0 — Foreground Dataverse planning snapshot and evidence
+### Architecture gate
+
+Run the planner once in architecture-only mode before any Dataverse discovery:
+
+```
+Spawn agent: mobile-app:native-app-planner
+
+Prompt:
+ Plan and approve architecture inputs for a Power Apps mobile app.
+ Architecture phase: gate-only
+ Requirements brief: <requirements_brief>
+ Original prompt: <full $ARGUMENTS verbatim>
+ Wizard answers: <Step 2 answers>
+ Target platforms: iOS and Android
+ Recommended Dataverse planning mode: <recommended_dataverse_planning_mode>
+ Working directory: <absolute path>
+ Plugin root: ${PLUGIN_ROOT}
+ Dataverse planning snapshot: NOT SUPPLIED
+ Dataverse planning evidence: NOT SUPPLIED
+```
+
+The planner presents native capabilities, then connectors, then the
+data-platform choice in Gate 1. On approval it writes
+`<working_dir>/.tmp/approved-architecture.md` and returns exactly
+`NEEDS_CONTEXT: dataverse-planning-mode:<required|connector-only>`.
+
+Treat that signal as the successful architecture result, set
+`<dataverse_planning_mode>` only after the architecture-result checks in the
+canonical status switch below pass, and continue. Any other terminal status
+follows that switch. If the nested planner is unavailable, prepare and approve
+all three architecture decisions inline: native capabilities, connectors, and
+the data-platform choice. Use the planner's Gate 1 dependency checks, write
+the same approved artifact, and continue without adding another approval.
+
+Now execute the deferred Step 1.7 publisher-prefix detection for `required`.
+For `connector-only`, set `$DETECTED_PUBLISHER_PREFIX = ""`, print
+`↷ Publisher-prefix discovery skipped — connector-only planning.`, and do not
+call `detect-publisher-prefix.js`.
-Planning stays read-only. Branch on `<dataverse_planning_mode>`:
+### Foreground Dataverse planning snapshot and evidence
+
+Planning stays read-only. Branch on the Gate 1-approved
+`<dataverse_planning_mode>`:
- `connector-only` — skip every command in this section. Set `SNAPSHOT_PATH`
and `EVIDENCE_PATH` to empty/not supplied, print
@@ -569,7 +621,7 @@ If the planner needs to record a `DONE_WITH_CONCERNS` from a sub-agent (data-mod
**Planner preflight (silent).** Before the full Task spawn, do a no-op `Task` probe for `mobile-app:native-app-planner` (same pattern as Step 11.0). If the probe fails with `Agent type … not found`, `tool unavailable`, or the host clearly cannot route nested agents, fall through to **inline-gate mode** (described below) without prompting. The orchestrator has the full tool surface itself — it can run the gates directly. Do not retry, do not ask the user.
**Announce the handoff before the Task call** (so the user isn't staring at a blank screen while the planner spins up):
-- `required`: > "→ Spawning planner agent from the verified foreground planning snapshot. Gate 1/data-model readiness is quality-first with a 10–15 minute target. I will print each factual `data-model-planning-status.json` milestone and elapsed count as it lands."
+- `required`: > "→ Spawning planner agent from the verified foreground planning snapshot. Gate 2/data-model readiness is quality-first with a 10–15 minute target. I will print each factual `data-model-planning-status.json` milestone and elapsed count as it lands."
- `connector-only`: > "→ Spawning planner agent in connector-only mode; a foreground planning snapshot and data-model mutation are not required."
Then spawn the `mobile-app:native-app-planner` agent via `Task` (the plugin name `mobile-app:` prefix is required — without it `Task` returns `Agent type not found`):
@@ -588,8 +640,12 @@ Prompt:
Original prompt: <full $ARGUMENTS verbatim>
Wizard answers: <Step 2 answers>
+ Target platforms: iOS and Android (fixed; no platform question)
Working directory: <absolute path of <working_dir>>
Plugin root: ${PLUGIN_ROOT}
+ Architecture phase: complete
+ Approved architecture artifact:
+ <working_dir>/.tmp/approved-architecture.md
Dataverse planning mode: <required | connector-only>
Dataverse planning failure reason: none
Normalized Dataverse foreground planning snapshot: <absolute SNAPSHOT_PATH verbatim for required; otherwise NOT SUPPLIED>
@@ -599,10 +655,17 @@ Prompt:
NOT SUPPLIED>
Publisher prefix (detected from env): <DETECTED_PUBLISHER_PREFIX from Step 1.7, e.g. "cr8142a" — use literally as `<prefix>_<entity>` in all logical names. If empty/NOT DETECTED, fall back to `cr` placeholder and surface a `DONE_WITH_CONCERNS` note that Dataverse will normalize at create time.>
- Follow native-app-planner.md. Run all 4 approval gates. On terminal return, emit one of `DONE` / `DONE_WITH_CONCERNS:` / `NEEDS_CONTEXT:` / `BLOCKED:` as the literal first line per AGENTS.md rule #10.
+ Follow native-app-planner.md. Restore the approved architecture without
+ re-asking Gate 1, then run conditional Dataverse modeling and the remaining
+ applicable approval gates. On terminal return, emit one of
+ `DONE` / `DONE_WITH_CONCERNS:` / `NEEDS_CONTEXT:` / `BLOCKED:` as the literal
+ first line per AGENTS.md rule #10.
```
-The planner runs gates internally for data model → native capabilities → connectors → screen plan, and writes `<working_dir>/native-app-plan.md`. Wait for it to return before continuing — do not proceed on a partially-approved plan.
+The planner runs gates internally for architecture → conditional data model →
+screen graph → screen specs, and writes `<working_dir>/native-app-plan.md`.
+Wait for it to return before continuing — do not proceed on a
+partially-approved plan.
On a successful `required` return, require both
`.tmp/dataverse-schema-contract.json` and `.tmp/mobile-plan-status.json`
before continuing. If the receipt is missing, STOP as `BLOCKED`; this
@@ -610,61 +673,147 @@ orchestrator must not synthesize it after the planner has returned.
#### 3.0a — Inline-gate fallback (planner unavailable OR returned `BLOCKED: tool surface missing`)
-When the preflight fails OR the planner returns `BLOCKED: tool surface missing <…>`, the orchestrator runs the four gates inline. Do NOT re-spawn the planner — it cannot succeed in this host. Print **once**:
+When the preflight fails OR the planner returns `BLOCKED: tool surface missing <…>`, the orchestrator runs all applicable gates inline. Do NOT re-spawn the planner — it cannot succeed in this host. Print **once**:
> "→ Planner agent unavailable in this host — running approval gates inline. (No action needed; this is automatic.)"
Then execute, in order, using your own `EnterPlanMode` + `AskUserQuestion`:
-1. **If a draft `native-app-plan.md` exists:** read it as baseline. Surface each populated section (`## Data Model`, `## Native Capabilities`, `## Connectors`) one at a time via `EnterPlanMode`, take user feedback inline, edit the file in place. Skip generating sections that are already populated and approved.
-2. **If no draft exists:** spawn `mobile-app:data-model-architect` directly via `Task` (single architect, not the orchestrator agent) to draft `## Data Model`; then build `## Native Capabilities` + `## Connectors` inline from the brief; then spawn `mobile-app:screen-planner` with `phase: graph` and `phase: specs` per the two-phase Gate 4 split.
-
- **Before each `screen-planner` spawn, print a one-line ETA so the user knows the agent is live and roughly how long to wait** (the agent's own `Bash echo` progress markers — see `agents/screen-planner.md` "Progress streaming" — surface every milestone, but the orchestrator's pre-spawn line gives the wall-clock budget):
- - Before `phase: graph`: `> "→ [Gate 4a] Spawning screen-planner phase=graph (~2 min for ${N} screens)…"`
- - Before `phase: specs`: `> "→ [Gate 4b] Spawning screen-planner phase=specs (~1 min/screen, ~${N} min for ${N} screens). Progress markers will appear inline."`
-
- **MUST forward the Dataverse planning mode in the direct architect prompt.**
- In `required`, also forward `SNAPSHOT_PATH` and `EVIDENCE_PATH` verbatim and
- do not resolve the environment or run Dataverse discovery again. In
- `connector-only`, state that both paths are not supplied; never invent
- placeholder artifacts.
-
- **MUST forward `$DETECTED_PUBLISHER_PREFIX` from Step 1.7 in the architect prompt** — same line as the planner prompt at Step 3 line 1034: *"Publisher prefix (detected from env): `<DETECTED_PUBLISHER_PREFIX>` — use literally as `<prefix>_<entity>` in all logical names. If empty/NOT DETECTED, fall back to `cr` placeholder and surface a `DONE_WITH_CONCERNS` note that Dataverse will normalize at create time."* Without this, the architect defaults to `cr_` and the whole plan needs a post-hoc sweep when the real prefix is something else (e.g. `cr3e9`).
+1. Read `<working_dir>/.tmp/approved-architecture.md`. If it is missing or malformed, return to the Architecture gate
+ above and recover the artifact from recorded user acceptance, or run that
+ gate inline when approval is absent. Do not invent approval or infer the
+ data platform from missing artifacts. Only then perform the conditional
+ foreground snapshot step and resume here; retain a valid existing approval
+ without re-asking it.
+2. Restore the approved native capabilities, connectors, and data-platform
+ mode without re-presenting Gate 1:
+ - In `connector-only`, write an explicit zero-table/no-Dataverse
+ `## Data Model` section and no schema contract or data-model approval
+ receipt.
+ - In `required`, spawn `mobile-app:data-model-architect` directly via
+ `Task`, passing `Approved native capabilities:` and
+ `Approved connectors:` verbatim along with the foreground
+ snapshot/evidence paths. Present its result as Gate 2 and require approval
+ before screen planning.
+
+ **MUST forward the approved architecture in the direct architect prompt.**
+ Include the exact Gate 1-approved native capabilities and connectors. In
+ `required`, also forward `SNAPSHOT_PATH` and `EVIDENCE_PATH` verbatim and do
+ not resolve the environment or run Dataverse discovery again. A
+ `connector-only` run never dispatches this architect.
+
+ **MUST forward `$DETECTED_PUBLISHER_PREFIX` from Step 1.7 in the architect prompt:** *"Publisher prefix (detected from env): `<DETECTED_PUBLISHER_PREFIX>` — use literally as `<prefix>_<entity>` in all logical names. If empty/NOT DETECTED, fall back to `cr` placeholder and surface a `DONE_WITH_CONCERNS` note that Dataverse will normalize at create time."* Without this, the architect defaults to `cr_` and the whole plan needs a post-hoc sweep when the real prefix is something else (e.g. `cr3e9`).
In `required`, also require the direct architect to write and normalize
`<working_dir>/.tmp/dataverse-schema-contract.json` per its agent contract.
- A draft Markdown section without that sidecar is not an executable Gate 1
+ A draft Markdown section without that sidecar is not an executable Gate 2
result.
**Why this works even though the planner just returned BLOCKED for tool surface:** the orchestrator (this skill, running in the user's slash-command session) always has the full tool surface — Task, EnterPlanMode, ExitPlanMode, AskUserQuestion, Read, Write, Bash. What's missing is the surface inside *nested* agent contexts (the `native-app-planner` agent runs in a sandbox without EnterPlanMode/AskUserQuestion, which is why its Step 0 preflight returned BLOCKED). The leaf agents `data-model-architect` and `screen-planner` only need Read/Write/Bash to draft markdown — they don't need EnterPlanMode/AskUserQuestion themselves. Spawn them; the orchestrator owns the gates.
-3. **Run the gates yourself** — use `EnterPlanMode` four times (data model → native caps + connectors merged → screen graph 4a → screen specs 4b). Same gate prompts as the planner agent would use. Gate 4 is a markdown screen-graph review only — design picking happens unconditionally at Step 6.75 via `/design-system` (no separate style-picker handoff at Gate 4 even in inline mode).
-4. **Write the final approved `native-app-plan.md`** with an `## Approvals` block at the bottom listing each gate, who approved (user), and a timestamp.
-
- **HARD RULES for the plan structure (mirror the planner agent's template at [`agents/native-app-planner.md`](${PLUGIN_ROOT}/agents/native-app-planner.md) Step 4):**
+3. **Prepare and approve screens in order.** Create the `native-app-plan.md` skeleton
+ from the planner's Step 6 template, including the approved architecture,
+ approved or not-applicable Data Model, an empty `## Screens`, and
+ `## Approvals` containing only approvals actually received.
+ For both screen dispatches, pass `plan_path: <working_dir>/native-app-plan.md`
+ and the approved model, native capabilities, and connectors verbatim. Pass
+ `skip_preview: true` for deferred or skipped design; graph generation never
+ renders a preview. Keep any explicitly selected legacy preview policy for
+ the specs phase separate from its canonical-plan write target.
+ - Spawn `mobile-app:screen-planner` with `phase: graph` first. Present its
+ navigation, screen map, and shared conventions as Gate 3 after its Step 5b
+ completeness repair; wait for approval.
+ - Embed the approved graph from `_screens_section.md` into `## Screens` in
+ `native-app-plan.md` and record Gate 3 acceptance before proceeding.
+ - Verify that the canonical plan contains the locked graph, then spawn
+ `mobile-app:screen-planner` with `phase: specs`. It reads that plan and
+ replaces only the phase-owned subsections using its Step 5 single-write
+ contract, without rewriting the approved graph or graph scratch file.
+ - On `NEEDS_CONTEXT: graph missing <thing>` from specs, leave the failed
+ specs output uncommitted, mark the screen approvals pending, and rerun
+ `phase: graph` with the missing items and approved context. Reopen Gate 3
+ and require fresh user approval before merging the corrected graph and
+ resuming specs. Do not retry specs against the same incomplete graph.
+ - Present the expanded canonical plan as Gate 4. On rejection revise only
+ specs using replacement, not append, unless the user changes the graph,
+ which requires Gate 3 again.
+ Print each phase and its ETA before dispatch. Design picking remains at
+ Step 6.75 via `/design-system`; do not generate a default-design preview.
+4. **Finalize the existing `native-app-plan.md`**, preserving the approved graph
+ and current specs. Update `## Approvals` with each actual user acceptance
+ and timestamp; do not rebuild it from `_screens_section.md`.
+
+ **HARD RULES for the plan structure (mirror the planner agent's template at [`agents/native-app-planner.md`](${PLUGIN_ROOT}/agents/native-app-planner.md) Step 6):**
- Top-level headings are EXACTLY: `## Overview`, `## App Requirements`, `## Data Model`, `## Native Capabilities`, `## Design Direction`, `## Connectors`, `## Screens`, `## Approvals`. Do NOT invent a `## Brief` super-section that nests the data model under it.
- `## App Requirements` is the user's confirmed brief verbatim (the `<requirements_brief>` from Step 2b), capped at ~80 lines. No expansion, no rewriting, no embedded preview of the data model.
- Discovery failure notes (e.g. `az login` on the wrong tenant, 401 from `dataverse-request.js`, all entities classified Create) go to `<working_dir>/memory-bank.md` under `## Discovery Notes`, NOT into the plan. Keep at most a single one-line breadcrumb in `## Data Model` like `> Discovery skipped — see memory-bank.md.` if relevant.
- Sample data notes, immutability plug-in notes, file-column setup notes, dispatch-block server rules go under a single `### Notes` subsection in `## Data Model`. Cap each at 2 sentences; link to `post-deployment-tasks.md` for longer write-ups instead of inlining.
-5. **Record the same structured approval receipt as the planner path.** At
- data-model acceptance, initialize
+5. **Record the same structured approval receipt as the planner path in
+ `required` mode only.** At data-model acceptance, initialize
`<working_dir>/.tmp/mobile-plan-status.json` with the exact normalized
contract content/hash. After each later gate is accepted, update only that
- gate's approval record and the current plan hash; after Gate 4b, record the
+ gate's approval record and the current plan hash; after Gate 4, record the
final structured service dependencies and integrity hash. Follow
`agents/native-app-planner.md` Step 6 exactly. Never call the operation
manifest builder to create or restamp this receipt. A changed approved
section invalidates its record until the existing inline gate approves it
again.
-If the orchestrator's OWN `Task` tool is unavailable (rare — would mean even leaf agents can't be spawned), fall further to fully-inline mode. In `required`, draft the data model from `SNAPSHOT_PATH` plus `EVIDENCE_PATH` with no live OData probe and write/normalize the same structured schema contract required by `agents/data-model-architect.md`. In `connector-only`, write an explicit zero-table/no-Dataverse `## Data Model` section and no contract. Then draft native caps + connectors heuristically, draft the screen graph + specs against `shared/references/screen-templates.md`, and run the four gates against the user. This is the last-resort path — functional but slower because the orchestrator does work the architects normally parallelize.
-
-**Hard rule:** never silently skip a gate just because the planner couldn't run. The user MUST approve each section through `EnterPlanMode` before any mutation step (Step 8 onwards) executes.
+ In `connector-only`, do not create `.tmp/mobile-plan-status.json` or any
+ Dataverse schema/approval artifact.
+
+If the orchestrator's OWN `Task` tool is unavailable (rare — would mean even
+leaf agents cannot be spawned), fall further to fully-inline mode. Draft and
+approve native capabilities, connectors, and data platform first. In
+`required`, then draft the data model from `SNAPSHOT_PATH` plus `EVIDENCE_PATH`
+with no live OData probe and write/normalize the same structured schema
+contract required by `agents/data-model-architect.md`. In `connector-only`,
+write an explicit zero-table/no-Dataverse `## Data Model` section and no
+contract or Data Model gate. Then draft the screen graph + specs against
+`shared/references/screen-templates.md`. This is the last-resort path —
+functional but slower because the orchestrator does work the architects
+normally perform.
+
+**Hard rule:** never silently skip an applicable gate just because the planner
+could not run. Connector-only intentionally skips the non-applicable Data Model
+gate; every other section must be approved before mutation starts.
+
+The architecture-only pass is the sole owner of the
+`NEEDS_CONTEXT: dataverse-planning-mode:<required|connector-only>` signal.
+During the completion pass, receiving that signal again is malformed and must
+be treated as `BLOCKED`.
#### 3.0 — Sub-agent return-status switch (canonical)
-Use the plugin-wide protocol in [`AGENTS.md`](${PLUGIN_ROOT}/AGENTS.md) rule #10 for every `Task` return in this skill: planner, parallel screen-builders, and future agent spawns. Parse the literal first line and branch: `DONE` continues; `DONE_WITH_CONCERNS:` surfaces + records in `memory-bank.md`; `NEEDS_CONTEXT:` re-dispatches with missing context, capped at 2 retries; `BLOCKED:` stops and records under `## Blocks`. Unknown first lines are malformed and must be treated as `BLOCKED`.
+**Architecture-gate result (handle before generic retries).** Only a planner
+dispatched with `Architecture phase: gate-only` may return exactly
+`NEEDS_CONTEXT: dataverse-planning-mode:required` or
+`NEEDS_CONTEXT: dataverse-planning-mode:connector-only` as success. Read
+`.tmp/approved-architecture.md`: its mode must match the returned value, it
+must contain the exact approved Native Capabilities and Connectors sections,
+the data-platform choice, and a user-approval timestamp. A missing or malformed
+artifact returns to the Architecture gate recovery path, not to metadata
+discovery. On success, restore those inputs, set `<dataverse_planning_mode>`,
+and continue to deferred publisher/snapshot work only for `required`. This
+does not consume the generic retry budget and must not re-present Gate 1.
+In `complete` phase or from any other agent, that signal is malformed; do not
+let it change an already approved data platform.
+
+**Screen-graph recovery (handle before generic retries).** A `screen-planner`
+dispatched with `phase: specs` may return `NEEDS_CONTEXT: graph missing <thing>`.
+Follow the graph-repair and Gate 3 approval loop in Step 3.0a above (or the same
+loop inside `native-app-planner`). Preserve other approved sections, invalidate
+the affected screen approvals, and require fresh user acceptance before specs
+resume. This does not authorize a specs pass to modify the approved graph.
+
+For all other first lines, use the plugin-wide protocol in
+[`AGENTS.md`](${PLUGIN_ROOT}/AGENTS.md) rule #12 for every `Task` return.
+`DONE` continues after output validation; `DONE_WITH_CONCERNS:` surfaces and
+queues concerns for the memory bank; `NEEDS_CONTEXT:` re-dispatches with missing
+context, capped at 2 retries; `BLOCKED:` reports the blocker. Unknown first
+lines are malformed. Recoverable artifact/input failures return to their
+owning phase for repair; they never authorize skipping an applicable gate.
**Data-model exact-name expansion:** when the planner or direct architect
returns exactly
@@ -744,7 +893,9 @@ Example: `INDUSTRY_CONFIRM_REQUESTED: productivity|no-keywords|field-ops,healthc
This fires before Gate 1 — it's not a gate, just a confidence check so the wrong industry doesn't silently lock in the design language for the entire app.
-**Skip this section if `<design_vibe_opt_in>` is `yes` or `skip`** — in those cases the user is either driving design explicitly (`yes`) or has opted out of design entirely (`skip`), so industry inference doesn't matter.
+**Skip this section if `<design_vibe_opt_in>` is `yes`, `done`, `deferred`, or
+`skip`**. The normal create flow uses `deferred`, so `/design-system` owns the
+user-facing design decision without another planning question.
**When you see `INDUSTRY_CONFIRM_REQUESTED:` and `<design_vibe_opt_in>` is `no`:**
@@ -803,36 +954,26 @@ This fires before Gate 1 — it's not a gate, just a confidence check so the wro
If the planner's first return is anything other than `DESIGN_VIBE_REQUESTED:` — i.e. it ran all gates including Gate 4 normally — skip directly to Step 3b.
-#### Step 3b — Open the plan preview in the user's browser (orchestrator-owned)
-
-The planner emits a line of the form `PLAN_PREVIEW_PATH: file://<abs-path>/_plan_preview.html` before each Gate 4 plan-mode entry. The planner itself does NOT open the browser — sub-agent shells often lose GUI context, and silent open-failures leave the user staring at the spinner with no preview. The orchestrator owns this step because it has the user's interactive session.
+#### Step 3b — Structural review and legacy preview output
-**When to run this:** every time the planner enters or re-enters Gate 4 (initial pass + each reject loop). Detection: scan the planner's most recent visible output for the `PLAN_PREVIEW_PATH:` token; the value after the colon is the absolute `file://` URL.
+Gate 4 remains markdown-only in this create flow, including reject/re-plan loops.
+For deferred or skipped design, screen-planner receives `skip_preview: true`, so
+no `PLAN_PREVIEW_PATH:` token is expected. Its absence is not an error, and
+`<visual_companion> = yes` does not request an earlier preview.
-**What to do:**
+If a legacy planner emits `PLAN_PREVIEW_PATH: file://<abs-path>/_plan_preview.html`,
+ignore that early preview output. Do not open it or request a replacement HTML
+preview at Gate 4. Step 6.75 produces the fresh preview after the design choice,
+using locked brand tokens or the design-system Skip path's defaults, and honors
+the persisted Visual Companion preference for automatic browser opening.
-1. Print the link in a dedicated message so the user always has the fallback (clickable in most terminals):
+After the structural review, print:
- > "Plan-time visual preview: file://<abs-path>/_plan_preview.html"
+> "Gate 4 reviewed structurally. Visual preview is deferred to Step 6.75."
-2. **If `<visual_companion> = no`, stop here.** Do not attempt to open a browser. The user explicitly opted out; the printed link is their handle. Continue immediately to the planner's Gate 4 prompt.
+With `--no-design`, Step 6.75 and its HTML preview are both skipped. Print instead:
-3. **Else** attempt to open in the user's default browser via the OS-portable chain:
-
- ```bash
- open "<abs-path>/_plan_preview.html" 2>/dev/null \
- || xdg-open "<abs-path>/_plan_preview.html" 2>/dev/null \
- || powershell.exe -NoProfile -Command "Start-Process '<abs-path>\_plan_preview.html'" 2>/dev/null \
- || echo "Auto-open failed. Use the link above."
- ```
-
-4. Do NOT block on success. If the chain prints "Auto-open failed", the link from step 1 is the user's fallback. Continue immediately so the planner's plan-mode prompt surfaces without delay.
-
-If the planner returns without emitting a `PLAN_PREVIEW_PATH:` line, that is **expected** — the planner passes `skip_preview: true` to screen-planner since `/design-system` (always installed) renders the single visual preview at Step 6.75 after brand locks. Print:
-
-> "→ Gate 4 reviewed structurally. Visual preview will appear at Step 6.75 after `/design-system` locks your brand tokens (~5 min from now after scaffold)."
-
-…and continue without attempting any browser open. **Do not warn or treat this as an error** — it is the documented behavior.
+> "Gate 4 reviewed structurally. HTML preview skipped (--no-design)."
#### 3.9 — Post-plan publisher-prefix gate
@@ -1139,7 +1280,7 @@ Immediately after creating `memory-bank.md`, flush any queued planner concerns f
**Also persist the Visual Companion preference** so re-runs (`/edit-app`, `/preview-screens`, future `/design-system` runs) honor it without re-asking. Append to the Project facts section:
```
-visual_companion: <yes|no> # set in Step 2b — controls whether browser previews open automatically
+visual_companion: <yes|no> # default from Step 2b; applied at Step 6.75 and later previews
```
`/preview-screens` reads this flag when invoked from inside this project; if `no`, it prints the file path instead of opening. `/edit-app` reads it to decide whether to re-open `_plan_preview.html` after a re-plan. The flag is per-project and does not leak across apps.
@@ -1163,7 +1304,7 @@ Arguments:
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.
Handle the return per the status protocol (AGENTS.md rule #10):
-- `DONE` → continue to Step 6.85. Record `brand_path`, `tokens_path`, `direction` in memory-bank.
+- `DONE` → finish the applicable preview branch below, then continue to Step 7. Record `brand_path`, `tokens_path`, `direction` in memory-bank.
- `DONE_WITH_CONCERNS` → surface concerns, ask user, continue.
- `NEEDS_CONTEXT` → surface question, re-invoke with answer.
- `BLOCKED` → surface error, STOP.
@@ -1185,7 +1326,7 @@ The user skipped the design system but still deserves to see their screens befor
2. **Render `_plan_preview.html`** — read the screen specs from `native-app-plan.md` `## Screens` section and render key screens (one List + one Form + one Detail, first match per archetype) using the `tamagui-html-mapping.md` reference and industry-inferred defaults from `## Design Direction`. Write to `<working_dir>/_plan_preview.html`.
-3. **Open in browser** (if `<visual_companion> = yes`):
+3. **Print the preview path; open in browser only if `<visual_companion> = yes`:**
```bash
open "<working_dir>/_plan_preview.html" 2>/dev/null \
|| xdg-open "<working_dir>/_plan_preview.html" 2>/dev/null \
@@ -1193,47 +1334,18 @@ The user skipped the design system but still deserves to see their screens befor
|| true
```
-4. **Auto-continue — no prompt.** The user already approved Gates 1–3 via plan-mode and just looked at the preview. A fourth confirmation here adds friction without adding decision power. Print one line and proceed:
-
- > `→ Preview rendered with default styling. Continuing to Step 6.85. (Interrupt and re-run /design-system or /edit-app to revise.)`
-
-This ensures **every path through the flow gets at least one visual preview** before screen-builders write code.
-
-**Why this matters:** under the OLD two-preview flow, the user saw screens at Gate 4 with default Tamagui colors, mentally committed, then the brand re-rendered later — confusing visual whiplash plus ~3–5 min of wasted token spend on the Gate 4 HTML. Under the NEW flow, Gate 4 is a markdown screen-graph (structural only), and the user only ever sees one HTML preview — at Step 6.75, with the locked brand applied. Single visual decision point, no waste.
+4. **Auto-continue — no prompt.** The user already approved the applicable planning gates; the preview does not introduce another approval gate. Print one line and proceed:
-### Step 6.85 — Offline profile (always asked)
+ > `→ Preview rendered with default styling. Continuing to Step 7. (Interrupt and re-run /design-system or /edit-app to revise.)`
-**Print before starting:**
-> "→ [Step 6.85/13] Asking whether to set up an offline profile…"
-
-Mobile Offline Profiles let users continue working when their device is disconnected — Dataverse syncs queued changes when connectivity returns. **This question must be asked on every run of `/create-mobile-app`** — do NOT skip it based on the initial prompt's wording, the feature picker checkboxes, the requirements brief content, or any keyword heuristic. The user's intent for offline support is not reliably inferrable from any earlier step; the only authoritative signal is an explicit answer here. The plugin owns the setup via [`/setup-offline-profile`](../setup-offline-profile/SKILL.md).
-
-**Pre-conditions — only TWO branches skip this question, both with the explicit print line shown:**
-
-| Condition | Action |
-|---|---|
-| App uses zero Dataverse tables (connectors-only — no `.datamodel-manifest.json`) | Skip — offline profiles are Dataverse-only. Print: `↷ Step 6.85 skipped — no Dataverse tables in this app.` Continue to Step 7. |
-| `memory-bank.md` `## Offline profile` already has `status: done` OR `status: not-applicable` from a prior run | Skip — answered previously. Print: `↷ Step 6.85 skipped — offline profile already <done\|not-applicable> from a prior run.` Continue to Step 7. |
-| Anything else (default — including "user didn't say 'offline' anywhere") | **Ask the question below.** |
+**Preview timing:** For current and legacy planner output, Gate 4 remains markdown-only.
+Step 6.75 is the only screen-preview stage in this create flow: Branch A uses locked
+brand tokens; Branch B uses defaults. `visual_companion: no` disables automatic
+browser opening, not rendering. `--no-design` skips this stage and its HTML preview.
-> **Important — do NOT add other skip conditions.** Earlier versions of this skill had an "auto-detect / keyword scan" preamble (`offline · field · remote · ...`) that varied the question default based on whether the initial prompt mentioned offline-indicator keywords. That heuristic was removed because it caused the orchestrator to skip the question entirely when no keywords matched, leaving users with a stale or missing profile on the next sync. The question is now unconditional for any Dataverse-backed app that hasn't already answered.
-
-**Ask one `AskUserQuestion`** — phrased neutrally, no implication that the user "should" answer Yes or No based on app type:
-
-> **Question header**: `Offline support`
->
-> **Question body**: "Mobile Offline Profiles let users continue working when their device is disconnected — Dataverse syncs queued changes when connectivity returns. Set one up now?"
->
-> **Options** (default = `Yes`):
-> - `Yes — create profile now (recommended)` — invokes `/setup-offline-profile`, walks the 3-gate flow, then continues to Step 7
-> - `Skip — I'll add it later via /setup-offline-profile` — continues to Step 7 with no profile (memory-bank status stays unset so the question fires again on the next `/create-mobile-app` run against this dir)
-> - `Skip — this app doesn't need offline support` — continues to Step 7; sets `memory-bank.md` `## Offline profile` `status: not-applicable` so future re-runs don't re-ask
-
-If the user picks Yes, invoke `/setup-offline-profile` as a sub-skill. It reads the same `.datamodel-manifest.json` you just wrote (Step 6 `/add-dataverse`'s Step 6d output) — no need to pass arguments. The sub-skill returns `DONE` / `DONE_WITH_CONCERNS:` / `BLOCKED:` per the agent return-status protocol. On `BLOCKED:`, propagate up. On `DONE_WITH_CONCERNS:`, surface concerns to the user inline, then continue.
-
-**State transfer:** `/setup-offline-profile` updates `memory-bank.md` `## Offline profile` and writes `offline-profile.json` to the project root. Step 13 (final summary) reads these for the wrap-up summary.
-
-**Hooked into `/add-dataverse`:** Step 6 (just before this step) sets `IsAvailableOffline=true` + `ChangeTrackingEnabled=true` on every new custom table (see [skills/add-dataverse/SKILL.md](../add-dataverse/SKILL.md) Step 5b body skeleton). That means `/setup-offline-profile` Gate 1 will be a no-op pass-through for fresh scaffolds — saving the user one approval click.
+Offline profile setup is intentionally deferred until after the approved
+Dataverse model has been materialized. Follow the shared connectivity-intent
+ownership contract during this phase.
### Step 7 — Auth config
@@ -1355,7 +1467,8 @@ Do NOT touch `src/playerConfig.ts` — auth identifiers live in `auth.config.jso
If `<dataverse_planning_mode> = connector-only`, verify the approved
`## Data Model` says zero Dataverse tables and no `.datamodel-manifest.json`
exists, print `↷ Step 8 skipped — connector-only app has no Dataverse data model.`,
-skip Step 8.5 as well, and continue to Step 9. A non-empty Dataverse plan in
+skip sample data and offline-profile setup, print
+`↷ Offline profile skipped — no Dataverse tables in this app.`, and continue to Step 9. A non-empty Dataverse plan in
this mode is a planning mismatch and must be corrected before continuing.
**Print before starting:**
@@ -1495,6 +1608,21 @@ If this fails, do not continue to native capabilities, connectors, navigation, o
### Step 8.5 — Seed sample data (auto)
+Before sample data or offline setup, require the materialized table inventory
+from `/add-dataverse` Step 6d, including verified reused tables. Compare its
+coverage with the validated operation manifest's `service.requiredTables` and
+run `verify-dataverse-services.js --project-root "<working_dir>" --manifest "$OPERATION_MANIFEST"`.
+Zero schema writes is a valid reuse-only result, not failed materialization.
+If an older run produced an empty or partial table inventory, recover through
+`/add-dataverse` Steps 6c–6d using the approved service list and verified live
+metadata. Rebuild the local manifest without replaying successful metadata
+writes, then rerun coverage/service verification.
+
+If `.datamodel-manifest.json` is missing, malformed, or contains no Dataverse
+tables after that recovery, return `BLOCKED: Dataverse materialization did not
+produce a usable .datamodel-manifest.json` with the remaining verification
+failure. Do not seed or offer offline setup from unverified table names.
+
**Print before starting:**
> "→ [Step 8.5/13] Checking existing record counts and seeding sample data into tables with fewer than 5 records."
@@ -1509,9 +1637,52 @@ Arguments:
`/add-sample-data` reads `.datamodel-manifest.json`, queries the current record count for each table, skips any table that already has ≥5 records, and seeds the rest with contextually appropriate rows in dependency-tier order. Inserted GUIDs are tracked in `memory-bank.md` for idempotent re-runs.
-If `.datamodel-manifest.json` is missing, surface as `DONE_WITH_CONCERNS` and continue — it means Step 8 didn't complete cleanly.
+If the seeding step fails (network drop, permission error, etc.), surface the
+failure but continue to the offline-profile phase — the app is still usable,
+just empty on first launch. The user can re-run `/add-sample-data` later to
+retry.
-If the seeding step fails (network drop, permission error, etc.), surface the failure but continue to Step 9 — the app is still usable, just empty on first launch. The user can re-run `/add-sample-data` later to retry.
+### Offline profile (Dataverse-backed apps)
+
+**Print before starting:**
+> "→ [Offline profile] Asking whether to set up a Mobile Offline Profile…"
+
+Mobile Offline Profiles let the runtime package continue against Dataverse
+when connectivity is unavailable and synchronize queued changes later. This phase owns Mobile Offline Profile opt-in. Apply
+[`shared/references/connectivity-intent-ownership.md`](${PLUGIN_ROOT}/shared/references/connectivity-intent-ownership.md).
+
+Before asking, parse `.datamodel-manifest.json` and require at least one
+verified Dataverse table, including reused tables. If the manifest is missing,
+malformed, empty, or missing a service-required table, use the read-only manifest
+recovery in Step 8.5 before asking. If verification still fails, report
+`BLOCKED: offline setup requires the materialized Dataverse manifest from Step 8`
+with the specific remaining failure.
+Do not infer connector-only from a missing manifest.
+
+Skip only when `memory-bank.md` `## Offline profile` already records
+`status: done` or `status: not-applicable`. Print:
+`↷ Offline profile skipped — already <done|not-applicable> from a prior run.`
+
+Otherwise ask one neutral foreground question:
+
+> **Question header:** `Offline support`
+>
+> **Question body:** "Mobile Offline Profiles let users continue working when
+> their device is disconnected — Dataverse syncs queued changes when
+> connectivity returns. Set one up now?"
+>
+> **Options:**
+> - `Yes — create profile now (recommended)` — invoke
+> `/setup-offline-profile`, then continue to Step 9
+> - `Skip — I'll add it later via /setup-offline-profile` — continue to Step 9
+> without recording a final answer
+> - `Skip — this app doesn't need offline support` — record
+> `status: not-applicable`, then continue to Step 9
+
+If the user selects Yes, invoke `/setup-offline-profile` from the project root.
+It consumes the materialized manifest, owns its own profile approval flow, and
+writes `offline-profile.json`. Surface concerns and stop on a substantive
+failure. Do not reopen data-model or screen approvals after this choice.
### Step 9 — Apply native capabilities
@@ -1540,7 +1711,7 @@ If the plan says "None — this app uses only standard React Native components a
Read and execute the Installation Contract in [`shared/references/javascript-dependency-planning.md`](${PLUGIN_ROOT}/shared/references/javascript-dependency-planning.md) for every approved row in `## Screens → ### JavaScript Dependencies`. If the subsection is absent or says `None.`, continue without changing dependencies.
-Gate 4b approval is consent for exactly the packages and versions in the table. Install them into `<working_dir>` before any skeleton or builder imports them, validate `package.json` and the lockfile, and verify module resolution. Do not substitute another package/version, infer a package from a compiler error, or route a JS-only package through `/add-native`. If final inspection finds native code/config or incompatible runtime dependencies, remove only the newly added package and STOP with the exact failed criterion.
+Gate 4 approval is consent for exactly the packages and versions in the table. Install them into `<working_dir>` before any skeleton or builder imports them, validate `package.json` and the lockfile, and verify module resolution. Do not substitute another package/version, infer a package from a compiler error, or route a JS-only package through `/add-native`. If final inspection finds native code/config or incompatible runtime dependencies, remove only the newly added package and STOP with the exact failed criterion.
### Step 9b — Apply design system
diff --git a/plugins/mobile-apps/skills/create-mobile-app/references/requirements-discovery.md b/plugins/mobile-apps/skills/create-mobile-app/references/requirements-discovery.md
index ea61f8818..869740147 100644
--- a/plugins/mobile-apps/skills/create-mobile-app/references/requirements-discovery.md
+++ b/plugins/mobile-apps/skills/create-mobile-app/references/requirements-discovery.md
@@ -9,11 +9,11 @@ Scan the user's description and wizard answers for these signals, then confirm i
| Signal in description | Infer |
|---|---|
| "log", "record", "submit", "fill out" | Data entry / form screens |
-| "photo", "attach", "image", "camera" | Camera capability + image column |
-| "pick file", "upload PDF", "import document", "attach file" | Document-picker capability + optional Dataverse File column |
-| "generate PDF", "export report", "print report", "evidence packet", "certificate PDF" | PDF-report capability + optional Dataverse File column when retained |
+| "photo", "attach", "image", "camera" | Camera capability; storage target is resolved at the architecture gate |
+| "pick file", "upload PDF", "import document", "attach file" | Document-picker capability; storage target is resolved at the architecture gate |
+| "generate PDF", "export report", "print report", "evidence packet", "certificate PDF" | PDF-report capability; retention target is resolved at the architecture gate |
| "view PDF", "open PDF", "preview PDF" | Native PDF viewer capability for HTTPS URLs or local `file://` URIs with viewer 0.2.9+ |
-| "signature", "sign", "sign off", "approval", "pen", "ink", "draw" | Pen-input capability + Dataverse Image/File storage target |
+| "signature", "sign", "sign off", "approval", "pen", "ink", "draw" | Pen-input capability; storage target is resolved at the architecture gate |
| "track location", "background location", "GPS tracking", "follow route", "breadcrumb", "field worker location" | Geolocation capability (`@microsoft/power-apps-native-bglocation`) + Dataverse location table (default `msdyn_locationrecords`) |
| "current location", "where am I", "tag with coordinates", "one-shot location" | One-shot location capability (`expo-location`) |
| "share", "send to", "export" | Sharing capability |
@@ -26,12 +26,20 @@ Scan the user's description and wizard answers for these signals, then confirm i
Do not infer capabilities the template does not ship. Resolve every native signal against the live `template/package.json`; if a package is absent or runtime-banned, surface that as a transparency note instead of pretending the capability exists. Use `agents/native-app-planner.md` Step 3.0 as the canonical native allowlist.
+Apply the shared
+[`connectivity-intent-ownership.md`](${PLUGIN_ROOT}/shared/references/connectivity-intent-ownership.md)
+contract during feature inference.
+
PDF/pen rules:
- Do not infer `document-picker` from generic "PDF" alone; use the specific signal rows above.
- Native PDF viewing supports HTTPS URLs and local `file://` URIs with `@microsoft/power-apps-native-pdf-viewer` 0.2.9+.
- Local generated PDFs require `expo-print`; preview requires native PDF viewer 0.2.9+, while sharing requires `expo-sharing`.
-- Retained generated PDFs require a Dataverse File column or child Evidence/Attachment table.
-- Signature/ink capture must record a Dataverse target in `native-app-plan.md`: Image column, File column, or child Evidence/Signature table.
+- Retained generated PDFs use a Dataverse File column or child
+ Evidence/Attachment table only when Dataverse is approved; otherwise use an
+ approved connector-owned or on-device/share-only target.
+- Signature/ink capture must record the Gate 1-approved target in
+ `native-app-plan.md`: Dataverse Image/File/child row, connector-owned storage,
+ or on-device/share-only.
- Background/continuous location tracking uses the `geolocation` capability (`@microsoft/power-apps-native-bglocation`, MSAL-only) and requires an existing Dataverse target table (default entity set `msdyn_locationrecords`, or a custom `tableName` whose `fieldMap` columns exist). `/add-native geolocation` must verify that table; if it is missing, do not allow the control to be used. The missing control table is not created through `/add-dataverse`; use the geolocation-control table provisioning/setup mechanism, then re-run `/add-native geolocation`. Use one-shot `location` (`expo-location`) for a single foreground coordinate read; do not conflate the two.
## Ask Shape
diff --git a/plugins/mobile-apps/skills/setup-offline-profile/SKILL.md b/plugins/mobile-apps/skills/setup-offline-profile/SKILL.md
index a318f1d63..f3f237085 100644
--- a/plugins/mobile-apps/skills/setup-offline-profile/SKILL.md
+++ b/plugins/mobile-apps/skills/setup-offline-profile/SKILL.md
@@ -18,7 +18,17 @@ model: opus
End-to-end wizard for creating a Dataverse Mobile Offline Profile that the app (and any other compatible Power Apps client) can use to download data for offline access.
-**Scope of v0**: authoring only. This skill creates the Dataverse entities (`mobileofflineprofile`, `mobileofflineprofileitem`, `mobileofflineprofileitemassociation`) and writes the full app-level offline config — profile metadata, per-table scope, and the temporary SDK-workaround fields — to `offline-profile.json`. **This skill does NOT modify `power.config.json`** (that file is owned by `npx power-apps init` and its schema is controlled upstream). It also does NOT scaffold an offline runtime (SQLite store, sync engine, write queue) in the generated app — that's gated on upstream `@microsoft/power-apps-native-host` runtime support.
+**Scope of v0**: configuration only. This skill creates records in the existing
+Dataverse Mobile Offline Profile tables (`mobileofflineprofile`,
+`mobileofflineprofileitem`, `mobileofflineprofileitemassociation`) and writes
+the full app-level offline config — profile metadata, per-table scope, and the
+temporary SDK-workaround fields — to `offline-profile.json`. **This skill does
+NOT modify `power.config.json`** (that file is owned by `npx power-apps init`
+and its schema is controlled upstream). The template already bundles
+`@microsoft/power-apps-native-offline`; `@microsoft/power-apps-native-host`
+consumes the profile and owns local SQLite access, queued synchronization,
+reconnect behavior, and status UX. This skill does not scaffold duplicate
+app-owned offline runtime code.
**Out of scope for v0**:
- Custom filter mode (`recorddistributioncriteria=3`, savedquery picker) — defer to v0.5
@@ -79,7 +89,7 @@ Read `memory-bank.md` `## Offline profile` block. Decide based on `status`:
| `status` value | Action |
|---|---|
| (section absent) OR `status: none` | First-time run. Continue to Step 2. |
-| `status: not-applicable` | User previously opted out via `/create-mobile-app` Step 6.85 ("doesn't need offline support"). Re-confirm: "Memory-bank says this app doesn't need offline. Override and proceed? (y/N)". Default N stops here. |
+| `status: not-applicable` | User previously opted out during `/create-mobile-app` offline-profile setup ("doesn't need offline support"). Re-confirm: "Memory-bank says this app doesn't need offline. Override and proceed? (y/N)". Default N stops here. |
| `status: done` AND a profile matching `profileId` still exists in env | Already complete. Print summary from the memory-bank block; ask user if they want to `/edit-offline-profile` (v0.2) or just exit. |
| `status: done` BUT `GET /mobileofflineprofiles(<profileId>)` returns 404 | Profile was deleted externally (maker portal or another env). Treat as `none`; clear the section; continue to Step 2. |
| `status: in-progress` AND profile exists in env | **Resume flow** — see below. |
@@ -693,9 +703,10 @@ Next steps:
- /preview-offline-scope → estimate download size before pushing the app (not yet implemented — v0.2)
- /edit-offline-profile <table> → re-scope one table (not yet implemented — v0.2)
-Note: The Expo runtime does not yet consume this profile automatically. The profile is now
-authored in Dataverse and any compatible Power Apps client (canvas, model-driven) will use it.
-Native runtime support remains deferred until upstream host support is confirmed.
+Runtime: The template bundles @microsoft/power-apps-native-offline.
+@microsoft/power-apps-native-host consumes the profile and owns local SQLite access,
+queued synchronization, reconnect behavior, and status UX. This skill configures
+that runtime; it does not scaffold a second app-owned store, queue, or sync engine.
```
## Status code (final line)