diff --git a/issues/issue-3604-3864-design-detail.md b/issues/issue-3604-3864-design-detail.md index 2e6b3081f1..fdc9515dba 100644 --- a/issues/issue-3604-3864-design-detail.md +++ b/issues/issue-3604-3864-design-detail.md @@ -243,7 +243,7 @@ Claude Code は利用者・`--settings`・管理・プロジェクトの設定 | --- | --- | --- | --- | | `LOCAL_PREFIXES`・`LOCAL_NAMES` | 定数 | `account_dir.py` | 順に `(".credentials.json", ".claude.json", ".oauth_refresh.lock")`(10 系と同じ。名前は `account_registry` の `CRED_FILE`・`CONFIG_FILE` から引く)・`(".config.json", "backups", "policy-limits.json", "policy-limits.json.stamp.json", "remote-settings.json", "mcp-needs-auth-cache.json", ".ndf-statusline-auth.json", "account.json", "usage.json", ".ndf-shared-base.json", ".ndf-shared-base.next.json", ".ndf-oauth-pending.json")`(10 系に途中の記録と保留の更新を足す。`account.json`・`usage.json`・`.ndf-shared-base.json`・`.ndf-shared-base.next.json`・`.ndf-oauth-pending.json` は `account_registry` の定数から引く。保留の更新を固有にするのは、共有側への symlink にすると別のアカウントの保留を読み書きするため) | | `SHARED_KEYS`・`ONBOARDING_KEYS`・`LOCK_STALE`・`RELOGIN_REASONS` | 定数 | `account_dir.py` | `SHARED_KEYS`・`ONBOARDING_KEYS`: `("projects", "mcpServers")`・`("hasCompletedOnboarding", "lastOnboardingVersion")`。`LOCK_STALE`・`RELOGIN_REASONS`: 順に 10 秒(本体と同じく、これより古い `<実パス>.lock` は残骸として除く)・`("no_refresh", "identity_mismatch", "legacy_config")` | -| 登録の世代 | 設定値 | `account.json` の `generation` | 登録・再登録のたびに新しい乱数の 16 進 32 字(`secrets.token_hex(16)`)。無い旧い記録は空文字の世代として扱う | +| 登録の世代 | 設定値 | `account.json` の `generation` | 登録・再登録のたびに新しい乱数の 16 進 32 字(`secrets.token_hex(16)`)。`generation` を持たない旧い登録の世代は `account_registry.legacy_generation(store, name)` で決める: `"legacy-"` + `sha256(<登録簿の realpath>\0<名前>)` の 16 進の先頭 32 字(状態の保存先を共有する別の登録簿の同じ名前と重ならない)。空文字は「登録が無い」(と、壊れた前の登録の後始末)にだけ使い、旧い登録の世代には使わない。世代を読む側・書く側(使用率のキャッシュのパス、外した間と上限の観測、取得の記録、`settle` の後始末)はどれも `account_registry.generation(store, name)` か `account_registry.load(store, name).generation` で世代を得て、`account.json` の `generation` を直に読まない。同じ旧い登録が呼び手によって別の世代(`_.json` と `legacy-….json`)に分かれないため | | 使用の届け | 設定値 | `<保存先>/.leases/<名前>/<届けの ID>.json` | `{"generation", "state", "owner", "child"}`。`state` は `starting`(用意の済んだ後・子の起動の前)か `running`(子の起動の後)。`owner` と `child` はそれぞれ `{"pid", "start"}`(`start` は `/proc//stat` の開始時刻。pid の使い回しと区別する)で、`child` は `starting` の間 null。ID は `secrets.token_hex(8)` で、`Prepared.lease` か `acquire` の返りが持ち、1 つのラッパーが同じ名前で順に起動しても起動ごとに別である。下の「使用の届けの状態」 | | `REASONS`・`Links`・`Checked` | `REASONS`: 定数。`Links`・`Checked`: 型 | `account_dir.py` | `REASONS`: 理由の符号 → 画面の 1 行の文(値を含まない。例: `no_refresh` → `リフレッシュトークンが空。ndf relay account add {name} で登録し直す`)。`Links`・`Checked`: `Links` は `added: int`・`skipped: list[str]`・`local_only: list[str]`・`projects_shared: bool`。`Checked` は `local: Local`・`resolved: Resolved`(`check_account` の成功の返り。`auth_overrides` の判定に使った `effective_env` の結果) | | `Resolved` | 型 | `account_dir.py` | `env: dict[str, str]`・`origin: dict[str, str]`・`helper: Optional[str]`・`helper_origin: Optional[str]`・`unresolved: list[str]`・`stamps: dict[str, Optional[tuple]]`・`pins: dict[str, Optional[str]]`。`env` は実効値、`origin` は変数ごとの出所。`helper` は実効の `apiKeyHelper` の値(シェルで実行する文字列。無ければ None)で、照合にだけ使い、画面・`log.jsonl`・理由の文・例外の文に出さない(利用者の helper はキーを直に含みうる)。`helper_origin` はその出所(`--settings`・`管理の設定(…)`・`利用者の設定` など。`helper` が None なら None)で、項目名に添えるのはこちらだけ。`unresolved` は解けない源の名前、`stamps` は読んだか探した源のパスごとの `(st_mtime_ns, st_ino, st_size)`(無ければ None。無かった利用者・プロジェクト・ローカルの設定のファイルと `managed-settings.json` も None で持ち、後から作られると印が変わる)。ファイルの集合が変わる源は、ディレクトリの印も持つ。`managed-settings.d` は、在ればそのディレクトリの印(ファイルの追加・削除・名前の変更で `st_mtime_ns` が変わる)を、無ければ親の `/etc/claude-code` の印を持ち、空のディレクトリに最初のファイルが足されたときも、ディレクトリが後から作られたときも当たる。`pins` は読んだか探した設定ファイルのパスごとの `gate_view` の SHA-256 の 16 進(無いファイルは空の object の値。解けないファイルは None)で、キーの子の照合した設定への固定(別冊の「照合した設定への固定」)にだけ使う。型は順に `dict[str, str]`・`dict[str, str]`・`Optional[str]`・`Optional[str]`・`list[str]`・`dict[str, Optional[tuple]]` | @@ -409,7 +409,7 @@ Claude Code が接続先を切り替える提供元の選択の変数は、`CLAU | --- | --- | --- | --- | --- | | `shared_config_dir`・`store_dir`・`mark_relogin`・`generation` | `account_registry.py` | 新設・変更・新設 | `shared_config_dir`・`store_dir` は `shared_config_dir` は `(environ: Mapping[str, str]) -> Path`、`store_dir` は 変わらない、`mark_relogin`・`generation` は `mark_relogin` は `(store: Path, name: str) -> None`、`generation` は `(store: Path, name: str) -> str` | `shared_config_dir`・`store_dir`: `shared_config_dir`: 共有の設定ディレクトリ。`NDF_SHARED_CONFIG_DIR` があればその値(空なら `~/.claude`)、無ければ `signals.claude_config_root(environ)`。`store_dir`: `NDF_ACCOUNTS_DIR` が無ければ `shared_config_dir(environ) / "ndf" / "accounts"`。振る舞いは今と同じ。`mark_relogin`・`generation`: `mark_relogin`: 呼ぶ側が持つアカウントの排他の中で、`account.json` の `needs_relogin` を真にして置き換えで書く。事前条件: `account_registry.locked(store, name)` を持っている(`account_dir.prepare` の中から呼ぶ)。副作用: `account.json` の書き換え(0600)。ほかの項目は変えない。`generation`: `account.json` の `generation`(無ければ空文字) | | 登録(`account add`) | `cli_account.py`・`account_registry.py` | 変更 | 変わらない | 先に同じ名前の取得の排他(`accounts.fetch_lock`)を待って取り、その中で登録の排他を取る(順は「取得の手順と排他」と同じ)。待ちの上限は 1 回の取得が排他を持つ最長(`relay.usage-http` × 2 + `relay.oauth-refresh` + `claude-accounts.lock` の待ち × 4。HTTP の秒は `request_json` の往復全体の期限なので、応答が少しずつ届いても超えない)で、取れなければ何も変えずに `使用率の取得が終わらない。少し待ってから打ち直す` で止める。登録の排他の中で、使用の届けを確かめ(生きていれば止める)、旧形式の `.config.json` を `backups/` へ移し、新しい `generation` を書く。成功の後、取得の排他を持ったまま `accounts.forget(state_dir, store, name, keep=新しい世代)` で外した間と上限の観測から旧い世代の項目を消す。取得の排他を持つ間は取得が資格情報を読まず送らないので、削除・再登録の後に旧い世代のトークンを送る要求が始まらない | -| 削除(`account remove`) | 同上 | 変更 | 変わらない | 登録と同じく取得の排他を待って取ってから、使用の届けを確かめ(生きていれば止める)、今の削除に加えて `accounts.forget(state_dir, store, name, keep=None)` を打つ | +| 削除(`account remove`) | 同上 | 変更 | 変わらない | 登録と同じく取得の排他を待って取ってから、使用の届けを確かめ(生きていれば止める)、今の削除に加えて `accounts.forget(state_dir, store, name, keep=None)` を打つ。登録を外す操作と残りのファイルの削除を分ける(`account_registry.unregister`): 登録の排他の中で世代を読み、登録のディレクトリを `<保存先>/.removing/<名前>/<世代>` へ 1 回の `os.replace` で移して一覧から外し(壊れて世代が読めなければ世代の形でない名前で移し、後始末はしない)、その世代の後始末を打ってから中身を消す。中身が消え残れば止めるが、登録は外れたままで、残りは世代の名前で残る。削除は全体を登録と同じ排他の中で行う(`account_registry.remove_account`): 残りがあれば、今の登録の有無によらずログアウトを打たずに、残った世代ごとの後始末と削除だけをやり直して返す(間に同じ名前で登録し直されていても、その登録は外さずに警告で知らせる。外すのは残りが無くなった後の `account remove <名前>`)。残りが無ければ、排他を取ったまま世代を読み、共有の項目の symlink を外してログアウトし、登録を外す(ログアウトの間の登録し直しは排他で待たせる) | | `recovery_keys`・`key_generation`・`key_value` | `account_registry.py` | 新設 | `recovery_keys` は `(store: Path) -> list[str]`、`key_value` は `(store: Path, name: str, generation: str) -> str`、`key_generation` は `(store: Path, name: str) -> str` | `recovery_keys`: 登録簿の使い方の設定が `off` でなければ、登録したキーの名前を名前の順に返す。`off`・登録簿が無い・壊れているときは空(決定 12)。`key_generation`: その名前の行の `generation`(`add-api-key` が登録のたびに新しく書く値)を返す。無い・空なら `AccountError`。`key_value`: 登録簿の行の `generation` が引数の世代と同じときだけキーの値を返す。無い名前・世代の違い(同じ名前を `add-api-key` で登録し直した後)は `AccountError`。呼ぶのは `api-key-helper` だけ | 世代の照合: 使用率のキャッシュのパス、外した間と上限の観測の項目は世代を持つ。読む側は今の `account.json` の世代と違うものを無いものとして読む。再登録の後に旧いセッションの status line やラッパーが遅れて書いても、旧い世代のパスか項目へ入るので、新しい登録の判断へ戻らない @@ -442,7 +442,7 @@ Claude Code が接続先を切り替える提供元の選択の変数は、`CLAU | 関数 | 保存先 | 種類 | シグネチャ | 責務 | | --- | --- | --- | --- | --- | -| `usage_dir`・`usage_path` | `accounts.py` | 新設・変更 | `usage_dir` は `(state_dir: Path) -> Path`、`usage_path` は `(state_dir: Path, name: str, generation: str) -> Path` | `usage_dir`: `<状態の保存先>/relay/accounts/usage`(ファイルの表の `relay-usage` の `path` の親から)。`usage_path`: アカウント 1 つ・登録の世代 1 つの使用率のキャッシュのパス(`usage/<名前>/<世代>.json`。世代が空文字なら `usage/<名前>/_.json`)。status line へは `NDF_ACCOUNT_USAGE_FILE` でこの結果を渡す | +| `usage_dir`・`usage_path` | `accounts.py` | 新設・変更 | `usage_dir` は `(state_dir: Path) -> Path`、`usage_path` は `(state_dir: Path, name: str, generation: str) -> Path` | `usage_dir`: `<状態の保存先>/relay/accounts/usage`(ファイルの表の `relay-usage` の `path` の親から)。`usage_path`: アカウント 1 つ・登録の世代 1 つの使用率のキャッシュのパス(`usage/<名前>/<世代>.json`。世代は「登録の世代」の行の共通の関数で得た値で、旧い登録なら `legacy-…`。空文字は登録の無いときだけで `usage/<名前>/_.json`)。status line へは `NDF_ACCOUNT_USAGE_FILE` でこの結果を渡す | | `usages` | `accounts.py` | 変更 | `(state_dir: Path, store: Path, now: float, generations: Mapping[str, str]) -> list[account_decide.Usage]` | 登録済みアカウントごとに今の世代のファイルだけを名前の順に読む。読むのは状態の保存先のキャッシュ(status line の窓)と登録簿の側の取得の記録(`fetch_path` の `windows`。使用率の API の窓)の 2 つで、窓ごとに `read_windows`(「書き込みの規則」の読み取り用の合成。`resets_at` の新しいほう、同じなら使用率の大きいほうで、失効した窓も捨てない)で合わせてから下を当てる。片方が読めなければ、もう片方だけで読む。窓ごとにリセットの時刻を過ぎていれば 0% にし、5 時間と 7 日の使用率と 7 日のリセットの時刻を返す。7 日の使用率は `seven_day` と、`seven_day_scoped` の識別ごとのモデル別の枠のうちリセットを過ぎていないものの最大の、大きいほうで読む(10 系の `Usage.weekly_score` と同じ。枠ごとに合わせた後で最大を求める)。同じ世代の取得の記録(`fetch_path`)の `spend_limit_reached` が真の名前は上限として読み、解ける時刻を持たない(`valid_until` と最も早く解けるアカウントの時刻の候補にしない。次の取得で偽になれば解く)。使用率(一覧の表示)は窓の最大、上限は過ぎていない窓のどれかが 100 以上。最後に `limits_seen` を重ね、上限の観測が続く名前を上限にする。使用率の行が無い(ファイルが無い・有効な窓が無い)名前に、上限の観測が続いているか、同じ世代の取得の記録の `spend_limit_reached` が真なら、`Usage(name, None, None, None, None, True)`(使用率は分からないが上限)の行を作る(判断の入力はすべてこの関数を通る)。事後条件: 返す名前は登録済みアカウント(`generations` のキー)だけである。読めないファイル・形の違うファイル・窓を 1 つも持たないファイル(未観測)は返さない。返さない名前は使用率の分からないアカウント(組 1)になり、0% として読まない。窓を持つファイルは、窓がすべてリセットの時刻を過ぎていても返す。過ぎた窓は 0%(受け入れ条件 #3864 の 3)で、その窓の次のリセットの時刻は分からないので、7 日の窓が過ぎていれば `seven_resets_at` は None とする。ただし、上限の観測が続く名前と、取得の記録の `spend_limit_reached` が真の名前は、ファイルも窓も無く画面で上限を観測していなくても `Usage(name, None, None, None, None, True)` で返す(最初の正常な応答が `five_hour: null` と `extra_usage.spend_limit_reached: true` を返したアカウントを、使用率の分からない候補に入れない)。使用率の API も status line も取れない経路で、上限の行を見たアカウントを「使用率の分からない候補」として選び直さないためである | | `write_usage`・`held_path`・`held`・`hold`・`unhold` | `accounts.py` | 新設 | `write_usage` は `(path: Path, windows: Mapping[str, tuple[float, float]], now: float) -> None`、`held_path`・`held`・`hold`・`unhold` は `held_path`・`held` は `held_path` は `(state_dir: Path) -> Path`、`held` は `(state_dir: Path, now: float, generations: Mapping[str, str]) -> dict[str, float]`、`hold`・`unhold` は `hold` は `(state_dir: Path, name: str, generation: str, until: float, now: float) -> None`、`unhold` は `(state_dir: Path, name: str) -> None` | `write_usage`: status line と同じ形・同じ合わせ方(取得の記録に触れない)(下の「書き込みの規則」)で 1 つの記録を書く(テストが使う。今の `write_usages` は消す)。`held_path`・`held`・`hold`・`unhold`: `held_path`・`held`: `held_path`: `<状態の保存先>/relay/accounts/held.json`。`held`: 外す終わりが `now` より後で、世代が今の登録と同じ名前と終わりの時刻。`hold`・`unhold`: `hold`: 錠の中で読み、終わった項目を消し、`name` の下の `generation` の項目だけを `{"until"}` で書いて置き換える。ほかの世代の項目は変えない(下の「世代ごとの項目」)。`hold`・`unhold`・`see_limit` の副作用: 書くファイルの `.lock` の錠(`signals.held`、待ちは `relay.signal-lock`)と置き換えの書き込み。`unhold`: 錠の中で `held.json` から `name` の項目を世代を問わず消す。`account use <名前>` が指定を書いた後に打つ。副作用は `hold` と同じ錠と置き換え | | `limits_path`・`limits_seen`・`see_limit`・`limit_until`・`forget` | `accounts.py` | 新設 | `limits_path`・`limits_seen`・`see_limit` は `see_limit(state_dir, name, generation, seen_at: float, until: float, window: Optional[str], window_resets_at: Optional[float])`・`limits_seen(state_dir, now, generations, windows: Mapping[str, Mapping[str, tuple[float, float]]]) -> dict[str, tuple[float, float]]`、`limit_until`・`forget` は `limit_until` は `(line: str, windows: Mapping[str, tuple[float, float]], seen_at: float, tz: tzinfo) -> tuple[float, Optional[str], Optional[float]]`、`forget` は `(state_dir: Path, store: Path, name: str, keep: Optional[str]) -> None` | `limits_path`・`limits_seen`・`see_limit`: 上限の観測(`<状態の保存先>/relay/accounts/limited.json`、`{"<名前>": {"<世代>": {"seen_at", "until", "window", "window_resets_at"}}}`。`window` は上限の窓を特定できたときの窓の名前で、特定できなければ null。`window_resets_at` は見た時刻のキャッシュでのその窓の `resets_at`(窓を特定した上で、キャッシュにその窓があったときだけ。無ければ null)。`until` は解除の推定の時刻で、窓の識別には使わない)。ラッパーが上限の行を初めて見たときに書く。`limits_seen` は下の「解除」に当たらない観測を返す(`windows` は名前ごとの今のキャッシュの窓)。`see_limit` の副作用は `hold` と同じ錠と置き換え。`limit_until`・`forget`: `limit_until`: 上限の行と使用率のキャッシュから `until`・窓の名前・見た時刻のその窓の `resets_at` を決める(下の「`until` の決め方」)。時計を読まない。`forget`: `held.json` と `limited.json` の `name` の下の、`keep`(今の世代。削除なら None)でない世代の項目を消し、`usage/<名前>/` の `keep` の世代でないファイル(キャッシュ・キャッシュの錠)と、登録簿の側の `.usage-fetch/<名前>/` の `keep` の世代でない取得の記録を消す(登録・削除の成功の後に、取得の排他を持ったまま打つ)。名前ごとの取得の排他のファイル(登録簿の `.fetch-locks/<名前>.lock`)は消さない | diff --git a/issues/issue-3864-requirements.md b/issues/issue-3864-requirements.md index ccd1a3e6b6..9bd44f6fd8 100644 --- a/issues/issue-3864-requirements.md +++ b/issues/issue-3864-requirements.md @@ -114,9 +114,9 @@ NDF `main` の d16aa39d0(11.0.8 の後)・d14325d76(11.0.13 の後)、Li | 対象 | 影響 | | --- | --- | -| 公開インタフェース | 変わる。使用率のキャッシュ(`usage.json`)の行にリセットの時刻が足される(今は書き手が無いので互換の問題は無い)。status line が使用率を記録する。コマンドの引数と結果の形は変わらない | +| 公開インタフェース | 変わる。使用率のキャッシュは、アカウントごと・登録の世代ごとのファイル `usage/<名前>/<世代>.json`(`<状態の保存先>/relay/accounts/` の下。書き手は NDF の status line)になり、使用率の API の取得の記録を `.usage-fetch/<名前>/<世代>.json`(`<アカウントの登録簿>/` の下。書き手は使用率の API の取得)に置く。どちらも窓ごとにリセットの時刻を持つ(今の `usage.json` は書き手が無いので互換の問題は無い)。status line が使用率を記録する。コマンドの引数と結果の形は変わらない | | 重さ | 中継のアカウントの切り替えが一度も働かない。2 つ以上のアカウントを登録した利用者のレーンが上限で止まる。回避は、`/exit` して手で別のアカウントで起動し直すこと | -| データ | `usage.json`(`<状態の保存先>/relay/accounts/`)に行のキーが増える。認証の失敗で外したアカウントの記録が状態の保存先に増える | +| データ | 使用率のキャッシュ `usage/<名前>/<世代>.json`(`<状態の保存先>/relay/accounts/` の下)と、取得の記録 `.usage-fetch/<名前>/<世代>.json`(`<アカウントの登録簿>/` の下)が増える。認証の失敗で外したアカウントの記録が状態の保存先に増える | | 既存の振る舞い | 上限・401・カットポイントでの切り替え、指定の効く時点、従量の接続への退避が変わる。手順書の大半の節が書き直しになる | ## 用語 diff --git a/plugins/ndf/contracts/domains/ndf-files.json b/plugins/ndf/contracts/domains/ndf-files.json index 5fc49a2981..0f4a621ea7 100644 --- a/plugins/ndf/contracts/domains/ndf-files.json +++ b/plugins/ndf/contracts/domains/ndf-files.json @@ -77,7 +77,9 @@ {"id": "relay-next", "location": "relay-wrappers", "path": "<名前>/next.json", "kind": "exchange", "tracked": false, "writer": "Stop の hook(M3a)", "ends": "run"}, {"id": "relay-question", "location": "relay-wrappers", "path": "<名前>/question.json", "kind": "exchange", "tracked": false, "writer": "PreToolUse の hook(M3a)", "ends": "run"}, {"id": "relay-stop", "location": "relay-wrappers", "path": "<名前>/stop", "kind": "exchange", "tracked": false, "writer": "ndf relay stop(M3b)と人(touch)", "ends": "run"}, - {"id": "relay-usage", "location": "relay-accounts", "path": "usage.json", "kind": "measured", "tracked": false, "writer": "使用率のセンサー(M3a)", "ends": "replaced", "keys": ["accounts"]}, + {"id": "relay-usage", "location": "relay-accounts", "path": "usage/<名前>/<世代>.json", "kind": "measured", "tracked": false, "writer": "NDF の status line(statusline.sh)", "ends": "replaced", "keys": ["windows", "recorded_at"]}, + {"id": "relay-auth-held", "location": "relay-accounts", "path": "held.json", "kind": "measured", "tracked": false, "writer": "中継のラッパー(M3b)", "ends": "replaced", "keys": []}, + {"id": "relay-limit-seen", "location": "relay-accounts", "path": "limited.json", "kind": "measured", "tracked": false, "writer": "中継のラッパー(M3b)", "ends": "replaced", "keys": []}, {"id": "gws-install-material", "location": "google-workspace", "path": "install.md", "kind": "document", "tracked": false, "writer": "gws の確認(S1d)", "ends": "replaced"}, {"id": "relay-pinned-account", "location": "relay-accounts", "path": "pinned.json", "kind": "ndf_settings", "tracked": false, "writer": "人(ndf relay account use)", "ends": "replaced"}, {"id": "relay-marker", "location": "relay-markers", "path": ".json", "kind": "exchange", "tracked": false, "writer": "中継のラッパー(M3b)", "ends": "run"}, diff --git a/plugins/ndf/contracts/limits.json b/plugins/ndf/contracts/limits.json index ef0e8f0188..494b45a039 100644 --- a/plugins/ndf/contracts/limits.json +++ b/plugins/ndf/contracts/limits.json @@ -143,6 +143,8 @@ "relay.registry-lock": {"summary": "リレーハブの登録簿の排他を待つ上限", "seconds": 5}, "relay.child-exit": {"summary": "ラッパーが子を強制終了した後、子の終わりを確かめるまで待つ上限。終わらなければ次の子を起動せずに止める(#3814)", "seconds": 5}, "relay.signal-lock": {"summary": "シグナルファイル(次のセグメントのマーカー・質問)の排他を待つ上限。hook の締め切りの中に収める", "seconds": 0.3}, + "relay.auth-hold": {"summary": "認証の失敗で、そのアカウントを替え先と指定の候補から外す秒(#3864)", "seconds": 3600}, + "relay.limit-unknown": {"summary": "上限の行を見たアカウントの使用率の記録に有効な窓が無いとき、上限として扱う秒(5 時間の窓の長さ)", "seconds": 18000}, "relay.usage-guard": {"summary": "利用上限の前にカットポイントでアカウントを替える使用率(百分率。#3336)", "count": 90}, "relay.transcript-tail": {"summary": "ラッパーが文脈の量を読む会話の記録の末尾の大きさ(バイト)", "count": 262144}, "relay.context": {"summary": "中継の下のセッションを次のセグメントへ切り替える文脈の量(token。#2595)", "count": 800000}, diff --git a/plugins/ndf/docs/contracts/files.md b/plugins/ndf/docs/contracts/files.md index 8c0ef741c2..6bf2003870 100644 --- a/plugins/ndf/docs/contracts/files.md +++ b/plugins/ndf/docs/contracts/files.md @@ -50,6 +50,7 @@ NDF の工程が書くファイル(設定・計測値・実行の記録・文 | `project` | `ndf` repo:.ndf | `project.json` | ndf_settings | 追跡 | 人と解析(M7) | kept | 内部(予告なく変えてよい) | | `project-measured` | `measured` state:measured | `/project.json` | measured | — | 解析とテストの実行(M7) | replaced | 内部(予告なく変えてよい) | | `projects` | `ndf` repo:.ndf | `projects.json` | ndf_settings | 追跡 | 人 | kept | 内部(予告なく変えてよい) | +| `relay-auth-held` | `relay-accounts` state:relay/accounts | `held.json` | measured | — | 中継のラッパー(M3b) | replaced | 内部(予告なく変えてよい) | | `relay-copy-launcher` | `relay-copy` config:ndf | `relay.py` | exchange | — | 人(ndf relay install) | replaced | 内部(予告なく変えてよい) | | `relay-copy-root` | `relay-copy` config:ndf | `relay.root` | exchange | — | 中継(M3b)・SessionStart hook(更新後の向け直し) | replaced | 内部(予告なく変えてよい) | | `relay-hub-log` | `relay-hub` state:relay/hub | `hub-log.jsonl` | record | — | 中継のリレーハブ(M3) | cleanup | 内部(予告なく変えてよい) | @@ -57,12 +58,13 @@ NDF の工程が書くファイル(設定・計測値・実行の記録・文 | `relay-hub-request` | `relay-hub` state:relay/hub | `requests-v2/.json` | exchange | — | 中継の頼む側(M3) | run | 内部(予告なく変えてよい) | | `relay-hub-result` | `relay-hub` state:relay/hub | `results/.json` | exchange | — | 中継のリレーハブ(M3) | run | 内部(予告なく変えてよい) | | `relay-hub-state` | `relay-hub` state:relay/hub | `hub.json` | exchange | — | 中継(M3) | replaced | 内部(予告なく変えてよい) | +| `relay-limit-seen` | `relay-accounts` state:relay/accounts | `limited.json` | measured | — | 中継のラッパー(M3b) | replaced | 内部(予告なく変えてよい) | | `relay-marker` | `relay-markers` state:relay/markers | `.json` | exchange | — | 中継のラッパー(M3b) | run | 内部(予告なく変えてよい) | | `relay-next` | `relay-wrappers` state:relay/wrappers | `<名前>/next.json` | exchange | — | Stop の hook(M3a) | run | 内部(予告なく変えてよい) | | `relay-pinned-account` | `relay-accounts` state:relay/accounts | `pinned.json` | ndf_settings | — | 人(ndf relay account use) | replaced | 内部(予告なく変えてよい) | | `relay-question` | `relay-wrappers` state:relay/wrappers | `<名前>/question.json` | exchange | — | PreToolUse の hook(M3a) | run | 内部(予告なく変えてよい) | | `relay-stop` | `relay-wrappers` state:relay/wrappers | `<名前>/stop` | exchange | — | ndf relay stop(M3b)と人(touch) | run | 内部(予告なく変えてよい) | -| `relay-usage` | `relay-accounts` state:relay/accounts | `usage.json` | measured | — | 使用率のセンサー(M3a) | replaced | 内部(予告なく変えてよい) | +| `relay-usage` | `relay-accounts` state:relay/accounts | `usage/<名前>/<世代>.json` | measured | — | NDF の status line(statusline.sh) | replaced | 内部(予告なく変えてよい) | | `relay-wrapper` | `relay-wrappers` state:relay/wrappers | `<名前>/wrapper.json` | exchange | — | 中継のラッパー(M3b) | replaced | 内部(予告なく変えてよい) | | `relay-wrapper-lock` | `relay-wrappers` state:relay/wrappers | `<名前>/relay.lock` | exchange | — | 中継のラッパー(M3b) | replaced | 内部(予告なく変えてよい) | | `relay-wrapper-log` | `relay-wrappers` state:relay/wrappers | `<名前>/log.jsonl` | record | — | 中継のラッパー(M3b) | cleanup | 内部(予告なく変えてよい) | diff --git a/plugins/ndf/docs/contracts/index.md b/plugins/ndf/docs/contracts/index.md index ed6a20ff7e..830edbea07 100644 --- a/plugins/ndf/docs/contracts/index.md +++ b/plugins/ndf/docs/contracts/index.md @@ -14,7 +14,7 @@ NDF を外から呼ぶ面(設定・サブコマンド・環境変数・受け | [サブコマンドの引数と結果](commands.md) | 公開 0・内部 28 | | [終了コードと停止理由](exit-codes.md) | 終了コード 11・停止理由 33 | | [環境変数](env.md) | 公開 10・内部 69 | -| [受け渡しのファイル](files.md) | 公開 12・内部 56 | +| [受け渡しのファイル](files.md) | 公開 12・内部 58 | | [hook の入出力](hooks.md) | 公開 6・内部 11 | | [Skill と起動スクリプト](skills.md) | 公開 1・内部 48 | diff --git a/plugins/ndf/src/ndf/domains/relay/account_login.py b/plugins/ndf/src/ndf/domains/relay/account_login.py index dda5bbfcf6..3c1949a2ce 100644 --- a/plugins/ndf/src/ndf/domains/relay/account_login.py +++ b/plugins/ndf/src/ndf/domains/relay/account_login.py @@ -264,18 +264,22 @@ def _wait_exit(p: dict[str, Any]) -> bool: return _wait_until(lambda: not _alive(p), limits.seconds("relay.login-exit")) -def _register(store: Path, claude: str, name: str, config_dir: Path, environ: Mapping[str, str], now: float) -> Added: - ident = _identity(claude, config_dir, environ) +# 登録の後始末(`reg.register` の `settle`。前の世代・新しい世代を受け、登録の排他の中で呼ばれる) +Settle = Optional[Callable[[Optional[str], str], None]] + + +def _register(store: Path, name: str, config_dir: Path, environ: Mapping[str, str], now: float, settle: Settle = None) -> Added: + ident = _identity(_claude(), config_dir, environ) if ident is None or not (config_dir / reg.CRED_FILE).is_file(): raise LoginError("refused", "ログインが通らなかった。登録しない") owner = owner_of(store, ident.email, ident.org_id, other_than=name) if owner: raise LoginError("refused", f"同じメールアドレスと組織で登録済み: {owner}") - reg.register(store, name, config_dir, ident, now) + reg.register(store, name, config_dir, ident, now, settle) return Added(name, needs_code=False, email=ident.email, org_name=ident.org_name or None) # noqa: NDF501 外部コマンド: 組織名の無い本人は null -def _finish(store: Path, name: str, code: str, environ: Mapping[str, str], now: float) -> Added: +def _finish(store: Path, name: str, code: str, environ: Mapping[str, str], now: float, settle: Settle = None) -> Added: p = _read_pending(store, name) try: if p is None: @@ -293,19 +297,24 @@ def _finish(store: Path, name: str, code: str, environ: Mapping[str, str], now: os.close(fd) if not _wait_exit(p): raise LoginError("refused", "claude auth login が終わらなかった。登録しない") - return _register(store, _claude(), name, pending_dir(store, name) / PENDING_CONFIG, environ, now) + return _register(store, name, pending_dir(store, name) / PENDING_CONFIG, environ, now, settle) finally: discard_pending(store, name) -def add(store: Path, name: str, code: Optional[str], environ: Mapping[str, str], now: Optional[float] = None) -> Added: - """`code` が無ければ待機中のログインを起動して認可コードを求め、あれば渡して登録する。""" +def add( + store: Path, name: str, code: Optional[str], environ: Mapping[str, str], now: Optional[float] = None, settle: Settle = None +) -> Added: + """`code` が無ければ待機中のログインを起動して認可コードを求め、あれば渡して登録する。 + + `settle` は登録の排他の中で前の世代の記録を片付ける呼び出し(`reg.register` の `settle`)。 + """ now = time.time() if now is None else now sweep_pending(store, now) check_name(store, name) if code is None: return _start(store, name, environ, now) - return _finish(store, name, code, environ, now) + return _finish(store, name, code, environ, now, settle) def logout(store: Path, name: str, environ: Mapping[str, str]) -> bool: diff --git a/plugins/ndf/src/ndf/domains/relay/account_registry.py b/plugins/ndf/src/ndf/domains/relay/account_registry.py index ab240d98e7..ddec96d569 100644 --- a/plugins/ndf/src/ndf/domains/relay/account_registry.py +++ b/plugins/ndf/src/ndf/domains/relay/account_registry.py @@ -12,15 +12,17 @@ from __future__ import annotations +import hashlib import json import os import re +import secrets import shlex import shutil -from contextlib import contextmanager +from contextlib import contextmanager, suppress from datetime import datetime, timezone from pathlib import Path -from typing import Any, Iterator, Mapping, NamedTuple, Optional +from typing import Any, Callable, Iterator, Mapping, NamedTuple, Optional from filelock import FileLock, Timeout @@ -30,6 +32,9 @@ from ndf.domains.relay import signals NAME_RE = re.compile(r"[a-z0-9][a-z0-9_-]{0,31}") +# 登録の世代の形(使用率のキャッシュのファイル名と記録のキーになる。`.`・`/` を含まない 1 つのパスの要素)。 +# 登録は `secrets.token_hex(16)` を書く(決定の表の「登録の世代」) +GEN_RE = re.compile(r"[A-Za-z0-9][A-Za-z0-9_-]{0,63}") METERED = "metered" # 従量の接続を表す予約の名前。登録できない ACCOUNT_FILE = "account.json" USAGE_FILE = "usage.json" @@ -40,6 +45,7 @@ BOOK_FILE = "api-keys.json" BOOK_LOCK = ".api-keys" # アカウントの名前(先頭は英小文字か数字)と重ならない LOCKS_DIR = ".locks" +REMOVING_DIR = ".removing" # 外した登録の残りを消し終えるまで置く(`unregister`) AWS_KEY_ENV = ("AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY", "AWS_SESSION_TOKEN") # 提供元の選択の変数(子の環境の表の provider の行。親の環境から外す・実効の設定の確かめ・従量の接続の検証が同じ分類を使う) PROVIDER_ENV = facts.ids("env", provider=True) @@ -131,6 +137,7 @@ class Account(NamedTuple): org_id: str org_name: str declared: dict[str, float] + generation: str = "" # 登録の世代(`generation` と同じ読み方) class Identity(NamedTuple): @@ -269,10 +276,30 @@ def locked(store: Path, name: str, wait: Optional[float] = None) -> Iterator[Non def generation(store: Path, name: str) -> str: - """アカウントの登録の世代(`account.json` の `generation`)。登録か世代が無ければ空文字、壊れていれば `AccountError`。""" - a = _read(account_dir(store, name) / ACCOUNT_FILE) - got = a.get("generation") if a is not None else None - return got if isinstance(got, str) else "" + """アカウントの登録の世代(`account.json` の `generation`)。登録が無ければ空文字、壊れていれば `AccountError`。 + + 世代を持たない旧い登録には `legacy_generation` を返す(登録簿ごとに違う値)。 + """ + path = account_dir(store, name) / ACCOUNT_FILE + return _generation_of(_read(path), path) + + +def legacy_generation(store: Path, name: str) -> str: + """世代を書く前の旧い登録の世代。登録簿の実際のパスと名前から決まり、状態の保存先を共有する別の登録簿の同じ名前と重ならない。""" + where = f"{os.path.realpath(store)}\0{name}".encode() + return "legacy-" + hashlib.sha256(where).hexdigest()[:32] + + +def _generation_of(a: Optional[dict[str, Any]], path: Path) -> str: + """`account.json` の中身の世代。登録が無ければ空文字、`GEN_RE` の形でなければ `AccountError`(パスの要素に使うため)。""" + if a is None: + return "" + got = a.get("generation") + if got is None: # 世代を書く前の旧い登録。登録簿ごとに区別できる値を割り当てる + return legacy_generation(path.parent.parent, path.parent.name) + if not isinstance(got, str) or not GEN_RE.fullmatch(got): + raise AccountError(f"{path} の generation の形が違う") + return got def _declared(v: Any) -> dict[str, float]: @@ -289,7 +316,8 @@ def capacity_view(declared: Mapping[str, float]) -> dict[str, Optional[float]]: def load(store: Path, name: str) -> Optional[Account]: """アカウントの `account.json`。無ければ None、壊れていれば `AccountError`。""" - a = _read(account_dir(store, name) / ACCOUNT_FILE) + path = account_dir(store, name) / ACCOUNT_FILE + a = _read(path) if a is None: return None return Account( @@ -299,6 +327,7 @@ def load(store: Path, name: str) -> Optional[Account]: org_id=str(a.get("org_id") or ""), # noqa: NDF501 ファイル: 組織を記録する前の旧い登録は組織を持たない org_name=str(a.get("org_name") or ""), # noqa: NDF501 ファイル: 組織を記録する前の旧い登録は組織を持たない declared=_declared(a.get("capacity")), + generation=_generation_of(a, path), ) @@ -314,11 +343,29 @@ def _replace_on_relogin(staging: Path, final: Path) -> None: shutil.rmtree(staging, ignore_errors=True) -def register(store: Path, name: str, staging: Path, who: Identity, now: float) -> None: - """ログインの済んだ `staging` を `name` として置く。同じ名前の保存先は丸ごと消さず、認証のファイルだけを置き換える。""" +def register( + store: Path, name: str, staging: Path, who: Identity, now: float, settle: Optional[Callable[[Optional[str], str], None]] = None +) -> str: + """ログインの済んだ `staging` を `name` として置き、新しい登録の世代を返す。同じ名前の保存先は丸ごと消さず、認証のファイルだけを置き換える。 + + 世代は登録のたびに新しく発行する(同じ名前の登録し直しでも、前の世代の記録を今の記録と読まない)。`settle` を渡すと、 + 置いた後に同じ排他の中で `settle(前の世代, 新しい世代)` を呼ぶ(前の世代の記録の後始末。前の登録が無ければ前の世代は None)。 + """ with locked(store, name): final = account_dir(store, name) - row: dict[str, Any] = {"name": name, "email": who.email, "registered_at": iso_utc(now), "needs_relogin": False, "limit": None} + try: + old: Optional[str] = generation(store, name) if (final / ACCOUNT_FILE).is_file() else None + except AccountError: # 壊れた前の登録は世代が分からない。後始末を空文字の世代で打つ + old = "" + new = secrets.token_hex(16) + row: dict[str, Any] = { + "name": name, + "email": who.email, + "registered_at": iso_utc(now), + "needs_relogin": False, + "limit": None, + "generation": new, + } if who.org_id: row.update(org_id=who.org_id, org_name=who.org_name) write(staging / ACCOUNT_FILE, row) @@ -329,6 +376,9 @@ def register(store: Path, name: str, staging: Path, who: Identity, now: float) - final.unlink() os.replace(staging, final) secure(store, name) + if settle is not None: + settle(old, new) + return new def set_capacity(store: Path, name: str, five: Optional[float], seven: Optional[float]) -> dict[str, Any]: @@ -359,9 +409,95 @@ def detach(store: Path, name: str) -> None: p.unlink() -def unregister(store: Path, name: str) -> None: +def removing_dir(store: Path, name: str) -> Path: + """外した登録の残りを消し終えるまで置く場所(`<保存先>/.removing/<名前>/<世代>`)。名前の形と重ならない。""" + return store / REMOVING_DIR / name + + +def removing(store: Path, name: str) -> bool: + """`name` の外した登録の残りが、消し終わらずに残っているか(`unregister` を打ち直すと続きを消す)。""" + d = removing_dir(store, name) + return d.is_dir() and any(d.iterdir()) + + +def unregister(store: Path, name: str, settle: Optional[Callable[[str], None]] = None) -> None: + """登録を外す。`settle` を渡すと、外した後に同じ排他の中で `settle(外した世代)` を呼ぶ(世代が読めなければ呼ばない)。 + + 登録を外す操作と残りのファイルの削除を分ける。まず登録のディレクトリを `removing_dir` の下へ世代の名前で移し + (1 回の `os.replace` で一覧から消える)、その世代で `settle` を呼んでから中身を消す。中身が消え残れば `OSError` で止めるが、 + 登録は外れたままで、残りは世代の名前で残る。残りの続きを消すのは `remove_account` の打ち直し(今の登録に触れない)。 + """ + with locked(store, name): + _unregister(store, name, settle) + + +def _unregister(store: Path, name: str, settle: Optional[Callable[[str], None]]) -> None: + d = account_dir(store, name) + if d.exists() or d.is_symlink(): + try: + gone: Optional[str] = generation(store, name) or None # noqa: NDF501 ファイル: 世代の無い登録は後始末の世代を持たない + except AccountError: # 壊れた登録は世代が分からないので後始末をしない(世代の形でない名前で置く) + gone = None + pending = removing_dir(store, name) + pending.mkdir(mode=0o700, parents=True, exist_ok=True) + os.replace(d, pending / (gone or f"-{secrets.token_hex(8)}")) + _finish_removal(store, name, settle) + + +class Removal(NamedTuple): + """`remove_account` の結果。""" + + leftovers: bool # 前の削除の残りだけを消した(今の登録には触れていない) + kept: bool # 残りを消した後も、同じ名前の今の登録が残っている(残りの後に登録し直された) + logged_out: Optional[bool] = None # 今の登録を外したときのログアウトの成否(残りだけを消したときは None) + + +def remove_account(store: Path, name: str, release: Callable[[], bool], settle: Optional[Callable[[str], None]] = None) -> Removal: + """`account remove <名前>` の本体。すべてを登録(`register`)と同じ排他の中で行う。 + + 1. 前の削除の残り(`removing`)があれば、残った世代ごとの `settle` と削除だけをやり直して返す。今の登録には触れない + (案内どおりの打ち直しで、間に登録し直された新しい認証情報・設定を消さない)。今の登録を外すのは、残りが無くなった後の削除 + 2. 残りが無ければ今の登録を外す。排他を取ったまま `release()`(共有の項目の symlink を外してログアウトし、成否を返す)を呼び、 + そのまま `unregister` と同じ手順で外す。世代は排他の中で 1 度だけ決まり、ログアウトから登録を外すまでに登録し直されない + + 排他を待つ前に残りを見ていれば、残りの後始末の呼び出しとして扱う。待つ間にほかの端末が残りを片付けても、2 へ進まずに返す + (残りの後始末として打ち直した呼び出しが、残りの後に登録し直された今の登録を外さない)。 + + 登録も残りも無ければ `NotRegistered`、消え残れば `OSError`(打ち直すと 1 から)。 + """ + check_name(name) + seen = removing(store, name) with locked(store, name): - shutil.rmtree(account_dir(store, name), ignore_errors=True) + if seen or removing(store, name): + _finish_removal(store, name, settle) + return Removal(leftovers=True, kept=(account_dir(store, name) / ACCOUNT_FILE).is_file()) + if not (account_dir(store, name) / ACCOUNT_FILE).is_file(): + raise NotRegistered(f"登録されていない: {name}") + out = release() + _unregister(store, name, settle) + return Removal(leftovers=False, kept=False, logged_out=out) + + +def _finish_removal(store: Path, name: str, settle: Optional[Callable[[str], None]]) -> None: + """`removing_dir` に残った世代ごとに `settle` を呼んで中身を消す。消え残れば `OSError`(打ち直すと続きから)。""" + pending = removing_dir(store, name) + if not pending.is_dir(): + return + left: list[Path] = [] + for p in sorted(pending.iterdir()): + if settle is not None and GEN_RE.fullmatch(p.name): + settle(p.name) + if p.is_symlink() or not p.is_dir(): + p.unlink(missing_ok=True) + else: + shutil.rmtree(p, ignore_errors=True) + if p.exists() or p.is_symlink(): + left.append(p) + if left: + raise OSError(f"外した登録の残りを消せなかった(登録は外した。同じ削除を打ち直すと続きを消す): {', '.join(map(str, left))}") + pending.rmdir() + with suppress(OSError): # noqa: NDF402 ファイル: ほかの名前の残りがあれば親は残す + pending.parent.rmdir() # ---------------------------------------------------------------- 従量の接続の設定 @@ -493,19 +629,31 @@ def _state(acc: Account, usage: Any) -> str: return "上限" if usage.limited else "使える" -def _oauth_rows(store: Path, pinned: Optional[str], usages: list[Any]) -> tuple[list[dict[str, Any]], list[str]]: - """OAuth で登録したアカウントの行と、壊れた登録の警告。""" - rows: list[dict[str, Any]] = [] +# 一覧の使用率の引き方(登録済みアカウントの名前 → 今の世代を受け、`Usage` の並びを返す) +UsagesOf = Callable[[Mapping[str, str]], list[Any]] + + +def _oauth_rows(store: Path, pinned: Optional[str], usages: UsagesOf) -> tuple[list[dict[str, Any]], list[str]]: + """OAuth で登録したアカウントの行と、壊れた登録の警告。 + + `account.json` は 1 回だけ読み、その世代で `usages` を引く(行の本人と使用率の世代が食い違わない)。 + """ + loaded: list[tuple[str, Optional[Account]]] = [] warnings: list[str] = [] - by_name = _usage_by_name(usages) for n in names(store): try: acc = load(store, n) except AccountError as exc: warnings.append(str(exc)) - rows.append({"name": n, "kind": "oauth", "state": "broken"}) + loaded.append((n, None)) continue + if acc is not None: + loaded.append((n, acc)) + by_name = _usage_by_name(usages({n: acc.generation for n, acc in loaded if acc is not None})) + rows: list[dict[str, Any]] = [] + for n, acc in loaded: if acc is None: + rows.append({"name": n, "kind": "oauth", "state": "broken"}) continue u = by_name.get(n) rows.append( @@ -548,8 +696,11 @@ def _api_key_rows(store: Path) -> tuple[list[dict[str, Any]], list[str]]: return rows, warnings -def list_rows(store: Path, environ: Mapping[str, str], pinned: Optional[str], usages: list[Any]) -> tuple[list[dict[str, Any]], list[str]]: - """登録したアカウント・従量の接続・API キーを 1 件ずつ並べる(キーの値とトークンを含まない)。壊れた登録は警告へ。""" +def list_rows(store: Path, environ: Mapping[str, str], pinned: Optional[str], usages: UsagesOf) -> tuple[list[dict[str, Any]], list[str]]: + """登録したアカウント・従量の接続・API キーを 1 件ずつ並べる(キーの値とトークンを含まない)。壊れた登録は警告へ。 + + `usages` は、読めた登録の名前と世代を受けて使用率の行を返す呼び出し(壊れた登録は渡さない)。 + """ oauth, oauth_warnings = _oauth_rows(store, pinned, usages) metered = _metered_rows(store, environ) keys, key_warnings = _api_key_rows(store) diff --git a/plugins/ndf/src/ndf/domains/relay/accounts.py b/plugins/ndf/src/ndf/domains/relay/accounts.py index 2c7d92b058..f3c958a8a6 100644 --- a/plugins/ndf/src/ndf/domains/relay/accounts.py +++ b/plugins/ndf/src/ndf/domains/relay/accounts.py @@ -5,20 +5,29 @@ どちらも `chosen` で選ぶ(`session_env.child_env` が子へ渡す)。指定のファイルが壊れていれば `AccountError` を 送出し、呼び出し元が理由を出して止まる(読めない指定を黙って既定へ倒さない)。 -使用率は使用率のセンサー(hook。M3a)が `usage.json` へ書くキャッシュで、中継は読むだけである(レーンの数だけ -API を呼ばない)。 +使用率は、アカウントごと・登録の世代ごとのキャッシュ(`usage/<名前>/<世代>.json`)を NDF の status line が書き、 +中継は読むだけである(#3864 の決定 4)。認証の失敗で外した間は `held.json`、上限の行の観測は `limited.json` が持ち、 +どちらも名前の下に世代ごとの項目を持つ(書き手は自分の世代の項目だけを書く)。 """ from __future__ import annotations import json -from pathlib import Path +import re +from datetime import datetime, timedelta, tzinfo +from pathlib import Path, PurePosixPath from typing import Any, Mapping, Optional +from zoneinfo import ZoneInfo -from ndf.contracts import facts -from ndf.domains.relay import account_decide, signals +from ndf.contracts import facts, limits +from ndf.domains.relay import account_decide, account_registry, signals NAME_RE = signals.NAME_RE +WINDOWS = account_registry.WINDOWS +SCOPED = "seven_day_scoped" # モデル別の週の窓。窓の名前は `seven_day_scoped/<識別>` +FULL = 100.0 +WINDOW_WORDS = (("five_hour", re.compile(r"\bsession\b", re.I)), ("seven_day", re.compile(r"\bweek(?:ly)?\b", re.I))) +RESETS_RE = re.compile(r"\bresets\s+(\d{1,2})(?::(\d{2}))?\s*([ap]m)\b(?:\s*\(([^)]+)\))?", re.I) class AccountError(ValueError): @@ -33,8 +42,30 @@ def pin_path(state_dir: Path) -> Path: return accounts_dir(state_dir) / "pinned.json" -def usage_path(state_dir: Path) -> Path: - return accounts_dir(state_dir) / "usage.json" +def usage_dir(state_dir: Path) -> Path: + """使用率のキャッシュの保存先(ファイルの表の `relay-usage` の `path` の先頭)。""" + return accounts_dir(state_dir) / PurePosixPath(facts.value("ndf-files", "relay-usage", "path")).parts[0] + + +def usage_path(state_dir: Path, name: Optional[str] = None, generation: str = "") -> Path: + """アカウント 1 つ・登録の世代 1 つのキャッシュ(`usage/<名前>/<世代>.json`。世代が空文字なら `_.json`)。 + + `name` を省くと旧い 1 つのキャッシュ(`usage.json`)を返す。ラッパーの今の呼び手(`_limit_pick`)と + そのテストのためだけに残し、ラッパーが `usages` の新しい形へ移る単位(U9)で消す。 + """ + if name is None: + return accounts_dir(state_dir) / "usage.json" + if not account_registry.valid_name(name): # 登録名の検査(`..`・`/` を通さない) + raise AccountError(f"アカウントの名前の形が違う: {name}") + return usage_dir(state_dir) / name / f"{_gen(generation)}.json" + + +def held_path(state_dir: Path) -> Path: + return accounts_dir(state_dir) / facts.value("ndf-files", "relay-auth-held", "path") + + +def limits_path(state_dir: Path) -> Path: + return accounts_dir(state_dir) / facts.value("ndf-files", "relay-limit-seen", "path") def pinned(state_dir: Path) -> Optional[str]: @@ -75,8 +106,130 @@ def chosen(environ: Mapping[str, str], state_dir: Path) -> Optional[str]: return pinned(state_dir) -def usages(state_dir: Path) -> list[account_decide.Usage]: - """使用率のキャッシュ。無ければ空(センサーがまだ書いていない)、壊れていれば `AccountError`。""" +# ---------------------------------------------------------------- 使用率のキャッシュ(#3864 の決定 4) + +Windows = dict[str, tuple[float, float]] # 窓の名前 → (使用率, resets_at の Unix 秒) + + +def _gen(generation: str) -> str: + """世代をファイルの名前と記録のキーにする(空文字は `_`)。`GEN_RE` の形でなければ `AccountError`(1 つのパスの要素に限る)。""" + if not generation: + return "_" + if not account_registry.GEN_RE.fullmatch(generation): + raise AccountError("登録の世代の形が違う") + return generation + + +def _number(v: Any) -> Optional[float]: + return float(v) if isinstance(v, (int, float)) and not isinstance(v, bool) else None + + +def _window(v: Any) -> Optional[tuple[float, float]]: + if not isinstance(v, dict): + return None + percent, resets = _number(v.get("percent")), _number(v.get("resets_at")) + return None if percent is None or resets is None else (percent, resets) + + +def _flat(windows: Any) -> Windows: + """記録の `windows` を窓の名前ごとの対にする。形の違う窓は捨てる。""" + if not isinstance(windows, dict): + return {} + got = {k: w for k in WINDOWS if (w := _window(windows.get(k))) is not None} + scoped = windows.get(SCOPED) + if isinstance(scoped, dict): + got.update({f"{SCOPED}/{k}": w for k, v in scoped.items() if (w := _window(v)) is not None}) + return got + + +def _nested(windows: Windows) -> dict[str, Any]: + out: dict[str, Any] = {} + for k, (percent, resets) in windows.items(): + row = {"percent": percent, "resets_at": resets} + if k.startswith(f"{SCOPED}/"): + out.setdefault(SCOPED, {})[k.split("/", 1)[1]] = row + else: + out[k] = row + return out + + +def _read_json(path: Path) -> dict[str, Any]: + """JSON の object。無い・読めない・形が違えば空(I7)。""" + try: + data = json.loads(path.read_text(encoding="utf-8")) + except (OSError, ValueError): + return {} + return data if isinstance(data, dict) else {} + + +def _read_windows(path: Path) -> Windows: + return _flat(_read_json(path).get("windows")) + + +def _merge(prev: Optional[tuple[float, float]], new: tuple[float, float], now: float) -> Optional[tuple[float, float]]: + """書き込みの規則の窓ごとの比べ。失効した入力・古い入力では前の値を残し、同じ窓の使用率は減らさない。""" + if new[1] <= now or (prev is not None and new[1] < prev[1]): + return prev + if prev is None or new[1] > prev[1]: + return new + return (max(prev[0], new[0]), prev[1]) + + +def write_usage(path: Path, windows: Mapping[str, tuple[float, float]], now: float) -> None: + """status line と同じ形・同じ合わせ方で 1 つの記録を書く。錠が取れなければその回は書かない。 + + 錠は status line と同じ `<ファイル>.lock` のファイルの `flock`(待たない)。オーナーが生きている間はほかの書き手が奪えない。 + 錠の場所がファイルでなければ(ディレクトリなど)消さずにその回は書かない。 + """ + path.parent.mkdir(parents=True, exist_ok=True) + lock = _lock_path(path) + if lock.is_dir(): # status line と同じく、錠の場所を塞ぐものを消さずにその回は書かない + return + with signals.held(lock, 0.0) as got: + if not got: + return + prev = _read_windows(path) + merged = dict(prev) + for k, w in windows.items(): + got_w = _merge(prev.get(k), w, now) + if got_w is not None: + merged[k] = got_w + if merged != prev: + signals.replace_json(path, {"windows": _nested(merged), "recorded_at": now}) + + +def _lock_path(path: Path) -> Path: + return path.with_name(path.name + ".lock") + + +def usages( + state_dir: Path, store: Optional[Path] = None, now: Optional[float] = None, generations: Optional[Mapping[str, str]] = None +) -> list[account_decide.Usage]: + """登録済みアカウントの今の世代のキャッシュを名前の順に読み、上限の観測を重ねる。 + + リセットの時刻を過ぎた窓は 0% として読み、上限は過ぎていない窓のどれかが 100 以上か、上限の観測が続くとき。 + 読めない・窓の無い記録は返さない(使用率の分からないアカウント)。ただし上限の観測が続く名前は使用率の + 分からない上限の行(`percent` が None)で返す。`store` は登録簿の側の取得の記録を読む単位(U5b)で使う。 + `generations` を省くと旧い 1 つのキャッシュを読む(ラッパーの今の呼び手のため。`usage_path` の行)。 + """ + if generations is None or now is None: + return _legacy_usages(state_dir) + seen = {n: _read_windows(usage_path(state_dir, n, g)) for n, g in generations.items()} + limited = limits_seen(state_dir, now, generations, seen) + rows = [] + for name in sorted(generations): + w = seen[name] + if not w: + if name in limited: + rows.append(account_decide.Usage(name, None, True)) # type: ignore[arg-type] # 型の変更は U6 + continue + percent = max(p if r > now else 0.0 for p, r in w.values()) + full = any(p >= FULL for p, r in w.values() if r > now) + rows.append(account_decide.Usage(name, percent, full or name in limited)) + return rows + + +def _legacy_usages(state_dir: Path) -> list[account_decide.Usage]: path = usage_path(state_dir) if not path.is_file(): return [] @@ -92,15 +245,169 @@ def usages(state_dir: Path) -> list[account_decide.Usage]: def _usage(row: Any, path: Path) -> account_decide.Usage: try: - return account_decide.Usage( - name=str(row["name"]), - percent=float(row["percent"]), - limited=bool(row["limited"]), - ) + return account_decide.Usage(name=str(row["name"]), percent=float(row["percent"]), limited=bool(row["limited"])) except (KeyError, TypeError, ValueError) as exc: raise AccountError(f"使用率のキャッシュの行の形が違う({path}): {row!r}") from exc def write_usages(state_dir: Path, rows: list[account_decide.Usage]) -> None: - """使用率のキャッシュを書く(センサーとテストが使う)。""" + """旧い 1 つのキャッシュを書く(ラッパーのテストだけが使う。`usage_path` の行と同じ時期に消す)。""" signals.replace_json(usage_path(state_dir), {"accounts": [r._asdict() for r in rows]}) + + +# ---------------------------------------------------------------- 外した間と上限の観測(世代ごとの項目) + + +def _entries(path: Path) -> dict[str, dict[str, dict[str, Any]]]: + """`{"<名前>": {"<世代>": {...}}}` の形の記録。壊れていれば空、形の違う項目は捨てる。""" + return { + n: {g: e for g, e in v.items() if isinstance(e, dict) and _number(e.get("until")) is not None} + for n, v in _read_json(path).items() + if isinstance(v, dict) + } + + +def _current(path: Path, generations: Mapping[str, str]) -> dict[str, dict[str, Any]]: + """今の世代の項目だけ(名前 → 項目)。""" + data = _entries(path) + return {n: data[n][_gen(g)] for n, g in generations.items() if n in data and _gen(g) in data[n]} + + +def _rewrite(path: Path, edit: Any) -> None: + """錠の中で読み直し、`edit(data)` で変えて置き換える。錠を取れなければ `TimeoutError`。""" + path.parent.mkdir(parents=True, exist_ok=True) + with signals.held(path.with_name(path.name + ".lock"), limits.seconds("relay.signal-lock")) as got: + if not got: + raise TimeoutError(f"記録の錠を取れない: {path}") + data = _entries(path) + edit(data) + signals.replace_json(path, {n: v for n, v in data.items() if v}) + + +def _put(path: Path, name: str, generation: str, entry: dict[str, Any], now: float) -> None: + def edit(data: dict[str, dict[str, dict[str, Any]]]) -> None: + for v in data.values(): + for g in [g for g, e in v.items() if e["until"] <= now]: + del v[g] + data.setdefault(name, {})[_gen(generation)] = entry + + _rewrite(path, edit) + + +def held(state_dir: Path, now: float, generations: Mapping[str, str]) -> dict[str, float]: + """外した間の名前と終わりの時刻(終わりが `now` より後で、世代が今の登録と同じもの)。""" + return {n: float(e["until"]) for n, e in _current(held_path(state_dir), generations).items() if e["until"] > now} + + +def hold(state_dir: Path, name: str, generation: str, until: float, now: float) -> None: + """`name` の `generation` の項目だけを `until` まで外す。終わった項目は消し、ほかの世代の項目は変えない。""" + _put(held_path(state_dir), name, generation, {"until": until}, now) + + +def unhold(state_dir: Path, name: str) -> None: + """`name` の外した間を世代を問わず消す(`account use <名前>` の後)。""" + path = held_path(state_dir) + if name in _entries(path): + _rewrite(path, lambda data: data.pop(name, None)) + + +def see_limit(state_dir: Path, name: str, generation: str, seen_at: float, limit: tuple[float, Optional[str], Optional[float]]) -> None: + """上限の行を初めて見た観測を書く(自分の世代の項目だけ)。`limit` は `limit_until` の返り(until・窓の名前・その resets_at)。""" + until, window, window_resets_at = limit + entry = {"seen_at": seen_at, "until": until, "window": window, "window_resets_at": window_resets_at} + _put(limits_path(state_dir), name, generation, entry, seen_at) + + +def limits_seen( + state_dir: Path, now: float, generations: Mapping[str, str], windows: Mapping[str, Mapping[str, tuple[float, float]]] +) -> dict[str, tuple[float, float]]: + """解除に当たらない上限の観測(名前 → (見た時刻, until))。 + + 解くのは `now ≥ until` か、観測の窓がキャッシュで `window_resets_at` と `until` のどちらよりも後の 100 未満の窓に + 入れ替わったときだけ(`until` 以下の窓は上限より前の入力が遅れて届いたものとみなし、解かない)。 + """ + out = {} + for n, e in _current(limits_path(state_dir), generations).items(): + if now >= e["until"]: + continue + w, at = e.get("window"), _number(e.get("window_resets_at")) + cur = windows[n].get(w) if n in windows and isinstance(w, str) and at is not None else None + seen = _number(e.get("seen_at")) + if seen is None or (cur is not None and at is not None and cur[1] > max(at, e["until"]) and cur[0] < FULL): + continue + out[n] = (seen, float(e["until"])) + return out + + +def limit_until( + line: str, windows: Mapping[str, tuple[float, float]], seen_at: float, tz: tzinfo +) -> tuple[float, Optional[str], Optional[float]]: + """上限の行とキャッシュから (until, 窓の名前, 見た時刻のその窓の resets_at) を決める(「上限の観測」の順)。時計を読まない。""" + word = next((k for k, pat in WINDOW_WORDS if pat.search(line)), None) + at = _line_reset(line, seen_at, tz) + if at is not None: + until, zone = at + name = word or next((k for k, (_, r) in windows.items() if _hm(r, zone) == _hm(until, zone)), None) + return until, name, (windows[name][1] if name in windows else None) + if word is not None and word in windows and windows[word][1] > seen_at: + return windows[word][1], word, windows[word][1] + full = [(r, k) for k, (p, r) in windows.items() if r > seen_at and p >= FULL] + if full: + r, k = max(full) + return r, k, r + five = windows.get("five_hour") + if five is not None and five[1] > seen_at: + return five[1], None, None + return seen_at + limits.seconds("relay.limit-unknown"), None, None + + +def _hm(at: float, zone: tzinfo) -> tuple[int, int]: + t = datetime.fromtimestamp(at, zone) + return t.hour, t.minute + + +def _line_reset(line: str, seen_at: float, tz: tzinfo) -> Optional[tuple[float, tzinfo]]: + """行の `resets 3pm (Asia/Tokyo)` の時刻のうち、`seen_at` より後で最も近いもの(と読んだ時間帯)。読めなければ None。""" + m = RESETS_RE.search(line) + if m is None: + return None + minute = int(m.group(2)) if m.group(2) is not None else 0 + if not 1 <= int(m.group(1)) <= 12 or minute > 59: + return None + zone = tz + if m.group(4): + try: + zone = ZoneInfo(m.group(4).strip()) + except (ValueError, KeyError): + zone = tz + hour = int(m.group(1)) % 12 + (12 if m.group(3).lower() == "pm" else 0) + t = datetime.fromtimestamp(seen_at, zone).replace(hour=hour, minute=minute, second=0, microsecond=0) + if t.timestamp() <= seen_at: + t += timedelta(days=1) + return t.timestamp(), zone + + +def forget(state_dir: Path, store: Path, name: str, drop: str) -> None: + """`name` の `drop` の世代(操作した登録簿の前の世代)の外した間・上限の観測・キャッシュを消す。ほかの世代は残す。 + + 登録簿の排他の中で呼ぶ(`account_registry.register`・`unregister` の `settle`)。世代は登録ごとに新しいので、同じ状態の + 保存先を別の登録簿(`NDF_ACCOUNTS_DIR`)と共有していても、ほかの登録簿の同じ名前の記録は消さない。 + 登録簿の側の取得の記録(`store` の `.usage-fetch/<名前>/`)を消すのは、取得の記録を足す単位(U5b)で入れる。 + 錠を取れなければ `TimeoutError`、消せなければ `OSError`。 + """ + key = _gen(drop) + + def edit(data: dict[str, dict[str, dict[str, Any]]]) -> None: + if name in data: + data[name].pop(key, None) + + for path in (held_path(state_dir), limits_path(state_dir)): + entries = _entries(path) + if name in entries and key in entries[name]: + _rewrite(path, edit) + cache = usage_path(state_dir, name, drop) + lock = _lock_path(cache) + for p in (cache, lock): + p.unlink(missing_ok=True) + if cache.parent.is_dir() and not any(cache.parent.iterdir()): # ほかの世代のファイルが残れば名前のディレクトリも残す + cache.parent.rmdir() diff --git a/plugins/ndf/src/ndf/domains/relay/cli_account.py b/plugins/ndf/src/ndf/domains/relay/cli_account.py index 40571a7c05..7e0afb60d0 100644 --- a/plugins/ndf/src/ndf/domains/relay/cli_account.py +++ b/plugins/ndf/src/ndf/domains/relay/cli_account.py @@ -10,6 +10,7 @@ import os import shutil import sys +import time from pathlib import Path from typing import Any, Callable, NamedTuple, Optional @@ -33,7 +34,9 @@ def run(args: argparse.Namespace) -> int: state_dir = identity.load().state_dir if args.account_action == "use": accounts.use(state_dir, args.name) - return result.emit(result.result(TOOL, result.OK, f"アカウント {args.name} を指定した")) + # 利用者が直して指定したアカウントを、外した間の残りで飛ばさない(I8)。指定は済んだので、解けなくても成功で返して警告に分ける + warnings = _cleanup(lambda: accounts.unhold(state_dir, args.name), "外した間を解けなかった(指定は保存した。打ち直してよい)") + return result.emit(result.result(TOOL, result.OK, f"アカウント {args.name} を指定した", warnings=warnings)) if args.account_action == "clear": done = accounts.clear(state_dir) return result.emit(result.result(TOOL, result.OK, "指定を消した" if done else "指定は無かった")) @@ -51,9 +54,31 @@ def _capacity_arg(v: str) -> Optional[float]: return x +def _cleanup(run: Callable[[], None], what: str) -> list[str]: + """確定した操作の後の記録の後始末を打つ。失敗は結果の警告の 1 行にし、確定した操作を失敗にしない(打ち直しで認証を繰り返させない)。""" + try: + run() + except OSError as exc: # 錠の待ちきれない(TimeoutError)・消せない + return [f"{what}: {exc}"] + return [] + + +def _forget_after(state_dir: Path, store: Path, name: str, warnings: list[str]) -> Callable[[Optional[str]], None]: + """登録簿の排他の中で、操作した登録の前の世代の記録を消す呼び出し(I8)。失敗は `warnings` に足す。""" + + def run(gone: Optional[str]) -> None: + if gone is not None: + what = "前の登録の使用率・外した間・上限の記録を消せなかった(登録の操作は済んだ。打ち直さない)" + warnings.extend(_cleanup(lambda: accounts.forget(state_dir, store, name, gone), what)) + + return run + + def _acc_add(store: Path, a: argparse.Namespace) -> int: code = (sys.stdin.readline() if a.code == "-" else a.code) if a.code is not None else None - got = account_login.add(store, a.name, code, os.environ) + warnings: list[str] = [] + forget = _forget_after(identity.load().state_dir, store, a.name, warnings) + got = account_login.add(store, a.name, code, os.environ, settle=lambda old, _new: forget(old)) if got.needs_code: detail = f"認可の URL: {got.url} をブラウザで開き、出た認可コードを {got.expires_at} までに渡す: printf '%s\\n' '<コード>' | ndf relay account add {a.name} --code -" return result.emit( @@ -68,6 +93,7 @@ def _acc_add(store: Path, a: argparse.Namespace) -> int: result.OK, f"登録した: {a.name}({who})", items=[{"name": a.name, "kind": "oauth", "email": got.email, "org_name": got.org_name}], + warnings=warnings, ) ) @@ -110,7 +136,10 @@ def _acc_use(store: Path, a: argparse.Namespace) -> int: def _acc_list(store: Path, a: argparse.Namespace) -> int: state_dir = identity.load().state_dir - rows, warnings = account_registry.list_rows(store, os.environ, accounts.pinned(state_dir), accounts.usages(state_dir)) + now = time.time() + rows, warnings = account_registry.list_rows( + store, os.environ, accounts.pinned(state_dir), lambda generations: accounts.usages(state_dir, store, now, generations) + ) metrics = {"accounts": sum(r["kind"] == "oauth" for r in rows), "keys": sum(r["kind"] == "api_key" for r in rows)} summary = f"登録: アカウント {metrics['accounts']} 件・API キー {metrics['keys']} 件" if rows else "登録済みのアカウントは無い" return result.emit(result.result(TOOL, result.OK, summary, items=rows, metrics=metrics, warnings=warnings)) @@ -122,20 +151,32 @@ def _acc_capacity(store: Path, a: argparse.Namespace) -> int: def _acc_remove(store: Path, a: argparse.Namespace) -> int: - if a.target != account_registry.METERED and a.target in account_registry.names(store): - # 古い claude ではログアウトできないまま登録だけを外さない。登録も symlink も残して止まる(#3691) + name = a.target + if not (account_registry.valid_name(name) and (name in account_registry.names(store) or account_registry.removing(store, name))): + row = account_metered.remove(store, name) + return result.emit(result.result(TOOL, result.OK, f"外した: {name}", items=[row])) + + def release() -> bool: + # 登録の排他の中で呼ばれる。古い claude ではログアウトできないまま登録だけを外さない。登録も symlink も残して止まる(#3691) claude = shutil.which(account_login.claude_adapter.CLAUDE) if claude is not None: - account_login.require_claude(claude, account_login.auth_env(os.environ, account_registry.account_dir(store, a.target))) - account_registry.detach(store, a.target) # logout が設定ディレクトリの中を消す前に、共有の項目への symlink を外す - out = account_login.logout(store, a.target, os.environ) - account_registry.unregister(store, a.target) - warnings = None if out else ["claude auth logout が通らなかった(登録は外した)"] - return result.emit( - result.result(TOOL, result.OK, f"外した: {a.target}", items=[{"name": a.target, "kind": "oauth"}], warnings=warnings) - ) - row = account_metered.remove(store, a.target) - return result.emit(result.result(TOOL, result.OK, f"外した: {a.target}", items=[row])) + account_login.require_claude(claude, account_login.auth_env(os.environ, account_registry.account_dir(store, name))) + account_registry.detach(store, name) # logout が設定ディレクトリの中を消す前に、共有の項目への symlink を外す + return account_login.logout(store, name, os.environ) + + warnings: list[str] = [] + got = account_registry.remove_account(store, name, release, _forget_after(identity.load().state_dir, store, name, warnings)) + item = {"name": name, "kind": "oauth"} + if got.leftovers: + # 前の削除が消し残した世代だけを消した。今の登録は外していない(外すのは残りが無くなった後の削除) + if got.kept: + warnings.append( + f"同じ名前の今の登録は残した(前の削除の後に登録し直された)。外すなら ndf relay account remove {name} をもう一度打つ" + ) + return result.emit(result.result(TOOL, result.OK, f"外した登録の残りを消した: {name}", items=[item], warnings=warnings)) + if not got.logged_out: + warnings.insert(0, "claude auth logout が通らなかった(登録は外した)") + return result.emit(result.result(TOOL, result.OK, f"外した: {name}", items=[item], warnings=warnings)) def _acc_check(store: Path, a: argparse.Namespace) -> int: diff --git a/plugins/ndf/src/ndf/domains/statusline/statusline.sh b/plugins/ndf/src/ndf/domains/statusline/statusline.sh index ca9b9d8bbc..638a1f7a05 100755 --- a/plugins/ndf/src/ndf/domains/statusline/statusline.sh +++ b/plugins/ndf/src/ndf/domains/statusline/statusline.sh @@ -4,6 +4,57 @@ # [<モデル名> 使用トークン │ <サブエージェントの説明> 使用トークン · ...] <接続先> input=$(cat) +# 登録済みアカウントの子だけが持つ NDF_ACCOUNT_USAGE_FILE へ、入力の rate_limits の 5 時間・7 日の窓を書く(#3864)。 +# 窓ごとに resets_at の新しいほう、同じなら使用率の大きいほうを残し、失効した入力と古い入力で値を下げない。 +# 入力に無い窓とモデル別の窓(seven_day_scoped)は前の値のまま。書けない・jq が無い・錠を取る手段(flock か perl)が無いときは +# 何もしない(表示は変えない) +# 変数の無い子は外部コマンドを起動しない。変数のある子も、値が前と同じ再描画は jq 1 回で終える +usage_merged() { + local src="$1" + [ -f "$src" ] || src=/dev/null + printf '%s' "$input" | jq -cn --argjson now "$now" ' + input as $in + | (try input catch null) as $prev + | ($in.rate_limits | if type == "object" then . else {} end) as $r + | ($prev | if type == "object" and (.windows | type) == "object" then .windows else {} end) as $old + | reduce ([("five_hour", "seven_day") as $k | $r[$k] + | select(type == "object" and (.used_percentage | type) == "number" and (.resets_at | type) == "number") + | {key: $k, value: {percent: .used_percentage, resets_at: .resets_at}}][]) as $e ($old; + .[$e.key] as $p + | if $e.value.resets_at <= $now then . + elif ($p | type) != "object" or ($p.resets_at | type) != "number" or ($p.percent | type) != "number" then .[$e.key] = $e.value + elif $e.value.resets_at < $p.resets_at then . + elif $e.value.resets_at > $p.resets_at then .[$e.key] = $e.value + else .[$e.key].percent = ([$p.percent, $e.value.percent] | max) end) + | if . == $old then empty else {windows: ., recorded_at: $now} end' - "$src" 2>/dev/null +} +record_usage() { + local f="${NDF_ACCOUNT_USAGE_FILE:-}" now merged + case "$f" in /*) ;; *) return 0 ;; esac + now=${EPOCHSECONDS:-$(date +%s)} + # 錠の外で 1 回比べ、変わるときだけ錠を取って読み直す + [ -n "$(usage_merged "$f")" ] || return 0 + # 錠は <ファイル>.lock のファイルの flock(2)(accounts.write_usage の fcntl.flock と同じ)。オーナーが生きている間は奪えず、 + # 死ねば OS が解く。flock コマンドが無い環境(標準の macOS)は perl の flock で同じ錠を取る + command -v flock >/dev/null 2>&1 || command -v perl >/dev/null 2>&1 || return 0 + [ -d "${f%/*}" ] || mkdir -p "${f%/*}" 2>/dev/null || return 0 + # 錠の場所がファイルとして開けなければ(ディレクトリなど)消さずにその回は書かない。取れなければその回は書かない。一時ファイルは同じ場所に mktemp で排他的に作り、名前を変えて置き換える + ( + if command -v flock >/dev/null 2>&1; then + flock -n 9 + else + perl -MFcntl=:flock -e 'open(my $l, ">&=", 9) or exit 1; flock($l, LOCK_EX | LOCK_NB) or exit 1' + fi || exit 0 + merged=$(usage_merged "$f") + [ -n "$merged" ] || exit 0 + tmp=$(mktemp "$f.XXXXXX" 2>/dev/null) || exit 0 + printf '%s\n' "$merged" > "$tmp" 2>/dev/null && mv -f "$tmp" "$f" 2>/dev/null + rm -f "$tmp" 2>/dev/null + ) 2>/dev/null 9>>"$f.lock" + return 0 +} +record_usage + # claude root のパスを取得(project_dir を優先し、なければ current_dir を使用) # jq 不在や無効な JSON 入力時に stderr が statusLine 描画に漏れないよう 2>/dev/null で抑制 claude_root=$(echo "$input" | jq -r '.workspace.project_dir // .workspace.current_dir // empty' 2>/dev/null) diff --git a/plugins/ndf/tests/domains/relay/test_account_registry.py b/plugins/ndf/tests/domains/relay/test_account_registry.py index 9e794aef4a..50d105190b 100644 --- a/plugins/ndf/tests/domains/relay/test_account_registry.py +++ b/plugins/ndf/tests/domains/relay/test_account_registry.py @@ -3,6 +3,7 @@ from __future__ import annotations import json +import shutil import os import signal import stat @@ -103,10 +104,143 @@ def test_generation_reads_the_registered_generation(tmp_path): _account(tmp_path, "work1", generation="g1") _account(tmp_path, "work2") assert reg.generation(tmp_path, "work1") == "g1" - assert reg.generation(tmp_path, "work2") == "" and reg.generation(tmp_path, "none") == "" + assert reg.generation(tmp_path, "none") == "" + # 世代を持たない旧い登録は、登録簿ごとに違う世代を持つ(同じ状態の保存先を共有しても記録が重ならない) + legacy = reg.generation(tmp_path, "work2") + assert legacy == reg.legacy_generation(tmp_path, "work2") and reg.GEN_RE.fullmatch(legacy) + assert reg.load(tmp_path, "work2").generation == legacy + _account(tmp_path / "other", "work2") + assert reg.generation(tmp_path / "other", "work2") not in ("", "_", legacy) (tmp_path / "work2" / reg.ACCOUNT_FILE).write_text("{broken") with pytest.raises(reg.AccountError): reg.generation(tmp_path, "work2") + # 世代はパスの要素になるので、1 つの安全な要素の形でなければ壊れた登録として扱う + for bad in ("../x", "/abs", "..", "a/b", 7): + _account(tmp_path, "work3", generation=bad) + with pytest.raises(reg.AccountError): + reg.generation(tmp_path, "work3") + with pytest.raises(reg.AccountError): + reg.load(tmp_path, "work3") + shutil.rmtree(tmp_path / "work3") + + +def test_register_issues_a_new_generation_and_settles_inside_the_lock(tmp_path): + store = tmp_path / "store" + seen = [] + + def settle(old, new): + # 登録の排他の中で呼ばれる(ほかの書き手は同じ名前の排他を取れない) + with pytest.raises(reg.AccountLockTimeout): + with reg.locked(store, "work1", wait=0): + pass + seen.append((old, new, reg.generation(store, "work1"))) + + gens = [] + for i in range(2): + staging = tmp_path / f"staging{i}" + staging.mkdir() + (staging / reg.CRED_FILE).write_text("{}") + gens.append(reg.register(store, "work1", staging, reg.Identity("a@example.com", "", ""), float(i), settle)) + assert gens[0] != gens[1] and all(reg.GEN_RE.fullmatch(g) for g in gens) + assert seen == [(None, gens[0], gens[0]), (gens[0], gens[1], gens[1])] + assert reg.load(store, "work1").generation == gens[1] + gone = [] + reg.unregister(store, "work1", gone.append) + assert gone == [gens[1]] and reg.names(store) == [] + + +def test_unregister_keeps_the_generation_of_a_partial_removal_and_retries(tmp_path, monkeypatch): + store = tmp_path / "store" + _account(store, "work1", generation="g1") + real = reg.shutil.rmtree + + def partial(path, ignore_errors=False): # account.json だけを消して、ほかの項目で失敗する(権限・使用中) + (Path(path) / reg.ACCOUNT_FILE).unlink(missing_ok=True) + + monkeypatch.setattr(reg.shutil, "rmtree", partial) + gone = [] + with pytest.raises(OSError, match="打ち直す"): + reg.unregister(store, "work1", gone.append) + assert gone == ["g1"] and reg.names(store) == [] and reg.removing(store, "work1") + monkeypatch.setattr(reg.shutil, "rmtree", real) + reg.unregister(store, "work1", gone.append) # 同じ削除の打ち直しで、残った世代の後始末と削除をやり直す + assert gone == ["g1", "g1"] and not reg.removing(store, "work1") and not (store / reg.REMOVING_DIR).exists() + + +def test_remove_account_rerun_clears_leftovers_first_and_keeps_a_new_registration(tmp_path, monkeypatch): + store = tmp_path / "store" + _account(store, "work1", generation="g1") + real = reg.shutil.rmtree + + def partial(path, ignore_errors=False): # account.json だけを消して、ほかの項目で失敗する + (Path(path) / reg.ACCOUNT_FILE).unlink(missing_ok=True) + + monkeypatch.setattr(reg.shutil, "rmtree", partial) + with pytest.raises(OSError): + reg.unregister(store, "work1") + monkeypatch.setattr(reg.shutil, "rmtree", real) + _account(store, "work1", generation="g2") # 打ち直しの前に、別の端末が同じ名前で登録し直した + released, gone = [], [] + got = reg.remove_account(store, "work1", lambda: released.append(1) or True, gone.append) + # 案内どおりの打ち直しは残りだけを消し、今の登録をログアウトも削除もしない + assert got == reg.Removal(leftovers=True, kept=True) and released == [] and gone == ["g1"] and not reg.removing(store, "work1") + assert reg.names(store) == ["work1"] and reg.generation(store, "work1") == "g2" + got = reg.remove_account(store, "work1", lambda: released.append(1) or True, gone.append) # 残りが無くなった後の削除で今の登録を外す + assert got == reg.Removal(leftovers=False, kept=False, logged_out=True) and released == [1] and gone == ["g1", "g2"] + assert reg.names(store) == [] + with pytest.raises(reg.NotRegistered): + reg.remove_account(store, "work1", lambda: True) + + +def test_remove_account_rerun_keeps_a_new_registration_when_leftovers_vanish_while_waiting(tmp_path, monkeypatch): + store = tmp_path / "store" + _account(store, "work1", generation="g1") + real = reg.shutil.rmtree + + def partial(path, ignore_errors=False): + (Path(path) / reg.ACCOUNT_FILE).unlink(missing_ok=True) + + monkeypatch.setattr(reg.shutil, "rmtree", partial) + with pytest.raises(OSError): + reg.unregister(store, "work1") + monkeypatch.setattr(reg.shutil, "rmtree", real) + _account(store, "work1", generation="g2") + real_locked = reg.locked + + def other_terminal_first(s, n, **kw): # 排他を待つ間に、別の端末の打ち直しが残りを片付けた + reg._finish_removal(s, n, None) + return real_locked(s, n, **kw) + + monkeypatch.setattr(reg, "locked", other_terminal_first) + released = [] + got = reg.remove_account(store, "work1", lambda: released.append(1) or True) + assert got == reg.Removal(leftovers=True, kept=True) and released == [] + assert reg.names(store) == ["work1"] and reg.generation(store, "work1") == "g2" + + +def test_remove_account_logs_out_and_unregisters_inside_the_register_lock(tmp_path): + store = tmp_path / "store" + _account(store, "work1", generation="g1") + seen = [] + + def release(): + # ログアウトの間も登録の排他を持つ(別の端末の登録し直しは、登録を外し終えるまで待つ) + with pytest.raises(reg.AccountLockTimeout): + with reg.locked(store, "work1", wait=0): + pass + seen.append(reg.generation(store, "work1")) + return False + + gone = [] + got = reg.remove_account(store, "work1", release, gone.append) + assert got == reg.Removal(leftovers=False, kept=False, logged_out=False) and seen == ["g1"] and gone == ["g1"] + assert reg.names(store) == [] + + +def test_unregister_without_a_registration_does_not_settle(tmp_path): + gone = [] + reg.unregister(tmp_path / "store", "work1", gone.append) + assert gone == [] @pytest.mark.parametrize("value", ["1", "true", "TRUE", "yes", "On", " on "]) @@ -265,7 +399,9 @@ def test_list_rows_hide_secrets_and_mark_broken(tmp_path): } reg.write(reg.book_path(tmp_path), book) usage = [account_decide.Usage(name="work1", percent=40.0, limited=False)] - rows, warnings = reg.list_rows(tmp_path, {"NDF_SUPERVISE_CLAUDE_FALLBACK": "AWS_REGION=us-east-1 AWS_PROFILE=p"}, "work1", usage) + rows, warnings = reg.list_rows( + tmp_path, {"NDF_SUPERVISE_CLAUDE_FALLBACK": "AWS_REGION=us-east-1 AWS_PROFILE=p"}, "work1", lambda _: usage + ) by = {r["name"]: r for r in rows} assert by["work1"]["pinned"] and by["work1"]["percent"] == 40.0 and by["work1"]["state"] == "使える" assert by["work2"]["state"] == "broken" and len(warnings) == 1 @@ -361,7 +497,7 @@ def test_list_rows_states_saved_metered_and_key_rows(tmp_path): account_decide.Usage(name="c-limited", percent=100.0, limited=True), account_decide.Usage(name="a-relogin", percent=5.0, limited=False), ] - rows, warnings = reg.list_rows(tmp_path, {}, None, usage) + rows, warnings = reg.list_rows(tmp_path, {}, None, lambda _: usage) assert warnings == [] assert rows == [ { @@ -412,12 +548,12 @@ def test_list_rows_broken_metered_broken_book_and_empty_env(tmp_path): reg.make_store(tmp_path) reg.metered_path(tmp_path).write_text("[]") reg.book_path(tmp_path).write_text('{"keys": []}') - rows, warnings = reg.list_rows(tmp_path, {}, None, []) + rows, warnings = reg.list_rows(tmp_path, {}, None, lambda _: []) assert rows == [{"name": "metered", "kind": "metered", "source": "saved", "state": "壊れている(設定なしとして扱う)"}] assert len(warnings) == 1 and warnings[0].endswith("(API キーを使わずに動く)") - rows, _ = reg.list_rows(tmp_path, {"NDF_SUPERVISE_CLAUDE_FALLBACK": ""}, None, []) + rows, _ = reg.list_rows(tmp_path, {"NDF_SUPERVISE_CLAUDE_FALLBACK": ""}, None, lambda _: []) assert rows == [] - assert reg.list_rows(tmp_path / "none", {}, "x", []) == ([], []) + assert reg.list_rows(tmp_path / "none", {}, "x", lambda _: []) == ([], []) STATUS_CLAUDE = """#!/bin/sh diff --git a/plugins/ndf/tests/domains/relay/test_relay_cli.py b/plugins/ndf/tests/domains/relay/test_relay_cli.py index 8d361cb509..1b86dccdda 100644 --- a/plugins/ndf/tests/domains/relay/test_relay_cli.py +++ b/plugins/ndf/tests/domains/relay/test_relay_cli.py @@ -7,6 +7,7 @@ import json import os import subprocess +from pathlib import Path import pytest @@ -402,3 +403,175 @@ def test_run_in_a_vanished_work_dir_does_not_launch_in_the_dir_pwd_names(tmp_pat other.mkdir() code, err, called, d, _ = _run_in_a_vanished_dir(tmp_path, monkeypatch, capsys, proc_readable=False, pwd=str(other)) _assert_launch_refused(code, err, called, d, str(other)) + + +# ---------------------------------------------------------------- 使用率と外した間の記録(#3864 U4) + + +def _registered(store, name: str, generation: str) -> None: + from ndf.domains.relay import account_registry + + d = store / name + d.mkdir(parents=True) + row = {"name": name, "email": f"{name}@example.com", "needs_relogin": False, "generation": generation} + (d / account_registry.ACCOUNT_FILE).write_text(json.dumps(row), encoding="utf-8") + + +def test_account_list_reads_the_cache_of_the_current_generation(tmp_path, monkeypatch, capsys, last_result): + import time + + store = tmp_path / "store" + monkeypatch.setenv("NDF_ACCOUNTS_DIR", str(store)) + _registered(store, "work1", "g1") + _registered(store, "work2", "g2") + (store / "work3").mkdir() + (store / "work3" / "account.json").write_text("{", encoding="utf-8") # 壊れた登録は一覧の警告に回り、止めない + state = identity.load().state_dir + later = time.time() + 3600 + accounts.write_usage(accounts.usage_path(state, "work1", "g1"), {"five_hour": (42.0, later)}, time.time()) + accounts.write_usage(accounts.usage_path(state, "work2", "old"), {"five_hour": (99.0, later)}, time.time()) + assert cli.main(["account", "list"]) == 0 + by = {r["name"]: r for r in last_result(capsys.readouterr().out)["items"]} + assert by["work1"]["percent"] == 42.0 and by["work1"]["state"] == "使える" + assert by["work2"]["percent"] is None and by["work2"]["state"] == "残量不明" + assert by["work3"]["state"] == "broken" + + +def test_i8_account_use_releases_the_held_account(capsys): + state = identity.load().state_dir + accounts.hold(state, "work1", "", 4_000_000_000.0, 1.0) + assert cli.main(["account", "use", "work1"]) == 0 + assert accounts.held(state, 1.0, {"work1": ""}) == {} + + +def _relogin(monkeypatch, tmp_path): + """`account_login.add` を、ログインの済んだ設定ディレクトリを実際の `account_registry.register` へ渡す形にする。""" + from ndf.domains.relay import account_login, account_registry + + def fake_add(store_, name, code, environ, settle=None): + staging = tmp_path / f"staging-{len(list(tmp_path.iterdir()))}" + staging.mkdir() + (staging / account_registry.CRED_FILE).write_text("{}", encoding="utf-8") + account_registry.register(store_, name, staging, account_registry.Identity(f"{name}@example.com", "", ""), 1.0, settle) + return account_login.Added(name=name, needs_code=False, email=f"{name}@example.com") + + monkeypatch.setattr(account_login, "add", fake_add) + + +def test_i8_add_and_remove_forget_the_old_generation(tmp_path, monkeypatch, capsys, last_result): + from ndf.domains.relay import account_login, account_registry + + store = tmp_path / "store" + monkeypatch.setenv("NDF_ACCOUNTS_DIR", str(store)) + state = identity.load().state_dir + _relogin(monkeypatch, tmp_path) + assert cli.main(["account", "add", "work1", "--code", "c"]) == 0 + first = account_registry.generation(store, "work1") + assert account_registry.GEN_RE.fullmatch(first) + # 前の世代の外した間・キャッシュと、ほかの登録簿(同じ状態の保存先を共有する)の同じ名前の世代の記録 + for g in (first, "other"): + accounts.hold(state, "work1", g, 4_000_000_000.0, 1.0) + accounts.write_usage(accounts.usage_path(state, "work1", g), {"five_hour": (10.0, 4_000_000_000.0)}, 1.0) + assert cli.main(["account", "add", "work1", "--code", "c"]) == 0 # 同じ名前の登録し直し + second = account_registry.generation(store, "work1") + assert second != first and "warnings" not in last_result(capsys.readouterr().out) + assert accounts.held(state, 1.0, {"work1": first}) == {} and accounts.held(state, 1.0, {"work1": second}) == {} + assert accounts.held(state, 1.0, {"work1": "other"}) == {"work1": 4_000_000_000.0} + # 登録し直す前の子の遅れた書き込みは前の世代のファイルへ入り、今の世代の記録にならない + accounts.write_usage(accounts.usage_path(state, "work1", first), {"five_hour": (99.0, 4_000_000_000.0)}, 1.0) + assert accounts.usages(state, store, 1.0, {"work1": second}) == [] + accounts.hold(state, "work1", second, 4_000_000_000.0, 1.0) + monkeypatch.setattr(cli_account.shutil, "which", lambda _: None) + monkeypatch.setattr(account_login, "logout", lambda *a: True) + assert cli.main(["account", "remove", "work1"]) == 0 + assert accounts.held(state, 1.0, {"work1": second}) == {} + assert accounts.held(state, 1.0, {"work1": "other"}) == {"work1": 4_000_000_000.0} + assert sorted(p.name for p in accounts.usage_path(state, "work1", "other").parent.iterdir()) == [ + f"{first}.json", + f"{first}.json.lock", + "other.json", + "other.json.lock", + ] + + +def test_i8_cleanup_failures_are_warnings_after_the_account_operation(tmp_path, monkeypatch, capsys, last_result): + from ndf.domains.relay import account_login, account_registry + + store = tmp_path / "store" + monkeypatch.setenv("NDF_ACCOUNTS_DIR", str(store)) + _relogin(monkeypatch, tmp_path) + assert cli.main(["account", "add", "work1", "--code", "c"]) == 0 + + def busy(*_a): + raise TimeoutError("記録の錠を取れない") + + monkeypatch.setattr(accounts, "forget", busy) + monkeypatch.setattr(accounts, "unhold", busy) + assert cli.main(["account", "add", "work1", "--code", "c"]) == 0 # 登録し直しは済み、後始末の失敗は警告 + got = last_result(capsys.readouterr().out) + assert got["status"] == "ok" and "打ち直さない" in got["warnings"][0] + assert cli.main(["account", "use", "work1"]) == 0 + got = last_result(capsys.readouterr().out) + assert got["status"] == "ok" and accounts.pinned(identity.load().state_dir) == "work1" and got["warnings"] + monkeypatch.setattr(cli_account.shutil, "which", lambda _: None) + monkeypatch.setattr(account_login, "logout", lambda *a: True) + assert cli.main(["account", "remove", "work1"]) == 0 + got = last_result(capsys.readouterr().out) + assert got["status"] == "ok" and got["warnings"] and account_registry.names(store) == [] + + +def test_i8_remove_that_leaves_files_can_be_rerun_to_finish(tmp_path, monkeypatch, capsys, last_result): + from ndf.domains.relay import account_login, account_registry + + store = tmp_path / "store" + monkeypatch.setenv("NDF_ACCOUNTS_DIR", str(store)) + state = identity.load().state_dir + _relogin(monkeypatch, tmp_path) + assert cli.main(["account", "add", "work1", "--code", "c"]) == 0 + gen = account_registry.generation(store, "work1") + accounts.hold(state, "work1", gen, 4_000_000_000.0, 1.0) + monkeypatch.setattr(cli_account.shutil, "which", lambda _: None) + logouts = [] + monkeypatch.setattr(account_login, "logout", lambda *a: logouts.append(a) or True) + real = account_registry.shutil.rmtree + + def partial(path, ignore_errors=False): # account.json を消した後で、ほかの項目の削除に失敗する + (Path(path) / account_registry.ACCOUNT_FILE).unlink(missing_ok=True) + + monkeypatch.setattr(account_registry.shutil, "rmtree", partial) + assert cli.main(["account", "remove", "work1"]) != 0 + got = last_result(capsys.readouterr().out) + assert got["status"] != "ok" and "打ち直す" in got["summary"] + assert account_registry.names(store) == [] and account_registry.removing(store, "work1") + monkeypatch.setattr(account_registry.shutil, "rmtree", real) + accounts.hold(state, "work1", gen, 4_000_000_000.0, 1.0) # 後始末をやり直すことを見るため、同じ世代の項目を戻す + assert cli.main(["account", "remove", "work1"]) == 0 # 同じ削除の打ち直しで残りの後始末に戻る + got = last_result(capsys.readouterr().out) + assert got["status"] == "ok" and not account_registry.removing(store, "work1") and len(logouts) == 1 + assert accounts.held(state, 1.0, {"work1": gen}) == {} + + +def test_i8_remove_rerun_after_a_new_registration_keeps_it(tmp_path, monkeypatch, capsys, last_result): + from ndf.domains.relay import account_login, account_registry + + store = tmp_path / "store" + monkeypatch.setenv("NDF_ACCOUNTS_DIR", str(store)) + _relogin(monkeypatch, tmp_path) + assert cli.main(["account", "add", "work1", "--code", "c"]) == 0 + monkeypatch.setattr(cli_account.shutil, "which", lambda _: None) + logouts = [] + monkeypatch.setattr(account_login, "logout", lambda *a: logouts.append(a) or True) + real = account_registry.shutil.rmtree + monkeypatch.setattr(account_registry.shutil, "rmtree", lambda path, ignore_errors=False: None) # 中身を消せずに止まる + assert cli.main(["account", "remove", "work1"]) != 0 + capsys.readouterr() + monkeypatch.setattr(account_registry.shutil, "rmtree", real) + assert cli.main(["account", "add", "work1", "--code", "c"]) == 0 # 打ち直しの前に別の端末が登録し直した + new = account_registry.generation(store, "work1") + capsys.readouterr() + assert cli.main(["account", "remove", "work1"]) == 0 # 案内どおりの打ち直し + got = last_result(capsys.readouterr().out) + assert got["status"] == "ok" and "残りを消した" in got["summary"] and "もう一度" in got["warnings"][-1] + assert len(logouts) == 1 and account_registry.names(store) == ["work1"] and account_registry.generation(store, "work1") == new + assert cli.main(["account", "remove", "work1"]) == 0 # 残りが無くなった後の削除で今の登録を外す + assert len(logouts) == 2 and account_registry.names(store) == [] diff --git a/plugins/ndf/tests/domains/relay/test_relay_usage_cache.py b/plugins/ndf/tests/domains/relay/test_relay_usage_cache.py new file mode 100644 index 0000000000..e970fe17de --- /dev/null +++ b/plugins/ndf/tests/domains/relay/test_relay_usage_cache.py @@ -0,0 +1,261 @@ +"""中継のアカウントの使用率のキャッシュ・認証の失敗で外した間・上限の観測(#3864 の 1〜3・6・11、I6・I7・I8・I11)。""" + +from __future__ import annotations + +import json +import os +from pathlib import Path + +from ndf.domains.relay import accounts +from ndf.domains.relay.account_decide import Usage + +NOW = 1_795_000_000.0 +LATER = NOW + 3600 + + +def _cache(state: Path, name: str, generation: str, windows: dict) -> Path: + path = accounts.usage_path(state, name, generation) + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps({"windows": windows, "recorded_at": NOW}), encoding="utf-8") + return path + + +def _windows(path: Path) -> dict: + return json.loads(path.read_text(encoding="utf-8"))["windows"] + + +def test_3864_1_write_usage_keeps_the_newer_value_per_window(tmp_path): + path = accounts.usage_path(tmp_path, "work1", "g1") + assert path == tmp_path / "relay" / "accounts" / "usage" / "work1" / "g1.json" + assert accounts.usage_path(tmp_path, "work1", "") == path.with_name("_.json") + accounts.write_usage(path, {"five_hour": (100.0, LATER), "seven_day": (30.0, LATER + 86400)}, NOW) + assert _windows(path) == { + "five_hour": {"percent": 100.0, "resets_at": LATER}, + "seven_day": {"percent": 30.0, "resets_at": LATER + 86400}, + } + # 同じ窓の古い入力(同じ resets_at で小さい使用率)・resets_at の古い入力・既に失効した入力では下げない + accounts.write_usage(path, {"five_hour": (40.0, LATER)}, NOW) + accounts.write_usage(path, {"five_hour": (10.0, LATER - 60)}, NOW) + accounts.write_usage(path, {"five_hour": (5.0, NOW - 1)}, NOW) + assert _windows(path)["five_hour"] == {"percent": 100.0, "resets_at": LATER} + # 新しい窓は使用率が小さくても採る。入力に無い窓とモデル別の窓は前の値を残す + scoped = {"claude-opus-4": {"percent": 31.0, "resets_at": LATER}} + data = json.loads(path.read_text(encoding="utf-8")) + data["windows"]["seven_day_scoped"] = scoped + path.write_text(json.dumps(data), encoding="utf-8") + accounts.write_usage(path, {"five_hour": (3.0, LATER + 18000)}, NOW) + got = _windows(path) + assert got["five_hour"] == {"percent": 3.0, "resets_at": LATER + 18000} + assert got["seven_day"]["percent"] == 30.0 and got["seven_day_scoped"] == scoped + # 前の窓が失効した後に、それより古い resets_at の入力を書いても前の値のまま + accounts.write_usage(path, {"five_hour": (50.0, LATER + 100)}, LATER + 20000) + assert _windows(path)["five_hour"] == {"percent": 3.0, "resets_at": LATER + 18000} + + +def test_write_usage_skips_while_locked_and_never_takes_a_held_lock(tmp_path, hold_lock): + path = accounts.usage_path(tmp_path, "work1", "g1") + lock = path.with_name(path.name + ".lock") + fd = hold_lock(lock) + os.utime(lock, (NOW - 3600, NOW - 3600)) # 古い錠のファイルでも、オーナーが生きている間は奪わない + accounts.write_usage(path, {"five_hour": (10.0, LATER)}, NOW) + assert not path.exists() + os.close(fd) + accounts.write_usage(path, {"five_hour": (10.0, LATER)}, NOW) + assert _windows(path) == {"five_hour": {"percent": 10.0, "resets_at": LATER}} + before = path.stat().st_mtime_ns + accounts.write_usage(path, {"five_hour": (10.0, LATER)}, NOW) # 同じ窓なら書かない + assert path.stat().st_mtime_ns == before + + +def test_write_usage_never_removes_a_directory_at_the_lock_path(tmp_path): + path = accounts.usage_path(tmp_path, "work1", "g1") + lock = path.with_name(path.name + ".lock") + lock.mkdir(parents=True) # 空のディレクトリでも、ほかの書き手のものかもしれないので消さずにその回は書かない + accounts.write_usage(path, {"five_hour": (10.0, LATER)}, NOW) + assert not path.exists() and lock.is_dir() + + +def test_usage_paths_stay_inside_the_cache(tmp_path): + import pytest + + for name in ("..", "a/../b", "/abs", "a/b"): + with pytest.raises(accounts.AccountError): + accounts.usage_path(tmp_path, name, "g1") + for generation in ("..", "../x", "/abs", "a/b", ".hidden"): + with pytest.raises(accounts.AccountError): + accounts.usage_path(tmp_path, "work1", generation) + with pytest.raises(accounts.AccountError): + accounts.usages(tmp_path, tmp_path / "store", NOW, {"work1": generation}) + + +def test_i6_one_account_record_leaves_the_other_files_alone(tmp_path): + a = accounts.usage_path(tmp_path, "work1", "g1") + b = accounts.usage_path(tmp_path, "work2", "g2") + accounts.write_usage(a, {"five_hour": (10.0, LATER)}, NOW) + accounts.write_usage(b, {"five_hour": (20.0, LATER)}, NOW) + accounts.write_usage(a, {"five_hour": (15.0, LATER)}, NOW) + assert _windows(b) == {"five_hour": {"percent": 20.0, "resets_at": LATER}} + got = accounts.usages(tmp_path, tmp_path / "store", NOW, {"work1": "g1", "work2": "g2"}) + assert got == [Usage("work1", 15.0, False), Usage("work2", 20.0, False)] + + +def test_3864_3_reset_windows_read_as_zero_and_not_limited(tmp_path): + gens = {"work1": "g1", "work2": "g2", "work3": "g3", "work4": "g4", "work5": "g5"} + _cache( + tmp_path, "work1", "g1", {"five_hour": {"percent": 100.0, "resets_at": NOW - 1}, "seven_day": {"percent": 40.0, "resets_at": NOW}} + ) + _cache( + tmp_path, "work2", "g2", {"seven_day": {"percent": 100.0, "resets_at": LATER}, "five_hour": {"percent": 20.0, "resets_at": LATER}} + ) + _cache(tmp_path, "work3", "g3", {}) # 窓を持たない記録は未観測 + _cache(tmp_path, "work4", "old", {"five_hour": {"percent": 5.0, "resets_at": LATER}}) # 旧い世代は読まない + scoped = {"claude-opus-4": {"percent": 70.0, "resets_at": LATER}, "x": {"percent": 100.0, "resets_at": NOW - 5}} + _cache(tmp_path, "work5", "g5", {"seven_day": {"percent": 10.0, "resets_at": LATER}, "seven_day_scoped": scoped}) + _cache(tmp_path, "other", "g", {"five_hour": {"percent": 1.0, "resets_at": LATER}}) # 登録の無い名前は返さない + got = accounts.usages(tmp_path, tmp_path / "store", NOW, gens) + assert got == [Usage("work1", 0.0, False), Usage("work2", 100.0, True), Usage("work5", 70.0, False)] + + +def test_i7_unreadable_usage_files_read_as_unknown(tmp_path): + path = accounts.usage_path(tmp_path, "work1", "g1") + path.parent.mkdir(parents=True) + for text in ("{", "[]", '{"windows": [1]}', '{"windows": {"five_hour": {"percent": "x", "resets_at": 1}}}'): + path.write_text(text, encoding="utf-8") + assert accounts.usages(tmp_path, tmp_path / "store", NOW, {"work1": "g1"}) == [] + # 壊れた記録へも次の書き込みは通る + accounts.write_usage(path, {"five_hour": (10.0, LATER)}, NOW) + assert accounts.usages(tmp_path, tmp_path / "store", NOW, {"work1": "g1"}) == [Usage("work1", 10.0, False)] + + +def test_i8_held_accounts_until_the_end_and_unhold(tmp_path): + assert accounts.held_path(tmp_path) == tmp_path / "relay" / "accounts" / "held.json" + assert accounts.held(tmp_path, NOW, {"work1": "g1"}) == {} + accounts.hold(tmp_path, "work1", "g1", NOW + 3600, NOW) + accounts.hold(tmp_path, "work2", "g2", NOW + 10, NOW) + gens = {"work1": "g1", "work2": "g2"} + assert accounts.held(tmp_path, NOW, gens) == {"work1": NOW + 3600, "work2": NOW + 10} + assert accounts.held(tmp_path, NOW + 10, gens) == {"work1": NOW + 3600} # 終わりちょうどで返らない + assert accounts.held(tmp_path, NOW, {"work1": "g9", "work2": "g2"}) == {"work2": NOW + 10} # 世代の違う項目は返らない + accounts.hold(tmp_path, "work3", "g3", NOW + 100, NOW + 20) # 終わった項目は次の書き込みで消える + data = json.loads(accounts.held_path(tmp_path).read_text(encoding="utf-8")) + assert set(data) == {"work1", "work3"} + accounts.unhold(tmp_path, "work1") + assert accounts.held(tmp_path, NOW, gens) == {} + + +def test_i8_hold_keeps_the_new_generation_in_either_order(tmp_path): + for first, second in (("old", "new"), ("new", "old")): + accounts.held_path(tmp_path).unlink(missing_ok=True) + accounts.hold(tmp_path, "work1", first, NOW + 100, NOW) + accounts.hold(tmp_path, "work1", second, NOW + 100, NOW) + assert accounts.held(tmp_path, NOW, {"work1": "new"}) == {"work1": NOW + 100} + accounts.held_path(tmp_path).write_text("{", encoding="utf-8") + assert accounts.held(tmp_path, NOW, {"work1": "new"}) == {} + accounts.hold(tmp_path, "work1", "new", NOW + 5, NOW) # 壊れたファイルへも書ける + assert accounts.held(tmp_path, NOW, {"work1": "new"}) == {"work1": NOW + 5} + + +def test_i11_a_seen_limit_holds_until_until_or_a_new_window(tmp_path): + gens = {"work1": "g1"} + store = tmp_path / "store" + assert accounts.limits_path(tmp_path) == tmp_path / "relay" / "accounts" / "limited.json" + _cache( + tmp_path, + "work1", + "g1", + {"five_hour": {"percent": 92.0, "resets_at": LATER}, "seven_day": {"percent": 50.0, "resets_at": LATER + 86400}}, + ) + accounts.see_limit(tmp_path, "work1", "g1", NOW, (LATER, "five_hour", LATER)) + assert accounts.usages(tmp_path, store, NOW, gens) == [Usage("work1", 92.0, True)] # 古い 92% の記録でも上限 + # 同じ窓の値の増加・上限より前の入力では解かない + accounts.write_usage(accounts.usage_path(tmp_path, "work1", "g1"), {"five_hour": (93.0, LATER)}, NOW) + accounts.write_usage(accounts.usage_path(tmp_path, "work1", "g1"), {"five_hour": (10.0, LATER - 600)}, NOW) + assert accounts.usages(tmp_path, store, NOW + 60, gens)[0].limited + # 観測の時刻のキャッシュが古く(window_resets_at が前の窓)、上限より前の今の窓(resets_at が until 以下)が遅れて届いても解かない + accounts.see_limit(tmp_path, "work1", "g1", NOW, (LATER, "five_hour", LATER - 18000)) + accounts.write_usage(accounts.usage_path(tmp_path, "work1", "g1"), {"five_hour": (60.0, LATER)}, NOW) + assert accounts.usages(tmp_path, store, NOW + 60, gens)[0].limited + # 観測の窓が新しい窓(resets_at が window_resets_at と until より後で 100 未満)に替われば until の前でも解く + accounts.write_usage(accounts.usage_path(tmp_path, "work1", "g1"), {"five_hour": (4.0, LATER + 18000)}, NOW) + assert accounts.usages(tmp_path, store, NOW + 60, gens) == [Usage("work1", 50.0, False)] + + +def test_i11_estimated_and_weekly_limits_are_not_released_by_another_window(tmp_path): + store = tmp_path / "store" + gens = {"work1": "g1", "work2": "g2"} + _cache(tmp_path, "work1", "g1", {"five_hour": {"percent": 92.0, "resets_at": LATER + 18000}}) + _cache( + tmp_path, + "work2", + "g2", + {"five_hour": {"percent": 92.0, "resets_at": LATER + 18000}, "seven_day": {"percent": 95.0, "resets_at": LATER + 86400}}, + ) + accounts.see_limit(tmp_path, "work1", "g1", NOW, (LATER, None, None)) # (4) の推定で窓が null + accounts.see_limit(tmp_path, "work2", "g2", NOW, (LATER + 86400, "seven_day", LATER + 86400)) + windows = { + "work1": {"five_hour": (92.0, LATER + 18000)}, + "work2": {"five_hour": (5.0, LATER + 36000), "seven_day": (95.0, LATER + 86400)}, + } + assert set(accounts.limits_seen(tmp_path, NOW, gens, windows)) == {"work1", "work2"} + assert set(accounts.limits_seen(tmp_path, LATER, gens, windows)) == {"work2"} # until を過ぎれば解く + assert accounts.limits_seen(tmp_path, NOW, {"work1": "g9"}, windows) == {} # 旧い世代の観測は読まない + # 使用率のファイルが無い名前に観測だけがあると、使用率の分からない上限の行になる + accounts.see_limit(tmp_path, "work3", "g3", NOW, (LATER, None, None)) + rows = accounts.usages(tmp_path, store, NOW, {"work3": "g3"}) + assert rows == [Usage("work3", None, True)] + assert accounts.usages(tmp_path, store, LATER, {"work3": "g3"}) == [] + accounts.limits_path(tmp_path).write_text("{", encoding="utf-8") + assert accounts.limits_seen(tmp_path, NOW, gens, windows) == {} + + +def test_i11_see_limit_keeps_the_new_generation_in_either_order(tmp_path): + for first, second in (("old", "new"), ("new", "old")): + accounts.limits_path(tmp_path).unlink(missing_ok=True) + accounts.see_limit(tmp_path, "work1", first, NOW, (LATER, None, None)) + accounts.see_limit(tmp_path, "work1", second, NOW, (LATER, None, None)) + assert accounts.limits_seen(tmp_path, NOW, {"work1": "new"}, {}) == {"work1": (NOW, LATER)} + + +def test_limit_until_follows_the_rules_in_order(): + from datetime import datetime, timezone + from zoneinfo import ZoneInfo + + tokyo = ZoneInfo("Asia/Tokyo") + seen = datetime(2026, 11, 21, 13, 0, tzinfo=tokyo).timestamp() + three = datetime(2026, 11, 21, 15, 0, tzinfo=tokyo).timestamp() + five = {"five_hour": (80.0, three), "seven_day": (90.0, seen + 86400)} + # (1) 行のリセットの時刻。窓は行の語、無ければ同じ時と分の窓 + assert accounts.limit_until("You've hit your session limit · resets 3pm (Asia/Tokyo)", five, seen, timezone.utc) == ( + three, + "five_hour", + three, + ) + assert accounts.limit_until("Limit reached · resets 3pm", five, seen, tokyo) == (three, "five_hour", three) + assert accounts.limit_until("Limit reached · resets 12:30pm", {}, seen, tokyo)[0] == three - 9000 + 86400 # 見た時刻より後で最も近い + # (2) 窓の語だけ + assert accounts.limit_until("weekly limit reached", five, seen, tokyo) == (seen + 86400, "seven_day", seen + 86400) + # (3) 100 以上の窓のうち遅いほう + full = {"five_hour": (100.0, three), "seven_day": (100.0, seen + 86400)} + assert accounts.limit_until("limit reached", full, seen, tokyo) == (seen + 86400, "seven_day", seen + 86400) + # (4) 推定: 5 時間の窓、無ければ見た時刻 + relay.limit-unknown。窓は null + assert accounts.limit_until("limit reached", five, seen, tokyo) == (three, None, None) + assert accounts.limit_until("limit reached · resets soon", {}, seen, tokyo) == (seen + 18000, None, None) + + +def test_forget_drops_only_the_given_generation(tmp_path): + store = tmp_path / "store" + for g in ("old", "new"): + accounts.write_usage(accounts.usage_path(tmp_path, "work1", g), {"five_hour": (10.0, LATER)}, NOW) + accounts.hold(tmp_path, "work1", g, LATER, NOW) + accounts.see_limit(tmp_path, "work1", g, NOW, (LATER, None, None)) + accounts.hold(tmp_path, "work2", "g2", LATER, NOW) + accounts.forget(tmp_path, store, "work1", "old") + assert sorted(p.name for p in accounts.usage_path(tmp_path, "work1", "new").parent.iterdir()) == ["new.json", "new.json.lock"] + assert accounts.held(tmp_path, NOW, {"work1": "old", "work2": "g2"}) == {"work2": LATER} + assert accounts.held(tmp_path, NOW, {"work1": "new"}) == {"work1": LATER} + assert accounts.limits_seen(tmp_path, NOW, {"work1": "old"}, {}) == {} + assert accounts.limits_seen(tmp_path, NOW, {"work1": "new"}, {}) == {"work1": (NOW, LATER)} + accounts.forget(tmp_path, store, "work1", "new") + assert not accounts.usage_path(tmp_path, "work1", "new").parent.exists() + assert accounts.held(tmp_path, NOW, {"work1": "new", "work2": "g2"}) == {"work2": LATER} + assert accounts.limits_seen(tmp_path, NOW, {"work1": "new"}, {}) == {} diff --git a/plugins/ndf/tests/domains/statusline/test_statusline_usage.py b/plugins/ndf/tests/domains/statusline/test_statusline_usage.py new file mode 100644 index 0000000000..60958d9daf --- /dev/null +++ b/plugins/ndf/tests/domains/statusline/test_statusline_usage.py @@ -0,0 +1,256 @@ +"""NDF の status line が子の環境の `NDF_ACCOUNT_USAGE_FILE` へ使用率を書く(#3864 の 1・2・11、I6・I7)。""" + +from __future__ import annotations + +import json +import os +import shutil +import subprocess +from pathlib import Path +from typing import Optional + +import pytest + +from ndf.domains.relay import accounts +from ndf.domains.relay.account_decide import Usage +from ndf.domains.statusline import settings + +if shutil.which("jq") is None: + pytest.skip("jq が無い", allow_module_level=True) + +LATER = 4_000_000_000 +NEEDED = ( + "bash", + "cat", + "date", + "sed", + "mkdir", + "mv", + "rm", + "rmdir", + "stat", + "basename", + "dirname", + "find", + "tail", + "sort", + "flock", + "mktemp", +) + + +def _input(rate_limits: Optional[object], **extra) -> str: + data: dict = {"workspace": {"project_dir": "/w/p"}, "model": {"display_name": "Opus 5"}, **extra} + if rate_limits is not None: + data["rate_limits"] = rate_limits + return json.dumps(data) + + +def _limits(five: Optional[float] = 42.0, seven: Optional[float] = 18.0, resets: int = LATER) -> dict: + got: dict = {} + if five is not None: + got["five_hour"] = {"used_percentage": five, "resets_at": resets} + if seven is not None: + got["seven_day"] = {"used_percentage": seven, "resets_at": resets + 86400} + return got + + +def _env(tmp_path: Path, usage: Optional[Path], path: Optional[str] = None) -> dict[str, str]: + env = { + "HOME": str(tmp_path / "home"), + "PATH": path or os.environ["PATH"], + "NDF_STATE_HOME": str(tmp_path / "state"), + "NDF_STATUSLINE_AUTH_CACHE": str(tmp_path / "auth.json"), + } + if usage is not None: + env["NDF_ACCOUNT_USAGE_FILE"] = str(usage) + return env + + +def _run(tmp_path: Path, text: str, usage: Optional[Path], path: Optional[str] = None) -> subprocess.CompletedProcess: + return subprocess.run( + ["bash", str(settings.BODY_SOURCE)], input=text, env=_env(tmp_path, usage, path), capture_output=True, text=True, check=False + ) + + +def _windows(path: Path) -> dict: + return json.loads(path.read_text(encoding="utf-8"))["windows"] + + +def test_3864_1_status_line_writes_the_two_windows_of_the_account(tmp_path): + usage = tmp_path / "state" / "relay" / "accounts" / "usage" / "work1" / "g1.json" + other = usage.with_name("g0.json") + other.parent.mkdir(parents=True) + other.write_text('{"windows": {}}', encoding="utf-8") + got = _run(tmp_path, _input(_limits()), usage) + assert got.returncode == 0 + assert _windows(usage) == { + "five_hour": {"percent": 42, "resets_at": LATER}, + "seven_day": {"percent": 18, "resets_at": LATER + 86400}, + } + assert other.read_text(encoding="utf-8") == '{"windows": {}}' + # 残るのは記録と錠のファイルだけ(一時ファイルを残さない) + assert not [p for p in usage.parent.iterdir() if p.name not in ("g1.json", "g1.json.lock", "g0.json")] + + +def test_3864_1_a_late_old_input_does_not_lower_the_value(tmp_path): + usage = tmp_path / "u" / "work1.json" + _run(tmp_path, _input(_limits(five=100.0)), usage) + data = json.loads(usage.read_text(encoding="utf-8")) + data["windows"]["seven_day_scoped"] = {"claude-opus-4": {"percent": 31.0, "resets_at": LATER}} + usage.write_text(json.dumps(data), encoding="utf-8") + _run(tmp_path, _input(_limits(five=40.0, seven=None)), usage) + got = _windows(usage) + assert got["five_hour"]["percent"] == 100 and got["seven_day"]["percent"] == 18 + assert got["seven_day_scoped"] == {"claude-opus-4": {"percent": 31.0, "resets_at": LATER}} + before = usage.stat().st_mtime_ns + _run(tmp_path, _input(_limits(five=100.0)), usage) # 同じ値なら書かない + assert usage.stat().st_mtime_ns == before + + +def test_3864_1_five_hour_window_may_be_missing(tmp_path): + usage = tmp_path / "u" / "work1.json" + _run(tmp_path, _input(_limits(five=None)), usage) + assert set(_windows(usage)) == {"seven_day"} + + +@pytest.mark.parametrize( + "rate_limits", + [None, {}, {"spend_limit": {"used_percentage": 50, "resets_at": LATER}}, {"five_hour": {"used_percentage": "x", "resets_at": LATER}}], +) +def test_3864_1_no_valid_window_writes_nothing(tmp_path, rate_limits): + usage = tmp_path / "u" / "work1.json" + assert _run(tmp_path, _input(rate_limits), usage).returncode == 0 + assert not usage.parent.exists() + + +def test_3864_2_i6_two_accounts_at_the_same_time_both_remain(tmp_path): + files = [tmp_path / "u" / f"work{i}" / "g.json" for i in (1, 2)] + procs = [ + subprocess.Popen( + ["bash", str(settings.BODY_SOURCE)], + stdin=subprocess.PIPE, + stdout=subprocess.DEVNULL, + env=_env(tmp_path, f), + text=True, + ) + for f in files + ] + for i, p in enumerate(procs): + p.communicate(_input(_limits(five=10.0 * (i + 1)))) + assert [_windows(f)["five_hour"]["percent"] for f in files] == [10, 20] + + +def test_3864_11_i7_unwritable_place_or_missing_jq_keeps_the_output(tmp_path): + text = _input(_limits()) + plain = _run(tmp_path, text, None) + blocker = tmp_path / "file" + blocker.write_text("", encoding="utf-8") + got = _run(tmp_path, text, blocker / "sub" / "u.json") + assert (got.returncode, got.stdout, got.stderr) == (0, plain.stdout, "") + assert _run(tmp_path, text, Path("relative.json")).stdout == plain.stdout + # jq の無い PATH(必要なコマンドだけを並べる) + bin_dir = tmp_path / "bin" + bin_dir.mkdir() + for name in NEEDED: + found = shutil.which(name) + if found: + (bin_dir / name).symlink_to(found) + bare = _run(tmp_path, text, None, str(bin_dir)) + usage = tmp_path / "u" / "work1.json" + got = _run(tmp_path, text, usage, str(bin_dir)) + assert (got.returncode, got.stdout, got.stderr) == (0, bare.stdout, "") and not usage.exists() + + +def test_status_line_and_usages_use_the_same_path(tmp_path): + state = tmp_path / "state" + usage = accounts.usage_path(state, "work1", "g1") + _run(tmp_path, _input(_limits(five=42.0, seven=18.0)), usage) + assert accounts.usages(state, tmp_path / "store", LATER - 10, {"work1": "g1"}) == [Usage("work1", 42.0, False)] + + +def test_status_line_never_takes_a_lock_another_writer_holds(tmp_path): + import fcntl + + usage = tmp_path / "u" / "work1.json" + lock = usage.with_name(usage.name + ".lock") + lock.parent.mkdir(parents=True) + fd = os.open(lock, os.O_RDWR | os.O_CREAT) + fcntl.flock(fd, fcntl.LOCK_EX) + try: + os.utime(lock, (1, 1)) # 古い錠のファイルでも、オーナーが生きている間は奪わない + assert _run(tmp_path, _input(_limits()), usage).returncode == 0 + assert not usage.exists() and lock.exists() + finally: + os.close(fd) + _run(tmp_path, _input(_limits()), usage) + assert _windows(usage)["five_hour"]["percent"] == 42 + + +def test_an_unchanged_redraw_starts_only_jq(tmp_path): + """値が前と同じ再描画は、錠・一時ファイル・時刻のコマンドを起動しない(jq の 1 回で比べて終える)。""" + bin_dir = tmp_path / "bin" + bin_dir.mkdir() + log = tmp_path / "calls.log" + watched = ("date", "mkdir", "rmdir", "dirname", "flock", "mktemp", "mv") + for name in (*NEEDED, "jq"): + found = shutil.which(name) + if not found: + continue + if name in watched: + (bin_dir / name).write_text(f'#!/bin/sh\necho {name} >> "{log}"\nexec "{found}" "$@"\n', encoding="utf-8") + (bin_dir / name).chmod(0o755) + else: + (bin_dir / name).symlink_to(found) + usage = tmp_path / "u" / "work1.json" + text = _input(_limits()) + _run(tmp_path, text, usage, str(bin_dir)) + assert _windows(usage)["five_hour"]["percent"] == 42 + log.unlink() + assert _run(tmp_path, text, usage, str(bin_dir)).returncode == 0 + assert not log.exists() + + +def _bin_without_flock(tmp_path: Path) -> Path: + """`flock` のコマンドが無い PATH(標準の macOS と同じ)。jq と perl は置く。""" + bin_dir = tmp_path / "bin-noflock" + bin_dir.mkdir() + for name in (*NEEDED, "jq", "perl"): + found = shutil.which(name) + if found and name != "flock": + (bin_dir / name).symlink_to(found) + return bin_dir + + +@pytest.mark.skipif(shutil.which("perl") is None, reason="perl が無い") +def test_status_line_without_flock_takes_the_same_lock_with_perl(tmp_path): + import fcntl + + path = str(_bin_without_flock(tmp_path)) + usage = tmp_path / "u" / "work1.json" + lock = usage.with_name(usage.name + ".lock") + lock.parent.mkdir(parents=True) + # Python(write_usage と同じ fcntl.flock)が錠を持つ間は書かない + fd = os.open(lock, os.O_RDWR | os.O_CREAT) + fcntl.flock(fd, fcntl.LOCK_EX) + try: + assert _run(tmp_path, _input(_limits()), usage, path).returncode == 0 + assert not usage.exists() + finally: + os.close(fd) + # 錠が空けば flock のコマンドが無くても書く + got = _run(tmp_path, _input(_limits()), usage, path) + assert (got.returncode, got.stderr) == (0, "") + assert _windows(usage)["five_hour"]["percent"] == 42 + # 書いた後の錠は残っておらず、Python の書き手がすぐ取れる + accounts.write_usage(usage, {"five_hour": (50.0, float(LATER))}, 1.0) + assert _windows(usage)["five_hour"]["percent"] == 50 + + +def test_status_line_never_removes_a_directory_at_the_lock_path(tmp_path): + usage = tmp_path / "u" / "work1.json" + lock = usage.with_name(usage.name + ".lock") + lock.mkdir(parents=True) # 空のディレクトリでも消さず、その回は書かない + got = _run(tmp_path, _input(_limits()), usage) + assert (got.returncode, got.stderr) == (0, "") + assert not usage.exists() and lock.is_dir()