mirror of
https://github.com/github/spec-kit.git
synced 2026-07-03 12:28:06 +08:00
* Initial plan * Extract agent context updates into bundled agent-context extension * Potential fix for pull request finding 'Unused import' Co-authored-by: Copilot Autofix powered by AI <223894421+github-code-quality[bot]@users.noreply.github.com> * Potential fix for pull request finding 'Unused import' Co-authored-by: Copilot Autofix powered by AI <223894421+github-code-quality[bot]@users.noreply.github.com> * fix: address review comments on agent-context extension - bash: parse init-options.json with a single python3 invocation instead of three separate read_json_field calls, for parity with the PowerShell ConvertFrom-Json approach and to avoid divergent error semantics - bash: use parameter expansion to strip PROJECT_ROOT prefix from plan path instead of sed interpolation, avoiding special-character fragility - powershell: limit Get-ChildItem to -Depth 1 so plan.md discovery matches the bash glob specs/*/plan.md (one level deep) — fixes cross-platform inconsistency with nested plan.md files - powershell: replace Substring+Length relative-path with [System.IO.Path]::GetRelativePath for robustness across case/PSDrive differences - __init__.py: move agent-context extension install to after save_init_options so init-options.json is present when hooks run - __init__.py: seed context_markers in init-options only when context_file is truthy; avoids noise for integrations without a context file - integrations/base.py: narrow blanket except Exception in _resolve_context_markers to ImportError / (OSError, ValueError) so unexpected bugs surface instead of being silently swallowed * fix: gate context_markers in _update_init_options_for_integration on context_file Apply the same gating logic used during `specify init`: only write context_markers to init-options.json when the integration actually has a context_file set. When switching to an integration without a context file the stale markers are removed, keeping the two init paths consistent. * fix: move context_file/context_markers from init-options.json to agent-context extension config * Potential fix for pull request finding 'Unused global variable' Co-authored-by: Copilot Autofix powered by AI <223894421+github-code-quality[bot]@users.noreply.github.com> * fix: clarify local import comment in agents.py * Fix remaining agent-context review findings * Fix follow-up agent-context review issues * Address review feedback: narrow except, improve PyYAML messaging, surface config-written note * Fix double-space in PyYAML install hint message * Potential fix for pull request finding 'Empty except' Co-authored-by: Copilot Autofix powered by AI <223894421+github-code-quality[bot]@users.noreply.github.com> * Potential fix for pull request finding 'Empty except' Co-authored-by: Copilot Autofix powered by AI <223894421+github-code-quality[bot]@users.noreply.github.com> * Address latest agent-context review feedback * Harden bash config parse output handling * Clarify ImportError-only fallback comment * Apply review feedback: drop dead try/except, guard ext-config creation, explicit ConvertFrom-Yaml check * Remove redundant $Options = $null in PS1 catch block * Add constitution directives, deprecation warning, agent-context auto-install, and init flow fix - Add constitution-loading directive to specify, clarify, tasks, checklist, taskstoissues commands - Add deprecation warning (v0.12.0) in upsert_context_section() - Auto-install agent-context extension during specify init - Move context_file from init-options.json to agent-context extension config - Add tests: deprecation warning, corrupt config, constitution directives - Update file inventories across all integration tests * Address review: fix init ordering, test coverage, and hermes inventory - Move agent-context extension install after init-options.json is saved so skill registration can read ai_skills + integration key - Write extension config after install (avoids template overwriting context_file) - Fix test_defaults_when_markers_field_missing to truly test missing markers key - Update hermes tests to allow extension-installed agent-context skill * Address review: chmod ordering, preserve markers, PS1 Python check, YAML key order - Move ensure_executable_scripts after agent-context extension install so extension scripts get execute bits set - Use preserve_markers=True on reinit to keep user-customized markers - Add Python 3 version check in PowerShell fallback (matching bash behavior) - Add sort_keys=False to yaml.safe_dump for stable config output * Address review: path traversal guards and docstring fix - Reject absolute paths and '..' segments in context_file in both bash and PowerShell scripts to prevent writes outside the project root - Fix docstring in _update_init_options_for_integration to accurately describe marker preservation behavior * Address review: strict enabled check, docstring, segment-level path traversal - Use 'is not False' for enabled check so only literal False disables - Update upsert_context_section docstring to mention disabled-extension return - Fix path traversal guards to check actual path segments, not substrings (allows filenames like 'notes..md' while rejecting '../' traversal) * Address review: UnicodeError handling, missing extension warning - Add UnicodeError to exception tuples in _load_agent_context_config and _resolve_context_markers so garbled UTF-8 config files fall back to defaults - Emit error (with reinstall command) instead of silent skip when bundled agent-context extension is not found during init * Address review: bash backslash traversal guard, wheel packaging - Reject backslash separators and Windows drive-letter paths in bash context_file validation (prevents traversal on Git-Bash/Windows) - Add extensions/agent-context to pyproject.toml force-include so the bundled extension is included in wheel builds * Address review: write extension config before init-options.json - Reorder writes in _update_init_options_for_integration so the agent-context extension config is updated first; if it fails, init-options.json remains consistent with the previous state --------- Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: Manfred Riem <15701806+mnriem@users.noreply.github.com> Co-authored-by: Copilot Autofix powered by AI <223894421+github-code-quality[bot]@users.noreply.github.com>
238 lines
7.5 KiB
PowerShell
238 lines
7.5 KiB
PowerShell
#!/usr/bin/env pwsh
|
|
# update-agent-context.ps1
|
|
#
|
|
# Refresh the managed Spec Kit section in the coding agent's context file
|
|
# (e.g. CLAUDE.md, .github/copilot-instructions.md, AGENTS.md).
|
|
#
|
|
# Reads `context_file` and `context_markers.{start,end}` from the
|
|
# agent-context extension config:
|
|
# .specify/extensions/agent-context/agent-context-config.yml
|
|
#
|
|
# Usage: update-agent-context.ps1 [plan_path]
|
|
|
|
[CmdletBinding()]
|
|
param(
|
|
[Parameter(Position = 0)]
|
|
[string]$PlanPath
|
|
)
|
|
|
|
function Get-ConfigValue {
|
|
param(
|
|
[AllowNull()][object]$Object,
|
|
[Parameter(Mandatory = $true)][string]$Key
|
|
)
|
|
|
|
if ($null -eq $Object) {
|
|
return $null
|
|
}
|
|
if ($Object -is [System.Collections.IDictionary]) {
|
|
return $Object[$Key]
|
|
}
|
|
$prop = $Object.PSObject.Properties[$Key]
|
|
if ($prop) {
|
|
return $prop.Value
|
|
}
|
|
return $null
|
|
}
|
|
|
|
function Test-ConfigObject {
|
|
param(
|
|
[AllowNull()][object]$Object
|
|
)
|
|
|
|
if ($null -eq $Object) {
|
|
return $false
|
|
}
|
|
if ($Object -is [System.Collections.IDictionary]) {
|
|
return $true
|
|
}
|
|
if ($Object -is [System.Management.Automation.PSCustomObject]) {
|
|
return $true
|
|
}
|
|
return $false
|
|
}
|
|
|
|
$ErrorActionPreference = 'Stop'
|
|
$DefaultStart = '<!-- SPECKIT START -->'
|
|
$DefaultEnd = '<!-- SPECKIT END -->'
|
|
$ProjectRoot = (Get-Location).Path
|
|
$ExtConfig = Join-Path $ProjectRoot '.specify/extensions/agent-context/agent-context-config.yml'
|
|
|
|
if (-not (Test-Path -LiteralPath $ExtConfig)) {
|
|
Write-Warning "agent-context: $ExtConfig not found; nothing to do."
|
|
exit 0
|
|
}
|
|
|
|
$Options = $null
|
|
if (Get-Command ConvertFrom-Yaml -ErrorAction SilentlyContinue) {
|
|
try {
|
|
$Options = Get-Content -LiteralPath $ExtConfig -Raw | ConvertFrom-Yaml -ErrorAction Stop
|
|
} catch {
|
|
# fall through to Python fallback
|
|
}
|
|
}
|
|
|
|
if ($null -eq $Options) {
|
|
# ConvertFrom-Yaml unavailable or failed; fall back to Python+PyYAML.
|
|
$pythonCmd = $null
|
|
foreach ($candidate in @('python3', 'python')) {
|
|
if (Get-Command $candidate -ErrorAction SilentlyContinue) {
|
|
# Verify it is Python 3
|
|
$verOut = & $candidate --version 2>&1
|
|
if ($verOut -match 'Python 3') {
|
|
$pythonCmd = $candidate
|
|
break
|
|
}
|
|
}
|
|
}
|
|
|
|
if ($pythonCmd) {
|
|
try {
|
|
$jsonOut = & $pythonCmd -c @'
|
|
import json
|
|
import sys
|
|
try:
|
|
import yaml
|
|
except ImportError:
|
|
print(
|
|
"agent-context: PyYAML is required to parse extension config; cannot update context.",
|
|
file=sys.stderr,
|
|
)
|
|
sys.exit(2)
|
|
|
|
try:
|
|
with open(sys.argv[1], "r", encoding="utf-8") as fh:
|
|
data = yaml.safe_load(fh)
|
|
except Exception as exc:
|
|
print(
|
|
f"agent-context: unable to parse {sys.argv[1]} ({exc}); cannot update context.",
|
|
file=sys.stderr,
|
|
)
|
|
sys.exit(2)
|
|
|
|
if not isinstance(data, dict):
|
|
data = {}
|
|
|
|
print(json.dumps(data))
|
|
'@ $ExtConfig
|
|
if ($LASTEXITCODE -eq 0 -and $jsonOut) {
|
|
$Options = $jsonOut | ConvertFrom-Json -ErrorAction Stop
|
|
}
|
|
} catch {
|
|
$Options = $null
|
|
}
|
|
}
|
|
|
|
if (-not $Options) {
|
|
Write-Warning "agent-context: unable to parse $ExtConfig; skipping update."
|
|
exit 0
|
|
}
|
|
}
|
|
|
|
if (-not (Test-ConfigObject -Object $Options)) {
|
|
Write-Warning "agent-context: $ExtConfig must contain a YAML mapping; skipping update."
|
|
exit 0
|
|
}
|
|
|
|
$ContextFile = Get-ConfigValue -Object $Options -Key 'context_file'
|
|
if (-not $ContextFile) {
|
|
Write-Warning 'agent-context: context_file not set in extension config; nothing to do.'
|
|
exit 0
|
|
}
|
|
|
|
# Reject absolute paths and '..' path segments in context_file
|
|
if ([System.IO.Path]::IsPathRooted($ContextFile)) {
|
|
Write-Warning "agent-context: context_file must be a project-relative path; got '$ContextFile'."
|
|
exit 1
|
|
}
|
|
$cfSegments = $ContextFile -split '[/\\]'
|
|
if ($cfSegments -contains '..') {
|
|
Write-Warning "agent-context: context_file must not contain '..' path segments; got '$ContextFile'."
|
|
exit 1
|
|
}
|
|
|
|
$MarkerStart = $DefaultStart
|
|
$MarkerEnd = $DefaultEnd
|
|
$cm = Get-ConfigValue -Object $Options -Key 'context_markers'
|
|
if ($cm) {
|
|
$cmStart = Get-ConfigValue -Object $cm -Key 'start'
|
|
if ($cmStart -is [string] -and $cmStart) {
|
|
$MarkerStart = $cmStart
|
|
}
|
|
$cmEnd = Get-ConfigValue -Object $cm -Key 'end'
|
|
if ($cmEnd -is [string] -and $cmEnd) {
|
|
$MarkerEnd = $cmEnd
|
|
}
|
|
}
|
|
|
|
if (-not $PlanPath) {
|
|
# Discover plan.md exactly one level deep (specs/<feature>/plan.md),
|
|
# matching the bash glob specs/*/plan.md. Wrap in try/catch so access errors under
|
|
# $ErrorActionPreference = 'Stop' don't abort the script.
|
|
try {
|
|
$specsDir = Join-Path $ProjectRoot 'specs'
|
|
$candidate = Get-ChildItem -Path $specsDir -Directory -ErrorAction SilentlyContinue |
|
|
ForEach-Object { Get-Item -LiteralPath (Join-Path $_.FullName 'plan.md') -ErrorAction SilentlyContinue } |
|
|
Where-Object { $_ } |
|
|
Sort-Object LastWriteTime -Descending |
|
|
Select-Object -First 1
|
|
if ($candidate) {
|
|
$PlanPath = [System.IO.Path]::GetRelativePath($ProjectRoot, $candidate.FullName).Replace('\','/')
|
|
}
|
|
} catch {
|
|
# Non-fatal: continue without a plan path.
|
|
}
|
|
}
|
|
|
|
$CtxPath = Join-Path $ProjectRoot $ContextFile
|
|
$CtxDir = Split-Path -Parent $CtxPath
|
|
if ($CtxDir -and -not (Test-Path -LiteralPath $CtxDir)) {
|
|
New-Item -ItemType Directory -Path $CtxDir -Force | Out-Null
|
|
}
|
|
|
|
$lines = @($MarkerStart,
|
|
'For additional context about technologies to be used, project structure,',
|
|
'shell commands, and other important information, read the current plan')
|
|
if ($PlanPath) {
|
|
$lines += "at $PlanPath"
|
|
}
|
|
$lines += $MarkerEnd
|
|
$Section = ($lines -join "`n") + "`n"
|
|
|
|
if (Test-Path -LiteralPath $CtxPath) {
|
|
$rawBytes = [System.IO.File]::ReadAllBytes($CtxPath)
|
|
# Strip UTF-8 BOM if present
|
|
if ($rawBytes.Length -ge 3 -and $rawBytes[0] -eq 0xEF -and $rawBytes[1] -eq 0xBB -and $rawBytes[2] -eq 0xBF) {
|
|
$content = [System.Text.Encoding]::UTF8.GetString($rawBytes, 3, $rawBytes.Length - 3)
|
|
} else {
|
|
$content = [System.Text.Encoding]::UTF8.GetString($rawBytes)
|
|
}
|
|
|
|
$s = $content.IndexOf($MarkerStart)
|
|
$e = if ($s -ge 0) { $content.IndexOf($MarkerEnd, $s) } else { $content.IndexOf($MarkerEnd) }
|
|
|
|
if ($s -ge 0 -and $e -ge 0 -and $e -gt $s) {
|
|
$endOfMarker = $e + $MarkerEnd.Length
|
|
if ($endOfMarker -lt $content.Length -and $content[$endOfMarker] -eq "`r") { $endOfMarker++ }
|
|
if ($endOfMarker -lt $content.Length -and $content[$endOfMarker] -eq "`n") { $endOfMarker++ }
|
|
$newContent = $content.Substring(0, $s) + $Section + $content.Substring($endOfMarker)
|
|
} elseif ($s -ge 0) {
|
|
$newContent = $content.Substring(0, $s) + $Section
|
|
} elseif ($e -ge 0) {
|
|
$endOfMarker = $e + $MarkerEnd.Length
|
|
if ($endOfMarker -lt $content.Length -and $content[$endOfMarker] -eq "`r") { $endOfMarker++ }
|
|
if ($endOfMarker -lt $content.Length -and $content[$endOfMarker] -eq "`n") { $endOfMarker++ }
|
|
$newContent = $Section + $content.Substring($endOfMarker)
|
|
} else {
|
|
if ($content -and -not $content.EndsWith("`n")) { $content += "`n" }
|
|
if ($content) { $newContent = $content + "`n" + $Section } else { $newContent = $Section }
|
|
}
|
|
} else {
|
|
$newContent = $Section
|
|
}
|
|
|
|
$newContent = $newContent.Replace("`r`n", "`n").Replace("`r", "`n")
|
|
[System.IO.File]::WriteAllText($CtxPath, $newContent, (New-Object System.Text.UTF8Encoding($false)))
|
|
|
|
Write-Host "agent-context: updated $ContextFile"
|