Skip to content

restore: snapshot cleared on spawn, not on resume — child loses store location through hc hook (cross-home restore reports success with 0 windows) #424

Backlog

Description

@KooshaPari

Summary

kcode restart restore reports success and clears the reboot snapshot based on the spawn of the
child process, not on the child actually resolving (resuming) its session. When the child fails, the
snapshot is already gone, so the restore is unrecoverable — the session is lost for that reboot.

This is a distinct defect from #389 (concurrent restores duplicating windows).

Observed (KCode 398d44f, v0.93.0-k0.1.0-dev)

Restore driven with the store in a non-default home (KCODE_HOME=/…/home-kcode34), spawn hook
configured as hc run --bg --outlive-parent:

=== restore (parent gets KCODE_HOME=/…/home-kcode34)
    Restored 1 jcode window(s).
    Cleared reboot snapshot after successful restore.
=== new terminal(s): t3d
    address   't3d'
    state     'finished'
    reason    'exited'
    exit_code 1                 <-- child died immediately
    argv      …/kcode --fresh-spawn --resume session_dromedary_1795478072092_c693226e634ccfc8
    cwd       '/tmp'            <-- correct

Snapshot file: removed (restart-snapshot.json gone). Windows restored: 0.

Root cause A — the child does not inherit the store location

hc children get the hc core's environment, not the client's, and hc run has no --env
(hc exec --env K=V does, verified). So the child falls back to the default store.

Controlled A/B on the same binary, same session id, same argv:

KCODE_HOME in child Result
set to the probe home resumes and renders the session (title updates observed)
unset Error: No session found matching 'session_dromedary_…' + rc=1

Measured directly (no pty wrapper needed for the error path):

$ env -u KCODE_HOME … kcode --fresh-spawn --resume session_dromedary_1795478072092_c693226e634ccfc8
Error: No session found matching 'session_dromedary_1795478072092_c693226e634ccfc8'
Use `jcode --resume` to list available sessions.
rc=1

There is also no argv-level override: the binary exposes no home/data-dir/store flag (--help has
none), so the child has no way to be pointed at a non-default store.

Root cause B — success is decided at spawn, so a failed child still burns the snapshot

Restored N jcode window(s). Cleared reboot snapshot after successful restore. is printed, and the
snapshot deleted, without any confirmation that the child process is alive or that its session
resolved. Any child failure (bad id, missing session, provider/module error, env mismatch) therefore
costs the user the snapshot.

Suggested fixes

  1. Have the restore spawn path forward the resolved store root to the child — e.g. prefix the child
    argv with env KCODE_HOME=…, or use hc run --env once that exists (see 3).
  2. Clear the snapshot only after the child proves it resolved its session (or keep the snapshot and
    mark the window as pending when spawn reports a non-zero exit / dies within a short grace window).
  3. hc run should get --env <K=V> for parity with hc exec --env.

Reproduction notes

  • The snapshot is only consumed under a pty: script -qec "<bin> restart restore" /dev/null.
  • hc ls records do not carry reported; use hc get <addr> for the full record (pid, exit_code).

Activity

  1. added
    bug
    kilo-triaged
    on Nov 28, 2026
  2. KooshaPari commented on Nov 28, 2026

    @KooshaPari
    OwnerAuthor

    Scoping update after more measurement — the failure is confined to redirected stores, and the child's own words are now captured.

    The child's error through the real hook path (session present only in a KCODE_HOME-redirected store, valid 867,314-byte copy):

    $ hc run --bg --outlive-parent <bin> --fresh-spawn --resume session_dromedary_…
    {"address":"t3h","agent":"kcode-recovered-1446000","state":"live",...}      # spawn "succeeded"
    t+8s: state=finished reason=exited exit_code=1
    screen:
      Error: No session found matching 'session_dromedary_1795478072092_c693226e634ccfc8'
      Use `jcode --resume` to list available sessions.
    

    Why the child cannot see it — the hc core's environment, which every spawned child inherits:

    HOME=/home/kooshapari
    KCODE_HOME=UNSET          <-- the client's value never reaches the child
    PWD=/home/kooshapari/CodeProjects/AgentHome
    

    So HOME is correct and the default store resolves fine; only a store relocated via KCODE_HOME is invisible to the child.

    What is NOT affected (measured, so the blast radius stays honest):

    • A session in the binary's default store (~/.kcode/sessions) restores through the hook and the child resumes normally — this is the fleet's normal case.
    • Resuming with KCODE_HOME present in the child works: same binary, same id, renders the session.
    • A first attempt that looked like "even the default store fails" was actually a legacy fixture: Error: Session '…' exists but failed to load (possibly corrupt): missing field jcode_version. That is a separate, benign path (old session format), not this defect.

    Net: the defect is exactly (1) the redirected store is not forwarded to the spawned child, and (2) the snapshot is cleared on spawn, so the user loses it even though nothing was restored. Suggested fixes in the description still stand; (3) hc run --env parity with hc exec --env would be the cheapest enabler.

  3. KooshaPari commented on Nov 28, 2026

    @KooshaPari
    OwnerAuthor

    A config-only workaround is verified. No code change needed for users on a redirected store; the store location can be carried in the hook line itself, because the child's argv is under our control even though its process environment is not.

    Two forms tested end-to-end on kcode v0.93.0-k0.1.0-dev (1d42e78), session present only in the redirected store (867,314 B valid copy, absent from ~/.kcode/sessions):

    A. Single line, no helper (recommended — what I verified last):

    [terminal]
    spawn_hook = "/home/kooshapari/.local/bin/hc run --bg --outlive-parent /usr/bin/env KCODE_HOME=/path/to/redirected/home"

    Result: restore printed success, snapshot consumed, and the child came back
    reported=True identity=ghostty state=live, title 🐪 User requests review v2 cockpit zi…,
    argv=['/usr/bin/env','KCODE_HOME=/…/home-kcode47','<kcode>','--fresh-spawn','--resume','session_dromedary_…'].

    B. Wrapper script, for a home that varies at runtime:

    #!/usr/bin/env bash
    BIN="$1"; shift
    exec /home/kooshapari/.local/bin/hc run --bg --outlive-parent \
      /usr/bin/env KCODE_HOME="${KCODE_HOME:-$HOME/.kcode}" "$BIN" "$@"

    Result: reported=True state=live, title 🐎 User requests review v2 cockpit zi….

    Why the wrapper must pass env ... as an argument rather than exporting the variable: exporting it only sets the hc client's environment, and hc children inherit the hc core's environment. Putting env KCODE_HOME=… in the child argv is what actually crosses that boundary.

    Two traps worth recording, both hit during this test:

    1. nixos has no /bin/bash. A spawn-hook script with #!/bin/bash fails to exec, and the binary reports only
      [WARN] Spawn hook '…' failed (No such file or directory (os error 2)); falling back to built-in terminal spawn
      — the restore still prints "Restored 1 window(s)" because the fallback spawn ran. Use #!/usr/bin/env bash.
      That silent fallback is arguably its own papercut: a hook misconfiguration is invisible unless you read the log.
    2. An unknown-id or stub session makes this hard to diagnose, because the spawn hook is used and the child exits 1; the distinguishing evidence is the child's own screen, not the parent's "restored" line.

    Still worth fixing upstream: the snapshot is cleared at spawn, so a hook that fails as in (1) loses the snapshot even though nothing was restored. The workaround above makes the child succeed; it does not make the snapshot handling safe.

  4. KooshaPari commented on Nov 28, 2026

    @KooshaPari
    OwnerAuthor

    Acceptance evidence for the mitigation, measured through the product's own CLI in the real home (real launcher, no KCODE_HOME override) rather than a hand-seeded snapshot.

    The working form

    [terminal]
    spawn_hook = "/home/kooshapari/.local/bin/hc run --bg --outlive-parent"

    Applied to ~/.kcode/config.toml, and it is the only change. Two earlier forms did not work and are recorded so nobody re-derives them:

    1. A wrapper script (spawn_hook = "/path/wrapper.sh"):
      • mine started #!/bin/bash, and this host has no /bin/bash, so the hook failed silently and the spawn fell back to the built-in path while the parent still printed Restored N;
      • after switching to #!/usr/bin/env bash it still failed because export KCODE_HOME=... inside the hook does not reach the child.
    2. export KCODE_HOME=... anywhere in the hook: the hc child inherits the core's environment (HOME, KCODE_HOME unset), not the spawning client's, so an exported variable never crosses. Only env VAR=value passed as argv crosses that boundary:
    spawn_hook = "/home/kooshapari/.local/bin/hc run --bg --outlive-parent /usr/bin/env KCODE_HOME=/path/to/home"

    That single-line form is what produced a live, rendered, registered child in the redirected-store probe.

    Measured results

    Cell Interface Observation
    restart restore, 1 session kcode restart restore Restored 1 jcode window(s); child reported=True identity=ghostty state=live, its own title rendered
    2-session snapshot kcode restart restore Restored 2 jcode window(s); both children reported=True state=live at t+8s and t+16s, each with its own title
    auto_restore_on_next_start=false plain start prints Restore it with: jcode restart restore, creates no terminal, snapshot not consumed (correct)
    redirected store, no env hook as applied child reports state=live then dies exit_code=1 with Error: No session found matching ... (the original report)
    redirected store, env in argv hook with the env prefix live rendered child resolving the redirected store
    default store hook as applied live rendered child; default-store restores are not affected by the underlying issue

    Both restore entries (restart restore, and plain-start auto-restore) share one engine and both go through spawn_hook, so either entry exercises the mitigation.

    Related defect found while testing

    restart restore reports success for a session id that no longer resolves, the child dies reported=False exit=1, and the snapshot is cleared so nothing can retry: filed as #426. That one bites default-store users and is unrelated to the env leakage above.

    Guard

    Because this mitigation is one unprotected line of config, a read-only checker now verifies it and exits 2 on drift: config key resolves via a real TOML load, hook matches the verified shape, hook is not a .sh wrapper, hook contains no export, launcher resolves to an executable whose --version matches the binary's revision, and any pending reboot snapshot names only resolvable sessions (the #426 trap). Live state today: 7/7 checks pass. Injected faults (wrapper hook, export form, hook removed, snapshot naming a missing session): 4/4 detected, rc=2.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugkilo-triaged

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions