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): scope data planning and source lifecycle (#635)

Shubham Agarwalc6994b291854
diff --git a/.github/workflows/mobile-apps-script-tests.yml b/.github/workflows/mobile-apps-script-tests.yml
index 1478e6090..22ba86091 100644
--- a/.github/workflows/mobile-apps-script-tests.yml
+++ b/.github/workflows/mobile-apps-script-tests.yml
@@ -5,8 +5,7 @@ name: mobile-apps-script-tests
on:
pull_request:
- branches:
- - main
+ # Cover stacked PRs too; the path filter keeps this workflow plugin-scoped.
paths:
- "plugins/mobile-apps/**"
- ".github/workflows/mobile-apps-script-tests.yml"
diff --git a/plugins/mobile-apps/.claude-plugin/plugin.json b/plugins/mobile-apps/.claude-plugin/plugin.json
index f7597a5b6..64c153ba4 100644
--- a/plugins/mobile-apps/.claude-plugin/plugin.json
+++ b/plugins/mobile-apps/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "mobile-app",
- "version": "0.5.1",
+ "version": "0.5.2",
"description": "Build and deploy Power Apps code apps for mobile using Expo (React Native), with native device functionality and Power Platform connectors",
"author": {
"name": "Microsoft",
diff --git a/plugins/mobile-apps/.plugin/plugin.json b/plugins/mobile-apps/.plugin/plugin.json
index f7597a5b6..64c153ba4 100644
--- a/plugins/mobile-apps/.plugin/plugin.json
+++ b/plugins/mobile-apps/.plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "mobile-app",
- "version": "0.5.1",
+ "version": "0.5.2",
"description": "Build and deploy Power Apps code apps for mobile using Expo (React Native), with native device functionality and Power Platform connectors",
"author": {
"name": "Microsoft",
diff --git a/plugins/mobile-apps/AGENTS.md b/plugins/mobile-apps/AGENTS.md
index df7f88d7e..16263df4a 100644
--- a/plugins/mobile-apps/AGENTS.md
+++ b/plugins/mobile-apps/AGENTS.md
@@ -84,6 +84,38 @@ Do not add preparation rewrites for `scheme`, `package`, `bundleIdentifier`, `sr
16. **Custom events are Application Insights-specific and opt-in** — Each generated app targets one customer-owned, workspace-based Application Insights resource. `app.json` → `expo.extra.appInsightsConfig` defaults to disabled and stores its connection string, matching the Power Apps canvas-app model. Treat the value as sensitive project configuration: do not print it, write it to `memory-bank.md`, or include it in summaries. Keep `includeUserId` false unless explicitly approved.
17. **Plugin update notification** — Immediately after the frontmatter of every `user-invocable: true` skill except `/check-updates`, run `node "${PLUGIN_ROOT}/scripts/check-version.js"` and show any output before proceeding. The check is best-effort and must never block the requested workflow. `/check-updates` owns its explicit plugin-version check in Step 1 and must not run a duplicate startup check.
+18. **Data-source operations preserve scope and app identity** — Before data
+ work, follow [Data-source invocation scope](shared/shared-instructions.md#data-source-invocation-scope).
+ Standalone workflows approve the current delta; child calls carry the owner,
+ phase, absolute root, and exact approved operations. Neither a flag nor an
+ old plan grants approval. Every shell/file operation uses the same root;
+ follow [app-working-directory.md](shared/references/app-working-directory.md)
+ for Bash and PowerShell guards.
+19. **Data-source retirement is app-local and CLI-owned** — After approved
+ consumer edits, use the supported removal command to update registrations,
+ schemas, and generated models/services, then regenerate the runtime schema
+ map. Never turn a removed plan row into server-table deletion. Follow
+ [data-source-removal.md](shared/references/data-source-removal.md)
+ for shared-reference safety, inventory/offline reconciliation, and no-op
+ detection; successful exit alone is insufficient.
+20. **Seed scope is not the schema inventory** — Orchestrated `/add-sample-data`
+ calls pass an approved `--tables` allowlist and retiring-table exclusions.
+ Lookup fanout, prototype seeds, media uploads, and retries cannot widen that
+ scope. Preserve transitional manifest entries until verified removal.
+21. **Offline retirement survives addition checks** — Preserve per-table
+ `offlineRetirement` outcomes in leaf results and memory-bank. Addition-only
+ `in-sync` never clears a pending profile decision/migration. App-binding
+ approval is not permission to delete offline profile items or server data.
+22. **Data-only planning shares creation's helpers, not its gates** —
+ Setup/standalone proposals use compact hash-bound evidence, snapshot-only
+ architect context, and decision validation before the existing approval.
+ The same checks apply to diagrams and inline fallbacks. Preapproval
+ environment resolution uses `--no-cache --require-tenant`; never downgrade
+ to the persistent resolver. Follow
+ [scoped Dataverse planning](shared/references/dataverse-change-planning.md).
+ Do not fabricate the four-approval create-only execution receipt for a
+ data-only change.
+
## Telemetry
Mobile Apps bundles the canonical stdlib-only telemetry helpers from the repo-root `shared/telemetry/lib` at `scripts/lib/telemetry/lib`. Edit the shared source first, then refresh this physical copy in the same change; never copy another plugin's `ikey.json` or resolver.
diff --git a/plugins/mobile-apps/README.md b/plugins/mobile-apps/README.md
index 0317bd2aa..a9bed701c 100644
--- a/plugins/mobile-apps/README.md
+++ b/plugins/mobile-apps/README.md
@@ -226,6 +226,24 @@ Native modules are allowlist-bound by the current template `package.json`. If th
Runs `pa app add data-source` under the hood, regenerates services, prints how to import in your screens.
+### Data-source planning, refresh, and retirement
+
+Use `/setup-datamodel` or `/add-dataverse` to review and approve a data change.
+Add `--plan-only` to preview it without changing the app or its data.
+
+For an existing binding, use the dedicated operation instead of adding it again:
+
+```text
+> /add-dataverse --refresh --data-source-name <registered-name>
+> /add-connector --refresh --data-source-name <registered-name>
+> /add-sharepoint --remove --data-source-name <registered-name>
+```
+
+Refresh updates an existing source without adding it again. Removal stops if
+app code still uses the source and never deletes server tables, records, lists,
+or connections. These commands update the data layer; request screen changes
+separately through `/edit-app`. Cloud-flow integration is not supported.
+
### 5. Iterate on the generated app after the fact
```text
@@ -271,7 +289,7 @@ Example edit flows:
| `/create-mobile-app` | ✅ v0 | Orchestrator — starts from a fresh installed `expo-app-standalone` template folder, gates planning, runs `pa app init`, resolves the selected environment tenant, discovers tenant-visible app registrations and checks the complete required permission profile, lets the user select or create one (or skip auth), then applies data/native/connectors, builds screens, starts dev server |
| `/set-app-registration-native` | ✅ v0 | Auth helper — discovers tenant-visible app registrations, checks the applicable native runtime permission profile, opens the environment-specific Wrap page for creation or repair, and writes the selected client ID to `auth.config.json`. |
| `/add-dataverse` | ✅ v0 | Add Dataverse — connect to existing tables, or create / extend tables in Tier 0 → N order via the Dataverse Web API, then generate TS services. Accepts ER diagrams via image / Mermaid / text, or spawns the data-model-architect agent. |
-| `/setup-datamodel` | ✅ v0 | Discoverable alias for `/add-dataverse` optimized for the design-first entry point ("how do I plan my Dataverse schema?"). Same workflow under a more searchable name. |
+| `/setup-datamodel` | ✅ v0 | Plan and approve a scoped Dataverse/connector change, apply only accepted data operations, refresh retained bindings, or retire app-local bindings after consumer checks. `--plan-only` returns before saving or applying. |
| `/add-connector` | ✅ v0 | Generic connector — runs `pa app add data-source` for any first-party or custom connector |
| `/add-native` | ✅ v0 | Add a supported native capability/control (camera, image-picker, barcode/QR scanner, document-picker, PDF viewer/report, pen/signature, secure-store, file-system, sharing, haptics, etc.) — verifies the module already ships in the template and writes typed wrappers under `src/native/` without installing native packages or editing `app.config.js` |
| `/list-connections` | ✅ v0 | Finds or creates a Power Platform connection ID, or resolves a solution connection reference, for `pa app add data-source`. Use when adding non-Dataverse connectors or re-binding after a 401. |
diff --git a/plugins/mobile-apps/agents/data-model-architect.md b/plugins/mobile-apps/agents/data-model-architect.md
index bd96fcda6..b9ddbf1c4 100644
--- a/plugins/mobile-apps/agents/data-model-architect.md
+++ b/plugins/mobile-apps/agents/data-model-architect.md
@@ -17,12 +17,23 @@ tools:
You are a Dataverse data model architect for native Power Apps code apps. Your job is to analyze the user's app requirements, discover existing tables in the target environment, and propose a complete data model — **without creating or modifying anything**. You are strictly read-only and advisory.
-You will be invoked by `native-app-planner` or `/edit-app` with a prompt that includes:
+**App root:** before any project read or command, execute
+[app-working-directory.md](${PLUGIN_ROOT}/shared/references/app-working-directory.md).
+Require the owner's absolute `working_dir` and use it for every shell call and
+file tool, including snapshot validation, legacy discovery, scratch output, and
+retries. Missing/conflicting context returns `NEEDS_CONTEXT` before project
+access; never use the agent's launch directory as a fallback.
+
+You will be invoked by `native-app-planner`, `/setup-datamodel`, `/edit-app`,
+or standalone `/add-dataverse` with a prompt that includes:
- The user's app requirements
- Wizard answers (target users, aesthetic, features)
- The working directory
- The plugin root
+- **Scoped change context** (setup/standalone) — current delta, retained
+ native/connector constraints, `phase: planning`, and the proposal-only mode.
+ Existing plan rows are context, not permission to recreate unrelated tables.
- **Normalized Dataverse foreground planning snapshot path (validation only)** —
an absolute path to
`<working_dir>/.tmp/dataverse-foreground-planning-snapshot.json`. Do not read
@@ -42,6 +53,12 @@ You will be invoked by `native-app-planner` or `/edit-app` with a prompt that in
## Hard Rules
- **Read-only.** You MUST NOT run `pa app add data-source --connector dataverse --org-url <env-url> --table <table>`, table-creation HTTP calls, or any mutating PowerShell. Mutation happens later in `/add-dataverse` after user approval.
+- **Scoped proposals preserve the owner.** For setup/standalone change
+ planning, use [dataverse-change-planning.md](../shared/references/dataverse-change-planning.md).
+ Return the proposed delta and required dependencies in `_dm_section.md` and
+ the normalized contract; do not copy unrelated historical creation rows into
+ the executable proposal. The owner merges accepted changes into the full
+ plan and runs its existing gate. Never save the live plan or mint approval.
- **Power Apps CLI failure refresh.** Follow [shared-instructions.md](../shared/shared-instructions.md) command-failure handling for any failed `$PA` (Power Apps CLI) command; retry the original command once after auth is corrected.
- **Reuse-first and target-grounded.** Use exact target metadata for every
proposed table, including standard tables, and prefer reuse > extension >
@@ -113,9 +130,10 @@ evidence path must be supplied. Before planning, validate their hash, environmen
table facts, candidate order, and top-three cap without reading the full snapshot:
```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
node "${PLUGIN_ROOT}/scripts/render-dataverse-architect-evidence.js" \
- --snapshot "<foreground snapshot path>" \
- --output "<compact architect evidence path>" \
+ --snapshot '<foreground snapshot path>' \
+ --output '<compact architect evidence path>' \
--validate-only
```
@@ -170,8 +188,9 @@ If validation succeeds, this path is mandatory:
If either required artifact is missing, invalid, or mismatched, return
`NEEDS_CONTEXT: matching-dataverse-snapshot-and-evidence`. Do not fall back to
live discovery from `required` mode. The legacy live path below remains only
-for callers that omit the new planning mode entirely (for example an older
-`/edit-app` flow).
+for callers that omit the new planning mode entirely (including the existing
+`/edit-app` path). Setup/standalone data planning must not omit `required` to
+bypass missing evidence. The `cross-entity-audit` short circuit remains separate.
## Step 1 — Resolve Target Environment
@@ -189,10 +208,20 @@ Look for `power.config.json` in the working directory:
If present, read the `environmentId` field and resolve it with `scripts/resolve-environment.js`. Otherwise, ask the orchestrator for the target environment URL or ID from context and resolve that:
```bash
-node "${PLUGIN_ROOT}/scripts/resolve-environment.js" <environment-id-or-url>
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
+node "${PLUGIN_ROOT}/scripts/resolve-environment.js" <environment-id-or-url> --no-cache --require-tenant
```
-Capture the **Environment URL** (e.g., `https://orgXXXXX.crm.dynamics.com`), **Environment ID**, and **Tenant ID** from the output. Use the URL as `<envUrl>` for subsequent script calls.
+Even this legacy planning path is non-persisting: do not remove these flags or
+redirect output into app/auth configuration. A failed lookup returns to the
+owner with its error; it never authorizes a configuration write.
+
+Capture the **Environment URL**, **Environment ID**, and **Tenant ID** from the
+output. Use the URL as `<envUrl>` and the validated nonempty tenant as
+`<tenantId>`. Pass `--tenant-id "<tenantId>"` on every metadata helper call and
+retry below; do not inherit a tenant from shell variables or the active Azure
+account. Missing or conflicting tenant context returns `NEEDS_CONTEXT` before
+metadata access.
If resolution fails (not authenticated or environment not visible to the logged-in account), do not stop the run. Skip further discovery, prepend a `Discovery skipped — environment not reachable` warning to your section, and finish with `DONE_WITH_CONCERNS`. The plan is a draft for the user's data-model review; `/add-dataverse` re-queries live metadata and blocks any mutation it cannot verify.
@@ -203,7 +232,8 @@ If resolution fails (not authenticated or environment not visible to the logged-
`resolve-environment.js` only resolves environment metadata; it does not prove Dataverse user access. Verify access before metadata discovery:
```bash
-node "${PLUGIN_ROOT}/scripts/verify-dataverse-access.js" <envUrl>
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
+node "${PLUGIN_ROOT}/scripts/verify-dataverse-access.js" <envUrl> --tenant-id "<tenantId>"
```
If it fails, skip Step 3 and Step 5's live queries, prepend a `Dataverse access failed — az login required` warning to your section, and finish with `DONE_WITH_CONCERNS`. Do not convert unverified guesses into confident decisions.
@@ -220,14 +250,17 @@ If it fails, skip Step 3 and Step 5's live queries, prepend a `Dataverse access
Query custom tables to discover conceptual reuse candidates. This broad query is advisory only; Step 5 still queries every selected custom, standard, and managed table by exact logical name before classifying it:
```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
node "${PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> GET \
- "EntityDefinitions?\$select=MetadataId,LogicalName,DisplayName,Description,IsCustomEntity,IsManaged,IsCustomizable,CanCreateAttributes&\$filter=IsCustomEntity eq true"
+ "EntityDefinitions?\$select=MetadataId,LogicalName,DisplayName,Description,IsCustomEntity,IsManaged,IsCustomizable,CanCreateAttributes&\$filter=IsCustomEntity eq true" \
+ --tenant-id "<tenantId>"
```
For the relevant tables, fetch their user-defined columns in a single call (system columns like `createdon`, `modifiedby`, `statecode`, `ownerid`, `versionnumber` are filtered out automatically):
```bash
-node "${PLUGIN_ROOT}/scripts/list-table-columns.js" <envUrl> <table1> <table2> ...
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
+node "${PLUGIN_ROOT}/scripts/list-table-columns.js" <envUrl> <table1> <table2> ... --tenant-id "<tenantId>"
```
Output is a clean JSON map of `{ tableName: [{ name, type, required }, ...] }`. Pass multiple tables in one invocation.
@@ -273,8 +306,10 @@ legacy live path, resolve every required entity — including `contact`,
dependencies — in a **single** filtered query that also expands their columns:
```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
node "${PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> GET \
- "EntityDefinitions?\$select=MetadataId,LogicalName,SchemaName,IsCustomEntity,IsManaged,IsCustomizable,CanCreateAttributes,PrimaryIdAttribute,PrimaryNameAttribute&\$filter=LogicalName eq '<table1>' or LogicalName eq '<table2>'&\$expand=Attributes(\$select=LogicalName,AttributeType,AttributeTypeName,RequiredLevel,IsManaged,IsCustomizable,IsPrimaryId,IsPrimaryName)"
+ "EntityDefinitions?\$select=MetadataId,LogicalName,SchemaName,IsCustomEntity,IsManaged,IsCustomizable,CanCreateAttributes,PrimaryIdAttribute,PrimaryNameAttribute&\$filter=LogicalName eq '<table1>' or LogicalName eq '<table2>'&\$expand=Attributes(\$select=LogicalName,AttributeType,AttributeTypeName,RequiredLevel,IsManaged,IsCustomizable,IsPrimaryId,IsPrimaryName)" \
+ --tenant-id "<tenantId>"
```
Build the `$filter` by OR-ing every selected logical name. This is the [documented way to query multiple table definitions at once](https://learn.microsoft.com/power-apps/developer/data-platform/query-schema-definitions#basic-retrievemetadatachanges-example) and replaces 2N requests with one. Keep the expanded `$select` to base `AttributeMetadata` properties — one query [cannot cast to a derived column type](https://learn.microsoft.com/power-apps/developer/data-platform/query-schema-definitions#evaluate-other-options-to-retrieve-schema-definitions).
@@ -642,9 +677,10 @@ representable integer bounds; never emit JavaScript-unsafe defaults.
After writing the JSON, normalize and validate it in place:
```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
node "${PLUGIN_ROOT}/scripts/build-dataverse-operation-manifest.js" \
- --normalize-contract "<working_dir>/.tmp/dataverse-schema-contract.json" \
- --output "<working_dir>/.tmp/dataverse-schema-contract.json"
+ --normalize-contract '<working_dir>/.tmp/dataverse-schema-contract.json' \
+ --output '<working_dir>/.tmp/dataverse-schema-contract.json'
```
If normalization fails, fix the exact schema error and rerun it. Do not return
diff --git a/plugins/mobile-apps/agents/native-app-planner.md b/plugins/mobile-apps/agents/native-app-planner.md
index 5d1770adb..84a5674a5 100644
--- a/plugins/mobile-apps/agents/native-app-planner.md
+++ b/plugins/mobile-apps/agents/native-app-planner.md
@@ -746,7 +746,7 @@ Reject loop = re-spawn data-model-architect in `mode: cross-entity-audit` with t
Run the mobile changed-file dispatcher against every file this planner wrote or edited, including `native-app-plan.md` and temporary section files that remain in the project:
```bash
-node "${PLUGIN_ROOT}/scripts/validate-mobile-files.js" --project-root "<working_dir>" --file "<changed-file>" [--file "<changed-file>" ...]
+node "${PLUGIN_ROOT}/scripts/validate-mobile-files.js" --project-root '<working_dir>' --file '<changed-file>' [--file '<changed-file>' ...]
```
Repair reported violations and rerun until it exits `0`. Pass exact changed files, never the whole project root.
@@ -756,8 +756,8 @@ time:
```bash
node "${PLUGIN_ROOT}/scripts/build-dataverse-operation-manifest.js" \
- --normalize-contract "<working_dir>/.tmp/dataverse-schema-contract.json" \
- --output "<working_dir>/.tmp/dataverse-schema-contract.json"
+ --normalize-contract '<working_dir>/.tmp/dataverse-schema-contract.json' \
+ --output '<working_dir>/.tmp/dataverse-schema-contract.json'
```
The gate-owning planner must now finalize the pre-existing
diff --git a/plugins/mobile-apps/agents/offline-profile-architect.md b/plugins/mobile-apps/agents/offline-profile-architect.md
index ca62af07b..1dacadcf1 100644
--- a/plugins/mobile-apps/agents/offline-profile-architect.md
+++ b/plugins/mobile-apps/agents/offline-profile-architect.md
@@ -14,16 +14,36 @@ tools:
# Offline Profile Architect
-You are a Dataverse Mobile Offline Profile architect for native Power Apps code apps. Your job is to analyze the app's data model and screen requirements and propose a complete offline profile — **without creating or modifying anything**. You are strictly read-only and advisory.
+You are a Dataverse Mobile Offline Profile architect for native Power Apps code apps. Your job is to analyze the app's data model and screen requirements and propose a complete offline profile without app or cloud mutations. You may write only the requested proposal section under the owner's app root.
You will be invoked by `/setup-offline-profile` with a prompt that includes:
-- Working directory
-- Plugin root
+- Absolute working directory (`working_dir`)
+- Absolute plugin root
+- Selected environment ID (`<selected-environment-id>`)
- Environment URL (`<envUrl>`)
+- Resolved tenant ID (`<tenantId>`)
+- Absolute manifest path within the app root
- Publisher prefix (e.g. `cr8142a`)
- **Mode** (optional) — `default` (full Steps 1–6) or `incremental` (only re-scope one table, given a table logical name)
+## Invocation context and root binding
+
+This is a child planning invocation. Before any project read or command, execute
+[app-working-directory.md](${PLUGIN_ROOT}/shared/references/app-working-directory.md).
+Require the owner's absolute `working_dir` and complete environment ID/URL/tenant
+context; missing, relative, or conflicting input returns `NEEDS_CONTEXT`.
+An inaccessible root is `BLOCKED`. Never use the launch cwd or ambient tenant.
+
+Use the same root for every shell call and file tool, including retries.
+Re-supply `PLUGIN_ROOT` and the selected identity in each call. File tools use
+absolute `<working_dir>/...` paths. A supplied manifest must identify one of the
+two app-local locations below; never read another app's manifest.
+Every Dataverse read passes `--tenant-id "<tenantId>"`. Failure returns to the
+owner; do not resolve a replacement environment or switch accounts.
+Planning grants no mutation approval. Write only
+`<working_dir>/_offline_section.md`; the owner owns the live plan and all gates.
+
## Hard Rules
- **Read-only.** You MUST NOT POST to `/mobileofflineprofiles`, PUT EntityMetadata, or call `pa app add data-source`. Mutation happens later in `/setup-offline-profile` after user approval through 3 gates.
@@ -53,13 +73,26 @@ You will be invoked by `/setup-offline-profile` with a prompt that includes:
Inputs you MUST read (use `Read` tool):
+First verify the bound app agrees with the supplied environment:
+
+```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
+environment_id=$(node -p "require('./power.config.json').environmentId || ''") || {
+ echo "BLOCKED: unreadable power.config.json" >&2; exit 1;
+}
+if [ -z "$environment_id" ] || [ "$environment_id" != "<selected-environment-id>" ]; then
+ echo "NEEDS_CONTEXT: selected environment does not match working_dir" >&2
+ exit 1
+fi
+```
+
| File | Purpose |
|---|---|
-| `<workdir>/.datamodel-manifest.json` OR `<workdir>/docs/plan-artifacts/.datamodel-manifest.json` | Authoritative list of app tables, columns, and FK relationships. Check root first; newer scaffolds (Step 10b+) put it under `docs/plan-artifacts/`. The orchestrator's spawn prompt also passes the resolved path explicitly — prefer that when present. |
-| `<workdir>/native-app-plan.md` `## Screens` section | Per-screen specs — tells you which tables each screen reads/writes |
-| `<workdir>/memory-bank.md` | Resume state if prior architect runs left notes |
+| `<working_dir>/.datamodel-manifest.json` OR `<working_dir>/docs/plan-artifacts/.datamodel-manifest.json` | Authoritative list of app tables, columns, and FK relationships. Check root first; newer scaffolds (Step 10b+) put it under `docs/plan-artifacts/`. The orchestrator's spawn prompt also passes the resolved path explicitly — prefer that when present. |
+| `<working_dir>/native-app-plan.md` `## Screens` section | Per-screen specs — tells you which tables each screen reads/writes |
+| `<working_dir>/memory-bank.md` | Resume state if prior architect runs left notes |
-If `.datamodel-manifest.json` is absent at BOTH `<workdir>/.datamodel-manifest.json` AND `<workdir>/docs/plan-artifacts/.datamodel-manifest.json`, the data model hasn't been created yet. STOP and return `NEEDS_CONTEXT: data model must exist before designing offline profile — run /add-dataverse first.`
+If `.datamodel-manifest.json` is absent at BOTH `<working_dir>/.datamodel-manifest.json` AND `<working_dir>/docs/plan-artifacts/.datamodel-manifest.json`, the data model hasn't been created yet. STOP and return `NEEDS_CONTEXT: data model must exist before designing offline profile — run /add-dataverse first.`
Build an internal `tables` list:
@@ -84,8 +117,10 @@ tables:
For each table in your list, query:
```bash
-node "${PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> GET \
- "EntityDefinitions(LogicalName='<table>')?\$select=IsAvailableOffline,ChangeTrackingEnabled,OwnershipType"
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
+node "${PLUGIN_ROOT}/scripts/dataverse-request.js" "<envUrl>" GET \
+ "EntityDefinitions(LogicalName='<table>')?\$select=IsAvailableOffline,ChangeTrackingEnabled,OwnershipType" \
+ --tenant-id "<tenantId>"
```
Tag each table with `offlineReady: true | false | partial` (partial = one of the two flags is missing).
@@ -102,8 +137,10 @@ Also capture `OwnershipType` per table:
> "→ Listing existing mobile offline profiles in the environment…"
```bash
-node "${PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> GET \
- "mobileofflineprofiles?\$select=name,description,publishedon,createdon&\$expand=MobileOfflineProfile_MobileOfflineProfileItem(\$select=selectedentitytypecode,recorddistributioncriteria)"
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
+node "${PLUGIN_ROOT}/scripts/dataverse-request.js" "<envUrl>" GET \
+ "mobileofflineprofiles?\$select=name,description,publishedon,createdon&\$expand=MobileOfflineProfile_MobileOfflineProfileItem(\$select=selectedentitytypecode,recorddistributioncriteria)" \
+ --tenant-id "<tenantId>"
```
For each profile, compute overlap with the app's tables (intersect `MobileOfflineProfile_MobileOfflineProfileItem[].selectedentitytypecode` with your table list).
@@ -156,8 +193,9 @@ A table qualifies as "pure child" (criterion #3) when:
**Row count probe:**
```bash
-node "${PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> GET \
- "<entitysetname>?\$count=true&\$top=0"
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
+node "${PLUGIN_ROOT}/scripts/dataverse-request.js" "<envUrl>" GET \
+ "<entitysetname>?\$count=true&\$top=0" --tenant-id "<tenantId>"
```
Read `@odata.count`. If 5000+ (Dataverse caps non-aggregate counts at 5000), treat as "large" and apply #5. If the count call returns null/error (some envs disable it), default to "small" and apply #4 — record the assumption in `DONE_WITH_CONCERNS`.
@@ -194,8 +232,10 @@ This audit is what makes the agent deterministic and reviewable — the orchestr
For each table T in the profile that is a candidate **parent** (could have children referencing it), query:
```bash
-node "${PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> GET \
- "EntityDefinitions(LogicalName='<T>')/OneToManyRelationships?\$select=MetadataId,SchemaName,ReferencingEntity,ReferencedEntity,ReferencingAttribute"
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
+node "${PLUGIN_ROOT}/scripts/dataverse-request.js" "<envUrl>" GET \
+ "EntityDefinitions(LogicalName='<T>')/OneToManyRelationships?\$select=MetadataId,SchemaName,ReferencingEntity,ReferencedEntity,ReferencingAttribute" \
+ --tenant-id "<tenantId>"
```
For each `OneToManyRelationship`:
@@ -262,15 +302,10 @@ The `selectedcolumns` field on `mobileofflineprofileitem` (memo, stored as strin
**Set C grep (specific):**
-```bash
-# For each manifest column logical name, check whether any screen file references it
-COLS_IN_MANIFEST=$(jq -r ".tables[] | select(.logicalName == \"<table>\") | .columns[].logicalName" .datamodel-manifest.json)
-for col in $COLS_IN_MANIFEST; do
- if grep -rq "\\b$col\\b" src/\(app\)/ src/components/ 2>/dev/null; then
- echo "$col"
- fi
-done
-```
+Read the selected table's columns from the resolved absolute manifest path.
+For each logical name, use `Grep` scoped to `<working_dir>/app/` and
+`<working_dir>/src/` to find screen/component references. Never search relative
+to the launch directory or replace the owner's manifest selection.
The `\\b<col>\\b` word-boundary match avoids false positives on substring (e.g., `chnl_name` shouldn't match `chnl_namespace`).
@@ -312,7 +347,7 @@ Range is hard-bounded by Dataverse: `[5, 1440]` minutes.
**Print before starting:**
> "→ Writing _offline_section.md for the orchestrator to embed into native-app-plan.md…"
-Write `_offline_section.md` in the working directory. Structure:
+Write `<working_dir>/_offline_section.md` in the approved app root. Structure:
```markdown
## Offline Profile
diff --git a/plugins/mobile-apps/agents/screen-builder.md b/plugins/mobile-apps/agents/screen-builder.md
index 78566939d..9334c0a18 100644
--- a/plugins/mobile-apps/agents/screen-builder.md
+++ b/plugins/mobile-apps/agents/screen-builder.md
@@ -1153,7 +1153,7 @@ Follow these whenever the spec touches navigation, list rows, or modals. Recipes
Before returning a status, run the mobile changed-file dispatcher against exactly `target_file`:
```bash
-node "${PLUGIN_ROOT}/scripts/validate-mobile-files.js" --project-root "<working_dir>" --file "<target_file>"
+node "${PLUGIN_ROOT}/scripts/validate-mobile-files.js" --project-root '<working_dir>' --file '<target_file>'
```
If it exits `2`, repair every reported violation and rerun it. Do not return `DONE` until it exits `0`. This explicit mobile-owned gate replaces the former plugin-wide write hooks, which also ran during unrelated Canvas Apps workflows.
diff --git a/plugins/mobile-apps/scripts/lib/validation-helpers.js b/plugins/mobile-apps/scripts/lib/validation-helpers.js
index fafb7f15d..7d4e341b9 100644
--- a/plugins/mobile-apps/scripts/lib/validation-helpers.js
+++ b/plugins/mobile-apps/scripts/lib/validation-helpers.js
@@ -148,12 +148,19 @@ function getAzAccessToken(resourceUrl, tenantId = null) {
/**
* Gets an Azure CLI access token for the given resource URL.
* Targets the env's tenant from Dataverse auth challenge when available.
- * Falls back to the active az tenant and then unqualified az token lookup.
+ * Without an explicit tenant, falls back to the active az tenant and then unqualified az token lookup.
* @param {string} resourceUrl Dataverse resource URL to request a token for
- * @param {string|null} explicitTenantId Resolved environment tenant; skips tenant discovery when valid
+ * @param {string|null} explicitTenantId Resolved environment tenant; never falls back to another tenant
* @returns {Promise<string|null>} Access token, or null if unavailable
*/
async function getAuthToken(resourceUrl, explicitTenantId = null) {
+ // A selected environment is authoritative. Falling back after its token fails
+ // could run the approved operation under an unrelated ambient identity.
+ if (explicitTenantId !== null) {
+ return typeof explicitTenantId === 'string' && explicitTenantId.trim()
+ ? getAzAccessToken(resourceUrl, explicitTenantId.trim()) : null;
+ }
+
// Candidates are produced LAZILY, in priority order. This used to be an array
// literal, and an array literal evaluates every element before `.filter()`
// runs — so each call paid for the WWW-Authenticate probe AND an
@@ -164,7 +171,6 @@ async function getAuthToken(resourceUrl, explicitTenantId = null) {
// Short-circuiting preserves the exact preference order and fallback below —
// it only skips work once a candidate has already minted a token.
const candidateProducers = [
- () => explicitTenantId,
() => process.env.POWER_PLATFORM_TENANT_ID,
() => process.env.DATAVERSE_TENANT_ID,
() => getDataverseTenantFromChallenge(resourceUrl),
diff --git a/plugins/mobile-apps/scripts/list-table-columns.js b/plugins/mobile-apps/scripts/list-table-columns.js
index 1540e9064..9a3050e35 100644
--- a/plugins/mobile-apps/scripts/list-table-columns.js
+++ b/plugins/mobile-apps/scripts/list-table-columns.js
@@ -6,7 +6,7 @@
//
// Wraps `dataverse-request.js` so it inherits auth, retry, and 401/429 handling.
//
-// Usage: node list-table-columns.js <envUrl> <table1> [<table2> ...]
+// Usage: node list-table-columns.js <envUrl> <table1> [<table2> ...] [--tenant-id <id>]
//
// Output (JSON to stdout):
// {
@@ -23,6 +23,7 @@
const { execFileSync } = require('child_process');
const path = require('path');
+const { parseArgs: parseCliArgs } = require('node:util');
const SYSTEM_COLUMN_PATTERNS = [
/^createdon/,
@@ -50,27 +51,33 @@ function isSystemColumn(name) {
}
function parseArgs() {
- const args = process.argv.slice(2);
- if (args.length < 2) {
- process.stderr.write(
- 'Usage: node list-table-columns.js <envUrl> <table1> [<table2> ...]\n'
+ const { positionals, values } = parseCliArgs({
+ options: { 'tenant-id': { type: 'string' } },
+ allowPositionals: true,
+ });
+ const tenantId = values['tenant-id'];
+ if (positionals.length < 2 || (tenantId !== undefined && !tenantId.trim())) {
+ throw new Error(
+ 'Usage: node list-table-columns.js <envUrl> <table1> [<table2> ...] [--tenant-id <id>]'
);
- process.exit(1);
}
return {
- envUrl: args[0].replace(/\/+$/, ''),
- tables: args.slice(1),
+ envUrl: positionals[0].replace(/\/+$/, ''),
+ tables: positionals.slice(1),
+ tenantId,
};
}
-function fetchColumns(envUrl, table) {
+function fetchColumns(envUrl, table, tenantId) {
const apiPath =
`EntityDefinitions(LogicalName='${table}')/Attributes` +
`?$select=LogicalName,AttributeType,RequiredLevel`;
const requestScript = path.join(__dirname, 'dataverse-request.js');
+ const args = [requestScript, envUrl, 'GET', apiPath];
+ if (tenantId) args.push('--tenant-id', tenantId);
const stdout = execFileSync(
process.execPath,
- [requestScript, envUrl, 'GET', apiPath],
+ args,
{ encoding: 'utf8', maxBuffer: 16 * 1024 * 1024 }
);
const parsed = JSON.parse(stdout);
@@ -88,11 +95,11 @@ function fetchColumns(envUrl, table) {
}));
}
-const { envUrl, tables } = parseArgs();
const out = {};
try {
+ const { envUrl, tables, tenantId } = parseArgs();
for (const table of tables) {
- out[table] = fetchColumns(envUrl, table);
+ out[table] = fetchColumns(envUrl, table, tenantId);
}
process.stdout.write(JSON.stringify(out, null, 2) + '\n');
} catch (e) {
diff --git a/plugins/mobile-apps/scripts/tests/app-edit-routing-contract.test.js b/plugins/mobile-apps/scripts/tests/app-edit-routing-contract.test.js
new file mode 100644
index 000000000..8a9117424
--- /dev/null
+++ b/plugins/mobile-apps/scripts/tests/app-edit-routing-contract.test.js
@@ -0,0 +1,384 @@
+'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, '../..');
+// Windows checkouts can use CRLF; the prose contracts should not depend on Git's EOL setting.
+const read = (file) => fs.readFileSync(path.join(pluginRoot, file), 'utf8').replace(/\r\n?/g, '\n');
+const skill = (name) => read(`skills/${name}/SKILL.md`);
+const shared = read('shared/shared-instructions.md');
+const removal = read('shared/references/data-source-removal.md');
+const create = skill('create-mobile-app');
+const pluginCheck = '> **Plugin check**: Run `node "${PLUGIN_ROOT}/scripts/check-version.js"` - if it outputs a message, show it to the user before proceeding.';
+const dataSkills = [
+ 'add-datasource',
+ 'setup-datamodel',
+ 'add-dataverse',
+ 'add-connector',
+ 'add-sharepoint',
+ 'add-sample-data',
+];
+
+function section(text, start, end) {
+ const startIndex = text.indexOf(start);
+ const endIndex = text.indexOf(end, startIndex + start.length);
+ assert.ok(startIndex >= 0, `Missing section: ${start}`);
+ assert.ok(endIndex > startIndex, `Missing section end: ${end}`);
+ return text.slice(startIndex, endIndex);
+}
+
+for (const [name, ending] of [['LF', '\n'], ['CRLF', '\r\n']]) {
+ test(`Markdown reader preserves the same data contracts with ${name} line endings`, (t) => {
+ const file = 'shared/shared-instructions.md';
+ const content = '# Shared Instructions\n\n## Data-source invocation scope\nfirst\nsecond\n\n## Version Check\n';
+ t.mock.method(fs, 'readFileSync', (filePath, encoding) => {
+ assert.equal(filePath, path.join(pluginRoot, file));
+ assert.equal(encoding, 'utf8');
+ return content.replace(/\n/g, ending);
+ });
+ const actual = read(file);
+ assert.equal(actual, content);
+ assert.match(section(actual, '## Data-source invocation scope', '## Version Check'), /first\nsecond/);
+ });
+}
+
+function assertSharedEntry(content, name) {
+ let body = content.replace(/^---\n[\s\S]*?\n---\n/, '').trimStart();
+ if (body.startsWith(`${pluginCheck}\n\n`)) body = body.slice(pluginCheck.length).trimStart();
+ const firstLine = body.split('\n')[0];
+ assert.match(firstLine, /\[shared-instructions\.md\]\([^)]+\/shared-instructions\.md\)/, `${name}: shared policy must be the first instruction`);
+ assert.match(firstLine, /read (?:this |both )?first/i, `${name}: read-first prerequisite`);
+ assert.match(content.match(/^allowed-tools: (.+)$/m)?.[1] || '', /\bRead\b/, `${name}: allow reading policy`);
+}
+
+for (const name of dataSkills) {
+ test(`${name} starts with the shared data-scope preflight`, () => {
+ const content = skill(name);
+ assertSharedEntry(content, name);
+ const entry = section(content, '**Invocation scope:**', '\n\n');
+ assert.match(entry, /shared-instructions\.md#data-source-invocation-scope/);
+ assert.ok(content.indexOf('**Invocation scope:**') < content.indexOf('## Workflow'));
+ assert.doesNotMatch(content, /#app-feature-entry-points|(?:app-edit-routing|native-artifact-compatibility)\.md/);
+ });
+}
+
+test('data workflows cannot omit, defer, or disable reading shared policy', () => {
+ const valid = '---\nallowed-tools: Read, Bash\n---\n\n**Shared instructions: [shared-instructions.md](../../shared/shared-instructions.md)** - read first.\n\n## Workflow\n';
+ assert.doesNotThrow(() => assertSharedEntry(valid, 'data-workflow'));
+ assert.doesNotThrow(() => assertSharedEntry(valid.replace('**Shared instructions:', `${pluginCheck}\n\n**Shared instructions:`), 'data-workflow'));
+ assert.throws(() => assertSharedEntry(valid.replace('**Shared instructions:', `${pluginCheck}\n\nRun auth first.\n**Shared instructions:`), 'data-workflow'));
+ assert.throws(() => assertSharedEntry(valid.replace('**Shared instructions:', 'Run auth first.\n**Shared instructions:'), 'data-workflow'));
+ assert.throws(() => assertSharedEntry(valid.replace('shared-instructions.md', 'other.md'), 'data-workflow'));
+ assert.throws(() => assertSharedEntry(valid.replace('read first', 'optional'), 'data-workflow'));
+ assert.throws(() => assertSharedEntry(valid.replace('Read, Bash', 'Bash'), 'data-workflow'));
+});
+
+test('shared data scope precedes operational work and does not turn caller markers into approval', () => {
+ const scope = section(shared, '## Data-source invocation scope', '## Version Check');
+ assert.match(scope, /before any workflow commands or app\/cloud writes/);
+ assert.match(scope, /cannot be loaded, STOP/);
+ assert.match(scope, /Resolve the current requested operation before discovery or mutation/);
+ assert.match(scope, /An existing plan or inventory is context, not permission to replay every row/);
+ assert.match(scope, /Standalone calls keep the data workflow's own approval and validation gates/);
+ assert.match(scope, /MOBILE_APP_ORCHESTRATING=1/);
+ for (const field of ['orchestrator', 'working_dir', 'phase', 'approved_scope']) {
+ assert.ok(scope.includes(`\`${field}\``));
+ }
+ assert.match(scope, /including routers and retries/);
+ assert.match(scope, /do not persist it, rely on a prior shell export, or infer\napproval from a flag alone/);
+ assert.match(scope, /expanded or conflicting scope returns `NEEDS_CONTEXT`/);
+ assert.match(scope, /Older callers without a complete approved handoff must establish current scope\nthrough the leaf's approval gate/);
+ assert.match(scope, /`--plan-only` or a planning-phase handoff never authorizes mutating leaves/);
+ assert.match(scope, /Propagate the mode and current scoped context through routers/);
+});
+
+test('shared prompt defaults cannot override explicit data approval gates', () => {
+ const policy = section(shared, '## Execution Style', '## Inline Shell');
+ assert.match(policy, /Explicit approval gates take precedence/);
+ assert.match(policy, /plan\/mutation, data-source removal, and deployment/);
+ assert.match(policy, /Cancellation or dismissal stops the pending operation/);
+ assert.match(policy, /empty or ambiguous answer requires clarification/);
+ assert.match(policy, /already-approved scoped child calls do not repeat approvals/);
+ assert.match(policy, /expanded scope returns to the owner for a new decision/);
+ assert.doesNotMatch(policy, /empty\/cancel answer auto-proceeds|empty answer proceeds|default-yes/);
+});
+
+test('shared connector setup requires approved implementation and preserves supplied bindings', () => {
+ const connector = section(shared, '## Connector Reference', '## Safety Guardrails');
+ assert.doesNotMatch(connector, /Always run `\/list-connections` first/);
+ assert.match(connector, /only in the approved implementation phase/);
+ assert.match(connector, /Reuse a supplied connection ID or reference/);
+ assert.match(connector, /Do not invoke it during planning, `--plan-only`, cancellation, or removal-only work/);
+ assert.match(connector, /Approved data child calls reuse their scoped handoff without repeating\napproval/);
+ assert.match(connector, /Direct operational `\/list-connections` requests keep their own workflow/);
+});
+
+test('data routers preserve the current request and proposal-only context without granting approval', () => {
+ const router = skill('add-datasource');
+ assert.match(router, /Forward the absolute `working_dir`, current request, owner\/phase\/scope,\n\s+supplied answers, and `--plan-only` or planning-phase status unchanged on every\n\s+handoff/);
+ assert.match(router, /a saved plan or router choice is not consent to mutate/);
+ assert.match(router, /Conflicting add\/refresh\/remove scopes return to the owner for separate calls/);
+ const connector = skill('add-connector');
+ assert.match(connector, /same `\$ARGUMENTS`, absolute `working_dir`,\ncurrent request, owner\/phase\/scope, and proposal-only mode/);
+ assert.match(connector, /Do not continue this\nskill's workflow.*or infer execution approval from this routing decision/);
+});
+
+test('creation passes scoped approval and the app root to data leaves', () => {
+ for (const [start, end, expected] of [
+ ['Invoke skill: /add-dataverse', '`/add-dataverse` validates', /bound operation-manifest artifacts/],
+ ['### Step 10 — Add connectors', '### Step 10b', /connector row and supplied/],
+ ]) {
+ const handoff = section(create, start, end);
+ assert.match(handoff, /MOBILE_APP_ORCHESTRATING=1/);
+ assert.match(handoff, /orchestrator: create-mobile-app/);
+ assert.match(handoff, /working_dir: <working_dir>|`working_dir`/);
+ assert.match(handoff, /--working-dir "?<working_dir>"?/);
+ assert.match(handoff, /phase: implementation/);
+ assert.match(handoff, expected);
+ }
+});
+
+test('connector-owned actions and SharePoint schemas do not imply Dataverse schema', () => {
+ assert.match(skill('add-connector'), /Action connectors do not imply Dataverse Data Model changes/);
+ assert.match(skill('add-sharepoint'), /Keep SharePoint list\/library schemas in Connectors, not the Dataverse\nData Model/);
+});
+
+test('setup-datamodel saves every approved path and passes scope to its leaves', () => {
+ const setup = skill('setup-datamodel');
+ const planning = section(setup, '### Phase 2', '### Phase 4');
+ assert.match(planning, /connector-only requests\ntake Path C/);
+ assert.match(planning, /Preserve any existing Data Model section/);
+ assert.doesNotMatch(planning, /On `ExitPlanMode` approval, write/);
+ assert.match(setup, /save both approved sections to `native-app-plan.md`/);
+ for (const [start, end] of [
+ ['Invoke skill: /add-dataverse', '`/add-dataverse` creates'],
+ ['Invoke skill: /add-connector', 'Run sequentially.'],
+ ]) {
+ const handoff = section(setup, start, end);
+ assert.match(handoff, /MOBILE_APP_ORCHESTRATING=1/);
+ assert.match(handoff, /orchestrator: setup-datamodel/);
+ assert.match(handoff, /approved_scope:/);
+ }
+});
+
+test('setup validates all Dataverse proposal paths before the one combined approval', () => {
+ const setup = skill('setup-datamodel');
+ const planning = section(setup, '### Phase 2', '### Phase 3');
+ const gate = section(setup, '### Phase 4', '### Phase 5');
+ const workflow = planning.indexOf('dataverse-change-planning.md');
+ assert.ok(workflow >= 0 && workflow < planning.indexOf('#### Path A'));
+ assert.ok(workflow < planning.indexOf('Task: mobile-app:data-model-architect'));
+ assert.match(planning, /Path C, removal-only work, and a\nretained-service-only refresh skip schema planning and its artifacts/);
+ assert.match(gate, /Dataverse proposal from any path[\s\S]*exit `0`\nbefore this gate/);
+ const validate = gate.indexOf('validate-dataverse-planning-decisions.js');
+ const proposalExit = gate.indexOf('**Proposal-only exit:**');
+ const approval = gate.indexOf('Present the full plan');
+ const save = gate.indexOf('- **Approved**');
+ assert.ok(validate >= 0 && validate < proposalExit && proposalExit < approval && approval < save);
+ assert.match(gate, /Connector-only, retirement-only, and refresh-only proposals[\s\S]*must not reuse stale schema-planning artifacts/);
+ assert.match(gate, /Revisions repeat validation, not broad discovery or another\napproval ceremony/);
+ assert.match(gate, /A saved plan or `--skip-planning` alone is not approval/);
+ assert.doesNotMatch(planning, /EnterPlanMode|ExitPlanMode|--approval-receipt/);
+});
+
+test('connector aliases and operations preserve dedicated routing and dependency gates', () => {
+ const connector = skill('add-connector');
+ assert.match(connector, /shared_sharepointonline/);
+ assert.match(connector, /shared_commondataserviceforapps/);
+ assert.match(connector, /actions\/functions follow the discovery-only branch/);
+ assert.doesNotMatch(connector, /npx expo install <missing-package>/);
+ assert.match(connector, /Do not install\nnative packages absent from the template/);
+ assert.match(connector, /Standalone removal must stop if\nit would leave broken consumers/);
+});
+
+test('Dataverse discovery executes before connector setup and ends the leaf', () => {
+ const connector = skill('add-connector');
+ const identify = section(connector, '### Step 2', '### Step 3');
+ const setup = section(connector, '### Step 3', '### Step 4');
+ assert.match(identify, /find-dataverse-api --search/);
+ assert.match(identify, /STOP this leaf/);
+ assert.match(identify, /Do not enter Step 3/);
+ assert.ok(identify.indexOf('find-dataverse-api') < identify.indexOf('| Connector API name'));
+ assert.doesNotMatch(setup, /find-dataverse-api/);
+});
+
+test('generic connector preserves supplied IDs and references before resolving a missing binding', () => {
+ const setup = section(skill('add-connector'), '### Step 3', '**Classify the connector');
+ assert.match(setup, /Supplied `--connection-id`[\s\S]*reuse that exact/);
+ assert.match(setup, /Supplied `--connection-ref`[\s\S]*preserve that/);
+ assert.match(setup, /skip `\/list-connections` and creation/);
+ assert.match(setup, /Missing binding only:.*invoke `\/list-connections`/);
+ assert.match(setup, /ambiguous supplied values return to the owner instead of creating a fallback/);
+ assert.match(setup, /`--connection-ref '<connectionRef>'` on `add-data-source` only/);
+ assert.match(setup, /backing ID for the approved reference/);
+ assert.doesNotMatch(setup, /Run the `\/list-connections` skill/);
+});
+
+test('SharePoint reuses supplied bindings and emits the matching registration form', () => {
+ const sharepoint = skill('add-sharepoint');
+ const binding = section(sharepoint, '### Step 6:', '### Step 7:');
+ assert.match(binding, /Supplied `--connection-id`[\s\S]*reuse the exact ID/);
+ assert.match(binding, /Supplied `--connection-ref`[\s\S]*retain the exact/);
+ assert.match(binding, /Missing binding only/);
+ assert.match(binding, /skip `create-connection` and `\/list-connections`/);
+ assert.match(binding, /Do not create another connection for discovery/);
+ const add = section(sharepoint, '### Step 9:', '### Step 10:');
+ assert.match(add, /Run only the applicable command/);
+ assert.match(add, /--connection-id '<connectionId>'/);
+ assert.match(add, /--connection-ref '<connectionRef>'/);
+ assert.match(section(sharepoint, '### Step 7:', '### Step 8:'), /Skip this picker/);
+ assert.match(section(sharepoint, '### Step 8:', '### Step 9:'), /Skip this picker/);
+});
+
+test('connector-only summary does not claim a nonexistent Dataverse manifest', () => {
+ const summary = section(skill('setup-datamodel'), '### Phase 7', '## Reference');
+ assert.match(summary, /Manifest as `not applicable`/);
+ assert.match(summary, /<verified manifest path and updated\/unchanged status, or "not applicable">/);
+ assert.doesNotMatch(summary, /Manifest\s+:\s+\.datamodel-manifest\.json/);
+});
+
+test('existing Dataverse plans are checked against the requested delta rather than replayed', () => {
+ const dataverse = skill('add-dataverse');
+ assert.match(dataverse, /restrict schema writes to the exact `approved_scope` delta/);
+ assert.match(dataverse, /flag alone must not suppress standalone reconciliation/);
+ assert.match(dataverse, /If the request adds nothing, verify the existing outcome and report a no-op/);
+ assert.doesNotMatch(dataverse, /empty\/cancel input auto-proceeds/);
+});
+
+test('data-source removal is an explicit app-only retirement, not server deletion', () => {
+ assert.match(removal, /shared-instructions\.md#data-source-invocation-scope/);
+ assert.doesNotMatch(removal, /#app-feature-entry-points|(?:app-edit-routing|native-artifact-compatibility)\.md/);
+ assert.match(removal, /does not authorize deleting the server table,\s+its columns\/records/);
+ assert.match(removal, /A missing row in a planner's output is a candidate, not consent/);
+ assert.match(removal, /lookup\/identity reads, and offline requirements/);
+ assert.match(removal, /Dynamic or ambiguous usage is a blocker/);
+ assert.match(removal, /Never mutate\s+configuration\/generated files during\s+planning or `--plan-only`/);
+});
+
+test('data-source retirement requires consumers to be retired before unregistering', () => {
+ const consumers = section(removal, '## 2.', '## 3.');
+ assert.match(consumers, /responsible app workflow adds\/refreshes replacement sources first/);
+ assert.match(consumers, /updates or removes the approved consumers and verifies they no longer depend\s+on the retiring source/);
+ assert.match(consumers, /Keep the old binding available until those source edits are complete/);
+ assert.match(consumers, /Only then call the appropriate leaf in removal mode/);
+ assert.match(consumers, /removal must stop if consumers remain/);
+ assert.match(consumers, /cannot be staged safely,\nreturn the conflict to the owner for an explicit migration plan/);
+});
+
+for (const name of ['add-connector', 'add-dataverse', 'add-sharepoint']) {
+ test(`${name} dispatches removals before its normal add workflow`, () => {
+ const content = skill(name);
+ const branch = section(content, '**Removal branch:**', '\n## ');
+ assert.match(branch, /--remove/);
+ assert.match(branch, /data-source-removal\.md/);
+ assert.match(branch, /return/);
+ assert.ok(content.indexOf('**Removal branch:**') < content.indexOf('**Telemetry checkpoint:'));
+ });
+ test(`${name} returns from targeted refresh before the add workflow`, () => {
+ const content = skill(name);
+ const branch = section(content, '**Refresh branch:**', '\n## ');
+ assert.match(branch, /--refresh/);
+ assert.match(branch, /data-source-removal\.md#refresh-a-retained-source/);
+ assert.match(branch, /--data-source-name/);
+ assert.match(branch, /returns before Steps/);
+ assert.match(branch, /(?:do not|Do not)[\s\S]*add-data-source/);
+ assert.ok(content.indexOf('**Refresh branch:**') < content.indexOf('**Telemetry checkpoint:'));
+ });
+}
+
+test('refresh preserves registration identity and never falls back to an add', () => {
+ const refresh = section(removal, '## Refresh a retained source', '## 1.');
+ assert.match(refresh, /`--plan-only` or a planning-phase handoff returns the proposed\s+refresh without executing it/);
+ assert.match(refresh, /Require one unambiguous stored\nregistration/);
+ assert.match(refresh, /name-only selector could refresh unrelated registrations, STOP/);
+ assert.match(refresh, /never guess from a display label or silently add an absent source/);
+ assert.match(refresh, /per-source failure output/);
+ assert.match(refresh, /preserve unrelated registration identities/);
+ assert.match(refresh, /do not repair generator output by hand or retry through addition/);
+ assert.match(skill('add-datasource'), /--refresh --data-source-name "<registered-name>"/);
+});
+
+test('the router and data-only orchestrator retain the removal operation', () => {
+ assert.match(skill('add-datasource'), /matching leaf's removal branch/);
+ const dataOnly = skill('setup-datamodel');
+ assert.match(dataOnly, /Skip this phase for a removal-only delta/);
+ const retirement = section(dataOnly, '### Phase 6.25', '### Phase 6.5');
+ assert.match(retirement, /--remove/);
+ assert.match(retirement, /MOBILE_APP_ORCHESTRATING=1/);
+ assert.match(retirement, /if any remain, stop/);
+});
+
+test('removal uses CLI-owned cleanup with explicit consent and verifies silent no-ops', () => {
+ assert.match(removal, /\$PA app remove data-source --connector dataverse --name '<registered-name>' --force --non-interactive/);
+ assert.match(removal, /--procedure '<procedure>' --force --non-interactive/);
+ assert.match(removal, /`PA_KIND=power-apps`[\s\S]*omit `--force`/);
+ assert.match(removal, /`--non-interactive` alone is not removal consent/);
+ assert.match(removal, /Do not manually delete `src\/generated\/` files/);
+ assert.match(removal, /flat CLI can return exit 0 for a not-found\/no-op removal/);
+ assert.match(removal, /same-named registrations in other\nconnectors\/datasets/);
+ assert.match(removal, /empty references used by remaining flows/);
+});
+
+test('schema-map generation is distinct from service refresh and removal', () => {
+ assert.match(removal, /does not infer unused tables from screen code, unregister sources/);
+ assert.match(removal, /\$PA app refresh data-source --name '<registered-name>'/);
+ assert.match(removal, /npm run generate-schemas\nnpx --no-install tsc --noEmit/);
+ assert.match(removal, /including when the\nlast source was removed/);
+});
+
+test('verified removal reconciles the app inventory without faking offline cleanup', () => {
+ assert.match(removal, /remove retired app-inventory entries while preserving verified facts/);
+ assert.match(removal, /valid empty\n`tables` array/);
+ assert.match(removal, /do not reuse old plan-bound operation manifests/i);
+ assert.match(removal, /detects additions, not excess profile tables/);
+ assert.match(removal, /do not silently remove them or edit the local\nsnapshot to pretend the server changed/);
+});
+
+test('generator ownership uses the shared PA resolver without a duplicate command catalog', () => {
+ const ownership = section(shared, '### Mandatory changed-file validation', '### MUST (required');
+ const cli = section(shared, '## CLI Invocation', '## Command Failure Handling');
+ for (const verb of ['init', 'add data-source', 'refresh data-source', 'remove data-source']) {
+ assert.ok(ownership.includes(`pa app ${verb}`), verb);
+ }
+ assert.match(ownership, /through the resolved `\$PA` command/);
+ assert.match(ownership, /not modified afterward by the skill or its subagents/);
+ assert.match(cli, /\[cli-binary\.md\]\(cli-binary\.md\)/);
+ assert.match(cli, /`npm run generate-schemas` is the separate template command/);
+ assert.doesNotMatch(shared, /Exact generated-output commands|Exact mobile command|^\s*(?:PA|PA_KIND)=/m);
+ assert.doesNotMatch(cli, /npx --no-install power-apps/);
+});
+
+test('CLI guidance has no version preflight, hardcoded retirement version, or upgrade fallback', () => {
+ const cli = section(shared, '## CLI Invocation', '## Command Failure Handling');
+ assert.doesNotMatch(cli, /project-local CLI gate|--version|node_modules\/@microsoft\/power-apps-cli\/package\.json/);
+ assert.match(cli, /Do not substitute a global binary/);
+ assert.match(cli, /If the command is unsupported, report\nthe error/);
+ assert.match(cli, /do not guess aliases, strip safety flags, or install another CLI/);
+ assert.doesNotMatch(removal, /\b\d+\.\d+\.\d+\b|npx --no-install power-apps/);
+ assert.match(removal, /\[command and flag mapping\]\(\.\.\/cli-binary\.md\)/);
+});
+
+test('unsupported cloud flows cannot enter connector routing or data-source lifecycle commands', () => {
+ const connector = skill('add-connector');
+ const router = skill('add-datasource');
+ for (const text of [connector, router, removal]) {
+ assert.match(text, /BLOCKED: cloud-flow integration is not supported/);
+ }
+ assert.ok(connector.indexOf('**Cloud flows are not supported') < connector.indexOf('**Removal branch:**'));
+ for (const text of [connector, router, removal, read('shared/connector-reference.md')]) {
+ assert.doesNotMatch(text, /\$PA app (?:add flow|remove flow|list-flows)|npx[^\n]*(?:add-flow|remove-flow|list-flows)/);
+ }
+ assert.match(removal, /Preserve existing flow dependencies/);
+});
+
+test('README explains data-source commands without internal execution mechanics', () => {
+ const examples = section(read('README.md'), '### Data-source planning, refresh, and retirement', '### 5.');
+ assert.match(examples, /--plan-only/);
+ assert.match(examples, /--refresh --data-source-name/);
+ assert.match(examples, /--remove --data-source-name/);
+ assert.match(examples, /never deletes server tables/);
+ assert.doesNotMatch(examples, /compact live-metadata|working_dir|PowerShell|Bash|schema map|allowlist|offline-profile-delta/);
+});
diff --git a/plugins/mobile-apps/scripts/tests/app-working-directory-contract.test.js b/plugins/mobile-apps/scripts/tests/app-working-directory-contract.test.js
new file mode 100644
index 000000000..274cfba20
--- /dev/null
+++ b/plugins/mobile-apps/scripts/tests/app-working-directory-contract.test.js
@@ -0,0 +1,611 @@
+'use strict';
+
+const assert = require('node:assert/strict');
+const { spawnSync } = require('node:child_process');
+const fs = require('node:fs');
+const os = require('node:os');
+const path = require('node:path');
+const test = require('node:test');
+const { shellBlocks } = require('./helpers/markdown-shell-blocks');
+
+const pluginRoot = path.resolve(__dirname, '../..');
+const normalize = (text) => text.replace(/\r\n?/g, '\n');
+const read = (file) => normalize(fs.readFileSync(file, 'utf8'));
+const appRootReference = read(path.join(pluginRoot, 'shared/references/app-working-directory.md'));
+const appRootLink = '[app-working-directory.md](${PLUGIN_ROOT}/shared/references/app-working-directory.md)';
+const guard = "cd -- '<working_dir>' || { echo \"BLOCKED: cannot enter working_dir\" >&2; exit 1; }";
+const powershellGuard = "Set-Location -LiteralPath '<working_dir>' -ErrorAction Stop";
+const quotedFileArgument = /--(?:working-dir|project-root|approval-receipt|contract|file|output|publish-checkpoint|reconciliation|snapshot|validate)\s+"[^"\n]*<[^>\n]+>[^"\n]*"/;
+
+function unsafePathLiteral(line) {
+ if (quotedFileArgument.test(line)) return true;
+ return [...line.matchAll(/"([^"\n]*)"/g)].some((match) =>
+ match[1].includes('<working_dir>') && !/^\$\(cat '<working_dir>[^']*'\)$/.test(match[1]));
+}
+
+for (const prefix of ['', ' ', '> ', '> ']) {
+ for (const eol of ['\n', '\r\n']) {
+ test(`shell recipe extraction retains source quoting with prefix ${JSON.stringify(prefix)} and ${eol === '\n' ? 'LF' : 'CRLF'}`, () => {
+ const body = `${guard}\nnode tool.js --project-root '<working_dir>'`;
+ const markdown = ['```bash', ...body.split('\n'), '```']
+ .map((line) => prefix + line).join(eol);
+ assert.deepEqual(shellBlocks(markdown), [body]);
+ assert.deepEqual(shellBlocks(markdown, 'powershell'), []);
+ });
+ }
+}
+
+function assertRootBinding(text) {
+ text = normalize(text);
+ assert.match(text, /before any project read or command, execute/);
+ assert.ok(text.includes(appRootLink));
+ assert.ok(text.indexOf(appRootLink) < text.indexOf('```bash'), 'Bind root before the first gate');
+ assert.match(text, /every shell call and\s+file tool/);
+ const blocks = shellBlocks(text);
+ assert.ok(blocks.length > 0);
+ for (const block of blocks) {
+ assert.ok(block.startsWith(`${guard}\n`), 'Every shell call must re-enter the app root');
+ assert.ok(!block.split('\n').some(unsafePathLiteral), 'Arguments and artifact aliases must preserve literal paths too');
+ }
+ for (const block of shellBlocks(text, 'powershell')) {
+ assert.ok(block.startsWith(`${powershellGuard}\n`), 'PowerShell calls need a literal fail-closed root');
+ }
+}
+
+function assertEveryGuardIsRequired(content, command, language = 'bash') {
+ let count = 0;
+ // Use source offsets: extracted list/blockquote snippets have already been dedented.
+ for (let index = content.indexOf(command); index !== -1; index = content.indexOf(command, index + command.length)) {
+ assert.throws(() => assertRootBinding(content.slice(0, index) + content.slice(index + command.length)));
+ count++;
+ }
+ assert.equal(count, shellBlocks(content, language).length);
+}
+
+// Use Git Bash, not WSL bash, for Windows checkout paths, as in the creation tests.
+const bashPaths = process.platform === 'win32'
+ ? (spawnSync('where.exe', ['bash'], { encoding: 'utf8' }).stdout || '').split(/\r?\n/)
+ : [];
+const bash = bashPaths.find((entry) => /[\\/]Git[\\/]/i.test(entry)) || 'bash';
+const shellLiteralContents = (value) => value.replaceAll('\\', '/').replaceAll("'", "'\\''");
+
+function fixture(t) {
+ const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'app-working-dir-'));
+ t.after(() => fs.rmSync(directory, { recursive: true, force: true }));
+ const owner = path.join(directory, "owner's app [test] $root $(printf expanded) `printf backtick`");
+ const caller = path.join(directory, 'different app');
+ for (const root of [owner, caller]) {
+ fs.mkdirSync(root, { recursive: true });
+ fs.writeFileSync(path.join(root, 'app.config.js'), 'module.exports = {};');
+ fs.writeFileSync(path.join(root, 'power.config.json'), JSON.stringify({ environmentId: root === owner ? 'owner' : 'caller' }));
+ fs.writeFileSync(path.join(root, 'native-app-plan.md'), '# Plan\n');
+ fs.mkdirSync(path.join(root, '.tmp'));
+ for (const name of ['dataverse-operation-all.json', 'dataverse-operation-phase-fixture.json']) {
+ fs.writeFileSync(path.join(root, '.tmp', name), '[]');
+ }
+ fs.writeFileSync(path.join(root, 'package.json'), '{"dependencies":{}}');
+ }
+ return { directory, owner, caller };
+}
+
+function run(block, owner, caller) {
+ const command = block.replaceAll('<working_dir>', shellLiteralContents(owner));
+ // Use the current Node executable; mutation tests supply local CLI probes.
+ const result = spawnSync(bash, ['-s'], {
+ input: `node() { "$REAL_NODE" "$@"; }\nPA="npx --no-install pa"\nPA_KIND=pa\n${command}`,
+ cwd: caller,
+ env: {
+ ...process.env,
+ REAL_NODE: process.execPath.replaceAll('\\', '/'),
+ PLUGIN_ROOT: pluginRoot.replaceAll('\\', '/'),
+ POWER_PLATFORM_SKILLS_TELEMETRY_MOBILE_APP_OPTOUT: '1',
+ },
+ encoding: 'utf8',
+ timeout: 10000,
+ });
+ assert.ifError(result.error);
+ return result;
+}
+
+test('shared root contract distinguishes direct defaults from required child context and file-tool scope', () => {
+ const scope = appRootReference;
+ const shared = read(path.join(pluginRoot, 'shared/shared-instructions.md'));
+ const heading = '## Data-source invocation scope';
+ const start = shared.indexOf(heading);
+ assert.ok(start >= 0, 'Data-source invocations must have a shared scope preflight');
+ const end = shared.indexOf('\n---', start);
+ assert.ok(end > start);
+ const invocation = shared.slice(start, end);
+ const binding = '[app-working-directory.md](references/app-working-directory.md)';
+ assert.ok(invocation.includes(binding));
+ assert.match(invocation, /before (?:reading|any project read)/);
+ assert.ok(invocation.indexOf(binding) < invocation.indexOf('`power.config.json`'),
+ 'Bind the owner root before reading the selected app environment');
+ assert.match(scope, /Child invocation[\s\S]*owner's absolute\s+`working_dir`/);
+ assert.match(scope, /Never fall back to the process cwd/);
+ assert.match(scope, /Missing or\s+relative owner context returns `NEEDS_CONTEXT` before project access/);
+ assert.match(scope, /Direct invocation[\s\S]*`--working-dir`[\s\S]*capture the\s+initial cwd once/);
+ assert.match(scope, /Canonicalize the existing filesystem directory/);
+ assert.match(scope, /fs\.realpathSync\.native/);
+ assert.match(scope, /different roots, return `NEEDS_CONTEXT`/);
+ assert.match(scope, /inaccessible directory is `BLOCKED`/);
+ assert.match(scope, /does not persist across tool calls/);
+ assert.match(scope, /shell-quoted literal argument/);
+ assert.match(scope, /keep the surrounding single quotes/);
+ assert.match(scope, /Never interpolate a path inside double quotes/);
+ assert.match(scope, /File tools do not inherit shell cwd/);
+ assert.match(scope, /Read\/Edit\/Write\/Grep\/Glob absolute\s+project paths/);
+ assert.match(scope, /grants no additional approval and does not relax\nplan-only mode/);
+ assert.match(scope, /Git Bash\s+on Windows/);
+ assert.match(scope, /existing PowerShell helper/);
+ assert.match(scope, /double\s+embedded apostrophes/);
+ assert.match(scope, /re-supply any required\nshell variables/);
+ assert.match(scope, /Resolve `\$PA` and `PA_KIND` for this app via \[cli-binary\.md\]/);
+ assert.match(scope, /not from another app's cached selection/);
+ assert.match(scope, /Re-supply both in each fresh shell\s+call after binding the root/);
+ assert.equal(shellBlocks(scope)[0], guard);
+ assert.equal(shellBlocks(scope, 'powershell')[0], powershellGuard);
+});
+
+for (const [file, selector] of [
+ ['agents/data-model-architect.md', '/render-dataverse-architect-evidence.js'],
+ ['shared/references/dataverse-change-planning.md', '/validate-dataverse-planning-decisions.js'],
+]) {
+ test(`${file} keeps caller-supplied evidence path aliases literal`, (t) => {
+ const { owner, caller } = fixture(t);
+ const block = shellBlocks(read(path.join(pluginRoot, file)))
+ .find((command) => command.includes(selector));
+ assert.ok(block);
+ const snapshot = `${owner.replaceAll('\\', '/')}/.tmp/snapshot.json`;
+ const evidence = `${owner.replaceAll('\\', '/')}/.tmp/evidence.json`;
+ const command = block
+ .replaceAll('<foreground snapshot path>', shellLiteralContents(snapshot))
+ .replaceAll('<compact architect evidence path>', shellLiteralContents(evidence))
+ .replaceAll('<SNAPSHOT_PATH>', shellLiteralContents(snapshot));
+ const probe = 'node() { "$REAL_NODE" -e \'console.log(JSON.stringify(process.argv.slice(1)))\' "$@"; }';
+ const result = run(`${probe}\n${command}`, owner, caller);
+ assert.equal(result.status, 0, result.stderr);
+ assert.equal(result.stderr, '');
+ const args = JSON.parse(result.stdout);
+ assert.equal(args[args.indexOf('--snapshot') + 1], snapshot);
+ if (args.includes('--output')) assert.equal(args[args.indexOf('--output') + 1], evidence);
+ });
+}
+
+test('canonical root guard treats dollar and backtick syntax as literal path contents', (t) => {
+ const { owner, caller } = fixture(t);
+ const literalPath = owner.replaceAll('\\', '/').replaceAll("'", "'\\''");
+ const command = guard.replace('<working_dir>', literalPath) +
+ '\nnode -p "process.cwd()"';
+ const result = run(command, owner, caller);
+ assert.equal(result.status, 0, result.stderr);
+ assert.equal(result.stderr, '');
+ assert.equal(fs.realpathSync.native(result.stdout.trim()), fs.realpathSync.native(owner));
+});
+
+function markdownFiles(directory) {
+ return fs.readdirSync(directory, { withFileTypes: true }).flatMap((entry) => {
+ const file = path.join(directory, entry.name);
+ return entry.isDirectory() ? markdownFiles(file) : entry.name.endsWith('.md') ? [file] : [];
+ });
+}
+
+test('shell commands and handoffs never interpolate root or artifact-path literals inside double quotes', () => {
+ const offenders = [];
+ for (const directory of ['agents', 'shared', 'skills']) {
+ for (const file of markdownFiles(path.join(pluginRoot, directory))) {
+ const text = read(file);
+ const snippets = [
+ ...shellBlocks(text),
+ ...shellBlocks(text, 'text').flatMap((snippet) =>
+ snippet.split('\n').filter((line) => quotedFileArgument.test(line))),
+ ...[...text.matchAll(/`([^`\n]+)`/g)].map((match) => match[1])
+ .filter((code) => !/^".*"$/.test(code.trim())),
+ ];
+ snippets.flatMap((snippet) => snippet.split('\n')).forEach((line) => {
+ // Structured file-tool arguments are not shell commands.
+ if (/\b(?:Grep|Glob|Read|Write|Edit)\b.*\b(?:path|file_path)=/.test(line)) return;
+ if (unsafePathLiteral(line)) offenders.push(`${path.relative(pluginRoot, file)}: ${line.trim()}`);
+ });
+ }
+ }
+ assert.deepEqual(offenders, []);
+});
+
+test('documented normalization arguments preserve literal root contents without repairing their quotes', (t) => {
+ const { owner, caller } = fixture(t);
+ const reference = read(path.join(pluginRoot, 'shared/references/dataverse-change-planning.md'));
+ const block = shellBlocks(reference).find((command) => command.includes('--normalize-contract'));
+ assert.ok(block);
+ const probe = 'node() { "$REAL_NODE" -e \'console.log(JSON.stringify({ cwd: process.cwd(), args: process.argv.slice(1) }))\' "$@"; }';
+ const result = run(`${probe}\n${block}`, owner, caller);
+ assert.equal(result.status, 0, result.stderr);
+ assert.equal(result.stderr, '');
+ const call = JSON.parse(result.stdout);
+ assert.equal(fs.realpathSync.native(call.cwd), fs.realpathSync.native(owner));
+ const contract = `${owner.replaceAll('\\', '/')}/.tmp/dataverse-schema-contract.json`;
+ assert.deepEqual(call.args.slice(1), ['--normalize-contract', contract, '--output', contract]);
+
+ const unsafe = block.replaceAll("'<working_dir>/.tmp/dataverse-schema-contract.json'", '"<working_dir>/.tmp/dataverse-schema-contract.json"');
+ assert.notEqual(unsafe, block);
+ const unsafeResult = run(`${probe}\n${unsafe}`, owner, caller);
+ assert.equal(unsafeResult.status, 0, unsafeResult.stderr);
+ assert.notDeepEqual(JSON.parse(unsafeResult.stdout).args.slice(1), call.args.slice(1),
+ 'The harness must expose unsafe source quoting, not rewrite it to a safe form');
+});
+
+test('delegated creation planning and recovery blocks bind each fresh invocation to the owner root', (t) => {
+ const { directory, owner, caller } = fixture(t);
+ const create = read(path.join(pluginRoot, 'skills/create-mobile-app/SKILL.md'));
+ const sections = [
+ ['### Foreground Dataverse planning snapshot and evidence', '#### Planner completion dispatch'],
+ ['#### Dataverse planning recovery', '#### Step 3.0a'],
+ ];
+ const blocks = sections.flatMap(([start, end]) => {
+ const begin = create.indexOf(start);
+ const finish = create.indexOf(end, begin);
+ assert.ok(begin >= 0 && finish > begin);
+ return shellBlocks(create.slice(begin, finish));
+ });
+ assert.equal(blocks.length, 4);
+ for (const block of blocks) {
+ assert.ok(block.startsWith(`${guard}\n`));
+ const rootProbe = `${block.split('\n')[0]}\nnode -p "process.cwd()"`;
+ const result = run(rootProbe, owner, caller);
+ assert.equal(result.status, 0, result.stderr);
+ assert.equal(fs.realpathSync.native(result.stdout.trim()), fs.realpathSync.native(owner));
+ const failed = run(rootProbe, path.join(directory, 'missing app'), caller);
+ assert.equal(failed.status, 1);
+ assert.match(failed.stderr, /BLOCKED: cannot enter working_dir/);
+ }
+});
+
+for (const file of [
+ 'shared/references/offline-profile-reconciliation.md',
+ 'skills/deploy/SKILL.md',
+ 'skills/edit-app/SKILL.md',
+]) {
+ test(`${file} checks the actual owner project from a different app launch directory`, (t) => {
+ const { owner, caller } = fixture(t);
+ for (const [root, table] of [[owner, 'cr_owner'], [caller, 'cr_caller']]) {
+ fs.writeFileSync(path.join(root, '.datamodel-manifest.json'),
+ JSON.stringify({ tables: [{ logicalName: table, columns: [] }] }));
+ fs.writeFileSync(path.join(root, 'offline-profile.json'),
+ JSON.stringify({ profileId: 'test-profile', tables: [] }));
+ }
+ const block = shellBlocks(read(path.join(pluginRoot, file)))
+ .find((command) => command.includes('/offline-profile-delta.js'));
+ assert.ok(block);
+ const result = run(block, owner, caller);
+ assert.equal(result.status, 0, result.stderr);
+ assert.equal(result.stderr, '');
+ const delta = JSON.parse(result.stdout);
+ assert.equal(delta.status, 'delta');
+ assert.deepEqual(delta.missingTables.map((table) => table.logicalName), ['cr_owner']);
+ });
+}
+
+const removal = read(path.join(pluginRoot, 'shared/references/data-source-removal.md'));
+
+for (const [eolName, eol] of [['LF', '\n'], ['CRLF', '\r\n']]) {
+ test(`data-source refresh, removal, and verification each re-enter the app root (${eolName})`, () => {
+ const blocks = shellBlocks(removal.replace(/\n/g, eol));
+ assert.equal(blocks.length, 3);
+ for (const block of blocks) {
+ assert.ok(block.startsWith(`${guard}\n`), 'Each call needs its own fail-closed root guard');
+ }
+ const scope = removal.split('## Bind refresh, removal, and verification to the app root\n')[1]
+ ?.split('## Removal is not schema-map generation')[0];
+ assert.ok(scope);
+ assert.match(scope, /Before any app-local read or command/);
+ assert.match(scope, /\[app-working-directory\.md\]\(app-working-directory\.md\)/);
+ assert.match(scope, /every shell call and file tool[\s\S]*CLI help[\s\S]*service verification, and retries/);
+ assert.match(scope, /does not grant removal approval or relax plan-only mode/);
+ });
+}
+
+test('documented data-source commands stay in the owner app across fresh calls and stop on missing roots', (t) => {
+ const { directory, owner, caller } = fixture(t);
+ const blocks = shellBlocks(removal);
+ const trace = path.join(owner, 'root-commands.jsonl');
+ const callerConfig = fs.readFileSync(path.join(caller, 'power.config.json'), 'utf8');
+ // Record the actual command arguments/cwd instead of invoking any real CLI or package manager.
+ const probes = `
+record_call() {
+ node -e 'require("node:fs").appendFileSync("root-commands.jsonl", JSON.stringify({ cwd: process.cwd(), args: process.argv.slice(1) }) + "\\n")' "$@"
+}
+npx() { record_call npx "$@"; }
+npm() { record_call npm "$@"; }
+`;
+ let expectedCalls = 0;
+ for (const block of blocks) {
+ const command = `${probes}\n${block}`;
+ const result = run(command, owner, caller);
+ assert.equal(result.status, 0, result.stderr);
+ expectedCalls += block.split('\n').filter((line) => /^(?:\$PA|npx|npm) /.test(line)).length;
+ const before = fs.readFileSync(trace, 'utf8');
+ const missingRoot = run(command, path.join(directory, 'missing app'), caller);
+ assert.equal(missingRoot.status, 1);
+ assert.match(missingRoot.stderr, /BLOCKED: cannot enter working_dir/);
+ assert.equal(fs.readFileSync(trace, 'utf8'), before, 'Failed cd must run no follow-up commands');
+ assert.equal(fs.existsSync(path.join(caller, 'root-commands.jsonl')), false);
+ }
+ const calls = fs.readFileSync(trace, 'utf8').trim().split('\n').map((line) => JSON.parse(line));
+ assert.equal(expectedCalls, 8);
+ assert.equal(calls.length, expectedCalls);
+ for (const call of calls) {
+ // Native realpath expands Windows 8.3 aliases retained by the JS resolver.
+ assert.equal(fs.realpathSync.native(call.cwd), fs.realpathSync.native(owner));
+ }
+ for (const operation of ['refresh', 'remove', 'generate-schemas', 'tsc']) {
+ assert.ok(calls.some((call) => call.args.includes(operation)), operation);
+ }
+ const cliCalls = calls.filter((call) => call.args[2] === 'pa');
+ assert.equal(cliCalls.length, 4);
+ for (const call of cliCalls) {
+ assert.deepEqual(call.args.slice(0, 4), ['npx', '--no-install', 'pa', 'app']);
+ assert.equal(call.args[5], 'data-source');
+ assert.ok(call.args.includes('--name'));
+ assert.ok(call.args.includes('--non-interactive'));
+ if (call.args[4] === 'remove') assert.ok(call.args.includes('--force'));
+ }
+ assert.equal(fs.readFileSync(path.join(caller, 'power.config.json'), 'utf8'), callerConfig);
+});
+
+const dataFiles = ['add-connector', 'add-dataverse', 'add-sharepoint']
+ .map((name) => path.join(pluginRoot, 'skills', name, 'SKILL.md'));
+const connectorReference = read(path.join(pluginRoot, 'shared/connector-reference.md'));
+
+test('shared connector command examples retain the same per-call root guard', () => {
+ assert.match(connectorReference, /\[app-working-directory\.md\]\(references\/app-working-directory\.md\)/);
+ for (const block of shellBlocks(connectorReference)) {
+ assert.ok(block.startsWith(`${guard}\n`));
+ }
+});
+
+const sampleData = read(path.join(pluginRoot, 'skills/add-sample-data/SKILL.md'));
+for (const [eolName, eol] of [['LF', '\n'], ['CRLF', '\r\n']]) {
+ test(`sample-data discovery, insertion, and retry commands re-enter the app root (${eolName})`, () => {
+ assert.match(sampleData, /before any project read or command\. Bind the absolute `working_dir` first/);
+ assert.match(sampleData, /reuse it for every shell call, file tool, media path, and retry/);
+ // Numbered instructions indent some command fences by three spaces.
+ const content = sampleData.replace(/\n/g, eol);
+ const blocks = shellBlocks(content.replace(/^ {3}/gm, ''));
+ assert.ok(blocks.length > 0);
+ assert.equal(blocks.length, [...sampleData.matchAll(/^ {0,3}```bash$/gm)].length);
+ for (const block of blocks) {
+ assert.ok(block.startsWith(`${guard}\n`), 'Each seed command needs a fail-closed root guard');
+ }
+ });
+}
+
+for (const file of dataFiles) {
+ const name = path.basename(path.dirname(file));
+ const content = read(file).replace(/^> ?/gm, '');
+ const blocks = shellBlocks(content);
+ for (const [eolName, eol] of [['LF', '\n'], ['CRLF', '\r\n']]) {
+ test(`${name} binds addition, discovery, and verification to the app root (${eolName})`, () => {
+ assertRootBinding(content.replace(/\n/g, eol));
+ });
+ }
+ test(`${name} rejects missing or deferred root guards`, () => {
+ assert.throws(() => assertRootBinding(content.replace(appRootLink, '') + `\n${appRootLink}`));
+ assertEveryGuardIsRequired(content, guard);
+ assertEveryGuardIsRequired(content, powershellGuard, 'powershell');
+ });
+ test(`${name} executes documented Bash operations only in the owner app`, (t) => {
+ const { directory, owner, caller } = fixture(t);
+ const trace = path.join(owner, 'root-commands.jsonl');
+ const callerConfig = fs.readFileSync(path.join(caller, 'power.config.json'), 'utf8');
+ // External tools are recorders, never real cloud/package operations. Preserve the
+ // shell syntax (including substitutions and conditionals) of each documented block.
+ const probes = `
+record_call() {
+ "$REAL_NODE" -e 'require("node:fs").appendFileSync("root-commands.jsonl", JSON.stringify({ cwd: process.cwd(), args: process.argv.slice(1) }) + "\\n")' "$@"
+}
+node() {
+ record_call node "$@"
+ if [ "$1" = "-p" ]; then "$REAL_NODE" "$@"; else printf '{}\\n'; fi
+}
+npx() { record_call npx "$@"; }
+npm() { record_call npm "$@"; }
+az() { record_call az "$@"; }
+`;
+ for (const block of blocks) {
+ // Substitute values only; changing the authored quotes would conceal a regression.
+ const command = block.replaceAll(/<(?!working_dir>)[^>]+>/g, 'fixture');
+ const result = run(`${probes}\n${command}`, owner, caller);
+ assert.equal(result.status, 0, `${name}:\n${block}\n${result.stderr}`);
+ const before = fs.existsSync(trace) ? fs.readFileSync(trace, 'utf8') : '';
+ const failed = run(`${probes}\n${command}`, path.join(directory, 'missing app'), caller);
+ assert.equal(failed.status, 1, failed.stderr);
+ assert.match(failed.stderr, /BLOCKED: cannot enter working_dir/);
+ assert.equal(fs.existsSync(trace) ? fs.readFileSync(trace, 'utf8') : '', before);
+ assert.equal(fs.existsSync(path.join(caller, 'root-commands.jsonl')), false);
+ }
+ const calls = fs.readFileSync(trace, 'utf8').trim().split('\n').map(JSON.parse);
+ for (const call of calls) {
+ assert.equal(fs.realpathSync.native(call.cwd), fs.realpathSync.native(owner));
+ }
+ for (const operation of ['data-source', 'generate-schemas', 'tsc']) {
+ assert.ok(calls.some((call) => call.args.includes(operation)), operation);
+ }
+ assert.ok(calls.some((call) => call.args.includes('add') && call.args.includes('data-source')));
+ if (name === 'add-dataverse') {
+ assert.ok(calls.some((call) => call.args.some((arg) => arg.endsWith('/resolve-environment.js')) && call.args.includes('owner')));
+ assert.match(content, /--operations "\$\(cat '<working_dir>\/\.tmp\/dataverse-operation-phase-<name>\.json'\)"/);
+ }
+ assert.equal(fs.readFileSync(path.join(caller, 'power.config.json'), 'utf8'), callerConfig);
+
+ fs.unlinkSync(path.join(owner, 'app.config.js'));
+ const invalidProject = run(`${probes}\n${blocks[0].replaceAll('<selected-environment-id>', 'owner')}`, owner, caller);
+ assert.equal(invalidProject.status, 1);
+ assert.match(invalidProject.stderr, /BLOCKED: working_dir is not an initialized app/);
+ });
+}
+
+for (const file of ['agents/data-model-architect.md', 'skills/list-connections/SKILL.md']) {
+ const content = read(path.join(pluginRoot, file));
+ for (const [eolName, eol] of [['LF', '\n'], ['CRLF', '\r\n']]) {
+ test(`${file} guards every project operation (${eolName})`, () => {
+ assertRootBinding(content.replace(/\n/g, eol));
+ assertEveryGuardIsRequired(content, guard);
+ });
+ }
+ test(`${file} executes from the owner root and blocks missing roots`, (t) => {
+ const { directory, owner, caller } = fixture(t);
+ const trace = path.join(owner, 'helper-calls.jsonl');
+ const probes = `
+node() { "$REAL_NODE" -e 'require("node:fs").appendFileSync("helper-calls.jsonl", JSON.stringify({ cwd: process.cwd(), args: process.argv.slice(1) }) + "\\n")' -- "$@"; }
+npx() { node "$@"; }
+`;
+ const blocks = shellBlocks(content);
+ assert.ok(blocks.length >= 3);
+ for (const block of blocks) {
+ const command = block.replaceAll(/<(?!working_dir>)[^>]+>/g, 'fixture');
+ const succeeded = run(`${probes}\n${command}`, owner, caller);
+ assert.equal(succeeded.status, 0, `${block}\n${succeeded.stderr}`);
+ const before = fs.readFileSync(trace, 'utf8');
+ const failed = run(`${probes}\n${command}`, path.join(directory, 'missing app'), caller);
+ assert.equal(failed.status, 1);
+ assert.match(failed.stderr, /BLOCKED: cannot enter working_dir/);
+ assert.equal(fs.readFileSync(trace, 'utf8'), before);
+ assert.equal(fs.existsSync(path.join(caller, 'helper-calls.jsonl')), false);
+ }
+ const calls = fs.readFileSync(trace, 'utf8').trim().split('\n').map(JSON.parse);
+ for (const call of calls) {
+ assert.equal(fs.realpathSync.native(call.cwd), fs.realpathSync.native(owner));
+ }
+ if (file.startsWith('agents/')) {
+ const resolver = calls.find((call) => call.args.some((arg) => arg.endsWith('/resolve-environment.js')));
+ assert.ok(resolver);
+ assert.ok(resolver.args.includes('--no-cache'));
+ assert.ok(resolver.args.includes('--require-tenant'));
+ const metadata = calls.filter((call) => /\/(?:verify-dataverse-access|dataverse-request|list-table-columns)\.js$/.test(call.args[0]));
+ assert.equal(metadata.length, 4);
+ for (const call of metadata) {
+ assert.ok(call.args.includes('--tenant-id'));
+ assert.equal(call.args[call.args.indexOf('--tenant-id') + 1], 'fixture');
+ }
+ } else {
+ assert.ok(calls.every((call) => call.args[0] === '--no-install'));
+ }
+ });
+}
+
+test('connector execution and referenced examples consistently use the resolved PA command', () => {
+ for (const file of ['skills/add-connector/SKILL.md', 'skills/list-connections/SKILL.md', 'shared/connector-reference.md']) {
+ const blocks = shellBlocks(read(path.join(pluginRoot, file)));
+ const commands = blocks.flatMap((block) => [...block.matchAll(/^\s*\$PA [^\n]*/gm)]
+ .map((match) => match[0].trim()));
+ assert.ok(commands.length >= 3, file);
+ for (const command of commands) {
+ assert.match(command, /^\$PA (?:app|connection) /, `${file}: ${command}`);
+ assert.doesNotMatch(command, /--(?:api-id|resource-name|data-source-name|sql-stored-procedure)\b/);
+ }
+ assert.doesNotMatch(blocks.join('\n'), /^\s*npx[^\n]*\b(?:power-apps|pa)\b/m);
+ }
+});
+
+const cliResolution = shellBlocks(read(path.join(pluginRoot, 'shared/cli-binary.md')))[0];
+for (const [shims, kind] of [
+ [['pa', 'power-apps'], 'pa'],
+ [['pa.cmd', 'power-apps.cmd'], 'pa'],
+ [['power-apps'], 'power-apps'],
+ [['power-apps.cmd'], 'power-apps'],
+ [[], 'none'],
+]) {
+ test(`CLI resolution in the owner app selects ${kind} with ${shims.join(', ') || 'no shims'}`, (t) => {
+ const { owner, caller } = fixture(t);
+ const bin = path.join(owner, 'node_modules', '.bin');
+ fs.mkdirSync(bin, { recursive: true });
+ for (const shim of shims) fs.writeFileSync(path.join(bin, shim), '');
+ const command = `${guard}\n${cliResolution}\nprintf '%s|%s' "$PA_KIND" "$PA"`;
+ const result = run(command, owner, caller);
+ assert.equal(result.status, 0, result.stderr);
+ assert.equal(result.stdout, `${kind}|${kind === 'none' ? '' : `npx --no-install ${kind}`}`);
+ });
+}
+
+const previewOpeners = [
+ ['skills/design-system/references/vibe/style-picker.md', '_design_vibe.html'],
+ ['skills/preview-screens/SKILL.md', 'preview.html'],
+];
+
+function captureWindowsOpener(t, file, filename) {
+ const { owner, caller } = fixture(t);
+ const block = shellBlocks(read(path.join(pluginRoot, file)))
+ .find((command) => command.includes('powershell.exe'));
+ assert.ok(block);
+ const probes = `
+open() { return 1; }
+xdg-open() { return 1; }
+powershell.exe() {
+ "$REAL_NODE" -e 'console.log(JSON.stringify({ path: process.env.MOBILE_APP_PREVIEW_PATH, args: process.argv.slice(1) }))' -- "$@"
+}
+`;
+ const result = run(`${probes}\n${block}`, owner, caller);
+ assert.equal(result.status, 0, result.stderr);
+ assert.equal(result.stderr, '');
+ const call = JSON.parse(result.stdout);
+ assert.equal(call.path, `${owner.replaceAll('\\', '/')}/${filename}`);
+ assert.deepEqual(call.args, ['-NoProfile', '-Command', 'Start-Process -FilePath $env:MOBILE_APP_PREVIEW_PATH']);
+ return { block, owner, caller, call };
+}
+
+for (const [file, filename] of previewOpeners) {
+ test(`${file} passes a literal Windows path as data and reports failed openers safely`, (t) => {
+ const { block, owner, caller } = captureWindowsOpener(t, file, filename);
+ const failed = run('open() { return 1; }\nxdg-open() { return 1; }\npowershell.exe() { return 1; }\n' + block,
+ owner, caller);
+ assert.equal(failed.status, 0, failed.stderr);
+ assert.equal(failed.stderr, '');
+ assert.match(failed.stdout, /Could not auto-open/);
+ assert.ok(failed.stdout.includes(`file://${owner.replaceAll('\\', '/')}/${filename}`));
+ });
+}
+
+const pwshProbe = spawnSync('pwsh', ['-NoProfile', '-NonInteractive', '-Command', '$PSVersionTable.PSVersion.ToString()'], {
+ encoding: 'utf8',
+});
+test('PowerShell root guards and preview openers preserve literal paths', {
+ skip: pwshProbe.error?.code === 'ENOENT' && !process.env.CI ? 'PowerShell is unavailable locally; required in CI' : false,
+}, (t) => {
+ assert.ifError(pwshProbe.error);
+ assert.equal(pwshProbe.status, 0, pwshProbe.stderr);
+ const { directory, owner, caller } = fixture(t);
+ const trace = path.join(owner, 'powershell-root.txt');
+ const content = read(path.join(pluginRoot, 'skills/add-sharepoint/SKILL.md'));
+ const quote = (value) => `'${value.replaceAll("'", "''")}'`;
+ for (const block of shellBlocks(content, 'powershell')) {
+ const call = (root) => spawnSync('pwsh', ['-NoProfile', '-NonInteractive', '-Command',
+ `${block.split('\n')[0].replace("'<working_dir>'", quote(root))}\n` +
+ "[System.IO.File]::WriteAllText((Join-Path (Get-Location).Path 'powershell-root.txt'), (Get-Location).Path)",
+ ], { cwd: caller, encoding: 'utf8', timeout: 10000 });
+ const result = call(owner);
+ assert.ifError(result.error);
+ assert.equal(result.status, 0, result.stderr);
+ assert.equal(fs.realpathSync.native(fs.readFileSync(trace, 'utf8')), fs.realpathSync.native(owner));
+ fs.unlinkSync(trace);
+ const failed = call(path.join(directory, 'missing app'));
+ assert.ifError(failed.error);
+ assert.notEqual(failed.status, 0);
+ assert.match(failed.stderr, /does not exist|Cannot find path/);
+ assert.equal(fs.existsSync(trace), false);
+ assert.equal(fs.existsSync(path.join(caller, 'powershell-root.txt')), false);
+ }
+ for (const [file, filename] of previewOpeners) {
+ const { call } = captureWindowsOpener(t, file, filename);
+ const result = spawnSync('pwsh', ['-NoProfile', '-NonInteractive', '-Command',
+ 'function Start-Process { param([string]$FilePath) @{ path = $FilePath } | ConvertTo-Json -Compress }\n' +
+ call.args[2],
+ ], {
+ env: { ...process.env, MOBILE_APP_PREVIEW_PATH: call.path },
+ encoding: 'utf8',
+ timeout: 10000,
+ });
+ assert.ifError(result.error);
+ assert.equal(result.status, 0, result.stderr);
+ assert.equal(JSON.parse(result.stdout).path, call.path);
+ }
+});
diff --git a/plugins/mobile-apps/scripts/tests/auth-token-resolution.test.js b/plugins/mobile-apps/scripts/tests/auth-token-resolution.test.js
index 480933b95..283feda29 100644
--- a/plugins/mobile-apps/scripts/tests/auth-token-resolution.test.js
+++ b/plugins/mobile-apps/scripts/tests/auth-token-resolution.test.js
@@ -87,6 +87,29 @@ test('explicit tenant argument short-circuits shell environment and discovery',
assert.equal(log.trim().split('\n').length, 1);
});
+test('an inaccessible explicit tenant cannot fall back to an ambient identity', (t) => {
+ const { token, log } = runGetAuthToken(t, {
+ POWER_PLATFORM_TENANT_ID: 'tenant-from-env',
+ DATAVERSE_TENANT_ID: 'secondary-tenant',
+ FAKE_AZ_ACCOUNT_TENANT: 'tenant-from-az-account',
+ FAKE_AZ_FAIL_TENANTS: 'selected-tenant',
+ }, 'selected-tenant');
+ assert.equal(token, 'null');
+ assert.equal(log.trim().split('\n').length, 1);
+ assert.match(log, /--tenant selected-tenant/);
+ assert.doesNotMatch(log, /account show|tenant-from-env|secondary-tenant|tenant-from-az-account/);
+});
+
+for (const tenant of ['', ' ']) {
+ test(`an empty explicit tenant ${JSON.stringify(tenant)} cannot use ambient auth`, (t) => {
+ const { token, log } = runGetAuthToken(t, {
+ POWER_PLATFORM_TENANT_ID: 'tenant-from-env',
+ }, tenant);
+ assert.equal(token, 'null');
+ assert.equal(log, '');
+ });
+}
+
test('env-supplied tenant short-circuits: no `az account show` is spawned', (t) => {
const { token, log } = runGetAuthToken(t, {
POWER_PLATFORM_TENANT_ID: 'tenant-from-env',
@@ -141,3 +164,213 @@ test('final fallback mints an unqualified token when no tenant resolves', (t) =>
assert.equal(token, 'token-for:active-account');
assert.doesNotMatch(log, /--tenant/);
});
+
+function runMetadataHelper(t, script, args, env = {}) {
+ const logPath = makeFakeAzLog(t);
+ const directory = path.dirname(logPath);
+ const requestLog = path.join(directory, 'requests.jsonl');
+ const preload = path.join(directory, 'metadata-preload.cjs');
+ const snapshot = {
+ profileId: 'mock-profile',
+ tables: [{
+ logicalName: 'cr_visit', itemId: 'mock-item', recordDistributionCriteria: 1,
+ recordsOwnedByMe: false, recordsOwnedByMyTeam: false, recordsOwnedByMyBusinessUnit: false,
+ syncIntervalInMinutes: 10, selectedColumns: ['cr_title'],
+ relationships: [{ relationshipId: 'mock-relationship' }],
+ }],
+ };
+ if (script === 'verify-offline-profile.js') {
+ fs.writeFileSync(path.join(directory, 'offline-profile.json'), JSON.stringify(snapshot));
+ }
+ // The preload follows list-table-columns into its request subprocesses, so
+ // the real argument/token plumbing runs without Azure or HTTP traffic.
+ fs.writeFileSync(preload, `
+const fs = require('node:fs');
+require(${JSON.stringify(FAKE_AZ_PRELOAD)});
+const helpers = require(${JSON.stringify(HELPERS)});
+const snapshot = ${JSON.stringify(snapshot)};
+let puts = 0;
+helpers.makeRequest = async ({ url, headers, method = 'GET' }) => {
+ fs.appendFileSync(${JSON.stringify(requestLog)}, JSON.stringify({
+ url, method, authorization: headers.Authorization,
+ }) + '\\n');
+ if (method === 'PUT') {
+ if (++puts === 1 && process.env.FAKE_METADATA_PUT_401 === '1') {
+ if (process.env.FAKE_METADATA_REFRESH_FAIL === '1') {
+ process.env.FAKE_AZ_FAIL_TENANTS = 'selected-tenant';
+ }
+ return { statusCode: 401, body: '{}' };
+ }
+ return { statusCode: 204, body: '' };
+ }
+ if (url.includes('/EntityDefinitions(') && !url.includes('/Attributes')) {
+ return {
+ statusCode: 200,
+ body: JSON.stringify({
+ MetadataId: 'mock-metadata', LogicalName: 'cr_visit', SchemaName: 'cr_Visit',
+ IsAvailableOffline: process.env.FAKE_OFFLINE_VERIFY === '1',
+ ChangeTrackingEnabled: process.env.FAKE_OFFLINE_VERIFY === '1',
+ IsCustomizable: { Value: true },
+ }),
+ };
+ }
+ if (url.includes('/mobileofflineprofiles(')) {
+ return {
+ statusCode: 200,
+ body: JSON.stringify({
+ mobileofflineprofileid: snapshot.profileId, name: 'Test profile',
+ publishedon: '2026-01-01T00:00:00Z', componentstate: 0,
+ MobileOfflineProfile_MobileOfflineProfileItem: snapshot.tables.map((table) => ({
+ mobileofflineprofileitemid: table.itemId, selectedentitytypecode: table.logicalName,
+ recorddistributioncriteria: table.recordDistributionCriteria,
+ recordsownedbyme: table.recordsOwnedByMe,
+ recordsownedbymyteam: table.recordsOwnedByMyTeam,
+ recordsownedbymybusinessunit: table.recordsOwnedByMyBusinessUnit,
+ syncintervalinminutes: table.syncIntervalInMinutes,
+ selectedcolumns: JSON.stringify({ Columns: table.selectedColumns }),
+ })),
+ }),
+ };
+ }
+ if (url.includes('/mobileofflineprofileitemassociations?')) {
+ return { statusCode: 200, body: JSON.stringify({ value: [{ relationshipid: 'mock-relationship' }] }) };
+ }
+ return {
+ statusCode: 200,
+ body: JSON.stringify(url.endsWith('/WhoAmI')
+ ? { UserId: 'mock-user', OrganizationId: 'mock-organization' }
+ : { value: [
+ { LogicalName: 'cr_title', AttributeType: 'String', RequiredLevel: { Value: 'ApplicationRequired' } },
+ { LogicalName: 'createdon', AttributeType: 'DateTime' },
+ ] }),
+ };
+};
+require(${JSON.stringify(path.join(__dirname, '..', 'emit-telemetry-checkpoint.js'))})
+ .captureSuccessfulDataverseRequest = () => {};
+`);
+ const result = spawnSync(process.execPath, [
+ path.join(__dirname, '..', script), UNREACHABLE_ENV_URL, ...args,
+ ], {
+ cwd: directory,
+ encoding: 'utf8',
+ timeout: 10000,
+ env: {
+ ...process.env,
+ NODE_OPTIONS: `--require=${JSON.stringify(preload)}`,
+ FAKE_AZ_LOG: logPath,
+ FAKE_AZ_STATIC_TOKEN: '',
+ FAKE_AZ_FAIL_TENANTS: '',
+ FAKE_METADATA_PUT_401: '',
+ FAKE_METADATA_REFRESH_FAIL: '',
+ FAKE_OFFLINE_VERIFY: script === 'verify-offline-profile.js' ? '1' : '',
+ POWER_PLATFORM_TENANT_ID: 'tenant-from-env',
+ DATAVERSE_TENANT_ID: 'secondary-tenant',
+ FAKE_AZ_ACCOUNT_TENANT: 'tenant-from-az-account',
+ POWER_PLATFORM_SKILLS_TELEMETRY_MOBILE_APP_OPTOUT: '1',
+ ...env,
+ },
+ });
+ assert.ifError(result.error);
+ return {
+ result,
+ calls: fs.existsSync(logPath) ? fs.readFileSync(logPath, 'utf8').trim().split('\n') : [],
+ requests: fs.existsSync(requestLog)
+ ? fs.readFileSync(requestLog, 'utf8').trim().split('\n').map(JSON.parse) : [],
+ };
+}
+
+for (const [script, positionals, count] of [
+ ['verify-dataverse-access.js', [], 1],
+ ['list-table-columns.js', ['cr_visit', 'cr_airport'], 2],
+ ['update-entity-offline-flags.js', ['--table', 'cr_visit'], 2],
+ ['verify-offline-profile.js', [], 3],
+]) {
+ for (const explicit of [true, false]) {
+ test(`${script} preserves output with ${explicit ? 'explicit' : 'legacy environment'} tenant selection`, (t) => {
+ const args = [...positionals, ...(explicit ? ['--tenant-id', 'selected-tenant'] : [])];
+ const { result, calls, requests } = runMetadataHelper(t, script, args);
+ assert.equal(result.status, 0, result.stderr);
+ const tenant = explicit ? 'selected-tenant' : 'tenant-from-env';
+ assert.equal(calls.length, script === 'list-table-columns.js' ? count : 1);
+ assert.ok(calls.every((call) => call.includes(`--tenant ${tenant}`)));
+ assert.equal(requests.length, count);
+ assert.ok(requests.every((request) => request.authorization === `Bearer token-for:${tenant}`));
+ const data = JSON.parse(result.stdout);
+ if (script === 'verify-dataverse-access.js') {
+ assert.equal(data.userId, 'mock-user');
+ assert.equal(data.organizationId, 'mock-organization');
+ assert.equal(data.token, `token-for:${tenant}`);
+ } else if (script === 'list-table-columns.js') {
+ assert.deepEqual(Object.keys(data), positionals);
+ for (const table of positionals) {
+ assert.deepEqual(data[table], [
+ { name: 'cr_title', type: 'String', required: 'ApplicationRequired' },
+ ]);
+ assert.ok(requests.some((request) => request.url.includes(`LogicalName='${table}'`)));
+ }
+ } else if (script === 'verify-offline-profile.js') {
+ assert.equal(data.status, 'ok');
+ assert.equal(data.profileId, 'mock-profile');
+ assert.ok(data.checks.every((check) => check.ok));
+ assert.ok(requests.every((request) => request.method === 'GET'));
+ } else {
+ assert.equal(data.status, 204);
+ assert.equal(data.table, 'cr_visit');
+ assert.deepEqual(data.after, { isAvailableOffline: true, changeTrackingEnabled: true });
+ assert.deepEqual(requests.map((request) => request.method), ['GET', 'PUT']);
+ }
+ });
+ }
+
+ test(`${script} stops after the selected tenant is rejected`, (t) => {
+ const { result, calls, requests } = runMetadataHelper(t, script,
+ [...positionals, '--tenant-id', 'selected-tenant'],
+ { FAKE_AZ_FAIL_TENANTS: 'selected-tenant' });
+ assert.notEqual(result.status, 0);
+ assert.match(result.stderr + result.stdout, /Failed to get Azure CLI token/);
+ assert.equal(calls.length, 1);
+ assert.match(calls[0], /--tenant selected-tenant/);
+ assert.deepEqual(requests, []);
+ });
+
+ for (const invalid of [
+ ['--tenant-id'], ['--tenant-id', ''], ['--tenant-id', ' '],
+ ['--tenant-id', '--unknown-option'],
+ ]) {
+ test(`${script} rejects malformed tenant arguments ${JSON.stringify(invalid)} before auth`, (t) => {
+ const { result, calls, requests } = runMetadataHelper(t, script, [...positionals, ...invalid]);
+ assert.notEqual(result.status, 0);
+ assert.match(result.stderr, /tenant-id/);
+ assert.deepEqual(calls, []);
+ assert.deepEqual(requests, []);
+ });
+ }
+}
+
+for (const rejectRefresh of [false, true]) {
+ test(`offline prerequisite refresh ${rejectRefresh ? 'fails closed' : 'retains the explicit tenant'}`, (t) => {
+ const { result, calls, requests } = runMetadataHelper(t, 'update-entity-offline-flags.js',
+ ['--table', 'cr_visit', '--tenant-id', 'selected-tenant'], {
+ FAKE_METADATA_PUT_401: '1',
+ FAKE_METADATA_REFRESH_FAIL: rejectRefresh ? '1' : '',
+ });
+ assert.equal(result.status, rejectRefresh ? 1 : 0, result.stderr);
+ assert.equal(calls.length, 2);
+ assert.ok(calls.every((call) => call.includes('--tenant selected-tenant')));
+ assert.equal(requests.length, rejectRefresh ? 2 : 3);
+ assert.ok(requests.every((request) => request.authorization === 'Bearer token-for:selected-tenant'));
+ const data = JSON.parse(result.stdout);
+ assert.equal(data.status, rejectRefresh ? 401 : 204);
+ if (rejectRefresh) assert.equal(data.error, 'token refresh failed');
+ });
+}
+
+for (const args of [['--project-root'], ['--project-root', '--tenant-id', 'selected-tenant']]) {
+ test(`offline verifier rejects a missing project-root value ${JSON.stringify(args)}`, (t) => {
+ const { result, calls, requests } = runMetadataHelper(t, 'verify-offline-profile.js', args);
+ assert.notEqual(result.status, 0);
+ assert.match(result.stderr, /--project-root requires a path/);
+ assert.deepEqual(calls, []);
+ assert.deepEqual(requests, []);
+ });
+}
diff --git a/plugins/mobile-apps/scripts/tests/create-mobile-app-quality-contract.test.js b/plugins/mobile-apps/scripts/tests/create-mobile-app-quality-contract.test.js
index 8ff7d95e9..f18f93544 100644
--- a/plugins/mobile-apps/scripts/tests/create-mobile-app-quality-contract.test.js
+++ b/plugins/mobile-apps/scripts/tests/create-mobile-app-quality-contract.test.js
@@ -8,6 +8,7 @@ const path = require('path');
const test = require('node:test');
const { createSnapshot } = require('../create-dataverse-snapshot');
const { loadAndValidateArchitectEvidence } = require('../render-dataverse-architect-evidence');
+const { shellBlocks } = require('./helpers/markdown-shell-blocks');
const skillPath = path.resolve(
__dirname,
@@ -16,10 +17,10 @@ const skillPath = path.resolve(
const skill = fs.readFileSync(skillPath, 'utf8');
function planningAttemptBlock(source) {
- const match = source.replace(/\r\n/g, '\n')
- .match(/```bash\n(SNAPSHOT_PATH=[\s\S]*?\nrun_dataverse_planning_attempt)\n```/);
- assert.ok(match, 'foreground snapshot commands must expose one recoverable attempt');
- return match[1];
+ const block = shellBlocks(source)
+ .find((command) => command.includes('run_dataverse_planning_attempt() {'));
+ assert.ok(block, 'foreground snapshot commands must expose one recoverable attempt');
+ return block;
}
test('foreground command extraction accepts LF and Windows CRLF checkouts', () => {
@@ -37,10 +38,11 @@ test('foreground Dataverse planning resolves and validates environment in one re
assert.notStrictEqual(planningStart, -1);
assert.notStrictEqual(planningEnd, -1);
const planning = skill.slice(planningStart, planningEnd);
- const commands = [...planning.matchAll(/```bash\r?\n([\s\S]*?)\r?\n```/g)];
+ const commands = shellBlocks(planning);
assert.strictEqual(commands.length, 1);
assert.strictEqual(
- commands[0][1].trim(),
+ commands[0],
+ "cd -- '<working_dir>' || { echo \"BLOCKED: cannot enter working_dir\" >&2; exit 1; }\n" +
'node "${PLUGIN_ROOT}/scripts/resolve-environment.js" "$ACTIVE_ENV_ID" --no-cache --require-tenant',
);
assert.doesNotMatch(planning, /PLANNING_ENV_JSON|node -e|JSON\.parse/);
@@ -54,7 +56,7 @@ test('approved architecture precedes typed discovery without retrying the normal
const publisher = skill.indexOf('Now execute the deferred Step 1.7');
const snapshotStart = skill.indexOf('### Foreground Dataverse planning');
const conceptsStart = skill.indexOf('Build `<working_dir>/.tmp/dataverse-concepts.json`');
- const commandsStart = skill.indexOf('SNAPSHOT_PATH="');
+ const commandsStart = skill.indexOf("SNAPSHOT_PATH='");
assert.ok(architectureStart >= 0 && architectureStart < publisher);
assert.ok(publisher < snapshotStart && snapshotStart < conceptsStart);
assert.ok(conceptsStart < commandsStart);
@@ -106,7 +108,7 @@ node() {
printf 'injected snapshot failure\\n' >&2
return 1
fi
- "$REAL_NODE" -e 'require("node:fs").writeFileSync(process.argv[1], process.env.FIXTURE_SNAPSHOT)' "$SNAPSHOT_PATH"
+ "$REAL_NODE" -e 'const fs=require("node:fs"); require("node:assert/strict").equal(fs.realpathSync.native(process.cwd()), fs.realpathSync.native(process.env.OWNER_ROOT)); fs.writeFileSync(process.argv[1], process.env.FIXTURE_SNAPSHOT)' "$SNAPSHOT_PATH"
;;
*/render-dataverse-architect-evidence.js)
if [ "$FAILURE_STAGE" = evidence ]; then
@@ -120,23 +122,30 @@ node() {
}
`;
for (const failureStage of ['snapshot', 'evidence']) {
- const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'planning recovery '));
+ const directory = fs.mkdtempSync(path.join(os.tmpdir(), "planning owner's $root `printf value` "));
testContext.after(() => fs.rmSync(directory, { recursive: true, force: true }));
const temporary = path.join(directory, '.tmp');
fs.mkdirSync(temporary);
+ const caller = path.join(directory, 'different app');
+ fs.mkdirSync(caller);
+ for (const root of [directory, caller]) {
+ fs.writeFileSync(path.join(root, 'power.config.json'), '{"environmentId":"same-environment"}');
+ fs.writeFileSync(path.join(root, 'app.config.js'), 'module.exports = {};');
+ }
const snapshotFile = path.join(temporary, 'dataverse-foreground-planning-snapshot.json');
const evidenceFile = path.join(temporary, 'dataverse-architect-evidence.json');
fs.writeFileSync(snapshotFile, '{"stale":true}');
fs.writeFileSync(evidenceFile, '{"stale":true}');
- const block = commands.replaceAll('<working_dir>', directory.replaceAll('\\', '/'));
+ const block = commands.replaceAll('<working_dir>', directory.replaceAll('\\', '/').replaceAll("'", "'\\''"));
const env = {
...process.env, PLUGIN_ROOT: pluginRoot.replaceAll('\\', '/'), REAL_NODE: process.execPath.replaceAll('\\', '/'),
FIXTURE_SNAPSHOT: JSON.stringify(snapshot), FAILURE_STAGE: failureStage,
+ OWNER_ROOT: directory,
POWER_PLATFORM_SKILLS_TELEMETRY_MOBILE_APP_OPTOUT: '1',
};
const failed = spawnSync(bash, ['-s'], {
input: `${stub}\n${block}\nresult=$?\nprintf 'CONTROLLER_READY:%s\\n' "$result"\nexit "$result"`,
- env, encoding: 'utf8', timeout: 10000,
+ env, cwd: caller, encoding: 'utf8', timeout: 10000,
});
assert.equal(failed.status, 2, failed.stderr);
assert.match(failed.stderr, /NEEDS_RECOVERY: dataverse-(snapshot|evidence)/);
@@ -149,11 +158,19 @@ node() {
const recovered = spawnSync(bash, ['-s'], {
input: `${stub}\n${block}`,
- env: { ...env, FAILURE_STAGE: '' }, encoding: 'utf8', timeout: 10000,
+ env: { ...env, FAILURE_STAGE: '' }, cwd: caller, encoding: 'utf8', timeout: 10000,
});
assert.equal(recovered.status, 0, recovered.stderr);
assert.match(recovered.stdout, /Dataverse inventory:/);
loadAndValidateArchitectEvidence(snapshotFile, evidenceFile);
+ const missing = commands.replaceAll('<working_dir>',
+ path.join(directory, 'missing app').replaceAll('\\', '/').replaceAll("'", "'\\''"));
+ const invalidRoot = spawnSync(bash, ['-s'], {
+ input: `${stub}\n${missing}`,
+ env: { ...env, FAILURE_STAGE: '' }, cwd: caller, encoding: 'utf8', timeout: 10000,
+ });
+ assert.equal(invalidRoot.status, 1);
+ assert.match(invalidRoot.stderr, /BLOCKED: cannot enter working_dir/);
}
});
diff --git a/plugins/mobile-apps/scripts/tests/data-model-edit-scope-contract.test.js b/plugins/mobile-apps/scripts/tests/data-model-edit-scope-contract.test.js
new file mode 100644
index 000000000..56a57c8bc
--- /dev/null
+++ b/plugins/mobile-apps/scripts/tests/data-model-edit-scope-contract.test.js
@@ -0,0 +1,329 @@
+'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 read = (file) => fs.readFileSync(path.join(pluginRoot, file), 'utf8').replace(/\r\n?/g, '\n');
+const skill = (name) => read(`skills/${name}/SKILL.md`);
+const setup = skill('setup-datamodel');
+const seed = skill('add-sample-data');
+const create = skill('create-mobile-app');
+
+for (const [eolName, eol] of [['LF', '\n'], ['CRLF', '\r\n']]) {
+ test(`every seed Dataverse command forwards the resolved tenant (${eolName})`, () => {
+ const commands = [...seed.replace(/\n/g, eol).replace(/\r\n?/g, '\n')
+ .matchAll(/^ *```bash\n([\s\S]*?)\n *```/gm)]
+ .map((match) => match[1])
+ .filter((block) => block.includes('node "${PLUGIN_ROOT}/scripts/dataverse-request.js"'));
+ assert.equal(commands.length, 8, 'Cover reads, both batch paths, and resumed parent lookup');
+ for (const command of commands) {
+ assert.equal((command.match(/scripts\/dataverse-request\.js/g) || []).length, 1);
+ assert.match(command, /--tenant-id '<tenantId-from-resolve-environment>'/);
+ }
+ });
+}
+
+test('seed media and recovery keep the selected tenant instead of ambient credentials', () => {
+ const identity = section(seed, 'Capture the **environment URL**', '### Step 2');
+ assert.match(identity, /validated Step 1 value again in every fresh shell call/);
+ assert.match(identity, /Missing or conflicting tenant context returns `NEEDS_CONTEXT` before the call/);
+ const media = section(seed, '#### Step 5d', '#### Step 5e');
+ assert.match(media, /Pass the Step 1 environment URL and tenant ID explicitly/);
+ assert.match(media, /authentication and token-refresh path/);
+ assert.match(media, /do not invoke it\s+or fall back to ambient credentials/);
+ const retry = section(seed, '#### Step 5f', '### Step 6');
+ assert.match(retry, /explicit `--tenant-id` from the validated Step 1 identity/);
+ assert.match(retry, /never switch tenants to recover/);
+});
+
+function section(text, start, end) {
+ const from = text.indexOf(start);
+ const to = text.indexOf(end, from + start.length);
+ assert.ok(from >= 0, `Missing section: ${start}`);
+ assert.ok(to > from, `Missing section end: ${end}`);
+ return text.slice(from, to);
+}
+
+// Scope bugs occur between owners and leaves, so check the executed handoffs
+// and downstream selection/insertion rules, not just a new entry-point sentence.
+test('the existing editor forwards approved data context and a bounded seed allowlist', () => {
+ const edit = skill('edit-app');
+ const apply = section(edit, '### Step 5 — Apply app mutations', '#### Step 5.5');
+ for (const required of ['MOBILE_APP_ORCHESTRATING=1', 'orchestrator: edit-app', 'working_dir',
+ 'phase: implementation', 'approved_scope', "--working-dir '<working_dir>'",
+ 'offline_reconciliation_owner: edit-app', '--tables', 'retiring_tables']) {
+ assert.ok(apply.includes(required), required);
+ }
+ assert.match(apply, /verified newly created tables|createdThisEdit/);
+ assert.match(apply, /empty[\s\S]*skip seeding|skip seeding[\s\S]*empty/);
+ assert.match(edit, /seed table allowlist|seed.*allowlist/i);
+ const reconcile = section(edit, '#### Step 5.6', '### Step 6');
+ assert.match(reconcile, /--project-root '<working_dir>'/);
+ assert.match(reconcile, /Scoped helper\s+handoffs/);
+ assert.match(reconcile, /--working-dir '<working_dir>'/);
+});
+
+test('setup dispatches retained connector refresh with an explicit selector and registered identity', () => {
+ const refresh = section(setup, '**Retained-source refresh only:**', 'Run sequentially.');
+ assert.match(refresh, /Invoke skill: \/add-connector/);
+ assert.match(refresh, /approved_scope: <refresh operation, exact registered name, verified API\/dataset\/resource and connection ID\/reference>/);
+ const args = refresh.split('Arguments:')[1];
+ for (const required of ["--working-dir '<working_dir>'", '--connector <verified-api-id>',
+ '--refresh', '--data-source-name "<registered-name>"']) {
+ assert.ok(args.includes(required), required);
+ }
+ assert.doesNotMatch(args, /add-data-source|create-connection/);
+});
+
+test('offline checker failures stop setup before helper mutations or clean summaries', () => {
+ const offline = section(setup, '### Phase 6.5', '### Phase 7');
+ const failure = section(offline, 'Capture the exit status', 'For a valid successful check');
+ for (const condition of ['non-zero exit', 'status: error', 'missing/malformed JSON', 'unknown status']) {
+ assert.ok(failure.includes(condition), condition);
+ }
+ assert.match(failure, /offline_reconciliation: failed/);
+ assert.match(failure, /skip mutation helpers/);
+ assert.match(failure, /DONE_WITH_CONCERNS/);
+ assert.match(failure, /BLOCKED/);
+ assert.match(failure, /Do not claim completed reconciliation/);
+ assert.match(offline, /Re-check to `in-sync` using the same failure path/);
+});
+
+test('offline reconciliation owners forward explicit roots and exact approved helper scopes', () => {
+ const reference = read('shared/references/offline-profile-reconciliation.md');
+ const handoff = section(reference, '### Scoped helper handoffs', 'Re-run the delta check');
+ assert.match(handoff, /orchestrator: <current reconciliation owner>/);
+ assert.match(handoff, /working_dir: <owner's resolved absolute working_dir>/);
+ assert.match(handoff, /approved_scope: <exact environment\/profile identity/);
+ assert.equal((handoff.match(/--working-dir '<working_dir>'/g) || []).length, 2);
+ assert.match(handoff, /Never send `--all-new`/);
+ for (const owner of ['setup-datamodel', 'edit-app', 'add-dataverse', 'deploy']) {
+ const content = skill(owner);
+ assert.match(content, /Scoped helper\s+handoffs/, owner);
+ assert.ok(content.includes(`orchestrator: ${owner}`), owner);
+ }
+});
+
+test('setup-datamodel resolves the owner before inspecting project or environment', () => {
+ const discovery = section(setup, '### Phase 1', '### Phase 2');
+ assert.match(discovery, /Resolve one absolute `working_dir` before reading project files/);
+ assert.match(discovery, /For a nested call, inherit the owner's absolute `working_dir`/);
+ assert.match(discovery, /a mismatch returns `NEEDS_CONTEXT` before any project or cloud work/);
+ assert.match(discovery, /Only a direct call without an override may use that invocation/);
+ assert.match(discovery, /A missing nested owner path is an error/);
+ assert.match(discovery, /cd -- '<working_dir>' \|\| \{ echo "BLOCKED: cannot enter working_dir" >&2; exit 1; \}/);
+ assert.match(discovery, /selected working directory is not an initialized mobile app/);
+ assert.match(discovery, /ERROR: selected app has no environmentId/);
+ assert.match(discovery, /resolve-environment\.js" "\$environment_id"/);
+ assert.match(discovery, /Stop on failure; do not switch directories or re-scaffold/);
+ assert.doesNotMatch(setup, /<cwd>/);
+});
+
+test('the setup planner and all child handoffs share the same absolute owner root', () => {
+ const planner = section(setup, 'Task: mobile-app:data-model-architect', '#### Path C');
+ assert.match(planner, /Working directory: <working_dir>/);
+ assert.match(planner, /Output proposal: <working_dir>\/_dm_section\.md/);
+ for (const [start, end] of [
+ ['Invoke skill: /add-dataverse', '`/add-dataverse` creates'],
+ ['Invoke skill: /add-connector', 'Run sequentially.'],
+ ]) {
+ const handoff = section(setup, start, end);
+ assert.match(handoff, /Context:[\s\S]*working_dir: <working_dir>/);
+ assert.match(handoff, /Arguments:[\s\S]*--working-dir '<working_dir>'/);
+ }
+ assert.match(setup, /--plan-section '<working_dir>\/native-app-plan\.md#data-model'/);
+ const retirement = section(setup, '### Phase 6.25', '### Phase 6.5');
+ assert.match(retirement, /working_dir: <working_dir>/);
+ assert.match(retirement, /--working-dir '<working_dir>'/);
+ const offline = section(setup, '### Phase 6.5', '### Phase 7');
+ assert.match(offline, /--project-root '<working_dir>'/);
+ assert.match(offline, /offline helpers also inherit the same absolute `working_dir`/);
+});
+
+test('data-model proposals and actual inventory keep separate lifecycle ownership', () => {
+ assert.match(setup, /scratch\n`_dm_section\.md` is not a second source of truth/);
+ assert.match(setup, /Do not reuse operation manifests\nor approval receipts bound to the previous plan/);
+ assert.match(setup, /verified materialized\nmanifest is updated after execution\/verification/);
+ assert.match(setup, /return a non-success status rather than claiming the plan is fully applied/);
+ assert.match(setup, /Connector-only work without Dataverse does\nnot require or create a Dataverse manifest/);
+});
+
+test('setup plan-only exits before saving or applying every proposal path', () => {
+ const approval = section(setup, '### Phase 4', '### Phase 5');
+ const guard = section(approval, '**Proposal-only exit:**', 'Present the full plan');
+ assert.match(guard, /`--plan-only` is present or the caller's phase is\nplanning/);
+ assert.match(guard, /Data Model, Connectors, and retirement\/offline\nimpact/);
+ assert.match(guard, /STOP before the execution approval/);
+ assert.match(guard, /Do not save `native-app-plan\.md`, mint approval receipts/);
+ assert.match(guard, /or invoke Phases 5–7/);
+ assert.match(guard, /separate request without that flag/);
+ assert.ok(approval.indexOf('**Proposal-only exit:**') < approval.indexOf('- **Approved**'));
+});
+
+test('every preapproval environment lookup permits only non-persisting tenant resolution', () => {
+ const shared = section(read('shared/shared-instructions.md'), 'For proposal-only environment context', '\n---');
+ assert.match(shared, /reuse matching complete caller context, or run/);
+ assert.match(shared, /conflicting or still\nincomplete context returns `NEEDS_CONTEXT`/);
+ assert.match(shared, /configuration-persisting resolver remains forbidden before\nimplementation approval/);
+ assert.match(shared, /Do not remove flags or redirect resolver output into app configuration/);
+ assert.match(shared, /not a forced-fresh metadata read/);
+ assert.doesNotMatch(shared, /Skip the resolver command|do not run it during `--plan-only`/);
+
+ for (const [name, content, start, end] of [
+ ['setup-datamodel', setup, '### Phase 1', '### Phase 2'],
+ ['add-dataverse', skill('add-dataverse'), '### Step 1', '### Step 2'],
+ ]) {
+ const discovery = section(content, start, end);
+ assert.match(discovery, /For `--plan-only` or a planning-phase handoff/);
+ assert.match(discovery, /(?:non-persisting lookup is used|non-persisting\nlookup) before approval in a normal invocation/);
+ assert.match(discovery, /returns `NEEDS_CONTEXT`/);
+ const commands = [...discovery.matchAll(/^node "[^"\n]*\/resolve-environment\.js" [^\n]+$/gm)];
+ assert.equal(commands.length, 1, `${name}: one explicit resolver command`);
+ assert.match(commands[0][0], / --no-cache --require-tenant$/);
+ assert.doesNotMatch(discovery, /Skip the resolver command|>\s*(?:auth\.config|app|\.resolved-environment)\.json/);
+ assert.ok(discovery.indexOf('read-only') < discovery.indexOf('resolve-environment.js'));
+ }
+});
+
+test('direct Dataverse requests cannot replay an unrelated existing plan', () => {
+ const dataverse = skill('add-dataverse');
+ const plan = section(dataverse, '### Step 2 — Resolve plan', '#### Step 2a');
+ const gate = section(plan, '**Resolve the current request', 'Before reading plan content');
+ assert.match(gate, /direct\nstandalone invocation must compare its requested/);
+ assert.match(gate, /Present and approve\nthat exact delta/);
+ assert.match(gate, /do not apply other pending rows/);
+ assert.match(gate, /`NEEDS_CONTEXT` without mutation/);
+ assert.match(gate, /`--plan-only` returns the proposal and STOPs before plan saving/);
+ assert.match(plan, /same restriction to the newly approved standalone request delta/);
+ const services = section(dataverse, '### Step 6 — Add data sources', '### Step 6b');
+ assert.match(services, /Preserve verified unchanged services outside the approved delta/);
+ assert.match(services, /Only an approved missing binding takes\nthe add command/);
+});
+
+test('setup distinguishes retained-source refresh from schema and connector addition', () => {
+ const data = section(setup, '### Phase 5', '### Phase 6 —');
+ const connectors = section(setup, '### Phase 6 —', '### Phase 6.25');
+ for (const phase of [data, connectors]) {
+ assert.match(phase, /--refresh --data-source-name "<registered-name>"/);
+ assert.match(phase, /approved_scope/);
+ }
+ assert.match(data, /do not execute the schema-add handoff/);
+ assert.match(connectors, /return without connection creation or `add-data-source`/);
+});
+
+test('offline retirement survives no-op addition checks, summaries, and resume', () => {
+ const removal = read('shared/references/data-source-removal.md');
+ const reconcile = read('shared/references/offline-profile-reconciliation.md');
+ for (const status of ['not-applicable', 'retained', 'pending', 'reconciled']) {
+ assert.ok(removal.includes(`| \`${status}\` |`), status);
+ }
+ assert.match(removal, /offlineRetirement.*leaf result and the existing\nmemory-bank entry/);
+ assert.match(removal, /Preserve pending outcomes on retries\/resume/);
+ assert.match(removal, /could break retained offline behavior blocks app-binding removal/);
+ assert.match(removal, /`in-sync`, `no-manifest`, or `no-profile` result never clears `offlineRetirement`/);
+ assert.match(reconcile, /None of `in-sync`, `no-manifest`, or `no-profile` clears a pending retirement/);
+ const offline = section(setup, '### Phase 6.5', '### Phase 7');
+ const summary = section(setup, '### Phase 7', '## Reference');
+ assert.match(offline, /never discard a recorded `offlineRetirement` outcome/);
+ assert.match(offline, /existing `offlineRetirement` outcomes unchanged/);
+ assert.match(summary, /`pending` returns `DONE_WITH_CONCERNS`, not a clean `DONE`/);
+ assert.match(summary, /whether to retain or remove that coverage is pending/);
+});
+
+test('sample seeding resolves a required explicit scope before auth or discovery', () => {
+ const scope = section(seed, '### Step 0', '## Prototype Seed Reuse');
+ assert.match(scope, /--tables <comma-separated-logical-names>/);
+ assert.match(scope, /Required for every orchestrated call, including fresh creation/);
+ assert.match(scope, /matching `--tables`\nbefore auth, record-count queries, or generation/);
+ assert.match(scope, /missing or malformed\nallowlist returns `NEEDS_CONTEXT`/);
+ assert.match(scope, /explicitly empty allowlist is a no-op/);
+ assert.match(scope, /return without cloud calls or writes/);
+ assert.match(scope, /overlaps `retiringTables`, stop/);
+ assert.match(scope, /Do not silently drop unknown\nnames/);
+ assert.match(scope, /For `--plan-only` or a planning-phase handoff/);
+ assert.match(scope, /media policy before Step 5\. Planning approval is not insertion approval/);
+ assert.match(scope, /Do not generate media files, insert\/update\/upload records, or change the app\nplan, manifest, or seeded-data history on this path/);
+ const discovery = section(seed, '### Step 1', '### Step 2');
+ assert.match(discovery, /^node "\$\{PLUGIN_ROOT\}\/scripts\/resolve-environment\.js" "\$environment_id" --no-cache --require-tenant$/m);
+ assert.match(discovery, /Incomplete or conflicting identity returns `NEEDS_CONTEXT`/);
+ assert.match(discovery, /Do not remove the safety flags, select another\nenvironment, or persist resolver output to recover/);
+ assert.ok(seed.indexOf('### Step 0') < seed.indexOf('### Step 1'));
+});
+
+test('transitional and unrelated manifest entries cannot enter the seed loop', () => {
+ const discovery = section(seed, '### Step 2', '### Step 3');
+ assert.match(discovery, /take only\nthe validated `seedTables` entries before any per-table metadata\/count query/);
+ assert.match(discovery, /Keep unrelated manifest entries as inventory only/);
+ assert.match(discovery, /missing in an orchestrated call, return `BLOCKED`/);
+ assert.match(discovery, /standalone request with an explicit allowlist, fetch metadata\nonly for those logical names/);
+ assert.match(seed, /Evaluate only the validated seed allowlist/);
+ assert.doesNotMatch(seed, /every table in the manifest gets seeded|All tables from the manifest are evaluated/);
+});
+
+test('lookup dependencies never implicitly expand seed scope', () => {
+ const dependencies = section(seed, '#### Step 3b', '### Step 4');
+ assert.match(dependencies, /reuse a verified existing\nparent record through a bounded read/);
+ assert.match(dependencies, /Reading a lookup parent is not permission to insert\/update it/);
+ assert.match(dependencies, /return `NEEDS_CONTEXT` to the owner/);
+ assert.match(dependencies, /Never auto-add\na parent to `seedTables`, create a retiring parent, or omit a required lookup/);
+ assert.match(dependencies, /Retiring lookup targets block/);
+});
+
+test('seed preview does not treat row counts or cancellation as insertion approval', () => {
+ const preview = section(seed, '#### Step 4d', '### Step 5');
+ assert.match(preview, /For `--plan-only` or a planning-phase handoff, return the preview and STOP here/);
+ assert.match(preview, /neither an earlier approval nor a populated manifest overrides that boundary/);
+ assert.match(preview, /exact seed tables\/count policy and\nany media writes are already approved/);
+ assert.match(preview, /Otherwise obtain explicit approval/);
+ assert.match(preview, /Row counts prevent duplicate volume; they are not consent/);
+ assert.match(preview, /Cancellation stops/);
+ assert.doesNotMatch(preview, /No confirmation prompt/);
+});
+
+test('batches, prototype seeds, media, and retries all honor the same allowlist', () => {
+ const prototype = section(seed, '## Prototype Seed Reuse', '### Step 1');
+ const batches = section(seed, '#### Step 5b', '#### Step 5c');
+ const media = section(seed, '#### Step 5d', '#### Step 5e');
+ const resume = section(seed, '#### Step 5f', '### Step 6');
+ assert.match(prototype, /prototype seed files cannot widen the approved set/);
+ assert.match(batches, /re-check every target logical name\nagainst `seedTables` and `retiringTables`/);
+ assert.match(batches, /reject the entire proposed batch/);
+ assert.match(batches, /scope error, not a record failure to continue past/);
+ assert.match(media, /must still be in `seedTables` and outside\n`retiringTables`/);
+ assert.match(resume, /Reconfirm the current approved `seedTables` and retirement exclusions/);
+ assert.match(resume, /never retry a retiring table/);
+});
+
+test('creation supplies a bounded sample-data handoff too', () => {
+ const seeding = section(create, '### Step 8.5', '### Offline profile');
+ assert.match(seeding, /excluding standard system tables by default/);
+ assert.match(seeding, /If the initial approval\ndid not cover the exact seed set/);
+ assert.match(seeding, /empty or declined scope skips seeding without cloud writes/);
+ assert.match(seeding, /orchestrator: create-mobile-app/);
+ assert.match(seeding, /working_dir: <working_dir>/);
+ assert.match(seeding, /--tables "<approved-seed-table-logical-names>"/);
+ assert.match(seeding, /before per-table discovery/);
+ assert.doesNotMatch(seeding, /not optional/);
+});
+
+test('manual post-Dataverse seeding does not replay the project inventory or auto-approve', () => {
+ const materialize = skill('add-dataverse');
+ const offer = section(materialize, 'After printing the summary', '## Key Rules');
+ assert.match(materialize, /actual created\/extended\/reused table sets for this invocation/);
+ assert.match(materialize, /never this transitional\ninventory as its insertion scope/);
+ assert.match(offer, /Only an explicit yes approves seeding/);
+ assert.match(offer, /--tables "<approved-logical-names>"/);
+ assert.match(offer, /--exclude-tables "<retiring-logical-names-or-empty>"/);
+ assert.doesNotMatch(offer, /empty input auto-proceeds/);
+});
+
+test('Dataverse operation classification is visibly before dedicated delegation', () => {
+ const connector = skill('add-connector');
+ const classification = connector.indexOf('Classify the requested operation before matching');
+ const table = connector.indexOf('| Connector API name');
+ assert.ok(classification >= 0 && table > classification);
+ assert.match(connector.slice(classification, table), /skipping\nconnection lookup and data-source generation/);
+});
diff --git a/plugins/mobile-apps/scripts/tests/helpers/markdown-shell-blocks.js b/plugins/mobile-apps/scripts/tests/helpers/markdown-shell-blocks.js
new file mode 100644
index 000000000..6950e02c0
--- /dev/null
+++ b/plugins/mobile-apps/scripts/tests/helpers/markdown-shell-blocks.js
@@ -0,0 +1,19 @@
+'use strict';
+
+function shellBlocks(text, language = 'bash') {
+ const normalized = text.replace(/\r\n?/g, '\n');
+ const fences = /^([ \t]*(?:>[ \t]*)*)```(\w+)[ \t]*\n([\s\S]*?)\n[ \t]*(?:>[ \t]*)*```[ \t]*(?=\n|$)/gm;
+ return [...normalized.matchAll(fences)]
+ .filter((match) => match[2] === language)
+ .map((match) => {
+ const prefix = match[1];
+ // Remove only the Markdown prefix, keeping the command's own indentation and quotes.
+ return match[3].split('\n').map((line) => {
+ if (line.startsWith(prefix)) return line.slice(prefix.length);
+ if (line.trim() === prefix.trim()) return '';
+ return line;
+ }).join('\n');
+ });
+}
+
+module.exports = { shellBlocks };
diff --git a/plugins/mobile-apps/scripts/tests/offline-helper-root-contract.test.js b/plugins/mobile-apps/scripts/tests/offline-helper-root-contract.test.js
new file mode 100644
index 000000000..84ea58adc
--- /dev/null
+++ b/plugins/mobile-apps/scripts/tests/offline-helper-root-contract.test.js
@@ -0,0 +1,541 @@
+'use strict';
+
+const assert = require('node:assert/strict');
+const { spawnSync } = require('node:child_process');
+const { randomUUID } = require('node:crypto');
+const fs = require('node:fs');
+const path = require('node:path');
+const test = require('node:test');
+const { shellBlocks } = require('./helpers/markdown-shell-blocks');
+
+const pluginRoot = path.resolve(__dirname, '../..');
+const read = (file) => fs.readFileSync(path.join(pluginRoot, file), 'utf8').replace(/\r\n?/g, '\n');
+const helpers = ['add-table-to-offline-profile', 'edit-offline-profile', 'enable-tables-offline'];
+const documents = Object.fromEntries(helpers.map((name) => [name, read(`skills/${name}/SKILL.md`)]));
+const reference = read('shared/references/app-working-directory.md');
+const rootLink = '[app-working-directory.md](${PLUGIN_ROOT}/shared/references/app-working-directory.md)';
+const guard = shellBlocks(reference)[0];
+const slashPath = (value) => value.replaceAll('\\', '/');
+
+// The documented Windows shell is Git Bash, not a WSL filesystem.
+const bashPaths = process.platform === 'win32'
+ ? (spawnSync('where.exe', ['bash'], { encoding: 'utf8' }).stdout || '').split(/\r?\n/)
+ : [];
+const bash = bashPaths.find((entry) => /[\\/]Git[\\/]/i.test(entry)) || 'bash';
+const context = {
+ environmentId: 'owner-environment',
+ environmentUrl: 'https://contoso.crm.dynamics.com',
+ tenantId: '00000000-0000-0000-0000-000000000000',
+ profileId: '11111111-1111-1111-1111-111111111111',
+ itemId: '22222222-2222-2222-2222-222222222222',
+ table: 'cr123_visit',
+};
+
+function section(text, from, to) {
+ const start = text.indexOf(from);
+ const end = text.indexOf(to, start + from.length);
+ assert.ok(start >= 0 && end > start, `Missing section: ${from}`);
+ return text.slice(start, end);
+}
+
+function fixture(t) {
+ // Keep generated fixtures in the checkout, never the system temporary directory.
+ const relative = `.offline-helper-root-fixture-${randomUUID()}`;
+ fs.mkdirSync(relative);
+ t.after(() => fs.rmSync(relative, { recursive: true, force: true }));
+ for (const [name, environmentId] of [
+ ["owner's app [test] $literal $(printf value) `printf tick`", context.environmentId],
+ ['different app', 'caller-environment'],
+ ]) {
+ const root = path.join(relative, name);
+ fs.mkdirSync(root);
+ fs.writeFileSync(path.join(root, 'app.config.js'), 'module.exports = {};\n');
+ fs.writeFileSync(path.join(root, 'power.config.json'), JSON.stringify({ environmentId }));
+ fs.writeFileSync(path.join(root, '.datamodel-manifest.json'),
+ JSON.stringify({ tables: [{ logicalName: root.includes('different') ? 'cr123_other' : context.table }] }));
+ fs.writeFileSync(path.join(root, 'offline-profile.json'),
+ JSON.stringify({ profileId: root.includes('different') ? 'other-profile' : context.profileId }));
+ fs.writeFileSync(path.join(root, 'memory-bank.md'), '# Existing memory\n');
+ }
+ fs.mkdirSync(path.join(relative, 'mock plugin'));
+ // Record every Node invocation, including config reads. Plugin scripts are
+ // intercepted, so no production auth, Dataverse, telemetry, or CLI can run.
+ fs.writeFileSync(path.join(relative, 'probe.cjs'), `
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const path = require('node:path');
+const { spawnSync } = require('node:child_process');
+const args = process.argv.slice(2);
+fs.appendFileSync(process.env.TRACE_FILE, JSON.stringify({
+ cwd: process.cwd(), args,
+}) + '\\n');
+if (args[0] === '-p') {
+ assert.equal(args[1], "require('./power.config.json').environmentId || ''");
+ const result = spawnSync(process.execPath, args, { stdio: 'inherit' });
+ assert.ifError(result.error);
+ process.exit(result.status);
+}
+const script = path.basename(args[0]);
+assert.ok(['resolve-environment.js', 'dataverse-request.js', 'update-entity-offline-flags.js'].includes(script));
+assert.equal(path.resolve(args[0]), path.resolve(process.env.PLUGIN_ROOT, 'scripts', script));
+if (script === 'resolve-environment.js') {
+ assert.deepEqual(args.slice(2), ['--no-cache', '--require-tenant']);
+ console.log(JSON.stringify({ environmentId: args[1] }));
+} else if (script === 'dataverse-request.js') {
+ assert.ok(['GET', 'POST', 'PATCH', 'DELETE'].includes(args[2]));
+ assert.ok(args[3] && !args[3].startsWith('--'), 'API path must precede options');
+ const bodyIndex = args.indexOf('--body');
+ if (bodyIndex >= 0) JSON.parse(args[bodyIndex + 1]);
+ console.log('{"status":204}');
+} else {
+ assert.deepEqual(args.slice(2, 4), ['--table', 'cr123_visit']);
+ assert.equal(args[args.indexOf('--tenant-id') + 1], ${JSON.stringify(context.tenantId)});
+ console.log('{"status":204}');
+}
+`);
+ const directory = path.resolve(relative);
+ const owner = path.join(directory, "owner's app [test] $literal $(printf value) `printf tick`");
+ const caller = path.join(directory, 'different app');
+ const callerFiles = Object.fromEntries(fs.readdirSync(caller)
+ .map((name) => [name, fs.readFileSync(path.join(caller, name), 'utf8')]));
+ return {
+ directory, owner, caller, callerFiles,
+ trace: path.join(directory, 'trace.jsonl'),
+ mockPlugin: path.join(directory, 'mock plugin'),
+ probe: path.join(directory, 'probe.cjs'),
+ };
+}
+
+function render(block, root) {
+ let command = block.replaceAll('<working_dir>', slashPath(root).replaceAll("'", "'\\''"));
+ for (const [token, value] of Object.entries({
+ 'selected-environment-id': context.environmentId,
+ envUrl: context.environmentUrl,
+ tenantId: context.tenantId,
+ profileId: context.profileId,
+ itemId: context.itemId,
+ newItemId: context.itemId,
+ table: context.table,
+ DisplayName: 'Visit',
+ relationshipSchemaName: 'cr123_visit_contact',
+ 'MetadataId-from-EntityDefinitions': '33333333-3333-3333-3333-333333333333',
+ '0|1|2': '1',
+ bool: 'true',
+ new: '10',
+ 'new-bool': 'true',
+ table_logical_name: context.table,
+ 'table-logicalname': context.table,
+ 'App Name': 'Test app',
+ 'Table Display Name': 'Visit',
+ 'URL-ENCODED-FETCH': 'fixture-fetch',
+ 'relationship-schema-name': 'cr123_visit_contact',
+ 'MetadataId-from-§5': '33333333-3333-3333-3333-333333333333',
+ parentItemId: context.itemId,
+ systemuserid: '44444444-4444-4444-4444-444444444444',
+ teamid: '55555555-5555-5555-5555-555555555555',
+ membershipid: '66666666-6666-6666-6666-666666666666',
+ 'team-name': 'Test team',
+ entitysetname: 'cr_visits',
+ T: context.table,
+ })) command = command.replaceAll(`<${token}>`, value);
+ // The recipes abbreviate the JSON-string selectedcolumns array with [...].
+ return command.replaceAll('[...]', '[\\"cr123_title\\"]');
+}
+
+function run(block, f, root = f.owner) {
+ const result = spawnSync(bash, ['-s'], {
+ input: `node() { "$REAL_NODE" "$PROBE" "$@"; }\n${render(block, root)}\n`,
+ cwd: f.caller,
+ env: {
+ ...process.env,
+ REAL_NODE: slashPath(process.execPath),
+ PROBE: slashPath(f.probe),
+ PLUGIN_ROOT: slashPath(f.mockPlugin),
+ TRACE_FILE: f.trace,
+ POWER_PLATFORM_SKILLS_TELEMETRY_MOBILE_APP_OPTOUT: '1',
+ },
+ encoding: 'utf8',
+ timeout: 10000,
+ });
+ assert.ifError(result.error);
+ return result;
+}
+
+function calls(f) {
+ return fs.existsSync(f.trace)
+ ? fs.readFileSync(f.trace, 'utf8').trim().split('\n').filter(Boolean).map(JSON.parse)
+ : [];
+}
+
+for (const name of helpers) {
+ const text = documents[name];
+
+ test(`${name}: child context uses the canonical fail-closed contract before project access`, () => {
+ const binding = section(text, '## Invocation context and root binding', '## Workflow');
+ assert.ok(binding.includes(rootLink));
+ assert.ok(text.indexOf(rootLink) < text.indexOf('```bash'));
+ assert.match(binding, /always a \*\*child invocation\*\*/);
+ assert.match(binding, /owner's absolute `working_dir`/);
+ assert.match(binding, /`--working-dir`[\s\S]*same native-canonical root/);
+ assert.match(binding, /Missing, relative, or conflicting root[\s\S]*`NEEDS_CONTEXT` before project access/);
+ assert.match(binding, /inaccessible directory[\s\S]*`BLOCKED`/);
+ assert.match(binding, /Never use the launch cwd/);
+ assert.doesNotMatch(text, /fs\.realpathSync|readlink|realpath --/);
+ assert.match(reference, /fs\.realpathSync\.native/);
+ assert.match(reference, /Set-Location -LiteralPath '<working_dir>' -ErrorAction Stop/);
+ for (const field of ['MOBILE_APP_ORCHESTRATING=1', 'orchestrator', 'working_dir', 'phase', 'approved_scope']) {
+ assert.ok(binding.includes(field), field);
+ }
+ assert.match(binding, /marker is\s+not\s+approval/);
+ assert.match(binding, /`--plan-only` or a planning-phase handoff/);
+ assert.match(binding, /gate response cannot lift proposal-only mode/);
+ });
+
+ test(`${name}: every shell/file operation and linked retry is rooted without persistent shell state`, () => {
+ for (const eol of ['\n', '\r\n']) {
+ const blocks = shellBlocks(text.replace(/\n/g, eol));
+ assert.ok(blocks.length >= 6);
+ for (const block of blocks) {
+ assert.ok(block.startsWith(`${guard}\n`), block);
+ if (block.includes('/dataverse-request.js')) {
+ assert.ok(block.includes('--tenant-id "<tenantId>"'), block);
+ assert.ok(block.includes('"<envUrl>"'), block);
+ }
+ if (block.includes('/resolve-environment.js')) {
+ assert.match(block, / --no-cache --require-tenant$/);
+ assert.match(block, /require\('\.\/power\.config\.json'\)\.environmentId/);
+ assert.ok(block.includes('"$environment_id" != "<selected-environment-id>"'));
+ }
+ }
+ }
+ const files = ['power.config.json', '.datamodel-manifest.json',
+ 'docs/plan-artifacts/.datamodel-manifest.json', 'memory-bank.md'];
+ if (name !== 'enable-tables-offline') files.push('offline-profile.json', 'app/', 'src/');
+ for (const file of files) assert.ok(text.includes(`<working_dir>/${file}`), file);
+ assert.match(text, /every shell call and file tool/);
+ assert.match(text, /Re-supply the absolute `PLUGIN_ROOT`/);
+ assert.match(text, /[Mm]issing values\s+return\s+`NEEDS_CONTEXT`/);
+ assert.match(text, /no\s+prior `cd`, export, or shell variable persists/);
+ assert.match(text, /All linked recovery commands, re-GET verification, and retries/);
+ assert.doesNotMatch(text, /\$PROFILE_ID|\bin cwd\b/);
+ if (name !== 'enable-tables-offline') {
+ assert.match(text, /--project-root '<working_dir>'` in its own guarded call/);
+ const handoff = section(text, '```text\nArguments: --working-dir', '\n```');
+ for (const field of [
+ "--working-dir '<working_dir>'", '--profile-id "<profileId>"', '--table "<table>"',
+ 'MOBILE_APP_ORCHESTRATING=1', 'orchestrator', 'working_dir', 'phase', 'approved_scope',
+ 'environment ID/URL/tenant', 'profile ID', 'table allowlist', 'item ID',
+ 'supplied answers', '--plan-only',
+ ]) assert.ok(handoff.includes(field), field);
+ assert.match(text, /recipient must enforce the same canonical root contract/);
+ assert.match(text, /do not fall back to direct invocation or rediscovery/);
+ }
+ });
+
+ test(`${name}: documented commands and fresh retries cannot be redirected by another app cwd`, (t) => {
+ const f = fixture(t);
+ const blocks = shellBlocks(text);
+ const missing = path.join(f.directory, 'missing owner');
+ const notDirectory = path.join(f.owner, 'power.config.json');
+ for (const block of blocks) {
+ // Each execution is a new Bash process launched in the other valid app.
+ for (let attempt = 0; attempt < 2; attempt++) {
+ const result = run(block, f);
+ assert.equal(result.status, 0, `${block}\n${result.stderr}`);
+ }
+ for (const invalidRoot of [missing, notDirectory]) {
+ const before = calls(f);
+ const result = run(block, f, invalidRoot);
+ assert.equal(result.status, 1, result.stderr);
+ assert.match(result.stderr, /BLOCKED: cannot enter working_dir/);
+ assert.deepEqual(calls(f), before, 'A failed root must prevent even config reads');
+ }
+ }
+ const recorded = calls(f);
+ assert.ok(recorded.length > 0);
+ const requests = [];
+ for (const call of recorded) {
+ assert.equal(fs.realpathSync.native(call.cwd), fs.realpathSync.native(f.owner));
+ const [script, ...args] = call.args;
+ if (script.endsWith('/resolve-environment.js')) {
+ assert.deepEqual(args, [context.environmentId, '--no-cache', '--require-tenant']);
+ } else if (script.endsWith('/dataverse-request.js')) {
+ requests.push(args);
+ assert.equal(args[0], context.environmentUrl);
+ assert.equal(args[args.indexOf('--tenant-id') + 1], context.tenantId);
+ if (args[2].startsWith('mobileofflineprofileitems(')) assert.ok(args[2].includes(context.itemId));
+ if (args[2].startsWith('mobileofflineprofiles(')) assert.ok(args[2].includes(context.profileId));
+ if (args[2].startsWith('EntityDefinitions(')) assert.ok(args[2].includes(context.table));
+ if (args[2] === 'PublishXml') {
+ const body = JSON.parse(args[args.indexOf('--body') + 1]);
+ const target = body.ParameterXml.includes('<entities>')
+ ? `<entity>${context.table}</entity>`
+ : `<mobileofflineprofile>${context.profileId}</mobileofflineprofile>`;
+ assert.ok(body.ParameterXml.includes(target));
+ }
+ if (args[2] === 'mobileofflineprofileitems') {
+ const body = JSON.parse(args[args.indexOf('--body') + 1]);
+ assert.equal(body['[email protected]'], `/mobileofflineprofiles(${context.profileId})`);
+ assert.equal(body.selectedentitytypecode, context.table);
+ }
+ } else if (script.endsWith('/update-entity-offline-flags.js')) {
+ assert.equal(args[0], context.environmentUrl);
+ assert.equal(args[args.indexOf('--tenant-id') + 1], context.tenantId);
+ } else {
+ assert.equal(script, '-p');
+ }
+ }
+ const methods = name === 'enable-tables-offline' ? ['GET', 'POST'] : ['GET', 'POST', 'PATCH'];
+ for (const method of methods) {
+ assert.ok(requests.some((args) => args[1] === method), method);
+ }
+ assert.deepEqual(fs.readdirSync(f.caller).sort(), Object.keys(f.callerFiles).sort());
+ for (const [file, original] of Object.entries(f.callerFiles)) {
+ assert.equal(fs.readFileSync(path.join(f.caller, file), 'utf8'), original);
+ }
+ });
+
+ test(`${name}: invalid owner markers or environment cannot borrow the launch app configuration`, (t) => {
+ const f = fixture(t);
+ const blocks = shellBlocks(text);
+ fs.unlinkSync(path.join(f.owner, 'app.config.js'));
+ const invalidProject = run(blocks[0], f);
+ assert.equal(invalidProject.status, 1);
+ assert.match(invalidProject.stderr, /BLOCKED: working_dir is not an initialized app/);
+ assert.deepEqual(calls(f), []);
+
+ const resolver = blocks.find((block) => block.includes('/resolve-environment.js'));
+ for (const environmentId of ['', 'other-environment']) {
+ fs.writeFileSync(path.join(f.owner, 'power.config.json'), JSON.stringify({ environmentId }));
+ const result = run(resolver, f);
+ assert.equal(result.status, 1);
+ assert.match(result.stderr, /NEEDS_CONTEXT: selected environment does not match working_dir/);
+ }
+ fs.writeFileSync(path.join(f.owner, 'power.config.json'), '{bad JSON');
+ const malformed = run(resolver, f);
+ assert.equal(malformed.status, 1);
+ assert.match(malformed.stderr, /BLOCKED: unreadable power.config.json/);
+ assert.ok(calls(f).every((call) => call.args[0] === '-p'),
+ 'No resolver, auth, or Dataverse call is allowed after an invalid config');
+ });
+}
+
+test('add-table manifest discovery stays within the owner for both supported locations and missing files', (t) => {
+ const f = fixture(t);
+ const block = shellBlocks(documents['add-table-to-offline-profile'])
+ .find((command) => command.includes('no manifest in working_dir'));
+ let result = run(block, f);
+ assert.equal(result.status, 0, result.stderr);
+ assert.equal(result.stdout.trim(), `${slashPath(f.owner)}/.datamodel-manifest.json`);
+ fs.mkdirSync(path.join(f.owner, 'docs/plan-artifacts'), { recursive: true });
+ fs.renameSync(path.join(f.owner, '.datamodel-manifest.json'),
+ path.join(f.owner, 'docs/plan-artifacts/.datamodel-manifest.json'));
+ result = run(block, f);
+ assert.equal(result.status, 0, result.stderr);
+ assert.equal(result.stdout.trim(), `${slashPath(f.owner)}/docs/plan-artifacts/.datamodel-manifest.json`);
+ fs.unlinkSync(path.join(f.owner, 'docs/plan-artifacts/.datamodel-manifest.json'));
+ result = run(block, f);
+ assert.equal(result.status, 1);
+ assert.match(result.stderr, /NEEDS_CONTEXT: no manifest in working_dir/);
+ assert.equal(result.stdout, '');
+ assert.ok(fs.existsSync(path.join(f.caller, '.datamodel-manifest.json')));
+});
+
+test('offline setup forwards its resolved root and exact approved prerequisites to the internal helper', () => {
+ const setup = read('skills/setup-offline-profile/SKILL.md');
+ const binding = section(setup, '## App-root binding', '## Workflow');
+ assert.ok(binding.includes(rootLink));
+ assert.ok(setup.indexOf(rootLink) < setup.indexOf('```bash'));
+ assert.match(binding, /inherit a child invocation's owner root/);
+ assert.match(binding, /file tools use absolute `<working_dir>\/\.\.\.` paths/);
+ assert.match(binding, /prior shell variables do not persist/);
+ assert.match(binding, /planning-phase caller returns[\s\S]*before entering this mutating wizard/);
+ for (const block of shellBlocks(setup)) assert.ok(block.startsWith(`${guard}\n`), block);
+ const handoff = section(setup, '### Step 4', '### Step 5');
+ for (const field of [
+ "--working-dir '<working_dir>'", 'MOBILE_APP_ORCHESTRATING=1',
+ 'orchestrator: setup-offline-profile', 'working_dir: <working_dir>',
+ 'phase: implementation', 'approved_scope:', 'environmentId:', 'environmentUrl:',
+ 'tenantId:', 'tables:', 'operations:', 'publication:', 'supplied_answers:',
+ ]) assert.ok(handoff.includes(field), field);
+ assert.match(handoff, /exact Gate 1-approved prerequisite table allowlist/);
+ assert.match(handoff, /Configuration review must already\s+be accepted/);
+ assert.match(handoff, /literal first-line status/);
+ const creation = read('skills/create-mobile-app/SKILL.md');
+ const caller = section(creation, 'If the user selects Yes, invoke `/setup-offline-profile`', 'Tables and generated services now exist');
+ assert.match(caller, /--working-dir '<working_dir>'/);
+ assert.match(caller, /orchestrator: create-mobile-app/);
+ assert.match(caller, /not its prerequisite or\s+profile mutations/);
+});
+
+test('offline architect reads only the supplied app and tenant and cannot borrow another root', (t) => {
+ const f = fixture(t);
+ const text = read('agents/offline-profile-architect.md');
+ const binding = section(text, '## Invocation context and root binding', '## Hard Rules');
+ assert.ok(binding.includes(rootLink));
+ assert.match(binding, /owner's absolute `working_dir` and complete environment ID\/URL\/tenant/);
+ assert.match(binding, /Never use the launch cwd or ambient tenant/);
+ assert.doesNotMatch(text, /<workdir>/);
+ assert.match(text, /Write `<working_dir>\/_offline_section\.md` in the approved app root/);
+ const blocks = shellBlocks(text);
+ assert.equal(blocks.length, 5);
+ for (const block of blocks) {
+ assert.ok(block.startsWith(`${guard}\n`));
+ const result = run(block, f);
+ assert.equal(result.status, 0, `${block}\n${result.stderr}`);
+ const before = calls(f);
+ const failed = run(block, f, path.join(f.directory, 'missing owner'));
+ assert.equal(failed.status, 1);
+ assert.deepEqual(calls(f), before);
+ }
+ const requests = calls(f).filter((call) => call.args[0].endsWith('/dataverse-request.js'));
+ assert.equal(requests.length, 4);
+ for (const call of requests) {
+ assert.equal(fs.realpathSync.native(call.cwd), fs.realpathSync.native(f.owner));
+ assert.equal(call.args[1], context.environmentUrl);
+ assert.equal(call.args[2], 'GET');
+ assert.equal(call.args[call.args.indexOf('--tenant-id') + 1], context.tenantId);
+ }
+ const before = calls(f).length;
+ fs.writeFileSync(path.join(f.owner, 'power.config.json'), '{"environmentId":"wrong-environment"}');
+ const conflict = run(blocks[0], f);
+ assert.equal(conflict.status, 1);
+ assert.match(conflict.stderr, /NEEDS_CONTEXT: selected environment does not match working_dir/);
+ assert.ok(calls(f).slice(before).every((call) => call.args[0] === '-p'));
+ const caller = section(read('skills/setup-offline-profile/SKILL.md'), 'agent: mobile-app:offline-profile-architect', '### Step 3.5');
+ for (const field of ['Working directory: <working_dir>', 'Environment ID:', 'Environment URL:', 'Tenant ID:',
+ 'Manifest path:', 'Phase: planning', 'Proposal output: <working_dir>/_offline_section.md']) {
+ assert.ok(caller.includes(field), field);
+ }
+});
+
+test('offline setup resolves identity only inside its selected app before handing off', (t) => {
+ const f = fixture(t);
+ const setup = read('skills/setup-offline-profile/SKILL.md');
+ const block = shellBlocks(setup)[0];
+ const result = run(block, f);
+ assert.equal(result.status, 0, result.stderr);
+ const recorded = calls(f);
+ assert.equal(recorded.length, 2);
+ assert.ok(recorded.every((call) => fs.realpathSync.native(call.cwd) === fs.realpathSync.native(f.owner)));
+ assert.deepEqual(recorded[1].args.slice(1), [context.environmentId, '--no-cache', '--require-tenant']);
+ const before = calls(f);
+ const failed = run(block, f, path.join(f.directory, 'missing owner'));
+ assert.equal(failed.status, 1);
+ assert.deepEqual(calls(f), before);
+ assert.match(failed.stderr, /BLOCKED: cannot enter working_dir/);
+});
+
+test('all shared offline recipes retain owner root and tenant through fresh calls and missing-root failures', (t) => {
+ const f = fixture(t);
+ const blocks = shellBlocks(read('shared/references/dataverse-offline-api.md'));
+ assert.ok(blocks.length >= 18);
+ for (const block of blocks) {
+ assert.ok(block.startsWith(`${guard}\n`));
+ const result = run(block, f);
+ assert.equal(result.status, 0, `${block}\n${result.stderr}`);
+ const before = calls(f);
+ const failed = run(block, f, path.join(f.directory, 'missing owner'));
+ assert.equal(failed.status, 1);
+ assert.match(failed.stderr, /BLOCKED: cannot enter working_dir/);
+ assert.deepEqual(calls(f), before);
+ }
+ const recorded = calls(f);
+ assert.equal(recorded.length, 21);
+ for (const call of recorded) {
+ assert.equal(fs.realpathSync.native(call.cwd), fs.realpathSync.native(f.owner));
+ assert.equal(call.args[1], context.environmentUrl);
+ assert.equal(call.args[call.args.indexOf('--tenant-id') + 1], context.tenantId);
+ }
+});
+
+test('indented timeout recovery uses the same approved root profile and tenant', (t) => {
+ const f = fixture(t);
+ const setup = read('skills/setup-offline-profile/SKILL.md');
+ const recovery = section(setup, 'Protocol after the POST call returns:', '### Step 9');
+ const blocks = shellBlocks(recovery);
+ assert.equal(blocks.length, 1);
+ assert.ok(blocks[0].startsWith(`${guard}\n`));
+ const result = run(blocks[0], f);
+ assert.equal(result.status, 0, result.stderr);
+ const recorded = calls(f);
+ assert.equal(recorded.length, 1);
+ assert.equal(fs.realpathSync.native(recorded[0].cwd), fs.realpathSync.native(f.owner));
+ assert.equal(recorded[0].args[1], context.environmentUrl);
+ assert.equal(recorded[0].args[3],
+ `mobileofflineprofiles(${context.profileId})?$select=componentstate,publishedon`);
+ assert.equal(recorded[0].args[recorded[0].args.indexOf('--tenant-id') + 1], context.tenantId);
+});
+
+test('offline verification and recipe callers carry explicit root and tenant on every request', () => {
+ for (const file of [
+ 'skills/setup-offline-profile/SKILL.md',
+ 'skills/assign-offline-profile/SKILL.md',
+ 'skills/preview-offline-scope/SKILL.md',
+ 'shared/references/dataverse-offline-api.md',
+ ]) {
+ for (const block of shellBlocks(read(file))) {
+ assert.ok(block.startsWith(`${guard}\n`), `${file}:\n${block}`);
+ const commands = block.replace(/\\\n/g, ' ').split('\n').filter((line) =>
+ /^node "\$\{PLUGIN_ROOT\}\/scripts\/(?:dataverse-request|verify-offline-profile|update-entity-offline-flags)\.js"/.test(line));
+ for (const command of commands) assert.ok(command.includes('--tenant-id "<tenantId>"'), command);
+ if (block.includes('/verify-offline-profile.js')) {
+ assert.ok(block.includes("--project-root '<working_dir>'"));
+ }
+ }
+ }
+ const reference = read('shared/references/dataverse-offline-api.md');
+ assert.match(reference, /requires separate explicit approval/);
+ assert.match(reference, /owner separately approves publishing/);
+ assert.doesNotMatch(reference, /A single bulk publish at the end is correct/);
+ assert.match(read('skills/setup-offline-profile/SKILL.md'),
+ /user separately approves publishing all pending environment customizations/);
+});
+
+test('offline enablement cannot widen the owner table list or repeat approval in planning mode', () => {
+ const enable = documents['enable-tables-offline'];
+ const tables = section(enable, '### Step 2', '### Step 3');
+ assert.match(tables, /only the exact table allowlist in the owner's `approved_scope`/);
+ assert.match(tables, /not permission to enable every\s+row/);
+ assert.match(tables, /Missing or conflicting table selection returns\s+`NEEDS_CONTEXT`/);
+ const gate = section(enable, '### Gate', '### Step 4');
+ assert.match(gate, /Gate 1 approval is reused without a duplicate\s+prompt/);
+ assert.match(gate, /owner[\s\S]*owns the approval gate/);
+ assert.match(gate, /Do not widen\s+scope or override proposal-only mode/);
+ assert.match(enable, /owner separately approves the broader publication/);
+ assert.match(enable, /Table-only approval does not authorize publishing unrelated changes/);
+ assert.match(enable, /literal first line/);
+});
+
+test('root reception preserves offline gates, exact deltas, permissions, and schema baselines', () => {
+ const add = documents['add-table-to-offline-profile'];
+ const edit = documents['edit-offline-profile'];
+ const prereqs = section(add, '### Step 3', '### Step 4');
+ assert.match(prereqs, /current offline approval covers these exact prerequisite changes/);
+ assert.match(prereqs, /obtain owner\/user approval first/);
+ assert.match(prereqs, /IsCustomizable.Value = false[\s\S]*BLOCKED/);
+ assert.match(prereqs, /"PublishXml" --tenant-id "<tenantId>"/);
+ assert.match(prereqs, /<entities><entity><table><\/entity><\/entities>/);
+ assert.doesNotMatch(shellBlocks(prereqs).join('\n'), /"PublishAllXml"/);
+ assert.match(prereqs, /owner separately approves publishing all pending/);
+ assert.match(add, /Cancel stops without[\s\S]*creating a profile item/);
+ assert.match(add, /--all-new[\s\S]*only within the owner's exact table allowlist/);
+ assert.match(add, /Steps 3–7 for[\s\S]*each approved missing table/);
+ assert.doesNotMatch(add, /no prompt — the user already opted|skills\/enable-tables-offline/);
+ const editGate = section(edit, '### Step 3', '### Step 4');
+ assert.match(editGate, /Apply this change\? \[Apply \/ Cancel\]/);
+ assert.match(editGate, /If `Cancel` → STOP/);
+ assert.match(edit, /Preserve every field and table outside the approved delta/);
+ assert.match(edit, /leave `schemaColumns`[\s\S]*untouched for scope\/sync\/rename-only edits/);
+ assert.match(add, /entry MUST include a `schemaColumns` array/);
+ for (const text of [add, edit]) {
+ assert.match(text, /403\/`PrivilegeCheckFailed`[\s\S]*`BLOCKED`/);
+ assert.match(text, /do not change identity or profile to[\s\S]*bypass permissions/);
+ assert.match(text, /broader publication/);
+ assert.match(text, /profile-scoped approval/);
+ assert.match(text, /schema approval alone does not authorize/);
+ assert.match(text, /selected environment/);
+ assert.match(text, /snapshot\/argument/);
+ }
+});
diff --git a/plugins/mobile-apps/scripts/tests/offline-profile-delta.test.js b/plugins/mobile-apps/scripts/tests/offline-profile-delta.test.js
index 50304824c..d5e8ec1dc 100644
--- a/plugins/mobile-apps/scripts/tests/offline-profile-delta.test.js
+++ b/plugins/mobile-apps/scripts/tests/offline-profile-delta.test.js
@@ -57,6 +57,26 @@ test('in-sync when every manifest table is covered and no new columns', () => {
assert.strictEqual(delta.summary.newColumnCount, 0);
});
+test('addition-only in-sync does not prove that retired profile tables were removed', () => {
+ const profile = {
+ tables: [
+ { logicalName: 'contoso_customer', schemaColumns: ['contoso_name'] },
+ { logicalName: 'contoso_order', schemaColumns: ['contoso_total'] },
+ ],
+ };
+ const original = JSON.stringify(profile);
+ for (const tables of [
+ [{ logicalName: 'contoso_customer', columns: ['contoso_name'] }],
+ [],
+ ]) {
+ const delta = computeOfflineProfileDelta({ tables }, profile);
+ assert.strictEqual(delta.status, 'in-sync');
+ assert.deepStrictEqual(delta.missingTables, []);
+ assert.deepStrictEqual(delta.tablesWithNewColumns, []);
+ assert.strictEqual(JSON.stringify(profile), original);
+ }
+});
+
test('flags a table present in the manifest but missing from the profile', () => {
const manifest = {
tables: [
diff --git a/plugins/mobile-apps/scripts/tests/scoped-dataverse-planning-contract.test.js b/plugins/mobile-apps/scripts/tests/scoped-dataverse-planning-contract.test.js
new file mode 100644
index 000000000..80ad0963c
--- /dev/null
+++ b/plugins/mobile-apps/scripts/tests/scoped-dataverse-planning-contract.test.js
@@ -0,0 +1,320 @@
+'use strict';
+
+const assert = require('node:assert/strict');
+const { spawnSync } = require('node:child_process');
+const { randomUUID } = require('node:crypto');
+const fs = require('node:fs');
+const path = require('node:path');
+const test = require('node:test');
+const { cacheMatchesTarget, canUseCachedResolution, parseArgs } = require('../resolve-environment');
+
+const pluginRoot = path.resolve(__dirname, '../..');
+const read = (file) => fs.readFileSync(path.join(pluginRoot, file), 'utf8').replace(/\r\n?/g, '\n');
+const skill = (name) => read(`skills/${name}/SKILL.md`);
+const planningPath = 'shared/references/dataverse-change-planning.md';
+const planning = read(planningPath);
+const setup = skill('setup-datamodel');
+const dataverse = skill('add-dataverse');
+const create = skill('create-mobile-app');
+
+function section(text, start, end) {
+ const from = text.indexOf(start);
+ const to = text.indexOf(end, from + start.length);
+ assert.ok(from >= 0, `Missing section: ${start}`);
+ assert.ok(to > from, `Missing section end: ${end}`);
+ return text.slice(from, to);
+}
+
+function inOrder(text, ...markers) {
+ let previous = -1;
+ for (const marker of markers) {
+ const index = text.indexOf(marker);
+ assert.ok(index > previous, `Missing or out-of-order instruction: ${marker}`);
+ previous = index;
+ }
+}
+
+function resolverFlags(text) {
+ const command = text.match(/^node "\$\{PLUGIN_ROOT\}\/scripts\/resolve-environment\.js" "<selected-environment-id>" ([^\n]+)$/m);
+ assert.ok(command, 'Scoped planning must document an executable selected-environment resolver command');
+ return command[1].trim().split(/\s+/);
+}
+
+for (const [name, ending] of [['LF', '\n'], ['CRLF', '\r\n']]) {
+ test(`scoped planning command and section boundaries survive ${name}`, (t) => {
+ t.mock.method(fs, 'readFileSync', (file, encoding) => {
+ assert.equal(file, path.join(pluginRoot, planningPath));
+ assert.equal(encoding, 'utf8');
+ return planning.replace(/\n/g, ending);
+ });
+ const content = read(planningPath);
+ assert.equal(content, planning);
+ assert.deepEqual(resolverFlags(section(content, '## 1.', '## 2.')), ['--no-cache', '--require-tenant']);
+ inOrder(content, '## 1.', '## 2.', '## 3.', '## 4.', '## 5.');
+ });
+}
+
+test('the documented planning resolver leaves cached app identity files byte-for-byte unchanged', (t) => {
+ const root = path.join(__dirname, `.scoped-dataverse-fixture-${randomUUID()}`);
+ fs.mkdirSync(root);
+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));
+ const configDir = path.join(root, 'telemetry-config');
+ fs.mkdirSync(configDir);
+ const cached = {
+ environmentId: '11111111-1111-4111-8111-111111111111',
+ environmentUrl: 'https://contoso.crm.dynamics.com',
+ tenantId: '22222222-2222-4222-8222-222222222222',
+ displayName: 'Planning fixture',
+ clusterEnvironment: 'Prod',
+ clusterGeoName: 'EU',
+ };
+ const fixtures = {
+ 'power.config.json': { environmentId: cached.environmentId },
+ 'auth.config.json': { msal: { clientId: 'preserve-client', tenantId: 'preserve-tenant' }, environment: cached },
+ '.resolved-environment.json': { ...cached, cachedAt: '2026-01-01T00:00:00.000Z' },
+ 'app.json': { expo: { name: 'Planning fixture', extra: { telemetry: { appInstanceId: 'preserve-instance', cluster: null } } } },
+ };
+ const before = new Map();
+ for (const [name, value] of Object.entries(fixtures)) {
+ const file = path.join(root, name);
+ fs.writeFileSync(file, `${JSON.stringify(value, null, 2)}\n`);
+ before.set(file, fs.readFileSync(file));
+ }
+
+ assert.equal(cacheMatchesTarget(cached, cached.environmentId), true);
+ assert.equal(canUseCachedResolution(cached, cached.environmentId), true);
+ const args = [cached.environmentId, ...resolverFlags(planning)];
+ assert.deepEqual(parseArgs(args), { noCache: true, target: cached.environmentId, requireTenant: true });
+ // Complete matching cache + no az executable keeps this real CLI invocation offline.
+ // Null cluster would be persisted by normal resolution, so byte equality checks routing too.
+ const result = spawnSync(process.execPath, [path.join(pluginRoot, 'scripts/resolve-environment.js'), ...args], {
+ cwd: root,
+ encoding: 'utf8',
+ timeout: 5000,
+ env: {
+ ...process.env,
+ PATH: '',
+ POWER_PLATFORM_SKILLS_CONFIG_DIR: configDir,
+ POWER_PLATFORM_SKILLS_TELEMETRY_MOBILE_APP_OPTOUT: '1',
+ },
+ });
+ assert.equal(result.error, undefined);
+ assert.equal(result.status, 0, result.stderr);
+ assert.equal(result.stderr, '');
+ assert.deepEqual(JSON.parse(result.stdout), { ...cached, source: 'cache' });
+ for (const [file, bytes] of before) assert.deepEqual(fs.readFileSync(file), bytes, path.basename(file));
+ assert.deepEqual(fs.readdirSync(root).sort(), [...Object.keys(fixtures), 'telemetry-config'].sort());
+ assert.deepEqual(fs.readdirSync(configDir), []);
+});
+
+test('scope and selected environment are established before compact discovery', () => {
+ const scope = section(planning, '## 1.', '## 2.');
+ inOrder(scope, 'one absolute `working_dir`', 'only the proposed delta', 'resolve-environment.js', 'On conflict');
+ assert.match(scope, /existing dependencies as `reuse`, not\s+`create`\/`extend`/);
+ assert.match(scope, /do not copy historical creation rows from the full plan/);
+ assert.match(scope, /Preserve unrelated services outside this contract/);
+ assert.match(scope, /missing dependency[\s\S]*additional mutations goes into the proposal for approval/);
+ assert.match(scope, /Connector-only,[\s\S]*removal-only, and retained-service-only\n\s+refresh requests skip/);
+ assert.match(scope, /do not create empty Dataverse artifacts or require a data-model receipt/);
+ assert.match(scope, /environment ID, HTTPS URL, and tenant to match/);
+ assert.match(scope, /`NEEDS_CONTEXT` to the owner before discovery/);
+ assert.match(scope, /never select another environment\nsilently/);
+ assert.match(scope, /Planning must\nnot change auth\/app configuration[\s\S]*live plan before its owning approval/);
+});
+
+test('scoped planning adapts only the named create helper sections, not its wizard or gates', () => {
+ const evidence = section(planning, '## 2.', '## 3.');
+ assert.match(planning, /does not invoke `\/create-mobile-app` or add another approval gate/);
+ assert.match(evidence, /Read and execute only\n\[Foreground Dataverse planning snapshot and evidence\]\(\.\.\/\.\.\/skills\/create-mobile-app\/SKILL\.md#foreground-dataverse-planning-snapshot-and-evidence\)/);
+ assert.match(evidence, /ending before \*\*Planner completion dispatch\*\*/);
+ assert.match(evidence, /not permission to run the create wizard, its planner, scaffolding, or gates/);
+ assert.match(planning, /\[Dataverse planning recovery\]\(\.\.\/\.\.\/skills\/create-mobile-app\/SKILL\.md#dataverse-planning-recovery\)/);
+ assert.match(evidence, /`<dataverse_planning_mode>` \| `required` only for this Dataverse delta/);
+ assert.match(evidence, /Exact existing targets and necessary dependencies, not every table used anywhere/);
+ assert.match(evidence, /Every proposed final custom logical name, including adapted names/);
+ assert.match(evidence, /production read concurrency\n`1`/);
+ assert.match(evidence, /valid cache is planning evidence only, never write authorization/);
+ assert.match(evidence, /Never dispatch on failed\/stale output/);
+ assert.match(evidence, /Agents read only the\ncompact sidecar; the full snapshot is an opaque validator input/);
+ const helper = section(create, '### Foreground Dataverse planning snapshot and evidence', '#### Planner completion dispatch');
+ inOrder(helper, 'resolve-environment.js', 'create-dataverse-snapshot.js', 'render-dataverse-architect-evidence.js', '--validate-only');
+ assert.match(helper, /--read-concurrency 1/);
+ assert.doesNotMatch(helper, /Task: mobile-app:native-app-planner|Invoke skill: \/create-mobile-app/);
+ assert.doesNotMatch(planning, /^(?:Invoke skill: \/create-mobile-app|Task: mobile-app:native-app-planner|.*--approval-receipt )/m);
+});
+
+test('all scoped proposal sources share required snapshot-only architect inputs and outputs', () => {
+ const proposal = section(planning, '## 3.', '## 4.');
+ inOrder(proposal, 'Task: mobile-app:data-model-architect', 'phase: planning', 'Dataverse planning mode: required', 'Structured schema contract output:');
+ for (const field of [
+ 'working_dir: <absolute owner root>',
+ 'proposal_only: <true for --plan-only or a planning-phase caller>',
+ 'Normalized Dataverse foreground planning snapshot (validator input only): <SNAPSHOT_PATH>',
+ 'Compact Dataverse architect evidence: <ARCHITECT_EVIDENCE_PATH>',
+ 'Output proposal: <working_dir>/_dm_section.md',
+ ]) assert.ok(proposal.includes(field), field);
+ assert.match(proposal, /do not save the live plan,\n\s+grant approval, run live discovery, or apply changes/);
+ assert.match(proposal, /diagram, parsed text, existing-plan delta, or unavailable-agent inline\nfallback, produce the same two outputs/);
+ assert.match(proposal, /Never use local models or Mermaid alone as\nproof/);
+ assert.match(proposal, /do not replace its unaffected sections with the scoped contract/);
+
+ const setupPlanner = section(setup, '#### Path B', '#### Path C');
+ assert.match(setupPlanner, /Dataverse planning mode: required/);
+ assert.match(setupPlanner, /snapshot \(validator input only\): <SNAPSHOT_PATH>/);
+ assert.match(setupPlanner, /Compact Dataverse architect evidence: <ARCHITECT_EVIDENCE_PATH>/);
+ assert.match(setupPlanner, /Structured schema contract output: <working_dir>\/\.tmp\/dataverse-schema-contract\.json/);
+ assert.doesNotMatch(setupPlanner, /Dataverse planning mode: (?:default|optional|legacy)/);
+ assert.match(section(setup, '#### Path A', '#### Path B'), /same decision validation as Path B before[\s\S]*Phase 4 approval/);
+ assert.match(section(dataverse, '### Step 2.5', '### Step 2.6'), /decision validation for the diagram just as for\nan architect result/);
+ assert.match(section(dataverse, '### Step 2.6', '### Step 2.7'), /If the host cannot spawn agents, produce both inline from that same evidence/);
+});
+
+test('the architect fails closed in required mode and preserves non-persisting legacy planning', () => {
+ const architect = read('agents/data-model-architect.md');
+ const snapshotOnly = section(architect, '## Snapshot-only', '## Step 1');
+ inOrder(snapshotOnly, 'render-dataverse-architect-evidence.js', '--validate-only', 'Read the compact architect evidence once');
+ assert.match(snapshotOnly, /Skip Steps 1–3[\s\S]*Skip every live Dataverse query in Step 5/);
+ assert.match(snapshotOnly, /Do \*\*not\*\* run Bash discovery or call `resolve-environment\.js`/);
+ assert.match(snapshotOnly, /`NEEDS_CONTEXT: matching-dataverse-snapshot-and-evidence`/);
+ assert.match(snapshotOnly, /Do not fall back to\nlive discovery from `required` mode/);
+ assert.match(snapshotOnly, /Setup\/standalone data planning must not omit `required`/);
+ assert.match(snapshotOnly, /legacy live path below remains only\nfor callers that omit the new planning mode entirely/);
+ const legacy = section(architect, '## Step 1', '## Step 2');
+ assert.match(legacy, /Legacy live path only\. Skip entirely in the validated snapshot-only path/);
+ assert.match(legacy, /^node "\$\{PLUGIN_ROOT\}\/scripts\/resolve-environment\.js" <environment-id-or-url> --no-cache --require-tenant$/m);
+ assert.match(legacy, /do not remove these flags or\nredirect output into app\/auth configuration/);
+});
+
+test('normalization and decision validation precede approval, including successful agent returns', () => {
+ const validation = section(planning, '## 4.', '## 5.');
+ inOrder(validation,
+ 'build-dataverse-operation-manifest.js',
+ '--normalize-contract',
+ 'Only if normalization succeeds',
+ 'validate-dataverse-planning-decisions.js',
+ 'Only exit `0` permits presenting an executable proposal',
+ 'Handle structured signals before generic agent retry limits');
+ assert.match(validation, /`DONE` \/ `DONE_WITH_CONCERNS` from an agent is not a validation result/);
+ assert.match(validation, /section and contract describe the same delta[\s\S]*neither exceeds\nthe requested scope/);
+ assert.match(validation, /deferred required dependency cannot be described as complete/);
+ assert.doesNotMatch(validation, /--approval-receipt|EnterPlanMode|ExitPlanMode|Invoke skill: \/add-dataverse/);
+ const directGate = section(dataverse, '### Step 2.7', '### Step 3');
+ inOrder(directGate, 'require exit `0`', 'validate-dataverse-planning-decisions.js', 'STOP before saving', 'EnterPlanMode', 'saves only that delta', 'verify\nit using Step 2b');
+ assert.match(directGate, /diagrams, architect results, inline fallbacks, and edits to an existing plan/);
+ assert.match(directGate, /Already-approved scoped child\ncalls and valid creation fast-path calls do not repeat this gate/);
+});
+
+test('structured metadata expansion and deterministic revision precede generic retries without new gates', () => {
+ const recovery = section(planning, 'Handle structured signals', '## 5.');
+ assert.match(recovery, /before generic agent retry limits/);
+ assert.match(recovery, /Exit `3`, `NEEDS_CONTEXT: detailed-dataverse-metadata:<names>`[^\n]*only names not already fully attempted[^\n]*regenerate\/validate compact evidence/);
+ assert.match(recovery, /Exit `3`, `NEEDS_CONTEXT: proposed-dataverse-names:<names>`[^\n]*collision-only[^\n]*never reinterpret it as detail discovery/);
+ assert.match(recovery, /Exit `4`, `NEEDS_REVISION: dataverse-plan-validation`[^\n]*same evidence[^\n]*no metadata read or user question/);
+ assert.match(recovery, /`NEEDS_CONTEXT: dataverse-plan-revision:<classification>`[^\n]*inline revision fallback, not a generic context retry/);
+ assert.match(recovery, /Exit `2`[^\n]*no approval, mutation, stale-output fallback, or downgrade to success/);
+ assert.match(recovery, /`DETAIL_ATTEMPTED_NAMES` and `PROPOSED_CHECKED_NAMES` are separate\nmonotonic sets/);
+ assert.match(recovery, /`core` detail remains eligible for full-detail expansion/);
+ assert.match(recovery, /already-unavailable names are not fetched repeatedly/);
+ assert.match(recovery, /On no progress,\nrevise inline using current evidence/);
+ assert.match(recovery, /Never import creation's Gate 1\/2 prompts/);
+ const canonical = section(create, '#### Dataverse planning recovery', '#### Step 3.0a');
+ assert.match(canonical, /NEW_DETAIL_NAMES = requested names - DETAIL_ATTEMPTED_NAMES/);
+ assert.match(canonical, /NEW_PROPOSED_NAMES = requested names - PROPOSED_CHECKED_NAMES/);
+ assert.match(canonical, /If it is empty, do not issue another network request/);
+ for (const owner of [
+ section(setup, '#### Path B', '#### Path C'),
+ section(dataverse, '### Step 2.6', '### Step 2.7'),
+ ]) assert.match(owner, /(?:shared planning recovery before|recovery before generic retry limits|shared structured-signal recovery before generic retries)/);
+});
+
+test('accepted data scopes bind evidence and exact hashes without create-only artifact flags', () => {
+ const accepted = planning.slice(planning.indexOf('## 5.'));
+ inOrder(accepted, 'existing gate approves implementation', 'save only the accepted plan', '`contract_sha256`', '`plan_sha256`', 'Before execution');
+ assert.match(accepted, /exact accepted operations\/dependencies/);
+ assert.match(accepted, /SHA-256 of the\nnormalized contract file bytes/);
+ assert.match(accepted, /never recalculate these approval hashes after discovering a mismatch/);
+ assert.match(accepted, /not a new\nreceipt format/);
+ assert.match(accepted, /receipt requires `workflow: create-mobile-app`\nand four approvals/);
+ assert.match(accepted, /Do not fabricate those approvals[\s\S]*weaken\nreceipt validation, or pass a partially populated fast-path argument set/);
+ const handoff = section(setup, 'Invoke skill: /add-dataverse', '\n```');
+ assert.match(handoff, /orchestrator: setup-datamodel/);
+ assert.match(handoff, /phase: implementation/);
+ assert.match(handoff, /planning_snapshot: <SNAPSHOT_PATH>/);
+ assert.match(handoff, /architect_evidence: <ARCHITECT_EVIDENCE_PATH>/);
+ assert.match(handoff, /schema_contract: <working_dir>\/\.tmp\/dataverse-schema-contract\.json/);
+ assert.match(handoff, /approved_scope: <[^\n]*delta[^\n]*contract_sha256, plan_sha256>/);
+ assert.match(handoff, /--skip-planning/);
+ assert.doesNotMatch(handoff, /--(?:schema-contract|approval-receipt|execution-reconciliation|operation-manifest|publish-checkpoint)\b/);
+});
+
+test('Step 2b verifies approval before fresh bounded reconciliation, not whole-plan replay', () => {
+ const entry = section(dataverse, 'For all non-fast-path Dataverse proposals', '#### Step 2a');
+ assert.match(entry, /approved child[\s\S]*enters Step 2b[\s\S]*must\nnot rediscover or re-approve it/);
+ assert.match(entry, /normalized contract's non-deferred\n`serviceRequired` declarations/);
+ assert.match(entry, /broader existing-app service\ninventory as retained context, not a registration or mutation work list/);
+ const binding = section(dataverse, '#### Step 2b', '### Step 2.5');
+ assert.match(binding, /Enter only for a shared compact-planning handoff, not an approved legacy child/);
+ inOrder(binding, 'Require all fields and real implementation approval', 'Before Step 3', 'compare SHA-256', 'verify the selected target identity', 'decision validators', 'After success', 'proceed to\nStep 3');
+ assert.match(binding, /partial, missing, changed, or mismatched context returns `NEEDS_CONTEXT`/);
+ assert.match(binding, /never a fallback to whole-plan replay or fresh approval inference/);
+ assert.match(binding, /Do not overwrite either hash to accept changed files/);
+ assert.match(binding, /normalized scoped contract, not historical Markdown rows/);
+ assert.match(binding, /proposal-only caller returns without mutation/);
+ assert.match(binding, /`<operation_manifest_mode> = fallback`/);
+ assert.match(binding, /skip Steps 2.5–2.7/);
+ const live = section(dataverse, '### Step 4 — Reconcile', '#### Step 4a');
+ inOrder(dataverse, '#### Step 2b', '### Step 3 —', '### Step 4 —', '### Step 5 —');
+ inOrder(live, 'only the approved\nnormalized contract', 'Do not substitute the planning snapshot or inventory cache', 'scripts/dataverse-request.js');
+ assert.match(live, /never all saved-plan rows/);
+ assert.match(live, /still unreadable after that is `unverified`: STOP before writes/);
+ assert.match(planning, /must not reconstruct mutation\nscope from all rows in the saved Markdown plan/);
+ assert.match(planning, /missing\/out-of-scope binding returns\nto the owner/);
+});
+
+test('legacy child handoffs require current approval and cannot bypass invalid compact artifacts', () => {
+ const legacy = section(dataverse, 'Older callers,', 'For the shared scoped path');
+ assert.match(legacy, /Do not assume compact evidence or complete approval from the caller's\nname/);
+ assert.match(legacy, /Without a complete approved handoff, resolve the current requested delta\nand use this leaf's normal proposal and Step 2\.7 approval path before execution/);
+ assert.match(legacy, /missing or conflicting child root\nstill returns `NEEDS_CONTEXT` before project access/);
+ assert.match(legacy, /Never silently replay the\nsaved plan or treat `--skip-planning` as consent/);
+ assert.match(legacy, /An approved legacy child without compact-planning artifacts keeps the supported\nMarkdown\/live-reconciliation path/);
+ assert.match(legacy, /current request, absolute\nroot, implementation phase, and exact approved delta are all established/);
+ assert.match(legacy, /Never use this legacy path to bypass a partial or invalid compact-planning\nhandoff, or to skip setup\/standalone proposal validation/);
+ assert.match(legacy, /Only the current approved\ndelta and its necessary dependencies enter live schema reconciliation/);
+ assert.match(legacy, /complete approved legacy handoff, proceed to Step 3 after this initialization/);
+ assert.match(legacy, /do not repeat proposal Steps 2\.5–2\.7 or require new compact artifacts/);
+ assert.match(legacy, /A planning-phase caller still returns without implementation/);
+});
+
+test('creation retains its complete receipt-owned fast path and fails closed on partial artifacts', () => {
+ const flags = ['schema-contract', 'approval-receipt', 'execution-reconciliation', 'operation-manifest', 'publish-checkpoint'];
+ const handoff = section(create, 'Invoke skill: /add-dataverse', '\n```');
+ const fast = section(dataverse, '#### Step 2a', '#### Step 2b');
+ assert.match(handoff, /orchestrator: create-mobile-app/);
+ for (const flag of flags) {
+ assert.match(handoff, new RegExp(`--${flag} <working_dir>/\\.tmp/`));
+ assert.match(fast, new RegExp(`--${flag} <working_dir>/\\.tmp/`));
+ }
+ assert.match(fast, /supplies all five paths/);
+ assert.match(fast, /entirely absent fast-path handoff[\s\S]*fallback/);
+ assert.match(fast, /partially supplied handoff[\s\S]*must fail closed/);
+ assert.match(fast, /Never jump to\nStep 4 without Step 2 initialization/);
+ assert.match(fast, /Do not reconstruct tables[\s\S]*from Markdown on this path/);
+ assert.match(fast, /Supplied execution\nartifacts never override `--plan-only` or a planning-phase caller/);
+ assert.match(fast, /return the proposal without entering Step 3/);
+ assert.match(section(create, '### Step 8 — Apply', 'Invoke skill: /add-dataverse'), /Step 8 cannot create or refresh this receipt/);
+});
+
+test('both publish paths still require cache recovery before completion without replaying writes', () => {
+ const fastPublish = section(dataverse, 'After the `publish` phase succeeds', '#### Step 5a');
+ const standalonePublish = section(dataverse, '### Step 6b', '### Step 6c');
+ for (const publish of [fastPublish, standalonePublish]) {
+ inOrder(publish, 'publish', 'dataverse-inventory-cache.js', '--invalidate', 'NEEDS_RECOVERY: dataverse-inventory-cache', 'exit 2');
+ }
+ assert.match(fastPublish, /at most two targeted retries\nof the invalidation command/);
+ assert.match(fastPublish, /do not replay metadata writes or publish to repair a local cache failure/);
+ assert.match(fastPublish, /Do not reuse the failed cache or continue to service generation, verification,\nsample data, or offline setup until invalidation exits `0`/);
+ assert.match(standalonePublish, /same cache-invalidation recovery rule from the validated publish path/);
+ assert.match(planning, /Preserve pending offline-retirement outcomes independently of\naddition checks/);
+ assert.match(planning, /never authorizes profile deletion/);
+});
diff --git a/plugins/mobile-apps/scripts/tests/verify-dataverse-services.test.js b/plugins/mobile-apps/scripts/tests/verify-dataverse-services.test.js
index a9505ba56..7d244a1ff 100644
--- a/plugins/mobile-apps/scripts/tests/verify-dataverse-services.test.js
+++ b/plugins/mobile-apps/scripts/tests/verify-dataverse-services.test.js
@@ -25,6 +25,20 @@ function writeService(root, name) {
);
}
+test('documented service generation uses the resolved CLI and grouped Dataverse selectors', () => {
+ const skill = fs.readFileSync(
+ path.resolve(__dirname, '../../skills/add-dataverse/SKILL.md'), 'utf8',
+ ).replace(/\r\n?/g, '\n');
+ const step = skill.slice(
+ skill.indexOf('### Step 6 — Add data sources'),
+ skill.indexOf('### Step 6b'),
+ );
+ const commands = [...step.matchAll(/^\$PA app add data-source[^\n]*$/gm)];
+ assert.equal(commands.length, 1, 'Expected one executable service-generation command');
+ assert.equal(commands[0][0], '$PA app add data-source --connector dataverse --org-url <envUrl> --table <table-logical-name>');
+ assert.doesNotMatch(step, /^npx[^\n]*\b(?:pa|power-apps)\b/m);
+});
+
test('accepts literal default.cds and entity-set-derived service names', (testContext) => {
const root = project(testContext);
fs.writeFileSync(path.join(root, 'power.config.json'), JSON.stringify({
diff --git a/plugins/mobile-apps/scripts/update-entity-offline-flags.js b/plugins/mobile-apps/scripts/update-entity-offline-flags.js
index 8a3c178c8..84e0a060d 100644
--- a/plugins/mobile-apps/scripts/update-entity-offline-flags.js
+++ b/plugins/mobile-apps/scripts/update-entity-offline-flags.js
@@ -16,6 +16,7 @@
// --table <table_logical_name> \
// [--offline true|false] (default: true)
// [--tracking true|false] (default: true)
+// [--tenant-id <id>] (resolved environment tenant, including retries)
//
// Output (single-line JSON to stdout):
// No-op: { "status": 200, "table": "...", "noop": true, "before": {...} }
@@ -41,6 +42,7 @@ function parseArgs() {
table: null,
offline: true,
tracking: true,
+ tenantId: null,
};
for (let i = 1; i < argv.length; i++) {
@@ -50,6 +52,11 @@ function parseArgs() {
case '--table': out.table = next; i++; break;
case '--offline': out.offline = parseBool('--offline', next); i++; break;
case '--tracking': out.tracking = parseBool('--tracking', next); i++; break;
+ case '--tenant-id':
+ if (!next || !next.trim() || next.startsWith('--')) usage('--tenant-id requires a value');
+ out.tenantId = next.trim();
+ i++;
+ break;
default: usage(`Unknown flag: ${flag}`);
}
}
@@ -72,7 +79,7 @@ function usage(msg) {
process.stderr.write(`Error: ${msg}\n\n`);
process.stderr.write(
'Usage: node update-entity-offline-flags.js <envUrl> --table <name> ' +
- '[--offline true|false] [--tracking true|false]\n'
+ '[--offline true|false] [--tracking true|false] [--tenant-id <id>]\n'
);
process.exit(1);
}
@@ -137,9 +144,9 @@ async function putMetadata(envUrl, table, current, desired, token) {
}
async function main() {
- const { envUrl, table, offline, tracking } = parseArgs();
+ const { envUrl, table, offline, tracking, tenantId } = parseArgs();
- let token = await getAuthToken(envUrl);
+ let token = await getAuthToken(envUrl, tenantId);
if (!token) {
process.stderr.write('Failed to get Azure CLI token. Run `az login` first.\n');
process.exit(1);
@@ -187,7 +194,7 @@ async function main() {
}
if (res.statusCode === 401 && attempt < maxRetries) {
- token = await getAuthToken(envUrl);
+ token = await getAuthToken(envUrl, tenantId);
if (!token) {
console.log(JSON.stringify({ status: 401, table, error: 'token refresh failed' }));
process.exit(1);
diff --git a/plugins/mobile-apps/scripts/verify-dataverse-access.js b/plugins/mobile-apps/scripts/verify-dataverse-access.js
index 86b0e3f59..4ea8b741f 100644
--- a/plugins/mobile-apps/scripts/verify-dataverse-access.js
+++ b/plugins/mobile-apps/scripts/verify-dataverse-access.js
@@ -1,20 +1,33 @@
#!/usr/bin/env node
// Verifies Dataverse API access by obtaining an Azure CLI token and calling WhoAmI.
-// Usage: node verify-dataverse-access.js <environmentUrl>
+// Usage: node verify-dataverse-access.js <environmentUrl> [--tenant-id <id>]
// Outputs JSON: { "token": "...", "userId": "...", "organizationId": "...", "tenantId": "..." }
// Exit 0 on success, exit 1 on failure (error message on stderr).
const { getAuthToken, makeRequest } = require('./lib/validation-helpers');
+const { parseArgs } = require('node:util');
+const usage = 'Usage: node verify-dataverse-access.js <environmentUrl> [--tenant-id <id>]';
async function main() {
- const envUrl = process.argv[2];
- if (!envUrl) {
- process.stderr.write('Usage: node verify-dataverse-access.js <environmentUrl>\n');
+ let parsed;
+ try {
+ parsed = parseArgs({
+ options: { 'tenant-id': { type: 'string' } },
+ allowPositionals: true,
+ });
+ } catch (error) {
+ process.stderr.write(`${error.message}\n${usage}\n`);
+ process.exit(1);
+ }
+ const [envUrl] = parsed.positionals;
+ const explicitTenantId = parsed.values['tenant-id'] ?? null;
+ if (!envUrl || parsed.positionals.length !== 1 || (explicitTenantId !== null && !explicitTenantId.trim())) {
+ process.stderr.write(`${usage}\n`);
process.exit(1);
}
- const token = await getAuthToken(envUrl);
+ const token = await getAuthToken(envUrl, explicitTenantId);
if (!token) {
process.stderr.write('Failed to get Azure CLI token. Run `az login` first.\n');
process.exit(1);
diff --git a/plugins/mobile-apps/scripts/verify-offline-profile.js b/plugins/mobile-apps/scripts/verify-offline-profile.js
index b4c68bddc..0e761f430 100644
--- a/plugins/mobile-apps/scripts/verify-offline-profile.js
+++ b/plugins/mobile-apps/scripts/verify-offline-profile.js
@@ -11,10 +11,11 @@
// the user invokes /preview-offline-scope or /list-connections.
//
// Usage:
-// node verify-offline-profile.js <envUrl> [--project-root <path>]
+// node verify-offline-profile.js <envUrl> [--project-root <path>] [--tenant-id <id>]
//
// <envUrl> - Dataverse env URL (e.g. https://org123.crm.dynamics.com)
// --project-root - Path containing offline-profile.json. Default: cwd.
+// --tenant-id - Resolved environment tenant; no ambient fallback when supplied.
//
// Output (single-line JSON to stdout):
// { "status": "ok", "profileId": "...", "checks": [ ... ] }
@@ -39,14 +40,24 @@ function parseArgs() {
const out = {
envUrl: argv[0].replace(/\/+$/, ''),
projectRoot: process.cwd(),
+ tenantId: null,
};
for (let i = 1; i < argv.length; i++) {
const flag = argv[i];
const next = argv[i + 1];
switch (flag) {
- case '--project-root': out.projectRoot = next; i++; break;
- default: usage(`Unknown flag: ${flag}`);
+ case '--project-root':
+ if (!next || next.startsWith('--')) usage('--project-root requires a path');
+ out.projectRoot = next;
+ i++;
+ break;
+ case '--tenant-id':
+ if (!next || !next.trim() || next.startsWith('--')) usage('--tenant-id requires a value');
+ out.tenantId = next.trim();
+ i++;
+ break;
+ default: usage(`Unknown flag: ${flag}`);
}
}
@@ -55,7 +66,7 @@ function parseArgs() {
function usage(msg) {
process.stderr.write(`Error: ${msg}\n\n`);
- process.stderr.write('Usage: node verify-offline-profile.js <envUrl> [--project-root <path>]\n');
+ process.stderr.write('Usage: node verify-offline-profile.js <envUrl> [--project-root <path>] [--tenant-id <id>]\n');
process.exit(1);
}
@@ -78,7 +89,7 @@ async function dvGet(envUrl, apiPath, token) {
}
async function main() {
- const { envUrl, projectRoot } = parseArgs();
+ const { envUrl, projectRoot, tenantId } = parseArgs();
// Load snapshot
const snapshotPath = path.join(projectRoot, 'offline-profile.json');
@@ -101,7 +112,7 @@ async function main() {
process.exit(1);
}
- const token = await getAuthToken(envUrl);
+ const token = await getAuthToken(envUrl, tenantId);
if (!token) {
console.log(JSON.stringify({
status: 'error',
@@ -142,7 +153,7 @@ async function main() {
checks.push({
name: 'profile published',
ok: profile.publishedon != null,
- detail: profile.publishedon || 'publishedon is null — re-run PublishAllXml',
+ detail: profile.publishedon || 'publishedon is null — retry the approved targeted publication',
});
checks.push({
name: 'profile is in published state',
diff --git a/plugins/mobile-apps/shared/connector-reference.md b/plugins/mobile-apps/shared/connector-reference.md
index cc16ddb30..3baacd2eb 100644
--- a/plugins/mobile-apps/shared/connector-reference.md
+++ b/plugins/mobile-apps/shared/connector-reference.md
@@ -4,6 +4,11 @@ Applies to non-Dataverse connector skills such as `/add-connector` and `/add-sha
Does NOT apply to `/add-dataverse` — Dataverse uses the runtime's built-in executor and doesn't need a separate connection ID.
+Before app-local reads or commands, apply
+[app-working-directory.md](references/app-working-directory.md). Reuse the
+caller's resolved root for every shell call and file tool, including examples
+and retries below; do not derive a new root from the launch directory.
+
## Connection ID or reference (required)
All non-Dataverse connectors require either a **connection ID** (`--connection-id` / `-c`) or a **connection reference** (`--connection-ref`) when adding via `pa app add data-source`. Without one, the command fails with:
@@ -17,10 +22,29 @@ CONNECTION_ID argument is required for connector data sources
Use one of these supported paths:
- If the caller already has an existing connection ID, use it directly with `--connection-id`.
+- If the caller supplied a connection reference, preserve it with `--connection-ref`;
+ do not rediscover or create a replacement binding.
- If the app is solution-aware and the caller has a solution ID, run `pa connection list-references` and use the returned connection reference name with `--connection-ref`.
- Otherwise create a connection with `pa connection create` and use the returned `connectionId`.
+Resolve from explicit arguments and the approved handoff before calling a picker.
+If both binding forms are supplied without a clear approved choice, or the
+connector/environment does not match, return `NEEDS_CONTEXT` to the owner (ask
+standalone). Blank or malformed supplied values are errors, not permission to
+create a new binding. Only a genuinely missing binding enters lookup/creation.
+When both values are intentionally supplied, follow the approved generation
+binding: a backing connection ID supplied only for picker calls does not replace
+the approved connection reference in `add-data-source`.
+
+For tabular discovery, use already-supplied dataset/table/procedure values when
+available. Picker commands below require a connection ID, not a reference name.
+If only a reference is available and a picker is needed, obtain that reference's
+backing ID or ask for the concrete dataset/table values. Preserve the approved
+reference in the final `add-data-source`; never create another connection to
+make discovery convenient.
+
```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
$PA connection create --connector <apiId> --json
$PA connection list-references --solution-id <solutionId> --json
```
@@ -34,13 +58,14 @@ If `pa connection create` fails because browser-based connection creation is dis
1. Construct the URL using the active environment ID from `power.config.json`:
`https://make.powerapps.com/environments/<environment-id>/connections`
2. Direct the user to **+ New connection** → search for the connector → sign in / consent.
-3. Capture the connection ID from the portal or rerun `$PA connection create --connector <apiId> --json` if the connector can now complete.
+3. Capture the connection ID from the portal or rerun `$PA connection create --connector <apiId> --json` from the same guarded app root if the connector can now complete.
### Step 3 — Add the data source
Use long-form flags. Run from the app root after `power.config.json` exists, and use the exact `apiId` plus either a `connectionId` from `pa connection create`/the portal or a `connectionRef` from `pa connection list-references`:
```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
# Non-tabular connectors (Teams, Office 365 Users, Azure DevOps, etc.)
$PA app add data-source --connector <apiId> --connection-id <connectionId>
@@ -53,6 +78,7 @@ $PA app add data-source --connector shared_sql --connection-id <connectionId> --
**Dataverse is different** — never needs a connection ID:
```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
$PA app add data-source --connector dataverse --org-url <environmentUrl> --table <table-logical-name>
```
@@ -75,6 +101,7 @@ These are common connector API IDs you may see in connection output:
## Discovering datasets and tables (tabular connectors)
```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
$PA connection list-datasets --connector <apiId> --connection-id <connectionId> --json
$PA connection list-tables --connector <apiId> --connection-id <connectionId> --dataset '<dataset>' --json
$PA connection list-procedures --connection-id <connectionId> --dataset '<database>' --json
@@ -87,19 +114,22 @@ For SharePoint, the **dataset** is the site URL (e.g., `https://contoso.sharepoi
Use these instead of hand-rolled discovery when they match the user's goal:
```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
$PA connection list-references --solution-id <solutionId> --json
$PA app list-environment-variables --json
-$PA app list-flows --search '<flow-name-or-keyword>' --json
$PA app find-dataverse-api --search '<operation-name>' --json
$PA connection create --connector <apiId> --json
```
-Cloud flows are added with `pa app add flow`, not `pa app add data-source`:
+Cloud-flow integration is not supported by mobile skills. Report the limitation
+and return without flow discovery or mutation; a flow is not a connector data source.
-```bash
-$PA app add flow --flow-id <flow-guid> --non-interactive
-$PA app remove flow --flow-id <flow-guid> --force --non-interactive
-```
+For removal, use [data-source-removal.md](references/data-source-removal.md).
+`pa app remove data-source` owns app registration, schema, and
+model/service cleanup; it does not delete server data. `npm run generate-schemas`
+only rebuilds the mobile runtime schema map afterward. Use the removal workflow
+for approval, shared-reference preflight, and postcondition checks; use
+[cli-binary.md](cli-binary.md) for grouped/flat commands and flags.
Do not use local Expo web-player testing from mobile-app skills. Mobile-app runtime diagnosis uses the native dev-client flow and `/debug-app` reading the sanitized `.powernative/metro-logs/` files.
diff --git a/plugins/mobile-apps/shared/references/app-working-directory.md b/plugins/mobile-apps/shared/references/app-working-directory.md
new file mode 100644
index 000000000..9d1c9b0a6
--- /dev/null
+++ b/plugins/mobile-apps/shared/references/app-working-directory.md
@@ -0,0 +1,66 @@
+# Bind operations to the app root
+
+Before any project read, package gate, or command, resolve one absolute
+`working_dir` for this invocation:
+
+- **Child invocation:** require the owner's absolute `working_dir`, including
+ `--working-dir` when supplied. Never fall back to the process cwd. Missing or
+ relative owner context returns `NEEDS_CONTEXT` before project access.
+- **Direct invocation:** use `--working-dir` when supplied; otherwise capture the
+ initial cwd once. Resolve a direct relative argument against that initial cwd.
+- Canonicalize the existing filesystem directory using the host's native path
+ APIs (for Node, `fs.realpathSync.native`). If the argument and owner context
+ identify different roots, return `NEEDS_CONTEXT`; do not choose one silently.
+ A missing or inaccessible directory is `BLOCKED`, not permission to scaffold
+ or use cwd. Do not use Unix-only `realpath`/`readlink` flags on Windows.
+
+Pass this resolved root unchanged to each nested helper. A prior `cd` or exported
+variable does not persist across tool calls: **every shell call** must set its cwd
+explicitly to this root, or begin with the applicable fail-closed guard below.
+This includes commands copied from references, inline commands, discovery,
+auth/environment checks, generation, refresh/removal, type-checking, validation,
+telemetry, and retries. Keep `PLUGIN_ROOT` absolute and re-supply any required
+shell variables from the current invocation context on each call; a missing
+value returns `NEEDS_CONTEXT`, never an empty path or a cwd fallback.
+
+Resolve `$PA` and `PA_KIND` for this app via [cli-binary.md](../cli-binary.md),
+not from another app's cached selection. Re-supply both in each fresh shell
+call after binding the root; use the shared grouped/flat command and flag mapping.
+
+## Shell guards
+
+Use a shell-quoted literal argument for the resolved root, including in Git Bash
+on Windows. Replace `<working_dir>` with the literal path and escape each
+embedded apostrophe as `'\''`; keep the surrounding single quotes. Apply the
+same escaping to every literal app-root path argument in a command, including
+paths to files under that root. Never interpolate a path inside double quotes
+or execute an unresolved placeholder.
+
+The same rule applies to caller-supplied artifact paths such as
+`<SNAPSHOT_PATH>`, evidence, contracts, manifests, and changed-file arguments.
+These placeholders are literal paths, not shell variables. Only an actual
+variable assigned safely in the current call may use double-quoted expansion.
+
+```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
+```
+
+For an existing PowerShell helper, use a single-quoted literal path and double
+embedded apostrophes:
+
+```powershell
+Set-Location -LiteralPath '<working_dir>' -ErrorAction Stop
+```
+
+When Bash launches PowerShell, do not embed a path in the `-Command` source.
+Pass it through a per-call environment variable and keep the PowerShell command
+constant; otherwise the path is parsed by two different shells.
+
+## File tools
+
+File tools do not inherit shell cwd. Give Read/Edit/Write/Grep/Glob absolute
+project paths rooted at `working_dir`, including configuration, `node_modules`,
+`native-app-plan.md`, `memory-bank.md`, `.tmp/`, `.power/`, `src/native/`, and
+`src/generated/`. Keep plugin reference/script paths rooted at the absolute
+`PLUGIN_ROOT`. Root binding grants no additional approval and does not relax
+plan-only mode.
diff --git a/plugins/mobile-apps/shared/references/connector-planning.md b/plugins/mobile-apps/shared/references/connector-planning.md
index 949a55d21..a3f1c203d 100644
--- a/plugins/mobile-apps/shared/references/connector-planning.md
+++ b/plugins/mobile-apps/shared/references/connector-planning.md
@@ -1,6 +1,8 @@
# Connector Planning Reference
-Shared logic for inferring and confirming Power Platform connectors from app requirements. Used by `native-app-planner` (Gate 3) and `setup-datamodel` (Phase 2).
+Shared logic for inferring and confirming Power Platform connectors from app
+requirements. Used by `native-app-planner` and `setup-datamodel`.
+Discovery and proposal are not implementation.
---
@@ -21,7 +23,11 @@ Scan the requirements text and wizard answers for keywords. Map matches to conne
If a requirement is vague (e.g., "external data", "third-party API") but no keyword matches, do not infer a connector — flag it as "unknown, will need /add-connector at runtime."
-**Important:** Dataverse is NOT listed here. If the requirements need custom business data / tables, that is handled by `/add-dataverse` and captured in the `## Data Model` section, not the `## Connectors` section.
+**Important:** Dataverse is NOT listed here. Dataverse schema belongs in
+`## Data Model` and is implemented by `/add-dataverse`. Do not infer Dataverse
+merely from structured data: SQL/Excel/SharePoint tables remain connector data.
+Action-only integrations need no Dataverse model unless the user separately
+requires Dataverse persistence. Reuse the approved data platform.
**Application Insights is also NOT a connector requirement.** If requirements mention Application Insights, app analytics, diagnostics, telemetry, traces, or monitoring of this generated app:
@@ -106,3 +112,8 @@ At execution time, each confirmed connector maps to a skill invocation:
| Any other non-Dataverse connector | `/add-connector <api-name>` |
`/add-connector` owns the `pa app add data-source` call for its connector. The orchestrator never calls `pa app add data-source` directly.
+
+Invoke these skills only in the implementation phase with
+`MOBILE_APP_ORCHESTRATING=1` and the explicit approved context from
+[Data-source invocation scope](../shared-instructions.md#data-source-invocation-scope).
+Forward it when a router delegates.
diff --git a/plugins/mobile-apps/shared/references/data-source-removal.md b/plugins/mobile-apps/shared/references/data-source-removal.md
new file mode 100644
index 000000000..f233bd0c8
--- /dev/null
+++ b/plugins/mobile-apps/shared/references/data-source-removal.md
@@ -0,0 +1,241 @@
+# Retiring an app data source
+
+Use this reference when a current data-source request removes or replaces an
+app's Dataverse table binding, connector data source, or SQL procedure.
+Follow [Data-source invocation scope](../shared-instructions.md#data-source-invocation-scope)
+first. Standalone calls resolve and approve their exact data delta here; child
+calls retain their current owner, phase, absolute root, and approved scope.
+Removing a source from the app does not authorize deleting the server table,
+its columns/records, a connection, a solution component, or the cloud flow itself.
+Cloud-flow binding changes are not supported by mobile skills; report
+`BLOCKED: cloud-flow integration is not supported` and return without discovery
+or mutation. Preserve existing flow dependencies when changing a supported source.
+
+## Bind refresh, removal, and verification to the app root
+
+Before any app-local read or command, execute
+[app-working-directory.md](app-working-directory.md). Reuse the resolved owner
+root on every shell call and file tool, including CLI help, refresh, removal,
+regeneration, type-checking, service verification, and retries. This shared
+contract applies equally to the Bash examples below and PowerShell equivalents.
+Root binding does not grant removal approval or relax plan-only mode.
+
+## Removal is not schema-map generation
+
+The template's `npm run generate-schemas` rebuilds the runtime connector schema
+map. It does not infer unused tables from screen code, unregister sources, or
+replace the Power Apps CLI's service/model generation.
+
+The supported inverse of `pa app add data-source` is `pa app remove data-source`. The CLI
+removes the source's schema registration, updates `power.config.json`, and
+regenerates models/services from the remaining schemas. Follow it with
+`npm run generate-schemas` to update the mobile runtime map.
+
+## Refresh a retained source
+
+For a source that remains in use but whose server schema changed, use the CLI's
+`pa app refresh data-source` instead. Hiding a field or dropping it from a screen spec
+does not mean deleting its server column or unregistering the whole table.
+
+After current data-scope approval, `--refresh` or an approved refresh
+operation selects this branch in the data-source leaves. It is skill-only:
+do not pass `--refresh` to the CLI. A refresh-only call returns from this branch
+without running the normal add workflow, creating a connection, or changing
+server schema. `--plan-only` or a planning-phase handoff returns the proposed
+refresh without executing it. Standalone calls preview and approve the exact
+retained registration before execution; existing app configuration is not consent.
+Mixed requests are split into separately scoped add/refresh/remove
+calls; conflicting operation flags return `NEEDS_CONTEXT`.
+
+Resolve `--data-source-name` against `power.config.json` and `.power/schemas/`
+in the resolved absolute `working_dir`. Match the approved API, dataset/table or
+procedure, and connection binding as applicable. Require one unambiguous stored
+registration; never guess from a display label or silently add an absent source.
+If the CLI's name-only selector could refresh unrelated registrations, STOP.
+Capture the existing binding identities before executing the command.
+Resolve `$PA` using [cli-binary.md](../cli-binary.md). The examples use grouped
+`pa` commands; on `PA_KIND=power-apps`, translate both verbs and flags using that
+reference. The skill's `--data-source-name` becomes the grouped CLI's `--name`.
+
+```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
+$PA app refresh data-source --name '<registered-name>' --non-interactive
+npm run generate-schemas
+npx --no-install tsc --noEmit
+```
+
+Refresh only the approved retained source. Inspect per-source failure output as
+well as generated artifacts; an exit code alone is not a refresh success check.
+Verify the expected fields/operations in the regenerated schema/model/service,
+preserve unrelated registration identities and app/environment configuration,
+and verify the runtime schema map and type-check. Report missing/partial results
+as failures; do not repair generator output by hand or retry through addition.
+For Dataverse, also run the existing service verifier for the exact logical
+tables and update their app-inventory facts only from verified metadata.
+Refresh the existing Generated Services snapshot, or record verified service
+facts in memory-bank when no plan exists. Return generator-owned outputs
+separately from authored files; do not require a full-app plan for a refresh.
+No refresh authorizes retiring another source.
+
+Sources: [Power Apps CLI reference](https://learn.microsoft.com/power-apps/developer/code-apps/reference/cli#pa-app-remove-data-source)
+and [connecting to data](https://learn.microsoft.com/power-apps/developer/code-apps/how-to/connect-to-data#add-a-connection-to-a-code-app).
+
+## 1. Plan the removal, do not infer permission from absence
+
+Compare the current request and any proposed data delta with actual local
+configuration/schemas. Read existing Data Model, Connectors, Screens, and
+Generated Services sections when present; a full app plan is not a prerequisite
+for standalone retirement. Classify each source as retain, add, refresh, or
+candidate removal. A missing row in a planner's output is a candidate, not consent.
+
+For each candidate, resolve the exact stored data-source name, API ID, and
+dataset/table/procedure identity from `power.config.json` and `.power/schemas/`.
+A display label, table logical name, and generated class name need not match.
+Preserve original spelling; do not guess a CLI selector from a screen title.
+
+Inspect remaining screens, navigation, hooks, shared helpers, native upload/sync
+wrappers, lookup/identity reads, and offline requirements. Search imports and
+actual service calls, not just table names in screen files. A source used only by
+an identity helper, relationship lookup, or background tracker is still used.
+Dynamic or ambiguous usage is a blocker to automatic removal, not proof of disuse.
+
+Present the candidate list, dependent app files to change, and preserved server
+data to the standalone user or in the current owner's mutation preview.
+Require explicit approval. Never mutate configuration/generated files during
+planning or `--plan-only`; return the proposal before execution even if an earlier
+scope was approved.
+
+## 2. Retire consumers before unregistering
+
+The responsible app workflow adds/refreshes replacement sources first, then
+updates or removes the approved consumers and verifies they no longer depend
+on the retiring source.
+Keep the old binding available until those source edits are complete.
+
+Only then call the appropriate leaf in removal mode, with the exact approved
+removal list and, for a child call, complete `MOBILE_APP_ORCHESTRATING=1` context.
+A leaf call must not mix addition and removal; do not run the normal add workflow or create a connection
+before removing one. Standalone removal must stop if consumers remain.
+Report that consumer work to the user; existing `/edit-app` may be requested
+separately, but do not automatically invoke it or promise consumer migration.
+Use the skill-only `--remove` argument or explicit removal intent to select this
+branch; do not pass `--remove` to the Power Apps CLI.
+If a replacement collides with the old registration and cannot be staged safely,
+return the conflict to the owner for an explicit migration plan.
+
+## 3. Execute only the approved app-local removal
+
+Use the resolved `$PA` from the app root and the shared
+[command and flag mapping](../cli-binary.md). Confirm its removal options with
+`$PA app remove data-source --help` (translated for the flat fallback) if the
+installed surface differs. Do not fetch another CLI version as a fallback.
+
+After approval, `--force` acknowledges grouped `pa`'s destructive-action prompt;
+`--non-interactive` alone is not removal consent. For `PA_KIND=power-apps`,
+translate the command and flags and omit `--force` as specified by the shared
+mapping; the approval and scope checks still apply. Run only the applicable
+command below:
+
+```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
+# Dataverse: use the registered data-source key, not a guessed display label.
+$PA app remove data-source --connector dataverse --name '<registered-name>' --force --non-interactive
+
+# Connector/table registration.
+$PA app remove data-source --connector '<apiId>' --name '<registered-name>' --force --non-interactive
+
+# SQL procedure: also use the exact stored procedure identity from its schema.
+$PA app remove data-source --connector shared_sql --name '<registered-name>' --procedure '<procedure>' --force --non-interactive
+```
+
+Run sequentially: each operation can regenerate the shared model/service output.
+Do not manually delete `src/generated/` files, schema registrations, or
+`power.config.json` entries to imitate the command.
+
+**Scope preflight matters.** Non-Dataverse cleanup can match source names across
+connection references and prune empty references. Before removal, check for same-named registrations in other
+connectors/datasets and empty references used by remaining flows. If the command
+could remove anything outside the approved scope, stop and report the CLI
+limitation; do not run it and hope to repair collateral changes afterward.
+Retain shared connection references and sources still needed by another consumer.
+
+## 4. Verify the outputs, not just the exit code
+
+Compare against the pre-removal inventory after every command:
+
+- The exact source is absent from its `.power/schemas/` registration and from
+ `databaseReferences` or `connectionReferences`/`dataSets` in `power.config.json`.
+- Retired source-specific generated services/models and exports are no longer
+ present. Shared helpers/models and remaining registrations still exist.
+- App identity, environment, unrelated bindings, and flow dependencies are
+ unchanged. Empty reference containers may be removed by the CLI only when
+ nothing retained depends on them.
+
+The flat CLI can return exit 0 for a not-found/no-op removal. Missing selectors,
+unchanged registrations, stale generated outputs, or unexpected deletions are
+failures to resolve, not success. Stop on a partial result, record what changed,
+and recover through supported CLI operations with the owner; never hand-edit
+generator-owned files or continue to deployment.
+
+After verified removal:
+
+```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
+npm run generate-schemas
+npx --no-install tsc --noEmit
+```
+
+Confirm the runtime schema map excludes the retired source, including when the
+last source was removed. Do not fabricate an empty map to hide a generator error.
+Return manual `writtenFiles` separately from CLI/generator-owned outputs.
+
+## 5. Reconcile the app inventory
+
+Refresh the existing Generated Services snapshot after removal, or report the
+verified remaining services in memory-bank when no plan exists; do not create
+a full-app plan or screen workflow just to retire a binding. Update the
+app-local `.datamodel-manifest.json` only after verifying the remaining Dataverse
+services; remove retired app-inventory entries while preserving verified facts
+for retained tables. If no Dataverse bindings remain, retain a valid empty
+`tables` array rather than stale entries. Preserve historical ownership facts in
+the existing history; this inventory update is not server schema deletion.
+Do not reuse old plan-bound operation manifests or approval receipts to recreate
+retired sources.
+
+During a mixed add/remove edit, the transitional manifest can still contain a
+retiring table. Do not seed it: the owner passes `/add-sample-data` an explicit
+approved seed-table allowlist plus retirement exclusions. Dependency fanout,
+prototype rows, media uploads, and retries cannot widen that set. Reconcile the
+final inventory only after verifying the CLI removal, not by pruning entries to
+control seed selection.
+
+Check `offline-profile.json` before retiring an offline dependency. The existing
+`offline-profile-delta.js` detects additions, not excess profile tables; `in-sync`
+does not prove removal reconciliation. Profile items/associations can be shared
+and are server configuration: do not silently remove them or edit the local
+snapshot to pretend the server changed. Keep required bindings, or obtain a
+separate approved profile migration; report any intentionally retained profile
+coverage and unresolved offline work.
+
+Carry a per-table `offlineRetirement` outcome in the leaf result and the existing
+memory-bank entry; do not invent a second profile snapshot:
+
+| Status | Evidence required |
+|---|---|
+| `not-applicable` | No profile coverage or dependency on the retiring table was found. |
+| `retained` | Coverage is intentionally kept; record the approved reason and any required app binding that must also remain. |
+| `pending` | Retain/remove decision is unanswered, migration is deferred, or the approved profile change is not yet verified. |
+| `reconciled` | The separately approved profile migration and its live readback succeeded. |
+
+Inspect offline dependencies before unregistering. An unresolved dependency that
+could break retained offline behavior blocks app-binding removal; record `pending`
+and return the blocker, not a completed app edit. When app removal is independently
+safe but coverage disposition remains pending, report both outcomes separately.
+Preserve pending outcomes on retries/resume until the user explicitly approves
+retention or the approved migration is verified. A later addition-only
+`in-sync`, `no-manifest`, or `no-profile` result never clears `offlineRetirement`.
+Do not infer permission to remove server profile items from app-binding approval.
+
+Update memory-bank with removed/retained sources, verification, and any partial
+failure. Return verified data-layer results and remaining concerns to the user
+or current owner; consumer integration and preview work are separate requests.
diff --git a/plugins/mobile-apps/shared/references/dataverse-change-planning.md b/plugins/mobile-apps/shared/references/dataverse-change-planning.md
new file mode 100644
index 000000000..b6afda79d
--- /dev/null
+++ b/plugins/mobile-apps/shared/references/dataverse-change-planning.md
@@ -0,0 +1,197 @@
+# Dataverse planning for scoped changes
+
+Use this contract from `setup-datamodel` and standalone
+`add-dataverse` when proposing Dataverse schema or a new table binding. It
+adapts the existing create-flow planning helpers to the owner's current delta;
+it does not invoke `/create-mobile-app` or add another approval gate.
+
+## 1. Establish the scope before discovery
+
+Retain one absolute `working_dir`, the current request, the existing plan, and
+the owner's planning/implementation mode across every call and retry.
+Planning is not implementation approval, including after a request to inspect
+or propose a data-model change.
+
+- Connector-only, native/design-only, removal-only, and retained-service-only
+ refresh requests skip this workflow. Use their existing scoped workflows;
+ do not create empty Dataverse artifacts or require a data-model receipt.
+ Mark planning paths as not supplied for this invocation; never consume old
+ scratch artifacts merely because they remain on disk.
+- For Dataverse changes, separate proposed schema/binding changes from retained
+ context and retirements. Unaffected plan rows, screens, and generated services
+ are not permission to replay schema work.
+- The structured contract contains only the proposed delta and its necessary
+ Dataverse dependencies. Represent existing dependencies as `reuse`, not
+ `create`/`extend`; do not copy historical creation rows from the full plan.
+ Preserve unrelated services outside this contract. A missing dependency that
+ would require additional mutations goes into the proposal for approval.
+- Preserve approved native capture/storage intent and connector ownership.
+ Connector-owned records do not become Dataverse tables unless an explicit
+ projection is part of the request. Diagram entities express desired intent,
+ not evidence that a table exists or permission to replace it.
+
+Read the selected environment ID from the owner's `power.config.json`.
+Resolve missing context using the shared non-persisting environment rule:
+
+```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
+node "${PLUGIN_ROOT}/scripts/resolve-environment.js" "<selected-environment-id>" --no-cache --require-tenant
+```
+
+Require the resulting environment ID, HTTPS URL, and tenant to match the
+selected app and any supplied owner context. On conflict, return
+`NEEDS_CONTEXT` to the owner before discovery; never select another environment
+silently. Resolve authentication/access failures through the existing bounded
+foreground recovery, not by enabling persistent resolution.
+
+Scratch proposals, evidence, and the planning-only inventory cache may be
+written under this app's `.tmp/`; `_dm_section.md` is a proposal. Planning must
+not change auth/app configuration, the materialized manifest, generated
+services, server schema/data, or the live plan before its owning approval.
+
+## 2. Obtain the canonical compact evidence
+
+Read and execute only
+[Foreground Dataverse planning snapshot and evidence](../../skills/create-mobile-app/SKILL.md#foreground-dataverse-planning-snapshot-and-evidence),
+ending before **Planner completion dispatch**. This is the shared helper recipe,
+not permission to run the create wizard, its planner, scaffolding, or gates.
+Bind its inputs as follows:
+
+| Create-flow input | Existing-app/data-only meaning |
+|---|---|
+| `WORKING_DIR` / `<working_dir>` | The owner's absolute app root; enter it in every shell invocation. |
+| `<dataverse_planning_mode>` | `required` only for this Dataverse delta. |
+| confirmed brief / Gate 1-approved architecture | The current request and retained native/connector constraints; not mutation approval. |
+| `ACTIVE_ENV_ID`, `ACTIVE_ENV_URL`, `ACTIVE_TENANT_ID` | The same verified selected environment. |
+| publisher-prefix metadata | Reuse matching verified context or run the existing read-only prefix detector for this target. |
+| typed concepts | Only unresolved app-owned entity concepts in this delta; roles/fields/actions/statuses/constraints are not tables. |
+| `<EXPLICIT_TABLES>` | Exact existing targets and necessary dependencies, not every table used anywhere in the app. |
+| `<PROPOSED_TABLES>` | Every proposed final custom logical name, including adapted names. |
+
+Use the existing progressive/combined read helpers, production read concurrency
+`1`, identity-scoped inventory cache, and recovery rules unchanged. Explicit
+targets use exact-name evidence; do not add broad concepts merely to increase
+coverage. A valid cache is planning evidence only, never write authorization.
+Resolve placeholders before executing the recipe; do not carry shell variables
+implicitly between tool calls.
+
+The outputs are the owner's absolute `SNAPSHOT_PATH` and
+`ARCHITECT_EVIDENCE_PATH`. Validate the compact evidence against the full
+snapshot with `render-dataverse-architect-evidence.js --validate-only` as the
+recipe requires. Never dispatch on failed/stale output. Agents read only the
+compact sidecar; the full snapshot is an opaque validator input.
+
+## 3. Produce a proposal on every path
+
+Use this handoff for the architect, including retries:
+
+```text
+Task: mobile-app:data-model-architect
+Context:
+ working_dir: <absolute owner root>
+ phase: planning
+ proposal_only: <true for --plan-only or a planning-phase caller>
+Prompt:
+ Current request and proposed scope: <delta, retained constraints, dependencies>
+ Existing Data Model: <context only; preserve unaffected decisions>
+ Approved native capabilities and connector ownership: <current constraints>
+ Dataverse planning mode: required
+ Normalized Dataverse foreground planning snapshot (validator input only): <SNAPSHOT_PATH>
+ Compact Dataverse architect evidence: <ARCHITECT_EVIDENCE_PATH>
+ Structured schema contract output: <working_dir>/.tmp/dataverse-schema-contract.json
+ Output proposal: <working_dir>/_dm_section.md
+ Working directory: <working_dir>
+ Plugin root: ${PLUGIN_ROOT}
+ Return a scoped proposal and normalized contract; do not save the live plan,
+ grant approval, run live discovery, or apply changes.
+```
+
+For a diagram, parsed text, existing-plan delta, or unavailable-agent inline
+fallback, produce the same two outputs using the architect's
+[structured schema contract](../../agents/data-model-architect.md#structured-dataverse-schema-contract-required-for-required-mode)
+and validated compact evidence. Never use local models or Mermaid alone as
+proof of current server metadata. Merge only the accepted delta into the full
+plan later; do not replace its unaffected sections with the scoped contract.
+
+## 4. Validate before the owner's existing gate
+
+After every proposal or revision, normalize and validate:
+
+```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
+node "${PLUGIN_ROOT}/scripts/build-dataverse-operation-manifest.js" \
+ --normalize-contract '<working_dir>/.tmp/dataverse-schema-contract.json' \
+ --output '<working_dir>/.tmp/dataverse-schema-contract.json'
+```
+
+Only if normalization succeeds:
+
+```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
+node "${PLUGIN_ROOT}/scripts/validate-dataverse-planning-decisions.js" \
+ --contract '<working_dir>/.tmp/dataverse-schema-contract.json' \
+ --snapshot '<SNAPSHOT_PATH>'
+```
+
+`DONE` / `DONE_WITH_CONCERNS` from an agent is not a validation result. Verify
+that the section and contract describe the same delta and that neither exceeds
+the requested scope. Only exit `0` permits presenting an executable proposal
+at the owner's existing approval gate. Surface `Adapt`/`Defer` and other
+concerns there; a deferred required dependency cannot be described as complete.
+
+Handle structured signals before generic agent retry limits, using
+[Dataverse planning recovery](../../skills/create-mobile-app/SKILL.md#dataverse-planning-recovery):
+
+| Result | Owner action |
+|---|---|
+| Exit `3`, `NEEDS_CONTEXT: detailed-dataverse-metadata:<names>` | Expand only names not already fully attempted, then regenerate/validate compact evidence and re-dispatch. |
+| Exit `3`, `NEEDS_CONTEXT: proposed-dataverse-names:<names>` | Run the separate collision-only check for new final names; never reinterpret it as detail discovery. |
+| Exit `4`, `NEEDS_REVISION: dataverse-plan-validation` | Revise automatically from the same evidence, with safe validator errors; no metadata read or user question for a routine correction. |
+| `NEEDS_CONTEXT: dataverse-plan-revision:<classification>` | Use the inline revision fallback, not a generic context retry. |
+| Exit `2`, invalid/mismatched artifacts, or a hard blocker | Report the failure and return to the artifact owner; no approval, mutation, stale-output fallback, or downgrade to success. |
+
+The recipe's `DETAIL_ATTEMPTED_NAMES` and `PROPOSED_CHECKED_NAMES` are separate
+monotonic sets. `core` detail remains eligible for full-detail expansion;
+already-unavailable names are not fetched repeatedly. Continue for new names
+derived from this request/evidence, not unrelated plan rows. On no progress,
+revise inline using current evidence or explicitly defer unsupported work.
+Ask the user only when a remaining alternative changes business semantics.
+Never import creation's Gate 1/2 prompts into this owner.
+
+For `--plan-only`, return the validated proposal (or explicit blocker) at the
+owner's proposal boundary. `setup-datamodel` and `add-dataverse` do not save the
+live plan. None of these modes grants implementation approval or mints an
+execution receipt.
+
+## 5. Carry the accepted scope into implementation
+
+After the existing gate approves implementation, save only the accepted plan
+delta. Carry the absolute `planning_snapshot`, `architect_evidence`, and
+`schema_contract` paths in the leaf context. In `approved_scope`, record the
+exact accepted operations/dependencies plus `contract_sha256` (SHA-256 of the
+normalized contract file bytes) and `plan_sha256` (the final saved plan bytes).
+These are evidence bindings in the existing invocation context, not a new
+receipt format. Revisions or changed files require returning to the owner;
+never recalculate these approval hashes after discovering a mismatch.
+
+The existing five-artifact operation-manifest fast path remains
+creation-receipt-owned. Its receipt requires `workflow: create-mobile-app`
+and four approvals. Do not fabricate those approvals for data-only changes, weaken
+receipt validation, or pass a partially populated fast-path argument set.
+Data-only changes use the scoped standalone execution path with their real approval.
+On resume without matching approval context, return `NEEDS_CONTEXT`; an old
+plan or scratch artifact does not grant permission.
+
+Before execution, `add-dataverse` checks these hashes, target identity, compact
+evidence, and planning decisions, then performs its existing fresh bounded
+live reconciliation for the scoped contract. It must not reconstruct mutation
+scope from all rows in the saved Markdown plan, trust the planning cache as
+current write evidence, or silently adapt names/requirements after approval.
+Preserve verified unrelated services; a missing/out-of-scope binding returns
+to the owner. A service-only refresh or app-binding retirement retains its
+separate branch and does not become a schema mutation.
+
+Keep both upstream publish/cache-invalidation recovery paths intact. Successful
+publication plus failed cache cleanup is unfinished work, not permission to
+replay writes. Preserve pending offline-retirement outcomes independently of
+addition checks; this workflow never authorizes profile deletion.
diff --git a/plugins/mobile-apps/shared/references/dataverse-offline-api.md b/plugins/mobile-apps/shared/references/dataverse-offline-api.md
index a9499eb4b..4bdf89ee4 100644
--- a/plugins/mobile-apps/shared/references/dataverse-offline-api.md
+++ b/plugins/mobile-apps/shared/references/dataverse-offline-api.md
@@ -6,6 +6,22 @@ All calls use `scripts/dataverse-request.js` from the plugin root unless otherwi
Field semantics are in [offline-profile-schema.md](./offline-profile-schema.md). This doc is just the *how* — the wire format.
+Before any example, apply [app-working-directory.md](app-working-directory.md)
+and reuse the caller's absolute `working_dir`, selected `<envUrl>` and
+`<tenantId>`, exact resource identities, phase, and approved scope. Missing or
+conflicting context returns `NEEDS_CONTEXT`; never borrow the launch app or an
+ambient tenant. Every discovery, mutation, verification, and recovery request
+uses that same root and explicit tenant. These recipes do not grant approval
+or override planning mode; membership, deletion, and broader publication need
+their own applicable approval.
+
+When a recovery reads an internal add/edit helper, use the
+[scoped helper handoffs](offline-profile-reconciliation.md#scoped-helper-handoffs):
+forward the current owner, absolute root, environment/tenant/profile identity,
+phase, and the exact approved repair. Include `--working-dir '<working_dir>'`
+and the selected profile/table arguments; abbreviated commands below are not
+permission to drop context or to reuse approval for a different operation.
+
---
## §1 — Per-table prerequisites (PUT EntityMetadata)
@@ -14,11 +30,17 @@ Field semantics are in [offline-profile-schema.md](./offline-profile-schema.md).
**Why not `dataverse-request.js`:** the PUT needs the `MSCRM.MergeLabels: true` header to preserve display labels, and the generic script does not accept arbitrary headers. Use the purpose-built helper instead:
+Use the tenant resolved for the approved environment as `<tenantId>`; the
+explicit argument also binds token refresh and fails closed if that tenant is
+unavailable. Do not substitute an ambient tenant.
+
```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
node "${PLUGIN_ROOT}/scripts/update-entity-offline-flags.js" <envUrl> \
--table <table_logical_name> \
--offline true \
- --tracking true
+ --tracking true \
+ --tenant-id "<tenantId>"
```
The helper internally:
@@ -41,11 +63,17 @@ After all PUTs land, publish customizations once at the end of Step 5 (see §2 b
**Use case:** End of `/enable-tables-offline` Step 5 (after EntityMetadata PUTs), end of `/setup-offline-profile` Step 8 (after profile creation).
```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
node "${PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> POST \
- "PublishAllXml" --body '{}'
+ "PublishXml" --tenant-id "<tenantId>" --body '{
+ "ParameterXml": "<importexportxml><entities><entity><table></entity></entities></importexportxml>"
+ }'
```
-Expected: `204 No Content`. Empty body — the message takes no arguments and publishes every unpublished customization in the org. A single bulk publish at the end is correct; granular `PublishXml` per table is slower and provides no benefit.
+Expected: `204 No Content`. Build the entity list from only the approved tables
+actually changed by prerequisite PUTs. For profile publication use §9 instead.
+`PublishAllXml` publishes every pending customization in the environment and
+requires separate explicit approval; a table/profile-scoped request is not consent.
If publish fails (rare — usually a transient server lock):
- The PUT changes are still committed in the metadata DB
@@ -59,8 +87,10 @@ If publish fails (rare — usually a transient server lock):
**Use case:** `/setup-offline-profile` Step 5.
```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
node "${PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> POST \
"mobileofflineprofiles" \
+ --tenant-id "<tenantId>" \
--body '{
"name": "<App Name> Offline Profile",
"description": "Auto-generated by mobile-app plugin. Tables: ..."
@@ -79,8 +109,10 @@ Expected: `204 No Content` with body `{ ... }` plus `headers["odata-entityid"]:
**Use case:** `/setup-offline-profile` Step 6. Issue one POST per table in the profile, sequentially.
```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
node "${PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> POST \
"mobileofflineprofileitems" \
+ --tenant-id "<tenantId>" \
--body '{
"name": "<Table Display Name>",
"[email protected]": "/mobileofflineprofiles(<profileId>)",
@@ -115,11 +147,14 @@ Expected: `204` with `OData-EntityId` → capture `mobileofflineprofileitemid`.
Two queries cover both directions of N:1 / 1:N from a parent table:
```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
node "${PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> GET \
- "EntityDefinitions(LogicalName='<table>')/ManyToOneRelationships?\$select=MetadataId,SchemaName,ReferencingEntity,ReferencedEntity"
+ "EntityDefinitions(LogicalName='<table>')/ManyToOneRelationships?\$select=MetadataId,SchemaName,ReferencingEntity,ReferencedEntity" \
+ --tenant-id "<tenantId>"
node "${PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> GET \
- "EntityDefinitions(LogicalName='<table>')/OneToManyRelationships?\$select=MetadataId,SchemaName,ReferencingEntity,ReferencedEntity"
+ "EntityDefinitions(LogicalName='<table>')/OneToManyRelationships?\$select=MetadataId,SchemaName,ReferencingEntity,ReferencedEntity" \
+ --tenant-id "<tenantId>"
```
Match by `SchemaName === <relationship name from architect>`. Capture:
@@ -133,8 +168,10 @@ Cache the lookup per parent table — re-querying for each association adds sign
File and Image columns participate in offline sync as relationships from the parent table to the image attribute. Discover via:
```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
node "${PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> GET \
- "EntityDefinitions(LogicalName='<table>')/Attributes?\$filter=AttributeType eq 'Image' or AttributeType eq 'File'&\$select=MetadataId,LogicalName,SchemaName,AttributeType"
+ "EntityDefinitions(LogicalName='<table>')/Attributes?\$filter=AttributeType eq 'Image' or AttributeType eq 'File'&\$select=MetadataId,LogicalName,SchemaName,AttributeType" \
+ --tenant-id "<tenantId>"
```
Each result is added as an association exactly like a relationship — `MetadataId` → `relationshipid`, `SchemaName` → `name` / `relationshipdisplayname`.
@@ -144,8 +181,9 @@ Each result is added as an association exactly like a relationship — `Metadata
The maker portal queries via FetchXML (joins through the parent profile item to filter by profile):
```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
node "${PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> GET \
- "mobileofflineprofileitemassociations?fetchXml=<URL-ENCODED-FETCH>"
+ "mobileofflineprofileitemassociations?fetchXml=<URL-ENCODED-FETCH>" --tenant-id "<tenantId>"
```
FetchXML (un-encoded) — replace `<profileId>` with the target `mobileofflineprofileid`:
@@ -177,8 +215,10 @@ Returns the existing associations across all items in the profile. Use this for
**Use case:** `/setup-offline-profile` Step 7a, or `/add-table-to-offline-profile` after adding a new table. Issue one POST per (parent-item, relationship) pair — best inside a `$batch` changeset so a partial failure rolls back all of them (see §6a below).
```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
node "${PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> POST \
"mobileofflineprofileitemassociations" \
+ --tenant-id "<tenantId>" \
--body '{
"name": "<relationship-schema-name>",
"relationshipdisplayname": "<relationship-schema-name>",
@@ -257,8 +297,10 @@ The skill should:
**Use case:** `/setup-offline-profile` Step 7b. After Gate 3 captures user-confirmed column lists and sync frequency edits, PATCH each item.
```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
node "${PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> PATCH \
"mobileofflineprofileitems(<itemId>)" \
+ --tenant-id "<tenantId>" \
--body '{
"selectedcolumns": "{\"Columns\":[\"cr123_title\",\"cr123_body\",\"modifiedon\",\"statecode\"]}",
"syncintervalinminutes": 10
@@ -285,8 +327,9 @@ Expected: `204 No Content`.
**Recommended (the maker portal's pattern, empirical 2026-05-24):** targeted `PublishXml` — publishes ONLY the specific profile, not the entire org's customizations. Avoids the rate-limit storms `PublishAllXml` triggers on shared envs.
```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
node "${PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> POST \
- "PublishXml" --body '{
+ "PublishXml" --tenant-id "<tenantId>" --body '{
"ParameterXml": "<publish><mobileofflineprofiles><mobileofflineprofile><profileId></mobileofflineprofile></mobileofflineprofiles></publish>"
}'
```
@@ -295,11 +338,15 @@ Replace `<profileId>` with the actual GUID (no braces, no quotes — raw GUID in
Expected: `204 No Content`. The maker portal makes this call inside a `$batch` changeset (along with any pending item/association mutations); standalone POST works fine for our usage.
-**Fallback — `PublishAllXml`:** the v0.1 skill used this. It works but rate-limits aggressively on shared envs (empirical: 4-retry 429 backoff → client timeout twice on chanel-rm + offline-demo-fixture demos). Useful as a last resort if the targeted publish fails:
+**Fallback — `PublishAllXml`:** only after the owner separately approves publishing
+all pending environment customizations. A targeted publish failure or rate limit
+does not grant broader approval. Keep the same root, tenant, and selected profile
+on the fallback and its readback:
```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
node "${PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> POST \
- "PublishAllXml" --body '{}'
+ "PublishAllXml" --tenant-id "<tenantId>" --body '{}'
```
**Handle publish errors:**
@@ -309,14 +356,15 @@ node "${PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> POST \
| `204` | Published | Continue |
| `400 / 0x80071141` "circular relationship" | Profile's association graph contains a cycle (e.g., `account => task => account`) | Parse the path from the error message, remove ONE association (prompt user at this point), re-attempt publish |
| `400 / 0x80071140` "no relationships are specified" for a Related-only table | A profile item has `recorddistributioncriteria=0` (Related rows only) but no `mobileofflineprofileitemassociation` rows targeting it. Without those, the runtime would sync zero rows. **Empirical 2026-05-24**: server enforces this at publish time — and the validation seems to look at associations published in an earlier `publishedon` snapshot, not the current uncommitted ones. So for profiles being **retrofitted** (existing publish + late association additions), publish can fail even after associations are added. | Parse the table name from the error message. Two recoveries: (a) read and execute `${PLUGIN_ROOT}/skills/add-table-to-offline-profile/SKILL.md` with `--table <tbl>` to add ALL relevant inbound associations, not just one; (b) read and execute `${PLUGIN_ROOT}/skills/edit-offline-profile/SKILL.md` with `--table <tbl> --scope 2 --me` to change scope away from Related-only. Prompt user to pick. |
-| `429` (rate limit) | Concurrent publish in progress on shared env | Back off via `dataverse-request.js` automatic retry; if still failing, fall through to the targeted-then-fallback pattern below |
+| `429` (rate limit) | Concurrent publish in progress on shared env | Back off via `dataverse-request.js` automatic retry; if still failing, report the result or verify the same target after a timeout. Do not widen publication without approval. |
| Client timeout, but server-side committed | Shared envs can take longer than `dataverse-request.js`'s 4-retry budget allows | Verify by re-GET — if `componentstate=0` AND `publishedon` is non-null + recent, treat as success |
After publish, re-GET the profile and assert state:
```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
node "${PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> GET \
- "mobileofflineprofiles(<profileId>)?\$select=publishedon,componentstate,isvalidated"
+ "mobileofflineprofiles(<profileId>)?\$select=publishedon,componentstate,isvalidated" --tenant-id "<tenantId>"
```
Expected post-publish: `componentstate=0` (Published), `publishedon=<iso8601>` (within last 5 min). **`isvalidated`** will typically be `true` after publish — but `false` is fine if Validate (§8) was skipped.
@@ -328,13 +376,15 @@ Expected post-publish: `componentstate=0` (Published), `publishedon=<iso8601>` (
**Use case:** `/setup-offline-profile` Step 2 (extend-vs-create-new decision). Also used by `/edit-offline-profile` and `/preview-offline-scope`.
```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
# List
node "${PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> GET \
- "mobileofflineprofiles?\$select=mobileofflineprofileid,name,description,publishedon,createdon"
+ "mobileofflineprofiles?\$select=mobileofflineprofileid,name,description,publishedon,createdon" --tenant-id "<tenantId>"
# Detail (with items + associations)
node "${PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> GET \
- "mobileofflineprofiles(<profileId>)?\$expand=MobileOfflineProfile_MobileOfflineProfileItem(\$select=mobileofflineprofileitemid,selectedentitytypecode,recorddistributioncriteria,recordsownedbyme,recordsownedbymyteam,recordsownedbymybusinessunit,syncintervalinminutes,selectedcolumns;\$expand=MobileOfflineProfileItem_MobileOfflineProfileItemAssociation(\$select=mobileofflineprofileitemassociationid,relationshipid,relationshipname))"
+ "mobileofflineprofiles(<profileId>)?\$expand=MobileOfflineProfile_MobileOfflineProfileItem(\$select=mobileofflineprofileitemid,selectedentitytypecode,recorddistributioncriteria,recordsownedbyme,recordsownedbymyteam,recordsownedbymybusinessunit,syncintervalinminutes,selectedcolumns;\$expand=MobileOfflineProfileItem_MobileOfflineProfileItemAssociation(\$select=mobileofflineprofileitemassociationid,relationshipid,relationshipname))" \
+ --tenant-id "<tenantId>"
```
The second query is the canonical "read full profile state" call — also used by `scripts/verify-offline-profile.js` post-create.
@@ -346,8 +396,9 @@ The second query is the canonical "read full profile state" call — also used b
**Use case:** `/setup-offline-profile` Step 1b. If a prior session left a half-built profile in `memory-bank.md` with `status: in-progress`, and the user picks "start fresh".
```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
node "${PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> DELETE \
- "mobileofflineprofiles(<profileId>)"
+ "mobileofflineprofiles(<profileId>)" --tenant-id "<tenantId>"
```
Cascade-deletes via the `MobileOfflineProfile_MobileOfflineProfileItem` and `MobileOfflineProfileItem_MobileOfflineProfileItemAssociation` relationships (both have `Delete: Cascade` configuration per the entity reference). Expected `204`.
@@ -363,8 +414,10 @@ Cascade-deletes via the `MobileOfflineProfile_MobileOfflineProfileItem` and `Mob
### User membership
```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
node "${PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> POST \
"usermobileofflineprofilememberships" \
+ --tenant-id "<tenantId>" \
--body '{
"[email protected]": "/mobileofflineprofiles(<profileId>)",
"[email protected]": "/systemusers(<systemuserid>)"
@@ -375,8 +428,10 @@ node "${PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> POST \
### Team membership
```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
node "${PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> POST \
"teammobileofflineprofilememberships" \
+ --tenant-id "<tenantId>" \
--body '{
"[email protected]": "/mobileofflineprofiles(<profileId>)",
"[email protected]": "/teams(<teamid>)"
@@ -387,11 +442,14 @@ node "${PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> POST \
### Listing existing memberships (for idempotency)
```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
node "${PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> GET \
- "usermobileofflineprofilememberships?\$filter=_mobileofflineprofileid_value eq <profileId>&\$expand=systemuserid_systemuser(\$select=domainname)"
+ "usermobileofflineprofilememberships?\$filter=_mobileofflineprofileid_value eq <profileId>&\$expand=systemuserid_systemuser(\$select=domainname)" \
+ --tenant-id "<tenantId>"
node "${PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> GET \
- "teammobileofflineprofilememberships?\$filter=_mobileofflineprofileid_value eq <profileId>&\$expand=teamid_team(\$select=name)"
+ "teammobileofflineprofilememberships?\$filter=_mobileofflineprofileid_value eq <profileId>&\$expand=teamid_team(\$select=name)" \
+ --tenant-id "<tenantId>"
```
> **⚠️ Verified empirically 2026-05-19 (MSProjectSienaV1 / Chanel profile demo):** the correct `@odata.bind` nav prop names for `usermobileofflineprofilemembership` and `teammobileofflineprofilemembership` are **PascalCase** — `MobileOfflineProfileId`, `SystemUserId`, `TeamId` — NOT the snake_case lookup-attribute names. The setup/edit skills use snake_case `regardingobjectid` which IS correct for `mobileofflineprofileitem` and `mobileofflineprofileitemassociation`. Dataverse is inconsistent across entities. Always probe via `EntityDefinitions(LogicalName='<entity>')/Attributes?$filter=AttributeType eq 'Lookup'&$select=LogicalName,SchemaName` and use the `SchemaName` column for `@odata.bind` if unsure.
@@ -401,8 +459,9 @@ node "${PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> GET \
### DELETE (unassign)
```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
node "${PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> DELETE \
- "usermobileofflineprofilememberships(<membershipid>)"
+ "usermobileofflineprofilememberships(<membershipid>)" --tenant-id "<tenantId>"
```
---
@@ -414,11 +473,11 @@ node "${PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> DELETE \
| 2 | §10 | List existing profiles |
| 5 | §3 | POST profile shell |
| 4 (pre-Gate-1) | §1 | PUT EntityMetadata per table needing prereqs |
-| 5 (mid-skill) | §2 | PublishAllXml (after prereq PUTs) |
+| 5 (mid-skill) | §2 | Targeted PublishXml for changed prerequisite tables |
| 6 | §4 | POST profile item per table |
| 7a | §5 → §6 | Resolve relationships → POST associations |
| 7b | §7 | PATCH selectedcolumns + syncintervalinminutes |
-| 8 | §8 → §9 | Validate (best-effort) → PublishAllXml |
+| 8 | §9 | Targeted PublishXml for the selected profile |
| 9 (verification) | §10 | Re-fetch full profile, compare to `offline-profile.json` |
The total HTTP cost for a typical 5-table profile with 3 relationships each: ~20 sequential calls (1 list + 1 publish-prereq + 1 publish-profile + 5 items + 15 associations + 5 PATCHes + 2 reads), bounded by Dataverse's serialization rules.
diff --git a/plugins/mobile-apps/shared/references/javascript-dependency-planning.md b/plugins/mobile-apps/shared/references/javascript-dependency-planning.md
index 90a1945c7..046c1c34e 100644
--- a/plugins/mobile-apps/shared/references/javascript-dependency-planning.md
+++ b/plugins/mobile-apps/shared/references/javascript-dependency-planning.md
@@ -78,7 +78,7 @@ Then verify:
```bash
node "${PLUGIN_ROOT}/scripts/validate-mobile-files.js" \
- --project-root "<working_dir>" \
+ --project-root '<working_dir>' \
--file package.json \
--approved-js-dependency "<package>@<exact-version>" \
[--approved-js-dependency "<another-package>@<exact-version>" ...]
diff --git a/plugins/mobile-apps/shared/references/offline-profile-reconciliation.md b/plugins/mobile-apps/shared/references/offline-profile-reconciliation.md
index 97ff1e7ef..86f8787f6 100644
--- a/plugins/mobile-apps/shared/references/offline-profile-reconciliation.md
+++ b/plugins/mobile-apps/shared/references/offline-profile-reconciliation.md
@@ -20,8 +20,13 @@ There are two related-but-distinct offline checks — do not confuse them:
## The delta check
+Apply [app-working-directory.md](app-working-directory.md) before project reads.
+Keep the owner's resolved absolute `working_dir` for checks, helper handoffs,
+file tools, and retries; do not rediscover a root in a child invocation.
+
```bash
-node "${PLUGIN_ROOT}/scripts/offline-profile-delta.js" [--project-root <path>]
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
+node "${PLUGIN_ROOT}/scripts/offline-profile-delta.js" --project-root '<working_dir>'
```
Purely local and deterministic — no `az` token, no Dataverse call — so it is safe and
@@ -31,6 +36,16 @@ stdout; exit `0` when the comparison ran (branch on `status`), exit `1` on a fat
(bad args, an explicit `--manifest`/`--profile` path that doesn't exist, or an
unreadable/invalid JSON file).
+Capture the exit status and stdout/stderr before dispatching on `status`.
+Any non-zero exit, `status: error`, missing/malformed JSON, or unknown status
+stops reconciliation: surface the diagnostic, do not invoke mutation helpers,
+and do not continue to a clean success summary. Schema edits already applied
+are not rolled back: record `offline_reconciliation: failed` and preserve
+`offlineRetirement` outcomes in memory-bank, then return `DONE_WITH_CONCERNS`.
+If no edits were applied, return `BLOCKED`. Apply the same failure handling to
+the re-check after helper execution; an unreadable profile is never evidence
+of `not-applicable` or `in-sync`.
+
| `status` | Meaning | What to do |
|---|---|---|
| `no-manifest` | No Dataverse schema in the project (connectors-only, or data model not applied). | Nothing to reconcile. Continue silently. |
@@ -48,6 +63,18 @@ A `delta` result carries:
- `columnBaselineMissing[]` — profiled tables whose snapshot predates the `schemaColumns`
baseline (see below). Column delta can't be computed for these; treat as advisory only.
+### Retirement outcomes are independent
+
+This checker detects additions, not excess profile tables or completed removals.
+Preserve the per-table `offlineRetirement` outcomes from
+[data-source-removal.md](data-source-removal.md) and prior memory-bank entries.
+None of `in-sync`, `no-manifest`, or `no-profile` clears a pending retirement.
+Report pending decisions/migrations even when the addition check needs no work;
+do not silently delete profile items or edit the local snapshot to simulate a
+server change. Only approved retention or verified profile migration resolves
+that pending outcome. A failure to read/verify the profile is not evidence of
+`not-applicable`.
+
---
## The `schemaColumns` baseline (why column delta is precise, not noisy)
@@ -87,14 +114,43 @@ default = update now):
> - **Yes — update the offline profile (recommended)**
> - Skip — I'll run it later (it will be re-checked at `/deploy`)
-On **Yes**, apply in this order (both are non-interactive when the target is explicit):
+On **Yes**, apply in this order using the scoped handoffs below. Reuse the exact
+approved scope; unresolved row filters or profile details still use the helper's
+normal approval gate. The initial prompt is not blanket profile-write consent.
1. For each `missingTables[]` entry, read and execute
`${PLUGIN_ROOT}/skills/add-table-to-offline-profile/SKILL.md` with
- `--table <logicalName>` (or `--all-new` to add them all at once).
+ `--working-dir '<working_dir>' --table <logicalName>`.
2. For each `tablesWithNewColumns[]` entry, read and execute
`${PLUGIN_ROOT}/skills/edit-offline-profile/SKILL.md` with
- `--table <logicalName> --columns add:<comma-separated newColumns>`.
+ `--working-dir '<working_dir>' --table <logicalName> --columns add:<comma-separated newColumns>`.
+
+### Scoped helper handoffs
+
+Pass this invocation context with **each** direct-read helper execution:
+
+```text
+Context:
+ MOBILE_APP_ORCHESTRATING=1
+ orchestrator: <current reconciliation owner>
+ working_dir: <owner's resolved absolute working_dir>
+ phase: implementation
+ approved_scope: <exact environment/profile identity, target logical table, and approved filter/column delta>
+
+Arguments for add-table-to-offline-profile:
+ --working-dir '<working_dir>'
+ --table "<logicalName>"
+
+Arguments for edit-offline-profile:
+ --working-dir '<working_dir>'
+ --table "<logicalName>"
+ --columns "add:<comma-separated newColumns>"
+```
+
+Never send `--all-new` as a replacement for an explicitly approved table set.
+Carry the same root, profile identity, and narrowed scope into nested helpers.
+`--plan-only` or a planning-phase handoff returns a proposal without calling
+mutation helpers; a marker or earlier schema approval cannot override it.
Re-run the delta check afterward; expect `in-sync`. Surface any remaining `delta` as a
concern rather than looping.
diff --git a/plugins/mobile-apps/shared/shared-instructions.md b/plugins/mobile-apps/shared/shared-instructions.md
index 1b5bbba10..07da75ed3 100644
--- a/plugins/mobile-apps/shared/shared-instructions.md
+++ b/plugins/mobile-apps/shared/shared-instructions.md
@@ -4,6 +4,54 @@
All skills reference this single file. When new shared instructions are added, update this file only — no changes needed to individual skills.
+## Data-source invocation scope
+
+Read this shared file before any workflow commands or app/cloud writes. If it
+cannot be loaded, STOP and report the missing prerequisite; do not proceed from
+a remembered or copied fragment. Before data-source work, bind the invocation through
+[app-working-directory.md](references/app-working-directory.md) before reading
+even the minimal local app markers. A child's launch directory is not its app root.
+
+Resolve the current requested operation before discovery or mutation: schema
+change/new binding, retained-source refresh, retirement, or sample seeding.
+An existing plan or inventory is context, not permission to replay every row.
+Standalone calls keep the data workflow's own approval and validation gates.
+They do not start a full-app integration wizard or automatically edit screens.
+
+For every data child handoff, including routers and retries, pass
+`MOBILE_APP_ORCHESTRATING=1`, the owning `orchestrator`, absolute `working_dir`,
+current `phase`, and exact `approved_scope` with supplied answers. The marker is
+invocation-scoped: do not persist it, rely on a prior shell export, or infer
+approval from a flag alone. Approved children reuse that same current scope and
+return to their owner; expanded or conflicting scope returns `NEEDS_CONTEXT`.
+Older callers without a complete approved handoff must establish current scope
+through the leaf's approval gate rather than silently applying the saved plan.
+
+`--plan-only` or a planning-phase handoff never authorizes mutating leaves,
+connection creation, generated services, seeding, or schema writes.
+Return the proposal before implementation; only a
+workflow's explicit plan-document approval may save planning documents.
+Propagate the mode and current scoped context through routers; missing or
+conflicting context returns `NEEDS_CONTEXT` before mutation.
+
+For proposal-only environment context, read the selected `power.config.json`
+environment ID and reuse matching complete caller context, or run
+`resolve-environment.js <selected-environment-id> --no-cache --require-tenant`
+from the owner's absolute working directory. This mode may read existing
+identity metadata but does not persist environment/auth caches, change telemetry
+routing, or replay pending telemetry. It is not a forced-fresh metadata read.
+Require a matching environment ID, HTTPS URL, and tenant; conflicting or still
+incomplete context returns `NEEDS_CONTEXT` after bounded read-only recovery.
+The ordinary, configuration-persisting resolver remains forbidden before
+implementation approval, including `--plan-only` and planning-phase child
+calls. Do not remove flags or redirect resolver output into app configuration
+to recover a planning failure. Scratch planning artifacts are allowed.
+
+For scoped Dataverse proposals, follow
+[dataverse-change-planning.md](references/dataverse-change-planning.md).
+It reuses creation's compact-evidence helpers without importing the create
+wizard or its approval gates into setup/standalone data planning.
+
---
## Version Check
@@ -27,14 +75,14 @@ summary when a measured run was created:
```bash
node "${PLUGIN_ROOT}/scripts/emit-telemetry-checkpoint.js" \
- --begin "<skill-name>" --project-root "<working_dir>" || true
+ --begin "<skill-name>" --project-root '<working_dir>' || true
```
A nested skill uses the supplied run ID and caller span by adding `--run-id`
and `--parent-span-id`; its returned span is a new skill invocation. Pass both
IDs as orchestration context when invoking another Skill or Task, not as Power
Apps CLI flags. Never infer a parent from a process or session ID. On resume,
-use `--resume "<skill-span-id>" --run-id "<run-id>" --project-root "<working_dir>"`
+use `--resume "<skill-span-id>" --run-id "<run-id>" --project-root '<working_dir>'`
instead of starting a second run, then replace `SKILL_SPAN_ID` with the newly
returned span ID. Resume is valid only after `needs_context`; it creates a new
immutable attempt in the same run. Each attempt can have only one retry;
@@ -55,11 +103,11 @@ that same span afterward:
node "${PLUGIN_ROOT}/scripts/emit-telemetry-checkpoint.js" \
"<skill-name>|<checkpoint-name>|started" \
--run-id "$RUN_ID" --parent-span-id "$SKILL_SPAN_ID" \
- --project-root "<working_dir>" || true
+ --project-root '<working_dir>' || true
node "${PLUGIN_ROOT}/scripts/emit-telemetry-checkpoint.js" \
"<skill-name>|<checkpoint-name>|completed" \
--run-id "$RUN_ID" --span-id "$STEP_SPAN_ID" \
- --project-root "<working_dir>" || true
+ --project-root '<working_dir>' || true
```
For one foreground command, prefer the wrapper so timing and outcome come from
@@ -70,7 +118,7 @@ command string. Use a real executable or `node <script>` on Windows, not a
```bash
bash "${PLUGIN_ROOT}/scripts/run-with-telemetry.sh" \
--execute "<skill-name>|<checkpoint-name>" --run-id "$RUN_ID" \
- --parent-span-id "$SKILL_SPAN_ID" --project-root "<working_dir>" \
+ --parent-span-id "$SKILL_SPAN_ID" --project-root '<working_dir>' \
-- node "<script-path>" "<argument>"
```
@@ -180,9 +228,18 @@ Note on `az`: on Windows where it is installed as a `.cmd` shim and not on the b
**📋 [connector-reference.md](./connector-reference.md)**
-All non-Dataverse connectors require a connection ID or connection reference before `pa app add data-source`. Read this before any `/add-*` connector skill. Always run `/list-connections` first to create a supported connection, reuse a caller-provided connection ID, or resolve a solution connection reference.
+All non-Dataverse connectors require a connection ID or connection reference
+before `pa app add data-source`. Read this reference before implementing
+any `/add-*` connector operation.
----
+Resolve connections only in the approved implementation phase, before adding
+the data source.
+Reuse a supplied connection ID or reference for the confirmed connector/environment;
+invoke `/list-connections` only when lookup or creation is needed.
+Do not invoke it during planning, `--plan-only`, cancellation, or removal-only work.
+Approved data child calls reuse their scoped handoff without repeating
+approval. Direct operational `/list-connections` requests keep their own workflow;
+they do not authorize unrelated app changes.
## Safety Guardrails
@@ -190,14 +247,14 @@ All non-Dataverse connectors require a connection ID or connection reference bef
Plugin-level hooks also run during unrelated plugin workflows, so every mutating mobile skill owns its validation:
-1. Track changed files by writer: the skill/subagents and preparation helpers versus trusted generators. Use a helper's returned `writtenFiles` when available; track removals separately, not as files to validate. Output from `pa app init` or `pa app add data-source` is excluded only when produced by that command and not modified afterward by the skill or its subagents. Newly generated does not mean manually written.
+1. Track changed files by writer: the skill/subagents and preparation helpers versus trusted generators. Use a helper's returned `writtenFiles` when available; track removals separately, not as files to validate. CLI-owned output means output actually produced by `pa app init`, `pa app add data-source`, `pa app refresh data-source`, or `pa app remove data-source` through the resolved `$PA` command. It is excluded only when produced by that command and not modified afterward by the skill or its subagents. Newly generated does not mean manually written.
2. Before returning success, pass each existing skill/helper-owned changed file explicitly:
```bash
node "${PLUGIN_ROOT}/scripts/validate-mobile-files.js" \
- --project-root "<working_dir>" \
- --file "<changed-file-1>" \
- --file "<changed-file-2>"
+ --project-root '<working_dir>' \
+ --file '<changed-file-1>' \
+ --file '<changed-file-2>'
```
3. On exit `2`, repair every finding and rerun. Exit `0` is required before `DONE`.
@@ -275,21 +332,25 @@ The CLI ships two binaries — grouped `pa` (preferred) and flat `power-apps` (f
Use the resolved `$PA` for Power Apps CLI commands, and direct `node` and `az` commands for the rest of the mobile-app plugin flow.
-Typical commands:
+Use [cli-binary.md](cli-binary.md) for command/flag translation and the owning
+skill for its approved operation. Do not duplicate the resolver or maintain a
+second command catalog here. Do not substitute a global binary or fetch another
+CLI to bypass a failure. Refresh/removal scope and postconditions are in
+[data-source-removal.md](references/data-source-removal.md).
-```bash
-$PA app init -t MobileApp --display-name '<name>' --environment-id <id> --non-interactive
-$PA app add data-source --connector <api> --connection-id <connection-id>
-$PA connection create --connector <api> --json
-$PA connection list-references --solution-id <solution-id> --json
-node scripts/resolve-environment.js [environment-id-or-url]
-```
+`npm run generate-schemas` is the separate template command that rebuilds
+`src/generated/connectorSchemas.ts`; it does not add/remove registrations or
+regenerate all model/service files. `npx --no-install tsc --noEmit` validates types; it is
+not a generator.
**Power Apps CLI required-argument rule:** when a skill invokes `$PA`, pass every value the skill already knows and run app-root verbs from the directory that contains `power.config.json`. In practice:
- `app init` and pre-project discovery commands can use `--environment-id` because there is no `power.config.json` yet.
-- After `power.config.json` exists, do **not** pass `--environment-id` to app-root verbs (`app add data-source`, `app push`, `connection list-datasets`, `connection list-tables`, `connection list-references`, `app add flow`, `app remove flow`, etc.). The CLI reads the environment and region from `power.config.json`; extra unregistered flags can fail command parsing.
-- Use `--non-interactive` only on commands whose required values are completely supplied and whose implementation supports non-interactive execution (`app init`, `app push`, `app add flow --flow-id`, `app remove flow --flow-id --force`, `connection create --connector` for SSO-eligible connectors, `app remove data-source --connector --name --force`). Grouped `pa` refuses a non-interactive removal without `--force`, so pass it only when the user asked for the removal. For `app add data-source`, prefer passing the connector-specific required flags and let the action layer request only the options it needs.
+- After `power.config.json` exists, do **not** pass `--environment-id` to app-root verbs (`app add data-source`, `app push`, `connection list-datasets`, `connection list-tables`, `connection list-references`, etc.). The CLI reads the environment and region from `power.config.json`; extra unregistered flags can fail command parsing.
+- Use `--non-interactive` only on commands whose required values are completely supplied and whose implementation supports non-interactive execution (`app init`, `app push`, `connection create --connector` for SSO-eligible connectors, `app remove data-source --connector --name --force`). Grouped `pa` refuses a non-interactive removal without `--force`, so pass it only when the user asked for the removal. For `app add data-source`, prefer passing the connector-specific required flags and let the action layer request only the options it needs.
+- Follow
+ [data-source-removal.md](references/data-source-removal.md), including verification
+ of the actual configuration/schemas/generated output even when the command exits 0.
- Prefer `--json` on list/discovery commands so downstream parsing is stable.
- For Dataverse table generation, pass `--connector dataverse`, `--table <table-logical-name>`, and `--org-url <environment-url>`.
- For non-Dataverse connectors, pass `--connector`, plus either `--connection-id` from `connection create` or `--connection-ref` from `connection list-references`; table-based connectors also need `--dataset` and `--table`.
@@ -306,7 +367,14 @@ node scripts/resolve-environment.js [environment-id-or-url]
In non-interactive mode (`--non-interactive` or CI), `auth switch` requires `--account <email>` when more than one account is cached; it will fail with an error listing the cached accounts if omitted.
-**Failure refresh policy (global):** if any `$PA` command exits non-zero, run `$PA auth status --json` to confirm the active account is correct. If the account needs to change, use `$PA auth switch`; if no account is cached, use `$PA auth login`. Only run `$PA auth logout` when the cache itself is corrupt or you want to remove all accounts. After correcting auth state, retry the same command once before further triage.
+**Failure refresh policy (global):** distinguish unknown-command/unknown-option
+failures from authentication failures. If the command is unsupported, report
+the error; do not guess aliases, strip safety flags, or install another CLI to
+conceal it. For an auth
+failure, run `$PA auth status --json` to confirm the active
+account. Use `$PA auth switch` or `$PA auth login` only when needed; `$PA auth logout` remains a last
+resort for a corrupt cache or explicitly requested sign-out. After correcting
+auth state, retry the same supported command once before further triage.
`az` calls work in bash on macOS/Linux directly. On Windows, wrap with `pwsh -NoProfile -Command "az …"` for consistency.
@@ -318,6 +386,9 @@ Apply these rules whenever an `az`, `npm`, `npx`, or `expo` command exits non-ze
### `$PA` (Power Apps CLI) failures (all commands)
+Unsupported command/option errors follow the failure policy above, not an auth
+retry. For authentication failures:
+
1. Run `$PA auth status --json` to verify the active account.
2. If the wrong account is active and the right one is cached, run `$PA auth switch --account <email>`.
3. If no account is cached or the right account is missing, run `$PA auth login [--account <email>]`.
@@ -372,13 +443,24 @@ When a skill is invoked from another skill (e.g., `/create-mobile-app` calls `/a
## Execution Style
- Do not announce steps before executing them. Proceed directly through the workflow.
-- Do not ask for permission to do read-only operations (Glob, Grep, Read, `node scripts/resolve-environment.js <environment-id-or-url>`).
+- Within the current approved phase, do not ask separately for read-only operations
+ (Glob, Grep, Read, `node scripts/resolve-environment.js <environment-id-or-url>`).
+ This does not authorize mutation or discovery outside the current data scope.
- For multi-step operations, use `manage_todo_list` to give the user visibility.
- After completing each step, update the memory bank — don't batch updates at the end.
### When to use `AskUserQuestion` — and when NOT to
-The user shouldn't have to read a question whose answer is mechanical. Each prompt costs a context switch. Apply this filter before calling `AskUserQuestion`:
+**Explicit approval gates take precedence** over the efficiency rules below:
+plan/mutation, data-source removal, and deployment gates require
+the user's explicit selection or approval. A recommended option, one viable
+path, stored preference, or deterministic recovery is not consent. Reuse approval
+only for the same current operation: already-approved scoped child calls do not repeat approvals,
+but expanded scope returns to the owner for a new decision.
+
+The user shouldn't have to read a question whose answer is mechanical. Apply this
+filter only to read-only work allowed in the current phase or decisions within
+an already-approved scope, never to skip a required approval gate:
| Situation | Action |
|---|---|
@@ -386,10 +468,13 @@ The user shouldn't have to read a question whose answer is mechanical. Each prom
| Auto-recoverable failure with a deterministic fix (e.g. probe alt names, retry with backoff, fall back to default) | **Auto-recover.** Surface only if recovery itself fails. |
| Detectable state (e.g. "is Metro running?") | **Probe first.** Use the available tool (MCP, file check, command) and only ask if the probe is inconclusive. |
| Display preference repeated across runs (e.g. "open in browser?") | **Use the persisted flag** (`memory-bank.md`, project config). Don't re-ask each time. |
-| One option is tagged `(Recommended)` AND alternatives are clearly worse | **Default to the recommended option** without prompting. If you must prompt (e.g. options have different costs), make the recommended option the default so an empty answer proceeds. |
+| One option is tagged `(Recommended)` AND alternatives are clearly worse | Explain the recommendation. If a decision requires consent or has different costs/scope, ask and wait for an explicit selection; the label does not approve it. |
| Genuinely ambiguous (multiple valid paths with real trade-offs the user must weigh) | **Ask.** This is the legitimate case. |
-The "Recommended (default-yes)" pattern: when you do call `AskUserQuestion`, structure the options so an empty/cancel answer auto-proceeds with the safe default — never block on a prompt the user can ignore.
+Cancellation or dismissal stops the pending operation without further work.
+An empty or ambiguous answer requires clarification or waiting; never convert
+it into approval or proceed with a recommended default. Preserve existing work
+and do not interpret stopping as permission to roll it back.
---
diff --git a/plugins/mobile-apps/skills/add-connector/SKILL.md b/plugins/mobile-apps/skills/add-connector/SKILL.md
index f80603da7..b7955271a 100644
--- a/plugins/mobile-apps/skills/add-connector/SKILL.md
+++ b/plugins/mobile-apps/skills/add-connector/SKILL.md
@@ -12,6 +12,42 @@ model: sonnet
# Add Connector (Generic)
+**App root:** before any project read or command, execute
+[app-working-directory.md](${PLUGIN_ROOT}/shared/references/app-working-directory.md).
+Use its resolved absolute `working_dir` for every shell call and file tool,
+including referenced commands and delegated skills; never inherit a prior `cd`.
+
+**Invocation scope:** follow [Data-source invocation scope](../../shared/shared-instructions.md#data-source-invocation-scope)
+before the workflow below. This skill owns connector bindings and generated
+services, not a full-app plan or screen implementation.
+
+For a standalone request, approve the current data-source delta before each
+mutation: the exact connector, environment, binding, and dataset/table or
+procedure as applicable. Connection creation needs explicit approval too.
+An approved child reuses only its owner's current scope; a missing choice may
+be resolved read-only, but a changed scope returns to that owner.
+For `--plan-only` or a planning-phase handoff, return the proposed bindings and
+unresolved choices before connection creation or `pa app add data-source`.
+Do not update the app plan, memory-bank, configuration, or generated files on
+that path; missing discovery access is not permission to create a connection.
+
+Action connectors do not imply Dataverse Data Model changes.
+
+**Cloud flows are not supported by mobile skills.** For a request to add,
+refresh, invoke, or remove a cloud-flow binding, report
+`BLOCKED: cloud-flow integration is not supported` and return before discovery
+or mutation. Do not treat a flow as a connector data source.
+
+**Removal branch:** after resolving invocation scope, if `--remove` or the approved scope
+requests removal, execute
+[data-source-removal.md](../../shared/references/data-source-removal.md) and return.
+Do not run Steps 1-6, connection creation, or `add-data-source` for a removal.
+
+**Refresh branch:** after resolving invocation scope, `--refresh` or an approved retained-source
+refresh executes [Refresh a retained source](../../shared/references/data-source-removal.md#refresh-a-retained-source)
+and returns before Steps 1-6. Preserve the exact `--data-source-name` and approved
+binding identity; do not create connections or run `add-data-source`.
+
Fallback skill for any connector not covered by a dedicated `/add-*` skill. For common connectors, prefer the dedicated skills:
- `/add-dataverse` — Dataverse tables
@@ -36,7 +72,11 @@ Check for `memory-bank.md` per [shared-instructions.md](${PLUGIN_ROOT}/shared/sh
Also confirm we're inside a Power Apps mobile app:
```bash
-test -f power.config.json && test -f app.config.js
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
+if [ ! -f power.config.json ] || [ ! -f app.config.js ]; then
+ echo "BLOCKED: working_dir is not an initialized app" >&2
+ exit 1
+fi
```
If either is missing, instruct the user to run `/create-mobile-app` first and stop.
@@ -49,14 +89,34 @@ If either is missing, instruct the user to run `/create-mobile-app` first and st
Otherwise, ask the user which connector they want to add. Browse available connectors: [Connector Reference](https://learn.microsoft.com/en-us/connectors/connector-reference/).
-**Before proceeding, check if the connector has a dedicated skill. If it does, delegate immediately and STOP:**
+Classify the requested operation before matching the delegation table. Dataverse
+actions/functions follow the discovery-only branch below directly, skipping
+connection lookup and data-source generation, never the table CRUD workflow.
+If the operation is ambiguous, ask before delegating.
+Use aliases only for routing; pass the exact discovered API ID to CLI commands.
+
+**Dataverse actions/functions: discover and return here.**
+
+```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
+$PA app find-dataverse-api --search '<operation-name>' --json
+```
+
+Surface the matching metadata and STOP this leaf with a clear note that this
+plugin adds Dataverse table CRUD, not actions/functions. Do not enter Step 3,
+invoke `/list-connections`, or generate a table service on this branch.
+If the user actually needs table CRUD, use the delegation table below.
+
+**Then check if this operation has a dedicated skill. If it does, delegate and STOP:**
| Connector API name | Delegate to |
| ----------------------- | ------------------ |
-| `sharepointonline` | `/add-sharepoint` |
-| `commondataservice` | `/add-dataverse` |
+| `sharepointonline`, `shared_sharepointonline` | `/add-sharepoint` |
+| `dataverse`, `commondataservice`, `shared_commondataservice`, `commondataserviceforapps`, `shared_commondataserviceforapps` (table CRUD only) | `/add-dataverse` |
-Invoke the appropriate skill with the same `$ARGUMENTS` and **do not continue this skill's workflow**.
+Invoke the appropriate skill with the same `$ARGUMENTS`, absolute `working_dir`,
+current request, owner/phase/scope, and proposal-only mode. **Do not continue this
+skill's workflow** or infer execution approval from this routing decision.
Common connector API names:
@@ -65,28 +125,32 @@ Common connector API names:
- `office365`, `office365users`, `office365groups`
- `sql`, `commondataservice`
-**Cloud flows are supported by the Power Apps CLI, but they are not connector data sources.** If the user wants to invoke an existing Power Automate cloud flow from the app, use the flow-specific commands instead of `pa app add data-source`:
-
-```bash
-$PA app list-flows --search '<flow-name-or-keyword>' --json
-$PA app add flow --flow-id <flow-guid> --non-interactive
-```
-
-To remove a flow later (only when the user asks; `pa` needs `--force` for a non-interactive removal):
-
-```bash
-$PA app remove flow --flow-id <flow-guid> --force --non-interactive
-```
-
-After `pa app add flow`, continue at Step 4 and inspect the generated service/model files the same way as connector data sources.
-
### Step 3 — Add Connector
**Telemetry checkpoint: `generate_connector_data_source`**
-**First, get the connection ID or connection reference** (see [connector-reference.md](${PLUGIN_ROOT}/shared/connector-reference.md)):
-
-Run the `/list-connections` skill with the connector API ID (for example `shared_office365users`). Capture the exact `connectionId` from `pa connection create`, or the `connectionRef` from `pa connection list-references` if the caller is solution-aware. If creation cannot complete in the CLI, direct the user to create one using the environment-specific Connections URL — construct it from the active environment ID in context (from `power.config.json` `environmentId` or a prior step):
+**First, preserve or resolve the connection binding** using
+[connector-reference.md](../../shared/connector-reference.md#step-1--get-a-connection):
+
+- Supplied `--connection-id` (or approved caller `connectionId`): reuse that exact
+ ID for the confirmed connector/environment; skip `/list-connections` and creation.
+- Supplied `--connection-ref` (or approved caller `connectionRef`): preserve that
+ reference for generation; skip `/list-connections` and creation. Do not replace
+ it with a newly selected ID.
+- Missing binding only: invoke `/list-connections` with the connector API ID
+ and current scoped context to resolve the missing value. Conflicting, blank,
+ or ambiguous supplied values return to the owner instead of creating a fallback.
+
+The commands below show the connection-ID path. For a reference binding,
+replace `--connection-id <connectionId>` with
+`--connection-ref '<connectionRef>'` on `add-data-source` only. Reuse supplied
+dataset/table/procedure choices and skip their discovery. If discovery is still
+needed and requires an ID, obtain the backing ID for the approved reference or
+the missing concrete choices; do not create another connection or pass an
+unsupported reference flag to a picker command.
+
+If creation was needed but cannot complete in the CLI, direct the user to the
+environment-specific Connections URL from `power.config.json` `environmentId`:
`https://make.powerapps.com/environments/<environment-id>/connections` → **+ New connection** → search for the connector → Create.
**Classify the connector before running `pa app add data-source`:**
@@ -103,39 +167,43 @@ Run the `/list-connections` skill with the connector API ID (for example `shared
Then run:
```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
$PA app add data-source --connector <apiId> --connection-id <connectionId>
```
**For table-based connectors, discover datasets and tables first:**
```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
$PA connection list-datasets --connector <apiId> --connection-id <connectionId> --json
$PA connection list-tables --connector <apiId> --connection-id <connectionId> --dataset '<dataset>' --json
```
-Present the datasets/tables to the user if they did not specify them. Add one data source per selected table:
+Present the datasets/tables to the user if they did not specify them. Approve
+the exact selected bindings before generation, or reuse matching current owner
+approval; proposal-only discovery returns without adding sources.
+Add one data source per approved table:
```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
$PA app add data-source --connector <apiId> --connection-id <connectionId> --dataset '<dataset>' --table '<table>'
```
**For SQL stored procedures, discover procedures only when the user asks to invoke a stored procedure rather than a table:**
```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
$PA connection list-procedures --connection-id <connectionId> --dataset '<database>' --json
-$PA app add data-source --connector shared_sql --connection-id <connectionId> --dataset '<database>' --procedure '<procedure>'
```
-**For Dataverse actions/functions rather than tables, discovery is available but this plugin only adds Dataverse table CRUD:**
+Approve the exact procedure binding before generation if it was not already in
+the current approved scope; proposal-only discovery returns without adding it.
```bash
-$PA app find-dataverse-api --search '<operation-name>' --json
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
+$PA app add data-source --connector shared_sql --connection-id <connectionId> --dataset '<database>' --procedure '<procedure>'
```
-Surface the matching operation metadata and STOP with a clear note that this plugin can add Dataverse table CRUD through `/add-dataverse`, but does not add Dataverse actions/functions.
-
-If the user actually needs Dataverse table CRUD, stop and delegate to `/add-dataverse`; do not add Dataverse tables from this generic connector skill.
-
**Parameter reference:**
- `--connector` — connector API ID (often `shared_<connector>`, e.g., `shared_office365users`). Use the exact value provided by the caller or connector docs.
@@ -152,7 +220,7 @@ If the user actually needs Dataverse table CRUD, stop and delegate to `/add-data
After adding, inspect the generated files. **Generated service files can be very large** — use `Grep` to find specific methods instead of reading the entire file:
```
-Grep pattern="async \w+" path="src/generated/services/<Connector>Service.ts"
+Grep pattern="async \w+" path="<working_dir>/src/generated/services/<Connector>Service.ts"
```
Files to check:
@@ -167,7 +235,9 @@ For each method the user needs:
2. Read just that method's section (use `offset` and `limit` parameters on Read)
3. Identify required vs optional parameters and response type
-Help the user write code using the generated service methods.
+Return the needed method signatures and usage guidance to the user or current
+owner. Do not change screens or launch another app workflow. Report generated
+service availability separately from consumer integration.
### Step 5 — Build
@@ -179,11 +249,18 @@ Help the user write code using the generated service methods.
`pa app add data-source` (Step 3) wrote new files into `.power/schemas/<connector>/`. The `connectorSchemas.ts` consumed by `app/_layout.tsx` is now stale — regenerate it before type-checking so the new connector is wired into the runtime schema map:
```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
npm run generate-schemas
npx --no-install tsc --noEmit
```
-Fix TypeScript errors before proceeding. Common gotcha: the new generated service may import a peer dependency you don't have installed yet — if so, `npx --no-install expo install <missing-package>` (NOT plain `npm install`, so versions stay Expo-compatible).
+Fix TypeScript errors before proceeding. If a generated service requires a missing
+dependency, inspect its package contents before choosing a repair. Do not install
+native packages absent from the template. Return a JS-only dependency requirement
+to the orchestrator for the approved exact-version
+[JavaScript dependency plan](../../shared/references/javascript-dependency-planning.md);
+for a standalone call obtain that approval before installation. Do not
+install an unplanned package merely to silence TypeScript.
Do NOT deploy yet — that's `/deploy`'s job after all data sources are added.
@@ -191,17 +268,18 @@ Do NOT deploy yet — that's `/deploy`'s job after all data sources are added.
Update `memory-bank.md` with: connector added, configured operations, build status.
-## Remove a data source or flow
+## Remove a data source
-If the user asks to remove a connector/table/stored procedure that this skill added, use the matching Power Apps CLI command with explicit arguments. The user's request is the confirmation: `pa` refuses a non-interactive removal without `--force` (drop `--force` on `power-apps`-only projects — see [cli-binary.md](${PLUGIN_ROOT}/shared/cli-binary.md)):
-
-```bash
-$PA app remove data-source --connector <apiId> --name '<data-source-or-table-name>' --force --non-interactive
-$PA app remove data-source --connector shared_sql --name '<procedure>' --procedure '<procedure>' --force --non-interactive
-$PA app remove flow --flow-id <flow-guid> --force --non-interactive
-```
+Apply the data-source invocation scope first for removals too. Identify consuming
+screens/services before deleting a dependency. Standalone removal must stop if
+it would leave broken consumers; report the required consumer work separately
+rather than automatically invoking another workflow.
-Then run `npm run generate-schemas` and `npx --no-install tsc --noEmit` before reporting success.
+Read and execute
+[data-source-removal.md](../../shared/references/data-source-removal.md) for the
+supported command, scope preflight, generated/config cleanup checks, and
+inventory reconciliation. This also covers sources originally added outside
+this skill; use the actual registered identity rather than assuming its name.
## Runtime connector handling
diff --git a/plugins/mobile-apps/skills/add-datasource/SKILL.md b/plugins/mobile-apps/skills/add-datasource/SKILL.md
index 9ff0a4c0a..a23dd92db 100644
--- a/plugins/mobile-apps/skills/add-datasource/SKILL.md
+++ b/plugins/mobile-apps/skills/add-datasource/SKILL.md
@@ -12,6 +12,11 @@ model: sonnet
# Add Data Source
+**Invocation scope:** follow [Data-source invocation scope](../../shared/shared-instructions.md#data-source-invocation-scope)
+before any project read or the workflow below. Resolve the absolute app root
+before reading memory-bank. Routing selects a data workflow, not implementation
+approval or a full-app integration workflow.
+
Router skill that understands the user's goal and connects them to the right data source — without requiring them to know Power Platform terminology.
## Workflow
@@ -34,21 +39,36 @@ Check for `memory-bank.md` per [shared-instructions.md](${PLUGIN_ROOT}/shared/sh
| User's goal | Best approach | Invoke |
|---|---|---|
+| Refresh generated services for a retained data source | Resolve the existing registration; preserve its platform and binding | Matching `/add-dataverse`, `/add-sharepoint`, or `/add-connector` with skill-only `--refresh --data-source-name "<registered-name>"` |
+| Stop using a registered table or connector in this app | Preserve the removal intent and resolve its existing registration type; do not infer a new data platform | Matching `/add-dataverse`, `/add-sharepoint`, or `/add-connector` with skill-only `--remove` |
| Store and manage structured business data (custom tables, forms, CRUD) | Dataverse is the platform's native database | `/add-dataverse` |
| Invoke an existing Dataverse action/function/API | Discover with `pa app find-dataverse-api`; this plugin only adds Dataverse table CRUD | `/add-connector` |
| Read lists, manage documents, integrate with SharePoint sites | SharePoint Online — dedicated skill with list creation support | `/add-sharepoint` |
-| Invoke an existing Power Automate cloud flow | Use `pa app list-flows` / `pa app add flow` support through the generic connector workflow | `/add-connector` |
+| Add, invoke, refresh, or remove a Power Automate cloud-flow binding | Cloud-flow integration is not supported by mobile skills | None; report the limitation and return without CLI calls |
| Anything else — Teams messages, Excel data, OneDrive files, Office 365 email/calendar, Azure DevOps, Copilot Studio, custom connectors | Generic connector (we'll figure out the right one) | `/add-connector` |
**Note:** Dedicated skills for Teams, Excel, OneDrive, Office 365, and Azure DevOps are planned for v1. Until then, `/add-connector` handles all of them — it covers every connector the platform supports and generates the same `src/generated/` service layer.
**Important routing rules:**
+- Forward the absolute `working_dir`, current request, owner/phase/scope,
+ supplied answers, and `--plan-only` or planning-phase status unchanged on every
+ handoff. Standalone calls use the selected leaf's own approval and verification
+ gates; a saved plan or router choice is not consent to mutate.
+- For refreshes, forward the exact registered identity, `--refresh`,
+ `--data-source-name`, proposal-only status, and current approved scope to the matching leaf.
+ Never convert a refresh into an add or request a new connection.
+ Conflicting add/refresh/remove scopes return to the owner for separate calls.
+- For removals, forward the approved identities and scope unchanged to the
+ matching leaf's removal branch; never turn "remove this source" into an add
+ command. Use [data-source-removal.md](../../shared/references/data-source-removal.md).
- When the user wants to **perform actions** (send an email, post a Teams message, create a file), route to `/add-connector` with the connector name as the argument (e.g., `/add-connector office365`, `/add-connector teams`).
-- When the user wants to **invoke a cloud flow**, route to `/add-connector` and tell it to use `$PA app list-flows --json` followed by `$PA app add flow --flow-id <flow-guid> --non-interactive` from the app root.
+- For a **cloud-flow binding** request, report `BLOCKED: cloud-flow integration is not supported` and return without discovery or mutation. Do not route it through a connector or Dataverse workflow.
- When the user wants to **invoke a Dataverse action/function/API** rather than table CRUD, route to `/add-connector` and tell it to use `$PA app find-dataverse-api --search '<operation-name>' --json`; then stop and explain that this plugin only adds Dataverse table CRUD.
- When the user wants to **store or query structured business data** with custom schema, route to `/add-dataverse`.
-4. If the user wants multiple capabilities, invoke each skill in sequence.
+4. If the approved scope includes multiple capabilities, invoke each skill in
+ sequence and return the combined results to the user or current owner. Do not independently
+ expand a connector request into schema or screen changes.
### When the User Isn't Sure
diff --git a/plugins/mobile-apps/skills/add-dataverse/SKILL.md b/plugins/mobile-apps/skills/add-dataverse/SKILL.md
index 4ebb2c99b..1a66a8f32 100644
--- a/plugins/mobile-apps/skills/add-dataverse/SKILL.md
+++ b/plugins/mobile-apps/skills/add-dataverse/SKILL.md
@@ -2,7 +2,7 @@
name: add-dataverse
description: Use when the user wants to add Dataverse tables (existing or new) to a Power Apps mobile app, extend an existing Dataverse table with new columns, or apply an approved data model plan.
user-invocable: true
-allowed-tools: Read, Edit, Write, Grep, Glob, Bash, AskUserQuestion, EnterPlanMode, ExitPlanMode, Task
+allowed-tools: Read, Edit, Write, Grep, Glob, Bash, AskUserQuestion, EnterPlanMode, ExitPlanMode, Task, Skill
model: opus
---
@@ -12,9 +12,33 @@ model: opus
# Add Dataverse
+**App root:** before any project read or command, execute
+[app-working-directory.md](${PLUGIN_ROOT}/shared/references/app-working-directory.md).
+Use its resolved absolute `working_dir` for every shell call and file tool,
+including referenced commands and delegated skills; never inherit a prior `cd`.
+
+**Invocation scope:** follow [Data-source invocation scope](../../shared/shared-instructions.md#data-source-invocation-scope)
+before the workflow below. Standalone calls use this skill's own data-delta
+approval and verification; do not start a full-app plan or screen workflow.
+
+An existing plan alone does not mean it includes or approves the new request;
+never replay the old Data Model instead of resolving the requested delta.
+
+**Removal branch:** after resolving invocation scope, `--remove` or an approved app-binding
+removal executes
+[data-source-removal.md](../../shared/references/data-source-removal.md), then
+returns without entering Steps 1-9. Removing a plan row is not implemented by
+re-running table creation or by deleting Dataverse metadata. For a mixed edit,
+the owner adds/refreshes first and invokes removal separately after consumer edits.
+
+**Refresh branch:** after resolving invocation scope, `--refresh` or an approved service-only
+refresh executes [Refresh a retained source](../../shared/references/data-source-removal.md#refresh-a-retained-source)
+and returns before Steps 1-9. Preserve the exact `--data-source-name` and approved
+binding identity. Do not replay schema writes, publish, or run `add-data-source`.
+
Two paths:
-- **Existing tables only** — skip to Step 5 (just runs `pa app add data-source` per table)
+- **Existing tables only** — resolve the current scope in Steps 1–2, then skip schema writes and use Step 6 to add only missing approved bindings or refresh approved retained sources.
- **New / extended tables** — full workflow with Web API mutations in dependency order
## Workflow
@@ -27,12 +51,25 @@ Two paths:
Confirm Power Apps mobile app:
+For `--plan-only` or a planning-phase handoff, check the app files read-only and
+use the shared proposal-only environment-context rule. Use the same non-persisting
+lookup before approval in a normal invocation. Incomplete or conflicting context
+returns `NEEDS_CONTEXT` after read-only recovery; never remove the safety flags
+or redirect output into configuration to make planning succeed.
+
```bash
-test -f power.config.json && test -f app.config.js
-node "${PLUGIN_ROOT}/scripts/resolve-environment.js" "$(node -e \"console.log(require('./power.config.json').environmentId)\")"
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
+if [ ! -f power.config.json ] || [ ! -f app.config.js ]; then
+ echo "BLOCKED: working_dir is not an initialized app" >&2
+ exit 1
+fi
+node "${PLUGIN_ROOT}/scripts/resolve-environment.js" "<selected-environment-id>" --no-cache --require-tenant
```
-Capture the **environment URL** (`https://orgXXX.crm.dynamics.com`), **environment ID**, and **tenant ID** from `resolve-environment.js` — needed for Step 3. If only the environment URL is available, pass that URL instead of the ID.
+Read `<selected-environment-id>` from this app's `power.config.json`. Capture the
+**environment URL** (for example `https://contoso.crm.dynamics.com`),
+**environment ID**, and **tenant ID** from the resolver for Step 3. Use the
+owner's absolute `working_dir` for every command and artifact.
### Step 2 — Resolve plan
@@ -41,29 +78,90 @@ Capture the **environment URL** (`https://orgXXX.crm.dynamics.com`), **environme
Look for `native-app-plan.md` in the project root:
```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
test -f native-app-plan.md
```
+**Resolve the current request before consuming an existing plan.** A direct
+standalone invocation must compare its requested tables/columns/service
+changes with the existing plan and read-only live evidence. Present and approve
+that exact delta at Step 2.7 after shared planning validation, then save only
+the accepted plan changes before implementation.
+If the request adds nothing, verify the existing outcome and report a no-op;
+do not apply other pending rows. If intent or scope is missing, ask or return
+`NEEDS_CONTEXT` without mutation. An explicit request to apply the whole existing
+plan still requires approval of the reconciled operation set.
+For an approved child call, use only the supplied current `approved_scope`.
+In either case, `--plan-only` returns the proposal and STOPs before plan saving,
+approval-receipt creation, service generation, or Steps 3–9; a planning-phase
+caller has the same proposal-only boundary.
+
Before reading plan content, inspect `$ARGUMENTS` for the five fast-path
artifact flags in Step 2a. When all are present, only confirm
`native-app-plan.md` exists for hash validation; do not parse its Data Model
section or build operations/service lists from Markdown.
-**If present and `<operation_manifest_mode> = fallback`:** read the
+For all non-fast-path Dataverse proposals from `/setup-datamodel` or a standalone
+request, including an existing-plan delta, read and execute
+[dataverse-change-planning.md](../../shared/references/dataverse-change-planning.md).
+Use its scoped evidence/contract for the diagram, architect, or inline path.
+An approved child with `planning_snapshot`, `architect_evidence`, and
+`schema_contract` instead enters Step 2b to verify that supplied scope; it must
+not rediscover or re-approve it. New-binding requests use this planning path;
+service-only refreshes and retirements have already returned from their branches.
+
+Older callers, including existing `/edit-app`, may not supply the new structured
+handoff. Do not assume compact evidence or complete approval from the caller's
+name. Without a complete approved handoff, resolve the current requested delta
+and use this leaf's normal proposal and Step 2.7 approval path before execution.
+Resolve required invocation context first; a missing or conflicting child root
+still returns `NEEDS_CONTEXT` before project access. Never silently replay the
+saved plan or treat `--skip-planning` as consent.
+
+An approved legacy child without compact-planning artifacts keeps the supported
+Markdown/live-reconciliation path below only when its current request, absolute
+root, implementation phase, and exact approved delta are all established.
+Never use this legacy path to bypass a partial or invalid compact-planning
+handoff, or to skip setup/standalone proposal validation.
+
+**Legacy input only, if present and `<operation_manifest_mode> = fallback`
+without a shared scoped contract:** read the
`## Data Model` section. Extract:
- The target reconciliation table (`reuse` / `extend` / `create` / `adapt` / `defer` decisions and evidence)
- The Mermaid ER diagram (informational)
- The "Creation Order" tier list
- Every table referenced by `## Screens`, identity resolution, related-entity fields, forms, dashboards, or shared hooks, including standard reused tables such as `systemuser`, `contact`, and `account`
-Build `SERVICE_REQUIRED_TABLES` as the union of:
+For legacy callers without scoped planning artifacts, build
+`SERVICE_REQUIRED_TABLES` as the union of:
1. every non-deferred row in Target Reconciliation (`reuse`, `extend`, `create`, or `adapt`);
2. every table in Creation Order;
3. every table named by screen/hook data requirements.
+Keep this full service inventory as retained context. Only the current approved
+delta and its necessary dependencies enter live schema reconciliation. With a
+complete approved legacy handoff, proceed to Step 3 after this initialization;
+do not repeat proposal Steps 2.5–2.7 or require new compact artifacts from that
+owner. A planning-phase caller still returns without implementation.
+
+For the shared scoped path, use the normalized contract's non-deferred
+`serviceRequired` declarations instead. Keep the broader existing-app service
+inventory as retained context, not a registration or mutation work list.
+
**Hard rule:** `reuse` means "do not mutate schema"; it does **not** mean "skip generated service." If app code reads or writes a reused table, that table must be in `SERVICE_REQUIRED_TABLES`.
Carry forward any `adapt` (auto-renamed) and `defer` (out-of-scope this run) decisions with their recorded reasons, and apply the alias map to every name you use. A data-modelling conflict never halts this skill — it resolves to `adapt` or `defer` and is reported in Step 9.
+This classification belongs to planning: after approval, a changed decision
+returns to the owner for revision/approval before any write.
+
+For a scoped handoff, restrict schema writes to the exact `approved_scope` delta;
+unaffected plan rows are context, not permission to replay their mutations.
+Apply the same restriction to the newly approved standalone request delta.
+Retain the full required-service set for existing screens. If reconciliation
+would change an approved name, storage target, or screen contract, return the
+proposed adaptation to the owner (or standalone user) before writing. Report
+dependent consumer changes for separate approval; do not silently rename
+underneath the app or treat data approval as permission to edit screens.
**If absent:** check `$ARGUMENTS` for diagram hints (`*.png`, `*.jpg`, `*.jpeg` filename, `erDiagram` keyword, `||--o{` cardinality syntax).
@@ -76,7 +174,13 @@ Carry forward any `adapt` (auto-renamed) and `defer` (out-of-scope this run) dec
> (b) Let the data-model-architect agent analyze and propose one (default)
> (c) Cancel — I'll plan it elsewhere first"
- Default the answer to (b) so empty/cancel input auto-proceeds. The 99% case (user gave a description but no diagram) skips this prompt entirely.
+ Recommend (b), but wait for an explicit answer. Empty input is not approval;
+ cancellation stops the workflow without planning or mutation. A supplied
+ description may select the read-only architect path, not approve its result.
+
+With an existing plan and a new request, take the same diagram or architect/
+inline proposal path for only that delta, then Step 2.7. Do not skip validation
+because a saved plan exists.
#### Step 2a — Approved operation-manifest fast path
@@ -104,6 +208,34 @@ exact validation errors and return control to the orchestrator. Never jump to
Step 4 without Step 2 initialization, partially trust a candidate, or mix its
operations with agent-derived operations.
+For an approved implementation candidate, continue to Step 3 and the existing
+Step 3c manifest validation; skip Steps 2b and 2.5–2.7. Supplied execution
+artifacts never override `--plan-only` or a planning-phase caller: those calls
+return the proposal without entering Step 3.
+
+#### Step 2b — Approved scoped planning context
+
+Enter only for a shared compact-planning handoff, not an approved legacy child
+or a creation fast-path candidate. The data owner passes the
+absolute `planning_snapshot`, `architect_evidence`, and `schema_contract` paths
+plus accepted operations, `contract_sha256`, and `plan_sha256` in
+`approved_scope`. Require all fields and real implementation approval;
+partial, missing, changed, or mismatched context returns `NEEDS_CONTEXT` to
+the owner, never a fallback to whole-plan replay or fresh approval inference.
+
+Before Step 3, compare SHA-256 of the contract and final plan file bytes with
+those frozen approval hashes, verify the selected target identity, and run the
+shared compact-evidence and decision validators against the supplied artifacts.
+Do not overwrite either hash to accept changed files. Read mutation intent
+from the normalized scoped contract, not historical Markdown rows; retain
+unaffected generated services. A proposal-only caller returns without mutation.
+
+After success, keep `<operation_manifest_mode> = fallback` for the existing
+standalone execution/reconciliation path, skip Steps 2.5–2.7, and proceed to
+Step 3. Planning evidence is not fresh write evidence: Step 4 still reconciles
+only this accepted delta and its required dependencies against the live target.
+Do not fabricate a `create-mobile-app` receipt or partially supply Step 2a flags.
+
### Step 2.5 — Path A: Parse user-provided diagram
Used when the user has an existing diagram from another tool (Visio, dbdiagram.io, screenshot, hand-drawn).
@@ -114,7 +246,7 @@ Accept three input formats:
|---|---|
| **Image path** (`*.png` / `*.jpg` / `*.jpeg`) | Use `Read` on the file path. The vision-capable model extracts entities, columns, relationships. |
| **Mermaid syntax** | User pastes a `erDiagram` block in chat. Parse the entities, columns, and `\|\|--o{` cardinalities directly. |
-| **Text description** | User types a structured description ("Account has many ServiceVisits; each ServiceVisit has many WorkItems and Photos"). Spawn `data-model-architect` agent in `parse-only` mode with the text as input. |
+| **Text description** | Parse the requested entities/relationships as intent, then use the shared snapshot-only architect handoff with the text and scoped compact evidence. |
Whichever format, normalize into the same structure used by the planner agent:
@@ -128,29 +260,55 @@ tables:
relationships: [...]
```
-Then:
-1. Query existing Dataverse (Step 4 logic) to mark each table as `new`, `modified`, or `reused`.
-2. Generate a Mermaid ER diagram from the parsed structure for visual confirmation.
-3. Present back to the user via `EnterPlanMode` for approval.
-4. On `ExitPlanMode`, write the approved data model into `native-app-plan.md` `## Data Model` section (creating the file if it doesn't exist).
-5. Continue to Step 3.
+Then follow the shared planning workflow to generate `_dm_section.md` with
+the Mermaid diagram and a normalized `.tmp/dataverse-schema-contract.json`
+from compact evidence. Run its decision validation for the diagram just as for
+an architect result, then continue to Step 2.7. Do not save the live plan here.
### Step 2.6 — Path B: Spawn architect agent
-If the user picked Path B (or the user-provided diagram parse failed), spawn the `mobile-app:data-model-architect` agent via `Task` (the `mobile-app:` plugin-name prefix is required) with the user's high-level requirements as input. The agent returns `_dm_section.md`. Embed it in `native-app-plan.md`, present via `EnterPlanMode` for approval, then continue to Step 3.
-
-If they need new tables and refuse both paths, recommend they run `/setup-datamodel` (alias of this skill) explicitly, or `native-app-planner` for a full app-level plan. STOP if neither.
+If the user picked Path B, use the shared workflow's
+`mobile-app:data-model-architect` handoff with `Dataverse planning mode: required`,
+the absolute snapshot/compact-evidence paths, the scoped request, and planning/
+proposal-only context. Require `_dm_section.md` and the normalized contract.
+If the host cannot spawn agents, produce both inline from that same evidence.
+Use the shared structured-signal recovery before generic retries. A diagram
+parse failure requires resolving the intended entities, not silently inventing
+a replacement model.
+
+If they need new tables and refuse both paths, recommend `/setup-datamodel` for
+data-only planning and stop. Do not start another workflow without a new request.
+
+### Step 2.7 — Validate and approve the standalone delta
+
+For every new standalone proposal, require exit `0` from
+`validate-dataverse-planning-decisions.js` for the current normalized contract
+and snapshot before presenting the existing approval gate. This includes
+diagrams, architect results, inline fallbacks, and edits to an existing plan.
+If either `--plan-only` or a planning-phase caller applies, return the validated
+proposal and STOP before saving the live plan or granting execution permission.
+
+Otherwise show the exact delta and its concerns with `EnterPlanMode`. Approval
+saves only that delta into `native-app-plan.md`, preserving unaffected sections.
+Freeze the shared planning paths, accepted operations, and current
+`contract_sha256` / `plan_sha256` as this invocation's approved context; verify
+it using Step 2b before implementation. Revision repeats planning validation;
+cancellation stops without saving or mutation. Already-approved scoped child
+calls and valid creation fast-path calls do not repeat this gate.
### Step 3 — Setup Dataverse Web API auth
-Required only if creating or extending tables. Skip to Step 5 for read-only `pa app add data-source`.
+Required only after implementation approval. For approved existing-table
+bindings with no schema mutation, skip to Step 6, not the schema-write phases.
#### Step 3a — Environment consistency check
The Power Apps CLI (`$PA`) and `az` authenticate independently — they can point to different accounts. Verify `power.config.json` resolves and `az` can token for the target tenant before making any Dataverse API calls:
```bash
-ENV_JSON=$(node "${PLUGIN_ROOT}/scripts/resolve-environment.js" "$(node -e \"console.log(require('./power.config.json').environmentId)\")")
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
+ENVIRONMENT_ID=$(node -p "require('./power.config.json').environmentId") || exit 1
+ENV_JSON=$(node "${PLUGIN_ROOT}/scripts/resolve-environment.js" "$ENVIRONMENT_ID") || exit 1
echo "$ENV_JSON"
az account show --query "{user: user.name, tenant: tenantId}" -o json
```
@@ -163,6 +321,7 @@ Compare the resolved environment URL with `<envUrl>` captured in Step 1. If they
>
> The Dataverse API token comes from `az`, which must target the same tenant as the selected environment. Run:
> ```bash
+> cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
> az login --tenant <tenant-id> # switch az to the right tenant
> ```
> Then re-run `/add-dataverse`."
@@ -172,6 +331,7 @@ Compare the resolved environment URL with `<envUrl>` captured in Step 1. If they
#### Step 3b — Acquire token
```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
az account show --query "user.name" -o tsv
```
@@ -180,6 +340,7 @@ If empty, instruct `az login` and stop.
**Script invocation contract — read this once, all subsequent calls in this skill follow it:**
```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
node "${PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> <METHOD> <apiPath> \
[--body '<json>'] [--include-headers] \
--tenant-id '<tenantId-from-resolve-environment>'
@@ -197,6 +358,7 @@ If the tenant is unknown, omit `--tenant-id` — discovery still works, it is ju
Acquire a Dataverse access token and verify connectivity:
```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
node "${PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> GET WhoAmI \
--tenant-id '<tenantId-from-resolve-environment>'
```
@@ -207,6 +369,7 @@ priority over shell environment variables and Azure account discovery.
`WhoAmI` is the Dataverse identity endpoint — capital W/A/I (case-sensitive). The response gives `UserId`, `BusinessUnitId`, `OrganizationId` but **does NOT include the publisher prefix**. To get the publisher prefix, query the solution's publisher (defaults to `Default`; pass a different solution name if the env uses a custom solution):
```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
node "${PLUGIN_ROOT}/scripts/detect-publisher-prefix.js" <envUrl> [solutionName] \
--tenant-id '<tenantId-from-resolve-environment>'
# solutionName defaults to "Default" if omitted
@@ -224,18 +387,19 @@ the resolved environment, tenant (when available), publisher, solution, current
plan bytes, structured-schema bytes, and fresh reconciliation bytes:
```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
node "${PLUGIN_ROOT}/scripts/build-dataverse-operation-manifest.js" \
- --validate "<operation-manifest-path>" \
- --contract "<schema-contract-path>" \
- --approval-receipt "<approval-receipt-path>" \
- --reconciliation "<execution-reconciliation-path>" \
- --plan "<working_dir>/native-app-plan.md" \
+ --validate '<operation-manifest-path>' \
+ --contract '<schema-contract-path>' \
+ --approval-receipt '<approval-receipt-path>' \
+ --reconciliation '<execution-reconciliation-path>' \
+ --plan '<working_dir>/native-app-plan.md' \
--environment-id "<environmentId>" \
--env-url "<envUrl>" \
--tenant-id "<tenantId>" \
--publisher-prefix "<customizationprefix>" \
--solution "<solution-uniquename>" \
- --publish-checkpoint "<publish-checkpoint-path>" \
+ --publish-checkpoint '<publish-checkpoint-path>' \
--require-executable
```
@@ -278,7 +442,12 @@ summary.
Do not use the custom-table list as the source of truth, and do not issue one request per table. Fetch **every** plan entry (`Reuse`, `Extend`, or `Create`) — including standard and managed dependencies — in a **single** filtered query that also expands their columns:
+On the scoped planning path, "every plan entry" means only the approved
+normalized contract and its required dependencies, never all saved-plan rows.
+Do not substitute the planning snapshot or inventory cache for this live read.
+
```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
node "${PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> GET \
"EntityDefinitions?\$select=MetadataId,LogicalName,SchemaName,IsCustomEntity,IsManaged,IsCustomizable,CanCreateAttributes,PrimaryIdAttribute,PrimaryNameAttribute&\$filter=LogicalName eq '<table1>' or LogicalName eq '<table2>'&\$expand=Attributes(\$select=MetadataId,LogicalName,AttributeType,AttributeTypeName,RequiredLevel,IsManaged,IsCustomizable,IsPrimaryId,IsPrimaryName,SourceType,SourceTypeMask)" \
--tenant-id '<tenantId-from-resolve-environment>'
@@ -331,9 +500,10 @@ semantics. Before classifying any such existing column as compatible:
`<working_dir>/.tmp/derived-metadata-operations.json`, then run:
```bash
+ cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
node "${PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> \
BATCH-METADATA derived-reconciliation \
- --operations "$(cat <working_dir>/.tmp/derived-metadata-operations.json)" \
+ --operations "$(cat '<working_dir>/.tmp/derived-metadata-operations.json')" \
--tenant-id '<tenantId-from-resolve-environment>'
```
@@ -352,9 +522,10 @@ semantics. Before classifying any such existing column as compatible:
Boolean mappings must contain exactly values 0 and 1. Then run:
```bash
+ cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
node "${PLUGIN_ROOT}/scripts/validate-derived-metadata.js" \
- --expected "<working_dir>/.tmp/derived-metadata-expected.json" \
- --actual "<working_dir>/.tmp/derived-metadata-live.json"
+ --expected '<working_dir>/.tmp/derived-metadata-expected.json' \
+ --actual '<working_dir>/.tmp/derived-metadata-live.json'
```
5. A lookup is compatible only when its complete target set matches. Planned choice
@@ -410,13 +581,14 @@ For each non-empty phase, write just that phase's `operations` array to
manifest, then execute every phase with the same project-local atomic journal:
```bash
-EXECUTION_JOURNAL="<working_dir>/.tmp/dataverse-metadata-execution-journal.json"
-ALL_MANIFEST_OPERATIONS="<working_dir>/.tmp/dataverse-operation-all.json"
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
+EXECUTION_JOURNAL='<working_dir>/.tmp/dataverse-metadata-execution-journal.json'
+ALL_MANIFEST_OPERATIONS='<working_dir>/.tmp/dataverse-operation-all.json'
# Write the flattened operations from every manifest phase to ALL_MANIFEST_OPERATIONS once.
node "${PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> \
BATCH-METADATA "manifest-<phase-name>" \
- --operations "$(cat <working_dir>/.tmp/dataverse-operation-phase-<name>.json)" \
+ --operations "$(cat '<working_dir>/.tmp/dataverse-operation-phase-<name>.json')" \
--solution "<solution-uniquename>" \
--tenant-id "<tenantId>" \
--journal "$EXECUTION_JOURNAL" \
@@ -482,13 +654,14 @@ Bind the contract through that pre-existing receipt, then roll the existing
publish checkpoint forward:
```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
node "${PLUGIN_ROOT}/scripts/build-dataverse-operation-manifest.js" \
--roll-forward-checkpoint "$PUBLISH_CHECKPOINT" \
--previous-manifest "$OPERATION_MANIFEST" \
--journal "$EXECUTION_JOURNAL" \
--contract "$SCHEMA_CONTRACT" \
--approval-receipt "$APPROVAL_RECEIPT" \
- --plan "<working_dir>/native-app-plan.md" \
+ --plan '<working_dir>/native-app-plan.md' \
--output "$PUBLISH_CHECKPOINT" \
--environment-id "<environmentId>" \
--env-url "<envUrl>" \
@@ -514,10 +687,11 @@ computed dependencies have already crossed the exact derived-metadata barrier;
unsupported projections are explicit `defer` rows. After the `publish` phase succeeds, delete the publish checkpoint and invalidate the planning-only inventory cache:
```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
node -e "const checkpoint = process.argv[1]; if (checkpoint) require('node:fs').rmSync(checkpoint, { force: true });" \
"${PUBLISH_CHECKPOINT:-}"
if ! node "${PLUGIN_ROOT}/scripts/dataverse-inventory-cache.js" \
- --file "<working_dir>/.tmp/dataverse-inventory-cache.json" --invalidate; then
+ --file '<working_dir>/.tmp/dataverse-inventory-cache.json' --invalidate; then
printf 'NEEDS_RECOVERY: dataverse-inventory-cache\n' >&2
exit 2
fi
@@ -555,6 +729,7 @@ issues requests strictly one at a time in array order, stopping on the first
non-2xx response by default.
```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
node "${PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> \
BATCH-METADATA schema-writes \
--operations '<ordered-json-array>' \
@@ -586,6 +761,7 @@ Before each create, confirm the target name is actually free: name-prefix collis
Only re-probe a single name when Step 4's batch did not cover it (for example a rename candidate generated later in this step):
```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
node "${PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> GET \
"EntityDefinitions(LogicalName='<prefix>_<table>')?\$select=MetadataId,LogicalName,IsCustomEntity,IsManaged,IsCustomizable,CanCreateAttributes" \
--tenant-id '<tenantId-from-resolve-environment>'
@@ -717,9 +893,10 @@ For each `Create` decision, in **tier order** (Tier 0 → Tier 1 → Tier 2 →
**Solution targeting (HARD):** every Step 5 / 5b POST MUST pass `--solution <uniquename>` so Dataverse routes the new artifact into our solution rather than the unmanaged default. Read the solution name from `memory-bank.md` Power Platform context (captured in Step 3b). Without this flag, multi-project environments end up with cross-solution leakage and the foreign-collision class of bug returns. The script translates `--solution` to the `MSCRM.SolutionUniqueName` HTTP header.
-**Scratch files:** When writing request body JSON to disk (e.g. table definitions, column metadata, relationship payloads), always write to `<working_dir>/.tmp/`, never to `/tmp/`. Keeping request bodies project-local prevents cross-project writes and makes cleanup deterministic. Create the folder if it doesn't exist: `mkdir -p <working_dir>/.tmp`.
+**Scratch files:** When writing request body JSON to disk (e.g. table definitions, column metadata, relationship payloads), always write to `<working_dir>/.tmp/`, never to `/tmp/`. Keeping request bodies project-local prevents cross-project writes and makes cleanup deterministic. After the per-call root guard, create the folder if it doesn't exist: `mkdir -p .tmp`.
```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
node "${PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> POST EntityDefinitions \
--body '<json-body-with-all-columns-inline>' \
--solution '<solution-uniquename-from-memory-bank>' \
@@ -800,6 +977,7 @@ For each `Extend` decision, POST a new column to the existing table.
> **⚠️ Table-level pre-flight (HARD — required for idempotent re-runs).** Reuse the complete attribute snapshot fetched for this table in Step 4. If the table was discovered only during collision recovery, or no current snapshot exists, fetch all attributes exactly once:
>
> ```bash
+> cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
> node "${PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> GET \
> "EntityDefinitions(LogicalName='<table>')/Attributes?\$select=MetadataId,LogicalName,SchemaName,AttributeType,AttributeTypeName,RequiredLevel,IsManaged,IsCustomizable,IsPrimaryId,IsPrimaryName" \
> --tenant-id '<tenantId-from-resolve-environment>'
@@ -818,6 +996,7 @@ For each `Extend` decision, POST a new column to the existing table.
After the complete comparison passes, POST the missing-column queue **one column at a time, sequentially** (no `$batch`; always pass `--solution`):
```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
node "${PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> POST \
"EntityDefinitions(LogicalName='<table>')/Attributes" \
--body '<column-json>' \
@@ -868,6 +1047,7 @@ Column shapes that have non-obvious gotchas (handle carefully):
Invocation (apiPath is `RelationshipDefinitions`, body via `--body`, always pass `--solution`):
```bash
+ cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
node "${PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> POST \
RelationshipDefinitions \
--body '<json-body-from-skeleton-above>' \
@@ -997,6 +1177,7 @@ https://learn.microsoft.com/power-apps/developer/data-platform/specialized-colum
**Do NOT use the `CreateEntityKey` action route.** In practice it can return 404 depending on route shape / environment. The reliable metadata route is POSTing to the table's `Keys` navigation collection:
```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
node "${PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> POST \
"EntityDefinitions(LogicalName='<table>')/Keys" \
--body '<entity-key-json>' \
@@ -1018,6 +1199,7 @@ Body skeleton:
**Pre-flight each key before POST** so re-runs are idempotent. A key can only pre-exist on a table that already existed at Step 4, so for a table created in this run, skip straight to the POST. Otherwise read `Keys` from that table's Step 4 snapshot. Query it directly only when the snapshot did not cover that table:
```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
node "${PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> GET \
"EntityDefinitions(LogicalName='<table>')?\$select=LogicalName&\$expand=Keys(\$select=SchemaName,KeyAttributes,EntityKeyIndexStatus)" \
--tenant-id '<tenantId-from-resolve-environment>'
@@ -1051,9 +1233,20 @@ When `<operation_manifest_mode> = valid`, set `SERVICE_REQUIRED_TABLES` from
names and exclude only explicit deferred rows. Service generation remains
sequential outside BATCH-METADATA.
-For each table in `SERVICE_REQUIRED_TABLES` (regardless of reuse/extend/create), generate the TS layer from the app root. Do not derive this list from Creation Order alone because reused tables are intentionally absent from creation tiers. The CLI reads the environment ID from `power.config.json`; pass the environment URL resolved earlier in the skill:
+For each table in `SERVICE_REQUIRED_TABLES` (regardless of reuse/extend/create),
+verify its registered service before deciding whether generation is needed.
+Preserve verified unchanged services outside the approved delta. For an approved
+refresh or a service affected by this run's approved schema changes, use
+[Refresh a retained source](../../shared/references/data-source-removal.md#refresh-a-retained-source)
+with the exact existing registration. Only an approved missing binding takes
+the add command below. A required unregistered service outside approved scope
+returns `NEEDS_CONTEXT`, not permission to register unrelated tables.
+Do not derive the service list from Creation Order alone because reused tables
+are intentionally absent from creation tiers. The CLI reads the environment ID
+from `power.config.json`; pass the environment URL resolved earlier in the skill:
```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
$PA app add data-source --connector dataverse --org-url <envUrl> --table <table-logical-name>
```
@@ -1068,8 +1261,9 @@ logical name. The verifier also accepts the legacy nested
`databaseReferences.default.cds` shape:
```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
node "${PLUGIN_ROOT}/scripts/verify-dataverse-services.js" \
- --project-root "<working_dir>" \
+ --project-root '<working_dir>' \
--manifest "$OPERATION_MANIFEST"
```
@@ -1097,6 +1291,7 @@ publish retry.
Only after **every** Step 5 metadata POST and **every** Step 6 `pa app add data-source` has returned successfully, publish so the new tables and columns are available to the runtime. `PublishXml` takes the same exclusive metadata lock as the create/extend calls — do not run it concurrently with anything from Steps 5 or 6.
```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
node "${PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> POST \
"PublishXml" \
--body "{\"ParameterXml\":\"<importexportxml><entities><entity>cr123_table1</entity><entity>cr123_table2</entity></entities></importexportxml>\"}" \
@@ -1111,8 +1306,9 @@ After a 2xx publish, invalidate the planning-only inventory cache before
verification so a later planning run cannot reuse pre-publication inventory:
```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
if ! node "${PLUGIN_ROOT}/scripts/dataverse-inventory-cache.js" \
- --file "<working_dir>/.tmp/dataverse-inventory-cache.json" --invalidate; then
+ --file '<working_dir>/.tmp/dataverse-inventory-cache.json' --invalidate; then
printf 'NEEDS_RECOVERY: dataverse-inventory-cache\n' >&2
exit 2
fi
@@ -1132,6 +1328,7 @@ standalone path's verified service list, not Creation Order alone. Use **one**
filtered query for the bounded set, not one request per table:
```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
node "${PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> GET \
"EntityDefinitions?\$select=LogicalName,DisplayName&\$filter=LogicalName eq '<table1>' or LogicalName eq '<table2>'" \
--tenant-id '<tenantId-from-resolve-environment>'
@@ -1185,17 +1382,26 @@ 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.
+During an edit with pending removals, preserve retiring entries until the
+removal branch verifies that their app bindings/services are gone. The owner
+then reconciles the final inventory; a shortened plan alone is not cleanup.
+Return the actual created/extended/reused table sets for this invocation to the
+user or current owner; historical manifest status is not evidence of creation
+in this invocation. Seeding must use an
+explicit approved allowlist excluding retirements, never this transitional
+inventory as its insertion scope.
+
### Step 7 — Inspect generated files
```text
-Glob: src/generated/services/*Service.ts
-Glob: src/generated/models/*Model.ts
+Glob: <working_dir>/src/generated/services/*Service.ts
+Glob: <working_dir>/src/generated/models/*Model.ts
```
For each table, check the generated service exposes the expected methods:
```text
-Grep pattern="async (create|getAll|getById|update|delete|upload|downloadFile|downloadImage)" path="src/generated/services/<Table>Service.ts"
+Grep pattern="async (create|getAll|getById|update|delete|upload|downloadFile|downloadImage)" path="<working_dir>/src/generated/services/<Table>Service.ts"
```
If the table has file or image columns, confirm the service includes `upload`, `downloadFile`, `downloadImage`, `deleteFileOrImage` — and the model exposes `<Table>FileColumnName` / `<Table>ImageColumnName` union types.
@@ -1258,6 +1464,7 @@ if (!upload.success) {
`pa app add data-source` (Step 5) wrote new files into `.power/schemas/<connector>/`. The `connectorSchemas.ts` consumed by `app/_layout.tsx` is now stale — regenerate it before type-checking, otherwise the new tables won't be wired into the runtime schema map and `tsc` will pass against an out-of-date snapshot:
```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
npm run generate-schemas
npx --no-install tsc --noEmit
```
@@ -1268,11 +1475,16 @@ Fix any errors. Common: missing peer dependencies — `npx --no-install expo ins
A schema change here (new table or new column) can leave an existing Mobile Offline Profile behind — new tables never sync to devices and new columns come down blank. Reconcile the profile with what you just created.
-**Skip this step entirely when `$ARGUMENTS` contains `--skip-planning`** (the orchestrator-invoked path). `/create-mobile-app`, `/setup-datamodel`, and `/edit-app` own offline reconciliation in their own flow, so running it here too would double-prompt.
+**Skip this step only for a valid scoped orchestrator handoff with
+`--skip-planning`** whose owner explicitly takes responsibility for offline
+reconciliation, as `/create-mobile-app` and `/setup-datamodel` do in their existing
+flows. Return the verified delta to that owner without double-prompting.
+The flag alone must not suppress standalone reconciliation.
Otherwise (manual `/add-dataverse`), run the local, no-network delta check:
```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
node "${PLUGIN_ROOT}/scripts/offline-profile-delta.js"
```
@@ -1282,7 +1494,7 @@ Branch on the JSON `status` per [offline-profile-reconciliation.md](${PLUGIN_ROO
|---|---|
| `no-manifest` / `no-profile` / `in-sync` | Continue to Step 9 silently. For `no-profile` (no offline profile exists) do not nag — the app may not use offline. |
| `error` | `offline-profile.json` is unreadable — the script prints `status: error` and **exits non-zero**. Do NOT treat this as an `/add-dataverse` failure (the tables are already created): surface the `error` string, **skip reconciliation** (never drive the update workflows against a corrupt file), and finish with `DONE_WITH_CONCERNS` telling the user to fix `offline-profile.json`. |
-| `delta` | Prompt the user (one `AskUserQuestion`, default = update now) to add the missing tables / new columns. For `missingTables[]`, read and execute `${PLUGIN_ROOT}/skills/add-table-to-offline-profile/SKILL.md`; for `tablesWithNewColumns[]`, read and execute `${PLUGIN_ROOT}/skills/edit-offline-profile/SKILL.md` with `--table <t> --columns add:<newColumns>`. Re-run the delta check; it should read `in-sync`. Follow the exact prompt + ordering in the reconciliation reference. |
+| `delta` | Prompt the user (one `AskUserQuestion`, default = update now) to add the missing tables / new columns. Use the reconciliation reference's **Scoped helper handoffs** with `orchestrator: add-dataverse`, the absolute `working_dir`, `phase: implementation`, and the approved environment/profile/table delta. For `missingTables[]`, read and execute `${PLUGIN_ROOT}/skills/add-table-to-offline-profile/SKILL.md` with `--working-dir '<working_dir>' --table <t>`; for `tablesWithNewColumns[]`, read and execute `${PLUGIN_ROOT}/skills/edit-offline-profile/SKILL.md` with those arguments plus `--columns add:<newColumns>`. Re-run the delta check using the reference's failure dispatch; it should read `in-sync`. |
### Step 9 — Summary
@@ -1327,12 +1539,19 @@ Next:
After printing the summary, **offer one-click sample-data seeding** — but only when invoked manually (not from `/create-mobile-app`, which handles this in its own Step 8.5).
-- **If `$ARGUMENTS` contains `--skip-planning`** (the orchestrator-invoked path): skip the prompt. The orchestrator invokes `/add-sample-data` separately.
-- **Otherwise (manual invocation)**, if the manifest contains any tables, ask:
+- **For a valid scoped orchestrator handoff with `--skip-planning`**: skip the
+ prompt. The orchestrator invokes `/add-sample-data` separately.
+- **Otherwise (manual invocation)**, propose exact verified, non-retiring seed
+ targets from this operation and a count policy; do not select every table
+ just because it appears in the manifest. Ask:
- > "Seed <N> tables with sample records so the app shows real-looking data on first launch? (yes / no — default: yes)"
+ > "Seed these <N> tables with sample records using the proposed counts? (yes / no)"
- Default to "yes" so empty input auto-proceeds. On "yes", invoke `/add-sample-data`. On "no", print "→ Skipped sample data. Run `/add-sample-data` later to populate." and stop.
+ Only an explicit yes approves seeding. On no/cancel/dismissal, stop without
+ inserts; empty input is not consent. On yes, invoke `/add-sample-data` with the
+ same absolute `--working-dir`, `--tables "<approved-logical-names>"`, and
+ `--exclude-tables "<retiring-logical-names-or-empty>"`. Carry the specific
+ approval forward; do not broaden it if lookups need additional parents.
## Key Rules
diff --git a/plugins/mobile-apps/skills/add-sample-data/SKILL.md b/plugins/mobile-apps/skills/add-sample-data/SKILL.md
index 509a00b4f..0bbc4867c 100644
--- a/plugins/mobile-apps/skills/add-sample-data/SKILL.md
+++ b/plugins/mobile-apps/skills/add-sample-data/SKILL.md
@@ -12,21 +12,74 @@ model: sonnet
# Add Sample Data
+**Invocation scope:** follow [Data-source invocation scope](../../shared/shared-instructions.md#data-source-invocation-scope)
+before any project read or command. Bind the absolute `working_dir` first and
+reuse it for every shell call, file tool, media path, and retry. This data-only
+workflow does not require creating a full app plan or changing screens.
+
Populate Dataverse tables with realistic sample records so a freshly-scaffolded code app shows real-looking data on first launch. Generates rows from each table's schema and inserts them in dependency order. Use after `/add-dataverse` (or `/setup-datamodel`) has created the tables.
## Core principles
-- **Coverage over volume — every table in the manifest gets seeded.** The #1 failure mode of a freshly-scaffolded code app is a home / dashboard / list screen that renders an empty state on first launch because its source table has zero rows. An empty downstream table is **worse than a 3-row table.** Default to minimal-but-complete: small counts everywhere, no table left empty. Volume is a secondary knob — coverage is the contract.
+- **Coverage within approved scope, not the entire manifest.** Cover each eligible
+ approved table with a small useful dataset. The manifest is verified app
+ inventory and can include retiring or unrelated tables; its presence is not
+ permission to seed them. Scope and retirement exclusions override every
+ coverage, fanout, prototype-reuse, media, and retry rule below.
- **Insertion order matters.** Parent / referenced tables must be inserted before child / referencing tables so lookup IDs are available.
- **Contextual data, not Lorem Ipsum.** Generate values that match column names + types. A `cr3e9_sitename` column in an inspection app gets "Westside Construction Site", not "Sample Name 1".
-- **Scenario-aware rows.** Read `native-app-plan.md`, especially `### Shared Conventions` and per-screen `Operational pattern` values defined in [screen-templates.md](${PLUGIN_ROOT}/shared/references/screen-templates.md). Seed rows should exercise the app's actual workflow: statuses, dates, relationships, priority/severity, media metadata, and edge cases that make the planned first viewport light up.
+- **Scenario-aware rows.** Read `native-app-plan.md` when present, especially `### Shared Conventions` and per-screen `Operational pattern` values defined in [screen-templates.md](${PLUGIN_ROOT}/shared/references/screen-templates.md); otherwise use the current data request and verified schema. Seed rows should exercise the app's actual workflow: statuses, dates, relationships, priority/severity, media metadata, and edge cases that make the planned first viewport light up.
- **Fail gracefully.** On insertion failure, log the error and continue with remaining records — never auto-rollback. The user can re-run after fixing the issue.
- **Idempotent re-runs.** If a previous run partially completed, the second run reads `memory-bank.md`'s seeded-data table and skips records already inserted.
- **Solution-scoped inserts.** Always pass `--solution <uniqueName>` so records land in our solution, not the default.
## Workflow
-1. Verify project + auth → 2. Discover tables → 3. Select tables + count → 4. Generate + preview → 5. Insert → 6. Summary
+0. Resolve approved seed scope → 1. Verify project + auth → 2. Discover scoped tables → 3. Select tables + count → 4. Generate + preview → 5. Insert → 6. Summary
+
+### Step 0 — Resolve approved seed scope
+
+Inputs are skill arguments, not flags for `dataverse-request.js`:
+
+- `--working-dir <absolute-root>`: inherit the caller's root; reject conflicting
+ explicit/inherited roots. Never default to shell cwd in a nested invocation.
+- `--tables <comma-separated-logical-names>`: the exact approved seed-table
+ allowlist. Required for every orchestrated call, including fresh creation.
+- `--exclude-tables <comma-separated-logical-names>`: retiring table names from
+ the approved edit; omit or pass an explicit empty string only when none retire.
+
+For an orchestrated call, require the scoped handoff and matching `--tables`
+before auth, record-count queries, or generation. A missing or malformed
+allowlist returns `NEEDS_CONTEXT`; never fall back to all manifest tables.
+An explicitly empty allowlist is a no-op: report no approved seed tables and
+return without cloud calls or writes.
+
+Validate logical names against the manifest and the approved plan/caller scope.
+Build `retiringTables` from the caller's retirement set plus any pending removals
+recorded in the current plan/history; include these in `--exclude-tables`.
+If an allowlisted name is absent/unverified or overlaps `retiringTables`, stop
+before insertion and return the scope mismatch. Do not silently drop unknown
+names or infer permission from a transitional manifest entry.
+
+For a standalone request, honor explicit `--tables` and exclusions. If no table
+list was supplied, discover candidates in Step 2 and ask the user to approve the
+specific table set/counts before Step 5, then freeze that selection as `seedTables`.
+For this standalone discovery path, validate against verified metadata when the
+local manifest is absent; never treat the discovery result itself as approval.
+Pending retirement always excludes a
+candidate; if that state is unclear, ask rather than treating the manifest as
+approval. Read-only fallback discovery is not permission to seed the environment.
+
+Keep a fixed `seedTables` allowlist throughout the invocation. All later
+selection, batches, media jobs, and resume operations must remain within it.
+Do not edit `.datamodel-manifest.json` or the app plan to make an excluded table
+eligible. Expanding scope requires returning to the owning approval gate.
+
+For `--plan-only` or a planning-phase handoff, use the supplied proposed table
+scope for read-only checks and return the proposed counts, dependency needs, and
+media policy before Step 5. Planning approval is not insertion approval.
+Do not generate media files, insert/update/upload records, or change the app
+plan, manifest, or seeded-data history on this path.
## Prototype Seed Reuse
@@ -37,7 +90,8 @@ src/generated/services/*/*.seed.json
src/generated/services/*.seed.json
```
-Map seed objects to Dataverse payloads using `.datamodel-manifest.json`:
+Map only `seedTables` objects to Dataverse payloads using `.datamodel-manifest.json`;
+prototype seed files cannot widen the approved set:
- Keep values only for real manifest columns.
- Translate lookup references into exact `<schemaName>@odata.bind` keys from the manifest.
@@ -51,16 +105,40 @@ If a seed file cannot be mapped safely, fall back to generated contextual sample
### Step 1 — Verify project & auth
+Run app-local commands from the resolved `working_dir` in each shell call.
+
```bash
-test -f power.config.json && test -f app.config.js
-node "${PLUGIN_ROOT}/scripts/resolve-environment.js" "$(node -e \"console.log(require('./power.config.json').environmentId)\")"
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
+if [ ! -f power.config.json ] || [ ! -f app.config.js ]; then
+ echo "BLOCKED: working_dir is not an initialized app" >&2
+ exit 1
+fi
+environment_id="$(node -p "require('./power.config.json').environmentId || ''")" || exit 1
+if [ -z "$environment_id" ]; then
+ printf '%s\n' 'ERROR: selected app has no environmentId' >&2
+ exit 1
+fi
+node "${PLUGIN_ROOT}/scripts/resolve-environment.js" "$environment_id" --no-cache --require-tenant
```
-Capture the **environment URL** for subsequent script calls. If resolution fails, instruct `az login --tenant <env-tenant>` or ask for the environment URL directly, then stop.
+Capture the **environment URL**, **environment ID**, and **tenant ID** for
+subsequent script calls; require a match with the selected app and any supplied
+owner context. Incomplete or conflicting identity returns `NEEDS_CONTEXT` after
+bounded read-only recovery. Do not remove the safety flags, select another
+environment, or persist resolver output to recover.
+
+Bind every subsequent Dataverse read, batch, PATCH, media upload, token refresh,
+and retry to that exact environment URL and tenant ID. For each
+`dataverse-request.js` invocation, pass
+`--tenant-id '<tenantId-from-resolve-environment>'` explicitly; substitute the
+validated Step 1 value again in every fresh shell call. Do not depend on a
+previous shell export, challenge discovery, or the active Azure CLI tenant.
+Missing or conflicting tenant context returns `NEEDS_CONTEXT` before the call.
Verify Azure CLI auth (the script needs an Azure CLI token):
```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
az account show --query "user.name" -o tsv
```
@@ -73,46 +151,67 @@ If empty, instruct `az login` and stop.
#### Step 2a — Path A: read `.datamodel-manifest.json` (preferred)
```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
test -f .datamodel-manifest.json
```
-If present, parse the JSON. It already contains `logicalName`, `displayName`, `status` (`new` / `extended` / `reused`), and `columns` for every table the project uses. **This is the preferred path** — fast, no API calls.
+If present, parse the JSON. It contains `logicalName`, `displayName`, `status`
+(`new` / `extended` / `reused`), and `columns` for the verified app inventory.
+**This is the preferred path** -- fast, no API calls. For scoped calls, take only
+the validated `seedTables` entries before any per-table metadata/count query.
+For standalone discovery, exclude retiring tables from the candidate list.
-```bash
-cat .datamodel-manifest.json | jq '.tables[] | { logicalName, displayName, columnCount: (.columns | length) }'
-```
+Keep unrelated manifest entries as inventory only; do not pass them to the
+record-count, generation, or insertion loops.
Skip Step 2b.
#### Step 2b — Path B: query OData (fallback)
-If `.datamodel-manifest.json` is missing, discover custom tables via the script:
+If `.datamodel-manifest.json` is missing in an orchestrated call, return `BLOCKED`
+to the owner for verified inventory recovery; do not broaden discovery or invent
+schema facts. For a standalone request with an explicit allowlist, fetch metadata
+only for those logical names. The following broad discovery is for a standalone
+request without a table list, to propose candidates for approval:
```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
node "${PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> GET \
- "EntityDefinitions?\$select=LogicalName,DisplayName,EntitySetName&\$filter=IsCustomEntity eq true"
+ "EntityDefinitions?\$select=LogicalName,DisplayName,EntitySetName&\$filter=IsCustomEntity eq true" \
+ --tenant-id '<tenantId-from-resolve-environment>'
```
-For each table the project uses, fetch its custom columns:
+For each candidate that the project uses (or each explicitly scoped table),
+fetch its custom columns:
```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
node "${PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> GET \
- "EntityDefinitions(LogicalName='<table>')/Attributes?\$select=LogicalName,DisplayName,AttributeType,RequiredLevel&\$filter=IsCustomAttribute eq true"
+ "EntityDefinitions(LogicalName='<table>')/Attributes?\$select=LogicalName,DisplayName,AttributeType,RequiredLevel&\$filter=IsCustomAttribute eq true" \
+ --tenant-id '<tenantId-from-resolve-environment>'
```
Build the same `{ logicalName, displayName, columns: [...] }` shape the manifest provides.
### Step 3 — Select tables + count
-All tables from the manifest are evaluated — including reused ones — because a mobile app that surfaces data from a shared table still needs rows to render on first launch. The only exception is standard system tables (e.g. `contact`, `account`, `systemuser`) where seeding is risky in shared production environments.
+Evaluate only the validated seed allowlist, including reused tables only when
+they are explicitly in that set. For standalone discovery, use only the proposed
+non-retiring candidates and obtain the selection approval before insertion.
+Never seed standard system tables (e.g. `contact`, `account`, `systemuser`)
+without the additional explicit shared-environment confirmation below.
**Pre-seeding row-count check (HARD — runs for every table before generating any rows):**
-For each table, query its current record count using the entity set name from the manifest (or derive it by appending `s` to the logical name as a fallback):
+For each scoped table, query its current record count using the verified entity
+set name from the manifest, or fetch that name from metadata as in Step 5a.
+Never derive it by appending `s` to a logical name.
```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
node "${PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> GET \
- "<entitySetName>?\$top=5&\$select=<primaryKeyColumn>"
+ "<entitySetName>?\$top=5&\$select=<primaryKeyColumn>" \
+ --tenant-id '<tenantId-from-resolve-environment>'
```
Count the rows returned in the `value` array.
@@ -122,7 +221,8 @@ Count the rows returned in the `value` array.
| **≥5** | **Skip this table entirely.** Log: `↷ <table> (≥5 records exist, skipping)`. Do not generate or insert any rows. |
| **<5** | Seed enough new rows to reach the per-class target count. If some records already exist (e.g. 2), generate only the gap (e.g. 3 more to reach 5). |
-If all tables already have ≥5 records, print `→ All tables already have ≥5 records. Nothing to seed.` and stop.
+If all eligible selected tables already have ≥5 records, report that nothing in
+the approved seed scope needs seeding and stop.
**Per-table count by class** (classify each table from manifest signals before generating; this beats a uniform `5` because reference tables don't need volume and transactional tables need state spread):
@@ -151,7 +251,13 @@ For the selected tables, build a dependency graph from lookup columns:
2. Tables with lookups only to Tier 0 → Tier 1
3. Continue until all selected tables are tiered
-If a selected table references an UNSELECTED parent, ask the user whether to add the parent to the selection or skip the lookup field. Don't silently insert null lookups.
+If a selected table references an UNSELECTED parent, reuse a verified existing
+parent record through a bounded read when that lookup is within the approved
+data scope. Reading a lookup parent is not permission to insert/update it. If no
+suitable record exists, return `NEEDS_CONTEXT` to the owner (or ask standalone)
+to extend the seed scope or explicitly omit an optional lookup. Never auto-add
+a parent to `seedTables`, create a retiring parent, or omit a required lookup.
+Retiring lookup targets block that dependent seed until the plan is reconciled.
### Step 4 — Generate sample data + preview
@@ -170,7 +276,7 @@ For each selected table, generate N rows. Match values to column names + types:
| **Boolean** | Mix true/false (~70/30 favoring true for `is_active` style names). |
| **Choice (Picklist)** | **Query options first** (Step 4b), then pick from valid integer values. |
| **MultiSelect Choice** | Pick 1-3 valid values per row from the option set. |
-| **Lookup** | Reference a record from the parent table that was (or will be) inserted in this run. Track parent GUIDs from Step 5's POST responses. |
+| **Lookup** | Reference a verified existing parent or one inserted within the approved seed scope. Track live parent GUIDs; never seed an unapproved parent just to satisfy a child. |
| **Image / File** | Default: skip — leave null. If media seeding is enabled and the column is business data (product image, inspection evidence, NC proof), use generated/synthetic local files from `assets/sample-*` and record provenance. Never upload decorative UI hero assets to Dataverse. |
**Media seeding policy (business data only, only if needed):**
@@ -230,8 +336,10 @@ For each selected table, generate N rows. Match values to column names + types:
For every choice column in the selected tables, query its option set before generating rows:
```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
node "${PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> GET \
- "EntityDefinitions(LogicalName='<table>')/Attributes(LogicalName='<column>')/Microsoft.Dynamics.CRM.PicklistAttributeMetadata?\$expand=OptionSet"
+ "EntityDefinitions(LogicalName='<table>')/Attributes(LogicalName='<column>')/Microsoft.Dynamics.CRM.PicklistAttributeMetadata?\$expand=OptionSet" \
+ --tenant-id '<tenantId-from-resolve-environment>'
```
Use the actual `Value` integers from the response. Don't hardcode `100000000`-style values — they vary per environment.
@@ -258,7 +366,15 @@ For tables with lookups, also show which parent record each child references:
#### Step 4d — Proceed to insert
-After the preview is shown, proceed directly to Step 5. No confirmation prompt — the row-count pre-check (Step 3) already ensures no existing data is overwritten.
+For `--plan-only` or a planning-phase handoff, return the preview and STOP here;
+neither an earlier approval nor a populated manifest overrides that boundary.
+
+Proceed without another prompt only when the exact seed tables/count policy and
+any media writes are already approved in the current scoped handoff or explicit
+standalone request. Otherwise obtain explicit approval of the preview first.
+Row counts prevent duplicate volume; they are not consent. Cancellation stops.
+If dependencies or rows require a wider scope, return to the owner rather than
+approving the expansion inside an orchestrated leaf.
### Step 5 — Insert sample data
@@ -276,8 +392,10 @@ Insert in the tier order from Step 3c. **Within a tier, parallelize across both
For each table, get its `EntitySetName` (the URL-path name, usually plural — e.g. `cr3e9_jobsites`). Read from `.datamodel-manifest.json` if it carries this; otherwise:
```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
node "${PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> GET \
- "EntityDefinitions(LogicalName='<table>')?\$select=EntitySetName"
+ "EntityDefinitions(LogicalName='<table>')?\$select=EntitySetName" \
+ --tenant-id '<tenantId-from-resolve-environment>'
```
Cache the result.
@@ -288,6 +406,12 @@ Cache the result.
For each tier from 0 → N:
+Before constructing or submitting a batch, re-check every target logical name
+against `seedTables` and `retiringTables`. Resolve its exact entity set, and
+reject the entire proposed batch if any insert/update targets an unapproved or
+retiring table. Apply the same guard before media PATCH/upload and every retry;
+an out-of-scope operation is a scope error, not a record failure to continue past.
+
1. **Build the operations array.** Collect every (entitySet, body) pair across all tables in this tier. Tag each with a unique `index` you'll use to map results back to your row identity.
```jsonc
@@ -304,11 +428,13 @@ For each tier from 0 → N:
2. **Fire BATCH-RECORDS once per tier.** The script handles concurrency, retry, GUID extraction, and adaptive throttling internally:
```bash
+ cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
node "${PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> BATCH-RECORDS \
"Tier <N>" \
--operations '<json-from-step-1>' \
--concurrency 5 \
- --solution '<solution-uniquename-from-memory-bank>'
+ --solution '<solution-uniquename-from-memory-bank>' \
+ --tenant-id '<tenantId-from-resolve-environment>'
```
Output is `{ "status": 200, "data": [{ "index": 0, "status": 204, "recordId": "<guid>" }, ...] }`. Results are ordered by input index (stable across parallel execution).
@@ -342,11 +468,13 @@ For Tier 1+ tables, build each row's body with `@odata.bind` referencing the par
Then:
```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
node "${PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> BATCH-RECORDS \
"Tier 1" \
--operations '<json-with-bound-lookups>' \
--concurrency 5 \
- --solution '<solution-uniquename-from-memory-bank>'
+ --solution '<solution-uniquename-from-memory-bank>' \
+ --tenant-id '<tenantId-from-resolve-environment>'
```
> **⚠️ Lookup write syntax (HARD — wrong shape silently saves null OR loudly 404s):**
@@ -360,6 +488,9 @@ node "${PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> BATCH-RECORDS \
Run this step only when Step 4a created media jobs for business Image/File columns. Never run it for decorative UI assets.
+Every media job's target table must still be in `seedTables` and outside
+`retiringTables`; a previously captured GUID does not authorize a new target.
+
Build a `mediaJobs` sidecar while generating rows:
```jsonc
@@ -379,6 +510,13 @@ Build a `mediaJobs` sidecar while generating rows:
After each tier's `BATCH-RECORDS` response, fill `recordId` from the in-memory `{ index → recordId }` map, then upload media by column type:
+- Pass the Step 1 environment URL and tenant ID explicitly to every media
+ helper, including its authentication and token-refresh path. Image PATCH
+ calls through `dataverse-request.js` require the same `--tenant-id` argument.
+ If a File upload helper cannot enforce that tenant binding, do not invoke it
+ or fall back to ambient credentials: leave bytes unset, report
+ `sample media skipped — tenant-bound upload helper missing`, and return a
+ media concern with the preserved metadata rows.
- **Image columns:** if the base64 value was already included in the create body, mark the media job complete. If not, PATCH the record with the base64 string using the entity set + record GUID. Keep images small and app-facing; never upload original multi-megabyte photos for seed data.
- **File columns:** call a supported upload helper after the row exists. In app code, the generated service shape is `Service.upload(recordId, columnName, file, fileDisplayName?)`; for CLI seeding, use a dedicated helper that performs the same Dataverse file upload flow. The JSON-only `dataverse-request.js BATCH-RECORDS` mode is not a binary upload mechanism.
@@ -416,11 +554,17 @@ If a tier fails partway and you need to retry, **do NOT write a hand-rolled `see
**The only safe resume pattern:**
+Reconfirm the current approved `seedTables` and retirement exclusions before
+resuming. Prior memory-bank successes or seed files do not authorize tables
+removed from the current scope; never retry a retiring table.
+
1. **Re-query parent GUIDs by a stable business key.** For every parent table referenced in the failed tier's `@odata.bind` values, run a fresh GET filtered by the row's natural identifier (name, tail-number, code — whatever you used as the primary name when seeding). Example:
```bash
+ cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
node "${PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> GET \
- "<parentEntitySet>?\$select=<parentIdColumn>,<naturalKey>&\$filter=startswith(<naturalKey>,'<seed prefix>')&\$top=50"
+ "<parentEntitySet>?\$select=<parentIdColumn>,<naturalKey>&\$filter=startswith(<naturalKey>,'<seed prefix>')&\$top=50" \
+ --tenant-id '<tenantId-from-resolve-environment>'
```
Build a fresh `{ naturalKey → guid }` map from the response.
@@ -431,7 +575,7 @@ If a tier fails partway and you need to retry, **do NOT write a hand-rolled `see
> `⛔ Resume aborted: expected <N> parent rows in <table>, found <K>. Re-run /add-sample-data from Tier 0 (don't trust the prior session's GUIDs).`
-4. **Re-issue the failed tier as a normal Step 5b/5c BATCH-RECORDS call** with the freshly-queried GUIDs and EntitySetNames substituted into the operations array. Same `--solution` flag, same concurrency rules.
+4. **Re-issue the failed tier as a normal Step 5b/5c BATCH-RECORDS call** with the freshly-queried GUIDs and EntitySetNames substituted into the operations array. Same `--solution` flag, explicit `--tenant-id` from the validated Step 1 identity, and concurrency rules; never switch tenants to recover.
5. **Continue forward** through subsequent tiers using the new in-memory `{ index → recordId }` map seeded from this resume's response.
@@ -444,6 +588,7 @@ If a tier fails partway and you need to retry, **do NOT write a hand-rolled `see
─────────────────────────────────────────────
Environment : <envUrl>
Solution : <solution>
+Seed scope : <approved targets; excluded/retiring targets>
Tables seeded : <list with counts, e.g. cr3e9_jobsite (5), cr3e9_inspection (5)>
Total records : <N>
Failures : <K> (see list below if K > 0)
@@ -456,9 +601,16 @@ Next steps:
If any record failed, print a sub-table of the failures with the error messages so the user can diagnose.
+Return a non-success/concern status for partial results; never describe unseeded
+or excluded tables as successfully populated. Seeding does not change the plan's
+schema or remove transitional entries from `.datamodel-manifest.json`.
+
## Hard rules
-- **Coverage-first — every table in scope gets at least 1 row.** If you find yourself dropping a table because "its parent count is small" or "the user probably doesn't need it on day 1," you're wrong. Empty downstream tables are the failure mode this skill exists to prevent. The only legitimate exclusions: shared standard tables (`contact`, `account`, `incident`) and reused-as-is tables.
+- **Coverage within the seed allowlist only.** Retiring/unapproved tables are
+ always excluded, even when present in the manifest or needed by a fanout target.
+ Respect row-count skips and standard-system-table confirmations; coverage
+ goals never authorize broadening the seed scope.
- **Per-parent fanout floor — every parent in Tier K-1 gets at least 1 child in Tier K** (when the relationship is required or implies 1-to-many). Random lookup distribution leaves orphan parents and breaks parent-detail screens. Generate child rows parent-by-parent, not as a flat batch with random parent picks.
- **State / status distribution for transactional, issue, override, log tables** — mix at least 2 distinct values; never all-`Open`, never all-`InProgress`, never all-`Pending`. See Step 4a for per-class targets.
- **Date distribution for transactional / log tables** — spread across today + last 14 days, not bunched on a single day. ~30% recent / 50% last week / 20% older.
diff --git a/plugins/mobile-apps/skills/add-sharepoint/SKILL.md b/plugins/mobile-apps/skills/add-sharepoint/SKILL.md
index ee0b54524..feea830fe 100644
--- a/plugins/mobile-apps/skills/add-sharepoint/SKILL.md
+++ b/plugins/mobile-apps/skills/add-sharepoint/SKILL.md
@@ -2,7 +2,7 @@
name: add-sharepoint
description: Use when the user wants to read or write SharePoint lists, manage documents in a SharePoint document library, or create a new SharePoint list from a Power Apps mobile app.
user-invocable: true
-allowed-tools: Read, Edit, Write, Grep, Glob, Bash, AskUserQuestion, EnterPlanMode, ExitPlanMode
+allowed-tools: Read, Edit, Write, Grep, Glob, Bash, AskUserQuestion, EnterPlanMode, ExitPlanMode, Skill
model: sonnet
---
@@ -18,6 +18,31 @@ model: sonnet
# Add SharePoint
+**App root:** before any project read or command, execute
+[app-working-directory.md](${PLUGIN_ROOT}/shared/references/app-working-directory.md).
+Use its resolved absolute `working_dir` for every shell call and file tool,
+including referenced commands and delegated skills; never inherit a prior `cd`.
+
+**Invocation scope:** follow [Data-source invocation scope](../../shared/shared-instructions.md#data-source-invocation-scope)
+before the workflow below. Standalone calls approve only their SharePoint
+schema/binding delta and verify it here; they do not start a full-app workflow.
+
+Keep SharePoint list/library schemas in Connectors, not the Dataverse
+Data Model. Forward supplied site/list/connection choices and ask only for missing
+values; return scope changes to the current owner, or ask the standalone user,
+before mutation. Reuse supplied approval only for the exact current data delta.
+
+**Removal branch:** after resolving invocation scope, `--remove` or an approved list/library
+binding removal executes
+[data-source-removal.md](../../shared/references/data-source-removal.md) and
+returns. Do not create a connection/list or run Steps 1-12 for removal; the
+SharePoint list/library and its contents remain on the server.
+
+**Refresh branch:** after resolving invocation scope, `--refresh` or an approved retained-list
+service refresh executes [Refresh a retained source](../../shared/references/data-source-removal.md#refresh-a-retained-source)
+and returns before Steps 1-12. Preserve the exact `--data-source-name` and approved
+binding identity; do not create a list/connection or run `add-data-source`.
+
Two paths: **existing lists** (skip to Step 6) or **new lists** (full workflow).
## Workflow
@@ -34,18 +59,29 @@ Check for `memory-bank.md` per [shared-instructions.md](${PLUGIN_ROOT}/shared/sh
Also confirm this is a mobile app:
```bash
-test -f power.config.json && test -f app.config.js && echo "OK" || echo "ERROR: not a mobile app"
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
+if [ ! -f power.config.json ] || [ ! -f app.config.js ]; then
+ echo "BLOCKED: working_dir is not an initialized app" >&2
+ exit 1
+fi
```
### Step 2: Plan
**Telemetry checkpoint: `plan_sharepoint_data_source`**
-Ask the user:
+Reuse the supplied site/list and existing-vs-new decisions. Ask only for missing
+values:
1. Which SharePoint list(s) do they need?
2. Do the lists **already exist** on their site, or do they need to **create new** ones?
+For `--plan-only` or a planning-phase handoff, present the proposed site/list
+bindings, any schema changes, and unresolved choices, then STOP before
+implementation. Do not create connections/lists, generate services, or update
+the app plan or memory-bank. Missing discovery access is not permission to
+create a connection.
+
**If lists already exist:** Skip to Step 6.
**If creating new lists:**
@@ -53,13 +89,16 @@ Ask the user:
- Ask about the data they need and design an appropriate schema
- Reuse existing lists when possible (don't duplicate)
- Enter plan mode with `EnterPlanMode`, present the list designs with columns and types
-- Get approval with `ExitPlanMode`
+- Get approval with `ExitPlanMode`, unless the exact list/schema delta already
+ has current owner approval. Read-only discovery that changes that delta must
+ return for approval before Step 5.
### Step 3: Setup Graph API Auth (if creating lists)
See [api-authentication-reference.md](./references/api-authentication-reference.md) for full details.
```powershell
+Set-Location -LiteralPath '<working_dir>' -ErrorAction Stop
az account show # Verify Azure CLI logged in
$api = Initialize-SharePointGraphApi -SiteUrl "https://<tenant>.sharepoint.com/sites/<site-name>"
@@ -74,6 +113,7 @@ Requires **Sites.Manage.All** permission.
**Always query existing lists first before creating:**
```powershell
+Set-Location -LiteralPath '<working_dir>' -ErrorAction Stop
$existingLists = Invoke-RestMethod -Uri "https://graph.microsoft.com/v1.0/sites/$siteId/lists?`$select=id,displayName,description,list&`$filter=list/hidden eq false" -Headers $headers
```
@@ -92,7 +132,9 @@ Present findings to user with `AskUserQuestion`:
**Print before starting:**
> "→ Creating SharePoint lists via Graph API (sequential per list, columns added after list exists)…"
-Get explicit confirmation before creating. Use safe functions from [list-management-reference.md](./references/list-management-reference.md):
+Require explicit current approval for the exact create/extend operations before
+writing; reuse matching owner approval rather than prompting twice. Use safe
+functions from [list-management-reference.md](./references/list-management-reference.md):
- `New-SharePointListIfNotExists`
- `Add-SharePointColumnIfNotExists`
@@ -100,13 +142,27 @@ Get explicit confirmation before creating. Use safe functions from [list-managem
### Step 6: Get Connection ID
-Get the SharePoint Online connection ID (see [connector-reference.md](${PLUGIN_ROOT}/shared/connector-reference.md)):
+Apply [connector-reference.md](../../shared/connector-reference.md#step-1--get-a-connection)
+before any lookup or creation. Use **`shared_sharepointonline`** as `apiId`.
+
+- Supplied `--connection-id` or approved `connectionId`: reuse the exact ID;
+ skip `create-connection` and `/list-connections`.
+- Supplied `--connection-ref` or approved `connectionRef`: retain the exact
+ reference for Step 9; skip `create-connection` and `/list-connections`.
+- Missing binding only: use the approved solution-reference lookup when
+ solution-aware, or obtain explicit approval to create a connection with the
+ command below. Conflicting,
+ blank, or wrong-environment supplied bindings must be clarified, not replaced.
```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
$PA connection create --connector shared_sharepointonline --json
```
-Use **`shared_sharepointonline`** as the `apiId` and capture **`connectionId`** from the output. Use these exact values in the commands below.
+Only on the creation path, capture the returned `connectionId`. The following
+picker examples use the ID path. With a reference, skip pickers when site/list
+values are supplied; otherwise obtain the backing ID for that same reference or
+ask for the missing choices. Do not create another connection for discovery.
If `pa connection create` cannot complete because browser-based connection creation is disabled or the connector needs interactive auth, direct the user to create one:
@@ -114,14 +170,17 @@ If `pa connection create` cannot complete because browser-based connection creat
### Step 7: Discover Sites
+Skip this picker when the approved site URL is already supplied.
+
**Print before starting:**
> "→ Discovering SharePoint sites accessible to this connection…"
```bash
-$PA connection list-datasets --connector <apiId-from-list> --connection-id <connection-id> --json
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
+$PA connection list-datasets --connector shared_sharepointonline --connection-id '<connectionId>' --json
```
-Present the sites to the user and ask which one(s) they want to connect to. If the user already specified a site URL, confirm it appears in the list.
+Present the discovered sites only when a site choice is missing.
**If `pa connection list-datasets` fails or returns no results:**
- Auth, wrong user, or multiple accounts: follow shared-instructions command-failure handling and retry once.
@@ -129,13 +188,16 @@ Present the sites to the user and ask which one(s) they want to connect to. If t
### Step 8: Discover Tables
+Skip this picker for supplied list/library identities; reuse the approved values.
+
**Print before starting:**
> "→ Discovering lists/document libraries on each selected site…"
For each selected site:
```bash
-$PA connection list-tables --connector <apiId-from-list> --connection-id <connection-id> --dataset '<site-url>' --json
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
+$PA connection list-tables --connector shared_sharepointonline --connection-id '<connectionId>' --dataset '<site-url>' --json
```
Present the tables to the user and ask which ones they want to add. Suggest tables that look relevant to their use case. If lists were created in Step 5, they should appear here.
@@ -147,19 +209,33 @@ Present the tables to the user and ask which ones they want to add. Suggest tabl
**Print before starting:**
> "→ Running `pa app add data-source` per list (sequential, ~10–20 seconds each)."
-SharePoint is a tabular datasource — requires `--connection-id`, `--dataset`, and `--table`:
+SharePoint is tabular: use `--dataset` and `--table` with the exact
+binding selected in Step 6. Confirm approval covers this environment, connection
+ID/reference, site, and list/library before registration. Ask the standalone
+user to approve any newly resolved binding; return a changed child scope to its
+owner. A picker selection alone is not execution approval.
+Run only the applicable command:
```bash
-$PA app add data-source --connector <apiId-from-list> --connection-id <connectionId-from-list> --dataset '<site-url>' --table '<table-name>'
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
+# Supplied/resolved connection ID
+$PA app add data-source --connector shared_sharepointonline --connection-id '<connectionId>' --dataset '<site-url>' --table '<table-name>'
+
+# Supplied/resolved connection reference
+$PA app add data-source --connector shared_sharepointonline --connection-ref '<connectionRef>' --dataset '<site-url>' --table '<table-name>'
```
Run once per list or document library.
### Step 10: Configure
+Inspect and return service signatures and usage guidance to the user or current
+owner. Do not independently edit screens or launch another app workflow;
+explicitly report that this data-source operation did not wire screens.
+
**Read [sharepoint-reference.md](./references/sharepoint-reference.md) before writing any SharePoint code** — column encoding, choice fields, and lookups have critical gotchas.
-Use `Grep` to find methods in `src/generated/services/SharePointOnlineService.ts` (generated files can be very large — see [connector-reference.md](${PLUGIN_ROOT}/shared/connector-reference.md#inspecting-large-generated-files)).
+Use `Grep` to find methods in `<working_dir>/src/generated/services/SharePointOnlineService.ts` (generated files can be very large — see [connector-reference.md](${PLUGIN_ROOT}/shared/connector-reference.md#inspecting-large-generated-files)).
Sample usage:
@@ -201,6 +277,7 @@ await SharePointOnlineService.PatchItem({
`pa app add data-source` wrote new files into `.power/schemas/sharepointonline/`. Regenerate `connectorSchemas.ts` before type-checking so the new list is wired into the runtime schema map:
```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
npm run generate-schemas
npx --no-install tsc --noEmit
```
diff --git a/plugins/mobile-apps/skills/add-table-to-offline-profile/SKILL.md b/plugins/mobile-apps/skills/add-table-to-offline-profile/SKILL.md
index 3117305f0..6a8c52c3b 100644
--- a/plugins/mobile-apps/skills/add-table-to-offline-profile/SKILL.md
+++ b/plugins/mobile-apps/skills/add-table-to-offline-profile/SKILL.md
@@ -20,6 +20,38 @@ Add a single table to an existing Mobile Offline Profile. Most common flow: user
Equivalent to running `/setup-offline-profile` and seeing the existing profile (extend-mode), but skips the per-table questionnaire for the tables already in the profile — only configures the new one.
+## Invocation context and root binding
+
+This internal helper is always a **child invocation**. Before any project read or
+command, execute [app-working-directory.md](${PLUGIN_ROOT}/shared/references/app-working-directory.md).
+Require the owner's absolute `working_dir`; `--working-dir`, when supplied, must
+identify that same native-canonical root. Missing, relative, or conflicting root
+context returns `NEEDS_CONTEXT` before project access; an inaccessible directory
+is `BLOCKED`. Never use the launch cwd or introduce another root resolver.
+
+Receive `MOBILE_APP_ORCHESTRATING=1`, `orchestrator`, `working_dir`, `phase`,
+`approved_scope`, and supplied answers from the owner. Keep the selected
+environment ID/URL/tenant, profile ID, exact table allowlist, and approved
+operations unchanged. Missing or conflicting scope returns `NEEDS_CONTEXT`;
+do not substitute another environment, profile, or table. The marker is not
+approval: schema approval alone does not authorize offline prerequisite changes,
+profile items, relationships, columns, publication, deletion, or membership edits.
+Reuse only the same current offline approvals; otherwise retain Steps 3–4's gates.
+For `--plan-only` or a planning-phase handoff, return a proposal after permitted
+read-only discovery, before any prerequisite update, profile mutation, publish,
+or artifact write. A gate response cannot lift proposal-only mode.
+
+Apply the canonical contract to **every shell call and file tool**, including
+version/auth checks, row counts, screen greps, commands copied from references,
+verification, recovery, and retries. Re-supply the absolute `PLUGIN_ROOT` and
+required context on each call; no prior `cd`, export, or shell variable persists.
+Use the canonical Bash guard below or its PowerShell equivalent. Replace
+placeholders with validated, shell-quoted invocation values; missing values
+return `NEEDS_CONTEXT`, never execute an unresolved placeholder.
+File tools use absolute `<working_dir>/...` paths; plugin reads/scripts use
+`${PLUGIN_ROOT}/...`. Resolve manifest location once within this root and keep
+that absolute path; never search another app when a file is absent.
+
## Workflow
1. Verify project + locate profile → 2. Resolve target table → 3. Prereq check (auto-enable if needed) → 4. Scope picker (single question) → 5. POST item + PATCH selectedcolumns → 6. Publish → 7. Update artifacts → 8. Summary
@@ -29,19 +61,54 @@ Equivalent to running `/setup-offline-profile` and seeing the existing profile (
### Step 1 — Verify project + locate profile
```bash
-test -f power.config.json
-node "${PLUGIN_ROOT}/scripts/resolve-environment.js" "$(node -e \"console.log(require('./power.config.json').environmentId)\")"
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
+if [ ! -f power.config.json ] || [ ! -f app.config.js ]; then
+ echo "BLOCKED: working_dir is not an initialized app" >&2
+ exit 1
+fi
+```
+
+Read `<working_dir>/power.config.json` and require a nonempty `environmentId`
+matching the owner's selected environment. Reuse matching complete environment
+context, or perform this non-persisting lookup from the bound root:
+
+```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
+environment_id=$(node -p "require('./power.config.json').environmentId || ''") || {
+ echo "BLOCKED: unreadable power.config.json" >&2; exit 1;
+}
+if [ -z "$environment_id" ] || [ "$environment_id" != "<selected-environment-id>" ]; then
+ echo "NEEDS_CONTEXT: selected environment does not match working_dir" >&2
+ exit 1
+fi
+node "${PLUGIN_ROOT}/scripts/resolve-environment.js" "$environment_id" --no-cache --require-tenant
```
-Manifest path (dual-location):
+Require the returned environment ID, HTTPS URL, and tenant to match the owner;
+incomplete or conflicting context returns `NEEDS_CONTEXT`. Never drop
+`--no-cache --require-tenant`, change configuration, or switch auth/environment
+to recover a failure. Use that exact `<envUrl>` and `<tenantId>` for every request.
+
+Manifest path (dual-location, both within the bound root):
```bash
-MANIFEST=$(test -f .datamodel-manifest.json && echo ".datamodel-manifest.json" || \
- (test -f docs/plan-artifacts/.datamodel-manifest.json && echo "docs/plan-artifacts/.datamodel-manifest.json"))
-test -n "$MANIFEST" && echo "✓ manifest at $MANIFEST"
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
+if [ -f .datamodel-manifest.json ]; then
+ printf '%s\n' '<working_dir>/.datamodel-manifest.json'
+elif [ -f docs/plan-artifacts/.datamodel-manifest.json ]; then
+ printf '%s\n' '<working_dir>/docs/plan-artifacts/.datamodel-manifest.json'
+else
+ echo "NEEDS_CONTEXT: no manifest in working_dir" >&2
+ exit 1
+fi
```
-Profile ID resolution (same as `/edit-offline-profile`).
+Read the profile from `<working_dir>/offline-profile.json` or the owner's explicit
+`--profile-id`, using `/edit-offline-profile`'s resolution rules inline. Verify it
+matches the owner's profile and the live profile in the selected environment.
+A conflicting snapshot/argument, 404, or permission failure is not permission to
+pick a different profile; return `NEEDS_CONTEXT` for conflict or `BLOCKED` for
+access failure. Do not execute the edit workflow just to locate a profile.
STOP if no profile exists. Recommend: `Run /setup-offline-profile first to create the profile.`
@@ -52,31 +119,64 @@ STOP if no profile exists. Recommend: `Run /setup-offline-profile first to creat
| Flag | Effect |
|---|---|
| `--table <logical-name>` | Explicit target |
-| `--all-new` | Add ALL tables in the manifest that aren't already in the profile (bulk mode) |
-| (no flags) | Interactive: list tables in manifest NOT yet in profile via `AskUserQuestion` (max 4); if more than 4 candidates, prompt user to specify by name in next message |
+| `--all-new` | Add missing manifest tables only within the owner's exact table allowlist (bulk mode); never widen to unrelated pending tables |
+| (no flags) | Interactive: list allowed tables in the manifest NOT yet in the selected profile via `AskUserQuestion` (max 4); if more than 4 candidates, prompt user to specify by name in next message |
-For bulk `--all-new` mode, loop through Steps 3-6 for each missing table; each runs sequentially because Dataverse profile-item POSTs serialize.
+An explicit `--table` must match the owner's allowlist. Conflicting selection
+returns `NEEDS_CONTEXT`. For bulk `--all-new` mode, loop through Steps 3–7 for
+each approved missing table; each runs sequentially because Dataverse profile-item
+POSTs serialize. Every iteration keeps the same root/environment/profile context.
### Step 3 — Prereq check (auto-enable if needed)
Query the target table's `EntityMetadata`:
```bash
-node "${PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> GET \
- "EntityDefinitions(LogicalName='<table>')?\$select=IsAvailableOffline,ChangeTrackingEnabled,OwnershipType,IsCustomizable"
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
+node "${PLUGIN_ROOT}/scripts/dataverse-request.js" "<envUrl>" GET \
+ "EntityDefinitions(LogicalName='<table>')?\$select=IsAvailableOffline,ChangeTrackingEnabled,OwnershipType,IsCustomizable" \
+ --tenant-id "<tenantId>"
```
| Flags state | Action |
|---|---|
| Both already `true` | Skip to Step 4 |
-| Either `false` AND IsCustomizable | Auto-enable via `update-entity-offline-flags.js` (no prompt — the user already opted into "offline this table" by invoking this skill) |
+| Either `false` AND IsCustomizable | Use `update-entity-offline-flags.js` only if the current offline approval covers these exact prerequisite changes and publication; otherwise show the changes and obtain owner/user approval first |
| `IsCustomizable.Value = false` | STOP with `BLOCKED: <table> is system-managed and cannot be flagged for offline. Use a different table or accept this row is read-only-offline.` |
-After auto-enable, single `POST PublishAllXml`.
+After approval, execute the helper for this table only with the resolved tenant.
+`--tenant-id` binds both initial authentication and 401 refresh; never rely on
+ambient tenant variables for this prerequisite mutation.
+
+```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
+node "${PLUGIN_ROOT}/scripts/update-entity-offline-flags.js" "<envUrl>" \
+ --table "<table>" --offline true --tracking true --tenant-id "<tenantId>"
+```
+
+Check the returned HTTP status, not just process exit. A 403/`PrivilegeCheckFailed`
+is `BLOCKED`; do not change identity or profile to bypass permissions.
+After a successful change, issue the approved prerequisite publication:
+
+```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
+node "${PLUGIN_ROOT}/scripts/dataverse-request.js" "<envUrl>" POST \
+ "PublishXml" --tenant-id "<tenantId>" --body '{
+ "ParameterXml": "<importexportxml><entities><entity><table></entity></entities></importexportxml>"
+ }'
+```
+
+Publish only this helper's changed prerequisite table. Do not use
+`PublishAllXml` unless the owner separately approves publishing all pending
+environment customizations; table-only approval does not cover that fallback.
+
+No prerequisite mutation or publication is allowed in proposal-only mode.
### Step 4 — Scope picker (single question)
-Pull from manifest the target table's `lookups[]` to inform defaults. Run a quick row-count probe to inform reference-data classification.
+Pull from the bound absolute manifest the target table's `lookups[]` to inform
+defaults. Run a root-bound row-count probe in the selected environment for this
+table only to inform reference-data classification.
`AskUserQuestion` with 4 options reflecting the architect's priority cascade:
@@ -89,13 +189,20 @@ Pull from manifest the target table's `lookups[]` to inform defaults. Run a quic
Recommendation in the question body should be derived from the architect's heuristics for the table being added (use the same priority cascade from `offline-profile-architect.md` Step 4 inline). The user can override.
+Show the proposed relationships, selected columns, and sync interval alongside
+the scope choice. Reuse supplied answers only when they approve this exact
+offline change; otherwise wait for the choice before Step 5. Cancel stops without
+creating a profile item. Neither invocation nor the orchestration marker answers
+this gate.
+
### Step 5 — POST item + associations + PATCH selectedcolumns
#### Step 5a — POST profile item
```bash
-node "${PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> POST \
- "mobileofflineprofileitems" \
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
+node "${PLUGIN_ROOT}/scripts/dataverse-request.js" "<envUrl>" POST \
+ "mobileofflineprofileitems" --tenant-id "<tenantId>" \
--body '{
"name": "<DisplayName>",
"[email protected]": "/mobileofflineprofiles(<profileId>)",
@@ -119,8 +226,9 @@ After the new item is created, walk the new table's relationships (from the mani
Recipe per [shared/references/dataverse-offline-api.md §5–§6](${PLUGIN_ROOT}/shared/references/dataverse-offline-api.md):
```bash
-node "${PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> POST \
- "mobileofflineprofileitemassociations" \
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
+node "${PLUGIN_ROOT}/scripts/dataverse-request.js" "<envUrl>" POST \
+ "mobileofflineprofileitemassociations" --tenant-id "<tenantId>" \
--body '{
"name": "<relationshipSchemaName>",
"relationshipdisplayname": "<relationshipSchemaName>",
@@ -136,30 +244,64 @@ For new tables that are `recorddistributioncriteria: 0` (Related rows only), at
#### Step 5c — PATCH selectedcolumns
-Build `selectedcolumns` using the deterministic union from [offline-profile-architect.md](${PLUGIN_ROOT}/agents/offline-profile-architect.md) Step 6 (always-include ∪ lookups ∪ screen-grep'd, dedupe, sort).
+Build `selectedcolumns` using the deterministic union from [offline-profile-architect.md](${PLUGIN_ROOT}/agents/offline-profile-architect.md) Step 6 (always-include ∪ lookups ∪ screen-grep'd, dedupe, sort). Scope file-tool greps to absolute `<working_dir>/app/` and `<working_dir>/src/` paths and the selected table; use the same proposed columns approved in Step 4.
```bash
-node "${PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> PATCH \
- "mobileofflineprofileitems(<itemId>)" \
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
+node "${PLUGIN_ROOT}/scripts/dataverse-request.js" "<envUrl>" PATCH \
+ "mobileofflineprofileitems(<itemId>)" --tenant-id "<tenantId>" \
--body '{"selectedcolumns":"{\"Columns\":[...]}"}'
```
### Step 6 — Publish (targeted PublishXml)
```bash
-node "${PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> POST \
- "PublishXml" --body '{
- "ParameterXml": "<publish><mobileofflineprofiles><mobileofflineprofile>'"$PROFILE_ID"'</mobileofflineprofile></mobileofflineprofiles></publish>"
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
+node "${PLUGIN_ROOT}/scripts/dataverse-request.js" "<envUrl>" POST \
+ "PublishXml" --tenant-id "<tenantId>" --body '{
+ "ParameterXml": "<publish><mobileofflineprofiles><mobileofflineprofile><profileId></mobileofflineprofile></mobileofflineprofiles></publish>"
}'
```
Publishes only this profile, not the entire org's customizations. See [shared/references/dataverse-offline-api.md §9](${PLUGIN_ROOT}/shared/references/dataverse-offline-api.md) for `0x80071141` circular-relationship handling + `PublishAllXml` fallback.
-### Step 7 — Update artifacts
+All linked recovery commands, re-GET verification, and retries must bind the
+same root and pass the same environment/tenant/profile/table/item context.
+Removing a cycle association requires the explicit user decision in that recipe.
+An org-wide `PublishAllXml` fallback needs approval for that broader publication;
+do not silently escalate a profile-scoped approval. Never retry on a different
+profile or bypass a permission failure. Confirm publication before Step 7.
+
+If a linked recovery recipe requires another offline helper, return the proposed
+change to the owner for approval first, then read the helper at its absolute
+`${PLUGIN_ROOT}/skills/<helper>/SKILL.md` path. Forward:
+
+```text
+Arguments: --working-dir '<working_dir>' --profile-id "<profileId>" --table "<table>" <exact-approved-change-flags>
+Context: MOBILE_APP_ORCHESTRATING=1, orchestrator, working_dir, phase, approved_scope,
+ selected environment ID/URL/tenant, profile ID, table allowlist, item ID,
+ supplied answers, --plan-only (if present)
+```
-Append the new table's entry to `offline-profile.json` `tables[]`. The entry MUST include a `schemaColumns` array — the added table's full set of schema column logical names from `.datamodel-manifest.json` at this moment. This is the schema-reconciliation baseline that `scripts/offline-profile-delta.js` diffs future manifest changes against; omitting it makes the lifecycle delta check report this table under `columnBaselineMissing` until it is re-reconciled. It is distinct from `selectedColumns` (the curated sync set) — see [offline-profile-reconciliation.md](${PLUGIN_ROOT}/shared/references/offline-profile-reconciliation.md). Match the canonical entry shape in [`/setup-offline-profile` Step 9a](../setup-offline-profile/SKILL.md).
+The recipient must enforce the same canonical root contract. Missing context
+returns `NEEDS_CONTEXT`; do not fall back to direct invocation or rediscovery.
+
+### Step 7 — Update artifacts
-Append to `memory-bank.md` `## Offline profile` block:
+Append the new table's entry to `<working_dir>/offline-profile.json` `tables[]`.
+The entry MUST include a `schemaColumns` array — the added table's full set of
+schema column logical names from the bound absolute manifest at this moment.
+This is the schema-reconciliation baseline that
+`${PLUGIN_ROOT}/scripts/offline-profile-delta.js` diffs future manifest changes
+against; omitting it reports `columnBaselineMissing` until re-reconciled. It is
+distinct from `selectedColumns` (the curated sync set) — see
+[offline-profile-reconciliation.md](${PLUGIN_ROOT}/shared/references/offline-profile-reconciliation.md).
+Match the canonical entry shape in
+[`/setup-offline-profile` Step 9a](${PLUGIN_ROOT}/skills/setup-offline-profile/SKILL.md)
+without executing that workflow. Any delta check uses
+`--project-root '<working_dir>'` in its own guarded call.
+
+Append to `<working_dir>/memory-bank.md` `## Offline profile` block:
```yaml
addedTables:
diff --git a/plugins/mobile-apps/skills/assign-offline-profile/SKILL.md b/plugins/mobile-apps/skills/assign-offline-profile/SKILL.md
index 2ba0a6ca0..ffd36c1b4 100644
--- a/plugins/mobile-apps/skills/assign-offline-profile/SKILL.md
+++ b/plugins/mobile-apps/skills/assign-offline-profile/SKILL.md
@@ -19,6 +19,15 @@ Bind one or more users and/or teams to an existing Mobile Offline Profile. Witho
Per the maker portal's UX (the "Assign profile to user" dialog under env settings), this is a separate operation from profile creation. Many users hit "I created the profile but offline still doesn't work" — the missing piece is membership.
+Before project reads or commands, apply
+[app-working-directory.md](${PLUGIN_ROOT}/shared/references/app-working-directory.md).
+Resolve one absolute `working_dir` for a direct call or require the child
+invocation's owner root. Keep every shell/file operation, referenced recipe,
+and retry on that root and the selected environment/tenant; missing or
+conflicting context is `NEEDS_CONTEXT`. File tools use `<working_dir>/...`.
+Planning-phase calls may discover and propose the membership diff but must
+return before the confirmation gate, POST/DELETE, or artifact updates.
+
## Workflow
1. Verify project + locate profile → 2. Pick users/teams → 3. Discover existing memberships → 4. Confirm diff (single gate) → 5. POST memberships → 6. Verify → 7. Summary
@@ -28,17 +37,27 @@ Per the maker portal's UX (the "Assign profile to user" dialog under env setting
### Step 1 — Verify project + locate profile
```bash
-test -f power.config.json
-node "${PLUGIN_ROOT}/scripts/resolve-environment.js" "$(node -e \"console.log(require('./power.config.json').environmentId)\")"
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
+environment_id=$(node -p "require('./power.config.json').environmentId || ''") || {
+ echo "BLOCKED: unreadable power.config.json" >&2; exit 1;
+}
+if [ -z "$environment_id" ]; then
+ echo "NEEDS_CONTEXT: selected app has no environmentId" >&2; exit 1;
+fi
+node "${PLUGIN_ROOT}/scripts/resolve-environment.js" "$environment_id" --no-cache --require-tenant
```
+Capture `<envUrl>` and `<tenantId>` and require them to match any supplied owner
+identity. Pass `--tenant-id "<tenantId>"` on every Dataverse request, including
+profile lookup, `WhoAmI`, membership discovery, mutation, readback, and retries.
+
Profile ID resolution (in order):
| Source | Used when |
|---|---|
| `$ARGUMENTS` contains `--profile-id <guid>` | Explicit override |
| `$ARGUMENTS` contains `--profile-name <name>` | Resolve via `GET /mobileofflineprofiles?$filter=name eq '<name>'&$select=mobileofflineprofileid` |
-| `offline-profile.json` in cwd | Read top-level `profileId` field |
+| `<working_dir>/offline-profile.json` | Read top-level `profileId` field |
| Otherwise | `GET /mobileofflineprofiles` and present `AskUserQuestion` with the list (max 4 options) |
STOP if no profile can be resolved. Print: `Run /setup-offline-profile first, or pass --profile-id`.
@@ -80,13 +99,16 @@ Then read the next user message and parse.
For idempotency:
```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
# Existing user memberships for this profile
node "${PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> GET \
- "usermobileofflineprofilememberships?\$filter=_mobileofflineprofileid_value eq <profileId>&\$select=usermobileofflineprofilemembershipid,_systemuserid_value&\$expand=systemuserid_systemuser(\$select=domainname)"
+ "usermobileofflineprofilememberships?\$filter=_mobileofflineprofileid_value eq <profileId>&\$select=usermobileofflineprofilemembershipid,_systemuserid_value&\$expand=systemuserid_systemuser(\$select=domainname)" \
+ --tenant-id "<tenantId>"
# Existing team memberships for this profile
node "${PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> GET \
- "teammobileofflineprofilememberships?\$filter=_mobileofflineprofileid_value eq <profileId>&\$select=teammobileofflineprofilemembershipid,_teamid_value&\$expand=teamid_team(\$select=name)"
+ "teammobileofflineprofilememberships?\$filter=_mobileofflineprofileid_value eq <profileId>&\$select=teammobileofflineprofilemembershipid,_teamid_value&\$expand=teamid_team(\$select=name)" \
+ --tenant-id "<tenantId>"
```
Build the set of `already-bound` UPNs and team names.
@@ -94,11 +116,13 @@ Build the set of `already-bound` UPNs and team names.
For each candidate user/team from Step 2, look up their `systemuserid` / `teamid` (skip if already in `already-bound`):
```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
node "${PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> GET \
- "systemusers?\$filter=domainname eq '<upn>'&\$select=systemuserid,fullname,domainname&\$top=1"
+ "systemusers?\$filter=domainname eq '<upn>'&\$select=systemuserid,fullname,domainname&\$top=1" \
+ --tenant-id "<tenantId>"
node "${PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> GET \
- "teams?\$filter=name eq '<team-name>' and teamtype eq 0&\$select=teamid,name&\$top=1"
+ "teams?\$filter=name eq '<team-name>' and teamtype eq 0&\$select=teamid,name&\$top=1" --tenant-id "<tenantId>"
```
(`teamtype eq 0` excludes Access Teams and Owner Teams — only Manage Teams get profile assignments.)
@@ -152,8 +176,10 @@ For each in `to_add`, POST sequentially (parallel POSTs occasionally return 429)
**User membership:**
```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
node "${PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> POST \
"usermobileofflineprofilememberships" \
+ --tenant-id "<tenantId>" \
--body '{
"[email protected]": "/mobileofflineprofiles(<profileId>)",
"[email protected]": "/systemusers(<systemuserid>)"
@@ -166,8 +192,10 @@ Expected 204 with `OData-EntityId` → capture membership GUID.
**Team membership:**
```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
node "${PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> POST \
"teammobileofflineprofilememberships" \
+ --tenant-id "<tenantId>" \
--body '{
"[email protected]": "/mobileofflineprofiles(<profileId>)",
"[email protected]": "/teams(<teamid>)"
@@ -178,8 +206,9 @@ node "${PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> POST \
For each in `to_remove`, DELETE:
```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
node "${PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> DELETE \
- "usermobileofflineprofilememberships(<membershipid>)"
+ "usermobileofflineprofilememberships(<membershipid>)" --tenant-id "<tenantId>"
```
> **⚠️ Duplicate handling:** POSTing a membership that already exists returns `409 Conflict`. The `dataverse-request.js` wrapper's `looksLikeDuplicate` rescue treats this as silent success (the Step 3 dedup should catch most cases first). Re-runs are safe.
diff --git a/plugins/mobile-apps/skills/create-mobile-app/SKILL.md b/plugins/mobile-apps/skills/create-mobile-app/SKILL.md
index 1de90e4e2..d6e9ccf7d 100644
--- a/plugins/mobile-apps/skills/create-mobile-app/SKILL.md
+++ b/plugins/mobile-apps/skills/create-mobile-app/SKILL.md
@@ -85,7 +85,7 @@ so a teammate opening the repo months later can see the environment, the approve
and the screen plan without re-reading a transcript.
```bash
-node "${PLUGIN_ROOT}/scripts/app-docs.js" --working-dir "<working_dir>" <command>
+node "${PLUGIN_ROOT}/scripts/app-docs.js" --working-dir '<working_dir>' <command>
```
| Command | Use |
@@ -116,12 +116,12 @@ the pattern each one follows:
```bash
DOCS="${PLUGIN_ROOT}/scripts/app-docs.js"
# 1. propose - the tab shows "Proposed - review this, then answer the prompt in your terminal"
-node "$DOCS" --working-dir "<working_dir>" set --section dataModel --json-file <tmp>/data-model.json --state proposed
-node "$DOCS" --working-dir "<working_dir>" step --id data-model --status active --note "Gate 2 — awaiting your approval"
+node "$DOCS" --working-dir '<working_dir>' set --section dataModel --json-file <tmp>/data-model.json --state proposed
+node "$DOCS" --working-dir '<working_dir>' step --id data-model --status active --note "Gate 2 — awaiting your approval"
# 2. point the user at that tab, then ask the gate question
# 3. on approval
-node "$DOCS" --working-dir "<working_dir>" set --section dataModel --json-file <tmp>/data-model.json --state approved
-node "$DOCS" --working-dir "<working_dir>" step --id data-model --status done --note "Gate 2 — approved"
+node "$DOCS" --working-dir '<working_dir>' set --section dataModel --json-file <tmp>/data-model.json --state approved
+node "$DOCS" --working-dir '<working_dir>' step --id data-model --status done --note "Gate 2 — approved"
```
Pass a fresh `--note` when you close a gate. A note belongs to the status it was written with, so
@@ -190,10 +190,10 @@ If `$ARGUMENTS` includes a `--working-dir` (or the user names an existing direct
**Reopen the build plan on resume.** A resume skips Step 2b, where the plan is created and
opened, so open `<working_dir>/docs/create-app-plan.html` in the browser yourself when it exists.
If the earlier run stopped on a failure, the plan still says so and has stopped reloading. Run
- `node "${PLUGIN_ROOT}/scripts/app-docs.js" --working-dir "<working_dir>" show`, and if it reports a `failedPhase`, reopen that phase before continuing:
+ `node "${PLUGIN_ROOT}/scripts/app-docs.js" --working-dir '<working_dir>' show`, and if it reports a `failedPhase`, reopen that phase before continuing:
```bash
- node "${PLUGIN_ROOT}/scripts/app-docs.js" --working-dir "<working_dir>" step --id <failedPhase> --status active
+ node "${PLUGIN_ROOT}/scripts/app-docs.js" --working-dir '<working_dir>' step --id <failedPhase> --status active
```
- **Bank absent** → fresh project. Continue to Step 1.
- **Bank present but corrupted** (missing required headings) → surface the parse error, ask the user whether to overwrite (lose history) or fix manually before proceeding.
@@ -379,8 +379,8 @@ a `"`, a backtick or `$(…)` in it would break out of a shell argument before N
```bash
-node "${PLUGIN_ROOT}/scripts/app-docs.js" --working-dir "<working_dir>" init --json-file <tmp>/plan-init.json
-node "${PLUGIN_ROOT}/scripts/app-docs.js" --working-dir "<working_dir>" step --id requirements --status active --note "Waiting for your answers to the setup questions"
+node "${PLUGIN_ROOT}/scripts/app-docs.js" --working-dir '<working_dir>' init --json-file <tmp>/plan-init.json
+node "${PLUGIN_ROOT}/scripts/app-docs.js" --working-dir '<working_dir>' step --id requirements --status active --note "Waiting for your answers to the setup questions"
```
The note is what raises the waiting-for-input banner on the plan, so the user can tell from the page
@@ -508,8 +508,8 @@ and none of it may go through the shell:
```
```bash
-node "${PLUGIN_ROOT}/scripts/app-docs.js" --working-dir "<working_dir>" set --section requirements --json-file <tmp>/requirements.json
-node "${PLUGIN_ROOT}/scripts/app-docs.js" --working-dir "<working_dir>" step --id requirements --status active --note "Brief confirmed"
+node "${PLUGIN_ROOT}/scripts/app-docs.js" --working-dir '<working_dir>' set --section requirements --json-file <tmp>/requirements.json
+node "${PLUGIN_ROOT}/scripts/app-docs.js" --working-dir '<working_dir>' step --id requirements --status active --note "Brief confirmed"
```
### Step 2c — Plan preview (rough, always shown)
@@ -578,9 +578,9 @@ Proceed, edit brief, or abort? [proceed/edit/abort]
Raise the wait before showing the estimate, and close the phase once the user approves:
```bash
-node "${PLUGIN_ROOT}/scripts/app-docs.js" --working-dir "<working_dir>" step --id requirements --status active --note "Waiting for you to approve the plan preview"
+node "${PLUGIN_ROOT}/scripts/app-docs.js" --working-dir '<working_dir>' step --id requirements --status active --note "Waiting for you to approve the plan preview"
# ... after they approve ...
-node "${PLUGIN_ROOT}/scripts/app-docs.js" --working-dir "<working_dir>" step --id requirements --status done
+node "${PLUGIN_ROOT}/scripts/app-docs.js" --working-dir '<working_dir>' step --id requirements --status done
```
> "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:
@@ -620,7 +620,7 @@ between gates the agents work for minutes, and the plan must not tell the user t
on them while it is not.
```bash
-node "${PLUGIN_ROOT}/scripts/app-docs.js" --working-dir "<working_dir>" step --id architecture --status active --note "Planning the architecture"
+node "${PLUGIN_ROOT}/scripts/app-docs.js" --working-dir '<working_dir>' step --id architecture --status active --note "Planning the architecture"
```
**Raise every gate in the plan as you present it, and take it down as soon as it is answered** -
@@ -637,11 +637,11 @@ browser, and its banner is how they can tell the run is waiting on them rather t
```bash
DOCS="${PLUGIN_ROOT}/scripts/app-docs.js"
# Just before presenting gate <N>:
-node "$DOCS" --working-dir "<working_dir>" set --section <section> --json-file <tmp>/<section>.json --state proposed
-node "$DOCS" --working-dir "<working_dir>" step --id <id> --status active --note "Gate <N> — awaiting your approval"
+node "$DOCS" --working-dir '<working_dir>' set --section <section> --json-file <tmp>/<section>.json --state proposed
+node "$DOCS" --working-dir '<working_dir>' step --id <id> --status active --note "Gate <N> — awaiting your approval"
# As soon as the user approves it:
-node "$DOCS" --working-dir "<working_dir>" set --section <section> --json-file <tmp>/<section>.json --state approved
-node "$DOCS" --working-dir "<working_dir>" step --id <next id> --status active --note "<note from the table>"
+node "$DOCS" --working-dir '<working_dir>' set --section <section> --json-file <tmp>/<section>.json --state approved
+node "$DOCS" --working-dir '<working_dir>' step --id <next id> --status active --note "<note from the table>"
```
Flip each section to `approved` when its gate is answered, not later in the Step 3.9 batch. A
@@ -689,6 +689,17 @@ call `detect-publisher-prefix.js`.
### Foreground Dataverse planning snapshot and evidence
+This read-only helper recipe is also used by
+[scoped Dataverse change planning](../../shared/references/dataverse-change-planning.md).
+Those callers supply their own request scope and approvals; they do not run
+the create wizard or dispatch its native-app planner.
+
+Apply [app-working-directory.md](../../shared/references/app-working-directory.md)
+before this recipe. Each shell block below and in Dataverse planning recovery
+re-enters the owner's absolute root. Re-supply the selected identity and artifact
+paths on every call; fresh-shell retries re-execute the complete guarded
+attempt block, including its variable assignments and function definition.
+
Planning stays read-only. The resolver's `--no-cache` mode may read existing
identity metadata, but must not persist the environment cache, auth settings,
or telemetry cluster, and must not replay pending telemetry. Normal resolution
@@ -708,6 +719,7 @@ Branch on the Gate 1-approved
nested planner or architect rediscover the tenant.
```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
node "${PLUGIN_ROOT}/scripts/resolve-environment.js" "$ACTIVE_ENV_ID" --no-cache --require-tenant
```
@@ -755,10 +767,11 @@ Detailed advisory discovery is quality-bounded:
expansion, at most once per newly selected logical name.
```bash
-SNAPSHOT_PATH="<working_dir>/.tmp/dataverse-foreground-planning-snapshot.json"
-CONCEPTS_PATH="<working_dir>/.tmp/dataverse-concepts.json"
-ARCHITECT_EVIDENCE_PATH="<working_dir>/.tmp/dataverse-architect-evidence.json"
-INVENTORY_CACHE_PATH="<working_dir>/.tmp/dataverse-inventory-cache.json"
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
+SNAPSHOT_PATH='<working_dir>/.tmp/dataverse-foreground-planning-snapshot.json'
+CONCEPTS_PATH='<working_dir>/.tmp/dataverse-concepts.json'
+ARCHITECT_EVIDENCE_PATH='<working_dir>/.tmp/dataverse-architect-evidence.json'
+INVENTORY_CACHE_PATH='<working_dir>/.tmp/dataverse-inventory-cache.json'
run_dataverse_planning_attempt() {
if ! node "${PLUGIN_ROOT}/scripts/create-dataverse-snapshot.js" \
@@ -864,6 +877,8 @@ live Dataverse calls inside the agent. For `connector-only`, pass the mode
explicitly and state that both paths are not supplied; never provide placeholder
file paths.
+#### Planner completion dispatch
+
**Hard rule — planner writes are restricted during Step 3.** The planner (and any sub-agents it spawns) is permitted to write to **only**:
- `<working_dir>/native-app-plan.md`
@@ -1084,6 +1099,8 @@ non-Dataverse context, capped at 2 retries; `BLOCKED:` reports the blocker. Unkn
lines are malformed. Recoverable artifact/input failures return to their
owning phase for repair; they never authorize skipping an applicable gate.
+#### Dataverse planning recovery
+
The structured Dataverse signals below use monotonic name tracking or
deterministic revision instead of the generic retry cap. In `required` only,
initialize two in-memory sets from the current validated snapshot before
@@ -1133,6 +1150,7 @@ Compute `NEW_DETAIL_NAMES = requested names - DETAIL_ATTEMPTED_NAMES`.
and a new app-owned table.
```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
node "${PLUGIN_ROOT}/scripts/create-dataverse-snapshot.js" \
--env-url "$ACTIVE_ENV_URL" \
--tenant-id "$ACTIVE_TENANT_ID" \
@@ -1181,6 +1199,7 @@ snapshot. Compute
this same set-difference rule automatically.
```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
node "${PLUGIN_ROOT}/scripts/create-dataverse-snapshot.js" \
--env-url "$ACTIVE_ENV_URL" \
--tenant-id "$ACTIVE_TENANT_ID" \
@@ -1263,7 +1282,7 @@ user-facing design decision without another planning question.
4. Persist the answer:
```bash
- echo "<chosen-industry-slug>" > "<working_dir>/.industry-confirmed"
+ echo "<chosen-industry-slug>" > '<working_dir>/.industry-confirmed'
```
For option (e), let the user free-text a description; map it to the closest slug (or `productivity` as final fallback) and store that.
@@ -1367,13 +1386,13 @@ document explaining what was agreed:
```bash
DOCS="${PLUGIN_ROOT}/scripts/app-docs.js"
-node "$DOCS" --working-dir "<working_dir>" set --section architecture --json-file <tmp>/architecture.json --state approved
-node "$DOCS" --working-dir "<working_dir>" step --id architecture --status done --note "Gate 1 — approved"
-node "$DOCS" --working-dir "<working_dir>" set --section trust --json-file <tmp>/trust.json --state proposed
-node "$DOCS" --working-dir "<working_dir>" set --section dataModel --json-file <tmp>/data-model.json --state approved
-node "$DOCS" --working-dir "<working_dir>" step --id data-model --status done --note "Gate 2 — <n> tables approved"
-node "$DOCS" --working-dir "<working_dir>" set --section screens --json-file <tmp>/screens.json --state approved
-node "$DOCS" --working-dir "<working_dir>" step --id screen-plan --status done --note "Gates 3-4 — <n> screens approved"
+node "$DOCS" --working-dir '<working_dir>' set --section architecture --json-file <tmp>/architecture.json --state approved
+node "$DOCS" --working-dir '<working_dir>' step --id architecture --status done --note "Gate 1 — approved"
+node "$DOCS" --working-dir '<working_dir>' set --section trust --json-file <tmp>/trust.json --state proposed
+node "$DOCS" --working-dir '<working_dir>' set --section dataModel --json-file <tmp>/data-model.json --state approved
+node "$DOCS" --working-dir '<working_dir>' step --id data-model --status done --note "Gate 2 — <n> tables approved"
+node "$DOCS" --working-dir '<working_dir>' set --section screens --json-file <tmp>/screens.json --state approved
+node "$DOCS" --working-dir '<working_dir>' step --id screen-plan --status done --note "Gates 3-4 — <n> screens approved"
```
**Write a first-pass trust report here.** Gate 1 settles the device capabilities and connectors,
@@ -1392,8 +1411,8 @@ the ER diagram, the column tables, and the new/reused/extended colours are all d
pending, or the plan never reaches 100%:
```bash
-node "$DOCS" --working-dir "<working_dir>" step --id data-model --status skipped
-node "$DOCS" --working-dir "<working_dir>" step --id dataverse --status skipped
+node "$DOCS" --working-dir '<working_dir>' step --id data-model --status skipped
+node "$DOCS" --working-dir '<working_dir>' step --id dataverse --status skipped
```
### Step 4 — Auth & environment selection
@@ -1413,7 +1432,7 @@ If the resolved environment doesn't match what the planner used in Step 3, ask t
Open the scaffold phase:
```bash
-node "${PLUGIN_ROOT}/scripts/app-docs.js" --working-dir "<working_dir>" step --id scaffold --status active
+node "${PLUGIN_ROOT}/scripts/app-docs.js" --working-dir '<working_dir>' step --id scaffold --status active
```
This step is template-only and foreground-only. Do not clone/copy templates, do not run background scaffold jobs, and do not use any legacy fallback path.
@@ -1496,7 +1515,7 @@ Bundle ID and scheme are left as template defaults — they are fixed across all
Manual `npm run dev` must remain the normal Expo entry point. The template's `metro.config.js` delegates to `createPowerAppsMetroConfig` from `@microsoft/power-apps-native-host/config/metroConfig`; that factory installs sanitized Metro terminal and HTTP bundle-failure logging under `.powernative/metro-logs/`. Manual starts and `/debug-app` use the same log source without a process-owning wrapper. Verify these script entries only; do not add wrapper-specific scripts:
```bash
-node - "<working_dir>" <<'NODE'
+node - '<working_dir>' <<'NODE'
const fs = require('node:fs');
const path = require('node:path');
const root = process.argv[2];
@@ -1541,7 +1560,13 @@ template or repair the precise stale import before continuing.
**Fix 6 — Schema generation boundary**
-`app/_layout.tsx` imports `schemaMap` from `src/generated/connectorSchemas.ts`, which is generated by `npm run generate-schemas` (the `generate-connector-schemas` binary from the `@microsoft/power-apps-cli` devDep). Do not generate an empty schema map during initial scaffold: the template's `@ts-ignore` boundary lets `tsc` validate the scaffold without that artifact, and schema generation is more useful after a data source exists or immediately before dev/build entry points.
+`app/_layout.tsx` imports `schemaMap` from `src/generated/connectorSchemas.ts`, which
+is generated by the template's `npm run generate-schemas` script. This builds the
+runtime schema map; Power Apps CLI add/refresh/remove commands own source
+registrations and generated models/services. Do not generate an empty schema map
+during initial scaffold: the template's `@ts-ignore` boundary lets `tsc` validate
+the scaffold without that artifact, and schema generation is more useful after a
+data source exists or immediately before dev/build entry points.
Do NOT hand-write a stub `connectorSchemas.ts` — the generated output has a specific shape that downstream code depends on; a placeholder will break `pa app push`.
@@ -1623,7 +1648,7 @@ do not add this CLI-generated file to Step 5's manual validation targets or hand
This step verifies dependencies only. The user must have run `npm install` before invoking the skill.
```bash
-[ -d "<working_dir>/node_modules/expo" ] && echo "✓ node_modules present" || echo "✗ missing — run npm install in the template folder and rerun"
+[ -d '<working_dir>/node_modules/expo' ] && echo "✓ node_modules present" || echo "✗ missing — run npm install in the template folder and rerun"
```
If `node_modules/expo` is missing, STOP. Tell the user to run `npm install` in the template folder. Do not provision ADO tokens or run `npm install` from this skill.
@@ -1658,13 +1683,13 @@ This is the **Scaffold gate** from the TypeScript Gate Policy. If it fails, capt
A clean scaffold gate is what completes the scaffold phase:
```bash
-node "${PLUGIN_ROOT}/scripts/app-docs.js" --working-dir "<working_dir>" step --id scaffold --status done
+node "${PLUGIN_ROOT}/scripts/app-docs.js" --working-dir '<working_dir>' step --id scaffold --status done
```
### Step 6.7 — Seed the memory bank
```bash
-cp "${PLUGIN_ROOT}/shared/memory-bank.md" "<working_dir>/memory-bank.md"
+cp "${PLUGIN_ROOT}/shared/memory-bank.md" '<working_dir>/memory-bank.md'
```
Fill in the Project facts and Power Platform context sections from Steps 2 and 4. From here on, every step appends to the relevant section of `<working_dir>/memory-bank.md` immediately after success — not at the end. This is what enables Step 0's resume on a future run.
@@ -1694,7 +1719,7 @@ visual_companion: <yes|no> # default from Step 2b; applied at Step 6.75 and la
it open, because this branch never reaches the `done` call below:
```bash
-node "${PLUGIN_ROOT}/scripts/app-docs.js" --working-dir "<working_dir>" step --id design --status skipped
+node "${PLUGIN_ROOT}/scripts/app-docs.js" --working-dir '<working_dir>' step --id design --status skipped
```
Marking it `active` here instead would leave it active through auth and most of Step 8, until
@@ -1706,7 +1731,7 @@ opening the next phase auto-closed it as `done` — reporting a design system th
asks for brand inputs, a cost choice and a style pick, so the phase opens as waiting:
```bash
-node "${PLUGIN_ROOT}/scripts/app-docs.js" --working-dir "<working_dir>" step --id design --status active --note "Waiting for your brand and design choices"
+node "${PLUGIN_ROOT}/scripts/app-docs.js" --working-dir '<working_dir>' step --id design --status active --note "Waiting for your brand and design choices"
```
```
@@ -1729,7 +1754,7 @@ As soon as `/design-system` returns, replace the note — the user has answered
working again:
```bash
-node "${PLUGIN_ROOT}/scripts/app-docs.js" --working-dir "<working_dir>" step --id design --status active --note "Applying your design system"
+node "${PLUGIN_ROOT}/scripts/app-docs.js" --working-dir '<working_dir>' step --id design --status active --note "Applying your design system"
```
Handle the return per the status protocol (AGENTS.md rule #10):
@@ -1779,7 +1804,7 @@ ownership contract during this phase.
of TSX exists. Those same per-screen blocks become the carousel:
```bash
-node "${PLUGIN_ROOT}/scripts/app-docs.js" --working-dir "<working_dir>" phone --stage screens --screens-file <tmp>/screens-preview.json
+node "${PLUGIN_ROOT}/scripts/app-docs.js" --working-dir '<working_dir>' phone --stage screens --screens-file <tmp>/screens-preview.json
```
`screens-preview.json` is `[{ "name": "Today's route", "html": "<the screen's markup>" }, …]`, in
@@ -1812,8 +1837,8 @@ goes to a file rather than through the shell:
```bash
-node "${PLUGIN_ROOT}/scripts/app-docs.js" --working-dir "<working_dir>" set --section design --json-file <tmp>/design.json
-node "${PLUGIN_ROOT}/scripts/app-docs.js" --working-dir "<working_dir>" step --id design --status done
+node "${PLUGIN_ROOT}/scripts/app-docs.js" --working-dir '<working_dir>' set --section design --json-file <tmp>/design.json
+node "${PLUGIN_ROOT}/scripts/app-docs.js" --working-dir '<working_dir>' step --id design --status done
```
Only `#rrggbb` literals render as swatches; any other value is shown as text rather than
@@ -1828,7 +1853,7 @@ own the plan showed nothing in progress here at all: the design phase closes bef
Dataverse phase does not open until Step 8.
```bash
-node "${PLUGIN_ROOT}/scripts/app-docs.js" --working-dir "<working_dir>" step --id auth --status active --note "Waiting for your Entra ID app registration"
+node "${PLUGIN_ROOT}/scripts/app-docs.js" --working-dir '<working_dir>' step --id auth --status active --note "Waiting for your Entra ID app registration"
```
**Print before starting:**
@@ -2029,8 +2054,8 @@ Do NOT touch `src/playerConfig.ts` — auth identifiers live in `auth.config.jso
Close the auth phase once the client ID is written and the config is in place:
```bash
-node "${PLUGIN_ROOT}/scripts/app-docs.js" --working-dir "<working_dir>" set --section auth --json-file <tmp>/auth.json
-node "${PLUGIN_ROOT}/scripts/app-docs.js" --working-dir "<working_dir>" step --id auth --status done
+node "${PLUGIN_ROOT}/scripts/app-docs.js" --working-dir '<working_dir>' set --section auth --json-file <tmp>/auth.json
+node "${PLUGIN_ROOT}/scripts/app-docs.js" --working-dir '<working_dir>' step --id auth --status done
```
`auth.json` is `{"status":"<Configured — how sign-in was set up|Deferred — why>"}`. It goes to a
@@ -2051,7 +2076,7 @@ Otherwise open the Dataverse phase now. Creating tables is one of the longest wa
with no phase open the plan reads "Waiting to start" through all of it:
```bash
-node "${PLUGIN_ROOT}/scripts/app-docs.js" --working-dir "<working_dir>" step --id dataverse --status active
+node "${PLUGIN_ROOT}/scripts/app-docs.js" --working-dir '<working_dir>' step --id dataverse --status active
```
**Print before starting:**
@@ -2078,23 +2103,23 @@ resolved context and these structured artifacts, never values inferred from
free-form Markdown:
```bash
-SCHEMA_CONTRACT="<working_dir>/.tmp/dataverse-schema-contract.json"
-APPROVAL_RECEIPT="<working_dir>/.tmp/mobile-plan-status.json"
-FOREGROUND_PLANNING_SNAPSHOT="<working_dir>/.tmp/dataverse-foreground-planning-snapshot.json"
-RECONCILIATION_SCOPE="<working_dir>/.tmp/dataverse-reconciliation-scope.json"
-EXECUTION_RECONCILIATION="<working_dir>/.tmp/dataverse-execution-reconciliation.json"
-OPERATION_MANIFEST="<working_dir>/.tmp/dataverse-operation-manifest.json"
-PUBLISH_CHECKPOINT="<working_dir>/.tmp/dataverse-publish-pending.json"
+SCHEMA_CONTRACT='<working_dir>/.tmp/dataverse-schema-contract.json'
+APPROVAL_RECEIPT='<working_dir>/.tmp/mobile-plan-status.json'
+FOREGROUND_PLANNING_SNAPSHOT='<working_dir>/.tmp/dataverse-foreground-planning-snapshot.json'
+RECONCILIATION_SCOPE='<working_dir>/.tmp/dataverse-reconciliation-scope.json'
+EXECUTION_RECONCILIATION='<working_dir>/.tmp/dataverse-execution-reconciliation.json'
+OPERATION_MANIFEST='<working_dir>/.tmp/dataverse-operation-manifest.json'
+PUBLISH_CHECKPOINT='<working_dir>/.tmp/dataverse-publish-pending.json'
ACTIVE_SOLUTION_UNIQUE_NAME="Default"
test -f "$SCHEMA_CONTRACT" -a -f "$APPROVAL_RECEIPT" \
-a -f "$FOREGROUND_PLANNING_SNAPSHOT" \
- -a -f "<working_dir>/native-app-plan.md"
+ -a -f '<working_dir>/native-app-plan.md'
node "${PLUGIN_ROOT}/scripts/build-dataverse-operation-manifest.js" \
--bind-plan "$SCHEMA_CONTRACT" \
--approval-receipt "$APPROVAL_RECEIPT" \
- --plan "<working_dir>/native-app-plan.md" \
+ --plan '<working_dir>/native-app-plan.md' \
--output "$SCHEMA_CONTRACT"
node "${PLUGIN_ROOT}/scripts/build-dataverse-operation-manifest.js" \
@@ -2117,7 +2142,7 @@ node "${PLUGIN_ROOT}/scripts/build-dataverse-operation-manifest.js" \
--contract "$SCHEMA_CONTRACT" \
--approval-receipt "$APPROVAL_RECEIPT" \
--reconciliation "$EXECUTION_RECONCILIATION" \
- --plan "<working_dir>/native-app-plan.md" \
+ --plan '<working_dir>/native-app-plan.md' \
--output "$OPERATION_MANIFEST" \
--environment-id "$ACTIVE_ENV_ID" \
--env-url "$ACTIVE_ENV_URL" \
@@ -2139,7 +2164,7 @@ node "${PLUGIN_ROOT}/scripts/build-dataverse-operation-manifest.js" \
--contract "$SCHEMA_CONTRACT" \
--approval-receipt "$APPROVAL_RECEIPT" \
--reconciliation "$EXECUTION_RECONCILIATION" \
- --plan "<working_dir>/native-app-plan.md" \
+ --plan '<working_dir>/native-app-plan.md' \
--environment-id "$ACTIVE_ENV_ID" \
--env-url "$ACTIVE_ENV_URL" \
--tenant-id "$ACTIVE_TENANT_ID" \
@@ -2155,6 +2180,13 @@ artifact paths:
```
Invoke skill: /add-dataverse
+Context:
+ MOBILE_APP_ORCHESTRATING=1
+ orchestrator: create-mobile-app
+ working_dir: <working_dir>
+ phase: implementation
+ approved_scope: <approved Data Model and bound operation-manifest artifacts>
+
Arguments:
--working-dir <working_dir>
--plan-section <native-app-plan.md#data-model>
@@ -2189,12 +2221,12 @@ npx --no-install tsc --noEmit
If this fails, do not continue to native capabilities, connectors, navigation, or screens. Capture the full error list once, batch-fix generated-service/model or alias-map issues, then rerun the gate. If the failure is a hidden Dataverse collision already recovered via an alias (for example `aircraft` → `aircraftv2`), make sure the alias is reflected in `native-app-plan.md`, `memory-bank.md`, and the Generated Services snapshot before rerunning.
-### Step 8.5 — Seed sample data (auto)
+### Step 8.5 — Seed sample data (approved scope)
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"`.
+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
@@ -2207,18 +2239,38 @@ 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."
+> "→ [Step 8.5/13] Confirming seed scope, then checking record counts for approved tables."
-Invoke `/add-sample-data` after Step 8. This step is **not optional** — every fresh-scaffolded app must have data to render on first launch:
+Run this phase after Step 8 for Dataverse apps. Derive the seed candidate list
+from the approved service requirements and verified materialized inventory,
+excluding standard system tables by default. Include reused custom tables when
+the approved app needs sample data from them. Do not infer insertion permission
+from `status: new`, record counts, or manifest presence. If the initial approval
+did not cover the exact seed set and count/media policy, obtain that approval
+before invoking; an empty or declined scope skips seeding without cloud writes.
```
Invoke skill: /add-sample-data
+Context:
+ MOBILE_APP_ORCHESTRATING=1
+ orchestrator: create-mobile-app
+ working_dir: <working_dir>
+ phase: implementation
+ approved_scope: <approved seed tables and count/media policy>
+ retiring_tables: <empty for fresh creation>
+
Arguments:
- --working-dir <working_dir>
+ --working-dir '<working_dir>'
+ --tables "<approved-seed-table-logical-names>"
```
-`/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.
+`/add-sample-data` validates this explicit allowlist against
+`.datamodel-manifest.json` before per-table discovery, then checks row counts
+only for approved targets. It skips tables with enough rows and seeds the
+eligible targets in dependency order. Inserted GUIDs are tracked in
+`memory-bank.md` for idempotent re-runs. Missing parents cannot widen the seed
+scope without returning to the owner for approval.
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,
@@ -2250,7 +2302,7 @@ Otherwise ask one neutral foreground question. Say so in the plan first, and rep
once the user answers:
```bash
-node "${PLUGIN_ROOT}/scripts/app-docs.js" --working-dir "<working_dir>" step --id dataverse --status active --note "Waiting for your offline support choice"
+node "${PLUGIN_ROOT}/scripts/app-docs.js" --working-dir '<working_dir>' step --id dataverse --status active --note "Waiting for your offline support choice"
```
@@ -2269,6 +2321,12 @@ node "${PLUGIN_ROOT}/scripts/app-docs.js" --working-dir "<working_dir>" step --i
> `status: not-applicable`, then continue to Step 9
If the user selects Yes, invoke `/setup-offline-profile` from the project root.
+Pass `--working-dir '<working_dir>'` and invocation context
+`MOBILE_APP_ORCHESTRATING=1`, `orchestrator: create-mobile-app`, the same absolute
+`working_dir`, `phase: implementation`, and the selected environment ID/URL/tenant.
+This choice approves entering the offline wizard, not its prerequisite or
+profile mutations; the wizard retains its own gates and forwards their exact
+approved scope to its helpers.
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.
@@ -2276,7 +2334,7 @@ failure. Do not reopen data-model or screen approvals after this choice.
Tables and generated services now exist, so the Dataverse phase is complete:
```bash
-node "${PLUGIN_ROOT}/scripts/app-docs.js" --working-dir "<working_dir>" step --id dataverse --status done
+node "${PLUGIN_ROOT}/scripts/app-docs.js" --working-dir '<working_dir>' step --id dataverse --status done
```
### Step 9 — Apply native capabilities
@@ -2286,7 +2344,7 @@ node "${PLUGIN_ROOT}/scripts/app-docs.js" --working-dir "<working_dir>" step --i
Open the capabilities phase; Step 10 closes it after connectors are added:
```bash
-node "${PLUGIN_ROOT}/scripts/app-docs.js" --working-dir "<working_dir>" step --id capabilities --status active
+node "${PLUGIN_ROOT}/scripts/app-docs.js" --working-dir '<working_dir>' step --id capabilities --status active
```
**Print before starting:**
@@ -2404,6 +2462,11 @@ Read the `## Connectors` section from `native-app-plan.md`. If it says "None", s
For each row in the table, route to the correct skill based on the API name:
+Pass `MOBILE_APP_ORCHESTRATING=1`, `orchestrator: create-mobile-app`,
+`phase: implementation`, `working_dir`, and `approved_scope` containing the
+connector row and supplied operation/dataset/table/connection choices to each
+invocation. A dedicated skill inherits this context when the generic skill routes.
+
| API name | Invoke |
|---|---|
| `sharepointonline` | `/add-sharepoint --working-dir <working_dir>` |
@@ -2416,7 +2479,7 @@ Run sequentially — each generates files under `src/generated/`. Parallel write
Device capabilities and connectors are both wired, so close the phase:
```bash
-node "${PLUGIN_ROOT}/scripts/app-docs.js" --working-dir "<working_dir>" step --id capabilities --status done
+node "${PLUGIN_ROOT}/scripts/app-docs.js" --working-dir '<working_dir>' step --id capabilities --status done
```
**Finalise the trust report.** Gate 1 wrote a first pass from the approved plan; everything it
@@ -2425,7 +2488,7 @@ what the offline profile syncs. Rewrite it in full and mark it `approved`, so it
app *does* rather than what was intended. `set` merges, so restate every key you want to change.
```bash
-node "${PLUGIN_ROOT}/scripts/app-docs.js" --working-dir "<working_dir>" set --section trust --json-file <tmp>/trust.json --state approved
+node "${PLUGIN_ROOT}/scripts/app-docs.js" --working-dir '<working_dir>' set --section trust --json-file <tmp>/trust.json --state approved
```
`trust.json` has four keys:
@@ -2483,7 +2546,7 @@ Open the screens phase here rather than at the first screen wave. Navigation, sh
first wave are most of what is left of the run, and the plan should say what is being built:
```bash
-node "${PLUGIN_ROOT}/scripts/app-docs.js" --working-dir "<working_dir>" step --id screens --status active
+node "${PLUGIN_ROOT}/scripts/app-docs.js" --working-dir '<working_dir>' step --id screens --status active
```
Read `## Screens → Navigation Pattern` from `native-app-plan.md`.
@@ -2716,7 +2779,7 @@ Read all per-screen specs in `## Screens → ### Per-Screen Specs`. Identify:
```bash
# Example — if plan has "Inspections" entity used on list + detail + home screens:
-cat > "<working_dir>/src/components/InspectionRow.tsx" << 'EOF'
+cat > '<working_dir>/src/components/InspectionRow.tsx' << 'EOF'
... generated component ...
EOF
```
@@ -2996,7 +3059,7 @@ npx --no-install tsc --noEmit
**Mark screen progress in the plan** once the wave's TypeScript gate is clean:
```bash
-node "${PLUGIN_ROOT}/scripts/app-docs.js" --working-dir "<working_dir>" step --id screens --status active --note "<n> of <total> screens built"
+node "${PLUGIN_ROOT}/scripts/app-docs.js" --working-dir '<working_dir>' step --id screens --status active --note "<n> of <total> screens built"
```
The plan's phone is already showing the screen carousel from Step 6.75, so there is nothing to
@@ -3087,7 +3150,7 @@ After `tsc` passes, offer a static HTML preview. The dev server starts next (Ste
Mark the wait, since the run does not continue until the user picks:
```bash
-node "${PLUGIN_ROOT}/scripts/app-docs.js" --working-dir "<working_dir>" step --id screens --status active --note "Waiting for your preview choice"
+node "${PLUGIN_ROOT}/scripts/app-docs.js" --working-dir '<working_dir>' step --id screens --status active --note "Waiting for your preview choice"
```
@@ -3110,7 +3173,7 @@ node "${PLUGIN_ROOT}/scripts/app-docs.js" --working-dir "<working_dir>" step --i
Every screen is built and type-checked, so close the screens phase:
```bash
-node "${PLUGIN_ROOT}/scripts/app-docs.js" --working-dir "<working_dir>" step --id screens --status done
+node "${PLUGIN_ROOT}/scripts/app-docs.js" --working-dir '<working_dir>' step --id screens --status done
```
### Step 12 — Start dev server (Metro writes project-local logs)
@@ -3123,7 +3186,7 @@ node "${PLUGIN_ROOT}/scripts/app-docs.js" --working-dir "<working_dir>" step --i
Open the final phase (Step 13 marks it done):
```bash
-node "${PLUGIN_ROOT}/scripts/app-docs.js" --working-dir "<working_dir>" step --id run --status active
+node "${PLUGIN_ROOT}/scripts/app-docs.js" --working-dir '<working_dir>' step --id run --status active
```
This skill launches the template's canonical `npm run dev` command. Its `predev` lifecycle runs schema generation followed by the final TypeScript gate before Expo starts, and logging is configured in `metro.config.js`.
@@ -3143,7 +3206,7 @@ The **port** is the log identity: it is what the QR encodes, what the device dia
**Launch command:**
```bash
-cd "<working_dir>"
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
npm run dev
```
@@ -3154,7 +3217,7 @@ This is a long-running dev server. In hosts that support background terminals, r
Read the initial terminal output and locate the generated `.powernative` log directly:
```bash
-ls -t "<working_dir>/.powernative/metro-logs"/metro-*-pid-*-port-*.log 2>/dev/null | head -1
+ls -t '<working_dir>/.powernative/metro-logs'/metro-*-pid-*-port-*.log 2>/dev/null | head -1
```
Branch as follows:
@@ -3168,7 +3231,7 @@ Branch as follows:
**When Expo prints a Metro URL:** Do not rely on Expo's terminal-rendered QR as the only presentation path.
1. **Generate QR code PNG and present it to the user** (chat-first, deterministic fallback):
- - Define `METRO_QR="<working_dir>/.expo/metro-qr.png"` and run `npx --no-install qrcode -o "$METRO_QR" "<metro-url>"`. The template pins `qrcode` as a devDependency, so this runs the copy from the user's `npm install` and never downloads. If it fails (for example, a project created before the pin), continue without the image — never retry with `--yes`, a bare `npx qrcode`, or a different registry.
+ - Define `METRO_QR='<working_dir>/.expo/metro-qr.png'` and run `npx --no-install qrcode -o "$METRO_QR" "<metro-url>"`. The template pins `qrcode` as a devDependency, so this runs the copy from the user's `npm install` and never downloads. If it fails (for example, a project created before the pin), continue without the image — never retry with `--yes`, a bare `npx qrcode`, or a different registry.
- Verify the PNG with a host-neutral Node check: `node -e "const fs=require('node:fs'); process.exit(fs.existsSync(process.argv[1]) ? 0 : 1)" "$METRO_QR"`. If it fails, print the qrcode error and continue without the image.
- **Chat-first render (best effort):** read and base64-encode the file with Node (`node -e "process.stdout.write(require('node:fs').readFileSync(process.argv[1]).toString('base64'))" "$METRO_QR"`) and embed in markdown as a data URI (`![QR](data:image/png;base64,<data>)`) so hosts that support inline image markdown show the QR directly in chat.
- **Guaranteed visible fallback: the build plan, not a new window.** If inline chat image rendering is unavailable, do **not** open the PNG with the host's file-open tool or an OS command. The plan already draws the QR in its phone frame and links the file underneath it for scanning full size, so a window opening on top of a run the user is watching adds nothing. Print the quoted path instead, and point at the plan. Never interpolate an unquoted project path.
@@ -3193,8 +3256,8 @@ Do not persist PIDs, ports, or Metro URLs to the memory bank. They are ephemeral
**Put the QR in the plan** so the document ends on the thing the user acts on:
```bash
-node "${PLUGIN_ROOT}/scripts/app-docs.js" --working-dir "<working_dir>" phone --stage qr \
- --qr-image "<working_dir>/.expo/metro-qr.png" --qr-url "<metro-url>"
+node "${PLUGIN_ROOT}/scripts/app-docs.js" --working-dir '<working_dir>' phone --stage qr \
+ --qr-image '<working_dir>/.expo/metro-qr.png' --qr-url "<metro-url>"
```
The PNG is inlined as a data URI, so the plan still shows the code after `.expo/` is cleaned. This
@@ -3245,7 +3308,7 @@ Debug logs : .powernative/metro-logs/
Close the build plan before printing the summary:
```bash
-node "${PLUGIN_ROOT}/scripts/app-docs.js" --working-dir "<working_dir>" step --id run --status done
+node "${PLUGIN_ROOT}/scripts/app-docs.js" --working-dir '<working_dir>' step --id run --status done
```
Point the user at `docs/create-app-plan.html` once — it holds the environment, the approved data
diff --git a/plugins/mobile-apps/skills/debug-app/SKILL.md b/plugins/mobile-apps/skills/debug-app/SKILL.md
index 0a43b8f57..f74bdd3ba 100644
--- a/plugins/mobile-apps/skills/debug-app/SKILL.md
+++ b/plugins/mobile-apps/skills/debug-app/SKILL.md
@@ -142,7 +142,7 @@ Do not resolve the environment or call Dataverse during ordinary bundle, React,
Use the validated `<working_dir>` from argument parsing. Enumerate **all** matching logs, newest first:
```bash
-LOG_DIR="<working_dir>/.powernative/metro-logs"
+LOG_DIR='<working_dir>/.powernative/metro-logs'
ls -t "$LOG_DIR"/metro-*-pid-*-port-*.log 2>/dev/null
```
@@ -272,7 +272,7 @@ Run the bundled verifier for every candidate diagnostic before writing:
```bash
printf '%s' "$DIAGNOSTIC_SUMMARY" | node \
"${PLUGIN_ROOT}/scripts/redact-debug-diagnostic.js" \
- --working-dir "<working_dir>"
+ --working-dir '<working_dir>'
```
Persist only the verifier's stdout. Build `DIAGNOSTIC_SUMMARY` from minimal fields first; do not pass a full Metro window or response body and rely on redaction to make it safe.
diff --git a/plugins/mobile-apps/skills/deploy/SKILL.md b/plugins/mobile-apps/skills/deploy/SKILL.md
index 8fccdbe02..acb4b4bf7 100644
--- a/plugins/mobile-apps/skills/deploy/SKILL.md
+++ b/plugins/mobile-apps/skills/deploy/SKILL.md
@@ -166,10 +166,16 @@ If a native packaging step fails, surface the error and STOP. If the app renders
This is the final chance to catch schema that never made it into the Mobile Offline Profile before it ships — a table added to the data model but not the profile never syncs to devices, and a new column arrives blank offline. Validate that every schema change is covered **before** pushing.
+For this offline gate, first resolve the approved app's absolute `working_dir`
+using [app-working-directory.md](${PLUGIN_ROOT}/shared/references/app-working-directory.md)
+before running the check below or any helper. Bind every offline check, file
+read, and helper call to that same root.
+
Run the local, no-network delta check (`.datamodel-manifest.json` vs `offline-profile.json`):
```bash
-node "${PLUGIN_ROOT}/scripts/offline-profile-delta.js"
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
+node "${PLUGIN_ROOT}/scripts/offline-profile-delta.js" --project-root '<working_dir>'
```
Branch on the JSON `status` (full contract in [offline-profile-reconciliation.md](${PLUGIN_ROOT}/shared/references/offline-profile-reconciliation.md)):
@@ -194,7 +200,7 @@ Branch on the JSON `status` (full contract in [offline-profile-reconciliation.md
Options:
-- **Update the offline profile now (recommended)** — read and execute `${PLUGIN_ROOT}/skills/add-table-to-offline-profile/SKILL.md` for each `missingTables[]` entry (or once with `--all-new`), then read and execute `${PLUGIN_ROOT}/skills/edit-offline-profile/SKILL.md` with `--table <t> --columns add:<newColumns>` for each `tablesWithNewColumns[]` entry. Follow the ordering in the reconciliation reference, then re-run the delta check; when it reports `in-sync`, continue to Step 3.
+- **Update the offline profile now (recommended)** — use the reconciliation reference's **Scoped helper handoffs** with `orchestrator: deploy`, absolute `working_dir`, `phase: implementation`, and the approved environment/profile/table scope. Read and execute `${PLUGIN_ROOT}/skills/add-table-to-offline-profile/SKILL.md` with `--working-dir '<working_dir>' --table <t>` for each approved `missingTables[]` entry, then `${PLUGIN_ROOT}/skills/edit-offline-profile/SKILL.md` with those arguments plus `--columns add:<newColumns>` for each approved `tablesWithNewColumns[]` entry. Re-run the guarded delta check; when it reports `in-sync`, continue to Step 3.
- **Deploy anyway** — requires an explicit override. Wait for the exact phrase `deploy without offline` (case-insensitive); a bare `y`/`yes` is not enough, mirroring the environment-mismatch gate in Step 3. Then continue to Step 3 and note the skipped reconciliation in the Step 4 build-history row.
Do not push until the gate is resolved (reconciled to `in-sync`, or explicitly overridden).
diff --git a/plugins/mobile-apps/skills/design-system/references/vibe/style-picker.md b/plugins/mobile-apps/skills/design-system/references/vibe/style-picker.md
index 92f46b492..0a1fbeec3 100644
--- a/plugins/mobile-apps/skills/design-system/references/vibe/style-picker.md
+++ b/plugins/mobile-apps/skills/design-system/references/vibe/style-picker.md
@@ -313,13 +313,16 @@ On `yes` (or no answer), try OS-appropriate openers in sequence and fall back to
it interrupts the user rather than showing them something new.
```bash
-open "<working_dir>/_design_vibe.html" 2>/dev/null \
- || xdg-open "<working_dir>/_design_vibe.html" 2>/dev/null \
- || powershell.exe -NoProfile -Command "Start-Process '<working_dir>\_design_vibe.html'" 2>/dev/null \
- || echo "Could not auto-open. Please open this URL: file://<working_dir>/_design_vibe.html"
+open '<working_dir>/_design_vibe.html' 2>/dev/null \
+ || xdg-open '<working_dir>/_design_vibe.html' 2>/dev/null \
+ || MOBILE_APP_PREVIEW_PATH='<working_dir>/_design_vibe.html' \
+ powershell.exe -NoProfile -Command 'Start-Process -FilePath $env:MOBILE_APP_PREVIEW_PATH' 2>/dev/null \
+ || printf '%s\n' 'Could not auto-open. Please open this URL: file://<working_dir>/_design_vibe.html'
```
-Do not block on whether the browser opened — the link is printed.
+Do not block on whether the browser opened — the link is printed. The Windows
+path is passed as data, never interpolated into PowerShell source. If all
+openers fail, report the manual link instead of claiming the browser opened.
## Step 5 — Ask the user which direction
diff --git a/plugins/mobile-apps/skills/edit-app/SKILL.md b/plugins/mobile-apps/skills/edit-app/SKILL.md
index cd70409a2..4d1d81d06 100644
--- a/plugins/mobile-apps/skills/edit-app/SKILL.md
+++ b/plugins/mobile-apps/skills/edit-app/SKILL.md
@@ -81,7 +81,14 @@ This is a focused edit workflow, not a lighter quality bar. Reuse `/create-mobil
**Telemetry checkpoint: `assess_app_health_and_drift`**
+Before any project read or command, execute
+[app-working-directory.md](${PLUGIN_ROOT}/shared/references/app-working-directory.md).
+Resolve the absolute `working_dir` once, bind every shell call to it with the
+fail-closed guard, and use absolute paths for file tools. Forward that same root
+to every data child; a previous `cd` or inherited launch cwd is not a handoff.
+
```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
test -f native-app-plan.md && echo "OK: plan found" || echo "ERROR: no plan"
test -f package.json && echo "OK: package found" || echo "ERROR: no package"
test -d app && echo "OK: app routes found" || echo "ERROR: no app routes"
@@ -150,6 +157,7 @@ Infer from `$ARGUMENTS` when possible, but do not mutate files until you have a
First inspect the app so questions can use real options instead of abstractions:
```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
find app -name '*.tsx' -not -name '_layout.tsx' -not -name '+not-found.tsx' | sort
ls -1 src/generated/services/*.ts 2>/dev/null | sed 's|src/generated/services/||;s|\.ts$||'
ls -1 src/generated/models/*.ts 2>/dev/null | sed 's|src/generated/models/||;s|\.ts$||'
@@ -379,7 +387,7 @@ For Native Capabilities (no separate agent), do it inline: read the current capa
- `pdf-report` generates a local PDF only when `expo-print` is present; local output may be opened by `native-pdf-viewer` 0.2.9+, shared with `expo-sharing` when present, or uploaded to Dataverse File storage.
- `pen-input` returns a PNG data URI; cancellation is a non-error state; Dataverse target must be Image, File, or child Evidence/Signature row.
-For connector/data-source edits, read and execute `/add-datasource` when the source type is unclear; use `/add-sharepoint`, `/add-connector`, or `/add-dataverse` directly only when the source type is clear. If the connector drives new screens or forms, update the Screens section too before applying code.
+For connector/data-source edits, read and execute `/add-datasource` when the source type is unclear; use `/add-sharepoint`, `/add-connector`, or `/add-dataverse` directly only when the source type is clear. Pass the data handoff context from Step 5 with `phase: planning`, the proposed scope, and `--plan-only --working-dir '<working_dir>'`; return a proposal, not mutations. If the connector drives new screens or forms, update the Screens section too before applying code.
### Step 3 — Gate intent, plan + app mutation preview
@@ -389,6 +397,8 @@ Show the user a side-by-side diff (or before/after) for every changed plan secti
- Edit brief: intent, target screens/routes, data/native/JavaScript/design dependencies, and assumptions
- Data/schema operations to run (`/add-dataverse --skip-planning`, connector add, native wrapper add)
+- Proposed seed table allowlist, count/media policy, and any lookup dependencies
+ requiring new records; no seed writes are authorized when this set is empty
- Screen files to create, rewrite, rename, or delete
- Navigation/layout files to update
- Verification commands to run
@@ -426,9 +436,18 @@ If this is `--plan-only`, update `memory-bank.md` with `plan_only: true`, print
Apply sections in dependency order so screens always build against the current data/native surface:
+For every data child (including connector routers), pass invocation-scoped
+`MOBILE_APP_ORCHESTRATING=1`, `orchestrator: edit-app`, absolute
+`working_dir: <working_dir>`, `phase: implementation`, and only the current
+Step 3-approved delta as `approved_scope`. Also pass the argument
+`--working-dir '<working_dir>'`. Forward this through nested data helpers.
+This legacy editor does not supply compact artifacts; keep the supported
+approved Markdown/live-reconciliation path rather than fabricating them.
+The marker is not consent and cannot turn a planning-phase call into a write.
+
0. **Environment drift gate for data edits** — before Dataverse, SharePoint, connector, or sample-data work, compare `memory-bank.md`, `power.config.json`, and `.resolved-environment.json`. If they disagree, show the values and ask the user which environment is intended. Do not create tables or connections until confirmed.
-1. **Data Model** — read and execute `/add-dataverse --skip-planning` with the approved Data Model section. It must create/extend Dataverse tables, refresh generated services/models, update `.datamodel-manifest.json`, and leave generated services compiling. After it returns, run `npm run generate-schemas` and `npx --no-install tsc --noEmit`; do not continue to screens until clean.
-2. **Sample Data** — if a new Dataverse table was created and any changed screen will show list/detail data from it, read and execute `/add-sample-data` for the project. If seeding fails, record a concern and continue only if the app handles empty states.
+1. **Data Model** — read and execute `/add-dataverse --skip-planning --working-dir '<working_dir>'` with the data child context above, the approved Data Model delta, and `offline_reconciliation_owner: edit-app`. Step 5.6 owns offline reconciliation; the leaf returns its verified created/extended/reused table results without running its own offline check. It must create/extend only the approved delta, refresh generated services/models, update `.datamodel-manifest.json`, and leave generated services compiling. After it returns, run `npm run generate-schemas` and `npx --no-install tsc --noEmit`; do not continue to screens until clean.
+2. **Sample Data** — intersect the Step 3-approved seed set with the leaf's verified newly created tables used by changed screens. Never derive the allowlist from the whole manifest or pass an empty/missing `--tables` to discovery. If the intersection is empty, skip seeding. Otherwise read and execute `/add-sample-data --working-dir '<working_dir>' --tables "<comma-separated approved logical names>"` with the data child context, the exact approved count/media policy in `approved_scope`, and `retiring_tables: <explicit exclusions or []>`. Newly needed seed dependencies require approval; do not silently expand the set. If seeding fails, record a concern and continue only if the app handles empty states.
3. **Connector/Data Source** — read and execute `/add-datasource` when ambiguous, or `/add-sharepoint` / `/add-connector` for approved connector changes. Regenerate services and record connection notes in `memory-bank.md`.
4. **Pure-JavaScript Dependencies** — execute the Installation Contract in [`shared/references/javascript-dependency-planning.md`](${PLUGIN_ROOT}/shared/references/javascript-dependency-planning.md) for new or changed rows in the approved `## Screens → ### JavaScript Dependencies` table. Approval is consent for those exact packages and versions. Install and validate before screen work; if final inspection finds native code/config or incompatible runtime dependencies, remove only the newly added package and stop with the exact failed criterion.
5. **Native Capabilities** — read and execute `/add-native <capability>` for every new capability. Do not install missing native packages or fake wrappers. If a capability is unsupported by the current template, stop before rebuilding screens that import it, record the block, and tell the user what upstream template support is missing.
@@ -441,7 +460,7 @@ After any Data Model, Connector/Data Source, JavaScript Dependency, or Native Ca
Run this after any data-source/schema/connector mutation and before any screen-builder prompt:
```bash
-cd <working_dir>
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
for svc in src/generated/services/*.ts; do
[ -e "$svc" ] || continue
name=$(basename "$svc" .ts)
@@ -461,10 +480,23 @@ If Step 5 created or extended Dataverse tables, an existing Mobile Offline Profi
Run the local, no-network delta check:
```bash
-node "${PLUGIN_ROOT}/scripts/offline-profile-delta.js"
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
+node "${PLUGIN_ROOT}/scripts/offline-profile-delta.js" --project-root '<working_dir>'
```
-Branch on the JSON `status` per [offline-profile-reconciliation.md](${PLUGIN_ROOT}/shared/references/offline-profile-reconciliation.md): `no-manifest` / `no-profile` / `in-sync` → continue silently (do not nag when no profile exists); `delta` → prompt to update, then read and execute `${PLUGIN_ROOT}/skills/add-table-to-offline-profile/SKILL.md` for `missingTables[]` and `${PLUGIN_ROOT}/skills/edit-offline-profile/SKILL.md` for `tablesWithNewColumns[]`, passing the arguments documented by each workflow, and re-check to `in-sync`. Record the reconciliation outcome in the Step 8 memory-bank edit entry.
+Capture the exit status and stdout/stderr and follow the failure dispatch in
+[offline-profile-reconciliation.md](${PLUGIN_ROOT}/shared/references/offline-profile-reconciliation.md)
+before continuing: a non-zero exit, `status: error`, malformed/missing JSON,
+or unknown status skips mutation helpers and ends with `DONE_WITH_CONCERNS`
+for already-applied changes (otherwise `BLOCKED`), never a clean success.
+For valid `no-manifest` / `no-profile` / `in-sync`, continue silently.
+For `delta`, obtain approval and execute the reference's **Scoped helper
+handoffs** with `orchestrator: edit-app`, the same absolute `working_dir`,
+`phase: implementation`, and the exact approved environment/profile/table
+scope. Pass `--working-dir '<working_dir>'` to each helper along with its table
+and column arguments, then re-check through the same failure dispatch.
+Record the outcome in the Step 8 memory-bank entry without clearing pending
+`offlineRetirement` outcomes.
### Step 6 — Rebuild affected screens
@@ -512,6 +544,7 @@ Shared scaffold algorithm:
Run the navigation/skeleton gate before screen-builder work:
```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
npx --no-install tsc --noEmit
```
@@ -558,6 +591,7 @@ Run verification after mutations. Batch-fix root causes, then rerun the failed g
Required gates, selected by what changed:
```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
npm run generate-schemas # if any data source/schema/connector changed
npx --no-install tsc --noEmit # always after app mutation
npm run check-routes --if-present
@@ -566,12 +600,14 @@ npm run check-routes --if-present
If `npm run check-routes` is absent but `scripts/check-routes.js` exists, run:
```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
node scripts/check-routes.js
```
When screen files changed, run the mobile plugin's report-mode validators explicitly:
```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
node "${PLUGIN_ROOT}/hooks/validate-screen-quality.js" --report <changed-screen-files-or-app-dir>
node "${PLUGIN_ROOT}/hooks/validate-color-contrast.js" --report <changed-screen-files-or-app-dir>
```
diff --git a/plugins/mobile-apps/skills/edit-offline-profile/SKILL.md b/plugins/mobile-apps/skills/edit-offline-profile/SKILL.md
index 2e6f1fbf6..cdd94ab55 100644
--- a/plugins/mobile-apps/skills/edit-offline-profile/SKILL.md
+++ b/plugins/mobile-apps/skills/edit-offline-profile/SKILL.md
@@ -18,7 +18,41 @@ model: sonnet
Re-run a single piece of an existing profile — change one table's row scope, update the column list, adjust sync frequency, or rename the profile. Avoids the cognitive cost of walking the full /setup-offline-profile wizard for a one-line change.
-Scope: existing profile (read from `offline-profile.json` or `--profile-id`); edits at the table-item granularity. To ADD a new table see `/add-table-to-offline-profile`; to delete the entire profile see [dataverse-offline-api.md §11](${PLUGIN_ROOT}/shared/references/dataverse-offline-api.md).
+Scope: existing profile (read from `<working_dir>/offline-profile.json` or
+`--profile-id`); edits at the table-item granularity. To ADD a new table return to
+the owner for `/add-table-to-offline-profile`; deleting an entire profile is
+outside this helper's scope, not an automatic recovery.
+
+## Invocation context and root binding
+
+This internal helper is always a **child invocation**. Before any project read or
+command, execute [app-working-directory.md](${PLUGIN_ROOT}/shared/references/app-working-directory.md).
+Require the owner's absolute `working_dir`; `--working-dir`, when supplied, must
+identify that same native-canonical root. Missing, relative, or conflicting root
+context returns `NEEDS_CONTEXT` before project access; an inaccessible directory
+is `BLOCKED`. Never use the launch cwd or introduce another root resolver.
+
+Receive `MOBILE_APP_ORCHESTRATING=1`, `orchestrator`, `working_dir`, `phase`,
+`approved_scope`, and supplied answers from the owner. Preserve the selected
+environment ID/URL/tenant, profile ID, table allowlist, item IDs, and exact
+scope/column/sync/name/description changes. Missing or conflicting scope returns
+`NEEDS_CONTEXT`, not another environment/profile/table selection. The marker is
+not approval: schema approval alone does not authorize profile edits, publication,
+deletion, or membership edits. Retain Step 3's single confirm unless supplied
+answers already approve that same current offline change.
+For `--plan-only` or a planning-phase handoff, return the current/proposed diff
+after read-only discovery and STOP before Apply, PATCH, publication, or artifact
+writes. A gate response cannot lift proposal-only mode.
+
+Apply the canonical contract to **every shell call and file tool**, including
+version/auth checks, manifest/screen reads, commands copied from references,
+verification, recovery, and retries. Re-supply the absolute `PLUGIN_ROOT` and
+required context on each call; no prior `cd`, export, or shell variable persists.
+Use the canonical Bash guard below or its PowerShell equivalent. Replace
+placeholders with validated, shell-quoted invocation values; missing values
+return `NEEDS_CONTEXT`, never execute an unresolved placeholder.
+File tools use absolute `<working_dir>/...` paths; plugin reads/scripts use
+`${PLUGIN_ROOT}/...`. Never search another app when a file is absent.
## Workflow
@@ -29,21 +63,52 @@ Scope: existing profile (read from `offline-profile.json` or `--profile-id`); ed
### Step 1 — Verify project + locate profile
```bash
-test -f power.config.json
-node "${PLUGIN_ROOT}/scripts/resolve-environment.js" "$(node -e \"console.log(require('./power.config.json').environmentId)\")"
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
+if [ ! -f power.config.json ] || [ ! -f app.config.js ]; then
+ echo "BLOCKED: working_dir is not an initialized app" >&2
+ exit 1
+fi
```
+Read `<working_dir>/power.config.json` and require a nonempty `environmentId`
+matching the owner's selected environment. Reuse matching complete environment
+context, or perform this non-persisting lookup from the bound root:
+
+```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
+environment_id=$(node -p "require('./power.config.json').environmentId || ''") || {
+ echo "BLOCKED: unreadable power.config.json" >&2; exit 1;
+}
+if [ -z "$environment_id" ] || [ "$environment_id" != "<selected-environment-id>" ]; then
+ echo "NEEDS_CONTEXT: selected environment does not match working_dir" >&2
+ exit 1
+fi
+node "${PLUGIN_ROOT}/scripts/resolve-environment.js" "$environment_id" --no-cache --require-tenant
+```
+
+Require the returned environment ID, HTTPS URL, and tenant to match the owner;
+incomplete or conflicting context returns `NEEDS_CONTEXT`. Never drop
+`--no-cache --require-tenant`, change configuration, or switch auth/environment
+to recover a failure. Use that exact `<envUrl>` and `<tenantId>` for every request.
+
Profile ID resolution (same priority as `/assign-offline-profile` Step 1):
| Source | Used when |
|---|---|
-| `$ARGUMENTS` `--profile-id <guid>` | Explicit override |
-| `offline-profile.json` top-level `profileId` in cwd | Default for `/setup-offline-profile`-created projects |
-| Otherwise | `AskUserQuestion` with list from `GET /mobileofflineprofiles` |
+| `$ARGUMENTS` `--profile-id <guid>` | Explicit selection matching the owner's profile context |
+| `<working_dir>/offline-profile.json` top-level `profileId` | Default for `/setup-offline-profile`-created projects, matching the owner's profile context |
+| Otherwise | Return `NEEDS_CONTEXT` to the owner to select the intended profile; never pick another profile silently |
STOP if no profile found: "Run `/setup-offline-profile` first."
-> **`power.config.json` is intentionally NOT consulted here.** That file is owned by `pa app init`. The profile ID lives in `offline-profile.json` only.
+Verify the selected live profile belongs to the selected environment. A conflicting
+snapshot/argument returns `NEEDS_CONTEXT`; a 404 or permission failure is
+`BLOCKED`, not permission to discover a substitute. Resolve each `<itemId>` only
+within this profile and verify its table matches the exact requested logical name.
+
+> **`<working_dir>/power.config.json` is intentionally NOT consulted for the profile ID.**
+> That file is owned by `pa app init`. The local profile ID lives in
+> `<working_dir>/offline-profile.json` only.
### Step 2 — Resolve target (what to edit)
@@ -64,13 +129,24 @@ If no flags → interactive picker. `AskUserQuestion` with up-to-4 most likely e
- "Change a table's sync frequency" → next message asks which table + value
- "Edit a table's column list" → next message asks which table + add/remove
+Restrict the picker and explicit flags to the owner's exact current scope.
+`--columns reset` reads the selected table from
+`<working_dir>/.datamodel-manifest.json` or
+`<working_dir>/docs/plan-artifacts/.datamodel-manifest.json` and greps only
+absolute `<working_dir>/app/` and `<working_dir>/src/` paths. Keep the chosen
+absolute manifest path for the whole invocation; no other-app fallback.
+Changing the table, profile, or operation requires returning `NEEDS_CONTEXT`
+to the owner, not expanding an existing approval.
+
### Step 3 — Show current vs proposed (single gate)
GET the current item state from Dataverse for any tables being edited:
```bash
-node "${PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> GET \
- "mobileofflineprofileitems(<itemId>)?\$select=name,recorddistributioncriteria,recordsownedbyme,recordsownedbymyteam,recordsownedbymybusinessunit,syncintervalinminutes,selectedcolumns"
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
+node "${PLUGIN_ROOT}/scripts/dataverse-request.js" "<envUrl>" GET \
+ "mobileofflineprofileitems(<itemId>)?\$select=name,recorddistributioncriteria,recordsownedbyme,recordsownedbymyteam,recordsownedbymybusinessunit,syncintervalinminutes,selectedcolumns" \
+ --tenant-id "<tenantId>"
```
Render a current/proposed diff:
@@ -94,8 +170,9 @@ If `Apply` → continue. If `Cancel` → STOP.
Build the PATCH body with only the fields that changed:
```bash
-node "${PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> PATCH \
- "mobileofflineprofileitems(<itemId>)" \
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
+node "${PLUGIN_ROOT}/scripts/dataverse-request.js" "<envUrl>" PATCH \
+ "mobileofflineprofileitems(<itemId>)" --tenant-id "<tenantId>" \
--body '{
"recorddistributioncriteria": <new>,
"recordsownedbyme": <new-bool>,
@@ -107,31 +184,68 @@ node "${PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> PATCH \
For profile-level edits (name / description):
```bash
-node "${PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> PATCH \
- "mobileofflineprofiles(<profileId>)" \
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
+node "${PLUGIN_ROOT}/scripts/dataverse-request.js" "<envUrl>" PATCH \
+ "mobileofflineprofiles(<profileId>)" --tenant-id "<tenantId>" \
--body '{"name": "...", "description": "..."}'
```
+Check returned HTTP statuses as well as process exit. A
+403/`PrivilegeCheckFailed` is `BLOCKED`; do not change identity or profile to
+bypass permissions. Preserve every field and table outside the approved delta.
+
### Step 5 — Publish
Use the **targeted `PublishXml`** recipe from [shared/references/dataverse-offline-api.md §9](${PLUGIN_ROOT}/shared/references/dataverse-offline-api.md):
```bash
-node "${PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> POST \
- "PublishXml" --body '{
- "ParameterXml": "<publish><mobileofflineprofiles><mobileofflineprofile>'"$PROFILE_ID"'</mobileofflineprofile></mobileofflineprofiles></publish>"
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
+node "${PLUGIN_ROOT}/scripts/dataverse-request.js" "<envUrl>" POST \
+ "PublishXml" --tenant-id "<tenantId>" --body '{
+ "ParameterXml": "<publish><mobileofflineprofiles><mobileofflineprofile><profileId></mobileofflineprofile></mobileofflineprofiles></publish>"
}'
```
Publishes only this profile, not the entire org's customizations. Avoids the 429 rate-limit storms on shared envs that the legacy `PublishAllXml` triggered.
-On `400 / 0x80071141` "circular relationship" — same handling as `/setup-offline-profile` Step 8 (parse cycle path, prompt user to drop one association, retry). Fallback to `PublishAllXml` only if `PublishXml` returns an unexpected error other than the cycle case.
+On `400 / 0x80071141` "circular relationship" — same handling as
+`/setup-offline-profile` Step 8 (parse cycle path, prompt user to drop one
+association, retry). Fallback to `PublishAllXml` only if `PublishXml` returns an
+unexpected error other than the cycle case **and** the owner/user approves that
+broader publication; a profile-scoped approval does not cover it.
+
+All linked recovery commands, re-GET verification, and retries must bind the
+same root and pass the same environment/tenant/profile/table/item context.
+Never retry on a different profile or bypass a permission failure. Confirm
+publication before Step 6.
+
+If a linked recipe requires another offline helper, return the proposed change
+to the owner for approval first, then read the helper at its absolute
+`${PLUGIN_ROOT}/skills/<helper>/SKILL.md` path. Forward:
+
+```text
+Arguments: --working-dir '<working_dir>' --profile-id "<profileId>" --table "<table>" <exact-approved-change-flags>
+Context: MOBILE_APP_ORCHESTRATING=1, orchestrator, working_dir, phase, approved_scope,
+ selected environment ID/URL/tenant, profile ID, table allowlist, item ID,
+ supplied answers, --plan-only (if present)
+```
-### Step 6 — Update artifacts
+The recipient must enforce the same canonical root contract. Missing context
+returns `NEEDS_CONTEXT`; do not fall back to direct invocation or rediscovery.
-Re-read the changed item(s) and rewrite the matching entry in `offline-profile.json`. When the edit changed a table's **columns** (`--columns add:/remove:/reset`), also refresh that table entry's `schemaColumns` to the table's current full column set from `.datamodel-manifest.json` (root or `docs/plan-artifacts/`). This re-baselines the schema-reconciliation marker so a delta that was just reconciled clears on the next `scripts/offline-profile-delta.js` run; leave `schemaColumns` untouched for scope/sync/rename-only edits. See [offline-profile-reconciliation.md](${PLUGIN_ROOT}/shared/references/offline-profile-reconciliation.md).
+### Step 6 — Update artifacts
-Append a one-line entry to `memory-bank.md` `## Offline profile` block:
+Re-read the changed item(s) in the same profile/environment and rewrite the
+matching entry in `<working_dir>/offline-profile.json`. When the edit changed a
+table's **columns** (`--columns add:/remove:/reset`), also refresh that entry's
+`schemaColumns` to the table's current full column set from the bound absolute
+manifest. This re-baselines the schema-reconciliation marker for the next
+`${PLUGIN_ROOT}/scripts/offline-profile-delta.js` run; leave `schemaColumns`
+untouched for scope/sync/rename-only edits. Any delta check uses
+`--project-root '<working_dir>'` in its own guarded call. See
+[offline-profile-reconciliation.md](${PLUGIN_ROOT}/shared/references/offline-profile-reconciliation.md).
+
+Append a one-line entry to `<working_dir>/memory-bank.md` `## Offline profile` block:
```yaml
edits:
diff --git a/plugins/mobile-apps/skills/enable-tables-offline/SKILL.md b/plugins/mobile-apps/skills/enable-tables-offline/SKILL.md
index 580f6dc27..24a989e7e 100644
--- a/plugins/mobile-apps/skills/enable-tables-offline/SKILL.md
+++ b/plugins/mobile-apps/skills/enable-tables-offline/SKILL.md
@@ -19,6 +19,33 @@ Flip `IsAvailableOffline=true` AND `ChangeTrackingEnabled=true` on the `EntityMe
Sequential (Dataverse metadata lock) and idempotent: re-running on an already-enabled table is a no-op.
+## Invocation context and root binding
+
+This internal helper is always a **child invocation**. Before any project read or
+command, execute [app-working-directory.md](${PLUGIN_ROOT}/shared/references/app-working-directory.md).
+Require the owner's absolute `working_dir`; `--working-dir`, when supplied, must
+identify that same native-canonical root. Missing, relative, or conflicting root
+context returns `NEEDS_CONTEXT` before project access; an inaccessible directory
+is `BLOCKED`. Never use the launch cwd or introduce another root resolver.
+
+Receive `MOBILE_APP_ORCHESTRATING=1`, `orchestrator: setup-offline-profile`,
+`working_dir`, `phase`, `approved_scope`, and supplied answers. Preserve the
+selected environment ID/URL/tenant and exact table/prerequisite/publication
+allowlist. The marker is not approval. Reuse only matching current offline
+approval; a missing or changed scope returns `NEEDS_CONTEXT` to the owner.
+For `--plan-only` or a planning-phase handoff, return the proposed prerequisite
+changes after permitted read-only inspection, before PUT, publication, or
+artifact writes. A gate response cannot lift proposal-only mode.
+
+Apply the canonical root contract to **every shell call and file tool**.
+Re-supply the absolute `PLUGIN_ROOT` and invocation context on each call; no
+prior `cd`, export, or shell variable persists. Missing values return
+`NEEDS_CONTEXT`; never execute an unresolved placeholder.
+All linked recovery commands, re-GET verification, and retries use the same
+root, environment, and explicit tenant. Read only absolute app-local paths,
+including `<working_dir>/power.config.json`, `<working_dir>/memory-bank.md`,
+and the manifest locations below.
+
## Workflow
1. Verify project & auth → 2. Resolve table list → 3. Inspect current state → Gate → 4. PUT EntityMetadata per table → 5. Publish → 6. Verify → 7. Summary
@@ -28,23 +55,45 @@ Sequential (Dataverse metadata lock) and idempotent: re-running on an already-en
### Step 1 — Verify project & auth
```bash
-test -f power.config.json && test -f app.config.js
-node "${PLUGIN_ROOT}/scripts/resolve-environment.js" "$(node -e \"console.log(require('./power.config.json').environmentId)\")"
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
+if [ ! -f power.config.json ] || [ ! -f app.config.js ]; then
+ echo "BLOCKED: working_dir is not an initialized app" >&2
+ exit 1
+fi
```
-Capture the **Environment URL** from the resolver for `<envUrl>`. STOP if not authenticated.
+Require the app's `environmentId` to match the owner's selected environment
+before any discovery or mutation. Use this non-persisting lookup from the same root:
-### Step 2 — Resolve table list
+```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
+environment_id=$(node -p "require('./power.config.json').environmentId || ''") || {
+ echo "BLOCKED: unreadable power.config.json" >&2; exit 1;
+}
+if [ -z "$environment_id" ] || [ "$environment_id" != "<selected-environment-id>" ]; then
+ echo "NEEDS_CONTEXT: selected environment does not match working_dir" >&2
+ exit 1
+fi
+node "${PLUGIN_ROOT}/scripts/resolve-environment.js" "$environment_id" --no-cache --require-tenant
+```
+
+Capture the **Environment URL** and **Tenant ID** from the resolver for
+`<envUrl>` and `<tenantId>`. Pass this tenant explicitly on every helper call
+and retry below; missing or conflicting tenant context is `NEEDS_CONTEXT`.
+Require the ID, URL, and tenant to match the owner; never switch accounts or
+environments to recover. STOP if not authenticated.
-Tables to enable come from one of (in order):
+### Step 2 — Resolve table list
-| Source | Used when |
-|---|---|
-| `$ARGUMENTS` | User passed a comma- or space-separated list of logical names (e.g. `/enable-tables-offline cr123_note,cr123_visit`) |
-| `.datamodel-manifest.json` | Default — read `tables[].logicalName` for every Dataverse-backed table in the app |
-| `AskUserQuestion` | Only if both above are absent. Show the table list from `src/generated/services/*Service.ts` filenames and let the user pick. |
+Use only the exact table allowlist in the owner's `approved_scope`. The comma-
+or space-separated table list in `$ARGUMENTS` must match it; `--working-dir` is
+root context, not a table name. Missing or conflicting table selection returns
+`NEEDS_CONTEXT`; an explicitly empty approved list is a verified no-op.
-If the resolved list is empty, STOP with: "No Dataverse tables found in this project. Run `/add-dataverse` first."
+Inspect `<working_dir>/.datamodel-manifest.json`, or
+`<working_dir>/docs/plan-artifacts/.datamodel-manifest.json` for newer apps, only
+to verify those selected tables. The manifest is not permission to enable every
+row. Do not discover another app's manifest or expand the allowlist silently.
### Step 3 — Inspect current state
@@ -54,8 +103,10 @@ If the resolved list is empty, STOP with: "No Dataverse tables found in this pro
For each table, in sequence:
```bash
-node "${PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> GET \
- "EntityDefinitions(LogicalName='<table>')?\$select=LogicalName,DisplayName,IsAvailableOffline,ChangeTrackingEnabled,IsCustomizable"
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
+node "${PLUGIN_ROOT}/scripts/dataverse-request.js" "<envUrl>" GET \
+ "EntityDefinitions(LogicalName='<table>')?\$select=LogicalName,DisplayName,IsAvailableOffline,ChangeTrackingEnabled,IsCustomizable" \
+ --tenant-id "<tenantId>"
```
Build a status table:
@@ -72,7 +123,11 @@ Build a status table:
### Gate — Approval before mutation
-Enter plan mode with the status table from Step 3 plus the planned operation per table. Wait for user `ExitPlanMode` before proceeding.
+Compare the status table from Step 3 with the owner's approved prerequisite and
+publication delta. Matching current Gate 1 approval is reused without a duplicate
+prompt. Otherwise return the status table and `NEEDS_CONTEXT: offline prerequisite
+approval` to `/setup-offline-profile`, which owns the approval gate. Do not widen
+scope or override proposal-only mode.
Plan body:
@@ -82,12 +137,12 @@ The following EntityMetadata changes will be PUT in sequence:
cr123_note → set IsAvailableOffline=true, ChangeTrackingEnabled=true
cr123_visit → set ChangeTrackingEnabled=true (IsAvailableOffline already true)
-After all updates, a single PublishAllXml request will commit the changes.
+After all updates, targeted PublishXml will publish only the changed tables.
Tables already in the desired state are skipped (no API call).
```
-If the user rejects, STOP. If they approve, proceed.
+If the user rejects, STOP. Proceed only with the exact approved delta.
### Step 4 — PUT EntityMetadata per table
@@ -99,10 +154,12 @@ If the user rejects, STOP. If they approve, proceed.
For each table needing change (skip ones already in target state):
```bash
-node "${PLUGIN_ROOT}/scripts/update-entity-offline-flags.js" <envUrl> \
- --table <table> \
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
+node "${PLUGIN_ROOT}/scripts/update-entity-offline-flags.js" "<envUrl>" \
+ --table "<table>" \
--offline true \
- --tracking true
+ --tracking true \
+ --tenant-id "<tenantId>"
```
The helper:
@@ -127,10 +184,11 @@ Print `✓ <table>` after each 204; print `↷ <table> (already enabled)` for no
**Use targeted `PublishXml`** scoped to the entities that were actually modified — avoids the org-wide rate-limit storms (`0x80071151` "concurrent PublishAll already running") observed on shared envs. Empirical 2026-05-25.
```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
# Build the <entities> XML body from the list of tables modified in Step 4
-node "${PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> POST \
- "PublishXml" --body '{
- "ParameterXml": "<importexportxml><entities><entity>cr720_fcbflag</entity><entity>cr720_rolloutevent</entity></entities></importexportxml>"
+node "${PLUGIN_ROOT}/scripts/dataverse-request.js" "<envUrl>" POST \
+ "PublishXml" --tenant-id "<tenantId>" --body '{
+ "ParameterXml": "<importexportxml><entities><entity><table></entity></entities></importexportxml>"
}'
```
@@ -140,11 +198,14 @@ Substitute `<entity>...</entity>` lines for every table the helper PUT'd flags o
**On 429 / 0x80071151 ("concurrent publish already running")**: back off automatically via `dataverse-request.js`'s retry logic. If still failing after 4 retries, return `DONE_WITH_CONCERNS: publish bottlenecked on shared env; metadata changes are committed but maker portal will not refresh until next publish`. The downstream skill (`/setup-offline-profile`) can proceed — metadata-level writes are durable.
-**Fallback to `PublishAllXml`** (only when the targeted call returns a non-rate-limit error like `0x80048d19` malformed body):
+**Fallback to `PublishAllXml`** only when the targeted call returns a non-rate-limit
+error such as `0x80048d19` and the owner separately approves the broader publication.
+Table-only approval does not authorize publishing unrelated changes.
```bash
-node "${PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> POST \
- "PublishAllXml" --body '{}'
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
+node "${PLUGIN_ROOT}/scripts/dataverse-request.js" "<envUrl>" POST \
+ "PublishAllXml" --tenant-id "<tenantId>" --body '{}'
```
Same timeout-but-success handling as `/setup-offline-profile` Step 8: if the client times out but a follow-up GET on the table's EntityMetadata shows the flags are set, treat as success.
@@ -167,14 +228,16 @@ Print:
Skipped (already enabled): contact
-Next: run /setup-offline-profile to design the offline profile that uses these tables.
+Next: return to the current /setup-offline-profile workflow.
```
-Update `memory-bank.md` under `## Offline profile` with the timestamp and table list.
+Update `<working_dir>/memory-bank.md` under `## Offline profile` with the timestamp
+and verified table list. Return the results to the current owner; do not launch
+another offline setup workflow.
## Status code
-Final line of the skill's response is one of:
+The literal first line of the skill's response is one of:
- `DONE` — all requested tables now have both flags set
- `DONE_WITH_CONCERNS: <list>` — some tables skipped (uncustomizable, publish warning, etc.)
- `NEEDS_CONTEXT: <missing>` — couldn't resolve table list and user didn't provide
diff --git a/plugins/mobile-apps/skills/list-connections/SKILL.md b/plugins/mobile-apps/skills/list-connections/SKILL.md
index 51bed71dc..4504df1cb 100644
--- a/plugins/mobile-apps/skills/list-connections/SKILL.md
+++ b/plugins/mobile-apps/skills/list-connections/SKILL.md
@@ -2,7 +2,7 @@
name: list-connections
description: Use to find or create a Power Platform connection ID or reference for an Expo/React Native Power Apps mobile app.
user-invocable: true
-allowed-tools: Bash
+allowed-tools: Read, Bash
model: haiku
---
@@ -12,6 +12,13 @@ model: haiku
# List Connections
+**App root:** before any project read or command, execute
+[app-working-directory.md](${PLUGIN_ROOT}/shared/references/app-working-directory.md).
+Reuse the resolved absolute `working_dir` for every shell call and
+file tool, including auth retries and the environment read used for portal URLs.
+Forwarded owner context is required for child calls; do not fall back to the
+launch directory. Reapply the guard and arguments in each fresh call.
+
Finds or creates a Power Platform connection with the Power Apps CLI. Returns the **Connection ID** or **Connection Reference** that callers feed into `pa app add data-source`.
## Workflow
@@ -28,17 +35,25 @@ Use one of the supported paths below.
If the caller already provided a connection ID, validate the connector/API ID from context and return it as-is for `--connection-id`.
+Preserve any supplied connection reference as well; do not create a replacement.
+Creation requires current approval for the selected environment and connector.
+For `--plan-only` or a planning-phase handoff, perform only permitted read-only
+lookup and return missing access/identity to the owner; never create a connection
+to unblock discovery. The invocation marker does not grant creation consent.
+
If the caller provided a connector API ID and needs a new connection, create it from the app root:
> Resolve the CLI first (see [cli-binary.md](${PLUGIN_ROOT}/shared/cli-binary.md)): run as `$PA connection create …` (`npx --no-install pa …`), never a bare `pa`. On `power-apps`-only projects, translate to `power-apps create-connection --api-id …`.
```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
$PA connection create --connector <api-id> --json
```
Use the returned `connectionId` for `--connection-id <connectionId>`. Optional display names are supported:
```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
$PA connection create --connector <api-id> --display-name '<display-name>' --json
```
@@ -49,12 +64,13 @@ Browser-based connection creation is disabled by default. If the connector is no
If the caller provided a solution ID and needs a connection reference name, list connection references from the app root:
```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
$PA connection list-references --solution-id <solution-id> --json
```
If a matching connection reference exists, return its reference name for `--connection-ref <connection-ref>`.
-If `pa connection create` or `pa connection list-references` fails because of auth, wrong user, multiple accounts, no output, or timeout, follow shared-instructions command-failure handling and retry once.
+If `pa connection create` or `pa connection list-references` fails because of auth, wrong user, multiple accounts, no output, or timeout, follow shared-instructions command-failure handling and retry once from the same guarded root. A missing app-local CLI is a blocker, not permission to retry without `--no-install` or install another version.
**Other failures:**
- Non-zero exit for any reason other than auth: report the exact output. STOP.
@@ -65,7 +81,7 @@ Show the supported add path. A **Connection ID** goes into `--connection-id <con
**If the needed connector is missing:**
-1. Share the direct Connections URL using the active environment ID from context (read from `power.config.json` `environmentId`):
+1. Share the direct Connections URL using the active environment ID from context (read from `<working_dir>/power.config.json` `environmentId`):
`https://make.powerapps.com/environments/<environment-id>/connections` → **+ New connection**
2. Search for and create the connector, then complete the sign-in / consent flow
3. Rerun `/list-connections <api-id>` or provide the portal connection ID so the data-source skill can continue
diff --git a/plugins/mobile-apps/skills/preview-offline-scope/SKILL.md b/plugins/mobile-apps/skills/preview-offline-scope/SKILL.md
index 1ecef2e8c..cf89fda94 100644
--- a/plugins/mobile-apps/skills/preview-offline-scope/SKILL.md
+++ b/plugins/mobile-apps/skills/preview-offline-scope/SKILL.md
@@ -17,6 +17,14 @@ Useful before:
- `/assign-offline-profile` (so users don't get surprised by data caps)
- `/edit-offline-profile` to gauge impact of a column-list change
+Before any project read or command, apply
+[app-working-directory.md](${PLUGIN_ROOT}/shared/references/app-working-directory.md).
+Resolve one absolute `working_dir` for this direct invocation, or require the
+owner's root for a child. Keep all shell calls, file reads, and retries on that
+root and the same resolved environment/tenant. Read
+`<working_dir>/offline-profile.json`; a supplied profile ID must match the
+snapshot before verification. Missing or conflicting context is `NEEDS_CONTEXT`.
+
## Workflow
1. Verify project + locate profile → 2. Run verify (drift check) → 3. Per-table row counts → 4. Cache-size estimate → 5. Report
@@ -28,17 +36,27 @@ Useful before:
Same as `/edit-offline-profile` Step 1. Read profileId from `offline-profile.json` or `$ARGUMENTS --profile-id`. Do not read profile metadata from `power.config.json`; it is owned by `pa app init`.
```bash
-test -f power.config.json
-node "${PLUGIN_ROOT}/scripts/resolve-environment.js" "$(node -e \"console.log(require('./power.config.json').environmentId)\")"
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
+environment_id=$(node -p "require('./power.config.json').environmentId || ''") || {
+ echo "BLOCKED: unreadable power.config.json" >&2; exit 1;
+}
+if [ -z "$environment_id" ]; then
+ echo "NEEDS_CONTEXT: selected app has no environmentId" >&2; exit 1;
+fi
+node "${PLUGIN_ROOT}/scripts/resolve-environment.js" "$environment_id" --no-cache --require-tenant
```
+Capture `<envUrl>` and `<tenantId>` and require them to match any owner identity.
+Pass that tenant explicitly on verification, row counts, identity reads, and retries.
+
### Step 2 — Run verify
**Telemetry checkpoint: `verify_offline_profile_snapshot`**
```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
node "${PLUGIN_ROOT}/scripts/verify-offline-profile.js" <envUrl> \
- --project-root "$(pwd)"
+ --project-root '<working_dir>' --tenant-id "<tenantId>"
```
If `status: drift`, surface the drift list verbatim. The estimate that follows is still meaningful but flag that the live profile diverges from `offline-profile.json` — recommend re-running `/setup-offline-profile` or `/edit-offline-profile` to reconcile.
@@ -57,13 +75,14 @@ For each table in the profile, run a `count` query that applies the same filter
| 2 + bu | recordsownedbymybusinessunit=true | `?$count=true&$top=0&$filter=_owningbusinessunit_value eq <current-bu-id>` |
| 0 (Related only) | n/a | Can't estimate independently — depends on parents. Report `~depends on parent counts`. |
-For current-user/current-BU filters, resolve identity only inside this skill by calling Dataverse `WhoAmI` through `scripts/dataverse-request.js` against the resolved `<envUrl>`. If that call fails, report the affected scope as `unknown — current user/BU unavailable` instead of blocking the whole preview. Do not expect `scripts/resolve-environment.js` or `auth.config.json.environment` to provide `UserId` / `BusinessUnitId`.
+For current-user/current-BU filters, resolve identity only inside this skill by calling Dataverse `WhoAmI` through `scripts/dataverse-request.js` against the resolved `<envUrl>` with `--tenant-id "<tenantId>"` from the same guarded root. If that call fails, report the affected scope as `unknown — current user/BU unavailable` instead of blocking the whole preview. Do not expect `scripts/resolve-environment.js` or `auth.config.json.environment` to provide `UserId` / `BusinessUnitId`.
For each table:
```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
node "${PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> GET \
- "<entitysetname>?\$count=true&\$top=0&<scope-filter>"
+ "<entitysetname>?\$count=true&\$top=0&<scope-filter>" --tenant-id "<tenantId>"
```
Cap at 5000 (Dataverse non-aggregate count cap). When the result is exactly 5000, prefix with `≥` in the report.
diff --git a/plugins/mobile-apps/skills/preview-screens/SKILL.md b/plugins/mobile-apps/skills/preview-screens/SKILL.md
index ceead0bc5..cd34f62cc 100644
--- a/plugins/mobile-apps/skills/preview-screens/SKILL.md
+++ b/plugins/mobile-apps/skills/preview-screens/SKILL.md
@@ -186,7 +186,7 @@ Print confirmation:
Read the flag and act:
```bash
-grep -E "^visual_companion:[[:space:]]*(yes|no)" "<working_dir>/memory-bank.md" 2>/dev/null
+grep -E "^visual_companion:[[:space:]]*(yes|no)" '<working_dir>/memory-bank.md' 2>/dev/null
```
| Flag | Action |
@@ -205,13 +205,17 @@ grep -E "^visual_companion:[[:space:]]*(yes|no)" "<working_dir>/memory-bank.md"
Then try OS-appropriate openers in sequence and fall back to printing the link if none work:
```bash
-open "<working_dir>/preview.html" 2>/dev/null \
- || xdg-open "<working_dir>/preview.html" 2>/dev/null \
- || powershell.exe -NoProfile -Command "Start-Process '<working_dir>\preview.html'" 2>/dev/null \
- || echo "Could not auto-open. Open this URL in your browser: file://<working_dir>/preview.html"
+open '<working_dir>/preview.html' 2>/dev/null \
+ || xdg-open '<working_dir>/preview.html' 2>/dev/null \
+ || MOBILE_APP_PREVIEW_PATH='<working_dir>/preview.html' \
+ powershell.exe -NoProfile -Command 'Start-Process -FilePath $env:MOBILE_APP_PREVIEW_PATH' 2>/dev/null \
+ || printf '%s\n' 'Could not auto-open. Open this URL in your browser: file://<working_dir>/preview.html'
```
-`open` is macOS-only; the chain covers Linux (`xdg-open`) and Windows / WSL (`powershell.exe Start-Process`). On headless / SSH sessions all three fail silently and the user just opens the link they were already given.
+`open` is macOS-only; the chain also tries Linux (`xdg-open`) and Windows
+(`powershell.exe Start-Process`). The Windows path is passed as data, not
+PowerShell source. On headless or unsupported cross-host sessions, report the
+failed launch and manual link instead of claiming the browser opened.
---
diff --git a/plugins/mobile-apps/skills/setup-app-insights/SKILL.md b/plugins/mobile-apps/skills/setup-app-insights/SKILL.md
index 9f6e9744a..16e3fea8e 100644
--- a/plugins/mobile-apps/skills/setup-app-insights/SKILL.md
+++ b/plugins/mobile-apps/skills/setup-app-insights/SKILL.md
@@ -91,7 +91,7 @@ node "${PLUGIN_ROOT}/hooks/run-telemetry.js" \
app-insights-selection \
"<enabled-or-disabled>" \
"<prompt-or-pretool>" \
- "<working_dir>"
+ '<working_dir>'
```
Pass the invocation source so the event's `invocationSource` matches how the skill was reached: `pretool` in Mode A (delegated from another skill such as `/edit-app` via the Skill tool) and `prompt` in Mode B (the user ran `/setup-app-insights` directly).
diff --git a/plugins/mobile-apps/skills/setup-datamodel/SKILL.md b/plugins/mobile-apps/skills/setup-datamodel/SKILL.md
index 718a36fe6..532e5ea9b 100644
--- a/plugins/mobile-apps/skills/setup-datamodel/SKILL.md
+++ b/plugins/mobile-apps/skills/setup-datamodel/SKILL.md
@@ -12,36 +12,87 @@ model: opus
# Set Up Data Model + Connectors
+**Invocation scope:** follow [Data-source invocation scope](../../shared/shared-instructions.md#data-source-invocation-scope)
+before any project read or the workflow below.
+
+This standalone data-only workflow does not require a complete app plan.
+It proposes and approves only the current schema/connector delta; preserve
+existing app sections without invoking full-app planning or screen generation.
+When called by an owner, retain its explicit current request, absolute root,
+phase, and scope, and return proposals or verified results to that owner.
+
Combined orchestrator for standalone data source planning. Designs the Dataverse schema, plans connectors, gets approval on both, then delegates execution to `/add-dataverse` and `/add-connector`.
| Use this skill when | Use `/add-dataverse` directly when |
|---|---|
-| Standalone schema + connector design (project may or may not exist yet) | The plan already exists and you just need to apply tables + generate services |
-| You have an existing ER diagram (image / Mermaid / text) to import | `/create-mobile-app` is invoking this as a sub-step with `--skip-planning` |
+| Standalone schema + connector design (initialized app; data plan optional) | The plan already exists and you just need to apply tables + generate services |
+| You have an existing ER diagram (image / Mermaid / text) to import | `/create-mobile-app` is invoking this as a sub-step with approved scoped context |
| Re-planning the schema or connectors mid-project | You only need to add a single table or a single connector |
## Workflow
-1. Verify project & auth → 2. Design data model → 3. Plan connectors → 4. Combined approval → 5. Execute data model → 6. Execute connectors → 7. Summary
+1. Resolve project root & verify auth → 2. Design data model → 3. Plan connectors → 4. Combined approval → 5. Execute additions/refreshes → 6. Execute connectors → 6.25 Retire approved bindings → 6.5 Reconcile offline profile → 7. Reconcile inventory & summarize
---
### Phase 1 — Verify Project & Auth
-Confirm we're inside a Power Apps mobile app:
+Resolve one absolute `working_dir` before reading project files or discovering
+the environment:
+
+- For a nested call, inherit the owner's absolute `working_dir`. If
+ `--working-dir` is also supplied, both must resolve to the same directory;
+ a mismatch returns `NEEDS_CONTEXT` before any project or cloud work.
+- For a direct call, resolve an explicit `--working-dir` against the invocation
+ directory. Only a direct call without an override may use that invocation
+ directory as its project root.
+- Require the selected directory to exist, normalize it to one absolute path,
+ and retain it for this invocation. A missing nested owner path is an error:
+ never fall back to the shell's current directory or search neighboring apps.
+
+All relative app paths below, including diagram inputs, `native-app-plan.md`,
+`_dm_section.md`, `.datamodel-manifest.json`, `offline-profile.json`, and
+`memory-bank.md`, are relative to this resolved root, not a later tool's cwd.
+Use absolute paths with file tools. Begin every shell invocation that reads or
+writes app-local files with the single-quoted fail-closed app-root guard; shell state does not
+carry across tool calls.
+
+Confirm the selected root is a Power Apps mobile app:
+
+For `--plan-only` or a planning-phase handoff, perform the file/environment
+checks read-only and use the shared proposal-only environment-context rule.
+The same non-persisting lookup is used before approval in a normal invocation.
+Incomplete or conflicting context returns `NEEDS_CONTEXT` after read-only
+recovery; never retry without the safety flags or redirect into app configuration.
```bash
-test -f power.config.json && echo "OK" || echo "ERROR: not a mobile app — run /create-mobile-app first"
-node "${PLUGIN_ROOT}/scripts/resolve-environment.js" "$(node -e \"console.log(require('./power.config.json').environmentId)\")"
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
+if [ ! -f power.config.json ] || [ ! -f app.config.js ]; then
+ printf '%s\n' 'ERROR: selected working directory is not an initialized mobile app' >&2
+ exit 1
+fi
+environment_id="$(node -p "require('./power.config.json').environmentId || ''")" || exit 1
+if [ -z "$environment_id" ]; then
+ printf '%s\n' 'ERROR: selected app has no environmentId' >&2
+ exit 1
+fi
+node "${PLUGIN_ROOT}/scripts/resolve-environment.js" "$environment_id" --no-cache --require-tenant
```
-Capture the **environment URL**, **environment ID**, **tenant ID**, and **organization ID** for Phase 5.
+Stop on failure; do not switch directories or re-scaffold. Capture the
+**environment URL**, **environment ID**, and **tenant ID**
+for this root for Phase 5. Pass this same absolute root in every planner/skill
+handoff and on retries.
### Phase 2 — Design Data Model
**Telemetry checkpoint: `design_dataverse_schema`**
-Check `$ARGUMENTS` for diagram hints first (`*.png`, `*.jpg`, `erDiagram` keyword, `||--o{` cardinality syntax). If a hint is present → Path A. If `$ARGUMENTS` describes the app at all → silently take Path B (architect propose). Only if both are empty, ask:
+Check whether the request needs Dataverse schema first; connector-only requests
+take Path C. Otherwise check `$ARGUMENTS` for diagram hints (`*.png`, `*.jpg`,
+`erDiagram`, `||--o{`). If present, take Path A. If a Dataverse requirement is
+already supplied, take Path B for a read-only proposal. If the choice is still
+unknown, ask:
> "How would you like to define the data model?"
@@ -51,7 +102,17 @@ Check `$ARGUMENTS` for diagram hints first (`*.png`, `*.jpg`, `erDiagram` keywor
| Let the Data Model Architect propose one (default) | Spawns `data-model-architect` agent to infer from requirements |
| Skip — no Dataverse tables needed | Jump to Phase 3 |
-Default the answer to "architect propose" so an empty answer auto-proceeds without blocking the user.
+Recommend "architect propose" only when Dataverse schema is needed. Connector-only
+requirements take Path C without inventing Dataverse tables. Empty/cancel input
+does not approve a choice; wait for an answer or stop.
+
+For Paths A and B, read and execute
+[dataverse-change-planning.md](../../shared/references/dataverse-change-planning.md).
+The foreground owns scoped discovery, compact-evidence validation, and recovery;
+pass `Dataverse planning mode: required` to the architect, never the legacy
+live-discovery path. Preserve the current request, absolute root, and
+proposal-only mode through every handoff. Path C, removal-only work, and a
+retained-service-only refresh skip schema planning and its artifacts.
#### Artifact storage rules for PDFs and signatures
@@ -59,7 +120,7 @@ When requirements mention signatures, sign-off, ink, drawings, generated PDFs, e
| User signal | Dataverse model implication |
|---|---|
-| "capture signature", "sign off", "approval signature", "ink" | Image column on the signed record for one current signature, or child Evidence/Signature table for multiple captures/history |
+| "capture signature", "sign off", "approval signature", "ink" | Ask whether retention is needed; only when Dataverse retention is selected, reuse or propose an Image/File column or child Evidence/Signature table |
| "generate PDF", "export report", "evidence packet", "certificate PDF" | Ask whether the generated PDF should be retained. If yes, use a Dataverse File column, usually on the parent record or a child Evidence/Attachment table. If no, document on-device/share-only behavior and add no column. |
| "upload PDF", "attach file", "import document" | File column or child Attachment table with lookup to parent |
| "view PDF" | Store or reference an HTTPS URL if the app has a durable source. Native PDF viewer 0.2.9+ also supports local `file://` URIs; `content://`, `blob:`, and `http://` remain unsupported. |
@@ -68,7 +129,12 @@ PDF content must never be modeled as long text/base64 text. Use Dataverse File c
#### Path A — Parse user-provided diagram
-Accept PNG/JPG (use `Read` to view), Mermaid syntax (paste in chat), or text description. Parse into tables + columns + relationships. Query existing Dataverse tables to mark each as new / extend / reuse. Generate a Mermaid ER diagram for confirmation. Enter `EnterPlanMode` for data model approval. On `ExitPlanMode` approval, write the data model into `native-app-plan.md` `## Data Model` section (creating the file if absent).
+Accept PNG/JPG (use `Read` to view), Mermaid syntax (paste in chat), or text
+description. Parse tables, columns, and relationships as requested intent.
+Use the shared compact-evidence workflow to draft `_dm_section.md` and the
+normalized `.tmp/dataverse-schema-contract.json`; diagram names alone do not
+prove existing schema. Run the same decision validation as Path B before the
+combined Phase 4 approval; do not update the live plan yet.
#### Path B — Spawn data-model-architect
@@ -78,10 +144,19 @@ Task: mobile-app:data-model-architect
Prompt:
You are the data-model-architect agent for a Power Apps mobile app.
Requirements: <$ARGUMENTS or ask the user what the app does>
- Working directory: <cwd>
+ Working directory: <working_dir>
+ Output proposal: <working_dir>/_dm_section.md
Plugin root: ${PLUGIN_ROOT}
-
- Follow your agent file. Return a ## Data Model section with Mermaid ER diagram,
+ Phase: planning
+ Proposal only: <true for --plan-only or a planning-phase caller>
+ Dataverse planning mode: required
+ Normalized Dataverse foreground planning snapshot (validator input only): <SNAPSHOT_PATH>
+ Compact Dataverse architect evidence: <ARCHITECT_EVIDENCE_PATH>
+ Structured schema contract output: <working_dir>/.tmp/dataverse-schema-contract.json
+ Scope: <current requested delta and necessary dependencies; unrelated rows are context only>
+ Native capabilities and connector ownership: <retained approved constraints>
+
+ Follow your snapshot-only path. Return a ## Data Model section with Mermaid ER diagram,
reuse/extend/create table, and dependency-tier ordering. If requirements mention
signatures, pen/ink, generated PDFs, report exports, evidence packets, or uploaded
documents, include the artifact storage target: on-device/share-only, Dataverse
@@ -89,11 +164,18 @@ Prompt:
PDF content must use a File column, not long text/base64.
```
-Present the returned section via `EnterPlanMode` / `ExitPlanMode` for approval.
+Handle structured Dataverse signals through the shared planning recovery before
+the generic `AGENTS.md` return protocol. Require both the section and normalized
+contract, then run the shared decision gate even for `DONE`/`DONE_WITH_CONCERNS`.
+If agents are unavailable, draft both artifacts inline from the same compact
+evidence and run the same validation. Keep the result as a proposal for Phase 4;
+stop on an unresolved blocker rather than treating the proposal as approved.
#### Path C — No Dataverse
-Write `## Data Model` as "None — no Dataverse tables needed." Continue to Phase 3.
+Propose no Dataverse changes. Preserve any existing Data Model section; only use
+"None — no Dataverse tables needed" when the project has no Dataverse model.
+Continue to Phase 3 without overwriting the plan.
### Phase 3 — Plan Connectors
@@ -113,7 +195,33 @@ If the user provided no requirements context, ask:
**Telemetry checkpoint: `approve_data_model_and_connectors`**
-Present the full plan — data model + connectors — together in a single `EnterPlanMode` block:
+For an existing data-only plan, compare current bindings with the proposal before
+writing it. Apply [data-source-removal.md](../../shared/references/data-source-removal.md)
+to classify and approve removals explicitly. Omitted tables are not automatic
+deletions; retain anything required by existing consumers. Report their required
+changes separately; the user may request existing `/edit-app` for consumer work,
+but this workflow does not invoke it automatically.
+
+For a Dataverse proposal from any path, require the current normalized contract
+and snapshot to pass `validate-dataverse-planning-decisions.js` with exit `0`
+before this gate. Revisions repeat validation, not broad discovery or another
+approval ceremony. Connector-only, retirement-only, and refresh-only proposals
+keep their own checks and must not reuse stale schema-planning artifacts.
+
+**Proposal-only exit:** if `--plan-only` is present or the caller's phase is
+planning, present the proposed Data Model, Connectors, and retirement/offline
+impact, then return to the caller and STOP before the execution approval below.
+Do not save `native-app-plan.md`, mint approval receipts, update the materialized
+manifest, or invoke Phases 5–7. A scratch proposal is not an applied plan.
+Approval to review the proposal does not override `--plan-only`; implementation
+requires a separate request without that flag and approval of its exact delta.
+
+Present the full plan for this data-source delta — data model + connectors —
+together in a single `EnterPlanMode` block. Distinguish retained context from
+additions, refreshes, and explicitly approved retirements. A current
+implementation-phase owner may supply the exact data approval instead; validate
+that it matches this proposal and return scope changes to that owner before
+writing. A saved plan or `--skip-planning` alone is not approval.
```
## Plan: Data Sources
@@ -129,9 +237,21 @@ Present the full plan — data model + connectors — together in a single `Ente
Approve both to proceed with execution?
```
-- **Approved** → proceed to Phase 5
+- **Approved** → save both approved sections to `native-app-plan.md`, preserving
+ unrelated sections, then proceed to Phase 5. This applies to every Phase 2 path,
+ including architect output and connector-only plans.
- **Change data model** → loop back to Phase 2 for that section only, then re-present Phase 4
- **Change connectors** → loop back to Phase 3, then re-present Phase 4
+- **Cancel** → stop without applying the proposed plan or data-source mutations.
+
+Save the accepted proposal into `<working_dir>/native-app-plan.md`; scratch
+`_dm_section.md` is not a second source of truth. Do not reuse operation manifests
+or approval receipts bound to the previous plan. The verified materialized
+manifest is updated after execution/verification, not by copying proposed rows.
+For approved Dataverse implementation, retain the shared planning paths and
+freeze the accepted `contract_sha256` and saved `plan_sha256` in
+`approved_scope`. This is not a create-flow receipt and does not grant unrelated
+native, connector, or screen approvals.
### Phase 5 — Execute Data Model
@@ -139,16 +259,40 @@ Approve both to proceed with execution?
Invoke `/add-dataverse` with `--skip-planning` so it reads the approved plan directly without re-prompting:
+Apply only additions/refreshes here. Skip this phase for a removal-only delta;
+approved retirements have their own Phase 6.25 handoff.
+
+For a service-only refresh of an already registered table, use the leaf's
+`--refresh --data-source-name "<registered-name>"` branch and pass its exact
+registered identity in `approved_scope`; do not execute the schema-add handoff
+below for that row. For schema changes, retain the normal handoff below.
+
```
Invoke skill: /add-dataverse
+Context:
+ MOBILE_APP_ORCHESTRATING=1
+ orchestrator: setup-datamodel
+ working_dir: <working_dir>
+ phase: implementation
+ offline_reconciliation_owner: setup-datamodel
+ planning_snapshot: <SNAPSHOT_PATH>
+ architect_evidence: <ARCHITECT_EVIDENCE_PATH>
+ schema_contract: <working_dir>/.tmp/dataverse-schema-contract.json
+ approved_scope: <approved Data Model delta and answers, contract_sha256, plan_sha256>
+
Arguments:
- --working-dir <cwd>
- --plan-section native-app-plan.md#data-model
+ --working-dir '<working_dir>'
+ --plan-section '<working_dir>/native-app-plan.md#data-model'
--skip-planning
```
-`/add-dataverse` creates tables in tier order, runs `pa app add data-source --connector dataverse --org-url <envUrl> --table <name>` per table from the app root, publishes customizations, writes `.datamodel-manifest.json`, and type-checks. Wait for it to return before Phase 6.
+`/add-dataverse` creates tables in tier order within this scope, adds only
+approved missing bindings or refreshes approved retained services, publishes
+customizations when needed, writes `.datamodel-manifest.json`, and type-checks.
+It validates the scoped planning context and performs fresh live reconciliation;
+do not send partial create-only fast-path flags. Wait for it to return before
+Phase 6.
**Cross-entity reads from the screen plan** — the approved
`### Cross-entity Reads` subsection contains formatted lookups, bounded chained
@@ -163,34 +307,129 @@ Skip if Phase 2 chose Path C (no Dataverse).
**Telemetry checkpoint: `generate_connector_data_sources`**
-Read `## Connectors` from `native-app-plan.md`. For each connector row, invoke `/add-connector`:
+Read `## Connectors` from `native-app-plan.md`. For each approved added/refreshed
+connector row (not retained or retiring rows), invoke `/add-connector`:
+
+Separate the operation before dispatch: an added row takes the normal handoff;
+a refreshed row adds `--refresh --data-source-name "<registered-name>"` and
+includes the verified API/dataset/connection identity in `approved_scope`.
+Do not infer the registered name from the connector display label. The refresh
+branch must return without connection creation or `add-data-source`.
+
+**Added source only:**
```
Invoke skill: /add-connector
+Context:
+ MOBILE_APP_ORCHESTRATING=1
+ orchestrator: setup-datamodel
+ working_dir: <working_dir>
+ phase: implementation
+ approved_scope: <approved connector row and answers>
+
Arguments:
- --working-dir <cwd>
+ --working-dir '<working_dir>'
--connector <api-name>
```
+**Retained-source refresh only:** use this separate handoff, never the add block.
+
+```text
+Invoke skill: /add-connector
+
+Context:
+ MOBILE_APP_ORCHESTRATING=1
+ orchestrator: setup-datamodel
+ working_dir: <working_dir>
+ phase: implementation
+ approved_scope: <refresh operation, exact registered name, verified API/dataset/resource and connection ID/reference>
+
+Arguments:
+ --working-dir '<working_dir>'
+ --connector <verified-api-id>
+ --refresh
+ --data-source-name "<registered-name>"
+```
+
Run sequentially. Skip if `## Connectors` is "None".
+### Phase 6.25 — Retire unused app bindings
+
+For each explicitly approved retirement, invoke the matching leaf with
+`--remove`, `MOBILE_APP_ORCHESTRATING=1`, `orchestrator: setup-datamodel`,
+`phase: implementation`, `working_dir: <working_dir>`, the argument
+`--working-dir '<working_dir>'`, and its `approved_scope`.
+Follow [data-source-removal.md](../../shared/references/data-source-removal.md).
+This standalone data-only flow does not edit consumers: if any remain, stop and
+report their integration work to the user or current owner instead of breaking
+them. The user may separately request `/edit-app`; never route there automatically.
+Verify the CLI cleanup and reconcile the actual remaining generated-service
+snapshot and app manifest before the summary. No retirement set means skip.
+Preserve each leaf's `offlineRetirement` outcome from the shared removal contract,
+including unresolved outcomes recorded in memory-bank by an earlier attempt.
+App-binding cleanup and offline-profile migration have separate completion states.
+
### Phase 6.5 — Offline profile reconciliation
**Telemetry checkpoint: `reconcile_offline_profile`**
-If Phase 5 created or extended Dataverse tables, an existing Mobile Offline Profile may now be missing those tables/columns. Because Phase 5 invoked `/add-dataverse` with `--skip-planning` (which suppresses that skill's own Step 8.5 reconciliation), this orchestrator owns the check. Skip when Phase 2 chose Path C (no Dataverse).
+If Phase 5 created or extended Dataverse tables, an existing Mobile Offline Profile may now be missing those tables/columns. Phase 5 passes a complete scoped handoff with `offline_reconciliation_owner: setup-datamodel`; together with `--skip-planning`, that makes this orchestrator the owner instead of running the leaf's Step 8.5 check twice. The flag alone is not enough. Skip the addition check when Phase 2 chose Path C (no Dataverse), but never discard a recorded `offlineRetirement` outcome.
Run the local, no-network delta check:
```bash
-node "${PLUGIN_ROOT}/scripts/offline-profile-delta.js"
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
+node "${PLUGIN_ROOT}/scripts/offline-profile-delta.js" --project-root '<working_dir>'
```
-Branch on the JSON `status` per [offline-profile-reconciliation.md](${PLUGIN_ROOT}/shared/references/offline-profile-reconciliation.md): `no-manifest` / `no-profile` / `in-sync` → continue to Phase 7 silently (do not nag when no profile exists); `delta` → prompt to update, then read and execute `${PLUGIN_ROOT}/skills/add-table-to-offline-profile/SKILL.md` for `missingTables[]` and `${PLUGIN_ROOT}/skills/edit-offline-profile/SKILL.md` for `tablesWithNewColumns[]`, passing the arguments documented by each workflow, and re-check to `in-sync`.
+Capture the exit status and stdout/stderr. Before any status dispatch or
+Phase 7 summary, a non-zero exit, `status: error`, missing/malformed JSON, or
+unknown status follows the failure path in
+[offline-profile-reconciliation.md](${PLUGIN_ROOT}/shared/references/offline-profile-reconciliation.md):
+surface the error, record `offline_reconciliation: failed` with existing
+retirement outcomes intact, skip mutation helpers, and return
+`DONE_WITH_CONCERNS` for already-applied data changes (otherwise `BLOCKED`).
+Do not claim completed reconciliation or continue to the clean success summary.
+
+For a valid successful check, branch on the JSON `status`: `no-manifest` /
+`no-profile` / `in-sync` means no addition work; continue to Phase 7 with the
+existing `offlineRetirement` outcomes unchanged (do not nag when no profile
+exists). For `delta`, obtain offline-update approval, then use the reference's
+**Scoped helper handoffs** with `orchestrator: setup-datamodel`,
+`working_dir: <working_dir>`, `phase: implementation`, and the exact approved
+environment/profile/table/filter-or-column scope. Pass
+`--working-dir '<working_dir>' --table <logicalName>` to
+`add-table-to-offline-profile` for `missingTables[]`, or those same arguments
+plus `--columns "add:<newColumns>"` to `edit-offline-profile` for
+`tablesWithNewColumns[]`. Re-check to `in-sync` using the same failure path.
+Declined or incomplete addition work remains a separate concern.
+
+These offline helpers also inherit the same absolute `working_dir`; no new root
+discovery is permitted during reconciliation.
### Phase 7 — Summary
+Before success, reconcile each affected plan section with this project's verified
+output and refresh the Generated Services snapshot. For Dataverse changes, also
+reconcile `.datamodel-manifest.json`, retaining a valid empty inventory after
+removing the last Dataverse binding. Connector-only work without Dataverse does
+not require or create a Dataverse manifest. Record partial execution or unresolved
+removals in memory-bank and return a non-success status rather than claiming the plan is fully applied.
+
+Render the summary from verified results, not the example's possible artifacts.
+For connector-only work without a Dataverse inventory, report Data Model and
+Manifest as `not applicable`; do not print a nonexistent manifest path. If a
+verified inventory already exists but was untouched, label it `unchanged`.
+
+Include every affected table's `offlineRetirement` status in memory-bank and the
+final response. `pending` returns `DONE_WITH_CONCERNS`, not a clean `DONE`:
+"App changes completed. The offline profile still includes Orders; deciding
+whether to retain or remove that coverage is pending."
+Use actual table names and verified app results; if app cleanup failed, report
+that failure instead of claiming completion. `retained` reports the approved
+reason; `reconciled` requires verified profile migration, not an `in-sync` result.
+
```
✅ Data sources set up
─────────────────────────────────────────────
@@ -198,7 +437,7 @@ Data model:
Tables reused : <list>
Tables extended: <list>
Tables created : <list>
- Manifest : .datamodel-manifest.json
+ Manifest : <verified manifest path and updated/unchanged status, or "not applicable">
Connectors:
<list of added connectors, or "None">
@@ -212,7 +451,7 @@ Type-check: PASS
Next steps:
/add-datasource — add more data sources
/add-native — add device capabilities
- screen-builder — implement screens using the generated services
+ /edit-app — separately request consumer/screen changes if needed
─────────────────────────────────────────────
```
diff --git a/plugins/mobile-apps/skills/setup-offline-profile/SKILL.md b/plugins/mobile-apps/skills/setup-offline-profile/SKILL.md
index adfeb671e..f4a8d4d95 100644
--- a/plugins/mobile-apps/skills/setup-offline-profile/SKILL.md
+++ b/plugins/mobile-apps/skills/setup-offline-profile/SKILL.md
@@ -37,6 +37,24 @@ app-owned offline runtime code.
- User/team membership assignment — split into `/assign-offline-profile`
- Row-count download estimation — split into `/preview-offline-scope`
+## App-root binding
+
+Before entering the wizard, and before any project read or command, execute
+[app-working-directory.md](${PLUGIN_ROOT}/shared/references/app-working-directory.md).
+Resolve one absolute `working_dir`: inherit a child invocation's owner root or
+use the direct invocation's explicit `--working-dir`/initial cwd per that contract.
+Missing or conflicting child context returns `NEEDS_CONTEXT`, never a launch-cwd
+fallback. Bind every shell call and file tool, including references and retries,
+to this root; file tools use absolute `<working_dir>/...` paths.
+
+Retain the selected environment ID/URL/tenant and supplied answers as invocation
+context. Re-supply the absolute `PLUGIN_ROOT` and required values in each fresh
+call; prior shell variables do not persist. Forward the same root and identity
+to the architect and prerequisite helper. Entry approval is not permission to
+skip the wizard's offline gates. A `--plan-only` or planning-phase caller returns
+`NEEDS_CONTEXT: offline setup requires an implementation-phase invocation`
+before entering this mutating wizard.
+
## Workflow
1. Verify project & auth → 2. Resolve mode (create vs extend) → 3. Spawn architect agent → **Gate 1** (table prerequisites) → 4. Run the internal `enable-tables-offline` workflow if needed → 5. POST profile shell → **Gate 2** (per-table row scope) → 6. POST profile items → **Gate 3** (relationships + columns + sync) → 7. POST associations → 8. Validate + publish → 9. Persist artifacts → 10. Summary
@@ -46,26 +64,42 @@ app-owned offline runtime code.
### Step 1 — Verify project & auth
```bash
-test -f power.config.json && test -f app.config.js
-# Manifest lives at either root (legacy) or docs/plan-artifacts/ (newer scaffolds)
-MANIFEST=$(test -f .datamodel-manifest.json && echo ".datamodel-manifest.json" || \
- (test -f docs/plan-artifacts/.datamodel-manifest.json && echo "docs/plan-artifacts/.datamodel-manifest.json"))
-test -n "$MANIFEST" && echo "✓ manifest at $MANIFEST"
-node "${PLUGIN_ROOT}/scripts/resolve-environment.js" "$(node -e \"console.log(require('./power.config.json').environmentId)\")"
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
+if [ ! -f power.config.json ] || [ ! -f app.config.js ]; then
+ echo "BLOCKED: working_dir is not an initialized app" >&2
+ exit 1
+fi
+environment_id=$(node -p "require('./power.config.json').environmentId || ''") || {
+ echo "BLOCKED: unreadable power.config.json" >&2; exit 1;
+}
+if [ -z "$environment_id" ]; then
+ echo "NEEDS_CONTEXT: selected app has no environmentId" >&2; exit 1;
+fi
+node "${PLUGIN_ROOT}/scripts/resolve-environment.js" "$environment_id" --no-cache --require-tenant
```
-Capture **Environment URL** for `<envUrl>` and **manifest path** for the architect spawn (Step 3) and the artifacts write (Step 9).
+Require the resolved environment ID, HTTPS URL, and tenant to match any supplied
+owner context. Capture them as `<selected-environment-id>`, `<envUrl>`, and
+`<tenantId>`. A mismatch returns `NEEDS_CONTEXT`; do not switch environment or
+account to proceed. Pass `--tenant-id "<tenantId>"` to every Dataverse request,
+including copied reference commands and retries.
+
+Locate `<working_dir>/.datamodel-manifest.json` or
+`<working_dir>/docs/plan-artifacts/.datamodel-manifest.json` with absolute file
+tools. Keep the selected absolute manifest path in invocation context for the
+architect (Step 3) and artifact updates (Step 9); never search another app.
**Web-only target detection** — Mobile Offline Profiles only apply to native targets (iOS/Android). If the project is web-only, the profile will be created in Dataverse but **the generated app will never use it**:
```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
# Inspect platforms declared in app.config.js
node -e "
-const c = require('$(pwd)/app.config.js');
+const c = require('./app.config.js');
const platforms = c?.expo?.platforms ?? [];
const hasNative = platforms.includes('ios') || platforms.includes('android');
console.log(JSON.stringify({ platforms, hasNative }));
-" 2>/dev/null
+"
```
| `hasNative` | Action |
@@ -137,8 +171,10 @@ Read `memory-bank.md` `## Offline profile` block. Decide based on `status`:
> "→ Checking for existing offline profiles in the environment…"
```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
node "${PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> GET \
- "mobileofflineprofiles?\$select=mobileofflineprofileid,name,description,publishedon"
+ "mobileofflineprofiles?\$select=mobileofflineprofileid,name,description,publishedon" \
+ --tenant-id "<tenantId>"
```
Decision tree — evaluate in order:
@@ -168,9 +204,15 @@ Spawn via `Task`:
```text
agent: mobile-app:offline-profile-architect
prompt:
- Working directory: <workdir>
+ Owner: setup-offline-profile
+ Phase: planning
+ Working directory: <working_dir>
Plugin root: ${PLUGIN_ROOT}
+ Environment ID: <selected-environment-id>
Environment URL: <envUrl>
+ Tenant ID: <tenantId>
+ Manifest path: <absolute manifest path within working_dir>
+ Proposal output: <working_dir>/_offline_section.md
Publisher prefix: <prefix>
Mode: default
```
@@ -338,13 +380,33 @@ configReview: accepted
**Telemetry checkpoint: `enable_dataverse_tables_offline`**
-If Gate 1 identified any table needing change, read and execute `${PLUGIN_ROOT}/skills/enable-tables-offline/SKILL.md` with the table list as its `$ARGUMENTS`:
+If Gate 1 identified any table needing change, read and execute
+`${PLUGIN_ROOT}/skills/enable-tables-offline/SKILL.md` with the approved table
+list and the complete scoped handoff below. Configuration review must already
+be accepted; neither a saved manifest nor a bare table list is approval.
```text
-$ARGUMENTS: cr123_note,cr123_visit
+$ARGUMENTS: --working-dir '<working_dir>' <comma-separated approved logical names>
+
+Context:
+ MOBILE_APP_ORCHESTRATING=1
+ orchestrator: setup-offline-profile
+ working_dir: <working_dir>
+ phase: implementation
+ approved_scope:
+ environmentId: <selected-environment-id>
+ environmentUrl: <envUrl>
+ tenantId: <tenantId>
+ tables: <exact Gate 1-approved prerequisite table allowlist>
+ operations: <approved IsAvailableOffline/ChangeTrackingEnabled changes>
+ publication: <approved targeted publication; broader fallback only if separately approved>
+ supplied_answers: <current offline gate responses>
```
-Wait for it to return. Expected final line: `DONE` or `DONE_WITH_CONCERNS:`.
+Wait for it to return and parse its literal first-line status. `DONE` continues;
+`DONE_WITH_CONCERNS` must be surfaced before continuing. On `NEEDS_CONTEXT`,
+resolve the missing context within this owner's approved root/scope or return
+the blocker; never re-dispatch with a different app or infer approval.
If `BLOCKED`, propagate the block up — STOP.
@@ -360,8 +422,10 @@ If all tables were already enabled, skip this step.
For `create-new` mode:
```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
node "${PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> POST \
"mobileofflineprofiles" \
+ --tenant-id "<tenantId>" \
--body '{
"name": "<app name> Offline Profile",
"description": "<auto-generated description referencing app name + scope summary>"
@@ -398,8 +462,10 @@ gate1: approved
For each table, in sequence:
```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
node "${PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> POST \
"mobileofflineprofileitems" \
+ --tenant-id "<tenantId>" \
--body '{
"name": "<table display name>",
"[email protected]": "/mobileofflineprofiles(<profileId>)",
@@ -434,8 +500,10 @@ Print `✓ <table>` after each 2xx.
Empirical 2026-05-24 + 2026-05-25 capture from maker portal **unblocked** association creation. Recipe (no `selectedrelationshipsschema` field — server fills it):
```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
node "${PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> POST \
"mobileofflineprofileitemassociations" \
+ --tenant-id "<tenantId>" \
--body '{
"name": "<relationshipSchemaName>",
"relationshipdisplayname": "<relationshipSchemaName>",
@@ -464,8 +532,10 @@ Skip Step 7a entirely if the architect's proposal includes zero relationships (r
#### Step 7b — PATCH `selectedcolumns` on each item
```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
node "${PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> PATCH \
"mobileofflineprofileitems(<itemId>)" \
+ --tenant-id "<tenantId>" \
--body '{
"selectedcolumns": "<JSON string — see below>"
}'
@@ -495,14 +565,22 @@ If syncintervalinminutes was edited at Gate 3, include it in the same PATCH.
**Targeted PublishXml — the maker portal's pattern** (empirical 2026-05-24):
```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
node "${PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> POST \
- "PublishXml" --body '{
- "ParameterXml": "<publish><mobileofflineprofiles><mobileofflineprofile>'"$PROFILE_ID"'</mobileofflineprofile></mobileofflineprofiles></publish>"
+ "PublishXml" --tenant-id "<tenantId>" --body '{
+ "ParameterXml": "<publish><mobileofflineprofiles><mobileofflineprofile><profileId></mobileofflineprofile></mobileofflineprofiles></publish>"
}'
```
Publishes ONLY this profile, not the entire org's customizations. Empirically much faster + less rate-limit-prone than `PublishAllXml` on shared envs.
+For the repair helpers below, use the reconciliation reference's
+[Scoped helper handoffs](${PLUGIN_ROOT}/shared/references/offline-profile-reconciliation.md#scoped-helper-handoffs)
+with `orchestrator: setup-offline-profile`, the same absolute `working_dir`,
+selected environment/tenant/profile, and the exact user-approved repair scope.
+Pass `--working-dir '<working_dir>'` and the selected profile/table arguments.
+Do not infer a new repair approval from the original profile-creation approval.
+
**On `400 / 0x80071141` "circular relationship":** the profile's association graph has a cycle (e.g. `account → task → account`). Parse the path from the error message, prompt the user to drop ONE of the offending associations, re-DELETE that association row via DELETE `/mobileofflineprofileitemassociations(<id>)`, then re-attempt publish. See [shared/references/dataverse-offline-api.md §6b](${PLUGIN_ROOT}/shared/references/dataverse-offline-api.md).
**On `400 / 0x80071140` "no relationships are specified" for a Related-only table:** a profile item has `recorddistributioncriteria=0` but no associations point at it. Parse the table name from the error message and prompt the user with two choices:
@@ -511,11 +589,15 @@ Publishes ONLY this profile, not the entire org's customizations. Empirically mu
For fresh `/setup-offline-profile` runs this error should never fire because Step 7a POSTs associations before Step 8 publish. But it CAN fire on retrofit scenarios where a profile published under v0.1's old "no associations" recipe is later edited — Dataverse's publish-validator appears to compare against the previously-published snapshot, not the current uncommitted state. Empirically observed 2026-05-24 on chanel-rm.
-**Fallback — `PublishAllXml`:** if the targeted publish fails with anything other than the circular-relationship error, try the broad publish. This was the v0.1 default and works correctly but rate-limits aggressively on shared envs:
+**Fallback — `PublishAllXml`:** only if targeted publication cannot complete and
+the user separately approves publishing all pending environment customizations.
+A profile-scoped approval, timeout, or rate limit is not broader publication
+consent. Otherwise report the failure without widening scope.
```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
node "${PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> POST \
- "PublishAllXml" --body '{}'
+ "PublishAllXml" --tenant-id "<tenantId>" --body '{}'
```
**Handle the timeout-but-success pattern** — empirically observed on shared envs (CRM527116 + chanel-rm demos): `PublishAllXml` triggers a 4-retry 429 backoff, `dataverse-request.js` times out client-side after ~2 min, but the publish **DID** commit server-side. The targeted `PublishXml` should avoid this in most cases, but the fallback path still needs to handle it.
@@ -526,8 +608,9 @@ Protocol after the POST call returns:
2. If status `0` AND error contains `Request timed out` OR `429 rate-limited` → DO NOT treat as failure. Run the verification GET below:
```bash
+ cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
node "${PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> GET \
- "mobileofflineprofiles(<profileId>)?\$select=componentstate,publishedon" 2>&1
+ "mobileofflineprofiles(<profileId>)?\$select=componentstate,publishedon" --tenant-id "<tenantId>"
```
- `componentstate == 0` AND `publishedon` is a non-null ISO8601 timestamp within the last 5 minutes → treat as success. Print: `↷ PublishAllXml client timed out but committed server-side (componentstate=0, publishedon=<ts>).` Continue.
@@ -599,6 +682,7 @@ After confirmed success, re-GET the profile and check `publishedon` for the arti
Example node script (writes the file in one shot — no read-modify-write against `power.config.json`):
```bash
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
node -e '
const fs = require("fs");
@@ -666,7 +750,9 @@ associationsCount: <M>
> "→ Verifying the on-server profile matches offline-profile.json…"
```bash
-node "${PLUGIN_ROOT}/scripts/verify-offline-profile.js" <envUrl>
+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
+node "${PLUGIN_ROOT}/scripts/verify-offline-profile.js" <envUrl> \
+ --project-root '<working_dir>' --tenant-id "<tenantId>"
```
Read the JSON output: