Spaces:
Paused
Paused
fix: align provider auth seat semantics
Browse filesFiles changed (10)
- .trellis/spec/backend/runtime-docker-hardening.md+20
- .trellis/tasks/05-21-autoteam1-provider-auth-seat-semantics/check.jsonlAdded+1
- .trellis/tasks/05-21-autoteam1-provider-auth-seat-semantics/implement.jsonlAdded+1
- .trellis/tasks/05-21-autoteam1-provider-auth-seat-semantics/prd.mdAdded+85
- .trellis/tasks/05-21-autoteam1-provider-auth-seat-semantics/research/code-diff-findings.mdAdded+96
- .trellis/tasks/05-21-autoteam1-provider-auth-seat-semantics/task.jsonAdded+26
- src/autoteam/api.py+168-5
- src/autoteam/manager.py+11-6
- src/autoteam/playwright_probe.py+5-2
- tests/unit/test_api_status.py+211
28 unmodified lines29303132333412 unmodified lines47484950515230 unmodified lines83848586878838 unmodified lines1271281291301311321339 unmodified lines14314414514614714818 unmodified lines16716816917017117217346 unmodified lines22022122222322422528 unmodified lines- `_record_task_progress(task: dict, stage: str, now: float | None = None) -> None`- `close_playwright_objects(page=None, context=None, browser=None, playwright=None, *, logger=None, label="playwright") -> None`- `python -m autoteam.playwright_probe team-member-count`- `ChatGPTTeamAPI.start_with_session(session_token, account_id, workspace_name="", require_browser=False)`- `ChatGPTTeamAPI.stop() -> None`- `MainCodexLoginFlow.complete() -> dict`12 unmodified lines- `get_chatgpt_http_proxy_url(proxy_url: str | None = None) -> str`- `get_cliproxy_health() -> dict[str, Any]`- `_collect_cpa_credential_gate() -> dict[str, Any]`- `_auth_repair_error_label(error_type: str | None) -> str`- `_oauth_retry_delay_seconds(error_type: str | None) -> int`- `_login_codex_with_result(email, password, *, mail_client=None, max_attempts=3, signup_profile=None, pre_signed_in_cookies=None, playwright_proxy_url=None) -> dict`30 unmodified lines- `/api/status` may include `runtime_resources`, but resource collection must never block or fail the status response.- `/api/status?fast=true` is the polling-safe status path. It must skip live Codex quota checks, keep the ordinary account/status summary shape, use a bounded CLIProxy health read, and return `status_mode.fast=true` with `live_quota=false`.- Background Team member count probes must run in a killable subprocess and return unknown (`-1`) on timeout/failure.- `ChatGPTTeamAPI.start_with_session()` must call `stop()` if the browser fallback path fails after partial initialization, not only when `_launch_browser()` itself fails.- `ChatGPTTeamAPI.start_with_session()` must also call `stop()` when HTTP transport startup succeeds but later workspace detection or admin-state persistence fails.- Direct HTTP API fetches must close and clear the bad `http_transport` before browser fallback when the transport raises, returns HTML/challenge, or fails again after a 401-triggered token refresh retry.38 unmodified lines- `/api/status` may include `cliproxy` and `rotation_validation`. These fields are additive and must not remove or rename existing status fields.- `cliproxy` health must stay read-only. It may read CLIProxyAPI management metadata (`/v0/management/auth-files`) and provider availability counts, but must never call sync/upload/delete/refresh endpoints.- Auto-check may use CLIProxyAPI provider-auth metadata only as a read-only CPA credential gate. The gate is enabled only when CPA sync is configured/enabled, must call `get_cliproxy_health(..., force_refresh=True)` without sync/upload/delete side effects, and may treat provider auth as zero only when `management_ok=true` and `available <= 0`.- When Team is full but local active child count is below the target and the CPA credential gate reports zero available credentials, auto-check may trigger the normal `auto-fill` / `cmd_rotate(..., background_post_sync=True)` path. This is a replacement/fill decision, not a remote CPA mutation.- `rotation_validation` must distinguish `ok`, `degraded`, and hard `failed` results. Hard post-task validation failure may convert a superficially completed mutation task into `failed`; degraded results keep operation success visible and expose cooldown/follow-up metadata.- `sync_to_cpa()` must refresh `proxy_url` in auth JSON for active/personal, non-disabled local accounts before upload. In required mode refresh failure must fail the sync; in non-required mode it may warn and upload the existing file.9 unmodified lines| `_launch_browser()` partially initializes then fails | Call `stop()` and re-raise the original exception || `start_with_session(..., require_browser=True)` or browser fallback starts Playwright then fails during navigation/token/workspace setup | Call `stop()` and re-raise the original exception || probe subprocess timeout | Kill the process group/tree and treat count as unknown || `curl_cffi` missing or transport init fails | Return `None`; continue with Playwright || transport returns HTML/challenge/401 token missing | Fall back to Playwright API fetch || `ChatGPTTeamAPI.start()` succeeds via HTTP transport only | Cleanup and reuse checks must use `is_started()` / `_chatgpt_session_ready()`, not `browser` alone |18 unmodified lines| CLIProxyAPI auth-file payload is malformed | Return provider/management diagnostic fields; do not treat it as an empty healthy provider set || CPA sync target is disabled | `_collect_cpa_credential_gate()` returns `enabled=false`; auto-check behavior is unchanged || CPA sync target is enabled and CLIProxyAPI management reports `available=0` with `management_ok=true` | Gate returns `zero_available=true`; a full Team with too few local active children may trigger `auto-fill` || CLIProxyAPI management check fails | Gate returns `management_ok=false`, `zero_available=false`; do not interpret this as no credentials || post-task remote sync fails after API-driven rotate | Log a warning, keep the local rotation result, and leave task completion unblocked || post-task runtime validation is degraded | Keep the task completed, record reasons and cooldown/follow-up metadata || post-task runtime validation is a hard failure | Convert the task to `failed` with a business reason |46 unmodified lines- Auto-check skips expensive probes while a task is active.- Full Team + local active shortage + `management_ok=true` + `available=0` triggers `auto-fill` without sync/upload/delete.- Management failure with `available=0` does not trigger replacement.- Rotate deferred post-sync and validation plumbing: `tests/unit/test_manager_rotate.py` and `tests/unit/test_api_status.py`- IPv6 pool/proxy persistence and strict required-mode behavior: `tests/unit/test_ipv6_pool.py`- IPv6 status and status-failure boundary: `tests/unit/test_api_status.py`28 unmodified lines29303132333435363712 unmodified lines5051525354555630 unmodified lines87888990919293949538 unmodified lines1341351361371381391401411421439 unmodified lines15315415515615715815916018 unmodified lines17918018118218318418518618718846 unmodified lines23523623723823924024124224324424528 unmodified lines- `_record_task_progress(task: dict, stage: str, now: float | None = None) -> None`- `close_playwright_objects(page=None, context=None, browser=None, playwright=None, *, logger=None, label="playwright") -> None`- `python -m autoteam.playwright_probe team-member-count`- `_TeamMemberCount(int)` with `.invites` and `.occupancy`- `_team_member_invite_count(team_count) -> int`- `_team_member_occupancy(team_count) -> int`- `ChatGPTTeamAPI.start_with_session(session_token, account_id, workspace_name="", require_browser=False)`- `ChatGPTTeamAPI.stop() -> None`- `MainCodexLoginFlow.complete() -> dict`12 unmodified lines- `get_chatgpt_http_proxy_url(proxy_url: str | None = None) -> str`- `get_cliproxy_health() -> dict[str, Any]`- `_collect_cpa_credential_gate() -> dict[str, Any]`- `_cpa_provider_auth_below_pool_target(gate: dict | None, pool_target: int) -> bool`- `_auth_repair_error_label(error_type: str | None) -> str`- `_oauth_retry_delay_seconds(error_type: str | None) -> int`- `_login_codex_with_result(email, password, *, mail_client=None, max_attempts=3, signup_profile=None, pre_signed_in_cookies=None, playwright_proxy_url=None) -> dict`30 unmodified lines- `/api/status` may include `runtime_resources`, but resource collection must never block or fail the status response.- `/api/status?fast=true` is the polling-safe status path. It must skip live Codex quota checks, keep the ordinary account/status summary shape, use a bounded CLIProxy health read, and return `status_mode.fast=true` with `live_quota=false`.- Background Team member count probes must run in a killable subprocess and return unknown (`-1`) on timeout/failure.- `python -m autoteam.playwright_probe team-member-count` must return `count`, `invites`, and `occupancy=count+invites` when Team state is readable. `_auto_check_team_member_count()` must preserve `int` compatibility while carrying invite/occupancy metadata through `_TeamMemberCount`.- Auto-check must treat pending Team invites as remote seat occupancy. If `members + invites > target_seats`, it should trigger `auto-cleanup` with diagnostic params `team_count`, `invite_count`, and `team_occupancy`; it must not treat unknown pending invites as safe-delete evidence.- Auto-check remains a single-main flow: `target_seats` is the total Team cap for one owner/main plus managed children, and provider-auth low-watermark targets only the managed-child pool (`target_seats - 1`). This contract must not enable or depend on multi-owner scheduling.- `ChatGPTTeamAPI.start_with_session()` must call `stop()` if the browser fallback path fails after partial initialization, not only when `_launch_browser()` itself fails.- `ChatGPTTeamAPI.start_with_session()` must also call `stop()` when HTTP transport startup succeeds but later workspace detection or admin-state persistence fails.- Direct HTTP API fetches must close and clear the bad `http_transport` before browser fallback when the transport raises, returns HTML/challenge, or fails again after a 401-triggered token refresh retry.38 unmodified lines- `/api/status` may include `cliproxy` and `rotation_validation`. These fields are additive and must not remove or rename existing status fields.- `cliproxy` health must stay read-only. It may read CLIProxyAPI management metadata (`/v0/management/auth-files`) and provider availability counts, but must never call sync/upload/delete/refresh endpoints.- Auto-check may use CLIProxyAPI provider-auth metadata only as a read-only CPA credential gate. The gate is enabled only when CPA sync is configured/enabled, must call `get_cliproxy_health(..., force_refresh=True)` without sync/upload/delete side effects, and may treat provider auth as zero only when `management_ok=true` and `available <= 0`.- Provider-auth low-watermark is a proactive signal, not only a zero-credential signal. When the gate is enabled, `safe_read_only=true`, `management_ok=true`, and `provider_auth.available < pool_active_target`, auto-check may trigger `auto-rotate` / sync with params `provider_auth_below_target`, `provider_auth_available`, and `provider_auth_target`; post-task runtime validation should degrade with `provider_auth_available=<available>/<target>`.- When Team is full but local active child count is below the target and the CPA credential gate reports zero available credentials, auto-check may trigger the normal `auto-fill` / `cmd_rotate(..., background_post_sync=True)` path. This is a replacement/fill decision, not a remote CPA mutation.- `zero_available` and provider-auth low-watermark must require `safe_read_only=true`. A management failure, malformed response, or non-read-only health check is unknown and must not trigger replacement.- Remote capacity preflight for direct registration may use `members+invites` only after `ChatGPTTeamAPI` is actually ready. Dynamic mock/duck attributes must not be allowed to spoof readiness; if `start()` returns without a ready browser/http transport, skip the remote preflight rather than calling Team APIs on an unusable session.- `rotation_validation` must distinguish `ok`, `degraded`, and hard `failed` results. Hard post-task validation failure may convert a superficially completed mutation task into `failed`; degraded results keep operation success visible and expose cooldown/follow-up metadata.- `sync_to_cpa()` must refresh `proxy_url` in auth JSON for active/personal, non-disabled local accounts before upload. In required mode refresh failure must fail the sync; in non-required mode it may warn and upload the existing file.9 unmodified lines| `_launch_browser()` partially initializes then fails | Call `stop()` and re-raise the original exception || `start_with_session(..., require_browser=True)` or browser fallback starts Playwright then fails during navigation/token/workspace setup | Call `stop()` and re-raise the original exception || probe subprocess timeout | Kill the process group/tree and treat count as unknown || Team probe returns members and pending invites | Preserve `count`, `invites`, and `occupancy`; use occupancy for over-target cleanup || Team probe returns `count=3, invites=1, occupancy=4` for target 3 | Trigger `auto-cleanup` and include `invite_count=1`, `team_occupancy=4` in task params || `curl_cffi` missing or transport init fails | Return `None`; continue with Playwright || transport returns HTML/challenge/401 token missing | Fall back to Playwright API fetch || `ChatGPTTeamAPI.start()` succeeds via HTTP transport only | Cleanup and reuse checks must use `is_started()` / `_chatgpt_session_ready()`, not `browser` alone |18 unmodified lines| CLIProxyAPI auth-file payload is malformed | Return provider/management diagnostic fields; do not treat it as an empty healthy provider set || CPA sync target is disabled | `_collect_cpa_credential_gate()` returns `enabled=false`; auto-check behavior is unchanged || CPA sync target is enabled and CLIProxyAPI management reports `available=0` with `management_ok=true` | Gate returns `zero_available=true`; a full Team with too few local active children may trigger `auto-fill` || CPA sync target is enabled and CLIProxyAPI management reports `available=1` while `pool_active_target=2` | Gate remains non-zero but below target; auto-check may trigger preventive `auto-rotate` / sync and runtime validation degrades || CLIProxyAPI management check fails | Gate returns `management_ok=false`, `zero_available=false`; do not interpret this as no credentials || CLIProxyAPI health is not confirmed read-only | Do not treat `available=0` or below-target as actionable rotation evidence || `ChatGPTTeamAPI.start()` returns but no browser/http transport is ready | Do not fetch Team members/invites; keep direct registration fallback behavior || post-task remote sync fails after API-driven rotate | Log a warning, keep the local rotation result, and leave task completion unblocked || post-task runtime validation is degraded | Keep the task completed, record reasons and cooldown/follow-up metadata || post-task runtime validation is a hard failure | Convert the task to `failed` with a business reason |46 unmodified lines- Auto-check skips expensive probes while a task is active.- Full Team + local active shortage + `management_ok=true` + `available=0` triggers `auto-fill` without sync/upload/delete.- Management failure with `available=0` does not trigger replacement.- Provider-auth `available < pool_active_target` triggers preventive `auto-rotate` / sync with provider-auth task params.- Runtime validation degrades when provider-auth is below target.- Non-read-only CLIProxy health does not produce `zero_available` or below-target action.- Pending invites count toward remote occupancy and over-target occupancy triggers `auto-cleanup`.- `_auto_check_team_member_count()` preserves `int` compatibility while carrying invite/occupancy metadata.- Rotate deferred post-sync and validation plumbing: `tests/unit/test_manager_rotate.py` and `tests/unit/test_api_status.py`- IPv6 pool/proxy persistence and strict required-mode behavior: `tests/unit/test_ipv6_pool.py`- IPv6 status and status-failure boundary: `tests/unit/test_api_status.py`
1{"_example": "Fill with {\"file\": \"<path>\", \"reason\": \"<why>\"}. Put spec/research files only — no code paths. Run `python .trellis/scripts/get_context.py --mode packages` to list available specs. Delete this line once real entries are added."}1{"_example": "Fill with {\"file\": \"<path>\", \"reason\": \"<why>\"}. Put spec/research files only — no code paths. Run `python .trellis/scripts/get_context.py --mode packages` to list available specs. Delete this line once real entries are added."}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485# brainstorm: align autoteam-1 latest provider-auth seat semantics
## Goal
把当前 `D:\Desktop\AutoTeam` 继续对齐 `D:\Desktop\autoteam-1\AutoTeam` 最新一轮轮转/巡检语义,重点补齐 CPA/CLIProxy provider-auth 低水位提前触发,以及 pending invite 也计入远端 Team 席位占用,避免本地账号看似健康但远端凭证池或邀请占位已经阻塞后续轮转。
## What I already know
* 用户明确点名需要继续对齐 `D:\Desktop\autoteam-1` 最新改动,例子包括 CPA/CLIProxy provider-auth 低水位提前触发、pending invite 也算远端席位占用。* 当前工作区是 `D:\Desktop\AutoTeam`,Trellis 当前无 active task,因此已新建本任务记录这轮对齐。* 当前仓库最新提交是 `be34853 fix: reduce rotation probe interference`;源仓库 `D:\Desktop\autoteam-1\AutoTeam` 最新提交是 `2f8d52d fix:reduce-rotation-probe-interference`。* 当前仓库已吸收 `GET /api/status?fast=true`、任务 `progress_history`、auto-check 忙碌时跳过昂贵探测等部分内容。* 当前仓库 `src/autoteam/api.py` 仍主要只用 `zero_available` 触发 CPA gate,缺少源仓库的 `_cpa_provider_auth_below_pool_target()` 低水位判断。* 当前仓库 `_collect_cpa_credential_gate()` 的 `zero_available` 判断未完全对齐源仓库的 `safe_read_only and management_ok and available <= 0` 安全边界。* 当前仓库 `_auto_check_team_member_count()` 只返回成员数 `count`;源仓库新增 `_TeamMemberCount`,保留 int 兼容同时携带 `invites` 与 `occupancy`。* 当前仓库 `manager.py` 已在创建新账号前使用 `members + invites` 判断远端容量,但 `api.py` 的 auto-check 决策层尚未把 pending invite 计入远端占用。* 当前仓库有本地状态机、OAuth backoff、setup diagnostics、前端等扩展,不能整文件覆盖源仓库 `api.py`,需要做语义级小补丁。
## Assumptions (temporary)
* 本轮目标是继续把当前仓库补齐到 `autoteam-1` 的运行语义,而不是重写当前仓库已有的 Round 11 状态机、状态 API 或单 main 主线。* 本轮保持单 main 主线:Team 目标仍按 `1 owner/main + 2 managed children = 3 seats` 计算,provider-auth 池目标只对应 managed children(`target_seats - 1`),不迁移或启用多 owner/multi-master 调度。* provider-auth 低水位应按池目标判断:目标子号数为 2 时,只要 CLIProxy provider-auth `available < 2` 且检查是 read-only、management OK,就应触发预防性轮转/同步,而不是等到 `available == 0`。* pending invite 计入远端占用的主战场是 auto-check 与自动 cleanup/rotate 的判断参数;前端 `/api/team/members` 已能展示 invite,不作为本轮主要 UI 改造。
## Open Questions
* None.
## Requirements (evolving)
* MVP 采用语义小补丁:只补 provider-auth 低水位、safe_read_only guard、pending invite 占用和对应测试,不做 auto-check 大重构。* 新增 provider-auth 低水位 helper,且仅在 CPA sync 已启用、CLIProxy health 是 read-only、management API OK 时生效。* `zero_available` 的安全条件必须包含 `safe_read_only`,不能把未知/失败的 CLIProxy 管理检查当作 0 可用凭证。* auto-check 应在 provider-auth `available < pool_active_target` 时提前触发正常 `cmd_rotate(..., background_post_sync=True)` 路径,并在 task params 中暴露 `provider_auth_below_target`、`provider_auth_available`、`provider_auth_target`。* post-task runtime validation 应在 provider-auth 低于池目标时标记 degraded follow-up,而不是仅检查本地 auth file 与 live quota。* Team 成员探针应兼容返回 `count`、`invites`、`occupancy`,并保持旧调用方把返回值当 `int` 使用不破坏。* auto-check 清理判断必须使用远端占用 `members + invites`,当占用超过目标时触发 cleanup,并传入 `invite_count` / `team_occupancy` 诊断参数。* pending invite 不等同于可删除证据;只能清理已能证明是 AutoTeam 遗留的 stale pending invite,不能删除未知来源邀请。
## Acceptance Criteria (evolving)
* [x] `tests/unit/test_api_status.py` 覆盖 provider-auth `available=1,target=2` 时触发提前 rotate/sync。* [x] `tests/unit/test_api_status.py` 覆盖 runtime validation 在 provider-auth 低水位时返回 degraded follow-up。* [x] `tests/unit/test_api_status.py` 覆盖 CLIProxy management failure / non-read-only 时不触发低水位轮转。* [x] `tests/unit/test_api_status.py` 覆盖 Team probe 返回 `count=3, invites=1, occupancy=4, target=3` 时触发 auto-cleanup,并记录 `invite_count=1`、`team_occupancy=4`。* [x] 现有 auto-check busy skip、fast status、CPA gate zero-available、manager pending invite capacity tests 继续通过。* [x] 针对本轮触及文件运行 ruff 与 targeted pytest。
## Definition of Done (team quality bar)
* Tests added/updated (unit/integration where appropriate)* Lint / typecheck / CI green for touched backend files* Docs/notes updated if behavior changes* Rollout/rollback considered if risky* 不使用 mock 代替真实语义;测试桩只模拟边界输入,业务判断必须对应真实 runtime contract
## Out of Scope (explicit)
* 不改 Team 席位上限,仍保持单 Team `1 owner/main + 2 managed children = 3 seats`。* 不做 create-before-remove,不把 pending invite 当作可以随意删除的远端对象。* 不改前端视觉/布局。* 不用 `/api/sync` 作为健康验证或 smoke test,因为它会 mutate 远端 CPA 状态。* 不整文件覆盖 `src/autoteam/api.py`,避免破坏当前仓库已有 Round 11、OAuth/backoff、状态 API 和单 main 主线。* 不把源仓库或历史分支里的 multi-master / 多 owner 调度作为本轮对齐目标。
## Technical Notes
* 源仓库最新对齐参考:`D:\Desktop\autoteam-1\AutoTeam` commits `2f8d52d`, `c93d246`, `8f17448`, `276ed0b`, `f120570`。* 当前仓库参考提交:`be34853`, `120638a`, `ceeba19`, `e49e827`。* 重点文件预计为 `src/autoteam/api.py`, `tests/unit/test_api_status.py`, 可能涉及 `docs/api.md` 或 backend spec。* 相关规范:`.trellis/spec/backend/runtime-docker-hardening.md`, `.trellis/spec/backend/account-disable-cpa-sync.md`。* 本轮代码调研见 `research/code-diff-findings.md`。
## Decision (ADR-lite)
**Context**: 当前仓库已经吸收了 `autoteam-1` 的部分最新变更,但 `api.py` 与源仓库结构明显分叉,直接覆盖会破坏现有 Round 11 OAuth/backoff、setup diagnostics、状态 API 和单 main 主线等本地约束。
**Decision**: 采用“语义小补丁”方案。只把源仓库新增运行契约迁入当前结构:provider-auth 低水位提前触发、`safe_read_only` 安全边界、pending invite 计入 Team 远端占用、runtime validation 低水位 degraded follow-up,以及对应单元测试。
**Consequences**: 回归面更小,能快速对齐用户点名缺陷;代价是当前 auto-check 分支仍保持本地形态,未来若继续迁移源仓库统一 state 收集模型,需要另起任务。
## Research References
* [`research/code-diff-findings.md`](research/code-diff-findings.md) — 当前仓库与 `autoteam-1` 最新 provider-auth / pending invite 语义差异。123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596# Code Diff Findings
## Scope
对比对象:
* Current repo: `D:\Desktop\AutoTeam`* Source repo: `D:\Desktop\autoteam-1\AutoTeam`
本次只记录与用户点名范围相关的 backend runtime 语义:CPA/CLIProxy provider-auth 低水位、pending invite 席位占用、以及 auto-check 对昂贵探测的约束。
## Git facts
* Current latest: `be34853 fix: reduce rotation probe interference`* Source latest: `2f8d52d fix:reduce-rotation-probe-interference`* Source provider-auth gate baseline: `8f17448 fix: add CPA credential gate to auto-check`* Source verified-domain/direct-first baseline: `c93d246 fix: prefer domain auto-join for rotation account creation`
## Findings
### 1. Current has busy-skip / fast status, but not low-water provider-auth
Current `src/autoteam/api.py` already includes:
* `_safe_cliproxy_health(**kwargs)` with bounded fast status usage.* `GET /api/status?fast=true` tests.* task `progress_history`.* auto-check skip when `_playwright_lock` / current task indicates a busy Playwright-bound operation.
But current auto-check still treats CPA gate mostly as zero-credential only:
* `_collect_cpa_credential_gate()` returns `zero_available`.* auto-fill branches check `cpa_credential_gate.get("zero_available")`.* There is no `_cpa_provider_auth_below_pool_target()` helper in current `api.py`.* Current `zero_available` expression is `management_ok and available <= 0`; source includes `safe_read_only and management_ok and available <= 0`.
Source behavior adds:
* `_cpa_provider_auth_below_pool_target(gate, pool_target)`.* Auto-check `provider_auth_below_target` when `available < pool_active_target`.* Preventive rotate when Team is full and provider auth is below target, even when `available` is not zero.* Runtime validation degraded follow-up when provider-auth available is below pool target.
### 2. Pending invite is counted in manager capacity but not current API auto-check
Current `manager.py` already has `_remote_team_occupancy()` and `_has_remote_capacity_for_new_seat()`, and logs `members`, `invites`, `total`. This protects the create path from blindly adding a new seat when pending invite occupies capacity.
Current `api.py` auto-check still has `_auto_check_team_member_count()` returning plain `int(result["count"])` from the Playwright probe. It does not carry `invites` or `occupancy` into:
* Team-full decision.* Over-cap cleanup trigger.* cleanup task params.
Source behavior adds:
* `_TeamMemberCount(int)` with `.invites` and `.occupancy`.* `_team_member_invite_count()` and `_team_member_occupancy()`.* `_auto_check_team_member_count()` parses `count`, `invites`, `occupancy` from probe JSON.* auto-check uses `actual_team_occupancy > target_seats` for cleanup and includes `invite_count` / `team_occupancy` params.* Unit test `test_auto_check_triggers_cleanup_when_pending_invite_exceeds_occupancy`.
### 3. Direct file replacement would be unsafe
The current repo has local divergence that source `autoteam-1` does not fully share:
* Round 11 OAuth/backoff logic.* Current status/task APIs and single-main operating contract.* Current setup diagnostics and frontend docs.* Existing pending-invite capacity logic in `manager.py`.
Therefore the implementation should adapt the source semantics into the current structure instead of replacing `api.py`.
## Recommended MVP
Implement a narrow semantic patch:
1. Add source-style provider-auth below-target helper and safe-read-only guard.2. Add `_TeamMemberCount` carrier and helper functions to `api.py`.3. Update current auto-check branches to use provider-auth low-water trigger and pending invite occupancy.4. Update runtime validation to include provider-auth below-target degraded follow-up.5. Add unit tests adapted to current repository shape.
## Verification targets
Suggested targeted commands after implementation:
```bash.\.venv\Scripts\python.exe -m ruff check src/autoteam/api.py tests/unit/test_api_status.py.\.venv\Scripts\python.exe -m pytest tests/unit/test_api_status.py -q```
If time allows, add current related suites:
```bash.\.venv\Scripts\python.exe -m pytest tests/unit/test_manager_rotate.py tests/unit/test_manager_fill.py -q```1234567891011121314151617181920212223242526{ "id": "autoteam1-provider-auth-seat-semantics", "name": "autoteam1-provider-auth-seat-semantics", "title": "brainstorm: align autoteam-1 latest provider-auth seat semantics", "description": "", "status": "in_progress", "dev_type": null, "scope": null, "package": null, "priority": "P2", "creator": "ZRainbow", "assignee": "ZRainbow", "createdAt": "2026-05-21", "completedAt": null, "branch": null, "base_branch": "main", "worktree_path": null, "commit": null, "pr_url": null, "subtasks": [], "children": [], "parent": null, "relatedFiles": [], "notes": "", "meta": {}}947 unmodified lines9489499509519529532865 unmodified lines38193820382138223823382416 unmodified lines384138423843384438453846384773 unmodified lines392139223923392439253926392739283929393060 unmodified lines39913992399339943995399614 unmodified lines401140124013401440154016401712 unmodified lines40304031403240334034403545 unmodified lines408140824083408440854086408711 unmodified lines40994100410141024103410423 unmodified lines4128412941304131413241334134413541364137413874 unmodified lines421342144215421642174218947 unmodified linesif quota_ok < pool_target:followup_reasons.append(f"quota_ok={quota_ok}/{pool_target}")if hard_reasons:validation.update({2865 unmodified linesreturn _parse_playwright_probe_stdout(stdout) if stdout else {}def _auto_check_team_member_count(timeout_seconds: float = 30, retries: int = 2) -> int:"""Return Team member count via a killable subprocess probe; -1 means unknown."""16 unmodified linesreturn -1try:return int(result.get("count", -1))except Exception:return -173 unmodified lines"available": available,"total": total,"reason": reason,"zero_available": management_ok and available <= 0,}def _auto_check_loop():"""后台巡检线程:定期检查额度,多个账号低于阈值时自动轮转"""from autoteam.accounts import STATUS_ACTIVE, is_account_disabled, load_accounts60 unmodified linescpa_credential_gate.get("safe_read_only"),)# Watchdog:active 账号数 < 子号目标时自动补位。# 之前的 `if not active: continue` 在 active 全 kick 进 standby# 之后会让 Team 永远萎缩。但触发频率必须节制 —— OpenAI 对短时间内反复14 unmodified lines# 冷却期内仍然继续做"低额度替换"(下面的 low_accounts 逻辑),# 只是不触发全量 cmd_rotate。例外:Team 真实人数不足时必须继续补位,# 否则 cooldown 会把实际席位缺口拖到下一轮甚至 4h backoff 之后。actual_team_count = _auto_check_team_member_count(timeout_seconds=30, retries=2)if actual_team_count >= target_seats:if replaceable_blockers:logger.warning(12 unmodified linescpa_credential_gate.get("total"),)should_start_auto_fill = Trueelse:logger.info("[巡检] auto-fill 冷却中且 Team 实际成员数=%d 已满;本轮只保留低额度替换检查",45 unmodified linesif backoff_triggered:continueactual_team_count = _auto_check_team_member_count(timeout_seconds=30, retries=2)if actual_team_count >= target_seats:if replaceable_blockers:logger.warning(11 unmodified linessub_account_target,cpa_credential_gate.get("total"),)else:logger.info("[巡检] 本地 active=%d < %d,但 Team 实际成员数=%d 已满;先跳过 auto-fill,等待同步/对账稳定",23 unmodified linestry:task_params = {"target_seats": target_seats}if cpa_credential_gate.get("enabled"):task_params.update({"trigger": "auto-check","shortage": max(0, sub_account_target - len(active)),"cpa_credential_gate": cpa_credential_gate,})_start_task(74 unmodified lines)except Exception as e:logger.error("[巡检] 即时替换启动失败: %s", e)else:logger.info("[巡检] 额度正常,无需替换")947 unmodified lines9489499509519529539549559569579589599609612865 unmodified lines3827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386116 unmodified lines387838793880388138823883388438853886388773 unmodified lines3961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398360 unmodified lines404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408614 unmodified lines41014102410341044105410612 unmodified lines411941204121412241234124412541264127412841294130413141324133413445 unmodified lines41804181418241834184418511 unmodified lines41974198419942004201420242034204420542064207420842094210421123 unmodified lines42354236423742384239424042414242424342444245424642474248424942504251425242534254425574 unmodified lines4330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381947 unmodified linesif quota_ok < pool_target:followup_reasons.append(f"quota_ok={quota_ok}/{pool_target}")cpa_credential_gate = _collect_cpa_credential_gate()if cpa_credential_gate.get("enabled"):validation["cpa_credential_gate"] = cpa_credential_gatevalidation["provider_auth_available"] = cpa_credential_gate.get("available")if _cpa_provider_auth_below_pool_target(cpa_credential_gate, pool_target):available = int(cpa_credential_gate.get("available") or 0)followup_reasons.append(f"provider_auth_available={available}/{pool_target}")if hard_reasons:validation.update({2865 unmodified linesreturn _parse_playwright_probe_stdout(stdout) if stdout else {}class _TeamMemberCount(int):def __new__(cls, count: int, *, invites: int = 0, occupancy: int | None = None):obj = int.__new__(cls, count)obj.invites = max(0, int(invites or 0))obj.occupancy = int(occupancy) if occupancy is not None else int(count) + obj.invitesreturn objdef _team_member_invite_count(team_count) -> int:try:return max(0, int(getattr(team_count, "invites", 0) or 0))except (TypeError, ValueError):return 0def _team_member_occupancy(team_count) -> int:try:count = int(team_count)except (TypeError, ValueError):return -1if count < 0:return -1try:occupancy = int(team_count.occupancy)except (AttributeError, TypeError, ValueError):occupancy = count + _team_member_invite_count(team_count)return max(count, occupancy)def _auto_check_team_member_count(timeout_seconds: float = 30, retries: int = 2) -> int:"""Return Team member count via a killable subprocess probe; -1 means unknown."""16 unmodified linesreturn -1try:count = int(result.get("count", -1))invites = int(result.get("invites", 0) or 0)occupancy = int(result.get("occupancy", count + invites if count >= 0 else -1))return _TeamMemberCount(count, invites=invites, occupancy=occupancy)except Exception:return -173 unmodified lines"available": available,"total": total,"reason": reason,"zero_available": safe_read_only and management_ok and available <= 0,}def _cpa_provider_auth_below_pool_target(gate: dict | None, pool_target: int) -> bool:if not isinstance(gate, dict):return Falseif not gate.get("enabled") or not gate.get("safe_read_only") or not gate.get("management_ok"):return Falsetry:available = int(gate.get("available"))target = max(1, int(pool_target))except (TypeError, ValueError):return Falsereturn available < targetdef _auto_check_loop():"""后台巡检线程:定期检查额度,多个账号低于阈值时自动轮转"""from autoteam.accounts import STATUS_ACTIVE, is_account_disabled, load_accounts60 unmodified linescpa_credential_gate.get("safe_read_only"),)provider_auth_below_target = _cpa_provider_auth_below_pool_target(cpa_credential_gate, sub_account_target)actual_team_count = _auto_check_team_member_count(timeout_seconds=30, retries=2)actual_invite_count = _team_member_invite_count(actual_team_count)actual_team_occupancy = _team_member_occupancy(actual_team_count)if actual_team_occupancy > target_seats:if not _playwright_lock.acquire(blocking=False):logger.info("[巡检] Team 远端占用超出目标,但有任务在跑,本轮跳过自动清理")continue_playwright_lock.release()logger.warning("[巡检] Team 远端占用超出目标: members=%d invites=%d total=%d/%d,触发自动清理",int(actual_team_count),actual_invite_count,actual_team_occupancy,target_seats,)from autoteam.manager import cmd_cleanuptry:_start_task("auto-cleanup",cmd_cleanup,{"max_seats": target_seats,"trigger": "auto-check","team_count": int(actual_team_count),"invite_count": actual_invite_count,"team_occupancy": actual_team_occupancy,},target_seats,)except Exception as e:logger.error("[巡检] 自动清理失败: %s", e)continue# Watchdog:active 账号数 < 子号目标时自动补位。# 之前的 `if not active: continue` 在 active 全 kick 进 standby# 之后会让 Team 永远萎缩。但触发频率必须节制 —— OpenAI 对短时间内反复14 unmodified lines# 冷却期内仍然继续做"低额度替换"(下面的 low_accounts 逻辑),# 只是不触发全量 cmd_rotate。例外:Team 真实人数不足时必须继续补位,# 否则 cooldown 会把实际席位缺口拖到下一轮甚至 4h backoff 之后。if actual_team_count >= target_seats:if replaceable_blockers:logger.warning(12 unmodified linescpa_credential_gate.get("total"),)should_start_auto_fill = Trueelif provider_auth_below_target:logger.warning("[巡检] auto-fill 冷却中但 CPA/CLIProxy provider-auth 可用凭证低水位: ""available=%s/%d local_active=%d/%d,继续补位/同步",cpa_credential_gate.get("available"),sub_account_target,len(active),sub_account_target,)should_start_auto_fill = Trueelse:logger.info("[巡检] auto-fill 冷却中且 Team 实际成员数=%d 已满;本轮只保留低额度替换检查",45 unmodified linesif backoff_triggered:continueif actual_team_count >= target_seats:if replaceable_blockers:logger.warning(11 unmodified linessub_account_target,cpa_credential_gate.get("total"),)elif provider_auth_below_target:logger.warning("[巡检] Team 已满且 CPA/CLIProxy provider-auth 可用凭证低水位: ""available=%s/%d local_active=%d/%d,触发 auto-fill 补位/同步",cpa_credential_gate.get("available"),sub_account_target,len(active),sub_account_target,)else:logger.info("[巡检] 本地 active=%d < %d,但 Team 实际成员数=%d 已满;先跳过 auto-fill,等待同步/对账稳定",23 unmodified linestry:task_params = {"target_seats": target_seats}if cpa_credential_gate.get("enabled"):try:provider_available = int(cpa_credential_gate.get("available") or 0)except (TypeError, ValueError):provider_available = 0task_params.update({"trigger": "auto-check","shortage": max(0,sub_account_target - min(len(active), provider_available),),"cpa_credential_gate": cpa_credential_gate,"provider_auth_below_target": provider_auth_below_target,"provider_auth_available": cpa_credential_gate.get("available"),"provider_auth_target": sub_account_target,})_start_task(74 unmodified lines)except Exception as e:logger.error("[巡检] 即时替换启动失败: %s", e)elif provider_auth_below_target and actual_team_count >= target_seats:try:provider_available = int(cpa_credential_gate.get("available") or 0)except (TypeError, ValueError):provider_available = 0shortage = max(1, sub_account_target - min(len(active), provider_available))if not _playwright_lock.acquire(blocking=False):logger.info("[巡检] CPA/CLIProxy provider-auth 低水位,但有任务在跑,本轮跳过预防性轮转")continue_playwright_lock.release()logger.warning("[巡检] CPA/CLIProxy provider-auth 可用凭证低水位: ""available=%d/%d local_active=%d/%d; trigger preventive auto-rotate/sync",provider_available,sub_account_target,len(active),sub_account_target,)from autoteam.manager import cmd_rotatetry:_start_task("auto-rotate",cmd_rotate,{"target": target_seats,"trigger": "auto-check","shortage": shortage,"low_accounts": 0,"cpa_credential_gate": cpa_credential_gate,"provider_auth_below_target": True,"provider_auth_available": cpa_credential_gate.get("available"),"provider_auth_target": sub_account_target,},target_seats,background_post_sync=True,)except Exception as e:logger.error("[巡检] provider-auth 低水位自动轮转失败: %s", e)elif provider_auth_below_target:logger.info("[巡检] CPA/CLIProxy provider-auth 低水位,但 Team 实际成员数=%s 未满或未知,本轮不做预防性轮转",actual_team_count if actual_team_count >= 0 else "unknown",)else:logger.info("[巡检] 额度正常,无需替换")
274 unmodified lines2752762772782792802812822832842852866 unmodified lines2932942952962972982636 unmodified lines293529362937293829392940274 unmodified lines"""if not chatgpt_api:return Falseis_started = getattr(chatgpt_api, "is_started", None)if callable(is_started):try:return bool(is_started())except Exception:passdef _declared_attr(name: str):# Avoid MagicMock/duck objects becoming "ready" via dynamic __getattr__.try:6 unmodified linesreturn getattr(chatgpt_api, name, None)return Nonereturn bool(_declared_attr("browser") or _declared_attr("http_transport"))2636 unmodified linesreturn Trueif not _chatgpt_session_ready(chatgpt_api):chatgpt_api.start()if _has_remote_capacity_for_new_seat(chatgpt_api, stage_label=stage_label):return True_cancel_stale_pending_invites_for_capacity(chatgpt_api, stage_label=stage_label)274 unmodified lines2752762772782792802816 unmodified lines2882892902912922932942952962972982993002636 unmodified lines293729382939294029412942294329442945274 unmodified lines"""if not chatgpt_api:return Falsedef _declared_attr(name: str):# Avoid MagicMock/duck objects becoming "ready" via dynamic __getattr__.try:6 unmodified linesreturn getattr(chatgpt_api, name, None)return Noneis_started = _declared_attr("is_started")if callable(is_started):try:return bool(is_started())except Exception:passreturn bool(_declared_attr("browser") or _declared_attr("http_transport"))2636 unmodified linesreturn Trueif not _chatgpt_session_ready(chatgpt_api):chatgpt_api.start()if not _chatgpt_session_ready(chatgpt_api):logger.warning("%s 无可用 Team API session,跳过远端席位预检", stage_label)return Trueif _has_remote_capacity_for_new_seat(chatgpt_api, stage_label=stage_label):return True_cancel_stale_pending_invites_for_capacity(chatgpt_api, stage_label=stage_label)
14 unmodified lines1516171819202122232425262714 unmodified linesdef _probe_team_member_count() -> dict[str, int]:from autoteam.chatgpt_api import ChatGPTTeamAPIfrom autoteam.manager import get_team_member_countchatgpt = ChatGPTTeamAPI()try:chatgpt.start()return {"count": int(get_team_member_count(chatgpt))}finally:chatgpt.stop()14 unmodified lines1516171819202122232425262728293014 unmodified linesdef _probe_team_member_count() -> dict[str, int]:from autoteam.account_ops import fetch_team_statefrom autoteam.chatgpt_api import ChatGPTTeamAPIchatgpt = ChatGPTTeamAPI()try:chatgpt.start()members, invites = fetch_team_state(chatgpt)count = len(members)invite_count = len(invites)return {"count": count, "invites": invite_count, "occupancy": count + invite_count}finally:chatgpt.stop()
292 unmodified lines293294295296297298146 unmodified lines4454464474484494501 unmodified line45245345445545645744 unmodified lines502503504505506507292 unmodified linesassert started == []def test_auto_check_skips_expensive_probe_when_task_is_running(monkeypatch, caplog):monkeypatch.setattr(api, "_auto_check_config", {"interval": 0, "target_seats": 3, "threshold": 10, "min_low": 1})monkeypatch.setattr(api, "_auto_check_stop", threading.Event())146 unmodified lines"reason": "no_provider_auth","zero_available": True,},}assert args == (3,)assert kwargs == {"background_post_sync": True}1 unmodified lineassert "CPA 可用凭证为 0/0" in caplog.textdef test_auto_check_cpa_gate_does_not_treat_management_failure_as_zero_credentials(monkeypatch, caplog):started = []44 unmodified linesassert "management_ok=False" in caplog.textdef test_sanitize_account_keeps_exportable_main_account_active_without_live_quota(tmp_path, monkeypatch):main_email = "owner@example.com"auth_file = tmp_path / "codex-main.json"292 unmodified lines293294295296297298299300301302303304305306307308146 unmodified lines4554564574584594604614624631 unmodified line46546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659744 unmodified lines642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718292 unmodified linesassert started == []def test_auto_check_team_member_count_carries_invites_and_occupancy(monkeypatch):monkeypatch.setattr(api, "_run_playwright_probe", lambda *args, **kwargs: {"count": 3, "invites": 1, "occupancy": 4})result = api._auto_check_team_member_count()assert result == 3assert api._team_member_invite_count(result) == 1assert api._team_member_occupancy(result) == 4def test_auto_check_skips_expensive_probe_when_task_is_running(monkeypatch, caplog):monkeypatch.setattr(api, "_auto_check_config", {"interval": 0, "target_seats": 3, "threshold": 10, "min_low": 1})monkeypatch.setattr(api, "_auto_check_stop", threading.Event())146 unmodified lines"reason": "no_provider_auth","zero_available": True,},"provider_auth_below_target": True,"provider_auth_available": 0,"provider_auth_target": 2,}assert args == (3,)assert kwargs == {"background_post_sync": True}1 unmodified lineassert "CPA 可用凭证为 0/0" in caplog.textdef test_auto_check_triggers_cleanup_when_pending_invite_exceeds_occupancy(monkeypatch):started = []def fake_start_task(command, func, params, *args, **kwargs):started.append((command, params, args, kwargs))monkeypatch.setattr(api, "_auto_fill_last_trigger_ts", 0.0)monkeypatch.setattr(api, "_auto_check_config", {"interval": 0, "target_seats": 3, "threshold": 10, "min_low": 1})monkeypatch.setattr(api, "log_runtime_resource_snapshot", lambda *args, **kwargs: {})monkeypatch.setattr(api, "_is_main_account_email", lambda _email: False)monkeypatch.setattr("autoteam.accounts.load_accounts", lambda: [])monkeypatch.setattr(api,"_auto_check_team_member_count",lambda *args, **kwargs: api._TeamMemberCount(3, invites=1, occupancy=4),)monkeypatch.setattr(api, "_start_task", fake_start_task)monkeypatch.setattr("autoteam.sync_targets.is_sync_target_enabled", lambda target: False)stop_event = threading.Event()restart_event = threading.Event()wait_calls = {"count": 0}def fake_wait(_seconds):wait_calls["count"] += 1return wait_calls["count"] > 1monkeypatch.setattr(stop_event, "wait", fake_wait)monkeypatch.setattr(api, "_auto_check_stop", stop_event)monkeypatch.setattr(api, "_auto_check_restart", restart_event)api._auto_check_loop()assert len(started) == 1command, params, args, kwargs = started[0]assert command == "auto-cleanup"assert params["max_seats"] == 3assert params["trigger"] == "auto-check"assert params["team_count"] == 3assert params["invite_count"] == 1assert params["team_occupancy"] == 4assert args == (3,)assert kwargs == {}def test_auto_check_triggers_preventive_rotate_when_provider_auth_below_target(tmp_path, monkeypatch, caplog):auth_ok = tmp_path / "active-ok.json"auth_other = tmp_path / "active-other.json"auth_ok.write_text(json.dumps({"access_token": "token-ok"}), encoding="utf-8")auth_other.write_text(json.dumps({"access_token": "token-other"}), encoding="utf-8")started = []def fake_start_task(command, func, params, *args, **kwargs):started.append((command, params, args, kwargs))monkeypatch.setattr(api, "_auto_fill_last_trigger_ts", 0.0)monkeypatch.setattr(api, "_auto_check_config", {"interval": 0, "target_seats": 3, "threshold": 10, "min_low": 1})monkeypatch.setattr(api, "log_runtime_resource_snapshot", lambda *args, **kwargs: {})monkeypatch.setattr(api, "_is_main_account_email", lambda _email: False)monkeypatch.setattr("autoteam.accounts.load_accounts",lambda: [{"email": "one@example.com", "status": "active", "auth_file": str(auth_ok)},{"email": "two@example.com", "status": "active", "auth_file": str(auth_other)},],)monkeypatch.setattr("autoteam.codex_auth.check_codex_quota",lambda _token: ("ok", {"primary_pct": 10, "primary_resets_at": 1234567890, "weekly_pct": 1}),)monkeypatch.setattr(api,"_auto_check_team_member_count",lambda *args, **kwargs: api._TeamMemberCount(3, invites=0, occupancy=3),)monkeypatch.setattr(api, "_start_task", fake_start_task)monkeypatch.setattr("autoteam.sync_targets.is_sync_target_enabled", lambda target: target == "cpa")monkeypatch.setattr("autoteam.cliproxy_health.get_cliproxy_health",lambda **_kwargs: {"ok": True,"safe_read_only": True,"management_api": {"ok": True},"provider_auth": {"ok": True,"provider": "codex","model": "gpt-5.5","reason": "provider_auth_has_candidates","total": 4,"available": 1,"check_type": "management_metadata","canary_required": True,},},)stop_event = threading.Event()restart_event = threading.Event()wait_calls = {"count": 0}def fake_wait(_seconds):wait_calls["count"] += 1return wait_calls["count"] > 1monkeypatch.setattr(stop_event, "wait", fake_wait)monkeypatch.setattr(api, "_auto_check_stop", stop_event)monkeypatch.setattr(api, "_auto_check_restart", restart_event)with caplog.at_level(logging.INFO):api._auto_check_loop()assert len(started) == 1command, params, args, kwargs = started[0]assert command == "auto-rotate"assert params["target"] == 3assert params["trigger"] == "auto-check"assert params["shortage"] == 1assert params["low_accounts"] == 0assert params["provider_auth_below_target"] is Trueassert params["provider_auth_available"] == 1assert params["provider_auth_target"] == 2assert params["cpa_credential_gate"]["available"] == 1assert args == (3,)assert kwargs == {"background_post_sync": True}assert "provider-auth 可用凭证低水位" in caplog.textdef test_auto_check_cpa_gate_does_not_treat_management_failure_as_zero_credentials(monkeypatch, caplog):started = []44 unmodified linesassert "management_ok=False" in caplog.textdef test_collect_cpa_credential_gate_requires_safe_read_only_for_zero_available(monkeypatch):monkeypatch.setattr("autoteam.sync_targets.is_sync_target_enabled", lambda target: target == "cpa")monkeypatch.setattr("autoteam.cliproxy_health.get_cliproxy_health",lambda **_kwargs: {"ok": True,"safe_read_only": False,"management_api": {"ok": True},"provider_auth": {"ok": True,"provider": "codex","model": "gpt-5.5","reason": "provider_auth_has_candidates","total": 2,"available": 0,"check_type": "management_metadata","canary_required": True,},},)gate = api._collect_cpa_credential_gate()assert gate["safe_read_only"] is Falseassert gate["zero_available"] is Falseassert api._cpa_provider_auth_below_pool_target(gate, 2) is Falsedef test_runtime_validation_degrades_when_provider_auth_below_target(tmp_path, monkeypatch):auth_one = tmp_path / "one.json"auth_two = tmp_path / "two.json"auth_one.write_text(json.dumps({"access_token": "token-one"}), encoding="utf-8")auth_two.write_text(json.dumps({"access_token": "token-two"}), encoding="utf-8")monkeypatch.setattr(api, "_auto_check_config", {"interval": 0, "target_seats": 3, "threshold": 10, "min_low": 1})monkeypatch.setattr(api, "_is_main_account_email", lambda _email: False)monkeypatch.setattr(api, "_auto_check_team_member_count", lambda *args, **kwargs: 3)monkeypatch.setattr("autoteam.accounts.load_accounts",lambda: [{"email": "one@example.com", "status": accounts.STATUS_ACTIVE, "auth_file": str(auth_one)},{"email": "two@example.com", "status": accounts.STATUS_ACTIVE, "auth_file": str(auth_two)},],)monkeypatch.setattr("autoteam.codex_auth.check_codex_quota", lambda _token: ("ok", {"primary_pct": 10}))monkeypatch.setattr(api,"_collect_cpa_credential_gate",lambda: {"enabled": True,"safe_read_only": True,"management_ok": True,"available": 1,"total": 4,"reason": "provider_auth_has_candidates","zero_available": False,},)validation = api._log_task_runtime_validation("auto-rotate")assert validation["ok"] is Falseassert validation["severity"] == "degraded"assert validation["operation_success"] is Trueassert validation["pool_health_ok"] is Falseassert validation["followup_required"] is Trueassert validation["provider_auth_available"] == 1assert validation["reason"] == "provider_auth_available=1/2"assert validation["cpa_credential_gate"]["available"] == 1def test_sanitize_account_keeps_exportable_main_account_active_without_live_quota(tmp_path, monkeypatch):main_email = "owner@example.com"auth_file = tmp_path / "codex-main.json"
.trellis/spec/backend/runtime-docker-hardening.md+20
.trellis/tasks/05-21-autoteam1-provider-auth-seat-semantics/check.jsonlAdded+1
.trellis/tasks/05-21-autoteam1-provider-auth-seat-semantics/implement.jsonlAdded+1
.trellis/tasks/05-21-autoteam1-provider-auth-seat-semantics/prd.mdAdded+85
.trellis/tasks/05-21-autoteam1-provider-auth-seat-semantics/research/code-diff-findings.mdAdded+96
.trellis/tasks/05-21-autoteam1-provider-auth-seat-semantics/task.jsonAdded+26
src/autoteam/api.py+168-5
src/autoteam/manager.py+11-6
src/autoteam/playwright_probe.py+5-2
tests/unit/test_api_status.py+211