Skip to content

Commit cf0a80d

Browse files
committed
fix: derive plan path from feature.json in update-agent-context
When `plan_path` is omitted, prefer `.specify/feature.json` (written by /speckit-specify) over the mtime heuristic. The old approach picked the most recently modified `specs/*/plan.md`, which could inject an unrelated plan into CLAUDE.md if another spec's plan was touched after the active feature directory was created but before its own plan.md existed. Bash: handle both relative and absolute feature_directory values, normalizing absolute paths back to project-relative for the context file. Fall back to mtime only when feature.json is absent or the derived plan.md does not yet exist. PowerShell: same logic, PS 5.1-compatible (nested Join-Path, IsPathRooted guard to avoid Unix Join-Path mis-joining absolute ChildPaths, manual prefix-strip instead of GetRelativePath). Fixes github#3067
1 parent c220487 commit cf0a80d

3 files changed

Lines changed: 271 additions & 24 deletions

File tree

‎extensions/agent-context/scripts/bash/update-agent-context.sh‎

Lines changed: 41 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -10,9 +10,9 @@
1010
#
1111
# Usage: update-agent-context.sh [plan_path]
1212
#
13-
# When `plan_path` is omitted, the script picks the most recently modified
14-
# `specs/*/plan.md` if any exist, otherwise emits the section without a
15-
# concrete plan path.
13+
# When `plan_path` is omitted, the script derives it from `.specify/feature.json`
14+
# (written by /speckit-specify). Falls back to the most recently modified
15+
# `specs/*/plan.md` only when feature.json is absent or its plan does not exist yet.
1616

1717
set -euo pipefail
1818

@@ -122,11 +122,41 @@ unset _cf_parts _seg
122122

123123
PLAN_PATH="${1:-}"
124124
if [[ -z "$PLAN_PATH" ]]; then
125-
# Pick the most recently modified plan.md one level deep (specs/<feature>/plan.md).
126-
# Use find + sort by modification time to avoid ls/head fragility with
127-
# spaces in paths or SIGPIPE from pipefail.
128-
_plan_abs="$("$_python" - "$PROJECT_ROOT" <<'PY'
129-
import sys, os
125+
# Prefer .specify/feature.json (written by /speckit-specify) over mtime heuristic.
126+
_feature_json="$PROJECT_ROOT/.specify/feature.json"
127+
if [[ -f "$_feature_json" ]]; then
128+
_feature_dir="$("$_python" - "$_feature_json" <<'PY'
129+
import sys, json
130+
try:
131+
d = json.load(open(sys.argv[1]))
132+
print(d.get("feature_directory", ""))
133+
except Exception:
134+
print("")
135+
PY
136+
)"
137+
if [[ -n "$_feature_dir" ]]; then
138+
# feature_directory may be relative or absolute (absolute paths outside PROJECT_ROOT
139+
# are preserved as-is by _persist_feature_json in common.sh).
140+
if [[ "$_feature_dir" == /* ]]; then
141+
_candidate="$_feature_dir/plan.md"
142+
else
143+
_candidate="$PROJECT_ROOT/$_feature_dir/plan.md"
144+
fi
145+
if [[ -f "$_candidate" ]]; then
146+
# Emit a PROJECT_ROOT-relative path when possible, otherwise use the absolute path.
147+
if [[ "$_candidate" == "$PROJECT_ROOT/"* ]]; then
148+
PLAN_PATH="${_candidate#"$PROJECT_ROOT/"}"
149+
else
150+
PLAN_PATH="$_candidate"
151+
fi
152+
fi
153+
fi
154+
fi
155+
156+
# Fall back to mtime only when feature.json is absent or its plan does not exist yet.
157+
if [[ -z "$PLAN_PATH" ]]; then
158+
_plan_abs="$("$_python" - "$PROJECT_ROOT" <<'PY'
159+
import sys
130160
from pathlib import Path
131161
specs = Path(sys.argv[1]) / "specs"
132162
plans = sorted(
@@ -137,8 +167,9 @@ plans = sorted(
137167
print(plans[0] if plans else "")
138168
PY
139169
)"
140-
if [[ -n "$_plan_abs" ]]; then
141-
PLAN_PATH="${_plan_abs#"$PROJECT_ROOT/"}"
170+
if [[ -n "$_plan_abs" ]]; then
171+
PLAN_PATH="${_plan_abs#"$PROJECT_ROOT/"}"
172+
fi
142173
fi
143174
fi
144175

‎extensions/agent-context/scripts/powershell/update-agent-context.ps1‎

Lines changed: 49 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,10 @@
99
# .specify/extensions/agent-context/agent-context-config.yml
1010
#
1111
# Usage: update-agent-context.ps1 [plan_path]
12+
#
13+
# When `plan_path` is omitted, the script derives it from `.specify/feature.json`
14+
# (written by /speckit-specify). Falls back to the most recently modified
15+
# `specs/*/plan.md` only when feature.json is absent or its plan does not exist yet.
1216

1317
[CmdletBinding()]
1418
param(
@@ -166,21 +170,52 @@ if ($cm) {
166170
}
167171

168172
if (-not $PlanPath) {
169-
# Discover plan.md exactly one level deep (specs/<feature>/plan.md),
170-
# matching the bash glob specs/*/plan.md. Wrap in try/catch so access errors under
171-
# $ErrorActionPreference = 'Stop' don't abort the script.
172-
try {
173-
$specsDir = Join-Path $ProjectRoot 'specs'
174-
$candidate = Get-ChildItem -Path $specsDir -Directory -ErrorAction SilentlyContinue |
175-
ForEach-Object { Get-Item -LiteralPath (Join-Path $_.FullName 'plan.md') -ErrorAction SilentlyContinue } |
176-
Where-Object { $_ } |
177-
Sort-Object LastWriteTime -Descending |
178-
Select-Object -First 1
179-
if ($candidate) {
180-
$PlanPath = [System.IO.Path]::GetRelativePath($ProjectRoot, $candidate.FullName).Replace('\','/')
173+
# Prefer .specify/feature.json (written by /speckit-specify) over mtime heuristic.
174+
$FeatureJson = Join-Path $ProjectRoot '.specify/feature.json'
175+
if (Test-Path -LiteralPath $FeatureJson) {
176+
try {
177+
$fj = Get-Content -LiteralPath $FeatureJson -Raw -Encoding UTF8 | ConvertFrom-Json
178+
$featureDir = $fj.feature_directory
179+
if ($featureDir) {
180+
# Join-Path on Unix does not treat absolute ChildPath as "wins"; check explicitly.
181+
if ([System.IO.Path]::IsPathRooted($featureDir)) {
182+
$candidatePlan = Join-Path $featureDir 'plan.md'
183+
} else {
184+
$candidatePlan = Join-Path (Join-Path $ProjectRoot $featureDir) 'plan.md'
185+
}
186+
if (Test-Path -LiteralPath $candidatePlan) {
187+
# Normalize absolute feature paths to project-relative (mirrors bash behavior).
188+
$relDir = $featureDir
189+
if ([System.IO.Path]::IsPathRooted($featureDir)) {
190+
$normRoot = $ProjectRoot.TrimEnd('\', '/') + [System.IO.Path]::DirectorySeparatorChar
191+
$normDir = $featureDir.Replace('/', [System.IO.Path]::DirectorySeparatorChar)
192+
if ($normDir.StartsWith($normRoot, [System.StringComparison]::OrdinalIgnoreCase)) {
193+
$relDir = $normDir.Substring($normRoot.Length)
194+
}
195+
}
196+
$PlanPath = $relDir.Replace('\', '/') + '/plan.md'
197+
}
198+
}
199+
} catch {
200+
# Non-fatal: fall through to mtime heuristic.
201+
}
202+
}
203+
204+
# Fall back to mtime only when feature.json is absent or its plan does not exist yet.
205+
if (-not $PlanPath) {
206+
try {
207+
$specsDir = Join-Path $ProjectRoot 'specs'
208+
$candidate = Get-ChildItem -Path $specsDir -Directory -ErrorAction SilentlyContinue |
209+
ForEach-Object { Get-Item -LiteralPath (Join-Path $_.FullName 'plan.md') -ErrorAction SilentlyContinue } |
210+
Where-Object { $_ } |
211+
Sort-Object LastWriteTime -Descending |
212+
Select-Object -First 1
213+
if ($candidate) {
214+
$PlanPath = [System.IO.Path]::GetRelativePath($ProjectRoot, $candidate.FullName).Replace('\','/')
215+
}
216+
} catch {
217+
# Non-fatal: continue without a plan path.
181218
}
182-
} catch {
183-
# Non-fatal: continue without a plan path.
184219
}
185220
}
186221

Lines changed: 181 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,181 @@
1+
"""Tests that update-agent-context.sh/.ps1 prefer feature.json over mtime."""
2+
3+
from __future__ import annotations
4+
5+
import json
6+
import os
7+
import shutil
8+
import subprocess
9+
import time
10+
from pathlib import Path
11+
12+
import pytest
13+
14+
from tests.conftest import requires_bash
15+
16+
PROJECT_ROOT = Path(__file__).resolve().parent.parent.parent
17+
UPDATE_AGENT_CTX_SH = (
18+
PROJECT_ROOT / "extensions" / "agent-context" / "scripts" / "bash" / "update-agent-context.sh"
19+
)
20+
UPDATE_AGENT_CTX_PS = (
21+
PROJECT_ROOT / "extensions" / "agent-context" / "scripts" / "powershell" / "update-agent-context.ps1"
22+
)
23+
24+
HAS_PWSH = shutil.which("pwsh") is not None
25+
_WINDOWS_POWERSHELL = (shutil.which("powershell.exe") or shutil.which("powershell")) if os.name == "nt" else None
26+
27+
28+
def _setup_project(root: Path, context_file: str = "CLAUDE.md") -> None:
29+
"""Write the minimal agent-context extension config."""
30+
cfg_dir = root / ".specify" / "extensions" / "agent-context"
31+
cfg_dir.mkdir(parents=True, exist_ok=True)
32+
(cfg_dir / "agent-context-config.yml").write_text(
33+
f"context_file: {context_file}\n"
34+
"context_markers:\n"
35+
" start: '<!-- SPECKIT START -->'\n"
36+
" end: '<!-- SPECKIT END -->'\n",
37+
encoding="utf-8",
38+
)
39+
40+
41+
def _write_feature_json(root: Path, feature_directory: str) -> None:
42+
specify_dir = root / ".specify"
43+
specify_dir.mkdir(parents=True, exist_ok=True)
44+
(specify_dir / "feature.json").write_text(
45+
json.dumps({"feature_directory": feature_directory}),
46+
encoding="utf-8",
47+
)
48+
49+
50+
def _make_plan(root: Path, feature_dir: str, content: str = "# plan\n") -> Path:
51+
p = root / feature_dir / "plan.md"
52+
p.parent.mkdir(parents=True, exist_ok=True)
53+
p.write_text(content, encoding="utf-8")
54+
return p
55+
56+
57+
@requires_bash
58+
def test_bash_uses_feature_json_when_plan_exists(tmp_path: Path) -> None:
59+
"""feature.json points to the active feature; that plan.md is injected."""
60+
_setup_project(tmp_path)
61+
_make_plan(tmp_path, "specs/001-active")
62+
_write_feature_json(tmp_path, "specs/001-active")
63+
64+
result = subprocess.run(
65+
["bash", str(UPDATE_AGENT_CTX_SH)],
66+
cwd=tmp_path,
67+
capture_output=True,
68+
text=True,
69+
check=False,
70+
)
71+
assert result.returncode == 0, result.stderr + result.stdout
72+
ctx = (tmp_path / "CLAUDE.md").read_text(encoding="utf-8")
73+
assert "specs/001-active/plan.md" in ctx
74+
75+
76+
@requires_bash
77+
def test_bash_ignores_newer_stale_plan_when_feature_json_present(tmp_path: Path) -> None:
78+
"""An older spec's plan.md modified more recently must NOT win over feature.json."""
79+
_setup_project(tmp_path)
80+
81+
# Create active feature plan first, then touch the stale one to make it newer.
82+
_make_plan(tmp_path, "specs/001-active")
83+
time.sleep(0.05)
84+
_make_plan(tmp_path, "specs/000-stale")
85+
86+
_write_feature_json(tmp_path, "specs/001-active")
87+
88+
result = subprocess.run(
89+
["bash", str(UPDATE_AGENT_CTX_SH)],
90+
cwd=tmp_path,
91+
capture_output=True,
92+
text=True,
93+
check=False,
94+
)
95+
assert result.returncode == 0, result.stderr + result.stdout
96+
ctx = (tmp_path / "CLAUDE.md").read_text(encoding="utf-8")
97+
assert "specs/001-active/plan.md" in ctx
98+
assert "specs/000-stale/plan.md" not in ctx
99+
100+
101+
@requires_bash
102+
def test_bash_falls_back_to_mtime_when_feature_json_absent(tmp_path: Path) -> None:
103+
"""No feature.json → mtime fallback selects the most recently modified plan."""
104+
_setup_project(tmp_path)
105+
_make_plan(tmp_path, "specs/000-old")
106+
time.sleep(0.05)
107+
_make_plan(tmp_path, "specs/001-newer")
108+
109+
result = subprocess.run(
110+
["bash", str(UPDATE_AGENT_CTX_SH)],
111+
cwd=tmp_path,
112+
capture_output=True,
113+
text=True,
114+
check=False,
115+
)
116+
assert result.returncode == 0, result.stderr + result.stdout
117+
ctx = (tmp_path / "CLAUDE.md").read_text(encoding="utf-8")
118+
assert "specs/001-newer/plan.md" in ctx
119+
120+
121+
@requires_bash
122+
def test_bash_falls_back_to_mtime_when_plan_not_yet_created(tmp_path: Path) -> None:
123+
"""feature.json exists but plan.md not yet written → fall back to mtime."""
124+
_setup_project(tmp_path)
125+
_make_plan(tmp_path, "specs/000-old")
126+
# feature.json points to 001-new but its plan.md doesn't exist yet
127+
_write_feature_json(tmp_path, "specs/001-new")
128+
129+
result = subprocess.run(
130+
["bash", str(UPDATE_AGENT_CTX_SH)],
131+
cwd=tmp_path,
132+
capture_output=True,
133+
text=True,
134+
check=False,
135+
)
136+
assert result.returncode == 0, result.stderr + result.stdout
137+
ctx = (tmp_path / "CLAUDE.md").read_text(encoding="utf-8")
138+
assert "specs/000-old/plan.md" in ctx
139+
140+
141+
@pytest.mark.skipif(not (HAS_PWSH or _WINDOWS_POWERSHELL), reason="no PowerShell available")
142+
def test_ps_uses_feature_json_when_plan_exists(tmp_path: Path) -> None:
143+
"""PowerShell: feature.json points to the active feature; that plan is injected."""
144+
_setup_project(tmp_path)
145+
_make_plan(tmp_path, "specs/001-active")
146+
_write_feature_json(tmp_path, "specs/001-active")
147+
148+
exe = "pwsh" if HAS_PWSH else _WINDOWS_POWERSHELL
149+
result = subprocess.run(
150+
[exe, "-NoProfile", "-File", str(UPDATE_AGENT_CTX_PS)],
151+
cwd=tmp_path,
152+
capture_output=True,
153+
text=True,
154+
check=False,
155+
)
156+
assert result.returncode == 0, result.stderr + result.stdout
157+
ctx = (tmp_path / "CLAUDE.md").read_text(encoding="utf-8")
158+
assert "specs/001-active/plan.md" in ctx
159+
160+
161+
@pytest.mark.skipif(not (HAS_PWSH or _WINDOWS_POWERSHELL), reason="no PowerShell available")
162+
def test_ps_ignores_newer_stale_plan_when_feature_json_present(tmp_path: Path) -> None:
163+
"""PowerShell: stale plan touched more recently must not win over feature.json."""
164+
_setup_project(tmp_path)
165+
_make_plan(tmp_path, "specs/001-active")
166+
time.sleep(0.05)
167+
_make_plan(tmp_path, "specs/000-stale")
168+
_write_feature_json(tmp_path, "specs/001-active")
169+
170+
exe = "pwsh" if HAS_PWSH else _WINDOWS_POWERSHELL
171+
result = subprocess.run(
172+
[exe, "-NoProfile", "-File", str(UPDATE_AGENT_CTX_PS)],
173+
cwd=tmp_path,
174+
capture_output=True,
175+
text=True,
176+
check=False,
177+
)
178+
assert result.returncode == 0, result.stderr + result.stdout
179+
ctx = (tmp_path / "CLAUDE.md").read_text(encoding="utf-8")
180+
assert "specs/001-active/plan.md" in ctx
181+
assert "specs/000-stale/plan.md" not in ctx

0 commit comments

Comments
 (0)