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.
JavaScript claude-code-pluginclaude-code-skillscode-appsgithub-copilot-pluginpower-appspower-pagespower-platform
[Pages][ALM] Enforce ALM plan refresh via PostToolUse reconcile backstop (auto-heal) (#194)
T-Nidc1f1341262c0
diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.jsonindex 119399ebc..207f7a55e 100644--- a/.claude-plugin/marketplace.json+++ b/.claude-plugin/marketplace.json@@ -13,7 +13,7 @@"source": "./plugins/power-pages","description": "Power Pages development and management plugin for Claude Code and GitHub Copilot","category": "development",- "version": "2.4.0",+ "version": "2.5.0","license": "MIT","tags": ["power platform",diff --git a/marketplace.json b/marketplace.jsonindex 119399ebc..207f7a55e 100644--- a/marketplace.json+++ b/marketplace.json@@ -13,7 +13,7 @@"source": "./plugins/power-pages","description": "Power Pages development and management plugin for Claude Code and GitHub Copilot","category": "development",- "version": "2.4.0",+ "version": "2.5.0","license": "MIT","tags": ["power platform",diff --git a/plugins/power-pages/.claude-plugin/plugin.json b/plugins/power-pages/.claude-plugin/plugin.jsonindex 13763c7f2..f3fa3f687 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.4.0",+ "version": "2.5.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/.plugin/plugin.json b/plugins/power-pages/.plugin/plugin.jsonindex 13763c7f2..f3fa3f687 100644--- a/plugins/power-pages/.plugin/plugin.json+++ b/plugins/power-pages/.plugin/plugin.json@@ -1,6 +1,6 @@{"name": "power-pages",- "version": "2.4.0",+ "version": "2.5.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.mdindex 5d7ce90c9..198394c06 100644--- a/plugins/power-pages/AGENTS.md+++ b/plugins/power-pages/AGENTS.md@@ -170,6 +170,8 @@ Skills are defined in `SKILL.md` files with YAML frontmatter (name, description,Hook registration is centralized in `hooks/hooks.json` — a single PostToolUse hook (matcher `Skill`) runs `hooks/run-skill-posttool-validation.js` after every Skill tool call. The runner derives tracked skills directly from `skills/*/SKILL.md` via `scripts/lib/powerpages-hook-utils.js`, looks up an optional `skills/<skill>/scripts/validate*.js` validator for the skill that just completed, and invokes it with the current cwd.+**ALM plan reconcile backstop (auto-heal).** After any **ALM plan skill** completes (`powerpages-hook-utils.js → ALM_PLAN_SKILLS` / `isAlmPlanSkill`) and a `docs/.alm-plan-data.json` exists in the cwd, the runner also `spawnSync`s `refresh-alm-plan-data.js --reconcile --render`. The `refresh-alm-plan-data.js` calls in each SKILL.md are advisory — silently dropped on session fragmentation, manual execution, or oversight — so the reconcile *performs* any refresh whose marker (`docs/alm/last-*.json`) is newer than the plan. This is **best-effort and non-blocking**: it never changes the hook's exit code, honors `.alm-deferred`, and is idempotent. Because it fires on *any* ALM skill (not just the marker's writer), a skip in skill A is healed when the next ALM skill (B) completes. Skills keep their explicit per-phase refresh calls as defense-in-depth + immediate render; the hook is the backstop.+To wire a new skill into validation:1. Write the validator at `skills/<skill>/scripts/validate-<skill>.js` using the `runValidation((cwd) => { ... })` pattern from `scripts/lib/validation-helpers.js`.@@ -198,7 +200,7 @@ Shared lib modules live at `scripts/lib/` and are imported by other scripts via- `scripts/lib/verify-alm-prerequisites.js`: Verifies all prerequisites for ALM skills — PAC CLI installed + authenticated (`pac env who`), Azure CLI installed + logged in, Dataverse API reachable (`WhoAmI`). Args: `--envUrl` (opt, overrides env from PAC CLI), `--require-manifest` (fails if `.solution-manifest.json` not found). Output: `{ envUrl, token, userId, organizationId, tenantId }`. Exit 0 on success, exit 1 on any failure. Used by `setup-solution`, `export-solution`, `import-solution`, `setup-pipeline`, `deploy-pipeline`, `plan-alm`.- `scripts/lib/detect-project-context.js`: Reads Power Pages project context from the project root. The `siteType` discriminator is the **build axis** — code/SPA vs declarative (design-studio) site — NOT the Dataverse data-model axis (a declarative site can be on the standard OR enhanced data model; both download to a `.powerpages-site/` tree). `siteType: "data-model"` is the (compat-named) declarative bucket; a future pass may rename it `"declarative"`. Resolves identity in order: (1) `powerpages.config.json` → `siteType: "code"` (code/SPA sites); (2) `.powerpages-site/` → `siteType: "data-model"` (declarative design-studio sites — standard or enhanced data model — which have **no** `powerpages.config.json`). The **authoritative declarative marker is the `.powerpages-site/.portalconfig/` directory** (only declarative sites have it); `website.yml` is the identity source (`id`→`websiteRecordId`, `name`→`siteName`) but is NOT a reliable declarative signal alone because **both** site types carry it. `environmentUrl: null` for declarative sites (no env URL in the local files — callers re-confirm via `pac env who`). Also reads `.solution-manifest.json` and `.datamodel-manifest.json`. Args: `--projectRoot` (opt). Output: `{ projectRoot, siteType, siteName, websiteRecordId, environmentUrl, solutionManifest, datamodelManifest }`. Exit 0 on success, exit 1 only if neither `powerpages.config.json` nor a `.powerpages-site/` (`.portalconfig/`/`website.yml`) marker is found. Note: `findProjectRoot` (in `validation-helpers.js`) likewise treats a `.powerpages-site/` directory as a project-root marker.- `scripts/lib/alm-paths.js`: Single source of truth for ALM artifact paths. Exports `ALM_DIR` (always `docs/alm`), `FILE_NAMES` (frozen object mapping logical key → filename for all 14 ALM artifacts), `almDir(projectRoot) → path`, `almPath(projectRoot, key) → path`, `ensureAlmDir(projectRoot) → path` (mkdir -p idempotent). Every ALM-only state file (5 plan/decision JSONs + 9 `last-*.json` skill-run markers including `last-export.json`) writes under `<projectRoot>/docs/alm/`. **Always resolve through this helper** — never inline a raw `docs/alm/...` path in a script. Files intentionally NOT moved here (and not in `FILE_NAMES`): `.solution-manifest.json`, `.datamodel-manifest.json`, `.alm-config.json`, `.alm-deferred`, `deployment-settings.json`. Adding a new ALM marker means adding its key + filename to `FILE_NAMES` first; `almPath` throws on unknown keys to catch typos at call-site.-- `scripts/lib/check-alm-plan.js`: Phase 0 gate helper used by every ALM skill to detect (a) whether an ALM plan exists for this project, (b) whether the user has explicitly deferred ALM via the `.alm-deferred` marker, and (c) whether an existing plan is stale (the source solution was modified after the plan was generated). Args: `--projectRoot`, `--envUrl` (opt — required for staleness check), `--token` (opt), `--solutionId` (opt — required for staleness check). Output: `{ exists, deferred, deferral, planPath, htmlPath, stale, staleness: { reason, detail }, generatedAt, planStatus, solution: {...} }`. Without env/solution context the helper does an existence-only check; with them it queries Dataverse for `solutions(solutionId)?$select=modifiedon` and compares against `planData.generatedAt`. Used by `setup-solution`, `setup-pipeline`, `deploy-pipeline`, `export-solution`, `import-solution`, `configure-env-variables`, `ensure-pipelines-host`, `force-link-environment` Phase 0 gates — the "fail closed when no plan" pattern.+- `scripts/lib/check-alm-plan.js`: Phase 0 gate helper used by every ALM skill to detect (a) whether an ALM plan exists for this project, (b) whether the user has explicitly deferred ALM via the `.alm-deferred` marker, and (c) whether an existing plan is stale (the source solution was modified after the plan was generated). Args: `--projectRoot`, `--envUrl` (opt — required for staleness check), `--token` (opt), `--solutionId` (opt — required for staleness check). Output: `{ exists, deferred, deferral, planPath, htmlPath, stale, staleness: { reason, detail }, generatedAt, planStatus, solution: {...} }`. Without env/solution context the helper does an existence-only check; with them it queries Dataverse for `solutions(solutionId)?$select=modifiedon` and compares against `planData.generatedAt`. Used by `setup-solution`, `setup-pipeline`, `deploy-pipeline`, `export-solution`, `import-solution`, `configure-env-variables`, `ensure-pipelines-host`, `force-link-environment` Phase 0 gates — the "fail closed when no plan" pattern. **PLAN_STATUS lifecycle — promotes `Approved` → `In Execution`:** plan-alm is plan-only and leaves the plan `Approved`; this helper performs the `Approved` → `In Execution` transition (and writes the first heartbeat) the **first time an execution skill's Phase 0 runs** — it is the only thing that sets `In Execution`, so without it the heartbeat/active-chain machinery (multi-hour-deploy `stale-heartbeat` reclassification) never engages. Gated on heartbeat-write: read-only callers pass `--no-heartbeat` (plan-alm's own deferral check, audits, tests) and are never promoted. The terminal `In Execution` → `Completed` transition is owned by `refresh-alm-plan-data.js` (completion evaluator).- `scripts/lib/resolve-target-solution.js`: Resolves "which solution should this new Dataverse record land in?" Implements the strict 3-step order from the ALM-aware-by-default principle: (1) explicit `--solutionUniqueName` (or equivalent caller arg) wins; (2) `.solution-manifest.json` in the project root; (3) neither → throw `NoSolutionConfiguredError`. **The module NEVER auto-picks from Dataverse** — interactive prompt UX is the caller's responsibility (catch the error, present an `AskUserQuestion` list, re-invoke with `explicit` populated). Callers that need to confirm the solution still exists in Dataverse can pass `verifyExists: true`; the module then enriches the result with `{ solutionId, version, ismanaged }`. Component-creation scripts must require this helper and pass through `--solutionUniqueName` so records land in the user's solution instead of `Default`.#### Solution Splitting Decision Tree (v1.3.0+)@@ -225,7 +227,7 @@ Shared lib modules live at `scripts/lib/` and are imported by other scripts via- `scripts/lib/link-site-setting-to-env-var.js`: Links an `mspp_sitesetting` record to an `environmentvariabledefinition` via OData PATCH on the v9.0 API (not v9.2). HAR-confirmed: navigation property is `[email protected]`; headers `if-match: *` and `clienthost: Browser` are required (omitting causes 400). Args: `--envUrl`, `--token`, `--siteSettingId`, `--definitionId`, `--schemaName`. Output: `{ ok, verified, siteSettingId, definitionId }`.- `scripts/lib/install-pipelines-app.js`: Installs the Power Platform Pipelines application package on an existing Dataverse env (replaces ensure-pipelines-host Phase 4.B's manual PPAC click-through). Resolution: BAP `applicationPackages` LIST + `/install` POST → 200 sync / 202 + Location poll, with PAC CLI fallback (`pac application install --environment-id ... --application-list msdyn_AppDeploymentAnchor`) on 401/403/5xx. 409 on install POST treated as idempotent (already-installed). Args: `--bapToken`, `--envId`, `--instanceApiUrl` (opt — for verification probe), `--hostToken` (opt), `--no-pac-fallback` (opt), `--correlationId`, `--timeoutSec`, `--apiVersion`, `--bapBase`. Output: `{ status, alreadyInstalled, installPath: 'bap'\|'pac'\|'cached', packageUniqueName, pipelinesSolutionVersion, durationSec, correlationId, pollAttempts, locationHeader, pacFallbackReason }`.- `scripts/lib/discover-env-var-definitions.js`: Enumerates env var definitions matching a publisher prefix and joins each with its bound `mspp_sitesetting` (if any). Used by `plan-alm` Phase 1 Step 10b to populate `planData.envVars[]` with row-level metadata so the rendered plan's Env Variables tab shows schema name, type, default value, and bound site setting per definition (instead of just a count). Args: `--envUrl`, `--publisherPrefix`, `--websiteRecordId`, `--token` (opt). Output: `{ envVars: [{ schemaName, type, defaultValue, siteSetting }], count }`. Degrades gracefully (empty array, exit 0) on auth failure or query errors so the renderer's count-summary fallback can take over.-- `scripts/lib/refresh-alm-plan-data.js`: Updates `docs/.alm-plan-data.json` with post-run state from the marker files written by setup-pipeline / deploy-pipeline / ensure-pipelines-host / test-site / import-solution / activate-site / configure-env-variables / setup-solution / export-solution, then optionally re-renders `docs/alm-plan.html`. Used by plan-alm Phases 6 / 7 / 8 so the rendered Pipelines tab, Validation tab, hostResolution card, env var values matrix, checklist, and risks list reflect actual run state instead of frozen pre-run intent. Args: `--projectRoot`, `--phase` (`setup-solution`/`setup-pipeline`/`configure-env-variables`/`deploy-pipeline`/`export-solution`/`import-solution`/`activate-site`/`test-site`/`finalize`), `--render` (also invoke renderer), `--stageName` (required for `test-site`; preferred for `import-solution`/`activate-site` though both can resolve via marker URL match). Output: `{ ok, phase, dataPath, htmlPath, rendered }`. Returns `ok:false` (soft no-op) when `docs/.alm-plan-data.json` is missing — caller should preserve that file across phases for the helper to work. Plan-alm Phase 3 must NOT delete the file after the initial render — it's read by `check-alm-plan.js` for downstream Phase 0 ALM-plan gates and by this helper for post-run refreshes. **Cross-cutting behaviors**: (a) `setStepStatus` flips the matching entry in `planData.steps[]` to `completed` (or `failed` when the phase's marker indicates failure) — case-insensitive keyword match + stage filter, respects `skip: true`, never regresses completed→pending; (b) `deploy-pipeline` AND `configure-env-variables` both backfill `planData.envVars[i].values{}` from the project root's `deployment-settings.json` so the rendered plan's "Values by Environment" matrix auto-populates (accepts both top-level-stage and nested-`stages` shapes; `SchemaName`/`Value` and camelCase variants; never overwrites a populated cell — manual override wins); (c) `configure-env-variables` and `setup-solution` both re-ingest `docs/alm/last-env-vars.json` (when present) so freshly-created definitions appear in `planData.envVars[]` and `plannedEnvVarCount` zeros out; (d) `export-solution` ingests `docs/alm/last-export.json` into `planData.manualMeta.lastExport` (all 10 marker fields: solutionUniqueName/solutionId/previousVersion/version/managed/sourceEnvironmentUrl/zipPath/fileSizeBytes/asyncOperationId/exportedAt) so the Manual-path tab can show the most recent export. Marker absence is a silent step-sync-only no-op (no `manualMeta.lastExport: null` row in the rendered plan); (e) `deploy-pipeline` ingests the `batchValidation` block from `last-deploy.json` into `planData.pipelineMeta.lastDeploy.batchValidation` (totalSolutions/succeeded/failed/pendingApproval/timedOut/elapsedSeconds/perSolutionStageRunIds) so the rendered plan can show the Phase 3.6 parallel-validation outcome distinct from the serial deploy outcome. Explicitly set to `null` for single-solution / legacy v2 deploys so renderers can branch on it; legacy `elapsedSecondsApprox` field name is accepted and normalized to `elapsedSeconds` on ingest.+- `scripts/lib/refresh-alm-plan-data.js`: Updates `docs/.alm-plan-data.json` with post-run state from the marker files written by setup-pipeline / deploy-pipeline / ensure-pipelines-host / test-site / import-solution / activate-site / configure-env-variables / setup-solution / export-solution, then optionally re-renders `docs/alm-plan.html`. Driven by the execution skills' final-phase refresh (and the PostToolUse `--reconcile` backstop) — NOT by plan-alm, which is now a plan-only 4-phase planner that only renders the initial plan in Phase 3 — so the rendered Pipelines tab, Validation tab, hostResolution card, env var values matrix, checklist, and risks list reflect actual run state instead of frozen pre-run intent. Args: `--projectRoot`, `--phase` (`setup-solution`/`setup-pipeline`/`configure-env-variables`/`deploy-pipeline`/`export-solution`/`import-solution`/`activate-site`/`test-site`/`ensure-pipelines-host`/`finalize`) **OR `--reconcile`** (mutually exclusive with `--phase`), `--render` (also invoke renderer), `--stageName` (required for `test-site`; preferred for `import-solution`/`activate-site` though both can resolve via marker URL match). Output: `{ ok, phase, dataPath, htmlPath, rendered }`. Returns `ok:false` (soft no-op) when `docs/.alm-plan-data.json` is missing — caller should preserve that file across phases for the helper to work. Plan-alm Phase 3 must NOT delete the file after the initial render — it's read by `check-alm-plan.js` for downstream Phase 0 ALM-plan gates and by this helper for post-run refreshes. **Cross-cutting behaviors**: (a) `setStepStatus` flips the matching entry in `planData.steps[]` to `completed` (or `failed` when the phase's marker indicates failure) — case-insensitive keyword match + stage filter, respects `skip: true`, never regresses completed→pending; (b) `deploy-pipeline` AND `configure-env-variables` both backfill `planData.envVars[i].values{}` from the project root's `deployment-settings.json` so the rendered plan's "Values by Environment" matrix auto-populates (accepts both top-level-stage and nested-`stages` shapes; `SchemaName`/`Value` and camelCase variants; never overwrites a populated cell — manual override wins); (c) `configure-env-variables` and `setup-solution` both re-ingest `docs/alm/last-env-vars.json` (when present) so freshly-created definitions appear in `planData.envVars[]` and `plannedEnvVarCount` zeros out; (d) `export-solution` ingests `docs/alm/last-export.json` into `planData.manualMeta.lastExport` (all 10 marker fields: solutionUniqueName/solutionId/previousVersion/version/managed/sourceEnvironmentUrl/zipPath/fileSizeBytes/asyncOperationId/exportedAt) so the Manual-path tab can show the most recent export. Marker absence is a silent step-sync-only no-op (no `manualMeta.lastExport: null` row in the rendered plan); (e) `deploy-pipeline` ingests the `batchValidation` block from `last-deploy.json` into `planData.pipelineMeta.lastDeploy.batchValidation` (totalSolutions/succeeded/failed/pendingApproval/timedOut/elapsedSeconds/perSolutionStageRunIds) so the rendered plan can show the Phase 3.6 parallel-validation outcome distinct from the serial deploy outcome. Explicitly set to `null` for single-solution / legacy v2 deploys so renderers can branch on it; legacy `elapsedSecondsApprox` field name is accepted and normalized to `elapsedSeconds` on ingest. **`ensure-pipelines-host` phase**: host-only update of `planData.hostResolution` from `last-host-check.json` (drops NoHost risks) WITHOUT touching `pipelineMeta` or the `Setup pipeline` step — for when the host was resolved but the pipeline doesn't exist yet. **`--reconcile` mode**: the enforcement backstop — scans the `last-*.json` markers and, for each one newer than `docs/.alm-plan-data.json` (a skipped refresh), applies the mapped phase (`MARKER_TO_PHASE`; `lastPipeline`→setup-pipeline supersedes the host-only phase; `lastEnvVars`→configure-env-variables if `deployment-settings.json` exists else setup-solution) against a single loaded planData, writes once, renders once. Honors `.alm-deferred`, soft no-op when no plan, idempotent. Output `{ ok, reconciled:[phases healed], failed:[{phase,error}], rendered }` — a phase whose refresh throws (e.g. a marker schema it can't parse) is captured in `failed` (and written to stderr) instead of being silently swallowed, while the remaining phases still heal. Invoked by the PostToolUse hook after every ALM skill (see Hooks). **Completion evaluator (`In Execution` → `Completed`):** after every phase's step-sync (both `refresh()` and `reconcile()`), `evaluatePlanCompletion` flips `PLAN_STATUS` to `Completed` + stamps `COMPLETED_AT` once every non-`skip` step is `completed` and none is `failed`. This is what makes the LAST execution skill terminate the plan automatically — no skill calls `--phase finalize` (the explicit `finalize` phase / `refreshFinalize` exists but nothing invoked it, so the lifecycle previously never reached `Completed`). Only advances from `In Execution` (the normal post-promotion state — see `check-alm-plan.js`) or `Approved` (defensive fallback); never regresses a `Draft` or already-`Completed` plan, and a `failed` step blocks completion so a failed deploy can't look "done".#### PP Pipelinesdiff --git a/plugins/power-pages/hooks/run-skill-posttool-validation.js b/plugins/power-pages/hooks/run-skill-posttool-validation.jsindex b53595790..d77959395 100644--- a/plugins/power-pages/hooks/run-skill-posttool-validation.js+++ b/plugins/power-pages/hooks/run-skill-posttool-validation.js@@ -1,11 +1,14 @@#!/usr/bin/env node+const fs = require('fs');const path = require('path');const { spawnSync } = require('child_process');const {getTrackedSkillFromToolInput,getValidatorScript,+ isAlmPlanSkill,} = require('../scripts/lib/powerpages-hook-utils');+const { planDataPath } = require('../scripts/lib/alm-paths');const DEBUG = process.env.DEBUG === '1' || process.env.DEBUG === 'true';@@ -36,19 +39,82 @@ process.stdin.on('end', () => {process.exit(0);}+ const cwd = input.cwd || process.cwd();+const validatorScript = getValidatorScript(skillName);if (validatorScript) {const validatorPath = path.join(__dirname, '..', validatorScript);const result = spawnSync(process.execPath, [validatorPath], {input: inputData,encoding: 'utf8',- cwd: input.cwd || process.cwd(),+ cwd,});if (result.stdout) process.stdout.write(result.stdout);if (result.stderr) process.stderr.write(result.stderr);validatorStatus = result.status ?? 0;debug(`[power-pages hook] Validator exited with code ${validatorStatus}\n`);}++ // ALM plan reconcile backstop (auto-heal). The refresh-alm-plan-data.js calls+ // in each SKILL.md are advisory — silently dropped on session fragmentation,+ // manual execution, or oversight. After ANY ALM plan skill completes, reconcile+ // the plan against the marker files: any marker newer than the plan (a skipped+ // refresh) is ingested automatically. Best-effort and NON-blocking — it never+ // changes the hook's exit code (the validator's status stands). Triggering on+ // any ALM skill (not just the marker's writer) catches a skip that surfaces only+ // when the NEXT ALM skill runs. Honors .alm-deferred + no-plan inside reconcile.+ if (isAlmPlanSkill(skillName) && fs.existsSync(planDataPath(cwd))) {+ try {+ const refreshPath = path.join(__dirname, '..', 'scripts', 'lib', 'refresh-alm-plan-data.js');+ const rec = spawnSync(process.execPath, [refreshPath, '--projectRoot', cwd, '--reconcile', '--render'], {+ encoding: 'utf8',+ cwd,+ timeout: 20000,+ });+ // spawnSync surfaces a spawn/timeout failure on rec.error (e.g. ETIMEDOUT)+ // and a non-zero / signalled exit on rec.status / rec.signal — none of which+ // produce parseable stdout. Track those so a broken reconcile is reported+ // rather than silently swallowed by the JSON.parse catch below.+ const spawnFailed = !!rec.error || rec.status !== 0 || !!rec.signal;+ let reconciled = [];+ let failed = [];+ let parsed = false;+ try {+ const out = JSON.parse((rec.stdout || '').trim());+ reconciled = out.reconciled || [];+ failed = out.failed || [];+ parsed = true;+ } catch { /* parsed stays false — surfaced in the spawnFailed/!parsed branch */ }+ if (reconciled.length > 0) {+ process.stdout.write(+ `[power-pages] ALM plan was out of sync with ${reconciled.length} run marker(s) — refreshed automatically (${reconciled.join(', ')}).\n`,+ );+ }+ // Failure reporting goes to STDERR (only on an actual failure, never on the+ // happy path — the hook fires on every Skill use, so clean runs must stay+ // quiet). A swallowed reconcile failure is exactly what makes a stale plan+ // impossible to diagnose, so we forward the child's stderr verbatim — that's+ // where refresh-alm-plan-data.js already writes its per-phase error detail,+ // which is what makes the summary line below actionable.+ if (failed.length > 0) {+ process.stderr.write(+ `[power-pages] ALM plan reconcile could not heal ${failed.length} phase(s): ${failed.map((f) => f.phase).join(', ')}. Details below.\n`,+ );+ if (rec.stderr) process.stderr.write(rec.stderr);+ } else if (spawnFailed || !parsed) {+ // The reconcile didn't even produce a parseable result (spawn error,+ // timeout, non-zero exit, or garbled stdout). Non-blocking, but the user+ // should still see why the auto-heal didn't run.+ const why = rec.error ? rec.error.message : rec.signal ? `signal ${rec.signal}` : `exit ${rec.status}`;+ process.stderr.write(`[power-pages] ALM plan reconcile did not complete (${why}). Details below.\n`);+ if (rec.stderr) process.stderr.write(rec.stderr);+ }+ debug(`[power-pages hook] reconcile reconciled=${JSON.stringify(reconciled)} failed=${JSON.stringify(failed)} spawnFailed=${spawnFailed} parsed=${parsed}\n`);+ } catch (e) {+ // Best-effort — a reconcile failure must never break the skill or the hook.+ debug(`[power-pages hook] reconcile error (ignored): ${e.message}\n`);+ }+ }} catch (err) {process.stderr.write(`[power-pages hook] Unexpected error: ${err.message}\n`);validatorStatus = 0;diff --git a/plugins/power-pages/scripts/lib/alm-paths.js b/plugins/power-pages/scripts/lib/alm-paths.jsindex b0546e081..2c09af8d3 100644--- a/plugins/power-pages/scripts/lib/alm-paths.js+++ b/plugins/power-pages/scripts/lib/alm-paths.js@@ -83,10 +83,31 @@ function ensureAlmDir(projectRoot) {return dir;}+// The rendered plan + its backing JSON live at the `docs/` ROOT (NOT under+// `docs/alm/`): `docs/alm-plan.html` and `docs/.alm-plan-data.json`. Centralized+// here so the PostToolUse hook, check-alm-plan.js, and refresh-alm-plan-data.js+// can't drift on the path.+const PLAN_DATA_FILE = '.alm-plan-data.json';+const PLAN_HTML_FILE = 'alm-plan.html';++function planDataPath(projectRoot) {+ if (!projectRoot) throw new Error('planDataPath: projectRoot is required');+ return path.join(projectRoot, 'docs', PLAN_DATA_FILE);+}++function planHtmlPath(projectRoot) {+ if (!projectRoot) throw new Error('planHtmlPath: projectRoot is required');+ return path.join(projectRoot, 'docs', PLAN_HTML_FILE);+}+module.exports = {ALM_DIR,FILE_NAMES,+ PLAN_DATA_FILE,+ PLAN_HTML_FILE,almDir,almPath,ensureAlmDir,+ planDataPath,+ planHtmlPath,};diff --git a/plugins/power-pages/scripts/lib/check-alm-plan.js b/plugins/power-pages/scripts/lib/check-alm-plan.jsindex f599b2e94..7ace858de 100644--- a/plugins/power-pages/scripts/lib/check-alm-plan.js+++ b/plugins/power-pages/scripts/lib/check-alm-plan.js@@ -80,6 +80,7 @@const fs = require('fs');const path = require('path');const helpers = require('./validation-helpers');+const { planDataPath, planHtmlPath } = require('./alm-paths');// Heartbeat window — how recent `lastInvocationAt` must be for the plan to count// as actively executing. 60 minutes is comfortably larger than the longest single@@ -185,8 +186,8 @@ function readDeferralLocal(projectRoot) {async function checkAlmPlan({ projectRoot, envUrl, token, solutionId, makeRequest, writeHeartbeat = true, now }) {if (!projectRoot) throw new Error('--projectRoot is required');- const planPath = path.join(projectRoot, 'docs', '.alm-plan-data.json');- const htmlPath = path.join(projectRoot, 'docs', 'alm-plan.html');+ const planPath = planDataPath(projectRoot);+ const htmlPath = planHtmlPath(projectRoot);const nowMs = (typeof now === 'number') ? now : Date.now();// Deferral marker check — runs first, regardless of plan presence.@@ -233,8 +234,40 @@ async function checkAlmPlan({ projectRoot, envUrl, token, solutionId, makeReques// way each in-chain skill's Phase 0 call both observes the prior heartbeat// (for its own decision) AND keeps the chain alive for the next skill.const priorLastInvocationAt = planData.LAST_INVOCATION_AT || null;- const planStatus = planData.PLAN_STATUS || null;- const inExecution = computeInExecution(planStatus, priorLastInvocationAt, nowMs);+ const priorPlanStatus = planData.PLAN_STATUS || null;++ // Classify `inExecution` from the PRIOR on-disk status, BEFORE any promotion.+ // An Approved plan is NOT yet an active orchestration — the user has just+ // approved it and this is the first execution skill to reach its Phase 0 gate.+ // If we promoted to "In Execution" first and then classified, computeInExecution+ // would return status:"active" (the "first heartbeat" branch) — and callers that+ // skip Phase 0 gates whenever inExecution.status === "active" (see deploy-pipeline+ // SKILL.md Phase 0) would take the active shortcut and bypass the stale-plan+ // confirmation that this helper computes further below. That would mask stale:true+ // on the FIRST execution after approval — defeating the ALM freshness gate exactly+ // when the source solution was modified between plan generation and approval. So+ // the first Approved->In Execution entry reports inExecution:"not-running", keeping+ // THIS caller on the normal Phase 0 path where it still honors stale:true. The+ // promotion is persisted below, so the NEXT in-chain skill reads "In Execution"+ // and correctly classifies as "active".+ const inExecution = computeInExecution(priorPlanStatus, priorLastInvocationAt, nowMs);++ // Promote Approved -> In Execution on the FIRST execution-skill Phase 0 entry and+ // persist it (+ the first heartbeat) so the NEXT in-chain skill sees an active+ // orchestration. plan-alm is plan-only: it leaves the plan "Approved" and the user+ // runs the execution skills themselves, so the first execution skill to reach its+ // Phase 0 gate is what actually starts execution — this is the transition that+ // activates the heartbeat/active-chain machinery (nothing else sets it). The+ // heartbeat write below then persists both the new status AND the first heartbeat+ // in one atomic write. This promotion intentionally does NOT change `inExecution`+ // for THIS caller (classified above from the prior status). Gated on `writeHeartbeat`+ // so read-only callers (--no-heartbeat: audits, tests, and plan-alm's own deferral+ // check) never mutate the plan's status.+ let planStatus = priorPlanStatus;+ if (writeHeartbeat && planStatus === 'Approved') {+ planStatus = 'In Execution';+ planData.PLAN_STATUS = 'In Execution';+ }if (writeHeartbeat && planStatus === 'In Execution') {try {diff --git a/plugins/power-pages/scripts/lib/powerpages-hook-utils.js b/plugins/power-pages/scripts/lib/powerpages-hook-utils.jsindex 9775fe0d5..af405f958 100644--- a/plugins/power-pages/scripts/lib/powerpages-hook-utils.js+++ b/plugins/power-pages/scripts/lib/powerpages-hook-utils.js@@ -105,9 +105,42 @@ function getValidatorScript(skillName) {return TRACKED_SKILLS[skillName]?.validatorScript ?? null;}+// Skills that write a `docs/alm/last-*.json` marker or otherwise consume the ALM+// plan. After any of these completes, the PostToolUse hook runs a plan reconcile+// (auto-heal) — so a refresh step skipped by ONE skill is caught when the NEXT+// ALM skill completes (covers manual/cross-session execution).+const ALM_PLAN_SKILLS = new Set([+ 'setup-solution',+ 'setup-pipeline',+ 'deploy-pipeline',+ 'export-solution',+ 'import-solution',+ 'configure-env-variables',+ 'activate-site',+ 'test-site',+ 'ensure-pipelines-host',+ 'force-link-environment',+]);++/**+ * True when `value` (a raw skill name, `/skill`, or `power-pages:skill`) resolves+ * to an ALM plan skill. Normalizes via `detectTrackedSkill`, so it also confirms+ * the skill actually exists in this plugin.+ * Accepts any value — non-strings (including null/undefined) resolve to false+ * via detectTrackedSkill, so callers may pass an unvalidated skill name.+ * @param {*} value+ * @returns {boolean}+ */+function isAlmPlanSkill(value) {+ const name = detectTrackedSkill(value);+ return name != null && ALM_PLAN_SKILLS.has(name);+}+module.exports = {TRACKED_SKILLS,+ ALM_PLAN_SKILLS,detectTrackedSkill,getTrackedSkillFromToolInput,getValidatorScript,+ isAlmPlanSkill,};diff --git a/plugins/power-pages/scripts/lib/refresh-alm-plan-data.js b/plugins/power-pages/scripts/lib/refresh-alm-plan-data.jsindex 564aa925f..27d912fe8 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,13 @@// finalize:// - PLAN_STATUS = "Completed"//+// After every phase's step-sync, a completion evaluator flips PLAN_STATUS to+// "Completed" (+ COMPLETED_AT) once all non-skip steps are completed and none+// failed — so the last execution skill terminates the plan automatically,+// without any skill needing to call the explicit "finalize" phase. The+// Approved -> In Execution promotion that starts the lifecycle lives in+// check-alm-plan.js (first execution-skill Phase 0).+//// 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@@ -49,7 +56,7 @@const fs = require('fs');const path = require('path');const { execFileSync } = require('child_process');-const { almPath } = require('./alm-paths');+const { almPath, planDataPath, planHtmlPath } = require('./alm-paths');const PHASES = new Set(['setup-solution',@@ -527,6 +534,33 @@ function refreshFinalize(planData) {return planData;}+// Completion evaluator. Once every non-skipped checklist step is `completed`+// (and none `failed`), the plan has been fully executed — transition it to+// "Completed" + stamp COMPLETED_AT. Runs after each phase's step-sync (in both+// refresh() and reconcile()), so the LAST execution skill to finish flips the+// plan terminal automatically — no skill has to call `--phase finalize`+// explicitly (nothing did, so the lifecycle previously never completed). Only+// advances from a pre-terminal, non-draft state: "In Execution" (the normal+// case after check-alm-plan.js promoted it on the first execution skill) or+// "Approved" (defensive fallback if that promotion didn't run). Never regresses+// a Draft or an already-Completed plan, and a `failed` step blocks completion+// (e.g. a failed deploy must not look "done" just because later steps are+// pending-skipped).+function evaluatePlanCompletion(planData) {+ if (!planData) return;+ const status = planData.PLAN_STATUS;+ if (status !== 'In Execution' && status !== 'Approved') return;+ if (!Array.isArray(planData.steps)) return;+ const live = planData.steps.filter((s) => s && s.skip !== true && typeof s.name === 'string');+ if (live.length === 0) return;+ const anyFailed = live.some((s) => s.status === 'failed');+ const allCompleted = live.every((s) => s.status === 'completed');+ if (!anyFailed && allCompleted) {+ planData.PLAN_STATUS = 'Completed';+ planData.COMPLETED_AT = new Date().toISOString();+ }+}+// Refresh-phase helper: stamp `LAST_SYNC_AT` on planData so check-alm-plan.js's// freshness check correctly accounts for source-solution modifications caused// by the just-completed phase. Called by every phase that touches the source@@ -1015,8 +1049,8 @@ function mtimeMs(filePath) {// 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');+ const dataPath = planDataPath(projectRoot);+ const htmlPath = planHtmlPath(projectRoot);// 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@@ -1085,6 +1119,7 @@ function reconcile({ projectRoot, render, rendererPath }) {process.stderr.write(`[refresh-alm-plan-data] reconcile phase "${phase}" failed: ${e.message}\n`);}}+ evaluatePlanCompletion(planData);fs.writeFileSync(dataPath, JSON.stringify(planData, null, 2), 'utf8');let rendered = false;@@ -1116,8 +1151,8 @@ function refresh({ projectRoot, phase, render, rendererPath, stageName }) {throw new Error('--phase must be one of: ' + [...PHASES].join(', '));}- const dataPath = path.join(projectRoot, 'docs', '.alm-plan-data.json');- const htmlPath = path.join(projectRoot, 'docs', 'alm-plan.html');+ const dataPath = planDataPath(projectRoot);+ const htmlPath = planHtmlPath(projectRoot);if (!fs.existsSync(dataPath)) {return {@@ -1135,6 +1170,7 @@ function refresh({ projectRoot, phase, render, rendererPath, stageName }) {}applyRefresh(planData, phase, projectRoot, stageName);+ evaluatePlanCompletion(planData);fs.writeFileSync(dataPath, JSON.stringify(planData, null, 2), 'utf8');let rendered = false;diff --git a/plugins/power-pages/scripts/tests/alm-paths.test.js b/plugins/power-pages/scripts/tests/alm-paths.test.jsindex c6c4903ae..6aef5a4a3 100644--- a/plugins/power-pages/scripts/tests/alm-paths.test.js+++ b/plugins/power-pages/scripts/tests/alm-paths.test.js@@ -6,7 +6,7 @@ const fs = require('fs');const path = require('path');const os = require('os');-const { almDir, almPath, ensureAlmDir, FILE_NAMES, ALM_DIR } = require('../lib/alm-paths');+const { almDir, almPath, ensureAlmDir, FILE_NAMES, ALM_DIR, planDataPath, planHtmlPath } = require('../lib/alm-paths');function makeTmp(t) {const root = fs.mkdtempSync(path.join(os.tmpdir(), 'alm-paths-'));@@ -73,6 +73,23 @@ test('ensureAlmDir is idempotent when docs/alm/ already exists', (t) => {assert.equal(fs.readFileSync(path.join(root, 'docs', 'alm', 'sentinel.txt'), 'utf8'), 'pre-existing');});+test('planDataPath / planHtmlPath resolve to the docs/ ROOT, not docs/alm/', () => {+ const root = path.join(path.sep, 'tmp', 'project');+ // The rendered plan + backing JSON intentionally live at docs/ (NOT docs/alm/).+ assert.equal(planDataPath(root), path.join(root, 'docs', '.alm-plan-data.json'));+ assert.equal(planHtmlPath(root), path.join(root, 'docs', 'alm-plan.html'));+ // Guard the dotfile + non-alm-subdir invariant the helpers exist to centralize.+ assert.ok(planDataPath(root).endsWith(path.join('docs', '.alm-plan-data.json')));+ assert.ok(!planDataPath(root).includes(path.join('docs', 'alm', '')), 'plan data must NOT be under docs/alm/');+});++test('planDataPath / planHtmlPath throw when projectRoot is missing', () => {+ assert.throws(() => planDataPath(undefined), /projectRoot is required/);+ assert.throws(() => planDataPath(''), /projectRoot is required/);+ assert.throws(() => planHtmlPath(undefined), /projectRoot is required/);+ assert.throws(() => planHtmlPath(''), /projectRoot is required/);+});+test('every FILE_NAMES entry resolves via almPath without error', () => {const root = path.join(path.sep, 'tmp', 'project');for (const key of Object.keys(FILE_NAMES)) {diff --git a/plugins/power-pages/scripts/tests/check-alm-plan.test.js b/plugins/power-pages/scripts/tests/check-alm-plan.test.jsindex 52eee4df0..4c7f6e052 100644--- a/plugins/power-pages/scripts/tests/check-alm-plan.test.js+++ b/plugins/power-pages/scripts/tests/check-alm-plan.test.js@@ -54,7 +54,8 @@ test('returns exists:true / stale:false when plan exists and no env credentials'PLAN_STATUS: 'Approved',});try {- const r = await checkAlmPlan({ projectRoot: dir });+ // writeHeartbeat:false → read-only check; an Approved plan is NOT promoted.+ const r = await checkAlmPlan({ projectRoot: dir, writeHeartbeat: false });assert.equal(r.exists, true);assert.equal(r.stale, false);assert.equal(r.generatedAt, '2026-04-01T00:00:00.000Z');@@ -515,3 +516,103 @@ test('Unparseable LAST_SYNC_AT falls back to GENERATED_AT (defensive)', async ()fs.rmSync(dir, { recursive: true, force: true });}});++// --- Approved -> In Execution promotion (lifecycle activation) ---------------++test('promotes Approved -> In Execution on the first execution-skill Phase 0 (writeHeartbeat default)', async () => {+ const dir = tempProject({ SITE_NAME: 'T', PLAN_STATUS: 'Approved' });+ try {+ const r = await checkAlmPlan({ projectRoot: dir });+ assert.equal(r.planStatus, 'In Execution', 'returned status reflects the promotion');+ // inExecution is classified from the PRIOR (Approved) status, so the FIRST+ // execution-skill entry reports "not-running" — NOT "active". This keeps the+ // caller on the normal Phase 0 path where it still honors stale:true; an+ // "active" shortcut here would mask a stale plan on the first run after approval.+ assert.equal(r.inExecution.status, 'not-running', 'first Approved->In Execution entry is not-running');+ // Promotion + heartbeat are still persisted to disk for the NEXT in-chain skill,+ // which reads "In Execution" + a fresh heartbeat and classifies as "active".+ const onDisk = JSON.parse(fs.readFileSync(path.join(dir, 'docs', '.alm-plan-data.json'), 'utf8'));+ assert.equal(onDisk.PLAN_STATUS, 'In Execution');+ assert.ok(onDisk.LAST_INVOCATION_AT, 'first heartbeat written');+ } finally {+ fs.rmSync(dir, { recursive: true, force: true });+ }+});++test('second in-chain skill sees the promoted In Execution plan as active', async () => {+ // Simulates the next execution skill after the promotion: PLAN_STATUS is already+ // "In Execution" with a fresh heartbeat on disk, so the active-chain machinery+ // engages and Phase 0 gates are skipped (no re-nagging within a running run).+ const dir = tempProject({+ SITE_NAME: 'T',+ PLAN_STATUS: 'In Execution',+ LAST_INVOCATION_AT: new Date().toISOString(),+ });+ try {+ const r = await checkAlmPlan({ projectRoot: dir });+ assert.equal(r.inExecution.status, 'active');+ } finally {+ fs.rmSync(dir, { recursive: true, force: true });+ }+});++test('Approved + stale source solution: stale gate is NOT masked by the promotion (inExecution stays not-running)', async () => {+ // Regression for the freshness-gate masking bug: an Approved plan whose source+ // solution was modified after generation must still surface stale:true on the+ // first execution skill. If the promotion classified inExecution as "active",+ // callers that skip Phase 0 on active status (deploy-pipeline SKILL.md) would+ // bypass the stale-plan confirmation. The promotion is persisted, but THIS call+ // must report inExecution "not-running" so stale:true is acted on.+ const dir = tempProject({+ SITE_NAME: 'T',+ PLAN_STATUS: 'Approved',+ GENERATED_AT: '2026-04-01T00:00:00.000Z',+ });+ // Solution modifiedon is AFTER GENERATED_AT → stale.+ const fakeRequest = async () => ({+ statusCode: 200,+ body: JSON.stringify({ modifiedon: '2026-04-15T08:42:00Z', version: '1.0.0.4' }),+ });+ try {+ const r = await checkAlmPlan({+ projectRoot: dir,+ envUrl: 'https://example.crm.dynamics.com',+ token: 'tok',+ solutionId: 'sol-guid',+ makeRequest: fakeRequest,+ });+ assert.equal(r.stale, true, 'stale source solution still flagged');+ assert.equal(r.staleness.reason, 'solution-modified');+ assert.notEqual(r.inExecution.status, 'active', 'active shortcut must NOT mask the stale gate');+ assert.equal(r.inExecution.status, 'not-running');+ // Promotion still happens on disk (next skill sees In Execution).+ const onDisk = JSON.parse(fs.readFileSync(path.join(dir, 'docs', '.alm-plan-data.json'), 'utf8'));+ assert.equal(onDisk.PLAN_STATUS, 'In Execution');+ } finally {+ fs.rmSync(dir, { recursive: true, force: true });+ }+});++test('does NOT promote Approved when writeHeartbeat is false (read-only callers: plan-alm, audits, tests)', async () => {+ const dir = tempProject({ SITE_NAME: 'T', PLAN_STATUS: 'Approved' });+ try {+ const r = await checkAlmPlan({ projectRoot: dir, writeHeartbeat: false });+ assert.equal(r.planStatus, 'Approved', 'read-only check leaves the plan Approved');+ const onDisk = JSON.parse(fs.readFileSync(path.join(dir, 'docs', '.alm-plan-data.json'), 'utf8'));+ assert.equal(onDisk.PLAN_STATUS, 'Approved', 'disk untouched');+ assert.equal(onDisk.LAST_INVOCATION_AT, undefined, 'no heartbeat written');+ } finally {+ fs.rmSync(dir, { recursive: true, force: true });+ }+});++test('does NOT promote a Draft plan (only Approved is promotable)', async () => {+ const dir = tempProject({ SITE_NAME: 'T', PLAN_STATUS: 'Draft' });+ try {+ const r = await checkAlmPlan({ projectRoot: dir });+ assert.equal(r.planStatus, 'Draft');+ assert.equal(r.inExecution.status, 'not-running');+ } finally {+ fs.rmSync(dir, { recursive: true, force: true });+ }+});diff --git a/plugins/power-pages/scripts/tests/powerpages-hook-utils.test.js b/plugins/power-pages/scripts/tests/powerpages-hook-utils.test.jsindex 65718dde3..e1becdaa3 100644--- a/plugins/power-pages/scripts/tests/powerpages-hook-utils.test.js+++ b/plugins/power-pages/scripts/tests/powerpages-hook-utils.test.js@@ -5,9 +5,11 @@ const path = require('path');const {TRACKED_SKILLS,+ ALM_PLAN_SKILLS,detectTrackedSkill,getTrackedSkillFromToolInput,getValidatorScript,+ isAlmPlanSkill,} = require('../lib/powerpages-hook-utils');const SKILLS_DIR = path.join(__dirname, '..', '..', 'skills');@@ -148,3 +150,27 @@ test('Object.prototype keys are not mistaken for tracked skills', () => {assert.equal(detectTrackedSkill('__proto__'), null);assert.equal(getTrackedSkillFromToolInput({ skill: 'toString' }), null);});++// --- ALM_PLAN_SKILLS / isAlmPlanSkill (reconcile-trigger gating) -------------++test('isAlmPlanSkill: true for ALM plan skills, normalizing prefixes', () => {+ assert.equal(isAlmPlanSkill('activate-site'), true);+ assert.equal(isAlmPlanSkill('/power-pages:activate-site'), true);+ assert.equal(isAlmPlanSkill('/activate-site'), true);+ assert.equal(isAlmPlanSkill('ensure-pipelines-host'), true);+ assert.equal(isAlmPlanSkill('setup-pipeline'), true);+});++test('isAlmPlanSkill: false for non-ALM skills and junk', () => {+ assert.equal(isAlmPlanSkill('create-site'), false);+ assert.equal(isAlmPlanSkill('add-seo'), false);+ assert.equal(isAlmPlanSkill('not-a-real-skill'), false);+ assert.equal(isAlmPlanSkill(null), false);+ assert.equal(isAlmPlanSkill(undefined), false);+});++test('ALM_PLAN_SKILLS members are all real tracked skills', () => {+ for (const name of ALM_PLAN_SKILLS) {+ assert.ok(TRACKED_SKILLS[name], `ALM_PLAN_SKILLS member "${name}" must be a tracked skill (have a SKILL.md)`);+ }+});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.jsindex ab23aecea..d538fff2c 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@@ -279,6 +279,74 @@ test('refresh finalize sets PLAN_STATUS to Completed', (t) => {assert.equal(planData.PLAN_STATUS, 'Completed');});+// evaluatePlanCompletion — the In Execution → Completed transition that makes the+// LAST execution skill terminate the plan automatically. These tests pin the+// status-gate edges (the defensive "Approved" fallback + the Draft / failed-step+// guards) so the lifecycle can't silently over- or under-complete.++test('completion: the last execution phase flips a plan from Approved straight to Completed (defensive fallback)', (t) => {+ // Normal flow promotes Approved → In Execution in check-alm-plan.js's Phase 0+ // gate. If that promotion was ever skipped (read-only caller, --no-heartbeat,+ // a manual run) the plan can still be "Approved" when its final step lands.+ // evaluatePlanCompletion accepts BOTH In Execution AND Approved so the plan+ // still terminates instead of getting wedged one transition short of done.+ const root = makeProject(t);+ writeJson(path.join(root, 'docs', '.alm-plan-data.json'), {+ PLAN_STATUS: 'Approved',+ SITE_NAME: 'TestSite',+ validationRuns: { Staging: null },+ steps: [+ { name: 'Deploy via pipeline to Staging', status: 'completed' },+ { 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: 'Staging' });++ const planData = readJson(path.join(root, 'docs', '.alm-plan-data.json'));+ assert.equal(planData.steps[1].status, 'completed', 'the final step flips to completed');+ assert.equal(planData.PLAN_STATUS, 'Completed', 'Approved → Completed (defensive fallback path)');+ assert.ok(planData.COMPLETED_AT, 'COMPLETED_AT is stamped on completion');+});++test('completion: a Draft plan is never auto-completed even when every step is done', (t) => {+ const root = makeProject(t);+ writeJson(path.join(root, 'docs', '.alm-plan-data.json'), {+ PLAN_STATUS: 'Draft',+ SITE_NAME: 'TestSite',+ validationRuns: { Staging: null },+ steps: [{ name: 'Test site in Staging', status: 'completed' }],+ });+ 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: 'Staging' });++ const planData = readJson(path.join(root, 'docs', '.alm-plan-data.json'));+ assert.equal(planData.PLAN_STATUS, 'Draft', 'an unapproved plan must not complete itself');+ assert.equal(planData.COMPLETED_AT, undefined, 'no COMPLETED_AT stamp for a Draft plan');+});++test('completion: a failed step blocks completion so a failed deploy can never look "done"', (t) => {+ const root = makeProject(t);+ writeJson(path.join(root, 'docs', '.alm-plan-data.json'), {+ PLAN_STATUS: 'In Execution',+ SITE_NAME: 'TestSite',+ validationRuns: { Staging: null },+ steps: [+ { name: 'Deploy via pipeline to Staging', status: 'failed' },+ { 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: 'Staging' });++ const planData = readJson(path.join(root, 'docs', '.alm-plan-data.json'));+ assert.equal(planData.PLAN_STATUS, 'In Execution', 'a failed step keeps the plan in execution');+ assert.equal(planData.COMPLETED_AT, undefined, 'no COMPLETED_AT while a step is failed');+});+test('refresh setup-pipeline preserves prior pipelineMeta.reusedByWiring annotation', (t) => {const root = makeProject(t);writeJson(path.join(root, 'docs', '.alm-plan-data.json'), {diff --git a/plugins/power-pages/scripts/tests/render-alm-plan.test.js b/plugins/power-pages/scripts/tests/render-alm-plan.test.jsindex 9380a86a7..f91b17f63 100644--- a/plugins/power-pages/scripts/tests/render-alm-plan.test.js+++ b/plugins/power-pages/scripts/tests/render-alm-plan.test.js@@ -1944,3 +1944,39 @@ test('render-alm-plan: checklist link onclick reuses the existing data-tab clickfs.rmSync(tmpDir, { recursive: true, force: true });}});++// ── COMPLETED_AT footer line (lifecycle terminal) ────────────────────────────++test('render-alm-plan: surfaces COMPLETED_AT in the footer when the plan is Completed', () => {+ const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'render-alm-completed-'));+ const outputPath = path.join(tmpDir, 'alm-plan.html');+ try {+ const { status } = runScript(+ makeValidData({ PLAN_STATUS: 'Completed', COMPLETED_AT: '2026-06-16T18:30:00.000Z' }),+ outputPath,+ );+ assert.equal(status, 0);+ const html = fs.readFileSync(outputPath, 'utf8');+ assert.match(html, /id="completed-at"/, 'completed-at span rendered');+ assert.match(html, /Completed:<\/strong>\s*<span id="completed-at">2026-06-16T18:30:00\.000Z<\/span>/);+ assert.ok(!html.includes('__COMPLETED_LINE__'), 'no orphan placeholder');+ assert.match(html, /class="plan-status completed"/, 'status badge styled completed');+ } finally {+ fs.rmSync(tmpDir, { recursive: true, force: true });+ }+});++test('render-alm-plan: omits the Completed footer line when COMPLETED_AT is absent', () => {+ const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'render-alm-nocompleted-'));+ const outputPath = path.join(tmpDir, 'alm-plan.html');+ try {+ const { status } = runScript(makeValidData({ PLAN_STATUS: 'In Execution' }), outputPath);+ assert.equal(status, 0);+ const html = fs.readFileSync(outputPath, 'utf8');+ assert.ok(!html.includes('id="completed-at"'), 'no completed-at span when not completed');+ assert.ok(!html.includes('__COMPLETED_LINE__'), 'placeholder still replaced (empty)');+ assert.match(html, /class="plan-status in-execution"/, 'status badge styled in-execution');+ } finally {+ fs.rmSync(tmpDir, { recursive: true, force: true });+ }+});diff --git a/plugins/power-pages/scripts/tests/run-skill-posttool-validation.test.js b/plugins/power-pages/scripts/tests/run-skill-posttool-validation.test.jsnew file mode 100644index 000000000..f15bb402c--- /dev/null+++ b/plugins/power-pages/scripts/tests/run-skill-posttool-validation.test.js@@ -0,0 +1,161 @@+'use strict';++// Smoke tests for the centralized PostToolUse hook (hooks/run-skill-posttool-validation.js).+//+// Two contracts are covered here that no other test exercised:+// 1. The ALM-plan reconcile BACKSTOP actually spawns after an ALM skill when a+// docs/.alm-plan-data.json exists — and heals a skipped refresh (auto-heal).+// 2. EXIT-CODE NEUTRALITY: the reconcile is best-effort and must never change the+// hook's exit code — the validator's status stands. We prove this by running the+// SAME blocking-validator scenario with the reconcile branch reachable (plan+// present) and unreachable (no plan) and asserting the exit code is identical.+//+// The hook is exercised as a real child process (the way Claude Code invokes it),+// piping a tool_input JSON over stdin.++const test = require('node:test');+const assert = require('node:assert/strict');+const fs = require('fs');+const path = require('path');+const os = require('os');+const { spawnSync } = require('child_process');++const HOOK_PATH = path.join(__dirname, '..', '..', 'hooks', 'run-skill-posttool-validation.js');++function makeProject(t) {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'hook-posttool-'));+ fs.mkdirSync(path.join(root, 'docs', 'alm'), { recursive: true });+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));+ return root;+}++function writeJson(filePath, data) {+ fs.mkdirSync(path.dirname(filePath), { recursive: true });+ fs.writeFileSync(filePath, JSON.stringify(data, null, 2), 'utf8');+}++function readJson(filePath) {+ return JSON.parse(fs.readFileSync(filePath, 'utf8'));+}++// 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 ts = (Date.now() - secondsAgo * 1000) / 1000;+ fs.utimesSync(p, ts, ts);+}++function runHook(root, skill) {+ return spawnSync(process.execPath, [HOOK_PATH], {+ input: JSON.stringify({ tool_input: { skill }, cwd: root }),+ encoding: 'utf8',+ cwd: root,+ });+}++test('hook spawns the reconcile backstop and heals a skipped refresh after an ALM skill', (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 in-skill refresh step was skipped).+ writeJson(path.join(root, 'docs', 'alm', 'last-deploy.json'), {+ pipelineId: 'p1',+ stageRunId: 'sr1',+ solutionName: 'MySolution',+ stageName: 'Staging',+ status: 'Succeeded',+ deployedAt: '2026-06-16T00:00:00.000Z',+ componentCount: 118,+ });+ backdatePlan(root);++ const res = runHook(root, 'deploy-pipeline');++ // Validator approves (all required fields present, not Failed) → exit 0.+ assert.equal(res.status, 0, `hook should exit 0; stderr=${res.stderr}`);+ // The backstop fired and announced the auto-heal.+ assert.match(res.stdout, /refreshed automatically/i,+ `expected the reconcile notice in stdout; got: ${res.stdout}`);+ // And it actually ingested the marker into the plan.+ 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);+ // A clean reconcile must stay quiet on stderr — the hook fires on every Skill+ // use, so success must not produce failure noise.+ assert.doesNotMatch(res.stderr, /reconcile/i, 'a successful reconcile must not write failure noise to stderr');+});++test('hook forwards reconcile failure detail to stderr without changing the exit code', (t) => {+ // A malformed plan file makes refresh-alm-plan-data.js --reconcile throw and exit+ // non-zero with its reason on stderr. The hook must (a) surface that — the prior+ // empty JSON.parse catch swallowed spawn errors / timeouts / non-zero exits — and+ // (b) stay non-blocking (the reconcile is best-effort; the validator's status stands).+ const root = makeProject(t);+ fs.writeFileSync(path.join(root, 'docs', '.alm-plan-data.json'), 'not json {{{', 'utf8');+ // A newer marker guarantees the reconcile reaches the plan-parse (and would heal if it could).+ writeJson(path.join(root, 'docs', 'alm', 'last-export.json'), { solutionUniqueName: 'S', exportedAt: '2026-06-16T00:00:00.000Z' });+ backdatePlan(root);++ // export-solution is an ALM skill; its validator gracefully approves (no zip) → exit 0.+ const res = runHook(root, 'export-solution');++ assert.equal(res.status, 0, 'a broken reconcile must not change the validator-determined exit code');+ assert.match(res.stderr, /reconcile did not complete/i, 'the hook must report the broken reconcile');+ assert.match(res.stderr, /Could not parse/i, 'the child reconcile stderr must be forwarded verbatim');+});++test('hook does NOT reconcile for a non-ALM skill even when a plan + newer marker exist', (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' }],+ });+ writeJson(path.join(root, 'docs', 'alm', 'last-deploy.json'), {+ pipelineId: 'p1', stageRunId: 'sr1', solutionName: 'S', status: 'Succeeded',+ deployedAt: '2026-06-16T00:00:00.000Z', componentCount: 99,+ });+ backdatePlan(root);++ // create-site is a tracked skill but NOT an ALM plan skill → isAlmPlanSkill === false.+ const res = runHook(root, 'create-site');++ assert.doesNotMatch(res.stdout, /refreshed automatically/i,+ 'non-ALM skill must not trigger the reconcile backstop');+ // The plan must be untouched — the deploy marker was NOT ingested.+ const planData = readJson(path.join(root, 'docs', '.alm-plan-data.json'));+ assert.equal(planData.pipelineMeta.lastDeploy, null,+ 'non-ALM skill path must leave the plan unchanged');+});++test('reconcile backstop is exit-code-neutral: a blocking validator status is unchanged whether or not the plan is present', (t) => {+ // A Failed deploy marker makes validate-deploy-pipeline.js BLOCK (exit 2). The+ // reconcile runs too (plan present) — and must NOT mask or alter that exit code.+ const failedMarker = {+ pipelineId: 'p1', stageRunId: 'sr1', solutionName: 'S', stageName: 'Staging',+ status: 'Failed', deployedAt: '2026-06-16T00:00:00.000Z',+ };++ // (A) Reconcile branch REACHABLE — docs/.alm-plan-data.json exists.+ const withPlan = makeProject(t);+ writeJson(path.join(withPlan, 'docs', 'alm', 'last-deploy.json'), failedMarker);+ writeJson(path.join(withPlan, 'docs', '.alm-plan-data.json'), {+ SITE_NAME: 'T', steps: [{ name: 'Deploy via pipeline to Staging', status: 'pending' }],+ });+ backdatePlan(withPlan);+ const resWith = runHook(withPlan, 'deploy-pipeline');++ // (B) Reconcile branch UNREACHABLE — no plan file at all.+ const withoutPlan = makeProject(t);+ writeJson(path.join(withoutPlan, 'docs', 'alm', 'last-deploy.json'), failedMarker);+ const resWithout = runHook(withoutPlan, 'deploy-pipeline');++ assert.equal(resWith.status, 2, 'blocking validator must surface exit 2 with the plan present');+ assert.equal(resWithout.status, 2, 'blocking validator must surface exit 2 with no plan');+ assert.equal(resWith.status, resWithout.status,+ 'the reconcile backstop must not change the validator-determined exit code');+});diff --git a/plugins/power-pages/skills/ensure-pipelines-host/SKILL.md b/plugins/power-pages/skills/ensure-pipelines-host/SKILL.mdindex 278a33acf..f639b77ff 100644--- a/plugins/power-pages/skills/ensure-pipelines-host/SKILL.md+++ b/plugins/power-pages/skills/ensure-pipelines-host/SKILL.md@@ -900,6 +900,17 @@ Record skill usage:Follow the skill tracking instructions in the reference to record this skill's usage. Use `--skillName "EnsurePipelinesHost"`.+**Refresh the ALM plan (if one exists):**++```bash+node "${PLUGIN_ROOT}/scripts/lib/refresh-alm-plan-data.js" \+ --projectRoot "." \+ --phase ensure-pipelines-host \+ --render+```++This updates `planData.hostResolution` from the `docs/alm/last-host-check.json` you just wrote (host-only — no pipeline yet) and drops the pre-run NoHost risks, then re-renders `docs/alm-plan.html`. **Do this here, not just in setup-pipeline Phase 7** — a host install can take 18+ minutes and cross a session boundary, so deferring the refresh risks the plan never reflecting the host. 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. The centralized PostToolUse hook also reconciles the plan as a backstop, but refreshing at the source keeps the rendered plan current immediately.+Present summary table:| Field | Value |diff --git a/plugins/power-pages/skills/plan-alm/SKILL.md b/plugins/power-pages/skills/plan-alm/SKILL.mdindex 652b28a1f..e3122ebb4 100644--- a/plugins/power-pages/skills/plan-alm/SKILL.md+++ b/plugins/power-pages/skills/plan-alm/SKILL.md@@ -43,9 +43,11 @@ Steps:0. **Detect prior ALM deferral for this project.** Before any discovery work, check whether the project root contains a `.alm-deferred` marker file. The marker is written by users who explicitly opted ALM-skill validators out of "missing artifacts" warnings (e.g. *"this site is handled separately"* or *"ni-dev — no ALM"*). If a user is now invoking `plan-alm`, we should surface that the marker is present and ask what to do, rather than silently proceeding (which would build a plan the user previously decided not to maintain) or silently removing the marker (which would re-enable nags on every other ALM skill).```bash- node "${PLUGIN_ROOT}/scripts/lib/check-alm-plan.js" --projectRoot "."+ node "${PLUGIN_ROOT}/scripts/lib/check-alm-plan.js" --projectRoot "." --no-heartbeat```+ > Use `--no-heartbeat` here: this is a **read-only** deferral check by the *planner*, not an execution-skill Phase 0 gate. Without it, `check-alm-plan.js` would promote an already-`Approved` plan to `In Execution` (and refresh the heartbeat) just because you re-opened `plan-alm` — but re-planning isn't execution. Execution skills call it *without* `--no-heartbeat` so the first one to run does the `Approved → In Execution` promotion.+<!-- gate: plan-alm:1.deferral | category=progress | cancel-leaves=deferral-marker -->> 🚦 **Gate (progress · plan-alm:1.deferral):** `.alm-deferred` marker present — continue and remove, continue and keep marker, or cancel. Determines whether downstream ALM skills resume gate enforcement.diff --git a/plugins/power-pages/skills/plan-alm/assets/alm-plan-template.html b/plugins/power-pages/skills/plan-alm/assets/alm-plan-template.htmlindex 495fa4e13..b59753a82 100644--- a/plugins/power-pages/skills/plan-alm/assets/alm-plan-template.html+++ b/plugins/power-pages/skills/plan-alm/assets/alm-plan-template.html@@ -30,6 +30,7 @@ body{font-family:var(--sans);background:var(--bg);color:var(--text);font-size:14.topbar-left{display:flex;align-items:center;gap:14px;}.logo{width:36px;height:36px;border-radius:var(--radius);background:linear-gradient(135deg,#0078d4,#5c2d91);display:flex;align-items:center;justify-content:center;font-size:13px;font-weight:800;color:#fff;font-family:var(--mono);}.topbar-title{font-size:16px;font-weight:700;color:var(--text-bright);}+.topbar-sub-row{display:flex;align-items:center;gap:10px;margin-top:1px;}.topbar-sub{font-size:11px;color:var(--text-dim);margin-top:1px;}.plan-status{font-size:10px;font-weight:700;padding:3px 10px;border-radius:10px;text-transform:uppercase;letter-spacing:0.6px;background:var(--accent-bg);color:var(--accent);border:1px solid var(--accent-border);}.plan-status.draft{background:var(--high-bg);color:var(--high);border-color:var(--high-border);}@@ -319,10 +320,12 @@ footer.page-footer{text-align:center;padding:12px;font-size:12px;color:var(--tex<div class="logo">PP</div><div><div class="topbar-title">ALM Plan — __SITE_NAME__</div>- <div class="topbar-sub">Generated __GENERATED_AT__</div>+ <div class="topbar-sub-row">+ <div class="topbar-sub">Generated __GENERATED_AT__</div>+ <span class="plan-status">__PLAN_STATUS__</span>+ </div></div></div>- <span class="plan-status">__PLAN_STATUS__</span></div><div class="layout">@@ -419,6 +422,7 @@ footer.page-footer{text-align:center;padding:12px;font-size:12px;color:var(--tex<div class="card" style="margin-top:20px;font-size:12px;color:var(--text-dim);"><strong>Approved by:</strong> <span id="approved-by">__APPROVED_BY__</span> · <strong>Approval date:</strong> <span id="approval-date">__APPROVAL_DATE__</span>+ __COMPLETED_LINE__</div></div>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.jsindex 33453328b..b19487f77 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@@ -9,6 +9,11 @@* SITE_NAME, GENERATED_AT, STRATEGY, PLAN_STATUS, APPROVED_BY, APPROVAL_DATE,* stages, steps, risks*+ * Optional lifecycle key:+ * COMPLETED_AT — present only once the plan reaches PLAN_STATUS "Completed";+ * the renderer emits the footer "Completed" line when it exists and omits it+ * otherwise (an in-flight plan has no COMPLETED_AT).+ ** Optional v2 keys (added for split-solutions support):* sizeAnalysis, assetAdvisory, proposedSolutions, appliedStrategies,* recommendations, envVars, breakdown, estimationMethod, estimationAccuracyPct@@ -1448,6 +1453,12 @@ const replacements = {PLAN_STATUS: escapeHtml(data.PLAN_STATUS || 'Draft'),APPROVED_BY: escapeHtml(data.APPROVED_BY || ''),APPROVAL_DATE: escapeHtml(data.APPROVAL_DATE || ''),+ // Completion footer line — only rendered once the plan reaches "Completed"+ // (refresh-alm-plan-data.js stamps COMPLETED_AT when every step is done).+ // Empty string otherwise, so the placeholder is always replaced (no orphan token).+ COMPLETED_LINE: data.COMPLETED_AT+ ? `<br><strong>Completed:</strong> <span id="completed-at">${escapeHtml(data.COMPLETED_AT)}</span>`+ : '',OVERVIEW_SUMMARY: buildOverviewSummary(),STAT_COMPONENTS: (componentCount || 0).toLocaleString(),STAT_ENVVARS: envVarStatDisplay(),