safe_commit.py 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. """
  2. Safe git-add helpers for Trellis-owned paths.
  3. Why this module exists
  4. ----------------------
  5. A real user incident: a project's `.gitignore` listed `.trellis/` (company-wide
  6. template / personal habit). When `add_session.py` and `task.py archive` ran
  7. their auto-commit and `git add` failed with `ignored by .gitignore`, the AI
  8. agent driving the workflow "fixed" it by retrying with
  9. `git add -f .trellis/` — which fan-out-included every ignored subtree
  10. (`.trellis/.backup-*/`, `.trellis/worktrees/`, `.trellis/.template-hashes.json`,
  11. `.trellis/.runtime/`), committing 548 files / 83474 lines of caches/backups.
  12. Design
  13. ------
  14. - Scripts only stage SPECIFIC product paths (journal files, index.md, the
  15. current task dir, the archive dir). Never the whole `.trellis/` tree.
  16. - If plain `git add <specific>` fails with "ignored by", DO NOT retry with
  17. ``-f``. The presence of `.trellis/` in `.gitignore` is treated as user
  18. intent ("keep .trellis/ local-only"). The script warns and skips the
  19. auto-commit; users who want auto-staging can either fix their `.gitignore`
  20. or set ``session_auto_commit: false`` and manage git themselves.
  21. - The warning includes a negative example: ``Do NOT use `git add -f .trellis/` ...``
  22. so any AI rereading the log doesn't reinvent the bug.
  23. History note: 0.5.10 introduced an automatic ``git add -f`` retry on the
  24. specific paths. That was reverted in 0.5.11 — auto-forcing into a tree the
  25. user had gitignored violates user intent even when the path list is narrow.
  26. The wider-grain forbidden command stays forbidden, and the narrow-grain auto
  27. ``-f`` is gone too.
  28. """
  29. from __future__ import annotations
  30. import sys
  31. from pathlib import Path
  32. from .git import run_git
  33. from .paths import (
  34. DIR_ARCHIVE,
  35. DIR_TASKS,
  36. DIR_WORKFLOW,
  37. DIR_WORKSPACE,
  38. FILE_JOURNAL_PREFIX,
  39. get_developer,
  40. )
  41. # Paths under .trellis/ that must NEVER be auto-staged. Listed here so the
  42. # warning to the user can show concrete subpaths to ignore individually
  43. # instead of ignoring the whole `.trellis/` tree.
  44. TRELLIS_IGNORED_SUBPATHS = (
  45. ".trellis/.backup-*",
  46. ".trellis/worktrees/",
  47. ".trellis/.template-hashes.json",
  48. ".trellis/.runtime/",
  49. ".trellis/.cache/",
  50. )
  51. def safe_trellis_paths_to_add(repo_root: Path) -> list[str]:
  52. """Return the list of repo-relative paths the auto-commit should stage.
  53. Only includes paths that exist on disk so callers don't pass non-existent
  54. arguments to git. The caller is responsible for `git diff --cached`
  55. checking afterwards.
  56. Included:
  57. - .trellis/workspace/<developer>/journal-*.md
  58. - .trellis/workspace/<developer>/index.md
  59. - .trellis/tasks/<task-dir>/ (every active task directory)
  60. - .trellis/tasks/archive/ (whole archive subtree, if present)
  61. Excluded (intentionally — these must not be staged):
  62. - .trellis/.backup-*, .trellis/worktrees/,
  63. .trellis/.template-hashes.json, .trellis/.runtime/, .trellis/.cache/
  64. """
  65. paths: list[str] = []
  66. # Workspace journal files + index.md
  67. developer = get_developer(repo_root)
  68. if developer:
  69. ws = repo_root / DIR_WORKFLOW / DIR_WORKSPACE / developer
  70. if ws.is_dir():
  71. for f in sorted(ws.glob(f"{FILE_JOURNAL_PREFIX}*.md")):
  72. if f.is_file():
  73. paths.append(
  74. f"{DIR_WORKFLOW}/{DIR_WORKSPACE}/{developer}/{f.name}"
  75. )
  76. index_md = ws / "index.md"
  77. if index_md.is_file():
  78. paths.append(
  79. f"{DIR_WORKFLOW}/{DIR_WORKSPACE}/{developer}/index.md"
  80. )
  81. # Active tasks: each direct child of tasks/ that is a directory and not
  82. # the archive root. The archive subtree is added as a single path below.
  83. tasks_dir = repo_root / DIR_WORKFLOW / DIR_TASKS
  84. if tasks_dir.is_dir():
  85. for child in sorted(tasks_dir.iterdir()):
  86. if not child.is_dir():
  87. continue
  88. if child.name == DIR_ARCHIVE:
  89. continue
  90. paths.append(f"{DIR_WORKFLOW}/{DIR_TASKS}/{child.name}")
  91. archive_dir = tasks_dir / DIR_ARCHIVE
  92. if archive_dir.is_dir():
  93. paths.append(f"{DIR_WORKFLOW}/{DIR_TASKS}/{DIR_ARCHIVE}")
  94. return paths
  95. def safe_archive_paths_to_add(
  96. repo_root: Path,
  97. task_name: str | None = None,
  98. modified_children: list[str] | None = None,
  99. ) -> list[str]:
  100. """Return paths to stage after `task.py archive`.
  101. Scoped to ONLY the paths the archive operation actually touched:
  102. - the archive subtree (where the freshly-moved task lives)
  103. - the source task directory (for source-side deletes; caller pairs
  104. this with `git rm --cached` since `git add` won't stage deletes
  105. for a path that no longer exists in the working tree)
  106. - any child task directories whose `task.json` was edited to drop
  107. the archived parent (parent-children relationship update)
  108. This narrow scope avoids "scope creep" — dirty changes in OTHER
  109. active task dirs (parallel-window edits) are NOT bundled into the
  110. archive commit. Callers handle each kind of change in its own
  111. commit boundary.
  112. Backwards-compat: with no arguments, the function walks the whole
  113. `.trellis/tasks/` subtree the old way (active tasks + archive). New
  114. callers should always pass `task_name`.
  115. """
  116. paths: list[str] = []
  117. tasks_dir = repo_root / DIR_WORKFLOW / DIR_TASKS
  118. if not tasks_dir.is_dir():
  119. return paths
  120. archive_dir = tasks_dir / DIR_ARCHIVE
  121. if task_name is not None:
  122. # Narrow scope — only paths that still exist on disk (so
  123. # `git add` doesn't choke on the moved-away source). The caller
  124. # handles the source-side deletes via `git rm --cached`
  125. # explicitly.
  126. if archive_dir.is_dir():
  127. paths.append(
  128. f"{DIR_WORKFLOW}/{DIR_TASKS}/{DIR_ARCHIVE}"
  129. )
  130. for child_name in modified_children or []:
  131. paths.append(f"{DIR_WORKFLOW}/{DIR_TASKS}/{child_name}")
  132. return paths
  133. # Legacy wide scope (no task_name): preserve old behavior so callers
  134. # that have not been updated keep working.
  135. if archive_dir.is_dir():
  136. paths.append(f"{DIR_WORKFLOW}/{DIR_TASKS}/{DIR_ARCHIVE}")
  137. for child in sorted(tasks_dir.iterdir()):
  138. if not child.is_dir():
  139. continue
  140. if child.name == DIR_ARCHIVE:
  141. continue
  142. paths.append(f"{DIR_WORKFLOW}/{DIR_TASKS}/{child.name}")
  143. return paths
  144. def _stderr_indicates_ignored(stderr: str) -> bool:
  145. """git add error indicates the path is excluded by .gitignore."""
  146. if not stderr:
  147. return False
  148. lowered = stderr.lower()
  149. return "ignored by" in lowered
  150. def safe_git_add(
  151. paths: list[str], repo_root: Path
  152. ) -> tuple[bool, bool, str]:
  153. """Run `git add` on specific paths; never retry with -f.
  154. Returns ``(success, used_force, stderr)``. The ``used_force`` field is
  155. kept for signature compatibility with the 0.5.10 implementation but is
  156. always ``False`` — we never auto-force.
  157. Behavior:
  158. - No paths passed → success, no force, empty stderr.
  159. - Plain ``git add -- <paths>`` succeeds → return success.
  160. - Plain fails (any reason — ignored or otherwise) → return failure with
  161. the stderr. Callers should inspect the stderr (see
  162. :func:`print_gitignore_warning`) and skip the auto-commit.
  163. """
  164. if not paths:
  165. return True, False, ""
  166. rc, _, err = run_git(["add", "--", *paths], cwd=repo_root)
  167. if rc == 0:
  168. return True, False, ""
  169. return False, False, err
  170. def print_gitignore_warning(paths: list[str]) -> None:
  171. """Explain to the user (and any AI reading the log) what to do.
  172. CRITICAL: includes the negative example
  173. ``Do NOT use `git add -f .trellis/``` — agents reading the warning are
  174. known to invent that command, which fans out to ignored caches/backups.
  175. """
  176. print(
  177. "[WARN] git add failed because .trellis/ paths are ignored by your .gitignore.",
  178. file=sys.stderr,
  179. )
  180. print(
  181. "[WARN] Skipping auto-commit. The journal/task files were still written to disk;",
  182. file=sys.stderr,
  183. )
  184. print(
  185. "[WARN] git was not touched.",
  186. file=sys.stderr,
  187. )
  188. print("[WARN]", file=sys.stderr)
  189. print(
  190. "[WARN] Trellis manages these specific paths and they should be tracked:",
  191. file=sys.stderr,
  192. )
  193. if paths:
  194. for p in paths:
  195. print(f"[WARN] {p}", file=sys.stderr)
  196. else:
  197. print(
  198. "[WARN] .trellis/workspace/<developer>/{journal-*.md,index.md}",
  199. file=sys.stderr,
  200. )
  201. print(
  202. "[WARN] .trellis/tasks/<task-dir>/",
  203. file=sys.stderr,
  204. )
  205. print(
  206. "[WARN] .trellis/tasks/archive/",
  207. file=sys.stderr,
  208. )
  209. print("[WARN]", file=sys.stderr)
  210. print(
  211. "[WARN] Recommended: change your .gitignore from `.trellis/` to specific",
  212. file=sys.stderr,
  213. )
  214. print(
  215. "[WARN] subpaths that should remain ignored, e.g.:",
  216. file=sys.stderr,
  217. )
  218. for sub in TRELLIS_IGNORED_SUBPATHS:
  219. print(f"[WARN] {sub}", file=sys.stderr)
  220. print("[WARN]", file=sys.stderr)
  221. print(
  222. "[WARN] Or, if you intentionally keep .trellis/ local-only, set in",
  223. file=sys.stderr,
  224. )
  225. print(
  226. "[WARN] .trellis/config.yaml:",
  227. file=sys.stderr,
  228. )
  229. print(
  230. "[WARN] session_auto_commit: false",
  231. file=sys.stderr,
  232. )
  233. print(
  234. "[WARN] so the scripts skip git entirely and you can review / commit",
  235. file=sys.stderr,
  236. )
  237. print(
  238. "[WARN] manually with `git status` / `git add` / `git commit`.",
  239. file=sys.stderr,
  240. )
  241. print("[WARN]", file=sys.stderr)
  242. print(
  243. "[WARN] Do NOT use `git add -f .trellis/` — it pulls in backups, worktrees,",
  244. file=sys.stderr,
  245. )
  246. print(
  247. "[WARN] and runtime caches that should never be committed.",
  248. file=sys.stderr,
  249. )