From c5b4e12402ed5254a0946334c955b978e7eae308 Mon Sep 17 00:00:00 2001 From: okash1n <48118431+okash1n@users.noreply.github.com> Date: Tue, 6 Oct 2026 18:07:56 +0900 Subject: [PATCH 1/5] =?UTF-8?q?feat:=20Claude=20Code=202.1.89=20=E6=9C=AA?= =?UTF-8?q?=E6=BA=80=E5=90=91=E3=81=91=E3=81=AE=20legacy=20hook=20?= =?UTF-8?q?=E7=B5=8C=E8=B7=AF=E3=82=92=E9=80=80=E5=BD=B9=EF=BC=88v0.79.0?= =?UTF-8?q?=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit v0.39.0 / v0.41.0 で入れた 2.1.89 未満向けの旧 hook 形状(auto-update は SessionStart のみ + 24h cache、pr-creation-log は if なしでスクリプト側が コマンドを再判定)を、v0.70.0(#120)で宣言した退役条件の成立に合わせて 廃止し、サポート最小 Claude Code を 2.1.89 と宣言する。hook は導入時の CLI バージョンに関係なく常に 1 つの形状で生成し、settings.json の生成時に claude --version を起動しない。旧 CLI 検出時の警告は足していない。 - features/*/hooks.legacy.json(2 本)を削除 - lib/deploy.sh: _version_ge / _claude_cli_semver / _claude_supports_async_hooks / _versioned_hooks_fragment と呼び出しを削除し、 build_settings_file は hooks.json を直接参照する - auto-update.sh: AUTO_UPDATE_LEGACY / LEGACY_CACHE_* と 24h cache を削除 - log-pr.sh: PR_CREATION_LOG_LEGACY 分岐を削除(絞り込みは hook の if のみ) - lib/update.sh: 稼働確認は CLI によらず SessionStart と SessionEnd の両方を 要求する。旧形状のエントリを現行のエントリへ書き換える _migrate_legacy_hook_entries を追加し、_update_phase_settings の retired 掃除と superseded 掃除の間で毎回実行する - MDM: render-expected.py は hooks.json を読み、manifest から async_hooks を 削除。install-mdm.sh は KIT_MDM_ASYNC_HOOKS の注入と async_hooks の検証を 削除。MDM が配備する pr-creation-log は if + async の形になる - README.md / README.en.md / docs/mdm/README.md / CLAUDE.md / CHANGELOG を更新 - .starter-kit-update-cache の掃除(setup.sh / uninstall.sh / lib/dryrun.sh / cleanup_paths)は旧環境の残骸対応として残し、理由をコメントに書いた 移行の理由: 旧形状と現行形状はコマンド文字列が違う(env 接頭辞)ため、 v0.77.0 のコマンド集合による同一性では対にならない。利用者が同じ配列に 自分の hook を足している環境の非対話 3-way merge では旧形状と現行形状が 両方残り、bootstrap merge では旧形状が置き換わらずに残っていた。移行は キットが生成した 2 つのコマンドに完全一致する hook だけを対象にし、同じ 配列に現行コマンドがあれば旧形状を取り除き、なければその場でキット現行の hook に置き換える。ほかの hook・エントリ・並び順は変えず、旧形状がない settings.json は書き換えない。 確認したこと(b4eea52 との比較、全体スイートは未実行): - build_settings_file の出力は、Standard / Full × ja / en で、CLI が 2.1.89 / 2.1.88 / 2.1.291 / 解析不能 / 不在のいずれでも b4eea52 の 2.1.89 向け出力とバイト一致(20 通り)。ビルド中の claude 起動は 16 回から 0 回 - MDM の policy.json は 5 通りの profile / language でバイト一致。期待状態の 差分は settings.json(pr-creation-log)、log-pr.sh、manifest.json のみ - 変更したテストファイルを 1 つずつ修正前のコードに当てると、移行関数の 10 件、設定フェーズの 4 件、退役の不変条件 6 件、シナリオ 2 件が失敗する - tests/unit/test-mdm-expected.sh 単体は 30 件すべて成功 旧形状を前提にしていた単体テスト 7 件とシナリオ 1 件は削除した。 Fixes #136 --- CHANGELOG.md | 34 +++ CLAUDE.md | 4 +- README.en.md | 4 +- README.md | 8 +- docs/mdm/README.md | 2 + features/auto-update/hooks.legacy.json | 15 -- features/auto-update/scripts/auto-update.sh | 27 -- features/pr-creation-log/hooks.legacy.json | 15 -- features/pr-creation-log/scripts/log-pr.sh | 5 - lib/deploy.sh | 100 +------- lib/dryrun.sh | 3 + lib/update.sh | 111 ++++++++- mdm/install-mdm.sh | 6 +- mdm/render-expected.py | 4 +- setup.sh | 8 +- tests/helpers.sh | 35 +++ tests/run-scenarios.sh | 79 +++++- tests/unit/test-auto-update.sh | 177 ++++++++----- tests/unit/test-deploy-refactor.sh | 44 ---- tests/unit/test-hook-fixtures.sh | 2 +- tests/unit/test-mdm-expected.sh | 35 ++- tests/unit/test-pr-creation-log.sh | 104 ++++---- tests/unit/test-retired-hooks.sh | 263 ++++++++++++++++++++ tests/unit/test-runtime-hooks.sh | 46 +++- tests/unit/test-update-refactor.sh | 169 +++++++++++++ uninstall.sh | 2 + 26 files changed, 945 insertions(+), 357 deletions(-) delete mode 100644 features/auto-update/hooks.legacy.json delete mode 100644 features/pr-creation-log/hooks.legacy.json diff --git a/CHANGELOG.md b/CHANGELOG.md index ffa169e..d230fa0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,40 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/), and this project adheres to [Semantic Versioning](https://semver.org/). +## [0.79.0] - 2026-10-06 + +Claude Code 2.1.89 未満向けの旧 hook 形状(legacy hook 経路)を退役し、サポート最小 Claude Code を 2.1.89 と宣言する(#136)。 + +### Changed +- **サポート最小 Claude Code を 2.1.89 に引き上げ(#136)**: auto-update と pr-creation-log の hook を、導入時の CLI バージョンに関係なく常に 1 つの形状で生成するようにした(auto-update は `SessionStart` + `SessionEnd` の `async` 実行、pr-creation-log は `if: "Bash(gh pr create *)"` + `async`)。v0.39.0 / v0.41.0 で入れた 2.1.89 未満向けのフォールバック(auto-update は `SessionStart` のみ + 24h cache、pr-creation-log は `if` を使わずスクリプト側でコマンドを再判定する形)は、v0.70.0(#120)で宣言した退役条件(2.1.89 のリリースから 6 か月後以降の最初の minor)が成立したため廃止した。`setup.sh` / `setup.sh --update` は `settings.json` の生成時に `claude --version` を起動しなくなった + - **2.1.89 以上で導入済みの環境**: 生成される `settings.json` は v0.78.2 と同一で、差分は出ない(Standard / Full × 日本語 / 英語の 4 通りで、v0.78.2 が 2.1.89 向けに生成する内容とバイト単位で一致することを確認)。更新で内容が変わるのは `~/.claude/hooks/auto-update/auto-update.sh` と `~/.claude/hooks/pr-creation-log/log-pr.sh` の 2 本 + - **旧形状で導入されていた環境**(導入時の CLI が 2.1.89 未満だった、または `claude --version` の出力を解析できなかった環境): 次回の `setup.sh --update` / 自動アップデートで、旧形状の hook エントリが現行のエントリへ自動的に置き換わる(下の Fixed を参照)。`settings.json` を手で編集する必要はない + - **2.1.89 未満の CLI を使い続ける場合**: 動作は保証しない。hook の `async` / `if` を旧 CLI がどう扱うかは実機で確認していない。キットは CLI のバージョンを検査せず、警告も出さないため、CLI のバージョンを固定している場合は `claude --version` で確認し、`claude update` で 2.1.89 以上へ更新する。README.md / README.en.md の前提条件と auto-update の互換性の記述も同じ内容に改めた + - **pr-creation-log の絞り込みは hook の `if` に一本化**: `log-pr.sh` は `tool_input.command` を再判定しなくなった + - **テスト**: 退役後の不変条件として単体テスト 7 件を追加した(`hooks.legacy.json` が同梱されていないこと、同梱スクリプトに退役したバージョン判定への参照が残っていないこと、hook スクリプトが `claude` を起動しないこと、`build_settings_file` の出力が CLI のバージョン〔2.1.89 / 2.1.88 / 解析不能〕で変わらず `claude` を起動しないこと、pr-creation-log が旧 CLI でも同じ形になること、`AUTO_UPDATE_LEGACY` と 24h cache が更新確認を抑止しないこと、稼働確認の `SessionEnd` 要求が CLI に依存しないこと)。テストファイルを 1 つずつ実行した場合、修正前のコードではこのうち 6 件が失敗する。シナリオ `auto-update-legacy-claude-fallback` は、旧 CLI でも同じ hook になることを確認する `auto-update-old-claude-same-hooks` に置き換えた。旧形状を前提にしていた単体テスト 7 件は削除した +- **auto-update の稼働確認は、CLI バージョンによらず `SessionStart` と `SessionEnd` の両方の登録を要求する**: 従来は、2.1.89 未満の CLI を検出した場合と CLI のバージョンを解析できない場合に、`SessionEnd` が未登録でも「有効」と表示していた +- **MDM: 配備する pr-creation-log hook が通常インストールと同じ形状になる**: MDM 管理下の `settings.json` は、`ENABLE_PR_CREATION_LOG` が有効な場合(Standard / Full の既定)に pr-creation-log が `if` + `async` の形になる。従来は 2.1.89 未満との互換性を優先し、`if` / `async` を持たない旧形状へ固定していた(auto-update は MDM では常に無効のため対象外)。MDM の更新は `settings.json` 全体をキット生成版で置き換えるため、既存の管理端末は Fixed に記載した移行処理によらず、次回の remediation で新しい形状になる + - **install bundle の再配布が必要**: `mdm/render-expected.py` と `mdm/install-mdm.sh` を変更した。v0.78.x 以前から v0.79.0 以降の SHA へ更新する MDM 配布環境は、同じリリースの `install-mdm.sh` と `render-expected.py` を再配布する必要がある(bundle 側と checkout 側の `render-expected.py` の SHA-256 が一致しないと remediation は失敗する) + - renderer 引数と feature policy が同じなら `KIT_MDM_EXPECTED_POLICY_SHA256` は変わらない(Standard / Full × 日本語 / 英語と Minimal × 英語の 5 通りで、変更前後の `policy.json` がバイト単位で一致することを確認) + - renderer が出力する `manifest.json` から `async_hooks` キーを削除し、installer 側の検証も合わせた(`schema_version` は 1 のまま)。`KIT_MDM_PREREQ_MODE=fail` や `KIT_MDM_INSTALL_CLAUDE_CLI=false` で Claude CLI を別途配布・固定している場合は 2.1.89 以上を配布する。`docs/mdm/README.md` に同じ内容を追記した + - `tests/unit/test-mdm-expected.sh` を現行形状へ切り替え、描画した `settings.json` の pr-creation-log が `if` + `async` であることの検査を 1 件追加した + +### Removed +- `features/auto-update/hooks.legacy.json` と `features/pr-creation-log/hooks.legacy.json` +- `auto-update.sh` の `AUTO_UPDATE_LEGACY` / `LEGACY_CACHE_FILE` / `LEGACY_CACHE_TTL` と 24h cache の処理(`_auto_update_legacy_cache_fresh` / `_auto_update_touch_legacy_cache`)。`AUTO_UPDATE_LEGACY=1` を付けて起動しても無視され、`~/.claude/.starter-kit-update-cache` は読み書きされない +- `log-pr.sh` の `PR_CREATION_LOG_LEGACY` 分岐 +- `lib/deploy.sh` の CLI バージョン判定(`_claude_cli_semver` / `_claude_supports_async_hooks` / `_versioned_hooks_fragment` / `_version_ge` とその呼び出し)、`lib/update.sh` の `require_session_end` 分岐 +- MDM の内部値 `KIT_MDM_ASYNC_HOOKS` +- **残したもの**: `~/.claude/.starter-kit-update-cache` を掃除する処理(`setup.sh --update` 時の削除、`uninstall.sh` のフォールバック一覧、`lib/dryrun.sh` のコピー対象、`lib/deploy.sh` の `cleanup_paths`)は、旧環境に残ったファイルを片付けるために当面残す。1〜2 リリース後にまとめて削除する + +### Fixed +- **旧形状の hook エントリが残った環境で、同じ hook が二重に登録される、または旧形状のまま残る問題を修正**: 旧形状と現行形状は hook のコマンド文字列が異なる(旧形状は `AUTO_UPDATE_LEGACY=1 ...` / `PR_CREATION_LOG_LEGACY=1 ...` の接頭辞を持つ)ため、v0.77.0 で導入した「コマンド集合による同一性」では対にならない。その結果、SessionStart / PostToolUse の配列に自分の hook を足している環境の非対話更新では、旧形状のエントリが「キットが削除した項目」として残り、現行のエントリと並んで二重登録になっていた。snapshot を持たない環境の bootstrap 更新では、旧形状のエントリが現行のエントリに置き換わらずに残っていた。どちらも v0.78.x 以前から、CLI を 2.1.89 未満から 2.1.89 以上へ上げた後のキット更新で起きていた + - 更新時に旧形状のエントリを現行のエントリへ書き換える `_migrate_legacy_hook_entries` を `lib/update.sh` に追加した。同じ配列に現行のコマンドが登録済みなら旧形状の hook を取り除き、未登録ならその場でキット現行の hook に置き換える(該当機能を無効にしていて、キットが生成する設定にその hook がない場合は取り除く)。対話・非対話のどちらの更新でも、3-way merge の実行有無にかかわらず毎回実行する + - 対象は、キット自身が生成した 2 つのコマンド文字列に完全一致する hook だけ。利用者が追加した hook、ほかのエントリとその並び順、手で書き換えた類似コマンドは変更しない。旧形状のエントリがない `settings.json` は書き換えない + - **移行されないケース**: 旧形状のコマンドを手で書き換えていた場合や、`settings.json` を生成したときと `$HOME` が変わっている場合は対象外で、エントリはそのまま残る。残った auto-update のエントリは `async` を持たず、24h cache も効かなくなるため、セッション開始のたびに更新確認を行う。該当する場合は、そのエントリをキットが生成する現行の形(`features/auto-update/hooks.json` / `features/pr-creation-log/hooks.json`)へ手で書き換える + - manifest を持たず既存の `settings.json` だけがある状態への新規インストールは、この移行を通らない(この経路は bootstrap merge だけを行う)。既存の退役 hook 掃除と同じ扱いで、今回は対象外 + - **回帰テスト**: 移行関数の単体テスト 10 件を `tests/unit/test-retired-hooks.sh` に、更新の設定フェーズ(`_update_phase_settings`)のテスト 6 件(呼び出し順の検査 1 件と、実際のビルドを使って通す 5 件)を `tests/unit/test-update-refactor.sh` に、`setup.sh --update --non-interactive` を通すシナリオ `update-migrates-legacy-hooks` を追加した。修正前のコードでは、移行関数のテストが 10 件すべて、設定フェーズのテストが 4 件、シナリオが失敗する(設定フェーズの残り 2 件は、利用者が触っていない旧形状の環境と、すでに現行形状の環境が従来どおり扱われることの確認) + ## [0.78.4] - 2026-10-07 `web-content-extraction` skill の `undici` / `source-map-js` 脆弱性を解消(Dependabot alert #27〜#47)。 diff --git a/CLAUDE.md b/CLAUDE.md index 7ee5686..1175868 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -202,7 +202,7 @@ Rules to remember: verify fresh install, `setup.sh --update`/`/update-kit`, and - **Windows interop from WSL/MSYS**: Use `powershell.exe -NoProfile -Command '...'` for Windows-side operations (font install, WT config). Always `tr -d '\r'` on output to strip CRLF. - **Codex Plugin scope**: Always use `claude plugin install codex --scope user` (user scope, not project scope). - **Timeout portability**: Use `_run_with_timeout` wrapper (macOS lacks `timeout`). -- **Claude CLI stdin**: Call non-interactive `claude` subcommands through `_claude_cli()` (`lib/codex-setup.sh`, runs `claude "$@" = 2.1.89 and never inspects the CLI version (the legacy cache-hook fallback was retired in v0.79.0; `_migrate_legacy_hook_entries` in `lib/update.sh` rewrites leftover legacy entries on update). - **Status Line**: Python statusLine command showing model, context usage, and 5h/7d rate limits. - **Doc Size Guard**: non-blocking size-hygiene warning when CLAUDE.md/AGENTS.md exceeds line targets after Write. - **Feature Recommendation**: writes pending feature names and notifies via SessionStart for enabled profiles. diff --git a/README.en.md b/README.en.md index 4bd5363..c76755a 100644 --- a/README.en.md +++ b/README.en.md @@ -65,6 +65,8 @@ Claude Code Starter Kit bootstraps a consistent, high-quality Claude Code enviro Missing or unsupported prerequisites are installed or upgraded automatically when possible: `git`, `jq`, `curl`, GNU `sed`, GNU `awk`, `bash 4+`, Node.js `22.19+`, `tmux`, and `gh`. On macOS, the kit also detects the system Bash 3.2 limitation, installs Bash 4+ when needed, and re-execs automatically. If automatic installation fails, setup exits with an error and shows the manual commands. +Hook settings generated by the kit require Claude Code `2.1.89` or later (since v0.79.0). The kit does not check the CLI version: if you pin the CLI, check it with `claude --version` and run `claude update` when it is older. + > **Before using `claude-security` (Full profile only)** > > - Launch it manually with `/claude-security`; no resident hook scans on your behalf. @@ -259,7 +261,7 @@ Automatically checks for new starter kit releases on GitHub on both `SessionStar - **Settings preserved**: 3-way merge keeps settings and hooks that use your own commands. Kit-shipped hook entries are kit-owned: an entry you edited in place, or a kit command you re-registered under another matcher, is consolidated back to the kit's single version on update - **One-liner installs only**: Only works when the kit is installed at `~/.claude-starter-kit/` - **SessionEnd is best-effort**: abrupt termination may skip the end-of-session check -- **Compatibility**: Verified on Claude Code `2.1.89`. When an older Claude Code is detected, the kit falls back to the legacy `SessionStart` + 24h cache hook +- **Compatibility**: Requires Claude Code `2.1.89` or later. The fallback to the legacy `SessionStart` + 24h cache hook for older versions was removed in v0.79.0. Check with `claude --version` and run `claude update` if it is older - **Dirty check**: If the kit repo has local changes, auto-update skips and suggests `git stash` - **Recovery info**: If the update fails, the hook prints the backup path and restore command - **Failure carry-over**: Background update failures are saved once and surfaced on the next hook run diff --git a/README.md b/README.md index 965599c..5a4b15a 100644 --- a/README.md +++ b/README.md @@ -134,6 +134,8 @@ Claude Code をインストールしただけでは、まっさらな状態で > **前提ツールは自動導入**: セットアップに必要な `git` `jq` `curl` GNU `sed` GNU `awk` `bash 4+` Node.js `22.19+` `tmux` `gh` は、見つからない場合や最低版を満たさない場合に自動で導入・更新を試みます。macOS の Bash 3.2 問題も自動検出して Bash 4+ へ切り替えます。自動導入に失敗した場合のみ、最後に手動コマンドを案内してセットアップを失敗として終了します。 +> **Claude Code のバージョン**: キットが生成する hook 設定は Claude Code `2.1.89` 以上を前提とします(v0.79.0 以降)。キットは CLI のバージョンを検査しないため、CLI のバージョンを固定している場合は `claude --version` で確認し、古い場合は `claude update` で更新してください。 + > **Linux について**: このキットは macOS と Windows を対象としています。Linux で利用する場合は、ディストリビューション(Ubuntu, Fedora 等)やデスクトップ環境(GNOME, KDE 等)に応じた調整が必要になる場合があります。方法 1 のワンライナーまたは方法 3 の手動インストールをお試しください。 --- @@ -532,13 +534,13 @@ SessionStart / SessionEnd フック発火 - **SessionEnd は best-effort**: 異常終了時は start 側のチェックだけに依存します - **dirty check**: kit リポジトリにローカル変更がある場合は更新をスキップし、`git stash` を案内します - **復旧案内**: 更新に失敗した場合、バックアップパスと復元コマンドを表示します(`~/.claude.backup.` から復元可能) -- **互換性**: Claude Code `2.1.89` で確認済みです。旧版を検出した場合は `SessionStart` + 24h cache の旧 hook へ自動フォールバックします +- **互換性**: Claude Code `2.1.89` 以上が必要です。旧版向けの `SessionStart` + 24h cache へのフォールバックは v0.79.0 で廃止しました。`claude --version` で確認し、古い場合は `claude update` で更新してください - **失敗の持ち越し**: バックグラウンド更新に失敗した場合は結果を保存し、次回 hook 実行時に 1 回だけ警告します -> **legacy auto-update の復旧**: 旧 24h cache 環境や auto-update 無効環境で、確実に最新版へ更新して hook を再配備したい場合は次を実行してください。 +> **auto-update の手動復旧**: auto-update 無効環境などで、確実に最新版へ更新して hook を再配備したい場合は次を実行してください。 > > ```bash -> test -z "$(git -C ~/.claude-starter-kit status --porcelain 2>/dev/null)" && rm -f ~/.claude/.starter-kit-update-cache && git -C ~/.claude-starter-kit fetch --tags && git -C ~/.claude-starter-kit pull --ff-only && bash ~/.claude-starter-kit/setup.sh --update || echo "Local changes detected in ~/.claude-starter-kit. Run: cd ~/.claude-starter-kit && git stash -u" +> test -z "$(git -C ~/.claude-starter-kit status --porcelain 2>/dev/null)" && git -C ~/.claude-starter-kit fetch --tags && git -C ~/.claude-starter-kit pull --ff-only && bash ~/.claude-starter-kit/setup.sh --update || echo "Local changes detected in ~/.claude-starter-kit. Run: cd ~/.claude-starter-kit && git stash -u" > ``` > > dirty な作業ツリーでは安全のため停止します。その場合は `git stash -u` などで退避してから再実行してください。 diff --git a/docs/mdm/README.md b/docs/mdm/README.md index 0d806dd..054f16d 100644 --- a/docs/mdm/README.md +++ b/docs/mdm/README.md @@ -121,6 +121,8 @@ production では対象のローカルアカウントと UID 501 以上が必要 `ENABLE_GHOSTTY_SETUP` / `ENABLE_FONTS_SETUP` だけは `PROFILE` にかかわらず MDM 既定 `false` で、CLI または管理設定ファイルによる明示的な `true` で opt-in できる。Ghostty の opt-in は、MDM が署名済みで `com.apple.quarantine` のない `/Applications/Ghostty.app` を先に配布することが前提で、対象ユーザーとして動く `setup.sh` は Homebrew cask の導入を試みず、署名・quarantine 検証とユーザー設定だけを行う。これにより非 admin アカウントで password / Gatekeeper prompt が発生しない。キットの auto-update、web updater、通常の marketplace plugin、Codex Plugin は MDM では常に無効にし、更新は新しい40桁 SHAを指定した MDM 再配布で行う。`SELECTED_PLUGINS` は MDM の許可キーではなく、指定すると `exit 50`。fresh / update とも profile preset や保存済みユーザー設定からこれらを再有効化しない。 +**hook の形状と Claude Code の最小バージョン(v0.79.0 以降)**: `ENABLE_PR_CREATION_LOG` が有効な場合(Standard / Full の既定)、MDM が配備する `settings.json` の pr-creation-log hook は通常インストールと同じ `if: "Bash(gh pr create *)"` + `async: true` の形になる。v0.78.x までは Claude Code 2.1.89 未満との互換性を優先し、`if` / `async` を持たない旧形状へ固定していた。これに伴い MDM 配布でも Claude Code 2.1.89 以上を前提とする。`KIT_MDM_PREREQ_MODE=fail` や `KIT_MDM_INSTALL_CLAUDE_CLI=false` で Claude CLI を別途配布・固定している場合は 2.1.89 以上を配布する。v0.78.x 以前から v0.79.0 以降の SHA へ更新するときは、同じリリースの `install-mdm.sh` と `render-expected.py` を必ず再配布する(bundle 側と checkout 側の `render-expected.py` の SHA-256 が一致しないと remediation は失敗する)。renderer 引数と feature policy が同じなら `KIT_MDM_EXPECTED_POLICY_SHA256` の値は変わらない。 + ### MDM 固有キー(`KIT_MDM_` 接頭辞) | キー | 既定値 | 意味 | diff --git a/features/auto-update/hooks.legacy.json b/features/auto-update/hooks.legacy.json deleted file mode 100644 index 995d7dd..0000000 --- a/features/auto-update/hooks.legacy.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "hooks": { - "SessionStart": [ - { - "matcher": "startup", - "hooks": [ - { - "type": "command", - "command": "AUTO_UPDATE_LEGACY=1 AUTO_UPDATE_HOOK=SessionStart __HOME__/.claude/hooks/auto-update/auto-update.sh" - } - ] - } - ] - } -} diff --git a/features/auto-update/scripts/auto-update.sh b/features/auto-update/scripts/auto-update.sh index 8967f14..0605cfc 100644 --- a/features/auto-update/scripts/auto-update.sh +++ b/features/auto-update/scripts/auto-update.sh @@ -6,10 +6,7 @@ KIT_DIR="${KIT_DIR:-${HOME}/.claude-starter-kit}" LOCK_DIR="${LOCK_DIR:-${HOME}/.claude/.starter-kit-update.lock}" BACKUP_PATH_FILE="${BACKUP_PATH_FILE:-$HOME/.claude/.starter-kit-last-backup}" STATUS_FILE="${STATUS_FILE:-$HOME/.claude/.starter-kit-update-status}" -LEGACY_CACHE_FILE="${LEGACY_CACHE_FILE:-$HOME/.claude/.starter-kit-update-cache}" -LEGACY_CACHE_TTL="${LEGACY_CACHE_TTL:-86400}" AUTO_UPDATE_HOOK="${AUTO_UPDATE_HOOK:-SessionStart}" -AUTO_UPDATE_LEGACY="${AUTO_UPDATE_LEGACY:-0}" _LOCK_HELD=false @@ -44,20 +41,6 @@ _auto_update_repo_exists() { [[ -d "${KIT_DIR}/.git" ]] } -_auto_update_legacy_cache_fresh() { - local last_check now - [[ -f "$LEGACY_CACHE_FILE" ]] || return 1 - last_check="$(cat "$LEGACY_CACHE_FILE" 2>/dev/null || echo "0")" - [[ "$last_check" =~ ^[0-9]+$ ]] || return 1 - now="$(_auto_update_now)" - (( now - last_check < LEGACY_CACHE_TTL )) -} - -_auto_update_touch_legacy_cache() { - mkdir -p "$(dirname "$LEGACY_CACHE_FILE")" - _auto_update_now > "$LEGACY_CACHE_FILE" -} - _auto_update_release_lock() { if [[ "$_LOCK_HELD" == "true" ]]; then rm -rf "$LOCK_DIR" @@ -78,9 +61,6 @@ _auto_update_maybe_detach() { LOCK_DIR="$LOCK_DIR" \ BACKUP_PATH_FILE="$BACKUP_PATH_FILE" \ STATUS_FILE="$STATUS_FILE" \ - LEGACY_CACHE_FILE="$LEGACY_CACHE_FILE" \ - LEGACY_CACHE_TTL="$LEGACY_CACHE_TTL" \ - AUTO_UPDATE_LEGACY="$AUTO_UPDATE_LEGACY" \ "$0" >/dev/null 2>&1 & return 0 fi @@ -138,13 +118,6 @@ _auto_update_run() { _auto_update_emit_previous_failure _auto_update_repo_exists || return 0 - if [[ "$AUTO_UPDATE_LEGACY" == "1" || "$AUTO_UPDATE_LEGACY" == "true" ]]; then - if _auto_update_legacy_cache_fresh; then - return 0 - fi - _auto_update_touch_legacy_cache - fi - _auto_update_acquire_lock || return 0 if ! git -C "$KIT_DIR" fetch --tags --quiet 2>/dev/null; then diff --git a/features/pr-creation-log/hooks.legacy.json b/features/pr-creation-log/hooks.legacy.json deleted file mode 100644 index 2bc0038..0000000 --- a/features/pr-creation-log/hooks.legacy.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "hooks": { - "PostToolUse": [ - { - "matcher": "Bash", - "hooks": [ - { - "type": "command", - "command": "PR_CREATION_LOG_LEGACY=1 __HOME__/.claude/hooks/pr-creation-log/log-pr.sh" - } - ] - } - ] - } -} diff --git a/features/pr-creation-log/scripts/log-pr.sh b/features/pr-creation-log/scripts/log-pr.sh index 12cd39c..921caad 100755 --- a/features/pr-creation-log/scripts/log-pr.sh +++ b/features/pr-creation-log/scripts/log-pr.sh @@ -3,11 +3,6 @@ set -euo pipefail input="$(cat)" -if [[ "${PR_CREATION_LOG_LEGACY:-0}" == "1" ]]; then - cmd="$(printf '%s' "$input" | jq -r '.tool_input.command // ""')" - printf '%s' "$cmd" | grep -qE 'gh pr create' || exit 0 -fi - output="$(printf '%s' "$input" | jq -r '[.tool_response.stdout // "", .tool_response.stderr // ""] | join("\n")')" # `|| true` prevents pipefail from propagating grep's no-match exit code (1) # when no PR URL is present, which would otherwise trigger `set -e` and diff --git a/lib/deploy.sh b/lib/deploy.sh index 2e9e942..ef6644c 100644 --- a/lib/deploy.sh +++ b/lib/deploy.sh @@ -69,93 +69,6 @@ _bool_to_string() { fi } -_version_ge() { - local lhs="${1:-0}" - local rhs="${2:-0}" - local lhs_a lhs_b lhs_c rhs_a rhs_b rhs_c _ - - IFS='.' read -r lhs_a lhs_b lhs_c _ < <(printf '%s\n' "$lhs") - IFS='.' read -r rhs_a rhs_b rhs_c _ < <(printf '%s\n' "$rhs") - lhs_a="${lhs_a:-0}"; lhs_b="${lhs_b:-0}"; lhs_c="${lhs_c:-0}" - rhs_a="${rhs_a:-0}"; rhs_b="${rhs_b:-0}"; rhs_c="${rhs_c:-0}" - - (( lhs_a > rhs_a )) && return 0 - (( lhs_a < rhs_a )) && return 1 - (( lhs_b > rhs_b )) && return 0 - (( lhs_b < rhs_b )) && return 1 - (( lhs_c >= rhs_c )) -} - -_CLAUDE_SEMVER_CACHE="${_CLAUDE_SEMVER_CACHE-}" -_CLAUDE_SEMVER_CACHE_SET="${_CLAUDE_SEMVER_CACHE_SET:-false}" - -_claude_cli_semver() { - local raw version - command -v claude &>/dev/null || return 1 - if [[ "$_CLAUDE_SEMVER_CACHE_SET" == "true" ]]; then - [[ -n "$_CLAUDE_SEMVER_CACHE" ]] || return 1 - printf '%s\n' "$_CLAUDE_SEMVER_CACHE" - return 0 - fi - _CLAUDE_SEMVER_CACHE_SET=true - # --version exits before touching stdin; detached anyway for consistency with - # _claude_cli() in lib/codex-setup.sh (macOS kqueue rejects a /dev/tty stdin). - raw="$(claude --version /dev/null | head -1)" - if ! [[ "$raw" =~ ([0-9]+\.[0-9]+\.[0-9]+) ]]; then - _CLAUDE_SEMVER_CACHE="" - return 1 - fi - version="${BASH_REMATCH[1]}" - _CLAUDE_SEMVER_CACHE="$version" - printf '%s\n' "$version" -} - -_claude_supports_async_hooks() { - local min_version="${1:-2.1.89}" - local current_version="" - - # The privileged MDM launcher pins this internal decision before running - # setup so both deployment and independent postcondition rendering use the - # same hook schema. It is deliberately not a public MDM config key. - if _deploy_mdm_managed; then - case "${KIT_MDM_ASYNC_HOOKS:-}" in - true) return 0 ;; - false) return 1 ;; - esac - fi - - # Fail open when Claude is absent so generated config stays forward-looking - # during offline tests or first install. Fail closed when a present CLI has an - # unparsable version because we cannot prove async hook support. - if ! command -v claude &>/dev/null; then - return 0 - fi - - current_version="$(_claude_cli_semver 2>/dev/null || true)" - [[ -n "$current_version" ]] || return 1 - _version_ge "$current_version" "$min_version" -} - -_versioned_hooks_fragment() { - local feature="$1" - local src="$PROJECT_DIR/features/${feature}/hooks.json" - local legacy_src="$PROJECT_DIR/features/${feature}/hooks.legacy.json" - - if _claude_supports_async_hooks "2.1.89"; then - printf '%s\n' "$src" - else - printf '%s\n' "$legacy_src" - fi -} - -_auto_update_hooks_fragment() { - _versioned_hooks_fragment "auto-update" -} - -_pr_creation_log_hooks_fragment() { - _versioned_hooks_fragment "pr-creation-log" -} - apply_settings_preferences() { local file="$1" local lang_name tmp_file attribution_enabled @@ -1209,6 +1122,9 @@ _normalize_mdm_managed_modes() { done } +# .starter-kit-update-cache is no longer written (the Claude Code < 2.1.89 hook +# path that used it was retired in v0.79.0, #136). It stays listed so uninstall +# still removes one left by an older install; see setup_deploy() in setup.sh. cleanup_paths_json() { jq -n \ --arg claude_dir "$CLAUDE_DIR" \ @@ -1990,11 +1906,6 @@ build_settings_file() { local hook_fragments=() local tmp_files=() - # Prime the semver cache in THIS shell: the fragment helpers below run in - # $(...) subshells, so cache writes made there never persist and `claude - # --version` would otherwise be spawned once per fragment. - _claude_cli_semver >/dev/null 2>&1 || true - # Assertion: safety-net must be first in _FEATURE_ORDER if [[ "${_FEATURE_ORDER[0]}" != "safety-net" ]]; then error "FATAL: safety-net must be first in _FEATURE_ORDER (got: ${_FEATURE_ORDER[0]:-empty})" @@ -2017,11 +1928,6 @@ build_settings_file() { continue fi local hooks_json="$PROJECT_DIR/features/$name/hooks.json" - if [[ "$name" == "auto-update" ]]; then - hooks_json="$(_auto_update_hooks_fragment)" - elif [[ "$name" == "pr-creation-log" ]]; then - hooks_json="$(_pr_creation_log_hooks_fragment)" - fi [[ -f "$hooks_json" ]] && hook_fragments+=("$hooks_json") done diff --git a/lib/dryrun.sh b/lib/dryrun.sh index 84de878..1ef6767 100644 --- a/lib/dryrun.sh +++ b/lib/dryrun.sh @@ -44,6 +44,9 @@ _dryrun_copy_path() { # # Copies only files needed for install/update simulation. Runtime-heavy user # state such as projects/ session transcripts is intentionally excluded. +# .starter-kit-update-cache is no longer written since v0.79.0 (#136); it is +# still copied so the simulated update starts from the same state as a real +# one when an older install left the file (see setup_deploy() in setup.sh). # --------------------------------------------------------------------------- _dryrun_init() { local real_dir="$1" diff --git a/lib/update.sh b/lib/update.sh index cff6d8a..cda96b3 100644 --- a/lib/update.sh +++ b/lib/update.sh @@ -1442,6 +1442,104 @@ _strip_superseded_kit_hook_generations() { fi } +# --------------------------------------------------------------------------- +# _migrate_legacy_hook_entries - Rewrite hook entries generated for +# Claude Code < 2.1.89 +# +# Usage: _migrate_legacy_hook_entries +# +# Until v0.78.x the kit generated a second shape of the auto-update and +# pr-creation-log hooks for Claude Code < 2.1.89 (hooks.legacy.json, retired +# in v0.79.0, #136). Those commands carry an env prefix, so they are a +# different identity from the current entries: a user-touched hooks array +# keeps the legacy hook NEXT TO the kit's current one (non-interactive 3-way +# merge treats it as "removed by the kit" and keeps it), and a bootstrap merge +# keeps it INSTEAD of the current one. Neither _merge_arrays_3way nor +# _strip_superseded_kit_hook_generations can pair them. The current scripts +# ignore the prefix, so a leftover auto-update entry (no `async`) would check +# for updates on every session start without the former 24h throttle. +# +# Per hooks array, for each of the two exact commands the kit itself wrote: +# - the current command is already registered there -> the legacy hook is +# removed; +# - otherwise the first legacy hook is replaced in place by the kit's +# current hook object for that script (removed when the freshly built kit +# settings do not ship it, e.g. the feature is disabled) and any further +# copy is removed. +# An entry left without hooks is dropped, and so is an array left empty. Only +# the legacy hooks are touched: other hooks, other entries and their order stay +# as they are, and a file without a legacy hook is not rewritten at all. +# Matching is exact against this $HOME (same premise as +# _strip_retired_hook_entries); a hand-edited variant is left alone. +# --------------------------------------------------------------------------- +_migrate_legacy_hook_entries() { + local settings_file="$1" + local kit_file="$2" + [[ -f "$settings_file" ]] || return 1 + [[ -f "$kit_file" ]] || return 0 + local filter=' + def current_command: + if type != "string" then null + elif . == ("AUTO_UPDATE_LEGACY=1 AUTO_UPDATE_HOOK=SessionStart " + $home + + "/.claude/hooks/auto-update/auto-update.sh") + then "AUTO_UPDATE_HOOK=SessionStart " + $home + + "/.claude/hooks/auto-update/auto-update.sh" + elif . == ("PR_CREATION_LOG_LEGACY=1 " + $home + + "/.claude/hooks/pr-creation-log/log-pr.sh") + then $home + "/.claude/hooks/pr-creation-log/log-pr.sh" + else null end; + def cmd: if type == "object" then .command else null end; + def inner: if type == "object" and (.hooks | type) == "array" + then .hooks else [] end; + def has_legacy: any(.[]; any(inner[]; (cmd | current_command) != null)); + def migrate($K): + . as $L + | [$L[] | inner[] | cmd | strings] as $registered + | reduce $L[] as $entry ({out: [], done: []}; + if [$entry] | has_legacy then + (reduce $entry.hooks[] as $hook ({hooks: [], done: .done}; + ($hook | cmd | current_command) as $now + | if $now == null then .hooks += [$hook] + elif any(($registered + .done)[]; . == $now) then . + else ([$K[]? | inner[] | select(cmd == $now)] | first) as $kit_hook + | if $kit_hook == null then . + else .hooks += [$kit_hook] | .done += [$now] end + end)) as $result + | .done = $result.done + | if ($result.hooks | length) > 0 + then .out += [$entry | .hooks = $result.hooks] else . end + else .out += [$entry] end) + | .out; + ($kit[0].hooks // {}) as $KH' + local probe_rc=0 + jq -e --arg home "$HOME" --slurpfile kit "$kit_file" "$filter"' | + any((.hooks // {}) | to_entries[] | .value; + type == "array" and has_legacy) + ' "$settings_file" >/dev/null 2>&1 || probe_rc=$? + case "$probe_rc" in + 0) ;; + 1) return 0 ;; + *) return 0 ;; # unreadable kit build or settings — nothing safe to do + esac + local tmp + tmp="$(mktemp)" || return 1 + _SETUP_TMP_FILES+=("$tmp") + if jq --arg home "$HOME" --slurpfile kit "$kit_file" "$filter"' | + .hooks |= with_entries( + ($KH[.key] // []) as $K + | if (.value | type) == "array" and (.value | has_legacy) + then .value |= migrate($K) | select((.value | length) > 0) + else . end) + ' "$settings_file" > "$tmp" 2>/dev/null; then + mv "$tmp" "$settings_file" || return 1 + ok "Migrated hook entries generated for Claude Code < 2.1.89 to the current kit hooks" + else + rm -f "$tmp" 2>/dev/null || true + warn "Could not migrate legacy hook entries in settings.json" + return 1 + fi +} + _retired_relative_path_is_safe() { local rel="$1" [[ -n "$rel" && "$rel" != /* && ! "$rel" =~ [[:cntrl:]] ]] || return 1 @@ -1757,6 +1855,12 @@ _update_phase_settings() { # deletes. Strip them explicitly. _strip_retired_hook_entries "$current_settings" || return 1 + # Hook entries generated for Claude Code < 2.1.89 (retired in v0.79.0, #136) + # carry a different command, so neither the merge above nor the sweep below + # can pair them with the kit's current entry. Rewrite them first; the sweep + # then sees only current commands. + _migrate_legacy_hook_entries "$current_settings" "$new_settings" || return 1 + # Heal arrays that already carry a stale kit hook generation next to the # kit's current entry (#163). The 3-way merge above only runs when snapshot, # current and new kit all differ, so without this sweep an already-duplicated @@ -2165,14 +2269,9 @@ _check_auto_update_health() { local issues=() local has_session_start=false local has_session_end=false - local require_session_end=false local hook_state_known=true local hook_issue=false - if _claude_supports_async_hooks "2.1.89"; then - require_session_end=true - fi - # `.hooks.[]?.hooks[]?.command | contains(...)` emits one output per # registered hook, and `jq -e` derives its exit code from the LAST output # only. Any hook registered after auto-update therefore reported "not @@ -2210,7 +2309,7 @@ _check_auto_update_health() { if [[ "$hook_state_known" == "true" ]]; then if [[ "$has_session_start" != "true" ]]; then hook_issue=true - elif [[ "$require_session_end" == "true" ]] && [[ "$has_session_end" != "true" ]]; then + elif [[ "$has_session_end" != "true" ]]; then hook_issue=true fi fi diff --git a/mdm/install-mdm.sh b/mdm/install-mdm.sh index 80b0835..035e15b 100755 --- a/mdm/install-mdm.sh +++ b/mdm/install-mdm.sh @@ -3503,9 +3503,6 @@ mdm_build_drop_argv() { # MDM 管理マーカー: setup.sh(wizard)が update/fresh の設定復元後に # MDM 注入 env を再適用するためのフラグ(固定値・R2-High) "KIT_MDM_MANAGED=true" - # MDMの独立期待値レンダラーとsetupのhook schemaを固定する内部値。 - # 公開設定にはせず、互換性を優先してlegacy schemaへ収束させる。 - "KIT_MDM_ASYNC_HOOKS=false" "KIT_MDM_REQUIRE_NODE_RUNTIME=${KIT_MDM_REQUIRE_NODE_RUNTIME:-false}" ) case "${_MDM_OUTER_TRANSACTION_ACTIVE:-false}" in @@ -5914,7 +5911,7 @@ import sys manifest_path, policy_path, profile, language, home = sys.argv[1:] manifest_keys = [ - "schema_version", "profile", "language", "logical_home", "async_hooks", + "schema_version", "profile", "language", "logical_home", "required_components", "policy_sha256", "files", "absent_files", "entries", "total_bytes", ] @@ -5983,7 +5980,6 @@ try: or manifest["profile"] != profile or manifest["language"] != language or manifest["logical_home"] != home - or manifest["async_hooks"] is not False or type(required) is not list or required != sorted(set(required)) or not required or not set(required).issubset(components) or type(files) is not list or files != sorted(set(files)) diff --git a/mdm/render-expected.py b/mdm/render-expected.py index cc029a6..b2b919c 100644 --- a/mdm/render-expected.py +++ b/mdm/render-expected.py @@ -490,8 +490,7 @@ def render_settings(checkout, values, language, logical_home, flags, order): continue if feature == "web-content-update" and not values["INSTALL_SKILLS"]: continue - suffix = ".legacy.json" if feature in ("auto-update", "pr-creation-log") else ".json" - fragment = parse_json(checkout, "features/{}/hooks{}".format(feature, suffix)) + fragment = parse_json(checkout, "features/{}/hooks.json".format(feature)) settings = merge_objects(settings, fragment, concatenate_arrays=True) settings["language"] = language environment = settings.get("env") @@ -722,7 +721,6 @@ def write_output( "profile": profile, "language": language, "logical_home": logical_home, - "async_hooks": False, "required_components": components, "policy_sha256": policy_sha256, "files": paths, diff --git a/setup.sh b/setup.sh index d09fa4d..0f0128b 100755 --- a/setup.sh +++ b/setup.sh @@ -582,9 +582,11 @@ _prepare_mdm_claude_root _rc=$? [[ "$_rc" -eq 0 ]] || return "$_rc" if [[ "${UPDATE_MODE:-false}" == "true" ]]; then - # Remove legacy 24h update cache so the old auto-update.sh (pre-v0.39.0) - # won't skip the next check. Once the new hook scripts are deployed by this - # update, the cache file is no longer used. + # Remove the 24h update cache written by the auto-update hook of installs + # made for Claude Code < 2.1.89. That hook path was retired in v0.79.0 (#136) + # and the scripts deployed by this update neither read nor write the file. + # Leftover cleanup only: keep it for a release or two, then drop it together + # with the same path in uninstall.sh, lib/dryrun.sh and cleanup_paths_json(). rm -f "$CLAUDE_DIR/.starter-kit-update-cache" 2>/dev/null || true if _has_user_customizations "$CLAUDE_DIR"; then diff --git a/tests/helpers.sh b/tests/helpers.sh index 881d3af..ef80648 100644 --- a/tests/helpers.sh +++ b/tests/helpers.sh @@ -184,6 +184,41 @@ install_fixture() { cp -a "$src"/. "$CLAUDE_DIR"/ } +# --------------------------------------------------------------------------- +# rewrite_settings_to_legacy_hooks - Rewrite a kit-built settings.json into the +# shape v0.78.x and earlier generated for Claude Code < 2.1.89 +# +# Usage: rewrite_settings_to_legacy_hooks +# +# The legacy fragments (hooks.legacy.json, retired in v0.79.0) can no longer be +# built, so migration tests derive that shape from a current build: the +# auto-update SessionStart command and the pr-creation-log command get their +# env prefix and lose async/asyncTimeout/if, and the auto-update SessionEnd +# entry is dropped. Commands are matched against the current $HOME. +# --------------------------------------------------------------------------- +rewrite_settings_to_legacy_hooks() { + local file="$1" tmp + tmp="$(mktemp)" || return 1 + if jq --arg home "$HOME" ' + ($home + "/.claude/hooks/auto-update/auto-update.sh") as $au + | ($home + "/.claude/hooks/pr-creation-log/log-pr.sh") as $pr + | .hooks.SessionStart |= map(.hooks |= map( + if .command == ("AUTO_UPDATE_HOOK=SessionStart " + $au) + then {type, command: ("AUTO_UPDATE_LEGACY=1 " + .command)} else . end)) + | .hooks.PostToolUse |= map(.hooks |= map( + if .command == $pr + then {type, command: ("PR_CREATION_LOG_LEGACY=1 " + .command)} else . end)) + | .hooks.SessionEnd |= map(select( + any(.hooks[]; .command == ("AUTO_UPDATE_HOOK=SessionEnd " + $au)) | not)) + | if (.hooks.SessionEnd | length) == 0 then del(.hooks.SessionEnd) else . end + ' "$file" > "$tmp"; then + mv "$tmp" "$file" + else + rm -f "$tmp" + return 1 + fi +} + # --------------------------------------------------------------------------- # Assertions # --------------------------------------------------------------------------- diff --git a/tests/run-scenarios.sh b/tests/run-scenarios.sh index 13d18ba..0d8b347 100644 --- a/tests/run-scenarios.sh +++ b/tests/run-scenarios.sh @@ -181,19 +181,24 @@ test_auto_update_session_hooks() { teardown_test_env } -# --- 4c. auto-update-legacy-claude-fallback --- -test_auto_update_legacy_claude_fallback() { +# --- 4c. auto-update-old-claude-same-hooks --- +# The hook shape no longer depends on the installed Claude Code (the < 2.1.89 +# fallback was retired in v0.79.0, #136): an old CLI gets the same async hooks. +test_auto_update_old_claude_same_hooks() { setup_test_env export MOCK_CLAUDE_VERSION="2.1.88 (Claude Code)" - run_setup --profile=standard >/dev/null 2>&1 || { fail "auto-update-legacy-claude-fallback (setup failed)"; teardown_test_env; unset MOCK_CLAUDE_VERSION; return; } + run_setup --profile=standard >/dev/null 2>&1 || { fail "auto-update-old-claude-same-hooks (setup failed)"; teardown_test_env; unset MOCK_CLAUDE_VERSION; return; } if jq -e ' - any(.hooks.SessionStart[]?.hooks[]?; ((.command? // "") | contains("auto-update")) and ((has("async") | not) or (.async != true))) and - (any(.hooks.SessionEnd[]?.hooks[]?; ((.command? // "") | contains("auto-update"))) | not) - ' "$CLAUDE_DIR/settings.json" >/dev/null 2>&1; then - pass "auto-update-legacy-claude-fallback" + def au($event): + [.hooks[$event][]?.hooks[]? | select((.command? // "") | contains("auto-update.sh"))]; + (au("SessionStart") | length) == 1 and au("SessionStart")[0].async == true + and (au("SessionEnd") | length) == 1 and au("SessionEnd")[0].async == true + ' "$CLAUDE_DIR/settings.json" >/dev/null 2>&1 \ + && assert_file_not_contains "$CLAUDE_DIR/settings.json" "_LEGACY=1"; then + pass "auto-update-old-claude-same-hooks" else - fail "auto-update-legacy-claude-fallback" + fail "auto-update-old-claude-same-hooks" fi unset MOCK_CLAUDE_VERSION @@ -700,6 +705,61 @@ test_update_noninteractive_safe() { teardown_test_env } +# --- 21b. update-migrates-legacy-hooks --- +# An install made by v0.78.x or earlier for Claude Code < 2.1.89 carries a +# second shape of the auto-update and pr-creation-log hooks (retired in v0.79.0, +# #136). With the user's own hooks in the same arrays, a non-interactive update +# must end with exactly one current entry per kit hook and keep the user's. +test_update_migrates_legacy_hooks() { + setup_test_env + run_setup --profile=standard >/dev/null 2>&1 || { fail "update-migrates-legacy-hooks (setup failed)"; teardown_test_env; return; } + + local settings="$CLAUDE_DIR/settings.json" + local snapshot="$CLAUDE_DIR/.starter-kit-snapshot/settings.json" + if ! rewrite_settings_to_legacy_hooks "$settings" \ + || ! rewrite_settings_to_legacy_hooks "$snapshot" \ + || ! jq '.hooks.SessionStart += [{"matcher":"startup","hooks":[{"type":"command","command":"echo user-start"}]}] + | .hooks.PostToolUse += [{"matcher":"Bash","hooks":[{"type":"command","command":"echo user-post"}]}]' \ + "$settings" > "$settings.tmp" \ + || ! mv "$settings.tmp" "$settings" \ + || ! grep -q 'AUTO_UPDATE_LEGACY=1' "$settings" \ + || ! grep -q 'PR_CREATION_LOG_LEGACY=1' "$settings"; then + fail "update-migrates-legacy-hooks (could not stage the legacy install)" + teardown_test_env + return + fi + + local rc=0 + run_setup_update >/dev/null 2>&1 || rc=$? + + if [[ $rc -eq 0 ]] \ + && jq -e ' + def kit($event; $suffix): + [.hooks[$event][]?.hooks[]? | select((.command? // "") | endswith($suffix))]; + def user($event; $command): + [.hooks[$event][]?.hooks[]? | select(.command? == $command)] | length; + kit("SessionStart"; "/auto-update/auto-update.sh") as $start + | kit("SessionEnd"; "/auto-update/auto-update.sh") as $end + | kit("PostToolUse"; "/pr-creation-log/log-pr.sh") as $pr + | ($start | length) == 1 and $start[0].async == true + and ($end | length) == 1 and $end[0].async == true + and ($pr | length) == 1 and $pr[0].async == true + and $pr[0].if == "Bash(gh pr create *)" + and user("SessionStart"; "echo user-start") == 1 + and user("PostToolUse"; "echo user-post") == 1 + ' "$settings" >/dev/null 2>&1 \ + && assert_file_not_contains "$settings" "_LEGACY=1" \ + && assert_file_not_contains "$snapshot" "_LEGACY=1" \ + && jq -e 'any(.hooks.SessionEnd[]?.hooks[]?; (.command? // "") | endswith("/auto-update/auto-update.sh"))' \ + "$snapshot" >/dev/null 2>&1; then + pass "update-migrates-legacy-hooks" + else + fail "update-migrates-legacy-hooks" + fi + + teardown_test_env +} + # ═══════════════════════════════════════════════════════════════════════════ # Bash version scenarios (2) # ═══════════════════════════════════════════════════════════════════════════ @@ -1525,7 +1585,7 @@ run_scenario update test_update_v019_to_latest_direct run_scenario update test_update_partial_failure_recovery run_scenario update test_update_progress_output run_scenario update test_auto_update_session_hooks -run_scenario update test_auto_update_legacy_claude_fallback +run_scenario update test_auto_update_old_claude_same_hooks run_scenario update test_auto_update_preserves_custom_config_binding run_scenario update test_update_kit_command_paths run_scenario update test_update_kit_repo_resolution @@ -1540,6 +1600,7 @@ run_scenario update-merge test_claudemd_section_preserve run_scenario update-merge test_claudemd_kit_edit_conflict run_scenario update-merge test_update_from_v020_customized run_scenario update-merge test_update_noninteractive_safe +run_scenario update-merge test_update_migrates_legacy_hooks run_scenario update-merge test_snapshot_format_v019_to_latest run_scenario update-merge test_snapshot_format_v020_compat run_scenario update-merge test_snapshot_double_marker_repair diff --git a/tests/unit/test-auto-update.sh b/tests/unit/test-auto-update.sh index 7b0c850..02f6fc9 100644 --- a/tests/unit/test-auto-update.sh +++ b/tests/unit/test-auto-update.sh @@ -75,16 +75,6 @@ exit "${MOCK_SETUP_RC:-0}" EOF chmod +x "$mockbin/bash" - cat >"$mockbin/claude" <<'EOF' -#!/bin/bash -if [[ "${1:-}" == "--version" ]]; then - printf '%s\n' "${MOCK_CLAUDE_VERSION_SCRIPT:-2.1.89 (Claude Code)}" - exit 0 -fi -exit 0 -EOF - chmod +x "$mockbin/claude" - env \ HOME="$tmpdir/home" \ PATH="$mockbin:${PATH}" \ @@ -96,8 +86,6 @@ EOF MOCK_GIT_FETCH_RC="${MOCK_GIT_FETCH_RC:-0}" \ MOCK_GIT_PULL_RC="${MOCK_GIT_PULL_RC:-0}" \ MOCK_SETUP_RC="${MOCK_SETUP_RC:-0}" \ - MOCK_CLAUDE_VERSION_SCRIPT="${MOCK_CLAUDE_VERSION_SCRIPT:-2.1.89 (Claude Code)}" \ - AUTO_UPDATE_LEGACY="${AUTO_UPDATE_LEGACY:-0}" \ "$REAL_BASH_BIN" "$AUTO_UPDATE_SCRIPT" } @@ -189,7 +177,6 @@ else fi MOCK_SETUP_RC="0" -rm -f "$_au_tmp/home/.claude/.starter-kit-update-cache" run_auto_update_with_mocks "$_au_tmp" >/dev/null 2>"$_au_tmp/previous-failure.err" || true if assert_matches "Previous auto-update failed: setup\\.sh --update --non-interactive failed" "$(cat "$_au_tmp/previous-failure.err")" \ && assert_file_not_exists "$_au_tmp/home/.claude/.starter-kit-update-status"; then @@ -198,25 +185,28 @@ else fail "auto-update: previous failure should be surfaced once" fi -# Legacy Claude Code should keep 24h cache behavior. -rm -f "$_au_tmp/home/.claude/.starter-kit-update-cache" +# The 24h cache of the retired < 2.1.89 path is gone: a leftover legacy hook +# entry (AUTO_UPDATE_LEGACY=1) and a fresh cache file must neither throttle the +# check nor be written to. +_au_cache="$_au_tmp/home/.claude/.starter-kit-update-cache" +# One minute old: fresh for the former 24h TTL, yet any rewrite changes it. +printf '%s\n' "$(( $(date +%s) - 60 ))" > "$_au_cache" +_au_cache_before="$(cat "$_au_cache")" : > "$_au_tmp/git.log" -MOCK_CLAUDE_VERSION_SCRIPT="2.1.88 (Claude Code)" -AUTO_UPDATE_LEGACY=1 MOCK_LOCAL_VER="v0.1.0" MOCK_REMOTE_VER="v0.1.0" -run_auto_update_with_mocks "$_au_tmp" >/dev/null 2>&1 || true -first_legacy_git_log="$(cat "$_au_tmp/git.log")" +AUTO_UPDATE_LEGACY=1 run_auto_update_with_mocks "$_au_tmp" >/dev/null 2>&1 || true +_au_first_git_log="$(cat "$_au_tmp/git.log")" : > "$_au_tmp/git.log" -run_auto_update_with_mocks "$_au_tmp" >/dev/null 2>&1 || true -if assert_matches "fetch --tags --quiet" "$first_legacy_git_log" \ - && assert_empty "$(cat "$_au_tmp/git.log")"; then - pass "auto-update: legacy Claude Code keeps 24h cache behavior" +AUTO_UPDATE_LEGACY=1 run_auto_update_with_mocks "$_au_tmp" >/dev/null 2>&1 || true +if assert_matches "fetch --tags --quiet" "$_au_first_git_log" \ + && assert_matches "fetch --tags --quiet" "$(cat "$_au_tmp/git.log")" \ + && assert_equals "$_au_cache_before" "$(cat "$_au_cache")"; then + pass "auto-update: AUTO_UPDATE_LEGACY and a fresh update cache no longer throttle the check" else - fail "auto-update: legacy Claude Code should skip repeated checks within cache TTL" + fail "auto-update: the retired 24h cache must not skip or record an update check" fi -unset MOCK_CLAUDE_VERSION_SCRIPT -AUTO_UPDATE_LEGACY=0 +rm -f "$_au_cache" # Hook fragment should expose both async session-boundary hooks. if jq -e ' @@ -238,8 +228,6 @@ if [[ "${1:-}" == "--version" ]]; then fi EOF chmod +x "$_au_tmp/claude-current-bin/claude" -_CLAUDE_SEMVER_CACHE="" -_CLAUDE_SEMVER_CACHE_SET=false PATH="$_au_tmp/claude-current-bin:$PATH" build_settings_file "$_au_settings" >/dev/null if jq -e ' any(.hooks.SessionStart[]?; .matcher == "startup" and any(.hooks[]?; .async == true and .asyncTimeout == 300000 and (.command | contains("auto-update.sh")))) and @@ -250,27 +238,62 @@ else fail "auto-update: merged settings should include async SessionStart and SessionEnd hooks with timeout" fi -# Older Claude Code should fall back to SessionStart-only without async. -_au_legacy_settings="$_au_tmp/auto-update-legacy-settings.json" -mkdir -p "$_au_tmp/claude-legacy-bin" -cat >"$_au_tmp/claude-legacy-bin/claude" <<'EOF' +# The hook shape no longer depends on the installed Claude Code (legacy path +# retired in v0.79.0, #136): a current CLI, an older one and one whose version +# cannot be parsed all get byte-identical settings, and building never starts +# `claude`. Each build runs in a fresh process so no shell state carried over +# from an earlier build can make the variants agree. +_au_spy_log="$_au_tmp/claude-spy.log" +: > "$_au_spy_log" +mkdir -p "$_au_tmp/claude-spy-bin" +cat >"$_au_tmp/claude-spy-bin/claude" <<'EOF' #!/bin/bash -if [[ "${1:-}" == "--version" ]]; then - printf '%s\n' '2.1.88 (Claude Code)' -fi +printf '%s\n' "$*" >> "${AU_CLAUDE_SPY_LOG:?}" +printf '%s\n' "${AU_CLAUDE_SPY_VERSION:?}" EOF -chmod +x "$_au_tmp/claude-legacy-bin/claude" -_CLAUDE_SEMVER_CACHE="" -_CLAUDE_SEMVER_CACHE_SET=false -PATH="$_au_tmp/claude-legacy-bin:$PATH" build_settings_file "$_au_legacy_settings" >/dev/null -if jq -e ' - any(.hooks.SessionStart[]?; .matcher == "startup" and any(.hooks[]?; (.command | contains("AUTO_UPDATE_LEGACY=1")) and (.command | contains("auto-update.sh")))) and - (any(.hooks.SessionEnd[]?.hooks[]?; ((.command? // "") | contains("auto-update.sh"))) | not) and - (any(.hooks.SessionStart[]?.hooks[]?; .async == true) | not) -' "$_au_legacy_settings" >/dev/null 2>&1; then - pass "auto-update: legacy Claude Code falls back to SessionStart without async" +chmod +x "$_au_tmp/claude-spy-bin/claude" + +_au_build_fresh() { # + AU_CLAUDE_SPY_LOG="$_au_spy_log" AU_CLAUDE_SPY_VERSION="$1" \ + HOME="$_au_tmp/home" PATH="$_au_tmp/claude-spy-bin:$PATH" \ + "$BASH" -c ' + set -euo pipefail + PROJECT_DIR="$1" + _SETUP_TMP_FILES=() + _au_child_cleanup() { + [[ "${#_SETUP_TMP_FILES[@]}" -eq 0 ]] || rm -rf "${_SETUP_TMP_FILES[@]}" + } + trap _au_child_cleanup EXIT + source "$PROJECT_DIR/lib/colors.sh" + source "$PROJECT_DIR/lib/features.sh" + source "$PROJECT_DIR/lib/template.sh" + source "$PROJECT_DIR/lib/json-builder.sh" + source "$PROJECT_DIR/lib/snapshot.sh" + source "$PROJECT_DIR/lib/merge.sh" + source "$PROJECT_DIR/lib/dryrun.sh" + source "$PROJECT_DIR/lib/deploy.sh" + source "$PROJECT_DIR/profiles/standard.conf" + LANGUAGE=en + build_settings_file "$2" >/dev/null + ' au-build-fresh "$PROJECT_DIR" "$2" +} + +_au_version_independent=true +_au_build_fresh "2.1.89 (Claude Code)" "$_au_tmp/fresh-current.json" \ + || _au_version_independent=false +_au_build_fresh "2.1.88 (Claude Code)" "$_au_tmp/fresh-old.json" \ + || _au_version_independent=false +_au_build_fresh "not a version" "$_au_tmp/fresh-unparsable.json" \ + || _au_version_independent=false +if [[ "$_au_version_independent" == "true" ]] \ + && jq -e 'any(.hooks.SessionEnd[]?.hooks[]?; .async == true and (.command | contains("auto-update.sh")))' \ + "$_au_tmp/fresh-current.json" >/dev/null 2>&1 \ + && cmp -s "$_au_tmp/fresh-current.json" "$_au_tmp/fresh-old.json" \ + && cmp -s "$_au_tmp/fresh-current.json" "$_au_tmp/fresh-unparsable.json" \ + && [[ ! -s "$_au_spy_log" ]]; then + pass "auto-update: build_settings_file does not depend on the installed Claude Code version" else - fail "auto-update: legacy Claude Code should fall back to SessionStart without async" + fail "auto-update: build_settings_file must emit one hook shape without starting claude (claude ran $(wc -l < "$_au_spy_log" | tr -d ' ') time(s))" fi # ── _check_auto_update_health: hook detection ────────────────────────────── @@ -291,8 +314,8 @@ source "$PROJECT_DIR/lib/update.sh" _auh_home="$_au_tmp/auh-home" mkdir -p "$_auh_home/.claude-starter-kit/.git" -_auh_run() { # -> health check output - local body="$1" async="$2" dir +_auh_run() { # -> health check output + local body="$1" dir dir="$(mktemp -d "$_au_tmp/auh-XXXXXX")" printf '%s' "$body" > "$dir/settings.json" # shellcheck disable=SC2034 # STR_* are read by _check_auto_update_health @@ -304,7 +327,6 @@ _auh_run() { # -> health check output STR_AUTOUPDATE_NO_REPO="NOREPO" STR_AUTOUPDATE_OUTDATED="OUTDATED" STR_AUTOUPDATE_OK="ACTIVE" - _claude_supports_async_hooks() { [[ "$async" == "true" ]]; } info() { printf '%s\n' "$*"; } ok() { printf '%s\n' "$*"; } _check_auto_update_health "$dir" @@ -318,14 +340,14 @@ _auh_end_au='{"matcher":"*","hooks":[{"type":"command","command":"AUTO_UPDATE_HO _auh_end_other='{"matcher":"*","hooks":[{"type":"command","command":"echo bye"}]}' # The regression itself: auto-update registered, another hook after it. -_auh_out="$(_auh_run "{\"hooks\":{\"SessionStart\":[$_auh_start_au,$_auh_start_other],\"SessionEnd\":[$_auh_end_au]}}" true)" +_auh_out="$(_auh_run "{\"hooks\":{\"SessionStart\":[$_auh_start_au,$_auh_start_other],\"SessionEnd\":[$_auh_end_au]}}")" if [[ "$_auh_out" != *NOHOOK* ]] && [[ "$_auh_out" == *ACTIVE* ]]; then pass "auto-update health: a hook registered after auto-update is not read as missing" else fail "auto-update health: trailing SessionStart hook must not fake a missing registration (got '$_auh_out')" fi -_auh_out="$(_auh_run "{\"hooks\":{\"SessionStart\":[$_auh_start_other,$_auh_start_au],\"SessionEnd\":[$_auh_end_au]}}" true)" +_auh_out="$(_auh_run "{\"hooks\":{\"SessionStart\":[$_auh_start_other,$_auh_start_au],\"SessionEnd\":[$_auh_end_au]}}")" if [[ "$_auh_out" != *NOHOOK* ]]; then pass "auto-update health: detection is independent of position in the array" else @@ -334,44 +356,75 @@ fi # A hook entry with no `command` key aborts an unguarded filter with jq exit 5, # which looks exactly like "absent" once the status is discarded. -_auh_out="$(_auh_run "{\"hooks\":{\"SessionStart\":[$_auh_start_nocmd,$_auh_start_au],\"SessionEnd\":[$_auh_end_au]}}" true)" +_auh_out="$(_auh_run "{\"hooks\":{\"SessionStart\":[$_auh_start_nocmd,$_auh_start_au],\"SessionEnd\":[$_auh_end_au]}}")" if [[ "$_auh_out" != *NOHOOK* ]]; then pass "auto-update health: an entry without a command does not hide the registration" else fail "auto-update health: commandless entry must not abort the probe (got '$_auh_out')" fi -_auh_out="$(_auh_run "{\"hooks\":{\"SessionStart\":[$_auh_start_other]}}" true)" +_auh_out="$(_auh_run "{\"hooks\":{\"SessionStart\":[$_auh_start_other]}}")" if [[ "$_auh_out" == *NOHOOK* ]]; then pass "auto-update health: a genuinely absent hook is still reported" else fail "auto-update health: missing auto-update must warn (got '$_auh_out')" fi -_auh_out="$(_auh_run '{}' true)" +_auh_out="$(_auh_run '{}')" if [[ "$_auh_out" == *NOHOOK* ]]; then pass "auto-update health: settings with no hooks at all is reported" else fail "auto-update health: empty settings must warn (got '$_auh_out')" fi -# SessionEnd is only required on a Claude Code that supports async hooks. -_auh_out="$(_auh_run "{\"hooks\":{\"SessionStart\":[$_auh_start_au,$_auh_start_other],\"SessionEnd\":[$_auh_end_other]}}" true)" +# SessionEnd is always required, whichever hook follows auto-update. +_auh_out="$(_auh_run "{\"hooks\":{\"SessionStart\":[$_auh_start_au,$_auh_start_other],\"SessionEnd\":[$_auh_end_other]}}")" if [[ "$_auh_out" == *NOHOOK* ]]; then - pass "auto-update health: a missing SessionEnd hook is reported on async-capable CLIs" + pass "auto-update health: a missing SessionEnd hook is reported" else fail "auto-update health: SessionEnd probe must not inherit the SessionStart answer (got '$_auh_out')" fi -_auh_out="$(_auh_run "{\"hooks\":{\"SessionStart\":[$_auh_start_au,$_auh_start_other],\"SessionEnd\":[$_auh_end_other]}}" false)" -if [[ "$_auh_out" != *NOHOOK* ]]; then - pass "auto-update health: legacy CLIs are not asked for a SessionEnd hook" +# The kit ships a single hook shape, so that answer must not change with the +# installed CLI: an old one on PATH used to switch the SessionEnd requirement +# off. A fresh process keeps shell state from the builds above out of it. +mkdir -p "$_au_tmp/auh-old-cli" +: > "$_au_spy_log" +printf '%s'"{\"hooks\":{\"SessionStart\":[$_auh_start_au],\"SessionEnd\":[$_auh_end_other]}}" \ + > "$_au_tmp/auh-old-cli/settings.json" +_auh_out="$( + AU_CLAUDE_SPY_LOG="$_au_spy_log" AU_CLAUDE_SPY_VERSION="2.1.88 (Claude Code)" \ + HOME="$_auh_home" PATH="$_au_tmp/claude-spy-bin:$PATH" \ + "$BASH" -c ' + set -euo pipefail + PROJECT_DIR="$1" + _SETUP_TMP_FILES=() + source "$PROJECT_DIR/lib/colors.sh" + source "$PROJECT_DIR/lib/features.sh" + source "$PROJECT_DIR/lib/template.sh" + source "$PROJECT_DIR/lib/json-builder.sh" + source "$PROJECT_DIR/lib/snapshot.sh" + source "$PROJECT_DIR/lib/merge.sh" + source "$PROJECT_DIR/lib/dryrun.sh" + source "$PROJECT_DIR/lib/deploy.sh" + source "$PROJECT_DIR/lib/update.sh" + STR_AUTOUPDATE_NO_HOOK="NOHOOK" + STR_AUTOUPDATE_NOTICE="NOTICE" + STR_AUTOUPDATE_HINT_HOOK="HINT" + STR_AUTOUPDATE_OK="ACTIVE" + info() { printf "%s\n" "$*"; } + ok() { printf "%s\n" "$*"; } + _check_auto_update_health "$2" + ' auh-old-cli "$PROJECT_DIR" "$_au_tmp/auh-old-cli" 2>&1 +)" || true +if [[ "$_auh_out" == *NOHOOK* ]] && [[ ! -s "$_au_spy_log" ]]; then + pass "auto-update health: the SessionEnd requirement does not depend on the installed CLI" else - fail "auto-update health: SessionEnd must not be required without async support (got '$_auh_out')" + fail "auto-update health: an old CLI on PATH must not relax the SessionEnd requirement (got '$_auh_out')" fi # An unreadable answer is not an answer: claim neither failure nor health. -_auh_out="$(_auh_run '{"hooks": ' true)" +_auh_out="$(_auh_run '{"hooks": ')" if [[ "$_auh_out" != *NOHOOK* ]] && [[ "$_auh_out" != *ACTIVE* ]]; then pass "auto-update health: an unparseable settings.json reports neither state" else diff --git a/tests/unit/test-deploy-refactor.sh b/tests/unit/test-deploy-refactor.sh index dcec8e7..5a518f2 100644 --- a/tests/unit/test-deploy-refactor.sh +++ b/tests/unit/test-deploy-refactor.sh @@ -47,18 +47,6 @@ source "$PROJECT_DIR/lib/deploy.sh" unset _wce_validator_source _wce_validator_quote_count } -{ - test_name="deploy-refactor: version comparison preserves numeric triples" - if _version_ge 2.1.0 2.0.99 \ - && ! _version_ge 2.0.99 2.1.0 \ - && _version_ge 1.2 1.2.0 \ - && _version_ge 1.2.3.4 1.2.3.9; then - pass "$test_name" - else - fail "$test_name" - fi -} - { test_name="deploy-refactor: build_claude_md delegates to build_claude_md_to_file" if grep -q 'build_claude_md_to_file "$out"' "$PROJECT_DIR/lib/deploy.sh" \ @@ -69,38 +57,6 @@ source "$PROJECT_DIR/lib/deploy.sh" fi } -{ - test_name="deploy-refactor: Claude semver lookup is cached" - _semver_tmp="$(mktemp -d)" - _SETUP_TMP_FILES+=("$_semver_tmp") - cat >"$_semver_tmp/claude" <<'EOF' -#!/bin/bash -count_file="${CLAUDE_VERSION_COUNT_FILE:?}" -count="$(cat "$count_file" 2>/dev/null || echo 0)" -count=$((count + 1)) -printf '%s\n' "$count" > "$count_file" -printf 'Claude Code 2.1.90\n' -EOF - chmod +x "$_semver_tmp/claude" - CLAUDE_VERSION_COUNT_FILE="$_semver_tmp/count" - export CLAUDE_VERSION_COUNT_FILE - _old_path="$PATH" - PATH="$_semver_tmp:$PATH" - hash -r 2>/dev/null || true - _CLAUDE_SEMVER_CACHE="" - _CLAUDE_SEMVER_CACHE_SET=false - printf '0\n' > "$CLAUDE_VERSION_COUNT_FILE" - _claude_cli_semver >/dev/null - _claude_cli_semver >/dev/null - PATH="$_old_path" - hash -r 2>/dev/null || true - if [[ "$(cat "$CLAUDE_VERSION_COUNT_FILE")" == "1" ]]; then - pass "$test_name" - else - fail "$test_name" - fi -} - { test_name="deploy-refactor: migrated CLAUDE.md composition preserves kit and user sections" _kit_file="$(mktemp)" diff --git a/tests/unit/test-hook-fixtures.sh b/tests/unit/test-hook-fixtures.sh index be57029..286a538 100644 --- a/tests/unit/test-hook-fixtures.sh +++ b/tests/unit/test-hook-fixtures.sh @@ -197,7 +197,7 @@ printf 'fixture-previous-failure\n' >"$_auf_home/.claude/.starter-kit-update-sta _auf_rc=0 HOME="$_auf_home" KIT_DIR="$_auf_home/.claude-starter-kit-missing" \ - AUTO_UPDATE_HOOK=SessionStart AUTO_UPDATE_LEGACY=0 \ + AUTO_UPDATE_HOOK=SessionStart \ bash "$PROJECT_DIR/features/auto-update/scripts/auto-update.sh" \ <"$_hook_fixture_dir/sessionstart-startup.json" >/dev/null 2>"$_auf_err" || _auf_rc=$? diff --git a/tests/unit/test-mdm-expected.sh b/tests/unit/test-mdm-expected.sh index 94d29b3..1ad0537 100644 --- a/tests/unit/test-mdm-expected.sh +++ b/tests/unit/test-mdm-expected.sh @@ -14,7 +14,7 @@ local _profile_override_render _safety_override_render _biome_override_render local _policy_base _policy_peer _policy_hash _peer_hash _policy_variant local _policy_drift_fail _variant_hash _policy_check _variant_output local _variant_args _oracle_log _renderer_policy_args _missing_arg_fail -local _c1_first _c1_last _c1_rejected +local _c1_first _c1_last _c1_rejected _pr_hook_check _expected_tmp="$(mktemp -d)" chmod 700 "$_expected_tmp" _renderer_policy_args=(--editor none --claude-cli-required true) @@ -72,7 +72,6 @@ if [[ "$profile/$language" == standard/ja ]]; then fi LANGUAGE="$language" KIT_MDM_MANAGED=true -KIT_MDM_ASYNC_HOOKS=false _SETUP_TMP_FILES=() source "$PROJECT_DIR/lib/features.sh" source "$PROJECT_DIR/lib/template.sh" @@ -209,6 +208,36 @@ else fail "mdm-expected: settings.json differs from the shell builder" fi +# The hook shape once pinned for Claude Code < 2.1.89 is retired (#136): an +# MDM deployment carries the same pr-creation-log entry as a normal install. +_pr_hook_check="$($PYTHON - "$_renderer_output/tree/settings.json" <<'PY' +import json +import sys +with open(sys.argv[1], encoding="utf-8") as source: + raw = source.read() +hooks = [ + hook + for entry in json.loads(raw).get("hooks", {}).get("PostToolUse", []) + for hook in entry.get("hooks", []) + if hook.get("command", "").endswith("/.claude/hooks/pr-creation-log/log-pr.sh") +] +valid = ( + len(hooks) == 1 + and hooks[0].get("command") + == "/Users/mdm-fixture/.claude/hooks/pr-creation-log/log-pr.sh" + and hooks[0].get("if") == "Bash(gh pr create *)" + and hooks[0].get("async") is True + and "_LEGACY=" not in raw +) +print("yes" if valid else "no") +PY +)" +if [[ "$_pr_hook_check" == yes ]]; then + pass "mdm-expected: pr-creation-log is rendered in the current if/async hook shape" +else + fail "mdm-expected: pr-creation-log hook is not in the current if/async shape" +fi + if cmp -s "$_shell_claude" "$_renderer_output/tree/CLAUDE.md" \ && [[ "$(tail -c 1 "$_renderer_output/tree/CLAUDE.md" | od -An -tuC | tr -d ' ')" == 10 ]]; then pass "mdm-expected: CLAUDE.md managed section has strict byte parity and trailing LF" @@ -267,7 +296,7 @@ with open(sys.argv[1], encoding="utf-8") as source: valid = ( value.get("profile") == "standard" and value.get("language") == "ja" - and value.get("async_hooks") is False + and "async_hooks" not in value and value.get("files") == sorted(value.get("files", [])) and value.get("absent_files") == sorted(value.get("absent_files", [])) and not set(value.get("files", [])).intersection(value.get("absent_files", [])) diff --git a/tests/unit/test-pr-creation-log.sh b/tests/unit/test-pr-creation-log.sh index 86ba5f6..428b3c2 100644 --- a/tests/unit/test-pr-creation-log.sh +++ b/tests/unit/test-pr-creation-log.sh @@ -21,18 +21,15 @@ source "$PROJECT_DIR/lib/deploy.sh" _pr_tmp="$(mktemp -d)" _SETUP_TMP_FILES+=("$_pr_tmp") _pr_hooks="$PROJECT_DIR/features/pr-creation-log/hooks.json" -_pr_legacy_hooks="$PROJECT_DIR/features/pr-creation-log/hooks.legacy.json" _pr_settings="$_pr_tmp/settings.json" # shellcheck disable=SC2034 # build_settings_file reads feature flags via indirect expansion ENABLE_PR_CREATION_LOG="true" if jq -e '.hooks.PostToolUse[0].hooks[0].if == "Bash(gh pr create *)"' "$_pr_hooks" >/dev/null 2>&1 \ - && jq -e '.hooks.PostToolUse[0].hooks[0].async == true' "$_pr_hooks" >/dev/null 2>&1 \ - && jq -e '.hooks.PostToolUse[0].hooks[0] | has("if") | not' "$_pr_legacy_hooks" >/dev/null 2>&1 \ - && jq -e '.hooks.PostToolUse[0].hooks[0] | has("async") | not' "$_pr_legacy_hooks" >/dev/null 2>&1; then - pass "pr-creation-log: modern and legacy hook fragments are split correctly" + && jq -e '.hooks.PostToolUse[0].hooks[0].async == true' "$_pr_hooks" >/dev/null 2>&1; then + pass "pr-creation-log: hook fragment declares if and async" else - fail "pr-creation-log: modern and legacy hook fragments should be split correctly" + fail "pr-creation-log: hook fragment should declare if and async" fi _pr_command="$(jq -r '.hooks.PostToolUse[0].hooks[0].command' "$_pr_hooks")" @@ -47,13 +44,13 @@ fi # Select this feature's entry by its command, never by matcher. # `.hooks.PostToolUse[] | select(.matcher == "Bash")` emits one output per # matching entry and `jq -e` derives its exit code from the LAST one, so a -# second Bash-matcher PostToolUse hook would silently decide the verdict — and -# for the negated legacy checks it would decide it as a PASS, masking exactly -# the regression they exist to catch. Collect first, then assert on the whole -# set: `length == 1` pins the entry and `all(...)` is the correct collapse for -# a negated condition (`any(...)` would still pass on a regressed first entry). -# Selection walks the PARENT PostToolUse entries (not the inner hooks) so the -# matcher stays visible: this feature must remain bound to matcher "Bash". +# second Bash-matcher PostToolUse hook would silently decide the verdict, +# masking exactly the regression this check exists to catch. Collect first, +# then assert on the whole set: `length == 1` pins the entry and `all(...)` +# cannot be satisfied by some other entry (`any(...)` would still pass on a +# regressed pr-creation-log entry). Selection walks the PARENT PostToolUse +# entries (not the inner hooks) so the matcher stays visible: this feature must +# remain bound to matcher "Bash". _pr_entries='[.hooks.PostToolUse[]? | select(any(.hooks[]?; (.command? // "") | contains("pr-creation-log/log-pr.sh")))]' @@ -66,15 +63,6 @@ _pr_modern_hook_ok() { # "$1" >/dev/null 2>&1 } -_pr_legacy_hook_ok() { # - jq -e "$_pr_entries - | length == 1 - and all(.matcher == \"Bash\" - and (.hooks | length == 1) - and all(.hooks[]; (has(\"if\") | not) and (has(\"async\") | not)))" \ - "$1" >/dev/null 2>&1 -} - build_settings_json \ "$PROJECT_DIR/config/settings-base.json" \ "$PROJECT_DIR/config/permissions.json" \ @@ -87,61 +75,71 @@ else fail "pr-creation-log: merged settings should keep if condition and async execution" fi -_pr_supported_settings="$_pr_tmp/settings-supported.json" -mkdir -p "$_pr_tmp/claude-current-bin" -cat >"$_pr_tmp/claude-current-bin/claude" <<'EOF' +# The hook shape does not depend on the installed Claude Code (the < 2.1.89 +# fallback fragment was retired in v0.79.0, #136). The old CLI is built first so +# this case does not lean on anything an earlier build left in the shell. +_pr_old_cli_settings="$_pr_tmp/settings-old-cli.json" +mkdir -p "$_pr_tmp/claude-old-bin" +cat >"$_pr_tmp/claude-old-bin/claude" <<'EOF' #!/bin/bash if [[ "${1:-}" == "--version" ]]; then - printf '%s\n' '2.1.89 (Claude Code)' + printf '%s\n' '2.1.88 (Claude Code)' fi EOF -chmod +x "$_pr_tmp/claude-current-bin/claude" -_CLAUDE_SEMVER_CACHE="" -_CLAUDE_SEMVER_CACHE_SET=false -PATH="$_pr_tmp/claude-current-bin:$PATH" build_settings_file "$_pr_supported_settings" >/dev/null +chmod +x "$_pr_tmp/claude-old-bin/claude" +PATH="$_pr_tmp/claude-old-bin:$PATH" build_settings_file "$_pr_old_cli_settings" >/dev/null -if _pr_modern_hook_ok "$_pr_supported_settings"; then - pass "pr-creation-log: supported Claude Code gets if/async hook" +if _pr_modern_hook_ok "$_pr_old_cli_settings" \ + && ! grep -q 'PR_CREATION_LOG_LEGACY' "$_pr_old_cli_settings"; then + pass "pr-creation-log: an old Claude Code gets the same if/async hook" else - fail "pr-creation-log: supported Claude Code should get if/async hook" + fail "pr-creation-log: the hook shape must not depend on the installed Claude Code" fi -_pr_legacy_settings="$_pr_tmp/settings-legacy.json" -mkdir -p "$_pr_tmp/claude-legacy-bin" -cat >"$_pr_tmp/claude-legacy-bin/claude" <<'EOF' +_pr_supported_settings="$_pr_tmp/settings-supported.json" +mkdir -p "$_pr_tmp/claude-current-bin" +cat >"$_pr_tmp/claude-current-bin/claude" <<'EOF' #!/bin/bash if [[ "${1:-}" == "--version" ]]; then - printf '%s\n' '2.1.88 (Claude Code)' + printf '%s\n' '2.1.89 (Claude Code)' fi EOF -chmod +x "$_pr_tmp/claude-legacy-bin/claude" -_CLAUDE_SEMVER_CACHE="" -_CLAUDE_SEMVER_CACHE_SET=false -PATH="$_pr_tmp/claude-legacy-bin:$PATH" build_settings_file "$_pr_legacy_settings" >/dev/null +chmod +x "$_pr_tmp/claude-current-bin/claude" +PATH="$_pr_tmp/claude-current-bin:$PATH" build_settings_file "$_pr_supported_settings" >/dev/null -if _pr_legacy_hook_ok "$_pr_legacy_settings"; then - pass "pr-creation-log: legacy Claude Code falls back to legacy hook fragment" +if _pr_modern_hook_ok "$_pr_supported_settings" \ + && cmp -s "$_pr_supported_settings" "$_pr_old_cli_settings"; then + pass "pr-creation-log: supported Claude Code gets if/async hook" else - fail "pr-creation-log: legacy Claude Code should fall back to legacy hook fragment" + fail "pr-creation-log: supported Claude Code should get if/async hook" fi -# The arity guard itself. Append a second Bash-matcher PostToolUse entry and -# regress the pr-creation-log one to the modern shape: the legacy assertion -# must now fail. The old `select(.matcher == "Bash") | .hooks[0] | has("if") | -# not` filter returns 0 here (the appended entry is the last output), and so -# does an `any(...)` rewrite — only selecting by command and collapsing with -# `all(...)` reports the regression. +# The arity guard itself. Regress the pr-creation-log entry (no `if`, no +# `async`) and append a second Bash-matcher PostToolUse entry that does carry +# both: the assertion must now fail. A `select(.matcher == "Bash") | .hooks[0] +# | .if == ...` filter returns 0 here (the appended entry is the last output), +# and so does an `any(...)` rewrite — only selecting by command and collapsing +# with `all(...)` reports the regression. The reverse arrangement (intact +# entry, unrelated second hook without `if`) must keep passing. _pr_arity_settings="$_pr_tmp/settings-two-bash.json" +jq '.hooks.PostToolUse = [ + {"matcher":"Bash","hooks":[{"type":"command", + "command":"__HOME__/.claude/hooks/pr-creation-log/log-pr.sh"}]}, + {"matcher":"Bash","hooks":[{"type":"command", + "command":"/somewhere/future-hook.sh", + "if":"Bash(gh pr create *)","async":true}]} + ]' "$_pr_supported_settings" > "$_pr_arity_settings" +_pr_arity_ok_settings="$_pr_tmp/settings-two-bash-ok.json" jq '.hooks.PostToolUse = [ {"matcher":"Bash","hooks":[{"type":"command", "command":"__HOME__/.claude/hooks/pr-creation-log/log-pr.sh", "if":"Bash(gh pr create *)","async":true}]}, {"matcher":"Bash","hooks":[{"type":"command", "command":"/somewhere/future-hook.sh"}]} - ]' "$_pr_legacy_settings" > "$_pr_arity_settings" + ]' "$_pr_supported_settings" > "$_pr_arity_ok_settings" -if ! _pr_legacy_hook_ok "$_pr_arity_settings" \ - && _pr_modern_hook_ok "$_pr_arity_settings"; then +if ! _pr_modern_hook_ok "$_pr_arity_settings" \ + && _pr_modern_hook_ok "$_pr_arity_ok_settings"; then pass "pr-creation-log: a second Bash-matcher hook cannot decide the verdict" else fail "pr-creation-log: assertions must select this feature's entry by command" diff --git a/tests/unit/test-retired-hooks.sh b/tests/unit/test-retired-hooks.sh index ded9ff1..453eec6 100644 --- a/tests/unit/test-retired-hooks.sh +++ b/tests/unit/test-retired-hooks.sh @@ -298,4 +298,267 @@ printf '%s\n' '{ fi } +# ── _migrate_legacy_hook_entries ─────────────────────────────────────────── +# +# Until v0.78.x the kit generated a second shape of the auto-update and +# pr-creation-log hooks for Claude Code < 2.1.89 (hooks.legacy.json, retired +# in v0.79.0 / #136). Their commands carry an env prefix, so they are a +# different identity from the current entries and neither the 3-way merge nor +# the two sweeps above can pair them. +_rh_migrate() { # + HOME=/home/u "${BASH:-bash}" -c ' + set -uo pipefail + PROJECT_DIR="'"$PROJECT_DIR"'" + ok(){ :; }; warn(){ :; }; info(){ :; }; is_true(){ [[ "$1" == "true" ]]; } + _SETUP_TMP_FILES=() + source "$PROJECT_DIR/lib/features.sh" + source "$PROJECT_DIR/lib/snapshot.sh" + source "$PROJECT_DIR/lib/update.sh" 2>/dev/null || true + _migrate_legacy_hook_entries "'"$1"'" "'"$2"'" + ' +} + +_rh_inode() { # -> inode number (a rewrite through mktemp + mv changes it) + # shellcheck disable=SC2012 # one known path; only the inode column is read + ls -i "$1" | awk '{print $1}' +} + +_rh_au='/home/u/.claude/hooks/auto-update/auto-update.sh' +_rh_pr='/home/u/.claude/hooks/pr-creation-log/log-pr.sh' +_rh_h_au_legacy='{"type":"command","command":"AUTO_UPDATE_LEGACY=1 AUTO_UPDATE_HOOK=SessionStart '"$_rh_au"'"}' +_rh_h_au_now='{"type":"command","command":"AUTO_UPDATE_HOOK=SessionStart '"$_rh_au"'","async":true,"asyncTimeout":300000}' +_rh_h_au_end='{"type":"command","command":"AUTO_UPDATE_HOOK=SessionEnd '"$_rh_au"'","async":true,"asyncTimeout":300000}' +_rh_h_pr_legacy='{"type":"command","command":"PR_CREATION_LOG_LEGACY=1 '"$_rh_pr"'"}' +_rh_h_pr_now='{"type":"command","if":"Bash(gh pr create *)","async":true,"command":"'"$_rh_pr"'"}' +_rh_h_user='{"type":"command","command":"echo user-hook"}' +_rh_e_au_legacy='{"matcher":"startup","hooks":['"$_rh_h_au_legacy"']}' +_rh_e_au_now='{"matcher":"startup","hooks":['"$_rh_h_au_now"']}' +_rh_e_au_end='{"matcher":"*","hooks":['"$_rh_h_au_end"']}' +_rh_e_pr_legacy='{"matcher":"Bash","hooks":['"$_rh_h_pr_legacy"']}' +_rh_e_pr_now='{"matcher":"Bash","hooks":['"$_rh_h_pr_now"']}' +_rh_e_user_start='{"matcher":"startup","hooks":['"$_rh_h_user"']}' +_rh_e_user_post='{"matcher":"Bash","hooks":['"$_rh_h_user"']}' + +_rh_lg_kit="$_rh_tmp/legacy-kit.json" +printf '%s\n' '{"hooks":{"SessionStart":['"$_rh_e_au_now"'],"SessionEnd":['"$_rh_e_au_end"'],"PostToolUse":['"$_rh_e_pr_now"']}}' > "$_rh_lg_kit" +_rh_lg_kit_off="$_rh_tmp/legacy-kit-features-off.json" +printf '%s\n' '{"hooks":{"PreToolUse":[{"matcher":"*","hooks":[{"type":"command","command":"safety.sh"}]}]}}' > "$_rh_lg_kit_off" + +{ + test_name="legacy-migration: a legacy entry next to the current one leaves only the current one" + _rh_lg="$_rh_tmp/legacy-dup.json" + printf '%s\n' '{"hooks":{ + "SessionStart":['"$_rh_e_au_legacy"','"$_rh_e_user_start"','"$_rh_e_au_now"'], + "SessionEnd":['"$_rh_e_au_end"'], + "PostToolUse":['"$_rh_e_pr_now"','"$_rh_e_user_post"','"$_rh_e_pr_legacy"']}}' > "$_rh_lg" + _rh_rc=0; _rh_migrate "$_rh_lg" "$_rh_lg_kit" >/dev/null 2>&1 || _rh_rc=$? + if [[ "$_rh_rc" -eq 0 ]] \ + && jq -e --argjson au "$_rh_e_au_now" --argjson pr "$_rh_e_pr_now" \ + --argjson us "$_rh_e_user_start" --argjson up "$_rh_e_user_post" \ + --argjson end "$_rh_e_au_end" ' + .hooks.SessionStart == [$us, $au] + and .hooks.SessionEnd == [$end] + and .hooks.PostToolUse == [$pr, $up]' "$_rh_lg" >/dev/null 2>&1 \ + && ! grep -q '_LEGACY=1' "$_rh_lg"; then + pass "$test_name" + else + fail "$test_name" + fi +} + +{ + test_name="legacy-migration: a legacy-only array (bootstrap merge) becomes the kit's current entry" + _rh_lg="$_rh_tmp/legacy-only.json" + printf '%s\n' '{"hooks":{ + "SessionStart":['"$_rh_e_au_legacy"','"$_rh_e_user_start"'], + "PostToolUse":['"$_rh_e_pr_legacy"']},"env":{"A":"1"}}' > "$_rh_lg" + _rh_rc=0; _rh_migrate "$_rh_lg" "$_rh_lg_kit" >/dev/null 2>&1 || _rh_rc=$? + if [[ "$_rh_rc" -eq 0 ]] \ + && jq -e --slurpfile kit "$_rh_lg_kit" --argjson us "$_rh_e_user_start" ' + .hooks.SessionStart == [$kit[0].hooks.SessionStart[0], $us] + and .hooks.PostToolUse == $kit[0].hooks.PostToolUse + and .env == {"A":"1"}' "$_rh_lg" >/dev/null 2>&1; then + pass "$test_name" + else + fail "$test_name" + fi +} + +{ + test_name="legacy-migration: repeated legacy entries collapse to a single current entry" + _rh_lg="$_rh_tmp/legacy-twice.json" + printf '%s\n' '{"hooks":{"SessionStart":['"$_rh_e_au_legacy"','"$_rh_e_user_start"','"$_rh_e_au_legacy"']}}' > "$_rh_lg" + _rh_rc=0; _rh_migrate "$_rh_lg" "$_rh_lg_kit" >/dev/null 2>&1 || _rh_rc=$? + if [[ "$_rh_rc" -eq 0 ]] \ + && jq -e --argjson au "$_rh_e_au_now" --argjson us "$_rh_e_user_start" ' + .hooks.SessionStart == [$au, $us]' "$_rh_lg" >/dev/null 2>&1; then + pass "$test_name" + else + fail "$test_name" + fi +} + +{ + test_name="legacy-migration: a legacy entry of a feature the kit no longer ships is removed" + _rh_lg="$_rh_tmp/legacy-feature-off.json" + printf '%s\n' '{"hooks":{ + "SessionStart":['"$_rh_e_au_legacy"','"$_rh_e_user_start"'], + "PostToolUse":['"$_rh_e_pr_legacy"'], + "Stop":[]}}' > "$_rh_lg" + _rh_rc=0; _rh_migrate "$_rh_lg" "$_rh_lg_kit_off" >/dev/null 2>&1 || _rh_rc=$? + if [[ "$_rh_rc" -eq 0 ]] \ + && jq -e --argjson us "$_rh_e_user_start" ' + .hooks.SessionStart == [$us] + and (.hooks | has("PostToolUse") | not) + and .hooks.Stop == []' "$_rh_lg" >/dev/null 2>&1; then + pass "$test_name" + else + fail "$test_name" + fi +} + +{ + test_name="legacy-migration: a legacy hook inside a user entry is replaced in place" + _rh_lg="$_rh_tmp/legacy-mixed.json" + printf '%s\n' '{"hooks":{"SessionStart":[{"matcher":"*","hooks":['"$_rh_h_user"','"$_rh_h_au_legacy"']}]}}' > "$_rh_lg" + _rh_lg2="$_rh_tmp/legacy-mixed-with-current.json" + printf '%s\n' '{"hooks":{"SessionStart":[{"matcher":"*","hooks":['"$_rh_h_user"','"$_rh_h_au_legacy"']},'"$_rh_e_au_now"']}}' > "$_rh_lg2" + _rh_rc1=0; _rh_migrate "$_rh_lg" "$_rh_lg_kit" >/dev/null 2>&1 || _rh_rc1=$? + _rh_rc2=0; _rh_migrate "$_rh_lg2" "$_rh_lg_kit" >/dev/null 2>&1 || _rh_rc2=$? + if [[ "$_rh_rc1" -eq 0 && "$_rh_rc2" -eq 0 ]] \ + && jq -e --argjson hu "$_rh_h_user" --argjson hau "$_rh_h_au_now" ' + .hooks.SessionStart == [{"matcher":"*","hooks":[$hu, $hau]}]' "$_rh_lg" >/dev/null 2>&1 \ + && jq -e --argjson hu "$_rh_h_user" --argjson au "$_rh_e_au_now" ' + .hooks.SessionStart == [{"matcher":"*","hooks":[$hu]}, $au]' "$_rh_lg2" >/dev/null 2>&1; then + pass "$test_name" + else + fail "$test_name" + fi +} + +{ + test_name="legacy-migration: unrelated entries in a migrated file are left exactly as they were" + _rh_lg="$_rh_tmp/legacy-bystanders.json" + printf '%s\n' '{"permissions":{"allow":["Read"]},"hooks":{ + "SessionStart":['"$_rh_e_user_start"','"$_rh_e_au_legacy"','"$_rh_e_user_start"',{"matcher":"*.py"}], + "PreToolUse":[{"matcher":"Bash","hooks":[{"type":"command","command":"mine.sh"}]},{"matcher":"Bash","hooks":[{"type":"command","command":"mine.sh"}]}], + "Stop":[]},"statusLine":{"type":"command","command":"x"}}' > "$_rh_lg" + _rh_before="$(jq -cS 'del(.hooks.SessionStart)' "$_rh_lg")" + _rh_rc=0; _rh_migrate "$_rh_lg" "$_rh_lg_kit" >/dev/null 2>&1 || _rh_rc=$? + if [[ "$_rh_rc" -eq 0 \ + && "$(jq -cS 'del(.hooks.SessionStart)' "$_rh_lg")" == "$_rh_before" ]] \ + && jq -e --argjson au "$_rh_e_au_now" --argjson us "$_rh_e_user_start" ' + .hooks.SessionStart == [$us, $au, $us, {"matcher":"*.py"}]' "$_rh_lg" >/dev/null 2>&1; then + pass "$test_name" + else + fail "$test_name" + fi +} + +{ + test_name="legacy-migration: settings without a legacy entry are not rewritten" + _rh_lg="$_rh_tmp/legacy-none.json" + # Compact, key order the kit never writes: any jq round trip changes bytes. + printf '{"hooks":{"SessionStart":[%s,%s],"PostToolUse":[%s]},"env":{"A":"1"}}\n' \ + "$_rh_e_au_now" "$_rh_e_user_start" "$_rh_e_pr_now" > "$_rh_lg" + _rh_before="$(cat "$_rh_lg")" + _rh_inode_before="$(_rh_inode "$_rh_lg")" + _rh_rc=0; _rh_migrate "$_rh_lg" "$_rh_lg_kit" >/dev/null 2>&1 || _rh_rc=$? + if [[ "$_rh_rc" -eq 0 && "$(cat "$_rh_lg")" == "$_rh_before" \ + && "$(_rh_inode "$_rh_lg")" == "$_rh_inode_before" ]]; then + pass "$test_name" + else + fail "$test_name" + fi +} + +{ + test_name="legacy-migration: look-alike commands the kit never generated are untouched" + _rh_lg="$_rh_tmp/legacy-lookalike.json" + printf '{"hooks":{"SessionStart":[{"matcher":"startup","hooks":[%s,%s,%s]}],"PostToolUse":[{"matcher":"Bash","hooks":[%s,%s]}]}}\n' \ + '{"type":"command","command":"AUTO_UPDATE_LEGACY=1 /opt/mine/auto-update.sh"}' \ + '{"type":"command","command":"AUTO_UPDATE_LEGACY=1 AUTO_UPDATE_HOOK=SessionStart /home/other/.claude/hooks/auto-update/auto-update.sh"}' \ + '{"type":"command","command":"AUTO_UPDATE_LEGACY=1 AUTO_UPDATE_HOOK=SessionStart '"$_rh_au"' --verbose"}' \ + '{"type":"command","command":"PR_CREATION_LOG_LEGACY=1 /opt/mine/log-pr.sh"}' \ + '{"type":"command","command":"PR_CREATION_LOG_LEGACY=1 '"$_rh_pr"' && echo done"}' > "$_rh_lg" + _rh_before="$(cat "$_rh_lg")" + _rh_inode_before="$(_rh_inode "$_rh_lg")" + _rh_rc=0; _rh_migrate "$_rh_lg" "$_rh_lg_kit" >/dev/null 2>&1 || _rh_rc=$? + if [[ "$_rh_rc" -eq 0 && "$(cat "$_rh_lg")" == "$_rh_before" \ + && "$(_rh_inode "$_rh_lg")" == "$_rh_inode_before" ]]; then + pass "$test_name" + else + fail "$test_name" + fi +} + +{ + test_name="legacy-migration: a missing or broken kit build or invalid settings changes nothing" + _rh_lg="$_rh_tmp/legacy-safe.json" + printf '{"hooks":{"SessionStart":[%s]}}\n' "$_rh_e_au_legacy" > "$_rh_lg" + printf 'not json' > "$_rh_tmp/legacy-broken-kit.json" + printf '{"hooks": ' > "$_rh_tmp/legacy-broken-settings.json" + _rh_before="$(cat "$_rh_lg")" + _rh_rc1=0; _rh_migrate "$_rh_lg" "$_rh_tmp/no-such-kit.json" >/dev/null 2>&1 || _rh_rc1=$? + _rh_rc2=0; _rh_migrate "$_rh_lg" "$_rh_tmp/legacy-broken-kit.json" >/dev/null 2>&1 || _rh_rc2=$? + _rh_rc3=0; _rh_migrate "$_rh_tmp/legacy-broken-settings.json" "$_rh_lg_kit" >/dev/null 2>&1 || _rh_rc3=$? + if [[ "$_rh_rc1" -eq 0 && "$_rh_rc2" -eq 0 && "$_rh_rc3" -eq 0 \ + && "$(cat "$_rh_lg")" == "$_rh_before" \ + && "$(cat "$_rh_tmp/legacy-broken-settings.json")" == '{"hooks": ' ]]; then + pass "$test_name" + else + fail "$test_name" + fi +} + +# Why a dedicated migration exists: with a user hook in the same array the +# non-interactive 3-way merge keeps the legacy entry as "removed by the kit" +# next to the kit's current one, and neither existing sweep pairs them. +{ + test_name="legacy-migration: merge and existing sweeps keep both generations; the migration heals them" + _rh_m_snap="$_rh_tmp/legacy-merge-snapshot.json" + _rh_m_cur="$_rh_tmp/legacy-merge-current.json" + _rh_m_out="$_rh_tmp/legacy-merge-out.json" + printf '%s\n' '{"hooks":{"SessionStart":['"$_rh_e_au_legacy"'],"PostToolUse":['"$_rh_e_pr_legacy"']}}' > "$_rh_m_snap" + printf '%s\n' '{"hooks":{"SessionStart":['"$_rh_e_au_legacy"','"$_rh_e_user_start"'],"PostToolUse":['"$_rh_e_pr_legacy"','"$_rh_e_user_post"']}}' > "$_rh_m_cur" + cp "$_rh_m_cur" "$_rh_m_out" + _rh_count='[(.hooks.SessionStart[]?.hooks[]?.command? // "" | select(endswith("/auto-update/auto-update.sh"))), + (.hooks.PostToolUse[]?.hooks[]?.command? // "" | select(endswith("/pr-creation-log/log-pr.sh")))] | length' + _rh_rc=0 + HOME=/home/u CLAUDE_DIR="$_rh_tmp/legacy-merge-claude" "${BASH:-bash}" -c ' + set -uo pipefail + PROJECT_DIR="$1" + _SETUP_TMP_FILES=() + _MERGE_INTERACTIVE=false + source "$PROJECT_DIR/lib/colors.sh" + source "$PROJECT_DIR/lib/progress.sh" + source "$PROJECT_DIR/lib/features.sh" + source "$PROJECT_DIR/lib/snapshot.sh" + source "$PROJECT_DIR/lib/merge.sh" + source "$PROJECT_DIR/lib/update.sh" + source "$PROJECT_DIR/i18n/en/strings.sh" + set +e + mkdir -p "$CLAUDE_DIR" + merge_settings_3way "$2" "$3" "$4" "$5" || exit 1 + _strip_retired_hook_entries "$5" || exit 1 + _strip_superseded_kit_hook_generations "$5" "$4" || exit 1 + cp "$5" "$5.before-migration" + _migrate_legacy_hook_entries "$5" "$4" || exit 1 + ' legacy-merge "$PROJECT_DIR" "$_rh_m_snap" "$_rh_m_cur" "$_rh_lg_kit" "$_rh_m_out" \ + >/dev/null 2>&1 || _rh_rc=$? + if [[ "$_rh_rc" -eq 0 ]] \ + && [[ "$(jq -r "$_rh_count" "$_rh_m_out.before-migration" 2>/dev/null)" == "4" ]] \ + && [[ "$(jq -r "$_rh_count" "$_rh_m_out" 2>/dev/null)" == "2" ]] \ + && jq -e --argjson au "$_rh_e_au_now" --argjson pr "$_rh_e_pr_now" \ + --argjson us "$_rh_e_user_start" --argjson up "$_rh_e_user_post" \ + --argjson end "$_rh_e_au_end" ' + (.hooks.SessionStart | sort) == ([$au, $us] | sort) + and .hooks.SessionEnd == [$end] + and (.hooks.PostToolUse | sort) == ([$pr, $up] | sort)' "$_rh_m_out" >/dev/null 2>&1; then + pass "$test_name" + else + fail "$test_name" + fi +} + rm -rf "$_rh_tmp" diff --git a/tests/unit/test-runtime-hooks.sh b/tests/unit/test-runtime-hooks.sh index d8ee9fb..4752469 100644 --- a/tests/unit/test-runtime-hooks.sh +++ b/tests/unit/test-runtime-hooks.sh @@ -57,10 +57,50 @@ fi } +# ── Legacy hook path (Claude Code < 2.1.89) stays retired ─────────────────── +# +# v0.79.0 (#136) removed the second hook shape the kit generated for Claude +# Code < 2.1.89 together with the CLI version gate that selected it. These +# guards keep a later change from quietly bringing either back. { - test_name="auto-update: runtime path no longer spawns claude --version" - if grep -q 'AUTO_UPDATE_LEGACY' "$PROJECT_DIR/features/auto-update/hooks.legacy.json" \ - && ! grep -q '_auto_update_supports_async_hooks' "$PROJECT_DIR/features/auto-update/scripts/auto-update.sh"; then + test_name="legacy hook path: no hooks.legacy.json fragment is shipped" + _lhp_fragments="$(find "$PROJECT_DIR/features" -name 'hooks.legacy*' -print)" + if [[ -z "$_lhp_fragments" ]]; then + pass "$test_name" + else + fail "$test_name (found: $_lhp_fragments)" + fi +} + +{ + test_name="legacy hook path: shipped code has no reference to the retired version gate" + _lhp_gate='_versioned_hooks_fragment|_claude_supports_async_hooks|_claude_cli_semver|_CLAUDE_SEMVER_CACHE|_version_ge|_auto_update_hooks_fragment|_pr_creation_log_hooks_fragment|require_session_end|LEGACY_CACHE_(FILE|TTL)|_auto_update_(legacy_cache_fresh|touch_legacy_cache)|KIT_MDM_ASYNC_HOOKS|async_hooks' + _lhp_markers='hooks\.legacy|AUTO_UPDATE_LEGACY|PR_CREATION_LOG_LEGACY' + # lib/update.sh is the one place that still names the two legacy commands: + # _migrate_legacy_hook_entries has to recognise them to rewrite them. + _lhp_hits="$( + cd "$PROJECT_DIR" && { + grep -rnE "$_lhp_gate|$_lhp_markers" \ + setup.sh install.sh install.ps1 uninstall.sh wizard mdm features \ + config profiles i18n commands 2>/dev/null || true + find lib -type f ! -name update.sh -exec grep -nE "$_lhp_gate|$_lhp_markers" {} + 2>/dev/null || true + grep -nE "$_lhp_gate" lib/update.sh 2>/dev/null || true + } + )" + if [[ -z "$_lhp_hits" ]]; then + pass "$test_name" + else + fail "$test_name (hits: $(printf '%s' "$_lhp_hits" | tr '\n' ';'))" + fi +} + +{ + test_name="legacy hook path: auto-update and pr-creation-log scripts never start claude" + # The bare word only: paths such as ~/.claude and ~/.claude-starter-kit are + # everywhere in these scripts and are not invocations. + if ! grep -nE '(^|[^[:alnum:]_./~-])claude([^[:alnum:]_./-]|$)' \ + "$PROJECT_DIR/features/auto-update/scripts/auto-update.sh" \ + "$PROJECT_DIR/features/pr-creation-log/scripts/log-pr.sh" >/dev/null; then pass "$test_name" else fail "$test_name" diff --git a/tests/unit/test-update-refactor.sh b/tests/unit/test-update-refactor.sh index 7f1f2c0..5ff04ba 100644 --- a/tests/unit/test-update-refactor.sh +++ b/tests/unit/test-update-refactor.sh @@ -428,3 +428,172 @@ MD fail "$test_name (scaffold=$_ust_rc_scaffold content=$_ust_rc_content markerless=$_ust_rc_markerless)" fi } + +# ── Legacy hook shape (Claude Code < 2.1.89) converges on update ──────────── +# +# v0.78.x and earlier generated a second shape of the auto-update and +# pr-creation-log hooks for Claude Code < 2.1.89 (retired in v0.79.0, #136). +# These cases drive the real _update_phase_settings against a real kit build: +# an install that still carries that shape must end up with exactly one current +# entry per hook, user hooks intact, and an install already on the current +# shape must not be rewritten at all. +{ + test_name="update: legacy hook migration runs between the retired and superseded sweeps" + _lgu_order="$(declare -f _update_phase_settings \ + | grep -nE '_strip_retired_hook_entries|_migrate_legacy_hook_entries|_strip_superseded_kit_hook_generations' \ + | sed -E 's/^[0-9]+:[[:space:]]*([A-Za-z_]+).*/\1/' | tr '\n' ' ')" + if [[ "$_lgu_order" == "_strip_retired_hook_entries _migrate_legacy_hook_entries _strip_superseded_kit_hook_generations " ]]; then + pass "$test_name" + else + fail "$test_name (got: $_lgu_order)" + fi +} + +_lgu_tmp="$(mktemp -d)" +_SETUP_TMP_FILES+=("$_lgu_tmp") +_lgu_prepare_rc=0 +( + set +e +u + export HOME="$_lgu_tmp/home" + mkdir -p "$HOME" + # shellcheck source=lib/progress.sh + source "$PROJECT_DIR/lib/progress.sh" + # shellcheck source=i18n/en/strings.sh + source "$PROJECT_DIR/i18n/en/strings.sh" + # shellcheck source=profiles/standard.conf + source "$PROJECT_DIR/profiles/standard.conf" + # shellcheck disable=SC2034 # consumed by the sourced builder and updater + LANGUAGE=en COMMIT_ATTRIBUTION=false KIT_MDM_MANAGED=false DRY_RUN=false + # shellcheck disable=SC2034 # consumed by the sourced merge library + _MERGE_INTERACTIVE=false + + build_settings_file "$_lgu_tmp/kit.json" >/dev/null 2>&1 || exit 1 + cp "$_lgu_tmp/kit.json" "$_lgu_tmp/legacy.json" + rewrite_settings_to_legacy_hooks "$_lgu_tmp/legacy.json" || exit 1 + grep -q 'AUTO_UPDATE_LEGACY=1' "$_lgu_tmp/legacy.json" || exit 1 + grep -q 'PR_CREATION_LOG_LEGACY=1' "$_lgu_tmp/legacy.json" || exit 1 + + _lgu_user='.hooks.SessionStart += [{"matcher":"startup","hooks":[{"type":"command","command":"echo user-start"}]}] + | .hooks.PostToolUse += [{"matcher":"Bash","hooks":[{"type":"command","command":"echo user-post"}]}]' + jq "$_lgu_user" "$_lgu_tmp/legacy.json" > "$_lgu_tmp/legacy-user.json" || exit 1 + jq "$_lgu_user" "$_lgu_tmp/kit.json" > "$_lgu_tmp/kit-user.json" || exit 1 + # What a v0.78.x update left behind once the CLI crossed 2.1.89 with a + # user-touched array: the legacy entries next to the current ones. + jq --slurpfile legacy "$_lgu_tmp/legacy.json" ' + def legacy_entries($event): + [$legacy[0].hooks[$event][] | select(any(.hooks[]; .command | contains("_LEGACY=1")))]; + .hooks.SessionStart += legacy_entries("SessionStart") + | .hooks.PostToolUse += legacy_entries("PostToolUse")' \ + "$_lgu_tmp/kit-user.json" > "$_lgu_tmp/duplicated.json" || exit 1 + + _lgu_case() { #