ai-battery 0.1.21 → 0.1.22

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # AI Battery
2
2
 
3
- 0.1.19: Codex wrapper는 현재 PATH를 따릅니다. nvm 등의 전환 후 새 Codex를 고정된 이전 경로 대신 실행합니다. Windows·WSL 사용량 공유 수정도 포함하므로 양쪽 설치를 업데이트하세요. Windows Terminal padding 변경은 로컬 표시 조정이며, 패키지는 사용자 터미널 설정을 자동 변경하지 않습니다.
3
+ 0.1.22: 기본 Codex 설치는 실행 명령·PATH·설정을 변경하지 않습니다. 이전 wrapper는 `setup codex`로 해제할 수 있고, 전체 `uninstall`은 통합 복원 후 캐시·전용 런타임·현재 npm 설치도 제거합니다. 기존 Bash 터미널에 삭제된 wrapper 경로가 남았다면 `hash -r`을 실행하세요.
4
4
 
5
5
  [한국어](README.md) · [English](docs/i18n/en/) · [日本語](docs/i18n/ja/) · [中文](docs/i18n/zh/) · [Español](docs/i18n/es/)
6
6
 
@@ -55,7 +55,7 @@ Codex 86% │ 5h 18:09 │ 7d 82% ┃ Claude 4% │ 5h 18:10 │ 7d 71%
55
55
  | `ai-battery --watch` | 지원 | 지원 | 지원 | 지원 | 터미널 안에서 주기적으로 갱신합니다. |
56
56
  | Claude statusLine | 지원 | 지원 | 지원 | 지원 | Claude Code `statusLine`에 `node <script>` 명령을 저장합니다. |
57
57
  | Codex fullscreen | 지원 | 지원 | 지원 | 지원 | Windows 기본값은 Fullscreen PTY 화면과 터미널 배터리 행을 합성합니다. WSL/Linux/macOS는 POSIX PTY와 `python3`를 사용합니다. |
58
- | `ai-battery setup codex` | 지원 | 지원 | 지원 | 지원 | Codex `[tui].status_line`을 맞추고, Windows는 `codex.cmd` wrapper, WSL/Linux/macOS는 POSIX shell wrapper를 설치합니다. |
58
+ | `ai-battery setup codex` | 지원 | 지원 | 지원 | 지원 | 기존 AI Battery wrapper를 해제합니다. 새 wrapper나 Codex 설정 변경은 명시적 옵션이 필요합니다. |
59
59
  | `ai-battery hud` | 지원 | 지원 | 미지원 | 지원 | Windows/WSL은 PowerShell/WinForms HUD, macOS는 menu bar status item입니다. |
60
60
 
61
61
  실행 중 감지는 Linux/WSL은 `/proc`, macOS는 `ps`, Windows는 PowerShell 프로세스 목록을 사용합니다. 텍스트 출력은 흰색/회색으로, macOS HUD는 실행 중인 항목만 색상 배터리바로 강조하고 비실행 항목은 흐린 회색 계열로 표시합니다.
@@ -82,7 +82,7 @@ npx ai-battery
82
82
  npm install -g ai-battery
83
83
  ```
84
84
 
85
- 2. Claude와 Codex 자동 표시를 설정합니다.
85
+ 2. Claude statusLine을 설정하고, 기존 Codex wrapper가 있으면 해제합니다.
86
86
 
87
87
  ```bash
88
88
  ai-battery setup
@@ -95,7 +95,7 @@ npx ai-battery
95
95
  codex
96
96
  ```
97
97
 
98
- 4. 데스크톱 HUD나 macOS menu bar 표시가 필요하면 실행합니다.
98
+ 4. Codex 사용량은 별도 터미널의 `ai-battery --watch 2`, 또는 Windows/WSL/macOS HUD로 확인합니다.
99
99
 
100
100
  ```bash
101
101
  ai-battery hud
@@ -131,13 +131,13 @@ ai-battery on codex
131
131
 
132
132
  ## Uninstall
133
133
 
134
- `off`는 표시만 숨기는 설정이고, `uninstall`은 `setup`과 HUD autostart가 만든 통합 지점을 제거합니다.
134
+ `off`는 표시만 숨깁니다. 인자 없는 `uninstall`은 통합을 복원하고, 소유권을 확인한 AI Battery 캐시·전용 런타임·별칭과 현재 실행 중인 npm 설치까지 제거합니다. 개발 checkout이나 임시 npx 실행에서는 npm 프로젝트를 삭제하지 않습니다.
135
135
 
136
136
  ```bash
137
137
  ai-battery uninstall
138
138
  ```
139
139
 
140
- 일부만 제거할 수도 있습니다.
140
+ 통합만 해제하고 패키지는 유지하려면 `ai-battery teardown`을 사용합니다. 아래처럼 특정 통합만 제거할 수도 있습니다.
141
141
 
142
142
  ```bash
143
143
  ai-battery uninstall codex
@@ -149,18 +149,18 @@ ai-battery uninstall hud
149
149
 
150
150
  복구 기록은 `ai-battery uninstall`이 해당 항목을 성공적으로 복원하거나 안전하게 제거한 뒤에만 지워집니다. Claude는 기존 `statusLine`과 파일 존재 여부·권한만 저장하며 `settings.json` 전체를 복제하지 않으므로 다른 설정이나 비밀값을 백업 파일에 중복 보관하지 않습니다. JSON 결과나 종료 코드를 확인하는 자동화에서는 0일 때만 완전한 정리로 간주하세요.
151
151
 
152
- 최신 npm은 패키지의 uninstall lifecycle을 실행하지 않기 때문에 `npm uninstall ai-battery` 또는 `npm uninstall -g ai-battery`만으로는 외부 통합 지점을 자동 정리할 수 없습니다. 완전히 제거하려면 npm 패키지를 지우기 전에 먼저 실행하세요.
152
+ 전체 삭제는 통합 복원에 성공한 경우에만 npm 제거로 진행합니다. 수정된 관리 블록, 확인할 수 없는 파일과 복구 기록은 보존하고 결과에 경로를 표시합니다. 같은 폴더에 사용자가 추가한 파일이나 다른 npm 패키지는 삭제하지 않습니다. Windows와 WSL에 각각 설치했다면 각 설치에서 실행하세요.
153
153
 
154
154
  ```bash
155
155
  ai-battery uninstall
156
- npm uninstall -g ai-battery
156
+ hash -r # Bash: 기존 터미널의 삭제된 wrapper 경로 캐시 해제 (zsh: rehash)
157
157
  ```
158
158
 
159
- 이미 npm 패키지를 먼저 지운 뒤라면, 다시 설치한 다음 `ai-battery uninstall`을 실행하거나 아래 항목을 직접 확인해 제거해야 합니다: AI Battery가 만든 Codex wrapper, shell rc의 `# >>> ai-battery setup >>>` block, Codex `~/.codex/config.toml`의 `[tui].status_line`, Claude `statusLine`, HUD/menu bar autostart.
159
+ 자식 프로세스인 CLI는 부모 셸의 명령 캐시를 지울 수 없습니다. 새 터미널을 열어도 캐시는 초기화됩니다. 현대 npm은 외부 통합을 정리하는 uninstall lifecycle을 실행하지 않으므로 `npm uninstall -g ai-battery`만 실행했던 구버전 사용자는 패키지를 다시 설치하고 `ai-battery uninstall`로 통합부터 정리하세요.
160
160
 
161
161
  ## Setup
162
162
 
163
- `setup`은 한 번만 실행합니다. Claude Code에는 statusLine hook을 설치하고, Codex에는 기본 status line 구성과 platform wrapper를 설치해서 이후에는 추가 명령 없이 원래처럼 실행하게 합니다.
163
+ `setup`은 Claude Code의 statusLine hook을 설정합니다. Codex는 기본적으로 독립 실행을 유지하며, 이전 버전의 AI Battery wrapper와 변경된 설정만 복원합니다. 원래 `codex` 실행 파일·PATH·설정에 새 변경을 추가하지 않습니다.
164
164
 
165
165
  ```bash
166
166
  ai-battery setup
@@ -173,7 +173,11 @@ ai-battery setup claude
173
173
  ai-battery setup codex
174
174
  ```
175
175
 
176
- Codex setup은 `~/.codex/config.toml`의 `[tui]`에 `model-with-reasoning`, `current-dir`, `git-branch` status line을 설정합니다. 기존 값이 있으면 uninstall 복구용으로 백업합니다. Codex wrapper는 기존 `codex` 명령을 직접 덮어쓰지 않습니다. `~/.local/bin`이 이미 PATH에서 원본 `codex`보다 앞에 있고 `~/.local/bin/codex`가 비어 있거나 AI Battery 관리 파일이면 그 위치에 wrapper를 둬서 바로 잡히게 합니다. 그렇지 않으면 `~/.local/share/ai-battery/bin/codex`에 관리형 wrapper를 만들고, 필요한 경우 셸 설정에 이 디렉터리를 PATH 앞쪽으로 추가합니다. `~/.local/bin/codex` 같은 공용 위치에 이미 다른 파일이 있으면 덮어쓰지 않습니다. 새 터미널부터 `codex`가 자동으로 AI Battery 하단 행과 함께 실행됩니다. 같은 터미널에서 이미 `codex`를 실행한 적이 있으면 셸 캐시 때문에 `hash -r`이 한 번 필요할 수 있고, PATH 추가가 필요한 경우에는 `setup` 출력에 표시되는 `source ...` 명령을 실행하세요.
176
+ Codex 실행 경로를 그대로 유지하려면 `ai-battery --watch 2` 또는 `ai-battery hud`를 사용하세요. 하단 행을 실행 세션 하나에만 추가하려면 POSIX에서는 `ai-battery-run -- codex`, Windows에서는 `ai-battery-run-win -- codex`를 직접 실행합니다.
177
+
178
+ 기존처럼 `codex` 명령에 wrapper를 연결하려는 경우에만 `ai-battery setup codex --wrap-codex`를 사용합니다. Codex `[tui].status_line` 변경도 별도 옵션인 `--configure-codex-statusline`이 필요합니다. 두 옵션은 실행 경로나 사용자 설정을 변경하므로 기본값에서 제외되어 있습니다. 관리형 변경은 복구 기록을 먼저 저장하고, uninstall 시 해당 변경만 복원합니다.
179
+
180
+ 다음 Windows runner 설명은 직접 runner를 실행하거나 wrapper를 명시적으로 선택한 경우에 적용됩니다.
177
181
 
178
182
  Windows native `cmd`/PowerShell에서는 `codex.cmd` wrapper가 현재 PATH에서 원본 Codex를 매번 찾고, 기본 `composite` runner로 실행합니다. Codex Fullscreen 화면은 `node-pty`의 bundled ConPTY와 `@xterm/headless` 안에서 해석한 뒤, 터미널 최하단의 AI Battery 1행과 합성합니다. Codex의 기본 상태·단축키 행은 본문 스크롤 이동에서 제외하며, 바뀐 화면만 다시 그립니다. 시스템 Node와 Codex 설치는 변경하지 않습니다.
179
183
 
@@ -214,16 +218,13 @@ ai-battery on all
214
218
 
215
219
  ## Codex Terminal Row
216
220
 
217
- `ai-battery setup`은 Codex 자체 status line을 `모델/추론강도 · 워크스페이스 · git branch` 구성으로 맞춥니다. 사용량 표시는 별도의 `codex` wrapper가 담당하므로, 사용자는 원래처럼 `codex`만 입력하면 `ai-battery-run`이 내부에서 Codex를 한 줄 짧은 PTY 안에서 실행합니다.
218
-
219
- ```bash
220
- codex
221
- ```
221
+ 기본 `codex`는 AI Battery를 거치지 않고 실행됩니다. 사용량을 독립적으로 보려면 `ai-battery --watch 2` 또는 지원 플랫폼에서 `ai-battery hud`를 실행하세요.
222
222
 
223
- 직접 wrapper를 실행해야 하는 고급 사용자는 아래 명령을 사용할 수 있습니다.
223
+ 세션 하나에 하단 행을 추가하려면 명시적으로 실행합니다.
224
224
 
225
225
  ```bash
226
- ai-battery-run --provider all codex
226
+ ai-battery-run --provider all -- codex # WSL/Linux/macOS
227
+ ai-battery-run-win --provider all -- codex # Windows cmd/PowerShell
227
228
  ```
228
229
 
229
230
  갱신 주기를 줄이려면 `--interval`을 사용합니다.
@@ -77,6 +77,10 @@ ai_battery_find_command() {
77
77
  ai_battery_usable_runner() {
78
78
  [ -f "$1" ] && [ -x "$1" ] || return 1
79
79
  ai_battery_runner_target=$(ai_battery_realpath "$1") || return 1
80
+ ai_battery_runner_header=$("$ai_battery_head" -c 64 "$ai_battery_runner_target" 2>/dev/null) || return 1
81
+ case "$ai_battery_runner_header" in
82
+ '#!/usr/bin/env python3'*) command -v python3 >/dev/null 2>&1 || return 1 ;;
83
+ esac
80
84
  case "$ai_battery_runner_target" in
81
85
  */versions/node/*) ai_battery_nvm_node "$ai_battery_runner_target" >/dev/null ;;
82
86
  *) return 0 ;;
package/docs/RELEASING.md CHANGED
@@ -1,64 +1,66 @@
1
1
  # npm release
2
2
 
3
- The current release candidate is **0.1.21**, prepared from the 0.1.20 main branch. npm `latest` was checked as **0.1.20** on 2026-10-15. This preparation does not publish to npm or create a release tag.
3
+ The current release candidate is **0.1.22**. It includes the 0.1.21 usage-refresh fixes and changes the default Codex integration to preserve independent execution. Preparing a tarball does not publish it to npm.
4
4
 
5
- ## Changes in 0.1.21
5
+ ## Changes in 0.1.22
6
6
 
7
- - Windows default PTY composition and POSIX terminal rows poll every 2 seconds by default. POSIX polling runs asynchronously so usage scans do not block terminal input or output.
8
- - Polls allow up to 10 seconds by default. Failed updates retry after 1 second, with backoff for repeated failures. A retained reading is marked `[stale]`; an initial failure displays `AI Battery unavailable`.
9
- - New and changed Codex session logs invalidate the parsing cache before its normal expiry. Account usage sharing between Windows and WSL, separate session stores, and existing runtime selection are preserved.
10
- - WSL reuses a brief Windows process scan cache. A known active Codex does not require another process scan just to fetch its usage.
11
- - The package no longer depends on an older copy of `ai-battery` itself.
12
-
13
- Values remain the latest usage reported by local Codex logs and Claude statusLine. They are not direct live server measurements; delayed source updates can delay the display.
7
+ - Default `setup codex` restores legacy AI Battery integrations without creating a Codex wrapper, adding PATH entries or configuring Codex's status line. Use an independent watcher/HUD, or explicitly launch a runner for one session. `--wrap-codex` and `--configure-codex-statusline` are separate opt-ins.
8
+ - Full `ai-battery uninstall` restores integrations, selectively removes verified caches and private runtimes, removes aliases belonging to this installation, and runs npm uninstall against the owning prefix. Other npm packages are preserved. `teardown` and targeted uninstall retain the package; development checkouts and npx do not remove an npm project.
9
+ - Shell and tmux recovery records preserve exact original content, permissions and file absence. User edits outside managed blocks survive repeated setup and uninstall. Edited blocks, retargeted symlinks and unresolved recovery records prevent unsafe removal.
10
+ - Windows PATH cleanup preserves unrelated whitespace and separators and reports failed writes. HUD cleanup verifies its Run value and launcher ownership and preserves unknown files. macOS LaunchAgent cleanup refuses foreign files and symlinks.
11
+ - Existing Bash terminals can cache a deleted legacy Codex wrapper. Run `hash -r` (zsh: `rehash`) or open a new terminal. A child CLI cannot clear its parent shell's command cache. A POSIX wrapper whose Python runner cannot start because Python is absent now runs the original Codex directly.
14
12
 
15
13
  ## Validation
16
14
 
17
- The integrated candidate passed the following checks on 2026-10-15:
15
+ Checked on 2026-10-15:
18
16
 
19
- | Check | Result |
17
+ | Environment | Result |
20
18
  | --- | --- |
21
- | WSL `npm run check` | 133 passed, 15 platform skips, 0 failures |
22
- | Windows native Node 22.23.2 `node --test` | 117 passed, 31 platform skips, 0 failures |
23
- | Focused polling and freshness tests | Slow polls, failed/empty/partial/oversized output, automatic recovery, zero remaining, new sessions, and cache invalidation |
19
+ | WSL `npm run check` | 155 passed, 16 platform skips, 0 failures |
20
+ | Windows native Node 22.23.2 full suite | 132 passed, 39 platform skips, 0 failures |
21
+
22
+ Validation results and tarball manifests are stored in `.cache/releases/0.1.22/`. The regression suite covers default command/config preservation, exact shell restoration, user edits, symlinks, custom integration paths, incomplete recovery, npm failure, global/local prefix selection, actual self-uninstall in isolated installations, and Windows registry ownership. Desktop operations in the npm self-uninstall fixture are stubbed; Windows autostart cleanup is separately exercised against a temporary registry key and profile.
24
23
 
25
- Tarball installation results, package contents, and checksums are saved with the local release artifacts under `.cache/releases/0.1.21/`. Windows ARM64 still requires a device check; native verification here uses x64.
24
+ The current WSL installation was removed with the new cleanup helpers after successful teardown. Original shell, Codex and Claude settings and the original Codex launcher were byte-identical afterward. Codex and Claude still ran successfully. Previous manual test backups were preserved under `.cache/uninstall-audit/preserved-local-test-backups/`.
25
+
26
+ Native Windows validation uses x64 Node 22.23.2. macOS LaunchAgent ownership and file handling are tested through an isolated fixture; native macOS and Windows ARM64 are not verified here.
26
27
 
27
28
  ## Prepare
28
29
 
29
30
  ```text
30
31
  npm run check
31
32
  npm pack --dry-run
32
- npm pack --pack-destination .cache/releases/0.1.21
33
+ npm pack --pack-destination .cache/releases/0.1.22
33
34
  ```
34
35
 
35
- Inspect the package file list. It must include `lib`, the bin entrypoints and required PowerShell modules. Screenshots, logs, credentials, local runtime binaries, tests and `.cache` must not be included. Test the exact tarball with a clean installation on Windows and POSIX. On Windows, also run `npm run smoke:composite` and `npm run smoke:codex-fullscreen-win` against the installed runner; the Codex fixture uses a local mock server and does not consume account quota.
36
+ Inspect the package file list. Include the core cleanup/recovery modules, platform modules, bin entrypoints and required PowerShell files. Exclude screenshots, logs, credentials, local runtime binaries, tests and `.cache`. Verify the exact tarball using an isolated npm prefix and provider homes. Release 0.1.21 fullscreen/compositor reports remain under `.cache/releases/0.1.21/`; this release changes setup/removal rather than terminal composition.
36
37
 
37
38
  ## Publish manually
38
39
 
39
40
  ```text
40
41
  npm login
41
42
  npm whoami
42
- npm publish .cache/releases/0.1.21/ai-battery-0.1.21.tgz --access public --tag latest
43
+ npm publish .cache/releases/0.1.22/ai-battery-0.1.22.tgz --access public --tag latest
43
44
  npm view ai-battery version dist-tags --json
44
45
  ```
45
46
 
46
- Use the exact tested tarball. Complete npm's authentication/2FA prompt when requested. Publishing the same name/version twice is not allowed. If 0.1.21 is already published when you release, increment the version and repeat preparation. Use `--tag next` instead of `--tag latest` for a preview release.
47
-
48
- After successful publication, tag the tested commit (`v0.1.21`) and push the release tag. Keep the remote release branch until the release commit is integrated into main.
47
+ Publish the exact tested tarball. Complete npm authentication/2FA when requested. If the version is already published, increment it and repeat preparation. After publication, tag the tested commit (`v0.1.22`) and integrate the release branch into main.
49
48
 
50
- ## Update installed integrations
49
+ ## Update or remove an installation
51
50
 
52
- Run separately in Windows and WSL:
51
+ Run separately for Windows and WSL:
53
52
 
54
53
  ```text
55
- npm install -g ai-battery@0.1.21
54
+ npm install -g ai-battery@0.1.22
56
55
  ai-battery setup codex
57
- ai-battery doctor
58
56
  ```
59
57
 
60
- Restart the terminal session after updating. A running PTY wrapper retains its loaded code. Existing managed wrappers must be regenerated by setup to adopt the current integration.
58
+ Default setup detaches a legacy wrapper. In an existing Bash terminal run `hash -r`; zsh uses `rehash`. Plain `codex` then runs independently. Display usage with `ai-battery --watch 2` or a supported desktop HUD. There is no built-in `ai-battery update` command.
61
59
 
62
- The private Windows runtime lives under `%LOCALAPPDATA%\ai-battery\runtimes` by default, or the selected AI Battery data directory. `AI_BATTERY_RUNTIME_DOWNLOAD=0` disables downloading. System Node, PATH and the original Codex installation are preserved.
60
+ To remove the installation including npm:
61
+
62
+ ```text
63
+ ai-battery uninstall
64
+ ```
63
65
 
64
- Official npm references: [publish](https://docs.npmjs.com/cli/v11/commands/npm-publish/), [login](https://docs.npmjs.com/cli/v11/commands/npm-login/).
66
+ Modified or unrecognized files are preserved and listed. A running wrapped session retains its loaded code until it exits. Cleanup of one npm prefix does not uninstall another Windows/WSL or Node-version installation.
package/lib/cli.js CHANGED
@@ -15,6 +15,8 @@ import { quoteWindowsCommandLineArg, rowptyExePath } from "./platforms/windows/c
15
15
  import { isWsl } from "./platforms/runtime.js";
16
16
  import { createProcessScanner } from "./platforms/process-scanner.js";
17
17
  import { createWindowsPathIntegration } from "./platforms/windows/path-integration.js";
18
+ import { cleanupBatteryArtifacts, isBatteryConfig, planPackageRemoval, removeInstalledPackage } from "./core/uninstall.js";
19
+ import { createIntegrationFiles } from "./core/integration-files.js";
18
20
  import {
19
21
  cacheAgeSeconds,
20
22
  clamp,
@@ -108,6 +110,8 @@ function parseArgs(argv) {
108
110
  hudState: false,
109
111
  silent: false,
110
112
  force: false,
113
+ wrapCodex: false,
114
+ configureCodexStatusLine: false,
111
115
  attachHud: false,
112
116
  header: true,
113
117
  usageRow: "auto",
@@ -148,6 +152,10 @@ function parseArgs(argv) {
148
152
  args.usageRow = false;
149
153
  } else if (arg === "--force") {
150
154
  args.force = true;
155
+ } else if (arg === "--wrap-codex") {
156
+ args.wrapCodex = true;
157
+ } else if (arg === "--configure-codex-statusline") {
158
+ args.configureCodexStatusLine = true;
151
159
  } else if (arg === "--attach-hud") {
152
160
  args.attachHud = true;
153
161
  } else if (arg === "--watch" || arg === "-w") {
@@ -205,8 +213,9 @@ function printHelp() {
205
213
 
206
214
  Usage:
207
215
  ai-battery [options]
208
- ai-battery setup [codex|claude] [--force]
209
- ai-battery uninstall [codex|claude|hud|all]
216
+ ai-battery setup [codex|claude] [--force] [--wrap-codex]
217
+ ai-battery uninstall [codex|claude|hud|tmux|all]
218
+ ai-battery teardown [codex|claude|hud|tmux|all]
210
219
  ai-battery doctor
211
220
  ai-battery hud [start|stop|status] [hud options]
212
221
  ai-battery hud autostart on|off|status
@@ -216,6 +225,10 @@ Usage:
216
225
  Aliases:
217
226
  claudex-battery
218
227
 
228
+ Setup leaves Codex's command, PATH and configuration unchanged by default.
229
+ Uninstall without targets restores integrations and removes its npm package.
230
+ Teardown and targeted uninstall retain the package.
231
+
219
232
  Options:
220
233
  -p, --provider all|codex|claude Provider to show (default: all)
221
234
  --json Print machine-readable JSON
@@ -232,6 +245,8 @@ Options:
232
245
  --menu-bar Print compact macOS menu bar text
233
246
  --tmux Emit tmux status-line color markup
234
247
  --force Replace an existing Claude statusLine
248
+ --wrap-codex Explicitly opt into intercepting codex on PATH
249
+ --configure-codex-statusline Explicitly configure Codex's own status line
235
250
  --no-color Disable ANSI colors
236
251
  -v, --version Show ai-battery version
237
252
  -h, --help Show this help
@@ -388,6 +403,9 @@ function readConfig(options = {}) {
388
403
  if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
389
404
  throw new Error(`AI Battery config is invalid and was left untouched: ${target}`);
390
405
  }
406
+ if (!isBatteryConfig(parsed)) {
407
+ throw new Error(`AI Battery config ownership could not be verified; file was left untouched: ${target}`);
408
+ }
391
409
  if (parsed.providers !== undefined
392
410
  && (!parsed.providers || typeof parsed.providers !== "object" || Array.isArray(parsed.providers))) {
393
411
  throw new Error(`AI Battery config providers must be a JSON object: ${target}`);
@@ -409,6 +427,8 @@ function writeConfig(config) {
409
427
  writeJsonAtomic(configPath(), config);
410
428
  }
411
429
 
430
+ const { installManagedText, removeManagedText, stripOwnedBlock } = createIntegrationFiles({ readConfig, writeConfig, writeTextAtomic });
431
+
412
432
  function providerVisible(provider) {
413
433
  const config = readConfig();
414
434
  return config.providers?.[provider] !== false;
@@ -975,13 +995,13 @@ function installTmuxStatus() {
975
995
  try {
976
996
  existing = fs.readFileSync(confPath, "utf8");
977
997
  } catch {}
978
- const withoutBlock = removeAiBatteryTmuxBlock(existing);
998
+ const withoutBlock = stripOwnedBlock(confPath, existing, removeAiBatteryTmuxBlock);
979
999
  const existingStatusRight = extractExistingStatusRight(withoutBlock);
980
1000
  const next = `${withoutBlock}${tmuxStatusBlock(existingStatusRight)}`;
981
1001
  if (next === existing) {
982
1002
  return { ok: true, confPath, changed: false };
983
1003
  }
984
- fs.writeFileSync(confPath, next, "utf8");
1004
+ installManagedText(confPath, next, next.slice(withoutBlock.length));
985
1005
  return {
986
1006
  ok: true,
987
1007
  confPath,
@@ -994,16 +1014,10 @@ function installTmuxStatus() {
994
1014
  function uninstallTmuxStatus() {
995
1015
  if (process.platform === "win32") return { skipped: true };
996
1016
  const confPath = tmuxConfPath();
997
- let existing;
998
- try {
999
- existing = fs.readFileSync(confPath, "utf8");
1000
- } catch {
1001
- return { changed: false, confPath };
1002
- }
1003
- const next = removeAiBatteryTmuxBlock(existing);
1004
- if (next === existing) return { changed: false, confPath };
1005
- fs.writeFileSync(confPath, next, "utf8");
1006
- return { changed: true, confPath };
1017
+ const records = readConfig({ strict: true }).integrationFiles || {};
1018
+ const paths = uniquePaths([confPath, ...Object.keys(records).filter(file => records[file]?.block?.includes("# >>> ai-battery tmux >>>"))]);
1019
+ const changedPaths = paths.filter(file => removeManagedText(file, removeAiBatteryTmuxBlock));
1020
+ return { changed: changedPaths.length > 0, confPath, changedPaths };
1007
1021
  }
1008
1022
 
1009
1023
  function removeAiBatteryShellPathBlock(text) {
@@ -1043,13 +1057,10 @@ function removeShellPathBlocks(extraShimDirs = [], options = {}) {
1043
1057
  }
1044
1058
 
1045
1059
  const changed = [];
1046
- for (const rcPath of shellRcCandidates()) {
1047
- if (!fs.existsSync(rcPath)) continue;
1048
- const existing = fs.readFileSync(rcPath, "utf8");
1049
- const next = removeAiBatteryShellPathBlock(existing);
1050
- if (next === existing) continue;
1051
- fs.writeFileSync(rcPath, next, "utf8");
1052
- changed.push(rcPath);
1060
+ const records = readConfig({ strict: true }).integrationFiles || {};
1061
+ const paths = uniquePaths([...shellRcCandidates(), ...Object.keys(records).filter(file => records[file]?.block?.includes("# >>> ai-battery setup >>>"))]);
1062
+ for (const rcPath of paths) {
1063
+ if (removeManagedText(rcPath, removeAiBatteryShellPathBlock)) changed.push(rcPath);
1053
1064
  }
1054
1065
  return changed;
1055
1066
  }
@@ -1082,10 +1093,10 @@ function ensureShimPath(shimDir, originalCommand) {
1082
1093
  const rcPath = shellRcPath();
1083
1094
  fs.mkdirSync(path.dirname(rcPath), { recursive: true });
1084
1095
  const existing = fs.existsSync(rcPath) ? fs.readFileSync(rcPath, "utf8") : "";
1085
- const withoutAiBatteryBlock = removeAiBatteryShellPathBlock(existing);
1096
+ const withoutAiBatteryBlock = stripOwnedBlock(rcPath, existing, removeAiBatteryShellPathBlock);
1086
1097
  const separator = withoutAiBatteryBlock && !withoutAiBatteryBlock.endsWith("\n") ? "\n" : "";
1087
1098
  const next = `${withoutAiBatteryBlock}${separator}${shellPathBlock(shimDir)}`;
1088
- fs.writeFileSync(rcPath, next, "utf8");
1099
+ installManagedText(rcPath, next, next.slice(withoutAiBatteryBlock.length));
1089
1100
 
1090
1101
  return {
1091
1102
  changed: true,
@@ -1676,6 +1687,7 @@ function uninstallCodexWrapper() {
1676
1687
  candidates.map((wrapperPath) => path.dirname(wrapperPath)),
1677
1688
  { windowsOwnedShimDirs }
1678
1689
  );
1690
+ config.integrationFiles = readConfig({ strict: true }).integrationFiles;
1679
1691
  if (clearedWrapperConfig) {
1680
1692
  config.codexWrapper = null;
1681
1693
  }
@@ -1752,6 +1764,7 @@ function installCodexWrapper(args) {
1752
1764
  }
1753
1765
 
1754
1766
  const pathResult = ensureShimPath(shimDir, originalPathForPath || originalCommand);
1767
+ config.integrationFiles = readConfig({ strict: true }).integrationFiles;
1755
1768
  const previousOwnedPath = config.codexWrapper?.pathAddedByAiBattery;
1756
1769
  config.codexWrapper = {
1757
1770
  wrapperPath,
@@ -1826,7 +1839,9 @@ function windowsOwnedShimDirsForUninstall(config) {
1826
1839
  ? path.dirname(config.codexWrapper.wrapperPath)
1827
1840
  : null;
1828
1841
  const explicitlyAdded = config.codexWrapper?.pathAddedByAiBattery;
1829
- if (explicitlyAdded) return [explicitlyAdded];
1842
+ if (config.codexWrapper && Object.hasOwn(config.codexWrapper, "pathAddedByAiBattery")) {
1843
+ return explicitlyAdded ? [explicitlyAdded] : [];
1844
+ }
1830
1845
  if (configuredShimDir && samePath(configuredShimDir, defaultCodexShimDir())) {
1831
1846
  return [configuredShimDir];
1832
1847
  }
@@ -2192,16 +2207,20 @@ function installRowPtyHost() {
2192
2207
  function uninstallRowPtyHost() {
2193
2208
  if (process.platform !== "win32") return { skipped: true };
2194
2209
  const binDir = path.join(dataDir(), "bin");
2210
+ try {
2211
+ if (fs.lstatSync(binDir).isSymbolicLink()) throw new Error(`Refusing to clean a symlinked runtime directory: ${binDir}`);
2212
+ } catch (error) { if (error.code !== "ENOENT") throw error; }
2195
2213
  sweepParkedRowPtyFiles(binDir);
2196
2214
  const removed = [];
2215
+ const errors = [];
2197
2216
  for (const name of ["rowpty.exe", "conpty.dll", "OpenConsole.exe", "rowpty.src.sha256"]) {
2198
2217
  const target = path.join(binDir, name);
2199
2218
  try {
2200
2219
  fs.unlinkSync(target);
2201
2220
  removed.push(name);
2202
- } catch {}
2221
+ } catch (error) { if (error.code !== "ENOENT") errors.push({ path: target, error: error.message }); }
2203
2222
  }
2204
- return { removed };
2223
+ return { removed, errors };
2205
2224
  }
2206
2225
 
2207
2226
  function setupTargets(targets) {
@@ -2237,12 +2256,24 @@ function runSetup(args) {
2237
2256
  results.tmux = installTmuxStatus();
2238
2257
  }
2239
2258
  if (targets.includes("codex")) {
2240
- const statusLine = installCodexStatusLine(args);
2241
- results.codex = {
2242
- ...installCodexWrapper(args),
2243
- statusLine
2244
- };
2245
- if (process.platform === "win32") {
2259
+ const statusLine = args.wrapCodex && args.configureCodexStatusLine ? installCodexStatusLine(args) : null;
2260
+ if (args.wrapCodex) {
2261
+ results.codex = { ...installCodexWrapper(args), statusLine };
2262
+ } else {
2263
+ const legacyCleanup = uninstallCodexWrapper();
2264
+ const failed = teardownResultFailed({ results: { codex: legacyCleanup } });
2265
+ results.codex = {
2266
+ ok: !failed,
2267
+ standalone: !failed,
2268
+ skipped: failed,
2269
+ legacyCleanup,
2270
+ reason: failed ? "Could not safely detach the legacy Codex integration; kept recovery metadata. Run ai-battery teardown codex for details."
2271
+ : "Codex command and configuration are left under Codex's control. Use ai-battery hud or ai-battery-run -- codex for usage display."
2272
+ };
2273
+ // An explicit status-line request is applied after legacy restoration.
2274
+ if (args.configureCodexStatusLine && !failed) results.codex.statusLine = installCodexStatusLine(args);
2275
+ }
2276
+ if (process.platform === "win32" && args.wrapCodex) {
2246
2277
  results.codex.rowpty = windowsSetupNeedsRowPty()
2247
2278
  ? (windowsClaudeLauncher || installRowPtyHost())
2248
2279
  : {
@@ -2297,7 +2328,7 @@ function runHudCommand(args) {
2297
2328
  return childResult(spawnSync(process.execPath, [hudPath, ...args], {
2298
2329
  encoding: "utf8",
2299
2330
  stdio: ["ignore", "pipe", "pipe"],
2300
- timeout: 5000,
2331
+ timeout: 15000,
2301
2332
  windowsHide: true
2302
2333
  }));
2303
2334
  }
@@ -2311,8 +2342,8 @@ function uninstallHud() {
2311
2342
  };
2312
2343
  }
2313
2344
 
2314
- const autostart = runHudCommand(["autostart", "off"]);
2315
2345
  const stop = runHudCommand(["stop"]);
2346
+ const autostart = runHudCommand(["autostart", "off"]);
2316
2347
  return {
2317
2348
  changed: autostart.ok || stop.ok,
2318
2349
  autostart,
@@ -2340,7 +2371,6 @@ function runTeardown(args) {
2340
2371
  }
2341
2372
  if (targets.includes("codex")) {
2342
2373
  runStep("codex", uninstallCodexWrapper);
2343
- runStep("rowpty", uninstallRowPtyHost);
2344
2374
  }
2345
2375
  if (targets.includes("tmux")) {
2346
2376
  runStep("tmux", uninstallTmuxStatus);
@@ -2348,8 +2378,31 @@ function runTeardown(args) {
2348
2378
  if (targets.includes("hud")) {
2349
2379
  runStep("hud", uninstallHud);
2350
2380
  }
2381
+ if (targets.includes("codex")) runStep("rowpty", uninstallRowPtyHost);
2382
+ const fullUninstall = args.command === "uninstall" && (!args.targets.length || args.targets.includes("all"));
2383
+ if (fullUninstall && !teardownResultFailed({ results })) {
2384
+ const pending = Object.keys(readConfig({ strict: true }).integrationFiles || {});
2385
+ if (pending.length) {
2386
+ results.recovery = { error: "Unrestored integration files remain; kept recovery metadata and npm package", paths: pending };
2387
+ return { targets, fullUninstall, results };
2388
+ }
2389
+ const plan = planPackageRemoval(path.resolve(scriptDir(), ".."));
2390
+ if (plan.error) {
2391
+ results.package = plan;
2392
+ } else {
2393
+ const roots = [stateDir(), dataDir(), path.join(os.tmpdir(), "ai-battery")];
2394
+ if (process.platform === "win32" && process.env.LOCALAPPDATA) roots.push(path.join(process.env.LOCALAPPDATA, "ai-battery"));
2395
+ results.artifacts = cleanupBatteryArtifacts({
2396
+ roots,
2397
+ home: userHome(),
2398
+ protectedRoots: [codexRuntimeHome(), homePath(".claude"), path.resolve(scriptDir(), "..")]
2399
+ });
2400
+ if (!results.artifacts.errors.length) results.package = removeInstalledPackage(plan, { home: userHome() });
2401
+ }
2402
+ }
2351
2403
  return {
2352
2404
  targets,
2405
+ fullUninstall,
2353
2406
  results
2354
2407
  };
2355
2408
  }
@@ -2570,6 +2623,7 @@ function readJson(filePath) {
2570
2623
  function teardownResultFailed(result) {
2571
2624
  return Object.values(result.results || {}).some((item) => Boolean(
2572
2625
  item?.error
2626
+ || item?.errors?.length
2573
2627
  || item?.retainedConfig
2574
2628
  || item?.retainedBackup
2575
2629
  || item?.skippedWrappers?.length
@@ -4974,6 +5028,25 @@ function printTeardownResult(result) {
4974
5028
  if (runningInsideAiBatteryCodexWrapper()) {
4975
5029
  console.log("Current Codex session was already started through AI Battery; exit this session to remove the terminal row.");
4976
5030
  }
5031
+ const artifacts = result.results.artifacts;
5032
+ for (const [name, item] of Object.entries(result.results)) {
5033
+ if (["codex", "claude", "hud", "artifacts", "package"].includes(name)) continue;
5034
+ if (item.error) console.log(`${name} cleanup error: ${item.error}`);
5035
+ for (const error of item.errors || []) console.log(`${name} cleanup error: ${error.path}: ${error.error}`);
5036
+ for (const file of item.paths || []) console.log(`Recovery pending: ${file}`);
5037
+ }
5038
+ if (artifacts) {
5039
+ for (const file of artifacts.removed) console.log(`Removed AI Battery artifact: ${file}`);
5040
+ for (const file of artifacts.retained) console.log(`Preserved unrecognized or user-owned file: ${file}`);
5041
+ for (const item of artifacts.errors) console.log(`Cleanup error: ${item.path}: ${item.error}`);
5042
+ }
5043
+ const pkg = result.results.package;
5044
+ if (pkg?.removed) console.log(`Removed ai-battery npm package from ${pkg.prefix}`);
5045
+ else if (pkg?.error) console.log(`Package uninstall failed: ${pkg.error}`);
5046
+ else if (pkg?.skipped) console.log(`Package: ${pkg.reason}`);
5047
+ if (result.targets.includes("codex") && process.platform !== "win32") {
5048
+ console.log("In this existing Bash terminal, run: hash -r (zsh: rehash). A child process cannot clear its parent shell's cached command paths.");
5049
+ }
4977
5050
  }
4978
5051
 
4979
5052
  async function main() {
@@ -5003,7 +5076,12 @@ async function main() {
5003
5076
  }
5004
5077
  }
5005
5078
  }
5006
- if (result.codex?.ok) {
5079
+ if (result.codex?.standalone) {
5080
+ console.log(result.codex.reason);
5081
+ if (result.codex.legacyCleanup.changed) {
5082
+ console.log("Removed legacy Codex integration. In this existing Bash terminal run: hash -r (zsh: rehash).");
5083
+ }
5084
+ } else if (result.codex?.ok) {
5007
5085
  console.log(`Codex wrapper installed: ${result.codex.wrapperPath}`);
5008
5086
  console.log(`Original codex: ${result.codex.originalCommand}`);
5009
5087
  if (result.codex.path?.note) console.log(result.codex.path.note);
@@ -5044,7 +5122,7 @@ async function main() {
5044
5122
  if (result.codex?.retainedConfig) {
5045
5123
  console.log("Kept the Codex recovery record because the configured wrapper could not be safely removed.");
5046
5124
  }
5047
- if (process.platform === "win32" && result.codex) {
5125
+ if (process.platform === "win32" && result.codex && !result.codex.standalone) {
5048
5126
  console.log("Windows terminal note: Codex uses fullscreen PTY composition by default, with a private VT-capable Node runtime when needed and a native HUD fallback. Open a new cmd/PowerShell after setup.");
5049
5127
  }
5050
5128
  console.log("To remove AI Battery cleanly later, run: ai-battery uninstall");
@@ -0,0 +1,75 @@
1
+ import fs from "node:fs";
2
+
3
+ export function createIntegrationFiles({ readConfig, writeConfig, writeTextAtomic }) {
4
+ const key = file => file;
5
+ const recordFor = file => readConfig({ strict: true }).integrationFiles?.[key(file)];
6
+ const read = file => {
7
+ try { return fs.readFileSync(file, "utf8"); } catch (error) { if (error.code === "ENOENT") return null; throw error; }
8
+ };
9
+ function checkTarget(file, record) {
10
+ let stat;
11
+ try { stat = fs.lstatSync(file); } catch (error) { if (error.code === "ENOENT") return; throw error; }
12
+ if ((record?.target && fs.realpathSync(file) !== record.target) || (!record?.target && stat.isSymbolicLink())) {
13
+ throw new Error(`Integration symlink target changed; left untouched: ${file}`);
14
+ }
15
+ }
16
+ function stripRecorded(text, record, file) {
17
+ if (text === record.beforeText) return text;
18
+ const index = text.indexOf(record.block);
19
+ if (index < 0) throw new Error(`AI Battery integration block was edited; kept the file and recovery record: ${file}`);
20
+ const before = text.slice(0, index);
21
+ const after = text.slice(index + record.block.length);
22
+ const separator = before && after && !before.endsWith("\n") && !after.startsWith("\n") ? "\n" : "";
23
+ return before + separator + after;
24
+ }
25
+ function stripOwnedBlock(file, text, fallback) {
26
+ const record = recordFor(file);
27
+ if (!record) return fallback(text);
28
+ checkTarget(file, record);
29
+ return stripRecorded(text, record, file);
30
+ }
31
+ function installManagedText(file, next, block) {
32
+ const config = readConfig({ strict: true });
33
+ const previous = config.integrationFiles?.[key(file)];
34
+ if (previous) checkTarget(file, previous);
35
+ const current = read(file);
36
+ if (previous && current !== null) {
37
+ checkTarget(file, previous);
38
+ stripRecorded(current, previous, file);
39
+ }
40
+ if (!block) throw new Error(`Cannot record an empty integration block: ${file}`);
41
+ const mode = current === null ? 0o600 : fs.statSync(file).mode & 0o777;
42
+ const record = {
43
+ beforeText: previous && current !== null
44
+ ? current === previous.installedText ? previous.beforeText : stripRecorded(current, previous, file)
45
+ : current,
46
+ target: previous?.target || (current === null ? null : fs.realpathSync(file)),
47
+ installedText: next,
48
+ block
49
+ };
50
+ config.integrationFiles = { ...config.integrationFiles, [key(file)]: record };
51
+ writeConfig(config);
52
+ writeTextAtomic(file, next, mode);
53
+ }
54
+ function removeManagedText(file, fallback) {
55
+ const config = readConfig({ strict: true });
56
+ const record = config.integrationFiles?.[key(file)];
57
+ if (record) checkTarget(file, record);
58
+ const current = read(file);
59
+ if (current === null) {
60
+ if (record) { delete config.integrationFiles[key(file)]; writeConfig(config); }
61
+ return false;
62
+ }
63
+ const next = record
64
+ ? current === record.installedText ? record.beforeText : stripRecorded(current, record, file)
65
+ : fallback(current);
66
+ const changed = next !== current;
67
+ if (changed) {
68
+ if (next === null) fs.unlinkSync(file);
69
+ else writeTextAtomic(file, next, fs.statSync(file).mode & 0o777);
70
+ }
71
+ if (record) { delete config.integrationFiles[key(file)]; writeConfig(config); }
72
+ return changed;
73
+ }
74
+ return { installManagedText, removeManagedText, stripOwnedBlock };
75
+ }
@@ -0,0 +1,145 @@
1
+ import fs from "node:fs";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+ import { spawnSync } from "node:child_process";
5
+
6
+ const ALIASES = ["ai-battery", "ai-battery-hud", "ai-battery-run", "ai-battery-run-win", "claudex-battery", "claudex-battery-hud", "claudex-battery-run"];
7
+ const STATE_FILES = /^(?:(?:codex-status|windows-processes|wsl-windows-processes|claude-rate-limit-hit)-scan-cache\.json|claude-statusline\.json|codex-account-usage\.json|windows-state-dir|hud-position\.json|hud-snapshot-[\w-]+\.json|(?:tui|hud)-dock-(?:request|host)(?:-\d+)?\.json|macos-menu-(?:bar|detail)\.svg|codex-menu-bar-transparent\.png)(?:\.\d+(?:\.\d+)?(?:\.[a-z0-9]+)?\.tmp)?$/;
8
+ const HUD_FILES = new Set(["main.ps1", "controls.ps1", "dock.ps1", "native.ps1", "rendering.ps1", "snapshot.ps1", "windowing.ps1", "ai-battery-hud.ps1"]);
9
+
10
+ function lstat(file) {
11
+ try { return fs.lstatSync(file); } catch (error) { if (error.code === "ENOENT") return null; throw error; }
12
+ }
13
+
14
+ function readJson(file) {
15
+ try { return JSON.parse(fs.readFileSync(file, "utf8").replace(/^\uFEFF/, "")); } catch { return null; }
16
+ }
17
+
18
+ export function isBatteryConfig(value) {
19
+ return Boolean(value && !Array.isArray(value) && value.version === 1
20
+ && ["providers", "codexWrapper", "codexStatusLineBackup", "claudeStatusLineBackup"].some(key => Object.hasOwn(value, key)));
21
+ }
22
+
23
+ function inside(file, root) {
24
+ const relative = path.relative(path.resolve(root), path.resolve(file));
25
+ return relative === "" || (!relative.startsWith(`..${path.sep}`) && relative !== ".." && !path.isAbsolute(relative));
26
+ }
27
+
28
+ export function cleanupBatteryArtifacts({ roots, home = os.homedir(), protectedRoots = [] }) {
29
+ const result = { removed: [], retained: [], errors: [] };
30
+ const protectedPaths = [home, path.parse(home).root, ...protectedRoots].map(file => {
31
+ try { return fs.realpathSync(file); } catch { return path.resolve(file); }
32
+ });
33
+ const removeFile = file => {
34
+ const stat = lstat(file);
35
+ if (!stat) return;
36
+ if (!stat.isFile() || stat.isSymbolicLink()) { result.retained.push(file); return; }
37
+ fs.unlinkSync(file);
38
+ result.removed.push(file);
39
+ };
40
+ const prune = directory => {
41
+ if (!fs.readdirSync(directory).length) { fs.rmdirSync(directory); result.removed.push(directory); }
42
+ };
43
+ const visit = (directory, kind) => {
44
+ for (const entry of fs.readdirSync(directory, { withFileTypes: true })) {
45
+ const file = path.join(directory, entry.name);
46
+ if (entry.isSymbolicLink()) { result.retained.push(file); continue; }
47
+ if (entry.isDirectory()) {
48
+ const childKind = kind === "root" && ["bin", "hud", "runtimes", "claude-statusline-sessions", "claude-hud-sessions"].includes(entry.name)
49
+ ? entry.name
50
+ : kind === "runtimes" && /^(?:node-v\d+\.\d+\.\d+-win-(?:x64|arm64)|\.node-download-[\w-]+)$/.test(entry.name) ? "runtime" : null;
51
+ if (childKind) { visit(file, childKind); prune(file); }
52
+ else result.retained.push(file);
53
+ continue;
54
+ }
55
+ let owned = kind === "root" && STATE_FILES.test(entry.name);
56
+ if (kind === "root" && entry.name === "config.json") {
57
+ const config = readJson(file);
58
+ owned = isBatteryConfig(config) && !config.codexWrapper && !config.codexStatusLineBackup && !config.claudeStatusLineBackup && !Object.keys(config.integrationFiles || {}).length;
59
+ }
60
+ if (["claude-statusline-sessions", "claude-hud-sessions"].includes(kind)) {
61
+ owned = /^[\w-]+\.json(?:\.\d+\.tmp)?$/.test(entry.name)
62
+ && (entry.name.endsWith(".tmp") || readJson(file)?.provider === "claude" || kind === "claude-hud-sessions");
63
+ }
64
+ if (kind === "bin") owned = /^(?:rowpty\.exe|conpty\.dll|OpenConsole\.exe|rowpty\.src\.sha256)(?:\.old-[\w.-]+)?$/.test(entry.name);
65
+ if (kind === "hud") owned = HUD_FILES.has(entry.name);
66
+ if (kind === "runtimes") owned = /^\.node-\d+\.\d+\.\d+-(?:x64|arm64)\.lock$/.test(entry.name);
67
+ if (kind === "runtime") owned = /^(?:node\.exe|extract\.ps1|SHASUMS256\.txt|node-v\d+\.\d+\.\d+-win-(?:x64|arm64)\.zip)$/.test(entry.name);
68
+ if (owned) removeFile(file);
69
+ else result.retained.push(file);
70
+ }
71
+ };
72
+ for (const root of [...new Set(roots.filter(Boolean).map(file => path.resolve(file)))]) {
73
+ try {
74
+ const stat = lstat(root);
75
+ if (!stat) continue;
76
+ const resolved = fs.realpathSync(root);
77
+ if (!stat.isDirectory() || stat.isSymbolicLink()
78
+ || protectedPaths.some(file => inside(file, resolved) || (file !== path.resolve(home) && file !== path.parse(home).root && inside(resolved, file)))) {
79
+ result.errors.push({ path: root, error: "Refusing to clean a shared, protected, or symlinked directory" });
80
+ continue;
81
+ }
82
+ visit(root, "root");
83
+ prune(root);
84
+ } catch (error) { result.errors.push({ path: root, error: error.message }); }
85
+ }
86
+ return result;
87
+ }
88
+
89
+ export function removeBatteryAliases({ packageRoot, packageJson, home = os.homedir() }) {
90
+ const removed = [];
91
+ for (const name of ALIASES) {
92
+ const target = packageJson.bin?.[name];
93
+ if (!target) continue;
94
+ const alias = path.join(home, ".local", "bin", name);
95
+ if (!lstat(alias)?.isSymbolicLink()) continue;
96
+ const resolved = path.resolve(path.dirname(alias), fs.readlinkSync(alias));
97
+ if (resolved !== path.resolve(packageRoot, target)) continue;
98
+ fs.unlinkSync(alias);
99
+ removed.push(alias);
100
+ }
101
+ return removed;
102
+ }
103
+
104
+ export function planPackageRemoval(packageRoot, { node = process.execPath } = {}) {
105
+ const root = path.resolve(packageRoot);
106
+ const packageJson = readJson(path.join(root, "package.json"));
107
+ if (packageJson?.name !== "ai-battery" || !packageJson.bin || typeof packageJson.bin !== "object"
108
+ || Object.entries(packageJson.bin).some(([name, target]) => !ALIASES.includes(name)
109
+ || typeof target !== "string" || path.isAbsolute(target) || !inside(path.resolve(root, target), root))) {
110
+ return { error: "Package identity or command ownership could not be verified" };
111
+ }
112
+ if (path.basename(path.dirname(root)) !== "node_modules" || /[\\/]_npx[\\/]/.test(root)) {
113
+ return { skipped: true, reason: "Development checkout or temporary npx installation; no npm project was changed" };
114
+ }
115
+ const modules = path.dirname(root);
116
+ const parent = path.dirname(modules);
117
+ const localProject = readJson(path.join(parent, "package.json"));
118
+ const declaredLocal = [localProject?.dependencies, localProject?.devDependencies, localProject?.optionalDependencies]
119
+ .some(deps => Object.hasOwn(deps || {}, "ai-battery"));
120
+ const global = !declaredLocal && !fs.existsSync(path.join(parent, "package.json"));
121
+ const prefix = global && process.platform !== "win32" && path.basename(parent) === "lib" ? path.dirname(parent) : parent;
122
+ const candidates = [
123
+ path.join(modules, "npm", "bin", "npm-cli.js"),
124
+ path.join(path.dirname(node), "node_modules", "npm", "bin", "npm-cli.js"),
125
+ path.resolve(path.dirname(node), "../lib/node_modules/npm/bin/npm-cli.js")
126
+ ];
127
+ const npm = candidates.find(file => lstat(file)?.isFile());
128
+ if (!npm) return { error: "Could not locate npm for the installed package; package was left intact" };
129
+ if (!global) {
130
+ const project = readJson(path.join(prefix, "package.json"));
131
+ if (![project?.dependencies, project?.devDependencies, project?.optionalDependencies].some(deps => Object.hasOwn(deps || {}, "ai-battery"))) {
132
+ return { error: "The parent npm project does not declare ai-battery; refusing to change it" };
133
+ }
134
+ }
135
+ return { node, npm, prefix, packageRoot: root, packageJson, global, args: ["uninstall", ...(global ? ["--global"] : []), "--prefix", prefix, "ai-battery", "--ignore-scripts", "--no-audit", "--no-fund"] };
136
+ }
137
+
138
+ export function removeInstalledPackage(plan, { home = os.homedir(), run = spawnSync } = {}) {
139
+ if (plan.error || plan.skipped) return plan;
140
+ const result = run(plan.node, [plan.npm, ...plan.args], { encoding: "utf8", windowsHide: true, stdio: ["ignore", "pipe", "pipe"], timeout: 120000 });
141
+ if (result.status !== 0 || result.error || lstat(plan.packageRoot)) {
142
+ return { error: result.error?.message || result.stderr?.trim() || "npm did not remove the installed package", prefix: plan.prefix };
143
+ }
144
+ return { removed: true, prefix: plan.prefix, global: plan.global, aliases: removeBatteryAliases({ ...plan, home }) };
145
+ }
@@ -7,7 +7,8 @@ function sleepSync(ms) {
7
7
  Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
8
8
  }
9
9
 
10
- export function createMacHudPlatform({ macStatusPath, relevantEnvPrefix, scriptDir, shellQuote }) {
10
+ export function createMacHudPlatform({ macStatusPath, relevantEnvPrefix, scriptDir, shellQuote,
11
+ home = os.homedir(), runLaunchctl = args => spawnSync("launchctl", args, { stdio: "ignore" }) }) {
11
12
  function parseMacHudArgs(cliArgs) {
12
13
  const options = {
13
14
  foreground: false,
@@ -106,7 +107,7 @@ function macHudPidsFromPsOutput(output, ownPid = process.pid) {
106
107
  }
107
108
 
108
109
  function macLaunchAgentPath() {
109
- return path.join(os.homedir(), "Library", "LaunchAgents", "com.ai-battery.hud.plist");
110
+ return path.join(home, "Library", "LaunchAgents", "com.ai-battery.hud.plist");
110
111
  }
111
112
 
112
113
  function macLaunchctlDomain() {
@@ -126,7 +127,7 @@ function plistString(value) {
126
127
  }
127
128
 
128
129
  function macAutostartPlist(options) {
129
- const args = [process.execPath, scriptPath, "start", "--interval", String(options.interval)];
130
+ const args = [process.execPath, path.join(scriptDir, "ai-battery-hud.js"), "start", "--interval", String(options.interval)];
130
131
  if (options.provider !== "all") args.push("--provider", options.provider);
131
132
  return `<?xml version="1.0" encoding="UTF-8"?>
132
133
  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
@@ -150,17 +151,32 @@ function macAutostartStatus() {
150
151
  return { enabled: fs.existsSync(filePath), filePath };
151
152
  }
152
153
 
154
+ function verifyMacAutostartOwnership(filePath) {
155
+ let stat;
156
+ try { stat = fs.lstatSync(filePath); } catch (error) { if (error.code === "ENOENT") return false; throw error; }
157
+ const text = stat.isFile() && !stat.isSymbolicLink() ? fs.readFileSync(filePath, "utf8") : "";
158
+ const args = text.match(/<key>ProgramArguments<\/key>\s*<array>([\s\S]*?)<\/array>/)?.[1];
159
+ const values = [...(args || "").matchAll(/<string>([^<]*)<\/string>/g)].map(match => match[1]);
160
+ if (!/<key>Label<\/key>\s*<string>com\.ai-battery\.hud<\/string>/.test(text)
161
+ || !/[\\/]ai-battery-hud\.js$/.test(values[1] || "") || values[2] !== "start") {
162
+ throw new Error(`LaunchAgent ownership could not be verified; left untouched: ${filePath}`);
163
+ }
164
+ return true;
165
+ }
166
+
153
167
  function macAutostartEnable(options) {
154
168
  const filePath = macLaunchAgentPath();
169
+ verifyMacAutostartOwnership(filePath);
155
170
  fs.mkdirSync(path.dirname(filePath), { recursive: true });
156
171
  fs.writeFileSync(filePath, macAutostartPlist(options), "utf8");
157
- spawnSync("launchctl", ["bootstrap", macLaunchctlDomain(), filePath], { stdio: "ignore" });
172
+ runLaunchctl(["bootstrap", macLaunchctlDomain(), filePath]);
158
173
  return filePath;
159
174
  }
160
175
 
161
176
  function macAutostartDisable() {
162
177
  const filePath = macLaunchAgentPath();
163
- spawnSync("launchctl", ["bootout", macLaunchctlDomain(), filePath], { stdio: "ignore" });
178
+ if (!verifyMacAutostartOwnership(filePath)) return filePath;
179
+ runLaunchctl(["bootout", macLaunchctlDomain(), filePath]);
164
180
  fs.rmSync(filePath, { force: true });
165
181
  return filePath;
166
182
  }
@@ -244,6 +260,8 @@ function runMacHud(cliArgs) {
244
260
  return {
245
261
  macHudCommandMatches,
246
262
  macHudPidsFromPsOutput,
263
+ macAutostartEnable,
264
+ macAutostartDisable,
247
265
  runMacHud
248
266
  };
249
267
  }
@@ -0,0 +1,35 @@
1
+ const quote = value => `'${String(value).replace(/'/g, "''")}'`;
2
+
3
+ // Parameters let the Windows regression test use its own temporary registry key.
4
+ export function windowsAutostartCleanupScript({ registryPath, registryName }) {
5
+ return [
6
+ "$ErrorActionPreference = 'Stop'",
7
+ "$dir = Join-Path $env:LOCALAPPDATA 'ai-battery'",
8
+ "$auto = Join-Path $dir 'autostart.ps1'",
9
+ "$hudDir = Join-Path $dir 'hud'",
10
+ "foreach ($p in @($dir, $auto, $hudDir)) { if ((Test-Path -LiteralPath $p) -and ((Get-Item -Force -LiteralPath $p).Attributes -band [IO.FileAttributes]::ReparsePoint)) { throw ('Refusing to follow an autostart symlink: ' + $p) } }",
11
+ `$v = (Get-ItemProperty -Path ${quote(registryPath)} -Name ${quote(registryName)} -ErrorAction SilentlyContinue).${registryName}`,
12
+ "$expected = 'powershell.exe -NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -File \"' + $auto + '\"'",
13
+ "if ($v -and $v -ne $expected) { throw 'AiBatteryHud registry value changed; left it untouched.' }",
14
+ "$ownedFile = $false",
15
+ "if (Test-Path -LiteralPath $auto) {",
16
+ " $ownedFile = (Get-Content -Raw -LiteralPath $auto).StartsWith('# Generated by: ai-battery hud autostart on')",
17
+ " if (-not $ownedFile) { throw 'Autostart file changed; left it and its registry value untouched.' }",
18
+ "}",
19
+ `if ($v) { Remove-ItemProperty -Path ${quote(registryPath)} -Name ${quote(registryName)} }`,
20
+ "if ($ownedFile) {",
21
+ " Remove-Item -LiteralPath $auto -Force",
22
+ " if (Test-Path -LiteralPath $hudDir) {",
23
+ " foreach ($name in @('main.ps1', 'controls.ps1', 'dock.ps1', 'native.ps1', 'rendering.ps1', 'snapshot.ps1', 'windowing.ps1', 'ai-battery-hud.ps1')) {",
24
+ " $file = Join-Path $hudDir $name",
25
+ " if (Test-Path -LiteralPath $file -PathType Leaf) {",
26
+ " if ((Get-Item -Force -LiteralPath $file).Attributes -band [IO.FileAttributes]::ReparsePoint) { continue }",
27
+ " Remove-Item -LiteralPath $file -Force",
28
+ " }",
29
+ " }",
30
+ " if (-not (Get-ChildItem -Force -LiteralPath $hudDir | Select-Object -First 1)) { Remove-Item -LiteralPath $hudDir }",
31
+ " }",
32
+ "}",
33
+ "if ((Test-Path -LiteralPath $dir) -and -not (Get-ChildItem -Force -LiteralPath $dir | Select-Object -First 1)) { Remove-Item -LiteralPath $dir }"
34
+ ].join("\n");
35
+ }
@@ -2,6 +2,7 @@ import { spawnSync } from "node:child_process";
2
2
  import fs from "node:fs";
3
3
  import os from "node:os";
4
4
  import path from "node:path";
5
+ import { windowsAutostartCleanupScript } from "./autostart-cleanup.js";
5
6
 
6
7
  export function createWindowsHudPlatform({
7
8
  buildStartProcessCommand,
@@ -748,20 +749,7 @@ function autostartEnable() {
748
749
  }
749
750
 
750
751
  function autostartDisable() {
751
- return runPowerShell([
752
- `$v = (Get-ItemProperty -Path '${AUTOSTART_REG_PATH}' -Name '${AUTOSTART_REG_NAME}' -ErrorAction SilentlyContinue).${AUTOSTART_REG_NAME}`,
753
- "$dir = Join-Path $env:LOCALAPPDATA 'ai-battery'",
754
- "$auto = Join-Path $dir 'autostart.ps1'",
755
- "$ownedFile = $false",
756
- "if (Test-Path -LiteralPath $auto) { $ownedFile = (Get-Content -Raw -LiteralPath $auto) -like '*Generated by: ai-battery hud autostart on*' }",
757
- "if ($v -and ($v -notlike '*ai-battery*autostart.ps1*')) { Write-Error 'AiBatteryHud registry value is not managed by AI Battery; left it untouched.'; exit 2 }",
758
- `Remove-ItemProperty -Path '${AUTOSTART_REG_PATH}' -Name '${AUTOSTART_REG_NAME}' -ErrorAction SilentlyContinue`,
759
- "if ($ownedFile) {",
760
- " Remove-Item -LiteralPath $auto -Force -ErrorAction SilentlyContinue",
761
- " $hudDir = Join-Path $dir 'hud'",
762
- " if ((Split-Path -Parent $hudDir) -eq $dir -and (Test-Path -LiteralPath $hudDir)) { Remove-Item -LiteralPath $hudDir -Recurse -Force -ErrorAction SilentlyContinue }",
763
- "}"
764
- ].join("\n"));
752
+ return runPowerShell(windowsAutostartCleanupScript({ registryPath: AUTOSTART_REG_PATH, registryName: AUTOSTART_REG_NAME }));
765
753
  }
766
754
 
767
755
  if (subcommand === "status") {
@@ -786,7 +774,12 @@ if (subcommand === "autostart") {
786
774
  console.log("Windows and WSL use the same Run entry; enabling from the other side replaces this launcher.");
787
775
  console.log("After updating ai-battery, run \"ai-battery hud autostart on\" again to refresh it.");
788
776
  } else if (autostartAction === "off") {
789
- autostartDisable();
777
+ const result = autostartDisable();
778
+ if (result.status !== 0 || result.error) {
779
+ console.error("ai-battery-hud: autostart cleanup failed; preserved files that could not be verified.");
780
+ if (result.stderr) console.error(result.stderr.trim());
781
+ process.exit(1);
782
+ }
790
783
  console.log("HUD autostart disabled.");
791
784
  } else {
792
785
  const auto = autostartStatus();
@@ -27,15 +27,15 @@ function windowsUserPathParts() {
27
27
  const result = runWindowsPowerShell("[Environment]::GetEnvironmentVariable('Path', 'User')");
28
28
  if (result.status !== 0) throw new Error("Could not read Windows user PATH; leaving it unchanged");
29
29
  const text = result.stdout;
30
- return String(text || "")
31
- .trim()
32
- .split(";")
33
- .map((entry) => entry.trim())
34
- .filter(Boolean);
30
+ // PowerShell adds one output line ending. Preserve every other PATH byte,
31
+ // including whitespace, empty entries and trailing separators.
32
+ const raw = String(text || "").replace(/\r?\n$/, "");
33
+ return raw ? raw.split(";") : [];
35
34
  }
36
35
 
37
36
  function sameWindowsPath(left, right) {
38
- return path.resolve(left).toLowerCase() === path.resolve(right).toLowerCase();
37
+ if (!String(left).trim() || !String(right).trim()) return false;
38
+ return path.resolve(String(left).trim()).toLowerCase() === path.resolve(String(right).trim()).toLowerCase();
39
39
  }
40
40
 
41
41
  function staleWindowsAiBatteryTempPath(entry) {
@@ -105,7 +105,8 @@ function removeWindowsUserPathEntries(shimDirs) {
105
105
  if (nextParts.length === parts.length) return [];
106
106
 
107
107
  const result = runWindowsPowerShell(`[Environment]::SetEnvironmentVariable('Path', ${psQuote(nextParts.join(";"))}, 'User')`);
108
- return result.status === 0 ? ["Windows user PATH"] : [];
108
+ if (result.status !== 0 || result.error) throw new Error("Could not remove the AI Battery entry from Windows user PATH; kept the recovery record");
109
+ return ["Windows user PATH"];
109
110
  }
110
111
  return {
111
112
  ensureWindowsShimPath,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ai-battery",
3
- "version": "0.1.21",
3
+ "version": "0.1.22",
4
4
  "description": "Tiny terminal battery meter for local Codex and Claude Code usage.",
5
5
  "type": "module",
6
6
  "keywords": [