Commit Graph

9 Commits

Author SHA1 Message Date
Teknium
ab1c29d8bb fix: worktree sweep keeps any tree holding work an archive cannot restore
The second review found trees deleted with bytes or commits that were in
neither git nor the archive: untracked files over archive_max_file_mb
(skipped from the snapshot, tree still removed), gitignored embedded
repositories (ls-files --exclude-standard never lists them) and every
ignored file (.env edits, *.secret, info/exclude notes). The classic
pruner had three older gaps of the same class: status.showUntrackedFiles=no
made new files invisible, skip-worktree/assume-unchanged edits read clean,
and commits held only by refs/worktree/* or refs/bisect/* died with the
tree's admin dir.

Rule now enforced at one decision point (worktree_retention.removal_blocker)
used by archive_preflight, the post-snapshot removal boundary in
archive_then_remove (sweep, exit Archive, subagent finalize), the classic
clean-tree pruner, the attended `hermes worktree prune` and the clean exit
path: a tree is removed only when everything irreproducible is in git or the
archive. Kept: keep-large-untracked (archive ref stays), keep-unarchivable
(embedded repo, ignored or not), keep-worktree-refs, keep-ignored-work
(ignored files outside a regenerable-dir allowlist that are not
byte-identical to the main checkout's copy, so .worktreeinclude .env copies
never block). Exit Archive and the subagent note name the reason. Every
dirty check forces --untracked-files=normal and counts flagged-index edits.
The ignored-path walk skips dependency stores without descending and is
capped per tree (unverifiable -> keep).
2026-10-17 21:49:14 -07:00
Teknium
ccb3c9a4e8 fix: worktree archive keeps submodule work and late staged edits, reports retained trees
A snapshot records a submodule only as its 160000 gitlink, so `git worktree
remove --force` after archiving deleted an initialized submodule's uncommitted
edits (and its per-worktree modules/ repo) with nothing in the archive to
restore them. The shared snapshot_worktree entry point and archive_preflight
now refuse any tree whose populated submodule is dirty (tracked or untracked,
recursively), checked out at another commit than recorded, or holds commits/
stashes no remote-tracking ref has; the planner shows it as
keep-submodule-work. Uninitialized or clean-at-recorded-commit submodules
still archive. Refusing in snapshot_worktree covers exit-time Archive and
subagent finalization, which do not go through the planner.

The post-snapshot removal gate used file/HEAD/reflog mtimes, which an
index-only change (git apply --cached) never moves. snapshot_worktree now
digests the semantic staged entries (ls-files --stage) of exactly the index
it captured; archive_then_remove compares them right before removal and keeps
the tree if they differ. A stat-only refresh by git status does not count.

execute_plan dropped archive_then_remove's removed flag, so a tree kept by the
safety gate was reported as "archived + removed"; the exit path and subagent
note said "removed" too. The flag now propagates: `hermes worktree prune`
prints "archived, kept (changed during the sweep)", the exit Archive prints
archived_kept, and the subagent note says the tree was kept (all locales).

Reported by @unsupportedpastels in review of #140603.
2026-10-17 21:49:14 -07:00
Teknium
71a83d74d5 fix: worktree sweep honours --older-than, re-gates each tree, archives exact bytes
Review of the snapshot-then-delete sweep found paths where it could remove
work it should keep or store bytes that differ from the working files:

- `hermes worktree prune --older-than N` ran the sweep before applying N; the
  plan now marks any tree idle < N days skip-young before anything runs.
- execute_plan checked liveness once per batch, then archived trees one by one.
  Each tree is now re-gated (lock, /proc cwd/fds, fresh activity) right before
  it is touched, and archive_then_remove re-checks after the snapshot, keeping
  the tree when a process entered or a file changed during capture.
- _last_activity ignored deleted paths; it now stats each changed path's
  nearest surviving folder, so a fresh deletion counts as activity.
- `--attr-source` does not cover info/attributes or core.attributesFile, so
  eol rules still rewrote bytes. Every blob is re-hashed with
  `hash-object --no-filters` and restore writes blob bytes directly.
- The classic CLI applied the exit Archive answer in atexit, after the exit
  watchdog was armed; it is now applied synchronously in _tui_shutdown, with
  a progress line, before _run_cleanup. A failed or interrupted archive keeps
  the tree.
- web_git.worktree_add's existingBranch path skipped the repo registry.
- subagent-* trees got the 72h named-tree tier; one prune_tier_hours helper
  now gives hermes-* and subagent-* the 24h tier in both planners.
- worktree_sweep.py had a text=True git call without encoding="utf-8" (CI red).
2026-10-17 21:49:14 -07:00
Teknium
3882113085 feat: archive stale dirty worktrees before removing them, sweep every repo, ask on dirty exit
The worktree pruner never removed a dirty or unpushed tree at any age, so leftovers of finished
lanes (stray probe files, WIP commits on closed PRs) accumulated forever: 658 trees / ~1 TB on
one machine, 553 of them named lane trees. Approved design (Teknium, 2026-10-17):

- Snapshot-then-delete: an idle tree past its tier (hermes-*/subagent-* 24h, named 72h) with
  uncommitted changes or unpushed commits is archived to refs/hermes/archive/<tree> (HEAD +
  staged + unstaged + non-ignored untracked bytes, built with a temporary index; large untracked
  files skipped and listed) and then removed. A failed archive keeps the tree. Branch kept when
  published on a remote, otherwise the archive anchors its commits.
- Never touched at any age or budget: live hermes lock owners, any live process whose cwd/open fd
  is inside the tree (/proc on Linux, psutil cwd elsewhere), trees with recent file/ref activity,
  Kanban t_<hex> trees.
- No count cap; optional worktrees.max_total_gb evicts the oldest idle trees first.
- Per-profile registry (<HERMES_HOME>/worktree_repos.json) of every repo Hermes made a worktree
  in (hermes -w, /worktree new, subagent isolation, Desktop git pane); the 6h cron sweep unions
  it with its existing sources, scoped and throttled per profile.
- Subagent worktrees with commits/edits are archived and removed at child finish (branch kept).
- Interactive `hermes -w` (CLI and --tui) exit with a dirty/unpushed tree asks Keep (default) /
  Archive & remove / Remove and discard; non-interactive exits never ask.
- `hermes worktree restore <name> [--path]`, archives in `hermes worktree list`, a full
  decision table in `hermes worktree prune --dry-run`, archive retention (30 days).
- worktrees.archive_dirty: false restores the classic never-delete-dirty pruner exactly.
2026-10-17 21:49:14 -07:00
Teknium
65a6b6831e Port from code-yeongyu/oh-my-openagent#7151: worktree audit gains --json, --older-than, and external-tree visibility
omo's omo-agent-toolkit worktree-sweep (their PR #7151) added three
capabilities our hermes worktree command lacked:

- --json on list and prune: machine-readable audit/result payloads so
  scripts and agents can consume verdicts without scraping table output.
- --older-than DAYS: an age floor that only ever RESTRICTS reaping
  (young-but-reapable trees are kept); it never widens eligibility, so
  the existing safety invariants are untouched.
- External-tree visibility: linked worktrees registered outside
  .worktrees/ are now reported read-only in the audit (branch, locked,
  missing) instead of being invisible, and registrations whose
  directory has vanished are dropped via git worktree prune (metadata
  only, no files touched) during prune.

Not ported: omo's ancestor-of-default-branch merge test (our git cherry
patch-equivalence is strictly stronger under rebase/squash merges), and
their hardcoded external-root exclusion list (we exclude by location:
everything outside .worktrees/ is hands-off).

Tests: 9 new contracts in tests/hermes_cli/test_worktree_gc.py (age gate
restrict-only, external trees never reaped, stale-registration prune
dry-run/real, JSON shapes, negative --older-than rejected). Live E2E on
a scratch repo verified all three flags end to end.
2026-09-13 20:55:29 -07:00
Teknium
71a0a35e88 refactor(web_server helpers): second pass — helper dedupe in windows_ssh_runtime, webhook via atomic_json_write, table packing
- windows_ssh_runtime: _open_existing shared by _read_shared/remove_artifact; _win32 builds
  its namespace via importlib; reparse/path checks folded
- webhook: _save_subscriptions -> utils.atomic_json_write(mode=0o600) (same fchmod-before-
  rename + post-replace chmod semantics); base URL builder tightened
- web_server_messaging: override table tuples single-line, catalog entry builder flattened,
  WhatsApp payload from a field tuple; channel keys as one comprehension
- web_server_oauth: poller bodies read sess fields inline; status dicts packed
- web_server_gateway: health URL normalisation via one regex; Popen detach kwargs inline;
  topology cache getter collapsed
- web_server_cron/xai_retirement/win_pty_bridge/worktree_gc: small collapses

Verification: routes identical, --help byte-identical (webhook/worktree + subcommands),
golden corpus identical, 189 test files / 2925 passed / 0 failed.
2026-09-02 23:08:44 -07:00
Teknium
f0a451f1da refactor(web_server helpers): compact gateway/messaging/cron/oauth helpers and CLI utils (-21% LOC, zero behavior change)
- web_server_cron: one _cron_store_scope ctx manager replaces 3 copies of the
  set_hermes_home_override + use_cron_store + reset pattern
- web_server_oauth: _token_status helper for the 2 credential-status dict builders,
  logged-out sentinel, catalog table packed one card per 2-3 lines (key order kept)
- web_server_messaging: telegram request collapsed to shared detail strings, catalog
  loop unified, env-prefix aliases lifted to a module table, catalog tuples single-line
- web_server_gateway: mode ladder -> dict lookup, owned-platforms comprehension,
  action log table derived; docstrings compacted (every WHY kept)
- windows_ssh_runtime: _read_shared/_write_new/_check/_sid_str helpers, dispatch()
  if-chain -> _OPERATIONS table (arity-checked), _win32 returns a namespace
- worktree_gc/webhook/xai_retirement/write_approval_commands/win_pty_bridge/
  worktree_cmd: dead _require_webhook_enabled/_repo_root inlined, _run helper,
  duplicated except branches merged, docstrings compacted

Parity: route table identical, webhook/worktree --help byte-identical, golden
corpus of 27 pure-function outputs identical vs base 113f04616b.
2026-09-02 21:54:36 -07:00
Teknium
2c7f5d12b5 refactor(hclib): cron/update/install lifecycle — cron status, update_* receipts and recovery, install repair, service manager 2026-09-02 14:45:25 -07:00
Teknium
f309f92d30 feat: hermes worktree list/prune — attended reclaim for accumulated worktrees and merged branches
The startup pruner is deliberately conservative (unattended, pre-banner),
so real installs accumulate what it can never touch: trees preserved for
untracked-only scratch, and orphaned local branches beyond the two
auto-generated prefixes it deletes. A measured multi-agent box: 35 trees /
15GB / 244 local branches, 120 of them fully merged.

New attended surface (hermes_cli/worktree_gc.py + worktree_cmd.py):
- hermes worktree list — audit every tree: age, size, verdict, reason,
  plus deletable-branch count
- hermes worktree prune [--dry-run|--trees-only|--branches-only]
- /worktree prune [--dry-run] — same engine in-session; never touches the
  session's own active tree
- startup escalation: one WARNING when .worktrees/ exceeds 10 trees or
  5GB, naming the reclaim commands (silence is how boxes hit 15GB)

Safety invariants (shared with the startup pruner via cli.py primitives):
tracked modifications and unique unpushed commits never deleted at any
age; live-locked trees untouched; branch deletion gated on worktree
removal success; untracked-only scratch ARCHIVED to
~/.hermes/archive/worktree-prune/ before its tree is reaped.

Branch GC is content-gated, not name-gated: any local branch fully merged
or git-cherry patch-equivalent upstream is safe to delete (rebase merges
rewrite SHAs, so --merged alone misses the dominant leak); unique-commit,
checked-out, protected, and stale-base (>50 ahead) branches are kept.
Classification is parallel (8 workers) — 244 branches audit in ~64s live.

git timeouts degrade to keep (returncode 124) instead of crashing the
audit — live-verified failure on a 746MB .git repo.

16 behavior-contract tests against real git fixtures; live dry-run on the
production repo: 12 trees reclaimable, 120 branches deletable, 0 false
positives among kept trees.
2026-08-19 23:55:20 -07:00