git-checkpoint.ts 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. /**
  2. * Git Checkpoint Extension
  3. *
  4. * Creates git stash checkpoints at each turn so /fork can restore code state.
  5. * When forking, offers to restore code to that point in history.
  6. */
  7. import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
  8. export default function (pi: ExtensionAPI) {
  9. const checkpoints = new Map<string, string>();
  10. let currentEntryId: string | undefined;
  11. // Track the current entry ID when user messages are saved
  12. pi.on("tool_result", async (_event, ctx) => {
  13. const leaf = ctx.sessionManager.getLeafEntry();
  14. if (leaf) currentEntryId = leaf.id;
  15. });
  16. pi.on("turn_start", async () => {
  17. // Create a git stash entry before LLM makes changes
  18. const { stdout } = await pi.exec("git", ["stash", "create"]);
  19. const ref = stdout.trim();
  20. if (ref && currentEntryId) {
  21. checkpoints.set(currentEntryId, ref);
  22. }
  23. });
  24. pi.on("session_before_fork", async (event, ctx) => {
  25. const ref = checkpoints.get(event.entryId);
  26. if (!ref) return;
  27. if (!ctx.hasUI) {
  28. // In non-interactive mode, don't restore automatically
  29. return;
  30. }
  31. const choice = await ctx.ui.select("Restore code state?", [
  32. "Yes, restore code to that point",
  33. "No, keep current code",
  34. ]);
  35. if (choice?.startsWith("Yes")) {
  36. await pi.exec("git", ["stash", "apply", ref]);
  37. ctx.ui.notify("Code restored to checkpoint", "info");
  38. }
  39. });
  40. pi.on("agent_end", async () => {
  41. // Clear checkpoints after agent completes
  42. checkpoints.clear();
  43. });
  44. }