From a015a758c1d0bf0bb29ef93186956eb9b76c66c9 Mon Sep 17 00:00:00 2001 From: rockyltwong Date: Thu, 5 Nov 2026 23:34:06 -0700 Subject: [PATCH 1/2] fix(publish): keep image assets out of link mapping, refuse empty-shell recovery, decode : styles - planner: leave manifest image destinations unmapped; add -NoBcDesignTokens - publisher: Assert-SpoRecoverableComponent refuses recovery of an empty shell; image size/alignment readers decode : - contract: -OutputPath belongs to the wave publisher only Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../scripts/new-page-migration-dry-run.ps1 | 24 +++-- .../references/modes/page-publish-contract.md | 13 ++- .../scripts/new-page-migration-dry-run.ps1 | 24 +++-- .../scripts/publish-spo-page.ps1 | 35 ++++-- .../tests/test_publish_page_fixes.py | 102 ++++++++++++++++++ 5 files changed, 174 insertions(+), 24 deletions(-) create mode 100644 plugins/sharepoint-workbench/tests/test_publish_page_fixes.py diff --git a/plugins/sharepoint-workbench/.apm/skills/modernizing-sharepoint-pages/scripts/new-page-migration-dry-run.ps1 b/plugins/sharepoint-workbench/.apm/skills/modernizing-sharepoint-pages/scripts/new-page-migration-dry-run.ps1 index 9e3a6662..0d0d85d5 100644 --- a/plugins/sharepoint-workbench/.apm/skills/modernizing-sharepoint-pages/scripts/new-page-migration-dry-run.ps1 +++ b/plugins/sharepoint-workbench/.apm/skills/modernizing-sharepoint-pages/scripts/new-page-migration-dry-run.ps1 @@ -16,6 +16,7 @@ maps each payload to an SPO text web part. - Optional image manifest produced by extract-page-images.ps1 - Optional -LibraryPathMapPath (inventory/library-path-map.csv) with -SourceHost: rewrites SP2016 links to their planned SPO location (assume-migrated link policy) +- Optional -NoBcDesignTokens: skips the BC design-token wrapper on text web parts - Optional -LeadingImageWebPartIds: web parts whose leading banner image becomes an Image web part reusing the already-migrated image (ExistingImageUrl, no upload) - -ConfigPath: config-spo-.psd1; Connection.Environment is the target environment @@ -66,7 +67,9 @@ param( [int]$PageHeaderZoneThemeIndex = 3, [string]$PageTitle, [string]$BreadcrumbSection, - [string]$BreadcrumbSectionUrl + [string]$BreadcrumbSectionUrl, + # Leaves the BC design-token wrapper (font, colour, 16px) off the text web parts. + [switch]$NoBcDesignTokens ) Set-StrictMode -Version Latest @@ -584,7 +587,9 @@ function ConvertTo-SpPageMappedLinks { [AllowEmptyString()][string]$PageUrl, [Parameter(Mandatory = $true)][string]$SourceHost, [string]$TargetSitePath, - [string]$RelativeBase + [string]$RelativeBase, + # Values already pointing at their final location (e.g. uploaded image assets) are left untouched. + [string[]]$PreservedValues = @() ) $sourceHostName = ($SourceHost -replace "^[a-z]+://", "").Trim("/") @@ -594,7 +599,8 @@ function ConvertTo-SpPageMappedLinks { param($match) $raw = $match.Groups["value"].Value $value = [System.Net.WebUtility]::HtmlDecode($raw).Trim() - if ($value -eq "" -or $value -match "^(#|mailto:|tel:|javascript:|data:)" -or $value -match "^/sites/") { + if ($value -eq "" -or $value -match "^(#|mailto:|tel:|javascript:|data:)" -or $value -match "^/sites/" -or + $PreservedValues -contains $value) { return $match.Value } $uri = $null @@ -901,7 +907,8 @@ function New-SpPageWave1DryRun { [int]$PageHeaderZoneThemeIndex = 3, [string]$PageTitle, [string]$BreadcrumbSection, - [string]$BreadcrumbSectionUrl + [string]$BreadcrumbSectionUrl, + [switch]$NoBcDesignTokens ) $useSpfx = $AccordionOutput -eq "Spfx" @@ -1081,7 +1088,8 @@ function New-SpPageWave1DryRun { if ($pathMap.Count -gt 0) { $mapped = ConvertTo-SpPageMappedLinks -Html $html -PathMap $pathMap -PageUrl $pageUrl ` -SourceHost $SourceHost -TargetSitePath $TargetSitePath ` - -RelativeBase $(if ($TargetSitePath) { if ([string]$page.SiteName -eq "Main") { "../" } else { "../../" } } else { "" }) + -RelativeBase $(if ($TargetSitePath) { if ([string]$page.SiteName -eq "Main") { "../" } else { "../../" } } else { "" }) ` + -PreservedValues @($webpartImages | ForEach-Object { [string]$_.DestinationRelativePath }) foreach ($link in @($mapped.Links)) { $link | Add-Member -NotePropertyName SourceWebPartId -NotePropertyValue $webpartId $linkRewrites.Add($link) @@ -1213,7 +1221,8 @@ function New-SpPageWave1DryRun { } $isFirstPiece = $false if ([string]::IsNullOrWhiteSpace($html)) { continue } - $components.Add((& $newComponent "TextWebPart" (Set-SpPageBcDesignTokenStyles -Html (ConvertTo-SpPageBcAlert -Html $html)) $section)) + $alerted = ConvertTo-SpPageBcAlert -Html $html + $components.Add((& $newComponent "TextWebPart" $(if ($NoBcDesignTokens) { $alerted } else { Set-SpPageBcDesignTokenStyles -Html $alerted }) $section)) } } if ($hasAccordion -and -not $useSpfx -and $pageLayout -notin @("", "One-Column")) { @@ -1338,5 +1347,6 @@ if ($MyInvocation.InvocationName -ne ".") { -PageHeaderZoneThemeIndex $PageHeaderZoneThemeIndex ` -PageTitle $PageTitle ` -BreadcrumbSection $BreadcrumbSection ` - -BreadcrumbSectionUrl $BreadcrumbSectionUrl + -BreadcrumbSectionUrl $BreadcrumbSectionUrl ` + -NoBcDesignTokens:$NoBcDesignTokens } diff --git a/plugins/sharepoint-workbench/.apm/skills/publishing-sharepoint-pages/references/modes/page-publish-contract.md b/plugins/sharepoint-workbench/.apm/skills/publishing-sharepoint-pages/references/modes/page-publish-contract.md index 9e62eb60..ce3bc5fd 100644 --- a/plugins/sharepoint-workbench/.apm/skills/publishing-sharepoint-pages/references/modes/page-publish-contract.md +++ b/plugins/sharepoint-workbench/.apm/skills/publishing-sharepoint-pages/references/modes/page-publish-contract.md @@ -31,8 +31,10 @@ asset through PnP read operations. Dry-run is the default and performs no tenant I/O. Real writes require both `-Execute` and the exact `PUBLISH-SPO-PAGE` confirmation token, plus an -explicit target configuration. Execution also requires ClientId, TenantId, -and a durable `-OutputPath` for the publication receipt. +explicit target configuration. Execution also requires ClientId and TenantId. +The wave publisher additionally requires a durable `-OutputPath` for the +publication receipt; the single-page `publish-spo-page.ps1` has no +`-OutputPath` parameter, so check the published page itself. ## Single-page and wave workflows @@ -165,8 +167,11 @@ position inside each Content Editor HTML payload are preserved. For the currently observed partial DEV page only, recovery requires the additional `-RecoverPartialPage` switch. Recovery refuses unless the existing -page has exactly one component; it then adds the remaining package components -in order before publishing and validating. +page has exactly one component and that component is a text web part with +visible content (when the package's first component is a text web part). An +empty draft shell is refused; republish it with `-Force` (backup, then +overwrite). Otherwise it adds the remaining package components in order before +publishing and validating. This capability does not update inventory. After independent publication validation, hand the verified destination URL to `sp-page-inventory-agent`. diff --git a/plugins/sharepoint-workbench/.apm/skills/publishing-sharepoint-pages/scripts/new-page-migration-dry-run.ps1 b/plugins/sharepoint-workbench/.apm/skills/publishing-sharepoint-pages/scripts/new-page-migration-dry-run.ps1 index 9e3a6662..0d0d85d5 100644 --- a/plugins/sharepoint-workbench/.apm/skills/publishing-sharepoint-pages/scripts/new-page-migration-dry-run.ps1 +++ b/plugins/sharepoint-workbench/.apm/skills/publishing-sharepoint-pages/scripts/new-page-migration-dry-run.ps1 @@ -16,6 +16,7 @@ maps each payload to an SPO text web part. - Optional image manifest produced by extract-page-images.ps1 - Optional -LibraryPathMapPath (inventory/library-path-map.csv) with -SourceHost: rewrites SP2016 links to their planned SPO location (assume-migrated link policy) +- Optional -NoBcDesignTokens: skips the BC design-token wrapper on text web parts - Optional -LeadingImageWebPartIds: web parts whose leading banner image becomes an Image web part reusing the already-migrated image (ExistingImageUrl, no upload) - -ConfigPath: config-spo-.psd1; Connection.Environment is the target environment @@ -66,7 +67,9 @@ param( [int]$PageHeaderZoneThemeIndex = 3, [string]$PageTitle, [string]$BreadcrumbSection, - [string]$BreadcrumbSectionUrl + [string]$BreadcrumbSectionUrl, + # Leaves the BC design-token wrapper (font, colour, 16px) off the text web parts. + [switch]$NoBcDesignTokens ) Set-StrictMode -Version Latest @@ -584,7 +587,9 @@ function ConvertTo-SpPageMappedLinks { [AllowEmptyString()][string]$PageUrl, [Parameter(Mandatory = $true)][string]$SourceHost, [string]$TargetSitePath, - [string]$RelativeBase + [string]$RelativeBase, + # Values already pointing at their final location (e.g. uploaded image assets) are left untouched. + [string[]]$PreservedValues = @() ) $sourceHostName = ($SourceHost -replace "^[a-z]+://", "").Trim("/") @@ -594,7 +599,8 @@ function ConvertTo-SpPageMappedLinks { param($match) $raw = $match.Groups["value"].Value $value = [System.Net.WebUtility]::HtmlDecode($raw).Trim() - if ($value -eq "" -or $value -match "^(#|mailto:|tel:|javascript:|data:)" -or $value -match "^/sites/") { + if ($value -eq "" -or $value -match "^(#|mailto:|tel:|javascript:|data:)" -or $value -match "^/sites/" -or + $PreservedValues -contains $value) { return $match.Value } $uri = $null @@ -901,7 +907,8 @@ function New-SpPageWave1DryRun { [int]$PageHeaderZoneThemeIndex = 3, [string]$PageTitle, [string]$BreadcrumbSection, - [string]$BreadcrumbSectionUrl + [string]$BreadcrumbSectionUrl, + [switch]$NoBcDesignTokens ) $useSpfx = $AccordionOutput -eq "Spfx" @@ -1081,7 +1088,8 @@ function New-SpPageWave1DryRun { if ($pathMap.Count -gt 0) { $mapped = ConvertTo-SpPageMappedLinks -Html $html -PathMap $pathMap -PageUrl $pageUrl ` -SourceHost $SourceHost -TargetSitePath $TargetSitePath ` - -RelativeBase $(if ($TargetSitePath) { if ([string]$page.SiteName -eq "Main") { "../" } else { "../../" } } else { "" }) + -RelativeBase $(if ($TargetSitePath) { if ([string]$page.SiteName -eq "Main") { "../" } else { "../../" } } else { "" }) ` + -PreservedValues @($webpartImages | ForEach-Object { [string]$_.DestinationRelativePath }) foreach ($link in @($mapped.Links)) { $link | Add-Member -NotePropertyName SourceWebPartId -NotePropertyValue $webpartId $linkRewrites.Add($link) @@ -1213,7 +1221,8 @@ function New-SpPageWave1DryRun { } $isFirstPiece = $false if ([string]::IsNullOrWhiteSpace($html)) { continue } - $components.Add((& $newComponent "TextWebPart" (Set-SpPageBcDesignTokenStyles -Html (ConvertTo-SpPageBcAlert -Html $html)) $section)) + $alerted = ConvertTo-SpPageBcAlert -Html $html + $components.Add((& $newComponent "TextWebPart" $(if ($NoBcDesignTokens) { $alerted } else { Set-SpPageBcDesignTokenStyles -Html $alerted }) $section)) } } if ($hasAccordion -and -not $useSpfx -and $pageLayout -notin @("", "One-Column")) { @@ -1338,5 +1347,6 @@ if ($MyInvocation.InvocationName -ne ".") { -PageHeaderZoneThemeIndex $PageHeaderZoneThemeIndex ` -PageTitle $PageTitle ` -BreadcrumbSection $BreadcrumbSection ` - -BreadcrumbSectionUrl $BreadcrumbSectionUrl + -BreadcrumbSectionUrl $BreadcrumbSectionUrl ` + -NoBcDesignTokens:$NoBcDesignTokens } diff --git a/plugins/sharepoint-workbench/.apm/skills/publishing-sharepoint-pages/scripts/publish-spo-page.ps1 b/plugins/sharepoint-workbench/.apm/skills/publishing-sharepoint-pages/scripts/publish-spo-page.ps1 index 4e640b2f..2a00016a 100644 --- a/plugins/sharepoint-workbench/.apm/skills/publishing-sharepoint-pages/scripts/publish-spo-page.ps1 +++ b/plugins/sharepoint-workbench/.apm/skills/publishing-sharepoint-pages/scripts/publish-spo-page.ps1 @@ -29,7 +29,7 @@ Get-SpoImageProportionalHeight, Get-SpoImageComponentUrl, ConvertTo-SpoPageHtml, New-SpoInlineImageHtml, Get-SpoInlineImageAlignment, Get-SpoInlineImageTableCellWidth, ConvertTo-SpoPageInlineImages, -Test-SpoPublicationPackageAssets, Read-SpoConfiguration, Publish-SpoPage. +Test-SpoPublicationPackageAssets, Assert-SpoRecoverableComponent, Read-SpoConfiguration, Publish-SpoPage. .EXAMPLE pwsh -File .\plugins\sp-migration\scripts\publication\publish-spo-page.ps1 ` @@ -482,7 +482,8 @@ function Get-SpoInlineImageAlignment { [Parameter(Mandatory = $true)][int]$ImageIndex ) - $prefix = $Html.Substring(0, $ImageIndex) + # SharePoint stores ':' in rich-text styles as ':'. + $prefix = $Html.Substring(0, $ImageIndex).Replace(':', ':') $openElements = [System.Collections.Generic.List[object]]::new() $alignment = "Left" $tagMatches = [regex]::Matches( @@ -547,7 +548,7 @@ function Get-SpoInlineImageDimensions { ) $styleMatch = [regex]::Match($ImageTag, '(?i)\bstyle\s*=\s*["'']([^"'']*)["'']') - $style = if ($styleMatch.Success) { $styleMatch.Groups[1].Value } else { "" } + $style = if ($styleMatch.Success) { $styleMatch.Groups[1].Value.Replace(':', ':') } else { "" } $getDimension = { param([string]$Name) $match = [regex]::Match($style, "(?i)\b$Name\s*:\s*(\d+)\s*px") @@ -1091,6 +1092,29 @@ function Backup-SpoExistingPage { } } +# Refuses partial-page recovery unless the page holds exactly one component that is the package's first one +# with real content; an empty shell would otherwise be "recovered" and published as a blank page. +function Assert-SpoRecoverableComponent { + [CmdletBinding()] + param( + [AllowEmptyCollection()][object[]]$ExistingComponents = @(), + [Parameter(Mandatory = $true)]$FirstPackageComponent + ) + + $existing = @($ExistingComponents | Where-Object { $null -ne $_ }) + if ($existing.Count -ne 1) { + throw "Partial-page recovery requires exactly one existing component; found $($existing.Count)." + } + if ([string]$FirstPackageComponent.OutputType -ne "TextWebPart") { return } + $text = if ($existing[0].PSObject.Properties["Text"]) { [string]$existing[0].Text } else { $null } + $visible = if ($null -ne $text) { + [System.Net.WebUtility]::HtmlDecode([regex]::Replace($text, '(?s)<[^>]*>', '')).Replace([string][char]0xA0, ' ').Trim() + } + if ([string]::IsNullOrWhiteSpace($visible)) { + throw "Partial-page recovery refused: the existing component is not a text web part with content (empty shell). Republish with -Force to back up and overwrite." + } +} + function Publish-SpoPage { [CmdletBinding()] param( @@ -1423,9 +1447,8 @@ function Publish-SpoPage { if ($RecoverPartialPage) { $existingComponents = @(Get-PnPPageComponent -Page $identity.CreateName -ErrorAction Stop) - if ($existingComponents.Count -ne 1) { - throw "Partial-page recovery requires exactly one existing component; found $($existingComponents.Count)." - } + Assert-SpoRecoverableComponent -ExistingComponents $existingComponents ` + -FirstPackageComponent @($package.Components)[0] $page = $identity.CreateName } else { $pageLayout = if ($package.Target.PSObject.Properties["PageLayout"] -and diff --git a/plugins/sharepoint-workbench/tests/test_publish_page_fixes.py b/plugins/sharepoint-workbench/tests/test_publish_page_fixes.py new file mode 100644 index 00000000..bb1183eb --- /dev/null +++ b/plugins/sharepoint-workbench/tests/test_publish_page_fixes.py @@ -0,0 +1,102 @@ +"""Tests for the page planner and publisher fixes found in the CSB news-message pilot. + +Purpose: planner must not re-map image sources it already pointed at an uploaded asset, and must let a caller drop the +BC design-token wrapper; the publisher must read SharePoint's `:` style colons and must refuse to "recover" a page +whose only component is an empty shell. + +Key Input Dependencies: pwsh, scripts/new-page-migration-dry-run.ps1 (modernizing and publishing copies) and +scripts/publish-spo-page.ps1 in publishing-sharepoint-pages (real scripts, no tenant access). +Usage: python -m pytest plugins/sharepoint-workbench/tests/test_publish_page_fixes.py + +Function index: run_planner_with_images, run_publisher_snippet, test_* cases. +""" +import json +import subprocess +from pathlib import Path + +import pytest + +from test_planner_numbered_titles import IDS, PLANNERS, PWSH, SKILLS, run_planner + +PUBLISHER = SKILLS / "publishing-sharepoint-pages" / "scripts" / "publish-spo-page.ps1" +pytestmark = pytest.mark.skipif(PWSH is None, reason="pwsh is required") + +BODY = '

Hello

a' +DESTINATION = "SiteAssets/Sheriff/a.png" + + +def run_planner_with_images(planner: Path, tmp_path: Path, **params) -> dict: + """Plan a page whose image is in the manifest and whose library map also covers the page folder.""" + (tmp_path / "images.json").write_text(json.dumps([{ + "SourceWebPartId": "wp1", "SourceUrl": "https://csb.jag.gov.bc.ca/PublishingImages/a.png", + "DestinationRelativePath": DESTINATION, "OutputFileName": "a.png"}]), encoding="utf-8") + (tmp_path / "map.csv").write_text( + "source_prefix,dest_prefix,status\n/Sheriff/Pages/,/sites/AG-CSB-INTRANET-DEV/SitePages/Sheriff/,planned\n", + encoding="utf-8") + return run_planner( + planner, tmp_path, [("wp1", "Body", BODY)], + ImageManifestPath=tmp_path / "images.json", LibraryPathMapPath=tmp_path / "map.csv", + SourceHost="csb.jag.gov.bc.ca", TargetSitePath="/sites/AG-CSB-INTRANET-DEV", **params) + + +def run_publisher_snippet(snippet: str) -> subprocess.CompletedProcess: + script = f". '{PUBLISHER}'\n{snippet}\n" + return subprocess.run([PWSH, "-NoProfile", "-Command", script], capture_output=True, text=True) + + +@pytest.mark.parametrize("planner", PLANNERS, ids=IDS) +def test_manifest_image_destination_is_not_link_mapped(planner, tmp_path): + plan = run_planner_with_images(planner, tmp_path) + html = " ".join(c["Html"] for c in plan["Components"]) + assert f'src="{DESTINATION}"' in html, html + + +@pytest.mark.parametrize("planner", PLANNERS, ids=IDS) +def test_design_token_wrapper_is_on_by_default(planner, tmp_path): + plan = run_planner_with_images(planner, tmp_path) + assert "data-sp-bc-tokens" in " ".join(c["Html"] for c in plan["Components"]) + + +@pytest.mark.parametrize("planner", PLANNERS, ids=IDS) +def test_design_token_wrapper_can_be_disabled(planner, tmp_path): + plan = run_planner_with_images(planner, tmp_path, NoBcDesignTokens="true") + html = " ".join(c["Html"] for c in plan["Components"]) + assert "data-sp-bc-tokens" not in html and "BC Sans" not in html, html + + +def test_inline_image_dimensions_read_encoded_colon(): + done = run_publisher_snippet( + "$d = Get-SpoInlineImageDimensions -ImageTag ''\n" + "\"$($d.Width)x$($d.Height)\"") + assert done.returncode == 0, done.stderr + assert done.stdout.strip() == "120x60" + + +def test_inline_image_alignment_reads_encoded_colon(): + html = '
' + done = run_publisher_snippet( + f"$h = '{html}'\nGet-SpoInlineImageAlignment -Html $h -ImageIndex $h.IndexOf(' Date: Thu, 5 Nov 2026 23:35:38 -0700 Subject: [PATCH 2/2] docs(map-debt): record publish-page pilot fixes Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- references/map-debt.md | 1 + 1 file changed, 1 insertion(+) diff --git a/references/map-debt.md b/references/map-debt.md index 5f59d459..4d3e1334 100644 --- a/references/map-debt.md +++ b/references/map-debt.md @@ -65,3 +65,4 @@ Persistent tracking of architectural friction, structural anomalies, and unclose | DEBT-20261104-07 | AI topic decomposition needed a provider-neutral, consent-gated, validated path | PARTIAL | M | NO | 2026-11-04 | Step 2 of 4. `scripts/enrichment/decompose.py` is agent-mediated (the host agent answers request files; no API keys, no model calls in code): consent gate, windowed requests, response validation with boundaries snapped to block edges (tables never split), retries and partial completion, verbatim topic files under `ai-navigation/`, `generation.json` with hashes, staleness checks. Tests in `test_enrichment_decompose.py`. **Open:** summaries, hierarchical index, relations, example package (PR 3); evaluation mode and docs (PR 4). | this PR | | DEBT-20261104-08 | Weakly structured documents had no summaries or hierarchical index for progressive discovery | PARTIAL | M | NO | 2026-11-04 | Step 3 of 4. `scripts/enrichment/navigation.py` (agent-mediated): per-topic summaries with keywords and synonyms, chapter/document roll-up and relations built from summaries only, `index.md`, `chapters/`, `navigation.json`, all carrying the AI notice and discovery-only metadata; human approval and a clean validation (notice, trust, pages, links, staleness) gate `publish`. Worked example in `assets/examples/enrichment-example/` built by `build_example.py`. Tests in `test_enrichment_navigation.py`. **Open:** evaluation mode and trust-model docs (PR 4). | this PR | | DEBT-20261104-09 | No way to measure whether structure and AI navigation aids help an agent reach authoritative content | RESOLVED | M | NO | 2026-11-04 | Step 4 of 4. `scripts/enrichment/evaluation.py` compares four arms (native PDF, large Markdown, topic Markdown, topic Markdown plus navigation): agent-mediated task files, run-record validation, deterministic scoring (retrieval accuracy, completeness, citation correctness, tokens, latency, files retrieved, answer length, failures to reach source) and a per-arm report. Trust model and optional workflow documented in `references/enrichment-trust-model.md`. Tests in `test_enrichment_evaluation.py`. **Open:** no evaluation has been run on a real corpus; results would apply to that corpus and agent only. | this PR | +| DEBT-20261105-10 | Page publish: link mapping rewrote uploaded image paths, recovery published an empty shell, `:` styles unread | RESOLVED | M | NO | 2026-11-05 | Found migrating CSB news messages. The planner link mapper rewrote manifest `SiteAssets/...` image paths when the page sat under a mapped `/Pages/` prefix (now left untouched); `-RecoverPartialPage` accepted any single component and published an empty shell (now `Assert-SpoRecoverableComponent` refuses); image size and alignment readers ignored SharePoint's `:` for `:` (now decoded); the planner design-token wrapper had no opt-out (`-NoBcDesignTokens`); the contract wrongly required `-OutputPath` on the single-page publisher. Tests in `test_publish_page_fixes.py`. **Open:** recovery refusal is unit-tested only, not run against a tenant. | this PR |