← Back to Pull requests

fix(stash): restore stashed changes when hk is terminated and recover them after a crash #1641

Closed
unknown closed this pull request without merging on Oct 04, 2026 02:47 UTC
View on GitHub
unknown unknown commented on Oct 03, 2026 23:40 UTC
Author

<!-- 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:

$ kill -TERM <hk pid>        # or SIGHUP when the terminal closes, or kill -9
$ cat file.txt
staged
$ git stash list
stash@{0}: On main: hk: 1234-...      # your unstaged edit, unmentioned

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:

$ kill -TERM <hk pid>
$ cat file.txt
staged
unstaged                               # restored; hk exited 143
$ ls "$(git rev-parse --git-dir)/hk-pending-stash"   # gone

And after kill -9, the next hk run in that repository (any hook, check, fix or run) either puts the changes back (clean working tree) or prints, and changes nothing else:

hk (pid 1234, hook `pre-commit`, started 2026-10-03 12:00:00) was stopped while it had your unstaged changes stashed, and they were not put back. The working tree has changes of its own, so hk did not apply them itself.
To get them back, once the working tree is ready for them, run:
  git stash apply <commit-id>
...

What changed

  • Pending-stash journal (src/stash_journal.rs): hk-pending-stash in 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 on hk-pending-stash.lock next 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 named create_new temp 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.

  • Recovery, early in every hook run before anything is stashed. It takes hk-stash.lock first (bounded by HK_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 the git 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 exact git stash apply command. 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 the core.sharedRepository mode. Nothing is dropped or overwritten automatically, and the journal stays until the entry is gone.

  • Signals (src/shutdown.rs, replaces watch_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 exits 128+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, full cargo 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.

  • New 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 held hk-stash.lock, and a reported journal not restored over a running fixer; every test/stash.bats file 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, with HK_LIBGIT2=1 and HK_LIBGIT2=0. The stash, pre-commit and MCP cancel bats files (134 ok of plan 134) pass under both backends.

  • Windows (jdx-win-ci): 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 with Stop-Process -Force and 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 check for the windows target locally is not possible (no mingw), so Windows compilation was checked on the CI box.

    Limitations and follow-ups

  • A run that finds a journal still in place (including one only reported) writes none of its own and now warns about it. The stash lock keeps other runs from recovering while it runs, but if that run is itself killed, its stash entry stays in git stash list as hk: <pid>-... without a journal.

  • hk-pending-stash.lock is opened like the stash lock (existing file read-only, new file with the core.sharedRepository mode).

  • No hk subcommand 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 -->
    ---

    [!NOTE]

    High Risk

    Changes how unstaged work is stashed, locked, and restored across signals and crashes; mistakes could lose or mis-apply user changes, though recovery errs toward reporting instead of auto-applying when ownership or the worktree is unclear.

    > Overview

    When hooks use Git stashing, hk now tracks in-flight stashes with a worktree-local hk-pending-stash journal (plus hk-pending-stash.lock), written before the working tree changes and updated as stash entries are created. The next hook run tries to auto-restore stranded changes when the owner process is clearly dead and the tree is clean; otherwise it warns and prints git stash apply commands without touching ambiguous or foreign-host/PID-namespace journals.

    > Graceful shutdown replaces Ctrl+C-only handling: SIGINT/SIGTERM/SIGHUP and Windows console events cancel the run, restore the stash, remove the journal, and use conventional exit codes (with a 10s grace period and terminal detachment on hangup). Stash entries now use per-run messages (hk: <pid>-…, including intent-to-add suffixes), and lock-file helpers honor core.sharedRepository for journal files too.

    > Docs (including pirate) add a long “stopped mid-run” section; coverage includes new Bats/Pester suites and extensive stash_journal unit tests.

    > <sup>Reviewed by Cursor Bugbot for commit defeb2406d1cb35b53228aad0402a1bf88c600fb. Bugbot is set up for automated code reviews on this repo. Configure here.</sup>

    <!-- /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 -->

    Diff: 650 lines (+487 / -163) across 8 files Reviewer: jdx Review duration: 187m
    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
    0.52
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.17 · 1 substantive comment(s)
    0.17
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    56%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    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
    Reviewers
    Assignees
    Unassigned
    Labels
    risk: low confidence: 56.8% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 52% (MEDIUM) · Higher = larger blast radius
    52%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 56.8% · Lower = rushed or shallow review
    56.8%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 22.5% · Safe to merge
    22.5%
    Repository