Skip to content

Commit b5a5e3f

Browse files
Copilotmnriem
andauthored
Add installed-file tracking with SHA-256 hashes for safe agent teardown
Setup records installed files and their SHA-256 hashes in .specify/agent-manifest-<agent_id>.json. Teardown uses the manifest to remove only individual files (never directories). If any tracked file was modified since installation, teardown requires --force. - Add record_installed_files(), check_modified_files(), remove_tracked_files() and AgentFileModifiedError to agent_pack.py - Update all 25 bootstrap modules to use file-tracked setup/teardown - Add --force flag to 'specify agent switch' - Add 11 new tests for file tracking (record, check, remove, force, directory preservation, deleted-file handling, manifest structure) Co-authored-by: mnriem <[email protected]> Agent-Logs-Url: https://github.com/github/spec-kit/sessions/779eabf6-21d5-428b-9f01-dd363df4c84a
1 parent ec5471a commit b5a5e3f

28 files changed

Lines changed: 639 additions & 207 deletions

File tree

‎src/specify_cli/__init__.py‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2533,6 +2533,7 @@ def agent_export(
25332533
@agent_app.command("switch")
25342534
def agent_switch(
25352535
agent_id: str = typer.Argument(..., help="Agent pack ID to switch to"),
2536+
force: bool = typer.Option(False, "--force", help="Remove agent files even if they were modified since installation"),
25362537
):
25372538
"""Switch the active AI agent in the current project.
25382539
@@ -2544,6 +2545,7 @@ def agent_switch(
25442545
load_bootstrap,
25452546
PackResolutionError,
25462547
AgentPackError,
2548+
AgentFileModifiedError,
25472549
)
25482550

25492551
show_banner()
@@ -2581,8 +2583,12 @@ def agent_switch(
25812583
current_resolved = resolve_agent_pack(current_agent, project_path=project_path)
25822584
current_bootstrap = load_bootstrap(current_resolved.path, current_resolved.manifest)
25832585
console.print(f" [dim]Tearing down {current_agent}...[/dim]")
2584-
current_bootstrap.teardown(project_path)
2586+
current_bootstrap.teardown(project_path, force=force)
25852587
console.print(f" [green]✓[/green] {current_agent} removed")
2588+
except AgentFileModifiedError as exc:
2589+
console.print(f"[red]Error:[/red] {exc}")
2590+
console.print("[yellow]Hint:[/yellow] Use --force to remove modified files.")
2591+
raise typer.Exit(1)
25862592
except AgentPackError:
25872593
# If pack-based teardown fails, try legacy cleanup via AGENT_CONFIG
25882594
agent_config = AGENT_CONFIG.get(current_agent, {})

‎src/specify_cli/agent_pack.py‎

Lines changed: 153 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,9 @@
1414
`pip install specify-cli && specify init --ai claude` works offline.
1515
"""
1616

17+
import hashlib
1718
import importlib.util
19+
import json
1820
import shutil
1921
from dataclasses import dataclass, field
2022
from pathlib import Path
@@ -52,6 +54,10 @@ class PackResolutionError(AgentPackError):
5254
"""Raised when no pack can be found for the requested agent id."""
5355

5456

57+
class AgentFileModifiedError(AgentPackError):
58+
"""Raised when teardown finds user-modified files and ``--force`` is not set."""
59+
60+
5561
# ---------------------------------------------------------------------------
5662
# Manifest
5763
# ---------------------------------------------------------------------------
@@ -191,15 +197,22 @@ def setup(self, project_path: Path, script_type: str, options: Dict[str, Any]) -
191197
"""
192198
raise NotImplementedError
193199

194-
def teardown(self, project_path: Path) -> None:
200+
def teardown(self, project_path: Path, *, force: bool = False) -> None:
195201
"""Remove agent-specific files from *project_path*.
196202
197203
Invoked by ``specify agent switch`` (for the *old* agent) and
198204
``specify agent remove`` when the user explicitly uninstalls.
199205
Must preserve shared infrastructure (specs, plans, tasks, etc.).
200206
207+
Only individual files recorded in the install manifest are removed
208+
— directories are never deleted. If any tracked file has been
209+
modified since installation and *force* is ``False``, raises
210+
:class:`AgentFileModifiedError`.
211+
201212
Args:
202213
project_path: Project directory to clean up.
214+
force: When ``True``, remove files even if they were modified
215+
after installation.
203216
"""
204217
raise NotImplementedError
205218

@@ -210,6 +223,145 @@ def agent_dir(self, project_path: Path) -> Path:
210223
return project_path / self.manifest.commands_dir.split("/")[0]
211224

212225

226+
# ---------------------------------------------------------------------------
227+
# Installed-file tracking
228+
# ---------------------------------------------------------------------------
229+
230+
def _manifest_path(project_path: Path, agent_id: str) -> Path:
231+
"""Return the path to the install manifest for *agent_id*."""
232+
return project_path / ".specify" / f"agent-manifest-{agent_id}.json"
233+
234+
235+
def _sha256(path: Path) -> str:
236+
"""Return the hex SHA-256 of a file."""
237+
h = hashlib.sha256()
238+
with open(path, "rb") as f:
239+
for chunk in iter(lambda: f.read(8192), b""):
240+
h.update(chunk)
241+
return h.hexdigest()
242+
243+
244+
def record_installed_files(
245+
project_path: Path,
246+
agent_id: str,
247+
files: List[Path],
248+
) -> Path:
249+
"""Record the installed files and their SHA-256 hashes.
250+
251+
Writes ``.specify/agent-manifest-<agent_id>.json`` containing a
252+
mapping of project-relative paths to their SHA-256 digests.
253+
254+
Args:
255+
project_path: Project root directory.
256+
agent_id: Agent identifier.
257+
files: Absolute or project-relative paths of the files that
258+
were created during ``setup()``.
259+
260+
Returns:
261+
Path to the written manifest file.
262+
"""
263+
entries: Dict[str, str] = {}
264+
for file_path in files:
265+
abs_path = project_path / file_path if not file_path.is_absolute() else file_path
266+
if abs_path.is_file():
267+
rel = str(abs_path.relative_to(project_path))
268+
entries[rel] = _sha256(abs_path)
269+
270+
manifest_file = _manifest_path(project_path, agent_id)
271+
manifest_file.parent.mkdir(parents=True, exist_ok=True)
272+
manifest_file.write_text(
273+
json.dumps({"agent_id": agent_id, "files": entries}, indent=2),
274+
encoding="utf-8",
275+
)
276+
return manifest_file
277+
278+
279+
def check_modified_files(
280+
project_path: Path,
281+
agent_id: str,
282+
) -> List[str]:
283+
"""Return project-relative paths of files modified since installation.
284+
285+
Returns an empty list when no install manifest exists or when every
286+
tracked file still has its original hash.
287+
"""
288+
manifest_file = _manifest_path(project_path, agent_id)
289+
if not manifest_file.is_file():
290+
return []
291+
292+
try:
293+
data = json.loads(manifest_file.read_text(encoding="utf-8"))
294+
except (json.JSONDecodeError, OSError):
295+
return []
296+
297+
modified: List[str] = []
298+
for rel_path, original_hash in data.get("files", {}).items():
299+
abs_path = project_path / rel_path
300+
if abs_path.is_file():
301+
if _sha256(abs_path) != original_hash:
302+
modified.append(rel_path)
303+
# If the file was deleted by the user, treat it as not needing
304+
# removal — skip rather than flag as modified.
305+
306+
return modified
307+
308+
309+
def remove_tracked_files(
310+
project_path: Path,
311+
agent_id: str,
312+
*,
313+
force: bool = False,
314+
) -> List[str]:
315+
"""Remove the individual files recorded in the install manifest.
316+
317+
Raises :class:`AgentFileModifiedError` if any tracked file was
318+
modified and *force* is ``False``.
319+
320+
Directories are **never** deleted — only individual files.
321+
322+
Args:
323+
project_path: Project root directory.
324+
agent_id: Agent identifier.
325+
force: When ``True``, delete even modified files.
326+
327+
Returns:
328+
List of project-relative paths that were removed.
329+
"""
330+
manifest_file = _manifest_path(project_path, agent_id)
331+
if not manifest_file.is_file():
332+
return []
333+
334+
try:
335+
data = json.loads(manifest_file.read_text(encoding="utf-8"))
336+
except (json.JSONDecodeError, OSError):
337+
return []
338+
339+
entries: Dict[str, str] = data.get("files", {})
340+
if not entries:
341+
manifest_file.unlink(missing_ok=True)
342+
return []
343+
344+
if not force:
345+
modified = check_modified_files(project_path, agent_id)
346+
if modified:
347+
raise AgentFileModifiedError(
348+
f"The following agent files have been modified since installation:\n"
349+
+ "\n".join(f" {p}" for p in modified)
350+
+ "\nUse --force to remove them anyway."
351+
)
352+
353+
removed: List[str] = []
354+
for rel_path in entries:
355+
abs_path = project_path / rel_path
356+
if abs_path.is_file():
357+
abs_path.unlink()
358+
removed.append(rel_path)
359+
360+
# Clean up the install manifest itself
361+
manifest_file.unlink(missing_ok=True)
362+
return removed
363+
364+
213365
# ---------------------------------------------------------------------------
214366
# Pack resolution
215367
# ---------------------------------------------------------------------------

‎src/specify_cli/core_pack/agents/agy/bootstrap.py‎

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
from pathlib import Path
44
from typing import Any, Dict
55

6-
from specify_cli.agent_pack import AgentBootstrap
6+
from specify_cli.agent_pack import AgentBootstrap, record_installed_files, remove_tracked_files
77

88

99
class Agy(AgentBootstrap):
@@ -16,10 +16,15 @@ def setup(self, project_path: Path, script_type: str, options: Dict[str, Any]) -
1616
"""Install Antigravity agent files into the project."""
1717
commands_dir = project_path / self.AGENT_DIR / self.COMMANDS_SUBDIR
1818
commands_dir.mkdir(parents=True, exist_ok=True)
19+
# Record installed files for tracked teardown
20+
installed = [p for p in commands_dir.rglob("*") if p.is_file()]
21+
record_installed_files(project_path, self.manifest.id, installed)
1922

20-
def teardown(self, project_path: Path) -> None:
21-
"""Remove Antigravity agent files from the project."""
22-
import shutil
23-
agent_dir = project_path / self.AGENT_DIR
24-
if agent_dir.is_dir():
25-
shutil.rmtree(agent_dir)
23+
def teardown(self, project_path: Path, *, force: bool = False) -> None:
24+
"""Remove Antigravity agent files from the project.
25+
26+
Only removes individual tracked files — directories are never
27+
deleted. Raises ``AgentFileModifiedError`` if any tracked file
28+
was modified and *force* is ``False``.
29+
"""
30+
remove_tracked_files(project_path, self.manifest.id, force=force)

‎src/specify_cli/core_pack/agents/amp/bootstrap.py‎

Lines changed: 9 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
from pathlib import Path
44
from typing import Any, Dict
55

6-
from specify_cli.agent_pack import AgentBootstrap
6+
from specify_cli.agent_pack import AgentBootstrap, record_installed_files, remove_tracked_files
77

88

99
class Amp(AgentBootstrap):
@@ -16,18 +16,15 @@ def setup(self, project_path: Path, script_type: str, options: Dict[str, Any]) -
1616
"""Install Amp agent files into the project."""
1717
commands_dir = project_path / self.AGENT_DIR / self.COMMANDS_SUBDIR
1818
commands_dir.mkdir(parents=True, exist_ok=True)
19+
# Record installed files for tracked teardown
20+
installed = [p for p in commands_dir.rglob("*") if p.is_file()]
21+
record_installed_files(project_path, self.manifest.id, installed)
1922

20-
def teardown(self, project_path: Path) -> None:
23+
def teardown(self, project_path: Path, *, force: bool = False) -> None:
2124
"""Remove Amp agent files from the project.
2225
23-
Only removes the commands/ subdirectory — preserves other .agents/
24-
content (e.g. Codex skills/) which shares the same parent directory.
26+
Only removes individual tracked files — directories are never
27+
deleted. Raises ``AgentFileModifiedError`` if any tracked file
28+
was modified and *force* is ``False``.
2529
"""
26-
import shutil
27-
commands_dir = project_path / self.AGENT_DIR / self.COMMANDS_SUBDIR
28-
if commands_dir.is_dir():
29-
shutil.rmtree(commands_dir)
30-
# Remove .agents/ only if now empty
31-
agents_dir = project_path / self.AGENT_DIR
32-
if agents_dir.is_dir() and not any(agents_dir.iterdir()):
33-
agents_dir.rmdir()
30+
remove_tracked_files(project_path, self.manifest.id, force=force)

‎src/specify_cli/core_pack/agents/auggie/bootstrap.py‎

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
from pathlib import Path
44
from typing import Any, Dict
55

6-
from specify_cli.agent_pack import AgentBootstrap
6+
from specify_cli.agent_pack import AgentBootstrap, record_installed_files, remove_tracked_files
77

88

99
class Auggie(AgentBootstrap):
@@ -16,10 +16,15 @@ def setup(self, project_path: Path, script_type: str, options: Dict[str, Any]) -
1616
"""Install Auggie CLI agent files into the project."""
1717
commands_dir = project_path / self.AGENT_DIR / self.COMMANDS_SUBDIR
1818
commands_dir.mkdir(parents=True, exist_ok=True)
19+
# Record installed files for tracked teardown
20+
installed = [p for p in commands_dir.rglob("*") if p.is_file()]
21+
record_installed_files(project_path, self.manifest.id, installed)
1922

20-
def teardown(self, project_path: Path) -> None:
21-
"""Remove Auggie CLI agent files from the project."""
22-
import shutil
23-
agent_dir = project_path / self.AGENT_DIR
24-
if agent_dir.is_dir():
25-
shutil.rmtree(agent_dir)
23+
def teardown(self, project_path: Path, *, force: bool = False) -> None:
24+
"""Remove Auggie CLI agent files from the project.
25+
26+
Only removes individual tracked files — directories are never
27+
deleted. Raises ``AgentFileModifiedError`` if any tracked file
28+
was modified and *force* is ``False``.
29+
"""
30+
remove_tracked_files(project_path, self.manifest.id, force=force)

‎src/specify_cli/core_pack/agents/bob/bootstrap.py‎

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
from pathlib import Path
44
from typing import Any, Dict
55

6-
from specify_cli.agent_pack import AgentBootstrap
6+
from specify_cli.agent_pack import AgentBootstrap, record_installed_files, remove_tracked_files
77

88

99
class Bob(AgentBootstrap):
@@ -16,10 +16,15 @@ def setup(self, project_path: Path, script_type: str, options: Dict[str, Any]) -
1616
"""Install IBM Bob agent files into the project."""
1717
commands_dir = project_path / self.AGENT_DIR / self.COMMANDS_SUBDIR
1818
commands_dir.mkdir(parents=True, exist_ok=True)
19+
# Record installed files for tracked teardown
20+
installed = [p for p in commands_dir.rglob("*") if p.is_file()]
21+
record_installed_files(project_path, self.manifest.id, installed)
1922

20-
def teardown(self, project_path: Path) -> None:
21-
"""Remove IBM Bob agent files from the project."""
22-
import shutil
23-
agent_dir = project_path / self.AGENT_DIR
24-
if agent_dir.is_dir():
25-
shutil.rmtree(agent_dir)
23+
def teardown(self, project_path: Path, *, force: bool = False) -> None:
24+
"""Remove IBM Bob agent files from the project.
25+
26+
Only removes individual tracked files — directories are never
27+
deleted. Raises ``AgentFileModifiedError`` if any tracked file
28+
was modified and *force* is ``False``.
29+
"""
30+
remove_tracked_files(project_path, self.manifest.id, force=force)

‎src/specify_cli/core_pack/agents/claude/bootstrap.py‎

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
from pathlib import Path
44
from typing import Any, Dict
55

6-
from specify_cli.agent_pack import AgentBootstrap
6+
from specify_cli.agent_pack import AgentBootstrap, record_installed_files, remove_tracked_files
77

88

99
class Claude(AgentBootstrap):
@@ -16,10 +16,15 @@ def setup(self, project_path: Path, script_type: str, options: Dict[str, Any]) -
1616
"""Install Claude Code agent files into the project."""
1717
commands_dir = project_path / self.AGENT_DIR / self.COMMANDS_SUBDIR
1818
commands_dir.mkdir(parents=True, exist_ok=True)
19+
# Record installed files for tracked teardown
20+
installed = [p for p in commands_dir.rglob("*") if p.is_file()]
21+
record_installed_files(project_path, self.manifest.id, installed)
1922

20-
def teardown(self, project_path: Path) -> None:
21-
"""Remove Claude Code agent files from the project."""
22-
import shutil
23-
agent_dir = project_path / self.AGENT_DIR
24-
if agent_dir.is_dir():
25-
shutil.rmtree(agent_dir)
23+
def teardown(self, project_path: Path, *, force: bool = False) -> None:
24+
"""Remove Claude Code agent files from the project.
25+
26+
Only removes individual tracked files — directories are never
27+
deleted. Raises ``AgentFileModifiedError`` if any tracked file
28+
was modified and *force* is ``False``.
29+
"""
30+
remove_tracked_files(project_path, self.manifest.id, force=force)

0 commit comments

Comments
 (0)