From 86a1300ec092eb1e0c076e8bc48b02bd300a514e Mon Sep 17 00:00:00 2001 From: Manfred Riem <15701806+mnriem@users.noreply.github.com> Date: Tue, 17 Nov 2026 08:06:34 -0600 Subject: [PATCH 1/5] feat: support preset Markdown section replacement Add bounded exactly-one section replacement for templates and Markdown commands, with shared CLI/helper semantics, explicit diagnostics, and focused regression coverage. Assisted-by: GitHub Copilot (model: GPT-6.1 Sol, autonomous) Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- docs/presets/api.md | 86 ++++++- docs/presets/developing.md | 15 ++ scripts/bash/common.sh | 39 +++- scripts/powershell/common.ps1 | 58 ++++- scripts/python/common.py | 55 ++++- src/specify_cli/artifacts/_operation_info.py | 2 +- src/specify_cli/artifacts/_operation_list.py | 2 +- src/specify_cli/artifacts/mcp_info.py | 2 +- src/specify_cli/artifacts/mcp_list.py | 2 +- src/specify_cli/artifacts/models.py | 2 +- src/specify_cli/markdown_sections.py | 169 ++++++++++++++ src/specify_cli/presets/_manifest.py | 34 ++- src/specify_cli/presets/_resolver.py | 137 ++++++----- src/specify_cli/presets/command_resolve.py | 10 +- src/specify_cli/shared_infra.py | 11 +- tests/integrations/test_cli.py | 20 ++ tests/parity_helpers.py | 44 ++++ tests/specify_cli/artifacts/test_mcp_list.py | 2 +- .../artifacts/test_operation_info.py | 15 ++ .../presets/test_command_resolve.py | 20 ++ .../presets/test_manager_commands.py | 35 +++ tests/specify_cli/presets/test_manifest.py | 33 +++ tests/specify_cli/presets/test_resolver.py | 67 ++++++ tests/test_markdown_sections.py | 95 ++++++++ tests/test_resolve_template_python_parity.py | 219 ++++++++++++++++++ 25 files changed, 1082 insertions(+), 92 deletions(-) create mode 100644 src/specify_cli/markdown_sections.py create mode 100644 tests/test_markdown_sections.py diff --git a/docs/presets/api.md b/docs/presets/api.md index f14fd433ca..af89d1e60f 100644 --- a/docs/presets/api.md +++ b/docs/presets/api.md @@ -58,6 +58,7 @@ provides: | `file` | Yes | Relative path within the preset, with no parent traversal | | `description` | No | Contribution description | | `strategy` | No | Defaults to `replace`; accepted strings are normalized to lowercase | +| `selector` | For `replace-section` only | Non-empty lowercase section anchor; no leading `#` | Template and script names use lowercase letters, digits, and hyphens. Command names additionally permit dots; use names such as `speckit.specify` @@ -138,11 +139,11 @@ against core commands even when a project does not have a ### Composition strategies -| Type | `replace` | `prepend` | `append` | `wrap` | -| --- | --- | --- | --- | --- | -| Template | Default | Supported | Supported | `{CORE_TEMPLATE}` | -| Command | Default | Supported | Supported | `{CORE_TEMPLATE}` | -| Script | Default | Not supported | Not supported | `$CORE_SCRIPT` | +| Type | `replace` | `prepend` | `append` | `wrap` | `replace-section` | +| --- | --- | --- | --- | --- | --- | +| Template | Default | Supported | Supported | `{CORE_TEMPLATE}` | Supported | +| Command | Default | Supported | Supported | `{CORE_TEMPLATE}` | Supported | +| Script | Default | Not supported | Not supported | `$CORE_SCRIPT` | Not supported | A highest-precedence `replace` layer wins entirely. Otherwise, resolution finds the nearest lower `replace` base and applies only the layers above it, @@ -162,6 +163,81 @@ The internal `strategy` key is removed from composed output. The active integration then renders the result in its supported command or skill format. +### Section replacement + +Use `replace-section` to customize one Markdown section without copying the +entire underlying document: + +```yaml +provides: + templates: + - type: template + name: spec-template + file: templates/team-requirements.md + strategy: replace-section + selector: requirements +``` + +The file contains the entire replacement **body**, not the selected heading. +An empty file deletes the body. The body extends from after the heading line +to the next heading at the same or a higher level, or to the end of the +document. Subordinate sections are part of that body. The original heading +and all text outside the body remain unchanged, including line endings. +Supply the blank lines and trailing newline needed before a following heading; +the strategy does not insert separators automatically. + +Declare both strategy and selector in `preset.yml`, not command frontmatter. +`selector` is rejected on other strategies. This is additive under manifest +schema `"1.0"`; set `requires.speckit_version` to a version supporting this +strategy when distributing the preset. + +Selectors use a bounded GitHub-style anchor contract: + +- ATX headings have one to six leading `#` characters, up to three leading + spaces, and whitespace or end of line after the heading markers. Optional + closing hash markers are excluded from the heading text. +- Inline emphasis/code formatting is removed while retaining its text; inline + links contribute their label, not their destination. +- Lowercase the text, remove punctuation/symbols except hyphens and + underscores, retain Unicode letters/numbers, and replace each space with + one hyphen. Repeated spaces are not collapsed. +- `## Review & Approval!` becomes `review--approval`; + `## API_v2 - Notes` becomes `api_v2---notes`; + `## **Café** Guide` becomes `café-guide`. +- Selectors match exactly, with no leading `#`, fuzzy matching, parent path, + or duplicate numbering. Two headings with the same normalized anchor are + ambiguous even at different heading levels. + +Backtick and tilde fenced code is ignored for both matching and section +boundaries. Fences allow up to three leading spaces; closing fences use the +same marker with at least the opening length. Backtick fence info cannot +contain a backtick. An unclosed fence protects the remainder of the document. +Initial YAML metadata is excluded from heading recognition. Setext headings, +HTML headings, and explicit HTML anchor targeting are not supported. + +Replacement applies to the document composed so far, in existing precedence +order. Later higher-precedence section replacements can replace an earlier +replacement of the same body. Section-only command edits preserve the +underlying command frontmatter exactly; section body files do not supply +replacement command metadata. Mixing with other command strategies retains +their established metadata merging behavior. + +Exactly one match is required. Zero matches fail with `SECTION_NOT_FOUND`; +multiple matches fail with `SECTION_AMBIGUOUS`. Diagnostics identify the +preset, contribution file, target artifact, selector, match count, and +remediation. Ambiguous diagnostics include candidate heading text and one-based +line numbers in the document composed at that point. These fields and error +identifiers are stable; prose wording may change. Check selectors/current +headings for missing matches, and make normalized heading anchors unique for +ambiguous matches. No first-match fallback or successful unchanged result is +returned. + +Executable scripts cannot use this strategy. It is not a general Markdown +editor. Runtime template helpers use the same section semantics as the CLI; +command materialization remains the CLI's responsibility. Keep the managed +companion Python helper installed alongside each script variant. Manifest-based +shell composition already requires Python 3 and PyYAML. + ## Command and skill lifecycle Installation copies preset files into `.specify/presets//` and records diff --git a/docs/presets/developing.md b/docs/presets/developing.md index 600d49f719..24c6d0fe0a 100644 --- a/docs/presets/developing.md +++ b/docs/presets/developing.md @@ -85,6 +85,16 @@ resolved lower-priority content, not necessarily unmodified core content. An append, prepend, or wrap contribution needs a lower `replace` base; a new self-contained command normally uses `replace`. +To change only an existing section's body, use `strategy: replace-section` +with `selector: requirements` (for a heading such as `## Requirements`). +Point `file` to a Markdown fragment containing only the new body, including +any desired blank lines; do not copy the heading or the whole template. +The same strategy supports Markdown commands but not executable scripts. +Exactly one heading must match: missing or duplicate normalized anchors fail +explicitly. See [section replacement](api.md#section-replacement) for anchor +normalization, nested-section boundaries, fenced-code safeguards, diagnostics, +and composition order. + Declare extension dependencies in `preset.yml` when the preset relies on extension capabilities. A namespace alone does not establish a dependency or suppress registration. See the API reference for warning behavior and @@ -172,6 +182,11 @@ behavior and failures; PowerShell scripts must target Windows PowerShell 5.1. Do not expect enable, disable, or priority changes alone to rewrite already delivered command or skill files. +For section replacement, test that an unrelated upstream section update flows +through unchanged. Also test a renamed target and duplicate normalized headings: +both must fail instead of silently publishing an unchanged or partial document. +Check the installed runtime helper as well as CLI composition. + After editing the development source, install a fresh copy. `--dev` does not watch or link it: diff --git a/scripts/bash/common.sh b/scripts/bash/common.sh index ff18cba4d9..55bcffa25c 100644 --- a/scripts/bash/common.sh +++ b/scripts/bash/common.sh @@ -633,6 +633,11 @@ resolve_template_content() { # Collect all layers (highest priority first) local -a layer_paths=() local -a layer_strategies=() + local -a layer_selectors=() + local -a layer_presets=() + local section_engine + section_engine="$(dirname "${BASH_SOURCE[0]}")/markdown_sections.py" + [ -f "$section_engine" ] || section_engine="$(dirname "${BASH_SOURCE[0]}")/../../src/specify_cli/markdown_sections.py" # Priority 1: Project overrides (always "replace") local override="$base/overrides/${template_name}.md" @@ -694,6 +699,7 @@ except Exception: if [ -n "$sorted_presets" ]; then while IFS= read -r preset_id; do local strategy="replace" + local selector="" local manifest_file="" local manifest="$presets_dir/$preset_id/preset.yml" local manifest_declared=false @@ -706,8 +712,8 @@ except Exception: local py_stderr local parse_status py_stderr=$(mktemp) - if result=$(SPECKIT_MANIFEST="$manifest" SPECKIT_TMPL="$template_name" "${python_cmd[@]}" -c " -import sys, os + if result=$(SPECKIT_MANIFEST="$manifest" SPECKIT_TMPL="$template_name" SPECKIT_SECTION_ENGINE="$section_engine" "${python_cmd[@]}" -c " +import sys, os, base64 try: import yaml except ImportError: @@ -731,7 +737,7 @@ try: if not templates: raise ValueError('manifest must provide at least one template') valid_types = ('template', 'command', 'script') - valid_strategies = ('replace', 'prepend', 'append', 'wrap') + valid_strategies = ('replace', 'prepend', 'append', 'wrap', 'replace-section') for t in templates: if not isinstance(t, dict): raise ValueError('manifest template entries must be mappings') @@ -750,11 +756,16 @@ try: raise ValueError('invalid manifest template strategy') if t['type'] == 'script' and strategy not in ('replace', 'wrap'): raise ValueError('invalid manifest script strategy') + if strategy == 'replace-section' or 'selector' in t: + import runpy + engine = runpy.run_path(os.environ['SPECKIT_SECTION_ENGINE']) + engine['validate_section_selector'](strategy, t.get('selector'), present='selector' in t) for t in templates: if t.get('name') == os.environ['SPECKIT_TMPL'] and t.get('type', 'template') == 'template': file_value = t.get('file', '') strategy = t.get('strategy', 'replace') - print('found\t' + strategy + '\t' + file_value) + selector = base64.b64encode(t.get('selector', '').encode('utf-8')).decode('ascii') + print('found\t' + strategy + '\t' + file_value + '\t' + selector) sys.exit(0) print('absent\treplace\t') except Exception as exc: @@ -770,13 +781,14 @@ except Exception as exc: echo "Error: PyYAML is required to resolve preset template composition" >&2 else echo "Error: invalid preset manifest $manifest" >&2 + cat "$py_stderr" >&2 fi rm -f "$py_stderr" return 2 fi if [ -n "$result" ]; then local declaration - IFS=$'\t' read -r declaration strategy manifest_file <<< "$result" + IFS=$'\t' read -r declaration strategy manifest_file selector <<< "$result" [ "$declaration" = "found" ] && manifest_declared=true strategy=$(printf '%s' "$strategy" | tr '[:upper:]' '[:lower:]') fi @@ -804,6 +816,8 @@ except Exception as exc: if [ -n "$candidate" ]; then layer_paths+=("$candidate") layer_strategies+=("$strategy") + layer_selectors+=("$selector") + layer_presets+=("$preset_id") if [ "$strategy" = "replace" ]; then effective_base_found=true break @@ -828,6 +842,8 @@ except Exception as exc: if [ -f "$candidate" ]; then layer_paths+=("$candidate") layer_strategies+=("replace") + layer_selectors+=("") + layer_presets+=("$extension_id") effective_base_found=true break fi @@ -839,6 +855,8 @@ except Exception as exc: if [ "$effective_base_found" = false ] && [ -f "$core" ]; then layer_paths+=("$core") layer_strategies+=("replace") + layer_selectors+=("") + layer_presets+=("core") fi local count=${#layer_paths[@]} @@ -904,6 +922,17 @@ except Exception as exc: layer_content="${layer_content%x}" case "$strat" in + replace-section) + if ! content=$( + printf '%s' "$content" | "${python_cmd[@]}" "$section_engine" \ + --preset "${layer_presets[$i]}" --artifact "$template_name" \ + --selector-base64 -- "${layer_selectors[$i]}" "$path" + status=$?; printf x; exit "$status" + ); then + return 2 + fi + content="${content%x}" + ;; replace) content="$layer_content" ;; prepend) content=$(printf '%s\n\n%s' "$layer_content" "$content"; printf x) diff --git a/scripts/powershell/common.ps1 b/scripts/powershell/common.ps1 index 0f254cbdec..b77d933b00 100644 --- a/scripts/powershell/common.ps1 +++ b/scripts/powershell/common.ps1 @@ -544,6 +544,12 @@ function Resolve-TemplateContent { # Collect all layers (highest priority first) $layerPaths = @() $layerStrategies = @() + $layerSelectors = @() + $layerPresets = @() + $sectionEngine = Join-Path $PSScriptRoot 'markdown_sections.py' + if (-not (Test-Path -LiteralPath $sectionEngine)) { + $sectionEngine = Join-Path $PSScriptRoot '../../src/specify_cli/markdown_sections.py' + } # Priority 1: Project overrides (always "replace") $override = Join-Path $base "overrides/$TemplateName.md" @@ -612,6 +618,7 @@ function Resolve-TemplateContent { foreach ($presetId in $sortedPresets) { # Read strategy and file path from preset manifest $strategy = 'replace' + $selector = '' $manifestFilePath = '' $manifestDeclared = $false $manifest = Join-Path $presetsDir "$presetId/preset.yml" @@ -624,7 +631,7 @@ function Resolve-TemplateContent { $pyArgs = if ($pyCmd.Count -gt 1) { $pyCmd[1..($pyCmd.Count-1)] } else { @() } $pyStderrFile = [System.IO.Path]::GetTempFileName() $stratResult = & $pyCmd[0] @pyArgs -c @" -import sys +import sys, base64 try: import yaml except ImportError: @@ -648,7 +655,7 @@ try: if not templates: raise ValueError('manifest must provide at least one template') valid_types = ('template', 'command', 'script') - valid_strategies = ('replace', 'prepend', 'append', 'wrap') + valid_strategies = ('replace', 'prepend', 'append', 'wrap', 'replace-section') for t in templates: if not isinstance(t, dict): raise ValueError('manifest template entries must be mappings') @@ -667,28 +674,35 @@ try: raise ValueError('invalid manifest template strategy') if t['type'] == 'script' and strategy not in ('replace', 'wrap'): raise ValueError('invalid manifest script strategy') + if strategy == 'replace-section' or 'selector' in t: + import runpy + engine = runpy.run_path(sys.argv[3]) + engine['validate_section_selector'](strategy, t.get('selector'), present='selector' in t) for t in templates: if t.get('name') == sys.argv[2] and t.get('type', 'template') == 'template': file_value = t.get('file', '') strategy = t.get('strategy', 'replace') - print('found\t' + strategy + '\t' + file_value) + selector = base64.b64encode(t.get('selector', '').encode('utf-8')).decode('ascii') + print('found\t' + strategy + '\t' + file_value + '\t' + selector) sys.exit(0) print('absent\treplace\t') except Exception as exc: print(f'manifest_invalid: {exc}', file=sys.stderr) sys.exit(3) -"@ $manifest $TemplateName 2>$pyStderrFile +"@ $manifest $TemplateName $sectionEngine 2>$pyStderrFile if ($LASTEXITCODE -ne 0) { if ($LASTEXITCODE -eq 2) { throw "PyYAML is required to resolve preset template composition" } - throw "Invalid preset manifest $manifest" + $detail = [System.IO.File]::ReadAllText($pyStderrFile, [System.Text.Encoding]::UTF8) + throw "Invalid preset manifest ${manifest}: $detail" } if ($stratResult) { - $parts = $stratResult.Trim() -split "`t", 3 + $parts = $stratResult.Trim() -split "`t", 4 $manifestDeclared = $parts[0] -eq 'found' $strategy = $parts[1].ToLowerInvariant() if ($parts.Count -gt 2 -and $parts[2]) { $manifestFilePath = $parts[2] } + if ($parts.Count -gt 3) { $selector = $parts[3] } } Remove-Item -LiteralPath $pyStderrFile -Force -ErrorAction SilentlyContinue } catch { @@ -719,6 +733,8 @@ except Exception as exc: if ($candidate) { $layerPaths += $candidate $layerStrategies += $strategy + $layerSelectors += $selector + $layerPresets += $presetId if ($strategy -eq 'replace') { $effectiveBaseFound = $true break @@ -738,6 +754,8 @@ except Exception as exc: if (Test-Path -LiteralPath $candidate) { $layerPaths += $candidate $layerStrategies += 'replace' + $layerSelectors += '' + $layerPresets += $extensionId $effectiveBaseFound = $true break } @@ -749,6 +767,8 @@ except Exception as exc: if (-not $effectiveBaseFound -and (Test-Path -LiteralPath $core)) { $layerPaths += $core $layerStrategies += 'replace' + $layerSelectors += '' + $layerPresets += 'core' } if ($layerPaths.Count -eq 0) { return $null } @@ -796,6 +816,32 @@ except Exception as exc: ) switch ($strat) { + 'replace-section' { + $inputFile = [System.IO.Path]::GetTempFileName() + $outputFile = [System.IO.Path]::GetTempFileName() + $errorFile = [System.IO.Path]::GetTempFileName() + try { + $utf8 = New-Object System.Text.UTF8Encoding($false) + [System.IO.File]::WriteAllText($inputFile, $content, $utf8) + $pyArgs = if ($pyCmd.Count -gt 1) { $pyCmd[1..($pyCmd.Count-1)] } else { @() } + $savedErrorActionPreference = $ErrorActionPreference + try { + $ErrorActionPreference = 'Continue' + & $pyCmd[0] @pyArgs $sectionEngine ` + --preset $layerPresets[$i] --artifact $TemplateName ` + --input $inputFile --output $outputFile ` + --selector-base64 -- $layerSelectors[$i] $path 2>$errorFile + } finally { + $ErrorActionPreference = $savedErrorActionPreference + } + if ($LASTEXITCODE -ne 0) { + throw [System.IO.File]::ReadAllText($errorFile, [System.Text.Encoding]::UTF8) + } + $content = [System.IO.File]::ReadAllText($outputFile, [System.Text.Encoding]::UTF8) + } finally { + Remove-Item -LiteralPath $inputFile, $outputFile, $errorFile -Force + } + } 'replace' { $content = $layerContent } 'prepend' { $content = "$layerContent`n`n$content" } 'append' { $content = "$content`n`n$layerContent" } diff --git a/scripts/python/common.py b/scripts/python/common.py index 0cd17e013d..928f969772 100644 --- a/scripts/python/common.py +++ b/scripts/python/common.py @@ -2,13 +2,16 @@ from __future__ import annotations +import importlib.util import json import os import re import subprocess import sys from dataclasses import dataclass +from functools import lru_cache from pathlib import Path +from types import ModuleType def _trim_trailing_separators(value: Path) -> str: @@ -360,10 +363,26 @@ class TemplateResolutionError(RuntimeError): # Mirror the canonical PresetManifest contract (see src/specify_cli/presets) # so runtime resolution rejects the same structurally malformed manifests. _VALID_TEMPLATE_TYPES = ("template", "command", "script") -_VALID_TEMPLATE_STRATEGIES = ("replace", "prepend", "append", "wrap") +_VALID_TEMPLATE_STRATEGIES = ("replace", "prepend", "append", "wrap", "replace-section") _VALID_SCRIPT_STRATEGIES = ("replace", "wrap") +@lru_cache(maxsize=1) +def _section_engine() -> ModuleType: + path = Path(__file__).with_name("markdown_sections.py") + if not path.is_file(): + path = Path(__file__).resolve().parents[2] / "src/specify_cli/markdown_sections.py" + spec = importlib.util.spec_from_file_location("speckit_markdown_sections", path) + if spec is None or spec.loader is None: + raise TemplateResolutionError(f"Could not load section engine: {path}") + module = importlib.util.module_from_spec(spec) + try: + spec.loader.exec_module(module) + except OSError as exc: + raise TemplateResolutionError(f"Could not load section engine: {path}: {exc}") from exc + return module + + def _validate_manifest_template_entry(entry: object) -> None: """Validate a single manifest template entry against the canonical rules.""" if not isinstance(entry, dict): @@ -385,6 +404,10 @@ def _validate_manifest_template_entry(entry: object) -> None: raise ValueError( f"invalid manifest script strategy '{strategy}'" ) + if strategy == "replace-section" or "selector" in entry: + _section_engine().validate_section_selector( + strategy, entry.get("selector"), present="selector" in entry, + ) class _DelegatedYAMLError(Exception): @@ -422,7 +445,7 @@ class _DelegatedYAML: is launched with). See #4443. Only ``_preset_template_layer`` calls this, and only the ``type``, - ``name``, ``file``, and ``strategy`` fields of each ``provides.templates`` + ``name``, ``file``, ``strategy``, and ``selector`` fields of each ``provides.templates`` entry are ever inspected, so the child drops every other top-level manifest field (e.g. free-form ``metadata``) and every other per-entry field (e.g. ``description``) before serializing: a valid, ignored YAML @@ -466,7 +489,7 @@ def safe_load(self, text: str) -> object: " if not isinstance(entry, dict):\n" " return _default(entry)\n" " fields = {}\n" - " for k in ('type', 'name', 'file', 'strategy'):\n" + " for k in ('type', 'name', 'file', 'strategy', 'selector'):\n" " if k not in entry:\n" " continue\n" " v = entry[k]\n" @@ -554,13 +577,13 @@ def _import_yaml() -> object | None: def _preset_template_layer( preset_dir: Path, template_name: str -) -> tuple[Path, str] | None: +) -> tuple[Path, str, str | None, str] | None: """Return the preset template path and composition strategy.""" manifest_path = preset_dir / "preset.yml" conventional = _conventional_template(preset_dir, template_name) if not manifest_path.is_file(): - return (conventional, "replace") if conventional is not None else None + return (conventional, "replace", None, preset_dir.name) if conventional is not None else None yaml = _import_yaml() if yaml is None: @@ -600,13 +623,13 @@ def _preset_template_layer( candidate = preset_dir / relative if not candidate.is_file(): return None - return candidate, strategy.lower() + return candidate, strategy.lower(), entry.get("selector"), preset_dir.name except (OSError, UnicodeError, ValueError, yaml.YAMLError) as exc: raise TemplateResolutionError( f"Failed to parse preset manifest {manifest_path}: {exc}" ) from exc - return (conventional, "replace") if conventional is not None else None + return (conventional, "replace", None, preset_dir.name) if conventional is not None else None def resolve_template_content(template_name: str, repo_root: Path) -> str | None: @@ -614,12 +637,12 @@ def resolve_template_content(template_name: str, repo_root: Path) -> str | None: if not _is_safe_component(template_name): return None - layers: list[tuple[Path, str]] = [] + layers: list[tuple[Path, str, str | None, str]] = [] def compose_from_base() -> str: try: content = layers[-1][0].read_bytes().decode("utf-8") - for path, strategy in reversed(layers[:-1]): + for path, strategy, selector, preset in reversed(layers[:-1]): layer_content = path.read_bytes().decode("utf-8") if strategy == "prepend": content = f"{layer_content}\n\n{content}" @@ -632,6 +655,14 @@ def compose_from_base() -> str: f"Wrap layer {path} is missing {placeholder}" ) content = layer_content.replace(placeholder, content) + elif strategy == "replace-section": + try: + content = _section_engine().replace_section( + content, layer_content, selector, preset=preset, + contribution=str(path), artifact=template_name, + ) + except ValueError as exc: + raise TemplateResolutionError(str(exc)) from exc else: raise TemplateResolutionError( f"Unknown template composition strategy '{strategy}' in {path}" @@ -650,7 +681,7 @@ def compose_from_base() -> str: / f"{template_name}.md" ) if override.is_file(): - layers.append((override, "replace")) + layers.append((override, "replace", None, "project override")) return compose_from_base() presets_dir = repo_root / ".specify" / "presets" @@ -666,12 +697,12 @@ def compose_from_base() -> str: extension_dir = extensions_dir / extension_id candidate = _conventional_template(extension_dir, template_name) if candidate is not None: - layers.append((candidate, "replace")) + layers.append((candidate, "replace", None, extension_id)) return compose_from_base() core = repo_root / ".specify" / "templates" / f"{template_name}.md" if core.is_file(): - layers.append((core, "replace")) + layers.append((core, "replace", None, "core")) return compose_from_base() if not layers: diff --git a/src/specify_cli/artifacts/_operation_info.py b/src/specify_cli/artifacts/_operation_info.py index 9993ec67b2..b13accdbc0 100644 --- a/src/specify_cli/artifacts/_operation_info.py +++ b/src/specify_cli/artifacts/_operation_info.py @@ -326,7 +326,7 @@ def _convert_named_stack( or not _is_optional_string(item["sourceId"]) or not _is_optional_string(item["presetId"]) or not _is_optional_string(item["presetName"]) - or item["strategy"] not in ("replace", "wrap", "prepend", "append") + or item["strategy"] not in ("replace", "wrap", "prepend", "append", "replace-section") or not isinstance(item["active"], bool) or not isinstance(item["hidden"], bool) or not _is_optional_string(item["manifestPath"]) diff --git a/src/specify_cli/artifacts/_operation_list.py b/src/specify_cli/artifacts/_operation_list.py index 91afd43347..9d9a080470 100644 --- a/src/specify_cli/artifacts/_operation_list.py +++ b/src/specify_cli/artifacts/_operation_list.py @@ -24,7 +24,7 @@ class ArtifactListStackEntry(TypedDict): sourceId: str | None presetId: str | None presetName: str | None - strategy: Literal["replace", "wrap", "prepend", "append"] + strategy: Literal["replace", "wrap", "prepend", "append", "replace-section"] active: bool hidden: bool manifestPath: str | None diff --git a/src/specify_cli/artifacts/mcp_info.py b/src/specify_cli/artifacts/mcp_info.py index 8a5b308ade..c2bc5e5d07 100644 --- a/src/specify_cli/artifacts/mcp_info.py +++ b/src/specify_cli/artifacts/mcp_info.py @@ -68,7 +68,7 @@ class ArtifactInfoStackEntryResult(BaseModel): sourceId: str | None presetId: str | None presetName: str | None - strategy: Literal["replace", "wrap", "prepend", "append"] + strategy: Literal["replace", "wrap", "prepend", "append", "replace-section"] active: bool hidden: bool manifestPath: str | None diff --git a/src/specify_cli/artifacts/mcp_list.py b/src/specify_cli/artifacts/mcp_list.py index bb1dd13694..feeb330390 100644 --- a/src/specify_cli/artifacts/mcp_list.py +++ b/src/specify_cli/artifacts/mcp_list.py @@ -72,7 +72,7 @@ class ArtifactListStackEntryResult(BaseModel): sourceId: str | None presetId: str | None presetName: str | None - strategy: Literal["replace", "wrap", "prepend", "append"] + strategy: Literal["replace", "wrap", "prepend", "append", "replace-section"] active: bool hidden: bool manifestPath: str | None diff --git a/src/specify_cli/artifacts/models.py b/src/specify_cli/artifacts/models.py index 737cd2df62..f1fb651c01 100644 --- a/src/specify_cli/artifacts/models.py +++ b/src/specify_cli/artifacts/models.py @@ -8,7 +8,7 @@ ArtifactKind = Literal["command", "template", "script", "hook"] LayerName = Literal["project", "preset", "extension"] -Strategy = Literal["replace", "wrap", "prepend", "append"] +Strategy = Literal["replace", "wrap", "prepend", "append", "replace-section"] HookLayerName = Literal["preset", "extension"] diff --git a/src/specify_cli/markdown_sections.py b/src/specify_cli/markdown_sections.py new file mode 100644 index 0000000000..634cd9c666 --- /dev/null +++ b/src/specify_cli/markdown_sections.py @@ -0,0 +1,169 @@ +"""Bounded Markdown section replacement, also shipped with standalone helpers.""" + +from __future__ import annotations + +import base64 +import json +import re +import unicodedata +from pathlib import Path +from typing import TypedDict + + +class SectionCandidate(TypedDict): + heading: str + line: int + + +class SectionDiagnostic(TypedDict): + code: str + preset: str + contribution: str + artifact: str + selector: str + match_count: int + candidates: list[SectionCandidate] + remediation: str + + +class SectionReplacementError(ValueError): + """A section selector did not identify exactly one eligible heading.""" + + def __init__(self, details: SectionDiagnostic): + self.details = details + super().__init__(json.dumps(details, ensure_ascii=True)) + + +def validate_section_selector(strategy: str, selector: object, *, present: bool) -> None: + """Validate opt-in selector metadata without silently changing strategies.""" + if strategy != "replace-section": + if present: + raise ValueError("selector is only valid with strategy 'replace-section'") + return + if ( + not isinstance(selector, str) + or not selector + or selector != selector.lower() + or any( + char not in "-_" and unicodedata.category(char)[0] not in "LN" + for char in selector + ) + ): + raise ValueError( + "replace-section selector must be a non-empty lowercase anchor " + "(letters, numbers, hyphens, underscores; no leading #)" + ) + + +def _anchor(text: str) -> str: + text = re.sub(r"!?\[([^\]]*)\]\([^)\r\n]*\)", r"\1", text) + text = re.sub(r"(`+)(.*?)\1", r"\2", text) + text = re.sub(r"(\*{1,2}|~~)(.*?)\1", r"\2", text) + text = re.sub(r"(? str: + """Replace one ATX section body without rewriting any surrounding text.""" + validate_section_selector("replace-section", selector, present=True) + headings: list[tuple[int, str, int, int, int]] = [] + fence_marker = "" + fence_length = 0 + metadata = content.startswith(("---\n", "---\r\n")) + offset = 0 + for number, line in enumerate(content.splitlines(keepends=True), 1): + start = offset + offset += len(line) + text = line.rstrip("\r\n") + if metadata: + if number > 1 and text == "---": + metadata = False + continue + if fence_marker: + closing = re.fullmatch(r" {0,3}(`+|~+)[ \t]*", text) + if closing and closing[1][0] == fence_marker and len(closing[1]) >= fence_length: + fence_marker = "" + continue + opening = re.match(r" {0,3}(`{3,}|~{3,})(.*)$", text) + if opening and not (opening[1][0] == "`" and "`" in opening[2]): + fence_marker, fence_length = opening[1][0], len(opening[1]) + continue + heading = re.fullmatch(r" {0,3}(#{1,6})(?:[ \t]+(.*?)|)[ \t]*", text) + if heading: + title = re.sub(r"[ \t]+#+[ \t]*$", "", heading[2] or "").strip(" \t") + headings.append((len(heading[1]), title, number, start, offset)) + + matches = [index for index, heading in enumerate(headings) if _anchor(heading[1]) == selector] + if len(matches) != 1: + raise SectionReplacementError({ + "code": "SECTION_NOT_FOUND" if not matches else "SECTION_AMBIGUOUS", + "preset": preset, + "contribution": contribution, + "artifact": artifact, + "selector": selector, + "match_count": len(matches), + "candidates": [ + {"heading": headings[index][1], "line": headings[index][2]} + for index in matches + ], + "remediation": ( + "Check the selector and current target headings." + if not matches else "Make the target heading anchors unique." + ), + }) + + index = matches[0] + level, _, _, _, body_start = headings[index] + body_end = next( + (heading[3] for heading in headings[index + 1:] if heading[0] <= level), + len(content), + ) + return content[:body_start] + replacement + content[body_end:] + + +def _main() -> int: + import argparse + import sys + + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("selector") + parser.add_argument("replacement", type=Path) + parser.add_argument("--preset", required=True) + parser.add_argument("--artifact", required=True) + parser.add_argument("--input", type=Path) + parser.add_argument("--output", type=Path) + parser.add_argument("--selector-base64", action="store_true") + args = parser.parse_args() + try: + content = args.input.read_bytes() if args.input else sys.stdin.buffer.read() + result = replace_section( + content.decode("utf-8"), args.replacement.read_bytes().decode("utf-8"), + base64.b64decode(args.selector, validate=True).decode("utf-8") + if args.selector_base64 else args.selector, + preset=args.preset, contribution=str(args.replacement), + artifact=args.artifact, + ).encode("utf-8") + if args.output: + args.output.write_bytes(result) + else: + sys.stdout.buffer.write(result) + except (OSError, UnicodeError, ValueError) as exc: + print(str(exc), file=sys.stderr) + return 2 + return 0 + + +if __name__ == "__main__": + raise SystemExit(_main()) diff --git a/src/specify_cli/presets/_manifest.py b/src/specify_cli/presets/_manifest.py index 6cd7d0d54e..e2a244a931 100644 --- a/src/specify_cli/presets/_manifest.py +++ b/src/specify_cli/presets/_manifest.py @@ -10,6 +10,7 @@ from packaging import version as pkg_version from packaging.specifiers import InvalidSpecifier, SpecifierSet +from ..markdown_sections import validate_section_selector class PresetError(Exception): """Base exception for preset-related errors.""" @@ -21,13 +22,17 @@ class PresetValidationError(PresetError): pass +class PresetSectionValidationError(PresetValidationError): + """Section declarations must never fall back to whole-file replacement.""" + + class PresetCompatibilityError(PresetError): """Raised when preset is incompatible with current environment.""" pass VALID_PRESET_TEMPLATE_TYPES = {"template", "command", "script"} -VALID_PRESET_STRATEGIES = {"replace", "prepend", "append", "wrap"} +VALID_PRESET_STRATEGIES = {"replace", "prepend", "append", "wrap", "replace-section"} # Scripts only support replace and wrap (prepend/append don't make semantic sense for executable code) VALID_SCRIPT_STRATEGIES = {"replace", "wrap"} @@ -49,7 +54,24 @@ def __init__(self, manifest_path: Path): """ self.path = manifest_path self.data = self._load_yaml(manifest_path) - self._validate() + provides = self.data.get("provides") + entries = provides.get("templates") if isinstance(provides, dict) else None + section_metadata = isinstance(entries, list) and any( + isinstance(entry, dict) and ( + "selector" in entry + or ( + isinstance(entry.get("strategy"), str) + and entry["strategy"].lower() == "replace-section" + ) + ) + for entry in entries + ) + try: + self._validate() + except PresetValidationError as exc: + if section_metadata: + raise PresetSectionValidationError(str(exc)) from exc + raise def _load_yaml(self, path: Path) -> dict: """Load YAML file safely.""" @@ -263,6 +285,14 @@ def _validate(self): f"Invalid strategy '{strategy}' for script: " f"scripts only support {sorted(VALID_SCRIPT_STRATEGIES)}" ) + try: + validate_section_selector( + strategy, tmpl.get("selector"), present="selector" in tmpl + ) + except ValueError as exc: + raise PresetValidationError( + f"Invalid template '{tmpl['name']}' in {self.path}: {exc}" + ) from exc # Validate template name format if tmpl["type"] == "command": diff --git a/src/specify_cli/presets/_resolver.py b/src/specify_cli/presets/_resolver.py index 5700fa8378..62b04c1053 100644 --- a/src/specify_cli/presets/_resolver.py +++ b/src/specify_cli/presets/_resolver.py @@ -8,7 +8,13 @@ from .._utils import dump_frontmatter from ..extensions import ExtensionRegistry, normalize_priority -from ._manifest import VALID_PRESET_STRATEGIES, PresetManifest, PresetValidationError +from ..markdown_sections import SectionReplacementError, replace_section +from ._manifest import ( + VALID_PRESET_STRATEGIES, + PresetManifest, + PresetSectionValidationError, + PresetValidationError, +) from ._registry import PresetRegistry @@ -43,6 +49,8 @@ def _get_manifest(self, pack_dir: Path) -> Optional["PresetManifest"]: if manifest_path.exists(): try: self._manifest_cache[key] = PresetManifest(manifest_path) + except PresetSectionValidationError: + raise except PresetValidationError: self._manifest_cache[key] = None else: @@ -601,6 +609,11 @@ def _find_in_subdirs(base_dir: Path) -> Optional[Path]: fm_data = yaml.safe_load(fm_text) if isinstance(fm_data, dict): fm_strategy = fm_data.get("strategy") + if isinstance(fm_strategy, str) and fm_strategy.lower() == "replace-section": + raise PresetSectionValidationError( + f"Declare replace-section and selector in {pack_dir / 'preset.yml'}, " + "not command frontmatter" + ) if isinstance(fm_strategy, str) and fm_strategy.lower() in VALID_PRESET_STRATEGIES: strategy = fm_strategy.lower() except (UnicodeDecodeError, yaml.YAMLError, OSError): @@ -612,6 +625,8 @@ def _find_in_subdirs(base_dir: Path) -> Optional[Path]: "path": candidate, "source": f"{pack_id} v{version}", "strategy": strategy, + **({"selector": entry["selector"], "preset_id": pack_id} + if strategy == "replace-section" and entry else {}), }) # Priority 3: Extension-provided templates (always "replace") @@ -759,6 +774,12 @@ def resolve_content( if not layers: return None + section_composition = False + for layer in layers: + if layer["strategy"] == "replace": + break + section_composition |= layer["strategy"] == "replace-section" + def _read_layer_content(layer: Dict[str, Any]) -> Optional[str]: """Read a layer's raw text, rewriting extension-relative subdir references (agents/, knowledge-base/, etc.) to their installed @@ -778,8 +799,15 @@ def _read_layer_content(layer: Dict[str, Any]) -> Optional[str]: not a raw UnicodeDecodeError at composition time. """ try: - text = layer["path"].read_text(encoding="utf-8") - except (OSError, UnicodeDecodeError): + text = ( + layer["path"].read_bytes().decode("utf-8") if section_composition + else layer["path"].read_text(encoding="utf-8") + ) + except (OSError, UnicodeDecodeError) as exc: + if section_composition: + raise PresetSectionValidationError( + f"Could not read section composition layer {layer['path']}: {exc}" + ) from exc return None extension_id = layer.get("extension_id") extension_dir = layer.get("extension_dir") @@ -813,6 +841,10 @@ def _read_layer_content(layer: Dict[str, Any]) -> Optional[str]: break if base_layer_idx is None: + if section_composition: + raise PresetSectionValidationError( + f"Template '{template_name}' has section replacements but no replace base" + ) return None # no replace base found # Convert to reversed_layers index @@ -827,7 +859,10 @@ def _read_layer_content(layer: Dict[str, Any]) -> Optional[str]: # For command composition, strip frontmatter from each layer to avoid # leaking YAML metadata into the composed body. The highest-priority # layer's frontmatter will be reattached at the end. - is_command = template_type == "command" + is_command = template_type == "command" and any( + layer["strategy"] != "replace-section" + for layer in layers[:base_layer_idx] + ) top_frontmatter_text = None base_frontmatter_text = None @@ -861,16 +896,58 @@ def _split_frontmatter(text: str) -> tuple: base_frontmatter_text = fm content = body + def _render_command(body: str) -> str: + if not is_command or not top_frontmatter_text: + return body + + def _parse_fm_yaml(fm_block: str) -> dict: + try: + parsed = yaml.safe_load("\n".join(fm_block.splitlines()[1:-1])) or {} + except yaml.YAMLError: + return {} + return parsed if isinstance(parsed, dict) else {} + + top_fm = _parse_fm_yaml(top_frontmatter_text) + if base_frontmatter_text and base_frontmatter_text != top_frontmatter_text: + base_fm = _parse_fm_yaml(base_frontmatter_text) + for key in ("scripts", "agent_scripts", "argument-hint"): + if key not in top_fm and key in base_fm: + top_fm[key] = base_fm[key] + top_fm.pop("strategy", None) + if not top_fm: + return body + return "---\n" + dump_frontmatter(top_fm) + "\n---\n\n" + body + # Apply composition layers from bottom to top for layer in reversed_layers[start_idx:]: try: - layer_content = layer["path"].read_text(encoding="utf-8") - except (OSError, UnicodeDecodeError): + layer_content = ( + layer["path"].read_bytes().decode("utf-8") if section_composition + else layer["path"].read_text(encoding="utf-8") + ) + except (OSError, UnicodeDecodeError) as exc: + if section_composition: + raise PresetSectionValidationError( + f"Could not read section composition layer {layer['path']}: {exc}" + ) from exc # Same tolerance as _read_layer_content: an unreadable layer # means the composed result cannot be produced. return None strategy = layer["strategy"] + if strategy == "replace-section": + command_prefix = _render_command("") + try: + content = replace_section( + command_prefix + content, layer_content, layer["selector"], + preset=layer["preset_id"], contribution=str(layer["path"]), + artifact=template_name, + ) + except SectionReplacementError as exc: + raise PresetSectionValidationError(str(exc)) from exc + content = content[len(command_prefix):] + continue + if is_command: fm, layer_body = _split_frontmatter(layer_content) layer_content = layer_body @@ -903,50 +980,4 @@ def _split_frontmatter(text: str) -> tuple: ) content = layer_content.replace(placeholder, content) - # Reattach the highest-priority frontmatter for commands, - # inheriting scripts/agent_scripts from the base if missing - # and stripping the strategy key (internal-only, not for agent output). - if is_command and top_frontmatter_text: - def _parse_fm_yaml(fm_block: str) -> dict: - """Parse YAML from a frontmatter block (with --- fences).""" - lines = fm_block.splitlines() - # Parse only interior lines (between --- fences) - if len(lines) >= 2: - yaml_lines = lines[1:-1] - else: - yaml_lines = [] - try: - parsed = yaml.safe_load("\n".join(yaml_lines)) or {} - except yaml.YAMLError: - return {} - # Valid YAML that is not a mapping is treated like invalid - # frontmatter, matching CommandRegistrar.parse_frontmatter. - return parsed if isinstance(parsed, dict) else {} - - top_fm = _parse_fm_yaml(top_frontmatter_text) - - # Inherit scripts/agent_scripts from base frontmatter if missing - if base_frontmatter_text and base_frontmatter_text != top_frontmatter_text: - base_fm = _parse_fm_yaml(base_frontmatter_text) - for key in ("scripts", "agent_scripts", "argument-hint"): - if key not in top_fm and key in base_fm: - top_fm[key] = base_fm[key] - - # Strip strategy key — it's an internal composition directive, - # not meant for rendered agent command files - top_fm.pop("strategy", None) - - if top_fm: - top_frontmatter_text = ( - "---\n" - + dump_frontmatter(top_fm) - + "\n---" - ) - else: - # Empty frontmatter — omit rather than emitting {} - top_frontmatter_text = None - - if top_frontmatter_text: - content = top_frontmatter_text + "\n\n" + content - - return content + return _render_command(content) diff --git a/src/specify_cli/presets/command_resolve.py b/src/specify_cli/presets/command_resolve.py index 7256307160..688b87398d 100644 --- a/src/specify_cli/presets/command_resolve.py +++ b/src/specify_cli/presets/command_resolve.py @@ -9,6 +9,7 @@ from .._console import console from ._commands import preset_app +from ._manifest import PresetSectionValidationError @preset_app.command("resolve") @@ -40,7 +41,11 @@ def preset_resolve( resolver = PresetResolver(project_root) template_type = "command" if is_command else "template" - layers = resolver.collect_all_layers(template_name, template_type) + try: + layers = resolver.collect_all_layers(template_name, template_type) + except PresetSectionValidationError as exc: + typer.echo(f"Error: {exc}", err=True) + raise typer.Exit(1) from exc safe_template_name = _escape_markup(str(template_name)) if layers: @@ -63,6 +68,9 @@ def preset_resolve( # Verify composition is actually possible try: composed = resolver.resolve_content(template_name, template_type) + except PresetSectionValidationError as exc: + typer.echo(f"Error: {exc}", err=True) + raise typer.Exit(1) from exc except Exception as exc: # noqa: BLE001 - render composition failures composed = None console.print( diff --git a/src/specify_cli/shared_infra.py b/src/specify_cli/shared_infra.py index 44960706a1..177da809cc 100644 --- a/src/specify_cli/shared_infra.py +++ b/src/specify_cli/shared_infra.py @@ -584,7 +584,11 @@ def _ensure_or_bucket_dir(directory: Path) -> bool: dest_variant = dest_scripts / variant_dir if not _ensure_or_bucket_dir(dest_variant): continue - for src_path in variant_src.rglob("*"): + section_engine = Path(__file__).with_name("markdown_sections.py") + sources = list(variant_src.rglob("*")) + if any(path.name in ("common.sh", "common.ps1", "common.py") for path in sources): + sources.append(section_engine) + for src_path in sources: if not src_path.is_file(): continue # Python bytecode caches are local artifacts, not @@ -596,7 +600,10 @@ def _ensure_or_bucket_dir(directory: Path) -> bool: # stale-cleanup cannot treat its managed scripts as obsolete. scanned_variant_dirs.add(variant_dir) - rel_path = src_path.relative_to(variant_src) + rel_path = ( + Path(src_path.name) if src_path == section_engine + else src_path.relative_to(variant_src) + ) dst_path = dest_variant / rel_path rel = dst_path.relative_to(project_path).as_posix() seen_rels.add(rel) diff --git a/tests/integrations/test_cli.py b/tests/integrations/test_cli.py index ed6864253b..a2290d956d 100644 --- a/tests/integrations/test_cli.py +++ b/tests/integrations/test_cli.py @@ -586,6 +586,26 @@ def test_shared_infra_installs_python_scripts_for_py(self, tmp_path): project / ".specify" / "scripts" / "python" / "common.py" ).exists() + @pytest.mark.parametrize("flavor,variant", [("sh", "bash"), ("ps", "powershell"), ("py", "python")]) + def test_section_engine_is_installed_tracked_and_user_edits_preserved( + self, tmp_path, flavor, variant, + ): + from pathlib import Path + + from specify_cli import _install_shared_infra, markdown_sections + from specify_cli.integrations.manifest import IntegrationManifest + + project = tmp_path / "section-project" + project.mkdir() + _install_shared_infra(project, flavor) + relative = f".specify/scripts/{variant}/markdown_sections.py" + engine = project / relative + assert engine.read_bytes() == Path(markdown_sections.__file__).read_bytes() + assert relative in IntegrationManifest.load("speckit", project).files + engine.write_text("# user customization\n", encoding="utf-8") + _install_shared_infra(project, flavor, refresh_managed=True) + assert engine.read_text(encoding="utf-8") == "# user customization\n" + def test_shared_infra_removes_stale_managed_script(self, tmp_path): """A managed script the core no longer ships (e.g. the legacy update-agent-context.sh, superseded by the agent-context extension) is diff --git a/tests/parity_helpers.py b/tests/parity_helpers.py index a6d0a15355..12cb189c99 100644 --- a/tests/parity_helpers.py +++ b/tests/parity_helpers.py @@ -50,6 +50,50 @@ def install_scripts(repo: Path, script: str) -> None: py_dir.mkdir(parents=True, exist_ok=True) shutil.copy(PY_DIR / "common.py", py_dir / "common.py") shutil.copy(PY_DIR / f"{py_name}.py", py_dir / f"{py_name}.py") + for directory in (bash_dir, ps_dir, py_dir): + shutil.copy( + PROJECT_ROOT / "src/specify_cli/markdown_sections.py", + directory / "markdown_sections.py", + ) + + +def install_section_stack( + repo: Path, + content: str, + replacement: str, + selector: object = "target", + *, + kind: str = "template", +) -> tuple[str, Path]: + import yaml + + name = "speckit.section-test" if kind == "command" else "section-template" + templates = repo / ".specify/templates" + core = templates / ("commands" if kind == "command" else "") / f"{name}.md" + core.parent.mkdir(parents=True, exist_ok=True) + core.write_bytes(content.encode("utf-8")) + presets = repo / ".specify/presets" + preset = presets / "team" + preset.mkdir(parents=True) + body = preset / "body.md" + body.write_bytes(replacement.encode("utf-8")) + (preset / "preset.yml").write_text( + yaml.safe_dump({ + "schema_version": "1.0", + "preset": {"id": "team", "name": "Team", "version": "1.0.0", "description": "Sections"}, + "requires": {"speckit_version": ">=0.1.0"}, + "provides": {"templates": [{ + "type": kind, "name": name, "file": "body.md", + "strategy": "replace-section", "selector": selector, + }]}, + }, allow_unicode=True), + encoding="utf-8", + ) + (presets / ".registry").write_text( + json.dumps({"schema_version": "1.0", "presets": {"team": {"priority": 1, "enabled": True}}}), + encoding="utf-8", + ) + return name, body def bash_cmd(repo: Path, script: str, *args: str) -> list[str]: diff --git a/tests/specify_cli/artifacts/test_mcp_list.py b/tests/specify_cli/artifacts/test_mcp_list.py index 7c57883838..19a2c81fe8 100644 --- a/tests/specify_cli/artifacts/test_mcp_list.py +++ b/tests/specify_cli/artifacts/test_mcp_list.py @@ -232,7 +232,7 @@ "title": "Presetname", }, "strategy": { - "enum": ["replace", "wrap", "prepend", "append"], + "enum": ["replace", "wrap", "prepend", "append", "replace-section"], "title": "Strategy", "type": "string", }, diff --git a/tests/specify_cli/artifacts/test_operation_info.py b/tests/specify_cli/artifacts/test_operation_info.py index 45a5f3b96d..f9386a7d20 100644 --- a/tests/specify_cli/artifacts/test_operation_info.py +++ b/tests/specify_cli/artifacts/test_operation_info.py @@ -35,6 +35,21 @@ from specify_cli.presets import PresetError from tests.conftest import install_preset from tests.specify_cli.artifacts.helpers import install_extension_with_hooks +from tests.parity_helpers import install_section_stack + + +def test_section_strategy_survives_operation_and_mcp_contracts(spec_kit_project): + from specify_cli.artifacts.mcp_info import ArtifactInfoNamedResult + from specify_cli.artifacts.mcp_list import ArtifactListRowResult + + name, _ = install_section_stack(spec_kit_project, "## Target\nold\n", "new\n") + result = get_artifact_info(ArtifactInfoRequest(spec_kit_project, f"template:{name}")) + payload = result.to_json_dict() + assert payload["stack"][0]["strategy"] == "replace-section" + assert not payload["stack"][1]["hidden"] + assert ArtifactInfoNamedResult.model_validate(payload).stack[0].strategy == "replace-section" + assert ArtifactListRowResult.model_validate(payload).stack[0].strategy == "replace-section" + def test_artifact_info_operation_descriptor_is_stable(): diff --git a/tests/specify_cli/presets/test_command_resolve.py b/tests/specify_cli/presets/test_command_resolve.py index 42e55d572a..e6b2bd1fee 100644 --- a/tests/specify_cli/presets/test_command_resolve.py +++ b/tests/specify_cli/presets/test_command_resolve.py @@ -3,11 +3,13 @@ from pathlib import Path import yaml +import pytest from specify_cli.presets import ( PresetManager, ) from tests.conftest import strip_ansi +from tests.parity_helpers import install_section_stack class TestPresetResolve: @@ -80,6 +82,24 @@ def _invoke(self, project_dir, args): with patch.object(Path, "cwd", return_value=project_dir): return CliRunner().invoke(app, args) + @pytest.mark.parametrize( + "content,code", + [("# No target\n", "SECTION_NOT_FOUND"), ("## Target\n## Target\n", "SECTION_AMBIGUOUS")], + ) + def test_section_errors_fail_inspection(self, project_dir, content, code): + name, _ = install_section_stack(project_dir, content, "new\n") + result = self._invoke(project_dir, ["preset", "resolve", name]) + assert result.exit_code == 1, result.output + assert code in result.output + assert "Final output is composed" not in result.output + + def test_section_missing_base_fails_inspection(self, project_dir): + name, _ = install_section_stack(project_dir, "## Target\nold\n", "new\n") + (project_dir / ".specify/templates" / f"{name}.md").unlink() + result = self._invoke(project_dir, ["preset", "resolve", name]) + assert result.exit_code == 1 + assert "no replace base" in result.output + def test_resolve_rejects_invalid_template_name(self, project_dir): """``preset resolve`` rejects names before joining them into paths.""" result = self._invoke(project_dir, ["preset", "resolve", "no[/red]such"]) diff --git a/tests/specify_cli/presets/test_manager_commands.py b/tests/specify_cli/presets/test_manager_commands.py index d83ef12d17..e6c91ee8de 100644 --- a/tests/specify_cli/presets/test_manager_commands.py +++ b/tests/specify_cli/presets/test_manager_commands.py @@ -10,6 +10,41 @@ PresetArtifactTestHelpers, install_self_test_preset, ) +from tests.parity_helpers import install_section_stack + + +@pytest.mark.parametrize("skills_mode", [False, True]) +def test_section_command_is_composed_before_delivery(tmp_path, skills_mode): + import json + + project = tmp_path / "project" + templates = project / ".specify/templates/commands" + templates.mkdir(parents=True) + name, body = install_section_stack( + tmp_path / "source", + "---\ndescription: Original command\n---\n\n## Target\nold\n## Next\nkeep\n", + "team-specific body\n", + kind="command", + ) + (templates / f"{name}.md").write_bytes( + (tmp_path / "source/.specify/templates/commands" / f"{name}.md").read_bytes() + ) + (project / ".specify/init-options.json").write_text( + json.dumps({"ai": "copilot", "ai_skills": skills_mode}), encoding="utf-8", + ) + delivery = project / ".github" / ("skills" if skills_mode else "agents") + delivery.mkdir(parents=True) + manager = PresetManager(project) + manager.install_from_directory(body.parent, "9.9.9") + output = ( + delivery / "speckit-section-test/SKILL.md" if skills_mode + else delivery / f"{name}.agent.md" + ) + text = output.read_text(encoding="utf-8") + assert "## Target\nteam-specific body\n## Next\nkeep" in text + assert "Original command" in text + assert "\nold\n" not in text + class TestSelfTestPreset: diff --git a/tests/specify_cli/presets/test_manifest.py b/tests/specify_cli/presets/test_manifest.py index 7fa2cc4992..06b196a871 100644 --- a/tests/specify_cli/presets/test_manifest.py +++ b/tests/specify_cli/presets/test_manifest.py @@ -13,6 +13,39 @@ class TestPresetManifest: """Test PresetManifest validation and parsing.""" + @pytest.mark.parametrize("kind", ["template", "command"]) + def test_section_replacement(self, temp_dir, valid_pack_data, kind): + entry = valid_pack_data["provides"]["templates"][0] + entry.update(type=kind, strategy="replace-section", selector="requirements") + path = temp_dir / "preset.yml" + path.write_text(yaml.safe_dump(valid_pack_data), encoding="utf-8") + assert PresetManifest(path).templates[0]["selector"] == "requirements" + + @pytest.mark.parametrize("selector", [None, "", " ", 3, [], "#target", "Target", "two words"]) + def test_invalid_section_selector(self, temp_dir, valid_pack_data, selector): + entry = valid_pack_data["provides"]["templates"][0] + entry.update(strategy="replace-section", selector=selector) + path = temp_dir / "preset.yml" + path.write_text(yaml.safe_dump(valid_pack_data), encoding="utf-8") + with pytest.raises(PresetValidationError, match="selector"): + PresetManifest(path) + + def test_section_strategy_rejects_scripts(self, temp_dir, valid_pack_data): + valid_pack_data["provides"]["templates"][0].update( + type="script", strategy="replace-section", selector="target", + ) + path = temp_dir / "preset.yml" + path.write_text(yaml.safe_dump(valid_pack_data), encoding="utf-8") + with pytest.raises(PresetValidationError, match="script"): + PresetManifest(path) + + def test_selector_requires_section_strategy(self, temp_dir, valid_pack_data): + valid_pack_data["provides"]["templates"][0]["selector"] = "target" + path = temp_dir / "preset.yml" + path.write_text(yaml.safe_dump(valid_pack_data), encoding="utf-8") + with pytest.raises(PresetValidationError, match="selector"): + PresetManifest(path) + def test_valid_manifest(self, pack_dir): """Test loading a valid manifest.""" manifest = PresetManifest(pack_dir / "preset.yml") diff --git a/tests/specify_cli/presets/test_resolver.py b/tests/specify_cli/presets/test_resolver.py index 5c62cb9c9f..1c306ed914 100644 --- a/tests/specify_cli/presets/test_resolver.py +++ b/tests/specify_cli/presets/test_resolver.py @@ -17,6 +17,73 @@ CORE_TEMPLATE_NAMES, install_self_test_preset, ) +from tests.parity_helpers import install_section_stack + + +@pytest.mark.parametrize("kind", ["template", "command"]) +@pytest.mark.parametrize("newline", ["\n", "\r\n"]) +def test_section_replacement_preserves_raw_document(tmp_path, kind, newline): + base = "---\ndescription: 'Keep exact quoting'\n---\n\n# Doc\n## Target\nold\n### Child\nnested\n## Next\nupstream" + base = base.replace("\n", newline) + name, _ = install_section_stack(tmp_path, base, "new\n", kind=kind) + expected = base[:base.index("old")] + "new\n" + base[base.index("## Next"):] + assert PresetResolver(tmp_path).resolve_content(name, kind) == expected + + +@pytest.mark.parametrize( + "content,code,count", + [("# Missing\n", "SECTION_NOT_FOUND", 0), ("## Target\n## TARGET!\n", "SECTION_AMBIGUOUS", 2)], +) +def test_section_replacement_selection_errors(tmp_path, content, code, count): + name, body = install_section_stack(tmp_path, content, "") + with pytest.raises(PresetValidationError) as caught: + PresetResolver(tmp_path).resolve_content(name) + details = json.loads(str(caught.value)) + assert details["code"] == code + assert details["match_count"] == count + assert details["contribution"] == str(body) + assert details["preset"] == "team" + + +def test_section_invalid_declaration_cannot_fall_back_to_whole_file(tmp_path): + name, _ = install_section_stack(tmp_path, "## Target\nold\n", "wrong full file", selector=None) + with pytest.raises(PresetValidationError, match="selector"): + PresetResolver(tmp_path).resolve_content(name) + + +def test_section_without_base_fails_explicitly(tmp_path): + name, _ = install_section_stack(tmp_path, "## Target\nold\n", "new\n") + (tmp_path / ".specify/templates" / f"{name}.md").unlink() + with pytest.raises(PresetValidationError, match="no replace base"): + PresetResolver(tmp_path).resolve_content(name) + + +@pytest.mark.parametrize("unreadable", ["body", "base"]) +def test_section_unreadable_input_fails_explicitly(tmp_path, unreadable): + name, body = install_section_stack(tmp_path, "## Target\nold\n", "new\n") + path = body if unreadable == "body" else tmp_path / ".specify/templates" / f"{name}.md" + path.write_bytes(b"\xff") + with pytest.raises(PresetValidationError, match="Could not read"): + PresetResolver(tmp_path).resolve_content(name) + + +@pytest.mark.parametrize("field", ["file", "name", "type", "version", "schema_version"]) +def test_invalid_section_manifest_never_uses_convention_fallback(tmp_path, field): + name, body = install_section_stack(tmp_path, "## Target\nold\n", "new\n") + manifest_path = body.parent / "preset.yml" + data = yaml.safe_load(manifest_path.read_text(encoding="utf-8")) + if field == "version": + data["preset"][field] = 5 + elif field == "schema_version": + data[field] = "invalid" + else: + data["provides"]["templates"][0][field] = 5 + manifest_path.write_text(yaml.safe_dump(data), encoding="utf-8") + conventional = body.parent / "templates" / f"{name}.md" + conventional.parent.mkdir() + conventional.write_text("Wrong full-file fallback\n", encoding="utf-8") + with pytest.raises(PresetValidationError): + PresetResolver(tmp_path).resolve_content(name) class TestPresetResolver: diff --git a/tests/test_markdown_sections.py b/tests/test_markdown_sections.py new file mode 100644 index 0000000000..a678c866a2 --- /dev/null +++ b/tests/test_markdown_sections.py @@ -0,0 +1,95 @@ +"""Contract cases for bounded Markdown section replacement.""" + +from __future__ import annotations + +import pytest + +from specify_cli.markdown_sections import SectionReplacementError, replace_section + + +@pytest.mark.parametrize( + "heading,selector", + [ + ("Review & Approval!", "review--approval"), + ("API_v2 - Notes", "api_v2---notes"), + ("**Café** Guide", "café-guide"), + ("[Review](https://example.test/other) `Guide`", "review-guide"), + ("__Review__ _Guide_", "review-guide"), + ("日本語 123", "日本語-123"), + ("Keep__these_words", "keep__these_words"), + ("Review ###", "review"), + ], +) +def test_heading_anchors(heading: str, selector: str) -> None: + content = f"## {heading}\nold\n## Next\nunchanged" + assert replace_section( + content, "new\n", selector, + preset="team", contribution="body.md", artifact="spec-template", + ) == f"## {heading}\nnew\n## Next\nunchanged" + + +@pytest.mark.parametrize("newline", ["\n", "\r\n"]) +@pytest.mark.parametrize("replacement", ["", "\nnew\n\n"]) +@pytest.mark.parametrize("tail", ["## Next\nkeep", ""]) +def test_preserves_everything_outside_body( + newline: str, replacement: str, tail: str, +) -> None: + prefix = "---\ndescription: |\n ## Target\n---\n\n# Doc\n## Target\n" + body = "old\n### Child\nnested\n" + content = (prefix + body + tail).replace("\n", newline) + expected = prefix.replace("\n", newline) + replacement + tail.replace("\n", newline) + assert replace_section( + content, replacement, "target", + preset="team", contribution="body.md", artifact="spec-template", + ) == expected + + +@pytest.mark.parametrize( + "fence,close", + [("```md", "```"), ("~~~~ text", "~~~~~"), (" ```", " ````")], +) +def test_fenced_headings_neither_match_nor_end_section(fence: str, close: str) -> None: + content = f"# Doc\n{fence}\n## Target\n{close}\n## Target\nold\n{fence}\n# Fake end\n{close}\n## Next\nkeep\n" + assert replace_section( + content, "new\n", "target", + preset="team", contribution="body.md", artifact="spec-template", + ) == f"# Doc\n{fence}\n## Target\n{close}\n## Target\nnew\n## Next\nkeep\n" + + +@pytest.mark.parametrize( + "content,code,count,lines", + [ + ("# No target\n", "SECTION_NOT_FOUND", 0, []), + ("```\n## Target\n", "SECTION_NOT_FOUND", 0, []), + ("~~~\n## Target\n```\n## Target\n", "SECTION_NOT_FOUND", 0, []), + ("````\n```\n## Target\n", "SECTION_NOT_FOUND", 0, []), + ("## Target\nold\n### TARGET!\n", "SECTION_AMBIGUOUS", 2, [1, 3]), + (" ## Target\nnot ATX\n", "SECTION_NOT_FOUND", 0, []), + ("##Target\nnot ATX\n", "SECTION_NOT_FOUND", 0, []), + ("Target\n------\n", "SECTION_NOT_FOUND", 0, []), + ], +) +def test_selection_diagnostics( + content: str, code: str, count: int, lines: list[int], +) -> None: + with pytest.raises(SectionReplacementError) as caught: + replace_section( + content, "new\n", "target", + preset="team", contribution="body.md", artifact="spec-template", + ) + details = caught.value.details + assert details["code"] == code + assert details["match_count"] == count + assert details["preset"] == "team" + assert details["contribution"] == "body.md" + assert details["artifact"] == "spec-template" + assert details["selector"] == "target" + assert [candidate["line"] for candidate in details["candidates"]] == lines + assert details["remediation"] + + +def test_unclosed_fence_cannot_end_selected_body() -> None: + assert replace_section( + "## Target\nold\n```\n# Fake end\n", "", "target", + preset="team", contribution="body.md", artifact="spec-template", + ) == "## Target\n" diff --git a/tests/test_resolve_template_python_parity.py b/tests/test_resolve_template_python_parity.py index 9a3cad1334..3db327ef66 100644 --- a/tests/test_resolve_template_python_parity.py +++ b/tests/test_resolve_template_python_parity.py @@ -21,6 +21,7 @@ clean_env, install_composition_stack, install_scripts, + install_section_stack, json_stdout, make_python3_path_shim, make_repo, @@ -28,12 +29,228 @@ ps_cmd, py_cmd, run, + WINDOWS_POWERSHELL, ) SCRIPT = "resolve-template" TEMPLATE = "constitution-template" +@pytest.mark.skipif(not WINDOWS_POWERSHELL, reason="Native Windows PowerShell requires Windows") +def test_native_section_runtime_is_windows_powershell_51(): + result = subprocess.run( + [WINDOWS_POWERSHELL, "-NoProfile", "-Command", "$PSVersionTable.PSVersion.ToString()"], + capture_output=True, text=True, check=True, timeout=30, + ) + assert result.stdout.strip().startswith("5.1.") + + +@pytest.mark.skipif(not HAS_POWERSHELL, reason="PowerShell unavailable") +def test_powershell_section_legacy_native_argument_passing(tmp_path): + repo = make_repo(tmp_path) + install_scripts(repo, SCRIPT) + name, _ = install_section_stack(repo, "## Café\nold", "new", "café") + command = ps_cmd(repo, SCRIPT, name, "-Json") + script = str(repo / ".specify/scripts/powershell/resolve-template.ps1").replace("'", "''") + command = [ + command[0], "-NoProfile", "-Command", + f"$PSNativeCommandArgumentPassing = 'Legacy'; & '{script}' '{name}' -Json", + ] + env = dict(clean_env(), SPECKIT_PYTHON_EXECUTABLE=sys.executable) + result = run(command, repo, env, timeout=30) + assert result.returncode == 0, result.stderr + assert json_stdout(result)["TEMPLATE_CONTENT"] == "## Café\nnew" + + +@pytest.mark.parametrize("route", ["domain", "python", "bash", "powershell", "windows-powershell"]) +@pytest.mark.parametrize( + "base,selector,replacement,expected,error", + [ + ("## Target\nold\n## Next\nkeep", "target", "new\n", "## Target\nnew\n## Next\nkeep", None), + ("## Target\nold\n### Child\nnested\n# Next\nkeep", "target", "", "## Target\n# Next\nkeep", None), + ("## Target", "target", "", "## Target", None), + ("## Target\n", "target", "body", "## Target\nbody", None), + ("# First\nkeep\n## Target\nold", "target", "new", "# First\nkeep\n## Target\nnew", None), + ("## Target\r\nold\r\n## Next\r\nkeep\r\n", "target", "café\n", "## Target\r\ncafé\n## Next\r\nkeep\r\n", None), + ("## **Café** & `Guide`!\nold\n", "café--guide", "new\n", "## **Café** & `Guide`!\nnew\n", None), + ("## [API_v2](https://example.test) - Notes\nold", "api_v2---notes", "", "## [API_v2](https://example.test) - Notes\n", None), + ("## 日本語\nold", "日本語", "new", "## 日本語\nnew", None), + ("```md\n## Target\n```\n## Target\nold\n~~~\n# Not end\n~~~\n## Next\nkeep", "target", "new\n", "```md\n## Target\n```\n## Target\nnew\n## Next\nkeep", None), + ("## Target\nold\n```\n# Fake end", "target", "", "## Target\n", None), + ("---\ndescription: |\n ## Target\n---\n## Target\nold", "target", "new", "---\ndescription: |\n ## Target\n---\n## Target\nnew", None), + ("# Missing\n", "target", "", None, "SECTION_NOT_FOUND"), + ("## Target\n### TARGET!\n", "target", "", None, "SECTION_AMBIGUOUS"), + ("~~~\n## Target\n", "target", "", None, "SECTION_NOT_FOUND"), + ("## Target\nold", None, "", None, "selector"), + ("## Target\nold", "", "", None, "selector"), + ], +) +def test_section_replacement_shared_matrix( + tmp_path, route, base, selector, replacement, expected, error, +): + repo = make_repo(tmp_path, "project [section]") + install_scripts(repo, SCRIPT) + name, body = install_section_stack(repo, base, replacement, selector) + if route == "domain": + from specify_cli.presets import PresetResolver, PresetValidationError + + if error: + with pytest.raises(PresetValidationError, match=error): + PresetResolver(repo).resolve_content(name) + else: + assert PresetResolver(repo).resolve_content(name) == expected + return + env = clean_env() + env["SPECKIT_PYTHON_EXECUTABLE"] = sys.executable + if route == "bash": + if not HAS_BASH: + pytest.skip("Bash unavailable") + env["SPECKIT_PYTHON_EXECUTABLE"] = _bash_posix_path(Path(sys.executable)) + command = bash_cmd(repo, SCRIPT, name, "--json") + elif route in ("powershell", "windows-powershell"): + if not HAS_POWERSHELL: + pytest.skip("PowerShell unavailable") + if route == "windows-powershell" and not WINDOWS_POWERSHELL: + pytest.skip("Native Windows PowerShell 5.1 evidence requires Windows") + command = ps_cmd(repo, SCRIPT, name, "-Json") + if route == "windows-powershell": + command[0] = WINDOWS_POWERSHELL + else: + command = py_cmd(repo, SCRIPT, name, "--json") + result = run(command, repo, env, timeout=30) + if error: + assert result.returncode != 0 + assert result.stdout == "" + assert error in result.stderr + if error.startswith("SECTION_"): + assert "match_count" in result.stderr + assert "remediation" in result.stderr + assert "team" in result.stderr + else: + assert result.returncode == 0, result.stderr + assert json_stdout(result)["TEMPLATE_CONTENT"] == expected + assert body.read_bytes() == replacement.encode("utf-8") + + +@pytest.mark.parametrize("duplicate", [False, True]) +def test_section_layers_respect_composition_order(tmp_path, duplicate): + import yaml + + from specify_cli.presets import PresetResolver, PresetValidationError + + repo = make_repo(tmp_path) + install_scripts(repo, SCRIPT) + name, body = install_section_stack( + repo, "## Target\nold\n## Next\nupstream\n", "middle\n", + ) + presets = body.parent.parent + manifest = yaml.safe_load((body.parent / "preset.yml").read_text(encoding="utf-8")) + registry = {"team": {"priority": 10}} + for preset_id, priority, strategy, text in [ + ("prep", 30, "prepend", "## Added\nkeep"), + ("wrapper", 20, "wrap", "before\n{CORE_TEMPLATE}\nafter"), + ("final", 5, "replace-section", "final\n"), + ("appendix", 1, "append", "appendix"), + ]: + directory = presets / preset_id + directory.mkdir() + data = json.loads(json.dumps(manifest)) + data["preset"]["id"] = preset_id + entry = data["provides"]["templates"][0] + entry["strategy"] = strategy + if strategy != "replace-section": + del entry["selector"] + if duplicate and preset_id == "prep": + text = "## Target\nextra" + (directory / "preset.yml").write_text(yaml.safe_dump(data), encoding="utf-8") + (directory / "body.md").write_text(text, encoding="utf-8") + registry[preset_id] = {"priority": priority} + (presets / ".registry").write_text(json.dumps({"presets": registry}), encoding="utf-8") + expected = "before\n## Added\nkeep\n\n## Target\nfinal\n## Next\nupstream\n\nafter\n\nappendix" + if duplicate: + with pytest.raises(PresetValidationError, match="SECTION_AMBIGUOUS"): + PresetResolver(repo).resolve_content(name) + else: + assert PresetResolver(repo).resolve_content(name) == expected + + env = dict(clean_env(), SPECKIT_PYTHON_EXECUTABLE=sys.executable) + commands = [(py_cmd(repo, SCRIPT, name, "--json"), env)] + if HAS_BASH: + commands.append(( + bash_cmd(repo, SCRIPT, name, "--json"), + dict(env, SPECKIT_PYTHON_EXECUTABLE=_bash_posix_path(Path(sys.executable))), + )) + if HAS_POWERSHELL: + commands.append((ps_cmd(repo, SCRIPT, name, "-Json"), env)) + if WINDOWS_POWERSHELL: + native = ps_cmd(repo, SCRIPT, name, "-Json") + native[0] = WINDOWS_POWERSHELL + commands.append((native, env)) + for command, command_env in commands: + result = run(command, repo, command_env, timeout=30) + if duplicate: + assert result.returncode != 0 + assert "SECTION_AMBIGUOUS" in result.stderr + assert result.stdout == "" + else: + assert result.returncode == 0, result.stderr + assert json_stdout(result)["TEMPLATE_CONTENT"] == expected + + +def test_section_selector_survives_delegated_yaml(tmp_path): + repo = make_repo(tmp_path) + install_scripts(repo, SCRIPT) + name, _ = install_section_stack(repo, "## Café\nold", "new", "café") + no_yaml = make_yaml_less_venv(tmp_path / "no-yaml") + env = dict(clean_env(), SPECKIT_PYTHON_EXECUTABLE=sys.executable) + command = py_cmd(repo, SCRIPT, name, "--json") + command[0] = str(no_yaml) + result = run(command, repo, env, timeout=30) + assert result.returncode == 0, result.stderr + assert json_stdout(result)["TEMPLATE_CONTENT"] == "## Café\nnew" + + +@pytest.mark.parametrize("invalid", ["script", "omitted-selector"]) +def test_all_routes_reject_invalid_section_declarations(tmp_path, invalid): + import yaml + + from specify_cli.presets import PresetResolver, PresetValidationError + + repo = make_repo(tmp_path) + install_scripts(repo, SCRIPT) + name, body = install_section_stack(repo, "## Target\nold", "") + path = body.parent / "preset.yml" + data = yaml.safe_load(path.read_text(encoding="utf-8")) + entry = data["provides"]["templates"][0] + if invalid == "script": + entry["type"] = "script" + message = "script" + else: + del entry["selector"] + message = "selector" + path.write_text(yaml.safe_dump(data), encoding="utf-8") + with pytest.raises(PresetValidationError, match=message): + PresetResolver(repo).resolve_content(name) + env = dict(clean_env(), SPECKIT_PYTHON_EXECUTABLE=sys.executable) + commands = [(py_cmd(repo, SCRIPT, name, "--json"), env)] + if HAS_BASH: + commands.append(( + bash_cmd(repo, SCRIPT, name, "--json"), + dict(env, SPECKIT_PYTHON_EXECUTABLE=_bash_posix_path(Path(sys.executable))), + )) + if HAS_POWERSHELL: + commands.append((ps_cmd(repo, SCRIPT, name, "-Json"), env)) + if WINDOWS_POWERSHELL: + native = ps_cmd(repo, SCRIPT, name, "-Json") + native[0] = WINDOWS_POWERSHELL + commands.append((native, env)) + for command, command_env in commands: + result = run(command, repo, command_env, timeout=30) + assert result.returncode != 0 + assert result.stdout == "" + assert message in result.stderr + + @pytest.mark.parametrize( "layer", [ @@ -1433,6 +1650,8 @@ def fail_if_called() -> object: assert python_common._preset_template_layer(preset_dir, TEMPLATE) == ( conventional, "replace", + None, + preset_dir.name, ) From a9870cc75885135b79018ea82b9b12d30f1925a7 Mon Sep 17 00:00:00 2001 From: Manfred Riem <15701806+mnriem@users.noreply.github.com> Date: Tue, 17 Nov 2026 08:22:04 -0600 Subject: [PATCH 2/5] test: include section engine in integration file inventories Keep exact generated-file assertions aligned with the managed section helper installed for every script variant. Assisted-by: GitHub Copilot (model: GPT-6.1 Sol, autonomous) Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- tests/integrations/test_integration_base_markdown.py | 4 ++-- tests/integrations/test_integration_base_skills.py | 2 ++ tests/integrations/test_integration_base_toml.py | 2 ++ tests/integrations/test_integration_base_yaml.py | 2 ++ tests/integrations/test_integration_cline.py | 2 ++ tests/integrations/test_integration_copilot.py | 3 +++ tests/integrations/test_integration_generic.py | 2 ++ tests/integrations/test_integration_junie.py | 2 ++ 8 files changed, 17 insertions(+), 2 deletions(-) diff --git a/tests/integrations/test_integration_base_markdown.py b/tests/integrations/test_integration_base_markdown.py index 16ee0bd49d..510bc2c2ed 100644 --- a/tests/integrations/test_integration_base_markdown.py +++ b/tests/integrations/test_integration_base_markdown.py @@ -242,11 +242,11 @@ def _expected_files(self, script_variant: str) -> list[str]: if script_variant == "sh": for name in ["check-prerequisites.sh", "common.sh", "create-new-feature.sh", - "resolve-template.sh", "setup-plan.sh", "setup-tasks.sh"]: + "markdown_sections.py", "resolve-template.sh", "setup-plan.sh", "setup-tasks.sh"]: files.append(f".specify/scripts/bash/{name}") else: for name in ["check-prerequisites.ps1", "common.ps1", "create-new-feature.ps1", - "resolve-template.ps1", "setup-plan.ps1", "setup-tasks.ps1"]: + "markdown_sections.py", "resolve-template.ps1", "setup-plan.ps1", "setup-tasks.ps1"]: files.append(f".specify/scripts/powershell/{name}") for name in ["checklist-template.md", diff --git a/tests/integrations/test_integration_base_skills.py b/tests/integrations/test_integration_base_skills.py index f190508382..af1448390b 100644 --- a/tests/integrations/test_integration_base_skills.py +++ b/tests/integrations/test_integration_base_skills.py @@ -494,6 +494,7 @@ def _expected_files(self, script_variant: str) -> list[str]: ".specify/scripts/bash/check-prerequisites.sh", ".specify/scripts/bash/common.sh", ".specify/scripts/bash/create-new-feature.sh", + ".specify/scripts/bash/markdown_sections.py", ".specify/scripts/bash/resolve-template.sh", ".specify/scripts/bash/setup-plan.sh", ".specify/scripts/bash/setup-tasks.sh", @@ -503,6 +504,7 @@ def _expected_files(self, script_variant: str) -> list[str]: ".specify/scripts/powershell/check-prerequisites.ps1", ".specify/scripts/powershell/common.ps1", ".specify/scripts/powershell/create-new-feature.ps1", + ".specify/scripts/powershell/markdown_sections.py", ".specify/scripts/powershell/resolve-template.ps1", ".specify/scripts/powershell/setup-plan.ps1", ".specify/scripts/powershell/setup-tasks.ps1", diff --git a/tests/integrations/test_integration_base_toml.py b/tests/integrations/test_integration_base_toml.py index c7950b85fb..caf9372304 100644 --- a/tests/integrations/test_integration_base_toml.py +++ b/tests/integrations/test_integration_base_toml.py @@ -494,6 +494,7 @@ def _expected_files(self, script_variant: str) -> list[str]: "check-prerequisites.sh", "common.sh", "create-new-feature.sh", + "markdown_sections.py", "resolve-template.sh", "setup-plan.sh", "setup-tasks.sh", @@ -504,6 +505,7 @@ def _expected_files(self, script_variant: str) -> list[str]: "check-prerequisites.ps1", "common.ps1", "create-new-feature.ps1", + "markdown_sections.py", "resolve-template.ps1", "setup-plan.ps1", "setup-tasks.ps1", diff --git a/tests/integrations/test_integration_base_yaml.py b/tests/integrations/test_integration_base_yaml.py index 68c921ed23..648b2d8b5c 100644 --- a/tests/integrations/test_integration_base_yaml.py +++ b/tests/integrations/test_integration_base_yaml.py @@ -408,6 +408,7 @@ def _expected_files(self, script_variant: str) -> list[str]: "check-prerequisites.sh", "common.sh", "create-new-feature.sh", + "markdown_sections.py", "resolve-template.sh", "setup-plan.sh", "setup-tasks.sh", @@ -418,6 +419,7 @@ def _expected_files(self, script_variant: str) -> list[str]: "check-prerequisites.ps1", "common.ps1", "create-new-feature.ps1", + "markdown_sections.py", "resolve-template.ps1", "setup-plan.ps1", "setup-tasks.ps1", diff --git a/tests/integrations/test_integration_cline.py b/tests/integrations/test_integration_cline.py index 3608f754e4..133868527d 100644 --- a/tests/integrations/test_integration_cline.py +++ b/tests/integrations/test_integration_cline.py @@ -432,6 +432,7 @@ def _expected_files(self, script_variant: str) -> list[str]: "check-prerequisites.sh", "common.sh", "create-new-feature.sh", + "markdown_sections.py", "resolve-template.sh", "setup-plan.sh", "setup-tasks.sh", @@ -442,6 +443,7 @@ def _expected_files(self, script_variant: str) -> list[str]: "check-prerequisites.ps1", "common.ps1", "create-new-feature.ps1", + "markdown_sections.py", "resolve-template.ps1", "setup-plan.ps1", "setup-tasks.ps1", diff --git a/tests/integrations/test_integration_copilot.py b/tests/integrations/test_integration_copilot.py index d741441c7e..033406db42 100644 --- a/tests/integrations/test_integration_copilot.py +++ b/tests/integrations/test_integration_copilot.py @@ -347,6 +347,7 @@ def test_complete_file_inventory_sh(self, tmp_path): ".specify/scripts/bash/check-prerequisites.sh", ".specify/scripts/bash/common.sh", ".specify/scripts/bash/create-new-feature.sh", + ".specify/scripts/bash/markdown_sections.py", ".specify/scripts/bash/resolve-template.sh", ".specify/scripts/bash/setup-plan.sh", ".specify/scripts/bash/setup-tasks.sh", @@ -410,6 +411,7 @@ def test_complete_file_inventory_ps(self, tmp_path): ".specify/scripts/powershell/check-prerequisites.ps1", ".specify/scripts/powershell/common.ps1", ".specify/scripts/powershell/create-new-feature.ps1", + ".specify/scripts/powershell/markdown_sections.py", ".specify/scripts/powershell/resolve-template.ps1", ".specify/scripts/powershell/setup-plan.ps1", ".specify/scripts/powershell/setup-tasks.ps1", @@ -923,6 +925,7 @@ def test_complete_file_inventory_skills_sh(self, tmp_path): ".specify/scripts/bash/check-prerequisites.sh", ".specify/scripts/bash/common.sh", ".specify/scripts/bash/create-new-feature.sh", + ".specify/scripts/bash/markdown_sections.py", ".specify/scripts/bash/resolve-template.sh", ".specify/scripts/bash/setup-plan.sh", ".specify/scripts/bash/setup-tasks.sh", diff --git a/tests/integrations/test_integration_generic.py b/tests/integrations/test_integration_generic.py index 3ea10f7b11..4f6cf885aa 100644 --- a/tests/integrations/test_integration_generic.py +++ b/tests/integrations/test_integration_generic.py @@ -2613,6 +2613,7 @@ def test_complete_file_inventory_sh(self, tmp_path): ".specify/scripts/bash/check-prerequisites.sh", ".specify/scripts/bash/common.sh", ".specify/scripts/bash/create-new-feature.sh", + ".specify/scripts/bash/markdown_sections.py", ".specify/scripts/bash/resolve-template.sh", ".specify/scripts/bash/setup-plan.sh", ".specify/scripts/bash/setup-tasks.sh", @@ -2760,6 +2761,7 @@ def test_complete_file_inventory_ps(self, tmp_path): ".specify/scripts/powershell/check-prerequisites.ps1", ".specify/scripts/powershell/common.ps1", ".specify/scripts/powershell/create-new-feature.ps1", + ".specify/scripts/powershell/markdown_sections.py", ".specify/scripts/powershell/resolve-template.ps1", ".specify/scripts/powershell/setup-plan.ps1", ".specify/scripts/powershell/setup-tasks.ps1", diff --git a/tests/integrations/test_integration_junie.py b/tests/integrations/test_integration_junie.py index 8fb0d1dd9d..186052db42 100644 --- a/tests/integrations/test_integration_junie.py +++ b/tests/integrations/test_integration_junie.py @@ -280,6 +280,7 @@ def _expected_files(self, script_variant: str) -> list[str]: "check-prerequisites.sh", "common.sh", "create-new-feature.sh", + "markdown_sections.py", "resolve-template.sh", "setup-plan.sh", "setup-tasks.sh", @@ -290,6 +291,7 @@ def _expected_files(self, script_variant: str) -> list[str]: "check-prerequisites.ps1", "common.ps1", "create-new-feature.ps1", + "markdown_sections.py", "resolve-template.ps1", "setup-plan.ps1", "setup-tasks.ps1", From 945b38fcd7ce3dc4fe726a81e4c8f833b67a9c68 Mon Sep 17 00:00:00 2001 From: Manfred Riem <15701806+mnriem@users.noreply.github.com> Date: Tue, 17 Nov 2026 08:24:03 -0600 Subject: [PATCH 3/5] test: preserve explicit newlines in section composition fixtures Avoid Windows text-mode translation in the LF composition-order scenario while retaining intentional CRLF parity cases. Assisted-by: GitHub Copilot (model: GPT-6.1 Sol, autonomous) Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- tests/test_resolve_template_python_parity.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/test_resolve_template_python_parity.py b/tests/test_resolve_template_python_parity.py index 3db327ef66..1cf90c454f 100644 --- a/tests/test_resolve_template_python_parity.py +++ b/tests/test_resolve_template_python_parity.py @@ -163,7 +163,7 @@ def test_section_layers_respect_composition_order(tmp_path, duplicate): if duplicate and preset_id == "prep": text = "## Target\nextra" (directory / "preset.yml").write_text(yaml.safe_dump(data), encoding="utf-8") - (directory / "body.md").write_text(text, encoding="utf-8") + (directory / "body.md").write_bytes(text.encode("utf-8")) registry[preset_id] = {"priority": priority} (presets / ".registry").write_text(json.dumps({"presets": registry}), encoding="utf-8") expected = "before\n## Added\nkeep\n\n## Target\nfinal\n## Next\nupstream\n\nafter\n\nappendix" From 3efcf1cb9b3eab68c36663b58c62321bbea75d75 Mon Sep 17 00:00:00 2001 From: Manfred Riem <15701806+mnriem@users.noreply.github.com> Date: Tue, 17 Nov 2026 11:40:05 -0600 Subject: [PATCH 4/5] fix(presets): address section replacement review feedback Handle balanced inline-link destinations, protect literal code-span contents during emphasis normalization, and ignore invalid section presets only when hidden below an effective replace base. Add positive, negative, and cross-route regressions while retaining strict validation for active section layers. Assisted-by: GitHub Copilot (model: GPT-6.1 Sol, autonomous) Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- docs/presets/api.md | 8 ++- src/specify_cli/markdown_sections.py | 52 ++++++++++++++++++- src/specify_cli/presets/_resolver.py | 15 ++++-- .../presets/test_command_resolve.py | 10 ++++ tests/specify_cli/presets/test_resolver.py | 36 +++++++++++++ tests/test_markdown_sections.py | 25 +++++++++ tests/test_resolve_template_python_parity.py | 51 ++++++++++++++++++ 7 files changed, 191 insertions(+), 6 deletions(-) diff --git a/docs/presets/api.md b/docs/presets/api.md index af89d1e60f..149083e884 100644 --- a/docs/presets/api.md +++ b/docs/presets/api.md @@ -151,6 +151,10 @@ bottom-up. Prepend and append separate the two contents with a blank line. The wrapper placeholder is replaced with the effective lower content, which may already contain other preset customizations. +Invalid section declarations below that winning `replace` base do not block +resolution. Section declarations in the contributing stack remain strictly +validated. + Without a `replace` base, composition cannot produce output. Command registration warns and skips an uncomposable command rather than requiring an extension based solely on its namespace. A wrapper missing its required @@ -197,7 +201,9 @@ Selectors use a bounded GitHub-style anchor contract: spaces, and whitespace or end of line after the heading markers. Optional closing hash markers are excluded from the heading text. - Inline emphasis/code formatting is removed while retaining its text; inline - links contribute their label, not their destination. + links contribute their label, not their destination, including destinations + with balanced parentheses. Code-span contents remain literal during emphasis + processing, so `` `__init__` `` retains its underscores. - Lowercase the text, remove punctuation/symbols except hyphens and underscores, retain Unicode letters/numbers, and replace each space with one hyphen. Repeated spaces are not collapsed. diff --git a/src/specify_cli/markdown_sections.py b/src/specify_cli/markdown_sections.py index 634cd9c666..3e81cb4806 100644 --- a/src/specify_cli/markdown_sections.py +++ b/src/specify_cli/markdown_sections.py @@ -55,11 +55,59 @@ def validate_section_selector(strategy: str, selector: object, *, present: bool) ) +_CODE_SPAN = re.compile(r"(? str: + parts: list[str] = [] + cursor = 0 + while cursor < len(text): + code = _CODE_SPAN.match(text, cursor) + if code: + parts.append(code[0]) + cursor = code.end() + continue + link = _INLINE_LINK.match(text, cursor) + if link: + depth = 1 + end = link.end() + while end < len(text) and depth: + if text[end] == "\\": + end += 2 + continue + if text[end] == "(": + depth += 1 + elif text[end] == ")": + depth -= 1 + end += 1 + if depth == 0: + parts.append(link[1]) + cursor = end + continue + parts.append(text[cursor]) + cursor += 1 + return "".join(parts) + + def _anchor(text: str) -> str: - text = re.sub(r"!?\[([^\]]*)\]\([^)\r\n]*\)", r"\1", text) - text = re.sub(r"(`+)(.*?)\1", r"\2", text) + text = _link_labels(text) + # Stripping markup cannot create a token with more NULs than the input contains. + prefix = "\0" * (text.count("\0") + 1) + code_contents: list[str] = [] + + def protect_code(match: re.Match[str]) -> str: + code_contents.append(match[2]) + return f"{prefix}{len(code_contents) - 1}Z" + + text = _CODE_SPAN.sub(protect_code, text) text = re.sub(r"(\*{1,2}|~~)(.*?)\1", r"\2", text) text = re.sub(r"(? Optional[Path]: # Read strategy and manifest file path from preset manifest strategy = "replace" manifest_has_strategy = False - entry, manifest_candidate = self._manifest_declared_template( - pack_dir, template_name, template_type - ) + try: + entry, manifest_candidate = self._manifest_declared_template( + pack_dir, template_name, template_type + ) + except PresetSectionValidationError: + if any(layer["strategy"] == "replace" for layer in layers): + continue + raise if entry is not None: strategy = entry.get("strategy", "replace") manifest_has_strategy = "strategy" in entry @@ -616,6 +621,10 @@ def _find_in_subdirs(base_dir: Path) -> Optional[Path]: ) if isinstance(fm_strategy, str) and fm_strategy.lower() in VALID_PRESET_STRATEGIES: strategy = fm_strategy.lower() + except PresetSectionValidationError: + if any(layer["strategy"] == "replace" for layer in layers): + continue + raise except (UnicodeDecodeError, yaml.YAMLError, OSError): # Best-effort legacy frontmatter parsing: keep default # strategy ("replace") when content is unreadable/invalid. diff --git a/tests/specify_cli/presets/test_command_resolve.py b/tests/specify_cli/presets/test_command_resolve.py index e6b2bd1fee..b563618726 100644 --- a/tests/specify_cli/presets/test_command_resolve.py +++ b/tests/specify_cli/presets/test_command_resolve.py @@ -100,6 +100,16 @@ def test_section_missing_base_fails_inspection(self, project_dir): assert result.exit_code == 1 assert "no replace base" in result.output + def test_hidden_invalid_section_does_not_block_inspection(self, project_dir): + name, _ = install_section_stack(project_dir, "## Target\nold\n", "invalid\n", selector=None) + override = project_dir / ".specify/templates/overrides" / f"{name}.md" + override.parent.mkdir(parents=True, exist_ok=True) + override.write_bytes(b"# Winning override\n") + result = self._invoke(project_dir, ["preset", "resolve", name]) + assert result.exit_code == 0, result.output + assert "project override" in result.output + assert "Error:" not in result.output + def test_resolve_rejects_invalid_template_name(self, project_dir): """``preset resolve`` rejects names before joining them into paths.""" result = self._invoke(project_dir, ["preset", "resolve", "no[/red]such"]) diff --git a/tests/specify_cli/presets/test_resolver.py b/tests/specify_cli/presets/test_resolver.py index 1c306ed914..f052361c76 100644 --- a/tests/specify_cli/presets/test_resolver.py +++ b/tests/specify_cli/presets/test_resolver.py @@ -86,6 +86,42 @@ def test_invalid_section_manifest_never_uses_convention_fallback(tmp_path, field PresetResolver(tmp_path).resolve_content(name) +@pytest.mark.parametrize("kind", ["template", "command"]) +@pytest.mark.parametrize("winner", ["override", "preset", "wrapped-preset"]) +def test_hidden_invalid_section_presets_do_not_block_replace(tmp_path, kind, winner): + name, body = install_section_stack( + tmp_path, "## Target\nold\n", "invalid lower contribution\n", selector=None, kind=kind, + ) + expected = "# Winning replacement\n" + presets = body.parent.parent + data = yaml.safe_load((body.parent / "preset.yml").read_text(encoding="utf-8")) + registry = PresetRegistry(presets) + registry.add("team", {"priority": 20, "enabled": True}) + if winner == "override": + override = tmp_path / ".specify/templates/overrides" / f"{name}.md" + override.parent.mkdir() + override.write_bytes(expected.encode("utf-8")) + else: + for preset_id, priority, strategy, content in [ + ("winner", 10, "replace", expected), + *([("outer", 5, "wrap", "before\n{CORE_TEMPLATE}\nafter")] if winner == "wrapped-preset" else []), + ]: + directory = presets / preset_id + directory.mkdir() + manifest = json.loads(json.dumps(data)) + manifest["preset"]["id"] = preset_id + entry = manifest["provides"]["templates"][0] + entry["strategy"] = strategy + del entry["selector"] + (directory / "preset.yml").write_text(yaml.safe_dump(manifest), encoding="utf-8") + (directory / "body.md").write_bytes(content.encode("utf-8")) + registry.add(preset_id, {"priority": priority, "enabled": True}) + if winner == "wrapped-preset": + expected = f"before\n{expected}\nafter" + resolver = PresetResolver(tmp_path) + assert resolver.resolve_content(name, kind) == expected + + class TestPresetResolver: """Test PresetResolver priority stack.""" diff --git a/tests/test_markdown_sections.py b/tests/test_markdown_sections.py index a678c866a2..2c75bfbd5c 100644 --- a/tests/test_markdown_sections.py +++ b/tests/test_markdown_sections.py @@ -14,6 +14,15 @@ ("API_v2 - Notes", "api_v2---notes"), ("**Café** Guide", "café-guide"), ("[Review](https://example.test/other) `Guide`", "review-guide"), + ("[API](https://example.test/a_(b)/guide)", "api"), + ("[API](https://example.test/a_(b_(c))/guide) Next", "api-next"), + (r"[API](https://example.test/a_\)/guide) Next", "api-next"), + ("`__init__`", "__init__"), + ("``__init__``", "__init__"), + ("__Review `__init__`__", "review-__init__"), + ("[`__init__`](https://example.test/a_(b)/guide)", "__init__"), + ("`[API](url)`", "apiurl"), + ("_Guide_`__init__`", "guide__init__"), ("__Review__ _Guide_", "review-guide"), ("日本語 123", "日本語-123"), ("Keep__these_words", "keep__these_words"), @@ -93,3 +102,19 @@ def test_unclosed_fence_cannot_end_selected_body() -> None: "## Target\nold\n```\n# Fake end\n", "", "target", preset="team", contribution="body.md", artifact="spec-template", ) == "## Target\n" + + +def test_code_underscores_do_not_match_emphasis_anchor() -> None: + with pytest.raises(SectionReplacementError, match="SECTION_NOT_FOUND"): + replace_section( + "## `__init__`\nold\n", "new\n", "init", + preset="team", contribution="body.md", artifact="spec-template", + ) + + +def test_unclosed_link_destination_does_not_match_label_only() -> None: + with pytest.raises(SectionReplacementError, match="SECTION_NOT_FOUND"): + replace_section( + "## [API](https://example.test/a_(b)\nold\n", "new\n", "api", + preset="team", contribution="body.md", artifact="spec-template", + ) diff --git a/tests/test_resolve_template_python_parity.py b/tests/test_resolve_template_python_parity.py index 1cf90c454f..1e2556e712 100644 --- a/tests/test_resolve_template_python_parity.py +++ b/tests/test_resolve_template_python_parity.py @@ -75,6 +75,8 @@ def test_powershell_section_legacy_native_argument_passing(tmp_path): ("## **Café** & `Guide`!\nold\n", "café--guide", "new\n", "## **Café** & `Guide`!\nnew\n", None), ("## [API_v2](https://example.test) - Notes\nold", "api_v2---notes", "", "## [API_v2](https://example.test) - Notes\n", None), ("## 日本語\nold", "日本語", "new", "## 日本語\nnew", None), + ("## [API](https://example.test/a_(b)/guide)\nold", "api", "new", "## [API](https://example.test/a_(b)/guide)\nnew", None), + ("## `__init__`\nold", "__init__", "new", "## `__init__`\nnew", None), ("```md\n## Target\n```\n## Target\nold\n~~~\n# Not end\n~~~\n## Next\nkeep", "target", "new\n", "```md\n## Target\n```\n## Target\nnew\n## Next\nkeep", None), ("## Target\nold\n```\n# Fake end", "target", "", "## Target\n", None), ("---\ndescription: |\n ## Target\n---\n## Target\nold", "target", "new", "---\ndescription: |\n ## Target\n---\n## Target\nnew", None), @@ -132,6 +134,55 @@ def test_section_replacement_shared_matrix( assert body.read_bytes() == replacement.encode("utf-8") +@pytest.mark.parametrize("winner", ["override", "preset"]) +def test_hidden_invalid_section_does_not_block_runtime_override(tmp_path, winner): + import yaml + + from specify_cli.presets import PresetResolver + + repo = make_repo(tmp_path) + install_scripts(repo, SCRIPT) + name, body = install_section_stack(repo, "## Target\nold\n", "invalid\n", selector=None) + expected = "# Winning replacement\n" + if winner == "override": + override = repo / ".specify/templates/overrides" / f"{name}.md" + override.parent.mkdir() + override.write_bytes(expected.encode("utf-8")) + else: + presets = body.parent.parent + directory = presets / "winner" + directory.mkdir() + manifest = yaml.safe_load((body.parent / "preset.yml").read_text(encoding="utf-8")) + manifest["preset"]["id"] = "winner" + entry = manifest["provides"]["templates"][0] + entry["strategy"] = "replace" + del entry["selector"] + (directory / "preset.yml").write_text(yaml.safe_dump(manifest), encoding="utf-8") + (directory / "body.md").write_bytes(expected.encode("utf-8")) + (presets / ".registry").write_text( + json.dumps({"presets": {"winner": {"priority": 1}, "team": {"priority": 20}}}), + encoding="utf-8", + ) + assert PresetResolver(repo).resolve_content(name) == expected + env = dict(clean_env(), SPECKIT_PYTHON_EXECUTABLE=sys.executable) + commands = [(py_cmd(repo, SCRIPT, name, "--json"), env)] + if HAS_BASH: + commands.append(( + bash_cmd(repo, SCRIPT, name, "--json"), + dict(env, SPECKIT_PYTHON_EXECUTABLE=_bash_posix_path(Path(sys.executable))), + )) + if HAS_POWERSHELL: + commands.append((ps_cmd(repo, SCRIPT, name, "-Json"), env)) + if WINDOWS_POWERSHELL: + native = ps_cmd(repo, SCRIPT, name, "-Json") + native[0] = WINDOWS_POWERSHELL + commands.append((native, env)) + for command, command_env in commands: + result = run(command, repo, command_env, timeout=30) + assert result.returncode == 0, result.stderr + assert json_stdout(result)["TEMPLATE_CONTENT"] == expected + + @pytest.mark.parametrize("duplicate", [False, True]) def test_section_layers_respect_composition_order(tmp_path, duplicate): import yaml From 6d3f65c8c822579721344955892b6aec0ad26774 Mon Sep 17 00:00:00 2001 From: Manfred Riem <15701806+mnriem@users.noreply.github.com> Date: Tue, 17 Nov 2026 12:38:20 -0600 Subject: [PATCH 5/5] fix(presets): preserve EOF headings and nested emphasis anchors Match complete underscore delimiter runs and normalize nested emphasis before detecting ambiguous headings. Insert a separating line terminator for nonempty replacements at unterminated EOF headings, preserving supplied newlines and empty fragments. Add regression and cross-route parity coverage and document the boundary behavior. Assisted-by: GitHub Copilot (model: GPT-6.1 Sol, autonomous) Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- docs/presets/api.md | 10 ++++-- src/specify_cli/markdown_sections.py | 15 ++++++++- tests/test_markdown_sections.py | 34 ++++++++++++++++++++ tests/test_resolve_template_python_parity.py | 4 +++ 4 files changed, 60 insertions(+), 3 deletions(-) diff --git a/docs/presets/api.md b/docs/presets/api.md index 149083e884..bbd2b94713 100644 --- a/docs/presets/api.md +++ b/docs/presets/api.md @@ -188,7 +188,11 @@ to the next heading at the same or a higher level, or to the end of the document. Subordinate sections are part of that body. The original heading and all text outside the body remain unchanged, including line endings. Supply the blank lines and trailing newline needed before a following heading; -the strategy does not insert separators automatically. +the strategy does not insert blank-line separators automatically. If the heading +is at EOF without a line terminator, a nonempty replacement gets a separating +line terminator unless the fragment already starts with one. This uses the +document's last line-ending style, defaulting to LF when there is none. Empty +replacements leave an unterminated heading unchanged. Declare both strategy and selector in `preset.yml`, not command frontmatter. `selector` is rejected on other strategies. This is additive under manifest @@ -203,7 +207,9 @@ Selectors use a bounded GitHub-style anchor contract: - Inline emphasis/code formatting is removed while retaining its text; inline links contribute their label, not their destination, including destinations with balanced parentheses. Code-span contents remain literal during emphasis - processing, so `` `__init__` `` retains its underscores. + processing, so `` `__init__` `` retains its underscores. Complete matching + underscore emphasis runs, including `___Target___`, are stripped; formatting + alone cannot distinguish otherwise duplicate heading anchors. - Lowercase the text, remove punctuation/symbols except hyphens and underscores, retain Unicode letters/numbers, and replace each space with one hyphen. Repeated spaces are not collapsed. diff --git a/src/specify_cli/markdown_sections.py b/src/specify_cli/markdown_sections.py index 3e81cb4806..c543cbbb88 100644 --- a/src/specify_cli/markdown_sections.py +++ b/src/specify_cli/markdown_sections.py @@ -102,7 +102,11 @@ def protect_code(match: re.Match[str]) -> str: text = _CODE_SPAN.sub(protect_code, text) text = re.sub(r"(\*{1,2}|~~)(.*?)\1", r"\2", text) - text = re.sub(r"(? 0 and content[last_newline - 1] == "\r" else "\n" + replacement = separator + replacement return content[:body_start] + replacement + content[body_end:] diff --git a/tests/test_markdown_sections.py b/tests/test_markdown_sections.py index 2c75bfbd5c..285a018d2d 100644 --- a/tests/test_markdown_sections.py +++ b/tests/test_markdown_sections.py @@ -24,6 +24,11 @@ ("`[API](url)`", "apiurl"), ("_Guide_`__init__`", "guide__init__"), ("__Review__ _Guide_", "review-guide"), + ("___Target___", "target"), + ("____Target____", "target"), + ("__Outer _Target_ end__", "outer-target-end"), + ("Keep___Target___words", "keep___target___words"), + ("`___Target___`", "___target___"), ("日本語 123", "日本語-123"), ("Keep__these_words", "keep__these_words"), ("Review ###", "review"), @@ -53,6 +58,34 @@ def test_preserves_everything_outside_body( ) == expected +@pytest.mark.parametrize( + "content,replacement,expected", + [ + ("## Target", "new body\n", "## Target\nnew body\n"), + ("# Doc\r\n## Target", "new body\r\n", "# Doc\r\n## Target\r\nnew body\r\n"), + ("## Target", "\nnew body\n", "## Target\nnew body\n"), + ("## Target", "\r\nnew body\r\n", "## Target\r\nnew body\r\n"), + ("## Target", "", "## Target"), + ], +) +def test_unterminated_heading_keeps_body_on_a_separate_line(content, replacement, expected): + assert replace_section( + content, replacement, "target", + preset="team", contribution="body.md", artifact="spec-template", + ) == expected + + +def test_unterminated_heading_remains_selectable_for_later_replacements(): + first = replace_section( + "## Target", "first\n", "target", + preset="first", contribution="first.md", artifact="spec-template", + ) + assert replace_section( + first, "second\n", "target", + preset="second", contribution="second.md", artifact="spec-template", + ) == "## Target\nsecond\n" + + @pytest.mark.parametrize( "fence,close", [("```md", "```"), ("~~~~ text", "~~~~~"), (" ```", " ````")], @@ -73,6 +106,7 @@ def test_fenced_headings_neither_match_nor_end_section(fence: str, close: str) - ("~~~\n## Target\n```\n## Target\n", "SECTION_NOT_FOUND", 0, []), ("````\n```\n## Target\n", "SECTION_NOT_FOUND", 0, []), ("## Target\nold\n### TARGET!\n", "SECTION_AMBIGUOUS", 2, [1, 3]), + ("## Target\nold\n## ___Target___\n", "SECTION_AMBIGUOUS", 2, [1, 3]), (" ## Target\nnot ATX\n", "SECTION_NOT_FOUND", 0, []), ("##Target\nnot ATX\n", "SECTION_NOT_FOUND", 0, []), ("Target\n------\n", "SECTION_NOT_FOUND", 0, []), diff --git a/tests/test_resolve_template_python_parity.py b/tests/test_resolve_template_python_parity.py index 1e2556e712..449ee16236 100644 --- a/tests/test_resolve_template_python_parity.py +++ b/tests/test_resolve_template_python_parity.py @@ -69,6 +69,9 @@ def test_powershell_section_legacy_native_argument_passing(tmp_path): ("## Target\nold\n## Next\nkeep", "target", "new\n", "## Target\nnew\n## Next\nkeep", None), ("## Target\nold\n### Child\nnested\n# Next\nkeep", "target", "", "## Target\n# Next\nkeep", None), ("## Target", "target", "", "## Target", None), + ("## Target", "target", "new body\n", "## Target\nnew body\n", None), + ("# Doc\r\n## Target", "target", "new body\r\n", "# Doc\r\n## Target\r\nnew body\r\n", None), + ("## Target", "target", "\nnew body\n", "## Target\nnew body\n", None), ("## Target\n", "target", "body", "## Target\nbody", None), ("# First\nkeep\n## Target\nold", "target", "new", "# First\nkeep\n## Target\nnew", None), ("## Target\r\nold\r\n## Next\r\nkeep\r\n", "target", "café\n", "## Target\r\ncafé\n## Next\r\nkeep\r\n", None), @@ -82,6 +85,7 @@ def test_powershell_section_legacy_native_argument_passing(tmp_path): ("---\ndescription: |\n ## Target\n---\n## Target\nold", "target", "new", "---\ndescription: |\n ## Target\n---\n## Target\nnew", None), ("# Missing\n", "target", "", None, "SECTION_NOT_FOUND"), ("## Target\n### TARGET!\n", "target", "", None, "SECTION_AMBIGUOUS"), + ("## Target\n## ___Target___\n", "target", "", None, "SECTION_AMBIGUOUS"), ("~~~\n## Target\n", "target", "", None, "SECTION_NOT_FOUND"), ("## Target\nold", None, "", None, "selector"), ("## Target\nold", "", "", None, "selector"),