Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
fix(upgrade): retire superseded install generations (#2122)
Call Whiteccc6039e640c
diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.ymlindex f6ead7629..580576423 100644--- a/.github/workflows/lint.yml+++ b/.github/workflows/lint.yml@@ -388,6 +388,7 @@ jobs:export VIBE_INSTALL_TEST_WHEEL="$(ls dist/*.whl)"pytest \tests/test_upgrade_flow.py \+ tests/test_install_generation_retirement.py \tests/test_install_script.py \tests/e2e/test_install_command.py \-v@@ -433,6 +434,23 @@ jobs:throw "Installer output missing custom package success message"}+ # Exercise retirement through the real hardlink/copy launcher on+ # Windows, not just mocked link fallbacks in the Python unit suite.+ 1..3 | ForEach-Object {+ & .\install.ps1+ if ($LASTEXITCODE -ne 0) { throw "Repeated installer failed" }+ $generations = @(Get-ChildItem "$env:USERPROFILE\.avibe\runtime\install-generations" -Directory)+ if ($generations.Count -ne 1) {+ $names = ($generations | ForEach-Object { $_.Name }) -join ", "+ $logPath = Join-Path $env:USERPROFILE ".avibe\logs\vibe_remote.log"+ if (Test-Path -LiteralPath $logPath) {+ Write-Host "Retention log tail:"+ Get-Content -LiteralPath $logPath -Tail 120+ }+ throw "Expected one selected generation, found $($generations.Count): $names"+ }+ }+- name: Verify vibe in fresh PowerShell sessionshell: pwshrun: |diff --git a/docs/plans/install-generation-retention-review-history.md b/docs/plans/install-generation-retention-review-history.mdnew file mode 100644index 000000000..db58829e8--- /dev/null+++ b/docs/plans/install-generation-retention-review-history.md@@ -0,0 +1,252 @@+# Install-generation retention: superseded design and review history++This is historical evidence, not the active contract. The direct user approved+a narrower recovery-oriented guarantee on 2026-09-25 at 01:43:52 Asia/Shanghai.+See `install-generation-retention.md` for the current implementation scope.++## Direct user acceptance revision (2026-09-25 Asia/Shanghai)++The direct user rejected the permanent exclusion of all pre-receipt history:+this PR must reclaim positively identified, unused historical installations as+well as bound future growth. The previous migration limitation below records an+earlier scope decision, not the current acceptance criterion. The implementation+does not yet meet this revised migration criterion; legacy artifact ownership,+concurrent staging and live-reference boundaries require isolated consuming+proof and independent review before publication. Directory age or a timestamp/+UUID name alone will not authorize deletion.++The user also explicitly required no README explanation of this internal+mechanism. The new English section has been removed, restoring both READMEs to+the PR baseline; maintenance documentation and this PR's evidence ledger own the+technical contract. Normal users should not have to manage generations.+Production installation mutation, service restart and merge remain unauthorized.++## Contract and scope++Successful automatic/manual upgrades and installer reruns must not retain one+complete environment per operation forever. Both installer naming schemes use+the shared Python activation lifecycle and the existing `.install.lock`.+No business state, rollback machinery, production installation, or service+restart is part of this change.++The previous GC in PR #1711 was removed because it could not prove ownership:+concurrent staging, alternate launchers, logical interpreter paths, and restart+handoffs invalidated a simple "keep latest two" rule. We therefore collect only+generations with a successful-activation receipt, not arbitrary old directories.++## Retention invariant++- Before switching a launcher, under the install lock, collect receipt-owned+ generations that no recorded stable launcher, live user process, current+ candidate, or source handoff references. The immediately previous target+ remains intact until a later operation.+- Pending, unknown, or unreadable restart ownership, concurrent installer staging,+ and incomplete process/receipt visibility defer collection. Both bootstrap+ scripts publish an installer PID marker before taking their source snapshot;+ another installer's live marker protects its entire handoff.+- Process references are collected for the managed install owner's filesystem+ identity, the updater itself, and recorded service/UI PIDs. Owner, command+ line, executable, or cwd inspection that is denied or ambiguous defers+ collection. Relative values in interpreter/script and explicit handoff path+ roles defer collection: the observed cwd cannot prove the launch cwd after a+ `chdir`. Generic application arguments are data, not paths inferred from+ slashes or from a coincidental file in the current cwd. Code/eval operands+ are not interpreted as filenames.+- Each successful activation attempts to record its stable launcher in its+ generation. All recorded launchers participate in collection, including symlink,+ hardlink, and copy fallback identities. Once a symlink, hardlink, or valid copy+ marker proves one generation, collection does not broaden that proof into a+ byte match across identical wheel copies. Missing or stale copy markers use the+ conservative byte fallback and cannot authorize deletion without a match.+- When a second launcher targets an already receipted generation, its launcher+ reference is written under the install lock before the launcher is published.+ A failed reservation leaves the launcher and existing receipt unchanged. Fresh+ candidates are still receipted only after activation.+- An alias activation targeting an unreceipted generation never creates a receipt;+ this preserves the permanent-unowned migration and failed-receipt contract.+- Failed candidates keep the existing discard path. Cleanup and receipt failures+ are logged and cannot turn a committed activation into failure.+ A failed new ownership receipt leaves that generation permanently unowned and+ excluded from automatic collection; it is not adopted on the next activation.+- With one stable launcher and no extra live references, repeated operations+ retain at most the selected and immediately previous managed generations.+ Proven extra live processes/launchers retain the generations they need;+ ambiguous process provenance retains the entire owned set for that operation.+ A later successful operation retries deferred cleanup of owned generations+ only. The bound assumes their activation receipts were written successfully.++## Superseded migration limitation (earlier orchestrator decision)++The original implementation treated pre-receipt generations as unowned history,+not collectible garbage. Neither+timestamps nor UUID names prove that an unknown custom launcher no longer uses+them. These directories remain untouched, including a legacy source generation.+The previously reported 6.5 GiB on this Mac is **not** automatically reclaimed;+it needs separate operator-verified cleanup. The fixed lifecycle bounds new+accumulation without claiming to infer ownership of released artifacts.+Externally created launcher aliases are outside the managed activation protocol.+The process-reference surface is the OS image/cwd, logical argv, supported+interpreter source operands and explicit Avibe handoff options, not arbitrary+code strings, environment variables, open-file/mapping inspection, or the+argument grammar of every third-party application. Unknown supported-interpreter+options and unreadable/ambiguous command fallback still defer collection.++## Validation plan++Use test-owned homes and real temporary files/processes. Cover repeated shared+activation, manual/API upgrades, installer reruns, canonical uv environments,+all launcher fallback shapes, logical Python symlinks, pending restarts, concurrent+staging/source handoffs, unowned historical directories, and cleanup failures.+Run focused existing upgrade/installer/restart tests, changed-file Ruff, and the+normal PR CI and exact-head Codex review gates. No production cleanup or restart.++## Local evidence++- The focused retention suite after the safety-boundary correction: 60 passed.+- The install/upgrade consumer suite (`test_upgrade_flow`, retention, installer+ script, and install-command E2E): 292 passed, 1 skipped locally because Docker+ is unavailable.+- First-head retention, dependency repair, and integrity suites: 255 passed;+ the Docker install test is skipped locally because Docker is unavailable.+- First-head CI pipeline contracts: 71 passed. Changed-file Ruff, shell syntax,+ and diff whitespace checks pass after the correction.+- Real temporary Python processes prove logical interpreter/source-argument+ discovery and collection after process exit. A read-only macOS process probe+ exposed `KERN_PROCARGS2` denial for `login`; command-reader fallback handles+ recoverable argv access, while denied owner/cwd/cmdline/exe provenance defers+ collection instead of guessing.+- Packaged Linux and Windows repeated-install bounds passed in first-head CI;+ every new head still requires fresh exact-head CI and Codex review.++## Review correction++The orchestrator found two gaps on `4bdcfe4d3`: collector restart parsing+accepted unknown future states, and the retry claim obscured permanent retention+after a failed receipt write. Retention now fails closed for unknown/missing/null+restart state without changing shared restart admission. A follow-up activation+test proves a failed-receipt generation stays unowned while subsequent successfully+receipted generations return to the ordinary two-generation bound.++## Safety-boundary correction++The review of `7a1d186dc5` identified three manifestations of two root causes:++| Finding | Root cause | Contract-preserving boundary |+| --- | --- | --- |+| A different-user worker was skipped | Process visibility was scoped to the updater's username | Match the managed root owner through platform/filesystem identity, while always including the updater and recorded service/UI PIDs; uncertainty defers collection |+| A relative interpreter path was skipped | Logical argv was filtered before cwd/provenance handling | Normalize quoted fallback argv, resolve relative values against the observed cwd, and defer when the launch cwd cannot be proven |+| An existing receipt lost a newly published alias | Receipt ownership was updated after launcher publication | Reserve the alias in the existing receipt under the same lock before publication; failed reservation aborts without changing the launcher |++The exact-head CI UI failure is a separate test-harness issue: all 6,023 UI+assertions passed, then a delayed `ToastProvider` timer accessed `window` after+test teardown. It is intentionally outside this retention patch.++The current process-scan correction skips only Linux tasks positively marked+`Kthread: 1` in `/proc/<pid>/status`. Empty or unreadable command lines from+ordinary userspace processes still defer collection; no process is ignored+based only on a name, status, or missing argv.++The local pre-push review also required narrow hardening corrections:+bare interpreter names from other processes and separator-free source arguments+fail closed as relative references; only the current collector's own bare+interpreter token is ignored. Ambiguous unquoted fallback command lines defer+collection, including path-bearing options whose quoting cannot be proven.+Inline `--candidate=`, `--launcher=`, and `--source-generation=` operands are+also inspected rather than discarded as flags. Windows owner probes declare+pointer-sized API handles and skip PID 0. A protected Windows process may use+the platform-reported account name when the token handle is unavailable; the+managed root carries the corresponding SID/account identity, while an+unreadable or ambiguous identity still defers collection. Processes that exit+during owner inspection are skipped as a normal snapshot race rather than+deferring the whole collection pass. An alias cannot adopt an unreceipted+generation. Copy fallback byte comparison is used only when the launcher has+no proven symlink, hardlink, or valid generation marker; this keeps repeated+identical wheel installs bounded while retaining marker failures conservatively.++## Current-head diagnosis (2026-09-24 UTC)++The direct delivery owner independently exhausted REST reviews, inline comments,+issue comments and reactions, GraphQL threads, and the exact-head Actions job+inventory for `b0c134dd19e3cdd596154b544c480142f6d06171`. Review is terminal+with two findings, not a pass. Eight threads remain unresolved across the PR.+Lint run `36024937039` attempt 1 is terminal failure: Linux installer, Windows+installer and their aggregate fail; the other 15 jobs, including UI, pass.++Six distinct Codex findings-bearing heads are recorded by their review envelopes:+`75f7a7a`, `7a1d186`, `561e4bd`, `bc4c327`, `7c33056`, and `b0c134d`.+The earlier independent findings on `4bdcfe4` are additional evidence, not an+extra Codex review. The repeated process-provenance and launcher-identity classes+require circuit-breaker diagnosis before another edit or push. The owner has+accepted that boundary; a peer independently reproduced Linux's false deferral+and will review the local correction before publication.++| Current evidence | Root cause | Scoped decision |+| --- | --- | --- |+| Shell `-c` text and Git refs with separators defer every collection | Arbitrary argument text was treated as a path without a path-bearing role | Classify interpreter/script and explicit handoff path roles; code strings and ordinary data are not relative path evidence |+| `python worker.py` after `chdir` loses a live source reference | Separator-free script operands were ignored | Recognize source operands even when absent beneath the observed cwd; unknown launch cwd still defers |+| Hardlink lookup returns a directory symlink before the owned real directory | Launcher proof and receipt ownership use different path identities | Normalize the proven generation through the shared canonical path owner |+| Fresh-byte test changed file length | The test did not reproduce the stat-cache collision | Use equal-size bytes and preserve mtime; demonstrate old code failure |+| Windows reaches three generations without a visible deferral reason | Successful installer activation swallows diagnostic output | Expose the existing retention logger on installer stderr and preserve successful activation output in PowerShell |++Windows' specific remaining deferral cause is not yet proven. Do not claim the+shell fix resolves Windows until the packaged Windows consumer demonstrates it.+Keep the receipt schema, shared lock and collection boundary unchanged; do not+add dependencies/workflows or mix unrelated UI changes. The direct user's later+historical-reclamation requirement above supersedes the blanket exclusion of+pre-receipt history, but does not authorize adoption of arbitrary directories.++Independent pre-push review on the unchanged published head found a further+argument-role parsing gap: clustered shell `-eo`/`-euo` options did not consume+their `pipefail` operand. This is the same process-provenance class, not a new+findings-bearing reviewed head. Full REST/GraphQL review and exact-head CI+inventories were independently refreshed; the eight unresolved threads, six+Codex findings-bearing heads and failed run are unchanged. The scoped local+correction must cover clustered shell option operands with real child processes.+Node inline configuration options are self-contained; supported boolean options+must not shift the source position. Unknown option arity and relative preload+paths still require conservative treatment rather than interpreting arbitrary+application data as paths. Final independent review remains required.++Evidence for the revised historical acceptance criterion:++- The immutable initial generation implementation (`2eb8b6dd0`) used+ `generation/tools/avibe-os`, later changed to `generation/uv/tools/avibe-os`.+ Both manual/API runtime staging operations already held the shared install+ lock. Shell installation staged outside that lock and encoded its shell PID+ in the timestamp-based generation name; that is relevant to protecting a+ concurrent legacy handoff, not sufficient ownership evidence for deletion.+- An offline minimal wheel installed by the real local uv 0.9.8 into a private+ temporary home produced `uv-receipt.toml` with an explicit `avibe-os`+ requirement and a `vibe` entrypoint pointing into the exact generation's+ export directory. It also produced `pyvenv.cfg` and the corresponding package+ environment. All HOME/XDG/tool/cache paths were isolated, downloads disabled,+ and the temporary installation was removed by the probe's context manager.+- These existing artifacts are candidate positive ownership evidence, not yet+ an implemented migration or proof of absent external launcher references.+ Independent diagnosis must reconcile legacy aliases and staging before+ historical collection can ship.++Local correction evidence before independent pre-push review:++- Current local validation: 275 retention/upgrade tests and 59 installer tests+ pass (334 total); Docker installer E2E is skipped because Docker is unavailable.+ Changed-file Ruff, compileall, shell syntax and diff whitespace checks pass.+- The new consuming boundary matrix failed 10 cases on unchanged `b0c134d`+ production code; the existing relative-path-with-separator control passed.+ This includes real Bash, sh and Python children, `worker.py` after `chdir`,+ an alias-first hardlink lookup, and ordinary non-path application operands.+- After correction the same matrix passes; the expanded classifier cases cover+ Python option clusters/value operands/`--`, eval and stdin, shell/PowerShell+ source roles and unknown option deferral.+- The subsequent peer-identified cluster/configuration matrix failed 13 cases+ before its correction, with 32 controls passing. The updated focused suites+ passed 352 tests, including actual Bash option clusters; installer diagnostics+ now preserve the exception reason without printing a non-fatal traceback.+- The equal-size/equal-mtime marker regression was executed against the immutable+ `7c33056` marker function in an isolated test process and failed as intended;+ it passes with the fresh-byte implementation.+- The real repeated shell-installer consumer verifies both the two-generation+ bound and visible retention output. The CLI diagnostic test verifies deferred+ collection still returns activation success and restores logging configuration.+- Packaged Windows convergence remains a required remote gate, not a claim+ inferred from the host-platform argument simulation.diff --git a/docs/plans/install-generation-retention.md b/docs/plans/install-generation-retention.mdnew file mode 100644index 000000000..2d575104c--- /dev/null+++ b/docs/plans/install-generation-retention.md@@ -0,0 +1,293 @@+# Retire superseded Avibe installations++## User-approved contract++On 2026-09-25 at 01:43:52 Asia/Shanghai the direct user approved a simpler+recovery-oriented lifecycle. The stable `vibe` command must remain usable;+arbitrary stale processes and commands that directly name retired environments+are not guaranteed to keep working. Their interrupted tasks are not promised+lossless recovery. This supersedes the former universal process/alias retention+contract and permanent exemption for environments without activation receipts.++Normal upgrades and installer reruns must reclaim unused historical Avibe+environments as well as stop future accumulation. Normally one selected+generation remains after handoff. Explicit current invocation, official+service/UI and concurrent handoff references may temporarily require more.+There is no implicit backup/rollback policy.++This is internal installer infrastructure. Both READMEs stay unchanged relative+to the PR baseline. No business-state change, production installation mutation,+service restart or merge is authorized.++## One owner, existing evidence++`vibe/install_generations.py` owns collection under the existing `.install.lock`.+It does not enumerate all user processes, interpret arbitrary interpreter+arguments, maintain an alias registry, or add an activation-receipt schema.++Existing uv installation artifacts identify eligible environments:++- a direct, real child of the managed generation root, never a directory alias;+- either released `tools/<package>` or `uv/tools/<package>` layout for+ `avibe-os` or `vibe-remote`, with `pyvenv.cfg`;+- a readable uv tool receipt naming that package and its `vibe` export into+ this exact generation.++Names and age alone never establish ownership. Unrecognized or incomplete+directories remain untouched. Canonical uv installs outside this root are+outside the deletion scope. Missing Avibe-specific activation receipts do not+exclude a positively identified uv installation.+The generation must contain only its chosen released installation layout and+marker, not a second layout or extra tool. The export `bin/` may contain only+the receipt's exports. Directory aliases are not followed.++## Collection boundaries++After candidate validation and launcher publication, collect retired+environments while preserving:++1. The stable launcher's symlink/hardlink/validated-copy target, including the+ command selected by PATH if this invocation came through a different alias.+2. This invocation's module/interpreter environment.+3. The recorded official service and UI interpreters until their handoff ends.+4. Pending restart and concurrent installation handoffs.++The optional PATH lookup only adds positively identified managed targets to the+keep set. An unrelated command earlier on PATH does not block retirement by a+validated managed launcher; it is outside the deletion scope.+If either selected command is positively mapped into this root but that+generation is unrecognized, collection defers: it can be a wrapper depending+on another generation. This is not the unrelated outside-PATH veto.++Only official recorded PIDs need process inspection. Unreadable or ambiguous+official runtime references defer collection; unrelated user processes do not.+The collector never signals or terminates runtime processes.++Full restart success and successful normal CLI startup retry retirement after+readiness has been established. Failure to start does not run final collection.+This removes the old official environment once it has actually exited. When no+runtime exists, a validated installer candidate can retire unused predecessors.++Runtime staging and Windows deferred activation reuse the existing installer+PID marker. Ownership is transferred to the helper while the parent still holds+the install lock. Released shell installers encode their PID in the generation+name; this can conservatively protect a live legacy handoff but cannot authorize+deletion by itself. Existing source-snapshot admission remains unchanged.++Cleanup uses a nonblocking acquisition of the same lock and is best-effort.+Busy ownership, unreadable evidence or a filesystem deletion failure keeps data;+no cleanup/marker-removal error after launcher publication can roll back a+successful activation or cause its active target to be discarded.+Retirement removes package contents before uv's receipt and `pyvenv.cfg`.+A partial deletion (including Windows loaded-library denial) therefore keeps+the existing evidence for the next pass; no new tombstone/receipt namespace is+needed. A failure while deleting the final proof files can leave tiny metadata+residue but not a full unidentifiable environment.++## Known by design++- Arbitrary detached workers and explicit paths/secondary aliases into retired+ environments may stop working. The selected stable command remains usable;+ this is recovery, not a guarantee that interrupted work is lossless.+- Canonical uv environments outside `install-generations` are never deleted.+ An outside or unrecognized plain/copy invocation cannot authorize retirement+ of managed generations; collection waits for a later identified activation.+ A different readable PATH-selected command with no managed target adds no+ retention pin and cannot prevent normal managed installations from converging.+- Incomplete, moved, malformed or mixed-use directories without matching uv+ evidence are retained. No directory name, age or missing Avibe receipt makes+ a directory disposable.+- Legacy timestamp shell staging has a liveness-only PID pin. Released Windows+ GUID staging/helpers have no ownership marker and cannot always be+ distinguished from retired installs. They may lose a concurrent candidate+ and need a retry through the selected command. New helpers publish their PID+ under the install lock before reporting a successful handoff.+- An unreadable official runtime reference, pending restart, active installer+ or deletion denial may temporarily retain extra generations. There is no+ universal hard count while one of these references remains unsettled.+- README changes are deliberately removed at the user's request: this is an+ internal lifecycle mechanism, not a new user workflow.++## Verification++All tests use private homes, files and processes. Cover:++- repeated timestamp/UUID installations, manual/API upgrades and canonical uv;+- both legacy layouts and both package names, including a many-generation+ migration fixture without activation receipts;+- active launcher identity across symlink, hardlink, copy, stale marker and+ alias-first directory enumeration;+- current invocation and official service/UI handoff, successful readiness+ versus startup failure, and retired unrecorded old processes;+- pending/future restart records, concurrent staging, legacy shell PID and+ Windows deferred-helper ownership;+- unknown/incomplete/outside/symlinked directories and non-ASCII paths;+- deletion/inspection/marker failures without invalidating successful activation;+- real repeated shell consumption and exact-head Linux/Windows packaged CI.++The initial recovery-contract consumer run against the old implementation was+8 failed / 3 passed: repeated installation across six layout/link combinations,+historical reclamation and unregistered-process retirement failed as expected;+failed-candidate, cleanup-failure and outside-data controls passed. The revised+boundary suite plus readiness consumers passed 59 tests, including real offline+uv installations in private homes; the related six-suite run passed 666 tests+and four subtests. These results precede the pre-push corrections below, and+are not a current-head CI or Codex pass.++### Independent pre-push inventory and scoped correction++The independent review of fingerprint `07230024d8d98fd4aa5ecbe5b4d4f780f36ab4b54e91bbcc98e80071338de21f`+reran 620 consuming tests but reported two actionable classes:++| Class | Evidence | Scope decision |+| --- | --- | --- |+| Positive installation identity | Four mixed-layout/extra-bin fixtures lost unrelated data | Make the permitted root depend on the one chosen layout; allow only receipted exports in `bin/`. Keep evidence-last retirement, independently verified safe. |+| Selected-command authority | Collecting from an outside alias deleted the normal command's target | An outside invocation cannot authorize retirement. Also protect PATH's selected command through one ordinary lookup, covering inside-root aliases of the same class without an alias registry. |++Before the correction, nine regression cases failed (the four mixed-data+shapes, outside/inside aliases through both explicit and inferred callers, and+the canonical-to-managed handoff policy); six normal repeated-install controls+passed. Both findings are accepted. They do not add a reviewed GitHub head.+The root classes remain within the user-approved recovery contract; no global+process scan, new receipt/schema, deletion-scope expansion or user decision is+needed. The fake shell uv fixture must match uv's real export-only `bin/`+layout, with its test support files inside the tool environment.++The minor notes (stale official PID/marker can defer, a future new export is+retained) are conservative liveness limitations, not reasons to delete more.+After this correction the retirement suite passes 64 tests and the real shell+installer suite passes 59 tests. The six-suite run passed 675 tests and four+subtests. Independent re-review of fingerprint+`5f780443dc3ee3d0cf2b4bc73ec8d94153b7ad314e87964e3656281761b5cfac`+confirmed both fixes and passed 867 tests, one existing Windows-only skip and+four subtests, but found one further liveness defect in the optional PATH lookup:++| Class | Evidence | Scope decision |+| --- | --- | --- |+| Optional selector veto | A foreign symlink or plain `vibe` earlier on PATH retained all three managed activations | PATH lookup adds confirmed managed targets only. Remove the unmatched-target veto; retain primary invocation validation and inside-root alias protection. No argv heuristics or extra ownership metadata. |++Both foreign-PATH regression cases fail before this correction, while all ten+normal convergence and inside/outside alias controls pass. This is another local+fingerprint, not a new reviewed GitHub head. The decision restores the approved+historical-reclamation contract instead of accepting unbounded accumulation.+After the correction, all 66 retirement tests pass (17.75s). The expanded+consumer run (retirement, upgrade flow, shell installer, restart supervisor, CLI,+and every runtime suite) passes 869 tests and four subtests, with one existing+Windows-only skip (126.97s; 28 existing SQLAlchemy reflection warnings).+Changed-file Ruff, shell syntax and whitespace checks pass. A terminal+independent review cleared fingerprint+`789b764530143110f89b94563fc2724b095a5e4bc5a65ef238bcbffe889658df`+with the same consuming results. Published commit+`091d11d0aff9c337f3bcae1754a1854a95e55d25` matches that diff exactly.++Independent pre-push review is required for the complete revised diff and its+failing-before/passing-after matrix. The original Watch remains armed. No manual+Codex review trigger or retry-until-green CI strategy is permitted.++### First recovery-contract review: bounded correction decision++Full REST reviews/comments and GraphQL thread/comment pagination at `091d11d`+show 12 threads: nine resolved and three new unresolved P2 findings in Codex+review 5309129819. There are seven distinct findings-bearing Codex heads+overall, exactly one after the recovery rewrite; reply reviews do not count.+The repeated selector and official-reference classes triggered diagnosis+before further implementation. Independent peer run `ca4ed3c2c51b` re-fetched+the threads, verified the immutable diff, reran the isolated failure probes,+and consumed all four real-uv installation cases. Its first request timed out;+that transport failure was not treated as approval.++The direct delivery owner authorizes one reversible, contract-preserving+correction after that diagnosis. No new receipt/schema, global scan, dependency,+workflow, deletion-root expansion, or README change is involved:++| Boundary | Failing-before evidence at `091d11d` | Scope decision |+| --- | --- | --- |+| Installer-marker publication (4097576298) | Empty marker in an incomplete generation makes three activations retain all five directories. Direct shell write failure also leaves a torn marker. | Both shell and PowerShell write a private staging file and rename before reading the source snapshot or starting uv. Failed publication aborts before handoff and cleans up its own failed staging. Keep malformed published markers conservative; do not treat unreadable GUID markers as dead or introduce age-based recovery. |+| Selected-command authority (4097576304) | Missing-receipt symlink/hardlink/copy selections delete all recognized history. An in-root wrapper breaks the selected command from exit 0 to 126; independent peer also reproduced the PATH-selected form. | If either lookup positively maps into an unrecognized generation, defer. A foreign outside-root command still adds no pin and no veto. Preserve normal convergence and identified inside-root aliases. |+| Official Windows reference completeness (4097576313) | Live base-Python UI child loses its generation when the redirector parent is absent or exits during inspection; present-parent control retains it (simulated Windows APIs). | Require the parent only when the child's own absolute paths do not identify a generation. On parent loss, distinguish a child that has exited from a still-live child; only the latter defers. No environment-variable or arbitrary-process scanning. |+| Released uv Windows receipt identity | Portable fixtures for both layouts are rejected with logical entrypoint `vibe` and physical export `vibe.exe`; ordinary POSIX controls are recognized. Exact CI reports zero managed environments. | Accept uv's bounded Windows suffix pair while retaining package, export-directory and exclusive-layout checks. Upstream uv 0.12.18 `ToolEntrypoint::new` removes the executable suffix from the logical name. Native Windows convergence remains an exact-head CI gate. |+| Deferred-activation consuming fixture | PERMISSIONS-026's existing fixture raises because its candidate is outside the authoritative managed root; its minimal fake process then lacks `terminate`. | Put the test candidate inside its isolated installation root and verify the helper PID marker. Preserve caller-context stripping assertions; do not weaken the production ownership guard. |++The marker consumer fallback suggested by the peer is deliberately not adopted:+an unreadable or malformed GUID marker cannot prove its owner has exited.+Atomic publication fixes the demonstrated producer failure without guessing at+historical state. A corrupt marker created outside that protocol still defers;+this PR's marker format has not shipped and needs no adoption/migration heuristic.++Exact-head lint 36046733488 attempt 1 is terminal failure: 14 of 18 jobs passed.+Linux packaged installer and its aggregate passed. Windows smoke and unit shard+2/6 failed as above; the unit aggregate also failed. UI failed separately on+mobile-WebKit search-focus typing timing out after all 6103 Vitest assertions+passed, not the earlier ToastProvider timer error. Session `ses6dzapvbkwm` owns+read-only investigation of that distinct CI boundary. No UI edits or blind+reruns are part of the retention correction.++Before changing production code, 16 distinct regression cases failed against+`091d11d`: two Windows receipt-layout cases, five selected-command cases, five+Windows parent/own-reference cases, three real-shell publication failures,+and the PowerShell publication-order contract. The first 45-case run had+15 failures and 30 passes; strengthening the shell rename-failure admission+trace then exposed its additional failure. PERMISSIONS-026 independently+failed before its fixture correction.++After the correction, the full retirement, shell-installer and permissions+entrypoint suites passed 196 tests (131.09s; five existing SQLAlchemy warnings).+Two additional controls explicitly retain corrupt published GUID markers;+they do not pretend that absent provenance proves a dead owner. Changed-file+Ruff, shell syntax and whitespace checks pass. Broader consumers and independent+frozen-diff review are recorded in PR evidence before publication.++A terminal independent review of the complete frozen correction is required+before another push. The three new threads remain unresolved until published+proof; the original Watch stays armed. Prior passing test counts do not override+this inventory.++## Review accounting++### Post-master-sync peer finding: stale follow-up ownership++The independent pre-push review of local merge `e4b2b9df4` found one+liveness defect: a failed supervisor's `pending_restart.json` survives future+jobs with different IDs, and the collector treated its existence as permanent+handoff ownership. This is a local finding, not another findings-bearing Codex+head. The remote head remains `a29e596a3`, with a clean head-bound automatic+review and all 12 threads resolved; its one exact-head lint run failed during+dependency installation. The local master merge includes the separately merged+SQLAlchemy fix from #2176 rather than duplicating it in this PR.++The delivery owner narrows the correction to the existing restart-ownership+boundary after inspecting the producer, consumer and successful supervisor tail:++- Ordinary scheduled/running ownership keeps the existing PID identity and+ bounded seed-grace policy, independent of a stale follow-up's job ID.+- A failed/cancelled/otherwise terminal non-successful job, missing status,+ or expired abandoned seed cannot turn a leftover follow-up into an owner.+- Success is not alone proof that the handoff ended: collection precedes+ follow-up consumption. A matching (or released unscoped) follow-up still pins+ a successful supervisor using the same PID identity/grace policy. A different+ job's marker adds no pin.+- Unknown or unreadable status remains conservative. The collector never+ consumes or rewrites the follow-up marker; that still belongs to the supervisor.++The existing follow-up test is expanded at the activation/retirement boundary+to distinguish live handoffs from failed, superseded, expired and PID-reused+ones and to verify repeated convergence without changing the marker. No new+schema, process scan, deletion eligibility, workflow or README change is needed.+Before the production correction, the matrix and existing restart controls+produced 11 failures (all stale owners retaining every generation) and 11 passes.+After the correction, all 22 pass. Independent frozen-diff re-review is required+before publishing this correction and the master synchronization.++The published head before this simplification is+`b0c134dd19e3cdd596154b544c480142f6d06171`: eight unresolved threads, terminal+Codex findings, and terminal installer CI failure. Six distinct Codex heads+carried findings before the simplification; earlier independent findings are+recorded separately. Repeated process-provenance and launcher-identity classes+triggered circuit-breaker diagnosis. The direct user's new decision narrows the+guarantees rather than claiming those earlier findings were false.++Historical contracts, findings, controls and test counts are retained in+`install-generation-retention-review-history.md`. Those pass counts do not prove+this revised implementation. Fresh exact-head review/CI, zero unresolved threads+and a direct report are required for delivery; explicit user authorization is+still required for merge.diff --git a/install.ps1 b/install.ps1index 20b107227..f95f25347 100644--- a/install.ps1+++ b/install.ps1@@ -418,15 +418,25 @@ function Invoke-UvToolInstallAttempt {$generationBin = Join-Path $generationRoot "bin"$stableBin = Get-StableBinDirectory$stableLauncher = Join-Path $stableBin "vibe.exe"- # The candidate's shared Python activation owner resolves this snapshot to- # a generation. PowerShell must not duplicate junction/symlink identity.- $launcherState = Get-LauncherState -Launcher $stableLauncher -RuntimeHome $runtimeHome- $previousSourcePath = $launcherState.SourcePathNew-Item -ItemType Directory -Force -Path $generationTools, $generationBin, $stableBin | Out-Null-+ # Protect the source snapshot throughout staging outside the Python lock.+ # The collector ignores this marker only for its own candidate.+ $installerMarker = Join-Path $generationRoot ".avibe-installing"+ $installerMarkerTemporary = "$installerMarker.new"$previousToolDir = $env:UV_TOOL_DIR$previousToolBinDir = $env:UV_TOOL_BIN_DIRtry {+ try {+ Set-Content -LiteralPath $installerMarkerTemporary -Value $PID -Encoding UTF8+ [System.IO.File]::Move($installerMarkerTemporary, $installerMarker)+ } catch {+ Remove-Item -LiteralPath $generationRoot -Recurse -Force -ErrorAction SilentlyContinue+ throw+ }+ # The candidate's shared Python activation owner resolves this snapshot to+ # a generation. PowerShell must not duplicate junction/symlink identity.+ $launcherState = Get-LauncherState -Launcher $stableLauncher -RuntimeHome $runtimeHome+ $previousSourcePath = $launcherState.SourcePath$env:UV_TOOL_DIR = $generationTools$env:UV_TOOL_BIN_DIR = $generationBin$result = Invoke-NativeCommand -FilePath "uv" -Arguments (@("tool", "install") + $Arguments)@@ -507,8 +517,14 @@ function Invoke-UvToolInstallAttempt {Output = if ($activation.Output) { $activation.Output } else { "candidate Avibe environment could not be activated" }}}+ if ($activation.Output) {+ # Retention may defer safely while activation succeeds. Do not hide+ # its ownership/visibility diagnostics in captured native output.+ Write-Host $activation.Output+ }return $result} finally {+ Remove-Item -LiteralPath $installerMarker -Force -ErrorAction SilentlyContinueif ($null -eq $previousToolDir) { Remove-Item Env:UV_TOOL_DIR -ErrorAction SilentlyContinue } else { $env:UV_TOOL_DIR = $previousToolDir }if ($null -eq $previousToolBinDir) { Remove-Item Env:UV_TOOL_BIN_DIR -ErrorAction SilentlyContinue } else { $env:UV_TOOL_BIN_DIR = $previousToolBinDir }}diff --git a/install.sh b/install.shindex 44a7d4424..54b3dbb36 100755--- a/install.sh+++ b/install.sh@@ -458,6 +458,17 @@ uv_tool_install() {return 1fimkdir -p "$generation_tools" "$generation_bin" "$stable_bin_dir"+ # Publish before the source snapshot. Collection in another activation+ # retains this installer's entire handoff while the shell is still alive.+ # The marker protects staging even after uv has finished its tool receipt.+ local installer_marker="$generation_root/.avibe-installing"+ local installer_marker_temporary="$installer_marker.new"+ if ! printf '%s\n' "$$" > "$installer_marker_temporary" ||+ ! mv -f -- "$installer_marker_temporary" "$installer_marker"; then+ warn "Could not protect the installer handoff"+ rm -rf -- "$generation_root"+ return 1+ fiif [ -e "$stable_bin_dir/vibe" ] || [ -L "$stable_bin_dir/vibe" ]; thenprevious_target="$(resolve_binary_path "$stable_bin_dir/vibe" || true)"local current_protocol=""@@ -477,7 +488,8 @@ uv_tool_install() {fifi- if UV_TOOL_DIR="$generation_tools" UV_TOOL_BIN_DIR="$generation_bin" uv tool install "$@"; then+ # Suppress package-manager progress only, not activation/retention diagnostics.+ if UV_TOOL_DIR="$generation_tools" UV_TOOL_BIN_DIR="$generation_bin" uv tool install "$@" 2>/dev/null; thenVIBE_CANDIDATE_BIN_PATH="$generation_bin/vibe"if [ ! -x "$VIBE_CANDIDATE_BIN_PATH" ]; thenwarn "uv completed but the candidate vibe launcher was not created"@@ -548,6 +560,7 @@ uv_tool_install() {fiVIBE_TOOL_BIN_DIR="$stable_bin_dir"VIBE_BIN_PATH="$stable_bin_dir/vibe"+ rm -f -- "$generation_root/.avibe-installing" || warn "Could not remove the completed installer marker"return 0firm -rf -- "$generation_root"@@ -559,9 +572,9 @@ install_package_candidate() {shiftif [ "$package_spec" = "$PACKAGE_NAME" ]; then- uv_tool_install "$package_spec" --force --refresh "$@" 2>/dev/null+ uv_tool_install "$package_spec" --force --refresh "$@"else- uv_tool_install "$package_spec" --force "$@" 2>/dev/null+ uv_tool_install "$package_spec" --force "$@"fi}diff --git a/tests/e2e/test_install_command.py b/tests/e2e/test_install_command.pyindex 33c353916..25e91bded 100644--- a/tests/e2e/test_install_command.py+++ b/tests/e2e/test_install_command.py@@ -90,7 +90,14 @@ def test_install_command_starts_vibe_for_new_user_without_local_bin_on_path():'echo "$status" | grep -q \'"running": true\' && break; '"sleep 1; ""done; "- 'echo "$status" | grep -q \'"running": true\''+ 'echo "$status" | grep -q \'"running": true\'; '+ # This runtime belongs to the disposable container. Stop it before+ # checking retirement down to the selected generation.+ "/home/installer/.local/bin/vibe stop; "+ "for attempt in 1 2 3; do "+ "bash /work/install.sh; "+ 'test "$(find /home/installer/.avibe/runtime/install-generations -mindepth 1 -maxdepth 1 -type d | wc -l)" -eq 1; '+ "done")command = ("apt-get update >/dev/null && "diff --git a/tests/scenarios/permissions/test_cli_invocation_authority.py b/tests/scenarios/permissions/test_cli_invocation_authority.pyindex ed2537660..c44b0606a 100644--- a/tests/scenarios/permissions/test_cli_invocation_authority.py+++ b/tests/scenarios/permissions/test_cli_invocation_authority.py@@ -675,11 +675,14 @@ def test_permissions_026_a_deferred_activation_runs_as_the_installation(launcher, so it is Avibe's own work by construction. The interpreterisolation this spawn already needs is unchanged — only the caller hop ends."""- from vibe import upgrade+ from vibe import install_generations, upgradecaller_environment("member")monkeypatch.setenv("PYTHONPATH", str(tmp_path / "checkout"))- candidate = tmp_path / "generation" / "python"+ root = tmp_path / "install-generations"+ monkeypatch.setattr(upgrade, "atomic_uv_install_root", lambda: root)+ generation = root / "generation"+ candidate = generation / "bin" / "python"candidate.parent.mkdir(parents=True, exist_ok=True)candidate.touch()monkeypatch.setattr(upgrade, "_candidate_python", lambda launcher: candidate)@@ -692,6 +695,9 @@ def test_permissions_026_a_deferred_activation_runs_as_the_installation(class Proc:pid = 99001+ def terminate(self):+ pytest.fail("a valid installation handoff must not terminate its helper")+return Proc()monkeypatch.setattr(upgrade.subprocess, "Popen", fake_popen)@@ -699,13 +705,14 @@ def test_permissions_026_a_deferred_activation_runs_as_the_installation(upgrade.defer_upgrade_activation(SimpleNamespace(launcher=tmp_path / "stable" / "vibe",- candidate_launcher=tmp_path / "generation" / "vibe",+ candidate_launcher=generation / "bin" / "vibe",source_generation=None,),parent_pid=os.getpid(),)assert "__activate-upgrade" in spawned["command"]+ assert (generation / install_generations.INSTALLER_PID).read_text() == "99001"assert set(spawned["env"]) & CALLER_CONTEXT_ENV_NAMES == set()# The isolation this spawn already had is still what it was.assert "PYTHONPATH" not in spawned["env"]diff --git a/tests/test_install_generation_retirement.py b/tests/test_install_generation_retirement.pynew file mode 100644index 000000000..3f960cc95--- /dev/null+++ b/tests/test_install_generation_retirement.py@@ -0,0 +1,1001 @@+"""Recovery-oriented retirement; arbitrary stale processes are not pinned."""++from __future__ import annotations++import json+import os+from pathlib import Path+import shutil+import subprocess+import sys+from types import SimpleNamespace+import zipfile++import psutil+import pytest++from config import paths+from vibe import install_generations as retention+from vibe import upgrade+from vibe import runtime++OFFICIAL_PATHS = retention._runtime_paths+INSTALLER_IS_LIVE = retention._installer_is_live+++def installation(tmp_path, monkeypatch):+ root = tmp_path / "home with 空格" / "runtime" / "install-generations"+ launcher = tmp_path / "stable" / "vibe"+ launcher.parent.mkdir()+ monkeypatch.setenv("PATH", os.pathsep.join([str(launcher.parent), os.environ.get("PATH", "")]))+ monkeypatch.setattr(upgrade, "atomic_uv_install_root", lambda: root)+ monkeypatch.setattr(upgrade, "verify_upgrade_candidate", lambda _: upgrade.IntegrityResult(True, 1))+ monkeypatch.setattr(retention, "_runtime_paths", lambda: set(), raising=False)+ monkeypatch.setattr(retention, "_invocation_paths", lambda: set(), raising=False)+ monkeypatch.setattr(retention, "_installer_is_live", lambda _: False)+ return root, launcher+++def candidate(+ root, name, *, layout="uv/tools", package="avibe-os",+ export_name="vibe", entry_name="vibe",+):+ generation = root / name+ environment = generation / layout / package+ target = environment / "bin" / "vibe"+ target.parent.mkdir(parents=True)+ target.write_text(f"#!/bin/sh\n# {generation}\nexit 0\n", encoding="utf-8")+ target.chmod(0o755)+ (environment / "pyvenv.cfg").write_text("include-system-site-packages = false\n")+ exported = generation / "bin" / export_name+ exported.parent.mkdir()+ exported.symlink_to(target)+ (environment / "uv-receipt.toml").write_text(+ f'[tool]\nrequirements = [{{ name = "{package}" }}]\n'+ f'entrypoints = [{{ name = {json.dumps(entry_name)}, install-path = {json.dumps(str(exported))} }}]\n',+ encoding="utf-8",+ )+ return exported+++def activate(root, launcher, name, **kwargs):+ exported = candidate(root, name, **kwargs)+ upgrade.activate_installer_candidate(upgrade.AtomicActivation(+ launcher, exported, upgrade._launcher_generation(launcher, root),+ ))+ return exported+++def collect(launcher):+ return retention.collect_install_generations(launcher)++[email protected]("link", ["symlink", "hardlink", "copy"])[email protected]("layout", ["tools", "uv/tools"])+def test_repeated_installations_leave_only_selected_generation(+ installation, monkeypatch, link, layout,+):+ root, launcher = installation+ if link != "symlink":+ monkeypatch.setattr(+ upgrade, "_prepare_launcher_replacement",+ lambda path, target: os.link(target.resolve(), path) if link == "hardlink" else shutil.copy2(target, path),+ )+ for index in range(6):+ name = f"1600000000-999999-{index}" if index % 2 else f"{index:032x}"+ current = activate(root, launcher, name, layout=layout)+ assert current.is_file()+ assert {path.name for path in root.iterdir()} == {name}+ assert upgrade._launcher_generation(launcher, root) == current.parent.parent++[email protected]("layout", ["tools", "uv/tools"])[email protected]("entry_name,export_name", [+ ("vibe", "vibe"), ("vibe", "vibe.exe"), ("vibe.exe", "vibe.exe"),+])+def test_uv_logical_entrypoint_and_platform_export_converge(+ installation, layout, entry_name, export_name,+):+ """uv strips EXE_SUFFIX from receipt names, not from Windows export paths.++ These are portable artifact/activation cases, not native Windows execution.+ """+ root, launcher = installation+ for index in range(3):+ exported = candidate(+ root, f"generation-{index}", layout=layout,+ entry_name=entry_name, export_name=export_name,+ )+ generation = exported.parent.parent+ assert retention._uv_installation(generation) is not None+ upgrade.activate_installer_candidate(upgrade.AtomicActivation(+ launcher, exported, upgrade._launcher_generation(launcher, root),+ ))+ assert {path.name for path in root.iterdir()} == {generation.name}+ assert launcher.resolve() == exported.resolve()++[email protected]("entry_name,export_name", [+ ("other", "vibe.exe"), ("vibe", "other.exe"),+ ("vibe", "vibe.exe.exe"), ("vibe.exe", "vibe"),+])+def test_receipt_export_normalization_is_not_general_suffix_matching(+ installation, entry_name, export_name,+):+ root, launcher = installation+ unknown = candidate(root, "unknown", entry_name=entry_name, export_name=export_name)+ assert retention._uv_installation(unknown.parent.parent) is None+ activate(root, launcher, "selected")+ assert unknown.exists()++[email protected]("foreign_kind", ["symlink", "script"])+def test_foreign_path_command_does_not_block_managed_retirement(+ installation, monkeypatch, tmp_path, foreign_kind,+):+ root, launcher = installation+ foreign = tmp_path / "foreign-bin" / "vibe"+ foreign.parent.mkdir()+ foreign_contents = "#!/bin/sh\n# unrelated installation outside the managed root\nexit 0\n"+ if foreign_kind == "symlink":+ target = tmp_path / "foreign-target"+ target.write_text(foreign_contents)+ target.chmod(0o755)+ foreign.symlink_to(target)+ else:+ foreign.write_text(foreign_contents)+ foreign.chmod(0o755)+ monkeypatch.setenv("PATH", os.pathsep.join([str(foreign.parent), os.environ["PATH"]]))+ assert shutil.which("vibe") == str(foreign)++ for index in range(3):+ current = activate(root, launcher, f"generation-{index}")++ assert {path.name for path in root.iterdir()} == {"generation-2"}+ assert launcher.resolve() == current.resolve()+ assert foreign.read_text() == foreign_contents+ assert subprocess.run([str(launcher)], check=False).returncode == 0++[email protected]("link", ["symlink", "hardlink", "copy"])+def test_unrecognized_in_root_selected_generation_cannot_authorize_retirement(+ installation, link,+):+ root, launcher = installation+ old = candidate(root, "old")+ selected = candidate(root, "selected")+ (root / "selected" / "uv" / "tools" / "avibe-os" / "uv-receipt.toml").unlink()+ if link == "symlink":+ launcher.symlink_to(selected)+ elif link == "hardlink":+ os.link(selected.resolve(), launcher)+ else:+ shutil.copy2(selected, launcher)+ upgrade._update_launcher_generation_marker(launcher, selected, root)+ assert collect(launcher) == []+ assert old.exists()+ assert subprocess.run([str(launcher)], check=False).returncode == 0+ # A later recognized activation restores ordinary retirement.+ current = activate(root, launcher, "recovered")+ assert not old.exists()+ assert selected.exists() # Unknown installations never become garbage by name.+ assert current.exists()++[email protected]("selector", ["primary", "path"])+def test_in_root_wrapper_preserves_the_selected_command_dependency(+ installation, tmp_path, monkeypatch, selector,+):+ root, launcher = installation+ old = candidate(root, "old")+ wrapper = root / "unknown" / "bin" / "vibe"+ wrapper.parent.mkdir(parents=True)+ wrapper.write_text(f'#!/bin/sh\nexec "{old}" "$@"\n')+ wrapper.chmod(0o755)+ if selector == "primary":+ selected_command = launcher+ else:+ selected_command = tmp_path / "path-first" / "vibe"+ selected_command.parent.mkdir()+ monkeypatch.setenv("PATH", os.pathsep.join([+ str(selected_command.parent), os.environ["PATH"],+ ]))+ selected_command.symlink_to(wrapper)+ assert subprocess.run([str(selected_command)], check=False).returncode == 0+ if selector == "primary":+ collect(launcher)+ else:+ current = activate(root, launcher, "current")+ assert current.exists()+ assert old.exists()+ assert subprocess.run([str(selected_command)], check=False).returncode == 0+++def test_reclaims_fifteen_historical_generations_without_activation_receipts(installation):+ root, launcher = installation+ for index in range(15):+ candidate(+ root, f"{index:032x}", layout="tools" if index % 2 else "uv/tools",+ package="vibe-remote" if index % 3 else "avibe-os",+ )+ unknown = root / "not-an-install"+ unknown.mkdir()+ (unknown / "user-file").write_text("preserve")+ selected = activate(root, launcher, "selected")+ assert selected.is_file()+ assert {path.name for path in root.iterdir()} == {"selected", "not-an-install"}+ assert (unknown / "user-file").read_text() == "preserve"+++def test_canonical_uv_history_is_retired_after_a_managed_activation(installation, tmp_path):+ root, launcher = installation+ candidate(root, "old-one", layout="tools")+ candidate(root, "old-two")+ canonical = tmp_path / "canonical-uv" / "bin" / "vibe"+ canonical.parent.mkdir(parents=True)+ canonical.write_text("#!/bin/sh\nexit 0\n")+ canonical.chmod(0o755)+ launcher.symlink_to(canonical)+ collect(launcher)+ assert {path.name for path in root.iterdir()} == {"old-one", "old-two"}+ assert launcher.resolve() == canonical+ assert canonical.is_file()+ current = activate(root, launcher, "selected")+ assert current.exists()+ assert {path.name for path in root.iterdir()} == {"selected"}+ assert canonical.is_file()+++def test_official_runtime_and_current_invocation_survive_until_handoff(+ installation, monkeypatch,+):+ root, launcher = installation+ service = candidate(root, "service")+ ui = candidate(root, "ui")+ invocation = candidate(root, "invocation")+ monkeypatch.setattr(retention, "_runtime_paths", lambda: {service, ui})+ monkeypatch.setattr(retention, "_invocation_paths", lambda: {invocation})+ current = activate(root, launcher, "current")+ assert {path.name for path in root.iterdir()} == {"service", "ui", "invocation", "current"}+ monkeypatch.setattr(retention, "_runtime_paths", lambda: {current})+ monkeypatch.setattr(retention, "_invocation_paths", lambda: {current})+ collect(launcher)+ assert {path.name for path in root.iterdir()} == {"current"}+++def test_unregistered_old_process_is_retired_and_current_command_still_runs(+ installation, tmp_path, monkeypatch,+):+ root, launcher = installation+ old = candidate(root, "old")+ generation = old.parent.parent+ environment = generation / "uv" / "tools" / "avibe-os"+ module = environment / "retired_feature.py"+ module.write_text("VALUE = 'old'\n")+ python = environment / "bin" / "python"+ python.symlink_to(sys.executable)+ process = subprocess.Popen(+ [str(python), "-c",+ "import sys; sys.path.insert(0, sys.argv[1]); print('ready', flush=True); "+ "sys.stdin.readline(); import retired_feature", str(environment)],+ cwd=tmp_path, stdin=subprocess.PIPE, stdout=subprocess.PIPE,+ stderr=subprocess.PIPE, text=True,+ )+ monkeypatch.setattr(+ retention.psutil, "process_iter",+ lambda *args, **kwargs: pytest.fail("retirement must not enumerate unrelated processes"),+ )+ try:+ assert process.stdout.readline().strip() == "ready"+ current = activate(root, launcher, "current")+ assert not generation.exists()+ assert current.exists()+ assert subprocess.run([str(launcher)], check=False).returncode == 0+ finally:+ _, error = process.communicate("\n", timeout=10)+ assert process.returncode != 0+ assert "ModuleNotFoundError" in error++[email protected]("state", [None, "future-state", "unknown", "scheduled", "running"])+def test_pending_or_unknown_restart_defers_retirement(installation, state):+ root, launcher = installation+ old = candidate(root, "old")+ current = candidate(root, "current")+ launcher.symlink_to(current)+ path = upgrade.runtime_mod.get_restart_status_path()+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(json.dumps({"state": state}))+ assert collect(launcher) == []+ assert old.exists()+ path.write_text(json.dumps({"state": "succeeded"}))+ collect(launcher)+ assert not old.exists()+ assert current.exists()+++def test_another_installer_protects_its_source_even_before_candidate_is_complete(+ installation, monkeypatch,+):+ root, launcher = installation+ source = candidate(root, "source")+ staging = root / "incomplete-stage"+ staging.mkdir()+ monkeypatch.setattr(retention, "_installer_is_live", lambda path: path == staging)+ selected = activate(root, launcher, "selected")+ assert source.exists()+ assert staging.exists()+ monkeypatch.setattr(retention, "_installer_is_live", lambda _: False)+ collect(launcher)+ assert not source.exists()+ assert selected.exists()+ assert staging.exists() # Unknown/incomplete directories are not adopted.+++def test_cleanup_failure_cannot_invalidate_successful_activation(installation, monkeypatch):+ root, launcher = installation+ old = candidate(root, "old")+ (root / "old" / "uv" / "tools" / "avibe-os" / "lib").mkdir()+ monkeypatch.setattr(+ retention.shutil, "rmtree",+ lambda _: (_ for _ in ()).throw(PermissionError("test-owned deletion failure")),+ )+ selected = activate(root, launcher, "selected")+ assert old.exists()+ assert launcher.resolve() == selected.resolve()+ assert selected.exists()+++def test_generation_symlinks_and_external_uv_data_are_never_collected(installation, tmp_path):+ root, launcher = installation+ external = candidate(tmp_path / "external", "unrelated")+ root.mkdir(parents=True)+ alias = root / "directory-alias"+ alias.symlink_to(external.parent.parent, target_is_directory=True)+ selected = activate(root, launcher, "selected")+ assert alias.is_symlink()+ assert external.exists()+ assert selected.exists()+++def test_failed_candidate_is_discarded_but_selected_install_is_unchanged(+ installation, monkeypatch,+):+ from vibe import cli++ root, launcher = installation+ selected = activate(root, launcher, "selected")+ failed = candidate(root, "failed")+ monkeypatch.setattr(upgrade, "verify_upgrade_candidate", lambda _: upgrade.IntegrityResult(False))+ assert cli._dispatch_installer_activation([+ "--launcher", str(launcher), "--candidate", str(failed),+ "--source-generation", str(selected.parent.parent),+ ]) == 1+ assert launcher.resolve() == selected.resolve()+ assert selected.exists()+ assert not failed.parent.parent.exists()++[email protected]("surface", ["manual", "automatic"])+def test_repeated_real_upgrade_callers_retire_history(installation, monkeypatch, surface):+ from vibe import api, cli++ root, launcher = installation+ caller = cli if surface == "manual" else api+ monkeypatch.setattr(caller, "_runtime_process_was_running", lambda: surface == "automatic")+ monkeypatch.setattr(caller, "schedule_restart", lambda **kwargs: {"job_id": "test"})+ monkeypatch.setattr(cli, "cache_running_vibe_path", lambda: str(launcher))+ monkeypatch.setattr(api, "get_running_vibe_path", lambda: str(launcher))+ version = {"error": None, "has_update": True, "latest": "99"}+ monkeypatch.setattr(cli, "get_latest_version", lambda: version)+ monkeypatch.setattr(api, "get_version_info", lambda: version)+ monkeypatch.setattr(cli, "_prepare_show_runtime_after_install", lambda *_: None)+ for index in range(5):+ exported = candidate(root, f"{index:032x}")+ activation = upgrade.AtomicActivation(launcher, exported, upgrade._launcher_generation(launcher, root))+ plan = upgrade.UpgradePlan(command=["test-uv"], env={}, method="uv", activation=activation)+ monkeypatch.setattr(caller, "build_upgrade_plan", lambda **kwargs: plan)+ monkeypatch.setattr(caller.subprocess, "run", lambda cmd, **kwargs: subprocess.CompletedProcess(cmd, 0, "", ""))+ result = cli.cmd_upgrade() if surface == "manual" else api.do_upgrade(auto_restart=True)+ assert result == 0 if surface == "manual" else result["ok"]+ assert {path.name for path in root.iterdir()} == {f"{index:032x}"}+ assert exported.exists()++[email protected]("record", ["service-pid", "ui-pid", "status", "lock-holder"])+def test_real_official_child_is_kept_until_exit(installation, monkeypatch, tmp_path, record):+ root, launcher = installation+ exported = candidate(root, "official")+ python = exported.parent.parent / "uv" / "tools" / "avibe-os" / "bin" / "python"+ python.symlink_to(sys.executable)+ process = subprocess.Popen(+ [str(python), "-c", "import sys; print('ready', flush=True); sys.stdin.readline()"],+ stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE,+ cwd=tmp_path, text=True,+ )+ monkeypatch.setattr(retention, "_runtime_paths", OFFICIAL_PATHS)+ monkeypatch.setattr(runtime, "service_instance_lock_available", lambda: (True, None))+ try:+ assert process.stdout.readline().strip() == "ready"+ paths.get_runtime_dir().mkdir(parents=True, exist_ok=True)+ if record == "status":+ paths.get_runtime_status_path().write_text(json.dumps({"service_pid": process.pid}))+ elif record == "lock-holder":+ monkeypatch.setattr(runtime, "service_instance_lock_available", lambda: (False, process.pid))+ else:+ path = paths.get_runtime_pid_path() if record == "service-pid" else paths.get_runtime_ui_pid_path()+ path.write_text(str(process.pid))+ assert python in OFFICIAL_PATHS()+ current = activate(root, launcher, "selected")+ assert exported.exists()+ assert current.exists()+ finally:+ process.communicate("\n", timeout=10)+ monkeypatch.setattr(runtime, "service_instance_lock_available", lambda: (True, None))+ collect(launcher)+ assert not exported.parent.parent.exists()+ assert current.exists()++[email protected]("boundary", ["cmdline", "exe", "lock-owner", "status", "pid"])+def test_unreadable_official_reference_defers_without_invalidating_activation(+ installation, monkeypatch, boundary,+):+ root, launcher = installation+ old = candidate(root, "official")+ monkeypatch.setattr(retention, "_runtime_paths", OFFICIAL_PATHS)+ monkeypatch.setattr(runtime, "service_instance_lock_available", lambda: (True, None))+ paths.get_runtime_dir().mkdir(parents=True, exist_ok=True)+ if boundary == "lock-owner":+ monkeypatch.setattr(runtime, "service_instance_lock_available", lambda: (False, None))+ elif boundary == "status":+ paths.get_runtime_status_path().write_text("{")+ elif boundary == "pid":+ paths.get_runtime_pid_path().write_text("unknown")+ else:+ paths.get_runtime_pid_path().write_text("123")++ def denied():+ raise psutil.AccessDenied(123)++ process = SimpleNamespace(+ status=lambda: psutil.STATUS_RUNNING, cmdline=lambda: [str(old)],+ exe=lambda: str(old),+ )+ setattr(process, boundary, denied)+ monkeypatch.setattr(retention.psutil, "Process", lambda _: process)+ current = activate(root, launcher, "selected")+ assert old.exists()+ assert launcher.resolve() == current.resolve()+++def test_windows_official_base_python_child_keeps_redirector_generation(installation, monkeypatch):+ root, launcher = installation+ old = candidate(root, "official-ui")+ monkeypatch.setattr(retention, "_runtime_paths", OFFICIAL_PATHS)+ monkeypatch.setattr(runtime, "service_instance_lock_available", lambda: (True, None))+ monkeypatch.setattr(retention, "sys", SimpleNamespace(platform="win32"))+ paths.get_runtime_dir().mkdir(parents=True, exist_ok=True)+ paths.get_runtime_ui_pid_path().write_text("123")+ monkeypatch.setattr(retention.psutil, "Process", lambda _: SimpleNamespace(+ status=lambda: psutil.STATUS_RUNNING,+ cmdline=lambda: [sys.executable, "-c", "from vibe.ui_server import run; run()"],+ exe=lambda: sys.executable,+ parent=lambda: SimpleNamespace(exe=lambda: str(old.with_name("python.exe"))),+ ))+ current = activate(root, launcher, "selected")+ assert old.exists()+ assert current.exists()++[email protected]("parent_state", ["missing", "exited", "denied"])[email protected]("child_state", ["live", "exited", "in-root", "zombie"])+def test_windows_redirector_loss_is_not_the_official_child_exiting(+ installation, monkeypatch, parent_state, child_state,+):+ root, launcher = installation+ old = candidate(root, "official-ui")+ monkeypatch.setattr(retention, "_runtime_paths", OFFICIAL_PATHS)+ monkeypatch.setattr(runtime, "service_instance_lock_available", lambda: (True, None))+ monkeypatch.setattr(retention, "sys", SimpleNamespace(platform="win32"))+ paths.get_runtime_dir().mkdir(parents=True, exist_ok=True)+ paths.get_runtime_ui_pid_path().write_text("123")+ inspections = []++ def parent():+ inspections.append("parent")+ if parent_state == "missing":+ return None++ def executable():+ if parent_state == "denied":+ raise psutil.AccessDenied(122)+ raise psutil.NoSuchProcess(122)++ return SimpleNamespace(exe=executable)++ child = SimpleNamespace(+ status=lambda: psutil.STATUS_ZOMBIE if child_state == "zombie" else psutil.STATUS_RUNNING,+ cmdline=lambda: [+ str(old.with_name("python.exe")) if child_state == "in-root" else sys.executable,+ "-c", "from vibe.ui_server import run; run()",+ ],+ exe=lambda: sys.executable,+ parent=parent,+ is_running=lambda: child_state != "exited",+ )+ monkeypatch.setattr(retention.psutil, "Process", lambda _: child)+ current = activate(root, launcher, "selected")+ must_keep = child_state in {"live", "in-root"} or (+ child_state == "exited" and parent_state == "denied"+ )+ assert old.exists() is must_keep+ assert current.exists()+ if child_state in {"in-root", "zombie"}:+ assert not inspections++[email protected]("interruption", ["write-failure", "interrupted-write", "rename-failure"])+def test_shell_marker_publication_failure_cannot_poison_future_collection(+ installation, monkeypatch, interruption,+):+ root, launcher = installation+ old = candidate(root, "old")+ launcher.symlink_to(old)+ source = (Path(__file__).resolve().parents[1] / "install.sh").read_text()+ source = source.rsplit('\nmain "$@"', 1)[0]+ hooks = {+ "write-failure": r"""+printf() {+ if [ "$1" = '%s\n' ] && [ "${2:-}" = "$$" ]; then return 1; fi+ builtin printf "$@"+}+""",+ "interrupted-write": r"""+printf() {+ if [ "$1" = '%s\n' ] && [ "${2:-}" = "$$" ]; then exit 91; fi+ builtin printf "$@"+}+""",+ "rename-failure": r"""+mv() {+ case "${*: -1}" in */.avibe-installing) return 1 ;; esac+ command mv "$@"+}+""",+ }+ # A publication failure must precede source snapshot and package installation.+ script = source + hooks[interruption] + r"""+VIBE_TOOL_BIN_DIR="$VIBE_TEST_STABLE_BIN"+launcher_destination_is_available() { return 0; }+resolve_binary_path() { echo snapshot >> "$VIBE_TEST_ADMISSION_TRACE"; exit 92; }+uv() { echo uv >> "$VIBE_TEST_ADMISSION_TRACE"; return 93; }+if uv_tool_install avibe-os; then exit 94; else exit 95; fi+"""+ trace = root.parent / "admission-trace"+ result = subprocess.run(+ ["bash", "-c", script],+ env={+ **os.environ, "HOME": str(root.parent.parent),+ "AVIBE_HOME": str(root.parent.parent),+ "VIBE_TEST_STABLE_BIN": str(launcher.parent),+ "VIBE_TEST_ADMISSION_TRACE": str(trace),+ },+ cwd=root.parent.parent, text=True, capture_output=True, timeout=15,+ )+ assert result.returncode in {91, 95}+ assert not trace.exists()+ staged = [generation for generation in root.iterdir() if generation.name != "old"]+ assert all(not (generation / retention.INSTALLER_PID).exists() for generation in staged)+ if interruption != "interrupted-write":+ assert not staged+ monkeypatch.setattr(retention, "_installer_is_live", INSTALLER_IS_LIVE)+ for index in range(3):+ current = activate(root, launcher, f"selected-{index}")+ assert not old.exists()+ assert current.exists()+ assert {generation.name for generation in root.iterdir()} == {+ "selected-2", *(generation.name for generation in staged),+ }++[email protected]("contents", ["", "not-a-pid"])+def test_corrupt_published_guid_marker_is_not_guessed_dead(+ installation, monkeypatch, contents,+):+ root, launcher = installation+ old = candidate(root, "old")+ stage = root / "0123456789abcdef0123456789abcdef"+ stage.mkdir()+ (stage / retention.INSTALLER_PID).write_text(contents)+ monkeypatch.setattr(retention, "_installer_is_live", INSTALLER_IS_LIVE)+ current = activate(root, launcher, "selected")+ assert old.exists()+ assert current.exists()+ assert launcher.resolve() == current.resolve()+ assert (stage / retention.INSTALLER_PID).read_text() == contents++[email protected]("legacy", [False, True])+def test_live_installer_pid_pins_handoff_without_process_table_scan(+ installation, monkeypatch, legacy,+):+ root, launcher = installation+ created = int(psutil.Process(os.getpid()).create_time())+ old = candidate(root, f"{created}-{os.getpid()}-17" if legacy else "staging")+ if not legacy:+ retention.mark_install_generation(old, os.getpid())+ monkeypatch.setattr(retention, "_installer_is_live", INSTALLER_IS_LIVE)+ current = activate(root, launcher, "selected")+ assert old.exists()+ assert current.exists()++[email protected]("condition", ["dead", "reused", "zombie"])+def test_old_marker_does_not_permanently_pin_retired_generation(installation, monkeypatch, condition):+ root, launcher = installation+ old = candidate(root, "old")+ retention.mark_install_generation(old, 123)+ marker = old.parent.parent / retention.INSTALLER_PID+ monkeypatch.setattr(retention, "_installer_is_live", INSTALLER_IS_LIVE)++ def process(_):+ if condition == "dead":+ raise psutil.NoSuchProcess(123)+ return SimpleNamespace(+ status=lambda: psutil.STATUS_ZOMBIE if condition == "zombie" else psutil.STATUS_RUNNING,+ create_time=lambda: marker.stat().st_mtime + 10,+ )++ monkeypatch.setattr(retention.psutil, "Process", process)+ current = activate(root, launcher, "selected")+ assert not old.parent.parent.exists()+ assert current.exists()++[email protected]("shape", [+ "malformed-receipt", "wrong-package", "outside-export", "nested-alias",+ "extra-tool", "user-data", "missing-receipt",+])+def test_unknown_installation_shapes_are_retained(installation, tmp_path, shape):+ root, launcher = installation+ old = candidate(root, "unknown")+ generation = old.parent.parent+ environment = generation / "uv" / "tools" / "avibe-os"+ receipt = environment / "uv-receipt.toml"+ if shape == "malformed-receipt":+ receipt.write_text("not a receipt")+ elif shape == "wrong-package":+ receipt.write_text(receipt.read_text().replace("avibe-os", "other-tool"))+ elif shape == "outside-export":+ receipt.write_text(receipt.read_text().replace(json.dumps(str(old)), json.dumps(str(tmp_path / "vibe"))))+ elif shape == "nested-alias":+ moved = tmp_path / "external-environment"+ environment.rename(moved)+ environment.symlink_to(moved, target_is_directory=True)+ elif shape == "extra-tool":+ (environment.parent / "other-tool").mkdir()+ elif shape == "user-data":+ (generation / "user-data").write_text("not ours")+ else:+ receipt.unlink()+ current = activate(root, launcher, "selected")+ assert generation.exists()+ assert current.exists()++[email protected]("layout,extra", [+ ("uv/tools", "tools/userdata/keep.txt"),+ ("tools", "uv/other/keep.txt"),+ ("tools", "uv/tools/other-pkg/keep.txt"),+ ("uv/tools", "bin/keep.txt"),+])+def test_mixed_layout_or_unexported_bin_data_is_not_an_installation(installation, layout, extra):+ root, launcher = installation+ old = candidate(root, "mixed", layout=layout)+ sentinel = old.parent.parent / extra+ sentinel.parent.mkdir(parents=True, exist_ok=True)+ sentinel.write_text("not installation data")+ current = activate(root, launcher, "selected")+ assert sentinel.read_text() == "not installation data"+ assert old.exists()+ assert current.exists()++[email protected]("alias_target", ["outside", "inside"])[email protected]("explicit", [False, True])+def test_alias_invocation_cannot_retire_the_path_selected_command(+ installation, monkeypatch, tmp_path, alias_target, explicit,+):+ root, launcher = installation+ selected = activate(root, launcher, "selected")+ alias = tmp_path / "secondary" / "vibe"+ alias.parent.mkdir()+ if alias_target == "outside":+ target = tmp_path / "canonical-uv" / "vibe"+ target.parent.mkdir()+ target.write_text("#!/bin/sh\nexit 0\n")+ target.chmod(0o755)+ else:+ target = candidate(root, "other")+ alias.symlink_to(target)+ monkeypatch.setattr(upgrade, "get_running_vibe_path", lambda: str(alias))+ retention.collect_install_generations(alias if explicit else None)+ assert selected.exists()+ assert launcher.resolve() == selected.resolve()+ assert subprocess.run([str(launcher)], check=False).returncode == 0+++def test_partial_removal_retains_uv_evidence_and_next_pass_finishes(installation, monkeypatch):+ root, launcher = installation+ old = candidate(root, "old")+ environment = old.parent.parent / "uv" / "tools" / "avibe-os"+ library = environment / "lib"+ library.mkdir()+ (library / "locked.pyd").write_text("loaded")+ original = retention.shutil.rmtree++ def fail_midway(path):+ if path == library:+ raise PermissionError("loaded library")+ original(path)++ monkeypatch.setattr(retention.shutil, "rmtree", fail_midway)+ current = activate(root, launcher, "selected")+ assert (environment / "uv-receipt.toml").is_file()+ assert (environment / "pyvenv.cfg").is_file()+ assert current.exists()+ monkeypatch.setattr(retention.shutil, "rmtree", original)+ collect(launcher)+ assert not environment.exists()+ assert {path.name for path in root.iterdir()} == {"selected"}+++def test_unknown_plain_launcher_defers_but_missing_copy_marker_recovers(installation):+ root, launcher = installation+ old = candidate(root, "old")+ launcher.write_text("unknown wrapper")+ collect(launcher)+ assert old.exists()+ selected = candidate(root, "selected")+ shutil.copy2(selected, launcher)+ collect(launcher)+ assert not old.exists()+ assert selected.exists()+ assert launcher.read_bytes() == selected.read_bytes()+++def test_hardlink_alias_first_still_protects_real_selected_generation(installation):+ root, launcher = installation+ old = candidate(root, "retire")+ alias = root / "aaa-alias"+ alias.symlink_to(root / "selected", target_is_directory=True)+ selected = candidate(root, "selected")+ os.link(selected.resolve(), launcher)+ assert upgrade._launcher_generation(launcher, root) == root / "selected"+ collect(launcher)+ assert not old.exists()+ assert selected.exists()+ assert alias.is_symlink()+++def test_staging_marker_failure_after_publication_is_nonfatal(installation, monkeypatch):+ root, launcher = installation+ exported = candidate(root, "selected")+ retention.mark_install_generation(exported, os.getpid())+ original = Path.unlink++ def denied(path, *args, **kwargs):+ if path.name == retention.INSTALLER_PID:+ raise PermissionError("readonly marker")+ return original(path, *args, **kwargs)++ monkeypatch.setattr(Path, "unlink", denied)+ upgrade.activate_installer_candidate(upgrade.AtomicActivation(launcher, exported))+ assert launcher.resolve() == exported.resolve()+ assert exported.exists()+++def test_installer_diagnostics_restore_logging_without_a_traceback(+ installation, monkeypatch, capsys, caplog,+):+ from vibe import cli++ root, launcher = installation+ exported = candidate(root, "selected")+ handlers = list(retention.logger.handlers)+ level = retention.logger.level++ def denied():+ raise PermissionError("official PID visibility denied")++ monkeypatch.setattr(retention, "_runtime_paths", denied)+ result = cli._dispatch_installer_activation([+ "--launcher", str(launcher), "--candidate", str(exported),+ ])+ diagnostic = capsys.readouterr().err+ assert result == 0+ assert exported.exists()+ assert launcher.resolve() == exported.resolve()+ assert "official PID visibility denied" in diagnostic+ assert "Traceback" not in diagnostic+ assert any(record.exc_info for record in caplog.records)+ assert retention.logger.handlers == handlers+ assert retention.logger.level == level++[email protected]("state,owner,old_status,marker_job,deferred", [+ ("failed", "live", False, "active", False),+ ("error", "dead", False, "active", False),+ ("cancelled", "dead", False, "active", False),+ ("skipped", "dead", False, "active", False),+ (None, "dead", False, "active", False),+ ("running", "dead", True, "active", False),+ ("scheduled", "seed", True, "active", False),+ ("succeeded", "dead", True, "active", False),+ ("succeeded", "reused", True, "active", False),+ ("succeeded", "legacy", True, "active", False),+ ("succeeded", "live", False, "previous-job", False),+ ("succeeded", "live", True, "active", True),+ ("succeeded", "live", True, None, True),+ ("succeeded", "dead", False, "active", True),+ ("unknown", "dead", True, "active", True),+ ("future-state", "dead", True, "active", True),+ ("unreadable", "dead", True, "active", True),+])+def test_pending_followup_respects_restart_ownership(+ installation, monkeypatch, state, owner, old_status, marker_job, deferred,+):+ """A stale follow-up cannot veto normal activations indefinitely.++ Existence-only coverage missed failed, superseded and abandoned jobs.+ A matching supervisor still owns its successful tail until it consumes the+ follow-up; unknown evidence and the existing seed grace remain conservative.+ """+ from vibe import restart_supervisor++ root, launcher = installation+ old = candidate(root, "old")+ restart_supervisor.mark_pending_restart(+ trigger="web-ui-config-pending", restart_job_id=marker_job,+ )+ marker = paths.get_runtime_dir() / "pending_restart.json"+ marker_bytes = marker.read_bytes()+ status = runtime.get_restart_status_path()+ if state is not None:+ payload = {+ "job_id": "active", "state": state,+ "supervisor_pid": None if owner == "seed" else 123,+ }+ if owner not in {"legacy", "seed"}:+ payload["supervisor_started_at"] = 100.0+ runtime.write_json(status, payload)+ if old_status:+ os.utime(status, (1, 1))+ monkeypatch.setattr(runtime, "pid_alive", lambda pid: owner not in {"dead", "seed"})+ monkeypatch.setattr(runtime, "process_create_time", lambda pid: 200.0 if owner == "reused" else 100.0)+ if state == "unreadable":+ original_read = Path.read_text++ def denied(path, *args, **kwargs):+ if path == status:+ raise PermissionError("restart status unavailable")+ return original_read(path, *args, **kwargs)++ monkeypatch.setattr(Path, "read_text", denied)++ for index in range(3):+ current = activate(root, launcher, f"selected-{index}")+ assert current.exists()+ assert launcher.resolve() == current.resolve()+ assert old.exists() is deferred+ expected = {"old", "selected-0", "selected-1", "selected-2"} if deferred else {"selected-2"}+ assert {path.name for path in root.iterdir()} == expected+ assert marker.read_bytes() == marker_bytes # Only the supervisor consumes it.+++def test_stage_is_marked_before_uv_and_failed_helper_transfer_stays_precommit(+ installation, monkeypatch, tmp_path,+):+ root, launcher = installation+ exported = candidate(root, "candidate")+ activation = upgrade.AtomicActivation(launcher, exported)+ plan = upgrade.UpgradePlan(["uv-fixture"], None, "uv", activation=activation)++ def run(command, **kwargs):+ assert (root / "candidate" / retention.INSTALLER_PID).read_text() == str(os.getpid())+ return subprocess.CompletedProcess(command, 0)++ upgrade.execute_upgrade_plan(plan, run=run)+ terminated = []+ monkeypatch.setattr(upgrade, "_candidate_python", lambda _: Path(sys.executable))+ monkeypatch.setattr(upgrade.runtime_mod, "process_create_time", lambda _: 1)+ monkeypatch.setattr(upgrade, "get_safe_cwd", lambda: str(tmp_path))+ monkeypatch.setattr(upgrade.subprocess, "Popen", lambda *args, **kwargs: SimpleNamespace(+ pid=123, terminate=lambda: terminated.append(123),+ ))+ monkeypatch.setattr(retention, "write_atomic", lambda *args: (_ for _ in ()).throw(PermissionError("readonly")))+ with pytest.raises(PermissionError, match="readonly"):+ upgrade.defer_upgrade_activation(activation, parent_pid=os.getpid())+ assert terminated == [123]+ assert not launcher.exists()+ assert exported.exists()++[email protected]("ready", [True, False])+def test_runtime_start_collects_only_after_readiness(installation, monkeypatch, ready):+ root, launcher = installation+ old = candidate(root, "old")+ current = candidate(root, "current")+ launcher.symlink_to(current)+ monkeypatch.setattr(upgrade, "get_running_vibe_path", lambda: str(launcher))+ monkeypatch.setattr(runtime, "_resolve_service_pid", lambda **kwargs: 123)+ monkeypatch.setattr(runtime, "wait_for_service_ready", lambda *args, **kwargs: 123 if ready else None)+ monkeypatch.setattr(runtime, "_raise_service_started_but_never_ran",+ lambda *args, **kwargs: (_ for _ in ()).throw(RuntimeError("not ready")))+ if ready:+ assert runtime.start_service() == 123+ assert not old.parent.parent.exists()+ else:+ with pytest.raises(RuntimeError, match="not ready"):+ runtime.start_service()+ assert old.exists()+ assert current.exists()++[email protected]("layout", ["tools", "uv/tools"])[email protected]("copy", [False, True])+def test_real_uv_installations_are_identified_and_retired(installation, tmp_path, monkeypatch, layout, copy):+ """Consume real uv receipts and launchers without network or production roots."""+ uv = shutil.which("uv")+ if uv is None:+ pytest.skip("uv is not installed")+ root, launcher = installation+ wheel = tmp_path / "avibe_os-0.0.0-py3-none-any.whl"+ info = "avibe_os-0.0.0.dist-info"+ files = {+ "vibe/__init__.py": "",+ "vibe/cli.py": "def main():\n print('isolated current install')\n",+ f"{info}/METADATA": "Metadata-Version: 2.1\nName: avibe-os\nVersion: 0.0.0\n",+ f"{info}/WHEEL": "Wheel-Version: 1.0\nRoot-Is-Purelib: true\nTag: py3-none-any\n",+ f"{info}/entry_points.txt": "[console_scripts]\nvibe = vibe.cli:main\n",+ }+ with zipfile.ZipFile(wheel, "w") as archive:+ for name, contents in files.items():+ archive.writestr(name, contents)+ archive.writestr(f"{info}/RECORD", "\n".join(f"{name},," for name in files) + f"\n{info}/RECORD,,\n")+ if copy:+ monkeypatch.setattr(upgrade, "_prepare_launcher_replacement", lambda path, target: shutil.copy2(target, path))+ for index in range(3):+ generation = root / f"{index:032x}"+ env = {+ "PATH": os.defpath,+ "HOME": str(tmp_path),+ "USERPROFILE": str(tmp_path),+ "AVIBE_HOME": str(root.parent.parent),+ "XDG_CONFIG_HOME": str(tmp_path / "config"),+ "XDG_DATA_HOME": str(tmp_path / "data"),+ "XDG_CACHE_HOME": str(tmp_path / "cache"),+ "UV_TOOL_DIR": str(generation / layout),+ "UV_TOOL_BIN_DIR": str(generation / "bin"),+ "UV_PYTHON_INSTALL_DIR": str(tmp_path / "pythons"),+ "UV_PYTHON_DOWNLOADS": "never",+ }+ if "SYSTEMROOT" in os.environ:+ env["SYSTEMROOT"] = os.environ["SYSTEMROOT"]+ result = subprocess.run(+ [uv, "--offline", "--no-config", "--no-cache", "tool", "install",+ "--no-index", "--python", sys.executable, str(wheel)],+ env=env, cwd=tmp_path, capture_output=True, text=True, timeout=60,+ )+ assert result.returncode == 0, result.stderr+ exported = generation / "bin" / ("vibe.exe" if os.name == "nt" else "vibe")+ assert retention._uv_installation(generation) is not None+ upgrade.activate_installer_candidate(upgrade.AtomicActivation(+ launcher, exported, upgrade._launcher_generation(launcher, root),+ ))+ assert {path.name for path in root.iterdir()} == {generation.name}+ result = subprocess.run([str(launcher)], env=env, capture_output=True, text=True, timeout=10)+ assert result.returncode == 0, result.stderr+ assert result.stdout.strip() == "isolated current install"diff --git a/tests/test_install_script.py b/tests/test_install_script.pyindex d71bbde1a..4e7c83f4a 100644--- a/tests/test_install_script.py+++ b/tests/test_install_script.py@@ -1,6 +1,7 @@from __future__ import annotationsimport os+import shleximport statimport subprocessimport sys@@ -58,6 +59,21 @@ def _run(command: str, *, cwd: Path, env: dict[str, str], timeout: int = 30) ->def _write_fake_uv(path: Path, uv_log: Path) -> None:+ activation_driver = (+ f"import sys; sys.path.insert(0, {str(REPO_ROOT)!r}); "+ "from vibe import cli, upgrade, install_generations; "+ "upgrade.verify_upgrade_candidate = lambda activation: upgrade.IntegrityResult(True, 1); "+ "sys.exit(cli._dispatch_installer_activation(sys.argv[1:]))"+ )+ receipt_driver = (+ "import json, sys; from pathlib import Path; "+ "environment = Path(sys.argv[1]); environment.mkdir(parents=True, exist_ok=True); "+ "(environment / 'pyvenv.cfg').write_text('include-system-site-packages = false\\n'); "+ "(environment / 'uv-receipt.toml').write_text("+ "'[tool]\\nrequirements = [{ name = \"avibe-os\" }]\\n'"+ " + 'entrypoints = [{ name = \"vibe\", install-path = '"+ " + json.dumps(sys.argv[2]) + ' }]\\n')"+ )_write_executable(path,f"""\@@ -77,10 +93,15 @@ def _write_fake_uv(path: Path, uv_log: Path) -> None:fibin_dir="${{UV_TOOL_BIN_DIR:-$HOME/.local/bin}}"- mkdir -p "$bin_dir"- cat > "$bin_dir/vibe-test-driver" <<'EOF'+ tool_env="${{UV_TOOL_DIR:-$HOME/.local/share/uv/tools}}/avibe-os"+ fixture_bin="$tool_env/bin"+ mkdir -p "$bin_dir" "$fixture_bin"+ cat > "$fixture_bin/vibe-test-driver" <<'EOF'#!/usr/bin/env bashset -euo pipefail+ if [ "${{VIBE_TEST_SHARED_ACTIVATION:-}}" = "1" ] && [ "${{1:-}}" = "__activate-install" ]; then+ exec "{sys.executable}" -c {shlex.quote(activation_driver)} "${{@:2}}"+ fiif [ "${{VIBE_TEST_REQUIRE_CANONICAL_HOME:-}}" = "1" ] && \[ "${{AVIBE_HOME:-}}" != "${{VIBE_TEST_EXPECTED_AVIBE_HOME:-}}" ]; thenecho "AVIBE_HOME was not canonicalized" >&2@@ -178,16 +199,18 @@ def _write_fake_uv(path: Path, uv_log: Path) -> None:echo "started"fiEOF- mkdir -p "$bin_dir/test-module/vibe"- touch "$bin_dir/test-module/vibe/__init__.py"- cat > "$bin_dir/test-module/vibe/cli.py" <<'EOF'+ mkdir -p "$fixture_bin/test-module/vibe"+ touch "$fixture_bin/test-module/vibe/__init__.py"+ cat > "$fixture_bin/test-module/vibe/cli.py" <<'EOF'import subprocess, sysfrom pathlib import Pathdef main():driver = Path(__file__).resolve().parents[2] / "vibe-test-driver"+ if sys.argv[1:3] == ["__activate-install", "--protocol-version"] and (driver.parent / ".legacy-activation").exists():+ return 2return subprocess.call(["bash", "-c", driver.read_text(), *sys.argv])EOF- cat > "$bin_dir/vibe" <<'EOF'+ cat > "$fixture_bin/vibe" <<'EOF'#!{sys.executable}import sysfrom pathlib import Path@@ -195,11 +218,16 @@ def _write_fake_uv(path: Path, uv_log: Path) -> None:from vibe.cli import mainsys.exit(main())EOF- chmod +x "$bin_dir/vibe"+ # Real uv console scripts contain their generation-specific interpreter.+ # Preserve that distinction in this fake using the test interpreter.+ printf '\\n# generation: %s\\n' "$bin_dir" >> "$fixture_bin/vibe"+ chmod +x "$fixture_bin/vibe"+ ln -s "$fixture_bin/vibe" "$bin_dir/vibe"+ "{sys.executable}" -c {shlex.quote(receipt_driver)} "$tool_env" "$bin_dir/vibe"if [ "${{VIBE_TEST_LEGACY_ACTIVATION:-}}" = "1" ]; then- touch "$bin_dir/.legacy-activation"+ touch "$fixture_bin/.legacy-activation"fi- cat > "$bin_dir/python3" <<'EOF'+ cat > "$fixture_bin/python3" <<'EOF'#!/usr/bin/env bashif [ "${1:-}" = "-c" ]; thenif [ "${{VIBE_TEST_CANDIDATE_PROBE_FAIL:-}}" = "1" ]; then@@ -211,7 +239,7 @@ def _write_fake_uv(path: Path, uv_log: Path) -> None:fiexit 1EOF- chmod +x "$bin_dir/python3"+ chmod +x "$fixture_bin/python3"if [ "${{VIBE_TEST_UV_FAIL:-}}" = "1" ]; thenexit 17fi@@ -408,17 +436,26 @@ def test_repeated_installer_runs_prune_old_generations(tmp_path):env = os.environ.copy()env["HOME"] = str(home_dir)env["PATH"] = os.pathsep.join([str(path_dir), "/usr/bin", "/bin"])-- first = _install(env)- first_generations = sorted((home_dir / ".avibe" / "runtime" / "install-generations").iterdir())- second = _install(env)- generations = sorted((home_dir / ".avibe" / "runtime" / "install-generations").iterdir())-- assert first.returncode == 0, first.stdout + first.stderr- assert second.returncode == 0, second.stdout + second.stderr- assert len(first_generations) == 1- assert len(generations) == 2- assert all(path.is_dir() for path in generations)+ env["VIBE_TEST_SHARED_ACTIVATION"] = "1"++ root = home_dir / ".avibe" / "runtime" / "install-generations"+ previous = None+ for index in range(5):+ result = _install(env)+ assert result.returncode == 0, result.stdout + result.stderr+ generations = list(root.iterdir())+ assert len(generations) == 1+ assert all((path / "uv/tools/avibe-os/uv-receipt.toml").is_file() for path in generations)+ assert not any((path / ".avibe-install.json").exists() for path in generations)+ assert not any((path / ".avibe-installing").exists() for path in generations)+ assert "Install generation retention:" in result.stderr+ if index >= 1:+ assert "Collected 1 retired install generations" in result.stderr+ current = (path_dir / "vibe").resolve()+ assert current.is_file()+ if previous:+ assert not previous.exists()+ previous = currentdef test_install_script_activates_a_wheel_without_the_shared_protocol(tmp_path):@@ -836,6 +873,7 @@ def test_windows_installer_honors_configured_tool_bin_and_cross_volume_copy_fallassert '$env:Path = "$stableBin;$persistedPath"' in powershellassert "& $stableLauncher --help" in powershellassert 'Invoke-NativeCommand -FilePath $stableLauncher -Arguments @("runtime", "prepare", "--strict")' in powershell+ assert "Write-Host $activation.Output" in powershelldef test_install_script_candidate_probes_ignore_python_path_overrides():@@ -1143,6 +1181,19 @@ def test_install_script_activation_fallback_refuses_an_unowned_destination(tmp_passert not (home_dir / ".avibe" / "runtime" / "install-generations").exists()+def test_powershell_publishes_complete_installer_marker_before_source_snapshot():+ source = INSTALL_POWERSHELL.read_text(encoding="utf-8")+ # PowerShell execution/convergence remains a native Windows CI gate.+ staging = source.split('$installerMarker = Join-Path $generationRoot ".avibe-installing"', 1)[1]+ staging = staging.split("$previousSourcePath = $launcherState.SourcePath", 1)[0]+ assert "Set-Content -LiteralPath $installerMarker " not in staging+ assert "Set-Content -LiteralPath $installerMarkerTemporary " in staging+ publication = "[System.IO.File]::Move($installerMarkerTemporary, $installerMarker)"+ assert publication in staging+ assert staging.index(publication) < staging.index("Get-LauncherState")+ assert "Remove-Item -LiteralPath $generationRoot -Recurse -Force" in staging++def test_install_script_skips_relative_path_entries_for_tool_bin(tmp_path):home_dir = tmp_path / "home"home_dir.mkdir()diff --git a/tests/test_restart_supervisor.py b/tests/test_restart_supervisor.pyindex 3b211e166..1233e8d50 100644--- a/tests/test_restart_supervisor.py+++ b/tests/test_restart_supervisor.py@@ -322,7 +322,10 @@ def test_a_recorded_outcome_reports_the_job_and_nothing_about_liveness(monkeypatassert "service_alive" not in status-def test_restart_job_stops_and_starts_service(monkeypatch, tmp_path):[email protected]("scope,ready", [("full", True), ("service", True), ("full", False)])+def test_restart_job_stops_and_starts_service(monkeypatch, tmp_path, scope, ready):+ from vibe import install_generations+monkeypatch.setenv("AVIBE_HOME", str(tmp_path))paths.ensure_data_dirs()paths.get_runtime_pid_path().write_text("111", encoding="utf-8")@@ -334,10 +337,24 @@ def test_restart_job_stops_and_starts_service(monkeypatch, tmp_path):monkeypatch.setattr(runtime, "pid_alive", lambda pid: pid == 222)monkeypatch.setattr(runtime, "service_pid_recorded", lambda pid: pid == 222)monkeypatch.setattr(runtime, "service_instance_started", lambda pid: pid == 222)+ monkeypatch.setattr(runtime, "wait_for_service_ready", lambda *args, **kwargs: 222 if ready else None)+ collected = []++ def collect(launcher):+ assert runtime.read_json(runtime.get_restart_status_path())["state"] == "succeeded"+ collected.append(launcher)- rc = restart_supervisor._run_restart_job(job_id="jobabc", delay_seconds=0, vibe_path="/bin/vibe", trigger="test")+ monkeypatch.setattr(install_generations, "collect_install_generations", collect)+ rc = restart_supervisor._run_restart_job(+ job_id="jobabc", delay_seconds=0, vibe_path="/bin/vibe", trigger="test", scope=scope,+ )+ if not ready:+ assert rc != 0+ assert collected == []+ returnassert rc == 0+ assert collected == (["/bin/vibe"] if scope == "full" else [])assert calls == ["stop_runtime", "start_runtime"]status = runtime.read_json(runtime.get_restart_status_path())assert status["ok"] is Truediff --git a/tests/test_upgrade_flow.py b/tests/test_upgrade_flow.pyindex b51eaecc3..a3a860335 100644--- a/tests/test_upgrade_flow.py+++ b/tests/test_upgrade_flow.py@@ -198,7 +198,7 @@ def test_activate_upgrade_candidate_replaces_windows_hardlink_launcher(monkeypatassert launcher.resolve() == candidate.resolve()-def test_activation_leaves_every_other_generation_untouched(monkeypatch, tmp_path):+def test_activation_retains_unidentified_directories_without_uv_artifacts(monkeypatch, tmp_path):from vibe import upgraderoot = tmp_path / "generations"@@ -516,6 +516,33 @@ def test_copy_marker_must_match_the_live_launcher(monkeypatch, tmp_path):assert upgrade._launcher_generation(launcher, root) == current.resolve()+def test_copy_marker_validation_reads_fresh_bytes_after_same_stat_replacement(+ monkeypatch, tmp_path,+):+ from vibe import upgrade++ root = tmp_path / "home" / "runtime" / "install-generations"+ generation = root / "current"+ launcher = tmp_path / ".local" / "bin" / "vibe.exe"+ marker = launcher.parent / ".vibe.exe.avibe-generation"+ candidate = generation / "bin" / "vibe.exe"+ candidate.parent.mkdir(parents=True)+ candidate.write_text("current\n", encoding="utf-8")+ launcher.parent.mkdir(parents=True)+ launcher.write_text("current\n", encoding="utf-8")+ marker.write_text(str(generation), encoding="utf-8")+ monkeypatch.setattr(upgrade, "atomic_uv_install_root", lambda: root)++ assert upgrade._launcher_generation(launcher, root) == generation.resolve()+ original_stat = launcher.stat()+ launcher.write_text("altered\n", encoding="utf-8")+ os.utime(launcher, ns=(original_stat.st_atime_ns, original_stat.st_mtime_ns))+ assert launcher.stat().st_size == original_stat.st_size+ assert launcher.stat().st_mtime_ns == original_stat.st_mtime_ns++ assert upgrade._launcher_generation(launcher, root) is None++def test_launcher_is_current_process_only_matches_windows_launcher(monkeypatch, tmp_path):from vibe import upgrade@@ -644,6 +671,7 @@ def test_deferred_upgrade_activation_uses_candidate_python(monkeypatch, tmp_pathactivation = AtomicActivation(launcher, candidate, tmp_path / "generation")calls = {}+ monkeypatch.setattr(upgrade, "atomic_uv_install_root", lambda: tmp_path)monkeypatch.setattr(upgrade, "_candidate_python", lambda _candidate: candidate_python)monkeypatch.setattr(upgrade.runtime_mod, "process_create_time", lambda _pid: 123.0)monkeypatch.setattr(upgrade, "get_safe_cwd", lambda: str(tmp_path))@@ -673,6 +701,7 @@ def test_deferred_upgrade_activation_uses_candidate_python(monkeypatch, tmp_pathassert "--restart" in calls["command"]assert "--prepare-show-runtime" in calls["command"]assert calls["kwargs"]["env"] == {"PATH": "clean"}+ assert (candidate.parent.parent / ".avibe-installing").read_text() == "456"def test_deferred_activation_rejects_missing_source_when_launcher_changed(monkeypatch, tmp_path):diff --git a/tests/test_vibe_cli.py b/tests/test_vibe_cli.pyindex d51f0bc80..2e9747881 100644--- a/tests/test_vibe_cli.py+++ b/tests/test_vibe_cli.py@@ -2016,6 +2016,13 @@ def test_cmd_start_keeps_the_service_it_started_once_the_receipt_is_out(monkeypa"""started = _ui_refuses_to_start(monkeypatch, reused=False, ui_outcome=5678)+ from vibe import install_generations++ collected = []+ monkeypatch.setattr(+ install_generations, "collect_install_generations",+ lambda launcher: collected.append(launcher),+ )assert cli.cmd_start() == 0@@ -2026,6 +2033,7 @@ def test_cmd_start_keeps_the_service_it_started_once_the_receipt_is_out(monkeypaf"cmd_start stopped the UI of a start that had already succeeded: {started.calls}")assert "@avibe-start-receipt:" in capsys.readouterr().out+ assert len(collected) == 1def test_ui_pid_probe_accepts_only_a_verified_ui_process(monkeypatch, tmp_path):diff --git a/vibe/cli.py b/vibe/cli.pyindex 8a6eb5f58..126bb007d 100644--- a/vibe/cli.py+++ b/vibe/cli.py@@ -13519,6 +13519,10 @@ def cmd_start(*, open_browser: bool | None = None):# still leaves evidence; either way the start has failed.runtime.stop_service()raise+ if service_ready:+ from vibe.install_generations import collect_install_generations++ collect_install_generations(cache_running_vibe_path())return 0@@ -17996,6 +18000,20 @@ def _dispatch_deferred_upgrade_activation(argv: list[str]) -> int:return 0+class _InstallerRetentionFormatter(logging.Formatter):+ """Show an optional collection failure without an installation traceback."""++ def format(self, record: logging.LogRecord) -> str:+ # Leave the original exception intact for service/file log handlers.+ diagnostic = logging.makeLogRecord(record.__dict__)+ if diagnostic.exc_info:+ diagnostic.msg = f"{record.getMessage()}: {diagnostic.exc_info[1]}"+ diagnostic.args = ()+ diagnostic.exc_info = None+ diagnostic.exc_text = None+ return super().format(diagnostic)++def _dispatch_installer_activation(argv: list[str]) -> int:"""Activate a staged one-command install through the shared Python owner."""@@ -18020,12 +18038,25 @@ def _dispatch_installer_activation(argv: list[str]) -> int:candidate_launcher=Path(args.candidate),source_generation=Path(args.source_generation) if args.source_generation else None,)+ # Bootstrap activation does not start the service logging infrastructure.+ # Keep best-effort retention decisions visible even when activation succeeds.+ from vibe.install_generations import logger as retention_logger++ handler = logging.StreamHandler(sys.stderr)+ handler.setFormatter(_InstallerRetentionFormatter())+ previous_level = retention_logger.level+ retention_logger.addHandler(handler)+ retention_logger.setLevel(logging.INFO)try:activate_installer_candidate(activation)except Exception as exc:discard_atomic_uv_install_generation(activation.candidate_launcher)print(f"installer activation failed: {exc}", file=sys.stderr)return 1+ finally:+ retention_logger.removeHandler(handler)+ retention_logger.setLevel(previous_level)+ handler.close()return 0diff --git a/vibe/install_generations.py b/vibe/install_generations.pynew file mode 100644index 000000000..41be8231c--- /dev/null+++ b/vibe/install_generations.py@@ -0,0 +1,399 @@+"""Retire managed installations without promising arbitrary old-process longevity.++uv's existing tool receipt identifies an installation, including released+pre-retention layouts. The selected launcher, this invocation, official runtime+and install/restart handoffs are protected. Unregistered stale processes and+commands naming retired directories are outside this recovery-oriented contract.+"""++from __future__ import annotations++import json+import logging+from pathlib import Path+import re+import shutil+import sys++import psutil+from packaging.requirements import Requirement+from packaging.utils import canonicalize_name++try:+ import tomllib+except ImportError: # Python 3.10; already a project dependency.+ import tomli as tomllib++from config import paths+from config.atomic_io import write_atomic++logger = logging.getLogger(__name__)+INSTALLER_PID = ".avibe-installing"+++def _uv_installation(generation: Path) -> tuple[Path, set[Path]] | None:+ """Recognize released Avibe tool layouts without trusting directory names."""+ environments = [+ generation / layout / package+ for layout in ("tools", "uv/tools")+ for package in ("avibe-os", "vibe-remote")+ if (generation / layout / package).is_dir()+ ]+ if len(environments) != 1:+ return None+ environment = environments[0]+ if environment.resolve() != environment:+ return None+ layout_root = environment.relative_to(generation).parts[0]+ if any(+ child.name not in {layout_root, "bin", INSTALLER_PID}+ for child in generation.iterdir()+ ):+ return None+ if any(+ child != environment and (+ child.name not in {".lock", ".gitignore", "CACHEDIR.TAG"}+ or not child.is_file() or child.is_symlink()+ )+ for child in environment.parent.iterdir()+ ):+ return None+ if layout_root == "uv" and any(+ child.name != "tools" for child in environment.parent.parent.iterdir()+ ):+ return None+ if (+ not (environment / "pyvenv.cfg").is_file()+ or (environment / "pyvenv.cfg").is_symlink()+ or (environment / "uv-receipt.toml").is_symlink()+ ):+ return None+ try:+ with (environment / "uv-receipt.toml").open("rb") as stream:+ tool = tomllib.load(stream)["tool"]+ requirement = tool["requirements"][0]+ name = requirement["name"] if isinstance(requirement, dict) else Requirement(requirement).name+ if canonicalize_name(name) != environment.name:+ return None+ exports: set[Path] = set()+ for entry in tool["entrypoints"]:+ if entry["name"].lower() not in {"vibe", "vibe.exe"}:+ return None+ exported = Path(entry["install-path"])+ if (+ exported.is_absolute()+ # uv records the logical name without Windows' EXE_SUFFIX.+ and (entry["name"].lower(), exported.name.lower()) in {+ ("vibe", "vibe"), ("vibe", "vibe.exe"), ("vibe.exe", "vibe.exe"),+ }+ and exported.parent.resolve() == generation / "bin"+ ):+ exports.add(exported)+ else:+ return None+ if not exports:+ return None+ export_names = {export.name for export in exports}+ # A partial retirement may already have removed bin or a symlink's+ # destination. Existing extra files/directories are never our payload.+ bin_dir = generation / "bin"+ if bin_dir.exists() and any(+ child.name not in export_names or child.is_dir()+ for child in bin_dir.iterdir()+ ):+ return None+ return environment, exports+ except (OSError, ValueError, TypeError, KeyError, IndexError):+ # Unknown/incomplete artifacts do not become deletion targets.+ return None+++def _retire_installation(generation: Path, environment: Path) -> None:+ """Keep uv's ownership evidence until all sizeable content has been removed.++ Windows may reject deletion of a loaded DLL midway through rmtree. Removing+ the receipt first would leave a full, permanently unrecognizable environment.+ Do not rename/adopt tombstones by name or invent another receipt owner.+ """+ evidence = {environment / "pyvenv.cfg", environment / "uv-receipt.toml"}++ def remove_content(directory: Path) -> None:+ for child in directory.iterdir():+ if child in evidence:+ continue+ if child.is_symlink() or not child.is_dir():+ child.unlink()+ elif child == environment or child in environment.parents:+ remove_content(child)+ else:+ shutil.rmtree(child)++ remove_content(generation)+ # Only the two small proof files and their empty parents remain. A failure+ # here can leave a few bytes, not an unidentifiable full Python environment.+ for proof in evidence:+ proof.unlink()+ directory = environment+ while directory != generation:+ directory.rmdir()+ directory = directory.parent+ generation.rmdir()+++def mark_install_generation(candidate: Path, pid: int) -> None:+ """Protect staging before publication; callers hold the install lock."""+ from vibe import upgrade++ generation = upgrade._generation_for_path(candidate, upgrade.atomic_uv_install_root())+ if generation is None or pid <= 0:+ raise ValueError("cannot establish staged installation ownership")+ generation.mkdir(parents=True, exist_ok=True)+ write_atomic(generation / INSTALLER_PID, str(pid))+++def finish_install_generation(candidate: Path) -> None:+ """Withdraw staging after activation without invalidating its commit."""+ from vibe import upgrade++ try:+ generation = upgrade._generation_for_path(candidate, upgrade.atomic_uv_install_root())+ if generation is not None:+ (generation / INSTALLER_PID).unlink(missing_ok=True)+ except Exception:+ logger.warning("Activated installation retained its staging marker", exc_info=True)+++def _installer_is_live(generation: Path) -> bool:+ marker = generation / INSTALLER_PID+ try:+ pid = int(marker.read_text(encoding="utf-8-sig").strip())+ created = marker.stat().st_mtime+ except FileNotFoundError:+ # Released shell installers encoded their own $$ before staging.+ # This only protects a handoff; it NEVER establishes deletion ownership.+ legacy = re.fullmatch(r"(\d+)-(\d+)-\d+", generation.name)+ if legacy is None:+ return False+ created, pid = int(legacy[1]), int(legacy[2])+ if pid <= 0:+ raise ValueError("invalid installer PID")+ try:+ process = psutil.Process(pid)+ return (+ process.status() != psutil.STATUS_ZOMBIE+ and int(process.create_time()) <= int(created)+ )+ except psutil.NoSuchProcess:+ return False+++def _invocation_paths() -> set[Path]:+ # Keep logical sys.executable as well as the actual module location: uv's+ # Python symlink may resolve to a shared interpreter outside its environment.+ return {Path(sys.executable).absolute(), Path(sys.prefix).absolute(), Path(__file__).absolute()}+++def _runtime_paths() -> set[Path]:+ """Inspect only official service/UI records, never the user's process table."""+ from vibe import runtime, upgrade++ root = upgrade.atomic_uv_install_root().expanduser().resolve()+ result: set[Path] = set()+ pids: set[int] = set()+ for pid_path in (paths.get_runtime_pid_path(), paths.get_runtime_ui_pid_path()):+ try:+ pid = int(pid_path.read_text(encoding="utf-8").strip())+ except FileNotFoundError:+ continue+ if pid <= 0:+ raise ValueError("invalid official runtime PID")+ pids.add(pid)+ try:+ status = json.loads(paths.get_runtime_status_path().read_text(encoding="utf-8"))+ except FileNotFoundError:+ status = {}+ if not isinstance(status, dict):+ raise ValueError("official runtime status could not be read")+ for key in ("service_pid", "ui_pid"):+ pid = status.get(key)+ if pid is not None:+ if type(pid) is not int or pid <= 0:+ raise ValueError("invalid official status PID")+ pids.add(pid)+ available, owner = runtime.service_instance_lock_available()+ if not available:+ if not owner:+ raise ValueError("official service lock owner could not be identified")+ pids.add(owner)+ for pid in pids:+ try:+ process = psutil.Process(pid)+ if process.status() == psutil.STATUS_ZOMBIE:+ continue+ argv = [argument.strip('"') for argument in process.cmdline()]+ executable = process.exe()+ if not argv or not Path(argv[0]).is_absolute() or not Path(executable).is_absolute():+ raise ValueError("official runtime interpreter could not be identified")+ process_paths = {Path(executable)}+ process_paths.update(Path(value) for value in argv if value and Path(value).is_absolute())+ if sys.platform == "win32" and not any(+ upgrade._generation_for_path(path, root) is not None for path in process_paths+ ):+ # Windows venv redirectors spawn a base-Python child. The UI's+ # -c command may need its parent to identify the environment.+ # Losing that parent is not proof the official child has exited.+ try:+ parent = process.parent()+ parent_executable = parent.exe() if parent is not None else ""+ except psutil.NoSuchProcess:+ parent_executable = ""+ if not parent_executable:+ if not process.is_running() or process.status() == psutil.STATUS_ZOMBIE:+ continue+ raise ValueError("live official runtime lost its redirector")+ if not Path(parent_executable).is_absolute():+ raise ValueError("official runtime redirector could not be identified")+ process_paths.add(Path(parent_executable))+ result.update(process_paths)+ except psutil.NoSuchProcess:+ continue+ # Access denial or an unknown official launch shape defers this pass.+ return result+++def _restart_is_unsettled() -> bool:+ from vibe import upgrade++ path = upgrade.runtime_mod.get_restart_status_path()+ try:+ payload = json.loads(path.read_text(encoding="utf-8"))+ except FileNotFoundError:+ return False+ if not isinstance(payload, dict):+ return True+ try:+ state = upgrade.RestartState(payload.get("state"))+ except (ValueError, TypeError):+ return True+ if state is upgrade.RestartState.UNKNOWN or upgrade.restart_record_is_pending(payload, path):+ return True+ if state is not upgrade.RestartState.SUCCEEDED:+ return False+ try:+ followup = json.loads((paths.get_runtime_dir() / "pending_restart.json").read_text(encoding="utf-8"))+ except FileNotFoundError:+ return False+ if not isinstance(followup, dict):+ return True+ job_id = followup.get("restart_job_id")+ if job_id and job_id != payload.get("job_id"):+ return False+ # Success is written before the supervisor consumes its follow-up. Reuse+ # the existing process identity/seed grace policy for that unfinished tail,+ # without letting failed, superseded or abandoned markers veto forever.+ # A released unscoped marker is consumable by any successful supervisor.+ return upgrade.restart_record_is_pending(+ {**payload, "state": upgrade.RestartState.RUNNING.value}, path,+ )+++def _launcher_targets(+ launcher: Path, root: Path, managed: dict[Path, tuple[Path, set[Path]]],+) -> set[Path]:+ from vibe import upgrade++ generation = upgrade._launcher_generation(launcher, root)+ if generation is not None:+ if generation not in managed:+ # An in-root wrapper can depend on another generation. Neither the+ # primary command nor PATH may authorize deleting that dependency.+ raise ValueError("selected in-root installation could not be recognized")+ return {generation}+ if launcher.is_symlink():+ # An outside alias proves nothing about which managed generation the+ # normal command selects. Wait for a managed activation instead.+ return set()+ current_bytes = launcher.read_bytes()+ return {+ generation for generation, (_, exports) in managed.items()+ if any(exported.is_file() and exported.read_bytes() == current_bytes for exported in exports)+ }+++def collect_install_generations(launcher: str | Path | None = None) -> list[Path]:+ """Best-effort retirement after activation or successful runtime startup.++ Normally only the selected environment remains. Current invocation/official+ runtime and concurrent handoffs may retain more temporarily. Old activation+ receipts and arbitrary old processes are not prerequisites for collection.+ """+ from vibe import upgrade++ try:+ root = upgrade.atomic_uv_install_root().expanduser().resolve()+ if not root.is_dir():+ return []+ selected = str(launcher) if launcher is not None else upgrade.get_running_vibe_path()+ if not selected or not upgrade._is_stable_launcher_path(Path(selected)):+ return []+ launcher_path = Path(selected).expanduser().absolute()+ if not launcher_path.is_file():+ return []+ # Same lock/path as installation, but optional maintenance must not make+ # startup wait behind a long package download.+ with upgrade.atomic_upgrade_lock(timeout_seconds=0):+ if _restart_is_unsettled():+ logger.info("Install generation collection deferred: restart in progress")+ return []+ generations = [+ path for path in root.iterdir()+ if not path.is_symlink() and path.is_dir() and path.resolve().parent == root+ ]+ selected_generation = upgrade._launcher_generation(launcher_path, root)+ if any(+ generation != selected_generation and _installer_is_live(generation)+ for generation in generations+ ):+ logger.info("Install generation collection deferred: installer handoff")+ return []+ managed = {+ generation: installation for generation in generations+ if (installation := _uv_installation(generation)) is not None+ }+ logger.info(+ "Install generation retention: %d managed, %d unrecognized retained",+ len(managed), len(generations) - len(managed),+ )+ if not managed:+ return []+ kept = _launcher_targets(launcher_path, root, managed)+ if not kept:+ logger.info("Install generation collection deferred: unknown launcher target")+ return []+ # Invoking an explicit alias is not permission to break the command+ # selected by PATH. This is one ordinary command lookup, not an+ # alias registry or filesystem scan. Only confirmed managed targets+ # add protection; an unrelated command cannot veto retirement.+ path_command = shutil.which("vibe")+ if path_command and Path(path_command).absolute() != launcher_path:+ kept.update(_launcher_targets(Path(path_command).absolute(), root, managed))+ references = _invocation_paths() | _runtime_paths()+ kept.update(+ generation for path in references+ if (generation := upgrade._generation_for_path(path, root)) is not None+ )+ removed = []+ for generation in managed.keys() - kept:+ try:+ _retire_installation(generation, managed[generation][0])+ removed.append(generation)+ except OSError:+ logger.warning("Could not retire installation %s", generation, exc_info=True)+ if removed:+ logger.info("Collected %d retired install generations", len(removed))+ return removed+ except Exception:+ # This includes nonblocking lock acquisition and inspection failures.+ # It must never escape to activation callers that discard a failed target.+ logger.warning("Install generation collection deferred", exc_info=True)+ return []diff --git a/vibe/restart_supervisor.py b/vibe/restart_supervisor.pyindex 4a01de174..6d1c829fe 100644--- a/vibe/restart_supervisor.py+++ b/vibe/restart_supervisor.py@@ -427,6 +427,11 @@ def _run_restart_job(_write_status(payload)write(f"restart job succeeded new_pid={new_pid}")+ if restart_ui:+ from vibe.install_generations import collect_install_generations++ collect_install_generations(vibe_path)+if prepare_show_runtime:env = get_restart_environment(vibe_path=vibe_path)prepare_command = [diff --git a/vibe/runtime.py b/vibe/runtime.pyindex 11fbde6dc..4dcabf004 100644--- a/vibe/runtime.py+++ b/vibe/runtime.py@@ -2009,6 +2009,9 @@ def start_service(_raise_service_started_but_never_ran(pid, timeout=SERVICE_SLOW_START_TIMEOUT_SECONDS)if start_info is not None:start_info.capture(ready_pid, reused=start_info.reused)+ from vibe.install_generations import collect_install_generations++ collect_install_generations()return ready_piddiff --git a/vibe/upgrade.py b/vibe/upgrade.pyindex 105e6c829..fbfe48aae 100644--- a/vibe/upgrade.py+++ b/vibe/upgrade.py@@ -1,7 +1,6 @@from __future__ import annotationsimport contextlib-import filecmpimport jsonimport loggingimport os@@ -134,6 +133,10 @@ def execute_upgrade_plan(if preflight.returncode != 0:return preflight+ if plan.activation is not None:+ from vibe.install_generations import mark_install_generation++ mark_install_generation(plan.activation.candidate_launcher, os.getpid())return run(plan.command, env=plan.env, **run_kwargs)@@ -197,11 +200,11 @@ def atomic_uv_install_root() -> Path:@contextlib.contextmanager-def atomic_upgrade_lock():+def atomic_upgrade_lock(*, timeout_seconds: float = UPGRADE_INSTALL_TIMEOUT_SECONDS):"""Serialize staged installation, launcher activation, and pruning."""lock_path = atomic_uv_install_root().expanduser().parent / ".install.lock"- with MigrationFileLock(lock_path, timeout_seconds=UPGRADE_INSTALL_TIMEOUT_SECONDS):+ with MigrationFileLock(lock_path, timeout_seconds=timeout_seconds):yield@@ -356,7 +359,7 @@ def defer_upgrade_activation(log_path = config_paths.get_logs_dir() / f"upgrade-activation-{uuid4().hex}.log"log_path.parent.mkdir(parents=True, exist_ok=True)with log_path.open("a", encoding="utf-8") as log:- return subprocess.Popen(+ process = subprocess.Popen(command,stdin=subprocess.DEVNULL,stdout=log,@@ -370,6 +373,20 @@ def defer_upgrade_activation(# hop on top of it, rather than changing what probes inherit.env=environment_without_caller_context(isolated_probe_environment()),)+ # The parent still owns the install lock and is alive. Publish the helper's+ # PID before releasing that lock, including the interval where the helper+ # is waiting for this Windows CLI to release its executable.+ from vibe.install_generations import mark_install_generation++ try:+ mark_install_generation(activation.candidate_launcher, process.pid)+ except Exception:+ # The helper cannot activate while its parent is alive. This is still+ # pre-commit; the caller can safely discard the failed candidate.+ with contextlib.suppress(OSError):+ process.terminate()+ raise+ return processdef get_cli_launcher_path(launcher: runtime_mod.ServiceLauncher) -> Path | None:@@ -452,7 +469,8 @@ def _generation_for_hardlink(launcher: Path, root: Path) -> Path | None:try:candidate_stat = candidate.stat()if generation.is_dir() and (candidate_stat.st_dev, candidate_stat.st_ino) == identity:- return generation+ # Directory aliases must use the collector's canonical identity.+ return _generation_for_path(generation, root)except OSError:continuereturn None@@ -479,7 +497,10 @@ def _launcher_generation(launcher: Path, root: Path) -> Path | None:# as a hint and prove that it still describes the live launcher before use.candidate = generation / "bin" / launcher.nametry:- return generation if filecmp.cmp(launcher, candidate, shallow=False) else None+ # Read both files on every check. Marker validation is a safety+ # boundary, and stat-keyed filecmp caching could reuse a comparison+ # after a same-size/same-mtime copy fallback was replaced.+ return generation if launcher.read_bytes() == candidate.read_bytes() else Noneexcept OSError:return None@@ -588,6 +609,18 @@ def _prepare_launcher_replacement(replacement: Path, target: Path) -> None:def activate_upgrade_candidate(activation: AtomicActivation) -> None:"""Atomically switch the stable launcher to a validated candidate."""+ # Runtime callers already own this lock; the lock is re-entrant so direct+ # activation and installer callers share the same collection boundary too.+ with atomic_upgrade_lock():+ _activate_upgrade_candidate_locked(activation)+++def _activate_upgrade_candidate_locked(activation: AtomicActivation) -> None:+ from vibe.install_generations import (+ collect_install_generations,+ finish_install_generation,+ )+result = verify_upgrade_candidate(activation)if not result.ok:raise RuntimeError(f"staged Avibe install failed integrity checks: {result.detail}")@@ -603,6 +636,8 @@ def activate_upgrade_candidate(activation: AtomicActivation) -> None:replacement.unlink()raise_update_launcher_generation_marker(launcher, activation.candidate_launcher, root)+ finish_install_generation(activation.candidate_launcher)+ collect_install_generations(launcher)def activate_installer_candidate(activation: AtomicActivation) -> None:@@ -620,6 +655,11 @@ def activate_installer_candidate(activation: AtomicActivation) -> None:def activate_launcher_target(launcher: str | os.PathLike[str], target: str | os.PathLike[str]) -> None:"""Atomically point a stable launcher at an installed target."""+ with atomic_upgrade_lock():+ _activate_launcher_target_locked(launcher, target)+++def _activate_launcher_target_locked(launcher: str | os.PathLike[str], target: str | os.PathLike[str]) -> None:launcher_path = Path(launcher).expanduser()target_path = Path(target).expanduser()if not target_path.is_file() or not os.access(target_path, os.X_OK):