fix(stash): restore stashed changes when hk is terminated and recover them after a crash #1641
All Vouch review confidence checks passed
Residual risk 0.22 = Change Risk (0.52) × (1 − Review Confidence (0.57)).
Review depth and reviewer attention state are adequate.
Model 1 · Change Risk (XGBoost)
Score: 0.52 · 650 lines diff across 8 files
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.17 · 1 substantive comment(s)
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 35%
Bedrock Claude 3 · Risk Narration
(disconnected)
Groq Risk Narration
AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
Model 1 · Change Risk Attribution
SHAP Weights
Diff Size
diff_size
0.388
Shallow Review Depth
shallow_review_depth
0.289
Real PR Conversation Timeline
1 comments
"Review active on #1641"
general
weight: 0.35
jdx
<!-- entire-trail-link-start -->
https://entire.io/gh/jdx/hk/trails/217
<!-- entire-trail-link-end -->
Based on
main, which includes #1636's cross-process stash lock (hk-stash.lock). Recovery takes that lock too.Problem
While a hook runs with
stash = "git", hk has set your unstaged changes aside. If hk is killed in that window, those changes stay in the stash and the working tree looks like they were deleted, with nothing to tell you.Before, with a step that is still running:
SIGINT already cancelled the run and restored the stash, but SIGTERM and SIGHUP killed hk outright, and a second Ctrl+C exited at once.
After:
And after
kill -9, the next hk run in that repository (any hook,check,fixorrun) either puts the changes back (clean working tree) or prints, and changes nothing else:What changed
src/stash_journal.rs):hk-pending-stashin the worktree's git dir, JSON with the stash commit ids, hk pid and process start token, worktree path, hook and timestamp. Every operation on it (create, update, remove, recovery) happens while holding an exclusive OS advisory lock onhk-pending-stash.locknext to it; the lock is held only for each short operation (a recovering run holds it while it restores), waits are bounded (15 s) and give up on shutdown, and the OS releases it if hk dies. Under the lock the journal is written durably (a uniquely namedcreate_newtemp file fsynced, atomically renamed into place, directory fsynced) before the working tree is modified, updated as entries are created, and removed after a successful restore. Temp names carry a time and counter beyond the pid and are never reopened, and leftovers from a crash are swept under the lock. If stashing fails, the journal is kept so the next run can report an entry git created but hk did not record; it is removed only when stashing finished without creating one.hk-stash.lockfirst (bounded byHK_STASH_LOCK_TIMEOUT; if it cannot, it warns and leaves the journal untouched), then the journal lock, and re-reads the journal and the tree under both, the same lock order as stashing. A journal whose owner is running here (pid alive, start token matches) is never touched (hk notes it when the journal names stashed entries), and does not make the run wait for the stash lock. A live pid whose start token cannot be read counts as an owner that cannot be told, not a running one. The journal records the owner's host name and (on Linux) PID namespace: the owner counts as gone only when those match the current process and the pid is not running. When they differ, cannot be read, or an older journal lacks them and its pid is not visible, nothing is restored or dropped; hk prints thegit stash apply <commit>command and says the journal was written elsewhere (a git directory can be shared by hosts or containers). For a dead owner, the journal stays at its well-known path the whole time (nothing is renamed or claimed), so an interrupted recovery loses nothing and the next run starts over; it is deleted only once there is nothing left to say. No entries and nothing hk-looking in the stash, or entries already gone, deletes the stale journal; recorded entries and a working tree with no unstaged or untracked changes are restored through the normal restore path (so its conflict checks still apply); a dirty tree, an entry hk created but never recorded, or more than one entry of a kind is only reported with the exactgit stash applycommand. A journal whose owner cannot be told and that names no entry still in the stash is removed with a notice, so later runs journal again. The journal, its temp file and lock files get thecore.sharedRepositorymode. Nothing is dropped or overwritten automatically, and the journal stays until the entry is gone.src/shutdown.rs, replaceswatch_for_ctrl_c): SIGINT/SIGTERM/SIGHUP, and on Windows Ctrl+C/Ctrl+Break/close/logoff/shutdown, cancel the run through the existing cancellation token, so steps stop, the stash is restored and the journal removed, then hk exits128+signal(130 for Ctrl+C, 143 SIGTERM, 129 SIGHUP/console close, 131 Ctrl+Break). Restoring has 10 seconds; the same signal twice exits at once. On SIGHUP or a closing console, stdout/stderr are redirected to the null device first, so a vanished terminal (EIO) cannot make hk's output panic during restore.Behavior changes to note: Ctrl+C now exits 130 instead of 1, and SIGTERM/SIGHUP no longer kill hk without cleanup.
Validation
cargo fmt --check,cargo clippy --all-targets -- -D warnings, fullcargo test(675 passed), including new unit tests for journal write/parse, the lock, concurrent create/record/recover, temp-name uniqueness after a simulated crash, pid liveness and the recovery decision.test/stash_interrupt_journal.bats(24 tests, 24 ok of plan 24, adding foreign host/namespace and missing-identity journals reported not restored, including an entry stashed before the journal recorded it, recovery waiting for a heldhk-stash.lock, and a reported journal not restored over a running fixer; everytest/stash.batsfile ok equals plan under both backends; including recovery killed before and after it restores), covering SIGTERM, SIGHUP and SIGINT mid-step with exit status, journal and stash checks, and SIGKILL followed by auto-restore and by the dirty-tree report, withHK_LIBGIT2=1andHK_LIBGIT2=0. The stash, pre-commit and MCP cancel bats files (134 ok of plan 134) pass under both backends.cargo build, the journal unit tests (including the Win32 liveness and process start code) and a new Pester test (e2e-win/stash_journal.Tests.ps1) that terminates hk mid-step withStop-Process -Forceand checks the next run recovers.Not verified: Windows Ctrl+C, Ctrl+Break and console-close handling (no console session over SSH) and the 5-second Windows close deadline; macOS (the pid start token uses
ps); a real terminal hangup.cargo checkfor the windows target locally is not possible (no mingw), so Windows compilation was checked on the CI box.Limitations and follow-ups
git stash listashk: <pid>-...without a journal.hk-pending-stash.lockis opened like the stash lock (existing file read-only, new file with thecore.sharedRepositorymode).hksubcommand to inspect or clear the journal; delete the file or drop the stash entry.🤖 Generated with Claude Code
AI-assisted — Tool: Claude Code; model: anthropic/claude-sonnet-5-5; version: unavailable.
<!-- CURSOR_SUMMARY -->
---
<!-- /CURSOR_SUMMARY -->
<!-- This is an auto-generated comment: release notes by coderabbit.ai -->
Summary by CodeRabbit
Reliability
Interrupted hook runs can restore stashed changes after the original process ends, when the working tree is safe. Recovery can occur during shutdown or a later run.
If recovery isn’t safe or ownership is uncertain, hk leaves the stash entries untouched and reports that they need attention.
* Termination signals on Windows and Unix allow runs time to shut down gracefully; a repeated signal can end a run immediately.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->