1414`pip install specify-cli && specify init --ai claude` works offline.
1515"""
1616
17+ import hashlib
1718import importlib .util
19+ import json
1820import shutil
1921from dataclasses import dataclass , field
2022from 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+ + "\n Use --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# ---------------------------------------------------------------------------
0 commit comments