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.

plan-alm: strict plan-only planner (execution skills self-maintain the plan) (#191)

T-Nida781215273f1
diff --git a/plugins/power-pages/.claude-plugin/plugin.json b/plugins/power-pages/.claude-plugin/plugin.json
index e531ef646..3021445a0 100644
--- a/plugins/power-pages/.claude-plugin/plugin.json
+++ b/plugins/power-pages/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "power-pages",
- "version": "2.1.0",
+ "version": "2.2.0",
"description": "Create and deploy Power Pages sites using modern development approaches. Supports code sites (SPAs) with React, Angular, Vue, or Astro. Includes ALM orchestration (plan-alm) with a solution-splitting decision tree, per-solution pipelines, Azure Blob asset advisory, manifest schema v2 for multi-solution deployments, and force-link remediation for cross-host pipeline migrations.",
"author": {
"name": "Microsoft",
diff --git a/plugins/power-pages/AGENTS.md b/plugins/power-pages/AGENTS.md
index 6f07d92aa..1772137c8 100644
--- a/plugins/power-pages/AGENTS.md
+++ b/plugins/power-pages/AGENTS.md
@@ -118,13 +118,13 @@ skills/
## ALM intent routing — `plan-alm` is the front door
-When the user expresses an **ALM intent** in natural language — *promote this site to {env}, ship to staging, deploy to production, set up CI/CD, move to next environment, push out a release, run the pipeline, export and import to staging* — invoke **`/power-pages:plan-alm` first**, before any individual ALM skill. The orchestrator detects the project state, runs the pre-plan completeness check, asks about promotion strategy, and dispatches to the right skills (`setup-solution`, `setup-pipeline`, `deploy-pipeline`, `activate-site`, `test-site`) in the right order.
+When the user expresses an **ALM intent** in natural language — *promote this site to {env}, ship to staging, deploy to production, set up CI/CD, move to next environment, push out a release, run the pipeline, export and import to staging* — invoke **`/power-pages:plan-alm` first**, before any individual ALM skill. `plan-alm` is a **planner**: it detects the project state, runs the pre-plan completeness check, asks about promotion strategy, and writes a rendered HTML plan (whose `steps[]` array is the recommended execution sequence). **It does not deploy anything.** After the user approves the plan, *the user runs* the individual skills (`setup-solution`, `setup-pipeline`, `deploy-pipeline`, or `export-solution`/`import-solution`, plus `activate-site`/`test-site`) in the plan's order. Each detects the approved plan via its Phase 0 gate, proceeds without re-nagging, refreshes the plan on completion, and points the user at the next step — but never auto-chains. This separation keeps `plan-alm` safe to run unattended (no single answer can trigger an irreversible deployment).
-**Do not** jump straight to `/power-pages:setup-pipeline`, `/power-pages:deploy-pipeline`, `/power-pages:export-solution`, or `/power-pages:import-solution` in response to an ALM intent. Those are individual building blocks; running them out of order misses the orchestrator's gates (completeness check, host resolution, deployment-strategy selection, post-deploy validation, rendered HTML plan).
+**Do not** jump straight to `/power-pages:setup-pipeline`, `/power-pages:deploy-pipeline`, `/power-pages:export-solution`, or `/power-pages:import-solution` in response to an ALM intent. Those are individual building blocks; running them without a plan first misses the planner's analysis (completeness check, host resolution, deployment-strategy selection, size/split decisions, rendered HTML plan).
**Skip `plan-alm` only when the user is explicit about the individual skill.** Phrases like *"just run setup-pipeline"*, *"skip planning, just deploy"*, *"I only need to export the solution zip"* are direct invocations — honor them. Anything ambiguous about deployment intent → `plan-alm` first.
-`setup-pipeline` and `deploy-pipeline` enforce this with a Phase 0 ALM-plan gate. If a user invokes them directly without a plan, those skills surface the recommendation to run `plan-alm` first (with an "I know what I'm doing" escape hatch). The Phase 0 gate is meant to fail closed — don't bypass it on the user's behalf.
+Every ALM execution skill enforces this with a Phase 0 ALM-plan gate. If a user invokes one directly without a plan, the skill recommends running `plan-alm` first (option 1, recommended) with a *"continue without a plan"* escape hatch; choosing to plan runs `plan-alm` (which only plans) and then the skill proceeds. The Phase 0 gate is meant to fail closed — don't bypass it on the user's behalf.
## Plugin Components
@@ -160,7 +160,7 @@ User-invocable via `/power-pages:<skill-name>`:
- `setup-pipeline`: 7-phase workflow — detect project context (`powerpages.config.json`, `.solution-manifest.json`, `pac env who`, `pac env list`, `RetrieveSetting('DefaultCustomPipelinesHostEnvForTenant')` on dev env to auto-discover host environment), select platform (Power Platform Pipelines = full; GitHub/ADO = coming soon), confirm pipeline configuration with auto-filled values (pipeline name, host env URL, target environments), run preflight checks (Pipelines installed, solution exists, no name conflict), create `deploymentenvironments` records for source + each target (poll `validationstatus` until Succeeded), create `deploymentpipelines` record + `$ref` associate source env (relative path + `@odata.context`) + create `deploymentstages` per target, verify and write `docs/alm/last-pipeline.json` + `docs/pipeline-setup.md` + commit. Uses `references/cicd-pipeline-patterns.md` for all HAR-confirmed API patterns.
- `deploy-pipeline`: 8-phase workflow — verify prerequisites (`docs/alm/last-pipeline.json`, az login, host env token), select target stage (from stages in `docs/alm/last-pipeline.json`; warn if last deploy failed), **pre-flight check on the target env's `blockedattachments` setting** via `fix-blocked-attachments.js --dry-run` (Phase 2.5, Power Pages projects only — prompts the user to unblock `.js`/`.css` proactively when they're on the env's blocklist, saving the ~50-75 min wasted import for sites with thousands of bundle chunks; complementary to the reactive Phase 7.6 handler), resolve pipeline info via `RetrieveDeploymentPipelineInfo` (v9.1) to get `SourceDeploymentEnvironmentId` and available artifacts, create `deploymentstageruns` record + call `ValidatePackageAsync` (204) + poll `operation` field until not `200000201` (surface `validationresults` issues), optionally PATCH `deploymentsettingsjson` for env var / connection reference overrides, **final deploy consent gate at Phase 6.0** (explicit `Deploy now / Cancel` `AskUserQuestion` before either `DeployPackageAsync` or the `pac pipeline deploy` fallback — closes a gap where Phase 5 → Phase 6.1 could fire without a final confirmation when validation passes cleanly), call `DeployPackageAsync` + poll `stagerunstatus` until terminal (handle approval gates with user pause), write `docs/alm/last-deploy.json` + present deployment summary.
- `force-link-environment`: 6-phase workflow — verify prerequisites (Azure CLI token for the target host, PAC CLI auth) and ground in Microsoft Learn (`custom-host-pipelines#using-force-link…`), identify host env URL (from `docs/alm/last-host-check.json`, `docs/alm/last-pipeline.json`, or user input) and source dev env's BAP env GUID, resolve or create the `deploymentenvironments` record on the new host (re-querying by `environmentid` to recover the record ID when `create-deployment-environment.js` throws on the "already associated" validation failure), require explicit `AskUserQuestion` consent for the destructive cross-host stamp move (makers in the previous host lose pipeline access for this env; previous host's record is left with stale `validationstatus`; reversible by re-running from the previous host), call `scripts/lib/force-link-environment.js` to POST `ManageEnvironmentStamp` + re-poll `validationstatus` until Succeeded, write `docs/alm/last-force-link.json` marker. Auto-fix entry point for Pattern 15 in `references/deployment-error-catalog.md`.
-- `plan-alm`: 8-phase orchestrator workflow — detect project state (powerpages.config.json, existing manifests, pac env who), gather ALM strategy via branched question flow (PP Pipelines or Manual export/import path), generate HTML ALM plan (docs/alm-plan.html with pipeline diagram and execution checklist), get user approval, then execute: setup-solution (conditional), setup-pipeline or export-solution (path-dependent), deploy-pipeline or import-solution per stage, finalize with HTML status update and git commit.
+- `plan-alm`: 4-phase **planner** workflow — detect project state (powerpages.config.json, existing manifests, pac env who), gather ALM strategy via branched question flow (PP Pipelines or Manual export/import path), generate HTML ALM plan (docs/alm-plan.html with pipeline diagram and a recommended-execution checklist), then save it (Approved or Draft) and commit. **It does not execute any deployment.** The user runs the individual ALM skills afterward — `setup-solution`, `setup-pipeline`/`export-solution`, `deploy-pipeline`/`import-solution`, `activate-site`, `test-site` — each of which detects the plan (Phase 0 gate), proceeds, and refreshes the plan on completion (via `refresh-alm-plan-data.js`, which also reports the next recommended step). This keeps `plan-alm` safe under autopilot: it never triggers an irreversible action.
For small mid-cycle changes (one file, one snippet, one site setting) that previously used a separate hotfix solution: instead, run `setup-solution` in sync mode to adopt the modified components into the existing base solution, bump the solution version, and use `deploy-pipeline` to ship. This keeps a single solution lineage (cleaner audit trail, simpler dependency management) and avoids solution sprawl. Power Platform Pipelines computes incremental imports internally, so re-deploying the base after a small fix is fast.
diff --git a/plugins/power-pages/README.md b/plugins/power-pages/README.md
index 4082725df..38e728746 100644
--- a/plugins/power-pages/README.md
+++ b/plugins/power-pages/README.md
@@ -257,15 +257,15 @@ Runs a guided, end-to-end security review of a Power Pages site and consolidates
> "Plan how to promote this site to staging and production"
-Orchestrator skill that creates an ALM (Application Lifecycle Management) plan for deploying a Power Pages site across environments. Gathers your promotion strategy, target environments, and approval requirements, generates a visual HTML plan, and after your approval executes the plan by calling the right ALM skills in sequence.
+Planner skill that creates an ALM (Application Lifecycle Management) plan for deploying a Power Pages site across environments. Gathers your promotion strategy, target environments, and approval requirements, then generates a visual HTML plan for your review and approval. **It does not deploy anything itself** — after you approve the plan, you run the individual ALM skills, which detect the plan and execute the right step in order.
- Detects project state (config, manifests, current environment)
- Branched flow for Power Platform Pipelines or manual export/import
-- Generates `docs/alm-plan.html` for review and approval
-- Dispatches to `setup-solution`, `setup-pipeline`, `export-solution`, `deploy-pipeline`, or `import-solution`
+- Generates `docs/alm-plan.html` for review and approval (the recommended execution sequence is the plan of record)
+- Recommends the skill sequence to run next — `setup-solution`, `setup-pipeline`/`export-solution`, `deploy-pipeline`/`import-solution` — each of which detects this plan, proceeds, and keeps it updated as it runs
> [!TIP]
-> `/plan-alm` is the front door for any ALM intent. Use it instead of jumping straight to individual ALM skills when you want to deploy to staging, ship to production, or set up CI/CD.
+> `/plan-alm` is the front door for any ALM intent — run it first to produce the plan. It plans only; you then run the execution skills it recommends. Use it instead of jumping straight to individual ALM skills when you want to deploy to staging, ship to production, or set up CI/CD.
#### `/setup-solution`
@@ -444,10 +444,14 @@ A common end-to-end workflow looks like this:
12. /deploy-site → Push final changes live
13. /test-site → Runtime smoke test on the live URL
14. /security-review → Full security review (headers, firewall, scan, permissions)
-15. /plan-alm → Plan multi-environment promotion
-16. /deploy-pipeline → Promote through staging → production
+15. /plan-alm → Plan multi-environment promotion (planning only — produces the plan)
+16. /setup-solution → Package the site into a Dataverse solution
+17. /setup-pipeline → Set up the Power Platform pipeline
+18. /deploy-pipeline → Promote through staging → production (run per stage)
```
+> Steps 16–18 are the execution sequence `/plan-alm` recommends — you run them yourself; each detects the approved plan and keeps it updated. `/plan-alm` never runs them for you.
+
Steps can be run independently — you don't need to follow this exact order. Each skill checks its own prerequisites and will tell you if something is missing. If something goes wrong, `/diagnose-deployment` pattern-matches deployment errors and `/report-issue` opens a pre-filled GitHub issue.
## Running Without Interruption
diff --git a/plugins/power-pages/references/approval-gates.md b/plugins/power-pages/references/approval-gates.md
index c4dc67c24..5ada7883c 100644
--- a/plugins/power-pages/references/approval-gates.md
+++ b/plugins/power-pages/references/approval-gates.md
@@ -256,7 +256,9 @@ Each section lists every `AskUserQuestion` in that skill. Catalog rows are marke
---
-### 6.1 `plan-alm` (19 calls; orchestrator)
+### 6.1 `plan-alm` (15 calls; planner)
+
+> `plan-alm` is a **planner** — it produces an approved/draft HTML plan and never executes. The execution gates that used to live in Phases 5–8 (deploy-failure, post-deploy activation, manual export/import checkpoint) now belong to the individual ALM skills the user runs afterward; they are catalogued under those skills' sections, not here.
| ID | Kind | Category | Phase | Trigger / question | Cancel leaves |
|---|---|---|---|---|---|
@@ -273,12 +275,8 @@ Each section lists every `AskUserQuestion` in that skill. Catalog rows are marke
| `plan-alm:2.q3-manual` | gate | plan | 2 (Q3 Manual) | *"How many target envs?"* | nothing |
| `plan-alm:2.q4-manual-target` | gate | plan | 2 (Q4 Manual per stage) | *"URL for target env {N}?"* | nothing |
| `plan-alm:2.q5-manual-type` | gate | plan | 2 (Q5 Manual) | *"Export managed or unmanaged?"* | nothing |
-| `plan-alm:2.q6-manual-checkpoint` | gate | plan | 2 (Q6 Manual) | *"Pause between export and import?"* | nothing |
-| `plan-alm:4.approve` | gate | plan | 4 | *"Approve and execute / save for later / change something"* | nothing |
-| `plan-alm:4.approver-fallback` | not-a-gate | — | 4 | Free-text "approver name" — pure data-gathering | — |
-| `plan-alm:7.manual-checkpoint` | gate | progress | 7 (Manual path) | `MANUAL_CHECKPOINT=true` — *"Export done; proceed to import?"* | partial-manifest |
-| `plan-alm:7.deploy-failure` | gate | plan | 7 (Step A.1) | deploy-pipeline halted before completing — *"Retry / Skip stage / Exit"*. Fires per failed stage. | nothing |
-| `plan-alm:7.activate-step-b` | gate | plan | 7 (Step B) | Post-deploy activation prompt per stage — *"Activate now / skip"* | nothing |
+| `plan-alm:4.approve` | gate | plan | 4 | *"Save approved / Save draft / Change something"* — saves the plan; never executes | nothing |
+| `plan-alm:4.approver` | not-a-gate | — | 4 | Approver-name capture (option 1 only) — always-on interactive prompt with git/OS-name prefill; data-gathering for the audit trail | — |
---
@@ -724,7 +722,7 @@ These need explicit confirmation from the reviewer before SKILL.md edits land. R
These are honest unresolved questions — not necessary to answer before v2 lands, but flagged for future tightening:
-- **Does `intent` need a sub-category for plan-alm itself?** plan-alm is the orchestrator; it doesn't have a Phase 0 ALM-plan gate (because it *is* the plan). The closest analogue is `plan-alm:1.deferral` (handle `.alm-deferred` marker) and `plan-alm:1.completeness` (completeness check). Both are tagged `progress` in §6.1 — defensible but worth a second look.
+- **Does `intent` need a sub-category for plan-alm itself?** plan-alm is the front-door planner; it doesn't have a Phase 0 ALM-plan gate (because it *is* the plan). The closest analogue is `plan-alm:1.deferral` (handle `.alm-deferred` marker) and `plan-alm:1.completeness` (completeness check). Both are tagged `progress` in §6.1 — defensible but worth a second look.
- **Should `pause` gates be allowed to auto-resume?** Currently the lint rule would flag any tooling that auto-responds. But if PP Pipelines exposes a polling endpoint that detects approval state, a deterministic auto-resume becomes possible. Worth a future rule extension.
- **Telemetry on gate cancellation.** A gate that's cancelled 80% of the time is asking the wrong question. Out of scope for v2; worth instrumenting once §5 lint lands.
- **Multi-prompt gates.** Some entries in §6 cover multiple `AskUserQuestion` calls under one marker (e.g., `setup-solution:5.5*` is one logical gate but renders three multiSelect prompts). The lint rule says one marker can cover multiple calls if the catalog row documents it. Worth a more precise rule once we see drift.
diff --git a/plugins/power-pages/scripts/lib/refresh-alm-plan-data.js b/plugins/power-pages/scripts/lib/refresh-alm-plan-data.js
index d61719fc8..564aa925f 100644
--- a/plugins/power-pages/scripts/lib/refresh-alm-plan-data.js
+++ b/plugins/power-pages/scripts/lib/refresh-alm-plan-data.js
@@ -36,6 +36,11 @@
// finalize:
// - PLAN_STATUS = "Completed"
//
+// stdout JSON includes `nextStep: { name, skill: string | null } | null` (when ok:true) — the first
+// still-pending checklist step and the slash command that runs it. Execution
+// skills echo this so the user knows the next step to invoke (user-driven
+// sequencing — never auto-fired). null when every step is complete.
+//
// Exit 0 on success (including no-op when planData missing — caller decides).
// Exit 1 on argparse / fatal error.
@@ -70,6 +75,7 @@ const PHASES = new Set([
'import-solution',
'activate-site',
'test-site',
+ 'ensure-pipelines-host',
'finalize',
]);
@@ -81,6 +87,7 @@ function parseArgs(argv) {
render: false,
rendererPath: null,
stageName: null,
+ reconcile: false,
};
for (let i = 0; i < args.length; i++) {
if (args[i] === '--projectRoot' && args[i + 1]) out.projectRoot = args[++i];
@@ -88,6 +95,7 @@ function parseArgs(argv) {
else if (args[i] === '--render') out.render = true;
else if (args[i] === '--rendererPath' && args[i + 1]) out.rendererPath = args[++i];
else if (args[i] === '--stageName' && args[i + 1]) out.stageName = args[++i];
+ else if (args[i] === '--reconcile') out.reconcile = true;
}
return out;
}
@@ -231,10 +239,29 @@ function backfillEnvVarValuesFromSettings(planData, projectRoot) {
// - Skip steps already in a terminal state UNLESS we're setting `failed`
// (a retry that succeeded after a failure is recorded as completed by a
// subsequent invocation; a fresh failure overrides any prior status).
+// Recover the bare target label from a pipeline stage name. setup-pipeline names
+// pipeline stages "Deploy to {targetLabel}" and the deploy marker carries that
+// verbatim (last-deploy.json's stageName = SELECTED_STAGE.name = "Deploy to
+// Staging"), but plan step names ("Deploy via pipeline to Staging", "Activate site
+// in Staging") AND the per-stage object keys (validationRuns/manualImports/
+// activations, which the renderer looks up by the bare label) all use just
+// "Staging". Strip a leading "Deploy to " so the step matcher and the keys line up.
+// Case-preserving + trimmed (callers lowercase if they need a case-insensitive
+// compare); a no-op when the prefix isn't present (a caller already passing the
+// bare label, e.g. test-site --stageName "Staging"). Centralizing this here keeps
+// every stage consumer consistent so the "Deploy to {label}" mismatch can't recur
+// in just one code path.
+function normalizeStageLabel(stage) {
+ if (typeof stage !== 'string') return stage;
+ return stage.replace(/^\s*deploy\s+to\s+/i, '').trim();
+}
+
function setStepStatus(planData, { keyword, stage, status }) {
if (!Array.isArray(planData.steps)) return 0;
if (!keyword) return 0;
- const targetStage = (typeof stage === 'string' && stage.length > 0) ? stage.toLowerCase() : null;
+ const targetStage = (typeof stage === 'string' && stage.length > 0)
+ ? normalizeStageLabel(stage).toLowerCase()
+ : null;
let flipped = 0;
for (const step of planData.steps) {
if (!step || typeof step.name !== 'string') continue;
@@ -319,6 +346,25 @@ function refreshSetupPipeline(planData, projectRoot) {
return planData;
}
+// Host-only refresh from docs/alm/last-host-check.json. Used when the Pipelines
+// host was resolved/provisioned (ensure-pipelines-host) but the pipeline doesn't
+// exist yet — so we update `hostResolution` + drop the NoHost risks WITHOUT
+// flipping the "Setup pipeline" step or touching `pipelineMeta` (those belong to
+// the later setup-pipeline phase). This is what lets a host install that crossed
+// a session boundary still surface in the plan.
+function refreshEnsurePipelinesHost(planData, projectRoot) {
+ const hostCheck = readJson(almPath(projectRoot, 'lastHostCheck'));
+ if (hostCheck) {
+ const next = buildHostResolutionFromCheck(hostCheck);
+ if (next) planData.hostResolution = next;
+ mirrorHostResolutionSnapshot(planData, projectRoot);
+ // Drop the pre-run NoHost / *Unbound* / Platform-Host warnings now that the
+ // host is resolved (same set setup-pipeline clears).
+ planData.risks = dropResolvedRisks(planData.risks, 'setup-pipeline');
+ }
+ return planData;
+}
+
function refreshDeployPipeline(planData, projectRoot) {
// Refresh hostResolution from the most recent host-check (and mirror into
// rawDiscovery.hostResolution if the plan was generated with that envelope).
@@ -413,14 +459,31 @@ function refreshDeployPipeline(planData, projectRoot) {
stage: deployMarker.stageName,
status: failed ? 'failed' : 'completed',
});
+ // The PP deploy flow can activate the site as part of deployment (deploy-pipeline
+ // Phase 7.7), recording the outcome in the marker's `activationStatus`. When the
+ // deploy succeeded AND the marker shows the site was actually activated, complete
+ // the matching "Activate site in {stage}" step too — otherwise computeNextStep
+ // would point the user at /activate-site for work the deploy already did. Gate on
+ // the explicit "Activated" outcome, NOT mere truthiness: deploy-pipeline writes
+ // activationStatus: "Pending" when the user DEFERS activation, which is truthy but
+ // means the Activate step is still REQUIRED. Any non-"Activated" value (Pending,
+ // null, a failure note) leaves the Activate step pending. Testing stays a separate
+ // step (the test-site skill flips it via refreshTestSite).
+ if (!failed && /^activated$/i.test(String(deployMarker.activationStatus || ''))) {
+ setStepStatus(planData, {
+ keyword: /\bactivate\b/i,
+ stage: deployMarker.stageName,
+ status: 'completed',
+ });
+ }
}
return planData;
}
function refreshTestSite(planData, projectRoot, stageName) {
// Stage resolution: explicit --stageName arg wins; falls back to the
- // marker's stageName field (test-site writes it when known, e.g. when
- // plan-alm orchestrates the call); finally falls back to the FIRST target
+ // marker's stageName field (test-site writes it when known, e.g. from the
+ // upstream deploy context); finally falls back to the FIRST target
// stage in planData.stages when planData has only one target. Standalone
// single-stage test-site invocations work without --stageName via the
// last fallback; multi-stage standalone runs need the explicit arg.
@@ -434,6 +497,7 @@ function refreshTestSite(planData, projectRoot, stageName) {
if (targets.length === 1 && targets[0].label) resolvedStage = targets[0].label;
}
if (!resolvedStage) return planData;
+ resolvedStage = normalizeStageLabel(resolvedStage);
planData.validationRuns = planData.validationRuns || {};
planData.validationRuns[resolvedStage] = {
@@ -690,7 +754,7 @@ function refreshImportSolution(planData, projectRoot, stageName) {
// targetEnvironment, importedAt, status, componentResults }. For Manual
// path with multiple targets, the file reflects the MOST RECENT import —
// not a per-stage history. We resolve the stage label from --stageName
- // (passed by plan-alm Phase 7's per-target loop) or by matching
+ // (passed by import-solution's final-phase refresh) or by matching
// docs/alm/last-import.json's targetEnvironment URL against planData.stages[].envUrl.
// The result writes into planData.manualImports[stageName] (parallel to
// validationRuns[stageName]) so reviewers see per-target outcome on the
@@ -713,6 +777,7 @@ function refreshImportSolution(planData, projectRoot, stageName) {
if (hit && hit.label) resolvedStage = hit.label;
}
}
+ if (resolvedStage) resolvedStage = normalizeStageLabel(resolvedStage);
if (!resolvedStage) {
// Defensive — write to a synthetic key so subsequent imports for resolvable
// stages don't clobber it. Caller should pass --stageName explicitly.
@@ -775,6 +840,7 @@ function refreshActivateSite(planData, projectRoot, stageName) {
if (hit && hit.label) resolvedStage = hit.label;
}
}
+ if (resolvedStage) resolvedStage = normalizeStageLabel(resolvedStage);
if (!resolvedStage) {
resolvedStage = `unresolved-${marker.environmentUrl || 'unknown'}`;
}
@@ -854,6 +920,50 @@ function refreshConfigureEnvVariables(planData, projectRoot) {
return planData;
}
+// Map a checklist step name (planData.steps[].name) to the slash command that
+// runs it. Single source of truth for the "what runs next" lookup so the 8 ALM
+// execution skills don't each re-derive it in SKILL.md prose. Matched by keyword
+// because step names carry stage suffixes ("Deploy via pipeline to Staging").
+// `finalize` and any unmatched name return null — there is no user-invocable
+// skill for them.
+const STEP_TO_SKILL = [
+ { test: /\bsetup\s+solution\b/i, skill: '/power-pages:setup-solution' },
+ { test: /\bsetup\s+pipeline\b/i, skill: '/power-pages:setup-pipeline' },
+ { test: /\bconfigure\s+env(?:ironment)?\s+var/i, skill: '/power-pages:configure-env-variables' },
+ { test: /\bexport\b/i, skill: '/power-pages:export-solution' },
+ { test: /\bimport\b/i, skill: '/power-pages:import-solution' },
+ { test: /\bdeploy\b/i, skill: '/power-pages:deploy-pipeline' },
+ { test: /\bactivate\b/i, skill: '/power-pages:activate-site' },
+ { test: /\btest\s+site\b/i, skill: '/power-pages:test-site' },
+];
+
+function mapStepToSkill(stepName) {
+ if (typeof stepName !== 'string') return null;
+ for (const entry of STEP_TO_SKILL) {
+ if (entry.test.test(stepName)) return entry.skill;
+ }
+ return null;
+}
+
+// Compute the next recommended step a user should run: the first steps[] entry
+// that is still pending (not completed/failed/in_progress) and not opted-out
+// (skip !== true). Returns { name, skill } or null when nothing remains. The
+// execution skills echo this after their final-phase refresh so the user is
+// pointed at the next skill — without ever auto-firing it (user-driven
+// sequencing). `skill` is null when the pending step has no user-invocable
+// command (e.g. an internal "Finalize" step), so callers still get the name.
+function computeNextStep(planData) {
+ if (!planData || !Array.isArray(planData.steps)) return null;
+ for (const step of planData.steps) {
+ if (!step || typeof step.name !== 'string') continue;
+ if (step.skip === true) continue;
+ const status = step.status || 'pending';
+ if (status !== 'pending') continue;
+ return { name: step.name, skill: mapStepToSkill(step.name) };
+ }
+ return null;
+}
+
function applyRefresh(planData, phase, projectRoot, stageName) {
switch (phase) {
case 'setup-solution': return refreshSetupSolution(planData, projectRoot);
@@ -864,11 +974,128 @@ function applyRefresh(planData, phase, projectRoot, stageName) {
case 'import-solution': return refreshImportSolution(planData, projectRoot, stageName);
case 'activate-site': return refreshActivateSite(planData, projectRoot, stageName);
case 'test-site': return refreshTestSite(planData, projectRoot, stageName);
+ case 'ensure-pipelines-host': return refreshEnsurePipelinesHost(planData, projectRoot);
case 'finalize': return refreshFinalize(planData);
default: throw new Error('Unknown phase: ' + phase);
}
}
+// Marker key (alm-paths FILE_NAMES) -> the refresh phase that ingests it. Used by
+// the reconcile pass. `lastForceLink` is intentionally absent — there is no
+// force-link refresh phase. `lastPipeline` maps to setup-pipeline, which also
+// ingests lastHostCheck, so a present lastPipeline supersedes the host-only phase.
+const MARKER_TO_PHASE = Object.freeze({
+ lastPipeline: 'setup-pipeline',
+ lastHostCheck: 'ensure-pipelines-host',
+ lastDeploy: 'deploy-pipeline',
+ lastExport: 'export-solution',
+ lastImport: 'import-solution',
+ lastActivate: 'activate-site',
+ lastTestSite: 'test-site',
+ // lastEnvVars resolved dynamically (configure-env-variables vs setup-solution).
+});
+
+// Returns the mtime (ms) of a file, or 0 if it doesn't exist / can't be stat'd.
+function mtimeMs(filePath) {
+ try {
+ return fs.statSync(filePath).mtimeMs;
+ } catch {
+ return 0;
+ }
+}
+
+// Reconcile: the enforcement backstop. Scans the ALM marker files and, for each
+// one that is NEWER than docs/.alm-plan-data.json (i.e. written by a skill whose
+// refresh step was skipped), applies the corresponding phase refresh against a
+// single loaded planData, writes once, and renders once. Idempotent — a marker
+// the plan already reflects (plan newer than marker) is skipped, so the steady
+// state is a cheap no-op. Honors the .alm-deferred opt-out and soft-no-ops when
+// there is no plan. Returns { ok, reconciled:[phases healed], failed:[{phase,error}],
+// rendered, nextStep } — `failed` is non-empty when a phase's refresh threw (e.g. a
+// marker schema the refresh can't parse); the reconcile still heals the other phases.
+function reconcile({ projectRoot, render, rendererPath }) {
+ if (!projectRoot) throw new Error('--projectRoot is required');
+ const dataPath = path.join(projectRoot, 'docs', '.alm-plan-data.json');
+ const htmlPath = path.join(projectRoot, 'docs', 'alm-plan.html');
+
+ // Respect the project-level ALM opt-out. nextStep is null on these early paths
+ // (there's nothing to guide toward), kept on the return for a stable contract so
+ // callers never have to special-case a missing property.
+ if (fs.existsSync(path.join(projectRoot, '.alm-deferred'))) {
+ return { ok: true, reconciled: [], failed: [], rendered: false, nextStep: null, reason: 'deferred' };
+ }
+ if (!fs.existsSync(dataPath)) {
+ return { ok: false, reconciled: [], failed: [], rendered: false, nextStep: null, reason: 'no-plan' };
+ }
+
+ const planMtime = mtimeMs(dataPath);
+
+ // Decide the env-var marker's phase: configure-env-variables when a
+ // deployment-settings.json is present (its per-stage values), else setup-solution.
+ const envVarPhase = fs.existsSync(path.join(projectRoot, 'deployment-settings.json'))
+ ? 'configure-env-variables'
+ : 'setup-solution';
+
+ // Collect pending phases (marker newer than the plan), deduped, in a stable order.
+ const pending = new Set();
+ for (const [markerKey, phase] of Object.entries(MARKER_TO_PHASE)) {
+ if (mtimeMs(almPath(projectRoot, markerKey)) > planMtime) pending.add(phase);
+ }
+ // lastHostCheck is covered by setup-pipeline when a pipeline marker is also
+ // pending — drop the host-only phase to avoid a redundant ingest.
+ if (pending.has('setup-pipeline')) pending.delete('ensure-pipelines-host');
+ if (mtimeMs(almPath(projectRoot, 'lastEnvVars')) > planMtime) pending.add(envVarPhase);
+
+ // Load the plan once. We parse it even when nothing is pending so the return
+ // can still carry nextStep — the plan may be current with all markers yet have
+ // unfinished checklist steps, and callers shouldn't lose "what to run next" (or
+ // have to special-case a missing property) just because no heal was needed.
+ let planData;
+ try {
+ planData = JSON.parse(fs.readFileSync(dataPath, 'utf8'));
+ } catch (e) {
+ throw new Error('Could not parse docs/.alm-plan-data.json: ' + e.message);
+ }
+
+ if (pending.size === 0) {
+ return { ok: true, reconciled: [], failed: [], rendered: false, nextStep: computeNextStep(planData) };
+ }
+
+ // Deterministic application order (source schema first, host/pipeline, then
+ // per-stage outcomes). Only the phases actually pending are applied.
+ const ORDER = [
+ 'setup-solution', 'configure-env-variables', 'ensure-pipelines-host',
+ 'setup-pipeline', 'export-solution', 'import-solution',
+ 'deploy-pipeline', 'activate-site', 'test-site',
+ ];
+ const phases = ORDER.filter((p) => pending.has(p));
+
+ // A single phase failing must not abort the reconcile — keep healing the rest —
+ // but the failure must be visible (an empty catch makes a broken marker schema
+ // impossible to diagnose: reconcile would report success while silently skipping
+ // the phase). Collect failures and surface them in the result + on stderr.
+ const reconciled = [];
+ const failed = [];
+ for (const phase of phases) {
+ try {
+ applyRefresh(planData, phase, projectRoot, null);
+ reconciled.push(phase);
+ } catch (e) {
+ failed.push({ phase, error: e.message });
+ process.stderr.write(`[refresh-alm-plan-data] reconcile phase "${phase}" failed: ${e.message}\n`);
+ }
+ }
+ fs.writeFileSync(dataPath, JSON.stringify(planData, null, 2), 'utf8');
+
+ let rendered = false;
+ if (render) {
+ invokeRenderer(findRendererPath(rendererPath), dataPath, htmlPath);
+ rendered = true;
+ }
+
+ return { ok: true, reconciled, failed, rendered, nextStep: computeNextStep(planData) };
+}
+
function findRendererPath(rendererPath) {
if (rendererPath) return rendererPath;
// The helper lives at scripts/lib/; the renderer at skills/plan-alm/scripts/.
@@ -916,15 +1143,20 @@ function refresh({ projectRoot, phase, render, rendererPath, stageName }) {
rendered = true;
}
- return { ok: true, phase, dataPath, htmlPath, rendered };
+ // nextStep: the first still-pending checklist step + its skill command, so
+ // the calling execution skill can tell the user what to run next (user-driven
+ // sequencing — never auto-fired). null when the plan is fully executed.
+ const nextStep = computeNextStep(planData);
+
+ return { ok: true, phase, dataPath, htmlPath, rendered, nextStep };
}
if (require.main === module) {
const args = parseArgs(process.argv);
try {
- const result = refresh(args);
+ const result = args.reconcile ? reconcile(args) : refresh(args);
process.stdout.write(JSON.stringify(result) + '\n');
- process.exit(result.ok ? 0 : 0); // ok:false is a soft no-op (missing planData)
+ process.exit(0); // ok:false (missing planData / deferred) is a soft no-op
} catch (err) {
process.stderr.write('refresh-alm-plan-data: ' + err.message + '\n');
process.exit(1);
@@ -933,10 +1165,15 @@ if (require.main === module) {
module.exports = {
refresh,
+ reconcile,
buildHostResolutionFromCheck,
dropResolvedRisks,
setStepStatus,
backfillEnvVarValuesFromSettings,
extractPerStageValues,
+ computeNextStep,
+ mapStepToSkill,
+ STEP_TO_SKILL,
+ MARKER_TO_PHASE,
PHASES,
};
diff --git a/plugins/power-pages/scripts/tests/plan-alm-q2-guardrails.test.js b/plugins/power-pages/scripts/tests/plan-alm-q2-guardrails.test.js
new file mode 100644
index 000000000..e316d5a1c
--- /dev/null
+++ b/plugins/power-pages/scripts/tests/plan-alm-q2-guardrails.test.js
@@ -0,0 +1,74 @@
+'use strict';
+
+/**
+ * Regression tests guarding the plan-alm Q2 "Strategy Selection" UX.
+ *
+ * Context: a prior run picked Manual export/import because
+ * (a) no option in Q2 was labeled "(Recommended)", and
+ * (b) the comparison/recommendation text was hidden behind option 4 ("Help me decide").
+ * The reader had nothing to anchor on, so it guessed wrong.
+ *
+ * Fix: option 1 carries an explicit "(Recommended ...)" label, option 2 is qualified
+ * as one-off, and the recommendation is surfaced inline in the prompt body. These tests
+ * fail loudly if any of those guardrails regress.
+ *
+ * (Note: an earlier draft also added an "autopilot defaults" policy + a manual-confirm
+ * gate. Those were reverted — a skill can't reliably detect it is running unattended,
+ * and the "(Recommended)" label already anchors the choice in attended and unattended
+ * runs alike. plan-alm is also plan-only, so a wrong Q2 pick produces a reviewable plan,
+ * not an action.)
+ */
+
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('fs');
+const path = require('path');
+
+const SKILL_MD = path.resolve(
+ __dirname,
+ '..',
+ '..',
+ 'skills',
+ 'plan-alm',
+ 'SKILL.md'
+);
+
+function readSkill() {
+ return fs.readFileSync(SKILL_MD, 'utf8');
+}
+
+function extractQ2Section(skill) {
+ const q2Heading = skill.indexOf('### Q2 — Strategy Selection');
+ assert.notEqual(q2Heading, -1, 'Q2 section heading must exist');
+ // Q2 section ends at the next "### " heading (e.g. the PP Pipelines Path section)
+ const nextHeading = skill.indexOf('\n### ', q2Heading + 5);
+ assert.notEqual(nextHeading, -1, 'A section after Q2 must exist');
+ return skill.slice(q2Heading, nextHeading);
+}
+
+test('plan-alm Q2: PP Pipelines option is labeled "(Recommended ...)"', () => {
+ const q2 = extractQ2Section(readSkill());
+ assert.match(
+ q2,
+ /Power Platform Pipelines\s*\(Recommended[^)]*\)/i,
+ 'Q2 option 1 must carry an explicit "(Recommended ...)" marker so the recommendation is in the option label itself, not hidden behind another option.'
+ );
+});
+
+test('plan-alm Q2: Manual option is qualified as "one-off"', () => {
+ const q2 = extractQ2Section(readSkill());
+ assert.match(
+ q2,
+ /Manual export\/import\s*\(one-off[^)]*\)/i,
+ 'Q2 option 2 must include a "(one-off ...)" qualifier so Manual is not treated as equivalent to PP Pipelines for ongoing CI/CD.'
+ );
+});
+
+test('plan-alm Q2: recommendation comparison is shown inline (not only behind option 4)', () => {
+ const q2 = extractQ2Section(readSkill());
+ assert.match(
+ q2,
+ /Recommendation:\s*Power Platform Pipelines/i,
+ 'Q2 must surface the recommendation paragraph inline in the prompt body. Hiding it behind option 4 ("Help me decide") leaves the reader guessing.'
+ );
+});
diff --git a/plugins/power-pages/scripts/tests/refresh-alm-plan-data.test.js b/plugins/power-pages/scripts/tests/refresh-alm-plan-data.test.js
index 265da8564..ab23aecea 100644
--- a/plugins/power-pages/scripts/tests/refresh-alm-plan-data.test.js
+++ b/plugins/power-pages/scripts/tests/refresh-alm-plan-data.test.js
@@ -8,8 +8,11 @@ const os = require('os');
const {
refresh,
+ reconcile,
buildHostResolutionFromCheck,
dropResolvedRisks,
+ computeNextStep,
+ mapStepToSkill,
} = require('../lib/refresh-alm-plan-data');
function makeProject(t) {
@@ -231,6 +234,27 @@ test('refresh test-site populates validationRuns[stage] from docs/alm/last-test-
assert.equal(planData.validationRuns.Staging.summary.total, 12);
});
+test('refresh test-site keys validationRuns by the BARE label even if given a "Deploy to {label}" stage', (t) => {
+ // Hardening (defense against the "Deploy to {label}" mismatch class): if a caller
+ // ever passes the pipeline stage NAME ("Deploy to Staging") instead of the bare
+ // label, the per-stage object key must still be "Staging" so the renderer (which
+ // looks up validationRuns by the bare label from the step name) finds it.
+ const root = makeProject(t);
+ writeJson(path.join(root, 'docs', '.alm-plan-data.json'), {
+ SITE_NAME: 'TestSite',
+ validationRuns: { Staging: null },
+ steps: [{ name: 'Test site in Staging', status: 'pending' }],
+ });
+ writeJson(path.join(root, 'docs', 'alm', 'last-test-site.json'), { runOutcome: 'passed', runAt: '2026-06-16T00:00:00.000Z' });
+
+ refresh({ projectRoot: root, phase: 'test-site', render: false, stageName: 'Deploy to Staging' });
+
+ const planData = readJson(path.join(root, 'docs', '.alm-plan-data.json'));
+ assert.ok(planData.validationRuns.Staging, 'keyed by bare "Staging"');
+ assert.equal(planData.validationRuns['Deploy to Staging'], undefined, 'must NOT key by the "Deploy to" stage name');
+ assert.equal(planData.steps[0].status, 'completed', 'and the matching Test step still flips');
+});
+
test('refresh test-site is a no-op when stageName is omitted', (t) => {
const root = makeProject(t);
writeJson(path.join(root, 'docs', '.alm-plan-data.json'), {
@@ -444,7 +468,7 @@ test('refresh deploy-pipeline ingests batchValidation block from last-deploy.jso
const root = makeProject(t);
writeJson(path.join(root, 'docs', '.alm-plan-data.json'), {
SITE_NAME: 'TestSite',
- STRATEGY: 'pipeline',
+ STRATEGY: 'pp-pipelines',
steps: [{ name: 'Deploy via pipeline to Staging', status: 'in_progress' }],
stages: [{ label: 'Staging', envUrl: 'https://staging.crm.dynamics.com' }],
});
@@ -494,6 +518,66 @@ test('refresh deploy-pipeline ingests batchValidation block from last-deploy.jso
});
});
+test('refresh deploy-pipeline completes the "Activate site" step when the marker evidences activation, but not Test', (t) => {
+ // The PP deploy flow activates the site internally (marker.activationStatus),
+ // so a successful deploy must also complete the matching "Activate site in {stage}"
+ // step — otherwise computeNextStep would redundantly point the user at
+ // /activate-site. Testing remains a separate step (test-site flips it).
+ const root = makeProject(t);
+ writeJson(path.join(root, 'docs', '.alm-plan-data.json'), {
+ SITE_NAME: 'TestSite',
+ STRATEGY: 'pp-pipelines',
+ steps: [
+ { name: 'Deploy via pipeline to Staging', status: 'pending' },
+ { name: 'Activate site in Staging', status: 'pending' },
+ { name: 'Test site in Staging', status: 'pending' },
+ ],
+ stages: [{ label: 'Staging', envUrl: 'https://staging.crm.dynamics.com' }],
+ });
+ writeJson(path.join(root, 'docs', 'alm', 'last-deploy.json'), {
+ stageRunId: 'srun-1', stageName: 'Staging', status: 'Succeeded',
+ deployedAt: '2026-06-16T00:00:00.000Z', activationStatus: 'Activated',
+ siteUrl: 'https://contoso.powerappsportals.com',
+ });
+
+ refresh({ projectRoot: root, phase: 'deploy-pipeline', render: false });
+ const steps = readJson(path.join(root, 'docs', '.alm-plan-data.json')).steps;
+ const byName = (n) => steps.find((s) => s.name === n).status;
+ assert.equal(byName('Deploy via pipeline to Staging'), 'completed');
+ assert.equal(byName('Activate site in Staging'), 'completed', 'deploy activates the site -> Activate step completes too');
+ assert.equal(byName('Test site in Staging'), 'pending', 'Test stays pending — it is the separate test-site step');
+});
+
+test('refresh deploy-pipeline leaves the "Activate site" step pending when activation was not done (null or deferred "Pending")', (t) => {
+ // Only an explicit "Activated" outcome completes the Activate step. A missing
+ // activationStatus (null) OR a deferred activation (deploy-pipeline writes
+ // "Pending" when the user defers) must leave the step pending — the user still
+ // needs to run /activate-site, and nextStep must keep surfacing it.
+ for (const activationStatus of [undefined, null, 'Pending', 'Failed']) {
+ const root = makeProject(t);
+ writeJson(path.join(root, 'docs', '.alm-plan-data.json'), {
+ SITE_NAME: 'TestSite',
+ STRATEGY: 'pp-pipelines',
+ steps: [
+ { name: 'Deploy via pipeline to Staging', status: 'pending' },
+ { name: 'Activate site in Staging', status: 'pending' },
+ ],
+ stages: [{ label: 'Staging', envUrl: 'https://staging.crm.dynamics.com' }],
+ });
+ const marker = { stageRunId: 'srun-1', stageName: 'Staging', status: 'Succeeded', deployedAt: '2026-06-16T00:00:00.000Z' };
+ if (activationStatus !== undefined) marker.activationStatus = activationStatus;
+ writeJson(path.join(root, 'docs', 'alm', 'last-deploy.json'), marker);
+
+ refresh({ projectRoot: root, phase: 'deploy-pipeline', render: false });
+ const steps = readJson(path.join(root, 'docs', '.alm-plan-data.json')).steps;
+ assert.equal(
+ steps.find((s) => s.name === 'Activate site in Staging').status,
+ 'pending',
+ `activationStatus=${JSON.stringify(activationStatus)} must NOT complete the Activate step`,
+ );
+ }
+});
+
test('refresh deploy-pipeline accepts legacy elapsedSecondsApprox name in batchValidation', (t) => {
// Backward-compatibility: legacy SKILL.md prose (pre-v1.x) used
// `elapsedSecondsApprox`. Markers written under that schema still in the
@@ -502,7 +586,7 @@ test('refresh deploy-pipeline accepts legacy elapsedSecondsApprox name in batchV
const root = makeProject(t);
writeJson(path.join(root, 'docs', '.alm-plan-data.json'), {
SITE_NAME: 'TestSite',
- STRATEGY: 'pipeline',
+ STRATEGY: 'pp-pipelines',
steps: [{ name: 'Deploy via pipeline to Staging', status: 'in_progress' }],
stages: [{ label: 'Staging', envUrl: 'https://staging.crm.dynamics.com' }],
});
@@ -539,7 +623,7 @@ test('refresh deploy-pipeline sets batchValidation to null when marker omits the
const root = makeProject(t);
writeJson(path.join(root, 'docs', '.alm-plan-data.json'), {
SITE_NAME: 'TestSite',
- STRATEGY: 'pipeline',
+ STRATEGY: 'pp-pipelines',
steps: [{ name: 'Deploy via pipeline to Staging', status: 'in_progress' }],
stages: [{ label: 'Staging', envUrl: 'https://staging.crm.dynamics.com' }],
});
@@ -1148,6 +1232,53 @@ test('step-sync: deploy-pipeline flips ONLY the matching stage step to completed
'Production deploy step must stay pending — stage filter disambiguates "Deploy" steps');
});
+test('step-sync: deploy-pipeline matches the REAL marker stageName "Deploy to {label}" (not just bare "Staging")', (t) => {
+ // Regression for the stage-name mismatch: setup-pipeline names pipeline stages
+ // "Deploy to {targetLabel}", and deploy-pipeline writes that verbatim as
+ // last-deploy.json's stageName ("Deploy to Staging"). The plan step is
+ // "Deploy via pipeline to Staging", so a raw substring match of the marker's
+ // "deploy to staging" against the step name FAILS and the step would never
+ // flip. setStepStatus must strip the leading "Deploy to " to recover "Staging".
+ const root = makeProject(t);
+ writeJson(path.join(root, 'docs', 'alm', 'last-deploy.json'), {
+ stageRunId: 'sr-real', stageName: 'Deploy to Staging', status: 'Succeeded',
+ deployedAt: '2026-06-16T10:00:00Z', activationStatus: 'Activated',
+ siteUrl: 'https://contoso.powerappsportals.com',
+ });
+ writeJson(path.join(root, 'docs', '.alm-plan-data.json'), {
+ SITE_NAME: 'TestSite',
+ steps: [
+ { name: 'Deploy via pipeline to Staging', status: 'pending' },
+ { name: 'Activate site in Staging', status: 'pending' },
+ { name: 'Test site in Staging', status: 'pending' },
+ { name: 'Deploy via pipeline to Production', status: 'pending' },
+ ],
+ });
+
+ refresh({ projectRoot: root, phase: 'deploy-pipeline', render: false });
+
+ const steps = readJson(path.join(root, 'docs', '.alm-plan-data.json')).steps;
+ const st = (n) => steps.find((s) => s.name === n).status;
+ assert.equal(st('Deploy via pipeline to Staging'), 'completed', 'real "Deploy to Staging" marker must flip the Staging deploy step');
+ assert.equal(st('Activate site in Staging'), 'completed', 'activation evidence + normalized stage must flip the Activate step');
+ assert.equal(st('Test site in Staging'), 'pending', 'Test stays the separate test-site step');
+ assert.equal(st('Deploy via pipeline to Production'), 'pending', 'Production must NOT be touched by a "Deploy to Staging" marker');
+});
+
+test('setStepStatus: exported helper normalizes a "Deploy to {label}" stage to the bare label', () => {
+ const { setStepStatus } = require('../lib/refresh-alm-plan-data');
+ const planData = {
+ steps: [
+ { name: 'Deploy via pipeline to Staging', status: 'pending' },
+ { name: 'Deploy via pipeline to Production', status: 'pending' },
+ ],
+ };
+ const flipped = setStepStatus(planData, { keyword: /\bdeploy\b/i, stage: 'Deploy to Staging', status: 'completed' });
+ assert.equal(flipped, 1);
+ assert.equal(planData.steps[0].status, 'completed');
+ assert.equal(planData.steps[1].status, 'pending');
+});
+
test('step-sync: deploy-pipeline records "failed" status when marker shows failure', (t) => {
const root = makeProject(t);
writeJson(path.join(root, 'docs', 'alm', 'last-deploy.json'), {
@@ -1593,3 +1724,231 @@ test('extractPerStageValues: defensive against null / wrong-type inputs', () =>
});
assert.deepEqual(result, { y: { Staging: 'v' } });
});
+
+// --- nextStep (DRY next-step lookup for user-driven sequencing) ---------------
+
+test('mapStepToSkill: maps each step-name family to its slash command', () => {
+ assert.equal(mapStepToSkill('Setup solution'), '/power-pages:setup-solution');
+ assert.equal(mapStepToSkill('Setup pipeline'), '/power-pages:setup-pipeline');
+ assert.equal(mapStepToSkill('Export solution'), '/power-pages:export-solution');
+ assert.equal(mapStepToSkill('Import to Production'), '/power-pages:import-solution');
+ assert.equal(mapStepToSkill('Deploy via pipeline to Staging'), '/power-pages:deploy-pipeline');
+ assert.equal(mapStepToSkill('Activate site in Staging'), '/power-pages:activate-site');
+ assert.equal(mapStepToSkill('Test site in Production'), '/power-pages:test-site');
+ assert.equal(mapStepToSkill('Configure environment variables'), '/power-pages:configure-env-variables');
+ // No user-invocable skill → null (e.g. an internal finalize step or junk).
+ assert.equal(mapStepToSkill('Finalize'), null);
+ assert.equal(mapStepToSkill(''), null);
+ assert.equal(mapStepToSkill(undefined), null);
+});
+
+test('computeNextStep: returns the first pending step + its skill', () => {
+ const next = computeNextStep({
+ steps: [
+ { name: 'Setup solution', status: 'completed' },
+ { name: 'Setup pipeline', status: 'pending' },
+ { name: 'Deploy via pipeline to Staging', status: 'pending' },
+ ],
+ });
+ assert.deepEqual(next, { name: 'Setup pipeline', skill: '/power-pages:setup-pipeline' });
+});
+
+test('computeNextStep: skips skip:true steps', () => {
+ const next = computeNextStep({
+ steps: [
+ { name: 'Setup solution', status: 'completed' },
+ { name: 'Setup pipeline', status: 'pending', skip: true },
+ { name: 'Deploy via pipeline to Staging', status: 'pending' },
+ ],
+ });
+ assert.deepEqual(next, { name: 'Deploy via pipeline to Staging', skill: '/power-pages:deploy-pipeline' });
+});
+
+test('computeNextStep: skips non-pending statuses (completed/failed/in_progress)', () => {
+ const next = computeNextStep({
+ steps: [
+ { name: 'Setup solution', status: 'completed' },
+ { name: 'Setup pipeline', status: 'failed' },
+ { name: 'Deploy via pipeline to Staging', status: 'in_progress' },
+ { name: 'Activate site in Staging', status: 'pending' },
+ ],
+ });
+ assert.deepEqual(next, { name: 'Activate site in Staging', skill: '/power-pages:activate-site' });
+});
+
+test('computeNextStep: treats a missing status as pending', () => {
+ const next = computeNextStep({ steps: [{ name: 'Setup solution' }] });
+ assert.deepEqual(next, { name: 'Setup solution', skill: '/power-pages:setup-solution' });
+});
+
+test('computeNextStep: returns null when every step is complete or there are no steps', () => {
+ assert.equal(computeNextStep({ steps: [{ name: 'Setup solution', status: 'completed' }] }), null);
+ assert.equal(computeNextStep({ steps: [] }), null);
+ assert.equal(computeNextStep({}), null);
+ assert.equal(computeNextStep(null), null);
+});
+
+test('refresh: surfaces nextStep in its return value after a phase refresh', (t) => {
+ const root = makeProject(t);
+ writeJson(path.join(root, 'docs', '.alm-plan-data.json'), {
+ SITE_NAME: 'TestSite',
+ steps: [
+ { name: 'Setup solution', status: 'pending' },
+ { name: 'Setup pipeline', status: 'pending' },
+ { name: 'Deploy via pipeline to Staging', status: 'pending' },
+ ],
+ });
+ // setup-solution refresh flips "Setup solution" → completed, so nextStep is Setup pipeline.
+ const result = refresh({ projectRoot: root, phase: 'setup-solution', render: false });
+ assert.equal(result.ok, true);
+ assert.deepEqual(result.nextStep, { name: 'Setup pipeline', skill: '/power-pages:setup-pipeline' });
+});
+
+test('refresh: nextStep is null once the final pending step completes', (t) => {
+ const root = makeProject(t);
+ writeJson(path.join(root, 'docs', '.alm-plan-data.json'), {
+ SITE_NAME: 'TestSite',
+ steps: [
+ { name: 'Setup solution', status: 'completed' },
+ { name: 'Setup pipeline', status: 'pending' },
+ ],
+ });
+ const result = refresh({ projectRoot: root, phase: 'setup-pipeline', render: false });
+ assert.equal(result.ok, true);
+ assert.equal(result.nextStep, null, 'all steps complete → nextStep null');
+});
+
+// --- reconcile (the enforcement backstop / auto-heal) ------------------------
+
+// Backdate the plan file so a just-written marker is unambiguously "newer".
+function backdatePlan(root, secondsAgo = 60) {
+ const p = path.join(root, 'docs', '.alm-plan-data.json');
+ const t = (Date.now() - secondsAgo * 1000) / 1000;
+ fs.utimesSync(p, t, t);
+}
+
+test('reconcile: heals a skipped refresh — a newer last-deploy.json is ingested', (t) => {
+ const root = makeProject(t);
+ writeJson(path.join(root, 'docs', '.alm-plan-data.json'), {
+ SITE_NAME: 'T', pipelineMeta: { lastDeploy: null }, steps: [{ name: 'Deploy via pipeline to Staging', status: 'pending' }],
+ stages: [{ label: 'Staging', envUrl: 'https://stg.crm.dynamics.com/', type: 'target' }],
+ });
+ // Marker written AFTER the plan (skill ran but its refresh step was skipped).
+ writeJson(path.join(root, 'docs', 'alm', 'last-deploy.json'), {
+ stageRunId: 'sr1', stageName: 'Staging', status: 'Succeeded', deployedAt: '2026-06-16T00:00:00.000Z',
+ artifactVersion: '1.0.0.2', componentCount: 118,
+ });
+ backdatePlan(root);
+
+ const result = reconcile({ projectRoot: root, render: false });
+ assert.equal(result.ok, true);
+ assert.deepEqual(result.reconciled, ['deploy-pipeline']);
+ // failed[] is part of the contract — empty when every phase heals cleanly.
+ assert.deepEqual(result.failed, []);
+ const planData = readJson(path.join(root, 'docs', '.alm-plan-data.json'));
+ assert.equal(planData.pipelineMeta.lastDeploy.status, 'Succeeded');
+ assert.equal(planData.pipelineMeta.lastDeploy.componentCount, 118);
+});
+
+test('reconcile: failed[] and nextStep are present on EVERY return path (stable contract)', (t) => {
+ // Contract guard (Copilot review on #191): a phase whose refresh throws must NOT
+ // be swallowed silently — it lands in result.failed = [{ phase, error }] while the
+ // other phases still heal, and BOTH failed[] and nextStep are present on the
+ // no-op / deferred / no-plan paths too so callers never special-case a missing
+ // property. (A phase only throws on a genuine marker-schema break — readJson is
+ // defensive — so we assert the contract shape rather than fabricate a throw.)
+ const noPlan = reconcile({ projectRoot: makeProject(t), render: false });
+ assert.ok(Array.isArray(noPlan.failed), 'no-plan path carries failed:[]');
+ assert.ok('nextStep' in noPlan && noPlan.nextStep === null, 'no-plan path carries nextStep:null');
+
+ const deferredRoot = makeProject(t);
+ writeJson(path.join(deferredRoot, 'docs', '.alm-plan-data.json'), { SITE_NAME: 'T' });
+ fs.writeFileSync(path.join(deferredRoot, '.alm-deferred'), 'deferred');
+ const deferred = reconcile({ projectRoot: deferredRoot, render: false });
+ assert.deepEqual(deferred.failed, [], 'deferred path carries failed:[]');
+ assert.ok('nextStep' in deferred && deferred.nextStep === null, 'deferred path carries nextStep:null');
+
+ // Nothing-pending but the plan still has an unfinished step -> reconcile must
+ // compute and return that step (not omit nextStep just because no heal ran).
+ const idleRoot = makeProject(t);
+ writeJson(path.join(idleRoot, 'docs', '.alm-plan-data.json'), {
+ SITE_NAME: 'T',
+ steps: [
+ { name: 'Setup solution', status: 'completed' },
+ { name: 'Setup pipeline', status: 'pending' },
+ ],
+ });
+ const future = (Date.now() + 60 * 1000) / 1000;
+ fs.utimesSync(path.join(idleRoot, 'docs', '.alm-plan-data.json'), future, future);
+ const idle = reconcile({ projectRoot: idleRoot, render: false });
+ assert.deepEqual(idle.failed, [], 'nothing-pending path carries failed:[]');
+ assert.deepEqual(idle.nextStep, { name: 'Setup pipeline', skill: '/power-pages:setup-pipeline' },
+ 'nothing-pending path still surfaces the next unfinished step');
+});
+
+test('reconcile: idempotent no-op when the plan already reflects the markers', (t) => {
+ const root = makeProject(t);
+ writeJson(path.join(root, 'docs', 'alm', 'last-deploy.json'), { stageName: 'Staging', status: 'Succeeded' });
+ // Plan written AFTER the marker -> already reflected -> nothing pending.
+ writeJson(path.join(root, 'docs', '.alm-plan-data.json'), { SITE_NAME: 'T' });
+ const future = (Date.now() + 60 * 1000) / 1000;
+ fs.utimesSync(path.join(root, 'docs', '.alm-plan-data.json'), future, future);
+
+ const result = reconcile({ projectRoot: root, render: false });
+ assert.deepEqual(result.reconciled, []);
+});
+
+test('reconcile: host-only phase when only last-host-check.json is pending (no pipeline yet)', (t) => {
+ const root = makeProject(t);
+ writeJson(path.join(root, 'docs', '.alm-plan-data.json'), {
+ SITE_NAME: 'T',
+ hostResolution: { status: 'NoHost', hostEnvUrl: null },
+ pipelineMeta: null,
+ steps: [{ name: 'Setup pipeline', status: 'pending' }],
+ });
+ writeJson(path.join(root, 'docs', 'alm', 'last-host-check.json'), {
+ resolutionStatus: 'AvailableUsingCustomHost',
+ finalHostEnvUrl: 'https://host.crm.dynamics.com/',
+ hostType: 'custom',
+ });
+ backdatePlan(root);
+
+ const result = reconcile({ projectRoot: root, render: false });
+ assert.deepEqual(result.reconciled, ['ensure-pipelines-host']);
+ const planData = readJson(path.join(root, 'docs', '.alm-plan-data.json'));
+ assert.equal(planData.hostResolution.status, 'AvailableUsingCustomHost');
+ assert.equal(planData.hostResolution.hostEnvUrl, 'https://host.crm.dynamics.com/');
+ assert.equal(planData.pipelineMeta, null, 'host-only phase must NOT fabricate pipelineMeta');
+ assert.equal(planData.steps[0].status, 'pending', 'host-only phase must NOT flip the Setup pipeline step');
+});
+
+test('reconcile: a pending last-pipeline.json supersedes the host-only phase', (t) => {
+ const root = makeProject(t);
+ writeJson(path.join(root, 'docs', '.alm-plan-data.json'), { SITE_NAME: 'T', steps: [{ name: 'Setup pipeline', status: 'pending' }] });
+ writeJson(path.join(root, 'docs', 'alm', 'last-host-check.json'), { resolutionStatus: 'AvailableUsingCustomHost', finalHostEnvUrl: 'https://h/' });
+ writeJson(path.join(root, 'docs', 'alm', 'last-pipeline.json'), { pipelineId: 'p1', pipelineName: 'My Pipeline', stages: [] });
+ backdatePlan(root);
+
+ const result = reconcile({ projectRoot: root, render: false });
+ assert.ok(result.reconciled.includes('setup-pipeline'));
+ assert.ok(!result.reconciled.includes('ensure-pipelines-host'), 'setup-pipeline covers the host — no redundant host-only phase');
+});
+
+test('reconcile: honors the .alm-deferred opt-out (no-op)', (t) => {
+ const root = makeProject(t);
+ writeJson(path.join(root, 'docs', '.alm-plan-data.json'), { SITE_NAME: 'T' });
+ writeJson(path.join(root, 'docs', 'alm', 'last-deploy.json'), { stageName: 'Staging', status: 'Succeeded' });
+ fs.writeFileSync(path.join(root, '.alm-deferred'), 'ni-dev — handled separately');
+ backdatePlan(root);
+
+ const result = reconcile({ projectRoot: root, render: false });
+ assert.equal(result.reconciled.length, 0);
+ assert.equal(result.reason, 'deferred');
+});
+
+test('reconcile: soft no-op when there is no plan', (t) => {
+ const root = makeProject(t);
+ const result = reconcile({ projectRoot: root, render: false });
+ assert.equal(result.ok, false);
+ assert.equal(result.reason, 'no-plan');
+});
diff --git a/plugins/power-pages/skills/activate-site/SKILL.md b/plugins/power-pages/skills/activate-site/SKILL.md
index 7b87201c8..6c388ceee 100644
--- a/plugins/power-pages/skills/activate-site/SKILL.md
+++ b/plugins/power-pages/skills/activate-site/SKILL.md
@@ -269,10 +269,10 @@ For consumers like the rendered ALM plan (Manual path's per-target Activate step
```bash
node -e "require('fs').mkdirSync('docs/alm',{recursive:true})"
-# Determine the stage label this activation was for. plan-alm orchestration
-# passes it via context (e.g. "Staging", "Production"); standalone invocations
-# may leave it null — refreshActivateSite falls back to env-URL matching
-# against planData.stages[].envUrl.
+# Determine the stage label this activation was for. The upstream ALM context
+# (e.g. the user running this after import-solution) supplies it as "Staging"/
+# "Production"; standalone invocations may leave it null — refreshActivateSite
+# falls back to env-URL matching against planData.stages[].envUrl.
node -e "require('fs').writeFileSync('docs/alm/last-activate.json', JSON.stringify({
stageName: <stageNameOrNull>,
siteName: '<siteName>',
@@ -304,9 +304,11 @@ node "${CLAUDE_PLUGIN_ROOT}/scripts/lib/refresh-alm-plan-data.js" \
--render
```
-`{stageNameOrEmpty}` is the Manual-path target stage label (e.g. `Staging`, `Production`) the agent was activating — usually carried in by plan-alm Phase 7 orchestration. Pass an empty string when unknown; `refreshActivateSite` falls back to URL-matching `docs/alm/last-activate.json`'s `environmentUrl` against `planData.stages[].envUrl`, so standalone invocations still get captured.
+`{stageNameOrEmpty}` is the Manual-path target stage label (e.g. `Staging`, `Production`) the agent was activating — stated by the user, or inferred from the target env. Pass an empty string when unknown; `refreshActivateSite` falls back to URL-matching `docs/alm/last-activate.json`'s `environmentUrl` against `planData.stages[].envUrl`, so standalone invocations still get captured.
-The helper reads `docs/alm/last-activate.json`, writes a per-target entry into `planData.activations[stageName]` (siteUrl, status, activatedAt), and re-renders `docs/alm-plan.html` so the matching `Activate site in {stageName}` checklist step shows an `ACTIVATED` badge with the live site URL inline. When `docs/.alm-plan-data.json` is absent (standalone, not via plan-alm), the helper returns `ok:false` as a soft no-op.
+The helper reads `docs/alm/last-activate.json`, writes a per-target entry into `planData.activations[stageName]` (siteUrl, status, activatedAt), and re-renders `docs/alm-plan.html` so the matching `Activate site in {stageName}` checklist step shows an `ACTIVATED` badge with the live site URL inline. When `docs/.alm-plan-data.json` is absent (standalone, not part of an ALM plan), the helper returns `ok:false` as a soft no-op.
+
+**Point the user at the next step (user-driven sequencing).** The helper's stdout JSON includes `nextStep: { name, skill: string | null } | null`. When non-null, branch on `skill`: when `skill` is non-null, tell the user *"Plan updated. Next in your plan: **{nextStep.name}** → run `{nextStep.skill}` when you're ready."*; when `skill` is `null` (an internal step such as Finalize, no user command), name the step only — *"Plan updated. Next in your plan: **{nextStep.name}**."* — and never print `run null`. When `null` or the helper returned `ok:false`, say nothing about a next step. **Never auto-invoke the next skill** — the user drives execution.
#### 5.3 Suggest Next Steps
diff --git a/plugins/power-pages/skills/configure-env-variables/SKILL.md b/plugins/power-pages/skills/configure-env-variables/SKILL.md
index e355add2b..81a577967 100644
--- a/plugins/power-pages/skills/configure-env-variables/SKILL.md
+++ b/plugins/power-pages/skills/configure-env-variables/SKILL.md
@@ -80,7 +80,7 @@ The helper returns JSON with `{ exists, deferred, stale, staleness: { reason, de
|---|---|---|
| Run `/power-pages:plan-alm` first? | ALM plan gate | Yes — run /power-pages:plan-alm now (Recommended), Continue without a plan (advanced — I know what I'm doing), Cancel |
-- **Yes (Recommended)** → invoke `/power-pages:plan-alm`. plan-alm's Phase 7 dispatches back into this skill at the appropriate stage with the pre-classified `siteSettings` already passed via `docs/alm/alm-plan-context.json`.
+- **Yes (Recommended)** → invoke `/power-pages:plan-alm`. It builds the plan and returns — `plan-alm` is a planner and does not deploy. This skill then re-runs the Phase 0 check (now `exists:true`) and proceeds to Phase 1, picking up the pre-classified `siteSettings` from `docs/alm/alm-plan-context.json`.
- **Continue without a plan** → set `BYPASSED_PLAN_GATE = true` and proceed to Phase 1.
- **Cancel** → exit cleanly.
@@ -482,6 +482,19 @@ Next steps:
Follow the skill tracking instructions in the reference to record this skill's usage. Use `--skillName "ConfigureEnvVariables"`.
+**7.5b Refresh the ALM plan (if one exists):**
+
+```bash
+node "${CLAUDE_PLUGIN_ROOT}/scripts/lib/refresh-alm-plan-data.js" \
+ --projectRoot "." \
+ --phase configure-env-variables \
+ --render
+```
+
+The helper re-reads `docs/alm/last-env-vars.json` so newly-created definitions appear in `planData.envVars[]`, backfills per-stage values from `deployment-settings.json` into the "Values by Environment" matrix, zeroes `plannedEnvVarCount`, stamps `LAST_SYNC_AT`, and re-renders `docs/alm-plan.html`. When `docs/.alm-plan-data.json` is absent (standalone invocation, not part of an ALM plan), the helper returns `ok:false` as a soft no-op — safe to run unconditionally.
+
+**Point the user at the next step (user-driven sequencing).** The helper's stdout JSON includes `nextStep: { name, skill: string | null } | null`. When non-null, branch on `skill`: when `skill` is non-null, tell the user *"Plan updated. Next in your plan: **{nextStep.name}** → run `{nextStep.skill}` when you're ready."*; when `skill` is `null` (an internal step such as Finalize, no user command), name the step only — *"Plan updated. Next in your plan: **{nextStep.name}**."* — and never print `run null`. When `null` or the helper returned `ok:false`, say nothing about a next step. **Never auto-invoke the next skill** — the user drives execution.
+
## Key Decision Points (Wait for User)
| Phase | Decision | Options |
diff --git a/plugins/power-pages/skills/deploy-pipeline/SKILL.md b/plugins/power-pages/skills/deploy-pipeline/SKILL.md
index 671deda4f..7465cc0c9 100644
--- a/plugins/power-pages/skills/deploy-pipeline/SKILL.md
+++ b/plugins/power-pages/skills/deploy-pipeline/SKILL.md
@@ -83,7 +83,7 @@ The helper returns JSON with `{ exists, stale, staleness: { reason, detail }, ge
|---|---|---|
| Run `/power-pages:plan-alm` first? | ALM plan gate | Yes — run /power-pages:plan-alm now (Recommended), Continue without a plan (advanced — I just want to deploy), Cancel |
-- **Yes (Recommended)** → invoke `/power-pages:plan-alm`. plan-alm's Phase 7 dispatches back into this skill at the appropriate stage.
+- **Yes (Recommended)** → invoke `/power-pages:plan-alm`. It builds the plan and returns — `plan-alm` is a planner and does not deploy. This skill then re-runs the Phase 0 check (now `exists:true`) and proceeds to Phase 1.
- **Continue without a plan** → set `BYPASSED_PLAN_GATE = true` and proceed to Phase 1. The deploy will still work, but env-var per-stage values, activation, and post-deploy validation aren't orchestrated.
- **Cancel** → exit cleanly.
@@ -942,9 +942,11 @@ node "${CLAUDE_PLUGIN_ROOT}/scripts/lib/refresh-alm-plan-data.js" \
--render
```
-The helper reads the `docs/alm/last-deploy.json` you just wrote, ingests it into `planData.pipelineMeta.lastDeploy`, drops any pre-deploy "host not yet provisioned" risks, and re-renders `docs/alm-plan.html` so the Pipelines tab shows the actual run state (status, version, component count, activation, site URL). When `docs/.alm-plan-data.json` is absent (the skill was invoked standalone, not via plan-alm), the helper returns `ok:false` as a soft no-op — safe to run unconditionally.
+The helper reads the `docs/alm/last-deploy.json` you just wrote, ingests it into `planData.pipelineMeta.lastDeploy`, drops any pre-deploy "host not yet provisioned" risks, and re-renders `docs/alm-plan.html` so the Pipelines tab shows the actual run state (status, version, component count, activation, site URL). When `docs/.alm-plan-data.json` is absent (the skill was invoked standalone, not part of an ALM plan), the helper returns `ok:false` as a soft no-op — safe to run unconditionally.
-This step is what makes the rendered plan stay current after a direct `/power-pages:deploy-pipeline` invocation. plan-alm Phase 7 also runs the same refresh as belt-and-suspenders; running it twice is idempotent (same input → same output).
+This step is what keeps the rendered plan current — `plan-alm` is a planner and does not refresh the plan itself, so each execution skill owns its own post-run refresh. Running it more than once is idempotent (same input → same output).
+
+**Point the user at the next step (user-driven sequencing).** The helper's stdout JSON includes `nextStep: { name, skill: string | null } | null`. When non-null, branch on `skill`: when `skill` is non-null, tell the user *"Plan updated. Next in your plan: **{nextStep.name}** → run `{nextStep.skill}` when you're ready."*; when `skill` is `null` (an internal step such as Finalize, no user command), name the step only — *"Plan updated. Next in your plan: **{nextStep.name}**."* — and never print `run null`. (For a multi-stage pipeline this is typically the next stage's deploy, or the next stage's activate/test if those are separate steps.) When `null` (all steps done) or the helper returned `ok:false` (no plan), say nothing about a next step. **Never auto-invoke the next skill** — the user drives execution.
**7.6 Present summary:**
diff --git a/plugins/power-pages/skills/export-solution/SKILL.md b/plugins/power-pages/skills/export-solution/SKILL.md
index 1e53baea9..489796e7d 100644
--- a/plugins/power-pages/skills/export-solution/SKILL.md
+++ b/plugins/power-pages/skills/export-solution/SKILL.md
@@ -73,7 +73,7 @@ The helper returns JSON with `{ exists, deferred, stale, staleness: { reason, de
|---|---|---|
| Run `/power-pages:plan-alm` first? | ALM plan gate | Yes — run /power-pages:plan-alm now (Recommended), Continue without a plan (advanced — I know what I'm doing), Cancel |
-- **Yes (Recommended)** → invoke `/power-pages:plan-alm`. plan-alm's Phase 7 dispatches back into this skill at the appropriate stage.
+- **Yes (Recommended)** → invoke `/power-pages:plan-alm`. It builds the plan and returns — `plan-alm` is a planner and does not deploy. This skill then re-runs the Phase 0 check (now `exists:true`) and proceeds to Phase 1.
- **Continue without a plan** → set `BYPASSED_PLAN_GATE = true` and proceed to Phase 1.
- **Cancel** → exit cleanly.
@@ -377,7 +377,9 @@ node "${CLAUDE_PLUGIN_ROOT}/scripts/lib/refresh-alm-plan-data.js" \
--render
```
-Re-renders `docs/alm-plan.html` so any step-status updates the agent made during this skill (`Export solution` → `status-completed`) flow through. When `docs/.alm-plan-data.json` is absent (standalone invocation, not via plan-alm), the helper returns `ok:false` as a soft no-op — safe to run unconditionally.
+Re-renders `docs/alm-plan.html` so any step-status updates the agent made during this skill (`Export solution` → `status-completed`) flow through. When `docs/.alm-plan-data.json` is absent (standalone invocation, not part of an ALM plan), the helper returns `ok:false` as a soft no-op — safe to run unconditionally.
+
+**Point the user at the next step (user-driven sequencing).** The helper's stdout JSON includes `nextStep: { name, skill: string | null } | null`. When non-null, branch on `skill`: when `skill` is non-null, tell the user *"Plan updated. Next in your plan: **{nextStep.name}** → run `{nextStep.skill}` when you're ready."*; when `skill` is `null` (an internal step such as Finalize, no user command), name the step only — *"Plan updated. Next in your plan: **{nextStep.name}**."* — and never print `run null`. (Typically: review the exported zip, then run `/power-pages:import-solution` for the first target.) When `null` or the helper returned `ok:false`, say nothing about a next step. **Never auto-invoke the next skill** — the user drives execution.
## Key Decision Points (Wait for User)
diff --git a/plugins/power-pages/skills/import-solution/SKILL.md b/plugins/power-pages/skills/import-solution/SKILL.md
index e4bd9eafd..35234ed34 100644
--- a/plugins/power-pages/skills/import-solution/SKILL.md
+++ b/plugins/power-pages/skills/import-solution/SKILL.md
@@ -69,7 +69,7 @@ The helper returns JSON with `{ exists, deferred, stale, staleness: { reason, de
|---|---|---|
| Run `/power-pages:plan-alm` first? | ALM plan gate | Yes — run /power-pages:plan-alm now (Recommended), Continue without a plan (advanced — I know what I'm doing), Cancel |
-- **Yes (Recommended)** → invoke `/power-pages:plan-alm`. plan-alm's Phase 7 dispatches back into this skill at the appropriate stage.
+- **Yes (Recommended)** → invoke `/power-pages:plan-alm`. It builds the plan and returns — `plan-alm` is a planner and does not deploy. This skill then re-runs the Phase 0 check (now `exists:true`) and proceeds to Phase 1.
- **Continue without a plan** → set `BYPASSED_PLAN_GATE = true` and proceed to Phase 1.
- **Cancel** → exit cleanly.
@@ -544,10 +544,12 @@ node "${CLAUDE_PLUGIN_ROOT}/scripts/lib/refresh-alm-plan-data.js" \
--render
```
-`{targetLabel}` is the Manual-path target stage (e.g. `Staging`, `Production`) the just-completed import was for — usually carried in by the orchestrator (plan-alm Phase 7) or derivable from the target env URL. The helper reads `docs/alm/last-import.json`, captures the import outcome (status, version, component count, component failures) into `planData.manualImports[targetLabel]`, and re-renders `docs/alm-plan.html` so the matching `Import to {targetLabel}` checklist step shows an `IMPORTED` / `FAILED` badge with version + component count inline. Subsequent imports to OTHER targets each get their own entry — the renderer surfaces a per-target history rather than overwriting on each call.
+`{targetLabel}` is the Manual-path target stage (e.g. `Staging`, `Production`) the just-completed import was for — the user states it, or it is derivable from the target env URL. The helper reads `docs/alm/last-import.json`, captures the import outcome (status, version, component count, component failures) into `planData.manualImports[targetLabel]`, and re-renders `docs/alm-plan.html` so the matching `Import to {targetLabel}` checklist step shows an `IMPORTED` / `FAILED` badge with version + component count inline. Subsequent imports to OTHER targets each get their own entry — the renderer surfaces a per-target history rather than overwriting on each call.
If `--stageName` is omitted the helper falls back to matching `docs/alm/last-import.json`'s `targetEnvironment` URL against `planData.stages[].envUrl`. When the match fails (rare — usually a stage-label/env-URL mismatch in planData), the import is captured under a synthetic key so it isn't silently lost; pass `--stageName` explicitly to keep the rendered plan clean. When `docs/.alm-plan-data.json` is absent, the helper returns `ok:false` as a soft no-op.
+**Point the user at the next step (user-driven sequencing).** The helper's stdout JSON includes `nextStep: { name, skill: string | null } | null`. When non-null, branch on `skill`: when `skill` is non-null, tell the user *"Plan updated. Next in your plan: **{nextStep.name}** → run `{nextStep.skill}` when you're ready."*; when `skill` is `null` (an internal step such as Finalize, no user command), name the step only — *"Plan updated. Next in your plan: **{nextStep.name}**."* — and never print `run null`. (Typically: import to the next target, or activate the site in this target.) When `null` or the helper returned `ok:false`, say nothing about a next step. **Never auto-invoke the next skill** — the user drives execution.
+
## Key Decision Points (Wait for User)
1. **Phase 1**: Confirm target environment — import is not easily undoable for managed solutions
diff --git a/plugins/power-pages/skills/plan-alm/SKILL.md b/plugins/power-pages/skills/plan-alm/SKILL.md
index 88e5eccc1..c36b2dd1d 100644
--- a/plugins/power-pages/skills/plan-alm/SKILL.md
+++ b/plugins/power-pages/skills/plan-alm/SKILL.md
@@ -3,9 +3,11 @@ name: plan-alm
description: >-
Creates an ALM (Application Lifecycle Management) plan for deploying a Power Pages
site across environments. Gathers your promotion strategy, target environments, and
- approval requirements upfront, generates a visual HTML plan document for review, then
- — after your approval — executes the plan by calling setup-solution, setup-pipeline,
- export-solution, and deploy-pipeline (or import-solution) in sequence.
+ approval requirements upfront, then generates a visual HTML plan document for your
+ review and approval. **plan-alm does not deploy anything itself** — it is a planner.
+ After you approve the plan, run the individual ALM skills (setup-solution,
+ setup-pipeline, deploy-pipeline, or export-solution/import-solution); each detects the
+ approved plan and executes the right step in order, keeping the plan updated as it runs.
Use when asked to: "plan my alm", "set up alm", "create deployment plan",
"plan my deployments", "help me deploy to multiple environments",
"set up promotion strategy", "create cicd plan", "plan site promotion",
@@ -20,13 +22,15 @@ model: opus
# plan-alm
-An 8-phase orchestrator that gathers ALM strategy from the user, generates an HTML deployment plan, gets approval, then executes the plan by calling existing skills in sequence.
+A 4-phase **planner** that gathers ALM strategy from the user, generates an HTML deployment plan, and gets approval. **It does not execute anything** — execution is delegated to the individual ALM skills, which the user runs afterward.
## Overview
-This skill detects the current project state (existing solution, pipeline), asks targeted questions about the desired promotion strategy (Power Platform Pipelines or Manual export/import), generates a visual `docs/alm-plan.html`, gets user approval, and then invokes `setup-solution`, `setup-pipeline` (or `export-solution`), and `deploy-pipeline` (or `import-solution`) in the correct order.
+This skill detects the current project state (existing solution, pipeline), asks targeted questions about the desired promotion strategy (Power Platform Pipelines or Manual export/import), generates a visual `docs/alm-plan.html`, and gets user approval. The four phases are: **Phase 1 — Detect**, **Phase 2 — Gather strategy**, **Phase 3 — Generate plan**, **Phase 4 — Approve & save**.
-**Do NOT create tasks at the start** — strategy is unknown until Phase 2 completes. Create all tasks in Phase 3 once the strategy is determined.
+**plan-alm never deploys.** The plan's `steps[]` array records the **recommended execution sequence**. After approval, the user invokes the individual skills — `setup-solution`, `setup-pipeline` (or `export-solution`), and `deploy-pipeline` (or `import-solution`) — in that order. Each of those skills detects the approved plan via its Phase 0 gate, proceeds without re-nagging, and refreshes the plan on completion. This separation is deliberate: it keeps `plan-alm` safe to run unattended (e.g. under autopilot) because no single answer can trigger an irreversible deployment.
+
+**Do NOT create tasks at the start** — strategy is unknown until Phase 2 completes. Create both tasks in Phase 3 once the strategy is determined.
---
@@ -59,16 +63,22 @@ Steps:
If `deferred === false`, skip this step silently and proceed to step 1.
-1. **Resolve the site identity from the local project.** ALM skills are normally invoked from a site-root directory where `pac pages download-code-site` (or a create-site scaffold followed by a deploy) has written `.powerpages-site/website.yml`. That YAML file is the source of truth for `websiteRecordId` and `siteName`.
+1. **Resolve the site identity from the local project.** `.powerpages-site/website.yml` is the source of truth for `websiteRecordId` and `siteName`, and it is present for **both** Power Pages site types:
+ - **Code / SPA sites** — scaffolded by `/power-pages:create-site` and downloaded with `pac pages download-code-site`. These also have a `powerpages.config.json` and SPA source (`src/`, build output in `dist/`/`build/`).
+ - **Data-model sites (standard and enhanced data model / "EDM")** — downloaded with `pac pages download --modelVersion 1|2`. These have **no** `powerpages.config.json`; instead `.powerpages-site/` holds the config tree (`web-pages/`, `web-templates/`, `content-snippets/`, …) plus a `.powerpages-site/.portalconfig/` manifest pair. There is no local build output.
**Resolution order** (first match wins):
- 1. **`.powerpages-site/website.yml`** (preferred, present for every deployed site) — read with the `Read` tool and extract:
+ 1. **`.powerpages-site/website.yml`** (preferred, present for every downloaded/deployed site) — read with the `Read` tool and extract:
- `id` field → `websiteRecordId`
- `name` field → `siteName` (the file uses short keys; it is `name:`, not `adx_name:`)
- 2. **`powerpages.config.json`** (fallback, used during plugin development from this repo root or for sites scaffolded but not yet deployed) — read `siteName` and `websiteRecordId`.
+ 2. **`powerpages.config.json`** (fallback — code/SPA sites only; used during plugin development from this repo root or for sites scaffolded but not yet deployed) — read `siteName` and `websiteRecordId`.
+
+ **Determine `SITE_TYPE`** (recorded in planData as `siteType`, surfaced in the plan, and used to skip SPA-only assumptions below):
+ - `data-model` when `.powerpages-site/.portalconfig/` exists, **or** `.powerpages-site/website.yml` resolved while no `powerpages.config.json` is present.
+ - `code` when `powerpages.config.json` is present.
- If neither is found, stop with:
- > "No Power Pages site found in the current directory. Run this skill from your site project root (where `.powerpages-site/` exists after `pac pages download-code-site`). If you haven't created the site yet, run `/power-pages:create-site` first."
+ If neither marker is found, stop with:
+ > "No Power Pages site found in the current directory. Run this skill from your site project root — that's where `.powerpages-site/` lives after `pac pages download-code-site` (code/SPA site) or `pac pages download --modelVersion 2` (enhanced data-model site). If you haven't created the site yet, run `/power-pages:create-site` first."
`environmentUrl` is always re-confirmed from `pac env who` in step 4 — it does not need to come from either source.
@@ -96,7 +106,9 @@ Steps:
```bash
node "${CLAUDE_PLUGIN_ROOT}/scripts/lib/verify-alm-prerequisites.js" --envUrl "{DEV_ENV_URL}"
```
- Store `.token` as `DEV_TOKEN` and `.userId` as `userId`. If this fails (auth error), set `DEV_TOKEN = null` and continue — contents discovery will be skipped gracefully.
+ Store `.token` as `DEV_TOKEN` and `.userId` as `userId`.
+
+ **Track plan quality.** Initialize a `PLAN_QUALITY` accumulator to `"complete"` at the start of Phase 1. If this token acquisition fails (auth error), set `DEV_TOKEN = null`, set `PLAN_QUALITY = "degraded"`, and record the cause (e.g. *"dev-environment auth failed — contents/size/host discovery skipped"*) — then continue. Contents discovery is skipped gracefully, but the resulting plan is built on partial inputs; Phase 3 surfaces this as a prominent risk so the user reviews before executing. (There is no execute path to block here — `plan-alm` only plans — but a degraded plan must be visibly flagged.)
7. Discover and classify site settings (if `DEV_TOKEN` is available and `websiteRecordId` is known):
@@ -170,6 +182,8 @@ Steps:
&& mv ./docs/alm/alm-size-estimate.json.tmp ./docs/alm/alm-size-estimate.json
```
When `SOLUTION_DONE = false`, omit `--solutionId`; the estimator's output will include `envVarCountScope: "publisher-prefix"` to signal the wider scope, and the renderer surfaces this caveat in the Env Variables tab so reviewers know the number reflects the tenant view, not a specific solution. `--projectRoot "."` enables the disk cross-check — the estimator walks the local build output (`dist/`, `public-output/`, `build/`, `.output/`) and surfaces `webFilesDiskMeasuredMB`. When that number is much larger than the Dataverse-measured `webFilesAggregateMB`, the estimator flips `truncationSuspected: true` with a warning — file-typed columns whose bytes aren't returned by `$select=content` are the usual cause and the plan should trust the disk number.
+
+> **`SITE_TYPE = "data-model"` (EDM/standard) sites have no build output**, so the disk cross-check finds no `dist/`/`build/` directory and `webFilesDiskMeasuredMB` stays `null` — this is expected, not a problem. Web files for data-model sites live as records under `.powerpages-site/web-files/` and are measured via the Dataverse query, so the size estimate is still valid; there's simply no SPA bundle on disk to cross-check against. Pass `--projectRoot "."` regardless — it's a harmless no-op for these sites.
Then run the decision tree (same tmp-file pattern):
```bash
node "${CLAUDE_PLUGIN_ROOT}/scripts/lib/compute-split-plan.js" \
@@ -187,10 +201,13 @@ Steps:
Report to the user:
```
Estimated size: {totalSizeMB} MB — components: {count} — tier: {overall tier}.
+ Tables: {tableCount} — scoped to the site's table permissions ({tableCountScope}).
Decision tree result: {splitStrategy} → {N} solutions recommended.
Asset advisory: {K} files flagged for Azure Blob externalization.
```
+ > **Table count is site-referenced, not publisher-prefix.** The estimator scopes custom tables to the tables the site actually references (its table permissions + datamodel manifest), so a shared/default publisher (`new_`) no longer inflates the count. `tableCountScope` reports how it was scoped: `site-referenced` (table permissions), `manifest-only`, or `unavailable` (no local `.powerpages-site/` signal — table count is 0, never an env-wide dump). When `unavailable`, note that the table-based split signal was skipped. The estimate command already passes `--projectRoot "."`, which supplies the local table permissions.
+
10b. **Enumerate environment variable definitions** (runs whenever `DEV_TOKEN` is available — the size estimator gives a count but not per-variable metadata).
The renderer's Env Variables tab needs schema name, type, default value, and bound site setting per definition. Without this step, the tab can only show a count-summary note while the size signal and the warning quote a number — three views that don't fully agree. Running this query produces the row-level data so the table renders properly.
@@ -313,6 +330,8 @@ Steps:
Ask questions in sequence. **Solution is always Q1** — it is the prerequisite for all other steps. Branch after Q2 based on promotion strategy selection.
+**Log every major decision.** As each decision is made below (Q1 solution, Q1b split/override, Q2 strategy, Q3 stages/targets, Q4 host, Q5 approval mode, Q5 manual export type), append to a `DECISIONS_LOG` array: `{ field, value, source }` where `source = "default"` when the recommended/auto value was accepted without an active change, or `"explicit"` when the user picked a non-default option. Phase 4 renders a **"Decisions defaulted (please review)"** section from this log so a reviewer can see at a glance which choices were defaults vs. deliberate picks (closes the *"I never agreed to managed export"* gap). This adds no new prompts — it only records what the existing prompts produced.
+
### Q1 — Solution Setup (always asked first)
**If `SOLUTION_DONE = true`** (manifest found in Phase 1):
@@ -404,22 +423,28 @@ Options:
### Q2 — Strategy Selection (always asked)
<!-- gate: plan-alm:2.q2-strategy | category=plan | cancel-leaves=nothing -->
-> 🚦 **Gate (plan · plan-alm:2.q2-strategy):** Pick promotion strategy — PP Pipelines, manual export/import, existing pipeline, or help-me-decide. Branches the rest of the plan.
+> 🚦 **Gate (plan · plan-alm:2.q2-strategy):** Pick promotion strategy — PP Pipelines (Recommended), manual export/import, existing pipeline, or help-me-decide. Branches the rest of the plan.
+
+**Recommendation prelude (shown inline in the prompt body).** Before listing the options, surface the recommendation and any state that affects it, so the user sees it up front instead of having to drill into option 4:
+
+> **Recommendation: Power Platform Pipelines for ongoing CI/CD** — automated promotion, approval gates, and deployment history in one place. Manual export/import is intended for **one-off migrations** only; repeating it for every change loses the audit trail and silently allows version-skew bugs.
+>
+> *(Conditional, append when `HOST_RESOLUTION.resolutionStatus` ∈ {`AvailableUsingCustomHost`, `AvailableUsingCustomHostByAdminDefault`, `AvailableUsingPlatformHost`, `AvailableUnboundCustomHost`}):*
+> A pipelines host already exists in your tenant at `{HOST_RESOLUTION.finalHostEnvUrl}` (Pipelines v`{HOST_RESOLUTION.pipelinesSolutionVersion}`). PP Pipelines requires **no new infrastructure** for this project.
Ask via `AskUserQuestion`:
> "How do you want to promote your solution between environments?"
Options:
-1. **Power Platform Pipelines** — Microsoft's native CI/CD, managed deployments, approval gates
-2. **Manual export/import** — export a zip from dev and import directly to each target environment
+1. **Power Platform Pipelines (Recommended for ongoing CI/CD)** — Microsoft's native CI/CD, managed deployments, approval gates
+2. **Manual export/import (one-off migrations only)** — export a zip from dev and import directly to each target environment
3. **I already have a pipeline set up** — run a deployment now
-4. **Help me decide** — show a quick comparison
+4. **Help me decide** — show the full comparison again
-**If option 4 selected:** Explain:
-> "Power Platform Pipelines is recommended for teams and multiple environments — it provides automated promotion, approval gates, and deployment history in one place. Manual export/import is simpler for one-off migrations or when you only need to deploy once. For ongoing CI/CD, choose Power Platform Pipelines."
+Record the pick in `DECISIONS_LOG` (`{ field: "strategy", value, source }`).
-Then re-ask Q2 with only options 1–3.
+**If option 4 selected:** Re-print the recommendation prelude above, then re-ask Q2 with only options 1–3.
**If option 3 selected:** Read `docs/alm/last-pipeline.json`, confirm pipeline name and stages, then skip to Phase 3 (generate plan) with `strategy = pp-pipelines`, `PIPELINE_DONE = true`.
@@ -545,19 +570,9 @@ Options:
1. Managed — for staging/production (cannot edit in target)
2. Unmanaged — for dev-to-dev (editable in target)
-Store as `EXPORT_TYPE`.
+Store as `EXPORT_TYPE`, and log the decision (`{ field: "exportType", value: EXPORT_TYPE, source: "default"|"explicit" }`).
-<!-- gate: plan-alm:2.q6-manual-checkpoint | category=plan | cancel-leaves=nothing -->
-> 🚦 **Gate (plan · plan-alm:2.q6-manual-checkpoint):** Pause between export and import for review, or proceed automatically.
-
-**Q6:** Ask via `AskUserQuestion`:
-> "Do you want a checkpoint pause between export and import for review?"
-
-Options:
-1. Yes — pause after export so I can review the zip before importing
-2. No — proceed automatically
-
-Store as `MANUAL_CHECKPOINT` (`true` or `false`).
+> **No checkpoint preference is collected.** `plan-alm` no longer runs the export/import itself, so the old *"pause between export and import?"* question (which only gated execution) is gone. The plan records the recommended sequence — `export-solution` then `import-solution` per target — and the user reviews the zip between those steps when they run them. A standing note to that effect is added to the plan's risks/steps in Phase 3.
**Q6 (auto-detect, no question):** Same as PP Pipelines Q6 — check for env var definitions.
@@ -565,45 +580,14 @@ Store as `MANUAL_CHECKPOINT` (`true` or `false`).
## Phase 3 — Generate HTML Plan
-**Now create all tasks** — strategy is known.
-
-### Task creation
-
-**For PP Pipelines path**, create these tasks (in order):
+**Now create the two planner tasks** — strategy is known. `plan-alm` is a planner, so it has exactly **two** tasks regardless of path:
| # | Subject | activeForm | Description |
|---|---------|-----------|-------------|
| 1 | Generate ALM plan | Generating ALM plan | Build planData, render docs/alm-plan.html |
-| 2 | Approve ALM plan | Awaiting plan approval | Present inline summary, get user confirmation |
-| 3 | Setup solution | Setting up solution | Invoke setup-solution skill (conditional) |
-| 4 | Setup pipeline | Setting up pipeline | Invoke setup-pipeline skill (conditional) |
-| 5..N | Deploy to {stageName} | Deploying to {stageName} | Invoke deploy-pipeline skill for this stage — one task per target stage |
-| 5..N+1 | Activate site in {stageName} | Activating site in {stageName} | Check activation status; if Pending/null: `pac env select --environment "{stage.targetEnvironmentUrl}"` then invoke activate-site — one task per target stage |
-| 5..N+2 | Test site in {stageName} | Testing site in {stageName} | Invoke /power-pages:test-site against the activated URL; capture pass/fail counts; non-blocking — one task per target stage |
-| N+3 | Finalize | Finalizing | Update HTML status, commit, run skill tracking |
-
-Create one **Deploy to {stageName}** + **Activate site in {stageName}** + **Test site in {stageName}** task triplet for each target stage in `PP_STAGES` (e.g. Staging, Production).
-
-**For Manual path**, create:
-
-| # | Subject | activeForm | Description |
-|---|---------|-----------|-------------|
-| 1 | Generate ALM plan | Generating ALM plan | Build planData, render docs/alm-plan.html |
-| 2 | Approve ALM plan | Awaiting plan approval | Present inline summary, get user confirmation |
-| 3 | Setup solution | Setting up solution | Invoke setup-solution skill (conditional) |
-| 4 | Export solution | Exporting solution | Invoke export-solution skill |
-| 5..N | Import to {targetLabel} | Importing solution | Switch PAC CLI context, invoke import-solution (one task per target) |
-| N+1 | Activate site in {targetLabel} | Activating site | Check activation status, invoke activate-site if not yet provisioned (one task per target, optional) |
-| N+2 | Finalize | Finalizing | Update HTML status, commit, run skill tracking |
-
-If `SOLUTION_DONE = true`, add `(will skip — already set up)` to the setup-solution task description.
-If `PIPELINE_DONE = true` (PP path), add `(will skip — already set up)` to the setup-pipeline task description.
-
-**Activation steps (PP path):** Create a separate **"Activate site in {stageName}"** task for every target stage. After each `deploy-pipeline` invocation succeeds, the activation task for that stage runs immediately — do not wait until all stages are deployed. The planData `steps` array must include one `"Deploy to {stageName}"` + one `"Activate site in {stageName}"` + one `"Test site in {stageName}"` triplet per target stage. Activation and testing happen after every stage deployment — not just Production.
+| 2 | Approve & save ALM plan | Awaiting plan approval | Present inline summary, capture approver, save (approved or draft) |
-**Test steps (PP path):** Create a separate **"Test site in {stageName}"** task for every target stage. After each activation completes (or is skipped), the test task runs immediately and is **non-blocking** — `test-site` writes `docs/alm/last-test-site.json`, plan-alm ingests it into `validationRuns[stageName]`, and the rendered HTML's **Validation** tab gets a per-stage sub-tab with categorized findings. Failures do not abort the plan.
-
-**Activation steps (Manual path):** For the Manual path, create one "Activate site in {targetLabel}" task per target environment. These run after the corresponding import completes. The Manual path does not include automatic test-site invocations — site testing is left to the user after manual deployment.
+> **Do not create Setup/Deploy/Activate/Test/Import/Finalize tasks.** Those are *execution* steps performed by the individual ALM skills the user runs after approval — they are not `plan-alm` tasks. The recommended sequence still appears in the plan: the planData `steps[]` array below lists it (all `status: "pending"`), and the rendered HTML's Execution Checklist shows it as the plan of record. Each downstream skill marks its own step complete (via `refresh-alm-plan-data.js`) when the user runs it.
Mark task 1 ("Generate ALM plan") as `in_progress`.
@@ -614,6 +598,7 @@ Build a `planData` object with all gathered strategy inputs:
```json
{
"SITE_NAME": "{siteName}",
+ "siteType": "code | data-model", // from Phase 1 Step 1 — "data-model" for enhanced/standard data-model (EDM) sites (no SPA build output), "code" for SPA sites
"GENERATED_AT": "{ISO timestamp}",
"STRATEGY": "pp-pipelines | manual",
"EXPORT_TYPE": "managed | unmanaged", // PP Pipelines path: always "managed"
@@ -621,7 +606,12 @@ Build a `planData` object with all gathered strategy inputs:
"HAS_ENV_VARS": true | false,
"SOLUTION_DONE": true | false,
"PIPELINE_DONE": true | false,
- "PLAN_STATUS": "Draft",
+ "PLAN_STATUS": "Draft", // set to "Approved" or "Draft" in Phase 4; plan-alm never sets "In Execution"/"Completed"
+ "PLAN_MODE": "draft", // "approved" | "draft" — set in Phase 4. Tooling/downstream skills distinguish an approved plan from a draft. Never "executed" (plan-alm doesn't execute).
+ "PLAN_QUALITY": "complete", // "complete" | "degraded" — degraded when discovery was incomplete (Phase 1 auth failure or the Phase 3 completeness check failed). Surfaced as a prominent risk.
+ "decisionsLog": [ // from DECISIONS_LOG (Phase 2) — drives the Phase 4 "Decisions defaulted" section
+ { "field": "strategy", "value": "pp-pipelines", "source": "explicit" }
+ ],
"LAST_INVOCATION_AT": null,
"APPROVED_BY": "",
"APPROVAL_DATE": "",
@@ -640,6 +630,17 @@ Build a `planData` object with all gathered strategy inputs:
{ "name": "Activate site in Production", "status": "pending", "skip": false },
{ "name": "Test site in Production", "status": "pending", "skip": false }
],
+ // The steps[] above is the PP Pipelines path. For the MANUAL path (STRATEGY = "manual")
+ // emit this shape instead — do NOT include "Setup pipeline"/"Deploy via pipeline":
+ // { "name": "Setup solution", ... },
+ // { "name": "Export solution", ... },
+ // then PER Manual target {targetLabel}:
+ // { "name": "Import to {targetLabel}", ... },
+ // { "name": "Activate site in {targetLabel}", ... }, // import-solution does NOT activate
+ // { "name": "Test site in {targetLabel}", ... }
+ // These names are what refresh-alm-plan-data.js step-sync (export/import/activate/test)
+ // and computeNextStep match on, so the manual checklist and next-step nudges resolve
+ // to /power-pages:export-solution → /power-pages:import-solution → /power-pages:activate-site → /power-pages:test-site.
"validationRuns": {
"Staging": null,
"Production": null
@@ -711,7 +712,7 @@ Build a `planData` object with all gathered strategy inputs:
`plannedEnvVarCount` is computed from `SITE_SETTINGS_DATA` (Phase 1 Step 7): `(SITE_SETTINGS_DATA.promoteToEnvVar?.length || 0) + (SITE_SETTINGS_DATA.credentialNeedsDecision?.length || 0)`. When `SITE_SETTINGS_DATA` is null (Step 7 query failed), set `plannedEnvVarCount = 0`. The renderer reads this alongside `envVars.length` (existing) and `sizeAnalysis.envVarCount.value` (size-estimator's count) to produce a "N today / +M planned" display in the Overview stat card and Size Analysis signal.
-**`validationRuns` block** (PP Pipelines path only — initialize one entry per target stage with value `null`; populated during Phase 7 Step C by ingesting `docs/alm/last-test-site.json` after each stage's test run). The full categorized test report drives the new **Validation** tab in the rendered HTML. Shape per stage:
+**`validationRuns` block** (PP Pipelines path only — initialize one entry per target stage with value `null`). plan-alm leaves these `null` at plan time; they are populated later by **`test-site`'s own final-phase refresh** (`refresh-alm-plan-data.js --phase test-site --stageName {stage}`) when the user runs `test-site` for each stage. The full categorized test report drives the **Validation** tab in the rendered HTML. Shape per stage:
```json
{
@@ -753,9 +754,9 @@ Build a `planData` object with all gathered strategy inputs:
}
```
-The shape is identical to `docs/alm/last-test-site.json` written by `test-site` Phase 6.7a — `plan-alm` reads that file verbatim and assigns it to `validationRuns[stageName]`. The renderer maps `runOutcome` to green / yellow / red Outcome badges and produces a sub-tab per stage on the Validation tab. For the Manual path, omit `validationRuns` from planData.
+The shape is identical to `docs/alm/last-test-site.json` written by `test-site` Phase 6.7a — the refresh helper reads that file verbatim and assigns it to `validationRuns[stageName]` when `test-site` runs. The renderer maps `runOutcome` to green / yellow / red Outcome badges and produces a sub-tab per stage on the Validation tab. For the Manual path, omit `validationRuns` from planData.
-**`pipelineMeta` block** (PP Pipelines path only — read from `docs/alm/last-pipeline.json` and `docs/alm/last-deploy.json` at planData-build time. `null` on fresh plans where no pipeline is configured yet; populated after `setup-pipeline` and refreshed after each `deploy-pipeline` run via the post-deploy re-render in Phase 7). Highlights the pipeline that is actually moving configurations for this project. Shape:
+**`pipelineMeta` block** (PP Pipelines path only — read from `docs/alm/last-pipeline.json` and `docs/alm/last-deploy.json` at planData-build time. `null` on fresh plans where no pipeline is configured yet. Later refreshed by `setup-pipeline`'s and `deploy-pipeline`'s own final-phase refresh when the user runs them). Highlights the pipeline that is actually moving configurations for this project. Shape:
```json
{
@@ -856,6 +857,17 @@ Populate `risks` based on gathered data:
- If `HOST_RESOLUTION.status === "MultipleUnboundCustomHosts"`: `{ type: "info", message: HOST_RESOLUTION.candidates.existingCustomHosts.length + " existing Custom Hosts found in tenant. setup-pipeline will prompt for selection." }`
- If `HOST_RESOLUTION.status === "PlatformHostExistsUnbound"`: `{ type: "info", message: "Tenant has a Platform Host. Reusing it is the lowest-friction option; creating a Custom Host instead provides better governance for separate-tenant or governed scenarios." }`
- If `HOST_RESOLUTION.status === "CannotRedirect"`: `{ type: "warning", message: "CannotRedirect: source env ProjectHostEnvironmentId points at PE but tenant default custom host is set elsewhere. Resolution requires Power Platform admin." }` (Note: Phase 2 Q4 normally blocks plan generation in this state; this is a defensive entry in case the plan is somehow generated.)
+- **Manual path** (always, when `STRATEGY = "manual"`): `{ type: "info", message: "Recommended sequence: run /power-pages:export-solution, review the produced zip, then run /power-pages:import-solution for each target. plan-alm does not perform the export/import itself." }`
+- **Raw-discovery gaps (#9)** — for each of `rawDiscovery.estimate`, `rawDiscovery.splitPlan`, and (PP path) `rawDiscovery.hostResolution` that is `null` at planData-build time: `{ type: "warning", message: "Discovery for {X} did not run; the related size/split/host decisions in this plan are unverified." }` (substitute `{X}` = "solution size estimate" / "split analysis" / "pipeline host resolution").
+
+**Plan completeness check (#10).** Before writing planData, verify the plan rests on real discovery:
+- `sizeAnalysis.totalSizeMB` is non-null,
+- `stages[]` is non-empty,
+- `solutionContents` is populated when a solution is configured (`SOLUTION_DONE = true`).
+
+If any check fails, set `PLAN_QUALITY = "degraded"` and record which check failed. (This is in addition to the Phase 1 Step 6 auth-failure path that already sets degraded.)
+
+**Degraded-plan risk (#8)** — if `PLAN_QUALITY === "degraded"` (from the auth-failure path or the completeness check), prepend to `risks`: `{ type: "warning", message: "⚠ PLAN QUALITY: DEGRADED — discovery was incomplete ({cause}). Review carefully before executing; re-run /power-pages:plan-alm after fixing the cause (commonly dev-environment auth) to regenerate a complete plan." }`. Use `type: "warning"` (the renderer styles it). Substitute `{cause}` from the recorded reason(s).
Write `planData` to `docs/.alm-plan-data.json` (create `docs/` if it doesn't exist).
@@ -867,7 +879,7 @@ node "${CLAUDE_PLUGIN_ROOT}/skills/plan-alm/scripts/render-alm-plan.js" \
--data "<projectRoot>/docs/.alm-plan-data.json"
```
-**Keep `docs/.alm-plan-data.json` on disk.** Phases 5 / 6 / 7 / 8 read this file to refresh `hostResolution`, `pipelineMeta`, `validationRuns`, `risks`, and the plan footer after each run step, then re-render `docs/alm-plan.html` so the rendered tabs reflect actual run state (not the pre-run plan). The file is also what `check-alm-plan.js` reads for the Phase 0 ALM-plan gate in `setup-pipeline` / `deploy-pipeline` / `setup-solution` / `export-solution` / `import-solution` / `configure-env-variables` — deleting it makes every downstream skill think no plan exists. Earlier guidance to delete this file after the initial render was incorrect and caused the Pipelines tab + risks list to stay frozen at pre-run state for the lifetime of the plan.
+**Keep `docs/.alm-plan-data.json` on disk — never delete it.** Two consumers depend on it after `plan-alm` exits: (1) the **execution skills' final-phase refresh** (`refresh-alm-plan-data.js`) reads it to update `hostResolution`, `pipelineMeta`, `validationRuns`, `risks`, `steps[]` status, and the footer as each skill runs, then re-renders `docs/alm-plan.html` so the rendered tabs reflect actual run state (not the pre-run plan); (2) `check-alm-plan.js` reads it for the Phase 0 ALM-plan gate in `setup-pipeline` / `deploy-pipeline` / `setup-solution` / `export-solution` / `import-solution` / `configure-env-variables` — deleting it makes every downstream skill think no plan exists (and fire its no-plan gate). Earlier guidance to delete this file after the initial render was incorrect and caused the Pipelines tab + risks list to stay frozen at pre-run state for the lifetime of the plan.
Write `docs/alm/alm-plan-context.json` (persists so `setup-solution` can read it):
```json
@@ -930,9 +942,11 @@ Mark task 1 as `completed`.
---
-## Phase 4 — Present Plan and Get Approval
+## Phase 4 — Present Plan, Approve & Save
+
+Mark task 2 ("Approve & save ALM plan") as `in_progress`.
-Mark task 2 ("Approve ALM plan") as `in_progress`.
+**`plan-alm` stops here.** This phase saves the plan (approved or draft) and exits. It does **not** invoke `setup-solution`, `setup-pipeline`, `deploy-pipeline`, `export-solution`, or `import-solution`. The user runs those afterward.
Present a concise inline Markdown summary:
@@ -944,377 +958,84 @@ Present a concise inline Markdown summary:
**Approval gates:** {description from PP_APPROVAL_MODE, or "N/A — manual path"}
**Solution export:** {Managed / Unmanaged}
**Pipeline host:** {hostEnvUrl} ({status}) — *(PP Pipelines path only; when `WILL_ENSURE_HOST = true`, render as `Will be ensured during setup-pipeline ({status})` instead)*
+**Plan quality:** {complete / ⚠ DEGRADED — <cause>}
-**Steps that will run:**
-- [ ] Setup solution {(SKIP — already set up) if SOLUTION_DONE}
-- [ ] Setup pipeline {(SKIP — already set up) if PIPELINE_DONE} {(PP path only)}
-- [ ] Export solution {(manual path only)}
-- [ ] Import to {targetLabel} × {N} {(manual path only)}
-- [ ] Deploy via pipeline {(PP path only)}
+**Decisions defaulted (please review):**
+{For each DECISIONS_LOG entry, one line: "- {field}: {value} ({default} or {your pick})". Tag source:"default" as (default) and source:"explicit" as (your pick). If every decision was explicit, write "- (none — every choice was an explicit pick)".}
+
+**Recommended execution sequence (you run these after approval):**
+- [ ] /power-pages:setup-solution {(SKIP — already set up) if SOLUTION_DONE}
+- [ ] /power-pages:setup-pipeline {(SKIP — already set up) if PIPELINE_DONE} {(PP path only)}
+- [ ] /power-pages:export-solution {(manual path only)}
+- [ ] /power-pages:deploy-pipeline — per stage {(PP path only)}
+- [ ] /power-pages:import-solution — per target {(manual path only)}
Full plan written to: docs/alm-plan.html
```
<!-- gate: plan-alm:4.approve | category=plan | cancel-leaves=nothing -->
-> 🚦 **Gate (plan · plan-alm:4.approve):** The capstone — user approves the rendered HTML plan before plan-alm dispatches any downstream skill. Save-for-later writes the plan but exits without execution.
+> 🚦 **Gate (plan · plan-alm:4.approve):** The capstone — user saves the rendered HTML plan. `plan-alm` never executes; this gate only chooses whether the plan is saved **Approved** (ready for the user to run the execution skills) or **Draft**, or sends the user back to revise. No downstream skill is dispatched here.
Ask via `AskUserQuestion`:
-> "Does this ALM plan look correct?"
+> "How would you like to save this ALM plan?"
Options:
-1. **Approve and execute the plan**
-2. **Save plan but execute manually later**
+1. **Save plan — approved, ready to execute** (saves as Approved; you run the execution skills next)
+2. **Save plan as draft** (saves as Draft; re-run plan-alm to approve later)
3. **I want to change something** — go back to questions
- **If option 3:** Re-run Phase 2 (ask which section to change, then re-gather those answers). Regenerate the plan (repeat Phase 3). Re-present for approval.
-- **If option 2:** Capture the approver (see below), stamp `<span id="approved-by">` and `<span id="approval-date">` in the HTML, then update HTML plan footer `plan-status` span to "Approved — Deferred" via `Edit` tool. Commit `docs/alm-plan.html` with message `"Add ALM plan for {siteName} (deferred)"`. Show next steps for manual execution. Mark task 2 as `completed`. Exit the skill.
-- **If option 1:** Capture the approver (see below), stamp the HTML, then update `<span class="plan-status">` to "In Execution" via `Edit` tool. **Also update `docs/.alm-plan-data.json`** — set `PLAN_STATUS: "In Execution"` and write `LAST_INVOCATION_AT: "<ISO timestamp>"` (now). This is the signal `check-alm-plan.js` reads to set `inExecution.status === "active"` so the downstream skills' Phase 0 gates skip silently. `check-alm-plan.js` will refresh `LAST_INVOCATION_AT` on every subsequent invocation that finds the plan in execution, so the chain stays alive even across multi-hour deploys. Mark task 2 as `completed`.
+- **If option 1 (approved):** Capture the approver (see below). Stamp `<span id="approved-by">` / `<span id="approval-date">` in the HTML and set `<span class="plan-status">` text to `Approved` via `Edit`. **Update `docs/.alm-plan-data.json`**: set `PLAN_STATUS: "Approved"` and `PLAN_MODE: "approved"`. Then run the finalize steps below (skill tracking + commit), print the next-steps guidance, mark task 2 `completed`, and **exit**.
+- **If option 2 (draft):** Do **not** capture an approver. Set `<span class="plan-status">` text to `Draft` via `Edit`. Update `docs/.alm-plan-data.json`: `PLAN_STATUS: "Draft"`, `PLAN_MODE: "draft"`. Run the finalize steps below (commit only — skip skill tracking or run it, your choice; commit message `"Add ALM plan for {siteName} (draft)"`), tell the user to re-run `/power-pages:plan-alm` when ready to approve, mark task 2 `completed`, and **exit**.
-**Capturing the approver (both options 1 and 2):**
+**Capturing the approver (option 1 only) — always interactive (#1):**
-Capture the name silently using git, falling back to the OS user:
+Never auto-apply a name silently. First compute a **prefill suggestion** from git / OS user:
```bash
node -e "const {execSync}=require('child_process');let n='';try{n=execSync('git config user.name',{encoding:'utf8'}).trim();}catch{};if(!n){n=process.env.USER||process.env.USERNAME||'';}process.stdout.write(n);"
```
-<!-- not-a-gate: approver-name fallback prompt — data-gathering when git config / env vars empty -->
+<!-- not-a-gate: approver-name capture — data-gathering prompt with git/OS-name prefill; always fires before stamping the audit trail -->
-Store the output as `APPROVER`. If `APPROVER` is empty (no git config, no USER env var), ask via `AskUserQuestion`:
+Then **always** ask via `AskUserQuestion` (even when the suggestion is non-empty) so a human actively confirms the approver recorded in the audit trail:
-> "Who is approving this plan? (needed for the audit trail in docs/alm-plan.html)"
+> "Who is approving this plan? (recorded in the audit trail in docs/alm-plan.html)"
>
-> Options: 1. *{current system user from `whoami`}* · 2. Other (enter name)
+> Options: 1. *{suggested name from git/OS, if any}* · 2. Other (enter name)
-Once `APPROVER` is known, use `Edit` to replace the empty/placeholder value in `docs/alm-plan.html`:
+If the command returned an empty string, present only option 2 (free-text). Store the confirmed result as `APPROVER`, then use `Edit` to replace the spans in `docs/alm-plan.html`:
- Find `<span id="approved-by">` (or `<span id="approved-by"></span>` / `<span id="approved-by">__APPROVED_BY__</span>`) and replace its inner text with `APPROVER`.
- Find `<span id="approval-date">` and replace its inner text with the current ISO timestamp.
Both spans are guaranteed to exist in the template — there is exactly one of each in the "Execution Checklist" tab footer.
----
-
-## Phase 5 — Execute: setup-solution (conditional)
-
-**If `SOLUTION_DONE = true`:**
-Mark the "Setup solution" task as `completed` with description "Skipped — solution already configured". Update the HTML checklist step for "Setup solution" to `status-skipped` via `Edit` tool. Skip to Phase 6.
-
-**If `SOLUTION_DONE = false`:**
-Mark the "Setup solution" task as `in_progress`. Update the HTML checklist step to `status-in-progress` via `Edit` tool.
-
-Invoke the skill:
-```
-/power-pages:setup-solution
-```
-
-After completion: mark the task as `completed`. Update the HTML checklist step to `status-completed` via `Edit` tool.
-
----
-
-## Phase 6 — Execute: setup-pipeline OR export-solution
-
-### PP Pipelines path
-
-**If `PIPELINE_DONE = true`:**
-Mark the "Setup pipeline" task as `completed` with description "Skipped — pipeline already configured". Update HTML checklist step to `status-skipped`. Skip to Phase 7.
-
-**If `PIPELINE_DONE = false`:**
-Mark the "Setup pipeline" task as `in_progress`. Update HTML checklist step to `status-in-progress`.
-
-Invoke the skill:
-```
-/power-pages:setup-pipeline
-```
-
-After completion: mark task as `completed`. Update HTML checklist step to `status-completed`. Then run the post-run plan refresh — this is **not optional**; without it the Pipelines tab stays at "Will be ensured during setup-pipeline" and the risks list keeps surfacing the pre-run NoHost warning even though the host now exists:
-
-```bash
-node "${CLAUDE_PLUGIN_ROOT}/scripts/lib/refresh-alm-plan-data.js" \
- --projectRoot "." \
- --phase setup-pipeline \
- --render
-```
-
-This (a) reads `docs/alm/last-host-check.json` and rewrites `planData.hostResolution` to the post-run state (status flips from `NoHost` to `AvailableUsingCustomHost`, all the `willEnsure*` / `willProvision*` / `chosenEnvUrl` flags clear), (b) reads `docs/alm/last-pipeline.json` and populates `planData.pipelineMeta` with the actual pipeline name + ID + host URL + stages (no `lastDeploy` yet — that fills in after Phase 7 Step A), (c) drops resolved entries from `planData.risks` (NoHost / *Unbound* / Platform-Host warnings), then (d) re-renders `docs/alm-plan.html`. If the helper exits with `ok:false`, surface the reason — the most likely cause is that `docs/.alm-plan-data.json` is missing (Phase 3 must have written it; the file should never be deleted between phases).
-
-### Manual path
-
-Mark the "Export solution" task as `in_progress`. Update HTML checklist step to `status-in-progress`.
-
-Invoke the skill:
-```
-/power-pages:export-solution
-```
-
-After completion: mark task as `completed`. Update HTML checklist step to `status-completed`.
-
-**Refresh the plan after export.** Run the helper (export-solution self-refreshes too — this is belt-and-suspenders):
-
-```bash
-node "${CLAUDE_PLUGIN_ROOT}/scripts/lib/refresh-alm-plan-data.js" \
- --projectRoot "." \
- --phase export-solution \
- --render
-```
-
-The helper re-renders `docs/alm-plan.html` so the Export-step status update is visible to reviewers immediately.
-
-<!-- gate: plan-alm:7.manual-checkpoint | category=progress | cancel-leaves=partial-manifest -->
-> 🚦 **Gate (progress · plan-alm:7.manual-checkpoint):** Manual path pause between export and import — user reviews zip before import proceeds. Defer-now exits cleanly leaving the zip.
-
-**If `MANUAL_CHECKPOINT = true`:** Ask via `AskUserQuestion`:
-> "Export complete. Review the solution zip at `{zipPath}` before importing. Ready to proceed with import?"
-
-Options:
-1. Yes, proceed with import
-2. Stop here — I'll import manually later
-
-If option 2: update HTML plan footer to "Approved — Deferred (paused after export)". Commit `docs/alm-plan.html`. Exit.
-
----
-
-## Phase 7 — Execute: Deploy
-
-### PP Pipelines path
-
-**For each target stage in `PP_STAGES` (e.g. Staging, then Production), run this loop:**
-
-**Step A — Deploy:**
-Mark the "Deploy to {stageName}" task as `in_progress`. Update HTML checklist step to `status-in-progress`.
-
-Invoke the skill:
-```
-/power-pages:deploy-pipeline
-```
-
-**Halt-on-failure check (Step A.1).** After `deploy-pipeline` returns, read `docs/alm/last-deploy.json` to see what actually happened. **Do NOT unconditionally mark the deploy task `completed`** — `deploy-pipeline` can halt at many points (validation failure, Phase 3.6 batch-validation-failed, blocked-attachments cancel, user-cancel at Phase 6.0 consent gate, mid-deploy `AttachmentBlocked`, etc.) and each writes a marker with a status field. Proceeding to Step B / the next stage on a failed deploy wastes time and produces confusing output (activate-site against a target that didn't receive the solution).
-
-```bash
-node -e "try { const d = require('./docs/alm/last-deploy.json'); const gaps = Array.isArray(d.knownGaps) ? d.knownGaps : []; process.stdout.write(JSON.stringify({status: d.status, stageName: d.stageName, knownGaps: gaps, knownGapsCount: gaps.length})) } catch (e) { process.stdout.write(JSON.stringify({status: 'NoMarker', knownGaps: [], knownGapsCount: 0, error: e.message})) }"
-```
-
-The extractor returns `knownGaps: []` when the field is absent or malformed — the agent branches on `knownGapsCount > 0` rather than null/undefined checks, which avoids the ambiguity between "field missing" and "field present but empty array".
-
-Branch on the parsed status. **Check `knownGaps` presence first** because Phase 3.6.5's "deploy succeeded subset" path writes `status: "Succeeded"` alongside a populated `knownGaps[]` — a naive `status === "Succeeded"` branch would miss the gap signal:
-
-- **`knownGaps` is a non-empty array** (regardless of `status`): A subset of solutions deployed (Phase 3.6.5 "deploy succeeded subset" path) but at least one was intentionally skipped. Mark the deploy task `completed-with-gaps` (or `completed` with a note in the rendered plan). Show the user the recorded `knownGaps` and confirm they want to proceed to Step B for the partial deploy. Run the refresh-plan step regardless.
-- **`status === "Succeeded"`** (and no `knownGaps`): Mark deploy task `completed`. Update HTML checklist step to `status-completed`. Proceed to the refresh-plan step below, then Step B.
-- **Any other status** (`"Failed"`, `"ValidationFailed"`, `"Canceled"`, `"PendingApproval"` — user cancelled the approval pause, `"Unknown"` — poll timed out, `"NoMarker"` — the file didn't exist or was unparseable, or any unrecognised value): Mark deploy task `failed`. Update HTML checklist step to `status-failed`. Run the refresh-plan step so the rendered plan shows the failure surface. Then fire the deploy-failure gate below. The catch-all clause covers future deploy-pipeline status values without requiring this skill to be updated in lockstep.
-
-<!-- gate: plan-alm:7.deploy-failure | category=plan | cancel-leaves=nothing -->
-> 🚦 **Gate (plan · plan-alm:7.deploy-failure):** deploy-pipeline halted before completing the deploy to `{stageName}`. Caller decides: retry this stage (re-invoke deploy-pipeline — Dataverse import idempotency makes already-succeeded solutions in a multi-solution loop a no-op), skip this stage and continue to the next (advanced — leaves a stage gap; the rendered plan will show it), or exit the orchestration. Cancel exits the loop without touching subsequent stages.
-
-Use `AskUserQuestion`:
-
- | Question | Header | Options |
- |---|---|---|
- | Deploy to `{stageName}` did not complete (`{status}`). What now? | Deploy failure | Retry this stage, Skip to next stage (advanced — leaves a gap), Exit orchestration |
-
- - **Retry**: re-invoke `/power-pages:deploy-pipeline` for this stage. Re-run the halt-on-failure check on the retry's marker. Loop up to the user's tolerance.
- - **Skip to next stage**: leave the deploy task `failed`, do NOT run Step B / Step C for this stage, continue the outer `PP_STAGES` loop. The rendered plan shows a stage gap; the user owns the consequence.
- - **Exit orchestration**: stop the skill. The rendered plan reflects current state (succeeded stages + the failed one). Re-invoking `/power-pages:plan-alm` later resumes from Phase 7 against the existing plan.
-
-**Refresh the plan after each stage's deploy.** Run the helper (regardless of success/failure — the refresh ingests both outcomes):
-
-```bash
-node "${CLAUDE_PLUGIN_ROOT}/scripts/lib/refresh-alm-plan-data.js" \
- --projectRoot "." \
- --phase deploy-pipeline \
- --render
-```
-
-The helper reads `docs/alm/last-deploy.json`, populates `planData.pipelineMeta.lastDeploy` (status, stageName, deployedAt, artifactVersion, componentCount, activationStatus, siteUrl), and re-renders `docs/alm-plan.html`. The Pipelines tab now shows the actual pipeline name + ACTIVE chip + last-run footer (Succeeded / Failed status + version + component count + stage label). Cheap; runs once per stage in the deploy loop. The `setStepStatus` cross-cutting behavior already maps failure-status markers to `failed` step status so the checklist surfaces what actually happened — Step A.1's halt-on-failure gate just adds the user-facing prompt that was previously missing.
-
-**Step B — Activate (immediately after deploy for this stage, only when Step A succeeded or completed-with-gaps):**
-Mark the "Activate site in {stageName}" task as `in_progress`. Update HTML checklist step to `status-in-progress`.
-
-Read `docs/alm/last-deploy.json` to check whether activation already happened inside `deploy-pipeline`:
-```bash
-node -e "const d=require('./docs/alm/last-deploy.json'); process.stdout.write(JSON.stringify({activationStatus: d.activationStatus, siteUrl: d.siteUrl}))"
-```
-
-- `activationStatus === "Activated"`: site is live. Mark task `completed`. Update checklist step to `status-completed`. Show site URL.
-- `activationStatus === "Pending"` or `null`: activation was deferred or didn't run inside `deploy-pipeline` Phase 7.7. Re-prompt the user.
-
- **Switch PAC CLI to the target environment first** — the activation flow reads the current env from `pac auth who` and looks up the site's record via `pac pages list` in that env. If PAC is still pointing at dev (or at the previous stage's env), activation would target the wrong environment. This mirrors the explicit switch pattern used by `deploy-pipeline` Phase 7.7 (the helper-and-switch-back pair around `check-activation-status.js`); plan-alm's Step C also switches PAC back at the end of the stage loop, but the forward switch BEFORE activate-site must happen here.
-
- ```bash
- pac env select --environment "{stage.targetEnvironmentUrl}"
- ```
-
- Where `{stage.targetEnvironmentUrl}` is the current stage's target environment URL — pulled from `planData.stages[]` (matched by `stage.label === stageName`, then `stage.envUrl`) or equivalently from `docs/alm/last-pipeline.json` `stages[].targetEnvironmentUrl`. Do NOT skip this switch even when only one target stage exists — by the time Step B runs, PAC may already have been switched back to dev by the end of `deploy-pipeline`.
-
- <!-- gate: plan-alm:7.activate-step-b | category=plan | cancel-leaves=nothing -->
- > 🚦 **Gate (plan · plan-alm:7.activate-step-b):** Per-stage post-deploy activation prompt — Step B second-chance when deploy-pipeline Phase 7.7 was skipped or errored. **Fires PER STAGE in the multi-stage execution loop.** Two stages (Staging + Production) where both need activation = two prompts. The "Yes, activate now" answer for Staging does NOT cover Production — each stage's activation is a distinct decision (different URLs, different audiences, different go-live timing). Do NOT batch.
-
- Then ask via `AskUserQuestion`:
-
- > "**{siteName}** was deployed to **{stageName}** successfully. The site is not yet activated (not publicly accessible). Activate it now?"
-
- Options:
- 1. **Yes, activate now** — invoke `/power-pages:activate-site`. After it completes, mark task `completed`, update checklist step to `status-completed`.
- 2. **No, skip for now** — mark task `skipped`, update checklist step to `status-skipped`.
-
- > **Why this gap mattered.** In the happy path, `deploy-pipeline` Phase 7.7 already activated the site (or got an explicit "No") and patched `activationStatus` into `docs/alm/last-deploy.json`. Step B sees `"Activated"` and skips. The gap shows up only when 7.7 was answered "No, I'll activate later" OR when 7.7 was skipped (e.g. activation-status check returned `error`) — in those cases Step B is the second-chance prompt, and it MUST do the PAC switch itself because 7.7's switch-back at the end of Phase 7.7 already returned PAC to dev. For a multi-stage plan this is especially important: on the Production iteration, PAC is back at dev after Staging's Step C; Step B for Production needs an explicit switch to the Production env URL, not Staging's.
-
-**Step C — Test site (immediately after activate for this stage):**
-Mark the "Test site in {stageName}" task as `in_progress`. Update HTML checklist step to `status-in-progress`.
-
-Determine the URL to test:
-- Prefer `siteUrl` from `docs/alm/last-deploy.json` (written by `deploy-pipeline`).
-- If absent or empty, fall back to the URL returned by the most recent `activate-site` invocation for this stage.
-- If both are unavailable (activation was skipped, no URL captured), mark the task `skipped` and set `validationRuns[stageName] = null`. Update checklist step to `status-skipped`.
-
-If a URL is available, invoke the skill (forwarding the URL as the argument):
-```
-/power-pages:test-site --siteUrl {activatedUrl}
-```
-
-When `test-site` completes, ingest its `docs/alm/last-test-site.json` marker into `validationRuns[stageName]` and re-render via the same refresh helper used by other phases:
-
-```bash
-node "${CLAUDE_PLUGIN_ROOT}/scripts/lib/refresh-alm-plan-data.js" \
- --projectRoot "." \
- --phase test-site \
- --stageName "{stageName}" \
- --render
-```
-
-The helper reads `docs/alm/last-test-site.json`, populates `planData.validationRuns[{stageName}]` with the test outcome (runOutcome, summary counts, categories), and re-renders `docs/alm-plan.html` so the Validation tab updates immediately.
-
-`runOutcome` is set by `test-site` itself (see Phase 6.7a in the test-site skill): `"failed"` when any critical/high failure exists, `"passed-with-warnings"` for any non-critical failure or console errors, `"passed"` otherwise. Trust the value as written — do not re-compute.
-
-**Decision rule (non-blocking):** Regardless of `runOutcome`, mark the task `completed` and continue to the next stage. Failures are diagnostic, not gating — the plan does not abort.
-
-Update the HTML checklist step:
-- `runOutcome === "failed"` → `status-warning` (NEW status — yellow).
-- otherwise → `status-completed`.
-
-**Checklist substep rendering** (the renderer handles this automatically once `validationRuns` is populated and the planData re-rendered): every `Test site in {stageName}` step gets an inline substep showing the test-result badge (`PASSED` / `WARNINGS` / `FAILED`), the tested URL, the `pass / fail / skip` summary line, and a "View details &rarr;" link that jumps to the Validation tab. Every `Deploy via pipeline to {stageName}` and `Activate site in {stageName}` step also gets a `Target: <envUrl>` substep so reviewers see the target env without leaving the Execution tab. The renderer derives env URLs from `data.stages[].envUrl` (matched by trailing stage label) — keep stage labels consistent across `data.stages` and `data.steps`.
-
-After handling activation and testing, switch PAC CLI back to the dev environment:
-```bash
-pac env select --environment "{devEnvUrl}"
-```
-
-**Then repeat Step A + B + C for the next stage** (if any).
-
-### Manual path (one import per target environment)
-
-For each entry in `MANUAL_TARGETS`:
-
-1. Mark the "Import to {targetLabel}" task as `in_progress`. Update the corresponding HTML checklist step to `status-in-progress`.
-
-2. Switch the PAC CLI context to the target environment:
- ```bash
- pac env select --environment "{targetEnvUrl}"
- ```
-
-3. Invoke the skill:
- ```
- /power-pages:import-solution
- ```
-
-4. After completion: mark the task as `completed`. Update the HTML checklist step to `status-completed`.
-
-5. **Refresh the plan after the import.** Run the helper (import-solution self-refreshes too — this is belt-and-suspenders):
-
- ```bash
- node "${CLAUDE_PLUGIN_ROOT}/scripts/lib/refresh-alm-plan-data.js" \
- --projectRoot "." \
- --phase import-solution \
- --stageName "{targetLabel}" \
- --render
- ```
-
- `{targetLabel}` is the current iteration's target (e.g. `Staging`, `Production`). The helper reads `docs/alm/last-import.json`, writes a per-target entry into `planData.manualImports[targetLabel]` (status, version, component count, failures), and re-renders `docs/alm-plan.html`. The matching `Import to {targetLabel}` checklist step picks up an `IMPORTED` (or `FAILED`) badge with import details inline — same idiom as the test-site validation substep on PP-path Test steps. Always pass `--stageName` from the per-target loop so the helper doesn't have to fall back to URL matching.
-
-6. **Activate site in {targetLabel}** (optional) — mark the "Activate site in {targetLabel}" task as `in_progress`. Update HTML checklist step to `status-in-progress`.
-
- PAC CLI is already pointing to the target environment from step 2. Run the activation check:
- ```bash
- node "${CLAUDE_PLUGIN_ROOT}/scripts/check-activation-status.js" --projectRoot "."
- ```
-
- - **`activated: true`**: Site is already live. Mark task as `completed`. Update checklist step to `status-completed`.
- - **`activated: false`**: Invoke `/power-pages:activate-site`. After completion, mark task as `completed`. Update checklist step to `status-completed`.
- - **`error`**: Mark task as `skipped`. Note error in summary.
-
-7. **Refresh the plan after activation.** Run the helper (activate-site self-refreshes too — this is belt-and-suspenders):
+**Finalize (both save options):**
+1. **Skill tracking** (option 1; optional for draft):
+ > Reference: `${CLAUDE_PLUGIN_ROOT}/references/skill-tracking-reference.md`
```bash
- node "${CLAUDE_PLUGIN_ROOT}/scripts/lib/refresh-alm-plan-data.js" \
- --projectRoot "." \
- --phase activate-site \
- --render
+ node "${CLAUDE_PLUGIN_ROOT}/scripts/update-skill-tracking.js" \
+ --projectRoot "." --skillName "PlanAlm" --authoringTool "ClaudeCode"
```
-
-After all imports: switch PAC CLI back to the dev environment:
-```bash
-pac env select --environment "{devEnvUrl}"
-```
-
----
-
-## Phase 8 — Finalize
-
-Mark the "Finalize" task as `in_progress`.
-
-### 8.1 Update HTML plan status
-
-Run the post-run plan refresh in `finalize` mode and re-render. This sets `planData.PLAN_STATUS = "Completed"` and produces the final HTML with all post-run state (latest hostResolution, pipelineMeta + lastDeploy, validationRuns, status footer) consistent across every tab:
-
-```bash
-node "${CLAUDE_PLUGIN_ROOT}/scripts/lib/refresh-alm-plan-data.js" \
- --projectRoot "." \
- --phase finalize \
- --render
-```
-
-If you also need to surface a timestamp in the footer (e.g. plan completion time), apply that via `Edit` tool **after** the re-render — the renderer doesn't currently emit a completion timestamp.
-
-### 8.2 Run skill tracking
-
-> Reference: `${CLAUDE_PLUGIN_ROOT}/references/skill-tracking-reference.md`
-
-```bash
-node "${CLAUDE_PLUGIN_ROOT}/scripts/update-skill-tracking.js" \
- --projectRoot "." \
- --skillName "PlanAlm" \
- --authoringTool "ClaudeCode"
-```
-
-### 8.3 Commit
-
-```bash
-git add docs/alm-plan.html && git commit -m "Add ALM plan for {siteName}"
-```
-
-### 8.4 Present final summary
-
-Display a summary:
-
-```
-## ALM Complete: {siteName}
-
-**Strategy used:** {PP Pipelines / Manual export/import}
-**Skills invoked:** {comma-separated list of skills that ran}
-
-**Artifacts created:**
-- docs/alm-plan.html — ALM plan document
-- .solution-manifest.json — Solution configuration {(if newly created)}
-- docs/alm/last-pipeline.json — Pipeline configuration {(PP path only, if newly created)}
-- docs/alm/last-deploy.json — Last deployment record {(PP path only)}
-- {solutionName}_{managed|unmanaged}.zip — Solution package {(manual path only)}
-
-**Site activation:** {
- PP path: "Activation status per stage is in docs/alm/last-deploy.json and each deploy history file."
- Manual path: list each target env and its activation status (Activated / Pending)
-}
-```
-
-Mark the "Finalize" task as `completed`.
+2. **Commit the plan** — pick the commit message for the save option the user chose:
+ - **Option 1 (Approved):**
+ ```bash
+ git add docs/alm-plan.html && git commit -m "Add ALM plan for {siteName}"
+ ```
+ - **Option 2 (Draft):**
+ ```bash
+ git add docs/alm-plan.html && git commit -m "Add ALM plan for {siteName} (draft)"
+ ```
+ `docs/.alm-plan-data.json` stays on disk — it is read by `check-alm-plan.js` for every downstream skill's Phase 0 gate and refreshed by those skills as they run. **Never delete it.**
+
+**Next-steps guidance (option 1 — print to the user, do NOT invoke):**
+
+> "Plan approved and saved. **plan-alm doesn't deploy** — run these next, in order. Each detects this plan and proceeds without re-asking, then updates the plan as it completes:
+> - **PP Pipelines path:** `/power-pages:setup-solution` → `/power-pages:setup-pipeline` → `/power-pages:deploy-pipeline` (once per target stage; the deploy flow activates the site for you — but if you defer activation, run `/power-pages:activate-site`) → `/power-pages:test-site` to validate each stage.
+> - **Manual path:** `/power-pages:setup-solution` → `/power-pages:export-solution` → review the zip → `/power-pages:import-solution` (once per target).
+> Skip any step marked *already set up*. You can re-open the plan any time at `docs/alm-plan.html`."
---
@@ -1323,33 +1044,26 @@ Mark the "Finalize" task as `completed`.
| Task subject | activeForm | Description |
|---|---|---|
| Generate ALM plan | Generating ALM plan | Gather strategy inputs, build planData, render docs/alm-plan.html |
-| Approve ALM plan | Awaiting plan approval | Present inline summary + HTML plan path, get user confirmation |
-| Setup solution | Setting up solution | Invoke setup-solution skill (skip if .solution-manifest.json exists) |
-| Setup pipeline | Setting up pipeline | Invoke setup-pipeline skill — PP Pipelines path only (skip if docs/alm/last-pipeline.json exists). May delegate to ensure-pipelines-host internally to resolve or provision the host environment when `hostResolution.willEnsureDuringExecution` is true; that delegation is transparent to plan-alm and is not a separate top-level task. |
-| Export solution | Exporting solution | Invoke export-solution skill — Manual path only |
-| Deploy to {stageName} | Deploying to {stageName} | Invoke deploy-pipeline skill — PP Pipelines path, one task per target stage |
-| Activate site in {stageName} | Activating site in {stageName} | Check activation status + invoke activate-site immediately after each stage deploys — one task per target stage |
-| Test site in {stageName} | Testing site in {stageName} | Invoke /power-pages:test-site against the activated URL; capture pass/fail counts; non-blocking |
-| Import to {targetEnv} | Importing solution | Switch PAC CLI context, invoke import-solution — Manual path, one task per target |
-| Activate site in {targetEnv} | Activating site | Check activation status + invoke activate-site if needed — Manual path, one task per target |
-| Finalize | Finalizing | Update HTML plan status, commit, run skill tracking, present summary |
+| Approve & save ALM plan | Awaiting plan approval | Present inline summary (incl. defaulted-decisions + plan quality), capture approver, save Approved or Draft, commit, print next-steps |
+
+> `plan-alm` has exactly these two tasks. Setup / pipeline / deploy / export / import / activate / test are performed by the individual ALM skills the user runs **after** approval — they appear in the plan's `steps[]` (the recommended sequence) but are never `plan-alm` tasks.
---
## Key Decision Points (Wait for User)
-1. **Phase 2, Q1**: Solution setup — confirm existing or include `setup-solution` in plan
-2. **Phase 2, Q2**: Promotion strategy — PP Pipelines, Manual, or already set up
-3. **Phase 2, Q3–Q6** (PP path): Stage count, host env, approval gates (managed auto-set)
- **Phase 2, Q3–Q6** (Manual path): Target count, target env URLs, export type, checkpoint pause
-4. **Phase 4**: Plan approval — execute, defer, or revise
-5. **Phase 6, Manual**: Checkpoint pause after export (if Q6 = Yes)
-6. **Phase 7 (delegated)**: Each invoked skill has its own approval gates
+1. **Phase 1**: `.alm-deferred` marker handling; pre-plan completeness check (if a solution exists)
+2. **Phase 2, Q1**: Solution setup — confirm existing or include `setup-solution` in plan
+3. **Phase 2, Q1b**: Split recommendation + override confirmation (if recommended)
+4. **Phase 2, Q2**: Promotion strategy — PP Pipelines, Manual, or already set up
+5. **Phase 2, Q3–Q5** (PP path): Stage count, host env, approval gates (managed auto-set)
+ **Phase 2, Q3–Q5** (Manual path): Target count, target env URLs, export type
+6. **Phase 4**: Save the plan — Approved, Draft, or revise. **This is the only "approval"; no execution follows.**
## Error Handling
-- No `powerpages.config.json`: stop, advise `/power-pages:create-site`
+- No `.powerpages-site/website.yml` **and** no `powerpages.config.json`: stop, advise `/power-pages:create-site` (Phase 1 resolves site identity from either marker — a data-model/EDM site has only `website.yml`, so don't hard-stop on the missing config alone)
- `pac env list` fails: skip ENV_LIST pre-filling; ask for environment URLs manually
- `render-alm-plan.js` fails (non-zero exit): report error, show planData JSON as fallback, ask user whether to proceed
-- Invoked skill fails: report the failure, mark the task as blocked, ask user whether to retry or exit
+- Discovery/auth failure: set `PLAN_QUALITY = "degraded"`, surface a prominent risk, still produce the plan (the user fixes auth and re-runs to regenerate)
- Plan approval = option 3 (change something): re-run Phase 2 fully, then regenerate plan — do not carry over stale answers
diff --git a/plugins/power-pages/skills/plan-alm/scripts/render-alm-plan.js b/plugins/power-pages/skills/plan-alm/scripts/render-alm-plan.js
index d6a36d1f2..33453328b 100644
--- a/plugins/power-pages/skills/plan-alm/scripts/render-alm-plan.js
+++ b/plugins/power-pages/skills/plan-alm/scripts/render-alm-plan.js
@@ -898,7 +898,7 @@ function buildValidationTab(d) {
// Renders the full "Site Validation" tab body. One sub-tab per target stage.
// Each sub-tab shows a summary grid + per-category test cards.
//
- // Data shape (from plan-alm Phase 7 Step C, ingesting test-site's docs/alm/last-test-site.json):
+ // Data shape (populated by test-site's own final-phase refresh, ingesting docs/alm/last-test-site.json):
// data.validationRuns = {
// "<stageName>": null | {
// url, runAt, durationSec, runOutcome,
diff --git a/plugins/power-pages/skills/setup-pipeline/SKILL.md b/plugins/power-pages/skills/setup-pipeline/SKILL.md
index 6adb631ca..710a8810e 100644
--- a/plugins/power-pages/skills/setup-pipeline/SKILL.md
+++ b/plugins/power-pages/skills/setup-pipeline/SKILL.md
@@ -84,7 +84,7 @@ The helper returns JSON with `{ exists, stale, staleness: { reason, detail }, ge
|---|---|---|
| Run `/power-pages:plan-alm` first? | ALM plan gate | Yes — run /power-pages:plan-alm now (Recommended), Continue without a plan (advanced — I know what I'm doing), Cancel |
-- **Yes (Recommended)** → invoke `/power-pages:plan-alm`. plan-alm's Phase 7 dispatches back into this skill at the appropriate stage.
+- **Yes (Recommended)** → invoke `/power-pages:plan-alm`. It builds the plan and returns — `plan-alm` is a planner and does not deploy. This skill then re-runs the Phase 0 check (now `exists:true`) and proceeds to Phase 1.
- **Continue without a plan** → set `BYPASSED_PLAN_GATE = true` and proceed to Phase 1.
- **Cancel** → exit cleanly.
@@ -529,7 +529,9 @@ node "${CLAUDE_PLUGIN_ROOT}/scripts/lib/refresh-alm-plan-data.js" \
--render
```
-The helper reads `docs/alm/last-host-check.json` + `docs/alm/last-pipeline.json`, refreshes `planData.hostResolution` and `planData.pipelineMeta`, drops pre-setup "no host detected" risks, and re-renders `docs/alm-plan.html`. When `docs/.alm-plan-data.json` is absent (standalone invocation, not via plan-alm), the helper returns `ok:false` as a soft no-op — safe to run unconditionally.
+The helper reads `docs/alm/last-host-check.json` + `docs/alm/last-pipeline.json`, refreshes `planData.hostResolution` and `planData.pipelineMeta`, drops pre-setup "no host detected" risks, and re-renders `docs/alm-plan.html`. When `docs/.alm-plan-data.json` is absent (standalone invocation, not part of an ALM plan), the helper returns `ok:false` as a soft no-op — safe to run unconditionally.
+
+**Point the user at the next step (user-driven sequencing).** The helper's stdout JSON includes `nextStep: { name, skill: string | null } | null`. When non-null, branch on `skill`: when `skill` is non-null, tell the user *"Plan updated. Next in your plan: **{nextStep.name}** → run `{nextStep.skill}` when you're ready."*; when `skill` is `null` (an internal step such as Finalize, no user command), name the step only — *"Plan updated. Next in your plan: **{nextStep.name}**."* — and never print `run null`. When `null` (all steps done) or the helper returned `ok:false` (no plan), say nothing about a next step. **Never auto-invoke the next skill** — the user drives execution.
**7.6 Present summary:**
diff --git a/plugins/power-pages/skills/setup-solution/SKILL.md b/plugins/power-pages/skills/setup-solution/SKILL.md
index 0feb106e1..2c44aeb39 100644
--- a/plugins/power-pages/skills/setup-solution/SKILL.md
+++ b/plugins/power-pages/skills/setup-solution/SKILL.md
@@ -69,7 +69,7 @@ The helper returns JSON with `{ exists, deferred, stale, staleness: { reason, de
|---|---|---|
| Run `/power-pages:plan-alm` first? | ALM plan gate | Yes — run /power-pages:plan-alm now (Recommended), Continue without a plan (advanced — I know what I'm doing), Cancel |
-- **Yes (Recommended)** → invoke `/power-pages:plan-alm`. plan-alm's Phase 7 dispatches back into this skill at the appropriate stage.
+- **Yes (Recommended)** → invoke `/power-pages:plan-alm`. It builds the plan and returns — `plan-alm` is a planner and does not deploy. This skill then re-runs the Phase 0 check (now `exists:true`) and proceeds to Phase 1.
- **Continue without a plan** → set `BYPASSED_PLAN_GATE = true` and proceed to Phase 1.
- **Cancel** → exit cleanly.
@@ -884,7 +884,14 @@ node "${CLAUDE_PLUGIN_ROOT}/scripts/lib/refresh-alm-plan-data.js" \
--render
```
-The helper resets `planData.plannedEnvVarCount` to 0 (the planned env vars have either been created or skipped at the user's request) and re-renders `docs/alm-plan.html` so the Overview stat card and Env Variables tab reflect post-setup state. When `docs/.alm-plan-data.json` is absent (standalone invocation, not via plan-alm), the helper returns `ok:false` as a soft no-op — safe to run unconditionally.
+The helper resets `planData.plannedEnvVarCount` to 0 (the planned env vars have either been created or skipped at the user's request) and re-renders `docs/alm-plan.html` so the Overview stat card and Env Variables tab reflect post-setup state. When `docs/.alm-plan-data.json` is absent (standalone invocation, not part of an ALM plan), the helper returns `ok:false` as a soft no-op — safe to run unconditionally.
+
+**Point the user at the next step (user-driven sequencing).** The helper's stdout JSON includes `nextStep: { name, skill: string | null } | null`. `skill` is `null` when the next pending step has no user-invocable command (e.g. an internal "Finalize" step) — so branch on it:
+
+- **`nextStep.skill` is non-null** → "Plan updated. Next in your plan: **{nextStep.name}** → run `{nextStep.skill}` when you're ready."
+- **`nextStep.skill` is `null`** → name the step only, with no command: "Plan updated. Next in your plan: **{nextStep.name}**." Never print `run null`.
+
+When `nextStep` itself is `null` (every planned step is done) or the helper returned `ok:false` (no plan on disk), say nothing about a next step. **Never auto-invoke the next skill** — `plan-alm` is a planner and the user drives execution one skill at a time.
## Key Decision Points (Wait for User)
diff --git a/plugins/power-pages/skills/test-site/SKILL.md b/plugins/power-pages/skills/test-site/SKILL.md
index 478f17de5..c1b3df680 100644
--- a/plugins/power-pages/skills/test-site/SKILL.md
+++ b/plugins/power-pages/skills/test-site/SKILL.md
@@ -730,7 +730,7 @@ EOF
```
or — when invoked from `plan-alm`, the orchestrator may supply the JSON inline. Either way, the marker file location is fixed: `docs/alm/last-test-site.json` (sibling to `docs/alm/last-deploy.json` and `docs/alm/last-pipeline.json`).
-**Always include `stageName` in the marker when known.** The agent learns the stage label from the upstream context — plan-alm Phase 7's per-target loop, `docs/alm/last-deploy.json`'s `stageName`, or an explicit user mention. If the stage cannot be inferred (e.g. test-site invoked standalone against an arbitrary URL), set `stageName` to `null`; the refresh helper has fallback resolution paths but the explicit field is the most reliable signal.
+**Always include `stageName` in the marker when known.** The agent learns the stage label from the upstream context — `docs/alm/last-deploy.json`'s `stageName`, the plan's `stages[]`, or an explicit user mention. If the stage cannot be inferred (e.g. test-site invoked standalone against an arbitrary URL), set `stageName` to `null`; the refresh helper has fallback resolution paths but the explicit field is the most reliable signal.
#### 6.7b Refresh the ALM plan (if one exists)
@@ -746,6 +746,8 @@ node "${CLAUDE_PLUGIN_ROOT}/scripts/lib/refresh-alm-plan-data.js" \
The helper reads `docs/alm/last-test-site.json`, populates `planData.validationRuns[{resolvedStage}]` with the categorized test outcome, and re-renders `docs/alm-plan.html` so the Validation tab updates immediately. When `docs/.alm-plan-data.json` is absent (standalone invocation, no plan in the project), the helper returns `ok:false` as a soft no-op — safe to run unconditionally.
+**Point the user at the next step (user-driven sequencing).** The helper's stdout JSON includes `nextStep: { name, skill: string | null } | null`. When non-null, branch on `skill`: when `skill` is non-null, tell the user *"Plan updated. Next in your plan: **{nextStep.name}** → run `{nextStep.skill}` when you're ready."*; when `skill` is `null` (an internal step such as Finalize, no user command), name the step only — *"Plan updated. Next in your plan: **{nextStep.name}**."* — and never print `run null`. (Typically: deploy/activate/test the next stage.) When `null` (this was the last step) or the helper returned `ok:false`, say nothing about a next step. **Never auto-invoke the next skill** — the user drives execution.
+
#### 6.8 Suggest Next Steps
Based on the test results, suggest relevant skills: