From bd2ba449b402369d3394e2132c6843a94f5c6f14 Mon Sep 17 00:00:00 2001 From: Epinephrine Date: Thu, 19 Nov 2026 11:10:35 +0900 Subject: [PATCH 1/9] fix(link): restore stop cleanup with bounded native Windows proof Restore the guarded file-route drain and exact stop ownership boundaries from #8803 after its Windows timeout revert. Replace repeated CIM owner probes with same-handle native creation/SID evidence, preserve Windows argv semantics, retain apply exclusion during recycle, and retry only closed, unpublished rollback listeners within a shared remaining budget. Native Windows acceptance remains pending; no CI policy or budget changes. --- .../docs/es/reference/cli/lifecycle.md | 24 +- .../docs/fr/reference/cli/lifecycle.md | 15 +- .../src/content/docs/guides/remote-link.md | 6 +- .../src/content/docs/ko/guides/remote-link.md | 2 + .../content/docs/reference/cli/lifecycle.md | 44 +- scripts/test-layout/layout-clients.json | 4 + scripts/test-layout/layout.json | 2 +- src/cli/index.ts | 184 +++--- src/cli/stop-client-process.ts | 51 ++ src/cli/stop-restore.ts | 411 +++++++++++- src/client/machine-listener.ts | 3 + src/client/runtime-recycle.ts | 29 + src/client/runtime-restart.ts | 1 + src/client/runtime-rollback.ts | 29 + src/client/runtime.ts | 217 ++++-- src/client/state.ts | 11 + src/client/stop-darwin-process.ts | 73 +++ src/client/stop-file-routing.ts | 49 ++ src/client/stop-native-handoff.ts | 101 +++ src/client/stop-routing.ts | 48 +- src/client/stop-teardown-owner.ts | 176 +++++ src/client/sync-runtime.ts | 27 +- src/config/pending-teardown.ts | 22 +- src/config/process-state.ts | 12 + src/integrations/route-intent-disconnect.ts | 58 +- src/lib/process-control.ts | 1 + src/server/port-reclaim.ts | 52 +- src/service/health-sentinel-linux.ts | 23 +- src/service/systemd.ts | 13 +- src/service/windows-process-native.ts | 54 +- structure/INDEX.md | 2 + structure/clients/integrations.md | 4 +- structure/config.md | 2 +- structure/manifest.json | 2 + structure/ops/service-health-recovery.md | 2 +- structure/ops/windows-checked-stop.md | 2 + structure/remote-link.md | 23 +- structure/runtime.md | 6 +- tests/cli/cli-client-start-fence.test.ts | 2 +- tests/cli/cli-dispatch.test.ts | 26 +- tests/cli/cli-start-journal-order.test.ts | 3 +- .../clients/client-link-stop-recovery.test.ts | 156 +++++ .../clients/client-link-stop-sibling.test.ts | 335 ++++++++++ tests/clients/client-link-stop.test.ts | 242 ++++--- .../clients/client-recycle-exclusion.test.ts | 67 ++ .../client-restart-rollback-lock.test.ts | 44 ++ tests/clients/client-runtime-restart.test.ts | 16 + .../clients/route-intent-runtime-stop.test.ts | 11 +- .../client-link-stop-recovery-runner.ts | 227 +++++++ tests/fixtures/client-link-stop-runner.ts | 618 +++++++++++++++++- tests/fixtures/parent-stop-runner.ts | 125 +++- tests/fixtures/test-layout-expected.json | 5 +- tests/helpers/client-link-stop.ts | 95 +++ tests/providers/xai/grok-lifecycle.test.ts | 32 +- .../connected-stop-capability-auth.test.ts | 63 +- tests/service/stop-deferred-teardown.test.ts | 255 +++++++- tests/update/update-teardown-handover.test.ts | 6 +- .../windows-stop-owner-identity.test.ts | 94 +++ 58 files changed, 3758 insertions(+), 449 deletions(-) create mode 100644 src/cli/stop-client-process.ts create mode 100644 src/client/runtime-recycle.ts create mode 100644 src/client/runtime-rollback.ts create mode 100644 src/client/stop-darwin-process.ts create mode 100644 src/client/stop-file-routing.ts create mode 100644 src/client/stop-native-handoff.ts create mode 100644 src/client/stop-teardown-owner.ts create mode 100644 tests/clients/client-link-stop-recovery.test.ts create mode 100644 tests/clients/client-link-stop-sibling.test.ts create mode 100644 tests/clients/client-recycle-exclusion.test.ts create mode 100644 tests/clients/client-restart-rollback-lock.test.ts create mode 100644 tests/fixtures/client-link-stop-recovery-runner.ts create mode 100644 tests/helpers/client-link-stop.ts create mode 100644 tests/windows/windows-stop-owner-identity.test.ts diff --git a/docs-site/src/content/docs/es/reference/cli/lifecycle.md b/docs-site/src/content/docs/es/reference/cli/lifecycle.md index 1213bd7440b..2ec012630d2 100644 --- a/docs-site/src/content/docs/es/reference/cli/lifecycle.md +++ b/docs-site/src/content/docs/es/reference/cli/lifecycle.md @@ -46,9 +46,22 @@ ocx start --socks5-off ### `ocx stop [--json] [--deadline-ms ]` -Un Child de Remote Link sin supervisor que recibe una señal de apagado restaura Codex nativo y Grok administrado antes de liberar su listener, comprobando de nuevo la conexión atendida antes de cada escritura. La supervisión de servicio o Desktop, la propiedad de otra instancia, los traspasos de reinicio o reciclaje y los recibos pendientes de parada del padre conservan las integraciones. Durante el apagado se rechaza un reinicio vinculado con `409 runtime_stopping`. Una terminación forzada puede omitir los manejadores de señales; sigue siendo necesaria la restauración del `ocx stop` del padre. Para volver a enrutar Codex por el Home, inicia primero el Child con `ocx start`, o `ocx service start` si está instalado como servicio, y después ejecuta `ocx sync --restart-codex`. Iniciar por sí solo no restablece el enrutamiento. Sincronizar con el Child detenido también lo restablece, pero apuntaría a un listener que no está ejecutándose: inicia primero el Child. +Si un proceso hermano sirve un Remote Link guardado, `ocx stop` verifica la instancia y la titularidad del Link y detiene solo ese proceso. El enrutamiento compartido se conserva. -Detiene el proxy en ejecución por su PID, elimina el archivo PID y restaura Codex nativo cuando el entorno es independiente. Si hay un servicio administrado, `ocx stop` lo detiene primero para impedir que vuelva a iniciar el proxy. +Un Child de Remote Link sin supervisor que recibe una señal de apagado restaura Codex nativo y Grok administrado antes de liberar su listener, comprobando de nuevo la conexión atendida antes de cada escritura. La supervisión de servicio o Desktop, la propiedad de otra instancia y los traspasos de reinicio o reciclaje conservan las integraciones. El Child aplaza la restauración de Codex nativo y Grok solo cuando una parada activa y verificada del padre es titular del recibo correspondiente. El Child completa la limpieza de archivos con la sincronización bloqueada antes de liberar el listener. Un recibo antiguo o ilegible, por sí solo, mantiene el listener abierto y conserva las pruebas de recuperación. Durante el apagado se rechaza un reinicio vinculado con `409 runtime_stopping`. Una terminación forzada puede omitir los manejadores de señales; sigue siendo necesaria la restauración del `ocx stop` del padre. Para volver a enrutar Codex por el Home, inicia primero el Child con `ocx start`, o `ocx service start` si está instalado como servicio, y después ejecuta `ocx sync --restart-codex`. Iniciar por sí solo no restablece el enrutamiento. Sincronizar con el Child detenido también lo restablece, pero apuntaría a un listener que no está ejecutándose: inicia primero el Child. + +Durante el apagado por señal sin supervisor, si se rechaza la limpieza de archivos o la restauración de Codex nativo o Grok, incluso por titularidad no verificable, el listener permanece abierto y la sincronización queda pausada; repara la configuración o la evidencia de titularidad indicada y vuelve a ejecutar `ocx stop`. Para salir del Home después de una parada rechazada, `ocx disconnect --recover-config --yes` completa la recuperación de la configuración y reinicia el Child retenido como OpenCodex independiente. Una parada o recuperación todavía en curso sigue rechazando el reinicio. Una parada explícita comprueba que el Child sigue atendiendo la conexión Link guardada y admite el bloqueo de parada. Después elimina las integraciones de archivos creadas por el Link antes de detener el proceso o el servicio. Si la conexión guardada no es válida, ha cambiado de titular o se rechaza la limpieza de archivos, repara la conexión o las pruebas de titularidad indicadas y vuelve a intentarlo. La parada también se rechaza antes de terminar el proceso si un registro de recuperación anterior impediría la restauración nativa. En una parada explícita con `ocx stop`, la restauración nativa se intenta después de que el Child haya terminado; un rechazo informa de la restauración incompleta y conserva las pruebas de recuperación, pero el listener ya está detenido. + +La orden debe guardar su recibo de recuperación antes de pedir al gestor del servicio o al proceso que se detenga. En Linux, la terminación directa requiere que el kernel admita pidfd. En macOS, la parada directa envía un solo SIGTERM. Si falla la parada directa, consulta el motivo en el terminal o supervisor del Child, corrige el problema indicado y vuelve a ejecutar `ocx stop`. + +Si un Child de Remote Link sigue ejecutando una versión sin el bloqueo de parada, como v2.100.4, la CLI actual rechaza detenerlo. Para conservar la conexión guardada con el Home: + +1. Cierra Codex, Grok y los demás clientes que usan el Child antes de liberar su puerto. +2. Detén el entorno antiguo desde su supervisor original. Pulsa Ctrl+C en su terminal si está en primer plano, usa Stop y cierra la aplicación Desktop si lo supervisa, o ejecuta `ocx stop` desde la **instalación antigua** si es un servicio en segundo plano, incluido el Programador de tareas de Windows. +3. Una vez detenido, ejecuta `ocx stop` desde la **instalación actual**, con el mismo `OPENCODEX_HOME` y los mismos directorios de los clientes. Así se completa la limpieza de las rutas de archivos y se conserva la conexión. Mantén cerrados los clientes y resuelve los errores de restauración antes de continuar. En Linux también funciona sin acceso al gestor de usuario de systemd si no existen la unidad instalada ni los registros de instalación del servicio y los endpoints locales conocidos están inactivos. +4. Inicia el entorno actual con `ocx start`, con `ocx service start` si hay un servicio instalado o con la aplicación Desktop actualizada si esta lo administra. Una vez que el Child esté activo, ejecuta `ocx sync --restart-codex`. + +Un cliente nativo que no pueda demostrar si atiende una conexión Link o Hub rechaza la parada. Actualiza y reinicia los clientes nativos antiguos mediante su supervisor y vuelve a intentarlo. En un entorno independiente, el comando detiene el proxy en ejecución por su PID, elimina el archivo PID y restaura Codex nativo. Si hay un servicio administrado, `ocx stop` lo detiene primero para impedir que vuelva a iniciar el proxy. En un cliente conectado a un Hub, la parada conserva el enrutamiento de Codex, su catálogo y la configuración de Grok, incluso si se detiene correctamente mediante la API. Esos ajustes pertenecen @@ -75,7 +88,10 @@ Los entornos antiguos o no verificados se rechazan antes de actuar. Actualiza o mediante su supervisor y reinténtalo. Usa `ocx disconnect` solo si quieres liberar las integraciones de la conexión. Si el cliente ya está detenido, otra parada verifica que el gestor del servicio esté inactivo y que no haya listeners en los endpoints locales conocidos antes de devolver el resultado -habitual de proceso ausente. +habitual de proceso ausente. Para un Child de Link en Linux sin servicio instalado, se aplica la +comprobación de ausencia descrita arriba. Con el puerto configurado en `0`, se comprueba el puerto concreto +guardado en el registro del entorno. Sin ese endpoint registrado, se rechaza la parada porque +no se puede demostrar que el entorno esté ausente. Mientras OpenCodex Desktop esté abierto, `ocx stop` no mantiene detenido el proxy: la aplicación lo trata como una salida inesperada y lo inicia de nuevo, en segundos si lo había iniciado ella o en aproximadamente un minuto si solo se había conectado a él. Usa **Stop proxy** en su bandeja, para un proxy iniciado por la aplicación, o **Quit** para mantenerlo detenido. Por esa misma razón, el botón **Stop** del dashboard rechaza la acción con `desktop_supervised` sin cambios cuando el proxy pertenece a la aplicación. En otros entornos, ejecuta `POST /api/stop`, salvo con el Programador de tareas de Windows: allí un contenedor puede reiniciar el proxy después de terminar la tarea. El dashboard responde `respawnable_service`, no cambia nada y pide ejecutar `ocx stop` desde fuera del proxy para verificar que no reaparezca antes de restaurar los ajustes del cliente. @@ -104,7 +120,7 @@ Si OpenCodex no puede confirmar que un envoltorio terminó porque no dispone de de objeto de proceso (handle), como puede ocurrir en ARM64, compruébalo en el Administrador de tareas desde la sesión de su propietario, detenlo si sigue en ejecución y vuelve a intentarlo. -Si no puede demostrarse que el servicio se detuvo, `ocx stop` no envía una solicitud de parada al proxy, deja intacta la configuración del cliente y falla. Con `--json`, el resumen conserva `outcome: "failed"` y `proxy: "unknown"`, y añade `serviceStopReason`: +Si no puede demostrarse que el servicio se detuvo, `ocx stop` no envía una solicitud de parada al proxy ni continúa con la restauración nativa compartida. En un Child de Remote Link, el prevuelo puede haber eliminado ya las integraciones de archivos propiedad del Link y pausado la sincronización; repara la parada del servicio y vuelve a ejecutar `ocx stop`. El comando falla. Con `--json`, el resumen conserva `outcome: "failed"` y `proxy: "unknown"`, y añade `serviceStopReason`: | `serviceStopReason` | Significado | Qué hacer | |---|---|---| diff --git a/docs-site/src/content/docs/fr/reference/cli/lifecycle.md b/docs-site/src/content/docs/fr/reference/cli/lifecycle.md index b1261a31d5d..e791391e7e9 100644 --- a/docs-site/src/content/docs/fr/reference/cli/lifecycle.md +++ b/docs-site/src/content/docs/fr/reference/cli/lifecycle.md @@ -32,11 +32,22 @@ ocx start --socks5-off ### `ocx stop` -Un Link Child non supervisé restaure Codex natif et Grok avant de libérer son listener lors d’un signal, en revérifiant la connexion à chaque écriture. Service/Desktop, sibling, transfert de redémarrage et reçu stop du parent préservent les intégrations. L’arrêt refuse le redémarrage avec `409 runtime_stopping`. Une terminaison forcée peut éviter le signal ; la restauration par `ocx stop` reste nécessaire. +Si une instance sœur dessert un Remote Link enregistré, `ocx stop` vérifie l’instance et la propriété du Link et arrête uniquement ce processus. Le routage partagé est conservé. + +Un Link Child non supervisé supprime les intégrations de fichiers créées par le Link, puis restaure Codex natif et Grok avant de libérer son listener lors d’un signal, en revérifiant la connexion à chaque écriture. Les intégrations autonomes antérieures et les modifications de l’utilisateur sont conservées. Pendant cet arrêt par signal sans supervision, si le nettoyage des fichiers ou la restauration de Codex natif ou Grok est refusé, y compris en cas de propriété non vérifiable, le listener reste ouvert et la synchronisation est suspendue : réparez la configuration signalée, puis relancez `ocx stop`. Pour quitter le Home après un refus, `ocx disconnect --recover-config --yes` termine la récupération de la configuration et redémarre le Child restant en OpenCodex autonome. Un arrêt ou une récupération encore en cours continue de refuser le redémarrage. Un arrêt explicite vérifie que le Child dessert toujours la connexion Link enregistrée et prend en charge le verrou d’arrêt. Il nettoie ces fichiers avant d’arrêter le processus ou le service. Si la connexion enregistrée est invalide, a changé de propriétaire ou si le nettoyage est refusé, corrigez la connexion ou les preuves de propriété signalées, puis réessayez. Un ancien enregistrement de récupération qui empêcherait la restauration native refuse aussi l’arrêt avant la terminaison. Service/Desktop, sibling et transfert de redémarrage préservent les intégrations. Le Child ne diffère la restauration de Codex natif et de Grok que si un arrêt actif et vérifié du parent possède le reçu correspondant. Le Child nettoie les fichiers avec la synchronisation suspendue avant de libérer le listener. Un reçu ancien ou illisible ne suffit pas : le listener reste ouvert et les preuves de récupération sont conservées. Lors d’un `ocx stop` explicite, la restauration native est tentée après la sortie du Child ; un refus conserve les preuves de récupération et signale une restauration incomplète, avec le listener déjà arrêté. L’arrêt refuse le redémarrage avec `409 runtime_stopping`. Une terminaison forcée peut éviter le signal ; la restauration par `ocx stop` reste nécessaire. + +La commande doit enregistrer son reçu de récupération avant de demander l’arrêt au gestionnaire du service ou au processus. Sous Linux, l’arrêt direct exige la prise en charge de pidfd par le noyau. Sous macOS, l’arrêt direct envoie un seul SIGTERM. Si l’arrêt direct échoue, consultez le terminal ou le superviseur du Child, corrigez le problème signalé, puis relancez `ocx stop`. + +Si un Child de Remote Link exécute encore une version dépourvue du verrou d’arrêt, comme v2.100.4, la CLI actuelle refuse de l’arrêter. Pour conserver la connexion au Home : + +1. Fermez Codex, Grok et les autres clients qui passent par le Child avant de libérer son port. +2. Arrêtez l’ancien processus avec son superviseur d’origine. Appuyez sur Ctrl+C dans son terminal s’il tourne au premier plan, utilisez Stop puis quittez l’application Desktop si elle le supervise, ou exécutez `ocx stop` depuis **l’ancienne installation** pour un service d’arrière-plan, y compris le Planificateur de tâches Windows. +3. Une fois le processus arrêté, exécutez `ocx stop` depuis **l’installation actuelle** avec le même `OPENCODEX_HOME` et les mêmes répertoires des clients. Cette étape termine le nettoyage des fichiers de routage et conserve la connexion. Gardez les clients fermés et corrigez les erreurs de restauration avant de continuer. Sous Linux, cette étape fonctionne aussi sans accès au gestionnaire utilisateur systemd si l’unité d’installation et les enregistrements d’installation du service sont absents et que les points d’accès locaux connus sont inactifs. +4. Démarrez la version actuelle avec `ocx start`, `ocx service start` pour un service installé ou l’application Desktop mise à jour si elle supervise le processus. Une fois le Child actif, exécutez `ocx sync --restart-codex`. Arrête le proxy actif à partir de son PID, supprime le fichier de PID et rétablit le fonctionnement natif de Codex. Si un service d’arrière-plan géré est installé, `ocx stop` l’arrête d’abord afin qu’il ne puisse pas relancer le proxy. Le levier du proxy du tableau de bord Web, tiré jusqu’en bas dans la barre latérale, exécute la même opération (`POST /api/stop`) sur tous les backends, sauf le Planificateur de tâches Windows : le wrapper peut y relancer le proxy après la fin de la tâche, donc le tableau de bord refuse avec `respawnable_service`, ne modifie rien et vous demande d'exécuter `ocx stop`. -Sur un client hub connecté, `ocx stop`, y compris via l’API, conserve le routage Codex, le catalogue et la configuration Grok appartenant à la connexion ; `ocx start` les dessert de nouveau. L’arrêt explicite d’un Remote Link Child rétablit au contraire, si la restauration partagée réussit, le routage natif de Codex, le catalogue et les métadonnées de reprise sauvegardées, et supprime la configuration Grok gérée. La connexion Home enregistrée reste conservée ; `ocx disconnect` la supprime. +Un client natif qui ne peut pas prouver s’il dessert une connexion Link ou Hub refuse l’arrêt. Mettez à jour et redémarrez les anciens clients natifs via leur superviseur, puis réessayez. Sur un client hub connecté, `ocx stop`, y compris via l’API, conserve le routage Codex, le catalogue et la configuration Grok appartenant à la connexion ; `ocx start` les dessert de nouveau. L’arrêt explicite d’un Remote Link Child rétablit au contraire, si la restauration partagée réussit, le routage natif de Codex, le catalogue et les métadonnées de reprise sauvegardées, et supprime la configuration Grok gérée. La connexion Home enregistrée reste conservée ; `ocx disconnect` la supprime. Pour réutiliser Home depuis Codex après cette restauration, lancez `ocx start` (ou `ocx service start` si un service est installé), puis `ocx sync --restart-codex`. Le démarrage seul ne réapplique pas le routage ; sync ne recrée pas le bloc Grok. Si l’appartenance de la connexion ne peut pas être confirmée avant l’arrêt du service, l’API d’arrêt renvoie HTTP 409 avec `sharedTeardown: "refused"` et laisse le proxy et le gestionnaire de service actifs. Attendez la fin de la connexion ou déconnexion en cours, puis réessayez. diff --git a/docs-site/src/content/docs/guides/remote-link.md b/docs-site/src/content/docs/guides/remote-link.md index 217193018dd..2413d0a9848 100644 --- a/docs-site/src/content/docs/guides/remote-link.md +++ b/docs-site/src/content/docs/guides/remote-link.md @@ -51,11 +51,11 @@ Connecting restarts OpenCodex on this computer. Codex turns that are already run The Child waits for its configured port while the old process releases it. If a CLI-managed restart still fails, run `ocx start` on the Child and check `~/.opencodex/restart-handoff.log`. In the desktop app, the app starts and supervises the replacement automatically. -An explicit `ocx stop` on a Remote Link Child stops its proxy and, when shared restoration succeeds, restores native Codex routing, its catalog and backed-up resume-history metadata and removes the managed Grok configuration. The saved Home connection is kept; use `ocx disconnect` to remove that connection. +An explicit `ocx stop` on a Remote Link Child stops its proxy and, when shared restoration succeeds, restores native Codex routing, its catalog and backed-up resume-history metadata and removes the managed Grok configuration. Before stopping the process or service, it removes file integrations created by the Link (such as Pi or OpenCode), preserving pre-existing standalone integrations and user edits. If cleanup is refused, the listener stays bound with synchronization paused; repair the reported configuration or ownership evidence and retry `ocx stop`. To leave Home after a refused stop, `ocx disconnect --recover-config --yes` completes configuration recovery and restarts the retained Child as standalone OpenCodex. A stop or recovery still in progress continues to refuse restart. If the running Child cannot prove support for safe stop, update and restart it through its supervisor before retrying. The saved Home connection is kept; use `ocx disconnect` to remove that connection. -If a hub connection takes ownership while stopping, its routing and configuration are preserved. A connection still being created or disconnected can refuse restoration; let that operation finish, then retry `ocx stop`. The dashboard stop API returns HTTP 409 with `sharedTeardown: "refused"` when ownership cannot be confirmed and keeps the listener running. Signal cleanup also preserves configuration when ownership cannot be confirmed. +If a hub connection takes ownership while stopping, its routing and configuration are preserved. A connection still being created or disconnected can refuse restoration; let that operation finish, then retry `ocx stop`. The dashboard stop API returns HTTP 409 with `sharedTeardown: "refused"` when ownership cannot be confirmed and keeps the listener running. During unsupervised signal cleanup, configuration is preserved when ownership cannot be confirmed, and refusal of file cleanup or native Codex/Grok restoration retains the listener with synchronization paused; repair the reported evidence and retry `ocx stop`. Only a verified active parent stop for this Child can defer native restoration; its receipt never skips file cleanup or the synchronization fence. A stale or unreadable receipt alone keeps the listener bound and the recovery evidence intact. An explicit stop also refuses before termination if an older recovery record would block native restoration. During explicit `ocx stop`, native restoration is attempted after the Child exits; a refusal then reports incomplete restoration and preserves recovery evidence with the listener already stopped. -To use Home from Codex again after restoration, start the Child with `ocx start` (or `ocx service start` for an installed service), then run `ocx sync --restart-codex`. Starting the runtime does not reapply a Child's Codex routing. Sync reapplies Codex settings when Codex is enabled for the saved connection, and the flag restarts Codex to load them; it does not recreate the Grok block. This is the explicit Link Child stop/start workflow; hub-client ownership and the separate restart, recycling, service-exit and sibling rules are unchanged. +To use Home from Codex again after restoration, start the Child with `ocx start` (or `ocx service start` for an installed service), then run `ocx sync --restart-codex`. Starting the runtime does not reapply a Child's Codex routing. With Home available, sync also reapplies its enabled file integrations. Sync reapplies Codex settings when Codex is enabled for the saved connection, and the flag restarts Codex to load them; it does not recreate the Grok block. This is the explicit Link Child stop/start workflow; hub-client ownership and the separate restart, recycling, service-exit and sibling rules are unchanged. If **Child** says to pair this machine first, open this computer's configured literal-loopback HTTP dashboard, for example `http://127.0.0.1:`. The local pairing form appears only when pairing is missing and the dashboard and API use the same loopback origin. Copy the form's `ocx gui pair --origin "http://127.0.0.1:"` command, run it in a terminal on this computer, and paste the one-use code into the form. Use the exact origin shown in the form; a provider API key or admin token is not a pairing code. Missing pairing is separate from a configured-port mismatch. diff --git a/docs-site/src/content/docs/ko/guides/remote-link.md b/docs-site/src/content/docs/ko/guides/remote-link.md index 4b295cd2a42..9e23fba87d3 100644 --- a/docs-site/src/content/docs/ko/guides/remote-link.md +++ b/docs-site/src/content/docs/ko/guides/remote-link.md @@ -47,6 +47,8 @@ Home의 프로바이더를 사용할 컴퓨터에서 다음을 진행합니다. 연결하면 이 컴퓨터의 OpenCodex가 다시 시작됩니다. 이미 실행 중인 Codex 작업은 먼저 끝나고, 다시 시작되는 동안 최대 1분 정도 새 요청이 실패할 수 있습니다. 그 뒤 대시보드가 스스로 새로 고쳐지고 Child 링크를 보여 줍니다. Codex는 이 컴퓨터의 `http://127.0.0.1:/v1`을 그대로 사용하며 토큰이나 환경 변수를 설정할 필요가 없습니다. 로컬 OpenCodex가 각 요청을 Home으로 전달하고, Home은 자신의 프로바이더와 계정으로 응답합니다. +Child에서 `ocx stop`을 실행하면 프로세스나 서비스를 종료하기 전에 Link가 만든 Pi·OpenCode 등의 파일 통합을 정리합니다. 연결 전부터 쓰던 독립형 통합과 사용자가 수정한 내용은 보존합니다. 파일이 충돌하거나 소유권을 확인할 수 없으면 종료를 거부하고, 동기화를 멈춘 채 로컬 포트를 유지합니다. 표시된 설정이나 소유권 기록을 복구한 뒤 `ocx stop`을 다시 실행하세요. 종료가 거부된 뒤 Home 연결도 끊으려면 `ocx disconnect --recover-config --yes`를 실행할 수 있습니다. 설정 복구가 완전히 끝나면 남아 있던 Child가 독립형 OpenCodex로 다시 시작합니다. 종료나 복구가 아직 진행 중이면 재시작을 계속 거부합니다. 실행 중인 Child가 안전한 종료 지원을 증명하지 못하는 구버전이라면, 해당 서비스를 관리하는 프로그램을 통해 업데이트하고 다시 시작한 뒤 재시도하세요. Home 연결 정보는 남으며, 연결 자체를 지우려면 `ocx disconnect`를 사용합니다. 다시 사용하려면 Child를 시작한 뒤 Home에 연결할 수 있는 상태에서 `ocx sync --restart-codex`를 실행하세요. 시작만으로는 통합 설정을 다시 적용하지 않습니다. 종료 신호를 처리하면서 파일 정리 이후 Codex 기본 설정이나 Grok 복원이 거부된 경우에도 Child는 동기화를 멈추고 로컬 포트를 유지합니다. 표시된 기록을 복구한 뒤 `ocx stop`을 다시 실행하세요. 이 Child의 종료를 실제로 맡은 상위 프로세스를 확인한 경우에만 Codex 기본 설정과 Grok 복원을 넘깁니다. 종료 기록만으로 파일 정리나 동기화 차단을 생략하지 않으며, 오래되거나 읽을 수 없는 기록만 남아 있으면 포트와 복구 기록을 유지합니다. 명시적인 중단 명령도 이전 복구 기록 때문에 기본 설정을 복원할 수 없는 경우에는 프로세스를 종료하기 전에 거부합니다. 명시적인 `ocx stop`은 Child가 종료된 뒤 기본 설정 복원을 시도하므로, 이 단계에서 복원이 거부되면 포트는 이미 닫힌 상태이고 미완료 복원과 남은 복구 기록을 알려 줍니다. + **Child**에 이 컴퓨터를 먼저 페어링하라는 안내가 나오면, 이 컴퓨터에 설정된 IP 주소 형식의 HTTP 루프백 대시보드(예: `http://127.0.0.1:`)를 여세요. 로컬 페어링 양식은 페어링이 필요하고 대시보드와 API가 같은 루프백 출처를 사용할 때만 표시됩니다. 양식의 `ocx gui pair --origin "http://127.0.0.1:"` 명령을 복사해 이 컴퓨터의 터미널에서 실행한 뒤, 일회용 코드를 양식에 붙여 넣으세요. 양식에 표시된 정확한 출처를 사용해야 하며, 프로바이더 API 키나 관리자 토큰은 페어링 코드가 아닙니다. 페어링 누락과 설정된 포트의 불일치는 서로 다른 사유입니다. **Child** 역할을 선택하려면 OpenCodex가 독립형 런타임으로 설정된 포트에서 실행 중이어야 합니다. Child는 정확히 그 포트에서 다시 시작하기 때문입니다. 대시보드가 설정된 포트에서 실행되고 있지 않다고 알리면, 먼저 그 포트에서 OpenCodex를 다시 시작하세요. diff --git a/docs-site/src/content/docs/reference/cli/lifecycle.md b/docs-site/src/content/docs/reference/cli/lifecycle.md index 8a538c6fca9..fad71c45a54 100644 --- a/docs-site/src/content/docs/reference/cli/lifecycle.md +++ b/docs-site/src/content/docs/reference/cli/lifecycle.md @@ -61,7 +61,11 @@ Grok and Claude stay pointed at the proxy that was already running. With a separ `OPENCODEX_HOME`, startup checks the default home's runtime record and managed Grok and Codex loopback destinations for a live opencodex owner before syncing. A custom home with no live owner still syncs normally; explicit `ocx sync` and `ocx grok apply` remain available. -Stopping that sibling with `ocx stop` or a signal leaves their configuration alone as well. While it runs, the proxy also +Stopping that sibling with `ocx stop` or a signal leaves their configuration alone as well. +If the sibling serves a saved Remote Link, `ocx stop` verifies the running instance and its +Link ownership and stops only that process. Unverified Link ownership or conflicting service +manager approval leaves the process running and reports an ownership refusal. +While it runs, the proxy also keeps Codex pointed at itself: when the opencodex routing in `~/.codex/config.toml` names another local port where no opencodex has answered for about 20 seconds (an instance that re-pointed it and then died, for example), the proxy re-points Codex at its own port and prints one warning. Codex @@ -82,11 +86,33 @@ ocx start --socks5-off ### `ocx stop [--json] [--deadline-ms ]` -An unsupervised Link Child handling a shutdown signal restores native Codex and managed Grok before releasing its listener, rechecking the served connection before each write. Service/Desktop supervision, sibling ownership, restart/recycle handoff and pending parent stop receipts preserve integrations. Shutdown rejects bound restart with `409 runtime_stopping`. Forced termination can bypass signal handlers; parent `ocx stop` restoration remains necessary. To route Codex through Home again after such a stop, start the Child (`ocx start`, or `ocx service start` for an installed service) and then run `ocx sync --restart-codex`. Starting alone does not reapply routing. A sync run while the Child is stopped still reapplies routing, which points Codex at a listener that is not running, so start the Child first. +An unsupervised Link Child handling a shutdown signal removes file integrations created by the Link, then restores native Codex and managed Grok before releasing its listener, rechecking the served connection before each write. Pre-existing standalone file integrations and user edits are preserved. During that unsupervised signal cleanup, if file cleanup or native Codex/Grok restoration is refused, including unverified ownership, the listener stays bound with synchronization paused; repair the reported configuration or ownership evidence and retry `ocx stop`. To leave Home after a refused stop, `ocx disconnect --recover-config --yes` completes configuration recovery and restarts the retained Child as standalone OpenCodex. A stop or recovery still in progress continues to refuse restart. Service/Desktop supervision, sibling ownership and restart/recycle handoff preserve integrations. The Child defers native Codex and Grok restoration only when a verified running parent stop owns the matching receipt. File cleanup and its synchronization fence still run before the listener is released. A stale or unreadable receipt alone keeps the listener bound and the recovery evidence intact. Shutdown rejects bound restart with `409 runtime_stopping`. + +An explicit `ocx stop` verifies that the running Child still serves the saved Link connection and supports the stop fence, then removes Link-created file integrations before stopping the process or service. If the saved connection is invalid, has changed owners, or file cleanup is refused, the command stops before terminating anything. Repair the saved connection or the reported ownership evidence and retry. The command also refuses before termination if an older recovery record would prevent native restoration; repair the reported evidence and retry. Native Codex/Grok restoration is then attempted by the stopping command after the Child exits. A refusal at that stage reports incomplete restoration and preserves recovery evidence; the listener is already stopped. Forced termination can bypass signal handlers; parent `ocx stop` restoration remains necessary. To route Codex through Home again after such a stop, start the Child (`ocx start`, or `ocx service start` for an installed service) and then run `ocx sync --restart-codex`. Starting alone does not reapply routing. With Home available, sync also reapplies its enabled file integrations. A sync run while the Child is stopped still reapplies routing, which points Codex at a listener that is not running, so start the Child first. + +The stopping command must record its recovery receipt before asking a service manager or process to stop. Linux requires kernel pidfd support for direct termination. On macOS, the direct path sends a single SIGTERM. If the direct stop fails, check the Child’s terminal or supervisor for the reason, repair the reported evidence, and retry `ocx stop`. + +If a Remote Link Child is still running an older version without the stop fence, such as v2.100.4, the current CLI refuses to stop it. To keep the saved Home connection: + +1. Close Codex, Grok and other clients routed through the Child before releasing its port. +2. Stop the old runtime using its original owner. Press Ctrl+C in its foreground terminal, use Stop and quit its Desktop supervisor, or run `ocx stop` from the **old installation** for a background service, including Windows Task Scheduler. +3. With the old runtime down, run `ocx stop` from the **current installation**, using the same `OPENCODEX_HOME` and client homes. This completes file-route cleanup and keeps the saved connection. Keep clients closed and resolve any restoration errors before continuing. On Linux this also works without a reachable systemd user manager when the installer unit and service installation records are absent and the known local endpoints are down. +4. Start the current runtime with `ocx start`, `ocx service start` for an installed service, or the updated Desktop app for a Desktop-managed runtime. Run `ocx sync --restart-codex` once the Child is serving. Stop the running proxy (by PID), remove the PID file, and restore native Codex for standalone owners. If a managed background service is installed, `ocx stop` also stops it first so it cannot respawn the proxy. -On a connected hub client, `ocx stop` leaves Codex routing, its +If the listener cannot prove its role, a standalone runtime record can still authorize the ordinary stop +when its recorded process creation identity matches the live PID and there is no Link evidence. +An older record without a creation identity requires a same-user OpenCodex start process that owns +the recorded listener. A wildcard record requires a wildcard listener, and an IPv4 loopback record +requires an exact loopback listener. On Linux and macOS, the process home and the caller's home +must resolve to the same directory, including through symlinks. Windows uses the +owner SID, start arguments, and exact listener ownership because CIM does not expose the process environment. +The CLI leaves the process running if it cannot establish that match or verify a supervisor. +If a live tracked PID could still be a Link Child, `ocx stop` leaves it running until it can verify +its role or tie the PID to a matching service registration. Run `ocx service status` to identify +its supervisor, or check the foreground terminal. Repair the runtime or saved Link records and retry. +A native client that cannot prove whether it serves a Link or Hub connection refuses to stop. Update and restart older native clients through their supervisor, then retry. On a connected hub client, `ocx stop` leaves Codex routing, its model catalog and the Grok config as they are, including after a successful API stop: the connection owns them, and `ocx start` serves them again without re-injecting routing. Use `ocx disconnect` to hand Codex back to its own account. If Codex on a connected client already reads native routing, `ocx status` names `ocx sync --restart-codex` to point it back. @@ -105,7 +131,9 @@ read. Older or unverified runtimes are refused before stop actions. Update/restart that runtime through its supervisor and retry; use `ocx disconnect` only when you intend to release the connection-owned integrations. Repeated stops of an already-stopped client confirm service-manager inactivity and absence at the -known local endpoints before returning the normal not-running result. +known local endpoints before returning the normal not-running result. With configured port `0`, +the recorded runtime port supplies the endpoint; without a concrete recorded endpoint, the stop +refuses because runtime absence cannot be proved. While the OpenCodex desktop app is running, `ocx stop` does not keep the proxy down: the app treats it as an unexpected exit and starts a proxy again, within seconds for one it started and after about a minute for one it had only attached to. Use the app's tray **Stop proxy** (for a proxy the app @@ -163,9 +191,11 @@ eligible for termination, stop it from its owning Windows session using Task Man If OpenCodex cannot confirm a wrapper's exit without a process handle, as can happen on ARM64, check it in Task Manager from its owning session, stop it if it is still running, and retry. -When the service cannot be proven stopped, `ocx stop` sends no stop request to the proxy, leaves -your client configuration alone, and fails. With `--json` the summary keeps `outcome: "failed"` -and `proxy: "unknown"`, and adds `serviceStopReason`: +When the service cannot be proven stopped, `ocx stop` sends no stop request to the proxy and +does not proceed to shared native restoration. On a Remote Link Child, preflight may already have +removed Link-owned file integrations and paused sync; repair the service stop and retry `ocx stop`. +The command fails. With `--json` the summary keeps `outcome: "failed"` and `proxy: "unknown"`, +and adds `serviceStopReason`: | `serviceStopReason` | Meaning | What to do | |---|---|---| diff --git a/scripts/test-layout/layout-clients.json b/scripts/test-layout/layout-clients.json index 05408aa0d37..53da2c38856 100644 --- a/scripts/test-layout/layout-clients.json +++ b/scripts/test-layout/layout-clients.json @@ -172,6 +172,10 @@ "client-link-relay.test.ts": "clients", "client-link-runtime.test.ts": "clients", "client-link-stop.test.ts": "clients", + "client-link-stop-recovery.test.ts": "clients", + "client-recycle-exclusion.test.ts": "clients", + "client-restart-rollback-lock.test.ts": "clients", + "client-link-stop-sibling.test.ts": "clients", "link-routes.test.ts": "clients", "client-link-state.test.ts": "clients", "client-link-status.test.ts": "clients", diff --git a/scripts/test-layout/layout.json b/scripts/test-layout/layout.json index db2dcc98531..cf3a96f32a8 100644 --- a/scripts/test-layout/layout.json +++ b/scripts/test-layout/layout.json @@ -1933,7 +1933,7 @@ "windows-elevation-spawn.test.ts": "windows", "windows-elevation.test.ts": "windows", "windows-guarded-manager.test.ts": "windows", "windows-checked-stop.test.ts": "windows", "windows-stop-binding.test.ts": "windows", "windows-checked-stop-live.test.ts": "windows", "windows-service-stop-wiring.test.ts": "windows", - "windows-popup-fix.test.ts": "windows", "windows-stop-confirm.test.ts": "windows", "windows-process-evidence.test.ts": "windows", "windows-stop-callers.test.ts": "windows", "windows-stop-ocx-stop.test.ts": "windows", + "windows-popup-fix.test.ts": "windows", "windows-stop-confirm.test.ts": "windows", "windows-process-evidence.test.ts": "windows", "windows-stop-owner-identity.test.ts": "windows", "windows-stop-callers.test.ts": "windows", "windows-stop-ocx-stop.test.ts": "windows", "windows-process-priority.test.ts": "windows", "windows-scheduler-errors.test.ts": "windows", "windows-scheduler-install-verification.test.ts": "windows", "windows-lifecycle-root-acl.test.ts": "windows", diff --git a/src/cli/index.ts b/src/cli/index.ts index 38bd9e803a6..d2e43dc48c0 100755 --- a/src/cli/index.ts +++ b/src/cli/index.ts @@ -166,7 +166,7 @@ import { uninstallPrivilegeRefusal } from "../lib/config-ownership"; import { withProcessRuntimeProvenance } from "../lib/bun-runtime"; import { startArgv } from "../lib/self-launch-argv"; import { initializeNodeLauncherContext } from "./launcher-context"; -import { assertConnectedClientStopSupported, clearRestoredStopReceipts, connectedClientStopSkipLine, notOwnedTeardownIsAcceptable, preflightConnectedClientStop, preserveConnectedClientRoutingOnExit, restoreBoundaryOwnership, restoreSharedClientStateAfterStop, settleUnrestoredStopBoundary } from "./stop-restore"; +import { abandonedTeardownIsSafeToFinish, assertConnectedClientStopSupported, classifyStopRole, clearRestoredStopReceipts, configuredStopEndpoint, connectedClientStopSkipLine, isRegisteredServiceStopTarget, notOwnedTeardownIsAcceptable, preflightConnectedClientStop, preserveConnectedClientRoutingOnExit, proveStandaloneStopRecord, restoreBoundaryOwnership, restoreSharedClientStateAfterStop, settleUnrestoredStopBoundary, stopOwnershipRefused, unclassifiedStopTarget, unsupportedConnectedStop, verifyConnectedStopTarget, type LinkStopPreflight, type StopTargetProof } from "./stop-restore"; import { stopRestoreWriteGuard } from "./stop-restore-guard"; import { startClientRuntimeUnderOwnershipLease } from "./client-start-fence"; import { recoverStartJournalAfterOwnerRecheck, recoverStartStateUnderOwnershipLease } from "./start-owner-fence"; @@ -511,6 +511,7 @@ async function handleStart(options: { block?: boolean } = {}) { // live daemon holding resources while it overwrites its own binary. Never from a // sibling: replacing the global package makes the live proxy drain and restart. if (!siblingStart) await maybeShowUpdatePrompt(); + const { readClientStopProcessStart } = await import("../client/stop-teardown-owner"); type StartServerModule = typeof import("../server"); type BoundStart = { @@ -610,6 +611,7 @@ async function handleStart(options: { block?: boolean } = {}) { port: bound.port, hostname: bound.server.hostname, attestationSecret: bound.localAttestationSecret, + startTime: readClientStopProcessStart(process.pid), command: currentServingCommand(), ...siblingRuntimeField(), }); updateRestartChild?.complete(); }, @@ -1013,8 +1015,10 @@ async function handleRestartStartWhenStopped(recoveringLiveRestart = false): Pro } async function handleStop(approval?: StopApproval) { const lease = acquireOwnershipMutationLease(serviceStatePaths()); + let finishConnectedStop: (() => Promise) | undefined; + const stop = (snapshot?: GuardedStopSnapshot) => handleStopUnlocked(snapshot, finish => { finishConnectedStop = finish; }); try { - if (!approval) return await handleStopUnlocked(); + if (!approval) return await stop(); return await runApprovedStop( approval, async () => { @@ -1029,50 +1033,18 @@ async function handleStop(approval?: StopApproval) { }, describeTrackedRuntimeTarget, () => inspectGuardedTarget(approval.pid, approval.port), - snapshot => handleStopUnlocked(snapshot), + stop, ); } - finally { lease.release(); } + finally { try { await finishConnectedStop?.(); } finally { lease.release(); } } } -async function handleStopUnlocked(snapshot?: GuardedStopSnapshot) { +async function handleStopUnlocked(snapshot: GuardedStopSnapshot | undefined, onFence: (finish: () => Promise) => void) { // The receipt must name the endpoint the owner was stopping — an obligation nobody can // locate cannot be proven discharged. Only the runtime record knows it; a proxy started // with an explicit --port is not on the configured one. const endpointOf = (runtime: { port: number; hostname?: string } | null): { hostname: string; port: number } | null => runtime?.port ? { hostname: runtime.hostname ?? "127.0.0.1", port: runtime.port } : null; - // Last-resort endpoint for a receipt: the address this home is configured to serve on, - // which is what a later recovery probe would ask about anyway. - const configuredEndpoint = (): { hostname: string; port: number } => { - try { - const config = loadConfig(); - return { - hostname: config.hostname ?? "127.0.0.1", - port: typeof config.port === "number" && config.port > 0 ? config.port : 10100, - }; - } catch { - return { hostname: "127.0.0.1", port: 10100 }; - } - }; - // Only a definitive "nothing is answering" authorizes finishing somebody else's - // abandoned teardown. The tri-state probe distinguishes that from "we could not tell" - // (timeout, a listener that withholds /healthz), which `findLiveProxy` collapses into - // the same null (#3008). - const abandonedTeardownIsSafeToFinish = async ( - endpoint: { hostname: string; port: number } | null, - ): Promise => { - // The endpoint has to come from the receipt. A crashed owner usually leaves no - // runtime-port record, and the configured port is the wrong question for a proxy - // started with an explicit --port: it refuses while the live one keeps serving. - // An obligation that cannot name its endpoint cannot be proven discharged. - if (!endpoint) return false; - try { - return await probeEndpointLiveness(endpoint) === "dead"; - } catch { - // A probe that could not run is not evidence of absence. - return false; - } - }; let stopFailed = false; let historyOnlyFailure = false; /** @@ -1094,25 +1066,14 @@ async function handleStopUnlocked(snapshot?: GuardedStopSnapshot) { // A sibling instance's shared teardown is not this stop's to run: the client routing belongs // to the live proxy it ran beside (`src/codex/sibling-start.ts`). Read before any stop removes // the record; a record left behind by a hard-killed sibling still says so. - const siblingOfPort = readRuntimePort()?.siblingOfPort; + const initialRuntime = readRuntimePort(); + const siblingOfPort = initialRuntime?.siblingOfPort; const stoppingSibling = siblingOfPort !== undefined; - const connectedClientSkip = stoppingSibling ? null : connectedClientStopSkipLine(readClientConnectionState()); - let connectedClientAlreadyStopped = false; - if (connectedClientSkip) { - const preflight = await preflightConnectedClientStop(snapshot?.approval); - if (preflight === "already-stopped") connectedClientAlreadyStopped = true; - else if (preflight) return preflight; + if (stoppingSibling && snapshot && snapshot.manager.kind !== "absent") { + return approvalChanged("the sibling runtime record conflicts with the approved service manager"); } - // Structured twin of the human lines below, for `ocx stop --json`: one document the - // desktop shell can read across the process boundary (D4). Every field is assigned - // where the corresponding boolean already flips — the summarizer never re-decides. - const record: StopRunRecord = { - service: "absent", - proxy: "unknown", - sharedTeardown: "skipped", - inheritedTeardownBlocks: false, - receiptClearFailed: false, - }; + const connectedClientState = readClientConnectionState(); + let connectedClientSkip = stoppingSibling ? null : connectedClientStopSkipLine(connectedClientState); // Deferring shared teardown to this process is an obligation, so record it on disk // before asking for it (#3008). A parent that dies mid-stop would otherwise leave the // client config routed at a proxy that is already gone, with nothing to find later. @@ -1136,34 +1097,78 @@ async function handleStopUnlocked(snapshot?: GuardedStopSnapshot) { // anything is restored. const teardownOwnerStillRunning = (ownerPid: number): boolean => isProcessAlive(ownerPid) && isLikelyOcxProcess(ownerPid); - const inheritedTeardowns = listPendingTeardowns() - .filter(read => isPendingTeardownAbandoned(read, teardownOwnerStillRunning)); + const savedLink = connectedClientState.kind === "connected" && connectedClientState.value.transport === "link"; + const pendingTeardowns = savedLink ? [] : listPendingTeardowns(); + const inheritedTeardownSnapshot = savedLink + ? (await import("../client/stop-native-handoff")).readLinkInheritedTeardowns() + : pendingTeardowns.filter(read => isPendingTeardownAbandoned(read, teardownOwnerStillRunning)); + let linkStop: LinkStopPreflight | undefined; + let stopTarget: StopTargetProof | undefined; + const stopRole = await classifyStopRole(connectedClientState, initialRuntime, pendingTeardowns); + const connectedStop = stopRole === "connected"; + const trackedStopPid = connectedStop ? null : snapshot?.approval.pid ?? readPid(); + const verifyStandaloneRecord = stopRole === "unknown" && connectedClientState.kind === "disconnected" && trackedStopPid !== null + ? await proveStandaloneStopRecord(initialRuntime, trackedStopPid, pendingTeardowns) : undefined; + if (trackedStopPid !== null) { + const standaloneRuntime = (stopRole === "standalone" || stoppingSibling || verifyStandaloneRecord) && initialRuntime?.pid === trackedStopPid + && Bun.deepEquals(readRuntimePort(trackedStopPid), initialRuntime, true); + if (!standaloneRuntime && !(connectedClientState.kind === "disconnected" && isRegisteredServiceStopTarget(trackedStopPid))) { + return stopOwnershipRefused(unclassifiedStopTarget(trackedStopPid)); + } + } + const preflight = connectedStop ? await preflightConnectedClientStop(snapshot?.approval, onFence, inheritedTeardownSnapshot, + proof => { linkStop = proof; connectedClientSkip = null; }, proof => { stopTarget = proof; }, siblingOfPort) : null; + const connectedClientAlreadyStopped = preflight === "already-stopped"; + if (preflight && preflight !== "already-stopped") return preflight; + const inheritedTeardowns = stopTarget?.terminateSibling ? [] : inheritedTeardownSnapshot; + // Structured twin of the human lines below, for `ocx stop --json`: one document the + // desktop shell can read across the process boundary (D4). Every field is assigned + // where the corresponding boolean already flips — the summarizer never re-decides. + const record: StopRunRecord = { + service: "absent", + proxy: "unknown", + sharedTeardown: "skipped", + inheritedTeardownBlocks: false, + receiptClearFailed: false, + }; let teardownNonce: string | undefined; // #7423: an update that restarts the proxy asks this stop to leave Codex routing for the replacement. // Client start never discharges a standalone update-handover receipt or reapplies routing. const handoverRequested = updateTeardownHandoverRequested(process.env, () => shouldSyncCodexOnStart(loadConfig())) && !stoppingSibling && readClientConnectionState().kind !== "connected"; let deferralHonoredByProxy = false; + const verifyStopTarget = (pid?: number) => { + if (connectedStop) return verifyConnectedStopTarget(stopTarget, linkStop, pid); + const current = readClientConnectionState(); + if (!stoppingSibling && current.kind === "connected" && current.value.transport === "link") throw unsupportedConnectedStop(); + const trackedPid = readPid(); + if (trackedPid !== null && trackedPid !== trackedStopPid) throw unclassifiedStopTarget(trackedPid); + verifyStandaloneRecord?.(); + }; const claimTeardown = (endpoint: { hostname: string; port: number }, endpointSource: "exact" | "guessed") => { - if (teardownNonce || stoppingSibling) return; - if (connectedClientSkip) return; + if (teardownNonce || stoppingSibling || (!linkStop && connectedClientSkip)) return; try { - teardownNonce = claimPendingTeardown(endpoint, endpointSource, process.pid, handoverRequested ? "update-restart" : undefined, windowsPartAReceiptRecord()).nonce; + teardownNonce = claimPendingTeardown(endpoint, endpointSource, process.pid, handoverRequested ? "update-restart" : undefined, windowsPartAReceiptRecord(), linkStop?.owner, linkStop?.inheritedTeardownDigest).nonce; } catch (err) { - // Windows wrappers can relaunch the proxy, so an undeferred stop is unsafe. + // A Link Child can exit before native restoration. Record that obligation first. + if (linkStop) throw new ProxyOwnershipRefusedError(`Link Child stop refused: could not record the deferred-teardown receipt (${err instanceof Error ? err.message : String(err)}). Repair the OpenCodex home's storage and retry ocx stop.`, "link_teardown_receipt_failed"); if (windowsStopRequiresReceipt()) { ownershipBlocked = true; stopFailed = true; throw err; } console.warn(`⚠️ Could not record the deferred-teardown receipt: ${err instanceof Error ? err.message : String(err)}`); } }; - // Resolve one target for receipt and request. Only a discovered endpoint may direct POST; - // a configured guess records an obligation but is never evidence for orphan recovery. - // Claim before any kill fallback so a parent crash leaves a durable teardown obligation. + // Use one endpoint for the receipt and POST. A connected stop needs its own proved target. const stopWithDeferral = async (pid: number, discovered?: { hostname: string; port: number } | null): Promise => { - // Resolve ONCE. Reading the runtime record twice let the receipt name the configured - // guess while the request went to a runtime endpoint that appeared in between. - const exact = discovered ?? endpointOf(readRuntimePort(pid)); + verifyStopTarget(pid); + if (stopTarget?.terminateSibling) { + stopTarget.terminateSibling(); + return false; + } + const verifiedLink = linkStop; + const exact = connectedStop ? endpointOf(stopTarget?.target ?? null) : discovered ?? endpointOf(readRuntimePort(pid)); + if (connectedStop && !exact) throw unsupportedConnectedStop(); if (connectedClientSkip) await assertConnectedClientStopSupported(exact ? { ...exact, pid } : null); - claimTeardown(exact ?? configuredEndpoint(), exact ? "exact" : "guessed"); + claimTeardown(exact ?? configuredStopEndpoint(), exact ? "exact" : "guessed"); + verifyStopTarget(pid); const graceful = await stopProxy(pid, { deferSharedTeardownNonce: teardownNonce, // "not-owned" is refused only for a positively identified Link connection, read at the @@ -1171,11 +1176,9 @@ async function handleStopUnlocked(snapshot?: GuardedStopSnapshot) { // restore. A connect committed mid-stop can make this a hub client whose answer is // truthful, so the entry-time skip snapshot cannot stand in for this check. acceptNotOwnedTeardown: notOwnedTeardownIsAcceptable(readClientConnectionState(), stoppingSibling), - // Only an exact endpoint may direct the request; the configured fallback is a guess - // good enough to record an obligation against, not to POST a stop to. Never re-read the - // record here: one published since would send the receipt to a port it does not name. runtimeEndpoint: exact ?? undefined, runtimeEndpointOnly: true, + ...(verifiedLink ? { forceKill: verifiedLink.forceKill } : { mayTerminate: () => { verifyStopTarget(pid); return true; } }), skipPortWait: windowsPartBOwnsPortWait(), // #7771: Part B owns the Windows port wait on both paths. }); // A valid receipt means the proxy deferred shared teardown to this process. If the @@ -1189,13 +1192,18 @@ async function handleStopUnlocked(snapshot?: GuardedStopSnapshot) { ? { hostname: probeHostname(snapshot.approval.hostname || undefined), port: snapshot.approval.port } : null; // Only an exact runtime endpoint may back a handover; without one the ordinary restore runs. - const claimHandoverBeforeManager = () => { const exact = handoverRequested ? endpointOf(readRuntimePort()) : null; if (exact) claimTeardown(exact, "exact"); }; + const claimHandoverBeforeManager = () => { + if (!handoverRequested) return; + const exact = endpointOf(connectedStop ? stopTarget?.target ?? null : readRuntimePort()); + if (exact) claimTeardown(exact, "exact"); + }; let guardedStep: Awaited> | null = null; try { const serviceStop = snapshot ? (guardedStep = await runGuardedManagerStep(snapshot, { revalidateManager: () => inspectGuardedTarget(snapshot.approval.pid, snapshot.approval.port), stopManager: () => { + verifyStopTarget(); if (approvedEndpoint) claimTeardown(approvedEndpoint, "exact"); return stopGuardedManager({ approvedPort: snapshot.approval.port, receiptNonce: () => teardownNonce, inheritedReceipts: inheritedTeardowns.length }); }, @@ -1207,7 +1215,13 @@ async function handleStopUnlocked(snapshot?: GuardedStopSnapshot) { // A sibling never runs under a service manager: an installed one belongs to the live owner, // and its ownership check would fail this stop and skip the stale-record purge below. // #7423: a manager stop takes the proxy down itself, so a handover claims its receipt first. - : stoppingSibling || connectedClientAlreadyStopped ? noServiceStop() : (claimHandoverBeforeManager(), await stopServiceForOcxStop({ receiptNonce: () => teardownNonce, inheritedReceipts: inheritedTeardowns.length })); + : stoppingSibling || connectedClientAlreadyStopped ? noServiceStop() : await (async () => { + verifyStopTarget(); + const linkEndpoint = linkStop && endpointOf(linkStop.target); + if (linkEndpoint) claimTeardown(linkEndpoint, "exact"); + else claimHandoverBeforeManager(); + return stopServiceForOcxStop({ receiptNonce: () => teardownNonce, inheritedReceipts: inheritedTeardowns.length }); + })(); record.service = serviceStop; stoppedService = serviceStop === "stopped" || serviceStop === "stopped-respawnable"; schedulerCanRespawn = serviceStop === "stopped-respawnable" || windowsPartBDue(); @@ -1231,11 +1245,13 @@ async function handleStopUnlocked(snapshot?: GuardedStopSnapshot) { ownershipBlocked = windowsPartAHolds(record) || ownershipBlocked; // #7771: no POST and no shared teardown. } catch (err) { record.service = "error"; - if (isServiceOwnershipError(err) || windowsChildStopHeld()) { + if (err instanceof ProxyOwnershipRefusedError || isServiceOwnershipError(err) || windowsChildStopHeld()) { ownershipBlocked = true; stopFailed = true; console.error(`❌ ${err instanceof Error ? err.message : String(err)}`); - console.error(" Skipping shared teardown (native Codex restore, Grok config): the installed service is still running."); + console.error(err instanceof ProxyOwnershipRefusedError + ? " Skipping shared teardown (native Codex restore, Grok config) because the stop could not be verified." + : " Skipping shared teardown (native Codex restore, Grok config): the installed service is still running."); } else { console.error(`⚠️ Service manager stop failed: ${err instanceof Error ? err.message : String(err)}`); } @@ -1259,16 +1275,13 @@ async function handleStopUnlocked(snapshot?: GuardedStopSnapshot) { record.proxy = "unknown"; console.error("The approved runtime could not be verified after the guarded stop step."); } - } else if (windowsChildStopHeld()) { /* #7771: Part A did not prove the manager stopped, so no POST. */ } else { - const pid = readPid(); + } else if (windowsChildStopHeld() || (connectedStop && ownershipBlocked)) { /* No process stop after the connected manager gate refused. */ } else { + const attestedPid = linkStop?.target.pid ?? (stopTarget?.terminateSibling ? stopTarget.target.pid : undefined); + const pid = readPid() ?? (attestedPid !== undefined && isProcessAlive(attestedPid) ? attestedPid : null); if (pid) { try { - // Graceful-first (management-API drain) — on Windows this is the only path where - // the proxy's shutdown handlers actually run; taskkill /F is the fallback inside. - // Shared teardown is deferred to this process: it happens after the respawn - // verification below, so a survivor does not get its client config pulled first. - // The receipt goes down first; Windows refuses if it cannot be recorded. - // Other platforms retain the existing undeferred fallback. + // The management API can drain before exit. A deferral receipt leaves shared teardown + // with this process until after respawn verification. nativeRestoreHandledByProxy = await stopWithDeferral(pid); console.log(`✅ Proxy (PID ${pid}) stopped.`); removePid(pid); @@ -1312,12 +1325,7 @@ async function handleStopUnlocked(snapshot?: GuardedStopSnapshot) { console.error(" Skipping shared teardown (native Codex restore, Grok config) while that proxy is running."); } else if (live?.pid) { try { - // The probe already found where it answers, and on this path the runtime record is - // typically what went missing in the first place. - nativeRestoreHandledByProxy = await stopWithDeferral( - live.pid, - { hostname: live.hostname ?? "127.0.0.1", port: live.port }, - ); + nativeRestoreHandledByProxy = await stopWithDeferral(live.pid, { hostname: live.hostname ?? "127.0.0.1", port: live.port }); console.log(`✅ Proxy (PID ${live.pid}) stopped.`); record.proxy = "stopped-orphan"; } catch (err) { diff --git a/src/cli/stop-client-process.ts b/src/cli/stop-client-process.ts new file mode 100644 index 00000000000..33f57c2f95b --- /dev/null +++ b/src/cli/stop-client-process.ts @@ -0,0 +1,51 @@ +import { isProcessAlive, ProxyOwnershipRefusedError, waitForExit } from "../lib/process-control"; +import { openVerifiedPidfd } from "../service/health-sentinel-linux"; +import { windowsProcessNative } from "../service/windows-process-native"; +import { unsupportedConnectedStop } from "./stop-restore"; + +/** Terminate the attested Child only, including at the escalation and port-reclaim boundaries. */ +export function terminateAttestedClient(pid: number, start: string, verify: (phase?: "after-term") => void): void { + if (!isProcessAlive(pid)) return; + verify(); + if (process.platform === "linux") { + const target = openVerifiedPidfd(pid, () => { verify(); return true; }); + if (target.kind !== "bound") { + throw new ProxyOwnershipRefusedError( + `Link Child forced stop refused: could not bind a Linux pidfd (${target.reason}). Use a kernel and environment that permit pidfd operations, or stop a managed Child through its supervisor. Then retry ocx stop to complete restoration.`, + "connected_client_stop_unsupported", + ); + } + const { handle } = target; + try { + for (const signal of [15, 9] as const) { + if (!isProcessAlive(pid)) return; + verify(signal === 9 ? "after-term" : undefined); + const result = handle.terminate(signal); + if (result === "not_target") return; + if (result !== "terminated") throw unsupportedConnectedStop(); + if (waitForExit(pid, 5000)) return; + } + throw new Error(`process ${pid} did not exit`); + } finally { handle.close(); } + } + if (process.platform === "win32") { + const ticks = /^win32:(\d{1,20})$/.exec(start)?.[1]; + const native = windowsProcessNative(); + if (!ticks || !native) throw unsupportedConnectedStop(); + const result = native.terminate(pid, BigInt(ticks)); + if (result.status === "gone") return; + if (result.status !== "terminated") throw unsupportedConnectedStop(); + if (!waitForExit(pid, 5000)) throw new Error(`process ${pid} did not exit`); + return; + } + if (process.platform !== "darwin") throw unsupportedConnectedStop(); + // The native macOS Child has no authenticated shutdown endpoint. Keep its + // orderly signal path, with no numeric-PID escalation after the wait. + process.kill(pid, "SIGTERM"); + if (waitForExit(pid, 5000)) return; + verify("after-term"); + throw new ProxyOwnershipRefusedError( + "Link Child did not exit after SIGTERM. Inspect its foreground terminal for the shutdown refusal or check its supervisor, repair the reported evidence, then retry ocx stop.", + "connected_client_stop_unsupported", + ); +} diff --git a/src/cli/stop-restore.ts b/src/cli/stop-restore.ts index 313b87a30b1..c7520ce3021 100644 --- a/src/cli/stop-restore.ts +++ b/src/cli/stop-restore.ts @@ -1,23 +1,31 @@ +import { lstatSync, statSync } from "node:fs"; +import { randomBytes } from "node:crypto"; import { restoreNativeCodexAsync } from "../codex/inject"; import type { RetainedCodexProviderTable } from "../codex/inject/restore"; import { stripGrokConfig } from "../grok/inject"; -import { readClientConnectionState, type ClientConnectionState } from "../client/state"; +import { linkStopConnectionOwner, readClientConnectionState, type ClientConnectionState } from "../client/state"; import { withClientLifecycleSync } from "../client/lifecycle-lock"; -import type { RestoreBoundaryOwnership } from "../client/restore-ownership"; +import { StopRestoreOwnershipError, type RestoreBoundaryOwnership } from "../client/restore-ownership"; export type { RestoreBoundaryOwnership } from "../client/restore-ownership"; import { inspectStopRestoreOwnership, stopRestoreWriteGuard } from "./stop-restore-guard"; export { clearRestoredStopReceipts, settleUnrestoredStopBoundary } from "./stop-restore-guard"; -import { readPid, readRuntimePort } from "../config/process-state"; +import { isOcxStartCommandLine, readAlivePid, readPid, readProcessCommandLine, readRuntimePort, type ClientStopOwner, type RuntimePortState } from "../config/process-state"; +import { getConfigDir } from "../config/paths"; +import type { OutstandingTeardown } from "../config/pending-teardown"; +import type { LinkInheritedTeardown } from "../client/stop-native-handoff"; import { loadConfig } from "../config"; import { readBoundedResponseBody } from "../lib/bounded-body"; +import { sameFileIdentity, type FileIdentity } from "../lib/file-identity"; import { createLocalAttestationChallenge, LOCAL_ATTESTATION_CHALLENGE_HEADER, LOCAL_ATTESTATION_PROOF_HEADER, verifyLocalAttestationProof } from "../lib/local-management-attestation"; import { LOCAL_MANAGEMENT_READ_PATHS } from "../lib/local-management-capability"; import { gracefulStopHost, isProcessAlive, ProxyOwnershipRefusedError, stopRequestFetch as directStopRequestFetch } from "../lib/process-control"; import { directLocalHttpFetch } from "../server/direct-local-http"; import { fetchBoundLocalManagementRead } from "../server/local-management-read-client"; import { isSharedTeardownDeferredOnExit } from "../server/stop-teardown"; -import { findLiveProxy, probeEndpointLiveness, proveLiveProxyOwnedByHome } from "../server/proxy-liveness"; -import { observeGuardedManagerStopped } from "../service/guarded-manager-target"; +import { findLiveProxy, isPackageTreeFencedHealthz, probeEndpointLiveness } from "../server/proxy-liveness"; +import { inspectGuardedManagerTarget, observeGuardedManagerStopped } from "../service/guarded-manager-target"; +import { assertServiceEnvironmentMatchesInstall } from "../service/guards"; +import { installedServiceListenPort } from "../service/health"; import type { StartExitTeardown } from "./dispatch"; import type { StopOutcome } from "./stop-report"; @@ -33,16 +41,188 @@ export function preserveConnectedClientRoutingOnExit(teardown: StartExitTeardown } type ConnectedStopTarget = { pid: number; port: number; hostname?: string }; +export type StopTargetProof = { target: ConnectedStopTarget; verify: () => void; siblingOnly?: true; terminateSibling?: () => void }; +export type LinkStopPreflight = StopTargetProof & { owner: ClientStopOwner; inheritedTeardownDigest?: string; forceKill: (pid: number) => void }; + const CONNECTED_STOP_PROBE_MS = 2000; -const unsupportedConnectedStop = () => new ProxyOwnershipRefusedError( - "Connected-client stop refused: runtime identity, shutdown preservation or safe runtime absence could not be verified. Inspect 'ocx service status' and update/restart an incompatible runtime through its supervisor, then retry; use 'ocx disconnect' only if you intend to release those integrations.", +export const unsupportedConnectedStop = () => new ProxyOwnershipRefusedError( + "Connected-client stop refused: runtime identity, saved connection ownership, shutdown preservation or safe runtime absence could not be verified. No process was stopped by this check. Inspect 'ocx service status', repair saved connection ownership or update/restart an incompatible runtime through its supervisor, then retry. Use 'ocx disconnect' only if you intend to release those integrations.", "connected_client_stop_unsupported", ); +export function unclassifiedStopTarget(pid: number): ProxyOwnershipRefusedError { + return new ProxyOwnershipRefusedError( + `Stop refused: could not verify that live OpenCodex PID ${pid} is standalone. Run 'ocx service status' to identify its supervisor, or check the terminal that started it. Repair its runtime or saved Link records, then retry 'ocx stop'.`, + "connected_client_stop_unsupported", + ); +} + +export function stopOwnershipRefused(error: ProxyOwnershipRefusedError): StopOutcome { + console.error(error.message); + process.exitCode = 1; + return { ok: false, summary: { schema: "ocx-stop/1", ok: false, outcome: "failed", exitCode: 1, + runtimeDown: false, service: "absent", proxy: "ownership-refused", sharedTeardown: "skipped", message: error.message } }; +} + +export function isRegisteredServiceStopTarget(pid: number): boolean { + try { + assertServiceEnvironmentMatchesInstall(); + const manager = inspectGuardedManagerTarget(pid, installedServiceListenPort()); + return (manager.kind === "bound" || manager.kind === "bound-stray") && manager.pid === pid; + } catch { return false; } +} + +function legacyLinkStopRefusal(): ProxyOwnershipRefusedError { + return new ProxyOwnershipRefusedError( + "Connected-client stop refused: this older Link Child has no stop fence. No process was stopped. To update/restart while keeping the Home connection: close Codex, Grok and other routed clients. Stop the old owner: press Ctrl+C in its foreground terminal, use Stop and quit its Desktop supervisor, or run the old installation's 'ocx stop' for a background service (including Task Scheduler). Once it is down, run the current installation's 'ocx stop' with the same OPENCODEX_HOME and client homes to clean up file routes. Keep clients closed until cleanup succeeds. Then run 'ocx start' (or 'ocx service start' for an installed service, or open the updated Desktop app) and run 'ocx sync --restart-codex'.", + "connected_client_stop_unsupported", + ); +} + +export function verifyConnectedStopTarget( + proof: StopTargetProof | undefined, linkStop: LinkStopPreflight | undefined, pid?: number, +): void { + const state = readClientConnectionState(); + if (state.kind === "invalid" || state.kind === "mismatched") throw unsupportedConnectedStop(); + if (pid !== undefined && pid !== proof?.target.pid) throw unsupportedConnectedStop(); + if (state.kind === "connected" && state.value.transport === "link" && !linkStop && !proof?.siblingOnly) throw unsupportedConnectedStop(); + if (proof && isProcessAlive(proof.target.pid)) proof.verify(); + const currentPid = readAlivePid(); + if (currentPid !== null && currentPid !== proof?.target.pid) throw unsupportedConnectedStop(); +} + +function hasClientRuntimeEvidence(runtime: RuntimePortState): boolean { + return runtime.role === "client" || runtime.clientLinkOwner !== undefined || runtime.servingGeneration !== undefined + || runtime.clientStopping === true || runtime.clientStopOwner !== undefined; +} + +/** A discovery miss cannot establish the role of a live tracked process. */ +export async function classifyStopRole( + connection: ClientConnectionState, runtime: RuntimePortState | null, receipts: readonly OutstandingTeardown[], +): Promise<"connected" | "standalone" | "unknown"> { + const sibling = runtime?.siblingOfPort; + if (connection.kind === "connected" && (connection.value.transport === "link" || sibling === undefined)) return "connected"; + if (connection.kind === "mismatched" || receipts.some(read => read.state === "valid" && read.receipt.ownerStartTime !== undefined)) return "connected"; + const { readRouteIntentReceipt } = await import("../integrations/route-intent-state"); + if (readRouteIntentReceipt()?.linkId !== undefined) return "connected"; + if (runtime && isProcessAlive(runtime.pid)) { + if (hasClientRuntimeEvidence(runtime)) return "connected"; + if (runtime.attestationSecret) { + const capability = await assertConnectedClientStopSupported(runtime, { healthOnly: true }).catch(() => null); + if (capability) return capability.linkStopFence || capability.nativeClient ? "connected" : "standalone"; + } + } + // Classification needs only the reported role. The preflight must verify identity itself. + const live = await findLiveProxy({ attempts: 1, verifyPidFn: () => null }).catch(() => null); + return live?.role === "client" && live.port !== sibling ? "connected" : "unknown"; +} + +function readStopDirectoryIdentity(path: string | undefined): FileIdentity | undefined { + if (!path) return; + try { + const stat = statSync(path, { bigint: true }); + if (stat.isDirectory()) return stat; + } catch { /* An unreadable directory cannot establish identity. */ } +} + +/** Called after role discovery yields no affirmative result. Never adopts an orphan PID. */ +export async function proveStandaloneStopRecord( + runtime: RuntimePortState | null, pid: number, receipts: readonly OutstandingTeardown[], +): Promise<(() => void) | undefined> { + if (runtime?.pid !== pid || hasClientRuntimeEvidence(runtime) + || receipts.some(read => read.state !== "valid" || read.receipt.ownerStartTime !== undefined)) return; + const { readRouteIntentReceiptStrict } = await import("../integrations/route-intent-state"); + const hasNoLinkReceipt = () => { + try { return readRouteIntentReceiptStrict()?.linkId === undefined; } catch { return false; } + }; + if (!hasNoLinkReceipt()) return; + const { isLegacyWindowsStartCommandLine, readClientStopProcessStart, readLegacyStopProcessHome } = await import("../client/stop-teardown-owner"); + const start = readClientStopProcessStart(pid); + if (!start) return; + let legacyHomeIsCurrent: (() => boolean) | undefined; + if (runtime.startTime !== undefined) { + if (runtime.startTime !== start) return; + } else { + const command = readProcessCommandLine(pid); + if (!command) return; + const windows = process.platform === "win32"; + // CIM does not expose the environment. Windows uses the SID-checked creation + // identity above, exact start argv and ownership of the recorded bind instead. + if (windows) { + if (!isLegacyWindowsStartCommandLine(command)) return; + } else { + if (!isOcxStartCommandLine(command)) return; + const home = readStopDirectoryIdentity(getConfigDir()); + if (!home) return; + const matchesHome = (path: string | undefined) => { + const identity = readStopDirectoryIdentity(path); + return identity !== undefined && sameFileIdentity(identity, home); + }; + legacyHomeIsCurrent = () => matchesHome(readLegacyStopProcessHome(pid)) && matchesHome(getConfigDir()); + if (!legacyHomeIsCurrent()) return; + } + const { inspectIpv4LoopbackListener, ownsLegacyStopBind, scanListenPidsForAddress } = await import("../server/port-reclaim"); + const bind = runtime.hostname?.trim().replace(/^\[(.*)\]$/, "$1"); + const wildcard = bind === "0.0.0.0" || bind === "::"; + const address = windows || wildcard + ? (bind && bind.toLowerCase() !== "localhost" ? bind : "127.0.0.1") + : gracefulStopHost(runtime.hostname).replace(/^\[(.*)\]$/, "$1"); + if (windows || wildcard) { + if (!await ownsLegacyStopBind(runtime.port, pid, address)) return; + } else if (address === "127.0.0.1") { + if ((await inspectIpv4LoopbackListener(runtime.port, pid)).kind !== "match") return; + } else { + const listeners = scanListenPidsForAddress(runtime.port, address); + if (!listeners.ok || listeners.pids.length !== 1 || listeners.pids[0] !== pid) return; + } + if (readClientStopProcessStart(pid) !== start || legacyHomeIsCurrent?.() === false) return; + } + return () => { + if (readClientConnectionState().kind !== "disconnected" || !hasNoLinkReceipt()) throw unsupportedConnectedStop(); + if (isProcessAlive(pid) && (readClientStopProcessStart(pid) !== start + || !Bun.deepEquals(readRuntimePort(pid), runtime, true) || legacyHomeIsCurrent?.() === false)) throw unclassifiedStopTarget(pid); + }; +} + +// A guessed endpoint can name a standalone teardown obligation but cannot direct POST. +export function configuredStopEndpoint(): { hostname: string; port: number } { + try { + const config = loadConfig(); + return { + hostname: config.hostname ?? "127.0.0.1", + port: typeof config.port === "number" && config.port > 0 ? config.port : 10100, + }; + } catch { + return { hostname: "127.0.0.1", port: 10100 }; + } +} + +// Only a definitive "nothing is answering" authorizes finishing somebody else's +// abandoned teardown. The tri-state probe distinguishes that from "we could not tell" +// (timeout, a listener that withholds /healthz), which `findLiveProxy` collapses into +// the same null (#3008). +export async function abandonedTeardownIsSafeToFinish( + endpoint: { hostname: string; port: number } | null, +): Promise { + // The endpoint has to come from the receipt. A crashed owner usually leaves no + // runtime-port record, and the configured port is the wrong question for a proxy + // started with an explicit --port: it refuses while the live one keeps serving. + // An obligation that cannot name its endpoint cannot be proven discharged. + if (!endpoint) return false; + try { + return await probeEndpointLiveness(endpoint) === "dead"; + } catch { + // A probe that could not run is not evidence of absence. + return false; + } +} + /** Require the pinned runtime's proof before accepting its shutdown contract. */ -export async function assertConnectedClientStopSupported(target: ConnectedStopTarget | null): Promise { +export async function assertConnectedClientStopSupported( + target: ConnectedStopTarget | null, options: { requireLinkStopFence?: boolean; healthOnly?: boolean } = {}, +): Promise<{ linkStopFence: boolean; nativeClient: boolean } | null> { if (!target) throw unsupportedConnectedStop(); - if (!isProcessAlive(target.pid)) return; // A manager may already have ended this exact target. + if (!isProcessAlive(target.pid)) return null; // A manager may already have ended this exact target. const runtime = readRuntimePort(target.pid); if (!runtime?.attestationSecret || runtime.pid !== target.pid || runtime.port !== target.port || gracefulStopHost(runtime.hostname) !== gracefulStopHost(target.hostname)) throw unsupportedConnectedStop(); @@ -50,13 +230,13 @@ export async function assertConnectedClientStopSupported(target: ConnectedStopTa const readPinnedRuntime = () => { const current = readRuntimePort(target.pid); return current?.pid === runtime.pid && current.port === runtime.port && current.hostname === runtime.hostname - && current.attestationSecret === runtime.attestationSecret ? current : null; + && current.attestationSecret === runtime.attestationSecret && current.clientLinkOwner === runtime.clientLinkOwner ? current : null; }; const origin = `http://${endpoint.hostname}:${endpoint.port}`; const deadline = Date.now() + CONNECTED_STOP_PROBE_MS; const signal = AbortSignal.timeout(CONNECTED_STOP_PROBE_MS); - const readDocument = async (response: Response): Promise | null> => { - if (!response.ok) { void response.body?.cancel().catch(() => {}); return null; } + const readDocument = async (response: Response, allowFenced = false): Promise | null> => { + if (!response.ok && !(allowFenced && response.status === 503)) { void response.body?.cancel().catch(() => {}); return null; } const body = await readBoundedResponseBody(response, { maxBytes: 4096, signal, fatalUtf8: true }); if (body.truncated) return null; const parsed: unknown = JSON.parse(body.text); @@ -72,10 +252,15 @@ export async function assertConnectedClientStopSupported(target: ConnectedStopTa void response.body?.cancel().catch(() => {}); throw unsupportedConnectedStop(); } - const health = await readDocument(response); + const health = await readDocument(response, options.healthOnly); + if (!response.ok && (!health || !isPackageTreeFencedHealthz(health))) throw unsupportedConnectedStop(); if (!readPinnedRuntime() || health?.service !== "opencodex" || health.pid !== target.pid) throw unsupportedConnectedStop(); - // Native machine listeners preserve integrations on signal and have no /api/stop route. - if (health.role === "client") return; + const linkStopFence = health.linkStopFence === true; + if (options.requireLinkStopFence && !linkStopFence) throw unsupportedConnectedStop(); + // A native listener proves its contract on health and has no /api/stop route. + if (health.role === "client") return { linkStopFence, nativeClient: true }; + if (health.role !== undefined) throw unsupportedConnectedStop(); + if (options.healthOnly) return { linkStopFence, nativeClient: false }; const remaining = deadline - Date.now(); if (remaining <= 0) throw unsupportedConnectedStop(); const read = await fetchBoundLocalManagementRead({ ...endpoint, source: "runtime" }, LOCAL_MANAGEMENT_READ_PATHS.stop, { @@ -84,32 +269,48 @@ export async function assertConnectedClientStopSupported(target: ConnectedStopTa if (read.kind !== "response") throw unsupportedConnectedStop(); const capability = await readDocument(read.response); if (readPinnedRuntime() && capability?.schema === "ocx-stop-capabilities/1" - && capability.pid === target.pid && capability.connectedClientOwnership === true) return; + && capability.pid === target.pid && capability.connectedClientOwnership === true) return { linkStopFence, nativeClient: false }; } catch { /* A missing or replaced runtime never grants shutdown authority. */ } throw unsupportedConnectedStop(); } /** Fail before either service-manager path, including a manager that cascades process exit. */ -export async function preflightConnectedClientStop(approved?: ConnectedStopTarget): Promise { +export async function preflightConnectedClientStop( + approved: ConnectedStopTarget | undefined, onFence: (finish: () => Promise) => void, + inheritedTeardowns?: readonly LinkInheritedTeardown[], + onLinkStop?: (preflight: LinkStopPreflight) => void, + onTarget?: (proof: StopTargetProof) => void, + siblingOfPort?: number, +): Promise { try { + const connection = readClientConnectionState(); + if (connection.kind === "invalid" || connection.kind === "mismatched") throw unsupportedConnectedStop(); let target = approved; if (!target) { - const pid = readPid(); - const runtime = readRuntimePort(pid ?? undefined); - if (pid && isProcessAlive(pid)) { - if (!runtime) throw unsupportedConnectedStop(); + const trackedPid = readPid() ?? readAlivePid(); + const runtime = readRuntimePort(); + const pid = trackedPid ?? (runtime?.servingGeneration ? runtime.pid : undefined); + if (pid && (trackedPid === pid || isProcessAlive(pid))) { + if (runtime?.pid !== pid) throw unsupportedConnectedStop(); target = { ...runtime, pid }; - } - else { - const live = await findLiveProxy({ acceptPackageTreeFenced: true }); - if (live?.pid) { - if (await proveLiveProxyOwnedByHome(live) !== "proven") throw unsupportedConnectedStop(); + } else { + const live = await findLiveProxy({ acceptPackageTreeFenced: true, attempts: 1 }); + if (live && live.port !== siblingOfPort) { + if (!live.pid) throw unsupportedConnectedStop(); target = { ...live, pid: live.pid }; } else { + if (runtime && isProcessAlive(runtime.pid)) throw unsupportedConnectedStop(); const config = loadConfig(); - const endpoints = [...(runtime ? [runtime] : []), { port: config.port, hostname: config.hostname }]; - if (endpoints.some(endpoint => !Number.isInteger(endpoint.port) || endpoint.port <= 0 || endpoint.port > 65535) - || await observeGuardedManagerStopped({ kind: "absent" }) !== "inactive") throw unsupportedConnectedStop(); + const endpoints = [...(runtime ? [runtime] : []), + ...(config.port === 0 || config.port === siblingOfPort ? [] : [{ port: config.port, hostname: config.hostname }])]; + const clientMayRemain = connection.kind !== "disconnected" || runtime?.clientLinkOwner !== undefined + || runtime?.servingGeneration !== undefined; + const manager = await observeGuardedManagerStopped({ kind: "absent" }); + const offlineForegroundLink = manager === "unknown" + && connection.kind === "connected" && connection.value.transport === "link" + && (await import("../service/systemd")).systemdInstallationAbsent(); + if ((clientMayRemain && endpoints.length === 0) + || (manager !== "inactive" && !offlineForegroundLink)) throw unsupportedConnectedStop(); for (const endpoint of endpoints) { if (await probeEndpointLiveness(endpoint) !== "dead") throw unsupportedConnectedStop(); } @@ -118,14 +319,126 @@ export async function preflightConnectedClientStop(approved?: ConnectedStopTarge } } if (!isProcessAlive(target.pid)) throw unsupportedConnectedStop(); - await assertConnectedClientStopSupported(target); + const stopTarget = target; + const pinned = readRuntimePort(target.pid); + const standaloneSibling = siblingOfPort !== undefined && pinned?.siblingOfPort === siblingOfPort + && pinned.clientLinkOwner === undefined && pinned.servingGeneration === undefined; + const savedLink = connection.kind === "connected" && connection.value.transport === "link"; + const publishedLink = pinned?.clientLinkOwner != null; + const clientRecord = pinned?.servingGeneration !== undefined || pinned?.clientLinkOwner !== undefined; + const { readClientStopProcessStart } = await import("../client/stop-teardown-owner"); + const targetStart = savedLink || clientRecord ? readClientStopProcessStart(target.pid) : undefined; + if ((savedLink || clientRecord) && !targetStart) throw unsupportedConnectedStop(); + const capability = await assertConnectedClientStopSupported(target, { healthOnly: connection.kind === "disconnected" || standaloneSibling }); + const sameStart = () => targetStart === undefined || readClientStopProcessStart(stopTarget.pid) === targetStart; + const checkPinnedTarget = (afterTerm?: RuntimePortState) => { + const current = readRuntimePort(stopTarget.pid); + if ((!Bun.deepEquals(current, pinned, true) && !(afterTerm && Bun.deepEquals(current, afterTerm, true))) + || !sameStart()) throw unsupportedConnectedStop(); + }; + checkPinnedTarget(); + if (!capability) throw unsupportedConnectedStop(); + if (standaloneSibling && !capability.nativeClient && !capability.linkStopFence) { + onTarget?.({ target, verify: checkPinnedTarget, siblingOnly: true }); + return null; + } + if (savedLink && capability.nativeClient && !capability.linkStopFence && pinned?.clientLinkOwner === undefined) { + throw legacyLinkStopRefusal(); + } + if (savedLink || publishedLink || capability.linkStopFence) { + if (!capability.linkStopFence || !targetStart) throw unsupportedConnectedStop(); + const link = connection.kind === "connected" && linkStopConnectionOwner(connection.value); + if (!link || pinned?.clientLinkOwner !== link) throw unsupportedConnectedStop(); + if (siblingOfPort !== undefined || pinned.siblingOfPort !== undefined) { + if (siblingOfPort === undefined || pinned.siblingOfPort !== siblingOfPort || !capability.nativeClient + || !pinned.servingGeneration) throw unsupportedConnectedStop(); + const { terminateAttestedClient } = await import("./stop-client-process"); + const stopping = { ...pinned, clientStopping: true as const }; + const verify = (phase?: "after-term") => { + checkPinnedTarget(phase === "after-term" ? stopping : undefined); + const current = readClientConnectionState(); + if (current.kind !== "connected" || linkStopConnectionOwner(current.value) !== link) throw unsupportedConnectedStop(); + }; + // The sibling owns its listener only. Keep shared routing and teardown with the owner. + onTarget?.({ target, verify, siblingOnly: true, terminateSibling: () => terminateAttestedClient(stopTarget.pid, targetStart, verify) }); + return null; + } + if (loadConfig().port !== target.port) throw unsupportedConnectedStop(); + // A native Child has no /api/stop refusal: SIGTERM can escalate to SIGKILL. + // Refuse known inherited restore blockers before any manager or kill step. + const { inheritedTeardownDigest, readLinkInheritedTeardowns } = await import("../client/stop-native-handoff"); + const normalizeHost = (value: string | undefined) => (value ?? "127.0.0.1").trim().toLowerCase().replace(/^\[(.*)\]$/, "$1"); + const verifiedForeign: Buffer[] = []; + for (const read of inheritedTeardowns ?? readLinkInheritedTeardowns()) { + if (read.state === "valid" && read.receipt.endpointSource === "exact") { + const endpoint = read.receipt.endpoint; + if (endpoint.port === target.port && normalizeHost(endpoint.hostname) === normalizeHost(target.hostname)) continue; + if (read.bytes && await probeEndpointLiveness(endpoint) === "dead") { + verifiedForeign.push(read.bytes); + continue; + } + } + throw new ProxyOwnershipRefusedError("Link Child native teardown preflight refused: pending recovery evidence would prevent native restoration. No process was stopped; repair that evidence, then retry ocx stop.", "link_native_teardown_refused"); + } + // A manager can kill the Child before its signal handler runs. Drain these file routes + // first, under an exact runtime fence; refusal must return before any manager/kill step. + if (!pinned?.attestationSecret || !Bun.deepEquals(readRuntimePort(target.pid), pinned, true)) throw unsupportedConnectedStop(); + const { finishClientRuntimeStop, markClientRuntimeStopping, markClientRuntimeStoppingWithRetry } = await import("../client/sync-runtime"); + const { restoreLinkFileRouting } = await import("../client/stop-file-routing"); + const startTime = readClientStopProcessStart(process.pid); + if (!startTime) throw unsupportedConnectedStop(); + const owner = { pid: process.pid, startTime, nonce: randomBytes(16).toString("hex") }; + const identity = { pid: target.pid, port: target.port, attestationSecret: pinned.attestationSecret }; + // The CLI holds its ownership mutation lease through this finalizer. A retained listener + // can distinguish a finished stop from one still about to call a manager or kill fallback. + onFence(async () => { + const finished = await markClientRuntimeStoppingWithRetry(identity, { mark: () => { + if (sameStart()) finishClientRuntimeStop(identity, owner); + } }); + if (!finished) console.warn("The retained Child's stop state could not be finalized; repair its runtime record before retrying recovery."); + }); + const stopping = { ...pinned, clientStopping: true, clientStopRequested: true, clientStopOwner: owner }; + const checkRuntime = () => { + if (!sameStart() || !Bun.deepEquals(readRuntimePort(identity.pid), stopping, true)) throw new Error("client_runtime_changed"); + }; + const fenced = await markClientRuntimeStoppingWithRetry(identity, { + mark: () => stopRestoreWriteGuard(connection.value).run(() => { + const current = readRuntimePort(identity.pid); + if (!sameStart() || (!Bun.deepEquals(current, pinned, true) && !Bun.deepEquals(current, stopping, true))) throw new Error("client_runtime_changed"); + // The marker is checked by every sync commit, including already admitted work. + markClientRuntimeStopping(identity, owner); + }), + }); + try { + if (!fenced) throw new Error("the runtime sync fence could not be verified"); + await restoreLinkFileRouting(connection.value, { beforeWrite: checkRuntime }); + const { terminateAttestedClient } = await import("./stop-client-process"); + const guard = stopRestoreWriteGuard(connection.value); + const verify = () => { + try { guard.run(() => { + checkRuntime(); + if (loadConfig().port !== identity.port) throw new Error("client_route_port_changed"); + }); } + catch { throw unsupportedConnectedStop(); } + }; + onTarget?.({ target, verify }); + onLinkStop?.({ target, owner, inheritedTeardownDigest: inheritedTeardownDigest(verifiedForeign), verify, forceKill: pid => { + if (pid !== stopTarget.pid) throw unsupportedConnectedStop(); + terminateAttestedClient(pid, targetStart, verify); + } }); + } catch (error) { + throw new ProxyOwnershipRefusedError(`Link Child file routing restore refused: ${error instanceof Error ? error.message : "restoration failed"}. No process was stopped. ${fenced ? "Sync remains fenced; " : ""}repair the client configuration or ownership evidence, then retry ocx stop.`, "link_file_restore_refused"); + } + } else if (capability.nativeClient && (connection.kind !== "connected" || pinned?.clientLinkOwner !== null)) { + // Older native listeners cannot distinguish Hub from Link once the saved connection drifts. + throw unsupportedConnectedStop(); + } else { + if (connection.kind === "disconnected" && clientRecord) throw unsupportedConnectedStop(); + onTarget?.({ target, verify: checkPinnedTarget }); + } return null; - } catch { - const error = unsupportedConnectedStop(); - console.error(error.message); - process.exitCode = 1; - return { ok: false, summary: { schema: "ocx-stop/1", ok: false, outcome: "failed", exitCode: 1, - runtimeDown: false, service: "absent", proxy: "ownership-refused", sharedTeardown: "skipped", message: error.message } }; + } catch (cause) { + return stopOwnershipRefused(cause instanceof ProxyOwnershipRefusedError ? cause : unsupportedConnectedStop()); } } @@ -190,6 +503,14 @@ export function restoreBoundaryOwnership(deps: { } } +async function hasLinkFileRouteEvidence(): Promise { + const { readRouteIntentReceiptStrict } = await import("../integrations/route-intent-state"); + const { homeRouteIntentPath } = await import("../client/link-home"); + try { lstatSync(homeRouteIntentPath()); return true; } + catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; } + return readRouteIntentReceiptStrict()?.linkId !== undefined; +} + /** * Restore shared client state after a stop. * @@ -214,6 +535,24 @@ export async function restoreSharedClientStateAfterStop( let historyDeferred = false; let other = false; const guard = stopRestoreWriteGuard(); + try { + const connection = readClientConnectionState(); + if (connection.kind === "connected" && connection.value.transport === "link") { + const { restoreLinkFileRouting } = await import("../client/stop-file-routing"); + await restoreLinkFileRouting(connection.value); + } else if (await hasLinkFileRouteEvidence()) { + throw new Error("Link route receipts remain. Repair the saved Link ownership and rerun 'ocx stop' before reopening clients."); + } + } catch (error) { + if (error instanceof StopRestoreOwnershipError) { + if (error.boundary === "unproven") return { historyOnly, historyDeferred, other, boundary: error.boundary }; + // A concurrent Hub connection can supersede native teardown. A surviving Link file + // receipt still needs recovery and must not be silently settled with the native receipt. + if (!await hasLinkFileRouteEvidence().catch(() => true)) return { historyOnly, historyDeferred, other, boundary: error.boundary }; + } + console.error(`⚠️ Link Child file routing restore failed: ${error instanceof Error ? error.message : "ownership could not be verified"}`); + return { historyOnly, historyDeferred, other: true }; + } try { const result = await restoreNativeCodexAsync({ withWriteGuard: guard.run }); if (guard.boundary() !== "restore") throw new Error("stop_restore_ownership_changed"); diff --git a/src/client/machine-listener.ts b/src/client/machine-listener.ts index a942543cc2f..f346ba7fdef 100644 --- a/src/client/machine-listener.ts +++ b/src/client/machine-listener.ts @@ -91,6 +91,8 @@ export interface MachineListenerDeps { attestationSecret: string; /** ISO start time of this runtime's process. */ startedAt: string; + /** The owning runtime preserves explicit Link stop fences across restart rollback. */ + linkStopFence?: true; request: () => Promise; }; serve?: (options: Parameters[0]) => Server; @@ -207,6 +209,7 @@ export function startMachineListener( const response = Response.json({ service: "opencodex", version: VERSION, role: "client", uptime: process.uptime(), pid: process.pid, port: server.port, ...(restart ? { startedAt: restart.startedAt, restartCapability: SYSTEM_RESTART_CAPABILITY_VERSION, restartBudgetMs: CLIENT_RESTART_BUDGET_MS } : {}), + ...(restart?.linkStopFence ? { linkStopFence: true } : {}), }); const challenge = restart ? req.headers.get(LOCAL_ATTESTATION_CHALLENGE_HEADER) : null; const proof = challenge && server.port diff --git a/src/client/runtime-recycle.ts b/src/client/runtime-recycle.ts new file mode 100644 index 00000000000..e0fb65498b3 --- /dev/null +++ b/src/client/runtime-recycle.ts @@ -0,0 +1,29 @@ +import { withConfigMutationLockSync } from "../config"; +import type { OcxClientConnectionConfig } from "../types"; +import { withLinkApply } from "./link-home"; +import { clientConnectionEnded } from "./runtime-restart"; +import { pendingClientConnectMayOwnToken, readClientConnectionStateWithEvidence } from "./state"; + +/** + * Called outside L: Link apply exclusion is outermost in the apply -> N -> L -> C order. + * Once admitted, keep it through all teardown awaits; a new connect cannot commit halfway. + */ +export async function runClientRecycleWithAdmission( + served: OcxClientConnectionConfig, + allowed: () => boolean, + teardown: () => Promise, +): Promise { + let admitted = false; + try { + return await withLinkApply(async () => { + admitted = withConfigMutationLockSync(() => allowed() && !pendingClientConnectMayOwnToken() + && clientConnectionEnded(served, readClientConnectionStateWithEvidence())); + if (!admitted) return false; + await teardown(); + return true; + }); + } catch (error) { + if (admitted) throw error; // A started teardown must not masquerade as an admission refusal. + return false; + } +} diff --git a/src/client/runtime-restart.ts b/src/client/runtime-restart.ts index 58b1d31629b..9b17da3f809 100644 --- a/src/client/runtime-restart.ts +++ b/src/client/runtime-restart.ts @@ -161,6 +161,7 @@ export function createClientRestartController(io: ClientRestartIo): ClientRestar // The recheck is the last step before the recycle, after the (asynchronous) supervisor lookup. flight = sleep(200).then(async () => { const supervisor = await io.supervisor(); + if (io.stopping?.()) return; if (restartRefusedByOwner(supervisor)) { warn("[client] restart: this runtime's owner could not be proven to relaunch it; it keeps serving"); return; } if (changed()) await recycle(supervisor); }).finally(() => { flight = null; }); diff --git a/src/client/runtime-rollback.ts b/src/client/runtime-rollback.ts new file mode 100644 index 00000000000..f2e0380377b --- /dev/null +++ b/src/client/runtime-rollback.ts @@ -0,0 +1,29 @@ +import { ConfigMutationLockError } from "../config"; +import { CLIENT_RESTART_REBIND_WAIT_MS } from "../lib/system-restart-contract"; + +export type ClientRollbackAttempt = "published" | "busy" | "refused"; + +export function retryableClientRollbackLock(error: unknown): boolean { + if (error && typeof error === "object" && "code" in error && error.code === "client_lifecycle_busy") return true; + const cause = error instanceof ConfigMutationLockError ? error.cause : undefined; + const code = cause && typeof cause === "object" && "code" in cause ? cause.code : undefined; + return code === "SQLITE_BUSY" || code === "SQLITE_LOCKED"; +} + +/** Each busy attempt must close its unpublished listener before this helper may yield. */ +export async function retryClientRollback( + attempt: (remainingMs: number) => Promise, + io: { now?: () => number; sleep?: (ms: number) => Promise; budgetMs?: number } = {}, +): Promise { + const now = io.now ?? (() => performance.now()); + const deadline = now() + (io.budgetMs ?? CLIENT_RESTART_REBIND_WAIT_MS); + while (now() < deadline) { + const result = await attempt(Math.max(0, deadline - now())); + if (result === "published") return true; + if (result !== "busy") return false; + const remaining = deadline - now(); + if (remaining <= 0) return false; + await (io.sleep ?? Bun.sleep)(Math.min(50, remaining)); + } + return false; +} diff --git a/src/client/runtime.ts b/src/client/runtime.ts index 3aee9b53d29..906bb0b9914 100644 --- a/src/client/runtime.ts +++ b/src/client/runtime.ts @@ -1,11 +1,12 @@ import { randomUUID } from "node:crypto"; +import { readDesktopDisconnectReceipt } from "../claude/desktop-remote-store"; import { flushLinkDiagnostics, recordLinkDiagnostic } from "../link/diagnostics"; import { existsSync } from "node:fs"; import type { Server } from "bun"; import { siblingRuntimeField, withSiblingMarker } from "../codex/sibling-start"; import { issueSiblingHandoff } from "../codex/sibling-handoff"; -import { loadConfig } from "../config"; -import { removePid, removeRuntimePort, writePid, writeRuntimePort, type RuntimePortState } from "../config/process-state"; +import { loadConfig, withConfigMutationLockSync } from "../config"; +import { readRuntimePort, removePid, removeRuntimePort, writePid, writeRuntimePort, type ClientStopOwner, type RuntimePortState } from "../config/process-state"; import { currentServingCommand } from "../config/serving-runtimes"; import { installCrashGuards } from "../lib/crash-guard"; import { observeLocalCredentials } from "../local-credentials/runtime-observation"; @@ -14,7 +15,6 @@ import { createLocalAttestationSecret } from "../lib/local-management-attestatio import { loadServiceTokenFromFile, serviceApiTokenFingerprint } from "../lib/service-secrets"; import { handledSignalExitCode } from "../lib/handled-signal-exit"; import { - CLIENT_RESTART_REBIND_WAIT_MS, DESKTOP_RESTART_EXIT_CODE, DESKTOP_SUPERVISED_ENV, DESKTOP_SUPERVISED_PORT_WAIT_MS, @@ -29,15 +29,18 @@ import { clientInitiatedLinkReadiness, createHomeInitiatedLinkReadiness } from " import { createClientLinkSupervisor, type ClientLinkSupervisor } from "./link-tunnel"; import { clientLinkStatePath, isChildInitiatedLink, recordChildInitiatedLink } from "./link-state"; import { startMachineListener, type MachineListenerDeps } from "./machine-listener"; -import { isLinkConnection, readClientConnectionState, readClientConnectionStateWithEvidence } from "./state"; +import { isLinkConnection, linkStopConnectionOwner, pendingClientConnectMayOwnToken, readClientConnectionState, readClientConnectionStateWithEvidence, sameClientConnectionOwner } from "./state"; import { withClientLifecycleSync } from "./lifecycle-lock"; import { clientConnectionEnded, clientRestartRollbackAction, clientRestartSupervisor, createClientRestartController, LEGACY_FLAG_RESTART_OWNER, restartOwnerEvidence, type ClientRestartController, type RecordedRestartOwner, type RestartOwner } from "./runtime-restart"; import { createLinkParityReporter, type LinkParityReporter } from "./link-parity-reporter"; -import { restoreLinkClientRouting } from "./stop-routing"; +import { restoreLinkClientRoutingBeforeExit } from "./stop-routing"; +import { observeClientStopOwner } from "./stop-teardown-owner"; import { SUPERVISOR_MARKER_ENVS } from "../lib/supervisor-markers"; import { markClientRuntimeStopping, markClientRuntimeStoppingWithRetry } from "./sync-runtime"; import { startRouteIntentTick, type RouteIntentTick } from "../integrations/route-intent-tick"; import { startRouteIntentWatch, type RouteIntentRuntimeWatch } from "./route-intent-watch"; +import { runClientRecycleWithAdmission } from "./runtime-recycle"; +import { retryClientRollback, retryableClientRollbackLock, type ClientRollbackAttempt } from "./runtime-rollback"; let activeServer: Server | null = null; let activePort: number | null = null; @@ -52,6 +55,10 @@ let recycleScheduled = false; let recycleTimer: ReturnType | undefined; let recycleFlight: Promise | null = null; let clientStopping = false; +let explicitClientStopRequested: boolean | undefined; +let explicitClientStopOwner: ClientStopOwner | undefined; +let standaloneRecycleAllowed = () => !clientStopping; +let activeLinkForRecycle: OcxClientConnectionConfig | undefined; /** * When this runtime's process started (OCX-6, P5): what `/healthz` reports as `startedAt` and the @@ -82,6 +89,8 @@ const LINK_BIND_ATTEMPTS = 3; export interface ClientRuntimeIo { /** Link-mode port budget; defaults to {@link LINK_PORT_WAIT_MS}. */ portWaitMs?: number; + /** Rollback bind attempts share one deadline instead of restarting the port wait. */ + bindDeadlineAt?: number; startListener?: typeof startMachineListener; /** Which supervisor owns this process for a bound restart; tests replace the production check. */ restartSupervisor?: () => Promise<"service" | "desktop" | null>; @@ -114,7 +123,10 @@ export function clientRuntimeRecord( ): RuntimePortState { let command: string[] | undefined; try { command = currentServingCommand(); } catch { /* no reliable relaunch identity; update admission fails closed */ } - return { pid, port, hostname: "127.0.0.1", attestationSecret, ...(command ? { command } : {}), ...siblingRuntimeField(), ...(clientStopping ? { clientStopping: true as const } : {}), ...(owner ? { restartOwner: owner } : {}) }; + return { pid, port, hostname: "127.0.0.1", attestationSecret, ...(command ? { command } : {}), ...siblingRuntimeField(), + ...(clientStopping ? { clientStopping: true as const } : {}), + ...(explicitClientStopRequested !== undefined ? { clientStopRequested: explicitClientStopRequested } : {}), + ...(explicitClientStopOwner ? { clientStopOwner: explicitClientStopOwner } : {}), ...(owner ? { restartOwner: owner } : {}) }; } /** Evaluated once: the launch environment and parent of this process do not change. */ @@ -155,11 +167,11 @@ export function standaloneRecycleEnv( } export function scheduleStandaloneRecycle(disconnectedTokenFingerprint: string): void { - if (recycleScheduled || clientStopping) return; + if (recycleScheduled || !standaloneRecycleAllowed()) return; recycleScheduled = true; recycleTimer = setTimeout(() => { recycleTimer = undefined; - if (clientStopping) return; + if (!standaloneRecycleAllowed()) { recycleScheduled = false; return; } recycleFlight = recycleStandalone(disconnectedTokenFingerprint).finally(() => { recycleFlight = null; }); void recycleFlight.catch(error => { if (!clientStopping) throw error; }); }, 50); @@ -189,26 +201,35 @@ export async function recycleStandalone( const exit = io.exitProcess ?? ((code: number) => { process.exit(code); }); // Capture the one-use sibling handoff before this process removes its runtime record. const serviceSupervised = (io.serviceSupervised ?? (() => process.env.OCX_SERVICE === "1"))(); - const replacementEnv = port && !serviceSupervised - ? withSiblingMarker(standaloneRecycleEnv(process.env, disconnectedTokenFingerprint), issueSiblingHandoff) - : null; - activeCredentialObservation?.stop(); activeCredentialObservation = null; - activeReporter?.stop(); activeReporter = null; - activeRouteWatch?.stop(); activeRouteWatch = null; - activeRouteSync?.stop(); activeRouteSync = null; - try { - await activeSupervisor?.stop(); - } catch (error) { - console.warn(`[client] link supervisor stop failed: ${error instanceof Error ? error.message : String(error)}`); - } - activeSupervisor = null; - try { - activeServer?.stop(true); - } catch (error) { - console.warn(`[client] listener stop failed: ${error instanceof Error ? error.message : String(error)}`); - } - cleanup(); - await flushLinkDiagnostics(); + let replacementEnv: NodeJS.ProcessEnv | null = null; + const teardown = async () => { + replacementEnv = port && !serviceSupervised + ? withSiblingMarker(standaloneRecycleEnv(process.env, disconnectedTokenFingerprint), issueSiblingHandoff) + : null; + activeCredentialObservation?.stop(); activeCredentialObservation = null; + activeReporter?.stop(); activeReporter = null; + activeRouteWatch?.stop(); activeRouteWatch = null; + activeRouteSync?.stop(); activeRouteSync = null; + try { + await activeSupervisor?.stop(); + } catch (error) { + console.warn(`[client] link supervisor stop failed: ${error instanceof Error ? error.message : String(error)}`); + } + activeSupervisor = null; + try { + await activeServer?.stop(true); + } catch (error) { + console.warn(`[client] listener stop failed: ${error instanceof Error ? error.message : String(error)}`); + } + cleanup(); + await flushLinkDiagnostics(); + }; + if (activeLinkForRecycle) { + if (!(await runClientRecycleWithAdmission(activeLinkForRecycle, standaloneRecycleAllowed, teardown))) { + recycleScheduled = false; + return; + } + } else await teardown(); // Recycling back to standalone after `ocx disconnect` must actually bring a standalone // proxy back, under every launch shape. // @@ -277,17 +298,19 @@ export async function bindClientListener( ): Promise<{ server: Server; port: number }> { const { linkMode } = request; const portWaitMs = io.portWaitMs ?? (linkMode ? linkPortWaitMs() : LINK_PORT_WAIT_MS); - const deadline = Date.now() + portWaitMs; + const deadline = io.bindDeadlineAt ?? Date.now() + portWaitMs; + const remaining = () => Math.max(0, deadline - Date.now()); const busy = (cause: unknown) => new Error( `link mode needs port ${request.configuredPort}; free it or change port`, { cause }, ); let port: number; try { + if (io.bindDeadlineAt !== undefined && remaining() <= 0) throw busy("rollback deadline expired"); if (linkMode) { const { reclaimListenPort } = await import("../server/port-reclaim"); await reclaimListenPort(request.configuredPort, "127.0.0.1", { - timeoutMs: portWaitMs, + timeoutMs: io.bindDeadlineAt === undefined ? portWaitMs : Math.min(portWaitMs, remaining()), intervalMs: 100, scanIntervalMs: 500, killOcxHolders: false, @@ -295,7 +318,8 @@ export async function bindClientListener( }); } port = await findAvailablePort(request.preferred, "127.0.0.1", { - preferRetryMs: request.explicitPort ? PINNED_PREFER_RETRY_MS : 750, + preferRetryMs: Math.min(request.explicitPort ? PINNED_PREFER_RETRY_MS : 750, + io.bindDeadlineAt === undefined ? Infinity : remaining()), preferRetryIntervalMs: 50, allowEphemeralFallback: linkMode ? false : !request.explicitPort, }); @@ -306,6 +330,7 @@ export async function bindClientListener( const startListener = io.startListener ?? startMachineListener; for (let attempt = 1; ; attempt += 1) { try { + if (io.bindDeadlineAt !== undefined && remaining() <= 0) throw busy("rollback deadline expired"); const server = startListener(port, { state: request.state, machineApi: { scheduleStandaloneRecycle }, @@ -320,8 +345,8 @@ export async function bindClientListener( } catch (error) { // Check-then-bind: the port can be taken between the probe and Bun.serve. if (!linkMode || !isAddrInUse(error)) throw error; - const waitMs = Math.max(1_000, deadline - Date.now()); - if (attempt >= LINK_BIND_ATTEMPTS + const waitMs = io.bindDeadlineAt === undefined ? Math.max(1_000, remaining()) : remaining(); + if (attempt >= LINK_BIND_ATTEMPTS || waitMs <= 0 || !(await waitForPortAvailable(port, "127.0.0.1", { timeoutMs: waitMs, intervalMs: 100 }))) { throw busy(error); } @@ -337,6 +362,7 @@ export async function startClientRuntime( if (state.kind !== "connected") throw new Error(`client runtime refused: client state is ${state.kind}`); const config = loadConfig(); const linkMode = isLinkConnection(state.value); + const clientLinkOwner = linkMode ? linkStopConnectionOwner(state.value) : null; if (linkMode && (!Number.isInteger(config.port) || config.port < 1 || config.port > 65535)) { throw new Error("link mode requires a valid local config port"); } @@ -360,9 +386,18 @@ export async function startClientRuntime( // restart rolls back (OCX-6); the stopped supervisor cannot be started twice, so each call builds one. // The port this process actually serves on; a rollback binds exactly this one again. let servedPort = preferred; - // Returns false only for a rollback whose connection changed while it was binding: the new - // listener is then closed unpublished and the caller recycles. - const serve = async (rollback?: { port: number; portWaitMs: number }): Promise => { + const observeExplicitStop = (): boolean => { + const current = readRuntimePort(process.pid); + if (current?.port === servedPort && current.attestationSecret === attestationSecret && current.clientStopRequested !== undefined) { + explicitClientStopRequested = current.clientStopRequested; + explicitClientStopOwner = current.clientStopOwner; + clientStopping = true; + } + return explicitClientStopRequested === true + && (!explicitClientStopOwner || observeClientStopOwner(explicitClientStopOwner) !== "confirmed-stale"); + }; + // An unpublishable rollback closes the new listener before the caller considers a recycle. + const serve = async (rollback?: { port: number; portWaitMs: number }): Promise => { const supervisor = supervised ? createClientLinkSupervisor({ diagnostic: recordLinkDiagnostic, @@ -385,24 +420,30 @@ export async function startClientRuntime( preferred: rollback?.port ?? preferred, explicitPort: rollback !== undefined || options.port !== undefined, configuredPort: config.port, - restart: { attestationSecret, startedAt: CLIENT_RUNTIME_STARTED_AT, request: () => restartController.request() }, + restart: { attestationSecret, startedAt: CLIENT_RUNTIME_STARTED_AT, ...(linkMode ? { linkStopFence: true as const } : {}), request: () => restartController.request() }, ...(linkMode ? { linkStatus: () => activeSupervisor?.status() ?? { kind: "stopped" as const }, linkKeySource: linkKey } : {}), ...(supervisor ? { linkTunnel: supervisor } : homeInitiated ? { linkTunnel: HOME_INITIATED_LINK_TUNNEL } : {}), ...(linkReadiness ? { linkReadiness } : {}), ...(supervisor ? { linkConnectionGeneration: () => supervisor.connectionGeneration() } : homeInitiated && link ? { linkConnectionGeneration: () => verifiedHomeConnection(link.linkId) } : {}), - }, rollback === undefined ? io : { ...io, portWaitMs: rollback.portWaitMs }); - const publish = (): void => { + }, rollback === undefined ? io : { ...io, portWaitMs: rollback.portWaitMs, bindDeadlineAt: Date.now() + rollback.portWaitMs }); + const publishRecord = (): void => { + // A parent stop can arrive after restart admission. Never clear its fence on rollback; + // a fresh process has another attestation identity and cannot inherit this request. + if (rollback) observeExplicitStop(); + writePid(process.pid); + // A new generation refuses commits from syncs admitted before the failed restart. + writeRuntimePort({ ...clientRuntimeRecord(process.pid, boundPort, attestationSecret), servingGeneration: randomUUID(), + clientLinkOwner }); + }; + const activate = (): void => { + activeLinkForRecycle = linkMode ? state.value : undefined; activeServer = server; activePort = boundPort; servedPort = boundPort; activeSupervisor = supervisor; supervisor?.start(); activeCredentialObservation ??= observeLocalCredentials(); - writePid(process.pid); - // A new generation per publication: syncs admitted before a failed restart refuse to commit - // into the runtime that serves again, while syncs admitted from here on proceed. - writeRuntimePort({ ...clientRuntimeRecord(process.pid, boundPort, attestationSecret), servingGeneration: randomUUID() }); if (linkMode && state.value.link && linkKey) { activeReporter = createLinkParityReporter({ connection: state.value, linkKey, runtimeStartedAt: CLIENT_RUNTIME_STARTED_AT }); activeReporter.start(); @@ -412,26 +453,27 @@ export async function startClientRuntime( } }; if (!rollback) { - publish(); - return true; + publishRecord(); + activate(); + return "published"; } - // A rollback publishes under the client lifecycle lock, after rechecking the connection there, - // so a disconnect or connect that committed during the bind can never be served over. A lock - // held by such an operation counts as a change. - let published = false; + // Admission and publication are synchronous after bind. A busy lock must close the + // rebound listener before yielding. Link takes C to preserve an explicit stop fence. + const publishIfOwned = () => { + if (clientRestartRollbackAction(state.value, readClientConnectionState()) === "recycle") return false; + publishRecord(); + return true; + }; + let published = false, busy = false; try { - published = withClientLifecycleSync(() => { - if (clientRestartRollbackAction(state.value, readClientConnectionState()) === "recycle") return false; - publish(); - return true; - }); - } catch { - published = false; - } - if (!published) { - try { await server.stop(true); } catch { /* never published */ } + published = withClientLifecycleSync(() => linkMode ? withConfigMutationLockSync(publishIfOwned) : publishIfOwned()); + } catch (error) { busy = retryableClientRollbackLock(error); } + if (published) activate(); + else { + // Do not retain an unrecorded listener across the contention retry's await. + await server.stop(true); } - return published; + return published ? "published" : busy ? "busy" : "refused"; }; // Stop everything this process serves, giving in-flight requests up to `drainMs`. @@ -464,8 +506,25 @@ export async function startClientRuntime( }; let shuttingDown = false; + standaloneRecycleAllowed = () => { + try { + if (shuttingDown || observeExplicitStop()) return false; + if (!clientStopping) return true; + // A retained sync fence is not an active exit. Only a completed disconnect of this exact + // served owner permits recovery; partial cleanup, a new connect or uncertain state cannot. + return withConfigMutationLockSync(() => { + if (observeExplicitStop()) return false; + const receipt = readDesktopDisconnectReceipt(); + return ownerProven() && !pendingClientConnectMayOwnToken() + && readClientConnectionStateWithEvidence().kind === "disconnected" + && receipt.kind === "valid" && receipt.value.phase === "complete" + && sameClientConnectionOwner(receipt.value.owner, state.value) + && receipt.value.tokenFingerprint === state.value.tokenFingerprint; + }); + } catch { return false; } + }; const restartController: ClientRestartController = createClientRestartController({ - stopping: () => shuttingDown, + stopping: () => !standaloneRecycleAllowed(), supervisor: io.restartSupervisor ?? clientRestartSupervisor, connectionChanged: () => clientConnectionEnded(state.value, readClientConnectionStateWithEvidence()), ownerProven, @@ -478,7 +537,12 @@ export async function startClientRuntime( // later commit stand down under C; the replacement's record, or the fresh generation a rollback // publishes, keeps those syncs refused and admits new ones. A mark that cannot be written // abandons the restart before anything stops. - fence: async () => !linkMode || await markClientRuntimeStoppingWithRetry({ pid: process.pid, port: servedPort, attestationSecret }), + fence: async () => !linkMode || await markClientRuntimeStoppingWithRetry({ pid: process.pid, port: servedPort, attestationSecret }, { + mark: () => withConfigMutationLockSync(() => { + if (observeExplicitStop()) throw new Error("client_stop_requested"); + markClientRuntimeStopping({ pid: process.pid, port: servedPort, attestationSecret }); + }), + }), stop: stopServing, spawnReplacement: async deadlineAt => { const { replacementStartEnvironment } = await import("../server/management/system-restart"); @@ -489,15 +553,22 @@ export async function startClientRuntime( ); }, resume: async () => { + const recycleAfterRollback = () => { + if (standaloneRecycleAllowed()) return recycleStandalone(state.value.tokenFingerprint); + }; // The connection may have changed while the replacement was starting (`ocx disconnect`, a // new connect). Serving the old one again would be a stale runtime nothing recycles; hand // off to the recycle, which starts whatever the durable state now calls for. if (clientRestartRollbackAction(state.value, readClientConnectionState()) === "recycle") { - await recycleStandalone(state.value.tokenFingerprint); + await recycleAfterRollback(); return; } - if (!(await serve({ port: servedPort, portWaitMs: CLIENT_RESTART_REBIND_WAIT_MS }))) { - await recycleStandalone(state.value.tokenFingerprint); + if (!(await retryClientRollback(async remainingMs => { + observeExplicitStop(); + if (clientRestartRollbackAction(state.value, readClientConnectionState()) === "recycle") return "refused"; + return serve({ port: servedPort, portWaitMs: remainingMs }); + }))) { + await recycleAfterRollback(); } }, exitProcess: async code => { @@ -515,7 +586,11 @@ export async function startClientRuntime( if (shuttingDown) return; shuttingDown = true; clientStopping = true; - if (recycleTimer) { clearTimeout(recycleTimer); recycleTimer = undefined; } + if (recycleTimer) { + clearTimeout(recycleTimer); + recycleTimer = undefined; + recycleScheduled = false; + } const fenceSync = () => { if (!linkMode) return true; try { markClientRuntimeStopping({ pid: process.pid, port: servedPort, attestationSecret }); return true; } @@ -541,8 +616,16 @@ export async function startClientRuntime( console.warn(`[client] link supervisor stop failed: ${error instanceof Error ? error.message : String(error)}`); } activeSupervisor = null; - const restored = linkMode ? restoreLinkClientRouting(state.value, { syncFenced }) : null; + const restored = linkMode ? await restoreLinkClientRoutingBeforeExit(state.value, { + syncFenced, runtime: { pid: process.pid, port: servedPort, attestationSecret }, + }) : null; if (restored && !restored.success) console.error(`[client] ${restored.message}`); + if (restored?.retainListener) { + // Keep the stopping record and socket. Another signal can retry after the operator + // repairs the retained file/ownership evidence; no background sync can reapply it. + shuttingDown = false; + return; + } try { activeServer?.stop(true); } catch (error) { diff --git a/src/client/state.ts b/src/client/state.ts index 766d418908b..ea8a66e2401 100644 --- a/src/client/state.ts +++ b/src/client/state.ts @@ -1,5 +1,6 @@ import { lstatSync, readFileSync, unlinkSync } from "node:fs"; import { join } from "node:path"; +import { createHash } from "node:crypto"; import { getConfigDir, getConfigPath, @@ -31,6 +32,16 @@ export function isLinkConnection(c: OcxClientConnectionConfig | undefined): bool return c?.transport === "link"; } +/** The serving Link's ownership, independent of selection and catalog sync observations. */ +export function linkStopConnectionOwner(connection: OcxClientConnectionConfig): string | undefined { + if (connection.transport !== "link" || !connection.link) return; + return createHash("sha256").update(JSON.stringify([ + connection.serverUrl, connection.managementUrl, connection.managementTransport, + connection.apiKeyId, connection.connectedAt, connection.tokenFingerprint, + connection.link.linkId, connection.link.tunnelPort, + ])).digest("hex"); +} + const pendingConnectPath = (): string => join(getConfigDir(), "client-connect-pending"); /** Validate pending ownership; an optional fingerprint restricts it to that exact key. */ diff --git a/src/client/stop-darwin-process.ts b/src/client/stop-darwin-process.ts new file mode 100644 index 00000000000..18c926d5373 --- /dev/null +++ b/src/client/stop-darwin-process.ts @@ -0,0 +1,73 @@ +import { dlopen, ptr } from "bun:ffi"; + +const MAX_ARGV_BYTES = 64 * 1024; + +/** Read argc, skip the executable path and padding, and keep the environment separate. */ +function parseProcessArgs(bytes: Buffer): { argv: string[]; environment: Buffer } | undefined { + if (bytes.length < 5) return; + const argc = bytes.readInt32LE(0); + if (argc < 1 || argc > 4096) return; + let start = bytes.indexOf(0, 4); + if (start < 5) return; + while (bytes[start] === 0) start++; + const argv: string[] = []; + const decode = new TextDecoder("utf-8", { fatal: true }); + for (let index = 0; index < argc; index++) { + const end = bytes.indexOf(0, start); + if (end < start || end >= MAX_ARGV_BYTES) return; + argv.push(decode.decode(bytes.subarray(start, end))); + start = end + 1; + } + return { argv, environment: bytes.subarray(start) }; +} + +function readDarwinStopProcessArgs(pid: number): ReturnType { + const lib = dlopen("/usr/lib/libSystem.B.dylib", { + sysctl: { args: ["ptr", "u32", "ptr", "ptr", "ptr", "u64"], returns: "i32" }, + }); + try { + const mib = new Int32Array([1, 49, pid]); // CTL_KERN, KERN_PROCARGS2, PID + // The kernel returns argv with its environment. Bound the native read. + const bytes = Buffer.alloc(1024 * 1024); + const size = new BigUint64Array([BigInt(bytes.length)]); + if (lib.symbols.sysctl(ptr(mib), mib.length, ptr(bytes), ptr(size), null, 0n) !== 0 + || size[0]! > BigInt(bytes.length)) return; + return parseProcessArgs(bytes.subarray(0, Number(size[0]))); + } finally { lib.close(); } +} + +export function readDarwinStopArgv(pid: number): string[] | undefined { + return readDarwinStopProcessArgs(pid)?.argv; +} + +export function readDarwinStopEnvironment(pid: number): Buffer | undefined { + return readDarwinStopProcessArgs(pid)?.environment; +} + +function readDarwinProcessInfo(pid: number, flavor: number, size: number): Buffer | undefined { + const lib = dlopen("/usr/lib/libproc.dylib", { + proc_pidinfo: { args: ["i32", "i32", "u64", "ptr", "i32"], returns: "i32" }, + }); + try { + const info = Buffer.alloc(size); + if (lib.symbols.proc_pidinfo(pid, flavor, 0n, ptr(info), size) === size) return info; + } finally { lib.close(); } +} + +/** PROC_PIDTBSDINFO supplies both the effective UID and microsecond process creation time. */ +export function readDarwinStopStart(pid: number): string | undefined { + // struct proc_bsdinfo from sys/proc_info.h, shared by arm64 and x86_64. + const info = readDarwinProcessInfo(pid, 3, 136); + if (!info || info.readUInt32LE(12) !== pid || info.readUInt32LE(20) !== process.geteuid?.()) return; + const seconds = info.readBigUInt64LE(120); + const micros = info.readBigUInt64LE(128); + if (seconds > 0n && micros < 1_000_000n) return `darwin:${seconds}:${micros}`; +} + +export function readDarwinStopCwd(pid: number): string | undefined { + // PROC_PIDVNODEPATHINFO, struct proc_vnodepathinfo.pvi_cdir.vip_path[MAXPATHLEN]. + const info = readDarwinProcessInfo(pid, 9, 2352); + const path = info?.subarray(152, 152 + 1024); + const end = path?.indexOf(0) ?? -1; + if (path && end > 0) return new TextDecoder("utf-8", { fatal: true }).decode(path.subarray(0, end)); +} diff --git a/src/client/stop-file-routing.ts b/src/client/stop-file-routing.ts new file mode 100644 index 00000000000..70035b79a61 --- /dev/null +++ b/src/client/stop-file-routing.ts @@ -0,0 +1,49 @@ +/** Stop only the file routes this Link created; connection and recovery records remain. */ +import { loadConfig } from "../config"; +import { getConfigDir, withConfigDirHardeningSettled } from "../config/paths"; +import { cleanupConnectedFileRouteIntent, readConnectedFileRouteIntentForCleanup } from "../integrations/route-intent-disconnect"; +import { readRouteIntentReceiptStrict } from "../integrations/route-intent-state"; +import { readServiceApiTokenState } from "../lib/service-secrets"; +import type { OcxClientConnectionConfig } from "../types"; +import { clearHomeRouteIntentRecord } from "./link-home"; +import { withClientLifecycleSync, type ClientLifecycleLockDeps } from "./lifecycle-lock"; +import { stopRestoreWriteGuard } from "./restore-ownership"; + +export async function restoreLinkFileRouting( + connection: OcxClientConnectionConfig, + options: { beforeWrite?: () => void; lifecycleLockDeps?: ClientLifecycleLockDeps } = {}, +): Promise { + if (connection.transport !== "link" || !connection.link) return false; + const expected = structuredClone(connection); + const ownership = stopRestoreWriteGuard(expected); + const port = loadConfig().port; + const boundary = () => { + options.beforeWrite?.(); + if (loadConfig().port !== port) throw new Error("client_route_port_changed"); + }; + // A fenced Link with no owned file route needs no credential or lifecycle mutation. Keep the + // strict disk proof (including missing-receipt residue) and recheck the owner after its awaits. + if (!await readConnectedFileRouteIntentForCleanup(expected)) { + ownership.run(boundary); + return false; + } + const guard = () => ownership.run(() => { + boundary(); + const token = readServiceApiTokenState(); + if (token.kind !== "present" || token.fingerprint !== expected.tokenFingerprint) throw new Error("client_token_changed"); + }); + return withConfigDirHardeningSettled(getConfigDir(), async () => { + withClientLifecycleSync(() => { + guard(); + const receipt = readRouteIntentReceiptStrict(); + if (receipt?.linkId !== undefined) { + if (receipt.linkId !== expected.link!.linkId) throw new Error("client_route_owner_changed"); + // A partial stop must not leave the Home's previous successful apply proof current. + clearHomeRouteIntentRecord(); + } + }, options.lifecycleLockDeps); + const restored = await cleanupConnectedFileRouteIntent(expected, guard, options.lifecycleLockDeps); + guard(); + return restored; + }); +} diff --git a/src/client/stop-native-handoff.ts b/src/client/stop-native-handoff.ts new file mode 100644 index 00000000000..eab4b19b01a --- /dev/null +++ b/src/client/stop-native-handoff.ts @@ -0,0 +1,101 @@ +import { readdirSync } from "node:fs"; +import { createHash } from "node:crypto"; +import { join } from "node:path"; +import { isPendingTeardownAbandoned, isValidPendingTeardownReceipt, type OutstandingTeardown, type PendingTeardownReceipt } from "../config/pending-teardown"; +import { isAnyTeardownObligationFileName, pendingTeardownNonceFromFileName } from "../config/pending-teardown-names.mjs"; +import { getConfigDir } from "../config/paths"; +import { isLikelyOcxProcess, type ClientStopOwner, type RuntimePortState } from "../config/process-state"; +import { readBoundedRegularFileSync } from "../lib/bounded-file-read"; +import { isProcessAlive } from "../lib/process-control"; +import { readSyncRuntime } from "./sync-runtime"; +import { observeClientStopOwner, readClientStopProcessStart } from "./stop-teardown-owner"; + +export type LinkStopRuntime = Required>; +export type NativeTeardownDecision = "restore" | "defer" | "refuse"; +const host = (value: string) => value.trim().toLowerCase().replace(/^\[(.*)\]$/, "$1"); + +type TeardownSnapshot = { state: "valid"; path: string; bytes: Buffer; receipt: PendingTeardownReceipt }; +export type LinkInheritedTeardown = OutstandingTeardown & { bytes?: Buffer }; + +type NativeTeardownEvidence = + | TeardownSnapshot + | { state: "invalid"; nonce: string; detail: string } + | { state: "quarantined" } + | { state: "unscannable"; detail: string }; + +/** The signal and parent preflight use the same bounded, no-follow disk evidence. */ +export function readLinkNativeTeardownEvidence(): NativeTeardownEvidence[] { + let names: string[]; + try { names = readdirSync(getConfigDir()).filter(isAnyTeardownObligationFileName); } + catch (error) { return (error as NodeJS.ErrnoException).code === "ENOENT" ? [] : [{ state: "unscannable", detail: "the opencodex home could not be listed" }]; } + return names.map(name => { + const nonce = pendingTeardownNonceFromFileName(name); + if (!nonce) return { state: "quarantined" }; + try { + const path = join(getConfigDir(), name); + const bytes = readBoundedRegularFileSync(path, 4 * 1024); + const receipt: unknown = JSON.parse(bytes.toString("utf8")); + return isValidPendingTeardownReceipt(receipt, nonce) ? { state: "valid", path, bytes, receipt } : { state: "invalid", nonce, detail: "malformed receipt" }; + } catch { return { state: "invalid", nonce, detail: "receipt is not bounded regular JSON" }; } + }); +} + +/** Bind the original JSON bytes, which include each receipt's filename nonce. */ +export function inheritedTeardownDigest(snapshots: readonly Buffer[]): string | undefined { + if (snapshots.length === 0) return; + const hash = createHash("sha256"); + for (const bytes of [...snapshots].sort(Buffer.compare)) { + hash.update(bytes).update("\0"); + } + return hash.digest("hex"); +} + +/** Preserve the parent's recovery ownership rules and use one snapshot before/after stop. */ +export function readLinkInheritedTeardowns(): LinkInheritedTeardown[] { + return readLinkNativeTeardownEvidence().flatMap(read => { + if (read.state === "quarantined") return []; + if (read.state === "valid" && read.receipt.ownerStartTime) { + const { ownerPid: pid, ownerStartTime: startTime, nonce } = read.receipt; + const ours = pid === process.pid && readClientStopProcessStart(pid) === startTime; + if (ours) return []; + const status = observeClientStopOwner({ pid, startTime, nonce }); + if (status === "active") return []; + if (status === "unverified") return [{ state: "unscannable", detail: "the pending-teardown receipt's stop owner could not be verified" }]; + return [read]; + } + return isPendingTeardownAbandoned(read, pid => isProcessAlive(pid) && isLikelyOcxProcess(pid)) ? [read] : []; + }); +} + +/** Before a receipt is issued, the bound owner already excludes concurrent recycle. */ +function activeClientStopOwner(runtime: RuntimePortState): ClientStopOwner | undefined { + const owner = runtime.clientStopOwner; + if (runtime.clientStopping && runtime.clientStopRequested && owner && observeClientStopOwner(owner) === "active") return owner; +} + +/** Receipts alone never release a socket still named by native loopback routing. */ +export function linkNativeTeardownDecision(expected?: LinkStopRuntime): NativeTeardownDecision { + const evidence = readLinkNativeTeardownEvidence(); + if (evidence.length === 0) return "restore"; + try { + const runtime = readSyncRuntime(); + if (!expected || expected.pid !== process.pid || !runtime || runtime.pid !== expected.pid + || runtime.port !== expected.port || runtime.attestationSecret !== expected.attestationSecret + || host(runtime.hostname ?? "127.0.0.1") !== "127.0.0.1" + || runtime.clientStopping !== true || runtime.clientStopRequested !== true) return "refuse"; + // A malformed/guessed inherited obligation blocks the parent's restore too. + if (evidence.some(read => read.state === "invalid" || read.state === "unscannable" + || read.state === "valid" && read.receipt.endpointSource !== "exact")) return "refuse"; + const sameEndpoint = (read: TeardownSnapshot) => + read.receipt.endpoint.port === expected.port && host(read.receipt.endpoint.hostname) === "127.0.0.1"; + const owner = activeClientStopOwner(runtime); + const claim = owner && evidence.find(read => read.state === "valid" && sameEndpoint(read) + && read.receipt.nonce === owner.nonce && read.receipt.ownerPid === owner.pid + && read.receipt.ownerStartTime === owner.startTime); + const foreign = evidence.flatMap(read => read.state === "valid" && !sameEndpoint(read) ? [read.bytes] : []); + if (claim?.state === "valid" && inheritedTeardownDigest(foreign) === claim.receipt.inheritedTeardownDigest + && readBoundedRegularFileSync(claim.path, 4 * 1024).equals(claim.bytes) + && Bun.deepEquals(readSyncRuntime(), runtime, true)) return "defer"; + } catch { /* unreadable or replaced runtime evidence is not an active parent */ } + return "refuse"; +} diff --git a/src/client/stop-routing.ts b/src/client/stop-routing.ts index f3a5377e9ee..cb763a32168 100644 --- a/src/client/stop-routing.ts +++ b/src/client/stop-routing.ts @@ -6,14 +6,15 @@ import { journalOwner, JOURNAL_PATH } from "../codex/journal"; import { CODEX_CONFIG_PATH } from "../codex/paths"; import { siblingOfLivePort, siblingSkipMessage } from "../codex/sibling-start"; import type { OcxClientConnectionConfig } from "../types"; -import { pendingTeardownOutstanding } from "../config/pending-teardown"; import { stripGrokConfig } from "../grok/inject"; import { isDesktopSupervised } from "../lib/system-restart-contract"; import { serviceEnvironmentOwnedHere } from "../service/guards"; import { stopRestoreWriteGuard } from "./restore-ownership"; import { isLinkConnection } from "./state"; +import { linkNativeTeardownDecision, type LinkStopRuntime } from "./stop-native-handoff"; -export type LinkRoutingRestoreResult = { success: boolean; restored: boolean; message: string }; +export type LinkRoutingRestoreResult = { success: boolean; restored: boolean; message: string; retainListener?: true }; +type LinkRoutingRestoreOptions = { syncFenced: boolean; runtime?: LinkStopRuntime }; const resumeGuidance = "After starting the Child again, run `ocx sync --restart-codex` to restore its Home routing."; const refusal = (reason: string): LinkRoutingRestoreResult => ({ @@ -21,19 +22,52 @@ const refusal = (reason: string): LinkRoutingRestoreResult => ({ message: `Link Child Codex routing restore refused: ${reason}. No further writes; inspect remaining recovery evidence.`, }); +function preserveSupervisedRouting(): boolean { + return process.env.OCX_SERVICE === "1" || isDesktopSupervised(); +} + +/** Await file writers before releasing the socket, retaining it when safe cleanup is refused. */ +export async function restoreLinkClientRoutingBeforeExit( + expected: OcxClientConnectionConfig, options: LinkRoutingRestoreOptions, +): Promise { + expected = structuredClone(expected); + options = { ...options, ...(options.runtime ? { runtime: { ...options.runtime } } : {}) }; + const retainOnRefusal = (result: LinkRoutingRestoreResult): LinkRoutingRestoreResult => result.success ? result : { + ...result, retainListener: true, + message: `${result.message} The listener remains bound; repair the reported evidence, then retry ocx stop.`, + }; + // A parent receipt defers native Codex/Grok only. It never proves that a live owner + // will remove Link file routes before this socket closes, even when the receipt is valid. + if (siblingOfLivePort() !== null || !isLinkConnection(expected) || preserveSupervisedRouting()) { + return retainOnRefusal(restoreLinkClientRouting(expected, options)); + } + try { + const { restoreLinkFileRouting } = await import("./stop-file-routing"); + if (!options.syncFenced) throw new Error("the runtime sync fence could not be verified"); + await restoreLinkFileRouting(expected, { beforeWrite: () => { + if (preserveSupervisedRouting() || siblingOfLivePort() !== null) throw new Error("restart or teardown ownership changed"); + } }); + } catch (error) { + return { success: false, restored: false, retainListener: true, + message: `Link Child file routing restore refused: ${error instanceof Error ? error.message : "restoration failed"}. The listener remains bound; repair the client configuration or ownership evidence, then retry ocx stop.` }; + } + return retainOnRefusal(restoreLinkClientRouting(expected, options)); +} + /** Unsupervised signal cleanup; explicit parent stop and restart retain their own restoration. */ -export function restoreLinkClientRouting(expected: OcxClientConnectionConfig, options: { syncFenced: boolean }): LinkRoutingRestoreResult { +export function restoreLinkClientRouting(expected: OcxClientConnectionConfig, options: LinkRoutingRestoreOptions): LinkRoutingRestoreResult { if (siblingOfLivePort() !== null) return { success: true, restored: false, message: siblingSkipMessage() }; if (!isLinkConnection(expected)) { return { success: true, restored: false, message: "Hub connection-owned integrations preserved." }; } - const preserve = () => process.env.OCX_SERVICE === "1" || isDesktopSupervised() - || pendingTeardownOutstanding(); - if (preserve()) return { success: true, restored: false, message: "Supervised restart or pending teardown owns the client integrations." }; + if (preserveSupervisedRouting()) return { success: true, restored: false, message: "Supervised restart owns native Codex and managed Grok restoration." }; if (options?.syncFenced !== true) return refusal("the runtime sync fence could not be verified"); + const nativeTeardown = linkNativeTeardownDecision(options.runtime); + if (nativeTeardown === "defer") return { success: true, restored: false, message: "The active parent stop owns native Codex and managed Grok restoration." }; + if (nativeTeardown === "refuse") return refusal("pending native teardown has no verified active parent stop"); const guard = stopRestoreWriteGuard(expected); const withWriteGuard = (write: () => T): T => guard.run(() => { - if (preserve()) throw new Error("restart or teardown ownership changed"); + if (preserveSupervisedRouting() || linkNativeTeardownDecision(options.runtime) !== "restore") throw new Error("restart or teardown ownership changed"); const owner = journalOwner({ readOnly: true }); if (existsSync(JOURNAL_PATH) && (owner?.kind !== "client" || owner.apiKeyId !== expected.apiKeyId)) { throw new Error("the Codex journal belongs to another owner or is unverified"); diff --git a/src/client/stop-teardown-owner.ts b/src/client/stop-teardown-owner.ts new file mode 100644 index 00000000000..0b4cc3e2fa2 --- /dev/null +++ b/src/client/stop-teardown-owner.ts @@ -0,0 +1,176 @@ +import { readlinkSync, statSync } from "node:fs"; +import { isAbsolute, join, resolve } from "node:path"; +import { NODE_LAUNCH_PROOF_PREFIX } from "../cli/launcher-context"; +import { parseStopApproval } from "../cli/stop-approval"; +import { readProcessCommandLine, type ClientStopOwner } from "../config/process-state"; +import { readBoundedRegularFileSync } from "../lib/bounded-file-read"; +import { windowsProcessNative } from "../service/windows-process-native"; +import { readDarwinStopArgv, readDarwinStopCwd, readDarwinStopEnvironment, readDarwinStopStart } from "./stop-darwin-process"; + +const basename = (value: string) => value.toLowerCase().replace(/\\/g, "/").split("/").pop() ?? ""; + +/** Windows native argv rules: apostrophes are literal; only double quotes group arguments. */ +function windowsArgv(commandLine: string): string[] { + if (commandLine.length > 64 * 1024 || /[\0\r\n]/.test(commandLine)) return []; + const argv: string[] = []; + let offset = 0; + while (offset < commandLine.length) { + while (/[ \t]/.test(commandLine[offset] ?? "")) offset++; + if (offset === commandLine.length) break; + let value = "", quoted = false; + while (offset < commandLine.length) { + const character = commandLine[offset]!; + if (!quoted && /[ \t]/.test(character)) break; + // argv[0] is a pathname: its backslashes are literal, including before a closing quote. + if (argv.length > 0 && character === "\\") { + let count = 0; + while (commandLine[offset] === "\\") { count++; offset++; } + if (commandLine[offset] !== '"') { value += "\\".repeat(count); continue; } + value += "\\".repeat(Math.floor(count / 2)); + if (count % 2) { value += '"'; offset++; continue; } + } else if (character !== '"') { value += character; offset++; continue; } + if (argv.length > 0 && quoted && commandLine[offset + 1] === '"') { value += '"'; offset += 2; } + else { quoted = !quoted; offset++; } + } + argv.push(value); + } + return argv; +} + +/** Recognize the invocation that sets the native Child's explicit-stop fence, not any ocx. */ +export function isClientStopCommandLine(commandLine: string): boolean { + if (commandLine.length > 64 * 1024) return false; + return isClientStopArgv(windowsArgv(commandLine)); +} + +export function isClientStopArgv(argv: readonly string[]): boolean { + const command = ocxCommandIndex(argv); + return command !== undefined && argv[command] === "stop" && parseStopApproval(argv.slice(command + 1)).ok; +} + +export function isLegacyWindowsStartCommandLine(commandLine: string): boolean { + if (commandLine.length > 64 * 1024) return false; + const argv = windowsArgv(commandLine); + const command = ocxCommandIndex(argv); + return command !== undefined && argv[command] === "start"; +} + +function ocxCommandIndex(argv: readonly string[]): number | undefined { + let next = 1; + if (/^bun(?:\.exe)?$/.test(basename(argv[0] ?? ""))) { + if (argv[next] === "run") next++; + const script = argv[next++]?.replace(/\\/g, "/"); + if (!script || !/(?:^|\/)src\/cli(?:\/index)?\.ts$/i.test(script)) return; + } else if (!/^(?:ocx|opencodex)(?:\.exe)?$/.test(basename(argv[0] ?? ""))) return; + // npm inserts this one token before the command. Its spelling is not proof of + // launcher trust; the current runtime fence and same-user live owner are separate. + if (argv[next]?.startsWith(NODE_LAUNCH_PROOF_PREFIX)) { + if (!/^[A-Za-z0-9_-]{43}$/.test(argv[next]!.slice(NODE_LAUNCH_PROOF_PREFIX.length))) return; + next++; + } + return next; +} + +/** Creation identity and same-user ownership, sampled freshly for each destructive boundary. */ +export function readClientStopProcessStart(pid: number): string | undefined { + if (!Number.isInteger(pid) || pid <= 0 || pid > 0x7fffffff) return; + try { + if (process.platform === "darwin") return readDarwinStopStart(pid); + if (process.platform === "linux") { + const dir = `/proc/${pid}`; + if (statSync(dir).uid !== process.geteuid?.()) return; + const stat = readBoundedRegularFileSync(`${dir}/stat`, 4096).toString(); + const end = stat.lastIndexOf(") "); + const ticks = end < 0 ? undefined : stat.slice(end + 2).trim().split(/\s+/)[19]; + const boot = readBoundedRegularFileSync("/proc/sys/kernel/random/boot_id", 64).toString().trim(); + if (ticks && /^\d+$/.test(ticks) && /^[a-f0-9-]{36}$/.test(boot)) return `linux:${boot}:${ticks}`; + } + if (process.platform === "win32") { + const ticks = windowsProcessNative()?.sameUserStartTicks?.(pid); + if (typeof ticks === "bigint" && ticks > 0n && ticks <= 3155378975999999999n) return `win32:${ticks}`; + } + } catch { /* unreadable ownership cannot authorize a native restoration handoff */ } +} + +/** Read only the home settings needed to bind a legacy record to its invoking process. */ +export function readLegacyStopProcessHome(pid: number): string | undefined { + try { + const environment = process.platform === "linux" ? readBoundedRegularFileSync(`/proc/${pid}/environ`, 1024 * 1024) + : process.platform === "darwin" ? readDarwinStopEnvironment(pid) : undefined; + if (!environment?.length || environment[environment.length - 1] !== 0) return; + const setting = (name: string) => { + const prefix = Buffer.from(`${name}=`); + for (let offset = 0; offset < environment.length;) { + const end = environment.indexOf(0, offset); + if (end < 0) break; + if (offset + prefix.length <= end && environment.subarray(offset, offset + prefix.length).equals(prefix)) { + return new TextDecoder("utf-8", { fatal: true }).decode(environment.subarray(offset + prefix.length, end)).trim(); + } + offset = end + 1; + } + }; + const override = setting("OPENCODEX_HOME"); + if (override && isAbsolute(override)) return resolve(override); + if (override && override !== "~" && !override.startsWith("~/") && !override.startsWith("~\\")) { + const cwd = process.platform === "linux" + ? new TextDecoder("utf-8", { fatal: true }).decode(readlinkSync(`/proc/${pid}/cwd`, { encoding: "buffer" })) + : readDarwinStopCwd(pid); + // procfs appends this marker when the working directory has been removed. + if (cwd && isAbsolute(cwd) && !(process.platform === "linux" && cwd.endsWith(" (deleted)"))) return resolve(cwd, override); + return; + } + const home = setting("HOME"); + if (!home || !isAbsolute(home)) return; + if (!override) return join(home, ".opencodex"); + return override === "~" ? resolve(home) : join(home, override.slice(2)); + } catch { /* An unreadable home cannot bind a legacy record. */ } +} + +export type ClientStopOwnerStatus = "active" | "confirmed-stale" | "unverified"; + +const creationIdentity: Partial> = { + darwin: /^darwin:([1-9]\d{0,19}):(?:0|[1-9]\d{0,5})$/, + linux: /^linux:[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}:(0|[1-9]\d{0,19})$/, + win32: /^win32:([1-9]\d{0,18})$/, +}; + +function validCreationIdentity(value: unknown): boolean { + if (typeof value !== "string" || value.length > 80) return false; + const ticks = creationIdentity[process.platform]?.exec(value)?.[1]; + return ticks !== undefined && BigInt(ticks) <= (process.platform === "win32" ? 3155378975999999999n : 0xffffffffffffffffn); +} + +/** Bracket argv with creation/UID reads so a recycled PID cannot inherit the fence. */ +export function observeClientStopOwner({ pid, startTime, nonce }: ClientStopOwner): ClientStopOwnerStatus { + if (!Number.isInteger(pid) || pid <= 0 || pid > 0x7fffffff + || !validCreationIdentity(startTime) + || typeof nonce !== "string" || !/^[a-f0-9]{32}$/.test(nonce)) return "unverified"; + try { process.kill(pid, 0); } + catch (error) { return (error as NodeJS.ErrnoException).code === "ESRCH" ? "confirmed-stale" : "unverified"; } + const before = readClientStopProcessStart(pid); + if (before === undefined) return "unverified"; + if (before !== startTime) return "confirmed-stale"; + if (pid === process.pid) return "unverified"; + try { + let stop: boolean; + if (process.platform === "linux") { + // /proc exposes argv, not a quoted command line. Preserve NUL boundaries: + // install paths and approval values can legitimately contain spaces. + const raw = new TextDecoder("utf8", { fatal: true }).decode(readBoundedRegularFileSync(`/proc/${pid}/cmdline`, 64 * 1024)); + if (raw.length <= 1 || !raw.endsWith("\0")) return "unverified"; + stop = isClientStopArgv(raw.slice(0, -1).split("\0")); + } else if (process.platform === "darwin") { + const argv = readDarwinStopArgv(pid); + if (!argv?.length) return "unverified"; + stop = isClientStopArgv(argv); + } else { + const commandLine = readProcessCommandLine(pid); + if (!commandLine?.trim() || commandLine.length > 64 * 1024) return "unverified"; + stop = isClientStopCommandLine(commandLine); + } + const after = readClientStopProcessStart(pid); + if (after === undefined) return "unverified"; + if (after !== startTime) return "confirmed-stale"; + return stop ? "active" : "unverified"; + } catch { return "unverified"; } +} diff --git a/src/client/sync-runtime.ts b/src/client/sync-runtime.ts index c11d93824fe..8aca45421ec 100644 --- a/src/client/sync-runtime.ts +++ b/src/client/sync-runtime.ts @@ -1,7 +1,7 @@ /** Cross-process admission for Link sync while its local runtime shuts down. */ import { lstatSync } from "node:fs"; import { ConfigMutationLockError, withConfigMutationLockSync } from "../config"; -import { getRuntimePortPath, isValidRuntimePortState, writeRuntimePort, type RuntimePortState } from "../config/process-state"; +import { getRuntimePortPath, isValidRuntimePortState, writeRuntimePort, type ClientStopOwner, type RuntimePortState } from "../config/process-state"; import { readBoundedRegularFileSync } from "../lib/bounded-file-read"; export class ClientSyncRuntimeError extends Error { @@ -10,7 +10,7 @@ export class ClientSyncRuntimeError extends Error { } } -function readSyncRuntime(): RuntimePortState | null { +export function readSyncRuntime(): RuntimePortState | null { const path = getRuntimePortPath(); try { lstatSync(path); } catch (error) { @@ -43,14 +43,33 @@ export function assertRouteIntentPort(port: number): void { } /** The same C transaction excludes every sync commit; never mark a replacement runtime. */ -export function markClientRuntimeStopping(expected: Required>): void { +export function markClientRuntimeStopping( + expected: Required>, stopOwner?: ClientStopOwner, +): void { withConfigMutationLockSync(() => { const current = readSyncRuntime(); if (!current || current.pid !== expected.pid || current.port !== expected.port || current.attestationSecret !== expected.attestationSecret) { throw new ClientSyncRuntimeError("client_runtime_changed"); } - if (!current.clientStopping) writeRuntimePort({ ...current, clientStopping: true }); + if (!current.clientStopping || (stopOwner && !Bun.deepEquals(current.clientStopOwner, stopOwner, true))) { + writeRuntimePort({ ...current, clientStopping: true, ...(stopOwner ? { clientStopRequested: true, clientStopOwner: stopOwner } : {}) }); + } + }); +} + +/** Finish only this parent's exact-runtime stop; sync stays fenced until its process exits. */ +export function finishClientRuntimeStop( + expected: Required>, stopOwner: ClientStopOwner, +): void { + withConfigMutationLockSync(() => { + const current = readSyncRuntime(); + if (current?.pid === expected.pid && current.port === expected.port + && current.attestationSecret === expected.attestationSecret && current.clientStopRequested === true + && Bun.deepEquals(current.clientStopOwner, stopOwner, true)) { + const { clientStopOwner: _finished, ...retained } = current; + writeRuntimePort({ ...retained, clientStopRequested: false }); + } }); } diff --git a/src/config/pending-teardown.ts b/src/config/pending-teardown.ts index 60a6e17814a..d1bff958b1f 100644 --- a/src/config/pending-teardown.ts +++ b/src/config/pending-teardown.ts @@ -4,6 +4,7 @@ import { join } from "node:path"; import { assertNotRealHomeUnderTest } from "../lib/test-home-guard"; import { atomicWriteFile } from "./atomic-write"; import { getConfigDir } from "./paths"; +import type { ClientStopOwner } from "./process-state"; /** * Ownership receipt for a deferred shared teardown (#3008). @@ -30,6 +31,10 @@ import { getConfigDir } from "./paths"; export type PendingTeardownReceipt = { /** Process that accepted the obligation, so a live owner is distinguishable from a dead one. */ ownerPid: number; + /** Optional process incarnation on claims bound to an active Link stop fence. */ + ownerStartTime?: string; + /** Exact foreign-endpoint receipt snapshot verified by this Link stop before signaling. */ + inheritedTeardownDigest?: string; /** Identity of this claim; also its filename, which is what makes a clear a single-syscall delete. */ nonce: string; /** ISO timestamp, for diagnostics only; recovery is decided by liveness, not by age. */ @@ -116,7 +121,7 @@ export function pendingTeardownPathFor(nonce: string): string { return join(getConfigDir(), `${PREFIX}${nonce}${SUFFIX}`); } -function isReceipt(value: unknown, nonce: string): value is PendingTeardownReceipt { +export function isValidPendingTeardownReceipt(value: unknown, nonce: string): value is PendingTeardownReceipt { if (!value || typeof value !== "object") return false; const receipt = value as Record; const endpoint = receipt.endpoint as Record | undefined; @@ -132,6 +137,10 @@ function isReceipt(value: unknown, nonce: string): value is PendingTeardownRecei // The body must agree with the name: a receipt whose nonce was edited to name a // different claim would let a request authorize a deferral it does not own. && receipt.nonce === nonce + && (receipt.ownerStartTime === undefined || (typeof receipt.ownerStartTime === "string" + && receipt.ownerStartTime.length > 0 && receipt.ownerStartTime.length <= 80)) + && (receipt.inheritedTeardownDigest === undefined || (typeof receipt.inheritedTeardownDigest === "string" + && /^[a-f0-9]{64}$/.test(receipt.inheritedTeardownDigest))) && typeof receipt.createdAt === "string" && (receipt.endpointSource === "exact" || receipt.endpointSource === "guessed") && (receipt.handover === undefined || receipt.handover === "update-restart") @@ -145,12 +154,19 @@ export function claimPendingTeardown( ownerPid: number = process.pid, handover?: "update-restart", partA?: PendingTeardownPartA | null, + stopOwner?: ClientStopOwner, + inheritedTeardownDigest?: string, ): PendingTeardownReceipt { const dir = getConfigDir(); assertNotRealHomeUnderTest(dir); - const nonce = randomBytes(16).toString("hex"); + if (stopOwner && (stopOwner.pid !== ownerPid || endpointSource !== "exact" || !/^[a-f0-9]{32}$/.test(stopOwner.nonce))) { + throw new Error("invalid Link stop receipt owner"); + } + const nonce = stopOwner?.nonce ?? randomBytes(16).toString("hex"); const receipt: PendingTeardownReceipt = { ownerPid, nonce, createdAt: new Date().toISOString(), endpoint, endpointSource, + ...(stopOwner ? { ownerStartTime: stopOwner.startTime } : {}), + ...(inheritedTeardownDigest ? { inheritedTeardownDigest } : {}), ...(handover ? { handover } : {}), ...(partA ? { partA } : {}), }; @@ -205,7 +221,7 @@ export function readPendingTeardown(nonce: string): PendingTeardownRead { } try { const parsed: unknown = JSON.parse(raw); - if (isReceipt(parsed, nonce)) return { state: "valid", receipt: parsed }; + if (isValidPendingTeardownReceipt(parsed, nonce)) return { state: "valid", receipt: parsed }; const digest = createHash("sha256").update(raw).digest("hex").slice(0, 12); return { state: "invalid", nonce, detail: `malformed receipt (sha256 ${digest})` }; } catch { diff --git a/src/config/process-state.ts b/src/config/process-state.ts index cbcc32c0ab0..8daebce35f1 100644 --- a/src/config/process-state.ts +++ b/src/config/process-state.ts @@ -148,16 +148,27 @@ export function writePid(pid: number): void { atomicWriteFile(getPidPath(), String(pid)); } +export type ClientStopOwner = { nonce: string; pid: number; startTime: string }; + export type RuntimePortState = { pid: number; port: number; hostname?: string; + role?: string; + /** OS creation identity of a standalone owner, when available. */ + startTime?: string; /** Absolute relaunch prefix written by runtimes that identify their serving install. */ command?: string[]; /** Per-process proof key; protected by the config directory and never served. */ attestationSecret?: string; /** A Link runtime is draining; new and in-flight sync commits must stand down. */ clientStopping?: true; + /** Parent stop: true while active, false after it finishes with this runtime still fenced. */ + clientStopRequested?: boolean; + /** This stop's exact deferred-teardown nonce and OS process incarnation. */ + clientStopOwner?: ClientStopOwner; + /** Stable serving Link fingerprint, or null for a native Hub client. */ + clientLinkOwner?: string | null; /** * Fresh for every publication of a client runtime, including the rollback of a failed restart. * A sync compares the whole record before each commit, so one captured before a restart cannot @@ -202,6 +213,7 @@ export function isValidRuntimePortState(value: unknown): value is RuntimePortSta && hostnameOk && attestationOk && (state.clientStopping === undefined || state.clientStopping === true) + && (state.clientStopRequested === undefined || (typeof state.clientStopRequested === "boolean" && state.clientStopping === true)) && (state.servingGeneration === undefined || (typeof state.servingGeneration === "string" && state.servingGeneration.length <= 64)) && (state.restartOwner === undefined || (typeof state.restartOwner === "string" && state.restartOwner.length <= 64)) && siblingOk; diff --git a/src/integrations/route-intent-disconnect.ts b/src/integrations/route-intent-disconnect.ts index bd4fa98f2ba..11abf3aafbb 100644 --- a/src/integrations/route-intent-disconnect.ts +++ b/src/integrations/route-intent-disconnect.ts @@ -1,4 +1,4 @@ -/** File clients drain before disconnect removes its connection and service credential. */ +/** Receipt-bound file cleanup shared by stop and disconnect. */ import { loadConfig } from "../config"; import { lstatSync } from "node:fs"; import { readClientConnectionState, sameClientConnectionOwner } from "../client/state"; @@ -8,6 +8,7 @@ import { readServiceApiTokenState } from "../lib/service-secrets"; import { readLocalRouteIntentOff, readRouteIntentReceiptStrict, readRouteIntentUnappliedProof } from "./route-intent-state"; import { homeRouteIntentPath } from "../client/link-home"; import type { OcxClientConnectionConfig } from "../types"; +import type { RouteIntentReceipt } from "./route-intent-contract"; /** Droid's empty-roster contribution has no selectors, so its generic classifier cannot prove absence. */ async function droidRoutingAbsent(port: number): Promise { @@ -33,9 +34,8 @@ async function droidRoutingAbsent(port: number): Promise { } catch { return false; } } -export async function cleanupConnectedRouteIntent( - connection: OcxClientConnectionConfig, expected: DesktopDisconnectReceipt, lifecycleLockDeps?: ClientLifecycleLockDeps, recoverConflicts = false, -): Promise { +/** Read-only ownership/absence proof. Callers still fence every subsequent file write. */ +export async function readConnectedFileRouteIntentForCleanup(connection: OcxClientConnectionConfig): Promise { const receipt = readRouteIntentReceiptStrict(); if (!receipt) { let homeReceiptPresent = false; @@ -63,28 +63,25 @@ export async function cleanupConnectedRouteIntent( && (!isIntegrationClientId(id) || readIntegrationState({ clientId: id, config, port: config.port, models: [], store }).state !== "absent")); const droidUnproved = connection.selectedClients.includes("droid") && !standalone("droid") && !await droidRoutingAbsent(config.port); if (homeReceiptPresent || owned || unproved || droidUnproved) { - throw new Error("Route intent cleanup receipt is missing; preserve the connection and repair its route ownership evidence before disconnect"); + throw new Error("Route intent cleanup receipt is missing; preserve the connection and repair its route ownership evidence before retrying cleanup"); } } - return; + return null; } // A valid unbound receipt is standalone Home state, not evidence of a Child apply. - if (receipt.linkId === undefined) return; - if (!connection.link || receipt.linkId !== connection.link.linkId) throw new Error("Route intent cleanup receipt belongs to another context; preserve it before disconnect"); - const guard = () => { - const pending = readDesktopDisconnectReceipt(); - const current = readClientConnectionState(); - const token = readServiceApiTokenState(); - if (pending.kind !== "valid" || JSON.stringify(pending.value) !== JSON.stringify(expected) - || current.kind !== "connected" || !sameClientConnectionOwner(current.value, connection) - || current.value.pendingOperation || token.kind !== "present" || token.fingerprint !== connection.tokenFingerprint) { - throw new Error("client_disconnect_owner_changed"); - } - }; + if (receipt.linkId === undefined) return null; + if (!connection.link || receipt.linkId !== connection.link.linkId) throw new Error("Route intent cleanup receipt belongs to another context; preserve it before retrying cleanup"); + return receipt; +} + +/** Shared file-only cleanup; the caller supplies its stop or disconnect ownership fence. */ +export async function cleanupConnectedFileRouteIntent( + connection: OcxClientConnectionConfig, guard: () => void, lifecycleLockDeps?: ClientLifecycleLockDeps, recoverConflicts = false, +): Promise { + const receipt = await readConnectedFileRouteIntentForCleanup(connection); + if (!receipt || !connection.link) return false; const local = loadConfig(); const { cleanupRouteIntent } = await import("./route-intent"); - const { stripGrokConfig } = await import("../grok/inject"); - const { injectClaudeAgentDefs } = await import("../claude/agents-inject"); const config = { ...local, hostname: "127.0.0.1", unauthenticatedLoopbackListener: undefined }; // Integrations the Child owned before this link come back instead of being removed; a local // opt-out is the person's own later choice and wins. @@ -96,7 +93,26 @@ export async function cleanupConnectedRouteIntent( const outcomes = await cleanupRouteIntent({ config, linkId: connection.link.linkId, document: receipt.document, models: receipt.models ?? [], beforeWrite: guard, recoverConflicts, withReceiptWrite: write => withClientLifecycleSync(() => { guard(); write(); }, lifecycleLockDeps), withFileWrites: work => withClientLifecycle(work, lifecycleLockDeps) }, standalone); - if (outcomes.some(row => row.outcome !== "current")) throw new Error("Route intent cleanup was partial; ownership and disconnect receipts retained. Repair the conflicting client and rerun ocx disconnect."); + if (outcomes.some(row => row.outcome !== "current")) throw new Error("Route intent cleanup was partial; ownership and recovery receipts retained. Repair the conflicting client and retry cleanup."); + return true; +} + +export async function cleanupConnectedRouteIntent( + connection: OcxClientConnectionConfig, expected: DesktopDisconnectReceipt, lifecycleLockDeps?: ClientLifecycleLockDeps, recoverConflicts = false, +): Promise { + const guard = () => { + const pending = readDesktopDisconnectReceipt(); + const current = readClientConnectionState(); + const token = readServiceApiTokenState(); + if (pending.kind !== "valid" || JSON.stringify(pending.value) !== JSON.stringify(expected) + || current.kind !== "connected" || !sameClientConnectionOwner(current.value, connection) + || current.value.pendingOperation || token.kind !== "present" || token.fingerprint !== connection.tokenFingerprint) { + throw new Error("client_disconnect_owner_changed"); + } + }; + if (!await cleanupConnectedFileRouteIntent(connection, guard, lifecycleLockDeps, recoverConflicts)) return; + const { stripGrokConfig } = await import("../grok/inject"); + const { injectClaudeAgentDefs } = await import("../claude/agents-inject"); withClientLifecycleSync(() => { guard(); const grok = stripGrokConfig(); diff --git a/src/lib/process-control.ts b/src/lib/process-control.ts index 8270a447c9d..79844643fbc 100644 --- a/src/lib/process-control.ts +++ b/src/lib/process-control.ts @@ -421,6 +421,7 @@ async function waitForStoppedPort( // Only the process we just stopped — never kill a newly started twin proxy. killOcxHolders: mayKill && !!(stoppedPid && stoppedPid > 0), onlyKillPids: mayKill && stoppedPid && stoppedPid > 0 ? [stoppedPid] : [], + ...(io.forceKill ? { killFn: io.forceKill } : io.mayTerminate ? { killFn: (pid: number) => killProxy(pid, io.mayTerminate) } : {}), }); } catch { /* best-effort — callers that need a hard guarantee reclaim again before bind */ diff --git a/src/server/port-reclaim.ts b/src/server/port-reclaim.ts index b436fdd738c..58da4700651 100644 --- a/src/server/port-reclaim.ts +++ b/src/server/port-reclaim.ts @@ -8,9 +8,11 @@ */ import { execFile, execFileSync } from "node:child_process"; import { readFile, readdir, readlink } from "node:fs/promises"; +import { join } from "node:path"; import { promisify } from "node:util"; import { verifyPidIdentity } from "../config/process-state"; import { isProcessAlive, killProxy } from "../lib/process-control"; +import { resolveTrustedWindowsSystemDirectory } from "../lib/windows-elevation"; import { isPortAvailable, type WaitForPortOptions } from "./ports"; import { dropWindowsTcpRowsForLocalPort } from "./windows-tcp-drop"; @@ -360,6 +362,30 @@ export function scanListenPidsForAddress(port: number, address = "127.0.0.1"): L return { ok: true, pids: [...pids] }; } +/** Bind a stamp-less runtime to a unique listener at its recorded address and port. */ +export async function ownsLegacyStopBind(port: number, pid: number, address: string): Promise { + const want = bareListenAddress(address); + const wildcard = want === "0.0.0.0" || want === "::"; + if (process.platform === "linux" && wildcard) { + return (await inspectListener(port, pid, {}, want)).kind === "match"; + } + try { + const scan = process.platform === "win32" + ? { ok: true as const, listeners: parseListenEntriesFromNetstat(execFileSync( + join(resolveTrustedWindowsSystemDirectory(), "netstat.exe"), ["-ano"], { + encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: OWNER_LOOKUP_TIMEOUT_MS, + maxBuffer: MAX_PROC_NET_BYTES, windowsHide: true, + }), port) } + : scanListenEntries(port); + if (!scan.ok) return false; + const pids = new Set(scan.listeners.filter(entry => entry.address === want || (wildcard && entry.address === "*")) + .map(entry => entry.pid)); + return pids.size === 1 && pids.has(pid); + } catch { + return false; + } +} + /** Best-effort PIDs currently LISTENing on `port`. Empty on probe failure. */ export function listListenPids(port: number): number[] { const scan = scanListenPids(port); @@ -373,12 +399,21 @@ const MAX_PROCESS_FDS = 4_096; /** The exact IPv4 listener the Child relay contacts; ::1 and wildcard binds are not proof. */ export function parseProcLoopbackListenInodes(tcp: string, tcp6: string, port: number): string[] { + return parseProcListenInodes(tcp, tcp6, port, "127.0.0.1"); +} + +type ProcBind = "127.0.0.1" | "0.0.0.0" | "::"; + +function parseProcListenInodes(tcp: string, tcp6: string, port: number, bind: ProcBind): string[] { const wantedPort = port.toString(16).toUpperCase().padStart(4, "0"); const inodes = new Set(); + // Linux reports IPv4-mapped addresses in native word order. for (const [content, wantedAddress] of [ - [tcp, "0100007F"], - [tcp6, "0000000000000000FFFF00000100007F"], // ::ffff:127.0.0.1 in proc word order + [tcp, bind === "127.0.0.1" ? "0100007F" : bind === "0.0.0.0" ? "00000000" : ""], + [tcp6, bind === "127.0.0.1" ? "0000000000000000FFFF00000100007F" + : bind === "::" ? "00000000000000000000000000000000" : ""], ] as const) { + if (!wantedAddress) continue; for (const line of content.split(/\r?\n/).slice(1)) { const fields = line.trim().split(/\s+/); const [address, hexPort] = (fields[1] ?? "").toUpperCase().split(":"); @@ -432,10 +467,19 @@ export interface LoopbackOwnerLookupIo { * Only match proves the expected PID; mismatch, inspection failure and timeout remain distinct. * elapsedMs uses a monotonic clock by default, and no raw OS output is returned. */ -export async function inspectIpv4LoopbackListener( +export function inspectIpv4LoopbackListener( port: number, expectedPid: number, io: LoopbackOwnerLookupIo = {}, +): Promise { + return inspectListener(port, expectedPid, io, "127.0.0.1"); +} + +async function inspectListener( + port: number, + expectedPid: number, + io: LoopbackOwnerLookupIo, + procBind: ProcBind, ): Promise { const now = io.nowMs ?? (() => performance.now()); const startedAt = now(); @@ -453,7 +497,7 @@ export async function inspectIpv4LoopbackListener( throw error; }); if (tcp.length > MAX_PROC_NET_BYTES || tcp6.length > MAX_PROC_NET_BYTES) return false; - const inodes = parseProcLoopbackListenInodes(tcp, tcp6, port); + const inodes = parseProcListenInodes(tcp, tcp6, port, procBind); if (inodes.length !== 1) return false; const fdDir = `/proc/${expectedPid}/fd`; const fds = await (io.listFds ?? readdir)(fdDir); diff --git a/src/service/health-sentinel-linux.ts b/src/service/health-sentinel-linux.ts index 6c29f82de69..93f4066fe70 100644 --- a/src/service/health-sentinel-linux.ts +++ b/src/service/health-sentinel-linux.ts @@ -16,7 +16,7 @@ export type PidfdSyscalls = { close(fd: number): void; dispose(): void; }; -export type ParentPidfd = { terminate(): TerminateResult; close(): void }; +export type ParentPidfd = { terminate(signal?: 15 | 9): TerminateResult; close(): void }; export type ParentPidfdResult = | { kind: "bound"; handle: ParentPidfd } | { kind: "unsupported"; reason: string } @@ -57,7 +57,16 @@ export function openParentPidfd( isParent: () => boolean, options: { arch?: string; load?: () => PidfdSyscalls } = {}, ): ParentPidfdResult { - if (!isParent()) return { kind: "refused", reason: "the sentinel is not the watched process's child" }; + return openVerifiedPidfd(pid, isParent, options); +} + +/** The verifier confirms the same PID ownership on both sides of pidfd acquisition. */ +export function openVerifiedPidfd( + pid: number, + verify: () => boolean, + options: { arch?: string; load?: () => PidfdSyscalls } = {}, +): ParentPidfdResult { + if (!verify()) return { kind: "refused", reason: "PID ownership could not be verified" }; const arch = options.arch ?? process.arch; if (arch !== "x64" && arch !== "arm64") return { kind: "unsupported", reason: `pidfd syscall ABI is unsupported on ${arch}` }; let api: PidfdSyscalls; @@ -81,7 +90,7 @@ export function openParentPidfd( : { kind: "refused", reason: `pidfd_open failed (errno ${opened.errno})` }; } fd = opened.value; - if (!isParent()) return refuse("the watched parent exited during pidfd acquisition"); + if (!verify()) return refuse("PID ownership changed during pidfd acquisition"); // Check both syscall support and permission before arming, without sending a signal. const probe = api.signal(fd, 0); if (probe.value < 0) { @@ -90,18 +99,18 @@ export function openParentPidfd( ? { kind: "unsupported", reason: "pidfd_send_signal is unsupported by this kernel" } : { kind: "refused", reason: `pidfd signal check failed (errno ${probe.errno})` }; } - if (!isParent()) return refuse("the watched parent exited during pidfd verification"); + if (!verify()) return refuse("PID ownership changed during pidfd verification"); return { kind: "bound", handle: { close, - terminate: () => { + terminate: (signal = 9) => { if (closed || signalled) return "not_target"; // A throwing binding must settle the recorded intent as "failed", like process.kill does. let sent: CallResult; - try { sent = api.signal(fd!, 9); } catch { return "failed"; } + try { sent = api.signal(fd!, signal); } catch { return "failed"; } if (sent.value < 0) return sent.errno === ESRCH ? "not_target" : "failed"; - signalled = true; + if (signal === 9) signalled = true; return "terminated"; }, }, diff --git a/src/service/systemd.ts b/src/service/systemd.ts index 58a07343a18..65d0361b71e 100644 --- a/src/service/systemd.ts +++ b/src/service/systemd.ts @@ -1,4 +1,4 @@ -import { readFileSync } from "node:fs"; +import { lstatSync, readFileSync } from "node:fs"; import { execFileSync, execSync } from "node:child_process"; import { existsSync, mkdirSync, unlinkSync } from "node:fs"; import { homedir } from "node:os"; @@ -10,7 +10,7 @@ import { systemdProperty } from "../service-manager-probe"; import { writeServiceApiTokenFile, sh } from "./guards"; import { shellQuote, buildServiceShellCommand, buildServiceLauncherShellCommand, resolvedProxyEnv, pinnedServiceHomeShellAssignments } from "./definition"; import type { ServiceInstallCleanupOps } from "./orchestration"; -import { SERVICE_MANAGED_ENV, TASK, cliEntry, filterTransientServicePath, stableLauncherEntry, logPath, serviceStatePath, currentCodexSqliteHomeAbsolute, currentCodexHome, currentOpenCodexHome, writeServiceInstallState } from "./state"; +import { SERVICE_MANAGED_ENV, TASK, cliEntry, filterTransientServicePath, stableLauncherEntry, logPath, serviceStatePath, currentCodexSqliteHomeAbsolute, currentCodexHome, currentOpenCodexHome, serviceStatePaths, writeServiceInstallState } from "./state"; import { writeServiceDefinitionFile } from "./windows-ops"; /** The `--port ` baked into the installed systemd user unit. Linux only. */ @@ -65,6 +65,15 @@ export function unitPath(): string { return join(unitDir(), `${TASK}.service`); } +/** Offline proof that OpenCodex has no recorded service installation or installer unit. */ +export function systemdInstallationAbsent(platform: NodeJS.Platform = process.platform): boolean { + if (platform !== "linux") return false; + return [unitPath(), ...serviceStatePaths()].every(path => { + try { lstatSync(path); return false; } + catch (error) { return (error as NodeJS.ErrnoException).code === "ENOENT"; } + }); +} + export function buildUnit( proxyEnv: { name: string; value: string }[] = resolvedProxyEnv(), deps: { launcher?: string | null; runtime?: DurableBunRuntime } = {}, diff --git a/src/service/windows-process-native.ts b/src/service/windows-process-native.ts index 1db77cf0b66..3d90f3f9791 100644 --- a/src/service/windows-process-native.ts +++ b/src/service/windows-process-native.ts @@ -37,6 +37,8 @@ const SERVICE_RUNNING = 4; const SERVICE_STATUS_PROCESS_BYTES = 36; const SERVICE_STATUS_STATE_OFFSET = 4; const SERVICE_STATUS_PID_OFFSET = 28; +/** 100 ns intervals between 0001-01-01 (.NET) and 1601-01-01 (FILETIME). */ +const FILETIME_DOTNET_EPOCH = 504_911_232_000_000_000n; /** 100 ns intervals between 1601-01-01 and 1970-01-01. */ const FILETIME_UNIX_EPOCH = 116_444_736_000_000_000n; const TERMINATE_EXIT_CODE = 1; @@ -61,7 +63,9 @@ export type WindowsProcessWatch = export interface WindowsProcessNativeApi { /** Creation time in epoch ms (FILETIME truncated to ms), or null when unreadable. */ creationTime(pid: number): number | null; - terminate(pid: number, boundStartTime: number): WindowsTerminateResult; + /** Same-user, live creation identity in CIM-compatible .NET ticks, read without a subprocess. */ + sameUserStartTicks?(pid: number): bigint | null; + terminate(pid: number, boundStartTime: number | bigint): WindowsTerminateResult; openWatch(pid: number, boundStartTime: number): WindowsProcessWatch; /** PID of the running Task Scheduler service host, or null when it cannot be read. */ scheduleServicePid(): number | null; @@ -74,6 +78,29 @@ export function fileTimeToEpochMs(fileTime: bigint): number | null { return ms > BigInt(Number.MAX_SAFE_INTEGER) ? null : Number(ms); } +/** Keep owner, lifetime and creation evidence on one process handle; never cache a PID proof. */ +export function readSameUserWindowsStart(pid: number, io: { + open: (pid: number) => number | bigint; + close: (handle: number | bigint) => void; + fileTime: (handle: number | bigint) => bigint | null; + exited: (handle: number | bigint) => boolean | null; + ownerSid: (handle: number | bigint) => string; + currentSid: () => string; +}): bigint | null { + if (!Number.isInteger(pid) || pid <= 0 || pid > 0x7fffffff) return null; + const handle = io.open(pid); + if (!handle) return null; + try { + const created = io.fileTime(handle); + if (created === null || created <= FILETIME_UNIX_EPOCH || io.exited(handle) !== false) return null; + const owner = io.ownerSid(handle); + if (!/^S-1-\d+(?:-\d+)+$/.test(owner) || owner !== io.currentSid() || io.exited(handle) !== false) return null; + // Preserve the creation identity already stored by the CIM-based stop owner protocol. + return (created + FILETIME_DOTNET_EPOCH) / 10n * 10n; + } catch { return null; } + finally { io.close(handle); } +} + /** Decode SERVICE_STATUS_PROCESS: the PID only while the service reports RUNNING. */ export function decodeServiceStatusProcess(buffer: Uint8Array): number | null { if (buffer.byteLength < SERVICE_STATUS_PROCESS_BYTES) return null; @@ -160,11 +187,15 @@ function loadNativeApi(): WindowsProcessNativeApi | null { closeHandle: token => { k.CloseHandle(token); }, }); - const handleCreationTime = (handle: Handle): number | null => { + const handleFileTime = (handle: Handle): bigint | null => { const times = new BigUint64Array(4); const base = ptr(times); const ok = k.GetProcessTimes(handle, base, base + 8, base + 16, base + 24); - return ok ? fileTimeToEpochMs(times[0]!) : null; + return ok && times[0]! > FILETIME_UNIX_EPOCH ? times[0]! : null; + }; + const handleCreationTime = (handle: Handle): number | null => { + const ticks = handleFileTime(handle); + return ticks === null ? null : fileTimeToEpochMs(ticks); }; // true = exited, false = running, null = unreadable. const handleExited = (handle: Handle): boolean | null => { @@ -192,12 +223,25 @@ function loadNativeApi(): WindowsProcessNativeApi | null { k.CloseHandle(handle); } }, + sameUserStartTicks(pid) { + return readSameUserWindowsStart(pid, { + open: target => k.OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION | SYNCHRONIZE, 0, target), + close: handle => { k.CloseHandle(handle); }, + fileTime: handleFileTime, + exited: handleExited, + ownerSid: handleUserSid, + currentSid: () => handleUserSid(k.GetCurrentProcess()), + }); + }, terminate(pid, boundStartTime) { const handle = k.OpenProcess(PROCESS_TERMINATE | PROCESS_QUERY_LIMITED_INFORMATION | SYNCHRONIZE, 0, pid); if (!handle) return { status: openFailure() }; try { - const created = handleCreationTime(handle); - if (created === null) return { status: "unavailable" }; + const fileTime = handleFileTime(handle); + if (fileTime === null) return { status: "unavailable" }; + // Stop-owner identities retain .NET ticks at microsecond precision. + const created = typeof boundStartTime === "number" ? fileTimeToEpochMs(fileTime) + : (fileTime + FILETIME_DOTNET_EPOCH) / 10n * 10n; if (created !== boundStartTime) return { status: "reused" }; const before = handleExited(handle); if (before === true) return { status: "gone" }; diff --git a/structure/INDEX.md b/structure/INDEX.md index 4bc97ab408f..448a257d4aa 100644 --- a/structure/INDEX.md +++ b/structure/INDEX.md @@ -285,7 +285,9 @@ A source area can be described by more than one doc, because these docs are orga | `src/client/link-home.ts` | [`remote-link.md`](remote-link.md) | | `src/client/link-management-relay.ts` | [`usage-client-attribution.md`](usage-client-attribution.md) | | `src/client/link-parity-reporter.ts` | [`remote-link.md`](remote-link.md) | +| `src/client/runtime-recycle.ts` | [`remote-link.md`](remote-link.md) | | `src/client/runtime-restart.ts` | [`remote-link.md`](remote-link.md) | +| `src/client/runtime-rollback.ts` | [`remote-link.md`](remote-link.md) | | `src/clients/` | [`clients/integrations.md`](clients/integrations.md)
[`clients/qoder.md`](clients/qoder.md)
[`clients/client-support-matrix.md`](clients/client-support-matrix.md)
[`clients/t3code.md`](clients/t3code.md) | | `src/clients/config-export.ts` | [`transports/timeouts.md`](transports/timeouts.md)
[`clients/export-model-names.md`](clients/export-model-names.md)
[`clients/omo-export-dialect.md`](clients/omo-export-dialect.md) | | `src/clients/config-export/` | [`clients/export-model-names.md`](clients/export-model-names.md) | diff --git a/structure/clients/integrations.md b/structure/clients/integrations.md index 4e8932684c9..6c7c0b0bae5 100644 --- a/structure/clients/integrations.md +++ b/structure/clients/integrations.md @@ -27,7 +27,7 @@ parsing and ownership rules below. | `src/integrations/mutation-plan.ts` | The shared observation both a preview and a mutation read, and the value-free plan an operator confirms. It owns no IO of its own, takes no lock, and must never import `writer.ts`. | | `src/integrations/store.ts` / `journal.ts` | One-root persistence for ownership records, operation history, snapshots, and retention maintenance. | -Native route materialization resolves Codex and Desktop paths from the device process environment. Under an effective first-party mode, Desktop enabled intent is current without a write and disabled intent is a conflict naming the mode switch; Home gateway file and marker writes share picker/lifecycle/config exclusion with mode switches. Offline first-party CLI apply retains one cross-process lifecycle lease through settings, gateway removal, mode save and rollback; nested writers validate and reuse it. Connected off uses remote-store ownership. Explicit takeover of an edited, selected, settled remote-owned projection snapshots its current JSON privately before the ordinary pending transaction, retaining owner, token, path and selection checks. Approved external Codex providers retain the existing injector's URL routing contract. Aside off with no strict ownership record requires no account manifest. Owned legacy/profile records must still match a registered profile; missing registration or unreadable ownership remains an incomplete apply. Missing common receipts allow Link disconnect only when ownership and selected file-config absence prove no materialization occurred; Droid rows are inspected independently of the current model roster, refusing OpenCodex labels and local-listener endpoints. Local opt-outs validate and invalidate the common receipt before publication. +Native route materialization resolves Codex and Desktop paths from the device process environment. Under an effective first-party mode, Desktop enabled intent is current without a write and disabled intent is a conflict naming the mode switch; Home gateway file and marker writes share picker/lifecycle/config exclusion with mode switches. Offline first-party CLI apply retains one cross-process lifecycle lease through settings, gateway removal, mode save and rollback; nested writers validate and reuse it. Connected off uses remote-store ownership. Explicit takeover of an edited, selected, settled remote-owned projection snapshots its current JSON privately before the ordinary pending transaction, retaining owner, token, path and selection checks. Approved external Codex providers retain the existing injector's URL routing contract. Aside off with no strict ownership record requires no account manifest. Owned legacy/profile records must still match a registered profile; missing registration or unreadable ownership remains an incomplete apply. The shared read-only cleanup inspection in `src/integrations/route-intent-disconnect.ts` proves no-op absence before stop requires a file-write credential; actual writers retain their lifecycle, token and ownership guards. Missing common receipts allow Link disconnect only when ownership and selected file-config absence prove no materialization occurred; Droid rows are inspected independently of the current model roster, refusing OpenCodex labels and local-listener endpoints. Local opt-outs validate and invalidate the common receipt before publication. Factory Droid's explicit integration writes only documented `customModels` rows in `~/.factory/settings.json` (`%USERPROFILE%\\.factory\\settings.json` on Windows). Each @@ -430,7 +430,7 @@ fingerprint-only tests are supplementary; they cannot prove the status and write ## Remote connection lifecycle -`src/client/lifecycle-lock.ts` keeps the stable per-user lifecycle database across release. On Windows it freshly verifies an already-private runtime directory before repeating inheritable ACL changes over its descendants; wrong or unverified ACLs still require hardening. Database-file hardening and exclusion are unchanged. See the [ACL contract](../ops/service-and-sidecars.md) and `tests/windows/windows-lifecycle-root-acl.test.ts`. Remote clients journal and restore native integrations locally while model traffic travels directly to the hub. Catalog writes occur only after protocol negotiation and full remote schema validation. The management relay is launcher-scoped and fixed to the connection's management origin. Claude/Codex launch behavior remains integration-scoped. Key rotation and recovery align both the local connection credential and the connection-owned Desktop profile before reporting completion. Disconnect restores owned Desktop settings and native integrations locally without automatic hub-key revocation or usage mirroring. Interrupted cleanup remains recoverable for the same connection; conflicts prevent a full-cleanup claim. +`src/client/lifecycle-lock.ts` keeps the stable per-user lifecycle database across release. On Windows it freshly verifies an already-private runtime directory before repeating inheritable ACL changes over its descendants; wrong or unverified ACLs still require hardening. Database-file hardening and exclusion are unchanged. See the [ACL contract](../ops/service-and-sidecars.md) and `tests/windows/windows-lifecycle-root-acl.test.ts`. Remote clients journal and restore native integrations locally while model traffic travels directly to the hub. Catalog writes occur only after protocol negotiation and full remote schema validation. The management relay is launcher-scoped and fixed to the connection's management origin. Claude/Codex launch behavior remains integration-scoped. Key rotation and recovery align both the local connection credential and the connection-owned Desktop profile before reporting completion. Disconnect restores owned Desktop settings and native integrations locally without automatic hub-key revocation or usage mirroring. Interrupted cleanup remains recoverable for the same connection; conflicts prevent a full-cleanup claim. `cleanupConnectedFileRouteIntent` in `src/integrations/route-intent-disconnect.ts` also serves orderly Link shutdown through `src/client/stop-file-routing.ts`: the same ownership receipt, pre-link originals and local opt-outs decide each file removal, while the stop caller supplies its served-connection/runtime fence and keeps the saved connection. Explicit disconnect keeps its separate pending-disconnect guard and native cleanup. See the [Link shutdown contract](../remote-link.md). ## Local destinations on a hub diff --git a/structure/config.md b/structure/config.md index 0ec307ba045..20d79bc6e2f 100644 --- a/structure/config.md +++ b/structure/config.md @@ -64,7 +64,7 @@ silently move the active installation. Config reads in this leaf and `src/config `withConfigDirHardeningSettled` in `src/config/paths.ts` admits synchronous mutation after the last unrelated await. Its registry includes the optional config flight, ancestors and retained timeout children; one existing ACL deadline bounds admission, including newly overlapping work. Expiry throws sanitized `WindowsSecretAclSettleTimeoutError` (`ETIMEDOUT`) without running the writer or dropping child cleanup ownership. The final empty-registry check and callback share one turn, with no await in the callback. Intercept/picker CA, token, cleanup, profile and snapshot phases re-enter after trust/discovery awaits. Config saves in `src/server/management/agent-settings-routes.ts` and `src/server/management/config-routes.ts`, Desktop intent/mode commits in `src/server/management/native-integration-routes.ts`, and gateway publication/cleanup in those routes and `src/cli/ensure-desired-integrations.ts` use the same admission. `src/cli/claude-desktop.ts` admits local profile/mode commits and the complete remote-store transaction again after hub download. Lifecycle/config locks are acquired inside admission; refresh re-read, mode/freshness checks, profile and marker publication share one callback. Live setting edits and their save/publication share the admitted synchronous callback; a refused admission leaves both live and durable state untouched. Ordered post-commit phases preserve applied-state warnings or settled compensation, including mode/fingerprint marker refusal and retained CLI intent after incomplete rollback. Synchronous leaf APIs retain their contracts. `tests/claude-integration/claude-config-root-writer-barrier.test.ts` holds parent flights and drives refusal deadlines without sleeps. Lexical/canonical aliases and uncertain identities drain conservatively; removal keeps its separate at-or-below scope and actual-exit requirement. Async local config commands (`src/cli/config-command.ts`, `src/cli/effort.ts`, `src/cli/models.ts`, `src/cli/provider.ts`) admit complete synchronous read/validate/save phases through `withConfigDirHardeningSettled`. Preliminary model selection and client-connection diagnostics use passive observations that cannot publish recovery copies. Final authority and recovery publication are re-read inside admission without starting optional hardening. `src/cli/config-mutation.ts` refuses invalid or unreadable authority, including array/non-object roots rejected before defaults repair, with `CliUsageError`; full-config commands retain fresh-install initialization when the file is absent, while set/unset retain the persisted mutation owner's missing-file refusal. Custom-model removal revalidates the confirmed row by identity and contents while retaining current siblings. Import reads its input and checks its target inside admission. Provider-add credential cleanup shares the synchronous post-save phase and retains its existing post-commit warning. Timeout leaves the mutation database and config untouched and follows existing CLI failure handling. `tests/windows/windows-config-root-async-writers.test.ts` covers held parent flights, deadline refusal, recovery copies, invalid authority and concurrent edits. Codex multi-agent management changes that can resolve a runtime additionally await fresh [selection admission](codex-cli-update.md#worker-realm-and-the-selection-commit-window) before entering this barrier, keep that owner across hardening, and re-evaluate the mode plan inside the synchronous callback; neither ACL wait is inserted into the callback, and refusal leaves the combined mutation untouched. Timer-driven caches under the config root admit their write the same way and build the snapshot inside the callback: the provider account quota cache (`src/providers/account-quota-disk.ts`), the Codex account quota cache (`src/codex/quota.ts`) and the reasoning support cache, while a models.dev refresh admits its publication after the network read (`src/providers/reasoning-metadata.ts`). A timed-out admission skips a best-effort cache write and fails that refresh unpublished, a joined refresh reports the same failure, and a cancel, clear or reset invalidates a write still waiting for admission (#7815; `tests/providers/provider-account-quota-persistence.test.ts`, `tests/codex-integration/reasoning-metadata.test.ts`). The integrations writer (`src/integrations/writer.ts`) runs every coordinated transaction (apply, refresh, overwrite, disable, restore; reached by the catalog fan-out, the Aside sync and profile routes, and integration routes) inside admission on its store root, with the store-lock re-probe in the same callback so no await separates it from the transaction; an admission timeout returns a `write_failed` refusal without a write. An async `revalidate` such as the Aside late confirmation check still runs before admission, so the wait sits between it and the transaction while the writer locks stay held. `disconnectClient` in `src/client/connect.ts` admits each of its two synchronous phases (a timeout before the second leaves the prepared receipt it resumes from), and key rotation admits both remote Desktop credential alignments that precede the hub commit; rollback and post-commit finalization keep their unadmitted paths (`tests/windows/windows-config-root-integration-writers.test.ts`). The CLI also waits once at startup (`src/cli/config-root-startup.ts`, called from `runCli`'s command branch before the version-skew notice and Codex-shim preflight): on Windows it starts the optional config-root flight and drains it with `withConfigDirHardeningSettled(root, () => undefined)` under one ACL deadline, then proceeds even on timeout (`tests/windows/windows-cli-config-root-startup.test.ts`). It skips every command `skipsCodexShimAutoRestore` (`src/cli/preflight-exemptions.ts`) exempts (adding one there also drops this wait), every `internal` and hidden `__*` helper, `start` and `ensure`; for the server and for `ensure`, which the Windows Codex shim runs before every launch, the wait would spend up to one ACL deadline of fixed startup budgets. Residual risk, accepted by owner decision for #7815: (1) only the first write is covered once a later atomic write invalidates the per-process ctime success memo and a later `loadConfig()` starts a new flight; admitted writers stay safe; (2) a fresh install has no directory to wait for, so the first `loadConfig()` after creating it starts a flight while later writers run; (3) a swallowed timeout can leave a retained icacls child running that synchronous writers may overlap; (4) paths that never reach `runCli` (the `start` service logger, the update-restart child, the orchestrated identity probe, the health sentinel, MCP entrypoints) and every excluded command that writes under the root (any command `skipsCodexShimAutoRestore` exempts plus `ensure`, internal and hidden helpers; among them uninstall/remove, sync, orchestrated update, `disconnect --orphaned-token`, codex-shim install/uninstall, `message`, `stop --expect-*`, `lab automation enable|disable`, `lab run`, `lab public import` and `doctor --recover-zero-byte-coordinator --yes`), and `ready`, whose own `runCli` branch runs the Codex-shim restore (which can write `codex-shim.json` and its restore lock under the root) without the wait so the readiness probe gains no icacls latency, keep their previous overlap; (5) the server's synchronous writers (`saveConfig`, persisted mutation, management and GUI session tokens, service secrets, the spend-ledger lease, the link store) stay synchronous and can overlap a flight any `loadConfig()` starts; (6) every eligible CLI run on Windows now waits for one icacls run it previously left unawaited, including the commands Remote Link enrollment runs on a Windows Child over SSH (`link port`, `config show --json`, `connect --link`, `restart`) inside its fixed per-command budget, because the success memo is per process and the compliant-ACL precheck is opt-in (`OPENCODEX_ACL_VERIFY_EXISTING`). The writers #7815 named are admitted: config saves and Desktop 3p publication (#7826), the remote Desktop store through `connect.ts` and `claude-desktop.ts` (#7826, #8532) and the integrations writer (#8532). -`src/config/process-state.ts` derives `ocx.pid` and `runtime-port.json` from that resolved directory. Ordinary and connected-client runtimes publish their absolute relaunch command in the runtime record; older records can omit it. Tracked runtime inspection retains an omitted hostname as `undefined` for guarded stop's legacy-record check. +`src/config/process-state.ts` derives `ocx.pid` and `runtime-port.json` from that resolved directory. Native Link signal teardown reuses the bounded regular-file runtime reader in `src/client/sync-runtime.ts`; `src/client/stop-native-handoff.ts` reads each candidate teardown receipt without following links and validates its nonce and schema with `src/config/pending-teardown.ts` before checking the current stop owner. Ordinary and connected-client runtimes publish their absolute relaunch command in the runtime record; older records can omit it. Tracked runtime inspection retains an omitted hostname as `undefined` for guarded stop's legacy-record check. A client runtime's optional boolean `clientStopRequested` is valid only together with `clientStopping: true`; `true` records a parent stop request, and `false` records a finished stop with the retained runtime still fenced. The optional `clientStopOwner` binds an active request to a nonce, PID and process creation identity. `clientLinkOwner` records a fingerprint of the serving Link connection, or `null` for a native Hub client. Recovery and rollback follow the [Link shutdown contract](remote-link.md). It owns their byte-compatible writes, parsing, expected-PID filters, cheap liveness, full OCX command identity, and snapshot-guarded removal. `RuntimePortState.attestationSecret` and `siblingOfPort` (the live owner's port, written only by a sibling instance) remain optional, owner-only state and are validated before a record is returned. `src/config.ts` re-exports the same diff --git a/structure/manifest.json b/structure/manifest.json index 8d9fc158a62..b3c5034a142 100644 --- a/structure/manifest.json +++ b/structure/manifest.json @@ -1457,7 +1457,9 @@ "src/link/", "src/client/link-home.ts", "src/client/link-parity-reporter.ts", + "src/client/runtime-recycle.ts", "src/client/runtime-restart.ts", + "src/client/runtime-rollback.ts", "src/cli/link-apply-restart.ts", "src/cli/status-codex-settings.ts", "src/cli/status-link.ts", diff --git a/structure/ops/service-health-recovery.md b/structure/ops/service-health-recovery.md index 5535e5d551e..0bf884df91a 100644 --- a/structure/ops/service-health-recovery.md +++ b/structure/ops/service-health-recovery.md @@ -75,7 +75,7 @@ Probes accept only numeric IPv4/IPv6 destinations. Default and localhost binds u `ENOSYS` from either startup syscall, or an unsupported syscall architecture, selects the existing live-parent fallback and logs the limitation. Permission/resource/identity errors and unavailable libc bindings refuse recovery. Both glibc and musl libc bindings are supported without new deps. - The watching line ends with `(pidfd)` when the binding succeeds. + The watching line ends with `(pidfd)` when the binding succeeds. Explicit Link Child stop reuses pidfd acquisition with the attested creation identity and rechecks it before SIGTERM and SIGKILL. - macOS, and Linux without pidfd support, check the live `process.ppid` immediately before SIGKILL. This fallback is probabilistic: if the sentinel is descheduled between the check and `kill` while the parent exits, is reaped, and its PID is reused, the signal can reach that process. diff --git a/structure/ops/windows-checked-stop.md b/structure/ops/windows-checked-stop.md index 7a13ef290fd..56bf3116661 100644 --- a/structure/ops/windows-checked-stop.md +++ b/structure/ops/windows-checked-stop.md @@ -28,6 +28,8 @@ lazily, caches a failed load as unavailable, and closes every handle in a `final - an exit watch: a handle opened at bind time and polled with `WaitForSingleObject(handle, 0)`; - the Task Scheduler service host PID through `QueryServiceStatusEx` on `Schedule`, only while it runs. +The Link Child reads its live same-user creation proof in-process on one native handle, using `GetProcessTimes` and the token user SID. It preserves the existing .NET tick identity at microsecond precision without spawning PowerShell or caching a PID proof. The process fallback compares that identity on the same handle used for termination. Unavailable native identity or handle binding refuses promptly; it does not fall back to repeated CIM subprocesses. `tests/windows/windows-stop-owner-identity.test.ts` covers handle ownership, stale identities and an actual-Windows-only repeated-read budget. + Windows ARM64, other platforms and any test that simulates a platform get no native API. `src/service/windows-process-evidence.ts` is the facade the operations use. Its process snapshot is one capped PowerShell snapshot that emits UTF-8 JSON and uses ISO UTC for `CreationDate`. diff --git a/structure/remote-link.md b/structure/remote-link.md index fdedb5a6b92..a716680b9f7 100644 --- a/structure/remote-link.md +++ b/structure/remote-link.md @@ -1,10 +1,27 @@ # Remote Link +An attested standalone sibling can stop even when its home has a saved Link connection. +If the sibling itself serves the saved Link, stop requires attested native Link health, +a matching Link owner and serving generation in the pinned record, and a verified process +incarnation. The CLI rechecks the record, Link owner and incarnation at termination and +stops only that process. After TERM, the recheck also accepts the exact record with +`clientStopping: true`, which the Child publishes during shutdown. Linux uses the same +bound pidfd for TERM and KILL. The service manager, teardown receipts and shared routing are +outside this stop's authority. Unverified Link ownership or conflicting manager approval refuses the stop. + Signal fencing uses the configuration mutation lock (`C`), yielding 50 ms between at most 20 attempts only when `ConfigMutationLockError` wraps `SQLITE_BUSY` or `SQLITE_LOCKED`; identity, storage and other failures refuse immediately. Restoration callers must explicitly supply their sync-fence verdict. `tests/clients/client-link-stop.test.ts` covers a real cross-process C transaction, retry exhaustion and non-contention errors. -`src/client/sync-runtime.ts` fences Link sync against the local runtime record. Signal shutdown marks its own PID/port/attestation generation as `clientStopping` under C before restoration, and retains that mark through its last await. Sync captures the record at admission and rechecks it under C before catalog, injection, settings-record and cache commits. A stopping, replaced, removed or unreadable record refuses the write; a stale operation cannot reinject after the Child exits. Failure to mark the runtime refuses restoration without overriding service, Desktop, sibling or parent-receipt preservation. No-runtime sync remains an explicit offline operation: it reapplies routing even though no Child listener is serving it. A stale stopping record is reconciled by the existing start/stop recovery paths, not by guessing PID ownership. A bound restart marks the record the same way before it drains the listener, and abandons the restart with the runtime still serving when the mark cannot be written; and every publication of the runtime record carries a fresh `servingGeneration`, so a sync admitted before a restart whose replacement failed is refused by the record the rollback publishes, while syncs admitted afterwards proceed (`tests/clients/client-restart-sync-fence.test.ts`). The separate-process catalog/settings-response holds in `tests/clients/client-link-stop.test.ts` cover late commits, fresh sync during shutdown and the completed-sync control. +`src/client/sync-runtime.ts` fences Link sync against the local runtime record. Signal shutdown marks its own PID/port/attestation generation as `clientStopping` under C before restoration, and retains that mark through its last await. Sync captures the record at admission and rechecks it under C before catalog, injection, settings-record and cache commits. A stopping, replaced, removed or unreadable record refuses the write; a stale operation cannot reinject after the Child exits. Failure to mark the runtime refuses restoration while service, Desktop and sibling preservation retain their own exclusions; a native teardown receipt never waives the file-route fence. No-runtime sync remains an explicit offline operation: it reapplies routing even though no Child listener is serving it. A stale stopping record is reconciled by the existing start/stop recovery paths, not by guessing PID ownership. A bound restart marks the record the same way before it drains the listener, and abandons the restart with the runtime still serving when the mark cannot be written; and every publication of the runtime record carries a fresh `servingGeneration`, so a sync admitted before a restart whose replacement failed is refused by the record the rollback publishes, while syncs admitted afterwards proceed (`tests/clients/client-restart-sync-fence.test.ts`). The separate-process catalog/settings-response holds in `tests/clients/client-link-stop.test.ts` cover late commits, fresh sync during shutdown and the completed-sync control. + +Orderly signals in an unsupervised Link Child await file-route cleanup in `src/client/stop-routing.ts` before releasing the listener, then reuse native Codex config/catalog/history restoration and managed Grok removal. The saved connection and credentials remain. `src/client/restore-ownership.ts` optionally binds each write under C to the immutable served connection, including selection and rotation state. Only `catalogFingerprint` and `catalogSyncedAt`, updated by normal catalog sync, are excluded from this restore-specific comparison; `priorCatalog` remains guarded and the shared full-snapshot CAS for asynchronous connection work is unchanged. A changed owner, pending transition or unverified journal refuses remaining writes. Service/desktop supervision, sibling ownership and accepted restart/recycle handoff preserve integrations for their existing owners. Native teardown receipts never skip unsupervised file-route cleanup or the sync fence. `src/client/stop-native-handoff.ts` defers native Codex/Grok only when a bounded, no-follow receipt names the exact loopback endpoint, the current PID/port/attestation record binds its nonce to the PID and creation identity of a distinct live same-user stop invocation, and the receipt names that same owner. `src/client/stop-teardown-owner.ts` reads Linux NUL-separated argv and uses `src/client/stop-darwin-process.ts` for native macOS argv and microsecond process creation time. On Windows, the same-user creation proof uses `GetProcessTimes` and the process token on one live native handle, without PowerShell/CIM subprocesses or cached PID proofs; unavailable native evidence refuses promptly. The stored .NET tick identity retains its existing microsecond precision. Windows command lines follow native double-quote/backslash rules and treat apostrophes literally. It accepts the supported compiled, source and npm stop forms, including installation paths containing spaces. Update workers launch a separate stop child. The Child rechecks the receipt bytes and runtime identity after inspecting the owner. The current claim can coexist with stale exact claims for this endpoint and quarantined obligations. For other endpoints, the current claim must carry the digest of the exact receipt bytes verified by the parent. A missing or changed snapshot, a malformed receipt or a guessed endpoint refuses signal deferral. Without that current owner, outstanding or unreadable receipt evidence refuses native restoration and retains the listener. Unreadable owner evidence blocks restart and recycle, as does a verified active stop. Both rollback paths that would recycle use the same admission check as scheduled recycle and bound restart. Signal shutdown waits for an accepted restart to hand off or finish rolling back; a pending admission owns no routing. It refuses new or pending restart admission with `409 runtime_stopping`; normal bound restart remains unchanged. After an ordinary unsupervised stop, start alone does not reapply routing; the operator steps live in the public CLI lifecycle reference. Coverage: `tests/clients/client-link-stop.test.ts`, `tests/clients/client-runtime-restart.test.ts`. + +`src/client/stop-file-routing.ts` shares the receipt-driven file cleanup in `src/integrations/route-intent-disconnect.ts` without disconnecting the Child. It removes only Link-created file integrations, preserves pre-link standalone integrations and local opt-outs, and retains connection/recovery records. After the runtime fence, strict receipt and on-disk absence inspection may prove no file cleanup is needed without acquiring L or requiring a token; the connection, configured port and runtime boundary are still checked. Each actual writer acquires L and repeats the immutable connection, configured port and physical token checks under C immediately before committing; a partial cleanup invalidates the earlier Home apply proof. A conflicting file, changed owner or unverified receipt refuses cleanup without overwriting the conflict. Signal shutdown keeps the listener bound with sync fenced and background watchers stopped; another signal or `ocx stop` retries after repair. For an explicit stop, `src/cli/stop-restore.ts` requires the runtime's attested Link fence capability, exact PID/port/runtime generation and the serving Link ownership fingerprint. The fingerprint must match the saved connection, and the configured port must match the serving port. Invalid or mismatched connection state refuses before manager or process mutation. Saved client state, Link receipts, a live client runtime record, an attested Link fence or client-role health trigger preflight. It requires the protected runtime record and attested health for both tracked and discovered live targets before service-manager mutation. Missing or unreadable identity refuses those targets even if saved state reads disconnected. Standalone stop uses the ordinary manager and restore path. Link stop pins the same-user OS creation identity on both sides of attestation, then rechecks it along with the fenced record and connection at each destructive boundary, including escalation and port reclaim. Linux requires a verified pidfd for both TERM and KILL. Windows checks creation time on the same handle used to terminate. macOS sends one orderly SIGTERM and returns a refusal if the Child stays up. That signal targets a numeric PID, so a same-user replacement can still receive it if the PID is reused between the final creation-time check and the signal syscall. Preflight checks the bounded inherited-teardown snapshot captured by `src/cli/index.ts`. Malformed/unscannable or guessed inherited evidence refuses before any manager or process stop. An exact receipt for this attested endpoint may be settled by this stop. For a different endpoint, the parent must prove absence and bind that receipt snapshot to its own claim. The parent still probes the inherited endpoints after shutdown before restoring or discharging receipts. Quarantine-only evidence and live concurrent/self-owned claims retain their existing recovery exclusions. Preflight marks the sync fence and drains these files before any service-manager stop, new teardown receipt or kill fallback. Each busy-lock retry takes a fresh guard and verifies the exact runtime inside C. The CLI revalidates the fenced record and connection immediately before invoking the manager or stopping the process, including forced fallback. A failed preflight returns without stopping a process. When all known concrete endpoints are dead and the manager is inactive, preflight returns `already-stopped`. For a saved Link on Linux with an unreadable manager, the offline path requires `lstat` to report `ENOENT` for the installer unit and every service installation record path. It runs without runtime attestation, fencing or file cleanup; the later parent restoration path attempts file cleanup. A surviving Link receipt without a matching saved Link refuses post-stop restoration and retains the evidence. An attested legacy native listener with saved Link ownership and neither a published owner nor a fence is refused with the ordered transition in the CLI lifecycle reference. The initial absence of file routes never skips the fence: an already-admitted Home update can enable its first file integration. Failure to establish the fence retains an unsupervised signal listener too. During unsupervised signal cleanup, a native Codex/Grok restoration refusal after file cleanup also retains the listener and sync fence. During explicit stop, native restoration is attempted by the parent after the Child exits; refusal retains recovery evidence and reports incomplete restoration with the listener already stopped. Successful native restoration and the supervised/sibling/handoff exclusions keep their existing owners. Coverage: `tests/clients/client-link-stop.test.ts` (file writers, listener release and late materializer commits) and `tests/clients/client-link-stop-sibling.test.ts` (CLI stop ordering, process identity and native handoff). + +A discovery miss requires independent standalone proof or a matching manager registration bound to the PID. The [standalone stop rules](runtime.md#lifecycle) describe the runtime-record fallback. With neither proof, `ocx stop` refuses before the service stop and signal ladder, preserving the Child's ability to refuse an unsafe shutdown. + +An explicit parent stop sets `clientStopRequested: true` and writes its nonce, owner PID and process creation identity in the same exact-runtime C transaction. A deferred-teardown receipt with that nonce and creation identity must be written before manager or process stop. `src/config/process-state.ts` accepts both boolean values only with `clientStopping: true`. Before releasing its ownership mutation lease, the CLI finalizer clears only the matching request and retains the sync fence. A finalization refusal keeps the fence and preserves the original stop result. The runtime observes it only for its own PID/port/attestation, rejects further restart admission and the pre-fence stage of an already-admitted restart, and preserves both active and finished states under C when publishing a failed-restart rollback. A retained fence blocks unchanged, pending, new or unverified connections. Only a validated disconnected config and a complete disconnect receipt for the served owner and token, checked together under C with no pending connect, admit a serialized standalone recycle after the parent stop finishes. A verified active or unverified parent stop blocks recovery, as does signal shutdown. Only a dead PID or a positively different creation identity is confirmed stale. A malformed identity or an unrecognized invocation at the same incarnation is unverified. A receipt whose owner cannot be verified remains outstanding and blocks parent recovery. The check covers a previously scheduled timer and a restart awaiting its final supervisor check. After a completed disconnect, a finished request or confirmed-stale owner permits recovery. Signal shutdown cancels a pending recycle timer and frees its scheduling slot for eligible recovery if the listener is retained. Shutdown still waits for a recycle already in flight. A fresh process has a new attestation and does not inherit a stale request. The owning runtime passes `linkStopFence: true` to `src/client/machine-listener.ts`, which advertises it in attested health. Link preflight requires that capability before writing the marker or files; older or unknown running builds refuse with supervisor update/restart guidance. A Hub stop does not require the Link fence. A native listener that does not report a Link fence must publish its Hub identity and still have a saved Hub connection. Older native listeners without a published owner refuse until updated and restarted through their supervisor. Ordinary restart has no explicit-stop marker, so a failed replacement still publishes a new generation and admits fresh sync. Rollback closes an unpublished rebound listener before yielding on lifecycle/configuration lock contention, retries within one shared rebind deadline, and rechecks connection ownership and explicit-stop evidence before each new bind and publication. It starts the tunnel supervisor and credential observer only after publication. The overlap and ordinary-rollback control use real runtime records and file writers in `tests/clients/client-link-stop-recovery.test.ts`. -Orderly signals in an unsupervised Link Child call `src/client/stop-routing.ts` before releasing the listener. It reuses native Codex config/catalog/history restoration and managed Grok removal; the saved connection and credentials remain. `src/client/restore-ownership.ts` optionally binds each write under C to the immutable served connection, including selection and rotation state. Only `catalogFingerprint` and `catalogSyncedAt`, updated by normal catalog sync, are excluded from this restore-specific comparison; `priorCatalog` remains guarded and the shared full-snapshot CAS for asynchronous connection work is unchanged. A changed owner, pending transition or unverified journal refuses remaining writes. Service/desktop supervision, sibling ownership, accepted restart/recycle handoff and outstanding parent teardown receipts preserve integrations for their existing owners. Signal shutdown waits for an accepted restart to hand off or finish rolling back; a pending admission owns no routing. It refuses new or pending restart admission with `409 runtime_stopping`; normal bound restart remains unchanged. After an ordinary unsupervised stop, start alone does not reapply routing; the operator steps live in the public CLI lifecycle reference. Coverage: `tests/clients/client-link-stop.test.ts`, `tests/clients/client-runtime-restart.test.ts`. +`src/client/runtime-recycle.ts` holds the Link apply exclusion from admission through listener drain and routing cleanup. Admission rechecks the served connection and explicit-stop policy under the configuration mutation lock; a pending transition, unchanged connection or retained stop obligation refuses teardown. The exclusion is released before replacement startup. `src/client/runtime-rollback.ts` retries only proven lifecycle or SQLite lock contention, with at most 50 ms between attempts and one remaining-time budget shared with listener rebinding. Coverage: `tests/clients/client-recycle-exclusion.test.ts`, `tests/clients/client-restart-rollback-lock.test.ts`, and the rollback controls in `tests/clients/client-link-stop-recovery.test.ts`. `src/link/ssh-argv.ts` and `src/link/remote-windows.ts` build every gated Child command through `remoteGatedOcxArgv` and `windowsGatedOcxArgv`: the script selects one executable, reads its version inside the remote script, refuses below the command's minimum with a named `ocx-fanout:` marker and exit 121, and only then runs the arguments. Every gated script exports `OCX_NO_DESKTOP_HANDOFF=1` before the version probe and the run, so a package launcher answers for itself and a Desktop handoff cannot pass the gate on behalf of an older launcher. The pinned sync is the 2.93.0 instance and executes `sync --expect-link`; the Home adds `--restart-app-server-only` or `--restart-codex` only for a restarting sync (the Child operation runners below and `ocx sync --restart-children`), never on Windows (the builder refuses it, `unsupported:windows-restart`) or for a link recorded as `ocx-child`, and withholds it for a link whose relayed model traffic is in flight (`src/cli/sync-fanout.ts`, `src/link/sync-then-restart.ts`). A link whose `childKind` is not recorded can receive the flag on that second sync, which is how the selected-kind marker reports `ocx-child`; `ocx-child` ignores it. The update builders in `src/link/child-gated-ocx.ts` require 2.97.0 inside the script, so the Home never sends `update` to an ocx that reports an older version; they refuse a selected `ocx-child` by file name (`ocx-fanout:child-ocx-ephemeral`) and on POSIX report `ocx-fanout:entry:pair|binary` (Windows reads no census, so its script prints no entry marker and the Home infers `binary`); the plan probe also reports the Child's clock, and the shipped builders refuse Windows apply. A Windows command that would exceed the encoded command-line budget throws `windows-command-too-long`; the plan probe fits a Home version of at least 40 characters. `src/link/child-update-contract.ts` is the Home's own strict copy of the Child's `update.orchestrated/1` plan and result documents and maps every apply exit to a closed verdict. `src/link/child-observations.ts` keeps a tolerant per-link cache in `/link/child-observations.json` beside the strict `links.json`: it drops unknown keys, prunes removed links on write and reads damage as empty. The per-Child sync classifier lives in `src/link/sync-fanout-classify.ts`. The plan probe is wired to the observe operation (`src/link/child-observe.ts`, below), which always passes the resolved platform to `classifyUpdatePlanProbe`; the apply builder and the sync restart flag are called from the Child operation runners (below) and `ocx sync --restart-children`; nothing runs on a timer except the Child-ops scheduler (below), which submits no-restart `sync` jobs and restarts app-servers only for idle Children under `childCodexRestart: "app-server-when-idle"`. The relay, not `onAuthenticatedCatalog` (which fires on admission and keeps driving the supervisor and the enrollment wait), records each Child's catalog pulls. Coverage: `tests/clients/link-gated-ocx-argv.test.ts`, `tests/clients/link-child-update-contract.test.ts`, `tests/clients/link-child-observations.test.ts`. Fan-out platform discovery in `src/link/remote-platform.ts` accepts a Windows marker on any stdout line or one framed uname line, so login-shell output cannot decide the platform. The Home requires one valid selection marker on stderr and one stdout delimiter, and classifies only the text after that delimiter; login-shell output before them is ignored. Oversized version probes are skipped. POSIX version capture and watchdog readiness use a private temporary directory, removed before execution or on refusal. The Home's `src/cli/sync-command.ts` fans out only after its catalog is current; the Child may still restart its own OpenCodex client runtime after applying changed Home settings. With `--overwrite-conflict` the pinned sync gate requires 2.100.0 and refuses ephemeral Children before executing; explicit client selection is forwarded. Known ephemeral links receive plain catalog sync. Coverage: `tests/clients/link-pinned-sync-overwrite.test.ts`, `tests/cli/cli-sync-fanout-ephemeral.test.ts`. @@ -322,7 +339,7 @@ When sync preserves an external Codex provider without applying configuration, i `ocx status --json` reports `appliedCodexSettingsDigest` on every device (a Child's record, or a Home's own projection, which is what it serves), and on a Child `lastApplyAt` and `runtimeStartedAt` as epoch ms (`src/cli/status-codex-settings.ts`). The client runtime's `/healthz` reports `startedAt`. After `ocx sync` records an apply, `src/cli/link-apply-restart.ts` restarts the client runtime through `handleProxyRestart`, the `ocx restart` path, only when the live client runtime started before `appliedAt` or reports no start; its start callback starts nothing unless an accepted restart left no runtime, which takes the ordinary recovery start. An explicit Desktop or service supervised refusal defers that restart without failing the applied sync; the notice directs Desktop users to Quit from the tray menu and reopen OpenCodex, or service users to `ocx service restart`. The next sync retries until the runtime starts after the apply. Other restart failures remain failures, and any earlier sync error is retained. The Child's JSON shape stays unchanged so existing Home fan-out parsers accept the successful result. -The client listener serves that bound restart (`src/client/machine-listener.ts`, `src/client/runtime-restart.ts`). `/healthz` answers the attestation challenge with the secret the runtime publishes in `runtime-port.json` and advertises `restartCapability: "v1"`; `POST /api/system/restart` admits only the HMAC capability bound to this pid and port, never a dashboard session, admin token or link key. If the relaunch command cannot be identified, `src/client/runtime.ts` omits it from the runtime record; update admission treats the identity as unproven, while client startup and shutdown continue. Under the desktop app or a viable service it answers `409 restart_supervised` naming the supervisor and keeps serving, because handing off to a supervisor means exiting before the replacement is proven; the CLI reports "not performed, runtime kept". That refusal applies only while the durable connection is still the one the runtime serves: after `ocx disconnect` or a newer connect there is nothing to keep, so the restart is accepted and hands off to the standalone recycle (desktop exit 75, a viable service exit 1, otherwise a spawned replacement carrying no supervisor marker). "Ended" needs evidence (`readClientConnectionStateWithEvidence`, one snapshot of config.json): a saved file that validates and records no client, or another connection; missing, unreadable or invalid is invalid. Ownership and relaunch are separate (`classifyClientRestartSupervisor`): manager-launched evidence is the current markers in the environment only (`isMarkedSupervisedServiceChild`: the managed marker or the Windows wrapper marker); a legacy Windows registration recognised only from its parent's command line counts as a bare OCX_SERVICE=1; relaunch needs the service diagnostic to be viable and running. Manager-launched without that is `service-unproven`. `service-unproven` keeps the runtime and is refused at admission even when the connection ended; on this PR's recycle path only a process whose owner is proven to be none detaches, carrying no supervisor marker. A bare OCX_SERVICE=1 is outside that path and is always refused as `legacy-flag` (#8545, owner decision 2026-11-16): its owner is never inferred, not from the service diagnostic and not from the parent's command line, so nothing is stopped, replaced or recycled. A marker proves only that the process was started with it, so no supervisor marker may reach a process that supervisor did not launch: `src/lib/supervisor-markers.ts` holds the one list, and every detached runtime launch (companions, recycle, replacement, detached and post-update starts) and every shell a runtime hands to a tool clears it. The ended-connection recycle needs positive ownership evidence (`restartOwnerProven`: the desktop app, a manager's marker, or no OCX_SERVICE at all). A bare OCX_SERVICE=1 (a service registered before v2.49, or the proxy of ocx claude, ocx codex or ocx opencode) cannot be told apart, so its client runtime refuses `ocx restart` with 409 `restart_supervised` and supervisor `legacy-flag` whatever the service state and whether or not the connection ended, and records `restartOwner: legacy-flag`. The refusal text (`LEGACY_FLAG_OWNER_ADVICE` in `src/cli/restart-failure.ts`) tells the user to re-register the service once with `ocx service repair`, which writes the current ownership marker, or, for a companion's proxy, to `ocx stop` and start it again; `ocx sync` defers with the same text. `ocx disconnect` restarts only a runtime whose record states an owner it handles (`restartOwner`: desktop, service-manager or none); for `legacy-flag` it sends no restart request, prints the advice on stderr and exits 0, because the disconnect itself completed and a later `ocx restart` refuses with the same advice. A runtime started before this field existed, or an unknown value, gets origin/dev's disconnect: no restart request, exit 0. An inconclusive liveness probe or an unreadable record still exits 1 before any request, the one deliberate difference from origin/dev (no runtime is stopped, and the Home's leave stops before its own `ocx restart`). Owner evidence for those runtimes is a separate design (follow-up issue). `ocx disconnect` (`src/cli/disconnect-runtime.ts`) runs that restart itself when a client runtime is still live, bound to the runtime generation it observed: it captures that runtime's record (pid, port, per-process attestation secret) and the bound restart attests and derives its capability from the captured record, so another process at a reused pid is refused. It reads the client state once after its observation; when no runtime or a non-client runtime answered, that read decides alone (exit 0 only if disconnected). When it restarted a client runtime, it reads the state again after the restart: exit 0 needs that read to be disconnected and a live non-client runtime answering, and every exit-1 outcome takes its advice from one function (`recoveryAdvice`) given the state read at that point and whether the captured runtime, a different one or nothing answers: a plain restart is advised only for the captured runtime under a disconnected state (or a start when nothing answers), and a connected or unreadable state gets `ocx status` inspection only. Every other outcome exits 1, so a Home-driven leave stops before its own `ocx restart`. No read fences a process that runs after the command has exited. Each `ocx disconnect` attempt holds its own lock D (`withClientDisconnectAttempt` in `src/client/lifecycle-lock.ts`, outermost and taken by nothing else), so a second attempt refuses with `client_disconnect_busy` instead of sharing the first one's receipt while Codex is restored outside L. A disconnect refused before its receipt reaches `desktop_restored` (in practice, by the Codex journal restore, which keeps Codex's own later edits through `preserveConfigEdits`) removes that `prepared` receipt (and an otherwise empty `desktop-remote/` folder) when this attempt wrote it, or when an earlier run's receipt finds the Desktop store with no restore started (`absent`, `active` or `legacy_current_connection`); otherwise the receipt is kept, because that run may have stopped inside the Desktop restore. On a link Child the route-intent drain has already run by then; the rollback leaves it, and the runtime's next route-intent apply restores the routed file integrations. A pending receipt makes client startup refuse with `client_disconnect_pending`; that startup refusal names `ocx disconnect` as the way to finish or roll back (`src/client/connect.ts`, `src/client/state.ts`). `inspectRemoteDesktopStore` reports which step failed and the path it read, and `src/client/desktop-refusal.ts` turns that into the refusal. Coverage: `tests/clients/client-disconnect-recovery.test.ts`, `tests/clients/client-disconnect-desktop-refusals.test.ts`. Right after its connection commits, `connectClient` (and each connected `ocx sync` injection) takes over a Codex journal another owner wrote (`adoptJournalForClient` in `src/codex/journal.ts`), keeping the original snapshot; before the commit the journal stays its live writer's, so a runtime starting mid-connect leaves it alone, and after it a supervisor relaunch does not read the standalone owner as a crashed session and restore native Codex. Only a disconnected state or a different committed connection counts as ended for a supervised restart; unreadable or mismatched state keeps the refusal, and the controller rechecks after its supervisor lookup, immediately before recycling, handing the recycle the same supervisor verdict (a service only when viable). Otherwise one budget (`CLIENT_RESTART_BUDGET_MS`, 90 s from acceptance) covers a 20 s listener drain, a replacement `ocx start` that must answer by 70 s (`spawnReplacementStart` with `notReady: "terminate"`, which stops an unready replacement and returns only after its exit is observed), and a rollback that binds the port again with a 10 s wait, builds a fresh tunnel supervisor (a stopped one cannot restart) and republishes the same attestation secret and start time. Before binding, and again under the client lifecycle lock right before it publishes, it checks that the durable connection is still the one it served; a disconnect, a new connection or a held lock closes the new listener unpublished and hands off to the standalone recycle, which starts what the current state calls for. `requestBoundSystemRestart` sends the request to a client target only while `CLIENT_RESTART_REQUEST_MIN_REMAINING_MS` remains, so a rollback always ends before the CLI's replacement observation and its recovery start. Coverage: `tests/clients/client-runtime-restart.test.ts`, `tests/server/restart-replacement-not-ready.test.ts`, `tests/cli/link-apply-restart.test.ts`. +The client listener serves that bound restart (`src/client/machine-listener.ts`, `src/client/runtime-restart.ts`). `/healthz` answers the attestation challenge with the secret the runtime publishes in `runtime-port.json` and advertises `restartCapability: "v1"`; `POST /api/system/restart` admits only the HMAC capability bound to this pid and port, never a dashboard session, admin token or link key. If the relaunch command cannot be identified, `src/client/runtime.ts` omits it from the runtime record; update admission treats the identity as unproven, while client startup and shutdown continue. Under the desktop app or a viable service it answers `409 restart_supervised` naming the supervisor and keeps serving, because handing off to a supervisor means exiting before the replacement is proven; the CLI reports "not performed, runtime kept". That refusal applies only while the durable connection is still the one the runtime serves: after `ocx disconnect` or a newer connect there is nothing to keep, so the restart is accepted and hands off to the standalone recycle (desktop exit 75, a viable service exit 1, otherwise a spawned replacement carrying no supervisor marker). "Ended" needs evidence (`readClientConnectionStateWithEvidence`, one snapshot of config.json): a saved file that validates and records no client, or another connection; missing, unreadable or invalid is invalid. Ownership and relaunch are separate (`classifyClientRestartSupervisor`): manager-launched evidence is the current markers in the environment only (`isMarkedSupervisedServiceChild`: the managed marker or the Windows wrapper marker); a legacy Windows registration recognised only from its parent's command line counts as a bare OCX_SERVICE=1; relaunch needs the service diagnostic to be viable and running. Manager-launched without that is `service-unproven`. `service-unproven` keeps the runtime and is refused at admission even when the connection ended; on this PR's recycle path only a process whose owner is proven to be none detaches, carrying no supervisor marker. A bare OCX_SERVICE=1 is outside that path and is always refused as `legacy-flag` (#8545, owner decision 2026-11-16): its owner is never inferred, not from the service diagnostic and not from the parent's command line, so nothing is stopped, replaced or recycled. A marker proves only that the process was started with it, so no supervisor marker may reach a process that supervisor did not launch: `src/lib/supervisor-markers.ts` holds the one list, and every detached runtime launch (companions, recycle, replacement, detached and post-update starts) and every shell a runtime hands to a tool clears it. The ended-connection recycle needs positive ownership evidence (`restartOwnerProven`: the desktop app, a manager's marker, or no OCX_SERVICE at all). A bare OCX_SERVICE=1 (a service registered before v2.49, or the proxy of ocx claude, ocx codex or ocx opencode) cannot be told apart, so its client runtime refuses `ocx restart` with 409 `restart_supervised` and supervisor `legacy-flag` whatever the service state and whether or not the connection ended, and records `restartOwner: legacy-flag`. The refusal text (`LEGACY_FLAG_OWNER_ADVICE` in `src/cli/restart-failure.ts`) tells the user to re-register the service once with `ocx service repair`, which writes the current ownership marker, or, for a companion's proxy, to `ocx stop` and start it again; `ocx sync` defers with the same text. `ocx disconnect` restarts only a runtime whose record states an owner it handles (`restartOwner`: desktop, service-manager or none); for `legacy-flag` it sends no restart request, prints the advice on stderr and exits 0, because the disconnect itself completed and a later `ocx restart` refuses with the same advice. A runtime started before this field existed, or an unknown value, gets origin/dev's disconnect: no restart request, exit 0. An inconclusive liveness probe or an unreadable record still exits 1 before any request, the one deliberate difference from origin/dev (no runtime is stopped, and the Home's leave stops before its own `ocx restart`). Owner evidence for those runtimes is a separate design (follow-up issue). `ocx disconnect` (`src/cli/disconnect-runtime.ts`) runs that restart itself when a client runtime is still live, bound to the runtime generation it observed: it captures that runtime's record (pid, port, per-process attestation secret) and the bound restart attests and derives its capability from the captured record, so another process at a reused pid is refused. It reads the client state once after its observation; when no runtime or a non-client runtime answered, that read decides alone (exit 0 only if disconnected). When it restarted a client runtime, it reads the state again after the restart: exit 0 needs that read to be disconnected and a live non-client runtime answering, and every exit-1 outcome takes its advice from one function (`recoveryAdvice`) given the state read at that point and whether the captured runtime, a different one or nothing answers: a plain restart is advised only for the captured runtime under a disconnected state (or a start when nothing answers), and a connected or unreadable state gets `ocx status` inspection only. Every other outcome exits 1, so a Home-driven leave stops before its own `ocx restart`. No read fences a process that runs after the command has exited. Each `ocx disconnect` attempt holds its own lock D (`withClientDisconnectAttempt` in `src/client/lifecycle-lock.ts`, outermost and taken by nothing else), so a second attempt refuses with `client_disconnect_busy` instead of sharing the first one's receipt while Codex is restored outside L. A disconnect refused before its receipt reaches `desktop_restored` (in practice, by the Codex journal restore, which keeps Codex's own later edits through `preserveConfigEdits`) removes that `prepared` receipt (and an otherwise empty `desktop-remote/` folder) when this attempt wrote it, or when an earlier run's receipt finds the Desktop store with no restore started (`absent`, `active` or `legacy_current_connection`); otherwise the receipt is kept, because that run may have stopped inside the Desktop restore. On a link Child the route-intent drain has already run by then; the rollback leaves it, and the runtime's next route-intent apply restores the routed file integrations. A pending receipt makes client startup refuse with `client_disconnect_pending`; that startup refusal names `ocx disconnect` as the way to finish or roll back (`src/client/connect.ts`, `src/client/state.ts`). `inspectRemoteDesktopStore` reports which step failed and the path it read, and `src/client/desktop-refusal.ts` turns that into the refusal. Coverage: `tests/clients/client-disconnect-recovery.test.ts`, `tests/clients/client-disconnect-desktop-refusals.test.ts`. Right after its connection commits, `connectClient` (and each connected `ocx sync` injection) takes over a Codex journal another owner wrote (`adoptJournalForClient` in `src/codex/journal.ts`), keeping the original snapshot; before the commit the journal stays its live writer's, so a runtime starting mid-connect leaves it alone, and after it a supervisor relaunch does not read the standalone owner as a crashed session and restore native Codex. Only a disconnected state or a different committed connection counts as ended for a supervised restart; unreadable or mismatched state keeps the refusal, and the controller rechecks after its supervisor lookup, immediately before recycling, handing the recycle the same supervisor verdict (a service only when viable). Otherwise one budget (`CLIENT_RESTART_BUDGET_MS`, 90 s from acceptance) covers a 20 s listener drain, a replacement `ocx start` that must answer by 70 s (`spawnReplacementStart` with `notReady: "terminate"`, which stops an unready replacement and returns only after its exit is observed), and a rollback that binds the port again with a 10 s wait, builds a fresh tunnel supervisor (a stopped one cannot restart) and republishes the same attestation secret and start time. Before binding, and again under the client lifecycle lock right before it publishes, it checks that the durable connection is still the one it served; Link rollback takes C inside the lifecycle lock to preserve any explicit stop fence. An unsuccessful publication closes the rebound listener in the binding turn. Only proved lifecycle or config SQLite contention retries, yielding with that listener closed and rechecking the durable owner and stop fence before a fresh bind/publication. All attempts share the existing 10 s rollback budget; ownership, storage and other failures do not retry. Link recycle takes the outer apply exclusion before its final C-protected owner/stop-receipt/pending-connect admission, outside L, and retains it through supervisor stop, listener closure, record cleanup and diagnostic drain. Once teardown begins it finishes under that exclusion instead of abandoning a partially stopped runtime. `requestBoundSystemRestart` sends the request to a client target only while `CLIENT_RESTART_REQUEST_MIN_REMAINING_MS` remains, so a rollback always ends before the CLI's replacement observation and its recovery start. Coverage: `tests/clients/client-runtime-restart.test.ts`, `tests/server/restart-replacement-not-ready.test.ts`, `tests/cli/link-apply-restart.test.ts`. The Home learns a Child's apply from the Child (`src/link/child-parity.ts`, `src/client/link-parity-reporter.ts`). The linked client runtime POSTs `{linkId, lastApplyAt, runtimeStartedAt, appliedCodexSettingsDigest, sequence}` to `/v1/link-management/child-parity` through the connection-bound relay, shortly after start with backoff and then once a minute; a 404 stops it. On the Home the hub-link listener admits exactly that POST beside the read table, and `src/server/index/link-management.ts` handles it before the passive-read dispatch: the admitting key must own the named link, the body is capped at 8 KiB and 5 s, the parse is strict, and the only effect is an in-memory entry pruned to current links. Entries are ordered by `runtimeStartedAt`, then by `sequence` (process-wide, so a rollback keeps counting), and an older report is ignored, so a late POST from a replaced runtime or an earlier send never moves the row backward. `GET /api/link/status` and `ocx link status --json` carry `lastApplyAt`, `runtimeStartedAt`, `appliedCodexSettingsDigest` and `reportedAt` (epoch ms) on every link row, null without a report; the CLI accepts their absence from an older runtime. Coverage: `tests/server/link-child-parity.test.ts`, `tests/clients/link-parity-reporter.test.ts`. diff --git a/structure/runtime.md b/structure/runtime.md index f4e1f8d7580..b6b70ac48ca 100644 --- a/structure/runtime.md +++ b/structure/runtime.md @@ -107,7 +107,7 @@ does not perform OAuth, and runtime credential resolution rereads the owned sour | `bin/ocx.mjs` | Published npm `bin` entry (Node shim). An inherited explicit `BUN_RUNTIME_TRANSPILER_CACHE_PATH` is scoped to a `bun-` leaf beneath the configured directory — appended on a version change, kept unchanged when the path already ends in that leaf — for the bundled or PATH runtime it starts (`src/lib/bun-transpiler-cache-scope.mjs`), because another Bun version sharing the directory evicts its entries. Before project dotenv: explicit Bun override, bundle, permitted installer recovery, then `src/lib/bun-path-runtime.mjs` validates absolute PATH Bun candidates with canonical regular/executable and size checks, POSIX validation of every original and symlink-expanded ancestor (root or effective-user ownership; group/world write permission is refused in every ancestor, including shared sticky directories), plus non-writable resolved files and final parent directories and a canonical realpath recheck that permits case-variant spelling, and bounded version-policy and identity checks (`--version` must match `-e`'s `Bun.version`; stable version has the dependency pin's major and is at least the pinned version); PATH selection stamps `process` with its canonical path and prints a version-only stderr notice. Failure names an executable macOS Desktop CLI when present without delegating. The proof-bound Anthropic snapshot, signal/exit propagation and zero-install updater inspection stay intact. `src/cli/version-skew-notice.ts`, called from `src/cli/root.ts`, makes one identity-checked 200 ms advisory probe for start/stop/restart/update/service, excluding JSON/help/internal; Node-managed update bypasses this notice. Before package repair or Bun resolution, `src/lib/desktop-cli-record.mjs` validates the bounded settled Desktop command record before JSON (POSIX private ownership/modes, no symlinks, matching no-follow nonblocking descriptor and macOS ACL checks; failures are `record-unsafe`) and `src/lib/desktop-cli-handoff.mjs` delegates eligible POSIX commands to its validated target with a regenerated argv proof, inherited IO and mirrored exit/signal. Windows always retains the package path and selects Desktop through user `Path` order. Update, removal, `capabilities --contracts`, internal inspection and `OCX_NO_DESKTOP_HANDOFF=1` retain the package path; an enabled, settled Desktop selection never resumes the package path when its target is missing or spawning fails. Repair or disable the terminal command, or explicitly opt out for a package invocation. Command selection is separate from runtime/service authority; see [command selection](cli-management.md#ocx-command-selection). | | `src/lib/bun-runtime.ts` | Bundled-Bun resolution: `isRealBunBinary()` (size gate vs the ~450-byte placeholder stub), `bundledBunPath()`, and `durableBunPath()` (path baked into service/shim artifacts). Durable selection accepts only the source/path pair already stamped for the running executable; it never re-reads a project-dotenv `OPENCODEX_BUN_PATH`. | | `src/lib/plain-data.ts` | Detached copies for a consumer that must not observe later edits. Descriptor-based reads, including array elements, so an accessor is refused rather than invoked; refuses cycles, functions, class instances and anything else JSON could not have produced, and returns a copy-or-refusal union rather than degrading silently. Symbol-keyed process bookkeeping is skipped. Each copied object property, including one named `__proto__`, is defined as an own data property on the detached copy; object properties whose value is `undefined` are omitted, and arrays copy only their indexed elements. | -| `src/cli/index.ts` | `ocx` / `opencodex` CLI. Lifecycle: init, start, stop, restart, status, sync, restore/eject, gui, service, update. Stop preserves connected hub/Link client integrations; disconnect owns their teardown, and start serves them without re-injecting routing. `restart` refuses an in-place restart requested by a CLI whose version differs from the attested `/healthz` version; a newer CLI may use the guarded standalone update path described below, because an in-place replacement respawns from the live installation; placeholder versions (unknown/0.0.0) stay incomparable and keep the restart path. Configuration: provider, account, models, combo/route, access, integrations, v2. Client launchers: Claude, OpenCode, MiniMax Code, and MiniMax CLI text. The MMX launcher owns a child-lifetime loopback path bridge from the client's hard-coded `/anthropic/v1/messages` path to the canonical `/v1/messages` data plane; the server does not expose an extra auth surface. Diagnostics: doctor, debug, observe, health. Windows adds tray. Hidden `__update-badge` prints the read-only package badge JSON without refresh or shim repair for the npm tray. The full top-level reference is rendered by `src/cli/help.ts`; this table names the groups, not every verb. After help/version and unknown-root early exits, recognized commands run the bounded best-effort Codex-shim auto-restore policy before dispatch. `status`, `doctor`, and `codex-shim status` skip shim auto-repair; `system codex-cli-update` and [command-local messaging](local-messaging.md#command-local-cli) suppress it for their whole namespaces, including malformed invocations. Keeps the `#!/usr/bin/env bun` shebang for from-source dev (`bun run src/cli/index.ts`). `src/cli/init.ts` validates an explicit setup port as a decimal integer from 1 through 65535 before publishing the initial configuration. Only an empty answer selects 10100; malformed input is reported and the port question is asked again, while EOF or SIGINT still cancels without saving. | +| `src/cli/index.ts` | `ocx` / `opencodex` CLI. Lifecycle: init, start, stop, restart, status, sync, restore/eject, gui, service, update. Stop preserves connected hub-client integrations; Link Child stop restores its owned routing according to the shutdown contract below. A sibling stop reads the marker before stopping the runtime and skips manager stops, teardown claims, shared restoration and system-env rollback. An attested native Link sibling uses the [process-only sibling stop](remote-link.md) after the CLI verifies the serving Link owner and process incarnation. A guarded stop refuses a manager approval that conflicts with the sibling marker. Client start does not re-inject routing. `restart` refuses an in-place restart requested by a CLI whose version differs from the attested `/healthz` version; a newer CLI may use the guarded standalone update path described below, because an in-place replacement respawns from the live installation; placeholder versions (unknown/0.0.0) stay incomparable and keep the restart path. Configuration: provider, account, models, combo/route, access, integrations, v2. Client launchers: Claude, OpenCode, MiniMax Code, and MiniMax CLI text. The MMX launcher owns a child-lifetime loopback path bridge from the client's hard-coded `/anthropic/v1/messages` path to the canonical `/v1/messages` data plane; the server does not expose an extra auth surface. Diagnostics: doctor, debug, observe, health. Windows adds tray. Hidden `__update-badge` prints the read-only package badge JSON without refresh or shim repair for the npm tray. The full top-level reference is rendered by `src/cli/help.ts`; this table names the groups, not every verb. After help/version and unknown-root early exits, recognized commands run the bounded best-effort Codex-shim auto-restore policy before dispatch. `status`, `doctor`, and `codex-shim status` skip shim auto-repair; `system codex-cli-update` and [command-local messaging](local-messaging.md#command-local-cli) suppress it for their whole namespaces, including malformed invocations. Keeps the `#!/usr/bin/env bun` shebang for from-source dev (`bun run src/cli/index.ts`). `src/cli/init.ts` validates an explicit setup port as a decimal integer from 1 through 65535 before publishing the initial configuration. Only an empty answer selects 10100; malformed input is reported and the port question is asked again, while EOF or SIGINT still cancels without saving. | | `src/cli/root.ts`, `src/cli/help.ts`, `src/cli/help-navigation.ts` | CLI head and compact/full help; see [head and help navigation](cli-management.md#head-and-help-navigation). | | `src/cli/help-catalog.ts`, `src/cli/help-models-context.ts`, `src/cli/help-recovery.ts` | Pure help resolution, contextual recovery and output sinks; see [head and help navigation](cli-management.md#head-and-help-navigation). | | `src/server/index.ts` | Bun server entrypoint: `startServer`, `/v1/responses` HTTP + WebSocket routing (compact handled before generic Responses), exact `POST /v1/images/generations` and `POST /v1/images/edits` routing, `/v1/models`, the Anthropic-shaped `/v1/messages` and OpenAI-shaped `/v1/chat/completions` compatibility surfaces, the Live/Realtime surface, the hosted-search relay, artifact serving, `/healthz`, the `/api/*` auth gate, the `/v1/*` JSON 404 guard, GUI fallback, the opt-in loopback-only hub-management listener, and facade re-exports for split server modules. The route table itself is built by `src/server/index/serve-options.ts`; this entry file owns the listener and the startup transaction. | @@ -177,7 +177,7 @@ described in [OpenAI quota ownership](providers/openai-tiers.md#public-provider- `runtime-port.json` through `src/config/process-state.ts`, syncs Codex config/catalog, then serves until shutdown. Standalone shutdown restores native Codex; connected hub clients preserve connection-owned Codex routing, catalog and Grok config across `ocx stop`/`ocx start`. An ordinary runtime rechecks persisted connection ownership in its exit cleanup: a connected Remote Link Child remains subject to the existing native Codex/Grok restoration decisions. Graceful signal shutdown runs that synchronous cleanup after draining and before releasing the listener. Sibling, recycling and service-managed exit exclusions remain intact; receipt-backed API stop may explicitly defer shared restoration to the stopping client. Only an accepted receipt deferral in `src/server/stop-teardown.ts` latches that process's exit deferral; CLI exit cleanup keeps native Codex and Grok restoration with the parent, while still stopping background owners and removing runtime records. Client start does not re-inject routing: use `ocx sync --restart-codex` to reapply it, or `ocx disconnect` to release connection ownership. A sibling instance beside a live proxy ([Codex home](codex-home.md#codex-home)) syncs and restores nothing, and `ocx stop` of a runtime whose record carries `siblingOfPort` skips the shared teardown. `src/cli/index.ts` resolves same-home ownership, then checks shared client hints through the cross-home owner helper, then reconciles the journal only when no sibling is marked. An indeterminate cross-home result refuses a new start before binding or publication, rather than persisting an unverified sibling topology; the next start performs fresh discovery. Service mode sets `OCX_SERVICE=1`, so managed restarts do not repeatedly restore/reinject; scheduler failure diagnostics follow the [service command contract](ops/service-and-sidecars.md#background-service-command-selection). Explicit service stop and -uninstall still restore. Native client signal cleanup follows the [served-connection and supervisor boundaries](remote-link.md); client update stops use full parent restoration because client start cannot discharge standalone handover receipts. `src/service/cli.ts` removes the service token on uninstall only when persisted client state is disconnected and no pending connect marker owns the newly issued key. `src/client/connect.ts` publishes that fingerprint marker before the key, then clears it with the connection commit or rollback under the client lifecycle and config mutation locks. Connected, invalid, or mismatched client state retains an existing token. A valid pending marker retains only its matching fingerprint; an older marker does not own a replacement service key. An absent token is reported as absent; unsafe, malformed, or unreadable markers and lock, state-read, or deletion failures leave cleanup unverified. +uninstall still restore. Explicit stop requires connected-client preflight before manager or process mutation when saved client state, Link receipts, a live client runtime record, an attested Link fence or client-role health indicates client ownership. Standalone stop uses the ordinary manager, PID fallback and restore path. Without usable HTTP attestation, `src/cli/stop-restore.ts` can authorize the ordinary stop from a matching tracked runtime record in the absence of client or Link evidence. It matches the recorded OS creation identity when present. An older record requires a same-user OpenCodex start process and OS listener ownership on the recorded endpoint. The socket check requires a wildcard listener for a recorded wildcard bind and an exact listener for IPv4 loopback. Linux and macOS also require the live process home and caller home to resolve to existing directories with the same filesystem device and inode. A relative `OPENCODEX_HOME` is resolved against the target process’s working directory and requires a readable absolute cwd. Both paths must still resolve to the originally verified directory at the manager and signal boundaries. On Windows, CIM exposes the owner SID and creation time but no process environment, so the legacy proof uses the same-user SID, exact start argv and the PID's ownership of the exact recorded listener. The stop rechecks the accepted incarnation and record before acting on a live PID. A live tracked PID with unverified role refuses before manager or process mutation unless it is bound to a matching service registration. An exact runtime endpoint can back an update handover. When a verified standalone stop lacks an exact runtime endpoint, a guessed endpoint can record a teardown obligation and the parent restores after shutdown. Native client signal cleanup, process incarnation checks and the explicit-stop file-route preflight follow the [served-connection and supervisor boundaries](remote-link.md); an unsupervised signal retains the listener and sync fence for a file or native-restoration refusal, while explicit stop refuses before termination for a file cleanup or inherited teardown preflight failure. Native teardown receipts never skip unsupervised file cleanup or its fence. Native signal deferral additionally requires the current exact-runtime explicit-stop marker and a bounded exact-endpoint receipt owned by a live same-user stop invocation; uncertain ownership retains the listener, while a verified current parent can recover coexisting stale exact-endpoint claims. The parent claims its durable receipt before mutating a manager or sending a stop to a live Link Child. For an inherited receipt on a different endpoint, the parent must prove absence and bind the exact receipt snapshot to its claim. The Child requires that snapshot for signal deferral. The parent rechecks endpoint absence after shutdown and before restoration. With an unreadable Linux manager, offline Link cleanup requires `lstat` to report `ENOENT` for the installer unit and every service installation state path. All known endpoints must also be down. Client update stops use full parent restoration because client start cannot discharge standalone handover receipts. `src/service/cli.ts` removes the service token on uninstall only when persisted client state is disconnected and no pending connect marker owns the newly issued key. `src/client/connect.ts` publishes that fingerprint marker before the key, then clears it with the connection commit or rollback under the client lifecycle and config mutation locks. Connected, invalid, or mismatched client state retains an existing token. A valid pending marker retains only its matching fingerprint; an older marker does not own a replacement service key. An absent token is reported as absent; unsafe, malformed, or unreadable markers and lock, state-read, or deletion failures leave cleanup unverified. `src/cli/tray-proxy.ts` coordinates `ocx restart` and tray restart. A second start requires proof the prior attempt never launched or its child exited, plus confirmed absence under a fresh bounded discovery window; a missing health response alone is insufficient. After an accepted restart, polling continues through uncertain observations until its deadline and requires a new runtime PID on the same port. If the old proxy then disappears, explicit recovery starts it regardless of the Codex autostart preference; a skipped recovery fails rather than reporting success. The Windows tray startup-health probe in `src/tray/windows-tray.ps1` requests termination at its 30-second deadline without waiting on the UI thread. It retains the process through later ticks until actual exit and both redirected readers settle; replacements cannot start while that reference is held. Launch setup failures follow the same cleanup. Tray shutdown alone waits at most 500 ms before disposal. `ocx restart` also restarts a connected client runtime, which serves the same bound `POST /api/system/restart` from its client listener; the CLI sends that request only while the client's 90-second restart budget still fits before replacement observation ends (`CLIENT_RESTART_REQUEST_MIN_REMAINING_MS`), and reports a supervised client's `409 restart_supervised` as "not performed, runtime kept"; a client whose connection was removed recycles to standalone when its owner is proven (`restartOwnerProven`), except that a manager whose relaunch is not proven (`service-unproven`) still refuses; a bare OCX_SERVICE=1 is refused as `legacy-flag` with advice to re-register the service once (`ocx service repair`), and nothing is stopped on inference (#8545). See [Remote Link](remote-link.md) for the rollback. The Remote Link Child listener checks its startup owner and link against durable client state once per `/readyz`, after readiness probing, and for authenticated machine/link status only on those routes. If they differ, `/readyz` and those status routes answer 503 with `client_state_changed`; the dashboard shows that reason with its recovery guidance. This reports divergence; it does not disconnect the relay or reconstruct a connection. `tests/clients/client-machine-listener.test.ts` covers missing and replaced records. Explicit `ocx disconnect --orphaned-token --yes` in `src/client/orphan-token-recovery.ts` preserves unowned token files only after the start lease, lifecycle lock, liveness proof and config-lock revalidation; Hub, admission-token use and installed or unverified services refuse. Windows closes source handles before rename while private hard links pin identity; a refusal removes a pin only while another name still holds the token, and an extra hard link left by an interrupted run is refused with a message naming the `.identity` pin to remove from the `orphaned-token-*` folder. Missing ownership is never reconstructed. `ocx config import` refuses to replace a connected client record under the config lock. `tests/clients/client-link-connect.test.ts` covers these refusals and local liveness. @@ -335,7 +335,7 @@ field for every tool. Only bare or `default.`-prefixed `exec` and `apply_patch` one recognized alternate body field or remove one complete outer Markdown fence; ambiguous alternate fields and every other freeform grammar pass through unchanged. -The server exposes read-only authenticated `GET /api/stop` with `schema: "ocx-stop-capabilities/1"`, PID and connected-client preservation for API, signal and manager shutdown. Before a connected-client service stop, `src/cli/stop-restore.ts` pins the protected runtime record's PID, port, hostname and attestation key and requires a fresh health proof. A proven client-role listener needs no capability route; an ordinary proxy also requires a valid response proof and preservation document from a single-use `GET /api/stop` capability. Both preflight reads omit reusable credentials and refuse a changed runtime record, sharing a two-second deadline and 4 KiB document limits. The probes use the proxy-independent TCP transport in `src/server/direct-local-http.ts`. `src/lib/process-control.ts` defaults every local runtime stop POST to that direct transport, ignoring HTTP(S)/ALL proxy environment variables for CLI stop, service cleanup and uninstall; its injected `fetchFn` takes precedence. The later POST retains ordinary management authorization and the existing target recheck before POST/kill. A stopped connected client skips manager mutation only after the manager is observed inactive and all known local endpoints are definitively dead; the ordinary receipt and environment cleanup still runs. `POST /api/stop`: `src/server/stop-teardown.ts` checks sibling then validated persisted connected-client ownership before receipt deferral or restoration. Sibling and connected hub client owners answer `sharedTeardown: "not-owned"` without restoring Codex/catalog or stripping Grok; an existing receipt remains outstanding. A Remote Link Child restores like an ordinary owner. The stopping CLI accepts `not-owned` unless the connection state read at the POST positively identifies a Link Child: only an older runtime answers `not-owned` for a link connection, and it does so while preserving the loopback route the stop must restore. The parent's `restoreBoundaryOwnership` inspection takes L but grants no write authority. `src/client/restore-ownership.ts`, re-exported by `src/cli/stop-restore-guard.ts`, revalidates committed ownership, pending connect markers and disconnect recovery under C at every restoration write. Stop history restoration takes H before C; each synchronous provider attempt keeps C from ownership validation through DB commit, rollout writes and manifest consumption or failure finalization. The Worker receives the stop policy as data, validates under its own C acquisition and returns a structured ownership refusal that the parent guard retains. Synchronous exit restoration takes the same H/C boundary; no C lease spans a Worker await or a retry delay. Config/profile/journal restoration uses the config-file lock and N/C on coordinated homes; legacy restoration uses the file lock and C. Catalog restoration takes K before C. Approved-provider URL restoration after history, Grok stripping and receipt discharge each revalidate under C again after awaits. Connection publication cannot interleave between a check and its synchronous writes. The default API stop and synchronous signal cleanup use the same guard for their native config/catalog and Grok writes, including approved-provider cleanup after history. An unproven API boundary returns HTTP 409 with `sharedTeardown: "refused"` before shutdown is scheduled; signal cleanup reports failure without restoring over it. Each pending API stop holds its own temporary automatic-restart veto; refusal or a thrown teardown releases only that intent, while accepted stops and signals retain a permanent veto. A refused stop therefore leaves later package-replacement restart available. An already admitted automatic restart waits for temporary intents to settle instead of losing its one-shot package notification; its original deadline remains the budget basis. These checks never acquire L inside N/C, acquire N inside L, or await inside a synchronous lock callback. A hub owner supersedes only the identified receipts, settled under C; pending, invalid, mismatched or busy state refuses the remaining restoration and keeps its obligations. `tests/service/stop-deferred-teardown.test.ts` covers post-inspection transitions and real config-file/N writer contention. Other owners restore native Codex/Grok, or defer only with the matching receipt. The route stops any installed service +The server exposes read-only authenticated `GET /api/stop` with `schema: "ocx-stop-capabilities/1"`, PID and connected-client preservation for API, signal and manager shutdown. Before a connected-client service stop, `src/cli/stop-restore.ts` pins the protected runtime record's PID, port, hostname and attestation key and requires a fresh health proof. A proven client-role listener needs no capability route; an ordinary proxy also requires a valid response proof and preservation document from a single-use `GET /api/stop` capability. Both preflight reads omit reusable credentials and refuse a changed runtime record, sharing a two-second deadline and 4 KiB document limits. The probes use the proxy-independent TCP transport in `src/server/direct-local-http.ts`. `src/lib/process-control.ts` defaults every local runtime stop POST to that direct transport, ignoring HTTP(S)/ALL proxy environment variables for CLI stop, service cleanup and uninstall; its injected `fetchFn` takes precedence. The later POST retains ordinary management authorization. For a native Link Child, the CLI matches the serving ownership fingerprint to the saved Link connection and requires attested Link stop-fence support before cleanup. It rechecks file-cleanup authority at the manager and process boundaries, including forced fallback. Invalid or mismatched saved connection state refuses before either path. A native Hub listener also needs a published Hub identity, so an older unclassified Link runtime cannot inherit a stale saved Hub connection's stop policy. Only the live owner incarnation named by the fenced nonce can take native restoration through its matching receipt. A stopped connected client skips manager mutation only after the manager is observed inactive and all known concrete local endpoints are definitively dead. Configured port `0` supplies no endpoint; at least one concrete recorded endpoint is still required, and invalid nonzero ports refuse. The ordinary receipt and environment cleanup still runs. `POST /api/stop`: `src/server/stop-teardown.ts` checks sibling then validated persisted connected-client ownership before receipt deferral or restoration. Sibling and connected hub client owners answer `sharedTeardown: "not-owned"` without restoring Codex/catalog or stripping Grok; an existing receipt remains outstanding. A Remote Link Child restores like an ordinary owner. The stopping CLI accepts `not-owned` unless the connection state read at the POST positively identifies a Link Child: only an older runtime answers `not-owned` for a link connection, and it does so while preserving the loopback route the stop must restore. The parent's `restoreBoundaryOwnership` inspection takes L but grants no write authority. `src/client/restore-ownership.ts`, re-exported by `src/cli/stop-restore-guard.ts`, revalidates committed ownership, pending connect markers and disconnect recovery under C at every restoration write. Stop history restoration takes H before C; each synchronous provider attempt keeps C from ownership validation through DB commit, rollout writes and manifest consumption or failure finalization. The Worker receives the stop policy as data, validates under its own C acquisition and returns a structured ownership refusal that the parent guard retains. Synchronous exit restoration takes the same H/C boundary; no C lease spans a Worker await or a retry delay. Config/profile/journal restoration uses the config-file lock and N/C on coordinated homes; legacy restoration uses the file lock and C. Catalog restoration takes K before C. Approved-provider URL restoration after history, Grok stripping and receipt discharge each revalidate under C again after awaits. Connection publication cannot interleave between a check and its synchronous writes. The default API stop and synchronous signal cleanup use the same guard for their native config/catalog and Grok writes, including approved-provider cleanup after history. An unproven API boundary returns HTTP 409 with `sharedTeardown: "refused"` before shutdown is scheduled; signal cleanup reports failure without restoring over it. Each pending API stop holds its own temporary automatic-restart veto; refusal or a thrown teardown releases only that intent, while accepted stops and signals retain a permanent veto. A refused stop therefore leaves later package-replacement restart available. An already admitted automatic restart waits for temporary intents to settle instead of losing its one-shot package notification; its original deadline remains the budget basis. These checks never acquire L inside N/C, acquire N inside L, or await inside a synchronous lock callback. A hub owner supersedes only the identified receipts, settled under C; pending, invalid, mismatched or busy state refuses the remaining restoration and keeps its obligations. `tests/service/stop-deferred-teardown.test.ts` covers post-inspection transitions and real config-file/N writer contention. Other owners restore native Codex/Grok, or defer only with the matching receipt. The route stops any installed service (to prevent respawn), and exits the process. Without an owned deferral receipt, the non-sibling API route first checks connection ownership under C; an unproven boundary refuses before manager mutation. The temporary stop intent covers this check and service stop as well as teardown, and every early return or exception releases only that intent. The preflight grants no write authority and no C lease reaches the manager or an await. Synchronous H lock unavailability reports a history-only artifact failure through the Worker outcome formatter, leaving Grok cleanup free to revalidate under C. `tests/service/stop-restoration-preflight.test.ts` covers real H contention and a refused API stop with zero manager calls and continued serving. The GUI sidebar stop button calls this endpoint. An observed 409 remains a stop refusal even when its response body is truncated or times out; the direct transport exposes the parsed status before body completion so the stop helper retains that decision. The CLI-selected transport delegates to the same status-preserving direct helper as the default; truncated and stalled refusal bodies never authorize a forced kill. Real history and transport coverage lives in `tests/service/stop-restore-history-ownership.test.ts` and `tests/cli/cli-stop-refusal-transport.test.ts`. > Decision record: [ADR-0004](decisions/ADR-0004-lifecycle.md) diff --git a/tests/cli/cli-client-start-fence.test.ts b/tests/cli/cli-client-start-fence.test.ts index b84e8871426..5c7e47b2a14 100644 --- a/tests/cli/cli-client-start-fence.test.ts +++ b/tests/cli/cli-client-start-fence.test.ts @@ -139,7 +139,7 @@ describe("connected-client start ownership fence", () => { // released only once the first serve() returned, i.e. after publication. const serve = runtime.slice(runtime.indexOf("const serve = async"), runtime.indexOf("const stopServing")); // Each publication also stamps a fresh servingGeneration (restart sync fence, #8416). - expect(serve).toMatch(/writePid\(process\.pid\);\s*\n(?:\s*\/\/[^\n]*\n)*\s*writeRuntimePort\(\{ \.\.\.clientRuntimeRecord\(process\.pid, boundPort, attestationSecret\), servingGeneration: randomUUID\(\) \}\);/); + expect(serve).toMatch(/writePid\(process\.pid\);\s*\n(?:\s*\/\/[^\n]*\n)*\s*writeRuntimePort\(\{ \.\.\.clientRuntimeRecord\(process\.pid, boundPort, attestationSecret\), servingGeneration: randomUUID\(\),\s+clientLinkOwner \}\);/); expect(runtime).toMatch(/await serve\(\);\s*\n\s*options\.afterPublish\?\.\(\);/); }); }); diff --git a/tests/cli/cli-dispatch.test.ts b/tests/cli/cli-dispatch.test.ts index a86a097e01a..e88eccf44d9 100644 --- a/tests/cli/cli-dispatch.test.ts +++ b/tests/cli/cli-dispatch.test.ts @@ -30,7 +30,6 @@ import { getConfigDir } from "../../src/config"; import { getAccountSet, removeCredential, saveCredential } from "../../src/oauth/store"; import { removeTreeWithRetry } from "../helpers/remove-tree"; import { repoPath } from "../helpers/repo-root"; -import type { OcxConfig } from "../../src/types"; /** Minimal fake deps. dispatchCommand only touches deps for real command * runners, which these tests never invoke, so an empty object is enough. */ @@ -640,11 +639,16 @@ describe("a sibling start leaves shared client routing to the live owner", () => test("ocx stop of a sibling claims no receipt and restores nothing", () => { const stop = slice("async function handleStopUnlocked(", "async function handleUninstall("); - const readAt = stop.indexOf("const siblingOfPort = readRuntimePort()?.siblingOfPort;"); + const readAt = stop.indexOf("const initialRuntime = readRuntimePort();"); + const siblingAt = stop.indexOf("const siblingOfPort = initialRuntime?.siblingOfPort;"); expect(readAt).toBeGreaterThan(-1); - // Read before the first stop can remove the record. - expect(readAt).toBeLessThan(stop.indexOf("stopServiceForOcxStop(")); - expect(stop).toContain("if (teardownNonce || stoppingSibling) return;"); + expect(siblingAt).toBeGreaterThan(readAt); + // Pin the marker before either stop path can remove the on-disk record. + for (const mutation of ["stopProxy(", "stopServiceForOcxStop(", "stopGuardedManager(", "removeRuntimePort("]) { + expect(stop.indexOf(mutation)).toBeGreaterThan(siblingAt); + } + expect(stop).toContain("const stoppingSibling = siblingOfPort !== undefined;"); + expect(stop).toContain("if (teardownNonce || stoppingSibling || (!linkStop && connectedClientSkip)) return;"); // #7563 adds a connected client to the same gate; the sibling term is unchanged. expect(stop).toContain("const restoreBlocked = ownershipBlocked || inheritedBlocks || nativeRestoreHandledByProxy || stoppingSibling || connectedClientSkip !== null;"); expect(stop).toContain('if (nativeRestoreHandledByProxy && !stoppingSibling && !connectedClientSkip) record.sharedTeardown = "performed-by-proxy";'); @@ -655,10 +659,14 @@ describe("a sibling start leaves shared client routing to the live owner", () => // A sibling never runs under a service manager, so an installed one is the live owner's. Asking // it failed the ownership check from the sibling's home: exit 1, and after a hard kill the // stale sibling records were never purged. - // #7423: the non-sibling branch claims an update-handover receipt first; the sibling term is unchanged. - expect(stop).toContain(': stoppingSibling || connectedClientAlreadyStopped ? noServiceStop() : (claimHandoverBeforeManager(), await stopServiceForOcxStop({ receiptNonce: () => teardownNonce, inheritedReceipts: inheritedTeardowns.length }));'); - // The only other caller is the guarded desktop step, which reaches the manager only when it - // provably owns the approved pid; a sibling's pid never is. Both go through the #7771 wiring. + expect(stop).toContain(": stoppingSibling || connectedClientAlreadyStopped ? noServiceStop() : await (async () => {"); + const managerBranch = stop.slice(stop.indexOf(": stoppingSibling || connectedClientAlreadyStopped ? noServiceStop()"), + stop.indexOf("record.service = serviceStop;")); + expect(managerBranch).toMatch(/else claimHandoverBeforeManager\(\);\s+return stopServiceForOcxStop\(\{ receiptNonce: \(\) => teardownNonce, inheritedReceipts: inheritedTeardowns\.length \}\);\s+\}\)\(\);/); + // The guarded desktop step refuses a manager approval for a sibling before #7771 wiring. + const guardedSiblingAt = stop.indexOf('if (stoppingSibling && snapshot && snapshot.manager.kind !== "absent") {\n return approvalChanged('); + expect(guardedSiblingAt).toBeGreaterThan(siblingAt); + expect(guardedSiblingAt).toBeLessThan(stop.indexOf("runGuardedManagerStep(snapshot,")); expect(stop).not.toContain("stopServiceIfInstalledDetailed("); expect(stop.split("stopServiceForOcxStop(").length - 1).toBe(1); expect(stop.split("stopGuardedManager(").length - 1).toBe(1); diff --git a/tests/cli/cli-start-journal-order.test.ts b/tests/cli/cli-start-journal-order.test.ts index f66e8f61739..5f1e450920a 100644 --- a/tests/cli/cli-start-journal-order.test.ts +++ b/tests/cli/cli-start-journal-order.test.ts @@ -182,7 +182,8 @@ describe("start and ensure journal ownership (#1230)", () => { + cli.slice(cli.indexOf("async function handleEnsure("), cli.indexOf("async function handleTrayProxyStart(")); const recovery = readFileSync(repoPath("src/cli/start-owner-fence.ts"), "utf8"); const recheck = recovery.slice(recovery.indexOf("export async function recoverStartJournalAfterOwnerRecheck("), recovery.indexOf("/** Hold ownership stable")); - const executable = new Bun.Transpiler({ loader: "ts" }).transformSync(bodies + recheck.replace("export ", "")); + const relocatedBodies = bodies.replace('"../client/stop-teardown-owner"', JSON.stringify(repoPath("src/client/stop-teardown-owner.ts"))); + const executable = new Bun.Transpiler({ loader: "ts" }).transformSync(relocatedBodies + recheck.replace("export ", "")); const script = join(fx.root, "missed-owner.ts"); writeFileSync(script, ` import { reconcileStartupJournal } from ${JSON.stringify(repoPath("src/cli/cross-home-owner.ts"))}; diff --git a/tests/clients/client-link-stop-recovery.test.ts b/tests/clients/client-link-stop-recovery.test.ts new file mode 100644 index 00000000000..a7d5871b4e4 --- /dev/null +++ b/tests/clients/client-link-stop-recovery.test.ts @@ -0,0 +1,156 @@ +import { expect, test } from "bun:test"; +import { mkdtempSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { fixturePath, repoPath } from "../helpers/repo-root"; +import { removeTreeWithRetry } from "../helpers/remove-tree"; +import { runStop } from "../helpers/client-link-stop"; + +async function runRecovery(mode: string, scheduled = false, env = process.env, attempt = 0): Promise> { + const root = mkdtempSync(join(tmpdir(), "ocx-link-stop-recovery-")); + const child = Bun.spawn([process.execPath, fixturePath("client-link-stop-recovery-runner.ts")], { + cwd: repoPath(), stdin: new Blob([JSON.stringify({ mode, scheduled })]), stdout: "pipe", stderr: "pipe", + env: { ...env, HOME: root, USERPROFILE: root, OPENCODEX_HOME: join(root, "ocx"), CODEX_HOME: join(root, "codex"), + OPENCODEX_CLAUDE_DESKTOP_CONFIG_DIR: join(root, "desktop"), OCX_SERVICE: "", OCX_SERVICE_MANAGED: "0" }, + }); + const timeout = setTimeout(() => child.kill("SIGKILL"), 15_000); + try { + const [exit, stdout, stderr] = await Promise.all([child.exited, new Response(child.stdout).text(), new Response(child.stderr).text()]); + if (exit === 75 && stderr.trim() === "fixture-port-collision") { + if (attempt >= 2) throw new Error("recovery fixture port collided three times"); + return runRecovery(mode, scheduled, env, attempt + 1); + } + expect(exit, stderr).toBe(0); + expect(stderr).not.toContain("uncaughtException"); + const line = stdout.split("\n").find(line => line.startsWith("{")); + expect(line, stdout + stderr).toBeDefined(); + return JSON.parse(line!); + } finally { + clearTimeout(timeout); + if (child.exitCode === null) { child.kill("SIGKILL"); await child.exited; } + removeTreeWithRetry(root); + } +} + +for (const mode of ["parent", "signal"]) for (const scheduled of [false, true]) { + test(`a refused ${mode} stop permits completed disconnect recovery through ${scheduled ? "scheduled recycle" : "bound restart"}`, async () => { + const result = await runRecovery(mode, scheduled); + expect(result).toMatchObject({ beforeRecoveryAdmission: 409, role: "standalone", spawned: 1, + file: { userSetting: "keep" }, state: "disconnected", token: "absent", phase: "complete", runtimePresent: false }); + if (mode === "parent") expect(result).toMatchObject({ stopRefused: true, activeAdmission: 409, finishedMarker: false }); + if (!scheduled) expect(result.recoveryAdmission).toBe(202); + }, 20_000); +} + +for (const mode of ["parent-active", "parent-unverified", "parent-malformed", "parent-malformed-start", "signal-active", "pending", "foreign-owner", "wrong-token", "corrupt-receipt", "missing-config", "new-connection", "pending-connect"]) { + test(`retained stop refuses disconnect recycle while ${mode}`, async () => { + const result = await runRecovery(mode); + expect(result).toMatchObject({ beforeRecoveryAdmission: 409, recoveryAdmission: 409, role: "client", spawned: 0, + file: { userSetting: "keep" }, token: "absent", runtimePresent: true }); + if (mode.startsWith("parent-")) expect(result.marker).toBe(true); + }, 20_000); +} + +test("recovery treats a foreground fixture as foreground even under a service-owned test runner", async () => { + const result = await runRecovery("parent", false, { ...process.env, OCX_SERVICE: "1" }); + expect(result).toMatchObject({ role: "standalone", spawned: 1, recoveryAdmission: 202 }); +}, 20_000); + +test("a parent stop admitted before a recovery timer fires prevents the scheduled replacement", async () => { + const result = await runRecovery("timer-parent-active"); + expect(result).toMatchObject({ role: "client", spawned: 0, state: "disconnected", phase: "complete", marker: true, runtimePresent: true }); +}, 20_000); + +test("a stale stop owner cannot block completed disconnect recovery", async () => { + const result = await runRecovery("parent-stale-owner"); + expect(result).toMatchObject({ recoveryAdmission: 202, role: "standalone", spawned: 1, phase: "complete" }); +}, 20_000); + +test("a refused signal stop can reschedule a canceled recycle after disconnect recovery", async () => { + const result = await runRecovery("signal-pending-recycle"); + expect(result).toMatchObject({ firstRecycleTimers: 1, firstRecycleCanceled: true, beforeRecoveryAdmission: 409, recoveryRecycleTimers: 1, + role: "standalone", spawned: 1, file: { userSetting: "keep" }, state: "disconnected", phase: "complete", runtimePresent: false }); +}, 20_000); + +test("a parent stop remains fenced through an already-admitted restart rollback", async () => { + const report = await runStop({ mode: "file-restart-overlap", preserve: "restart-rollback", fileClients: ["pi"] }); + expect(report.result).toEqual({ preflight: null, rolledBack: true, bound: true, stopping: true, explicitStop: true, + sync: "client_runtime_stopping", admission: { kind: "stopping" } }); + expect(report.fileAfter.pi).not.toContain("127.0.0.1"); + expect(report.protectedUnchanged).toBe(true); +}, 20_000); + +for (const failedRollback of ["before-rebind", "during-rebind"]) { + for (const unverifiedStopOwner of [false, true]) test(`failed rollback (${failedRollback}) cannot recycle over an ${unverifiedStopOwner ? "unverified" : "active"} parent stop`, async () => { + const report = await runStop({ mode: "file-restart-overlap", preserve: "restart-rollback", fileClients: ["pi"], failedRollback, unverifiedStopOwner }); + expect(report.result).toEqual({ preflight: null, replacementAttempts: 1, runtimePresent: true, explicitStop: true }); + expect(report.fileAfter.pi).not.toContain("127.0.0.1"); + }, 20_000); +} + +test.skipIf(process.platform === "win32")("Link stop requires its recovery receipt before attempting any stop action", async () => { + const report = await runStop({ mode: "file-stop", fileClients: ["pi"], receiptWriteFails: true }); + expect(report.result).toEqual({ exitCode: 1, calls: { service: 0, killed: 0 }, bound: true, stopping: true }); + expect(report.after).toBe(report.before); + expect(report.protectedUnchanged).toBe(true); +}, 20_000); + +test("parent preflight retries a busy config lock before fencing the exact runtime", async () => { + const report = await runStop({ mode: "file-preflight", fileClients: ["pi"], busyStopFence: true }); + expect(report.result).toEqual({ outcome: null, bound: true, stopping: true }); + expect(report.fileAfter.pi).not.toContain("127.0.0.1"); +}, 20_000); + +test("restart rollback closes its unpublished listener in the binding turn when the config lock is busy", async () => { + const report = await runStop({ mode: "file-restart-overlap", preserve: "restart-rollback", fileClients: ["pi"], busyRollbackPublication: true }); + expect(report.result).toEqual({ preflight: null, closedBeforeYield: true, published: false, replacementAttempts: 1 }); + expect(report.fileAfter.pi).not.toContain("127.0.0.1"); +}, 20_000); + +for (const retryRollbackPublication of ["lifecycle", "config", "owner-changed"] as const) { + test("restart rollback rechecks its owner after " + retryRollbackPublication + " contention", async () => { + const report = await runStop({ mode: "file-restart-overlap", preserve: "restart-rollback", fileClients: ["pi"], retryRollbackPublication }); + const resumed = retryRollbackPublication !== "owner-changed"; + expect(report.result).toEqual({ preflight: null, closedBeforeYield: true, published: resumed, bound: resumed, + rollbackBinds: resumed ? 2 : 1, replacementAttempts: 1, stopping: true, explicitStop: true }); + expect(report.fileAfter.pi).not.toContain("127.0.0.1"); + }, 20_000); +} + +test("ordinary restart rollback keeps file routes and admits fresh sync", async () => { + const report = await runStop({ mode: "file-restart-control", preserve: "restart-rollback", fileClients: ["pi"] }); + expect(report.result).toEqual({ rolledBack: true, bound: true, stopping: false, explicitStop: false, sync: "accepted" }); + expect(report.fileAfter).toEqual(report.fileOwnedBytes); + expect(report.protectedUnchanged).toBe(true); +}, 20_000); + +test("a finished parent stop preserves the retained sync fence through restart rollback", async () => { + const report = await runStop({ mode: "file-restart-overlap", preserve: "restart-rollback", fileClients: ["pi"], finishStopBeforeRollback: true }); + expect(report.result).toEqual({ preflight: null, rolledBack: true, bound: true, stopping: true, explicitStop: false, retainedStop: true, + sync: "client_runtime_stopping", admission: { kind: "stopping" } }); + expect(report.fileAfter.pi).not.toContain("127.0.0.1"); +}, 20_000); + +test("a pending restart admission cannot leave routing behind on signal shutdown", async () => { + const report = await runStop({ mode: "runtime", preserve: "restart" }); + expect(report.after).toBe('model = "native"\n'); + expect(report.journalRetained).toBe(false); + expect(report.catalogAfter.models).toEqual([{ slug: "fixture-native", visibility: "list" }]); + expect(report.grokAfter).toBe('theme = "fixture"\n'); +}, 20_000); + +test.each(["restart-rollback", "restart-rollback-recycle"])("signal shutdown joins %s before restoring", async preserve => { + const report = await runStop({ mode: "runtime", preserve }); + expect(report.after).toBe('model = "native"\n'); + expect(report.journalRetained).toBe(false); + expect(report.catalogAfter.models).toEqual([{ slug: "fixture-native", visibility: "list" }]); + expect(report.grokAfter).toBe('theme = "fixture"\n'); +}, 20_000); + +test("a scheduled recycle cannot skip restoration or spawn after signal shutdown", async () => { + const report = await runStop({ mode: "runtime", preserve: "recycle-pending" }); + expect(report.after).toBe('model = "native"\n'); + expect(report.journalRetained).toBe(false); + expect(report.catalogAfter.models).toEqual([{ slug: "fixture-native", visibility: "list" }]); + expect(report.grokAfter).toBe('theme = "fixture"\n'); +}, 20_000); diff --git a/tests/clients/client-link-stop-sibling.test.ts b/tests/clients/client-link-stop-sibling.test.ts new file mode 100644 index 00000000000..34da1579848 --- /dev/null +++ b/tests/clients/client-link-stop-sibling.test.ts @@ -0,0 +1,335 @@ +import { expect, test } from "bun:test"; +import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, realpathSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { dirname, join } from "node:path"; +import { fixturePath, repoPath } from "../helpers/repo-root"; +import { removeTreeWithRetry } from "../helpers/remove-tree"; +import { runStop } from "../helpers/client-link-stop"; +import { isClientStopArgv, isClientStopCommandLine, observeClientStopOwner, readClientStopProcessStart } from "../../src/client/stop-teardown-owner"; + +test("Linux Link forced stop refuses an unavailable pidfd without sending a numeric signal", async () => { + const report = await runStop({ mode: "termination", terminationPlatform: "linux" }); + expect(report.result).toMatchObject({ signals: [], message: expect.stringContaining("pidfd") }); +}, 20_000); + +test.each(["stopping", "different-generation"] as const)("Linux Link sibling escalation after TERM with %s", async siblingEscalation => { + const { result } = await runStop({ mode: "runtime", preserve: "sibling", siblingEscalation }); + expect(result).toEqual({ + signals: siblingEscalation === "stopping" ? [[73, 15], [73, 9]] : [[73, 15]], + openedExactlyOnceForTarget: true, closed: [73], stopping: true, + ...(siblingEscalation === "different-generation" ? { refusal: expect.stringContaining("Connected-client stop refused") } : {}), + }); +}, 20_000); + +test("macOS Link stop sends only an orderly signal when the attested Child remains live", async () => { + const report = await runStop({ mode: "termination", terminationPlatform: "darwin" }); + expect(report.result).toMatchObject({ signals: ["SIGTERM"], message: expect.stringContaining("foreground terminal") }); +}, 20_000); + +for (const stopConnectionDrift of ["invalid", "mismatched", "disconnected", "other-link", "hub"]) { + test(`ocx stop refuses a live Link Child with ${stopConnectionDrift} saved ownership`, async () => { + const report = await runStop({ mode: "file-stop", fileClients: ["pi"], stopConnectionDrift, expectedUnsupportedStop: true }); + expect(report.result).toEqual({ exitCode: 1, calls: { service: 0, killed: 0 }, bound: true, stopping: false }); + expect(report.fileAfter).toEqual(report.fileOwnedBytes); + }, 20_000); +} + +for (const missingStopRecord of ["absent", "invalid"]) { + test(`ocx stop retains a live tracked Child with a disconnected saved state and ${missingStopRecord} runtime record`, async () => { + const report = await runStop({ mode: "file-stop", fileClients: ["pi"], stopConnectionDrift: "disconnected", + missingStopRecord, expectedUnsupportedStop: true }); + expect(report.result).toEqual({ exitCode: 1, calls: { service: 0, killed: 0 }, bound: true, stopping: false }); + expect(report.fileAfter).toEqual(report.fileOwnedBytes); + }, 20_000); +} + +test("ocx stop refuses a new process incarnation after an unanswered Link stop", async () => { + const report = await runStop({ mode: "file-stop", fileClients: ["pi"], startIdentityChanges: "request", expectedUnsupportedStop: true }); + expect(report.result).toEqual({ exitCode: 1, calls: { service: 1, killed: 0 }, bound: true, stopping: true }); + expect(report.fileAfter.pi).not.toContain("127.0.0.1"); +}, 20_000); + +test.skipIf(process.platform === "win32")("ocx stop refuses escalation when the Child incarnation changes after SIGTERM", async () => { + const report = await runStop({ mode: "file-stop", fileClients: ["pi"], startIdentityChanges: "escalation", expectedUnsupportedStop: true }); + expect(report.result).toEqual({ exitCode: 1, calls: { service: 1, killed: 1 }, bound: true, stopping: true }); + expect(report.fileAfter.pi).not.toContain("127.0.0.1"); +}, 20_000); + +test("ocx stop rechecks Link ownership before forced fallback after an unanswered stop", async () => { + const report = await runStop({ mode: "file-stop", fileClients: ["pi"], driftDuringFallback: true, expectedUnsupportedStop: true }); + expect(report.result).toEqual({ exitCode: 1, calls: { service: 1, killed: 0 }, bound: true, stopping: true }); + expect(report.fileAfter.pi).not.toContain("127.0.0.1"); +}, 20_000); + +test("the legacy Link refusal gives a connection-preserving recovery in execution order", async () => { + const report = await runStop({ mode: "file-stop", fileClients: ["pi"], oldStopCapability: true, + legacyOwnerRecord: true, expectedUnsupportedStop: true, expectLegacyRecovery: true }); + expect(report.result).toEqual({ exitCode: 1, calls: { service: 0, killed: 0 }, bound: true, stopping: false }); + expect(report.fileAfter).toEqual(report.fileOwnedBytes); +}, 20_000); + +test("an older native Child cannot be treated as Hub-owned from saved config alone", async () => { + const report = await runStop({ mode: "file-stop", fileClients: ["pi"], oldStopCapability: true, + legacyOwnerRecord: true, stopConnectionDrift: "hub", expectedUnsupportedStop: true }); + expect(report.result).toEqual({ exitCode: 1, calls: { service: 0, killed: 0 }, bound: true, stopping: false }); + expect(report.fileAfter).toEqual(report.fileOwnedBytes); +}, 20_000); + +for (const preserve of ["service", "desktop", "sibling"]) { + test(`native Link signal preserves ${preserve} restoration ownership`, async () => { + const report = await runStop({ mode: "runtime", preserve, fileClients: ["pi"] }); + expect(report.after).toBe(report.before); + expect(report.profileAfter).toBe(report.profileBefore); + expect(report.journalRetained).toBe(true); + expect(report.protectedUnchanged).toBe(true); + expect(report.catalogAfter).toEqual(JSON.parse(report.catalogBefore)); + expect(report.grokAfter).toBe(report.grokBefore); + expect(report.fileAfter).toEqual(report.fileOwnedBytes); + }, 20_000); +} + +for (const receiptState of ["live", "abandoned", "quarantined", "invalid", "parent-invalid", "parent-start", "parent-status", "parent-unfenced", "parent-finished", "parent-port", "parent-host", "parent-guessed", "parent-oversized", "parent-nonregular", "parent-reused", "parent-wrong-nonce", ...(process.platform === "win32" ? [] : ["parent-symlink"])]) { + test(`an unverified native teardown (${receiptState}) cleans files but retains its listener`, async () => { + const report = await runStop({ mode: "runtime", preserve: "receipt", receiptState, fileClients: ["pi"], + observeNativeRefusal: true, expectedRefusal: true }); + expect(report.result).toEqual({ refused: true, bound: true, stopping: true }); + expect(report.fileAfter.pi).not.toContain("127.0.0.1"); + expect(JSON.parse(report.fileAfter.pi)).toMatchObject({ fixtureUserSetting: "keep" }); + expect(report.teardownOutstanding).toBe(true); + expect(report.after).toBe(report.before); + expect(report.profileAfter).toBe(report.profileBefore); + expect(report.journalRetained).toBe(true); + expect(report.catalogAfter).toEqual(JSON.parse(report.catalogBefore)); + expect(report.grokAfter).toBe(report.grokBefore); + expect(report.protectedUnchanged).toBe(true); + }, 20_000); +} + +for (const receiptState of ["invalid", "abandoned-guessed", "abandoned-other", "abandoned-unknown"]) { + test(`ocx stop refuses inherited native teardown (${receiptState}) before service or process termination`, async () => { + const report = await runStop({ mode: "file-stop", preserve: "receipt", receiptState, fileClients: ["pi"], expectedNativePreflightRefusal: true }); + expect(report.result).toEqual({ exitCode: 1, calls: { service: 0, killed: 0 }, bound: true, stopping: false }); + expect(report.fileAfter).toEqual(report.fileOwnedBytes); + expect(report.after).toBe(report.before); + expect(report.profileAfter).toBe(report.profileBefore); + expect(report.journalRetained).toBe(true); + expect(report.teardownOutstanding).toBe(true); + expect(report.grokAfter).toBe(report.grokBefore); + }, 20_000); +} + +for (const receiptState of ["abandoned", "abandoned-dead-other", "quarantined"]) { + test(`native recovery preflight keeps the supported ${receiptState} parent stop`, async () => { + const report = await runStop({ mode: "file-preflight", preserve: "receipt", receiptState, fileClients: ["pi"] }); + expect(report.result).toEqual({ outcome: null, bound: true, stopping: true }); + expect(report.fileAfter.pi).not.toContain("127.0.0.1"); + expect(report.teardownOutstanding).toBe(true); + expect(report.after).toBe(report.before); + expect(report.profileAfter).toBe(report.profileBefore); + expect(report.protectedUnchanged).toBe(true); + }, 20_000); +} + +test("ocx stop refuses a native Link sibling whose published owner differs from the saved Link", async () => { + const report = await runStop({ mode: "file-stop", preserve: "sibling", fileClients: ["pi"], + stopConnectionDrift: "other-link", expectedUnsupportedStop: true }); + expect(report.result).toEqual({ exitCode: 1, calls: { service: 0, killed: 0 }, bound: true, stopping: false }); + expect(report.fileAfter).toEqual(report.fileOwnedBytes); +}, 20_000); + +test.skipIf(process.platform === "win32")("ocx stop stops an attested native Link sibling without touching shared routing", async () => { + const root = realpathSync(mkdtempSync(join(tmpdir(), "ocx-link-sibling-stop-"))); + const home = join(root, "ocx"); + const env = { ...process.env, HOME: root, USERPROFILE: root, OPENCODEX_HOME: home, CODEX_HOME: join(root, "codex"), + OCX_SERVICE: "", OCX_SERVICE_MANAGED: "0", PI_CODING_AGENT_DIR: join(root, ".pi", "agent") }; + const child = Bun.spawn([process.execPath, fixturePath("client-link-stop-runner.ts")], { + cwd: repoPath(), env, stdout: "ignore", stderr: "pipe", + stdin: new Blob([JSON.stringify({ mode: "runtime", osSignal: true, preserve: "sibling", fileClients: ["pi"] })]), + }); + const childError = new Response(child.stderr).text(); + try { + const deadline = Date.now() + 5000; + while (!existsSync(join(home, "ready")) && child.exitCode === null && Date.now() < deadline) await Bun.sleep(10); + expect(existsSync(join(home, "ready"))).toBe(true); + const runtime = JSON.parse(readFileSync(join(home, "runtime-port.json"), "utf8")); + expect(runtime).toMatchObject({ pid: child.pid, siblingOfPort: 10100, clientLinkOwner: expect.any(String) }); + expect((await fetch(`http://127.0.0.1:${runtime.port}/healthz`)).ok).toBe(true); + const cli = join(root, "stop.ts"); + const unexpected = join(root, "unexpected-stop-side-effects"); + const inheritedReceipt = join(home, `pending-teardown-${"a".repeat(32)}.json`); + writeFileSync(inheritedReceipt, "{"); + writeFileSync(cli, ` + import { mock } from "bun:test"; + import { appendFileSync } from "node:fs"; + const lifecyclePath = ${JSON.stringify(repoPath("src/client/lifecycle-lock.ts"))}; + const lifecycle = await import(lifecyclePath); + const deps = { lockPath: ${JSON.stringify(join(home, "lifecycle.sqlite"))} }; + mock.module(lifecyclePath, () => ({ ...lifecycle, + withClientLifecycle: work => lifecycle.withClientLifecycle(work, deps), + withClientLifecycleSync: work => lifecycle.withClientLifecycleSync(work, deps) })); + for (const [path, name] of ${JSON.stringify([ + [repoPath("src/config/pending-teardown.ts"), "claimPendingTeardown"], + [repoPath("src/service.ts"), "stopServiceIfInstalledDetailed"], + [repoPath("src/server/system-env.ts"), "revertSystemEnv"], + ])}) { + const original = await import(path); + mock.module(path, () => ({ ...original, [name]: () => { + appendFileSync(${JSON.stringify(unexpected)}, name + "\\n"); + throw new Error(name); + } })); + } + mock.module(${JSON.stringify(repoPath("src/cli/codex-shim-autorestore.ts"))}, () => ({ maybeAutoRestoreCodexShimAsync: async () => {} })); + await import(${JSON.stringify(repoPath("src/cli/index.ts"))}); + `); + const stop = await Bun.$`${process.execPath} ${cli} stop --json`.env(env).quiet().nothrow(); + expect(stop.exitCode, stop.stderr.toString()).toBe(0); + expect(JSON.parse(stop.stdout.toString())).toMatchObject({ runtimeDown: true, service: "absent", sharedTeardown: "skipped" }); + expect(await child.exited, await childError).toBe(0); + const atExit = JSON.parse(readFileSync(join(home, "exit.json"), "utf8")); + expect(atExit).toMatchObject({ after: atExit.before, profileAfter: atExit.profileBefore, journalRetained: true, + catalogAfter: JSON.parse(atExit.catalogBefore), grokAfter: atExit.grokBefore, fileAfter: atExit.fileOwnedBytes, + protectedUnchanged: true, teardownOutstanding: true }); + expect(readFileSync(inheritedReceipt, "utf8")).toBe("{"); + expect(existsSync(unexpected)).toBe(false); + } finally { + if (child.exitCode === null) child.kill("SIGKILL"); + await child.exited; + removeTreeWithRetry(root); + } +}, 20_000); + +for (const changedReceipt of [false, true]) test.skipIf(process.platform !== "darwin")( + changedReceipt ? "foreground CLI stop retains the listener if the older endpoint receipt changes after preflight" + : "foreground CLI stop completes native handoff with a verified older endpoint receipt", async () => { + const root = realpathSync(mkdtempSync(join(tmpdir(), "ocx-link-stop-handoff-"))); + const home = join(root, "ocx"), codex = join(root, "codex"); + const env = { ...process.env, HOME: root, USERPROFILE: root, OPENCODEX_HOME: home, CODEX_HOME: codex, + OCX_SERVICE: "", OCX_SERVICE_MANAGED: "0", PI_CODING_AGENT_DIR: join(root, ".pi", "agent") }; + const cli = join(root, "src", "cli", "index.ts"); + mkdirSync(dirname(cli), { recursive: true }); + const child = Bun.spawn([process.execPath, fixturePath("client-link-stop-runner.ts")], { + cwd: repoPath(), env, stdout: "ignore", stderr: "pipe", + stdin: new Blob([JSON.stringify({ mode: "runtime", osSignal: true, preserve: "receipt", receiptState: "abandoned-dead-other", fileClients: ["pi"] })]), + }); + const childError = new Response(child.stderr).text(); + try { + const deadline = Date.now() + 5000; + while (!existsSync(join(home, "ready")) && child.exitCode === null && Date.now() < deadline) await Bun.sleep(10); + expect(existsSync(join(home, "ready"))).toBe(true); + const receipts = () => readdirSync(home).filter(name => name.includes("pending-teardown")); + expect(receipts()).toHaveLength(1); + const inheritedPath = join(home, receipts()[0]!); + writeFileSync(cli, ` + import { mock } from "bun:test"; + import { appendFileSync } from "node:fs"; + const lifecyclePath = ${JSON.stringify(repoPath("src/client/lifecycle-lock.ts"))}; + const lifecycle = await import(lifecyclePath); + const { withClientLifecycle, withClientLifecycleSync } = lifecycle; + const deps = { lockPath: ${JSON.stringify(join(home, "lifecycle.sqlite"))} }; + mock.module(lifecyclePath, () => ({ ...lifecycle, + withClientLifecycle: work => withClientLifecycle(work, deps), + withClientLifecycleSync: work => withClientLifecycleSync(work, deps) })); + const servicePath = ${JSON.stringify(repoPath("src/service.ts"))}; + const service = await import(servicePath); + mock.module(servicePath, () => ({ ...service, stopServiceIfInstalledDetailed: () => { + ${changedReceipt ? `appendFileSync(${JSON.stringify(inheritedPath)}, " ");` : ""} + return "absent"; + } })); + mock.module(${JSON.stringify(repoPath("src/cli/codex-shim-autorestore.ts"))}, () => ({ maybeAutoRestoreCodexShimAsync: async () => {} })); + await import(${JSON.stringify(repoPath("src/cli/index.ts"))}); + `); + const stop = await Bun.$`${process.execPath} ${cli} stop --json`.env(env).quiet().nothrow(); + if (changedReceipt) { + expect(stop.exitCode, stop.stderr.toString()).toBe(1); + expect(stop.stderr.toString()).toContain("Link Child did not exit after SIGTERM"); + const { port } = JSON.parse(readFileSync(join(home, "runtime-port.json"), "utf8")); + expect((await fetch(`http://127.0.0.1:${port}/healthz`)).ok).toBe(true); + expect(receipts()).toHaveLength(2); + return; + } + expect(stop.exitCode, stop.stderr.toString()).toBe(0); + expect(JSON.parse(stop.stdout.toString())).toMatchObject({ runtimeDown: true, sharedTeardown: "restored" }); + expect(await child.exited, await childError).toBe(0); + const atExit = JSON.parse(readFileSync(join(home, "exit.json"), "utf8")); + expect(atExit.after).toBe(atExit.before); + expect(atExit.fileAfter.pi).not.toContain("127.0.0.1"); + expect(readFileSync(join(codex, "config.toml"), "utf8")).toBe('model = "native"\n'); + expect(receipts()).toEqual([]); + } finally { + if (child.exitCode === null) child.kill("SIGKILL"); + await child.exited; + removeTreeWithRetry(root); + } +}, 20_000); + +for (const receiptState of ["parent", "parent-stale", "parent-spaced"]) { + test(`an active native stop (${receiptState}) defers only native restoration after file cleanup`, async () => { + const report = await runStop({ mode: "runtime", preserve: "receipt", receiptState, fileClients: ["pi"] }); + expect(report.result).toEqual({ atListenerStop: true }); + expect(report.fileAfter.pi).not.toContain("127.0.0.1"); + expect(JSON.parse(report.fileAfter.pi)).toMatchObject({ fixtureUserSetting: "keep" }); + expect(report.teardownOutstanding).toBe(true); + expect(report.after).toBe(report.before); + expect(report.profileAfter).toBe(report.profileBefore); + expect(report.journalRetained).toBe(true); + expect(report.catalogAfter).toEqual(JSON.parse(report.catalogBefore)); + expect(report.grokAfter).toBe(report.grokBefore); + expect(report.protectedUnchanged).toBe(true); + }, 20_000); +} + +test("native teardown recognizes only supported stop invocations, including an updater's stop child", () => { + expect(isClientStopArgv(["/opt/Program Files/ocx", "stop", "--json", "--expect-pid", "12", "--expect-port", "10100", + "--expect-hostname", "127.0.0.1", "--expect-config-home", "/home/person with spaces/.opencodex", "--expect-cli-version", "1.0.0", + "--expect-compatibility-token", "a".repeat(64)])).toBe(true); + for (const command of ["/usr/local/bin/ocx stop", '"C:\\Program Files\\ocx.exe" stop --json', "bun src/cli.ts stop", + "bun run /install/src/cli/index.ts stop --deadline-ms 5000 --json", + `bun /npm/node_modules/@bitkyc08/opencodex/src/cli/index.ts --ocx-internal-launch-proof=${"a".repeat(43)} stop --json`]) { + expect(isClientStopCommandLine(command), command).toBe(true); + } + for (const command of ["ocx start", "ocx status", "ocx update", "ocx update --plan", "ocx update --desktop --check", "ocx __gui-update-worker", + "ocx stop --help", "ocx status stop", "node -e 'ocx stop'", "bun -e 'src/cli.ts stop'", "bun other.ts stop", + "bun src/cli/index.ts --ocx-internal-launch-proof=invalid stop", "ocx stop --expect-pid 5", "ocx stop --deadline-ms 0"]) { + expect(isClientStopCommandLine(command), command).toBe(false); + } +}); + +test("stop owner with malformed creation identity or unrecognized invocation remains unverified", async () => { + const child = Bun.spawn([process.execPath, "-e", 'console.log("ready"); setInterval(() => {}, 1000)'], { stdout: "pipe" }); + try { + const reader = child.stdout.getReader(); + const ready = await reader.read(); + reader.releaseLock(); + expect(new TextDecoder().decode(ready.value)).toContain("ready"); + const startTime = readClientStopProcessStart(child.pid); + expect(startTime).toBeDefined(); + const owner = { pid: child.pid, nonce: "a".repeat(32) }; + expect([ + observeClientStopOwner({ ...owner, startTime: "malformed" }), + observeClientStopOwner({ ...owner, startTime: startTime! }), + ]).toEqual(["unverified", "unverified"]); + } finally { + child.kill(); + await child.exited; + } +}, 20_000); + +test("an abandoned native teardown receipt cannot release a conflicting Link file route", async () => { + const report = await runStop({ mode: "runtime", preserve: "receipt", receiptState: "abandoned", + fileClients: ["pi"], fileConflict: true, observeFileRefusal: true, expectedFileRefusal: true }); + expect(report.result).toEqual({ refused: true, bound: true, stopping: true }); + expect(report.fileAfter.pi).toContain("operator-edited-placeholder"); + expect(report.fileAfter.pi).toContain("127.0.0.1"); + expect(report.teardownOutstanding).toBe(true); + expect(report.after).toBe(report.before); + expect(report.journalRetained).toBe(true); +}, 20_000); + +test("a native teardown receipt cannot skip the Link signal sync fence", async () => { + const report = await runStop({ mode: "runtime", preserve: "receipt", runtimeRecord: "absent", + observeFileRefusal: true, expectedFileRefusal: true }); + expect(report.result).toEqual({ refused: true, bound: true, stopping: false }); + expect(report.teardownOutstanding).toBe(true); + expect(report.after).toBe(report.before); + expect(report.grokAfter).toBe(report.grokBefore); +}, 20_000); diff --git a/tests/clients/client-link-stop.test.ts b/tests/clients/client-link-stop.test.ts index eb42fdf19f3..a8f6a8cade3 100644 --- a/tests/clients/client-link-stop.test.ts +++ b/tests/clients/client-link-stop.test.ts @@ -1,46 +1,146 @@ import { expect, test } from "bun:test"; -import { existsSync, mkdtempSync, readFileSync, realpathSync, writeFileSync } from "node:fs"; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; -import { join } from "node:path"; +import { dirname, join } from "node:path"; import { fixturePath, repoPath } from "../helpers/repo-root"; import { removeTreeWithRetry } from "../helpers/remove-tree"; import { hostedWindowsQuarantine } from "../helpers/windows-ci-quarantine"; +import { runStop } from "../helpers/client-link-stop"; -async function runStop(options: Record) { - const root = mkdtempSync(join(tmpdir(), "ocx-link-stop-")); - const home = join(root, "ocx"); - const child = Bun.spawn([process.execPath, fixturePath("client-link-stop-runner.ts")], { - cwd: repoPath(), stdin: new Blob([JSON.stringify(options)]), stdout: "pipe", stderr: "pipe", - env: { ...process.env, HOME: root, USERPROFILE: root, OPENCODEX_HOME: home, CODEX_HOME: join(root, "codex"), OCX_SERVICE: "", OCX_SERVICE_MANAGED: "0" }, - }); - const timeout = setTimeout(() => child.kill(), 15_000); - try { - if (options.osSignal) { - const deadline = Date.now() + 10_000; - while (!existsSync(join(home, "ready")) && child.exitCode === null && Date.now() < deadline) await Bun.sleep(10); - if (!existsSync(join(home, "ready"))) throw new Error("fixture did not publish its signal-ready listener"); - child.kill("SIGTERM"); - } - const [exit, stdout, stderr] = await Promise.all([child.exited, new Response(child.stdout).text(), new Response(child.stderr).text()]); - if (options.expectedFailure || options.expectedRefusal) { - expect(exit, stdout).toBe(options.expectedFailure ? 1 : 0); - expect(stderr).toContain("Link Child Codex routing restore refused"); - } else if (String(options.preserve).startsWith("restart-rollback")) { - expect(exit, stdout).toBe(0); - expect(stderr.trim()).toBe("[client] restart: the replacement did not start (not_ready); this runtime keeps serving"); - } else expect({ exit, stderr }, stdout).toEqual({ exit: 0, stderr: "" }); - const report = JSON.parse(readFileSync(join(home, "result.json"), "utf8")); - const atExit = JSON.parse(readFileSync(join(home, "exit.json"), "utf8")); - for (const field of ["after", "profileAfter", "journalRetained", "journalHomeBound", "catalogAfter", "grokAfter", "protectedUnchanged"]) { - expect(atExit[field], `no late restoration after listener release: ${field}`).toEqual(report[field]); - } - return report; - } finally { - clearTimeout(timeout); - if (child.exitCode === null) { child.kill(); await child.exited; } - removeTreeWithRetry(root); +test("Link signal drains Home-created Pi and OpenCode routes before listener release", async () => { + const report = await runStop({ mode: "runtime", fileClients: ["pi", "opencode"], fileOnly: true, osSignal: process.platform !== "win32" }); + expect(report.result).toEqual({ atListenerStop: true }); + for (const client of ["pi", "opencode"]) { + expect(report.fileOwnedBytes[client]).toContain("fixture/home-model"); + expect(JSON.parse(report.fileAfter[client])).toMatchObject({ fixtureUserSetting: "keep" }); + expect(report.fileAfter[client]).not.toContain("fixture/home-model"); + expect(report.fileAfter[client]).not.toContain("127.0.0.1"); } -} + expect(report.protectedUnchanged).toBe(true); +}, 20_000); + +test("a fenced stop with proved file absence needs no file token mutation", async () => { + const report = await runStop({ mode: "runtime", fileOnly: true, removeToken: true }); + expect(report.result).toEqual({ atListenerStop: true }); + expect(report.protectedUnchanged).toBe(false); +}, 20_000); + +test("a missing token still refuses an owned file route and retains the listener", async () => { + const report = await runStop({ mode: "runtime", fileOnly: true, fileClients: ["pi"], removeToken: true, observeFileRefusal: true, expectedFileRefusal: true }); + expect(report.result).toEqual({ refused: true, bound: true, stopping: true }); + expect(report.fileAfter).toEqual(report.fileOwnedBytes); +}, 20_000); + +test("an already-started Home file sync cannot reapply a route after signal cleanup", async () => { + const report = await runStop({ mode: "runtime", fileClients: ["pi"], fileOnly: true, lateFileSync: true }); + expect(report.fileLateResult).toContain("client_runtime_stopping"); + expect(report.fileAfter.pi).not.toContain("127.0.0.1"); + expect(report.fileAfter.pi).not.toContain("fixture/late-home-model"); + expect(report.protectedUnchanged).toBe(true); +}, 20_000); + +test("a Link stop keeps a file integration that was owned before connection", async () => { + const report = await runStop({ mode: "runtime", fileClients: ["pi"], fileStandalone: true, fileOnly: true }); + expect(report.fileAfter).toEqual(report.fileOwnedBytes); + expect(report.protectedUnchanged).toBe(true); +}, 20_000); + +test("a conflicting file route keeps the stopping listener until repair and a second signal", async () => { + const report = await runStop({ mode: "runtime", fileClients: ["pi"], fileConflict: true, repairFileRefusal: true, fileOnly: true }); + expect(report.fileRefusal).toMatchObject({ bound: true, stopping: true }); + expect(JSON.parse(report.fileRefusal.before.pi).providers.opencodex.apiKey).toBe("operator-edited-placeholder"); + expect(report.fileAfter.pi).not.toContain("127.0.0.1"); + expect(JSON.parse(report.fileAfter.pi)).toMatchObject({ fixtureUserSetting: "keep" }); + expect(report.result).toEqual({ atListenerStop: true }); + expect(report.protectedUnchanged).toBe(true); +}, 20_000); + +test("the parent stop drains Home-created file routes while its verified listener stays bound", async () => { + const report = await runStop({ mode: "file-preflight", fileClients: ["pi", "opencode"] }); + expect(report.result).toEqual({ outcome: null, bound: true, stopping: true }); + expect(report.fileAfter.pi).not.toContain("127.0.0.1"); + expect(report.fileAfter.opencode).not.toContain("127.0.0.1"); + expect(report.after).toBe(report.before); + expect(report.protectedUnchanged).toBe(true); +}, 20_000); + +test("a parent stop with no current file routes fences a later Home enable", async () => { + const report = await runStop({ mode: "file-preflight", fileClients: ["pi"], deferFileApply: true }); + expect(report.result).toEqual({ outcome: null, bound: true, stopping: true }); + expect(report.fileLateResult).toBe("client_runtime_stopping"); + expect(report.fileAfter.pi).toBe(report.fileOwnedBytes.pi); + expect(report.fileAfter.pi).not.toContain("127.0.0.1"); + expect(report.protectedUnchanged).toBe(true); +}, 20_000); + +test("offline Link cleanup preserves the connection on Linux without a user manager or unit", async () => { + const report = await runStop({ mode: "offline-stop", fileClients: ["pi"] }); + expect(report.result).toEqual({ exitCode: 0 }); + expect(report.fileAfter.pi).not.toContain("127.0.0.1"); + expect(report.protectedUnchanged).toBe(true); +}, 20_000); + +test("offline Link cleanup refuses an installed Linux unit when its manager is unreadable", async () => { + const report = await runStop({ mode: "offline-stop", fileClients: ["pi"], installedUnit: true, expectedUnsupportedStop: true }); + expect(report.result).toEqual({ exitCode: 1 }); + expect(report.fileAfter).toEqual(report.fileOwnedBytes); +}, 20_000); + +test.skipIf(process.platform === "win32")("offline Link cleanup refuses a dangling service record with an unreadable manager", async () => { + const report = await runStop({ mode: "offline-stop", fileClients: ["pi"], danglingServiceRecord: true, expectedUnsupportedStop: true }); + expect(report.result).toEqual({ exitCode: 1 }); + expect(report.fileAfter).toEqual(report.fileOwnedBytes); +}, 20_000); + +test("the parent preflight refuses a conflicting file route without releasing its listener", async () => { + const report = await runStop({ mode: "file-preflight", fileClients: ["pi"], fileConflict: true, expectedFileRefusal: true }); + expect(report.result).toMatchObject({ outcome: { ok: false, summary: { runtimeDown: false, proxy: "ownership-refused" } }, bound: true, stopping: true }); + expect(JSON.parse(report.fileAfter.pi).providers.opencodex.apiKey).toBe("operator-edited-placeholder"); + expect(report.after).toBe(report.before); + expect(report.protectedUnchanged).toBe(true); +}, 20_000); + +test("ocx stop refuses a file conflict before any service stop, signal or kill fallback", async () => { + const report = await runStop({ mode: "file-stop", fileClients: ["pi"], fileConflict: true, expectedFileRefusal: true }); + expect(report.result).toEqual({ exitCode: 1, calls: { service: 0, killed: 0 }, bound: true, stopping: true }); + expect(JSON.parse(report.fileAfter.pi).providers.opencodex.apiKey).toBe("operator-edited-placeholder"); + expect(report.after).toBe(report.before); + expect(report.protectedUnchanged).toBe(true); +}, 20_000); + +test("failure to finalize a retained parent fence does not replace the original stop refusal", async () => { + const report = await runStop({ mode: "file-stop", fileClients: ["pi"], fileConflict: true, finalizeFailure: true, expectedFileRefusal: true }); + expect(report.result).toEqual({ exitCode: 1, calls: { service: 0, killed: 0 }, bound: true, stopping: true, activeStop: true }); + expect(JSON.parse(report.fileAfter.pi).providers.opencodex.apiKey).toBe("operator-edited-placeholder"); +}, 20_000); + +test("ocx stop refuses an attested older Link runtime before file, service or process changes", async () => { + const report = await runStop({ mode: "file-stop", fileClients: ["pi"], oldStopCapability: true, expectedUnsupportedStop: true }); + expect(report.result).toEqual({ exitCode: 1, calls: { service: 0, killed: 0 }, bound: true, stopping: false }); + expect(report.fileAfter).toEqual(report.fileOwnedBytes); + expect(report.after).toBe(report.before); + expect(report.protectedUnchanged).toBe(true); +}, 20_000); + +test("file cleanup refuses a connection replaced across its asynchronous writer boundary", async () => { + const report = await runStop({ mode: "file-preflight", fileClients: ["pi"], fileOwnerChange: true, expectedFileRefusal: true }); + expect(report.result).toMatchObject({ outcome: { ok: false }, bound: true, stopping: true }); + expect(report.fileAfter).toEqual(report.fileOwnedBytes); + expect(report.after).toBe(report.before); + expect(report.protectedUnchanged).toBe(false); +}, 20_000); + +test("repeated file cleanup retains the connection for a later explicit Home sync", async () => { + const report = await runStop({ mode: "file-cycle", fileClients: ["pi", "opencode"] }); + expect(report.result).toMatchObject({ first: true, second: true }); + for (const client of ["pi", "opencode"]) { + expect(report.result.stopped[client]).not.toContain("127.0.0.1"); + expect(report.fileAfter[client]).toContain("fixture/home-model"); + expect(JSON.parse(report.fileAfter[client])).toMatchObject({ fixtureUserSetting: "keep" }); + } + expect(report.result.reapplied.every((row: { outcome: string }) => row.outcome === "current")).toBe(true); + expect(report.protectedUnchanged).toBe(true); +}, 20_000); for (const signal of process.platform === "win32" ? ["SIGINT", "SIGTERM"] : ["SIGINT", "SIGTERM", "SIGHUP"]) { test(`native Link ${signal} restores its owned Codex routing before listener release`, async () => { @@ -88,14 +188,29 @@ test("native hub signal exit preserves the connection-owned route", async () => }, 20_000); test("native Link signal refuses a connection swapped after runtime publication", async () => { - const report = await runStop({ mode: "runtime", mutation: "connection", expectedFailure: true }); - expect(report.result).toEqual({ atListenerStop: true }); + const report = await runStop({ mode: "runtime", mutation: "connection", observeFileRefusal: true, expectedFileRefusal: true }); + expect(report.result).toEqual({ refused: true, bound: true, stopping: true }); expect(report.after).toBe(report.before); expect(report.profileAfter).toBe(report.profileBefore); expect(report.journalRetained).toBe(true); expect(report.protectedUnchanged).toBe(true); }, 20_000); +for (const mutation of ["journal", "process-journal", "unverified"]) { + test(`native Codex refusal retains the Link listener after file cleanup (${mutation})`, async () => { + const report = await runStop({ mode: "runtime", mutation, fileClients: ["pi"], observeNativeRefusal: true, expectedRefusal: true }); + expect(report.result).toEqual({ refused: true, bound: true, stopping: true }); + expect(report.after).toBe(report.before); + expect(report.profileAfter).toBe(report.profileBefore); + expect(report.journalRetained).toBe(true); + expect(report.protectedUnchanged).toBe(true); + expect(report.catalogAfter).toEqual(JSON.parse(report.catalogBefore)); + expect(report.grokAfter).toBe(report.grokBefore); + expect(report.fileAfter.pi).not.toContain("127.0.0.1"); + expect(JSON.parse(report.fileAfter.pi)).toMatchObject({ fixtureUserSetting: "keep" }); + }, 20_000); +} + test("owned Link full restore is idempotent and retains connection credentials", async () => { const report = await runStop({ mode: "helper", repeat: true }); expect(report.result.first).toMatchObject({ success: true, restored: true }); @@ -154,50 +269,22 @@ test("Link API teardown preserves the merged parent deferral contract", async () }); test("parent Link teardown retains the merged full restoration contract", async () => { - const report = await runStop({ mode: "parent" }); + const report = await runStop({ mode: "parent", fileClients: ["pi"] }); expect(report.result).toEqual({ historyOnly: false, historyDeferred: false, other: false }); expect(report.after).toBe('model = "native"\n'); expect(report.journalRetained).toBe(false); expect(report.protectedUnchanged).toBe(true); expect(report.catalogAfter.models).toEqual([{ slug: "fixture-native", visibility: "list" }]); expect(report.grokAfter).toBe('theme = "fixture"\n'); + expect(report.fileAfter.pi).not.toContain("127.0.0.1"); }); -for (const preserve of ["service", "desktop", "receipt", "sibling"]) { - test(`native Link signal preserves ${preserve} restoration ownership`, async () => { - const report = await runStop({ mode: "runtime", preserve }); - expect(report.after).toBe(report.before); - expect(report.profileAfter).toBe(report.profileBefore); - expect(report.journalRetained).toBe(true); - expect(report.protectedUnchanged).toBe(true); - expect(report.catalogAfter).toEqual(JSON.parse(report.catalogBefore)); - expect(report.grokAfter).toBe(report.grokBefore); - }, 20_000); -} - -test("a pending restart admission cannot leave routing behind on signal shutdown", async () => { - const report = await runStop({ mode: "runtime", preserve: "restart" }); - expect(report.after).toBe('model = "native"\n'); - expect(report.journalRetained).toBe(false); - expect(report.catalogAfter.models).toEqual([{ slug: "fixture-native", visibility: "list" }]); - expect(report.grokAfter).toBe('theme = "fixture"\n'); -}, 20_000); - -test.each(["restart-rollback", "restart-rollback-recycle"])("signal shutdown joins %s before restoring", async preserve => { - const report = await runStop({ mode: "runtime", preserve }); - expect(report.after).toBe('model = "native"\n'); - expect(report.journalRetained).toBe(false); - expect(report.catalogAfter.models).toEqual([{ slug: "fixture-native", visibility: "list" }]); - expect(report.grokAfter).toBe('theme = "fixture"\n'); -}, 20_000); - -test("a scheduled recycle cannot skip restoration or spawn after signal shutdown", async () => { - const report = await runStop({ mode: "runtime", preserve: "recycle-pending" }); - expect(report.after).toBe('model = "native"\n'); - expect(report.journalRetained).toBe(false); - expect(report.catalogAfter.models).toEqual([{ slug: "fixture-native", visibility: "list" }]); - expect(report.grokAfter).toBe('theme = "fixture"\n'); -}, 20_000); +test("post-stop restore reports unowned Link file receipts despite disconnected saved state", async () => { + const report = await runStop({ mode: "parent", fileClients: ["pi"], stopConnectionDrift: "disconnected", + expectedUnownedFileRecovery: true }); + expect(report.result.other).toBe(true); + expect(report.fileAfter).toEqual(report.fileOwnedBytes); +}); for (const mutation of ["connection", "selection", "rotation", "hub", "prior-catalog", "api-key", "token", "management", "link-id"]) { test(`served-connection guard rechecks ${mutation} at each write and freezes its snapshot`, async () => { @@ -226,9 +313,10 @@ for (const retryError of ["busy", "locked", "exhausted", "permission", "unwrappe }); } -for (const runtimeRecord of ["absent", "invalid", "foreign"]) { +for (const runtimeRecord of ["absent", "invalid", "foreign", "explicit-stop-unfenced"]) { test(`signal refuses restoration when its runtime record is ${runtimeRecord}`, async () => { - const report = await runStop({ mode: "runtime", runtimeRecord, expectedFailure: true }); + const report = await runStop({ mode: "runtime", runtimeRecord, observeFileRefusal: true, expectedFileRefusal: true }); + expect(report.result).toEqual({ refused: true, bound: true, stopping: false }); expect(report.after).toBe(report.before); expect(report.profileAfter).toBe(report.profileBefore); expect(report.catalogAfter).toEqual(JSON.parse(report.catalogBefore)); @@ -237,7 +325,7 @@ for (const runtimeRecord of ["absent", "invalid", "foreign"]) { }, 20_000); } -for (const preserve of ["service", "desktop", "receipt", "sibling"]) { +for (const preserve of ["service", "desktop", "sibling"]) { test(`${preserve} signal preservation does not require a restoration sync fence`, async () => { const report = await runStop({ mode: "runtime", preserve, runtimeRecord: "absent" }); expect(report.after).toBe(report.before); diff --git a/tests/clients/client-recycle-exclusion.test.ts b/tests/clients/client-recycle-exclusion.test.ts new file mode 100644 index 00000000000..34359c711b7 --- /dev/null +++ b/tests/clients/client-recycle-exclusion.test.ts @@ -0,0 +1,67 @@ +import { afterEach, beforeEach, expect, test } from "bun:test"; +import { Database } from "bun:sqlite"; +import { writeFileSync } from "node:fs"; +import { getDefaultConfig, saveConfig } from "../../src/config"; +import { prepareConfigMutationDatabasePathForWrite } from "../../src/config/mutation-lock"; +import { LinkApplyBusyError, withLinkApply } from "../../src/client/link-home"; +import { markClientConnectPending } from "../../src/client/state"; +import { runClientRecycleWithAdmission } from "../../src/client/runtime-recycle"; +import type { OcxClientConnectionConfig } from "../../src/types"; +import { createTempHome, type TempHome } from "../helpers/temp-home"; + +const served: OcxClientConnectionConfig = { + serverUrl: "http://127.0.0.1:34567", managementUrl: "http://127.0.0.1:34567", managementTransport: "direct", transport: "link", + link: { tunnelPort: 34567, linkId: "lnk_0123456789abcdef" }, selectedClients: [], tokenEnv: "OPENCODEX_API_AUTH_TOKEN", + apiKeyId: "fixture-client", tokenFingerprint: "c".repeat(64), protocolVersion: 1, connectedAt: "2026-10-01T00:00:00.000Z", +}; +let home: TempHome; +beforeEach(() => { home = createTempHome("recycle-exclusion-"); saveConfig(getDefaultConfig()); }); +afterEach(() => home.remove()); + +test("an in-flight Link apply refuses recycle before any teardown", async () => { + let stopped = 0; + await withLinkApply(async () => { + expect(await runClientRecycleWithAdmission(served, () => true, async () => { stopped++; })).toBe(false); + }); + expect(stopped).toBe(0); +}); + +test("recycle retains apply exclusion through every teardown await", async () => { + let entered!: () => void, release!: () => void; + const ready = new Promise(resolve => { entered = resolve; }); + const held = new Promise(resolve => { release = resolve; }); + let admissions = 0, completed = false; + const flight = runClientRecycleWithAdmission(served, () => { admissions++; return true; }, async () => { + entered(); await held; + await expect(withLinkApply(async () => {})).rejects.toBeInstanceOf(LinkApplyBusyError); + completed = true; + }); + await ready; + try { await expect(withLinkApply(async () => {})).rejects.toBeInstanceOf(LinkApplyBusyError); } + finally { release(); } + expect(await flight).toBe(true); + expect({ admissions, completed }).toEqual({ admissions: 1, completed: true }); + await withLinkApply(async () => {}); +}); + +for (const state of ["same-connection", "unreadable", "pending-connect", "stop-refused", "config-busy"] as const) { + test("recycle rechecks " + state + " inside apply exclusion", async () => { + let stopped = 0; + let lock: Database | undefined; + if (state === "same-connection") { + const config = getDefaultConfig(); config.runtimeRole = "client"; config.client = served; saveConfig(config); + } + if (state === "unreadable") writeFileSync(home.path("config.json"), "{"); + if (state === "pending-connect") markClientConnectPending("d".repeat(64)); + if (state === "config-busy") { lock = new Database(prepareConfigMutationDatabasePathForWrite()); lock.exec("BEGIN IMMEDIATE"); } + try { + expect(await runClientRecycleWithAdmission(served, () => state !== "stop-refused", async () => { stopped++; })).toBe(false); + expect(stopped).toBe(0); + } finally { lock?.close(); } + }); +} + +test("a failure after teardown begins is propagated instead of reported as an admission refusal", async () => { + await expect(runClientRecycleWithAdmission(served, () => true, async () => { throw new LinkApplyBusyError(); })) + .rejects.toBeInstanceOf(LinkApplyBusyError); +}); diff --git a/tests/clients/client-restart-rollback-lock.test.ts b/tests/clients/client-restart-rollback-lock.test.ts new file mode 100644 index 00000000000..50d1bc7807d --- /dev/null +++ b/tests/clients/client-restart-rollback-lock.test.ts @@ -0,0 +1,44 @@ +import { expect, test } from "bun:test"; +import { ConfigMutationLockError } from "../../src/config"; +import { retryClientRollback, retryableClientRollbackLock } from "../../src/client/runtime-rollback"; + +test("rollback retries only known lifecycle or configuration contention", () => { + expect(retryableClientRollbackLock({ code: "client_lifecycle_busy" })).toBe(true); + for (const code of ["SQLITE_BUSY", "SQLITE_LOCKED"]) { + expect(retryableClientRollbackLock(new ConfigMutationLockError("busy", { cause: { code } }))).toBe(true); + } + for (const error of [undefined, new Error("busy"), { code: "SQLITE_BUSY" }, { code: "client_lifecycle_lock_failed" }, + new ConfigMutationLockError("unavailable", { cause: { code: "SQLITE_CORRUPT" } })]) { + expect(retryableClientRollbackLock(error)).toBe(false); + } +}); + +test("rollback closes each busy attempt before yielding and keeps one remaining budget", async () => { + let clock = 0, calls = 0, listener = false; + const remaining: number[] = []; + expect(await retryClientRollback(async budget => { + remaining.push(budget); calls++; listener = true; clock += 10; + if (calls === 3) return "published"; + listener = false; return "busy"; + }, { budgetMs: 200, now: () => clock, sleep: async ms => { + expect(listener).toBe(false); clock += ms; + } })).toBe(true); + expect(remaining).toEqual([200, 140, 80]); + expect(listener).toBe(true); +}); + +test("rollback contention exhaustion never extends its budget", async () => { + let clock = 0, calls = 0; + expect(await retryClientRollback(async () => { calls++; clock += 20; return "busy"; }, { + budgetMs: 100, now: () => clock, sleep: async ms => { clock += ms; }, + })).toBe(false); + expect({ clock, calls }).toEqual({ clock: 100, calls: 2 }); +}); + +test("a changed owner or non-contention refusal stops rollback retries immediately", async () => { + let clock = 0, calls = 0; + expect(await retryClientRollback(async () => ++calls === 1 ? "busy" : "refused", { + now: () => clock, sleep: async ms => { clock += ms; }, + })).toBe(false); + expect(calls).toBe(2); +}); diff --git a/tests/clients/client-runtime-restart.test.ts b/tests/clients/client-runtime-restart.test.ts index 50f2c41bdcf..8d7f3fd1690 100644 --- a/tests/clients/client-runtime-restart.test.ts +++ b/tests/clients/client-runtime-restart.test.ts @@ -331,6 +331,22 @@ describe("client restart controller", () => { expect(recycled).toEqual([]); }); + test("a stop begun during an accepted recycle's supervisor lookup prevents the handoff", async () => { + let stopping = false, lookups = 0; + let release!: () => void, entered!: () => void; + const paused = new Promise(resolve => { entered = resolve; }); + const wait = new Promise(resolve => { release = resolve; }); + const { io, calls } = fakeIo({ stopping: () => stopping, connectionChanged: () => true, + supervisor: async () => { if (++lookups === 2) { entered(); await wait; } return null; }, + recycle: async () => { calls.push("recycle"); }, + }); + const controller = createClientRestartController(io); + expect(await controller.request()).toEqual({ kind: "accepted", alreadyRestarting: false }); + await paused; stopping = true; release(); + await controller.settled(); + expect(calls).toEqual([]); + }); + // Final review: a manager that owns this process but cannot be proven to relaunch it must keep // the runtime; refused at admission, nothing recycled or detached. // The restart decision table (PR body): every supervisor verdict, with the connection ended diff --git a/tests/clients/route-intent-runtime-stop.test.ts b/tests/clients/route-intent-runtime-stop.test.ts index 6eb574de463..1ac0635a3ea 100644 --- a/tests/clients/route-intent-runtime-stop.test.ts +++ b/tests/clients/route-intent-runtime-stop.test.ts @@ -38,6 +38,8 @@ test("runtime recycle cancels its watch and tick before replacement handoff", () }), })); const runtime = await import(${JSON.stringify(repoPath("src/client/runtime.ts"))}); + const { clearClientConnection } = await import(${JSON.stringify(repoPath("src/client/state.ts"))}); + const { withLinkApply } = await import(${JSON.stringify(repoPath("src/client/link-home.ts"))}); const probe = Bun.serve({hostname:'127.0.0.1',port:0,fetch:()=>new Response(null)}); const port = probe.port; await probe.stop(true); const token = 'ocx_data_'+'c'.repeat(40); @@ -49,15 +51,22 @@ test("runtime recycle cancels its watch and tick before replacement handoff", () configApi.saveConfig(config); writeFileSync(join(process.env.OPENCODEX_HOME,'service-api-token'), token); try { await runtime.startClientRuntime({block:false}, {restartSupervisor:async()=>null, - startListener: port => ({port,stop(){events.push('listener-stop');}})}); + startListener: port => ({port,async stop(){ + events.push('listener-stop'); + await withLinkApply(async()=>{events.push('apply-entered-during-stop');}) + .catch(error=>{if(error.code==='link_apply_busy')events.push('apply-blocked-during-stop');else throw error;}); + }})}); for(let i=0;i<100&&!active;i++)await Bun.sleep(5); expect(active).toBe(true); + expect(clearClientConnection(config.client)).toBe('committed'); await runtime.recycleStandalone(serviceApiTokenFingerprint(token), { isDesktopSupervised:()=>false, spawnReplacement:async()=>{expect(active).toBe(false);events.push('replacement');}, exitProcess:code=>events.push('exit:'+code), }); expect(events.indexOf('watch-cancelled')).toBeGreaterThanOrEqual(0); + expect(events).toContain('apply-blocked-during-stop'); + expect(events).not.toContain('apply-entered-during-stop'); expect(events.indexOf('tick-stop')).toBeGreaterThanOrEqual(0); expect(events.filter(event => event === 'credential-observation-stop')).toHaveLength(1); expect(events.indexOf('watch-cancelled')).toBeLessThan(events.indexOf('listener-stop')); diff --git a/tests/fixtures/client-link-stop-recovery-runner.ts b/tests/fixtures/client-link-stop-recovery-runner.ts new file mode 100644 index 00000000000..4f2d30685fc --- /dev/null +++ b/tests/fixtures/client-link-stop-recovery-runner.ts @@ -0,0 +1,227 @@ +/** Real file recovery and bound restart; only replacement process launch is a loopback fixture. */ +import { mock, spyOn } from "bun:test"; +import { mkdirSync, readFileSync, unlinkSync, writeFileSync } from "node:fs"; +import { dirname, join } from "node:path"; +import { getDefaultConfig, saveConfig } from "../../src/config"; +import { serviceApiTokenFingerprint, writeServiceApiTokenFile, readServiceApiTokenState } from "../../src/lib/service-secrets"; +import { readRuntimePort, type ClientStopOwner } from "../../src/config/process-state"; +import { readClientConnectionStateWithEvidence, markClientConnectPending } from "../../src/client/state"; +import { readDesktopDisconnectReceipt } from "../../src/claude/desktop-remote-store"; +import { storePaths } from "../../src/claude/desktop-remote-store-io"; +import { createLocalAttestationChallenge } from "../../src/lib/local-management-attestation"; +import { createSystemRestartCapability, SYSTEM_RESTART_CAPABILITY_HEADER, SYSTEM_RESTART_EXPECTED_PID_HEADER, + SYSTEM_RESTART_NONCE_HEADER, SYSTEM_RESTART_PATH } from "../../src/lib/system-restart-contract"; + +const options = JSON.parse(readFileSync(0, "utf8")) as { mode: string; scheduled?: boolean }; +let phase = "fixture setup"; +const home = process.env.OPENCODEX_HOME!; +mkdirSync(home, { recursive: true }); +const lifecycle = await import("../../src/client/lifecycle-lock"); +const lock = lifecycle.withClientLifecycleSync, asyncLock = lifecycle.withClientLifecycle; +const lifecycleLockDeps = { lockPath: join(home, "lifecycle.sqlite") }; +mock.module("../../src/client/lifecycle-lock", () => ({ ...lifecycle, + withClientLifecycleSync: (work: Parameters[0], deps?: Parameters[1]) => lock(work, { lockPath: deps?.lockPath ?? lifecycleLockDeps.lockPath }), + withClientLifecycle: (work: Parameters[0], deps?: Parameters[1]) => asyncLock(work, { lockPath: deps?.lockPath ?? lifecycleLockDeps.lockPath }), +})); + +async function main() { + const token = `ocx_data_${"c".repeat(40)}`; + const probe = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch: () => new Response(null) }); + const config = getDefaultConfig(); config.port = probe.port!; + config.runtimeRole = "client"; + config.client = { serverUrl: "http://127.0.0.1:34567", managementUrl: "http://127.0.0.1:34567", managementTransport: "direct", transport: "link", + link: { tunnelPort: 34567, linkId: "lnk_0123456789abcdef" }, selectedClients: ["pi"], tokenEnv: "OPENCODEX_API_AUTH_TOKEN", + apiKeyId: "fixture-client", tokenFingerprint: serviceApiTokenFingerprint(token), protocolVersion: 1, connectedAt: "2026-10-01T00:00:00.000Z" }; + saveConfig(config); writeServiceApiTokenFile(token); + const expected = structuredClone(config.client); + process.env.PI_CODING_AGENT_DIR = join(process.env.HOME!, ".pi", "agent"); + const { INTEGRATION_CLIENTS } = await import("../../src/integrations/registry"); + const path = INTEGRATION_CLIENTS.pi.configPath(process.env, process.env.HOME!); + mkdirSync(dirname(path), { recursive: true }); writeFileSync(path, '{"userSetting":"keep"}\n'); + const { ROUTE_CLIENT_IDS } = await import("../../src/link/route-intent"); + const { applyConnectedRouteIntent } = await import("../../src/integrations/route-intent-connected"); + const document = { version: 1 as const, home: { name: "fixture", version: "1" }, + clients: Object.fromEntries(ROUTE_CLIENT_IDS.map(id => [id, { enabled: id === "pi" }])), + sources: Object.fromEntries(ROUTE_CLIENT_IDS.map(id => [id, "default"])) } as import("../../src/link/route-intent").HomeRouteIntentDocument; + const applied = await applyConnectedRouteIntent(expected, token, { document, stale: false, fetchedAt: "2026-11-16T00:00:00.000Z" }, + { onlyClients: ["pi"], lifecycleLockDeps }, { fetchImpl: (async () => Response.json({ data: [{ id: "fixture/home-model" }] })) as typeof fetch }); + if (applied?.outcomes.find(row => row.client === "pi")?.outcome !== "current") throw new Error("fixture apply failed"); + const edited = JSON.parse(readFileSync(path, "utf8")); edited.providers.opencodex.apiKey = "operator-edited-placeholder"; + writeFileSync(path, JSON.stringify(edited)); + + let signalEntered!: () => void, signalRefused!: () => void; + const entered = new Promise(resolve => { signalEntered = resolve; }); + const refused = new Promise(resolve => { signalRefused = resolve; }); + const error = console.error; + console.error = (...args: unknown[]) => { error(...args); if (args.some(value => String(value).includes("The listener remains bound"))) signalRefused(); }; + if (options.mode === "signal-active") { + const routing = await import("../../src/client/stop-routing"); + mock.module("../../src/client/stop-routing", () => ({ ...routing, restoreLinkClientRoutingBeforeExit: async () => { + signalEntered(); return await new Promise(() => {}); + } })); + } + + let spawned = 0; + const observations: Record = {}; + const report = async (role: string) => { + const receipt = readDesktopDisconnectReceipt(); + console.log(JSON.stringify({ ...observations, role, spawned, file: JSON.parse(readFileSync(path, "utf8")), + state: readClientConnectionStateWithEvidence().kind, token: readServiceApiTokenState().kind, + phase: receipt.kind === "valid" ? receipt.value.phase : receipt.kind, + marker: readRuntimePort(process.pid)?.clientStopRequested, runtimePresent: readRuntimePort(process.pid) !== null })); + }; + const replacement = await import("../../src/server/restart-replacement"); + mock.module("../../src/server/restart-replacement", () => ({ ...replacement, spawnReplacementStart: async (request: { port: number }) => { + spawned++; + // A successful bind proves the real Child listener released its port. No native coordinator, + // provider request or external process participates in this replacement seam. + const server = Bun.serve({ hostname: "127.0.0.1", port: request.port, fetch: () => Response.json({ role: "standalone" }) }); + try { + const health = await (await fetch(new URL("/healthz", server.url), { headers: { Connection: "close" } })).json() as { role: string }; + await report(health.role); + } finally { + await server.stop(true); + } + } })); + // This fixture runs CLI preflight and the Child together. Model the CLI incarnation + // with the real process's creation identity, preserving stale-proof detection. + const owner = await import("../../src/client/stop-teardown-owner"); + const observeOwner = owner.observeClientStopOwner; + mock.module("../../src/client/stop-teardown-owner", () => ({ ...owner, + observeClientStopOwner: (proof: ClientStopOwner) => { + if (options.mode === "parent-unverified") return "unverified"; + if (proof.nonce === "malformed" || proof.startTime === "malformed") return observeOwner(proof); + return owner.readClientStopProcessStart(proof.pid) === proof.startTime ? "active" : "confirmed-stale"; + }, + })); + const { startClientRuntime, scheduleStandaloneRecycle } = await import("../../src/client/runtime"); + const { startMachineListener } = await import("../../src/client/machine-listener"); + const { isAddrInUse } = await import("../../src/server/ports"); + phase = "starting the Child listener"; + // Keep the selected port reserved while preparing the fixture and loading the runtime. + await probe.stop(true); + try { + await startClientRuntime({ block: false }, { restartSupervisor: async () => null, + startListener: (port, deps) => { + try { return startMachineListener(port, deps); } + catch (error) { + // Only a proven bind collision requests a fresh, fully owned fixture from the parent. + if (isAddrInUse(error)) throw new Error("fixture-port-collision"); + throw error; + } + }, + }); + } catch (error) { + if (error instanceof Error && error.message === "fixture-port-collision") { + console.error("fixture-port-collision"); process.exit(75); + } + throw error; + } + const pendingRecycle = options.mode === "signal-pending-recycle"; + let lastRecycleTimer: ReturnType | undefined; + const scheduleAndCountTimers = () => { + const timer = spyOn(globalThis, "setTimeout"); + try { + scheduleStandaloneRecycle(expected.tokenFingerprint); + const index = timer.mock.calls.findIndex(([, delay]) => delay === 50); + lastRecycleTimer = index < 0 ? undefined : timer.mock.results[index]!.value; + return timer.mock.calls.filter(([, delay]) => delay === 50).length; + } finally { timer.mockRestore(); } + }; + const restart = async () => { + const runtime = readRuntimePort(process.pid)!; + const nonce = createLocalAttestationChallenge(); + const response = await fetch(`http://127.0.0.1:${config.port}${SYSTEM_RESTART_PATH}`, { method: "POST", headers: { + Connection: "close", + [SYSTEM_RESTART_EXPECTED_PID_HEADER]: String(process.pid), [SYSTEM_RESTART_NONCE_HEADER]: nonce, + [SYSTEM_RESTART_CAPABILITY_HEADER]: createSystemRestartCapability(runtime.attestationSecret!, nonce, "POST", SYSTEM_RESTART_PATH, process.pid, config.port), + } }); + await response.arrayBuffer(); return response.status; + }; + let finishStop: () => Promise = async () => {}; + phase = "observing the refused stop"; + if (options.mode.startsWith("signal")) { + // Queue and signal in one turn so the first timer is still pending at shutdown. + if (pendingRecycle) { + observations.firstRecycleTimers = scheduleAndCountTimers(); + const original = lastRecycleTimer; + if (original === undefined) throw new Error("fixture did not create the first recycle timer"); + const cancel = spyOn(globalThis, "clearTimeout"); + try { + process.emit("SIGTERM", "SIGTERM"); + observations.firstRecycleCanceled = cancel.mock.calls.some(([timer]) => timer === original); + } finally { cancel.mockRestore(); } + } else process.emit("SIGTERM", "SIGTERM"); + await (options.mode === "signal-active" ? entered : refused); + } else { + const { preflightConnectedClientStop } = await import("../../src/cli/stop-restore"); + const outcome = await preflightConnectedClientStop({ pid: process.pid, port: config.port }, finish => { finishStop = finish; }); + observations.stopRefused = outcome !== null && outcome !== "already-stopped" && !outcome.ok; + observations.activeAdmission = await restart(); // Latch the active marker before finalization. + if (["parent-stale-owner", "parent-malformed", "parent-malformed-start"].includes(options.mode)) { + const runtimePath = join(home, "runtime-port.json"); + const disk = JSON.parse(readFileSync(runtimePath, "utf8")); + const currentStart: string = disk.clientStopOwner.startTime; + const otherStart = currentStart.replace(/:\d+$/, value => value === ":0" ? ":1" : `:${BigInt(value.slice(1)) - 1n}`); + if (options.mode === "parent-malformed") disk.clientStopOwner.nonce = "malformed"; + else disk.clientStopOwner.startTime = options.mode === "parent-malformed-start" ? "malformed" : otherStart; + writeFileSync(runtimePath, JSON.stringify(disk)); + } else if (!["parent-active", "parent-unverified"].includes(options.mode)) await finishStop(); + } + observations.beforeRecoveryAdmission = await restart(); + observations.finishedMarker = readRuntimePort(process.pid)?.clientStopRequested; + phase = "disconnecting the Child"; + const { disconnectClient } = await import("../../src/client/connect"); + await disconnectClient({ recoverConfig: true }, { lifecycleLockDeps }); + const receiptPath = storePaths().disconnect; + if (["pending", "foreign-owner", "wrong-token"].includes(options.mode)) { + const receipt = JSON.parse(readFileSync(receiptPath, "utf8")); + if (options.mode === "pending") receipt.phase = "clearing_connection"; + if (options.mode === "foreign-owner") receipt.owner.apiKeyId = "another-client"; + if (options.mode === "wrong-token") receipt.tokenFingerprint = "d".repeat(64); + writeFileSync(receiptPath, JSON.stringify(receipt)); + } + if (options.mode === "corrupt-receipt") writeFileSync(receiptPath, "{"); + if (options.mode === "missing-config") unlinkSync(join(home, "config.json")); + if (options.mode === "new-connection") { config.client!.connectedAt = "2026-11-16T01:00:00.000Z"; saveConfig(config); } + if (options.mode === "pending-connect") markClientConnectPending("b".repeat(64)); + phase = "observing restart or recycle after disconnect"; + if (pendingRecycle) { + observations.recoveryRecycleTimers = scheduleAndCountTimers(); + if (observations.recoveryRecycleTimers === 0) { + const health = await (await fetch(`http://127.0.0.1:${config.port}/healthz`)).json() as { role: string }; + await report(health.role); process.exit(0); + } + return; // The scheduled replacement reports after binding the released listener's port. + } else if (options.mode === "timer-parent-active") { + const { markClientRuntimeStopping } = await import("../../src/client/sync-runtime"); + const runtime = readRuntimePort(process.pid)!; + const startTime = owner.readClientStopProcessStart(process.pid); + if (!startTime) throw new Error("fixture stop creation identity unavailable"); + // Queue the recycle and publish the stop in the same turn. Loading the + // marker module after scheduling could yield to the timer on a busy runner. + if (scheduleAndCountTimers() !== 1) throw new Error("fixture did not schedule the pre-stop recycle"); + markClientRuntimeStopping( + { pid: process.pid, port: config.port, attestationSecret: runtime.attestationSecret! }, + { pid: process.pid, startTime, nonce: "b".repeat(32) }, + ); + } else if (options.scheduled) { + if (scheduleAndCountTimers() !== 1) throw new Error("fixture did not schedule the post-disconnect recycle"); + } else observations.recoveryAdmission = await restart(); + if (["parent", "signal"].includes(options.mode) && !options.scheduled && observations.recoveryAdmission !== 202) { + const health = await (await fetch(`http://127.0.0.1:${config.port}/healthz`)).json() as { role: string }; + await report(health.role); process.exit(0); + } + if (!["parent", "signal", "parent-stale-owner"].includes(options.mode) || options.mode === "parent-stale-owner" && observations.recoveryAdmission !== 202) { + // Also exercise the scheduled callback; neither path may replace an active or unproven owner. + scheduleStandaloneRecycle(expected.tokenFingerprint); + await Bun.sleep(350); + const health = await (await fetch(`http://127.0.0.1:${config.port}/healthz`)).json() as { role: string }; + await report(health.role); + process.exit(0); // Dispose only this synthetic retained runtime after observing it. + } +} + +const deadline = setTimeout(() => { console.error(`recovery fixture timed out (${options.mode}: ${phase})`); process.exit(1); }, 10_000); +deadline.unref(); +try { await main(); } catch (error) { console.error(error); process.exit(1); } diff --git a/tests/fixtures/client-link-stop-runner.ts b/tests/fixtures/client-link-stop-runner.ts index 316a8c88c8b..1b5864ce573 100644 --- a/tests/fixtures/client-link-stop-runner.ts +++ b/tests/fixtures/client-link-stop-runner.ts @@ -1,26 +1,61 @@ /** Isolated disk and native-runtime coverage for a connected Link Child's stop. */ import { mock } from "bun:test"; -import { existsSync, mkdirSync, readFileSync, statSync, unlinkSync, writeFileSync } from "node:fs"; -import { join } from "node:path"; -import { getDefaultConfig, saveConfig } from "../../src/config"; +import { Database } from "bun:sqlite"; +import { existsSync, mkdirSync, readFileSync, statSync, symlinkSync, unlinkSync, writeFileSync } from "node:fs"; +import { dirname, join } from "node:path"; +import { getDefaultConfig, prepareConfigMutationDatabasePathForWrite, saveConfig } from "../../src/config"; import { CODEX_CONFIG_PATH, CODEX_HOME, CODEX_PROFILE_PATH, DEFAULT_CATALOG_PATH } from "../../src/codex/paths"; import { JOURNAL_PATH, markJournalInjectedState, writeJournal } from "../../src/codex/journal"; import { serviceApiTokenFingerprint } from "../../src/lib/service-secrets"; import { ensureCatalogBackup } from "../../src/codex/catalog/parsing"; import { takeDesktopSupervisedMarker } from "../../src/lib/system-restart-contract"; -import { claimPendingTeardown } from "../../src/config/pending-teardown"; +import { claimPendingTeardown, pendingTeardownOutstanding, pendingTeardownPathFor, quarantinePendingTeardown } from "../../src/config/pending-teardown"; +import type { ClientStopOwner } from "../../src/config/process-state"; +import type { StopTargetProof } from "../../src/cli/stop-restore"; +import { randomBytes } from "node:crypto"; const options = JSON.parse(readFileSync(0, "utf8")) as { - mode: "runtime" | "helper" | "api" | "parent" | "guard" | "retry"; + mode: "runtime" | "helper" | "api" | "parent" | "guard" | "retry" | "file-preflight" | "file-stop" | "file-cycle" | "file-restart-overlap" | "file-restart-control" | "offline-stop" | "termination"; transport?: "link" | "hub"; signal?: NodeJS.Signals; osSignal?: boolean; syncBeforeStop?: boolean; externalSignal?: boolean; holdShutdown?: boolean; - runtimeRecord?: "absent" | "invalid" | "foreign"; + runtimeRecord?: "absent" | "invalid" | "foreign" | "explicit-stop-unfenced"; retryError?: "busy" | "locked" | "exhausted" | "permission" | "unwrapped" | "identity"; repeat?: boolean; + fileClients?: Array<"pi" | "opencode">; + fileStandalone?: boolean; + fileConflict?: boolean; + fileOwnerChange?: boolean; + fileOnly?: boolean; + lateFileSync?: boolean; + deferFileApply?: boolean; + oldStopCapability?: boolean; + missingStopRecord?: "absent" | "invalid"; + startIdentityChanges?: "request" | "escalation"; + failedRollback?: "before-rebind" | "during-rebind"; + legacyOwnerRecord?: boolean; + stopConnectionDrift?: "invalid" | "mismatched" | "disconnected" | "other-link" | "hub"; + driftDuringFallback?: boolean; + finishStopBeforeRollback?: boolean; + unverifiedStopOwner?: boolean; + receiptWriteFails?: boolean; + installedUnit?: boolean; + danglingServiceRecord?: boolean; + busyStopFence?: boolean; + busyRollbackPublication?: boolean; + retryRollbackPublication?: "lifecycle" | "config" | "owner-changed"; + terminationPlatform?: "linux" | "darwin"; + siblingEscalation?: "stopping" | "different-generation"; + removeToken?: boolean; + receiptOwnerPid?: number; + finalizeFailure?: boolean; + repairFileRefusal?: boolean; + observeFileRefusal?: boolean; + observeNativeRefusal?: boolean; + receiptState?: "live" | "abandoned" | "abandoned-guessed" | "abandoned-other" | "abandoned-unknown" | "abandoned-dead-other" | "quarantined" | "invalid" | "parent" | "parent-stale" | "parent-invalid" | "parent-start" | "parent-status" | "parent-unfenced" | "parent-finished" | "parent-port" | "parent-host" | "parent-guessed" | "parent-oversized" | "parent-nonregular" | "parent-symlink" | "parent-reused" | "parent-wrong-nonce" | "parent-spaced"; preserve?: "service" | "desktop" | "receipt" | "sibling" | "restart" | "restart-rollback" | "recycle-pending" | "restart-rollback-recycle"; mutation?: "connection" | "journal" | "process-journal" | "config" | "profile" | "unverified" | "selection" | "oversized" | "nonregular" | "rotation" | "hub" | "catalog" | "prior-catalog" | "api-key" | "token" | "management" | "link-id"; }; @@ -29,8 +64,10 @@ mkdirSync(CODEX_HOME, { recursive: true }); mkdirSync(home, { recursive: true }); const lifecycle = await import("../../src/client/lifecycle-lock"); const lock = lifecycle.withClientLifecycleSync; +const asyncLock = lifecycle.withClientLifecycle; mock.module("../../src/client/lifecycle-lock", () => ({ ...lifecycle, - withClientLifecycleSync: (work: Parameters[0]) => lock(work, { lockPath: join(home, "lifecycle.sqlite") }), + withClientLifecycleSync: (work: Parameters[0], deps?: Parameters[1]) => lock(work, { lockPath: deps?.lockPath ?? join(home, "lifecycle.sqlite") }), + withClientLifecycle: (work: Parameters[0], deps?: Parameters[1]) => asyncLock(work, { lockPath: deps?.lockPath ?? join(home, "lifecycle.sqlite") }), })); const token = `ocx_data_${"c".repeat(40)}`; const config = getDefaultConfig(); @@ -43,11 +80,27 @@ config.client = { managementUrl: options.transport === "hub" ? "https://hub.example.test" : "http://127.0.0.1:34567", managementTransport: "direct", transport: options.transport ?? "link", ...(options.transport === "hub" ? {} : { link: { tunnelPort: 34567, linkId: "lnk_0123456789abcdef" } }), - selectedClients: ["codex"], tokenEnv: "OPENCODEX_API_AUTH_TOKEN", apiKeyId: "fixture-client", + selectedClients: ["codex", ...(options.deferFileApply ? [] : options.fileClients ?? [])], tokenEnv: "OPENCODEX_API_AUTH_TOKEN", apiKeyId: "fixture-client", tokenFingerprint: serviceApiTokenFingerprint(token), protocolVersion: 1, connectedAt: "2026-10-01T00:00:00.000Z", }; saveConfig(config); const expected = structuredClone(config.client); +const codexProbe = join(home, "unexpected-codex-discovery"); +if (process.platform !== "win32") { + const executable = join(home, "fixture-codex"); + writeFileSync(executable, '#!/bin/sh\n: > "$OPENCODEX_HOME/unexpected-codex-discovery"\nprintf "codex-cli 0.135.0\\n"\n', { mode: 0o700 }); + process.env.CODEX_CLI_PATH = executable; +} +// The fixture supplies its catalogs. Neither driver needs to launch an installed Codex +// CLI, whose Node wrapper can leave subprocesses and caches behind after the fixture exits. +const codexRuntime = await import("../../src/codex/runtime"); +mock.module("../../src/codex/runtime", () => ({ + ...codexRuntime, + resolveAndPersistCodexRuntime: (): import("../../src/codex/runtime").ResolveCodexRuntimeResult => ({ + runtime: { command: join(home, "unavailable-fixture-codex"), source: "environment", version: null }, failures: [], + }), + resolveAndPersistCodexRuntimeAsync: async () => null, +})); const original = 'model = "native"\n'; const injected = `# Auto-injected by opencodex (undo: ocx restore)\nopenai_base_url = "http://127.0.0.1:${config.port}/v1"\n${original}`; writeFileSync(CODEX_CONFIG_PATH, original); @@ -62,6 +115,53 @@ writeFileSync(DEFAULT_CATALOG_PATH, JSON.stringify(nativeCatalog)); ensureCatalogBackup(DEFAULT_CATALOG_PATH, nativeCatalog); writeFileSync(DEFAULT_CATALOG_PATH, '{"models":[{"slug":"fixture/home-model"}]}'); writeFileSync(join(home, "service-api-token"), token); +const filePaths: Record = {}; +const fileOwnedBytes: Record = {}; +let preparedFileIntent: import("../../src/integrations/route-intent-connected").PreparedConnectedRouteIntent | undefined; +if (options.fileClients?.length) { + process.env.XDG_CONFIG_HOME = join(process.env.HOME!, ".config"); + process.env.PI_CODING_AGENT_DIR = join(process.env.HOME!, ".pi", "agent"); + const { INTEGRATION_CLIENTS } = await import("../../src/integrations/registry"); + const writers = await import("../../src/integrations/writer"); + const { createIntegrationStateStore } = await import("../../src/integrations/store"); + const { ROUTE_CLIENT_IDS } = await import("../../src/link/route-intent"); + const { applyConnectedRouteIntent } = await import("../../src/integrations/route-intent-connected"); + for (const client of options.fileClients) { + const spec = INTEGRATION_CLIENTS[client]; + const path = filePaths[client] = spec.configPath(process.env, process.env.HOME!); + mkdirSync(spec.detectDir(process.env, process.env.HOME!), { recursive: true }); + mkdirSync(dirname(path), { recursive: true }); + writeFileSync(path, '{"fixtureUserSetting":"keep"}\n'); + if (options.fileStandalone) { + const applied = writers.applyIntegration({ clientId: client, config, port: config.port, + models: [{ namespaced: "fixture/native", provider: "fixture", id: "native" }], store: createIntegrationStateStore() }); + if (!applied.ok) throw new Error(applied.message); + } + } + const document = { version: 1 as const, home: { name: "fixture", version: "1" }, + clients: Object.fromEntries(ROUTE_CLIENT_IDS.map(id => [id, { enabled: options.fileClients!.includes(id as "pi" | "opencode") }])), + sources: Object.fromEntries(ROUTE_CLIENT_IDS.map(id => [id, "default"])) } as import("../../src/link/route-intent").HomeRouteIntentDocument; + preparedFileIntent = { document, stale: false, fetchedAt: "2026-11-16T00:00:00.000Z" }; + const applied = options.deferFileApply ? undefined : await applyConnectedRouteIntent(expected, token, preparedFileIntent, { + onlyClients: options.fileClients, lifecycleLockDeps: { lockPath: join(home, "lifecycle.sqlite") }, + }, { fetchImpl: (async () => Response.json({ data: [{ id: "fixture/home-model" }] })) as typeof fetch }); + for (const client of options.fileClients) { + if (!options.deferFileApply && applied?.outcomes.find(row => row.client === client)?.outcome !== "current") throw new Error("fixture route apply failed"); + fileOwnedBytes[client] = readFileSync(filePaths[client]!, "utf8"); + } + if (options.fileConflict) { + const path = filePaths.pi!; + const changed = JSON.parse(fileOwnedBytes.pi!); changed.providers.opencodex.apiKey = "operator-edited-placeholder"; + writeFileSync(path, JSON.stringify(changed)); + } + if (options.fileOwnerChange) { + const disable = writers.disableIntegrationCoordinated; + mock.module("../../src/integrations/writer", () => ({ ...writers, disableIntegrationCoordinated: async (...args: Parameters) => { + config.client!.connectedAt = "2026-11-16T01:00:00.000Z"; saveConfig(config); + return disable(...args); + } })); + } +} const grokHome = join(home, "grok"); process.env.GROK_HOME = grokHome; mkdirSync(grokHome, { recursive: true }); @@ -109,20 +209,76 @@ const configContents = () => statSync(CODEX_CONFIG_PATH).isFile() ? readFileSync const before = configContents(); const profileBefore = readFileSync(CODEX_PROFILE_PATH, "utf8"); let syncEvidence: { changedFields: string[]; fullCasRefused: boolean; catalogWritten: boolean; injected: boolean; journalHomeBound: boolean } | undefined; +let fileRefusal: { bound: boolean; stopping: boolean; before: Record } | undefined; +let fileLateResult: string | undefined; +let fileSyncFlight: Promise | undefined; +let releaseFileModels: (() => void) | undefined; const snapshot = (result: unknown) => ({ result, before, profileBefore, syncEvidence, after: configContents(), profileAfter: existsSync(CODEX_PROFILE_PATH) ? readFileSync(CODEX_PROFILE_PATH, "utf8") : null, journalRetained: existsSync(JOURNAL_PATH), journalHomeBound: existsSync(JOURNAL_PATH) && typeof JSON.parse(readFileSync(JOURNAL_PATH, "utf8")).opencodexHome === "string", - protectedUnchanged: protectedPaths.every((path, index) => readFileSync(path, "utf8") === protectedBefore[index]), + protectedUnchanged: protectedPaths.every((path, index) => existsSync(path) && readFileSync(path, "utf8") === protectedBefore[index]), catalogBefore, catalogAfter: JSON.parse(readFileSync(DEFAULT_CATALOG_PATH, "utf8")), grokBefore, grokAfter: readFileSync(grokPath, "utf8"), + fileOwnedBytes, fileAfter: Object.fromEntries(Object.entries(filePaths).map(([id, path]) => [id, readFileSync(path, "utf8")])), fileRefusal, fileLateResult, + teardownOutstanding: pendingTeardownOutstanding(), codexDiscovery: existsSync(codexProbe), }); const report = (result: unknown) => writeFileSync(join(home, "result.json"), JSON.stringify(snapshot(result))); process.on("exit", () => writeFileSync(join(home, "exit.json"), JSON.stringify(snapshot(null)))); +function holdConfigLock() { + const db = new Database(prepareConfigMutationDatabasePathForWrite()); + db.exec("BEGIN IMMEDIATE"); + setTimeout(() => db.close(), 120); +} +let receiptOwner: ClientStopOwner | undefined; if (options.preserve === "service") process.env.OCX_SERVICE = "1"; if (options.preserve === "desktop") takeDesktopSupervisedMarker({ OCX_DESKTOP_SUPERVISED: "1" }); -if (options.preserve === "receipt") claimPendingTeardown({ hostname: "127.0.0.1", port: config.port }, "exact"); +if (options.preserve === "receipt") { + let ownerPid = process.pid; + if (options.receiptState?.startsWith("abandoned")) { + const owner = Bun.spawn([process.execPath, "-e", "process.exit(0)"], { stdout: "ignore", stderr: "ignore" }); + await owner.exited; ownerPid = owner.pid; + } + if (options.receiptState?.startsWith("parent")) { + if (options.receiptOwnerPid === undefined) throw new Error("fixture stop owner missing"); + ownerPid = options.receiptOwnerPid; + const { readClientStopProcessStart } = await import("../../src/client/stop-teardown-owner"); + const observedStart = readClientStopProcessStart(ownerPid); + if (!observedStart) throw new Error("fixture stop process creation identity unavailable"); + const startTime = options.receiptState === "parent-reused" + ? observedStart.replace(/:\d+$/, value => value === ":0" ? ":1" : `:${BigInt(value.slice(1)) - 1n}`) + : observedStart; + receiptOwner = { pid: ownerPid, nonce: randomBytes(16).toString("hex"), startTime }; + } + const other = ["abandoned-other", "abandoned-unknown", "abandoned-dead-other"].includes(options.receiptState ?? "") + ? Bun.serve({ hostname: "127.0.0.1", port: 0, fetch: () => options.receiptState === "abandoned-unknown" + ? new Response(null, { status: 503 }) : Response.json({ service: "opencodex", version: "1.0.0", pid: process.pid }) }) : null; + const otherPort = other?.port; + if (options.receiptState === "abandoned-dead-other") await other?.stop(true); + const guessed = options.receiptState === "parent-guessed" || options.receiptState === "abandoned-guessed"; + const receipt = claimPendingTeardown({ hostname: options.receiptState === "parent-host" ? "192.0.2.10" : "127.0.0.1", + port: otherPort ?? (options.receiptState === "parent-port" ? (config.port === 65535 ? config.port - 1 : config.port + 1) : config.port) }, + guessed ? "guessed" : "exact", ownerPid, undefined, undefined, guessed ? undefined : receiptOwner); + const path = pendingTeardownPathFor(receipt.nonce); + if (options.receiptState === "quarantined" && !quarantinePendingTeardown(receipt.nonce)) throw new Error("fixture quarantine failed"); + if (options.receiptState === "invalid") writeFileSync(pendingTeardownPathFor(receipt.nonce), "{"); + if (options.receiptState === "parent-oversized") writeFileSync(path, JSON.stringify(receipt) + " ".repeat(4096)); + if (options.receiptState === "parent-nonregular") { unlinkSync(path); mkdirSync(path); } + if (options.receiptState === "parent-symlink") { const target = `${path}.fixture`; writeFileSync(target, readFileSync(path)); unlinkSync(path); symlinkSync(target, path); } + if (options.receiptState === "parent-stale") { + const stale = claimPendingTeardown({ hostname: "127.0.0.1", port: config.port }, "exact", process.pid); + writeFileSync(pendingTeardownPathFor(stale.nonce), "{"); + if (!quarantinePendingTeardown(stale.nonce)) throw new Error("fixture stale quarantine failed"); + const owner = Bun.spawn([process.execPath, "-e", "process.exit(0)"], { stdout: "ignore", stderr: "ignore" }); + await owner.exited; + claimPendingTeardown({ hostname: "127.0.0.1", port: config.port }, "exact", owner.pid); + } + if (options.receiptState === "parent-invalid") { + const invalid = claimPendingTeardown({ hostname: "127.0.0.1", port: config.port }, "exact", process.pid); + writeFileSync(pendingTeardownPathFor(invalid.nonce), "{"); + } +} if (options.preserve === "sibling") (await import("../../src/codex/sibling-start")).markSiblingStart(10100); if (options.mode === "retry") { const { ConfigMutationLockError } = await import("../../src/config"); @@ -153,30 +309,373 @@ if (options.mode === "retry") { try { guard.run(() => writes.push("after-change")); } catch { refused = true; } protectedBefore = protectedPaths.map(path => readFileSync(path, "utf8")); report({ writes, refused, boundary: guard.boundary() }); -} else if (options.mode === "runtime") { - if (options.holdShutdown) { +} else if (["runtime", "file-preflight", "file-stop", "file-restart-overlap", "file-restart-control"].includes(options.mode)) { + if (options.mode === "file-restart-overlap") { + // Exercise parent preflight and Child restart in one synthetic process. + const owner = await import("../../src/client/stop-teardown-owner"); + mock.module("../../src/client/stop-teardown-owner", () => ({ ...owner, + observeClientStopOwner: (proof: ClientStopOwner) => options.unverifiedStopOwner ? "unverified" + : owner.readClientStopProcessStart(proof.pid) === proof.startTime ? "active" : "confirmed-stale", + })); + } + if (options.fileOnly) { + // File-route tests isolate the existing native restore owner. Its own real-disk tests + // above remain independent; this stub performs no Codex/catalog/history writes. + const native = await import("../../src/codex/inject"); + mock.module("../../src/codex/inject", () => ({ ...native, restoreNativeCodex: () => ({ success: true, message: "native restore outside this fixture", + artifacts: { config: { state: "skipped", changed: false }, catalog: { state: "skipped", changed: false }, history: { state: "skipped", changed: false } }, + }) })); + } + if (options.holdShutdown || options.lateFileSync) { const diagnostics = await import("../../src/link/diagnostics"); mock.module("../../src/link/diagnostics", () => ({ ...diagnostics, flushLinkDiagnostics: async () => { - writeFileSync(join(home, "shutdown-drained"), "ready"); - while (!existsSync(join(home, "shutdown-release"))) await Bun.sleep(10); + if (options.holdShutdown) { + writeFileSync(join(home, "shutdown-drained"), "ready"); + while (!existsSync(join(home, "shutdown-release"))) await Bun.sleep(10); + } + await fileSyncFlight; + } })); + } + let replacementAttempts = 0; + let rollbackBinds = 0, publicationHeld = false; + let observeRollback!: (closed: boolean) => void; + const rollbackTurn = new Promise(resolve => { observeRollback = resolve; }); + let restartSettled: (() => Promise) | undefined; + const replaceSavedConnection = () => { + config.client!.connectedAt = "2026-11-17T00:00:00.000Z"; + saveConfig(config); + protectedBefore = protectedPaths.map(path => readFileSync(path, "utf8")); + }; + if (options.failedRollback || options.retryRollbackPublication) { + const controller = await import("../../src/client/runtime-restart"); + const create = controller.createClientRestartController; + mock.module("../../src/client/runtime-restart", () => ({ ...controller, createClientRestartController: (...args: Parameters) => { + const result = create(...args); + restartSettled = result.settled; + return result; } })); } if (options.preserve?.startsWith("restart-rollback")) { const replacement = await import("../../src/server/restart-replacement"); mock.module("../../src/server/restart-replacement", () => ({ ...replacement, - spawnReplacementStart: async () => { throw Object.assign(new Error("fixture replacement refused"), { code: "not_ready" }); }, + spawnReplacementStart: async () => { + replacementAttempts++; + if (options.failedRollback === "before-rebind") replaceSavedConnection(); + if (replacementAttempts === 1) throw Object.assign(new Error("fixture replacement refused"), { code: "not_ready" }); + }, })); } const { scheduleStandaloneRecycle, startClientRuntime } = await import("../../src/client/runtime"); const { startMachineListener } = await import("../../src/client/machine-listener"); let requestRestart: (() => Promise) | undefined; + let restartStopEntered!: () => void, releaseRestartStop!: () => void; + const restartStopping = new Promise(resolve => { restartStopEntered = resolve; }); + const restartRelease = new Promise(resolve => { releaseRestartStop = resolve; }); await startClientRuntime({ block: false }, { restartSupervisor: () => options.preserve?.startsWith("restart-rollback") ? Promise.resolve(null) : new Promise(() => {}), startListener: (port, deps) => { + if (replacementAttempts === 1) rollbackBinds++; requestRestart = deps?.restart?.request; - const server = startMachineListener(port, deps); + if (options.failedRollback === "during-rebind" && replacementAttempts === 1) replaceSavedConnection(); + const server = startMachineListener(port, options.oldStopCapability && deps?.restart + ? { ...deps, restart: { ...deps.restart, linkStopFence: undefined } } : deps); + if ((options.busyRollbackPublication || options.retryRollbackPublication) && replacementAttempts === 1 && !publicationHeld) { + publicationHeld = true; + const lock = new Database(options.retryRollbackPublication === "lifecycle" + ? join(home, "lifecycle.sqlite") : prepareConfigMutationDatabasePathForWrite()); + lock.exec("BEGIN IMMEDIATE"); + const stop = server.stop.bind(server); + let closed = false; + server.stop = ((force: boolean) => { const result = stop(force); closed = force; return result; }) as typeof server.stop; + // The bind and failed admission complete before the next event-loop turn. Keep C + // held until the observation, so a retry cannot publish in the meantime. + setImmediate(() => { + observeRollback(closed); lock.close(); + if (options.retryRollbackPublication === "owner-changed") replaceSavedConnection(); + }); + return server; + } const stop = server.stop.bind(server); - server.stop = ((close: boolean) => { report({ atListenerStop: true }); return stop(close); }) as typeof server.stop; + server.stop = ((close: boolean) => { + if (options.mode === "file-restart-overlap" && !close) { + restartStopEntered(); return restartRelease.then(() => stop(close)); + } + report({ atListenerStop: true }); releaseFileModels?.(); return stop(close); + }) as typeof server.stop; return server; } }); + if (options.mode === "file-restart-overlap" || options.mode === "file-restart-control") { + const { readRuntimePort } = await import("../../src/config/process-state"); + const { clientSyncRuntimeGuard } = await import("../../src/client/sync-runtime"); + const before = readRuntimePort(process.pid)!; + if (!requestRestart) throw new Error("fixture missing restart admission"); + await requestRestart(); + let preflight: unknown; + if (options.mode === "file-restart-overlap") { + await restartStopping; + let finishStop = async () => {}; + preflight = await (await import("../../src/cli/stop-restore")).preflightConnectedClientStop({ pid: process.pid, port: config.port, hostname: "127.0.0.1" }, finish => { finishStop = finish; }); + if (options.finishStopBeforeRollback) await finishStop(); + releaseRestartStop(); + } + if (options.busyRollbackPublication) { + const closedBeforeYield = await rollbackTurn; + report({ preflight, closedBeforeYield, published: readRuntimePort(process.pid)?.servingGeneration !== before.servingGeneration, replacementAttempts }); + process.exit(0); + } + if (options.retryRollbackPublication) { + const closedBeforeYield = await rollbackTurn; + await restartSettled!(); + const after = readRuntimePort(process.pid)!; + const published = after.servingGeneration !== before.servingGeneration; + const bound = published && (await fetch(`http://127.0.0.1:${config.port}/healthz`)).ok; + report({ preflight, closedBeforeYield, published, bound, rollbackBinds, replacementAttempts, + stopping: after.clientStopping, explicitStop: after.clientStopRequested }); + process.exit(0); + } + if (options.failedRollback) { + await restartSettled!(); + report({ preflight, replacementAttempts, runtimePresent: readRuntimePort(process.pid) !== null, + explicitStop: readRuntimePort(process.pid)?.clientStopRequested }); + process.exit(0); + } + let after = readRuntimePort(process.pid)!; + for (let attempt = 0; attempt < 400 && after.servingGeneration === before.servingGeneration; attempt++) { + await Bun.sleep(10); after = readRuntimePort(process.pid)!; + } + let sync = "accepted"; + try { clientSyncRuntimeGuard()(); } catch (error) { sync = (error as { code: string }).code; } + const admission = options.mode === "file-restart-overlap" ? await requestRestart() : undefined; + const health = await fetch(`http://127.0.0.1:${config.port}/healthz`); + report({ preflight, rolledBack: after.servingGeneration !== before.servingGeneration, bound: health.ok, + stopping: after.clientStopping === true, explicitStop: after.clientStopRequested === true, + ...(options.finishStopBeforeRollback ? { retainedStop: after.clientStopRequested === false } : {}), sync, admission }); + process.exit(0); + } + if (options.lateFileSync) { + const { clientSyncRuntimeGuard } = await import("../../src/client/sync-runtime"); + const { withConfigMutationLockSync } = await import("../../src/config"); + const { applyConnectedRouteIntent } = await import("../../src/integrations/route-intent-connected"); + const guard = clientSyncRuntimeGuard(); + let modelsReady!: () => void; + const ready = new Promise(resolve => { modelsReady = resolve; }); + const release = new Promise(resolve => { releaseFileModels = resolve; }); + // The real materializer has already committed its write-ahead receipt, then awaits + // this Home catalog response. Deliver it only after the stopping listener releases. + fileSyncFlight = applyConnectedRouteIntent(expected, token, preparedFileIntent, { + onlyClients: options.fileClients, lifecycleLockDeps: { lockPath: join(home, "lifecycle.sqlite") }, + beforeWrite: () => withConfigMutationLockSync(guard), + }, { fetchImpl: (async () => { + modelsReady(); await release; return Response.json({ data: [{ id: "fixture/late-home-model" }] }); + }) as typeof fetch }).then(() => { fileLateResult = "unexpected completion"; }, error => { fileLateResult = error.message; }); + await ready; + } + if (options.siblingEscalation) { + const { preflightConnectedClientStop } = await import("../../src/cli/stop-restore"); + const { readRuntimePort, writeRuntimePort } = await import("../../src/config/process-state"); + const { markClientRuntimeStopping } = await import("../../src/client/sync-runtime"); + const runtime = readRuntimePort(process.pid)!; + const control = await import("../../src/lib/process-control"); + const owner = await import("../../src/client/stop-teardown-owner"); + const linux = await import("../../src/service/health-sentinel-linux"); + const state = await import("../../src/client/state"); + const readConnection = state.readClientConnectionState; + const readStart = owner.readClientStopProcessStart; + const open = linux.openVerifiedPidfd; + const platform = Object.getOwnPropertyDescriptor(process, "platform")!; + const setPlatform = (value: string) => Object.defineProperty(process, "platform", { ...platform, value }); + const native = (action: () => T): T => { + const previous = process.platform; + setPlatform(platform.value); + try { return action(); } finally { setPlatform(previous); } + }; + const signals: Array<[fd: number, signal: number]> = []; + const closed: number[] = []; + const opened: number[] = []; + mock.module("../../src/lib/process-control", () => ({ ...control, waitForExit: () => signals.some(([, signal]) => signal === 9) })); + mock.module("../../src/client/stop-teardown-owner", () => ({ ...owner, readClientStopProcessStart: (pid: number) => native(() => readStart(pid)) })); + mock.module("../../src/client/state", () => ({ ...state, readClientConnectionState: () => native(readConnection) })); + mock.module("../../src/service/health-sentinel-linux", () => ({ ...linux, + openVerifiedPidfd: (pid: number, verify: () => boolean) => open(pid, verify, { load: () => ({ + open: target => { + opened.push(target); + return { value: 73, errno: 0 }; + }, + signal: (fd, signal) => { + if (signal !== 0) signals.push([fd, signal]); + if (signal === 15) native(() => { + markClientRuntimeStopping({ pid, port: runtime.port, attestationSecret: runtime.attestationSecret! }); + if (options.siblingEscalation === "different-generation") { + writeRuntimePort({ ...readRuntimePort(pid)!, servingGeneration: randomBytes(16).toString("hex") }); + } + }); + return { value: 0, errno: 0 }; + }, + close: fd => { closed.push(fd); }, + dispose: () => {}, + }) }), + })); + let proof: StopTargetProof | undefined; + const outcome = await preflightConnectedClientStop(runtime, () => { + throw new Error("a sibling must not acquire the shared stop fence"); + }, undefined, undefined, value => { proof = value; }, 10100); + if (outcome !== null || !proof?.terminateSibling) throw new Error("fixture sibling preflight did not admit termination"); + let refusal: string | undefined; + try { + setPlatform("linux"); + proof.terminateSibling(); + } catch (error) { + refusal = (error as Error).message; + } finally { + Object.defineProperty(process, "platform", platform); + } + report({ signals, openedExactlyOnceForTarget: Bun.deepEquals(opened, [process.pid]), closed, refusal, + stopping: readRuntimePort(process.pid)?.clientStopping }); + process.exit(0); + } + if (options.mode === "file-stop") { + if (options.receiptWriteFails) { + const pending = await import("../../src/config/pending-teardown"); + mock.module("../../src/config/pending-teardown", () => ({ ...pending, claimPendingTeardown: () => { + throw new Error("fixture receipt write denied"); + } })); + } + if (options.missingStopRecord) { + const path = join(home, "runtime-port.json"); + if (options.missingStopRecord === "absent") unlinkSync(path); + else writeFileSync(path, "{"); + const processState = await import("../../src/config/process-state"); + mock.module("../../src/config/process-state", () => ({ ...processState, readPid: () => process.pid })); + } + if (options.legacyOwnerRecord) { + const path = join(home, "runtime-port.json"); + const runtime = JSON.parse(readFileSync(path, "utf8")); + delete runtime.clientLinkOwner; + writeFileSync(path, JSON.stringify(runtime)); + } + if (options.stopConnectionDrift) { + const path = join(home, "config.json"); + const saved = JSON.parse(readFileSync(path, "utf8")); + switch (options.stopConnectionDrift) { + case "invalid": saved.client = {}; break; + case "mismatched": delete saved.runtimeRole; break; + case "disconnected": delete saved.runtimeRole; delete saved.client; break; + case "other-link": saved.client.connectedAt = "2026-11-17T00:00:00Z"; break; + case "hub": + saved.client.transport = "hub"; delete saved.client.link; + saved.client.serverUrl = saved.client.managementUrl = "https://hub.example.test"; + break; + } + writeFileSync(path, JSON.stringify(saved)); + } + if (options.finalizeFailure) { + const sync = await import("../../src/client/sync-runtime"); + mock.module("../../src/client/sync-runtime", () => ({ ...sync, finishClientRuntimeStop: () => { throw new Error("fixture storage refusal"); } })); + } + const calls = { service: 0, killed: 0 }; + let startChanged = false; + const kill = process.kill; + process.kill = ((pid: number, signal?: number | NodeJS.Signals) => { + if (signal === 0) return kill(pid, signal); + calls.killed++; + if (options.startIdentityChanges === "escalation" && signal === "SIGTERM") { + startChanged = true; + return true; + } + throw new Error("unexpected stop signal after file refusal"); + }) as typeof process.kill; + if (options.startIdentityChanges === "escalation" && process.platform === "linux") { + const linux = await import("../../src/service/health-sentinel-linux"); + mock.module("../../src/service/health-sentinel-linux", () => ({ ...linux, + openVerifiedPidfd: (pid: number, verify: () => boolean) => { + verify(); + return { kind: "bound", handle: { + terminate: (signal: number) => { process.kill(pid, signal === 15 ? "SIGTERM" : "SIGKILL"); return "terminated"; }, + close() {}, + } }; + }, + })); + } + if (options.startIdentityChanges) { + const owner = await import("../../src/client/stop-teardown-owner"); + const readStart = owner.readClientStopProcessStart; + mock.module("../../src/client/stop-teardown-owner", () => ({ ...owner, + readClientStopProcessStart: (pid: number) => startChanged ? "fixture:replacement" : readStart(pid), + })); + } + const control = await import("../../src/lib/process-control"); + const realStopProxy = control.stopProxy; + mock.module("../../src/lib/process-control", () => ({ ...control, stopProxy: async (pid: number, io: Parameters[1]) => { + if (options.driftDuringFallback || options.startIdentityChanges) { + return realStopProxy(pid, { ...io, fetchFn: async () => { + if (options.driftDuringFallback) writeFileSync(join(home, "config.json"), "{"); + if (options.startIdentityChanges === "request") startChanged = true; + return new Response(null, { status: 404 }); + } }); + } + calls.killed++; throw new Error("unexpected process stop after file refusal"); + } })); + const service = await import("../../src/service"); + mock.module("../../src/service", () => ({ ...service, stopServiceIfInstalledDetailed: () => { + calls.service++; + if (options.driftDuringFallback || options.startIdentityChanges) return "absent"; + throw new Error("unexpected service stop after file refusal"); + } })); + const dispatch = await import("../../src/cli/dispatch"); + const command = dispatch.dispatchCommand; + mock.module("../../src/cli/dispatch", () => ({ ...dispatch, dispatchCommand: async (...args: Parameters) => { + const exitCode = await command(...args); + const health = await fetch(`http://127.0.0.1:${config.port}/healthz`); + const runtime = (await import("../../src/config/process-state")).readRuntimePort(); + report({ exitCode, calls, bound: health.ok, stopping: runtime?.clientStopping === true, + ...(options.finalizeFailure ? { activeStop: runtime?.clientStopRequested === true } : {}) }); + return exitCode; + } })); + mock.module("../../src/cli/codex-shim-autorestore", () => ({ async maybeAutoRestoreCodexShimAsync() {} })); + process.argv = [process.execPath, "ocx", "stop", "--json"]; + await import("../../src/cli/index"); + } + if (options.mode === "file-preflight") { + const { clientSyncRuntimeGuard } = await import("../../src/client/sync-runtime"); + const { withConfigMutationLockSync } = await import("../../src/config"); + const admitted = options.deferFileApply ? clientSyncRuntimeGuard() : undefined; + const { preflightConnectedClientStop } = await import("../../src/cli/stop-restore"); + const outcome = await preflightConnectedClientStop({ pid: process.pid, port: config.port, hostname: "127.0.0.1" }, () => { + if (options.busyStopFence) holdConfigLock(); + }); + if (admitted) { + try { + await (await import("../../src/integrations/route-intent-connected")).applyConnectedRouteIntent(expected, token, preparedFileIntent, { + onlyClients: options.fileClients, lifecycleLockDeps: { lockPath: join(home, "lifecycle.sqlite") }, + beforeWrite: () => withConfigMutationLockSync(admitted), + }, { fetchImpl: (async () => Response.json({ data: [{ id: "fixture/home-model" }] })) as typeof fetch }); + fileLateResult = "unexpected completion"; + } catch (error) { fileLateResult = (error as { code: string }).code; } + } + const health = await fetch(`http://127.0.0.1:${config.port}/healthz`); + report({ outcome, bound: health.ok, stopping: JSON.parse(readFileSync(join(home, "runtime-port.json"), "utf8")).clientStopping === true }); + // The test owns this synthetic runtime and disposes it after observing the preflight. + process.exit(0); + } + if (options.repairFileRefusal || options.observeFileRefusal || options.observeNativeRefusal) { + const printError = console.error; + console.error = (...args: unknown[]) => { + printError(...args); + if (!args.some(value => String(value).includes(options.observeNativeRefusal + ? "Link Child Codex routing restore refused" : "The listener remains bound"))) return; + void (async () => { + const health = await fetch(`http://127.0.0.1:${config.port}/healthz`); + const { readRuntimePort } = await import("../../src/config/process-state"); + fileRefusal = { bound: health.ok, stopping: readRuntimePort(process.pid)?.clientStopping === true, + before: Object.fromEntries(Object.entries(filePaths).map(([id, path]) => [id, readFileSync(path, "utf8")])) }; + if (options.observeFileRefusal || options.observeNativeRefusal) { + report({ refused: true, bound: fileRefusal.bound, stopping: fileRefusal.stopping }); + // Dispose only this synthetic process after observing that production kept it bound. + process.exit(0); + } + for (const [id, path] of Object.entries(filePaths)) writeFileSync(path, fileOwnedBytes[id]!); + process.emit("SIGTERM", "SIGTERM"); + })(); + }; + } if (options.syncBeforeStop) { const { syncConnectedClient } = await import("../../src/client/connect"); const { assertClientConnectionUnchanged } = await import("../../src/client/state"); @@ -197,10 +696,25 @@ if (options.mode === "retry") { const path = join(home, "runtime-port.json"); if (options.runtimeRecord === "absent") unlinkSync(path); else if (options.runtimeRecord === "invalid") writeFileSync(path, "{"); + else if (options.runtimeRecord === "explicit-stop-unfenced") { + const record = JSON.parse(readFileSync(path, "utf8")); record.clientStopRequested = true; delete record.clientStopping; + writeFileSync(path, JSON.stringify(record)); + } else { const record = JSON.parse(readFileSync(path, "utf8")); record.pid += 100_000; writeFileSync(path, JSON.stringify(record)); } } + if (options.receiptState?.startsWith("parent") && options.receiptState !== "parent-unfenced") { + const { readRuntimePort } = await import("../../src/config/process-state"); + const { markClientRuntimeStopping, finishClientRuntimeStop } = await import("../../src/client/sync-runtime"); + const runtime = readRuntimePort(process.pid)!; + const identity = { pid: process.pid, port: config.port, attestationSecret: runtime.attestationSecret! }; + if (!receiptOwner) throw new Error("fixture stop owner missing"); + const proof = options.receiptState === "parent-wrong-nonce" ? { ...receiptOwner, nonce: "b".repeat(32) } : receiptOwner; + markClientRuntimeStopping(identity, proof); + if (options.receiptState === "parent-finished") finishClientRuntimeStop(identity, proof); + } mutate(); - protectedBefore = protectedPaths.map(path => readFileSync(path, "utf8")); + if (options.removeToken) unlinkSync(join(home, "service-api-token")); + if (!options.removeToken) protectedBefore = protectedPaths.map(path => readFileSync(path, "utf8")); if (options.preserve === "restart") { if (!requestRestart) throw new Error("fixture missing real restart admission"); void requestRestart(); @@ -217,7 +731,75 @@ if (options.mode === "retry") { process.emit(options.signal ?? "SIGTERM", options.signal ?? "SIGTERM"); } else if (options.osSignal) writeFileSync(join(home, "ready"), "ready"); else process.emit(options.signal ?? "SIGTERM", options.signal ?? "SIGTERM"); +} else if (options.mode === "termination") { + const control = await import("../../src/lib/process-control"); + const linux = await import("../../src/service/health-sentinel-linux"); + const { terminateAttestedClient } = await import("../../src/cli/stop-client-process"); + mock.module("../../src/lib/process-control", () => ({ ...control, waitForExit: () => false })); + mock.module("../../src/service/health-sentinel-linux", () => ({ ...linux, + openVerifiedPidfd: () => ({ kind: "unsupported", reason: "fixture kernel without pidfd" }), + })); + const platform = Object.getOwnPropertyDescriptor(process, "platform")!; + const kill = process.kill; + const signals: Array = []; + let message = ""; + try { + Object.defineProperty(process, "platform", { ...platform, value: options.terminationPlatform }); + process.kill = ((pid: number, signal?: number | NodeJS.Signals) => { + if (signal === 0) return kill(pid, signal); + signals.push(signal ?? "SIGTERM"); + return true; + }) as typeof process.kill; + terminateAttestedClient(process.pid, "fixture", () => {}); + } catch (error) { + message = (error as Error).message; + } finally { + process.kill = kill; + Object.defineProperty(process, "platform", platform); + } + report({ signals, message }); +} else if (options.mode === "offline-stop") { + const systemd = await import("../../src/service/systemd"); + const { unitPath, systemdInstallationAbsent } = systemd; + // Model only the Linux manager policy; filesystem, ACL and token checks use the real OS. + mock.module("../../src/service/systemd", () => ({ ...systemd, + systemdInstallationAbsent: () => systemdInstallationAbsent("linux"), + })); + if (options.danglingServiceRecord) symlinkSync(join(home, "missing-service-state"), join(home, "service-state.json")); + if (options.installedUnit) { + mkdirSync(dirname(unitPath()), { recursive: true }); + writeFileSync(unitPath(), "[Service]\n"); + } + const manager = await import("../../src/service/guarded-manager-target"); + mock.module("../../src/service/guarded-manager-target", () => ({ ...manager, + observeGuardedManagerStopped: async () => "unknown", + })); + const dispatch = await import("../../src/cli/dispatch"); + const command = dispatch.dispatchCommand; + mock.module("../../src/cli/dispatch", () => ({ ...dispatch, dispatchCommand: async (...args: Parameters) => { + const exitCode = await command(...args); + report({ exitCode }); + return exitCode; + } })); + mock.module("../../src/cli/codex-shim-autorestore", () => ({ async maybeAutoRestoreCodexShimAsync() {} })); + process.argv = [process.execPath, "ocx", "stop", "--json"]; + await import("../../src/cli/index"); +} else if (options.mode === "file-cycle") { + const { restoreLinkFileRouting } = await import("../../src/client/stop-file-routing"); + const first = await restoreLinkFileRouting(expected); + const second = await restoreLinkFileRouting(expected); + const stopped = Object.fromEntries(Object.entries(filePaths).map(([id, path]) => [id, readFileSync(path, "utf8")])); + const { applyConnectedRouteIntent } = await import("../../src/integrations/route-intent-connected"); + const reapplied = await applyConnectedRouteIntent(expected, token, preparedFileIntent, { + onlyClients: options.fileClients, lifecycleLockDeps: { lockPath: join(home, "lifecycle.sqlite") }, + }, { fetchImpl: (async () => Response.json({ data: [{ id: "fixture/home-model" }] })) as typeof fetch }); + report({ first, second, stopped, reapplied: reapplied?.outcomes.filter(row => options.fileClients?.includes(row.client as "pi" | "opencode")) }); } else { + if (options.mode === "parent" && options.stopConnectionDrift === "disconnected") { + delete config.client; + delete config.runtimeRole; + saveConfig(config); + } const result = options.mode === "api" ? await (await import("../../src/server/stop-teardown")).performStopTeardown(new URL("http://127.0.0.1:10100/api/stop?deferSharedTeardown=1&teardownNonce=fixture"), { ownsReceipt: () => true }) : options.mode === "parent" ? await (await import("../../src/cli/stop-restore")).restoreSharedClientStateAfterStop(() => {}) diff --git a/tests/fixtures/parent-stop-runner.ts b/tests/fixtures/parent-stop-runner.ts index 50f1ab1605b..1394e678807 100644 --- a/tests/fixtures/parent-stop-runner.ts +++ b/tests/fixtures/parent-stop-runner.ts @@ -16,10 +16,15 @@ const options = JSON.parse(readFileSync(0, "utf8")) as { status?: number; /** #7563: run the stop as a connected client of this transport. */ clientTransport?: "hub" | "link"; + siblingRecord?: "standalone" | "link"; serverTeardown?: boolean; json?: boolean; clientServer?: "legacy" | "unknown" | "wrong-pid" | "malformed" | "oversized" | "unauthorized" | "redirect" | "body-timeout"; managerCascades?: boolean; + managerBound?: boolean; + discoveryMiss?: boolean; + standaloneRecord?: "legacy" | "current" | "stale" | "wrong-home" | "wrong-port" | "client-role"; + legacyWindowsEvidence?: "match" | "foreign-sid" | "wrong-argv" | "wrong-pid" | "wrong-port" | "wrong-bind" | "client-role" | "serving-generation"; guarded?: boolean; /** #7771: the guarded path on a simulated win32, with a bound scheduler manager (separate child stop). */ windowsGuarded?: boolean; @@ -32,6 +37,7 @@ const options = JSON.parse(readFileSync(0, "utf8")) as { stopBodyFailure?: boolean; proxyProbePort?: number; alreadyStopped?: boolean; + staleRuntimeRecord?: boolean; absence?: "dead" | "unknown" | "live"; managerState?: "inactive" | "active" | "unknown"; /** Commit a disconnect while the capability probe is in flight. */ @@ -66,6 +72,50 @@ const options = JSON.parse(readFileSync(0, "utf8")) as { windowsWinswStopped?: boolean; windowsPartAReject?: boolean; }; +if (options.legacyWindowsEvidence) { + // Fake Windows process evidence at the OS boundary. The production argv/listener + // readers and standalone proof run here without touching the host's process table. + const evidence = options.legacyWindowsEvidence; + const record = { pid: 4242, port: 10100, hostname: "127.0.0.1", + ...(evidence === "client-role" ? { role: "client" as const } : {}), + ...(evidence === "serving-generation" ? { servingGeneration: "a".repeat(32) } : {}), + }; + const { proveStandaloneStopRecord } = await import("../../src/cli/stop-restore"); + const { setProcessCommandLinePlatformForTests } = await import("../../src/config/process-state"); + setProcessCommandLinePlatformForTests("win32"); + const { readSameUserWindowsStart, setWindowsProcessNativeForTests } = await import("../../src/service/windows-process-native"); + setWindowsProcessNativeForTests({ creationTime: () => null, terminate: () => ({ status: "unavailable" }), + openWatch: () => ({ status: "unavailable" }), scheduleServicePid: () => null, + sameUserStartTicks: pid => readSameUserWindowsStart(pid, { + open: target => target === record.pid ? 1 : 0, close: () => {}, + fileTime: () => 134_088_768_000_000_000n, exited: () => false, + ownerSid: () => evidence === "foreign-sid" ? "S-1-5-21-2" : "S-1-5-21-1", currentSid: () => "S-1-5-21-1", + }), + }); + const windows = await import("../../src/lib/windows-elevation"); + mock.module("../../src/lib/windows-elevation", () => ({ ...windows, + resolveTrustedWindowsSystemDirectory: () => "system", + resolveTrustedWindowsPowerShellExe: () => "powershell.exe", + })); + mock.module("node:child_process", () => ({ ...childProcess, + execFileSync(file: string, args: string[]) { + if (file.endsWith("netstat.exe")) { + const host = evidence === "wrong-bind" ? "0.0.0.0" : record.hostname; + const pid = evidence === "wrong-pid" ? 4243 : record.pid; + const port = evidence === "wrong-port" ? record.port + 1 : record.port; + return `TCP ${host}:${port} 0.0.0.0:0 LISTENING ${pid}\r\n`; + } + if (file.endsWith("WMIC.exe")) { + const verb = evidence === "wrong-argv" ? 'status "start"' : "start"; + return `CommandLine="C:\\Program Files\\Bun\\bun.exe" run "C:\\work tree\\src\\cli\\index.ts" ${verb}\r\n`; + } + throw new Error(`Unexpected Windows evidence command: ${file}`); + }, + })); + Object.defineProperty(process, "platform", { value: "win32" }); + console.log(JSON.stringify({ proved: Boolean(await proveStandaloneStopRecord(record, record.pid, [])) })); + process.exit(0); +} if (options.proxyProbePort) { // Deliberately bypass every fixture mock for the real proxy-environment regression. const origin = `http://127.0.0.1:${options.proxyProbePort}`; @@ -101,17 +151,20 @@ function writeHubConnection(): void { const lifecycle = await import("../../src/client/lifecycle-lock"); mock.module("../../src/client/lifecycle-lock", () => ({ ...lifecycle, withClientLifecycleSync: (work: Parameters[0]) => { - if (options.lifecycleBusy) throw new Error("client_lifecycle_busy"); + // These scenarios target the restore boundary after termination, not the new + // connected-Link file preflight while its listener is still alive. + if (options.lifecycleBusy && !alive) throw new Error("client_lifecycle_busy"); calls.lifecycle += 1; const value = work(Object.freeze({}) as Parameters[0]); - if (options.connectAfterBoundary) queueMicrotask(writeHubConnection); - if (options.pendingAfterBoundary) queueMicrotask(publishPending); + if (options.connectAfterBoundary && !alive) queueMicrotask(writeHubConnection); + if (options.pendingAfterBoundary && !alive) queueMicrotask(publishPending); return value; }, })); const endpoint = { hostname: "127.0.0.1", port: 10100 }; const fakePid = 4242; -const calls = { killed: 0, native: 0, grok: 0, cleared: 0, exited: 0, service: 0, lifecycle: 0, partB: 0, reclaim: 0 }; +const calls = { killed: 0, native: 0, grok: 0, cleared: 0, exited: 0, service: 0, lifecycle: 0, partB: 0, reclaim: 0, systemEnv: 0 }; +const signals: string[] = []; /** The timeout each reclaimListenPort call asked for; #7771 makes a skipped 15 s wait visible. */ const reclaimTimeouts: number[] = []; /** The Part A record each stop POST's receipt carried when the POST was sent (#7771). */ @@ -121,6 +174,7 @@ const { Database } = await import("bun:sqlite"); const { prepareConfigMutationDatabasePathForWrite } = await import("../../src/config"); const urls: string[] = []; const probes: string[] = []; +const absenceProbes: number[] = []; const transports: string[] = []; let viaDirect = false; const unexpectedIo: string[] = []; @@ -134,6 +188,12 @@ function unexpected(operation: string): never { // Neither an accidental POSIX signal nor the Windows taskkill fallback may reach the host. process.kill = ((pid: number, signal?: number | NodeJS.Signals) => { + if (options.discoveryMiss && pid === fakePid && (signal === "SIGTERM" || signal === "SIGKILL")) { + signals.push(signal); + calls.killed++; + if (signal === "SIGKILL" || options.standaloneRecord) alive = false; + return true; + } if (options.nativeSignal && pid === fakePid && signal === "SIGTERM") { calls.killed++; alive = false; return true; } if (pid !== fakePid || signal !== 0) { calls.killed += 1; @@ -146,6 +206,7 @@ process.kill = ((pid: number, signal?: number | NodeJS.Signals) => { mock.module("node:child_process", () => ({ ...childProcess, execFileSync: (file: string) => { + if (options.discoveryMiss && file.endsWith("taskkill.exe")) { signals.push("taskkill /F"); calls.killed++; alive = false; return Buffer.alloc(0); } if (options.nativeSignal && file.endsWith("taskkill.exe")) { calls.killed++; alive = false; return Buffer.alloc(0); } calls.killed += 1; return unexpected("execFileSync"); }, @@ -156,7 +217,7 @@ if (options.windowsStopWiring) (await import("../../src/cli/stop-windows-checked process.on("exit", () => { receiptBlocker?.close(); writeFileSync(join(home, "parent-stop-result.json"), JSON.stringify({ - calls, reclaimTimeouts, urls, probes, transports, unexpectedIo, nonce, postPartA, + calls, signals, reclaimTimeouts, urls, probes, absenceProbes, transports, unexpectedIo, nonce, postPartA, receiptExists: nonce !== undefined && existsSync(receipts.pendingTeardownPathFor(nonce)), })); }); @@ -174,12 +235,39 @@ mock.module("../../src/config/pending-teardown", () => ({ })); const state = await import("../../src/config/process-state"); +// The human stop notice must not inspect the host process with this fixture's synthetic PID. +const supervision = await import("../../src/service/desktop-supervision.mjs"); +mock.module("../../src/service/desktop-supervision.mjs", () => ({ + ...supervision, + inspectDesktopSupervision: () => ({ kind: "none" }), +})); +const readRuntime = state.readRuntimePort; +if ((!options.alreadyStopped || options.staleRuntimeRecord) && !options.noRuntimeRecord) { + const { linkStopConnectionOwner, readClientConnectionState } = await import("../../src/client/state"); + const connection = readClientConnectionState(); + const clientLinkOwner = connection.kind === "connected" && options.siblingRecord !== "standalone" + ? linkStopConnectionOwner(connection.value) ?? null : undefined; + const record = { ...endpoint, pid: fakePid, ...(options.siblingRecord ? { siblingOfPort: 10101 } : {}) }; + writeFileSync(join(home, "runtime-port.json"), JSON.stringify(options.standaloneRecord === "legacy" + || options.standaloneRecord === "wrong-home" || options.standaloneRecord === "wrong-port" ? record : { + ...record, attestationSecret: ATTESTATION_SECRET, clientLinkOwner, + startTime: options.standaloneRecord ? options.standaloneRecord === "stale" ? "fixture:previous-runtime" : "fixture:serving-runtime" : undefined, + role: options.standaloneRecord === "client-role" ? "client" : undefined, + })); +} +const stopOwner = await import("../../src/client/stop-teardown-owner"); +mock.module("../../src/client/stop-teardown-owner", () => ({ ...stopOwner, + readClientStopProcessStart: (pid: number) => pid === process.pid ? "fixture:stop-owner" + : pid === fakePid && alive ? "fixture:serving-runtime" : undefined, + readLegacyStopProcessHome: () => options.standaloneRecord === "wrong-home" ? join(home, "other") : home, +})); mock.module("../../src/config/process-state", () => ({ ...state, readPid: () => options.orphan || options.alreadyStopped || (options.deadPidReadsNull && !alive) ? null : fakePid, - readRuntimePort: () => options.alreadyStopped || options.noRuntimeRecord ? null : { ...endpoint, pid: fakePid, attestationSecret: ATTESTATION_SECRET }, + readProcessCommandLine: (pid: number) => pid === fakePid && alive ? "ocx start" : undefined, + readRuntimePort: (pid?: number) => (options.alreadyStopped && !options.staleRuntimeRecord) || options.noRuntimeRecord ? null : readRuntime(pid), removePid() {}, - removeRuntimePort() {}, + removeRuntimePort: options.siblingRecord ? state.removeRuntimePort : () => {}, })); const service = await import("../../src/service"); mock.module("../../src/service", () => ({ ...service, stopServiceIfInstalledDetailed: () => { @@ -187,6 +275,14 @@ mock.module("../../src/service", () => ({ ...service, stopServiceIfInstalledDeta if (options.managerCascades) { alive = false; return "stopped"; } return "absent"; } })); +if (options.discoveryMiss || options.managerBound) { + const guarded = await import("../../src/service/guarded-manager-target"); + mock.module("../../src/service/guarded-manager-target", () => ({ ...guarded, + inspectGuardedManagerTarget: (pid: number) => options.managerBound && pid === fakePid && alive + ? { kind: "bound", pid, managerPid: pid, backend: "systemd", childNeedsSeparateStop: false } + : { kind: "unknown", reason: "fixture manager does not own the tracked PID" }, + })); +} if (options.guarded) { const approval = { pid: fakePid, ...endpoint, configHome: home, cliVersion: "2.93.0", compatibilityToken: "fixture" }; const manager = options.windowsGuarded @@ -204,15 +300,15 @@ if (options.guarded) { observeGuardedManagerStopped: () => (options.windowsGuarded ? "inactive" : "stopped"), })); } -if (options.orphan || options.alreadyStopped) { +if (options.orphan || options.alreadyStopped || options.discoveryMiss) { const liveness = await import("../../src/server/proxy-liveness"); mock.module("../../src/server/proxy-liveness", () => ({ ...liveness, findLiveProxy: async () => { if (options.connectDuringDiscovery) writeHubConnection(); - return alive ? { ...endpoint, pid: fakePid, source: "config" } : null; + return alive && !options.discoveryMiss ? { ...endpoint, pid: fakePid, source: "config" } : null; }, proveLiveProxyOwnedByHome: async () => "proven", - probeEndpointLiveness: async () => options.absence ?? "dead", + probeEndpointLiveness: async (target: { port: number }) => { absenceProbes.push(target.port); return options.absence ?? "dead"; }, })); } if (options.alreadyStopped) { @@ -245,9 +341,11 @@ mock.module("../../src/grok/inject", () => ({ }, })); const systemEnv = await import("../../src/server/system-env"); -mock.module("../../src/server/system-env", () => ({ ...systemEnv, revertSystemEnv() {} })); +mock.module("../../src/server/system-env", () => ({ ...systemEnv, revertSystemEnv() { calls.systemEnv++; } })); const portReclaim = await import("../../src/server/port-reclaim"); mock.module("../../src/server/port-reclaim", () => ({ ...portReclaim, + inspectIpv4LoopbackListener: async () => ({ kind: options.standaloneRecord === "wrong-port" ? "mismatch" : "match", elapsedMs: 0 }), + ownsLegacyStopBind: async () => options.standaloneRecord !== "wrong-port", reclaimListenPort: async (_port: number, _host: string, options?: { timeoutMs?: number }) => { calls.reclaim += 1; reclaimTimeouts.push(options?.timeoutMs ?? 0); @@ -267,8 +365,10 @@ globalThis.fetch = (async (input: string | URL | Request, init?: RequestInit) => const proof = nonce ? createLocalAttestationProof(ATTESTATION_SECRET, nonce, fakePid, endpoint.port) : null; const headers = proof ? { [LOCAL_ATTESTATION_PROOF_HEADER]: proof } : undefined; if (url.endsWith("/healthz")) { + if (options.standaloneRecord) throw new Error("fixture listener cannot answer health"); return Response.json({ service: "opencodex", version: "2.93.0", pid: fakePid, - ...(!options.serverTeardown && !options.clientServer ? { role: "client" } : {}) }, { headers }); + ...(options.clientTransport === "link" && options.siblingRecord !== "standalone" ? { linkStopFence: true } : {}), + ...(options.clientTransport && options.siblingRecord !== "standalone" && !options.serverTeardown && !options.clientServer ? { role: "client" } : {}) }, { headers }); } if (!url.endsWith("/api/stop")) return unexpected(`GET ${url}`); if (options.clientServer === "unknown") throw new Error("fixture probe unavailable"); @@ -290,6 +390,7 @@ globalThis.fetch = (async (input: string | URL | Request, init?: RequestInit) => urls.push(url); postPartA.push(receipts.pendingTeardownPartA(new URL(url).searchParams.get("teardownNonce"))); transports.push(viaDirect ? "direct" : "global"); + if (options.standaloneRecord === "current") throw new Error("fixture listener cannot answer stop"); if (options.connectDuringPost) writeHubConnection(); const body = options.serverTeardown && !options.apiFailure ? await (await import("../../src/server/stop-teardown")).performStopTeardown(new URL(url)) diff --git a/tests/fixtures/test-layout-expected.json b/tests/fixtures/test-layout-expected.json index 5456ea950de..5a5790138a1 100644 --- a/tests/fixtures/test-layout-expected.json +++ b/tests/fixtures/test-layout-expected.json @@ -1580,7 +1580,7 @@ "windows-elevation-spawn.test.ts": "windows", "windows-elevation.test.ts": "windows", "windows-guarded-manager.test.ts": "windows", "windows-checked-stop.test.ts": "windows", "windows-stop-binding.test.ts": "windows", "windows-checked-stop-live.test.ts": "windows", "windows-service-stop-wiring.test.ts": "windows", - "windows-popup-fix.test.ts": "windows", "windows-stop-confirm.test.ts": "windows", "windows-process-evidence.test.ts": "windows", "windows-stop-callers.test.ts": "windows", "windows-stop-ocx-stop.test.ts": "windows", + "windows-popup-fix.test.ts": "windows", "windows-stop-confirm.test.ts": "windows", "windows-process-evidence.test.ts": "windows", "windows-stop-owner-identity.test.ts": "windows", "windows-stop-callers.test.ts": "windows", "windows-stop-ocx-stop.test.ts": "windows", "windows-process-priority.test.ts": "windows", "windows-scheduler-errors.test.ts": "windows", "windows-scheduler-install-verification.test.ts": "windows", "windows-lifecycle-root-acl.test.ts": "windows", @@ -1648,6 +1648,9 @@ "grok-47-build-fast-metadata.test.ts": "providers/xai", "grok-47-fast-model.test.ts": "providers/xai", "grok-47-fast-model-wire.test.ts": "providers/xai", "client-link-connect.test.ts": "clients", "client-link-relay.test.ts": "clients", "client-link-runtime.test.ts": "clients", "client-link-stop.test.ts": "clients", + "client-link-stop-recovery.test.ts": "clients", + "client-recycle-exclusion.test.ts": "clients", + "client-restart-rollback-lock.test.ts": "clients", "client-link-stop-sibling.test.ts": "clients", "link-routes.test.ts": "clients", "client-link-state.test.ts": "clients", "client-link-status.test.ts": "clients", "client-link-teardown.test.ts": "clients", "client-disconnect-recovery.test.ts": "clients", "client-disconnect-desktop-refusals.test.ts": "clients", "client-link-tunnel.test.ts": "clients", "link-ports.test.ts": "clients", diff --git a/tests/helpers/client-link-stop.ts b/tests/helpers/client-link-stop.ts new file mode 100644 index 00000000000..28836370fb2 --- /dev/null +++ b/tests/helpers/client-link-stop.ts @@ -0,0 +1,95 @@ +import { expect } from "bun:test"; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { dirname, join } from "node:path"; +import { fixturePath, repoPath } from "./repo-root"; +import { removeTreeWithRetry } from "./remove-tree"; + +export async function runStop(options: Record) { + const root = mkdtempSync(join(tmpdir(), "ocx-link-stop-")); + const home = join(root, "ocx"); + const env = { ...process.env, HOME: root, USERPROFILE: root, OPENCODEX_HOME: home, + CODEX_HOME: join(root, "codex"), OPENCODEX_CLAUDE_DESKTOP_CONFIG_DIR: join(root, "desktop"), OCX_SERVICE: "", OCX_SERVICE_MANAGED: "0" }; + let owner: Bun.Subprocess<"pipe", "pipe", "ignore"> | undefined; + let child: Bun.Subprocess | undefined; + const timeout = setTimeout(() => { + if (child?.exitCode === null) child.kill("SIGKILL"); + if (owner?.exitCode === null) owner.kill("SIGKILL"); + }, 15_000); + try { + const receiptState = options.receiptState; + if (options.preserve === "receipt" && typeof receiptState === "string" && receiptState.startsWith("parent")) { + // Own the inert stop process here so a killed runtime cannot orphan it. EOF + // also releases it if the test process itself is killed by the batch watchdog. + const path = join(home, process.platform === "linux" || receiptState === "parent-spaced" + ? "fixture owner" : "fixture-owner", "src", "cli", "index.ts"); + mkdirSync(dirname(path), { recursive: true }); + writeFileSync(path, 'console.log("ready"); await Bun.stdin.text();'); + const verb = receiptState === "parent-start" ? "start" : receiptState === "parent-status" ? "status" : "stop"; + owner = Bun.spawn([process.execPath, path, `--ocx-internal-launch-proof=${"a".repeat(43)}`, verb, "--json"], + { env, stdin: "pipe", stdout: "pipe", stderr: "ignore" }); + const reader = owner.stdout.getReader(); + try { + const ready = await reader.read(); + if (ready.done) throw new Error("fixture owner did not start"); + } finally { + reader.releaseLock(); + } + } + child = Bun.spawn([process.execPath, fixturePath("client-link-stop-runner.ts")], { + cwd: repoPath(), stdin: new Blob([JSON.stringify({ ...options, receiptOwnerPid: owner?.pid })]), + stdout: "pipe", stderr: "pipe", env, + }); + if (options.osSignal) { + const deadline = Date.now() + 10_000; + while (!existsSync(join(home, "ready")) && child.exitCode === null && Date.now() < deadline) await Bun.sleep(10); + if (!existsSync(join(home, "ready"))) throw new Error("fixture did not publish its signal-ready listener"); + child.kill("SIGTERM"); + } + const [exit, stdout, stderr] = await Promise.all([child.exited, new Response(child.stdout).text(), new Response(child.stderr).text()]); + if (options.expectedUnsupportedStop) { + expect(exit, stdout).toBe(1); + expect(stderr).toContain("Connected-client stop refused"); + expect(stderr).toContain("update/restart"); + if (options.expectLegacyRecovery) { + expect(stderr).toMatch(/close.*clients.*old.*ocx stop.*current.*ocx stop.*ocx start.*ocx sync --restart-codex/is); + } + } else if (options.expectedUnownedFileRecovery) { + expect(exit, stdout).toBe(0); + expect(stderr).toContain("Link Child file routing restore failed"); + } else if (options.receiptWriteFails) { + expect(exit, stdout).toBe(1); + expect(stderr).toContain("fixture receipt write denied"); + } else if (options.mode === "offline-stop") { + expect(exit, stderr).toBe(0); + expect(JSON.parse(stdout)).toMatchObject({ runtimeDown: true, sharedTeardown: "restored" }); + } else if (options.expectedNativePreflightRefusal) { + expect(exit, stdout).toBe(1); + expect(stderr).toContain("Link Child native teardown preflight refused"); + expect(stderr).toContain("No process was stopped"); + } else if (options.expectedFileRefusal || options.repairFileRefusal) { + expect(exit, stdout).toBe(options.mode === "file-stop" ? 1 : 0); + expect(stderr).toContain("Link Child file routing restore refused"); + expect(stderr).toContain("retry ocx stop"); + } else if (options.expectedFailure || options.expectedRefusal) { + expect(exit, stdout).toBe(options.expectedFailure ? 1 : 0); + expect(stderr).toContain("Link Child Codex routing restore refused"); + } else if (String(options.preserve).startsWith("restart-rollback")) { + expect(exit, stdout).toBe(0); + expect(stderr.trim()).toBe("[client] restart: the replacement did not start (not_ready); this runtime keeps serving"); + } else expect({ exit, stderr }, stdout).toEqual({ exit: 0, stderr: "" }); + const report = JSON.parse(readFileSync(join(home, "result.json"), "utf8")); + const atExit = JSON.parse(readFileSync(join(home, "exit.json"), "utf8")); + expect(atExit.codexDiscovery).toBe(false); + for (const field of ["after", "profileAfter", "journalRetained", "journalHomeBound", "catalogAfter", "grokAfter", "protectedUnchanged", "fileAfter", "codexDiscovery"]) { + expect(atExit[field], `no late restoration after listener release: ${field}`).toEqual(report[field]); + } + return { ...report, fileLateResult: atExit.fileLateResult }; + } finally { + clearTimeout(timeout); + if (child?.exitCode === null) child.kill("SIGKILL"); + if (owner?.exitCode === null) owner.kill("SIGKILL"); + await Promise.all([child?.exited, owner?.exited]); + removeTreeWithRetry(root); + } +} diff --git a/tests/providers/xai/grok-lifecycle.test.ts b/tests/providers/xai/grok-lifecycle.test.ts index bb4183e499a..b84f13c8def 100644 --- a/tests/providers/xai/grok-lifecycle.test.ts +++ b/tests/providers/xai/grok-lifecycle.test.ts @@ -162,7 +162,7 @@ describe("Grok fence lifecycle wiring", () => { // A proxy ownership refusal means a foreign service still owns the running proxy, so the // shared teardown must be skipped at both call sites, exactly like the service-manager path. - const ownershipRefusals = stopFn.match(/err instanceof ProxyOwnershipRefusedError[\s\S]{0,200}?ownershipBlocked = true;/g); + const ownershipRefusals = stopFn.match(/if \(err instanceof ProxyOwnershipRefusedError\) {\s+ownershipBlocked = true;/g); expect(ownershipRefusals).toHaveLength(2); expect(stopFn.match(/Skipping shared teardown \(native Codex restore, Grok config\): the refusing proxy is still running\./g)).toHaveLength(2); expect(PROCESS_CONTROL_SOURCE).toContain("throw new ProxyOwnershipRefusedError("); @@ -239,20 +239,15 @@ describe("Grok fence lifecycle wiring", () => { // The deferral is an obligation, so it is claimed on disk BEFORE it is requested and // released only after THIS process has restored the shared config itself. A bare // query flag could not survive the parent dying mid-stop. - const claimAt = stopFn.indexOf("claimTeardown(exact ?? configuredEndpoint()"); + const claimAt = stopFn.indexOf('claimTeardown(exact ?? configuredStopEndpoint(), exact ? "exact" : "guessed");'); expect(claimAt).toBeGreaterThan(-1); expect(claimAt).toBeLessThan(stopFn.indexOf("deferSharedTeardownNonce: teardownNonce")); - // One resolved stop target feeds BOTH the receipt and the request, so the endpoint - // recorded is the endpoint contacted — recovery probes exactly that one. - // The endpoint is resolved ONCE: reading the runtime record twice let the receipt name - // the configured guess while the request went to one that appeared in between. - expect(stopFn).toContain("const exact = discovered ?? endpointOf(readRuntimePort(pid));"); - // Every stop claims a receipt, including the one that resolves no endpoint at all — - // that path goes straight to the kill ladder with no child teardown, so a warning - // instead of a receipt is exactly the parent-crash window this exists to close. - expect(stopFn).toContain('claimTeardown(exact ?? configuredEndpoint(), exact ? "exact" : "guessed");'); - // A guessed endpoint records an obligation but must not direct the stop request. - expect(stopFn).toContain("runtimeEndpoint: exact ?? undefined"); + // Connected stops pin the attested endpoint. Standalone stops resolve the endpoint + // once as well, and a guessed receipt never directs the POST. + const stopWithDeferral = sliceFn(stopFn, "const stopWithDeferral = ", "const approvedEndpoint"); + expect(stopWithDeferral).toContain("const exact = connectedStop ? endpointOf(stopTarget?.target ?? null) : discovered ?? endpointOf(readRuntimePort(pid));"); + expect(stopWithDeferral).toContain("if (connectedStop && !exact) throw unsupportedConnectedStop();"); + expect(stopWithDeferral).toContain("runtimeEndpoint: exact ?? undefined"); // Nor may it authorize a later recovery: "the configured port refuses" is not proof // that a proxy on an explicit --port is down. expect(stopFn).toContain('if (read.receipt.endpointSource === "guessed")'); @@ -315,16 +310,19 @@ describe("Grok fence lifecycle wiring", () => { // proxy clears only its own and older obligations accumulate forever. expect(stopFn).toContain("if (inheritedTeardowns.length > 0 && !ownershipBlocked)"); expect(stopFn).toContain("teardownNonce ? [teardownNonce, ...recoveredNonces] : recoveredNonces"); - // The orphan path hands over the endpoint the probe already found; its runtime record - // is typically what went missing in the first place. - expect(stopFn).toContain('nativeRestoreHandledByProxy = await stopWithDeferral(\n live.pid,\n { hostname: live.hostname ?? "127.0.0.1", port: live.port },\n );'); + // Orphan discovery supplies an endpoint for standalone stop. Connected stop still + // verifies the PID against preflight and uses the attested endpoint. + expect(stopFn).toContain('nativeRestoreHandledByProxy = await stopWithDeferral(live.pid, { hostname: live.hostname ?? "127.0.0.1", port: live.port });'); + expect(sliceFn(stopFn, "const stopWithDeferral = ", "const approvedEndpoint")).toContain("verifyStopTarget(pid);"); + expect(stopFn).toContain("verifyStopTarget(pid);"); + expect(STOP_RESTORE_SOURCE).toContain("pid !== proof?.target.pid"); // A live proxy with no killable pid is not "no proxy found": purging state and // restoring over it is the same failure arrived at from the other direction. expect(stopFn).toContain("} else if (live) {"); const noPidBranch = stopFn.slice(stopFn.indexOf("} else if (live) {"), stopFn.indexOf('} else if (!stoppedService) {')); expect(noPidBranch).toContain("stopFailed = true;"); expect(noPidBranch).toContain("ownershipBlocked = true;"); - const gateFn = sliceFn(CLI_SOURCE, "const abandonedTeardownIsSafeToFinish", "let stopFailed = false;"); + const gateFn = sliceFn(STOP_RESTORE_SOURCE, "export async function abandonedTeardownIsSafeToFinish(", "export async function assertConnectedClientStopSupported("); expect(gateFn).toContain('probeEndpointLiveness(endpoint) === "dead"'); expect(gateFn).toContain("return false;"); }); diff --git a/tests/service/connected-stop-capability-auth.test.ts b/tests/service/connected-stop-capability-auth.test.ts index c8cf2836970..95a66509625 100644 --- a/tests/service/connected-stop-capability-auth.test.ts +++ b/tests/service/connected-stop-capability-auth.test.ts @@ -2,10 +2,11 @@ import { afterEach, beforeEach, describe, expect, test } from "bun:test"; import { mkdtempSync, readFileSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import { assertConnectedClientStopSupported } from "../../src/cli/stop-restore"; +import { assertConnectedClientStopSupported, classifyStopRole } from "../../src/cli/stop-restore"; import { startMachineListener } from "../../src/client/machine-listener"; import { saveConfig } from "../../src/config"; -import { writeRuntimePort } from "../../src/config/process-state"; +import { isValidRuntimePortState, readRuntimePort, writeRuntimePort } from "../../src/config/process-state"; +import { clientSyncRuntimeGuard, finishClientRuntimeStop, markClientRuntimeStopping } from "../../src/client/sync-runtime"; import { createLocalAttestationChallenge, createLocalAttestationProof, @@ -64,9 +65,37 @@ afterEach(async () => { removeTreeWithRetry(home); }); +test("finishing an exact parent stop keeps sync fenced and never changes a different runtime", () => { + const identity = { pid: process.pid, port: 17001, attestationSecret: SECRET }; + const owner = { pid: process.pid + 1, nonce: "a".repeat(32), startTime: "darwin:1:0" }; + writeRuntimePort({ ...identity, clientStopping: true, clientStopRequested: true, clientStopOwner: owner }); + const active = readRuntimePort(process.pid); + for (const foreign of [{ ...identity, pid: process.pid + 1 }, { ...identity, port: 17002 }, { ...identity, attestationSecret: "B".repeat(43) }]) { + finishClientRuntimeStop(foreign, owner); + expect(readRuntimePort(process.pid)).toEqual(active); + } + finishClientRuntimeStop(identity, { ...owner, nonce: "b".repeat(32) }); + expect(readRuntimePort(process.pid)).toEqual(active); + finishClientRuntimeStop(identity, owner); + expect(readRuntimePort(process.pid)).toMatchObject({ ...identity, clientStopping: true, clientStopRequested: false }); + expect(() => clientSyncRuntimeGuard()).toThrow("client_runtime_stopping"); + const finished = readRuntimePort(process.pid); + finishClientRuntimeStop(identity, owner); + expect(readRuntimePort(process.pid)).toEqual(finished); + markClientRuntimeStopping(identity, owner); + expect(readRuntimePort(process.pid)?.clientStopRequested).toBe(true); +}); + +test.each([true, false])("both parent stop states require a stopping sync fence (%s)", clientStopRequested => { + const identity = { pid: process.pid, port: 17001, attestationSecret: SECRET, clientStopRequested }; + expect(isValidRuntimePortState(identity)).toBe(false); + expect(isValidRuntimePortState({ ...identity, clientStopping: true })).toBe(true); +}); + type FixtureOptions = { health?: "proxy" | "client" | "foreign"; healthProof?: boolean; + linkStopFence?: boolean; readProof?: boolean; missingRecord?: boolean; record?: Record; @@ -96,7 +125,7 @@ function listener(options: FixtureOptions = {}) { return options.health === "foreign" ? Response.json({ service: "other" }, { status: 404 }) : Response.json({ service: "opencodex", pid: process.pid, - ...(options.health === "client" ? { role: "client" } : {}) }, { headers }); + ...(options.health === "client" ? { role: "client" } : {}), ...(options.linkStopFence ? { linkStopFence: true } : {}) }, { headers }); } const error = requireManagementAuth(req, auth, undefined, record()); if (error) return error; @@ -107,6 +136,19 @@ function listener(options: FixtureOptions = {}) { } describe("connected stop preflight runtime authority", () => { + test.each([true, false])("a fence-only health response is client evidence only with attestation (%s)", async healthProof => { + listener({ healthProof, linkStopFence: true }); + const runtime = readRuntimePort(process.pid); + expect(await classifyStopRole({ kind: "disconnected" }, runtime, [])).toBe(healthProof ? "connected" : "unknown"); + }); + + test("a legacy client role triggers preflight even without a runtime record", async () => { + const { target } = listener({ health: "client", missingRecord: true }); + saveConfig({ ...serverAuthConfig(), port: target.port, hostname: target.hostname }); + expect(await classifyStopRole({ kind: "disconnected" }, null, [])).toBe("connected"); + await expect(assertConnectedClientStopSupported(target)).rejects.toThrow("Connected-client stop refused"); + }); + test("a foreign health response never receives a reusable administrator credential", async () => { const fixture = listener({ health: "foreign" }); let refused = false; @@ -129,6 +171,21 @@ describe("connected stop preflight runtime authority", () => { expect(fixture.requests[0]!.headers.has("x-opencodex-api-key")).toBe(false); }); + test("Link preflight refuses an attested older native runtime without the explicit-stop fence capability", async () => { + const fixture = listener({ health: "client", healthProof: true }); + const before = readFileSync(join(home, "runtime-port.json"), "utf8"); + await expect(assertConnectedClientStopSupported(fixture.target, { requireLinkStopFence: true })).rejects.toThrow("Connected-client stop refused"); + expect(fixture.requests.map(req => req.path)).toEqual(["/healthz"]); + expect(readFileSync(join(home, "runtime-port.json"), "utf8")).toBe(before); + }); + + test("Link preflight accepts the explicit-stop fence capability only on the attested runtime", async () => { + const fixture = listener({ health: "client", healthProof: true, linkStopFence: true }); + await assertConnectedClientStopSupported(fixture.target, { requireLinkStopFence: true }); + expect(fixture.requests.map(req => req.path)).toEqual(["/healthz"]); + expect(fixture.requests[0]!.headers.has("x-opencodex-api-key")).toBe(false); + }); + test("an ordinary proxy proves its bound read without receiving the admin token", async () => { const fixture = listener({ healthProof: true, readProof: true }); await assertConnectedClientStopSupported(fixture.target); diff --git a/tests/service/stop-deferred-teardown.test.ts b/tests/service/stop-deferred-teardown.test.ts index 473f2c95ab8..07fef4d3e97 100644 --- a/tests/service/stop-deferred-teardown.test.ts +++ b/tests/service/stop-deferred-teardown.test.ts @@ -1,9 +1,9 @@ import { afterEach, beforeEach, describe, expect, test } from "bun:test"; import { spawnSync } from "node:child_process"; -import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs"; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import { stopProxyGracefully } from "../../src/lib/process-control"; +import { killProxy, stopProxyGracefully } from "../../src/lib/process-control"; import { performStopTeardown } from "../../src/server/stop-teardown"; import { markSiblingStart, resetSiblingStartForTests } from "../../src/codex/sibling-start"; import type { CodexNativeRestoreResult } from "../../src/codex/inject"; @@ -12,6 +12,7 @@ import { removeTreeWithRetry } from "../helpers/remove-tree"; import { fixturePath, repoPath } from "../helpers/repo-root"; import { createLocalAttestationProof, LOCAL_ATTESTATION_CHALLENGE_HEADER, LOCAL_ATTESTATION_PROOF_HEADER } from "../../src/lib/local-management-attestation"; import { LOCAL_MANAGEMENT_NONCE_HEADER } from "../../src/lib/local-management-capability"; +import { serviceApiTokenFingerprint } from "../../src/lib/service-secrets"; /** * Behavioural cover for the deferred shared teardown (#3008). @@ -52,29 +53,34 @@ function restoreResult(success: boolean): CodexNativeRestoreResult { } as unknown as CodexNativeRestoreResult; } -function connectClient(transport: "hub" | "link") { +function connectClient(transport: "hub" | "link", port?: number) { + const token = `ocx_data_${"c".repeat(40)}`; + writeFileSync(join(home, "service-api-token"), token); const serverUrl = transport === "link" ? "http://127.0.0.1:10200" : "https://hub.example.test"; - writeFileSync(join(home, "config.json"), JSON.stringify({ runtimeRole: "client", providers: {}, defaultProvider: "openai", client: { + writeFileSync(join(home, "config.json"), JSON.stringify({ port, runtimeRole: "client", providers: {}, defaultProvider: "openai", client: { serverUrl, managementUrl: serverUrl, managementTransport: "direct", transport, ...(transport === "link" ? { link: { tunnelPort: 10200, linkId: "lnk_0123456789abcdef" } } : {}), selectedClients: ["codex"], tokenEnv: "OPENCODEX_API_AUTH_TOKEN", apiKeyId: "fixture-client", - tokenFingerprint: "a".repeat(64), protocolVersion: 1, connectedAt: "2026-10-01T00:00:00.000Z", + tokenFingerprint: serviceApiTokenFingerprint(token), protocolVersion: 1, connectedAt: "2026-10-01T00:00:00.000Z", } })); } async function runParentStop(options: { receipt: boolean; response: unknown; restore: CodexNativeRestoreResult; status?: number; clientTransport?: "hub" | "link"; + siblingRecord?: "standalone" | "link"; serverTeardown?: boolean; json?: boolean; clientServer?: "legacy" | "unknown" | "wrong-pid" | "malformed" | "oversized" | "unauthorized" | "redirect" | "body-timeout"; - managerCascades?: boolean; guarded?: boolean; orphan?: boolean; exitCleanup?: boolean; + managerCascades?: boolean; managerBound?: boolean; discoveryMiss?: boolean; guarded?: boolean; orphan?: boolean; exitCleanup?: boolean; + standaloneRecord?: "legacy" | "current" | "stale" | "wrong-home" | "wrong-port" | "client-role"; nativeSignal?: boolean; apiFailure?: boolean; stopBodyFailure?: boolean; alreadyStopped?: boolean; absence?: "dead" | "unknown" | "live"; managerState?: "inactive" | "active" | "unknown"; + configuredPort?: number; staleRuntimeRecord?: boolean; noRuntimeRecord?: boolean; deadPidReadsNull?: boolean; disconnectDuringProbe?: boolean; connectDuringDiscovery?: boolean; connectDuringPost?: boolean; lifecycleBusy?: boolean; connectAfterBoundary?: boolean; pendingAfterBoundary?: boolean; connectDuringRestore?: boolean; connectAfterExitInspection?: boolean; pendingAfterExitInspection?: boolean; pendingAfterGrok?: boolean; receiptClearBusy?: boolean; windowsStopWiring?: boolean; }) { - if (options.clientTransport) connectClient(options.clientTransport); + if (options.clientTransport) connectClient(options.clientTransport, options.configuredPort); const child = spawnSync(process.execPath, [fixturePath("parent-stop-runner.ts")], { cwd: repoPath(), env: { ...process.env, OPENCODEX_HOME: home }, @@ -88,22 +94,21 @@ async function runParentStop(options: { const reportPath = join(home, "parent-stop-result.json"); expect(existsSync(reportPath), child.stderr).toBe(true); const report = JSON.parse(readFileSync(reportPath, "utf8")) as { - calls: { killed: number; native: number; grok: number; cleared: number; exited: number; service: number }; - probes: string[]; + calls: { killed: number; native: number; grok: number; cleared: number; exited: number; service: number; systemEnv: number }; + probes: string[]; absenceProbes: number[]; signals: string[]; urls: string[]; transports: string[]; nonce?: string; receiptExists: boolean; unexpectedIo: string[]; }; expect(report.unexpectedIo, child.stderr).toEqual([]); - // The Windows checked stop needs its receipt before it sends anything. - const refusedWithoutReceipt = options.windowsStopWiring === true && !options.receipt; - expect(report.urls, child.stderr).toHaveLength(options.clientServer || options.exitCleanup || options.alreadyStopped || refusedWithoutReceipt ? 0 : 1); + const refusedWithoutReceipt = !options.receipt && (options.windowsStopWiring === true || options.clientTransport === "link"); + const changedBeforeLinkFence = options.clientTransport === "link" && options.connectDuringDiscovery; + const stoppedByManager = options.managerCascades && options.deadPidReadsNull; + if (!options.standaloneRecord && !options.siblingRecord) expect(report.urls, child.stderr).toHaveLength(options.clientServer || options.exitCleanup || options.alreadyStopped || options.noRuntimeRecord || stoppedByManager || refusedWithoutReceipt || changedBeforeLinkFence ? 0 : 1); return { ...report, exitCode: child.status, stderr: child.stderr, stdout: child.stdout }; } /** - * Off Windows a stop whose teardown receipt cannot be claimed still runs, and the cases using this assert that - * contract. On Windows the checked stop (#8573) needs the receipt first (windowsStopRequiresReceipt in - * src/cli/index.ts) and refuses before any POST, so those cases run off Windows; "the Windows checked stop - * refuses ..." below asserts that refusal for the same scenarios on every host. + * An ordinary POSIX stop can proceed without a receipt. Live Link stops and checked Windows + * stops require it. The checked Windows refusal is also exercised on other hosts. */ const posixReceiptTest = test.skipIf(process.platform === "win32"); @@ -148,6 +153,149 @@ describe("API stop through process exit cleanup", () => { }); describe("parent CLI shared teardown completion", () => { + test.each([ + ["match", true], ["foreign-sid", false], ["wrong-argv", false], ["wrong-pid", false], + // CIM has no process environment. A matching SID and start argv still need the recorded port. + ["wrong-port", false], + ["wrong-bind", false], ["client-role", false], ["serving-generation", false], + ] as const)("legacy Windows foreground evidence (%s)", (legacyWindowsEvidence, proved) => { + const child = spawnSync(process.execPath, [fixturePath("parent-stop-runner.ts")], { + cwd: repoPath(), env: { ...process.env, OPENCODEX_HOME: home }, + input: JSON.stringify({ legacyWindowsEvidence }), encoding: "utf8", timeout: 10_000, + }); + expect(child.error, child.stderr).toBeUndefined(); + expect(child.status, child.stderr).toBe(0); + expect(JSON.parse(child.stdout)).toEqual({ proved }); + }); + + for (const homeEvidence of ["absolute", "relative-match", "relative-mismatch", "relative-alias", "retargeted-alias"] as const) test.skipIf( + !["linux", "darwin", "win32"].includes(process.platform) || (process.platform === "win32" && homeEvidence !== "absolute"), + )( + `legacy standalone proof checks a live foreground process and its recorded listener scope (${homeEvidence})`, + async () => { + const { proveStandaloneStopRecord } = await import("../../src/cli/stop-restore"); + const hostname = process.platform === "win32" ? "127.0.0.1" : "0.0.0.0"; + const configHome = realpathSync(home); + const usesAlias = homeEvidence === "relative-alias" || homeEvidence === "retargeted-alias"; + const alias = join(configHome, "alias"); + const otherHome = join(configHome, "other"); + if (usesAlias) symlinkSync(configHome, alias); + process.env.OPENCODEX_HOME = usesAlias ? alias : configHome; + const cwd = homeEvidence === "relative-mismatch" ? otherHome : process.env.OPENCODEX_HOME; + mkdirSync(cwd, { recursive: true }); + const scriptDir = join(home, "src", "cli"); + mkdirSync(scriptDir, { recursive: true }); + const script = join(scriptDir, "index.ts"); + writeFileSync(script, ` + const listener = Bun.listen({ hostname: ${JSON.stringify(hostname)}, port: 0, socket: { data() {} } }); + console.log(listener.port); + `); + const targetHome = homeEvidence === "absolute" ? configHome : homeEvidence === "retargeted-alias" ? alias : "."; + const proxy = Bun.spawn([process.execPath, script, "start"], { + cwd, + env: { ...process.env, OPENCODEX_HOME: targetHome }, + stdout: "pipe", stderr: "inherit", signal: AbortSignal.timeout(15_000), + }); + try { + const { value } = await proxy.stdout.getReader().read(); + const port = Number(new TextDecoder().decode(value).trim()); + expect(port).toBeGreaterThan(0); + const record = { pid: proxy.pid, port, hostname }; + writeFileSync(join(configHome, "runtime-port.json"), JSON.stringify(record)); + const proof = await proveStandaloneStopRecord(record, proxy.pid, []); + if (homeEvidence === "relative-mismatch") { + expect(proof).toBeUndefined(); + return; + } + if (!proof) throw new Error("Expected a standalone stop proof for the same home directory"); + expect(proof).not.toThrow(); + if (homeEvidence === "retargeted-alias") { + mkdirSync(otherHome); + writeFileSync(join(otherHome, "runtime-port.json"), JSON.stringify(record)); + const replacement = join(configHome, "replacement-alias"); + symlinkSync(otherHome, replacement); + renameSync(replacement, alias); + let signalAuthorized = false; + expect(() => killProxy(proxy.pid, () => { + proof(); + signalAuthorized = true; + return true; + })).toThrow("could not verify"); + expect(signalAuthorized).toBe(false); + expect(proxy.exitCode).toBeNull(); + return; + } + const wrongBind = hostname === "0.0.0.0" ? "127.0.0.1" : "0.0.0.0"; + expect(await proveStandaloneStopRecord({ ...record, hostname: wrongBind }, proxy.pid, [])).toBeUndefined(); + } finally { + proxy.kill(); + await proxy.exited; + } + }, 17_000, + ); + + test("an already-down standalone stop restores even when the user manager is unreadable", async () => { + const outcome = await runParentStop({ receipt: true, alreadyStopped: true, managerState: "unknown", + json: true, response: null, restore: restoreResult(true) }); + expect(outcome.exitCode, outcome.stderr).toBe(0); + expect(outcome.calls).toMatchObject({ service: 1, killed: 0, native: 1, grok: 1 }); + expect(JSON.parse(outcome.stdout)).toMatchObject({ runtimeDown: true, sharedTeardown: "restored" }); + }); + + test("a standalone service can stop through its manager without a runtime record", async () => { + const outcome = await runParentStop({ receipt: true, managerBound: true, managerCascades: true, + discoveryMiss: true, deadPidReadsNull: true, noRuntimeRecord: true, + json: true, response: null, restore: restoreResult(true) }); + expect(outcome.exitCode, outcome.stderr).toBe(0); + expect(outcome.calls).toMatchObject({ service: 1, killed: 0, native: 1, grok: 1 }); + expect(JSON.parse(outcome.stdout)).toMatchObject({ runtimeDown: true, service: "stopped", sharedTeardown: "restored" }); + }); + + test.each([ + ["legacy", ["wrong-home", "wrong-port"]], + ["current", ["stale", "client-role"]], + ] as const)("only a matching %s standalone record permits the ordinary stop after a discovery miss", async (standaloneRecord, mismatches) => { + const outcome = await runParentStop({ receipt: true, standaloneRecord, discoveryMiss: true, deadPidReadsNull: true, + json: true, response: { success: true }, restore: restoreResult(true) }); + expect(outcome.exitCode, outcome.stderr).toBe(0); + expect(outcome.calls).toMatchObject({ service: 1, native: 1, grok: 1 }); + expect(outcome.urls).toHaveLength(1); + expect(outcome.signals).toEqual(standaloneRecord === "legacy" ? [] : [process.platform === "win32" ? "taskkill /F" : "SIGTERM"]); + expect(JSON.parse(outcome.stdout)).toMatchObject({ runtimeDown: true, proxy: "stopped", sharedTeardown: "restored" }); + for (const mismatch of mismatches) { + if (mismatch === "wrong-home" && process.platform === "win32") continue; + const refusal = await runParentStop({ receipt: true, standaloneRecord: mismatch, discoveryMiss: true, managerCascades: true, + json: true, response: null, restore: restoreResult(true) }); + expect(refusal.exitCode, `${mismatch}: ${refusal.stderr}`).toBe(1); + expect(refusal.calls).toMatchObject({ service: 0, killed: 0, native: 0, grok: 0 }); + expect(refusal.urls).toEqual([]); + expect(JSON.parse(refusal.stdout)).toMatchObject({ runtimeDown: false, proxy: "ownership-refused", sharedTeardown: "skipped" }); + } + }); + + test.each([false, true])("a discovery miss refuses to stop an unclassified live ocx start PID (cascading manager=%s)", async managerCascades => { + const outcome = await runParentStop({ receipt: true, noRuntimeRecord: true, discoveryMiss: true, managerCascades, + deadPidReadsNull: true, json: true, response: null, restore: restoreResult(true) }); + expect({ managerStops: outcome.calls.service, signals: outcome.signals }).toEqual({ managerStops: 0, signals: [] }); + expect(outcome.calls).toMatchObject({ native: 0, grok: 0 }); + expect(outcome.nonce).toBeUndefined(); + expect(outcome.exitCode, outcome.stderr).toBe(1); + expect(JSON.parse(outcome.stdout)).toMatchObject({ runtimeDown: false, proxy: "ownership-refused", sharedTeardown: "skipped" }); + expect(outcome.stderr).toContain("could not verify that live OpenCodex PID 4242 is standalone"); + expect(outcome.stderr).toContain("ocx service status"); + }); + + for (const staleRuntimeRecord of [true, false]) { + test(`an ephemeral-port Link stop requires a concrete recorded endpoint (record=${staleRuntimeRecord})`, async () => { + const outcome = await runParentStop({ receipt: true, clientTransport: "link", alreadyStopped: true, + configuredPort: 0, staleRuntimeRecord, json: true, response: null, restore: restoreResult(true) }); + expect(outcome.exitCode, outcome.stderr).toBe(staleRuntimeRecord ? 0 : 1); + expect(JSON.parse(outcome.stdout)).toMatchObject({ ok: staleRuntimeRecord, runtimeDown: staleRuntimeRecord }); + expect(outcome.calls).toMatchObject({ service: 0, killed: 0 }); + expect(outcome.absenceProbes).toEqual(staleRuntimeRecord ? [ENDPOINT.port] : []); + expect(existsSync(join(home, "runtime-port.json"))).toBe(false); + }); + } test("consecutive connected stops preserve configuration and the stopped managed client remains update-eligible", async () => { const first = await runParentStop({ receipt: true, clientTransport: "hub", serverTeardown: true, json: true, response: null, restore: restoreResult(true) }); @@ -324,16 +472,22 @@ describe("parent CLI shared teardown completion", () => { expect(outcome.exitCode, outcome.stderr).toBe(0); }); - posixReceiptTest("a Link Child not-owned answer without a receipt still gets the parent's restoration", async () => { - // An old build answers not-owned for ANY connected client before it ever checks the - // deferral query, and this stop has no receipt to send. That answer preserves the - // link route instead of tearing it down, so it cannot confirm the parent's teardown: - // the parent owns the restoration itself, exactly as for an unconfirmed stop. + test("a Link Child stop with an unwritable receipt never reaches the manager or POST", async () => { const outcome = await runParentStop({ receipt: false, clientTransport: "link", json: true, response: { success: true, sharedTeardown: "not-owned" }, restore: restoreResult(true) }); - expect(outcome.urls).toEqual(["http://127.0.0.1:10100/api/stop"]); + expect(outcome.urls).toEqual([]); expect(outcome.nonce).toBeUndefined(); - expect(outcome.calls).toMatchObject({ killed: 0, exited: 1, native: 1, grok: 1, cleared: 0 }); + expect(outcome.calls).toMatchObject({ service: 0, killed: 0, exited: 0, native: 0, grok: 0, cleared: 0 }); + expect(JSON.parse(outcome.stdout)).toMatchObject({ ok: false, runtimeDown: false, sharedTeardown: "skipped" }); + expect(outcome.stderr).toContain("receipt storage unavailable"); + expect(outcome.exitCode).toBe(1); + }); + + test("a receipt-backed Link stop still restores after an unconfirmed not-owned response", async () => { + const outcome = await runParentStop({ receipt: true, clientTransport: "link", json: true, + response: { success: true, sharedTeardown: "not-owned" }, restore: restoreResult(true) }); + expect(outcome.urls).toEqual([`http://127.0.0.1:10100/api/stop?deferSharedTeardown=1&teardownNonce=${outcome.nonce}`]); + expect(outcome.calls).toMatchObject({ killed: 0, exited: 1, native: 1, grok: 1, cleared: 1 }); expect(JSON.parse(outcome.stdout)).toMatchObject({ ok: true, runtimeDown: true, sharedTeardown: "restored" }); expect(outcome.exitCode, outcome.stderr).toBe(0); }); @@ -352,18 +506,22 @@ describe("parent CLI shared teardown completion", () => { for (const [label, transition] of [["during orphan discovery", { orphan: true, connectDuringDiscovery: true }], ["while the POST is in flight", { connectDuringPost: true }]] as const) { for (const receipt of [true, false]) { - (receipt ? test : posixReceiptTest)(`a Link stop never restores over a hub connected ${label} (receipt ${receipt ? "claimed" : "unavailable"})`, async () => { + test(`a Link stop never restores over a hub connected ${label} (receipt ${receipt ? "claimed" : "unavailable"})`, async () => { // #7736 r5: the late not-owned refusal must not let the parent restore over the hub that // now owns routing. Only the ownership read at the restore boundary decides. const outcome = await runParentStop({ receipt, clientTransport: "link", serverTeardown: true, json: true, response: null, restore: restoreResult(true), ...transition }); - expect(outcome.calls, outcome.stderr).toMatchObject({ killed: 0, native: 0, grok: 0, cleared: receipt ? 1 : 0 }); + if ("connectDuringDiscovery" in transition || !receipt) { + expect(outcome.calls).toMatchObject({ service: 0, killed: 0, native: 0, grok: 0, cleared: 0 }); + expect(outcome.nonce).toBeUndefined(); + expect(JSON.parse(outcome.stdout)).toMatchObject({ ok: false, runtimeDown: false, sharedTeardown: "skipped" }); + expect(outcome.exitCode).toBe(1); + return; + } + expect(outcome.calls, outcome.stderr).toMatchObject({ killed: 0, native: 0, grok: 0, cleared: 1 }); expect(outcome.receiptExists).toBe(false); - // Seen before the POST without a nonce, the hub's not-owned answer already confirms the stop. - const settledAtPost = "connectDuringDiscovery" in transition && !receipt; - expect(JSON.parse(outcome.stdout)).toMatchObject({ ok: true, runtimeDown: true, - sharedTeardown: settledAtPost ? "performed-by-proxy" : "skipped" }); - if (!settledAtPost) expect(outcome.stdout + outcome.stderr).toContain("A hub connection was committed while this stop ran"); + expect(JSON.parse(outcome.stdout)).toMatchObject({ ok: true, runtimeDown: true, sharedTeardown: "skipped" }); + expect(outcome.stdout + outcome.stderr).toContain("A hub connection was committed while this stop ran"); expect(outcome.exitCode, outcome.stderr).toBe(0); }); } @@ -371,8 +529,8 @@ describe("parent CLI shared teardown completion", () => { for (const transition of ["connectAfterBoundary", "connectDuringRestore"] as const) { for (const receipt of [true, false]) { (receipt ? test : posixReceiptTest)(`R6 ${transition} preserves hub writes (receipt ${receipt})`, async () => { - const outcome = await runParentStop({ receipt, clientTransport: "link", json: true, - [transition]: true, response: { success: true, sharedTeardown: "not-owned" }, restore: restoreResult(true) }); + const outcome = await runParentStop({ receipt, ...(receipt ? { clientTransport: "link" } as const : {}), json: true, + [transition]: true, response: { success: false, sharedTeardown: "performed" }, restore: restoreResult(true) }); expect(outcome.calls, outcome.stderr).toMatchObject({ native: 0, grok: 0, cleared: receipt ? 1 : 0 }); expect(outcome.receiptExists).toBe(false); expect(JSON.parse(outcome.stdout)).toMatchObject({ ok: true, sharedTeardown: "skipped" }); @@ -503,9 +661,35 @@ describe("parent CLI shared teardown completion", () => { expect(outcome.exitCode).toBe(0); }); - // The scenarios the posixReceiptTest cases run without a receipt. Through the Windows checked stop each one is - // refused before the POST: nothing is signalled, restored or cleared, and the stop fails. + // Checked Windows stop refuses all of these receipt failures before POST, including + // cases an ordinary POSIX stop can still complete. const notOwned = { success: true, sharedTeardown: "not-owned" } as const; + test("a standalone sibling stop with a saved Link skips the manager and shared teardown", async () => { + const outcome = await runParentStop({ receipt: true, clientTransport: "link", siblingRecord: "standalone", json: true, + response: notOwned, restore: restoreResult(true) }); + expect(outcome.exitCode, outcome.stderr).toBe(0); + expect(outcome.urls).toEqual(["http://127.0.0.1:10100/api/stop"]); + expect(outcome.nonce).toBeUndefined(); + expect(outcome.calls).toMatchObject({ service: 0, killed: 0, native: 0, grok: 0, systemEnv: 0 }); + expect(JSON.parse(outcome.stdout)).toMatchObject({ runtimeDown: true, service: "absent", sharedTeardown: "skipped" }); + expect(existsSync(join(home, "runtime-port.json"))).toBe(false); + }); + + for (const conflict of ["Link", "guarded manager"] as const) { + test(`a sibling stop refuses conflicting ${conflict} ownership before mutation`, async () => { + const outcome = await runParentStop({ receipt: true, json: true, response: notOwned, restore: restoreResult(true), + ...(conflict === "Link" ? { clientTransport: "link", siblingRecord: "link" } : { siblingRecord: "standalone", guarded: true }) }); + expect(outcome.nonce).toBeUndefined(); + expect(outcome.urls).toEqual([]); + expect(outcome.calls).toMatchObject({ service: 0, killed: 0, native: 0, grok: 0, systemEnv: 0 }); + expect(outcome.exitCode, outcome.stderr).toBe(1); + expect(JSON.parse(outcome.stdout)).toMatchObject({ runtimeDown: false, sharedTeardown: "skipped" }); + const record = JSON.parse(readFileSync(join(home, "runtime-port.json"), "utf8")); + expect(record.siblingOfPort).toBe(10101); + expect(record.clientStopping).toBeUndefined(); + }); + } + for (const [name, scenario] of [ ["a Link Child not-owned answer", { clientTransport: "link", json: true, response: notOwned }], ["a connection committed during orphan discovery", { orphan: true, connectDuringDiscovery: true, serverTeardown: true, json: true, response: null }], @@ -520,7 +704,8 @@ describe("parent CLI shared teardown completion", () => { const outcome = await runParentStop({ ...scenario, receipt: false, windowsStopWiring: true, restore: restoreResult(true) }); expect(outcome.calls, outcome.stderr).toMatchObject({ killed: 0, native: 0, grok: 0, cleared: 0 }); expect(outcome.nonce).toBeUndefined(); - expect(outcome.stderr).toContain("receipt storage unavailable"); + expect(outcome.stderr).toContain("clientTransport" in scenario && scenario.clientTransport === "link" + && "connectDuringDiscovery" in scenario ? "runtime sync fence could not be verified" : "receipt storage unavailable"); expect(outcome.exitCode, outcome.stderr).toBe(1); }); } diff --git a/tests/update/update-teardown-handover.test.ts b/tests/update/update-teardown-handover.test.ts index a0216e46ac1..2db72c1e6a7 100644 --- a/tests/update/update-teardown-handover.test.ts +++ b/tests/update/update-teardown-handover.test.ts @@ -237,7 +237,7 @@ describe("ocx stop under an update handover", () => { tokenEnv: "OPENCODEX_API_AUTH_TOKEN", apiKeyId: "fixture-client", tokenFingerprint: "a".repeat(64), protocolVersion: 1, connectedAt: "2026-10-01T00:00:00.000Z", } })); - const run = runStop(true, { managerCascades: true, deadPidReadsNull: true }); + const run = runStop(true, { managerCascades: true, deadPidReadsNull: true, clientTransport: "link" }); expect(run.exitCode, run.stderr).toBe(0); expect(run.calls).toMatchObject({ native: 1, grok: 1, service: 1 }); expect(run.receiptExists).toBe(false); @@ -245,8 +245,8 @@ describe("ocx stop under an update handover", () => { expect(JSON.parse(run.stdout)).toMatchObject({ sharedTeardown: "restored", exitCode: 0 }); }); - test("without a runtime record the stop restores instead of handing over a guessed receipt", () => { - const run = runStop(true, { noRuntimeRecord: true, nativeSignal: true }); + test("a manager-bound standalone stop without a runtime record restores instead of handing over a guessed receipt", () => { + const run = runStop(true, { noRuntimeRecord: true, managerBound: true, nativeSignal: true }); expect(run.exitCode, run.stderr).toBe(0); expect(run.calls).toMatchObject({ native: 1, grok: 1 }); expect(receiptNames()).toEqual([]); diff --git a/tests/windows/windows-stop-owner-identity.test.ts b/tests/windows/windows-stop-owner-identity.test.ts new file mode 100644 index 00000000000..2fba73d0da6 --- /dev/null +++ b/tests/windows/windows-stop-owner-identity.test.ts @@ -0,0 +1,94 @@ +import { expect, test } from "bun:test"; +import { readSameUserWindowsStart } from "../../src/service/windows-process-native"; +import { isClientStopCommandLine, isLegacyWindowsStartCommandLine, readClientStopProcessStart } from "../../src/client/stop-teardown-owner"; + +const fileTime = 133_000_000_000_000_007n; +const ticks = 637_911_232_000_000_000n; +const sid = "S-1-5-21-100-200-300-1001"; + +function nativeRead(overrides: Partial[1]> = {}) { + const handles: Array = [], closed: Array = []; + const result = readSameUserWindowsStart(42, { + open: pid => { expect(pid).toBe(42); return 101n; }, + close: handle => { closed.push(handle); }, + fileTime: handle => { handles.push(handle); return fileTime; }, + exited: handle => { handles.push(handle); return false; }, + ownerSid: handle => { handles.push(handle); return sid; }, + currentSid: () => sid, + ...overrides, + }); + return { result, handles, closed }; +} + +test("Windows stop creation and same-user evidence use one live handle and preserve protocol precision", () => { + const result = nativeRead(); + expect(result.result).toBe(ticks); + expect(result.handles).toEqual([101n, 101n, 101n, 101n]); + expect(result.closed).toEqual([101n]); +}); + +test("Windows stop owner evidence fails closed and closes every opened handle", () => { + for (const overrides of [ + { fileTime: () => null }, + { exited: () => true }, + { exited: () => null }, + { ownerSid: () => "S-1-5-21-100-200-300-1002" }, + { ownerSid: () => "", currentSid: () => "" }, + { ownerSid: () => { throw new Error("access denied"); } }, + { currentSid: () => { throw new Error("token unreadable"); } }, + ]) { + const result = nativeRead(overrides); + expect(result.result).toBeNull(); + expect(result.closed).toEqual([101n]); + } + expect(nativeRead({ open: () => 0 }).closed).toEqual([]); + let reads = 0; + expect(nativeRead({ exited: () => ++reads === 1 ? false : true }).result).toBeNull(); +}); + +test("a reused PID gets a fresh handle and cannot inherit a prior creation proof", () => { + let opens = 0; + const io = { + open: () => ++opens, + close: () => {}, + fileTime: (handle: number | bigint) => fileTime + BigInt(handle) * 10n, + exited: () => false, + ownerSid: () => sid, + currentSid: () => sid, + }; + expect(readSameUserWindowsStart(42, io)).toBe(ticks + 10n); + expect(readSameUserWindowsStart(42, io)).toBe(ticks + 20n); + for (const pid of [0, -1, 1.5, 0x80000000]) expect(readSameUserWindowsStart(pid, io)).toBeNull(); + expect(opens).toBe(2); +}); + +test("Windows stop and legacy start recognize apostrophes without shell quoting", () => { + for (const command of [ + "C:\\Users\\O'Neil\\ocx.exe stop", + '"C:\\Users\\O\'Neil\\Program Files\\ocx.exe" stop --json', + 'bun.exe "C:\\Users\\O\'Neil\\app\\src\\cli\\index.ts" stop --deadline-ms 5000', + '"C:\\Program Files\\ocx.exe"\tstop\t--json', + ]) expect(isClientStopCommandLine(command), command).toBe(true); + expect(isLegacyWindowsStartCommandLine("C:\\Users\\O'Neil\\ocx.exe start")).toBe(true); + expect(isLegacyWindowsStartCommandLine('bun.exe "C:\\Users\\O\'Neil\\app\\src\\cli.ts" start')).toBe(true); + for (const command of [ + "'C:\\Program Files\\ocx.exe' stop", "ocx.exe 'stop'", 'ocx.exe "stop --json"', + 'ocx.exe "st\\"op"', 'ocx.exe "st""op"', 'ocx.exe stop\0 --json', "ocx.exe start stop", + ]) expect(isClientStopCommandLine(command), command).toBe(false); +}); + +test("Windows stop approval preserves quoted backslashes and embedded quote boundaries", () => { + const approved = 'ocx.exe stop --json --expect-pid 12 --expect-port 10100 --expect-hostname 127.0.0.1 ' + + '--expect-config-home "C:\\Users\\O\'Neil\\Home Folder\\\\" --expect-cli-version 1.0.0 ' + + '--expect-compatibility-token ' + "a".repeat(64); + expect(isClientStopCommandLine(approved)).toBe(true); + expect(isClientStopCommandLine(approved.replace('Home Folder\\\\"', 'Home Folder\\"'))).toBe(false); +}); + +test.skipIf(process.platform !== "win32" || process.arch !== "x64")("Windows repeated stop proofs stay in-process and within the fixture budget", () => { + const expected = readClientStopProcessStart(process.pid); + expect(expected).toMatch(/^win32:\d+$/); + const started = performance.now(); + for (let attempt = 0; attempt < 30; attempt++) expect(readClientStopProcessStart(process.pid)).toBe(expected); + expect(performance.now() - started).toBeLessThan(3000); +}); From 9914824e9a9b90280f532ee1a5eb7c5a61be78cb Mon Sep 17 00:00:00 2001 From: Epinephrine Date: Thu, 19 Nov 2026 13:31:49 +0900 Subject: [PATCH 2/9] ci: refresh measured test durations Apply the identical generated timing table from lidge-jun/opencodex#8940 (d190515a19cef9cc391d5a68e901d538bbe07f44). Completed primary-file samples update scheduling weights only; test coverage, five-shard execution, time limits, and workflow policy remain unchanged. --- scripts/ci/test-durations.tsv | 6351 +++++++++++++++++---------------- 1 file changed, 3339 insertions(+), 3012 deletions(-) diff --git a/scripts/ci/test-durations.tsv b/scripts/ci/test-durations.tsv index 6ff82545deb..fefe8b5fcb2 100644 --- a/scripts/ci/test-durations.tsv +++ b/scripts/ci/test-durations.tsv @@ -1,3026 +1,3353 @@ # Per-file Bun test durations in milliseconds, read from hosted CI job logs. # Consumed by scripts/ci/run-bun-test-batches.sh to balance shards; a file without a row weighs the median. # Regenerate with scripts/ci/test-durations.ts (usage in its header); do not edit by hand. -# Source: Ubuntu and macOS passing jobs: run 42694893702 on 4b38e9a072 (test 1-5/5: 129424126084,129424126100,129424126131,129424126088,129424126091; macos 1-4/4: 129424126216,129424126104,129424126041,129424125988); unmeasured existing rows retained -372 tests/adapters/abort-race.test.ts -496 tests/adapters/adapter-buffered-tool-conformance.test.ts -105 tests/adapters/adapter-error-inline.test.ts -1756 tests/adapters/adapter-inner-send-budget-wiring.test.ts -2834 tests/adapters/adapter-inner-send-budget.test.ts -471 tests/adapters/adapter-input-media-guard.test.ts -315 tests/adapters/adapter-registry-authority.test.ts -1105 tests/adapters/adapter-tool-conformance.test.ts -100 tests/adapters/adapter-usage.test.ts -851 tests/adapters/anthropic/anthropic-429-policy.test.ts -49 tests/adapters/anthropic/anthropic-account-metadata.test.ts -142 tests/adapters/anthropic/anthropic-account-pause-outbound.test.ts -319 tests/adapters/anthropic/anthropic-account-pause.test.ts -379 tests/adapters/anthropic/anthropic-account-pool.test.ts -852 tests/adapters/anthropic/anthropic-account-threshold.test.ts -97 tests/adapters/anthropic/anthropic-active-limit-routing.test.ts -278 tests/adapters/anthropic/anthropic-affinity-restart.test.ts -1241 tests/adapters/anthropic/anthropic-affinity-store.test.ts -40 tests/adapters/anthropic/anthropic-agentrouter-language-framing.test.ts -72 tests/adapters/anthropic/anthropic-baseurl-override.test.ts -35 tests/adapters/anthropic/anthropic-beta-allowlist.test.ts -40 tests/adapters/anthropic/anthropic-beta-body-pairs.test.ts -293 tests/adapters/anthropic/anthropic-billing-ownership.test.ts -308 tests/adapters/anthropic/anthropic-billing-refusal.test.ts -47 tests/adapters/anthropic/anthropic-client-identity.test.ts -358 tests/adapters/anthropic/anthropic-combo-account-cooldown.test.ts -2550 tests/adapters/anthropic/anthropic-compatible-stream.test.ts -164 tests/adapters/anthropic/anthropic-cooldown-recovery.test.ts -45 tests/adapters/anthropic/anthropic-empty-content.test.ts -89 tests/adapters/anthropic/anthropic-eof-tolerance.test.ts -240 tests/adapters/anthropic/anthropic-error-body.test.ts -40 tests/adapters/anthropic/anthropic-error-stop-reason.test.ts -357 tests/adapters/anthropic/anthropic-fast-opt-in.test.ts -58 tests/adapters/anthropic/anthropic-fast-speed.test.ts -36 tests/adapters/anthropic/anthropic-haiku-5-5-contract.test.ts -40 tests/adapters/anthropic/anthropic-hardening.test.ts -172 tests/adapters/anthropic/anthropic-image-guard.test.ts -3268 tests/adapters/anthropic/anthropic-image-normalize.test.ts -15607 tests/adapters/anthropic/anthropic-image-retry-e2e.test.ts -164 tests/adapters/anthropic/anthropic-image-retry.test.ts -513 tests/adapters/anthropic/anthropic-instance-isolation.test.ts -502 tests/adapters/anthropic/anthropic-instance-pool-parity.test.ts -679 tests/adapters/anthropic/anthropic-instance-quota.test.ts -4009 tests/adapters/anthropic/anthropic-instance-recovery.test.ts -51 tests/adapters/anthropic/anthropic-message-stop-termination.test.ts -46 tests/adapters/anthropic/anthropic-messages-passthrough-oauth.test.ts -32 tests/adapters/anthropic/anthropic-messages-passthrough.test.ts -959 tests/adapters/anthropic/anthropic-model-routes.test.ts -582 tests/adapters/anthropic/anthropic-model-weekly-admission.test.ts -40 tests/adapters/anthropic/anthropic-opaque-strip.test.ts -85 tests/adapters/anthropic/anthropic-output-maxima.test.ts -37 tests/adapters/anthropic/anthropic-parallel-tool-disable.test.ts -124 tests/adapters/anthropic/anthropic-pool-toggle-copy.test.ts -247 tests/adapters/anthropic/anthropic-pool-usage-limit.test.ts -888 tests/adapters/anthropic/anthropic-progress-updates.test.ts -198 tests/adapters/anthropic/anthropic-quota-cooldown-recovery.test.ts -864 tests/adapters/anthropic/anthropic-quota-dispatch.test.ts -232 tests/adapters/anthropic/anthropic-ratelimit-headers.test.ts -143 tests/adapters/anthropic/anthropic-reasoning.test.ts -61 tests/adapters/anthropic/anthropic-replay.test.ts -63 tests/adapters/anthropic/anthropic-reset-grants.test.ts -368 tests/adapters/anthropic/anthropic-revoked-token-boundaries.test.ts -219 tests/adapters/anthropic/anthropic-revoked-token-continuation.test.ts -445 tests/adapters/anthropic/anthropic-revoked-token-sidecars.test.ts -2356 tests/adapters/anthropic/anthropic-revoked-token.test.ts -131 tests/adapters/anthropic/anthropic-sidecar-account-failover.test.ts -39 tests/adapters/anthropic/anthropic-sonnet-5-5-contract.test.ts +# Source: Completed primary-file samples only; existing unmeasured rows retained. +# Green dev lane=all: lidge-jun/opencodex run 44386662799, c38d6eef7986b3b9acbb6e8ac17407ab84e5633e; Ubuntu jobs 135093186424,135093186236,135093186230,135093186350,135093186295; macOS jobs 135093186207,135093186360,135093186156,135093186139. +# Additional Ubuntu PR samples: luvs01/opencodex #840 run 44448708478, 374867f6a068c50beaa2ec4e17e57876c88c87cc; jobs 135307330817,135307330808,135307330846,135307330937,135307330890. Workflow cancelled; 2/5's unfinished stop-deferred-teardown file excluded; 3/5 finished its tests but its job was cancelled. +# Additional Ubuntu PR samples: luvs01/opencodex #841 run 44448420609, 31e5078742f928592d7f88287cdb98a688cbc975; jobs 135313932894,135313932243,135313993098,135313933788,135313933743. Successful latest-attempt job set, including retained earlier successful jobs; not a cross-platform dev dispatch. +251 tests/adapters/abort-race.test.ts +347 tests/adapters/adapter-buffered-tool-conformance.test.ts +269 tests/adapters/adapter-error-inline.test.ts +1675 tests/adapters/adapter-inner-send-budget-wiring.test.ts +2957 tests/adapters/adapter-inner-send-budget.test.ts +260 tests/adapters/adapter-input-media-guard.test.ts +199 tests/adapters/adapter-registry-authority.test.ts +1469 tests/adapters/adapter-tool-conformance.test.ts +333 tests/adapters/adapter-usage.test.ts +1007 tests/adapters/agy-acp-adapter.test.ts +275 tests/adapters/agy-acp-policy.test.ts +120 tests/adapters/agy-acp-protocol.test.ts +1137 tests/adapters/anthropic/anthropic-429-policy.test.ts +71 tests/adapters/anthropic/anthropic-account-metadata.test.ts +168 tests/adapters/anthropic/anthropic-account-pause-outbound.test.ts +458 tests/adapters/anthropic/anthropic-account-pause.test.ts +524 tests/adapters/anthropic/anthropic-account-pool.test.ts +621 tests/adapters/anthropic/anthropic-account-threshold.test.ts +224 tests/adapters/anthropic/anthropic-active-limit-routing.test.ts +501 tests/adapters/anthropic/anthropic-affinity-restart.test.ts +1356 tests/adapters/anthropic/anthropic-affinity-store.test.ts +69 tests/adapters/anthropic/anthropic-agentrouter-language-framing.test.ts +104 tests/adapters/anthropic/anthropic-baseurl-override.test.ts +79 tests/adapters/anthropic/anthropic-beta-allowlist.test.ts +76 tests/adapters/anthropic/anthropic-beta-body-pairs.test.ts +479 tests/adapters/anthropic/anthropic-billing-ownership.test.ts +305 tests/adapters/anthropic/anthropic-billing-refusal.test.ts +61 tests/adapters/anthropic/anthropic-client-identity.test.ts +410 tests/adapters/anthropic/anthropic-combo-account-cooldown.test.ts +2582 tests/adapters/anthropic/anthropic-compatible-stream.test.ts +336 tests/adapters/anthropic/anthropic-cooldown-recovery-worker.test.ts +236 tests/adapters/anthropic/anthropic-cooldown-recovery.test.ts +60 tests/adapters/anthropic/anthropic-empty-content.test.ts +91 tests/adapters/anthropic/anthropic-eof-tolerance.test.ts +453 tests/adapters/anthropic/anthropic-error-body.test.ts +66 tests/adapters/anthropic/anthropic-error-stop-reason.test.ts +528 tests/adapters/anthropic/anthropic-fast-opt-in.test.ts +107 tests/adapters/anthropic/anthropic-fast-speed.test.ts +1227 tests/adapters/anthropic/anthropic-funded-roster.test.ts +59 tests/adapters/anthropic/anthropic-haiku-5-5-contract.test.ts +55 tests/adapters/anthropic/anthropic-hardening.test.ts +158 tests/adapters/anthropic/anthropic-image-guard.test.ts +3361 tests/adapters/anthropic/anthropic-image-normalize.test.ts +16064 tests/adapters/anthropic/anthropic-image-retry-e2e.test.ts +147 tests/adapters/anthropic/anthropic-image-retry.test.ts +756 tests/adapters/anthropic/anthropic-instance-isolation.test.ts +686 tests/adapters/anthropic/anthropic-instance-pool-parity.test.ts +929 tests/adapters/anthropic/anthropic-instance-quota.test.ts +3068 tests/adapters/anthropic/anthropic-instance-recovery.test.ts +76 tests/adapters/anthropic/anthropic-message-stop-termination.test.ts +166 tests/adapters/anthropic/anthropic-messages-passthrough-oauth.test.ts +75 tests/adapters/anthropic/anthropic-messages-passthrough.test.ts +1142 tests/adapters/anthropic/anthropic-model-routes.test.ts +683 tests/adapters/anthropic/anthropic-model-weekly-admission.test.ts +61 tests/adapters/anthropic/anthropic-opaque-strip.test.ts +66 tests/adapters/anthropic/anthropic-output-cap-by-model.test.ts +135 tests/adapters/anthropic/anthropic-output-maxima.test.ts +69 tests/adapters/anthropic/anthropic-parallel-tool-disable.test.ts +104 tests/adapters/anthropic/anthropic-per-message-effort.test.ts +120 tests/adapters/anthropic/anthropic-pool-toggle-copy.test.ts +531 tests/adapters/anthropic/anthropic-pool-usage-limit.test.ts +172 tests/adapters/anthropic/anthropic-progress-updates.test.ts +377 tests/adapters/anthropic/anthropic-quota-cooldown-recovery.test.ts +2086 tests/adapters/anthropic/anthropic-quota-dispatch.test.ts +332 tests/adapters/anthropic/anthropic-ratelimit-headers.test.ts +186 tests/adapters/anthropic/anthropic-reasoning.test.ts +69 tests/adapters/anthropic/anthropic-replay.test.ts +93 tests/adapters/anthropic/anthropic-reset-grants.test.ts +399 tests/adapters/anthropic/anthropic-revoked-token-boundaries.test.ts +471 tests/adapters/anthropic/anthropic-revoked-token-continuation.test.ts +544 tests/adapters/anthropic/anthropic-revoked-token-sidecars.test.ts +1504 tests/adapters/anthropic/anthropic-revoked-token.test.ts +409 tests/adapters/anthropic/anthropic-sidecar-account-failover.test.ts +87 tests/adapters/anthropic/anthropic-sonnet-5-5-contract.test.ts 61 tests/adapters/anthropic/anthropic-stream-hardening.test.ts -609 tests/adapters/anthropic/anthropic-subscription-chain.test.ts -97 tests/adapters/anthropic/anthropic-tail-guard.test.ts -53 tests/adapters/anthropic/anthropic-thinking-display-policy.test.ts -105 tests/adapters/anthropic/anthropic-thinking-signature.test.ts -60 tests/adapters/anthropic/anthropic-thinking-usage.test.ts -40 tests/adapters/anthropic/anthropic-tool-call-id.test.ts -141 tests/adapters/anthropic/anthropic-tool-declaration-constraints.test.ts -50 tests/adapters/anthropic/anthropic-tool-schema.test.ts -497 tests/adapters/anthropic/anthropic2-fast-parity.test.ts -90 tests/adapters/bridge-legacy-shell-normalization.test.ts -3537 tests/adapters/bridge-lifecycle.test.ts -199 tests/adapters/bridge-nonstreaming-terminal.test.ts -97 tests/adapters/bridge-raw-reasoning-hidden.test.ts -39 tests/adapters/bridge-reasoning-replay-batch.test.ts -94 tests/adapters/bridge-stall.test.ts -112 tests/adapters/bridge-terminal-refusal.test.ts -53 tests/adapters/bridge-terminal-singleness.test.ts -235 tests/adapters/bridge.test.ts -80 tests/adapters/buffered-response-shape-guards.test.ts -120 tests/adapters/coding-agent-history-projection.test.ts -28 tests/adapters/coding-agent-tool-result-images.test.ts -175 tests/adapters/coding-agent-windows-dispatch.test.ts -71 tests/adapters/dsh-account-adapter.test.ts -399 tests/adapters/empty-tool-output-annotation.test.ts -112 tests/adapters/exec-tool-result-normalize.test.ts -116 tests/adapters/fix-tool-number-preservation.test.ts -83 tests/adapters/google/antigravity-account-roster.test.ts -59 tests/adapters/google/antigravity-baseurl-override.test.ts -42 tests/adapters/google/antigravity-discovered-families.test.ts -30 tests/adapters/google/antigravity-refusal.test.ts -394 tests/adapters/google/antigravity-routing-carry.test.ts -79 tests/adapters/google/antigravity-static-catalog.test.ts -5368 tests/adapters/google/gcp-adc.test.ts -547 tests/adapters/google/gcp-credential-boundary.test.ts -234 tests/adapters/google/gcp-sa-adapter.test.ts -392 tests/adapters/google/gcp-sa-marker.test.ts -55 tests/adapters/google/gemini-37-flash-migration.test.ts -99 tests/adapters/google/gemini-4-argon-antigravity.test.ts -46 tests/adapters/google/gemini-progress-history.test.ts -147 tests/adapters/google/gemini-web-search.test.ts -66 tests/adapters/google/google-adapter.test.ts -58 tests/adapters/google/google-ai-studio-foreign-call-signature.test.ts -4156 tests/adapters/google/google-antigravity-oauth.test.ts -2192 tests/adapters/google/google-antigravity-replay.test.ts -51 tests/adapters/google/google-antigravity-wire.test.ts -49 tests/adapters/google/google-buffered-stop-reason.test.ts -41 tests/adapters/google/google-claude-prefill-guard.test.ts -51 tests/adapters/google/google-empty-content.test.ts -41 tests/adapters/google/google-errors.test.ts -40 tests/adapters/google/google-hardening.test.ts -153 tests/adapters/google/google-models-listing.test.ts -34 tests/adapters/google/google-output-clamp.test.ts -29 tests/adapters/google/google-provider-metadata-roundtrip.test.ts -79 tests/adapters/google/google-signature-history-roundtrip.test.ts -39 tests/adapters/google/google-stream-fragmentation.test.ts -33 tests/adapters/google/google-strict-tool-validated-mode.test.ts -36 tests/adapters/google/google-structured-output.test.ts -40 tests/adapters/google/google-tool-result-adjacency.test.ts -54 tests/adapters/google/google-tool-schema-contract.test.ts -44 tests/adapters/google/google-tool-schema.test.ts -4694 tests/adapters/google/google-vertex-http.test.ts -131 tests/adapters/google/google-vertex-key-project.test.ts -53 tests/adapters/google/google-vertex-stream.test.ts -60 tests/adapters/google/google-vertex-thought-signature.test.ts -64 tests/adapters/google/google-wire-compiler.test.ts -50 tests/adapters/google/google-wire-shape.test.ts -91 tests/adapters/google/vertex-catalog.test.ts -81 tests/adapters/identity-neutralize.test.ts -289 tests/adapters/identity-subagent.test.ts -389 tests/adapters/key-failover.test.ts -80 tests/adapters/openai/inline-think-boundaries.test.ts -1884 tests/adapters/openai/openai-api-virtual-models.test.ts -38 tests/adapters/openai/openai-chat-audio.test.ts -145 tests/adapters/openai/openai-chat-bounded-tool-names.test.ts -35 tests/adapters/openai/openai-chat-dangling-toolcalls.test.ts -44 tests/adapters/openai/openai-chat-developer-position.test.ts -38 tests/adapters/openai/openai-chat-eof.test.ts -62 tests/adapters/openai/openai-chat-glm-summary.test.ts -178 tests/adapters/openai/openai-chat-hardening.test.ts -3633 tests/adapters/openai/openai-chat-image-normalization.test.ts -48 tests/adapters/openai/openai-chat-inline-think-tags.test.ts -66 tests/adapters/openai/openai-chat-invalid-tool-call-diagnostics.test.ts -85 tests/adapters/openai/openai-chat-mistral-content.test.ts -44 tests/adapters/openai/openai-chat-mistral-policy.test.ts -100 tests/adapters/openai/openai-chat-model-suffix.test.ts -394 tests/adapters/openai/openai-chat-native-policy.test.ts -120 tests/adapters/openai/openai-chat-nonce-tool-call-content.test.ts -61 tests/adapters/openai/openai-chat-parallel-stream.test.ts -63 tests/adapters/openai/openai-chat-path-override.test.ts -51 tests/adapters/openai/openai-chat-qwen38-leading-system.test.ts -104 tests/adapters/openai/openai-chat-reasoning-wire-policy.test.ts -51 tests/adapters/openai/openai-chat-required-tool.test.ts -132 tests/adapters/openai/openai-chat-sanitization-review-regressions.test.ts -54 tests/adapters/openai/openai-chat-serialized-tool-call-content.test.ts -190 tests/adapters/openai/openai-chat-serialized-tool-call-hold-bound.test.ts -84 tests/adapters/openai/openai-chat-serialized-tool-call-scaling.test.ts -42 tests/adapters/openai/openai-chat-serialized-tool-call-think.test.ts -40 tests/adapters/openai/openai-chat-single-system.test.ts -240 tests/adapters/openai/openai-chat-standalone-bare-block.test.ts -86 tests/adapters/openai/openai-chat-system-order.test.ts -48 tests/adapters/openai/openai-chat-tool-call-id-remint.test.ts -41 tests/adapters/openai/openai-chat-tool-result-images.test.ts -39 tests/adapters/openai/openai-chat-url.test.ts -37 tests/adapters/openai/openai-chat-video-part.test.ts -111 tests/adapters/openai/openai-empty-assistant-history.test.ts -151 tests/adapters/openai/openai-native-hosted-search-history.test.ts -863 tests/adapters/openai/openai-provider-option-e2e.test.ts -279 tests/adapters/openai/openai-provider-option-migration.test.ts -44 tests/adapters/openai/openai-provider-option-startup.test.ts -46 tests/adapters/openai/openai-provider-option-tooling.test.ts -37 tests/adapters/openai/openai-provider-option.test.ts -36 tests/adapters/openai/opengateway-input.test.ts -108 tests/adapters/physical-send.test.ts -52 tests/adapters/qoder-spawn-readmission.test.ts -49 tests/adapters/reasoning-replay-identity.test.ts -228 tests/adapters/reasoning-replay-robustness.test.ts -104 tests/adapters/routed-agent-messages.test.ts -76 tests/adapters/run-turn-queue.test.ts -397 tests/adapters/terminal-continuation-owner-rotation.test.ts -116 tests/adapters/tool-argument-integers.test.ts -35 tests/adapters/tool-catalog-nudge.test.ts -36 tests/adapters/tool-choice-performance.test.ts -35 tests/adapters/tool-envelope-echo-whole-line.test.ts -41 tests/adapters/tool-identity-hash.test.ts -185 tests/adapters/translator-budget-lifetime.test.ts -4792 tests/adapters/translator-budget.test.ts -43 tests/adapters/upstream-http-error.test.ts -38 tests/adapters/workbuddy-adapter.test.ts -65 tests/advisor/advisor-adaptive.test.ts -91 tests/advisor/advisor-authority-transport.test.ts -115 tests/advisor/advisor-budget.test.ts -184 tests/advisor/advisor-caller-policy-compact.test.ts -257 tests/advisor/advisor-caller-policy-host-key.test.ts -286 tests/advisor/advisor-caller-policy-http.test.ts -274 tests/advisor/advisor-caller-policy-ingress.test.ts -402 tests/advisor/advisor-caller-policy-jev.test.ts -310 tests/advisor/advisor-caller-policy-replay.test.ts -437 tests/advisor/advisor-caller-policy-routing.test.ts -453 tests/advisor/advisor-caller-policy-self-fetch.test.ts -147 tests/advisor/advisor-caller-policy-sidecar-authority.test.ts -284 tests/advisor/advisor-caller-policy-vision.test.ts -428 tests/advisor/advisor-caller-policy.test.ts -48 tests/advisor/advisor-consult.test.ts -46 tests/advisor/advisor-context.test.ts -33 tests/advisor/advisor-continuation-limit.test.ts -361 tests/advisor/advisor-core-boundary.test.ts -52 tests/advisor/advisor-evidence.test.ts -62 tests/advisor/advisor-guard.test.ts -171 tests/advisor/advisor-internal-authority.test.ts -45 tests/advisor/advisor-plan.test.ts -847 tests/advisor/advisor-responses-wiring.test.ts -281 tests/advisor/advisor-retention.test.ts -375 tests/advisor/advisor-scope-transport.test.ts -131 tests/advisor/advisor-settings.test.ts -68 tests/advisor/advisor-state.test.ts -91 tests/advisor/advisor-web-search.test.ts -3492 tests/ci-workflows/assert-mergeable-review.test.ts -52 tests/ci-workflows/brand-favicons.test.ts -182 tests/ci-workflows/build-desktop-icon-set.test.ts -109 tests/ci-workflows/build-release-changelog.test.ts -355 tests/ci-workflows/bump-dev-version.test.ts -145 tests/ci-workflows/bun-runtime.test.ts -45 tests/ci-workflows/ci-bun-crash-classifier.test.ts -38607 tests/ci-workflows/ci-bun-install-frozen.test.ts -54 tests/ci-workflows/ci-concurrency-groups.test.ts -5589 tests/ci-workflows/ci-crash-disposition.test.ts -1574 tests/ci-workflows/ci-gui-typecheck-gate.test.ts -73 tests/ci-workflows/ci-pr-hygiene-approvals.test.ts -1050 tests/ci-workflows/ci-privacy-gate.test.ts -7069 tests/ci-workflows/ci-review-lanes.test.ts -803 tests/ci-workflows/ci-scope-gaps.test.ts -523 tests/ci-workflows/ci-scope-reduction.test.ts -1994 tests/ci-workflows/ci-shard-balance.test.ts -30 tests/ci-workflows/ci-structure-gate.test.ts -1522 tests/ci-workflows/ci-test-lane.test.ts -653 tests/ci-workflows/ci-workflows.test.ts -43 tests/ci-workflows/cleanup-orphaned-workflows.test.ts -171 tests/ci-workflows/client-support-matrix.test.ts -1139 tests/ci-workflows/client-support-runtime.test.ts -41 tests/ci-workflows/closed-pr-branch-cleanup.test.ts -6830 tests/ci-workflows/cold-spawn-warmup.test.ts -129 tests/ci-workflows/compatibility-version.test.ts -45 tests/ci-workflows/docs-429-failover-claims.test.ts -41 tests/ci-workflows/docs-bun-source-requirement.test.ts -153 tests/ci-workflows/docs-developer-role-policy.test.ts -120 tests/ci-workflows/docs-gjc-reasoning-export.test.ts -86 tests/ci-workflows/docs-gpt61-terra.test.ts -32 tests/ci-workflows/docs-gui-screenshot-policy.test.ts -369 tests/ci-workflows/docs-link-targets.test.ts -35 tests/ci-workflows/docs-navigation-label.test.ts -54 tests/ci-workflows/docs-provider-billing-claims.test.ts -54 tests/ci-workflows/docs-provider-discovery-limits.test.ts -41 tests/ci-workflows/docs-provider-preset-counts.test.ts -106 tests/ci-workflows/docs-readme-memory-inventory.test.ts -74 tests/ci-workflows/docs-readme-translation-parity.test.ts -54 tests/ci-workflows/docs-remote-hub-claims.test.ts -190 tests/ci-workflows/docs-telemetry-dashboard.test.ts -199 tests/ci-workflows/docs-telemetry-leaderboard.test.ts -245 tests/ci-workflows/dsh-path-contract.test.ts -299 tests/ci-workflows/dsh-rc6-compat-script.test.ts -534 tests/ci-workflows/dsh-writer-lock.test.ts -70 tests/ci-workflows/exhaustive-deps-suppression.test.ts -778 tests/ci-workflows/file-size-ratchet.test.ts -581 tests/ci-workflows/fixture-dir-uniqueness.test.ts -49 tests/ci-workflows/fixture-teardown-helper.test.ts -488 tests/ci-workflows/fixture-windows-runtime-preload.test.ts -529 tests/ci-workflows/import-cycle-ratchet.test.ts -193 tests/ci-workflows/install-scripts.test.ts -51 tests/ci-workflows/installed-gate-drivers.test.ts -39 tests/ci-workflows/keyring-smoke.test.ts -41 tests/ci-workflows/linux-desktop-packaged-ci.test.ts -155 tests/ci-workflows/linux-desktop-packaged-e2e.test.ts -5829 tests/ci-workflows/macos-serial-lanes.test.ts -2711 tests/ci-workflows/package-tree-fenced-restart.test.ts -2718 tests/ci-workflows/package-tree-integrity.test.ts -100 tests/ci-workflows/package-tree-restart-ownership.test.ts -104 tests/ci-workflows/package-tree-retarget.test.ts -75 tests/ci-workflows/pr-readiness-reattest.test.ts -36 tests/ci-workflows/privacy-scan-asset-names.test.ts -49 tests/ci-workflows/privacy-scan-meta-key.test.ts -32 tests/ci-workflows/privacy-scan-ssh-endpoint.test.ts -62 tests/ci-workflows/release-desktop-scripts.test.ts -1853 tests/ci-workflows/release-helper.test.ts -54 tests/ci-workflows/release-notes.test.ts -219 tests/ci-workflows/release-outcome-report.test.ts -4708 tests/ci-workflows/release-pipeline-contract.test.ts -3449 tests/ci-workflows/release-preflight.test.ts -1698 tests/ci-workflows/release-resume-identity.test.ts -47 tests/ci-workflows/release-version-line.test.ts -353 tests/ci-workflows/release-version-sources.test.ts -9335 tests/ci-workflows/release-windows-signing.test.ts -228 tests/ci-workflows/repo-hygiene.test.ts -398 tests/ci-workflows/repo-import-resolution.test.ts -418 tests/ci-workflows/setup-hooks.test.ts -411 tests/ci-workflows/skill-ocx-generated.test.ts -103 tests/ci-workflows/skill-ocx-workflows.test.ts -71 tests/ci-workflows/skill-ocx.test.ts -574 tests/ci-workflows/structure-ssot.test.ts -735 tests/ci-workflows/test-home-guard-unpreloaded.test.ts -38311 tests/ci-workflows/test-home-guard.test.ts -20882 tests/ci-workflows/test-run-lock-generation.test.ts -157 tests/ci-workflows/test-runner-bun.test.ts -399 tests/ci-workflows/test-runner-spawnsync-finalizer.test.ts -18336 tests/ci-workflows/test-runner.test.ts -36 tests/ci-workflows/test-sandbox-cleanup.test.ts -41 tests/ci-workflows/test-temp-quarantine.test.ts -44 tests/ci-workflows/version-line.test.ts -70 tests/ci-workflows/warmup-registration.test.ts -61 tests/ci-workflows/zz-ci-api-usage-isolation.test.ts -32 tests/ci-workflows/zz-ci-storage-policy-isolation.test.ts -67 tests/ci-workflows/zz-pr-coderabbit-readiness-revalidation.test.ts -1737 tests/claude-integration/anthropic2-native-routing.test.ts -2630 tests/claude-integration/claude-529-mapping.test.ts -76 tests/claude-integration/claude-agent-startup-sync.test.ts -92 tests/claude-integration/claude-agents-inject-client.test.ts -135 tests/claude-integration/claude-agents-inject.test.ts -180 tests/claude-integration/claude-alias.test.ts -46 tests/claude-integration/claude-auth-detect.test.ts -79 tests/claude-integration/claude-auth-mode.test.ts -35 tests/claude-integration/claude-authmode-migration.test.ts -680 tests/claude-integration/claude-bridge-pool-dispatch.test.ts -100 tests/claude-integration/claude-bridge-pool-session.test.ts -347 tests/claude-integration/claude-cli-picker-surface.test.ts -452 tests/claude-integration/claude-cli-picker.test.ts -91 tests/claude-integration/claude-cli.test.ts -1129 tests/claude-integration/claude-client-refusal-status.test.ts -177 tests/claude-integration/claude-code-thought-signature-scope.test.ts -43 tests/claude-integration/claude-compatibility.test.ts -290 tests/claude-integration/claude-config-home-isolation.test.ts -1070 tests/claude-integration/claude-config-root-late-admission.test.ts -319 tests/claude-integration/claude-config-root-stale-updates.test.ts -388 tests/claude-integration/claude-config-root-writer-barrier.test.ts -94 tests/claude-integration/claude-context-accounting.test.ts -174 tests/claude-integration/claude-context-windows.test.ts -126 tests/claude-integration/claude-desktop-1m.test.ts -654 tests/claude-integration/claude-desktop-cli.test.ts -345 tests/claude-integration/claude-desktop-config-path.test.ts -701 tests/claude-integration/claude-desktop-discovery.test.ts -305 tests/claude-integration/claude-desktop-first-party-guards.test.ts -761 tests/claude-integration/claude-desktop-first-party.test.ts -94 tests/claude-integration/claude-desktop-mode-explanation.test.ts -475 tests/claude-integration/claude-desktop-model-visibility.test.ts -86 tests/claude-integration/claude-desktop-native-context.test.ts -506 tests/claude-integration/claude-desktop-picker-profile.test.ts -399 tests/claude-integration/claude-desktop-picker-routes.test.ts -127 tests/claude-integration/claude-desktop-picker.test.ts -36 tests/claude-integration/claude-desktop-policy.test.ts -6077 tests/claude-integration/claude-desktop-remote-hub.test.ts -121 tests/claude-integration/claude-desktop-system-proxy.test.ts -468 tests/claude-integration/claude-devin-output-order.test.ts -142 tests/claude-integration/claude-dotenv-provenance-transport.test.ts -232 tests/claude-integration/claude-endpoint-lifetime.test.ts -444 tests/claude-integration/claude-estimate-projection.test.ts -250 tests/claude-integration/claude-first-party-agent-sync.test.ts -132 tests/claude-integration/claude-first-party-union.test.ts -80 tests/claude-integration/claude-gateway-cache.test.ts -269 tests/claude-integration/claude-gateway-output-cap.test.ts -213 tests/claude-integration/claude-inbound-cache-stabilize.test.ts -46 tests/claude-integration/claude-inbound-debug.test.ts -63 tests/claude-integration/claude-inbound-token-footer.test.ts -597 tests/claude-integration/claude-inbound-tool-loading.test.ts -83 tests/claude-integration/claude-inbound-tool-reference.test.ts -109 tests/claude-integration/claude-inbound.test.ts -197 tests/claude-integration/claude-installation-helper.test.ts -263 tests/claude-integration/claude-intercept-acl-barrier.test.ts -64 tests/claude-integration/claude-intercept-cleanup.test.ts -128 tests/claude-integration/claude-intercept-client-class.test.ts -94 tests/claude-integration/claude-intercept-local-ca-files.test.ts -136 tests/claude-integration/claude-intercept-local-ca-windows.test.ts -147 tests/claude-integration/claude-intercept-local-ca.test.ts -213 tests/claude-integration/claude-intercept-model-bindings.test.ts -101 tests/claude-integration/claude-intercept-no-proxy.test.ts -204 tests/claude-integration/claude-intercept-on-demand.test.ts -180 tests/claude-integration/claude-intercept-proxy-auth.test.ts -105 tests/claude-integration/claude-intercept-proxy.test.ts -91 tests/claude-integration/claude-intercept-settings.test.ts -87 tests/claude-integration/claude-long-context-eligibility.test.ts -4730 tests/claude-integration/claude-management-api.test.ts -4799 tests/claude-integration/claude-messages-endpoint.test.ts -448 tests/claude-integration/claude-messages-thread.test.ts -93 tests/claude-integration/claude-model-default-labels.test.ts -90 tests/claude-integration/claude-model-info.test.ts -1085 tests/claude-integration/claude-models-discovery.test.ts -2190 tests/claude-integration/claude-native-affinity.test.ts -850 tests/claude-integration/claude-native-fast-1m-ingress.test.ts -7876 tests/claude-integration/claude-native-passthrough.test.ts -143 tests/claude-integration/claude-native-rate-limit-headers.test.ts -80 tests/claude-integration/claude-native-reasoning-continuity.test.ts -442 tests/claude-integration/claude-native-reasoning-provenance.test.ts -2019 tests/claude-integration/claude-outbound.test.ts -119 tests/claude-integration/claude-output-schema-strict.test.ts -260 tests/claude-integration/claude-picker-bootstrap.test.ts -343 tests/claude-integration/claude-picker-ca-store.test.ts -431 tests/claude-integration/claude-picker-ca.test.ts -104 tests/claude-integration/claude-picker-linger.test.ts -812 tests/claude-integration/claude-picker-listener.test.ts -95 tests/claude-integration/claude-picker-models.test.ts -841 tests/claude-integration/claude-picker-recovery.test.ts -165 tests/claude-integration/claude-picker-relay-intent.test.ts -376 tests/claude-integration/claude-picker-runtime.test.ts -1196 tests/claude-integration/claude-picker-startup.test.ts -70 tests/claude-integration/claude-picker-trust-windows.test.ts -38 tests/claude-integration/claude-picker-trust.test.ts -3969 tests/claude-integration/claude-picker-upload.test.ts -539 tests/claude-integration/claude-picker-windows.test.ts -2001 tests/claude-integration/claude-prompt-too-long.test.ts -81 tests/claude-integration/claude-shell-hook.test.ts -167 tests/claude-integration/claude-sidecar-override.test.ts -79 tests/claude-integration/claude-source-envelope.test.ts -116 tests/claude-integration/claude-subagent-model-force.test.ts -90 tests/claude-integration/claude-system-env-auto.test.ts -296 tests/claude-integration/claude-tool-loading-destinations.test.ts -286 tests/claude-integration/claude-translated-cache-ttl.test.ts -497 tests/claude-integration/claude-translated-server-tools.test.ts -308 tests/claude-integration/claude-translated-tool-restrictions.test.ts -145 tests/claude-integration/claude-uncoded-context-overflow.test.ts -218 tests/claude-integration/messages-error-contracts.test.ts -1463 tests/claude-integration/messages-error-normalization.test.ts -60 tests/claude-integration/messages-header-normalization.test.ts -424 tests/claude-integration/messages-lane-errors.test.ts -254 tests/claude-integration/messages-native-clean-eof.test.ts -54 tests/claude-integration/messages-native-combo-framing.test.ts -1448 tests/claude-integration/messages-native-combo.test.ts -348 tests/claude-integration/messages-native-decline-trace.test.ts -454 tests/claude-integration/messages-native-empty-inline.test.ts -589 tests/claude-integration/messages-native-key-selection.test.ts -1844 tests/claude-integration/messages-native-oauth.test.ts -176 tests/claude-integration/messages-native-opaque-state.test.ts -500 tests/claude-integration/messages-native-scope.test.ts -2444 tests/claude-integration/messages-native-stream-parity.test.ts -2560 tests/claude-integration/messages-native.test.ts -682 tests/claude-integration/messages-overflow-baseline-contract.test.ts -18283 tests/claude-integration/messages-overflow-builtin.test.ts -4873 tests/claude-integration/messages-overflow-collectors.test.ts -10517 tests/claude-integration/messages-overflow-native.test.ts -5946 tests/claude-integration/messages-overflow-stream.test.ts -15269 tests/claude-integration/messages-overflow-translated.test.ts -7791 tests/claude-integration/messages-overflow-verdicts.test.ts -15858 tests/claude-integration/messages-proxy-refusals.test.ts -1776 tests/claude-integration/messages-request-id-endpoint.test.ts -115 tests/claude-integration/messages-request-id-headers.test.ts -1529 tests/claude-integration/messages-review-regressions.test.ts -1204 tests/claude-integration/messages-revoked-token.test.ts -290 tests/claude-integration/messages-shared-sse.test.ts -86 tests/claude-integration/messages-sse-baseline-contract.test.ts -4481 tests/claude-integration/messages-sse-builtin-errors.test.ts -2240 tests/claude-integration/messages-sse-continuation.test.ts -925 tests/claude-integration/messages-sse-control-fields.test.ts -3769 tests/claude-integration/messages-sse-count-tokens-errors.test.ts -34 tests/claude-integration/messages-sse-delivery.test.ts -427 tests/claude-integration/messages-sse-fold-errors.test.ts -57 tests/claude-integration/messages-sse-guard-errors.test.ts -4222 tests/claude-integration/messages-sse-native-errors.test.ts -5345 tests/claude-integration/messages-sse-passthrough-errors.test.ts -3109 tests/claude-integration/messages-sse-tap-tails.test.ts -2644 tests/claude-integration/messages-sse-workflow-refusal.test.ts -279 tests/claude-integration/messages-success-media-types.test.ts -99 tests/claude-integration/messages-surface-matrix.test.ts -33 tests/cli/agent-driven.test.ts -85 tests/cli/agent-subagent-force.test.ts -866 tests/cli/bun-transpiler-cache-scope.test.ts -64 tests/cli/claude-config-first-party.test.ts -15191 tests/cli/cli-access-audio-live.test.ts -266 tests/cli/cli-access-audio.test.ts -97 tests/cli/cli-access-data-plane.test.ts -68 tests/cli/cli-access-key-guard.test.ts -195 tests/cli/cli-access-rename.test.ts -62 tests/cli/cli-account-alias-target.test.ts -148 tests/cli/cli-account-cancel-flow.test.ts -69 tests/cli/cli-account-key-pause.test.ts -162 tests/cli/cli-account-key-quota.test.ts -67 tests/cli/cli-account-kiro-device.test.ts -318 tests/cli/cli-account-login-options.test.ts -60 tests/cli/cli-account-orca-import.test.ts -59 tests/cli/cli-account-pin-drain.test.ts -484 tests/cli/cli-account-policy.test.ts -62 tests/cli/cli-account-pool-verbs.test.ts -103 tests/cli/cli-account-preservation.test.ts -65 tests/cli/cli-account-slot-identity.test.ts -81 tests/cli/cli-account-threshold.test.ts -31 tests/cli/cli-account-verify-status.test.ts -542 tests/cli/cli-account.test.ts -163 tests/cli/cli-agent-runtime-settings.test.ts -199 tests/cli/cli-agent-settings.test.ts -104 tests/cli/cli-alias-json.test.ts -63 tests/cli/cli-anthropic-account-threshold.test.ts -132 tests/cli/cli-anthropic2-account.test.ts -104 tests/cli/cli-api-protocols.test.ts -154 tests/cli/cli-aside-sync.test.ts -116 tests/cli/cli-capabilities-arguments.test.ts -87 tests/cli/cli-capabilities.test.ts -180 tests/cli/cli-capability-access-workflows.test.ts -114 tests/cli/cli-capability-account-workflows.test.ts -92 tests/cli/cli-capability-agent-workflows.test.ts -2146 tests/cli/cli-capability-data.test.ts -103 tests/cli/cli-capability-integration-workflows.test.ts -211 tests/cli/cli-capability-lab-workflows.test.ts -176 tests/cli/cli-capability-operation-workflows.test.ts -67 tests/cli/cli-capability-provider-workflows.test.ts -121 tests/cli/cli-catalog-command-result.test.ts -34 tests/cli/cli-catalog-prewarm.test.ts -388 tests/cli/cli-claude-desktop-profile.test.ts -136 tests/cli/cli-client-start-fence.test.ts -2415 tests/cli/cli-client-start-owner-e2e.test.ts -6778 tests/cli/cli-codex-cli-update-boundary.test.ts -479 tests/cli/cli-codex-cli-update.test.ts -71 tests/cli/cli-codex-log-guard-compact.test.ts -73 tests/cli/cli-codex-log-guard-protection.test.ts -94 tests/cli/cli-codex-log-guard.test.ts -136 tests/cli/cli-combo-parity.test.ts -62 tests/cli/cli-combo-partial-update.test.ts -134 tests/cli/cli-combo-session-pin.test.ts -119 tests/cli/cli-combo-set-targets.test.ts -139 tests/cli/cli-combo-stats.test.ts -271 tests/cli/cli-companion-timeline.test.ts -82 tests/cli/cli-companion-usage.test.ts -101 tests/cli/cli-companion.test.ts -564 tests/cli/cli-config-bom.test.ts -7125 tests/cli/cli-config-command.test.ts -1376 tests/cli/cli-config-default-show.test.ts -2197 tests/cli/cli-config-show-client.test.ts -7349 tests/cli/cli-connect-readiness.test.ts -77 tests/cli/cli-dispatch.test.ts -113 tests/cli/cli-dto-fidelity.test.ts -101 tests/cli/cli-effort-slug.test.ts -260 tests/cli/cli-effort.test.ts -104 tests/cli/cli-ensure-client-state.test.ts -159 tests/cli/cli-ensure-desktop-cold-start.test.ts -74 tests/cli/cli-ensure-readiness.test.ts -465 tests/cli/cli-export-command.test.ts -158 tests/cli/cli-export-model-names.test.ts -200 tests/cli/cli-fallback.test.ts -49 tests/cli/cli-head.test.ts -270 tests/cli/cli-headless-parity.test.ts -2185 tests/cli/cli-help-navigation.test.ts -13366 tests/cli/cli-help-paths.test.ts -4994 tests/cli/cli-help-recovery.test.ts -10523 tests/cli/cli-help.test.ts -1041 tests/cli/cli-init-port.test.ts -111 tests/cli/cli-injection-follow.test.ts -99 tests/cli/cli-integer-options.test.ts -83 tests/cli/cli-integration-cursor.test.ts -83 tests/cli/cli-integration-droid.test.ts -182 tests/cli/cli-integration-journal.test.ts -785 tests/cli/cli-integration-preview.test.ts -139 tests/cli/cli-json-contract.test.ts -284 tests/cli/cli-json-input.test.ts -77 tests/cli/cli-kiro-auto-selection.test.ts -239 tests/cli/cli-link-child.test.ts -111 tests/cli/cli-link-cleanup.test.ts -43 tests/cli/cli-link-enrollment.test.ts -589 tests/cli/cli-link-force.test.ts -110 tests/cli/cli-link.test.ts -271 tests/cli/cli-log-follow.test.ts -119 tests/cli/cli-log-history.test.ts -377 tests/cli/cli-log-view-filter.test.ts -76 tests/cli/cli-logout-runtime.test.ts -58 tests/cli/cli-logs-request-id.test.ts -74 tests/cli/cli-management-auth.test.ts -1467 tests/cli/cli-message-mcp.test.ts -188 tests/cli/cli-models-custom-runtime.test.ts -173 tests/cli/cli-models-display-name.test.ts -57 tests/cli/cli-models-free-only.test.ts -205 tests/cli/cli-models-local-result.test.ts -104 tests/cli/cli-models-order.test.ts -94 tests/cli/cli-models-price.test.ts -123 tests/cli/cli-models-prompt-length-pricing.test.ts -446 tests/cli/cli-models-reasoning.test.ts -172 tests/cli/cli-models-runtime-dispatch.test.ts -108 tests/cli/cli-models-set.test.ts -20551 tests/cli/cli-models.test.ts -124 tests/cli/cli-native-profile.test.ts -111 tests/cli/cli-observe-logs.test.ts -109 tests/cli/cli-observe-snapshot.test.ts -104 tests/cli/cli-path-diagnostics.test.ts -221 tests/cli/cli-provider-batch.test.ts -39 tests/cli/cli-provider-cc-switch-import.test.ts -184 tests/cli/cli-provider-lifecycle-runtime.test.ts -1789 tests/cli/cli-provider-list-active.test.ts -62 tests/cli/cli-provider-result.test.ts -191 tests/cli/cli-provider-settings.test.ts -445 tests/cli/cli-provider-sync-result.test.ts -20692 tests/cli/cli-provider.test.ts -1290 tests/cli/cli-ready-subprocess.test.ts -35 tests/cli/cli-ready.test.ts -78 tests/cli/cli-registry.test.ts -126 tests/cli/cli-remote-workspace-hub.test.ts -2393 tests/cli/cli-resolve-subprocess.test.ts +1055 tests/adapters/anthropic/anthropic-subscription-chain.test.ts +57 tests/adapters/anthropic/anthropic-tail-guard.test.ts +135 tests/adapters/anthropic/anthropic-thinking-display-policy.test.ts +243 tests/adapters/anthropic/anthropic-thinking-signature.test.ts +95 tests/adapters/anthropic/anthropic-thinking-usage.test.ts +51 tests/adapters/anthropic/anthropic-tool-call-id.test.ts +144 tests/adapters/anthropic/anthropic-tool-declaration-constraints.test.ts +69 tests/adapters/anthropic/anthropic-tool-schema.test.ts +636 tests/adapters/anthropic/anthropic2-fast-parity.test.ts +121 tests/adapters/bridge-legacy-shell-normalization.test.ts +3564 tests/adapters/bridge-lifecycle.test.ts +748 tests/adapters/bridge-nonstreaming-terminal.test.ts +77 tests/adapters/bridge-raw-reasoning-hidden.test.ts +96 tests/adapters/bridge-reasoning-replay-batch.test.ts +107 tests/adapters/bridge-stall.test.ts +61 tests/adapters/bridge-terminal-refusal.test.ts +69 tests/adapters/bridge-terminal-singleness.test.ts +228 tests/adapters/bridge.test.ts +154 tests/adapters/buffered-response-shape-guards.test.ts +205 tests/adapters/coding-agent-history-projection.test.ts +49 tests/adapters/coding-agent-tool-result-images.test.ts +96 tests/adapters/coding-agent-windows-dispatch.test.ts +84 tests/adapters/dsh-account-adapter.test.ts +490 tests/adapters/empty-tool-output-annotation.test.ts +177 tests/adapters/exec-tool-result-normalize.test.ts +211 tests/adapters/fix-tool-number-preservation.test.ts +156 tests/adapters/google/antigravity-account-roster.test.ts +116 tests/adapters/google/antigravity-baseurl-override.test.ts +119 tests/adapters/google/antigravity-discovered-families.test.ts +43 tests/adapters/google/antigravity-refusal.test.ts +525 tests/adapters/google/antigravity-routing-carry.test.ts +102 tests/adapters/google/antigravity-static-catalog.test.ts +5634 tests/adapters/google/gcp-adc.test.ts +1125 tests/adapters/google/gcp-credential-boundary.test.ts +387 tests/adapters/google/gcp-sa-adapter.test.ts +824 tests/adapters/google/gcp-sa-marker.test.ts +117 tests/adapters/google/gemini-37-flash-migration.test.ts +113 tests/adapters/google/gemini-4-argon-antigravity.test.ts +128 tests/adapters/google/gemini-4-hydrogen-antigravity.test.ts +71 tests/adapters/google/gemini-progress-history.test.ts +131 tests/adapters/google/gemini-web-search.test.ts +56 tests/adapters/google/google-429-retry-evidence.test.ts +201 tests/adapters/google/google-adapter.test.ts +130 tests/adapters/google/google-ai-studio-foreign-call-signature.test.ts +4177 tests/adapters/google/google-antigravity-oauth.test.ts +2390 tests/adapters/google/google-antigravity-replay.test.ts +113 tests/adapters/google/google-antigravity-wire.test.ts +102 tests/adapters/google/google-buffered-stop-reason.test.ts +77 tests/adapters/google/google-claude-prefill-guard.test.ts +86 tests/adapters/google/google-empty-content.test.ts +38 tests/adapters/google/google-errors.test.ts +102 tests/adapters/google/google-hardening.test.ts +143 tests/adapters/google/google-models-listing.test.ts +103 tests/adapters/google/google-output-clamp.test.ts +65 tests/adapters/google/google-provider-metadata-roundtrip.test.ts +159 tests/adapters/google/google-signature-history-roundtrip.test.ts +105 tests/adapters/google/google-stream-fragmentation.test.ts +99 tests/adapters/google/google-strict-tool-validated-mode.test.ts +112 tests/adapters/google/google-structured-output.test.ts +143 tests/adapters/google/google-tool-result-adjacency.test.ts +117 tests/adapters/google/google-tool-schema-contract.test.ts +77 tests/adapters/google/google-tool-schema.test.ts +4693 tests/adapters/google/google-vertex-http.test.ts +149 tests/adapters/google/google-vertex-key-project.test.ts +116 tests/adapters/google/google-vertex-stream.test.ts +124 tests/adapters/google/google-vertex-thought-signature.test.ts +91 tests/adapters/google/google-wire-compiler.test.ts +102 tests/adapters/google/google-wire-shape.test.ts +189 tests/adapters/google/vertex-adc-verified.test.ts +145 tests/adapters/google/vertex-catalog.test.ts +318 tests/adapters/google/vertex-model-discovery.test.ts +253 tests/adapters/identity-neutralize.test.ts +409 tests/adapters/identity-subagent.test.ts +578 tests/adapters/key-failover.test.ts +91 tests/adapters/openai/inline-think-boundaries.test.ts +2145 tests/adapters/openai/openai-api-virtual-models.test.ts +95 tests/adapters/openai/openai-chat-audio.test.ts +241 tests/adapters/openai/openai-chat-bounded-tool-names.test.ts +58 tests/adapters/openai/openai-chat-dangling-toolcalls.test.ts +109 tests/adapters/openai/openai-chat-developer-position.test.ts +87 tests/adapters/openai/openai-chat-eof.test.ts +99 tests/adapters/openai/openai-chat-glm-summary.test.ts +363 tests/adapters/openai/openai-chat-hardening.test.ts +4962 tests/adapters/openai/openai-chat-image-normalization.test.ts +83 tests/adapters/openai/openai-chat-inline-think-tags.test.ts +68 tests/adapters/openai/openai-chat-invalid-tool-call-diagnostics.test.ts +96 tests/adapters/openai/openai-chat-mistral-content.test.ts +88 tests/adapters/openai/openai-chat-mistral-policy.test.ts +215 tests/adapters/openai/openai-chat-model-suffix.test.ts +524 tests/adapters/openai/openai-chat-native-policy.test.ts +115 tests/adapters/openai/openai-chat-nonce-tool-call-content.test.ts +121 tests/adapters/openai/openai-chat-parallel-stream.test.ts +139 tests/adapters/openai/openai-chat-path-override.test.ts +65 tests/adapters/openai/openai-chat-qwen38-leading-system.test.ts +156 tests/adapters/openai/openai-chat-reasoning-wire-policy.test.ts +89 tests/adapters/openai/openai-chat-required-tool.test.ts +151 tests/adapters/openai/openai-chat-sanitization-review-regressions.test.ts +94 tests/adapters/openai/openai-chat-serialized-tool-call-content.test.ts +243 tests/adapters/openai/openai-chat-serialized-tool-call-hold-bound.test.ts +156 tests/adapters/openai/openai-chat-serialized-tool-call-scaling.test.ts +68 tests/adapters/openai/openai-chat-serialized-tool-call-think.test.ts +69 tests/adapters/openai/openai-chat-single-system.test.ts +391 tests/adapters/openai/openai-chat-standalone-bare-block.test.ts +163 tests/adapters/openai/openai-chat-system-order.test.ts +59 tests/adapters/openai/openai-chat-tool-call-id-remint.test.ts +67 tests/adapters/openai/openai-chat-tool-result-images.test.ts +69 tests/adapters/openai/openai-chat-url.test.ts +99 tests/adapters/openai/openai-chat-video-part.test.ts +194 tests/adapters/openai/openai-empty-assistant-history.test.ts +387 tests/adapters/openai/openai-native-hosted-search-history.test.ts +1251 tests/adapters/openai/openai-provider-option-e2e.test.ts +499 tests/adapters/openai/openai-provider-option-migration.test.ts +93 tests/adapters/openai/openai-provider-option-startup.test.ts +80 tests/adapters/openai/openai-provider-option-tooling.test.ts +70 tests/adapters/openai/openai-provider-option.test.ts +57 tests/adapters/openai/opengateway-input.test.ts +95 tests/adapters/physical-send.test.ts +133 tests/adapters/qoder-spawn-readmission.test.ts +67 tests/adapters/reasoning-replay-identity.test.ts +178 tests/adapters/reasoning-replay-robustness.test.ts +157 tests/adapters/routed-agent-messages.test.ts +169 tests/adapters/run-turn-queue.test.ts +378 tests/adapters/terminal-continuation-owner-rotation.test.ts +110 tests/adapters/tool-argument-integers.test.ts +50 tests/adapters/tool-catalog-nudge.test.ts +62 tests/adapters/tool-choice-performance.test.ts +247 tests/adapters/tool-envelope-echo-whole-line.test.ts +70 tests/adapters/tool-identity-hash.test.ts +206 tests/adapters/translator-budget-lifetime.test.ts +8667 tests/adapters/translator-budget.test.ts +50 tests/adapters/upstream-http-error.test.ts +65 tests/adapters/workbuddy-adapter.test.ts +142 tests/advisor/advisor-adaptive.test.ts +90 tests/advisor/advisor-authority-transport.test.ts +73 tests/advisor/advisor-budget.test.ts +569 tests/advisor/advisor-caller-policy-compact.test.ts +383 tests/advisor/advisor-caller-policy-host-key.test.ts +411 tests/advisor/advisor-caller-policy-http.test.ts +283 tests/advisor/advisor-caller-policy-ingress.test.ts +329 tests/advisor/advisor-caller-policy-jev.test.ts +314 tests/advisor/advisor-caller-policy-replay.test.ts +529 tests/advisor/advisor-caller-policy-routing.test.ts +480 tests/advisor/advisor-caller-policy-self-fetch.test.ts +376 tests/advisor/advisor-caller-policy-sidecar-authority.test.ts +349 tests/advisor/advisor-caller-policy-vision.test.ts +670 tests/advisor/advisor-caller-policy.test.ts +73 tests/advisor/advisor-consult.test.ts +101 tests/advisor/advisor-context.test.ts +62 tests/advisor/advisor-continuation-limit.test.ts +436 tests/advisor/advisor-core-boundary.test.ts +66 tests/advisor/advisor-evidence.test.ts +185 tests/advisor/advisor-guard.test.ts +196 tests/advisor/advisor-internal-authority.test.ts +454 tests/advisor/advisor-messages-replay-config.test.ts +92 tests/advisor/advisor-plan.test.ts +1609 tests/advisor/advisor-responses-wiring.test.ts +371 tests/advisor/advisor-retention.test.ts +372 tests/advisor/advisor-scope-transport.test.ts +154 tests/advisor/advisor-settings.test.ts +107 tests/advisor/advisor-state.test.ts +296 tests/advisor/advisor-web-search.test.ts +3219 tests/ci-workflows/assert-mergeable-review.test.ts +58 tests/ci-workflows/audit-exceptions.test.ts +60 tests/ci-workflows/brand-favicons.test.ts +51 tests/ci-workflows/build-desktop-icon-set.test.ts +162 tests/ci-workflows/build-release-changelog.test.ts +197 tests/ci-workflows/bump-dev-version.test.ts +172 tests/ci-workflows/bun-runtime.test.ts +51 tests/ci-workflows/ci-bun-crash-classifier.test.ts +36410 tests/ci-workflows/ci-bun-install-frozen.test.ts +83 tests/ci-workflows/ci-concurrency-groups.test.ts +6308 tests/ci-workflows/ci-crash-disposition.test.ts +1694 tests/ci-workflows/ci-gui-typecheck-gate.test.ts +109 tests/ci-workflows/ci-pr-hygiene-approvals.test.ts +906 tests/ci-workflows/ci-privacy-gate.test.ts +6044 tests/ci-workflows/ci-review-lanes.test.ts +715 tests/ci-workflows/ci-scope-gaps.test.ts +564 tests/ci-workflows/ci-scope-reduction.test.ts +1207 tests/ci-workflows/ci-shard-balance.test.ts +75 tests/ci-workflows/ci-structure-gate.test.ts +1902 tests/ci-workflows/ci-test-lane.test.ts +1229 tests/ci-workflows/ci-workflows.test.ts +54 tests/ci-workflows/cleanup-orphaned-workflows.test.ts +275 tests/ci-workflows/client-support-matrix.test.ts +1462 tests/ci-workflows/client-support-runtime.test.ts +58 tests/ci-workflows/closed-pr-branch-cleanup.test.ts +467 tests/ci-workflows/codex-home-sandbox.test.ts +6645 tests/ci-workflows/cold-spawn-warmup.test.ts +260 tests/ci-workflows/compatibility-version.test.ts +69 tests/ci-workflows/docs-429-failover-claims.test.ts +46 tests/ci-workflows/docs-bun-source-requirement.test.ts +107 tests/ci-workflows/docs-developer-role-policy.test.ts +61 tests/ci-workflows/docs-gjc-reasoning-export.test.ts +116 tests/ci-workflows/docs-gpt61-terra.test.ts +49 tests/ci-workflows/docs-gui-screenshot-policy.test.ts +358 tests/ci-workflows/docs-link-targets.test.ts +52 tests/ci-workflows/docs-navigation-label.test.ts +51 tests/ci-workflows/docs-provider-billing-claims.test.ts +80 tests/ci-workflows/docs-provider-discovery-limits.test.ts +65 tests/ci-workflows/docs-provider-preset-counts.test.ts +140 tests/ci-workflows/docs-readme-memory-inventory.test.ts +71 tests/ci-workflows/docs-readme-translation-parity.test.ts +89 tests/ci-workflows/docs-remote-hub-claims.test.ts +434 tests/ci-workflows/docs-spanish-localization.test.ts +204 tests/ci-workflows/docs-telemetry-dashboard.test.ts +196 tests/ci-workflows/docs-telemetry-leaderboard.test.ts +199 tests/ci-workflows/dsh-path-contract.test.ts +303 tests/ci-workflows/dsh-rc6-compat-script.test.ts +210 tests/ci-workflows/dsh-writer-lock.test.ts +96 tests/ci-workflows/exhaustive-deps-suppression.test.ts +706 tests/ci-workflows/file-size-ratchet.test.ts +614 tests/ci-workflows/fixture-dir-uniqueness.test.ts +69 tests/ci-workflows/fixture-teardown-helper.test.ts +606 tests/ci-workflows/fixture-windows-runtime-preload.test.ts +586 tests/ci-workflows/import-cycle-ratchet.test.ts +283 tests/ci-workflows/install-scripts.test.ts +59 tests/ci-workflows/installed-gate-drivers.test.ts +60 tests/ci-workflows/keyring-smoke.test.ts +117 tests/ci-workflows/linux-desktop-packaged-ci.test.ts +50 tests/ci-workflows/linux-desktop-packaged-e2e.test.ts +4674 tests/ci-workflows/macos-serial-lanes.test.ts +2810 tests/ci-workflows/package-tree-fenced-restart.test.ts +3360 tests/ci-workflows/package-tree-integrity.test.ts +132 tests/ci-workflows/package-tree-restart-ownership.test.ts +214 tests/ci-workflows/package-tree-retarget.test.ts +57 tests/ci-workflows/pr-gates-workflow.test.ts +104 tests/ci-workflows/pr-readiness-reattest.test.ts +54 tests/ci-workflows/privacy-scan-asset-names.test.ts +61 tests/ci-workflows/privacy-scan-meta-key.test.ts +70 tests/ci-workflows/privacy-scan-ssh-endpoint.test.ts +131 tests/ci-workflows/release-desktop-scripts.test.ts +2075 tests/ci-workflows/release-helper.test.ts +66 tests/ci-workflows/release-notes.test.ts +137 tests/ci-workflows/release-outcome-report.test.ts +4572 tests/ci-workflows/release-pipeline-contract.test.ts +3454 tests/ci-workflows/release-preflight.test.ts +2039 tests/ci-workflows/release-resume-identity.test.ts +49 tests/ci-workflows/release-version-line.test.ts +349 tests/ci-workflows/release-version-sources.test.ts +276 tests/ci-workflows/release-windows-signing-outcome.test.ts +18532 tests/ci-workflows/release-windows-signing.test.ts +279 tests/ci-workflows/repo-hygiene.test.ts +505 tests/ci-workflows/repo-import-resolution.test.ts +440 tests/ci-workflows/setup-hooks.test.ts +654 tests/ci-workflows/skill-ocx-generated.test.ts +164 tests/ci-workflows/skill-ocx-workflows.test.ts +152 tests/ci-workflows/skill-ocx.test.ts +672 tests/ci-workflows/structure-ssot.test.ts +722 tests/ci-workflows/test-git-isolation.test.ts +940 tests/ci-workflows/test-home-guard-unpreloaded.test.ts +42296 tests/ci-workflows/test-home-guard.test.ts +100 tests/ci-workflows/test-network-egress-guard.test.ts +21476 tests/ci-workflows/test-run-lock-generation.test.ts +199 tests/ci-workflows/test-runner-bun.test.ts +400 tests/ci-workflows/test-runner-spawnsync-finalizer.test.ts +18166 tests/ci-workflows/test-runner.test.ts +62 tests/ci-workflows/test-sandbox-cleanup.test.ts +57 tests/ci-workflows/test-temp-quarantine.test.ts +66 tests/ci-workflows/version-line.test.ts +82 tests/ci-workflows/warmup-registration.test.ts +60 tests/ci-workflows/zz-ci-api-usage-isolation.test.ts +70 tests/ci-workflows/zz-ci-storage-policy-isolation.test.ts +94 tests/ci-workflows/zz-pr-coderabbit-readiness-revalidation.test.ts +2335 tests/claude-integration/anthropic2-native-routing.test.ts +3083 tests/claude-integration/claude-529-mapping.test.ts +180 tests/claude-integration/claude-agent-startup-sync.test.ts +162 tests/claude-integration/claude-agents-inject-client.test.ts +149 tests/claude-integration/claude-agents-inject.test.ts +97 tests/claude-integration/claude-alias.test.ts +63 tests/claude-integration/claude-auth-detect.test.ts +108 tests/claude-integration/claude-auth-mode.test.ts +50 tests/claude-integration/claude-authmode-migration.test.ts +790 tests/claude-integration/claude-bridge-pool-dispatch.test.ts +201 tests/claude-integration/claude-bridge-pool-session.test.ts +654 tests/claude-integration/claude-chat-tool-dispatch-routes.test.ts +536 tests/claude-integration/claude-chat-tool-dispatch.test.ts +461 tests/claude-integration/claude-cli-picker-surface.test.ts +602 tests/claude-integration/claude-cli-picker.test.ts +133 tests/claude-integration/claude-cli.test.ts +1152 tests/claude-integration/claude-client-refusal-status.test.ts +229 tests/claude-integration/claude-code-thought-signature-scope.test.ts +59 tests/claude-integration/claude-compatibility.test.ts +386 tests/claude-integration/claude-config-home-isolation.test.ts +797 tests/claude-integration/claude-config-root-late-admission.test.ts +533 tests/claude-integration/claude-config-root-stale-updates.test.ts +563 tests/claude-integration/claude-config-root-writer-barrier.test.ts +216 tests/claude-integration/claude-context-accounting.test.ts +121 tests/claude-integration/claude-context-windows.test.ts +155 tests/claude-integration/claude-desktop-1m.test.ts +865 tests/claude-integration/claude-desktop-cli.test.ts +621 tests/claude-integration/claude-desktop-config-path.test.ts +1099 tests/claude-integration/claude-desktop-discovery.test.ts +567 tests/claude-integration/claude-desktop-first-party-guards.test.ts +1062 tests/claude-integration/claude-desktop-first-party.test.ts +159 tests/claude-integration/claude-desktop-mode-explanation.test.ts +740 tests/claude-integration/claude-desktop-model-visibility.test.ts +128 tests/claude-integration/claude-desktop-native-context.test.ts +553 tests/claude-integration/claude-desktop-picker-profile.test.ts +567 tests/claude-integration/claude-desktop-picker-routes.test.ts +151 tests/claude-integration/claude-desktop-picker.test.ts +73 tests/claude-integration/claude-desktop-policy.test.ts +7887 tests/claude-integration/claude-desktop-remote-hub.test.ts +164 tests/claude-integration/claude-desktop-system-proxy.test.ts +546 tests/claude-integration/claude-devin-output-order.test.ts +190 tests/claude-integration/claude-dotenv-provenance-transport.test.ts +424 tests/claude-integration/claude-endpoint-lifetime.test.ts +578 tests/claude-integration/claude-estimate-projection.test.ts +517 tests/claude-integration/claude-first-party-agent-sync.test.ts +161 tests/claude-integration/claude-first-party-union.test.ts +63 tests/claude-integration/claude-gateway-cache.test.ts +522 tests/claude-integration/claude-gateway-output-cap.test.ts +400 tests/claude-integration/claude-inbound-cache-stabilize.test.ts +75 tests/claude-integration/claude-inbound-debug.test.ts +141 tests/claude-integration/claude-inbound-token-footer.test.ts +588 tests/claude-integration/claude-inbound-tool-loading.test.ts +106 tests/claude-integration/claude-inbound-tool-reference.test.ts +292 tests/claude-integration/claude-inbound.test.ts +343 tests/claude-integration/claude-installation-helper.test.ts +410 tests/claude-integration/claude-intercept-acl-barrier.test.ts +104 tests/claude-integration/claude-intercept-cleanup.test.ts +180 tests/claude-integration/claude-intercept-client-class.test.ts +129 tests/claude-integration/claude-intercept-local-ca-files.test.ts +185 tests/claude-integration/claude-intercept-local-ca-windows.test.ts +187 tests/claude-integration/claude-intercept-local-ca.test.ts +232 tests/claude-integration/claude-intercept-model-bindings.test.ts +166 tests/claude-integration/claude-intercept-no-proxy.test.ts +418 tests/claude-integration/claude-intercept-on-demand.test.ts +159 tests/claude-integration/claude-intercept-proxy-auth.test.ts +155 tests/claude-integration/claude-intercept-proxy.test.ts +170 tests/claude-integration/claude-intercept-settings.test.ts +2544 tests/claude-integration/claude-keychain-healthz.test.ts +129 tests/claude-integration/claude-long-context-eligibility.test.ts +6522 tests/claude-integration/claude-management-api.test.ts +6157 tests/claude-integration/claude-messages-endpoint.test.ts +524 tests/claude-integration/claude-messages-thread.test.ts +154 tests/claude-integration/claude-model-default-labels.test.ts +128 tests/claude-integration/claude-model-info.test.ts +1728 tests/claude-integration/claude-models-discovery.test.ts +586 tests/claude-integration/claude-native-affinity.test.ts +562 tests/claude-integration/claude-native-fast-1m-ingress.test.ts +9452 tests/claude-integration/claude-native-passthrough.test.ts +171 tests/claude-integration/claude-native-rate-limit-headers.test.ts +125 tests/claude-integration/claude-native-reasoning-continuity.test.ts +405 tests/claude-integration/claude-native-reasoning-provenance.test.ts +2518 tests/claude-integration/claude-outbound.test.ts +162 tests/claude-integration/claude-output-schema-strict.test.ts +254 tests/claude-integration/claude-picker-bootstrap.test.ts +479 tests/claude-integration/claude-picker-ca-store.test.ts +522 tests/claude-integration/claude-picker-ca.test.ts +113 tests/claude-integration/claude-picker-linger.test.ts +676 tests/claude-integration/claude-picker-listener.test.ts +119 tests/claude-integration/claude-picker-models.test.ts +1086 tests/claude-integration/claude-picker-recovery.test.ts +227 tests/claude-integration/claude-picker-relay-intent.test.ts +567 tests/claude-integration/claude-picker-runtime.test.ts +1618 tests/claude-integration/claude-picker-startup.test.ts +1297 tests/claude-integration/claude-picker-trust-linux.test.ts +81 tests/claude-integration/claude-picker-trust-windows.test.ts +80 tests/claude-integration/claude-picker-trust.test.ts +4150 tests/claude-integration/claude-picker-upload.test.ts +714 tests/claude-integration/claude-picker-windows.test.ts +2091 tests/claude-integration/claude-prompt-too-long.test.ts +185 tests/claude-integration/claude-shell-hook.test.ts +241 tests/claude-integration/claude-sidecar-override.test.ts +110 tests/claude-integration/claude-source-envelope.test.ts +220 tests/claude-integration/claude-subagent-model-force.test.ts +144 tests/claude-integration/claude-system-env-auto.test.ts +803 tests/claude-integration/claude-tool-loading-destinations.test.ts +1415 tests/claude-integration/claude-translated-advisor-tool.test.ts +417 tests/claude-integration/claude-translated-cache-ttl.test.ts +665 tests/claude-integration/claude-translated-hosted-advisor-choice.test.ts +725 tests/claude-integration/claude-translated-server-tools.test.ts +372 tests/claude-integration/claude-translated-tool-restrictions.test.ts +250 tests/claude-integration/claude-uncoded-context-overflow.test.ts +229 tests/claude-integration/messages-error-contracts.test.ts +1695 tests/claude-integration/messages-error-normalization.test.ts +101 tests/claude-integration/messages-header-normalization.test.ts +556 tests/claude-integration/messages-lane-errors.test.ts +400 tests/claude-integration/messages-native-clean-eof.test.ts +140 tests/claude-integration/messages-native-combo-framing.test.ts +1637 tests/claude-integration/messages-native-combo.test.ts +217 tests/claude-integration/messages-native-decline-trace.test.ts +665 tests/claude-integration/messages-native-empty-inline.test.ts +919 tests/claude-integration/messages-native-key-selection.test.ts +2973 tests/claude-integration/messages-native-oauth.test.ts +418 tests/claude-integration/messages-native-opaque-state.test.ts +850 tests/claude-integration/messages-native-scope.test.ts +2762 tests/claude-integration/messages-native-stream-parity.test.ts +3040 tests/claude-integration/messages-native.test.ts +685 tests/claude-integration/messages-overflow-baseline-contract.test.ts +19273 tests/claude-integration/messages-overflow-builtin.test.ts +6646 tests/claude-integration/messages-overflow-collectors.test.ts +14062 tests/claude-integration/messages-overflow-native.test.ts +6927 tests/claude-integration/messages-overflow-stream.test.ts +19676 tests/claude-integration/messages-overflow-translated.test.ts +13022 tests/claude-integration/messages-overflow-verdicts.test.ts +20577 tests/claude-integration/messages-proxy-refusals.test.ts +3221 tests/claude-integration/messages-request-id-endpoint.test.ts +233 tests/claude-integration/messages-request-id-headers.test.ts +2343 tests/claude-integration/messages-review-regressions.test.ts +1562 tests/claude-integration/messages-revoked-token.test.ts +329 tests/claude-integration/messages-shared-sse.test.ts +126 tests/claude-integration/messages-sse-baseline-contract.test.ts +7004 tests/claude-integration/messages-sse-builtin-errors.test.ts +4287 tests/claude-integration/messages-sse-continuation.test.ts +1448 tests/claude-integration/messages-sse-control-fields.test.ts +5454 tests/claude-integration/messages-sse-count-tokens-errors.test.ts +67 tests/claude-integration/messages-sse-delivery.test.ts +770 tests/claude-integration/messages-sse-fold-errors.test.ts +59 tests/claude-integration/messages-sse-guard-errors.test.ts +5794 tests/claude-integration/messages-sse-native-errors.test.ts +5704 tests/claude-integration/messages-sse-passthrough-errors.test.ts +3734 tests/claude-integration/messages-sse-tap-tails.test.ts +1875 tests/claude-integration/messages-sse-workflow-refusal.test.ts +271 tests/claude-integration/messages-success-media-types.test.ts +369 tests/claude-integration/messages-surface-matrix.test.ts +56 tests/cli/agent-driven.test.ts +90 tests/cli/agent-subagent-force.test.ts +888 tests/cli/bun-transpiler-cache-scope.test.ts +88 tests/cli/claude-config-first-party.test.ts +15209 tests/cli/cli-access-audio-live.test.ts +378 tests/cli/cli-access-audio.test.ts +134 tests/cli/cli-access-data-plane.test.ts +124 tests/cli/cli-access-key-guard.test.ts +196 tests/cli/cli-access-rename.test.ts +98 tests/cli/cli-account-alias-target.test.ts +117 tests/cli/cli-account-cancel-flow.test.ts +103 tests/cli/cli-account-key-pause.test.ts +220 tests/cli/cli-account-key-quota.test.ts +89 tests/cli/cli-account-kiro-device.test.ts +2389 tests/cli/cli-account-login-options.test.ts +53 tests/cli/cli-account-orca-import.test.ts +107 tests/cli/cli-account-pin-drain.test.ts +610 tests/cli/cli-account-policy.test.ts +105 tests/cli/cli-account-pool-verbs.test.ts +93 tests/cli/cli-account-preservation.test.ts +86 tests/cli/cli-account-slot-identity.test.ts +152 tests/cli/cli-account-threshold.test.ts +105 tests/cli/cli-account-verify-status.test.ts +653 tests/cli/cli-account.test.ts +171 tests/cli/cli-agent-runtime-settings.test.ts +327 tests/cli/cli-agent-settings.test.ts +148 tests/cli/cli-alias-json.test.ts +85 tests/cli/cli-anthropic-account-threshold.test.ts +109 tests/cli/cli-anthropic2-account.test.ts +169 tests/cli/cli-api-protocols.test.ts +122 tests/cli/cli-aside-sync.test.ts +165 tests/cli/cli-capabilities-arguments.test.ts +153 tests/cli/cli-capabilities.test.ts +107 tests/cli/cli-capability-access-workflows.test.ts +160 tests/cli/cli-capability-account-workflows.test.ts +203 tests/cli/cli-capability-agent-workflows.test.ts +2354 tests/cli/cli-capability-data.test.ts +210 tests/cli/cli-capability-integration-workflows.test.ts +269 tests/cli/cli-capability-lab-workflows.test.ts +128 tests/cli/cli-capability-operation-workflows.test.ts +118 tests/cli/cli-capability-provider-workflows.test.ts +127 tests/cli/cli-catalog-command-result.test.ts +59 tests/cli/cli-catalog-prewarm.test.ts +421 tests/cli/cli-claude-desktop-profile.test.ts +158 tests/cli/cli-client-start-fence.test.ts +3730 tests/cli/cli-client-start-owner-e2e.test.ts +8452 tests/cli/cli-codex-cli-update-boundary.test.ts +683 tests/cli/cli-codex-cli-update.test.ts +156 tests/cli/cli-codex-log-guard-compact.test.ts +167 tests/cli/cli-codex-log-guard-protection.test.ts +177 tests/cli/cli-codex-log-guard.test.ts +207 tests/cli/cli-combo-parity.test.ts +128 tests/cli/cli-combo-partial-update.test.ts +211 tests/cli/cli-combo-session-pin.test.ts +199 tests/cli/cli-combo-set-targets.test.ts +191 tests/cli/cli-combo-stats.test.ts +127 tests/cli/cli-companion-timeline.test.ts +118 tests/cli/cli-companion-usage.test.ts +108 tests/cli/cli-companion.test.ts +865 tests/cli/cli-config-bom.test.ts +17024 tests/cli/cli-config-command.test.ts +1828 tests/cli/cli-config-default-show.test.ts +3173 tests/cli/cli-config-show-client.test.ts +6387 tests/cli/cli-connect-readiness.test.ts +333 tests/cli/cli-dispatch.test.ts +171 tests/cli/cli-dto-fidelity.test.ts +121 tests/cli/cli-effort-slug.test.ts +232 tests/cli/cli-effort.test.ts +143 tests/cli/cli-ensure-client-state.test.ts +150 tests/cli/cli-ensure-desktop-cold-start.test.ts +67 tests/cli/cli-ensure-readiness.test.ts +830 tests/cli/cli-export-command.test.ts +150 tests/cli/cli-export-model-names.test.ts +86 tests/cli/cli-fallback.test.ts +72 tests/cli/cli-head.test.ts +402 tests/cli/cli-headless-parity.test.ts +3331 tests/cli/cli-help-navigation.test.ts +18717 tests/cli/cli-help-paths.test.ts +7514 tests/cli/cli-help-recovery.test.ts +14076 tests/cli/cli-help.test.ts +1449 tests/cli/cli-init-port.test.ts +133 tests/cli/cli-injection-follow.test.ts +98 tests/cli/cli-integer-options.test.ts +141 tests/cli/cli-integration-cursor.test.ts +107 tests/cli/cli-integration-droid.test.ts +440 tests/cli/cli-integration-journal.test.ts +438 tests/cli/cli-integration-preview.test.ts +148 tests/cli/cli-json-contract.test.ts +335 tests/cli/cli-json-input.test.ts +95 tests/cli/cli-kiro-auto-selection.test.ts +100 tests/cli/cli-link-activity.test.ts +167 tests/cli/cli-link-capture.test.ts +129 tests/cli/cli-link-check.test.ts +134 tests/cli/cli-link-child-ops.test.ts +288 tests/cli/cli-link-child.test.ts +108 tests/cli/cli-link-cleanup.test.ts +98 tests/cli/cli-link-diagnostics.test.ts +129 tests/cli/cli-link-enrollment.test.ts +99 tests/cli/cli-link-explicit-route.test.ts +285 tests/cli/cli-link-force.test.ts +114 tests/cli/cli-link-operation.test.ts +99 tests/cli/cli-link-policy.test.ts +118 tests/cli/cli-link-recover.test.ts +96 tests/cli/cli-link-route-intent.test.ts +90 tests/cli/cli-link-routes.test.ts +120 tests/cli/cli-link.test.ts +359 tests/cli/cli-log-follow.test.ts +110 tests/cli/cli-log-history.test.ts +368 tests/cli/cli-log-view-filter.test.ts +125 tests/cli/cli-logout-runtime.test.ts +92 tests/cli/cli-logs-request-id.test.ts +132 tests/cli/cli-management-auth.test.ts +1281 tests/cli/cli-message-mcp-resume.test.ts +3065 tests/cli/cli-message-mcp.test.ts +258 tests/cli/cli-models-custom-runtime.test.ts +183 tests/cli/cli-models-display-name.test.ts +107 tests/cli/cli-models-free-only.test.ts +243 tests/cli/cli-models-local-result.test.ts +133 tests/cli/cli-models-order.test.ts +137 tests/cli/cli-models-price.test.ts +100 tests/cli/cli-models-prompt-length-pricing.test.ts +159 tests/cli/cli-models-reasoning.test.ts +140 tests/cli/cli-models-runtime-dispatch.test.ts +189 tests/cli/cli-models-set.test.ts +28494 tests/cli/cli-models.test.ts +180 tests/cli/cli-native-profile.test.ts +106 tests/cli/cli-observe-logs.test.ts +97 tests/cli/cli-observe-snapshot.test.ts +65 tests/cli/cli-path-diagnostics.test.ts +302 tests/cli/cli-provider-batch.test.ts +90 tests/cli/cli-provider-cc-switch-import.test.ts +141 tests/cli/cli-provider-lifecycle-runtime.test.ts +2714 tests/cli/cli-provider-list-active.test.ts +90 tests/cli/cli-provider-result.test.ts +135 tests/cli/cli-provider-settings.test.ts +475 tests/cli/cli-provider-sync-result.test.ts +27646 tests/cli/cli-provider.test.ts +1474 tests/cli/cli-ready-subprocess.test.ts +59 tests/cli/cli-ready.test.ts +110 tests/cli/cli-registry.test.ts +199 tests/cli/cli-remote-workspace-hub.test.ts +3037 tests/cli/cli-resolve-subprocess.test.ts 92 tests/cli/cli-resolve.test.ts -121 tests/cli/cli-restart-handoff.test.ts -2500 tests/cli/cli-restart-health.test.ts -2000 tests/cli/cli-restore-back.test.ts -475 tests/cli/cli-role-suggestion-history.test.ts -104 tests/cli/cli-route-policy-not-found.test.ts -777 tests/cli/cli-route-policy-write.test.ts -2734 tests/cli/cli-start-auxiliary-bind.test.ts -14200 tests/cli/cli-start-journal-order.test.ts -2493 tests/cli/cli-start-owner-absence.test.ts -3245 tests/cli/cli-start-owner-evidence.test.ts -38 tests/cli/cli-start-routing-heal-wiring.test.ts -95 tests/cli/cli-status-codex-routing-drift.test.ts -2808 tests/cli/cli-status-hub-state.test.ts -11344 tests/cli/cli-status-json.test.ts -88 tests/cli/cli-status-oauth-health.test.ts -1763 tests/cli/cli-status-startup-health.test.ts -106 tests/cli/cli-stop-json.test.ts -429 tests/cli/cli-stop-refusal-transport.test.ts -181 tests/cli/cli-storage-inspect.test.ts -195 tests/cli/cli-storage-policy-fields.test.ts -251 tests/cli/cli-sync-expect-link.test.ts -183 tests/cli/cli-system-health.test.ts -126 tests/cli/cli-system-settings-parity.test.ts -77 tests/cli/cli-telemetry-profile.test.ts -123 tests/cli/cli-telemetry.test.ts -96 tests/cli/cli-transport-honesty.test.ts -997 tests/cli/cli-update-badge.test.ts -696 tests/cli/cli-update-restart-admission.test.ts -56 tests/cli/cli-update-restart-child.test.ts -84 tests/cli/cli-update-restart-desktop-service.test.ts -188 tests/cli/cli-update-restart-home.test.ts -53 tests/cli/cli-update-restart-service-record.test.ts -38 tests/cli/cli-update-restart-supervision.test.ts -536 tests/cli/cli-update-restart-transport.test.ts -213 tests/cli/cli-update-restart.test.ts -2740 tests/cli/cli-usage-compare.test.ts -98 tests/cli/cli-usage-hub.test.ts -117 tests/cli/cli-usage-model-search.test.ts -103 tests/cli/cli-usage-report.test.ts -178 tests/cli/cli-usage-scope.test.ts -758 tests/cli/cli-usage-top.test.ts -471 tests/cli/cli-v2-runtime.test.ts -9118 tests/cli/cli-version-skew.test.ts -251 tests/cli/cross-home-loopback-family.test.ts -52 tests/cli/ensure-desired-integrations-race.test.ts -810 tests/cli/hub-disable.test.ts -310 tests/cli/hub-gated-local-clients.test.ts -160 tests/cli/hub-invite.test.ts -51 tests/cli/interactive-confirm.test.ts -55 tests/cli/link-apply-restart.test.ts -116 tests/cli/local-credentials.test.ts -107 tests/cli/model-selection-guidance.test.ts -3518 tests/cli/ocx-launcher-desktop-handoff.test.ts -23 tests/cli/ocx-launcher-fixture-trust.test.ts -2552 tests/cli/ocx-launcher-runtime.test.ts -73 tests/cli/ocx-launcher-source.test.ts -90 tests/cli/ocx-run.test.ts -1084 tests/cli/restore-completes-shared-teardown.test.ts -795 tests/cli/route-explainability.test.ts -14590 tests/cli/sibling-home-client-sync.test.ts -71 tests/cli/star-deferral.test.ts -82 tests/cli/start-args.test.ts -35 tests/cli/start-ownership-publication.test.ts -410 tests/cli/status-install-method.test.ts -1785 tests/cli/sync-command-fanout.test.ts -2713 tests/cli/sync-fanout-process.test.ts -165 tests/cli/sync-fanout.test.ts -242 tests/cli/sync-link-status.test.ts -39 tests/cli/system-restart-client-package-tree.test.ts -41 tests/cli/system-restart-client.test.ts -464 tests/cli/uninstall.test.ts -169 tests/clients/agent-clients.test.ts -42 tests/clients/aside-profile-identity.test.ts -205 tests/clients/aside-profile-paths.test.ts -1450 tests/clients/aside-profile-sync-owner.test.ts -248 tests/clients/aside-profiles-catalog-refresh.test.ts -385 tests/clients/aside-profiles.test.ts -55 tests/clients/client-catalog-compatibility.test.ts -16303 tests/clients/client-connect.test.ts -195 tests/clients/client-export-effective-metadata.test.ts -475 tests/clients/client-export-live-wire.test.ts -144 tests/clients/client-export-modality-enum.test.ts -260 tests/clients/client-export-model-names.test.ts -103 tests/clients/client-export-reasoning-controls.test.ts -138 tests/clients/client-export-reasoning-metadata.test.ts -183 tests/clients/client-fingerprint.test.ts -290 tests/clients/client-home-unreachable.test.ts -27 tests/clients/client-hub-relay.test.ts -54 tests/clients/client-hub-state.test.ts -53 tests/clients/client-hub-usage.test.ts -230 tests/clients/client-lifecycle-lock.test.ts -2012 tests/clients/client-link-connect.test.ts -5271 tests/clients/client-link-relay.test.ts -6518 tests/clients/client-link-runtime.test.ts -96 tests/clients/client-link-state.test.ts -40 tests/clients/client-link-status.test.ts -19159 tests/clients/client-link-stop.test.ts -262 tests/clients/client-link-teardown.test.ts -4653 tests/clients/client-link-tunnel.test.ts -5278 tests/clients/client-machine-listener.test.ts -157 tests/clients/client-path.test.ts -101 tests/clients/client-runtime-restart.test.ts -94 tests/clients/client-runtime.test.ts -114 tests/clients/cline-client.test.ts -312 tests/clients/cline-writer.test.ts -106 tests/clients/command-code-client-contract.test.ts -106 tests/clients/command-code-client.test.ts -105 tests/clients/desktop-3p-guard.test.ts -959 tests/clients/desktop-3p-removal.test.ts -902 tests/clients/desktop-3p-write-files.test.ts -201 tests/clients/desktop-3p.test.ts -58 tests/clients/desktop-app-restart-posix.test.ts -92 tests/clients/desktop-app-restart.test.ts -145 tests/clients/desktop-app-server-exec-boundary.test.ts -3169 tests/clients/desktop-app-server-shim-launcher.test.ts -42 tests/clients/desktop-app-server-shim.test.ts -16108 tests/clients/desktop-bundle-trust-async.test.ts -41 tests/clients/desktop-chatgpt-config.test.ts -45 tests/clients/desktop-cli-command-surface.test.ts -77 tests/clients/desktop-cli-contracts.test.ts -64 tests/clients/desktop-compatibility-authority.test.ts -49 tests/clients/desktop-compatibility-build-probe.test.ts -47 tests/clients/desktop-compatibility-certificate-service.test.ts -78 tests/clients/desktop-compatibility-connection-store.test.ts -55 tests/clients/desktop-compatibility-launch.test.ts -38 tests/clients/desktop-compatibility-native-identity.test.ts -114 tests/clients/desktop-compatibility-relay.test.ts -38 tests/clients/desktop-compatibility-routing.test.ts -284 tests/clients/desktop-compatibility-runtime.test.ts -36 tests/clients/desktop-compatibility-trust.test.ts -47 tests/clients/desktop-exit-ownership.test.ts -71 tests/clients/desktop-host-visibility.test.ts -50 tests/clients/desktop-install-identity.test.ts -401 tests/clients/desktop-profile.test.ts -35 tests/clients/desktop-proxy-direct-transport.test.ts -428 tests/clients/desktop-remote-store.test.ts -35 tests/clients/desktop-restart-handoff.test.ts -38 tests/clients/desktop-runtime-identity.test.ts -42 tests/clients/desktop-start-at-login-default.test.ts -56 tests/clients/desktop-startup-surface.test.ts -416 tests/clients/desktop-supervised-restart.test.ts -538 tests/clients/desktop-telemetry-installer.test.ts -39 tests/clients/desktop-tray-availability.test.ts -39 tests/clients/desktop-update-surface.test.ts -38 tests/clients/desktop-widget-entry.test.ts -107 tests/clients/droid-client.test.ts -220 tests/clients/droid-managed-reasoning-defaults.test.ts -130 tests/clients/droid-normalized-reasoning-defaults.test.ts -103 tests/clients/gentle-shell-client.test.ts -97 tests/clients/gentle-shell-path.test.ts -159 tests/clients/hermes-catalog-refresh.test.ts -355 tests/clients/hermes-profile-routes.test.ts -134 tests/clients/hermes-profiles.test.ts -233 tests/clients/integrations-current-store.test.ts -173 tests/clients/integrations-dsh-profile-patch.test.ts -269 tests/clients/integrations-hermes-affinity.test.ts -160 tests/clients/integrations-journal.test.ts -150 tests/clients/integrations-merge.test.ts -229 tests/clients/integrations-model-names.test.ts -62 tests/clients/integrations-serialize.test.ts -151 tests/clients/integrations-state.test.ts -111 tests/clients/integrations-superseded-store.test.ts -204 tests/clients/integrations-writer-frozen-config.test.ts -111 tests/clients/integrations-writer-guard.test.ts -439 tests/clients/integrations-writer.test.ts -154 tests/clients/kilo-client.test.ts -42 tests/clients/lazycodex-detection.test.ts -33 tests/clients/link-admission-wait.test.ts -61 tests/clients/link-apply-record.test.ts -39 tests/clients/link-boundary.test.ts -417 tests/clients/link-child-plant-foundations.test.ts -43 tests/clients/link-codex-settings-digest.test.ts -51 tests/clients/link-compensation.test.ts -149 tests/clients/link-connection-generation.test.ts -88 tests/clients/link-diagnostics.test.ts -191 tests/clients/link-ephemeral-child-discovery.test.ts -59 tests/clients/link-fingerprint.test.ts -60 tests/clients/link-home-settings.test.ts -10045 tests/clients/link-ocx-child-conformance.test.ts -12137 tests/clients/link-ocx-child-e2e.test.ts -60 tests/clients/link-parity-reporter.test.ts -100 tests/clients/link-peer-compatibility.test.ts -2598 tests/clients/link-pinned-sync-argv.test.ts -91 tests/clients/link-ports.test.ts -106 tests/clients/link-readiness.test.ts -295 tests/clients/link-relay-bound-transport.test.ts -215 tests/clients/link-routes.test.ts -814 tests/clients/link-ssh-argv-discovery.test.ts -677 tests/clients/link-ssh-argv.test.ts -67 tests/clients/link-ssh-config.test.ts -489 tests/clients/link-ssh-runner.test.ts -40 tests/clients/link-status-projection.test.ts -127 tests/clients/link-store.test.ts -1575 tests/clients/link-supervisor.test.ts -339 tests/clients/link-tunnel-history.test.ts -39 tests/clients/link-tunnel-state.test.ts -191 tests/clients/mutation-plan.test.ts -94 tests/clients/omo-client.test.ts -476 tests/clients/omo-responses-loop.test.ts -98 tests/clients/omo-role-models.test.ts -67 tests/clients/omp-path-contract.test.ts -62 tests/clients/omp-yaml-source-inline-comments.test.ts -146 tests/clients/opencode-kilo-refresh.test.ts -96 tests/clients/pi-path-contract.test.ts -79 tests/clients/prime-client.test.ts -238 tests/clients/qoder-client.test.ts -250 tests/clients/raycast-client.test.ts -35 tests/clients/raycast-detect.test.ts -6949 tests/clients/remote-catalog.test.ts -60 tests/clients/remote-control-prototype.test.ts -104 tests/clients/remote-workspace-activation.test.ts -74 tests/clients/remote-workspace-agent-wire.test.ts -99 tests/clients/remote-workspace-app-server.integration.test.ts -42 tests/clients/remote-workspace-claude.integration.test.ts -322 tests/clients/remote-workspace-cli-runtimes.test.ts -81 tests/clients/remote-workspace-cli.test.ts -3069 tests/clients/remote-workspace-codex-runtime.test.ts -82 tests/clients/remote-workspace-command-runner.test.ts -50 tests/clients/remote-workspace-device.test.ts -44 tests/clients/remote-workspace-hub.test.ts -474 tests/clients/remote-workspace-linux-confinement.test.ts -199 tests/clients/remote-workspace-management.test.ts -64 tests/clients/remote-workspace-platform.test.ts -36 tests/clients/remote-workspace-protocol.test.ts -46 tests/clients/remote-workspace-rpc-framing.test.ts -149 tests/clients/remote-workspace-secret-store.test.ts -595 tests/clients/remote-workspace-server.test.ts -84 tests/clients/remote-workspace-session-binding.test.ts -252 tests/clients/remote-workspace-sessions.test.ts -41 tests/clients/remote-workspace-tool-bridge.test.ts -266 tests/clients/remote-workspace.test.ts -861 tests/clients/sync-client-integrations-unattended.test.ts -270 tests/clients/sync-client-integrations.test.ts -102 tests/clients/t3code-client-lifecycle.test.ts -522 tests/clients/t3code-client.test.ts -188 tests/clients/workbuddy-selector-recovery.test.ts -575 tests/codex-integration/active-registry-admission.test.ts -1356 tests/codex-integration/active-turn-disconnect.test.ts -101 tests/codex-integration/anthropic2-catalog.test.ts -99 tests/codex-integration/app-owned-memory.test.ts -4221 tests/codex-integration/bearer-admission-routed-provider.test.ts -4145 tests/codex-integration/catalog-async-lifetime.test.ts -293 tests/codex-integration/catalog-auto-refresh-client-fanout.test.ts -1111 tests/codex-integration/catalog-auto-refresh-scheduler.test.ts -64 tests/codex-integration/catalog-auto-review-override.test.ts -2490 tests/codex-integration/catalog-auto-review-row.test.ts -87 tests/codex-integration/catalog-context-window-ladder.test.ts -73 tests/codex-integration/catalog-cursor-search.test.ts -88 tests/codex-integration/catalog-custom-ordering.test.ts -73 tests/codex-integration/catalog-duplicate-slug-dedup.test.ts -116 tests/codex-integration/catalog-free-pricing-status.test.ts -4070 tests/codex-integration/catalog-full-picker-order.test.ts -99 tests/codex-integration/catalog-gated-native-suppression-reason.test.ts -106 tests/codex-integration/catalog-go-exact-efforts.test.ts -94 tests/codex-integration/catalog-hub-context-window.test.ts -124 tests/codex-integration/catalog-input-modality-enum.test.ts -117 tests/codex-integration/catalog-llamacpp-capabilities.test.ts -656 tests/codex-integration/catalog-modelalias-unique-sync.test.ts -58 tests/codex-integration/catalog-native-max-context.test.ts -140 tests/codex-integration/catalog-oauth-observation.test.ts -3069 tests/codex-integration/catalog-omit-disabled-native.test.ts -134 tests/codex-integration/catalog-opencode-go-context-window.test.ts -121 tests/codex-integration/catalog-opencode-go-static.test.ts -101 tests/codex-integration/catalog-opengateway-hints.test.ts -944 tests/codex-integration/catalog-remote-pull.test.ts -84 tests/codex-integration/catalog-retain-models.test.ts -90 tests/codex-integration/catalog-routed-comp-hash.test.ts -102 tests/codex-integration/catalog-seed-window-fill.test.ts -56 tests/codex-integration/catalog-slug-uniqueness-boundary.test.ts -165 tests/codex-integration/catalog-verbosity-default.test.ts -215 tests/codex-integration/catalog-vision-sidecar-disabled.test.ts -105 tests/codex-integration/catalog-vision-sidecar-modalities.test.ts -101 tests/codex-integration/catalog-zero-credit-picker.test.ts -3783 tests/codex-integration/client-injection-guard.test.ts -269 tests/codex-integration/code-mode-collab-surface.test.ts -166 tests/codex-integration/codex-account-clear-paused.test.ts -190 tests/codex-integration/codex-account-delete-atomicity.test.ts -37 tests/codex-integration/codex-account-label.test.ts -39 tests/codex-integration/codex-account-namespaces.test.ts -279 tests/codex-integration/codex-account-selection-atomicity.test.ts -99 tests/codex-integration/codex-account-selection-preferences.test.ts -109 tests/codex-integration/codex-account-slot-identity.test.ts -151 tests/codex-integration/codex-account-store-quota-isolation.test.ts -180 tests/codex-integration/codex-account-store-refresh-classification.test.ts -954 tests/codex-integration/codex-account-store.test.ts -452 tests/codex-integration/codex-account-threshold-api.test.ts -150 tests/codex-integration/codex-account-threshold-auth.test.ts -138 tests/codex-integration/codex-account-threshold-routing.test.ts -248 tests/codex-integration/codex-account-unusable-reason.test.ts -180 tests/codex-integration/codex-admission-primitives.test.ts -116 tests/codex-integration/codex-admission.test.ts -85 tests/codex-integration/codex-affinity-debug.test.ts -121 tests/codex-integration/codex-affinity-lease-gap.test.ts -99 tests/codex-integration/codex-affinity-request-owned.test.ts -10400 tests/codex-integration/codex-affinity-restart-matrix.test.ts -11709 tests/codex-integration/codex-affinity-restart.test.ts -1686 tests/codex-integration/codex-affinity-store.test.ts -380 tests/codex-integration/codex-agent-thread-limit.test.ts -51 tests/codex-integration/codex-app-server-path-spaces.test.ts -1094 tests/codex-integration/codex-app-server-processes.test.ts -96 tests/codex-integration/codex-app-server-restart-service.test.ts -1821 tests/codex-integration/codex-auth-api.test.ts -81 tests/codex-integration/codex-auth-cancel-ownership.test.ts -132 tests/codex-integration/codex-auth-collision.test.ts -757 tests/codex-integration/codex-auth-context.test.ts -186 tests/codex-integration/codex-auth-headless-accounts.test.ts -195 tests/codex-integration/codex-auth-release.test.ts -144 tests/codex-integration/codex-catalog-admission.test.ts -88 tests/codex-integration/codex-catalog-exclusions.test.ts -66 tests/codex-integration/codex-catalog-golden.test.ts -290 tests/codex-integration/codex-catalog-heal-integration.test.ts -140 tests/codex-integration/codex-catalog-heal-reanchor.test.ts -99 tests/codex-integration/codex-catalog-identity-neutral.test.ts -154 tests/codex-integration/codex-catalog-intent.test.ts -176 tests/codex-integration/codex-catalog-ladders.test.ts -80 tests/codex-integration/codex-catalog-model-picker-order.test.ts -125 tests/codex-integration/codex-catalog-readonly-windows.test.ts -45 tests/codex-integration/codex-catalog-refresh-status.test.ts -1060 tests/codex-integration/codex-catalog-restore.test.ts -73 tests/codex-integration/codex-catalog-routed-removal.test.ts -136 tests/codex-integration/codex-catalog-self-heal.test.ts -19958 tests/codex-integration/codex-catalog-sync-hardening.test.ts -311 tests/codex-integration/codex-catalog-write-audit.test.ts -64 tests/codex-integration/codex-catalog-write-serialization.test.ts -229 tests/codex-integration/codex-catalog-writer.test.ts -1609 tests/codex-integration/codex-catalog.test.ts -104 tests/codex-integration/codex-clamp-notice.test.ts -514 tests/codex-integration/codex-cli-install-provenance.test.ts -35 tests/codex-integration/codex-cli-installation-identity.test.ts -77 tests/codex-integration/codex-cli-installation-targets.test.ts -3157 tests/codex-integration/codex-cli-update-admission.test.ts -110362 tests/codex-integration/codex-cli-update-apply.test.ts -2939 tests/codex-integration/codex-cli-update-artifacts.test.ts -46 tests/codex-integration/codex-cli-update-integrity.test.ts -72 tests/codex-integration/codex-cli-update-launcher-policy.test.ts -229 tests/codex-integration/codex-cli-update-parent-async.test.ts -52 tests/codex-integration/codex-cli-update-paths.test.ts -1430 tests/codex-integration/codex-cli-update-plan.test.ts -20711 tests/codex-integration/codex-cli-update-process-fixture.test.ts -2401 tests/codex-integration/codex-cli-update-recovery.test.ts -33 tests/codex-integration/codex-cli-update-windows-apply-install.test.ts -54 tests/codex-integration/codex-cli-update-windows-apply-outcomes.test.ts -32 tests/codex-integration/codex-cli-update-windows-apply-shared.test.ts -59 tests/codex-integration/codex-cli-update-windows-apply.test.ts -97 tests/codex-integration/codex-cli-update-windows-layout.test.ts -33 tests/codex-integration/codex-cli-update-windows-pending.test.ts -445 tests/codex-integration/codex-cli-update-windows-recovery.test.ts -49 tests/codex-integration/codex-cli-update-windows-review.test.ts -389 tests/codex-integration/codex-cli-update-worker.test.ts -1317 tests/codex-integration/codex-cli-update-zero-effect.test.ts -42 tests/codex-integration/codex-cli-windows-child.test.ts -61 tests/codex-integration/codex-cli-windows-installation-files.test.ts -98 tests/codex-integration/codex-cli-windows-plan.test.ts -20411 tests/codex-integration/codex-composed-acceptance.test.ts -2174 tests/codex-integration/codex-config-drift-heal.test.ts -192 tests/codex-integration/codex-config-generation.test.ts -2139 tests/codex-integration/codex-config-preservation.test.ts -4362 tests/codex-integration/codex-config-write-lock.test.ts +152 tests/cli/cli-restart-handoff.test.ts +3672 tests/cli/cli-restart-health.test.ts +2818 tests/cli/cli-restore-back.test.ts +501 tests/cli/cli-role-suggestion-history.test.ts +151 tests/cli/cli-route-policy-not-found.test.ts +1411 tests/cli/cli-route-policy-write.test.ts +118 tests/cli/cli-route-to-aliases.test.ts +113 tests/cli/cli-route-to-confirmation.test.ts +212 tests/cli/cli-route-to.test.ts +3512 tests/cli/cli-start-auxiliary-bind.test.ts +19555 tests/cli/cli-start-journal-order.test.ts +4282 tests/cli/cli-start-owner-absence.test.ts +4053 tests/cli/cli-start-owner-evidence.test.ts +65 tests/cli/cli-start-routing-heal-wiring.test.ts +117 tests/cli/cli-status-codex-routing-drift.test.ts +2892 tests/cli/cli-status-hub-state.test.ts +18085 tests/cli/cli-status-json.test.ts +90 tests/cli/cli-status-oauth-health.test.ts +1798 tests/cli/cli-status-startup-health.test.ts +161 tests/cli/cli-stop-json.test.ts +504 tests/cli/cli-stop-refusal-transport.test.ts +106 tests/cli/cli-storage-inspect.test.ts +316 tests/cli/cli-storage-policy-fields.test.ts +659 tests/cli/cli-sync-expect-link.test.ts +217 tests/cli/cli-sync-fanout-ephemeral.test.ts +174 tests/cli/cli-system-health.test.ts +105 tests/cli/cli-system-settings-parity.test.ts +132 tests/cli/cli-telemetry-profile.test.ts +176 tests/cli/cli-telemetry.test.ts +156 tests/cli/cli-transport-honesty.test.ts +1505 tests/cli/cli-update-badge.test.ts +1255 tests/cli/cli-update-desktop-routing.test.ts +555 tests/cli/cli-update-restart-admission.test.ts +47 tests/cli/cli-update-restart-child.test.ts +104 tests/cli/cli-update-restart-desktop-service.test.ts +162 tests/cli/cli-update-restart-home.test.ts +67 tests/cli/cli-update-restart-service-record.test.ts +54 tests/cli/cli-update-restart-supervision.test.ts +660 tests/cli/cli-update-restart-transport.test.ts +151 tests/cli/cli-update-restart.test.ts +3081 tests/cli/cli-usage-compare.test.ts +115 tests/cli/cli-usage-hub.test.ts +119 tests/cli/cli-usage-model-search.test.ts +102 tests/cli/cli-usage-report.test.ts +246 tests/cli/cli-usage-scope.test.ts +1331 tests/cli/cli-usage-top.test.ts +232 tests/cli/cli-v2-plaintext.test.ts +891 tests/cli/cli-v2-runtime.test.ts +8822 tests/cli/cli-version-skew.test.ts +131 tests/cli/cross-home-loopback-family.test.ts +163 tests/cli/disconnect-runtime.test.ts +149 tests/cli/ensure-desired-integrations-race.test.ts +1427 tests/cli/hub-disable.test.ts +225 tests/cli/hub-gated-local-clients.test.ts +190 tests/cli/hub-invite.test.ts +108 tests/cli/interactive-confirm.test.ts +75 tests/cli/link-apply-restart.test.ts +149 tests/cli/local-credentials.test.ts +76 tests/cli/model-selection-guidance.test.ts +4150 tests/cli/ocx-launcher-desktop-handoff.test.ts +76 tests/cli/ocx-launcher-fixture-trust.test.ts +2529 tests/cli/ocx-launcher-runtime.test.ts +66 tests/cli/ocx-launcher-source.test.ts +76 tests/cli/ocx-run.test.ts +1015 tests/cli/restore-completes-shared-teardown.test.ts +855 tests/cli/route-explainability.test.ts +16407 tests/cli/sibling-home-client-sync.test.ts +123 tests/cli/star-deferral.test.ts +39 tests/cli/start-args.test.ts +59 tests/cli/start-ownership-publication.test.ts +538 tests/cli/status-install-method.test.ts +227 tests/cli/sync-command-child-flags.test.ts +2258 tests/cli/sync-command-fanout.test.ts +3188 tests/cli/sync-fanout-process.test.ts +156 tests/cli/sync-fanout-select-restart.test.ts +149 tests/cli/sync-fanout.test.ts +219 tests/cli/sync-link-status.test.ts +104 tests/cli/system-restart-client-installed-image.test.ts +68 tests/cli/system-restart-client-package-tree.test.ts +73 tests/cli/system-restart-client.test.ts +217 tests/cli/uninstall.test.ts +157 tests/clients/agent-clients.test.ts +111 tests/clients/aside-profile-identity.test.ts +176 tests/clients/aside-profile-paths.test.ts +1623 tests/clients/aside-profile-sync-owner.test.ts +150 tests/clients/aside-profiles-catalog-refresh.test.ts +481 tests/clients/aside-profiles.test.ts +62 tests/clients/client-catalog-compatibility.test.ts +23106 tests/clients/client-connect.test.ts +6681 tests/clients/client-disconnect-config-recovery.test.ts +4589 tests/clients/client-disconnect-desktop-refusals.test.ts +2187 tests/clients/client-disconnect-edited-codex.test.ts +1057 tests/clients/client-disconnect-field-snapshot.test.ts +2334 tests/clients/client-disconnect-recovery.test.ts +158 tests/clients/client-export-effective-metadata.test.ts +641 tests/clients/client-export-live-wire.test.ts +179 tests/clients/client-export-modality-enum.test.ts +248 tests/clients/client-export-model-names.test.ts +184 tests/clients/client-export-reasoning-controls.test.ts +132 tests/clients/client-export-reasoning-metadata.test.ts +121 tests/clients/client-fingerprint.test.ts +370 tests/clients/client-home-unreachable.test.ts +92 tests/clients/client-hub-relay.test.ts +96 tests/clients/client-hub-state.test.ts +66 tests/clients/client-hub-usage.test.ts +267 tests/clients/client-lifecycle-lock.test.ts +2222 tests/clients/client-link-connect.test.ts +5386 tests/clients/client-link-relay.test.ts +7080 tests/clients/client-link-runtime.test.ts +54 tests/clients/client-link-state.test.ts +58 tests/clients/client-link-status.test.ts +19015 tests/clients/client-link-stop.test.ts +1655 tests/clients/client-link-teardown.test.ts +4260 tests/clients/client-link-tunnel.test.ts +5397 tests/clients/client-machine-listener.test.ts +150 tests/clients/client-path.test.ts +1397 tests/clients/client-restart-sync-fence.test.ts +201 tests/clients/client-runtime-restart.test.ts +209 tests/clients/client-runtime.test.ts +146 tests/clients/cline-client.test.ts +362 tests/clients/cline-writer.test.ts +178 tests/clients/command-code-client-contract.test.ts +118 tests/clients/command-code-client.test.ts +111 tests/clients/desktop-3p-guard.test.ts +1243 tests/clients/desktop-3p-removal.test.ts +1021 tests/clients/desktop-3p-write-files.test.ts +339 tests/clients/desktop-3p.test.ts +79 tests/clients/desktop-app-restart-posix.test.ts +82 tests/clients/desktop-app-restart.test.ts +126 tests/clients/desktop-app-server-exec-boundary.test.ts +4009 tests/clients/desktop-app-server-shim-launcher.test.ts +52 tests/clients/desktop-app-server-shim.test.ts +16097 tests/clients/desktop-bundle-trust-async.test.ts +83 tests/clients/desktop-chatgpt-config.test.ts +59 tests/clients/desktop-cli-command-surface.test.ts +95 tests/clients/desktop-cli-contracts.test.ts +98 tests/clients/desktop-compatibility-authority.test.ts +94 tests/clients/desktop-compatibility-build-probe.test.ts +53 tests/clients/desktop-compatibility-certificate-service.test.ts +140 tests/clients/desktop-compatibility-connection-store.test.ts +54 tests/clients/desktop-compatibility-launch.test.ts +68 tests/clients/desktop-compatibility-native-identity.test.ts +180 tests/clients/desktop-compatibility-relay.test.ts +60 tests/clients/desktop-compatibility-routing.test.ts +274 tests/clients/desktop-compatibility-runtime.test.ts +66 tests/clients/desktop-compatibility-trust.test.ts +60 tests/clients/desktop-exit-ownership.test.ts +87 tests/clients/desktop-host-visibility.test.ts +55 tests/clients/desktop-install-identity.test.ts +430 tests/clients/desktop-profile.test.ts +36 tests/clients/desktop-proxy-direct-transport.test.ts +658 tests/clients/desktop-remote-store.test.ts +60 tests/clients/desktop-restart-handoff.test.ts +57 tests/clients/desktop-runtime-identity.test.ts +51 tests/clients/desktop-start-at-login-default.test.ts +68 tests/clients/desktop-startup-surface.test.ts +662 tests/clients/desktop-supervised-restart.test.ts +629 tests/clients/desktop-telemetry-installer.test.ts +95 tests/clients/desktop-tray-availability.test.ts +52 tests/clients/desktop-update-surface.test.ts +66 tests/clients/desktop-widget-entry.test.ts +175 tests/clients/droid-client.test.ts +148 tests/clients/droid-managed-reasoning-defaults.test.ts +143 tests/clients/droid-normalized-reasoning-defaults.test.ts +139 tests/clients/gentle-shell-client.test.ts +122 tests/clients/gentle-shell-path.test.ts +64 tests/clients/held-socket-writes.test.ts +261 tests/clients/hermes-catalog-refresh.test.ts +430 tests/clients/hermes-profile-routes.test.ts +228 tests/clients/hermes-profiles.test.ts +247 tests/clients/home-route-intent-upgrade.test.ts +280 tests/clients/integrations-current-store.test.ts +416 tests/clients/integrations-dsh-profile-patch.test.ts +217 tests/clients/integrations-hermes-affinity.test.ts +171 tests/clients/integrations-journal.test.ts +297 tests/clients/integrations-merge.test.ts +381 tests/clients/integrations-model-names.test.ts +65 tests/clients/integrations-serialize.test.ts +165 tests/clients/integrations-state.test.ts +147 tests/clients/integrations-superseded-store.test.ts +227 tests/clients/integrations-writer-frozen-config.test.ts +181 tests/clients/integrations-writer-guard.test.ts +417 tests/clients/integrations-writer.test.ts +185 tests/clients/kilo-client.test.ts +61 tests/clients/lazycodex-detection.test.ts +56 tests/clients/link-admission-wait.test.ts +120 tests/clients/link-alias-lock.test.ts +88 tests/clients/link-apply-record.test.ts +65 tests/clients/link-boundary.test.ts +78 tests/clients/link-child-activity.test.ts +250 tests/clients/link-child-binary-cache-fill.test.ts +107 tests/clients/link-child-catalog-freshness.test.ts +79 tests/clients/link-child-observations.test.ts +74 tests/clients/link-child-observe.test.ts +124 tests/clients/link-child-ops-engine.test.ts +181 tests/clients/link-child-ops-ignore-activity.test.ts +197 tests/clients/link-child-ops-runners.test.ts +2196 tests/clients/link-child-ops-scheduler.test.ts +307 tests/clients/link-child-plant-foundations.test.ts +106 tests/clients/link-child-policy.test.ts +1170 tests/clients/link-child-update-contract.test.ts +2513 tests/clients/link-child-update-launcher.test.ts +50 tests/clients/link-codex-settings-digest.test.ts +49 tests/clients/link-compensation.test.ts +113 tests/clients/link-connection-generation.test.ts +95 tests/clients/link-diagnostics-read.test.ts +139 tests/clients/link-diagnostics.test.ts +294 tests/clients/link-ephemeral-child-discovery.test.ts +114 tests/clients/link-explicit-route-no-ssh-config.test.ts +85 tests/clients/link-explicit-route-paths.test.ts +286 tests/clients/link-explicit-route.test.ts +51 tests/clients/link-fingerprint.test.ts +76 tests/clients/link-full-install-census.test.ts +1112 tests/clients/link-gated-ocx-argv.test.ts +79 tests/clients/link-home-route-intent.test.ts +100 tests/clients/link-home-settings.test.ts +9183 tests/clients/link-ocx-child-conformance.test.ts +9957 tests/clients/link-ocx-child-e2e.test.ts +3313 tests/clients/link-ocx-child-ws-feature.test.ts +13241 tests/clients/link-ocx-child-ws-gate.test.ts +69 tests/clients/link-operations-journal.test.ts +52 tests/clients/link-parity-reporter.test.ts +147 tests/clients/link-peer-compatibility.test.ts +2091 tests/clients/link-pinned-sync-argv.test.ts +428 tests/clients/link-pinned-sync-overwrite.test.ts +216 tests/clients/link-ports.test.ts +209 tests/clients/link-readiness.test.ts +400 tests/clients/link-relay-bound-transport.test.ts +104 tests/clients/link-relay-wait-observer.test.ts +409 tests/clients/link-request-zstd.test.ts +142 tests/clients/link-retirement.test.ts +140 tests/clients/link-revoke-suspend.test.ts +59 tests/clients/link-route-proof-relay.test.ts +94 tests/clients/link-route-proof.test.ts +45 tests/clients/link-route-select.test.ts +138 tests/clients/link-route-supervisor.test.ts +55 tests/clients/link-route-trust.test.ts +52 tests/clients/link-routes-argv.test.ts +114 tests/clients/link-routes-openssh.test.ts +121 tests/clients/link-routes-status.test.ts +48 tests/clients/link-routes-store.test.ts +124 tests/clients/link-routes.test.ts +689 tests/clients/link-ssh-argv-discovery.test.ts +691 tests/clients/link-ssh-argv.test.ts +52 tests/clients/link-ssh-capture-redact.test.ts +127 tests/clients/link-ssh-capture-tunnels.test.ts +124 tests/clients/link-ssh-capture.test.ts +81 tests/clients/link-ssh-config.test.ts +56 tests/clients/link-ssh-runner-abort.test.ts +492 tests/clients/link-ssh-runner.test.ts +71 tests/clients/link-status-projection.test.ts +105 tests/clients/link-store.test.ts +1603 tests/clients/link-supervisor.test.ts +183 tests/clients/link-traffic-child-status.test.ts +716 tests/clients/link-traffic.test.ts +443 tests/clients/link-tunnel-history.test.ts +51 tests/clients/link-tunnel-state.test.ts +221 tests/clients/link-tunnel-status.test.ts +72 tests/clients/link-windows-gated-served.test.ts +96 tests/clients/link-ws-activity-holds-operator.test.ts +281 tests/clients/link-ws-activity-holds.test.ts +85 tests/clients/link-ws-advertisement.test.ts +57 tests/clients/link-ws-autobahn.test.ts +200 tests/clients/link-ws-child-status.test.ts +222 tests/clients/link-ws-fallback.test.ts +114 tests/clients/link-ws-framer.test.ts +259 tests/clients/link-ws-relay-edges.test.ts +616 tests/clients/link-ws-relay.test.ts +185 tests/clients/link-ws-transport.test.ts +266 tests/clients/link-ws-unknown-try.test.ts +265 tests/clients/mutation-plan.test.ts +144 tests/clients/omo-client.test.ts +559 tests/clients/omo-responses-loop.test.ts +126 tests/clients/omo-role-models.test.ts +124 tests/clients/omp-path-contract.test.ts +87 tests/clients/omp-yaml-source-inline-comments.test.ts +229 tests/clients/opencode-kilo-refresh.test.ts +150 tests/clients/pi-family-developer-role.test.ts +126 tests/clients/pi-path-contract.test.ts +235 tests/clients/pi-sync-owner.test.ts +181 tests/clients/prime-client.test.ts +326 tests/clients/qoder-client.test.ts +162 tests/clients/raycast-client.test.ts +51 tests/clients/raycast-detect.test.ts +6905 tests/clients/remote-catalog.test.ts +71 tests/clients/remote-control-prototype.test.ts +270 tests/clients/remote-workspace-activation.test.ts +81 tests/clients/remote-workspace-agent-wire.test.ts +93 tests/clients/remote-workspace-app-server.integration.test.ts +67 tests/clients/remote-workspace-claude.integration.test.ts +351 tests/clients/remote-workspace-cli-runtimes.test.ts +126 tests/clients/remote-workspace-cli.test.ts +6819 tests/clients/remote-workspace-codex-runtime.test.ts +109 tests/clients/remote-workspace-command-runner.test.ts +66 tests/clients/remote-workspace-device.test.ts +82 tests/clients/remote-workspace-hub.test.ts +755 tests/clients/remote-workspace-linux-confinement.test.ts +156 tests/clients/remote-workspace-management.test.ts +71 tests/clients/remote-workspace-platform.test.ts +68 tests/clients/remote-workspace-protocol.test.ts +52 tests/clients/remote-workspace-rpc-framing.test.ts +68 tests/clients/remote-workspace-secret-store.test.ts +817 tests/clients/remote-workspace-server.test.ts +67 tests/clients/remote-workspace-session-binding.test.ts +92 tests/clients/remote-workspace-sessions.test.ts +107 tests/clients/remote-workspace-tool-bridge.test.ts +260 tests/clients/remote-workspace.test.ts +269 tests/clients/route-intent-aside.test.ts +1348 tests/clients/route-intent-claude-surface.test.ts +9122 tests/clients/route-intent-codex-connect-disabled.test.ts +39857 tests/clients/route-intent-codex-transitions.test.ts +475 tests/clients/route-intent-connect-post-commit.test.ts +3577 tests/clients/route-intent-connect-recovery.test.ts +164 tests/clients/route-intent-connected-capabilities.test.ts +7984 tests/clients/route-intent-connected-review.test.ts +22221 tests/clients/route-intent-connected.test.ts +129 tests/clients/route-intent-desktop.test.ts +5577 tests/clients/route-intent-file-originals.test.ts +3792 tests/clients/route-intent-home-consent.test.ts +65 tests/clients/route-intent-local-receipt.test.ts +482 tests/clients/route-intent-materializer.test.ts +348 tests/clients/route-intent-native-originals.test.ts +9995 tests/clients/route-intent-native-review.test.ts +4232 tests/clients/route-intent-offline-mode-switch.test.ts +212 tests/clients/route-intent-overwrite.test.ts +72 tests/clients/route-intent-parity-fallback.test.ts +1895 tests/clients/route-intent-parity-withdrawal.test.ts +56 tests/clients/route-intent-parity.test.ts +62 tests/clients/route-intent-reporter.test.ts +410 tests/clients/route-intent-runtime-stop.test.ts +194 tests/clients/route-intent-scheduler.test.ts +59 tests/clients/route-intent-state.test.ts +150 tests/clients/route-intent-watch-client.test.ts +104 tests/clients/route-intent.test.ts +507 tests/clients/sync-client-integrations-unattended.test.ts +307 tests/clients/sync-client-integrations.test.ts +139 tests/clients/t3code-client-lifecycle.test.ts +274 tests/clients/t3code-client.test.ts +328 tests/clients/workbuddy-selector-recovery.test.ts +723 tests/codex-integration/active-registry-admission.test.ts +1714 tests/codex-integration/active-turn-disconnect.test.ts +206 tests/codex-integration/anthropic2-catalog.test.ts +149 tests/codex-integration/app-owned-memory.test.ts +5563 tests/codex-integration/bearer-admission-routed-provider.test.ts +4210 tests/codex-integration/catalog-async-lifetime.test.ts +328 tests/codex-integration/catalog-auto-refresh-client-fanout.test.ts +265 tests/codex-integration/catalog-auto-refresh-link-fanout.test.ts +1172 tests/codex-integration/catalog-auto-refresh-scheduler.test.ts +148 tests/codex-integration/catalog-auto-review-override.test.ts +2896 tests/codex-integration/catalog-auto-review-row.test.ts +184 tests/codex-integration/catalog-context-window-ladder.test.ts +127 tests/codex-integration/catalog-cursor-search.test.ts +150 tests/codex-integration/catalog-custom-ordering.test.ts +153 tests/codex-integration/catalog-duplicate-slug-dedup.test.ts +150 tests/codex-integration/catalog-free-pricing-status.test.ts +4723 tests/codex-integration/catalog-full-picker-order.test.ts +92 tests/codex-integration/catalog-gated-native-suppression-reason.test.ts +115 tests/codex-integration/catalog-go-exact-efforts.test.ts +83 tests/codex-integration/catalog-hub-context-window.test.ts +213 tests/codex-integration/catalog-input-modality-enum.test.ts +105 tests/codex-integration/catalog-llamacpp-capabilities.test.ts +634 tests/codex-integration/catalog-modelalias-unique-sync.test.ts +82 tests/codex-integration/catalog-native-max-context.test.ts +153 tests/codex-integration/catalog-oauth-observation.test.ts +4493 tests/codex-integration/catalog-omit-disabled-native.test.ts +131 tests/codex-integration/catalog-opencode-go-context-window.test.ts +146 tests/codex-integration/catalog-opencode-go-static.test.ts +119 tests/codex-integration/catalog-opengateway-hints.test.ts +1309 tests/codex-integration/catalog-remote-pull.test.ts +132 tests/codex-integration/catalog-retain-models.test.ts +133 tests/codex-integration/catalog-routed-comp-hash.test.ts +722 tests/codex-integration/catalog-routed-defaults.test.ts +99 tests/codex-integration/catalog-seed-window-fill.test.ts +80 tests/codex-integration/catalog-slug-uniqueness-boundary.test.ts +132 tests/codex-integration/catalog-verbosity-default.test.ts +220 tests/codex-integration/catalog-vision-sidecar-disabled.test.ts +199 tests/codex-integration/catalog-vision-sidecar-modalities.test.ts +131 tests/codex-integration/catalog-zero-credit-picker.test.ts +4267 tests/codex-integration/client-injection-guard.test.ts +238 tests/codex-integration/code-mode-collab-surface.test.ts +155 tests/codex-integration/codex-account-clear-paused.test.ts +229 tests/codex-integration/codex-account-delete-atomicity.test.ts +59 tests/codex-integration/codex-account-label.test.ts +59 tests/codex-integration/codex-account-namespaces.test.ts +400 tests/codex-integration/codex-account-selection-atomicity.test.ts +224 tests/codex-integration/codex-account-selection-preferences.test.ts +149 tests/codex-integration/codex-account-slot-identity.test.ts +126 tests/codex-integration/codex-account-store-quota-isolation.test.ts +187 tests/codex-integration/codex-account-store-refresh-classification.test.ts +1036 tests/codex-integration/codex-account-store.test.ts +262 tests/codex-integration/codex-account-threshold-api.test.ts +227 tests/codex-integration/codex-account-threshold-auth.test.ts +184 tests/codex-integration/codex-account-threshold-routing.test.ts +135 tests/codex-integration/codex-account-unusable-reason.test.ts +119 tests/codex-integration/codex-admission-primitives.test.ts +144 tests/codex-integration/codex-admission.test.ts +54 tests/codex-integration/codex-affinity-debug.test.ts +268 tests/codex-integration/codex-affinity-lease-gap.test.ts +132 tests/codex-integration/codex-affinity-request-owned.test.ts +13167 tests/codex-integration/codex-affinity-restart-matrix.test.ts +13506 tests/codex-integration/codex-affinity-restart.test.ts +1901 tests/codex-integration/codex-affinity-store.test.ts +442 tests/codex-integration/codex-agent-thread-limit.test.ts +3578 tests/codex-integration/codex-app-rewrite-routing.test.ts +49 tests/codex-integration/codex-app-server-path-spaces.test.ts +968 tests/codex-integration/codex-app-server-processes.test.ts +116 tests/codex-integration/codex-app-server-restart-service.test.ts +2113 tests/codex-integration/codex-auth-api.test.ts +176 tests/codex-integration/codex-auth-cancel-ownership.test.ts +171 tests/codex-integration/codex-auth-collision.test.ts +916 tests/codex-integration/codex-auth-context.test.ts +4208 tests/codex-integration/codex-auth-device-only.test.ts +270 tests/codex-integration/codex-auth-headless-accounts.test.ts +294 tests/codex-integration/codex-auth-release.test.ts +125 tests/codex-integration/codex-catalog-admission.test.ts +100 tests/codex-integration/codex-catalog-exclusions.test.ts +103 tests/codex-integration/codex-catalog-golden.test.ts +348 tests/codex-integration/codex-catalog-heal-integration.test.ts +170 tests/codex-integration/codex-catalog-heal-reanchor.test.ts +100 tests/codex-integration/codex-catalog-identity-neutral.test.ts +248 tests/codex-integration/codex-catalog-intent.test.ts +113 tests/codex-integration/codex-catalog-ladders.test.ts +97 tests/codex-integration/codex-catalog-model-picker-order.test.ts +160 tests/codex-integration/codex-catalog-readonly-windows.test.ts +52 tests/codex-integration/codex-catalog-refresh-status.test.ts +1512 tests/codex-integration/codex-catalog-restore.test.ts +189 tests/codex-integration/codex-catalog-routed-removal.test.ts +172 tests/codex-integration/codex-catalog-self-heal.test.ts +25828 tests/codex-integration/codex-catalog-sync-hardening.test.ts +447 tests/codex-integration/codex-catalog-write-audit.test.ts +76 tests/codex-integration/codex-catalog-write-serialization.test.ts +303 tests/codex-integration/codex-catalog-writer.test.ts +1775 tests/codex-integration/codex-catalog.test.ts +153 tests/codex-integration/codex-clamp-notice.test.ts +321 tests/codex-integration/codex-cli-install-provenance.test.ts +67 tests/codex-integration/codex-cli-installation-identity.test.ts +59 tests/codex-integration/codex-cli-installation-targets.test.ts +6666 tests/codex-integration/codex-cli-update-admission.test.ts +95197 tests/codex-integration/codex-cli-update-apply.test.ts +2630 tests/codex-integration/codex-cli-update-artifacts.test.ts +98 tests/codex-integration/codex-cli-update-integrity.test.ts +74 tests/codex-integration/codex-cli-update-job-read-race.test.ts +65 tests/codex-integration/codex-cli-update-launcher-policy.test.ts +378 tests/codex-integration/codex-cli-update-parent-async.test.ts +62 tests/codex-integration/codex-cli-update-paths.test.ts +1622 tests/codex-integration/codex-cli-update-plan.test.ts +34941 tests/codex-integration/codex-cli-update-process-fixture.test.ts +2893 tests/codex-integration/codex-cli-update-recovery.test.ts +141 tests/codex-integration/codex-cli-update-windows-apply-install.test.ts +98 tests/codex-integration/codex-cli-update-windows-apply-outcomes.test.ts +59 tests/codex-integration/codex-cli-update-windows-apply-shared.test.ts +66 tests/codex-integration/codex-cli-update-windows-apply.test.ts +150 tests/codex-integration/codex-cli-update-windows-layout.test.ts +42 tests/codex-integration/codex-cli-update-windows-pending.test.ts +397 tests/codex-integration/codex-cli-update-windows-recovery.test.ts +82 tests/codex-integration/codex-cli-update-windows-review.test.ts +455 tests/codex-integration/codex-cli-update-worker.test.ts +1301 tests/codex-integration/codex-cli-update-zero-effect.test.ts +52 tests/codex-integration/codex-cli-windows-child.test.ts +65 tests/codex-integration/codex-cli-windows-installation-files.test.ts +114 tests/codex-integration/codex-cli-windows-plan.test.ts +21145 tests/codex-integration/codex-composed-acceptance.test.ts +2060 tests/codex-integration/codex-config-drift-heal.test.ts +336 tests/codex-integration/codex-config-generation.test.ts +2326 tests/codex-integration/codex-config-preservation.test.ts +6408 tests/codex-integration/codex-config-write-lock.test.ts 157 tests/codex-integration/codex-context-owner.test.ts -4647 tests/codex-integration/codex-convergence-account-selectors.test.ts -995 tests/codex-integration/codex-convergence-contract.test.ts -370 tests/codex-integration/codex-cooldown-recovery.test.ts -117 tests/codex-integration/codex-coordinator-doctor.test.ts -623 tests/codex-integration/codex-credit-retry-after.test.ts -400 tests/codex-integration/codex-credit-scoped-retry.test.ts -163 tests/codex-integration/codex-credits-after-limit-main.test.ts -201 tests/codex-integration/codex-credits-after-limit.test.ts -181 tests/codex-integration/codex-credits-probes.test.ts -176 tests/codex-integration/codex-credits-settings.test.ts -41 tests/codex-integration/codex-credits.test.ts -168 tests/codex-integration/codex-desired-state.test.ts -517 tests/codex-integration/codex-direct-credit-renewal.test.ts -226 tests/codex-integration/codex-direct-renewal-revocation.test.ts -89 tests/codex-integration/codex-entitlement-identity-read-fence.test.ts -646 tests/codex-integration/codex-envkey-admission-substitution.test.ts -80 tests/codex-integration/codex-exec-invocation.test.ts -447 tests/codex-integration/codex-failure-window.test.ts -81 tests/codex-integration/codex-features-cache.test.ts -48 tests/codex-integration/codex-features-residual.test.ts -75 tests/codex-integration/codex-filesystem-evidence.test.ts -92 tests/codex-integration/codex-forward-access-programs-writer.test.ts -342 tests/codex-integration/codex-gather-authority.test.ts -2086 tests/codex-integration/codex-history-job.test.ts -125 tests/codex-integration/codex-history-lock.test.ts -54 tests/codex-integration/codex-history-pending-wal.test.ts -2090 tests/codex-integration/codex-history-provider.test.ts -997 tests/codex-integration/codex-history-reachability.test.ts -34 tests/codex-integration/codex-history-worker-boundary.test.ts -1965 tests/codex-integration/codex-history-worker.test.ts -62 tests/codex-integration/codex-history-writer.test.ts -8096 tests/codex-integration/codex-home-owner-lifecycle.test.ts -966 tests/codex-integration/codex-home-owner.test.ts -42 tests/codex-integration/codex-home-wsl-local-state.test.ts -111 tests/codex-integration/codex-home-wsl.test.ts -326 tests/codex-integration/codex-idle-window.test.ts -177 tests/codex-integration/codex-inject-history-wording.test.ts -62860 tests/codex-integration/codex-inject-integration.test.ts -1695 tests/codex-integration/codex-inject-missing-config.test.ts -772 tests/codex-integration/codex-inject-retained-table.test.ts -10183 tests/codex-integration/codex-inject-v1-reconcile.test.ts -7156 tests/codex-integration/codex-inject-write-lock.test.ts -79 tests/codex-integration/codex-inject.test.ts -36 tests/codex-integration/codex-injected-marker.test.ts -45 tests/codex-integration/codex-installation-acl.test.ts -63 tests/codex-integration/codex-installation-id.test.ts -510 tests/codex-integration/codex-installation-invalid-account.test.ts -725 tests/codex-integration/codex-installation-live-content.test.ts -560 tests/codex-integration/codex-installation-live-http.test.ts -1059 tests/codex-integration/codex-installation-live-ws.test.ts -328 tests/codex-integration/codex-installation-sidecars.test.ts -98 tests/codex-integration/codex-installation-wire.test.ts -64 tests/codex-integration/codex-integration-record.test.ts -3524 tests/codex-integration/codex-journal-recovery.test.ts -12512 tests/codex-integration/codex-journal.test.ts -202 tests/codex-integration/codex-launcher-admission.test.ts -110 tests/codex-integration/codex-launcher-darwin-acl.test.ts -36 tests/codex-integration/codex-launcher-darwin-identity.test.ts -144 tests/codex-integration/codex-launcher-diagnostics.test.ts -251 tests/codex-integration/codex-launcher-endpoint.test.ts -226 tests/codex-integration/codex-launcher-env.test.ts -2262 tests/codex-integration/codex-launcher-process.test.ts -177 tests/codex-integration/codex-launcher-security.test.ts -115 tests/codex-integration/codex-launcher.test.ts -117 tests/codex-integration/codex-legacy-config-keys.test.ts -208 tests/codex-integration/codex-lineage-placement.test.ts -266 tests/codex-integration/codex-linked-account-pause.test.ts -78 tests/codex-integration/codex-log-guard-coderabbit.test.ts -55 tests/codex-integration/codex-log-guard-doctor-coderabbit.test.ts -38 tests/codex-integration/codex-log-guard-doctor-protection.test.ts -35 tests/codex-integration/codex-log-guard-doctor.test.ts -95 tests/codex-integration/codex-log-guard-inspect.test.ts -42 tests/codex-integration/codex-log-guard-lock.test.ts -276 tests/codex-integration/codex-log-guard-maintenance-coderabbit.test.ts -212 tests/codex-integration/codex-log-guard-maintenance.test.ts -38 tests/codex-integration/codex-log-guard-policy.test.ts -47 tests/codex-integration/codex-log-guard-processes.test.ts -209 tests/codex-integration/codex-log-guard-protection.test.ts -68 tests/codex-integration/codex-log-guard-status-zero-write.test.ts -131 tests/codex-integration/codex-main-account-refresh.test.ts -253 tests/codex-integration/codex-main-grant-refusal.test.ts -334 tests/codex-integration/codex-main-rotation.test.ts -119 tests/codex-integration/codex-main-token-invalidated.test.ts -73 tests/codex-integration/codex-management-convergence.test.ts -216 tests/codex-integration/codex-metadata-integrity.test.ts -6602 tests/codex-integration/codex-missing-home.test.ts -72 tests/codex-integration/codex-model-availability-error.test.ts -281 tests/codex-integration/codex-model-denial-evidence.test.ts -67 tests/codex-integration/codex-model-entitlement-admission.test.ts -221 tests/codex-integration/codex-model-entitlements-program-shape.test.ts -113 tests/codex-integration/codex-model-entitlements.test.ts -138 tests/codex-integration/codex-models-cache-invalidate.test.ts -765 tests/codex-integration/codex-native-availability-nux.test.ts -508 tests/codex-integration/codex-native-residue.test.ts -144 tests/codex-integration/codex-pin-drain-projection.test.ts -105 tests/codex-integration/codex-plan.test.ts -332 tests/codex-integration/codex-plugins-doctor.test.ts -96 tests/codex-integration/codex-pool-caller-fallback-policy.test.ts -177 tests/codex-integration/codex-pool-credit-policy.test.ts -109 tests/codex-integration/codex-pool-plan-exclusion.test.ts -43 tests/codex-integration/codex-pool-refresh-backoff.test.ts -206 tests/codex-integration/codex-pool-request-owned-main.test.ts -540 tests/codex-integration/codex-pool-rotation.test.ts -258 tests/codex-integration/codex-preserve-signed-in.test.ts -175 tests/codex-integration/codex-priority-failback.test.ts -40 tests/codex-integration/codex-proc-scan-errors.test.ts -4785 tests/codex-integration/codex-profile-preservation.test.ts -81 tests/codex-integration/codex-prompt-adopt.test.ts -253 tests/codex-integration/codex-prompt-base-variants.test.ts -73 tests/codex-integration/codex-prompt-journal.test.ts -51 tests/codex-integration/codex-prompt-layers-read.test.ts -228 tests/codex-integration/codex-prompt-layers-write.test.ts -41 tests/codex-integration/codex-prompt-layers.test.ts -248 tests/codex-integration/codex-prompt-lock-sharing.test.ts -348 tests/codex-integration/codex-prompt-lock.test.ts -1117 tests/codex-integration/codex-prompt-route.test.ts -118 tests/codex-integration/codex-prompt-scalar-scope.test.ts -886 tests/codex-integration/codex-prompt-text-probe.test.ts -468 tests/codex-integration/codex-prompt-writes.test.ts -14901 tests/codex-integration/codex-provider-routing.test.ts -724 tests/codex-integration/codex-provider-table-retention.test.ts -108 tests/codex-integration/codex-quota-auto-refresh-generation.test.ts -192 tests/codex-integration/codex-quota-auto-refresh-main-admission.test.ts -261 tests/codex-integration/codex-quota-auto-refresh.test.ts -50 tests/codex-integration/codex-quota-capacity.test.ts -95 tests/codex-integration/codex-quota-history.test.ts -104 tests/codex-integration/codex-quota-parser-parity.test.ts -49 tests/codex-integration/codex-quota-persistence.test.ts -323 tests/codex-integration/codex-quota-prime.test.ts -111 tests/codex-integration/codex-quota-query-backoff.test.ts -190 tests/codex-integration/codex-quota-rejection.test.ts -138 tests/codex-integration/codex-refresh.test.ts -304 tests/codex-integration/codex-request-owned-affinity.test.ts -727 tests/codex-integration/codex-reset-credit-auto-redeem.test.ts -429 tests/codex-integration/codex-reset-credit-operation-ledger.test.ts -298 tests/codex-integration/codex-reset-credit-recovery.test.ts -57 tests/codex-integration/codex-restart-contract-parity.test.ts -305 tests/codex-integration/codex-restart-route.test.ts -4686 tests/codex-integration/codex-restore-app-rewrite.test.ts -7836 tests/codex-integration/codex-retained-root-serialization.test.ts -194 tests/codex-integration/codex-round-robin-headroom.test.ts -90 tests/codex-integration/codex-routing-cache-affinity-detour.test.ts -68 tests/codex-integration/codex-routing-elapsed-short-reset.test.ts -5864 tests/codex-integration/codex-routing.test.ts -121 tests/codex-integration/codex-runtime-macos-desktop.test.ts -128 tests/codex-integration/codex-runtime-wsl-desktop.test.ts -142 tests/codex-integration/codex-runtime.test.ts -453 tests/codex-integration/codex-service-manager-probe-hardening.test.ts -188 tests/codex-integration/codex-service-manager-probe.test.ts -37161 tests/codex-integration/codex-shim-autorestore.test.ts -71 tests/codex-integration/codex-shim-bypass-token.test.ts -215 tests/codex-integration/codex-shim-destroyed-probe.test.ts -66 tests/codex-integration/codex-shim-ensure-failure.test.ts -96 tests/codex-integration/codex-shim-fnm.test.ts -83 tests/codex-integration/codex-shim-legacy-record.test.ts -434 tests/codex-integration/codex-shim-migration.test.ts -79 tests/codex-integration/codex-shim-overlay-candidates.test.ts -589 tests/codex-integration/codex-shim-overlay-readiness.test.ts -2283 tests/codex-integration/codex-shim-overlay-transaction.test.ts -622 tests/codex-integration/codex-shim-overlay.test.ts -4265 tests/codex-integration/codex-shim-path-readiness.test.ts -29221 tests/codex-integration/codex-shim-readiness.test.ts -69 tests/codex-integration/codex-shim-runtime-preflight.test.ts -747 tests/codex-integration/codex-shim-standalone.test.ts -142 tests/codex-integration/codex-shim-windows-revision.test.ts -25942 tests/codex-integration/codex-shim.test.ts -1875 tests/codex-integration/codex-sidecar-credit-policy.test.ts -131 tests/codex-integration/codex-signin-lockout.test.ts -231 tests/codex-integration/codex-spark-visibility.test.ts -39 tests/codex-integration/codex-sqlite-home.test.ts -305 tests/codex-integration/codex-stored-main-duplicate.test.ts -1397 tests/codex-integration/codex-sync-api.test.ts -262 tests/codex-integration/codex-sync-new-model-policy.test.ts -52 tests/codex-integration/codex-sync-response.test.ts -22026 tests/codex-integration/codex-sync-user-edits.test.ts -232 tests/codex-integration/codex-systemd-env-probe.test.ts -121 tests/codex-integration/codex-tool-mode.test.ts -527 tests/codex-integration/codex-transition-state-adoption.test.ts -69 tests/codex-integration/codex-transition-state-first-use-regression.test.ts -1815 tests/codex-integration/codex-transition-state-race.test.ts -199 tests/codex-integration/codex-transition-state.test.ts -154 tests/codex-integration/codex-use-remaining-quota.test.ts -63 tests/codex-integration/codex-user-identity.test.ts -775 tests/codex-integration/codex-v2-gate.test.ts -322 tests/codex-integration/codex-warmup.test.ts -2808 tests/codex-integration/codex-web-search-switch.test.ts -72 tests/codex-integration/codex-websocket-registry.test.ts -32 tests/codex-integration/codex-windows-current-sid.test.ts -2341 tests/codex-integration/codex-write-lock.test.ts -43 tests/codex-integration/combo-authoritative-reset.test.ts -30 tests/codex-integration/combo-codex-exhaustion-cooldown.test.ts -79 tests/codex-integration/combo-cooldown-reprobe.test.ts -456 tests/codex-integration/combo-description-catalog.test.ts -37 tests/codex-integration/combo-last-resort.test.ts -88 tests/codex-integration/combo-permanent-failure-cooldown.test.ts -142 tests/codex-integration/combo-reset-window-model-scope.test.ts -31 tests/codex-integration/combos-kiro-profile-hop.test.ts -307 tests/codex-integration/combos.test.ts -751 tests/codex-integration/compatibility-manifest.test.ts -88 tests/codex-integration/configured-native-models.test.ts -1300 tests/codex-integration/configured-ultrafast-picker.test.ts -31 tests/codex-integration/context-compat.test.ts -37 tests/codex-integration/custom-model-catalog-migration.test.ts -233 tests/codex-integration/deferred-collab-surface.test.ts -173 tests/codex-integration/discovered-native-models.test.ts -374 tests/codex-integration/doctor.test.ts -419 tests/codex-integration/effort-policy.test.ts -339 tests/codex-integration/exec-boundary-launch.test.ts -78 tests/codex-integration/exec-cli-bundle-containment.test.ts -77 tests/codex-integration/exec-cli-renamed-app-bundle.test.ts -124 tests/codex-integration/exec-known-app-bundles.test.ts -69 tests/codex-integration/exec-launcher-boundary.test.ts -40 tests/codex-integration/exec-renamed-app-bundle.test.ts -343 tests/codex-integration/exec-trust-boundary.test.ts -77 tests/codex-integration/fast-row-listing.test.ts -87 tests/codex-integration/fast-row.test.ts -117 tests/codex-integration/gather-routed-models-single-flight.test.ts -79 tests/codex-integration/gpt6-native-rows.test.ts -85 tests/codex-integration/gpt61-sol-rows.test.ts -207 tests/codex-integration/gpt61-terra-rows.test.ts -50 tests/codex-integration/history-migration-guardian.test.ts -37 tests/codex-integration/history-ocx-compaction-recovery.test.ts -39 tests/codex-integration/history-paginated-openai-compat.test.ts -1434 tests/codex-integration/history-paginated-transition-destinations.test.ts -97 tests/codex-integration/injection-link-websocket.test.ts -249 tests/codex-integration/injection-model-api.test.ts -169 tests/codex-integration/injection-model-suggest-routes.test.ts -35 tests/codex-integration/injection-routing-drift.test.ts -4489 tests/codex-integration/injection-routing-heal-apply.test.ts -536 tests/codex-integration/injection-routing-healer.test.ts -6142 tests/codex-integration/issue-452-empty-503.test.ts -3207 tests/codex-integration/issue-702-expired-replay-state.test.ts -646 tests/codex-integration/issue-914-transport-attribution.test.ts -155 tests/codex-integration/low-quota-desktop-notifier.test.ts -1222 tests/codex-integration/low-quota-protection.test.ts -351 tests/codex-integration/main-account-credit-renewal.test.ts -33 tests/codex-integration/main-account-external-usage.test.ts -13607 tests/codex-integration/main-account-hard-lock-auth.test.ts -134 tests/codex-integration/main-account-hard-lock-default.test.ts -547 tests/codex-integration/main-account-hard-lock-fallback-off.test.ts -358 tests/codex-integration/main-account-hard-lock-fallback-routing.test.ts -39 tests/codex-integration/main-account-hard-lock-policy.test.ts -488 tests/codex-integration/main-account-hard-lock-profile-dispatch.test.ts -428 tests/codex-integration/main-account-hard-lock-recovery.test.ts -127 tests/codex-integration/main-account-hard-lock-retirement.test.ts -125 tests/codex-integration/main-account-hard-lock-thresholds.test.ts -125 tests/codex-integration/main-account-hard-lock-usage-limit.test.ts -532 tests/codex-integration/main-account-policy-binding-wait.test.ts -65 tests/codex-integration/main-device-reauth-api.test.ts -161 tests/codex-integration/main-device-reauth.test.ts -276 tests/codex-integration/main-quota-evidence-validation.test.ts -20376 tests/codex-integration/main-quota-provenance.test.ts -556 tests/codex-integration/main-quota-window-observation.test.ts -2647 tests/codex-integration/messaging-local-cli.test.ts -84 tests/codex-integration/messaging-local-discovery.test.ts -136 tests/codex-integration/messaging-local-envelope.test.ts -707 tests/codex-integration/messaging-local-lifecycle.test.ts -326 tests/codex-integration/messaging-local-send.test.ts -45 tests/codex-integration/messaging-local-socket.test.ts -12330 tests/codex-integration/messaging-mcp-queue.test.ts -1478 tests/codex-integration/messaging-mcp-replies.test.ts -8091 tests/codex-integration/messaging-remote-admission.test.ts -594 tests/codex-integration/messaging-remote-contract.test.ts -562 tests/codex-integration/messaging-remote-enrollment-gaps.test.ts -11801 tests/codex-integration/messaging-remote-enrollment.test.ts -36 tests/codex-integration/messaging-remote-forward-failure.test.ts -3572 tests/codex-integration/messaging-remote-gaps.test.ts -45 tests/codex-integration/messaging-remote-interop.test.ts -17209 tests/codex-integration/messaging-remote-lifecycle.test.ts -44 tests/codex-integration/messaging-remote-native.test.ts -66 tests/codex-integration/messaging-remote-port-reservation.test.ts -13199 tests/codex-integration/messaging-remote-process.test.ts -3948 tests/codex-integration/messaging-remote-replies.test.ts -1402 tests/codex-integration/messaging-remote-scratch.test.ts -8268 tests/codex-integration/messaging-remote-send.test.ts -1194 tests/codex-integration/messaging-remote-store.test.ts -30 tests/codex-integration/model-cache-generation-tombstone.test.ts -98 tests/codex-integration/model-cache.test.ts -138 tests/codex-integration/model-display-names-management-api.test.ts -105 tests/codex-integration/model-metadata-sync.test.ts -552 tests/codex-integration/model-pinned-effort.test.ts -625 tests/codex-integration/model-visibility-management-api.test.ts -614 tests/codex-integration/multi-agent-compat.test.ts -537 tests/codex-integration/multi-agent-keep-native-v1.test.ts -75 tests/codex-integration/multi-agent-origin.test.ts -95 tests/codex-integration/native-alias-maintainer-regressions.test.ts -235 tests/codex-integration/native-claude-code-toggle.test.ts -261 tests/codex-integration/native-claude-desktop-toggle.test.ts -3744 tests/codex-integration/native-codex-toggle.test.ts -606 tests/codex-integration/native-grok-toggle.test.ts -45 tests/codex-integration/native-main-auth-temp.test.ts -56 tests/codex-integration/native-main-claim-cache.test.ts -124 tests/codex-integration/native-main-claim.test.ts -9917 tests/codex-integration/native-main-owner-lifetime.test.ts -1145 tests/codex-integration/native-main-refresh-mode.test.ts -367 tests/codex-integration/native-model-toggle.test.ts -56 tests/codex-integration/native-profile-api.test.ts -8983 tests/codex-integration/native-profile-crash-boundaries.test.ts -2076 tests/codex-integration/native-profile-drain-server.test.ts -2674 tests/codex-integration/native-profile-manager.test.ts -324 tests/codex-integration/native-profile-processes.test.ts -116 tests/codex-integration/native-profile-recovery.test.ts -487 tests/codex-integration/native-profile-route-security.test.ts -304 tests/codex-integration/native-profile-stage-lifecycle.test.ts -340 tests/codex-integration/native-profile-startup-release.test.ts -13565 tests/codex-integration/native-profile-startup.test.ts -252 tests/codex-integration/native-profile-store.test.ts -221 tests/codex-integration/native-source-priority.test.ts -1252 tests/codex-integration/native-ultrafast-picker.test.ts -288 tests/codex-integration/orca-import.test.ts -82 tests/codex-integration/parallel-tool-calls-optin.test.ts -56 tests/codex-integration/pool-monthly-window-retirement.test.ts -95 tests/codex-integration/project-config-warning-snapshot.test.ts -191 tests/codex-integration/project-config-warnings.test.ts -152 tests/codex-integration/reasoning-effort.test.ts -118 tests/codex-integration/reasoning-metadata.test.ts -576 tests/codex-integration/reserve-auth-context.test.ts -47 tests/codex-integration/reserve-availability.test.ts -5755 tests/codex-integration/reserve-catalog-lifecycle.test.ts -271 tests/codex-integration/reserve-catalog.test.ts -1511 tests/codex-integration/reserve-dispatch.test.ts -180 tests/codex-integration/reserve-helper-boundary.test.ts -63 tests/codex-integration/reserve-passive-revocation.test.ts -299 tests/codex-integration/reserve-quota-scope.test.ts -269 tests/codex-integration/selected-models.test.ts -142 tests/codex-integration/slug-codec.test.ts -242 tests/codex-integration/token-guardian.test.ts -844 tests/codex-integration/ultrafast-live-catalog.test.ts -984 tests/codex-integration/ultrafast-tier-honesty.test.ts -190 tests/codex-integration/upstream-reachability.test.ts +4839 tests/codex-integration/codex-convergence-account-selectors.test.ts +1184 tests/codex-integration/codex-convergence-contract.test.ts +269 tests/codex-integration/codex-cooldown-recovery.test.ts +174 tests/codex-integration/codex-coordinator-doctor.test.ts +804 tests/codex-integration/codex-credit-retry-after.test.ts +332 tests/codex-integration/codex-credit-scoped-retry.test.ts +187 tests/codex-integration/codex-credits-after-limit-main.test.ts +226 tests/codex-integration/codex-credits-after-limit.test.ts +194 tests/codex-integration/codex-credits-probes.test.ts +298 tests/codex-integration/codex-credits-settings.test.ts +64 tests/codex-integration/codex-credits.test.ts +159 tests/codex-integration/codex-desired-state.test.ts +362 tests/codex-integration/codex-direct-credit-renewal.test.ts +209 tests/codex-integration/codex-direct-renewal-revocation.test.ts +58 tests/codex-integration/codex-disconnect-fields.test.ts +61 tests/codex-integration/codex-disconnect-owned-recovery.test.ts +91 tests/codex-integration/codex-entitlement-identity-read-fence.test.ts +566 tests/codex-integration/codex-envkey-admission-substitution.test.ts +107 tests/codex-integration/codex-exec-invocation.test.ts +442 tests/codex-integration/codex-failure-window.test.ts +75 tests/codex-integration/codex-features-cache.test.ts +86 tests/codex-integration/codex-features-residual.test.ts +104 tests/codex-integration/codex-filesystem-evidence.test.ts +172 tests/codex-integration/codex-forward-access-programs-writer.test.ts +361 tests/codex-integration/codex-gather-authority.test.ts +2261 tests/codex-integration/codex-history-job.test.ts +135 tests/codex-integration/codex-history-lock.test.ts +78 tests/codex-integration/codex-history-pending-wal.test.ts +1905 tests/codex-integration/codex-history-provider.test.ts +543 tests/codex-integration/codex-history-reachability.test.ts +57 tests/codex-integration/codex-history-worker-boundary.test.ts +1534 tests/codex-integration/codex-history-worker.test.ts +72 tests/codex-integration/codex-history-writer.test.ts +10325 tests/codex-integration/codex-home-owner-lifecycle.test.ts +1427 tests/codex-integration/codex-home-owner.test.ts +55 tests/codex-integration/codex-home-wsl-local-state.test.ts +172 tests/codex-integration/codex-home-wsl.test.ts +246 tests/codex-integration/codex-idle-window.test.ts +875 tests/codex-integration/codex-inject-catalog-tilde.test.ts +151 tests/codex-integration/codex-inject-history-wording.test.ts +72828 tests/codex-integration/codex-inject-integration.test.ts +3727 tests/codex-integration/codex-inject-missing-config.test.ts +800 tests/codex-integration/codex-inject-retained-table.test.ts +13944 tests/codex-integration/codex-inject-v1-reconcile.test.ts +8493 tests/codex-integration/codex-inject-write-lock.test.ts +125 tests/codex-integration/codex-inject.test.ts +50 tests/codex-integration/codex-injected-marker.test.ts +65 tests/codex-integration/codex-installation-acl.test.ts +96 tests/codex-integration/codex-installation-id.test.ts +588 tests/codex-integration/codex-installation-invalid-account.test.ts +936 tests/codex-integration/codex-installation-live-content.test.ts +623 tests/codex-integration/codex-installation-live-http.test.ts +781 tests/codex-integration/codex-installation-live-ws.test.ts +385 tests/codex-integration/codex-installation-sidecars.test.ts +128 tests/codex-integration/codex-installation-wire.test.ts +97 tests/codex-integration/codex-integration-record.test.ts +311 tests/codex-integration/codex-journal-provider-reserialization.test.ts +3330 tests/codex-integration/codex-journal-recovery.test.ts +19776 tests/codex-integration/codex-journal.test.ts +276 tests/codex-integration/codex-launcher-admission.test.ts +64 tests/codex-integration/codex-launcher-darwin-acl.test.ts +91 tests/codex-integration/codex-launcher-darwin-identity.test.ts +223 tests/codex-integration/codex-launcher-diagnostics.test.ts +167 tests/codex-integration/codex-launcher-endpoint.test.ts +244 tests/codex-integration/codex-launcher-env.test.ts +3021 tests/codex-integration/codex-launcher-process.test.ts +144 tests/codex-integration/codex-launcher-security.test.ts +129 tests/codex-integration/codex-launcher.test.ts +83 tests/codex-integration/codex-legacy-config-keys.test.ts +239 tests/codex-integration/codex-lineage-placement.test.ts +371 tests/codex-integration/codex-linked-account-pause.test.ts +102 tests/codex-integration/codex-log-guard-coderabbit.test.ts +44 tests/codex-integration/codex-log-guard-doctor-coderabbit.test.ts +61 tests/codex-integration/codex-log-guard-doctor-protection.test.ts +53 tests/codex-integration/codex-log-guard-doctor.test.ts +144 tests/codex-integration/codex-log-guard-inspect.test.ts +53 tests/codex-integration/codex-log-guard-lock.test.ts +385 tests/codex-integration/codex-log-guard-maintenance-coderabbit.test.ts +685 tests/codex-integration/codex-log-guard-maintenance.test.ts +115 tests/codex-integration/codex-log-guard-policy.test.ts +51 tests/codex-integration/codex-log-guard-processes.test.ts +152 tests/codex-integration/codex-log-guard-protection.test.ts +63 tests/codex-integration/codex-log-guard-status-zero-write.test.ts +180 tests/codex-integration/codex-main-account-refresh.test.ts +384 tests/codex-integration/codex-main-grant-refusal.test.ts +319 tests/codex-integration/codex-main-rotation.test.ts +190 tests/codex-integration/codex-main-token-invalidated.test.ts +94 tests/codex-integration/codex-management-convergence.test.ts +152 tests/codex-integration/codex-metadata-integrity.test.ts +7745 tests/codex-integration/codex-missing-home.test.ts +102 tests/codex-integration/codex-model-availability-error.test.ts +195 tests/codex-integration/codex-model-denial-evidence.test.ts +81 tests/codex-integration/codex-model-entitlement-admission.test.ts +151 tests/codex-integration/codex-model-entitlements-program-shape.test.ts +194 tests/codex-integration/codex-model-entitlements.test.ts +148 tests/codex-integration/codex-models-cache-invalidate.test.ts +955 tests/codex-integration/codex-native-availability-nux.test.ts +640 tests/codex-integration/codex-native-residue.test.ts +155 tests/codex-integration/codex-pin-drain-projection.test.ts +166 tests/codex-integration/codex-plan.test.ts +459 tests/codex-integration/codex-plugins-doctor.test.ts +122 tests/codex-integration/codex-pool-caller-fallback-policy.test.ts +214 tests/codex-integration/codex-pool-credit-policy.test.ts +177 tests/codex-integration/codex-pool-only-policy.test.ts +139 tests/codex-integration/codex-pool-plan-exclusion.test.ts +52 tests/codex-integration/codex-pool-refresh-backoff.test.ts +258 tests/codex-integration/codex-pool-request-owned-main.test.ts +798 tests/codex-integration/codex-pool-rotation.test.ts +349 tests/codex-integration/codex-preserve-signed-in.test.ts +326 tests/codex-integration/codex-priority-failback.test.ts +64 tests/codex-integration/codex-proc-scan-errors.test.ts +5551 tests/codex-integration/codex-profile-preservation.test.ts +95 tests/codex-integration/codex-prompt-adopt.test.ts +263 tests/codex-integration/codex-prompt-base-variants.test.ts +89 tests/codex-integration/codex-prompt-journal.test.ts +60 tests/codex-integration/codex-prompt-layers-read.test.ts +199 tests/codex-integration/codex-prompt-layers-write.test.ts +52 tests/codex-integration/codex-prompt-layers.test.ts +244 tests/codex-integration/codex-prompt-lock-sharing.test.ts +394 tests/codex-integration/codex-prompt-lock.test.ts +1385 tests/codex-integration/codex-prompt-route.test.ts +186 tests/codex-integration/codex-prompt-scalar-scope.test.ts +975 tests/codex-integration/codex-prompt-text-probe.test.ts +653 tests/codex-integration/codex-prompt-writes.test.ts +16823 tests/codex-integration/codex-provider-routing.test.ts +785 tests/codex-integration/codex-provider-table-retention.test.ts +106 tests/codex-integration/codex-quota-auto-refresh-generation.test.ts +190 tests/codex-integration/codex-quota-auto-refresh-main-admission.test.ts +393 tests/codex-integration/codex-quota-auto-refresh.test.ts +73 tests/codex-integration/codex-quota-capacity.test.ts +143 tests/codex-integration/codex-quota-history.test.ts +116 tests/codex-integration/codex-quota-parser-parity.test.ts +63 tests/codex-integration/codex-quota-persistence.test.ts +440 tests/codex-integration/codex-quota-prime.test.ts +123 tests/codex-integration/codex-quota-query-backoff.test.ts +323 tests/codex-integration/codex-quota-rejection.test.ts +70 tests/codex-integration/codex-quota-weekly-rollover.test.ts +404 tests/codex-integration/codex-quota-window-conflict.test.ts +175 tests/codex-integration/codex-refresh.test.ts +305 tests/codex-integration/codex-request-owned-affinity.test.ts +809 tests/codex-integration/codex-reset-credit-auto-redeem.test.ts +462 tests/codex-integration/codex-reset-credit-operation-ledger.test.ts +351 tests/codex-integration/codex-reset-credit-recovery.test.ts +76 tests/codex-integration/codex-restart-contract-parity.test.ts +384 tests/codex-integration/codex-restart-route.test.ts +5392 tests/codex-integration/codex-restore-app-rewrite.test.ts +12127 tests/codex-integration/codex-restore-later-edits.test.ts +198 tests/codex-integration/codex-resume-if-healthy.test.ts +7505 tests/codex-integration/codex-retained-root-serialization.test.ts +264 tests/codex-integration/codex-round-robin-headroom.test.ts +132 tests/codex-integration/codex-routing-cache-affinity-detour.test.ts +102 tests/codex-integration/codex-routing-elapsed-short-reset.test.ts +4503 tests/codex-integration/codex-routing.test.ts +194 tests/codex-integration/codex-runtime-macos-desktop.test.ts +65 tests/codex-integration/codex-runtime-wsl-desktop.test.ts +198 tests/codex-integration/codex-runtime.test.ts +481 tests/codex-integration/codex-service-manager-probe-hardening.test.ts +271 tests/codex-integration/codex-service-manager-probe.test.ts +37857 tests/codex-integration/codex-shim-autorestore.test.ts +139 tests/codex-integration/codex-shim-bypass-token.test.ts +223 tests/codex-integration/codex-shim-destroyed-probe.test.ts +116 tests/codex-integration/codex-shim-ensure-failure.test.ts +89 tests/codex-integration/codex-shim-fnm.test.ts +105 tests/codex-integration/codex-shim-legacy-record.test.ts +469 tests/codex-integration/codex-shim-migration.test.ts +106 tests/codex-integration/codex-shim-overlay-candidates.test.ts +664 tests/codex-integration/codex-shim-overlay-readiness.test.ts +1995 tests/codex-integration/codex-shim-overlay-transaction.test.ts +691 tests/codex-integration/codex-shim-overlay.test.ts +3667 tests/codex-integration/codex-shim-path-readiness.test.ts +28766 tests/codex-integration/codex-shim-readiness.test.ts +110 tests/codex-integration/codex-shim-runtime-preflight.test.ts +837 tests/codex-integration/codex-shim-standalone.test.ts +190 tests/codex-integration/codex-shim-windows-revision.test.ts +25318 tests/codex-integration/codex-shim.test.ts +1713 tests/codex-integration/codex-sidecar-credit-policy.test.ts +129 tests/codex-integration/codex-signin-lockout.test.ts +219 tests/codex-integration/codex-spark-visibility.test.ts +92 tests/codex-integration/codex-sqlite-home.test.ts +301 tests/codex-integration/codex-stored-main-duplicate.test.ts +1477 tests/codex-integration/codex-sync-api.test.ts +388 tests/codex-integration/codex-sync-new-model-policy.test.ts +64 tests/codex-integration/codex-sync-response.test.ts +20729 tests/codex-integration/codex-sync-user-edits.test.ts +189 tests/codex-integration/codex-systemd-env-probe.test.ts +165 tests/codex-integration/codex-tool-mode.test.ts +617 tests/codex-integration/codex-transition-state-adoption.test.ts +101 tests/codex-integration/codex-transition-state-first-use-regression.test.ts +1828 tests/codex-integration/codex-transition-state-race.test.ts +257 tests/codex-integration/codex-transition-state.test.ts +233 tests/codex-integration/codex-use-remaining-quota.test.ts +87 tests/codex-integration/codex-user-identity.test.ts +676 tests/codex-integration/codex-v2-gate.test.ts +346 tests/codex-integration/codex-warmup.test.ts +3480 tests/codex-integration/codex-web-search-switch.test.ts +50 tests/codex-integration/codex-websocket-registry.test.ts +57 tests/codex-integration/codex-windows-current-sid.test.ts +2932 tests/codex-integration/codex-write-lock.test.ts +56 tests/codex-integration/combo-authoritative-reset.test.ts +54 tests/codex-integration/combo-codex-exhaustion-cooldown.test.ts +107 tests/codex-integration/combo-cooldown-reprobe.test.ts +669 tests/codex-integration/combo-description-catalog.test.ts +71 tests/codex-integration/combo-last-resort.test.ts +54 tests/codex-integration/combo-permanent-failure-cooldown.test.ts +66 tests/codex-integration/combo-reset-window-model-scope.test.ts +70 tests/codex-integration/combos-kiro-profile-hop.test.ts +355 tests/codex-integration/combos.test.ts +700 tests/codex-integration/compatibility-manifest.test.ts +128 tests/codex-integration/configured-native-models.test.ts +1885 tests/codex-integration/configured-ultrafast-picker.test.ts +78 tests/codex-integration/context-compat.test.ts +62 tests/codex-integration/custom-model-catalog-migration.test.ts +275 tests/codex-integration/deferred-collab-surface.test.ts +179 tests/codex-integration/discovered-native-models.test.ts +488 tests/codex-integration/doctor.test.ts +348 tests/codex-integration/effort-policy.test.ts +378 tests/codex-integration/exec-boundary-launch.test.ts +139 tests/codex-integration/exec-cli-bundle-containment.test.ts +245 tests/codex-integration/exec-cli-renamed-app-bundle.test.ts +152 tests/codex-integration/exec-known-app-bundles.test.ts +137 tests/codex-integration/exec-launcher-boundary.test.ts +100 tests/codex-integration/exec-renamed-app-bundle.test.ts +743 tests/codex-integration/exec-trust-boundary.test.ts +127 tests/codex-integration/fast-row-listing.test.ts +105 tests/codex-integration/fast-row.test.ts +179 tests/codex-integration/gather-routed-models-single-flight.test.ts +177 tests/codex-integration/gpt6-native-rows.test.ts +109 tests/codex-integration/gpt61-sol-rows.test.ts +163 tests/codex-integration/gpt61-terra-rows.test.ts +138 tests/codex-integration/gpt62-output-limits.test.ts +114 tests/codex-integration/gpt62-rows.test.ts +64 tests/codex-integration/history-migration-guardian.test.ts +55 tests/codex-integration/history-ocx-compaction-recovery.test.ts +68 tests/codex-integration/history-paginated-openai-compat.test.ts +3165 tests/codex-integration/history-paginated-transition-destinations.test.ts +128 tests/codex-integration/injection-link-websocket.test.ts +284 tests/codex-integration/injection-model-api.test.ts +230 tests/codex-integration/injection-model-suggest-routes.test.ts +88 tests/codex-integration/injection-routing-drift.test.ts +4318 tests/codex-integration/injection-routing-heal-apply.test.ts +596 tests/codex-integration/injection-routing-healer.test.ts +5822 tests/codex-integration/issue-452-empty-503.test.ts +2978 tests/codex-integration/issue-702-expired-replay-state.test.ts +638 tests/codex-integration/issue-914-transport-attribution.test.ts +176 tests/codex-integration/low-quota-desktop-notifier.test.ts +1310 tests/codex-integration/low-quota-protection.test.ts +466 tests/codex-integration/main-account-credit-renewal.test.ts +47 tests/codex-integration/main-account-external-usage.test.ts +18851 tests/codex-integration/main-account-hard-lock-auth.test.ts +216 tests/codex-integration/main-account-hard-lock-default.test.ts +637 tests/codex-integration/main-account-hard-lock-fallback-off.test.ts +646 tests/codex-integration/main-account-hard-lock-fallback-routing.test.ts +63 tests/codex-integration/main-account-hard-lock-policy.test.ts +349 tests/codex-integration/main-account-hard-lock-profile-dispatch.test.ts +607 tests/codex-integration/main-account-hard-lock-recovery.test.ts +183 tests/codex-integration/main-account-hard-lock-refusal-read.test.ts +95 tests/codex-integration/main-account-hard-lock-retirement.test.ts +55 tests/codex-integration/main-account-hard-lock-thresholds.test.ts +169 tests/codex-integration/main-account-hard-lock-usage-limit.test.ts +626 tests/codex-integration/main-account-policy-binding-wait.test.ts +87 tests/codex-integration/main-device-reauth-api.test.ts +212 tests/codex-integration/main-device-reauth.test.ts +152 tests/codex-integration/main-quota-evidence-validation.test.ts +22426 tests/codex-integration/main-quota-provenance.test.ts +475 tests/codex-integration/main-quota-window-observation.test.ts +3630 tests/codex-integration/messaging-local-cli.test.ts +127 tests/codex-integration/messaging-local-discovery.test.ts +169 tests/codex-integration/messaging-local-envelope.test.ts +807 tests/codex-integration/messaging-local-lifecycle.test.ts +369 tests/codex-integration/messaging-local-send.test.ts +62 tests/codex-integration/messaging-local-socket.test.ts +12517 tests/codex-integration/messaging-mcp-queue.test.ts +12598 tests/codex-integration/messaging-mcp-replies.test.ts +210 tests/codex-integration/messaging-mcp-resume.test.ts +64531 tests/codex-integration/messaging-mcp-wait.test.ts +4539 tests/codex-integration/messaging-remote-admission.test.ts +314 tests/codex-integration/messaging-remote-contract.test.ts +414 tests/codex-integration/messaging-remote-enrollment-gaps.test.ts +9088 tests/codex-integration/messaging-remote-enrollment.test.ts +57 tests/codex-integration/messaging-remote-forward-failure.test.ts +2557 tests/codex-integration/messaging-remote-gaps.test.ts +52 tests/codex-integration/messaging-remote-interop.test.ts +14783 tests/codex-integration/messaging-remote-lifecycle.test.ts +51 tests/codex-integration/messaging-remote-native.test.ts +98 tests/codex-integration/messaging-remote-port-reservation.test.ts +13301 tests/codex-integration/messaging-remote-process.test.ts +1617 tests/codex-integration/messaging-remote-replies.test.ts +1266 tests/codex-integration/messaging-remote-scratch.test.ts +5973 tests/codex-integration/messaging-remote-send.test.ts +515 tests/codex-integration/messaging-remote-store.test.ts +45 tests/codex-integration/model-cache-generation-tombstone.test.ts +49 tests/codex-integration/model-cache.test.ts +250 tests/codex-integration/model-display-names-management-api.test.ts +143 tests/codex-integration/model-metadata-sync.test.ts +867 tests/codex-integration/model-pinned-effort.test.ts +843 tests/codex-integration/model-visibility-management-api.test.ts +749 tests/codex-integration/multi-agent-compat.test.ts +416 tests/codex-integration/multi-agent-keep-native-v1.test.ts +147 tests/codex-integration/multi-agent-origin.test.ts +419 tests/codex-integration/multi-agent-v2-plaintext.test.ts +152 tests/codex-integration/native-alias-maintainer-regressions.test.ts +219 tests/codex-integration/native-claude-code-toggle.test.ts +514 tests/codex-integration/native-claude-desktop-toggle.test.ts +4035 tests/codex-integration/native-codex-toggle.test.ts +625 tests/codex-integration/native-grok-toggle.test.ts +68 tests/codex-integration/native-main-auth-temp.test.ts +37 tests/codex-integration/native-main-claim-cache.test.ts +140 tests/codex-integration/native-main-claim.test.ts +375 tests/codex-integration/native-main-credentials-retention.test.ts +8340 tests/codex-integration/native-main-owner-lifetime.test.ts +1097 tests/codex-integration/native-main-refresh-mode.test.ts +340 tests/codex-integration/native-model-toggle.test.ts +91 tests/codex-integration/native-profile-api.test.ts +7718 tests/codex-integration/native-profile-crash-boundaries.test.ts +2005 tests/codex-integration/native-profile-drain-server.test.ts +921 tests/codex-integration/native-profile-healthz.test.ts +2586 tests/codex-integration/native-profile-manager.test.ts +365 tests/codex-integration/native-profile-processes.test.ts +52 tests/codex-integration/native-profile-recovery.test.ts +705 tests/codex-integration/native-profile-route-security.test.ts +271 tests/codex-integration/native-profile-stage-lifecycle.test.ts +314 tests/codex-integration/native-profile-startup-release.test.ts +14319 tests/codex-integration/native-profile-startup.test.ts +387 tests/codex-integration/native-profile-store.test.ts +138 tests/codex-integration/native-source-priority.test.ts +1639 tests/codex-integration/native-ultrafast-picker.test.ts +395 tests/codex-integration/orca-import.test.ts +122 tests/codex-integration/parallel-tool-calls-optin.test.ts +113 tests/codex-integration/pool-monthly-window-retirement.test.ts +57 tests/codex-integration/project-config-warning-snapshot.test.ts +223 tests/codex-integration/project-config-warnings.test.ts +314 tests/codex-integration/reasoning-effort.test.ts +111 tests/codex-integration/reasoning-metadata.test.ts +372 tests/codex-integration/reserve-auth-context.test.ts +77 tests/codex-integration/reserve-availability.test.ts +5932 tests/codex-integration/reserve-catalog-lifecycle.test.ts +275 tests/codex-integration/reserve-catalog.test.ts +1544 tests/codex-integration/reserve-dispatch.test.ts +183 tests/codex-integration/reserve-helper-boundary.test.ts +120 tests/codex-integration/reserve-passive-revocation.test.ts +145 tests/codex-integration/reserve-quota-scope.test.ts +105 tests/codex-integration/selected-models.test.ts +122 tests/codex-integration/slug-codec.test.ts +217 tests/codex-integration/token-guardian.test.ts +1042 tests/codex-integration/ultrafast-live-catalog.test.ts +1396 tests/codex-integration/ultrafast-tier-honesty.test.ts +101 tests/codex-integration/upstream-reachability.test.ts 150 tests/codex-integration/vendor-context.test.ts -29 tests/codex-integration/warmup.test.ts -213 tests/codex-integration/websocket-capacity-activity.test.ts -115 tests/config/atomic-write-exclusive.test.ts -108 tests/config/atomic-write-nofollow-streamed.test.ts -181 tests/config/client-config-export-new-clients.test.ts -165 tests/config/client-config-export-output-limit.test.ts -145 tests/config/client-config-export.test.ts -62 tests/config/client-config-kimi-efforts.test.ts -206 tests/config/client-config-new-clients.test.ts -108 tests/config/compaction-recovery-settings.test.ts -622 tests/config/config-account-auto-pause-revisions.test.ts -45 tests/config/config-account-thresholds.test.ts -254 tests/config/config-anthropic-instance-pool.test.ts -42 tests/config/config-blocked-model-redirects.test.ts -48 tests/config/config-catalog-auto-refresh.test.ts -33 tests/config/config-commandcode-claude-pin.test.ts -64 tests/config/config-concurrent-inbound-body.test.ts -39 tests/config/config-hosted-search-projection.test.ts -182 tests/config/config-load-degrade.test.ts -701 tests/config/config-mutation-lock.test.ts -41 tests/config/config-native-reasoning-retention.test.ts -62 tests/config/config-non-object-backup.test.ts -151 tests/config/config-opencode-go-upgrade.test.ts -143 tests/config/config-opencode-zen-upgrade.test.ts -3031 tests/config/config-ownership-concurrent-record.test.ts -420 tests/config/config-ownership-removal.test.ts -159 tests/config/config-ownership-uninstall.test.ts -105 tests/config/config-rebase-provenance-writers.test.ts -109 tests/config/config-removed-opencode-free-preserve-failure.test.ts -1459 tests/config/config-removed-opencode-free.test.ts -45 tests/config/config-save-boundary.test.ts -47 tests/config/config-skills-catalog-refresh.test.ts -45 tests/config/config-spend-ceilings.test.ts -54 tests/config/config-spend-pool-collision.test.ts -58 tests/config/config-thinking-display.test.ts -343 tests/config/config-user-edits.test.ts -41 tests/config/config-workflow-budget.test.ts -45 tests/config/expand-user-path.test.ts -263 tests/config/hub-disable-live-save.test.ts -57 tests/config/lmstudio-system-policy.test.ts -4129 tests/config/local-credential-generation.test.ts -236 tests/config/model-pinned-effort-config.test.ts -69 tests/config/owner-registry-acl.test.ts -90 tests/config/owner-registry-isolation.test.ts -98 tests/config/protocol-settings.test.ts -1042 tests/config/serving-runtimes.test.ts -3333 tests/config/settings-desktop-switch-apply.test.ts -132 tests/config/settings-fast-rows.test.ts -214 tests/config/settings-main-account-hard-lock.test.ts -153 tests/config/settings-memory-models.test.ts -117 tests/config/settings-oauth-open-browser.test.ts -238 tests/config/settings-reasoning-retention.test.ts -104 tests/config/settings-startup-health-seam.test.ts -13069 tests/config/settings-stream-mode.test.ts -81 tests/config/telemetry-live-save.test.ts -55 tests/config/types-barrel-identity.test.ts -116 tests/config/url-normalization.test.ts -61 tests/config/yaml-fragment-source.test.ts -93 tests/e2e-style/phase100-native-parity.test.ts -37 tests/gui/alibaba-intl-token-plan.test.ts -36 tests/gui/claude-manual-env.test.ts -35 tests/gui/codex-account-mode-state.test.ts -34 tests/gui/codex-auth-modal-status.test.ts -30 tests/gui/codex-set-prompt.test.ts -43 tests/gui/combo-workspace-data.test.ts -42 tests/gui/combo-workspace-jev-decision.test.ts -43 tests/gui/dashboard-sidecar-codex-write.test.ts -76 tests/gui/dashboard-uptime.test.ts -37 tests/gui/gui-api-error.test.ts -63 tests/gui/gui-codex-usage-score-parity.test.ts -38 tests/gui/gui-desktop-sidecar-script.test.ts -51 tests/gui/gui-desktop-sidecar-signing.test.ts -113 tests/gui/gui-management-session.test.ts -33 tests/gui/gui-pair-capability.test.ts -128 tests/gui/gui-pair-client.test.ts -180 tests/gui/gui-pair-delivery.test.ts -1965 tests/gui/gui-pair-http.test.ts -43 tests/gui/gui-static.test.ts -36 tests/gui/gui-tray-vibrancy-surface.test.ts -60 tests/gui/html-lang-boot-script.test.ts -186 tests/gui/integrations-invariants.test.ts -51 tests/gui/logs-model-tier-confirmation.test.ts -45 tests/gui/main-device-reauth-ui.test.ts -28 tests/gui/models-feedback-callback.test.ts -48 tests/gui/models-free-filter.test.ts -29 tests/gui/models-page-groups.test.ts +52 tests/codex-integration/warmup.test.ts +233 tests/codex-integration/websocket-capacity-activity.test.ts +187 tests/config/agy-acp-config.test.ts +122 tests/config/atomic-write-exclusive.test.ts +135 tests/config/atomic-write-nofollow-streamed.test.ts +128 tests/config/client-config-export-new-clients.test.ts +138 tests/config/client-config-export-output-limit.test.ts +257 tests/config/client-config-export.test.ts +121 tests/config/client-config-kimi-efforts.test.ts +183 tests/config/client-config-new-clients.test.ts +152 tests/config/compaction-recovery-settings.test.ts +435 tests/config/config-account-auto-pause-revisions.test.ts +86 tests/config/config-account-thresholds.test.ts +291 tests/config/config-anthropic-instance-pool.test.ts +61 tests/config/config-blocked-model-redirects.test.ts +67 tests/config/config-catalog-auto-refresh.test.ts +71 tests/config/config-commandcode-claude-pin.test.ts +103 tests/config/config-concurrent-inbound-body.test.ts +125 tests/config/config-hosted-search-projection.test.ts +590 tests/config/config-load-degrade.test.ts +831 tests/config/config-mutation-lock.test.ts +70 tests/config/config-native-reasoning-retention.test.ts +51 tests/config/config-non-object-backup.test.ts +189 tests/config/config-opencode-go-upgrade.test.ts +128 tests/config/config-opencode-zen-upgrade.test.ts +3937 tests/config/config-ownership-concurrent-record.test.ts +278 tests/config/config-ownership-removal.test.ts +139 tests/config/config-ownership-uninstall.test.ts +56 tests/config/config-rebase-provenance-writers.test.ts +152 tests/config/config-removed-opencode-free-preserve-failure.test.ts +2167 tests/config/config-removed-opencode-free.test.ts +112 tests/config/config-routed-catalog-defaults.test.ts +78 tests/config/config-save-boundary.test.ts +70 tests/config/config-skills-catalog-refresh.test.ts +75 tests/config/config-spend-ceilings.test.ts +78 tests/config/config-spend-pool-collision.test.ts +62 tests/config/config-thinking-display.test.ts +407 tests/config/config-user-edits.test.ts +70 tests/config/config-workflow-budget.test.ts +59 tests/config/expand-user-path.test.ts +420 tests/config/hub-disable-live-save.test.ts +59 tests/config/lmstudio-system-policy.test.ts +347 tests/config/local-credential-fence.test.ts +3807 tests/config/local-credential-generation.test.ts +304 tests/config/model-pinned-effort-config.test.ts +75 tests/config/owner-registry-acl.test.ts +101 tests/config/owner-registry-isolation.test.ts +120 tests/config/protocol-settings.test.ts +382 tests/config/reserve-capability-migration.test.ts +69 tests/config/routing-profile-types-reexport.test.ts +1071 tests/config/serving-runtimes.test.ts +4333 tests/config/settings-desktop-switch-apply.test.ts +199 tests/config/settings-fast-rows.test.ts +296 tests/config/settings-main-account-hard-lock.test.ts +261 tests/config/settings-memory-models.test.ts +184 tests/config/settings-oauth-open-browser.test.ts +240 tests/config/settings-reasoning-retention.test.ts +181 tests/config/settings-startup-health-seam.test.ts +13395 tests/config/settings-stream-mode.test.ts +155 tests/config/telemetry-live-save.test.ts +51 tests/config/types-barrel-identity.test.ts +43 tests/config/url-normalization.test.ts +50 tests/config/yaml-fragment-source.test.ts +929 tests/e2e-style/link-child-catalog-oracle.test.ts +800 tests/e2e-style/link-gate-codex-binary.test.ts +240 tests/e2e-style/link-websocket-child-gate.test.ts +207 tests/e2e-style/link-websocket-child-restart.test.ts +211 tests/e2e-style/link-websocket-release-gate.test.ts +173 tests/e2e-style/link-websocket-rss-child.test.ts +95 tests/e2e-style/link-websocket-rss.test.ts +614 tests/e2e-style/link-ws-child-home.test.ts +199 tests/e2e-style/phase100-native-parity.test.ts +57 tests/gui/alibaba-intl-token-plan.test.ts +50 tests/gui/claude-manual-env.test.ts +46 tests/gui/codex-account-mode-state.test.ts +58 tests/gui/codex-auth-modal-status.test.ts +46 tests/gui/codex-set-prompt.test.ts +56 tests/gui/combo-workspace-data.test.ts +58 tests/gui/combo-workspace-jev-decision.test.ts +72 tests/gui/dashboard-sidecar-codex-write.test.ts +91 tests/gui/dashboard-uptime.test.ts +45 tests/gui/gui-api-error.test.ts +94 tests/gui/gui-codex-usage-score-parity.test.ts +52 tests/gui/gui-desktop-sidecar-script.test.ts +48 tests/gui/gui-desktop-sidecar-signing.test.ts +145 tests/gui/gui-management-session.test.ts +52 tests/gui/gui-pair-capability.test.ts +267 tests/gui/gui-pair-client.test.ts +386 tests/gui/gui-pair-delivery.test.ts +6535 tests/gui/gui-pair-http.test.ts +72 tests/gui/gui-static.test.ts +46 tests/gui/gui-tray-vibrancy-surface.test.ts +101 tests/gui/html-lang-boot-script.test.ts +309 tests/gui/integrations-invariants.test.ts +65 tests/gui/logs-model-tier-confirmation.test.ts +76 tests/gui/main-device-reauth-ui.test.ts +47 tests/gui/models-feedback-callback.test.ts +52 tests/gui/models-free-filter.test.ts +57 tests/gui/models-page-groups.test.ts 52 tests/gui/models-workspace-tabs.test.ts -32 tests/gui/oauth-first-add-hint.test.ts -64 tests/gui/oauth-tos-warning.test.ts -525 tests/gui/platform-dialog-guard.test.ts -52 tests/gui/provider-payload.test.ts -79 tests/gui/provider-subscription-cli.test.ts -40 tests/gui/provider-workspace-auth.test.ts -95 tests/gui/provider-workspace-data.test.ts -81 tests/gui/provider-workspace-rail.test.ts -63 tests/gui/provider-workspace-state.test.ts -69 tests/gui/quota-bars-rows.test.ts -36 tests/gui/qwen-cloud-endpoints.test.ts -38 tests/gui/rate-limit-reset-credits.test.ts -44 tests/gui/routing-intelligence-ui.test.ts -42 tests/gui/routing-profile-editor-data.test.ts -35 tests/gui/standalone-build-script.test.ts -767 tests/gui/startup-health-ui.test.ts -92 tests/gui/tencent-siliconflow-providers.test.ts -96 tests/gui/vision-sidecar-timeout-bounds.test.ts -176 tests/gui/volcengine-providers.test.ts -89 tests/images/artifacts-prune.test.ts -84 tests/images/artifacts-ssrf.test.ts -73 tests/images/download-cap-default.test.ts -82 tests/images/download-connect-deadline-default.test.ts -49 tests/images/gemini-inline.test.ts -88 tests/images/loop-reasoning-replay.test.ts -60 tests/images/loop-terminal-refusal.test.ts -3101 tests/images/loop.test.ts -47 tests/images/pinned-https-get.test.ts -90 tests/images/plan.test.ts -45 tests/images/synthetic-tool.test.ts -189 tests/images/xai-client.test.ts -133 tests/images/z-fulfill.test.ts -288 tests/images/z-handler-activation.test.ts -424 tests/lab/core-lab-boundary.test.ts -236 tests/lab/core-link-boundary.test.ts -251 tests/lab/lab-activation.test.ts -233 tests/lab/lab-automation-coderabbit-regressions.test.ts -152 tests/lab/lab-automation-final-coderabbit-regressions.test.ts -131 tests/lab/lab-automation-ingwannu-regressions.test.ts -166 tests/lab/lab-automation-management-http.test.ts -44 tests/lab/lab-automation-persisted-cap-regression.test.ts -325 tests/lab/lab-automation-review-regressions.test.ts -261 tests/lab/lab-automation.test.ts -123 tests/lab/lab-community-evidence.test.ts -261 tests/lab/lab-community-filename-contract.test.ts -204 tests/lab/lab-community-mutation-lock.test.ts -100 tests/lab/lab-community-publisher-continuity.test.ts -118 tests/lab/lab-conformance-harness.test.ts -104 tests/lab/lab-conformance-runner-failures.test.ts -378 tests/lab/lab-evidence-ledger.test.ts -219 tests/lab/lab-evidence-sanitization.test.ts -94 tests/lab/lab-fabric-outcome-validation.test.ts -43 tests/lab/lab-fabric-persistence-boundary.test.ts -166 tests/lab/lab-fabric-producer-deadline.test.ts -95773 tests/lab/lab-fabric-task.test.ts -40 tests/lab/lab-installation-salt-cache.test.ts -815 tests/lab/lab-ledger-mutation-lock.test.ts -303 tests/lab/lab-live-pinned-timeouts.test.ts -125 tests/lab/lab-live-probe.test.ts -124 tests/lab/lab-live-receipt-integrity.test.ts -81 tests/lab/lab-live-review-regressions.test.ts -199 tests/lab/lab-live-sandbox.test.ts -109 tests/lab/lab-passive-production-evidence.test.ts -316 tests/lab/lab-passive-production-surfaces.test.ts -28 tests/lab/lab-paths-security.test.ts -150 tests/lab/lab-post-merge-hardening.test.ts -174 tests/lab/lab-post-merge-projection.test.ts -39 tests/lab/lab-private-file-consumer-recovery.test.ts -40 tests/lab/lab-private-file-durability.test.ts -118 tests/lab/lab-public-api-json.test.ts -74 tests/lab/lab-public-artifact-policy.test.ts -234 tests/lab/lab-public-coderabbit-regressions.test.ts -38 tests/lab/lab-public-core-contract.test.ts -128 tests/lab/lab-public-deep-review-regressions.test.ts -108 tests/lab/lab-public-evidence.test.ts -105 tests/lab/lab-public-export-transaction.test.ts -74 tests/lab/lab-public-file-safety.test.ts -159 tests/lab/lab-public-final-review-regressions.test.ts -255 tests/lab/lab-public-lifecycle-hardening.test.ts -54 tests/lab/lab-public-privacy-ipv6.test.ts -354 tests/lab/lab-public-provenance-recovery.test.ts -218 tests/lab/lab-public-review-fixes.test.ts -57 tests/lab/lab-public-route-registry.test.ts -64 tests/lab/lab-public-security-regressions.test.ts -214 tests/lab/lab-public-surfaces.test.ts -64 tests/lab/lab-public-wire-contract.test.ts -147 tests/lab/lab-read-filter-validation.test.ts -320 tests/lab/lab-read-surfaces.test.ts -714 tests/lib/abort-idle-deadline.test.ts -28 tests/lib/acl-error-classification.test.ts -355 tests/lib/ambiguous-resend-composition.test.ts -37 tests/lib/ambiguous-resend-gate.test.ts -27 tests/lib/authorization-scheme.test.ts -47 tests/lib/bounded-file-read.test.ts -142 tests/lib/bun-runtime-preflight.test.ts -31 tests/lib/bun-stream-caps.test.ts -137 tests/lib/clearable-deadline.test.ts -62 tests/lib/client-error-body.test.ts -36 tests/lib/client-retry-after.test.ts -302 tests/lib/credential-redirect-guard.test.ts -41 tests/lib/debug.test.ts -124 tests/lib/execution-budget-permits.test.ts -41 tests/lib/failure-attribution.test.ts -74 tests/lib/failure-stage-model.test.ts -63 tests/lib/file-identity-callers.test.ts -34 tests/lib/file-identity.test.ts -32 tests/lib/fix-jsonc-cr-comments.test.ts -22 tests/lib/fix-jsonc-empty-comma.test.ts -46 tests/lib/fix-plain-data-own-keys.test.ts -14 tests/lib/fix-plain-data-shape.test.ts -32 tests/lib/fix-retry-release-timer.test.ts -98 tests/lib/local-chat-completion.test.ts -17 tests/lib/local-destinations.test.ts -28 tests/lib/local-upstream.test.ts -40 tests/lib/messages-sse-error-presentation.test.ts -3063 tests/lib/opaque-proxy-tunnel-protocol.test.ts -471 tests/lib/opaque-proxy-tunnel.test.ts -880 tests/lib/optional-desktop-upstream.test.ts -144 tests/lib/optional-shutdown-hooks.test.ts -121 tests/lib/pinned-http-content-coding.test.ts -2057 tests/lib/pinned-http.test.ts -362 tests/lib/plugin-loader.test.ts -38 tests/lib/plugin-upstream-hooks.test.ts -28 tests/lib/privacy-mask-account.test.ts -33 tests/lib/private-sqlite-path.test.ts -33 tests/lib/process-control-graceful.test.ts -31 tests/lib/process-control.test.ts -41 tests/lib/provider-egress.test.ts -35 tests/lib/reasoning-replay-scope-source.test.ts -250 tests/lib/redact.test.ts -55 tests/lib/remove-tree-helper.test.ts -44 tests/lib/self-launch-argv.test.ts -1313 tests/lib/socks5-fetch.test.ts -50 tests/lib/socks5-reader-lifecycle.test.ts -27 tests/lib/socks5-timeout-cleanup.test.ts -74 tests/lib/socks5-tls-lifecycle.test.ts -50 tests/lib/socks5-upload-lifecycle.test.ts -164 tests/lib/spend-ceiling-enforcement.test.ts -15 tests/lib/spend-contract-c.test.ts -32 tests/lib/spend-corruption-compat.test.ts -71 tests/lib/spend-experimental-history.test.ts -84 tests/lib/spend-ledger-file-journal.test.ts -1294 tests/lib/spend-ledger-owner.test.ts -303 tests/lib/spend-pool-continuity.test.ts -57 tests/lib/spend-reservation-ledger.test.ts -798 tests/lib/spend-seed-overflow.test.ts -41 tests/lib/spend-unbound-expiry.test.ts -54 tests/lib/spend-zero-config-compat.test.ts -34 tests/lib/stall-subprocess-exit.test.ts -31 tests/lib/stall-timeout.test.ts -40 tests/lib/standalone.test.ts -28 tests/lib/strict-semver.test.ts -58 tests/lib/synced-state-location.test.ts -39 tests/lib/system-restart-contract-security.test.ts -38 tests/lib/token-estimate.test.ts -30 tests/lib/transient-budget-scope-source.test.ts -68 tests/lib/transport-null-body.test.ts -39 tests/lib/upstream-condition.test.ts -246 tests/lib/upstream-error-message-fallback.test.ts -29 tests/lib/upstream-retry-zero-output.test.ts -14020 tests/lib/upstream-retry.test.ts -259 tests/lib/worker-embed-coverage.test.ts -48 tests/lib/worker-embed.test.ts -87 tests/lib/workflow-budget.test.ts -342 tests/oauth/adapter-event-oauth-failover.test.ts -525 tests/oauth/anthropic2-discovery-ownership.test.ts -4154 tests/oauth/chatgpt-device-auth.test.ts -30 tests/oauth/chatgpt-oauth.test.ts -128 tests/oauth/chatgpt-token-boundaries.test.ts -125 tests/oauth/chatgpt-token-expiry.test.ts -10145 tests/oauth/dsh-login.test.ts -311 tests/oauth/generic-oauth-combo-account-cooldown.test.ts -359 tests/oauth/generic-oauth-failover.test.ts -289 tests/oauth/generic-oauth-refusal-composition.test.ts -710 tests/oauth/generic-session-affinity.test.ts -772 tests/oauth/key-login-live-update.test.ts -64 tests/oauth/key-login-preserves-model-costs.test.ts -57 tests/oauth/local-token-detect.test.ts -228 tests/oauth/oauth-account-attribution.test.ts -1292 tests/oauth/oauth-account-auto-pause-revision.test.ts -215 tests/oauth/oauth-account-auto-pause.test.ts -67 tests/oauth/oauth-account-id-collision.test.ts -139 tests/oauth/oauth-account-plans.test.ts -103 tests/oauth/oauth-account-quota-rank.test.ts -1097 tests/oauth/oauth-accounts-api.test.ts -210 tests/oauth/oauth-anthropic-identity.test.ts -310 tests/oauth/oauth-anthropic-instance-health.test.ts -699 tests/oauth/oauth-anthropic-instance-multiprocess.test.ts -498 tests/oauth/oauth-anthropic-instance-refresh.test.ts -377 tests/oauth/oauth-anthropic-instance-registration.test.ts -33 tests/oauth/oauth-callback-binds.test.ts -42 tests/oauth/oauth-callback-server.test.ts -3032 tests/oauth/oauth-code-login.test.ts -70 tests/oauth/oauth-device-code-contract.test.ts -119 tests/oauth/oauth-health.test.ts -1182 tests/oauth/oauth-kiro-refresh-attention.test.ts -55 tests/oauth/oauth-log.test.ts -111 tests/oauth/oauth-login-cli-browser-launch.test.ts -3109 tests/oauth/oauth-login-cli-errors.test.ts -535 tests/oauth/oauth-login-cli-live-update.test.ts -82 tests/oauth/oauth-login-open-browser.test.ts -46 tests/oauth/oauth-login-summary.test.ts -507 tests/oauth/oauth-manual-code.test.ts -405 tests/oauth/oauth-meta-muse-login-diagnostics.test.ts -68 tests/oauth/oauth-open-browser-choice.test.ts -70 tests/oauth/oauth-open-url-result.test.ts -196 tests/oauth/oauth-provider-reconcile.test.ts -375 tests/oauth/oauth-public-surface.test.ts -165 tests/oauth/oauth-reauth-bind.test.ts -72 tests/oauth/oauth-reconcile-operator-maps.test.ts -564 tests/oauth/oauth-refresh-generic-lock.test.ts -3007 tests/oauth/oauth-refresh-lock-multiprocess.test.ts -453 tests/oauth/oauth-refresh-stale-capacity.test.ts -1303 tests/oauth/oauth-refresh.test.ts -322 tests/oauth/oauth-status-privacy.test.ts -640 tests/oauth/oauth-store-multi.test.ts -218 tests/oauth/oauth-store-quota-isolation.test.ts -96 tests/oauth/oauth-upsert-paused-api-key.test.ts -112 tests/oauth/oauth-upsert-preserves-api-key.test.ts -31 tests/oauth/pool-kernel-generic-sweep.test.ts -93 tests/oauth/state-store-sweeper.test.ts -57 tests/oauth/workbuddy-login.test.ts -585 tests/providers/aistupidlevel-provider.test.ts -61 tests/providers/alibaba-region-backup.test.ts -99 tests/providers/alibaba-region-migration.test.ts -42 tests/providers/alibaba-region-startup.test.ts -145 tests/providers/alibaba-token-plan-responses-optin.test.ts -256 tests/providers/alibaba-token-plan-wire-defaults.test.ts -116 tests/providers/api-key-auto-pause-distribution.test.ts -91 tests/providers/api-key-catalog-authority.test.ts -44 tests/providers/api-key-selection-capture.test.ts -92 tests/providers/api-key-selection-cooldown.test.ts -86 tests/providers/aside-client.test.ts -52 tests/providers/auto-compact-budget.test.ts -107 tests/providers/azure-adapter.test.ts -33 tests/providers/azure-model-router-tool-schema.test.ts -212 tests/providers/azure-vendor-metadata.test.ts -98 tests/providers/baseten-provider.test.ts -236 tests/providers/cc-switch-import.test.ts -198 tests/providers/cheapaimodel-provider.test.ts -112 tests/providers/chutes-provider.test.ts -70 tests/providers/claude-chat-gateway-tool-schema.test.ts -1007 tests/providers/claude-cli-adapter.test.ts -646 tests/providers/claude-cli-client-http.test.ts -49 tests/providers/claude-cli-efficiency.test.ts -85 tests/providers/claude-cli-tool-capture.test.ts -298 tests/providers/claude-cli-usage-admission.test.ts -250 tests/providers/cline-pass-deepseek-v4-tool-replay.test.ts -267 tests/providers/cline-pass-provider.test.ts -76 tests/providers/cline-pass-reasoning-efforts.test.ts -38 tests/providers/cline-provider.test.ts -205 tests/providers/codebuddy-adapter.test.ts -36 tests/providers/codebuddy-live-acceptance.test.ts -108 tests/providers/codebuddy-live-models.test.ts -4220 tests/providers/codebuddy-mcp-server.test.ts -47 tests/providers/codebuddy-protocol.test.ts -244 tests/providers/codebuddy-tool-bridge-turn.test.ts -54 tests/providers/codebuddy-tool-bridge.test.ts -37 tests/providers/coding-agent-json-lines-scaling.test.ts -69 tests/providers/command-code-buffer-budget.test.ts -128 tests/providers/command-code-credit-failover.test.ts -1357 tests/providers/command-code-credit-rotation.test.ts -1166 tests/providers/command-code-efforts.test.ts -58 tests/providers/command-code-error-finish.test.ts -89 tests/providers/command-code-fakeip-discovery.test.ts -1281 tests/providers/command-code-plan-denial.test.ts -2195 tests/providers/command-code-project-context.test.ts -437 tests/providers/command-code-provider.test.ts -82 tests/providers/command-code-quota.test.ts -92 tests/providers/command-code-tool-text-prose-split.test.ts -347 tests/providers/command-code-tool-text.test.ts -30 tests/providers/command-code-workspace-cache.test.ts -160 tests/providers/commandcode-provider.test.ts -58 tests/providers/context-cap-unknown-window.test.ts -30 tests/providers/context-window-seed-repair.test.ts -122 tests/providers/crusoe-provider.test.ts -217 tests/providers/cursor/cursor-adapter.test.ts -30 tests/providers/cursor/cursor-arg-normalize.test.ts -85 tests/providers/cursor/cursor-blob-claude-client-tools.test.ts -36 tests/providers/cursor/cursor-blob-integrity.test.ts -285 tests/providers/cursor/cursor-blob.test.ts -40 tests/providers/cursor/cursor-call-id.test.ts -61 tests/providers/cursor/cursor-cancel-provenance.test.ts -37 tests/providers/cursor/cursor-catalog.test.ts -28 tests/providers/cursor/cursor-claude-id.test.ts -129 tests/providers/cursor/cursor-continuation-invariants.test.ts -100 tests/providers/cursor/cursor-continuity-retention.test.ts -47 tests/providers/cursor/cursor-default-catalog-suppression.test.ts -75 tests/providers/cursor/cursor-desktop-exec.test.ts -33 tests/providers/cursor/cursor-discovery.test.ts -78 tests/providers/cursor/cursor-display-names.test.ts -458 tests/providers/cursor/cursor-effort-rows.test.ts -58 tests/providers/cursor/cursor-effort-suffix.test.ts -38 tests/providers/cursor/cursor-effort-table.test.ts -117 tests/providers/cursor/cursor-envelope-echo-retry.test.ts -78 tests/providers/cursor/cursor-eof-terminal.test.ts -72 tests/providers/cursor/cursor-errors.test.ts -33 tests/providers/cursor/cursor-exec-empty-result.test.ts -66 tests/providers/cursor/cursor-fast-listing.test.ts -47 tests/providers/cursor/cursor-fast-tier.test.ts -249 tests/providers/cursor/cursor-foreground-shell.test.ts -68 tests/providers/cursor/cursor-framing.test.ts -47 tests/providers/cursor/cursor-freeform-args.test.ts -227 tests/providers/cursor/cursor-h2-pool-shutdown.test.ts -2813 tests/providers/cursor/cursor-hardening.test.ts -80 tests/providers/cursor/cursor-http1-transport.test.ts -2798 tests/providers/cursor/cursor-images.test.ts -474 tests/providers/cursor/cursor-integration-status.test.ts -67 tests/providers/cursor/cursor-interaction-query.test.ts -35 tests/providers/cursor/cursor-kv-store.test.ts -28 tests/providers/cursor/cursor-live-smoke-gate.test.ts -165 tests/providers/cursor/cursor-live-transport.test.ts -35 tests/providers/cursor/cursor-local-installer.test.ts -415 tests/providers/cursor/cursor-local-models-schema.test.ts -114 tests/providers/cursor/cursor-mcp-manager.test.ts -273 tests/providers/cursor/cursor-mcp-stdio.test.ts -34 tests/providers/cursor/cursor-message-mapper.test.ts -50 tests/providers/cursor/cursor-native-exec-common.test.ts -105 tests/providers/cursor/cursor-native-exec-policy.test.ts -148 tests/providers/cursor/cursor-native-exec-shell.test.ts -223 tests/providers/cursor/cursor-native-exec.test.ts -62 tests/providers/cursor/cursor-native-grep-globs.test.ts -68 tests/providers/cursor/cursor-oauth-shell.test.ts -721 tests/providers/cursor/cursor-oauth.test.ts -39 tests/providers/cursor/cursor-pool.test.ts -64 tests/providers/cursor/cursor-protobuf-events.test.ts -94 tests/providers/cursor/cursor-repetition-breaker.test.ts -101 tests/providers/cursor/cursor-request-builder.test.ts -59 tests/providers/cursor/cursor-request-compat.test.ts -78 tests/providers/cursor/cursor-roster-account-scope.test.ts -44 tests/providers/cursor/cursor-silent-redirect.test.ts -106 tests/providers/cursor/cursor-static-catalog.test.ts -3526 tests/providers/cursor/cursor-stream-health.test.ts -72 tests/providers/cursor/cursor-structured-edit.test.ts -49 tests/providers/cursor/cursor-tool-arg-decoding.test.ts -45 tests/providers/cursor/cursor-tool-choice.test.ts -73 tests/providers/cursor/cursor-tool-continuation.test.ts -83 tests/providers/cursor/cursor-tool-definitions.test.ts -3985 tests/providers/cursor/cursor-tool-finalize-race.test.ts -88 tests/providers/cursor/cursor-tool-result-image.test.ts -203 tests/providers/cursor/cursor-tool-result-invocation.test.ts -66 tests/providers/cursor/cursor-tool-suspended-checkpoint.test.ts -122 tests/providers/cursor/cursor-tool-wording.test.ts -66 tests/providers/cursor/cursor-toolresult-normalize.test.ts -1955 tests/providers/cursor/cursor-transport-retry.test.ts -53 tests/providers/cursor/cursor-ultra-mode.test.ts -57 tests/providers/cursor/cursor-umbrella-rows.test.ts -31 tests/providers/cursor/cursor-uncallable-quarantine.test.ts -90 tests/providers/cursor/cursor-vision-wire-harness.test.ts -178 tests/providers/cyber-policy-error-fidelity.test.ts -172 tests/providers/deepinfra-provider.test.ts -39 tests/providers/deepseek-artifact-tool-schema.test.ts -69 tests/providers/deepseek-bare-tool-call-replay.test.ts -3107 tests/providers/deepseek-image-files.test.ts -334 tests/providers/deepseek-inbound-wire.test.ts -76 tests/providers/deepseek-quota-currency.test.ts -96 tests/providers/deepseek-reasoning-replay-gaps.test.ts -79 tests/providers/deepseek-reasoning-replay.test.ts -291 tests/providers/deepseek-responses-item-id-repair.test.ts -2073 tests/providers/devin-adapter-reset-wait.test.ts -135 tests/providers/devin-adapter.test.ts -159 tests/providers/devin-anthropic-signature-fallback.test.ts -173 tests/providers/devin-chat-wire-fixes.test.ts -77 tests/providers/devin-cli-authmode-migration.test.ts -78 tests/providers/devin-effort-ladder.test.ts -74 tests/providers/devin-family-resolution.test.ts -79 tests/providers/devin-hardening.test.ts -62 tests/providers/devin-image-passthrough.test.ts -74 tests/providers/devin-live-models.test.ts -107 tests/providers/devin-login.test.ts -59 tests/providers/devin-output-budget.test.ts -115 tests/providers/devin-prompt-cache.test.ts -75 tests/providers/devin-provider-merge-migration.test.ts -80 tests/providers/devin-quota.test.ts -149 tests/providers/devin-reasoning-continuation.test.ts -51 tests/providers/devin-stated-reset-hardening.test.ts -47 tests/providers/devin-stated-reset-retry.test.ts -104 tests/providers/devin-stream-deadline.test.ts -65 tests/providers/devin-stream-queue.test.ts -48 tests/providers/devin-trajectory.test.ts -112 tests/providers/digitalocean-scaleway-provider.test.ts -514 tests/providers/dsh-account.test.ts -176 tests/providers/exa-web-search.test.ts -201 tests/providers/explicit-key-pause-oauth-boundary.test.ts -81 tests/providers/fast-row-ingress.test.ts -123 tests/providers/featherless-provider.test.ts -134 tests/providers/flash-route-image-modalities.test.ts -381 tests/providers/forward-admission-separation.test.ts -38 tests/providers/free-directory-runcrate.test.ts -463 tests/providers/github-copilot/github-copilot-account-origin.test.ts -2109 tests/providers/github-copilot/github-copilot-auto-runtime.test.ts -62 tests/providers/github-copilot/github-copilot-auto.test.ts -81 tests/providers/github-copilot/github-copilot-catalog-hints.test.ts -54 tests/providers/github-copilot/github-copilot-context-tier.test.ts -16100 tests/providers/github-copilot/github-copilot-oauth.test.ts -43 tests/providers/github-copilot/github-copilot-sse-rewrite.test.ts -525 tests/providers/github-copilot/github-copilot-stream-contract.test.ts -358 tests/providers/github-copilot/github-copilot-wire-defaults.test.ts -1657 tests/providers/gpt61-terra-provider-rows.test.ts -86 tests/providers/haiku-5-5-catalog.test.ts -129 tests/providers/hyperbolic-provider.test.ts -294 tests/providers/initial-model-selection.test.ts -374 tests/providers/initial-selection-write-fence.test.ts -111 tests/providers/jev-provider.test.ts -82 tests/providers/kimi-coding-output-include.test.ts -106 tests/providers/kimi-monthly-quota.test.ts -213 tests/providers/kimi-oauth-identity.test.ts -111 tests/providers/kimi-responses-adjacency.test.ts -53 tests/providers/kiro/kiro-account-load.test.ts -152 tests/providers/kiro/kiro-account-quota.test.ts -3924 tests/providers/kiro/kiro-account-state-disk.test.ts -702 tests/providers/kiro/kiro-account-state-imports.test.ts -234 tests/providers/kiro/kiro-adapter.test.ts -359 tests/providers/kiro/kiro-auth-context-continuation.test.ts -81 tests/providers/kiro/kiro-auto-selection.test.ts -90 tests/providers/kiro/kiro-builder-id-profile.test.ts -78 tests/providers/kiro/kiro-calibration.test.ts -60 tests/providers/kiro/kiro-completion-retry-wording.test.ts -94 tests/providers/kiro/kiro-completion-with-real-tools.test.ts -182 tests/providers/kiro/kiro-content-filter.test.ts -86 tests/providers/kiro/kiro-device-builder.test.ts -121 tests/providers/kiro/kiro-device-iam.test.ts -166 tests/providers/kiro/kiro-device-social.test.ts -81 tests/providers/kiro/kiro-fallback-error-body.test.ts -2897 tests/providers/kiro/kiro-images.test.ts -1236 tests/providers/kiro/kiro-leased-responses.test.ts -40 tests/providers/kiro/kiro-metering-events.test.ts -83 tests/providers/kiro/kiro-metering-usage.test.ts -183 tests/providers/kiro/kiro-model-catalog.test.ts -96 tests/providers/kiro/kiro-model-preference.test.ts -154 tests/providers/kiro/kiro-oauth.test.ts -260 tests/providers/kiro/kiro-org-user-identity.test.ts -465 tests/providers/kiro/kiro-pool-load-settings.test.ts -106 tests/providers/kiro/kiro-pool-rank.test.ts -77 tests/providers/kiro/kiro-quota-metrics.test.ts -92 tests/providers/kiro/kiro-reasoning-roundtrip.test.ts -1569 tests/providers/kiro/kiro-refusal-failover.test.ts -61 tests/providers/kiro/kiro-refusal.test.ts -93 tests/providers/kiro/kiro-remote-image.test.ts -579 tests/providers/kiro/kiro-retry.test.ts -116 tests/providers/kiro/kiro-review-regressions.test.ts -72 tests/providers/kiro/kiro-single-final.test.ts -222 tests/providers/kiro/kiro-stream.test.ts -133 tests/providers/kiro/kiro-structured-output-strict.test.ts -116 tests/providers/kiro/kiro-structured-output.test.ts -133 tests/providers/kiro/kiro-tool-byte-accounting.test.ts -552 tests/providers/kiro/kiro-transport-parity.test.ts -77 tests/providers/kiro/kiro-usage-quota.test.ts -62 tests/providers/kiro/kiro-usage-restart.test.ts -47 tests/providers/kiro/kiro-windows-cli-db-path.test.ts -24 tests/providers/kiro/kiro-windows-cli-executable-path.test.ts -53 tests/providers/kiro/kiro-wire-estimate.test.ts -120 tests/providers/meta-model-api-provider.test.ts -78 tests/providers/meta-muse-device.test.ts -5129 tests/providers/meta-muse-keychain.test.ts -103 tests/providers/meta-muse-login-order.test.ts -138 tests/providers/meta-muse-oauth.test.ts -168 tests/providers/meta-muse-plan-refusal.test.ts -67 tests/providers/meta-muse-wonder.test.ts -136 tests/providers/mimo-effort.test.ts -199 tests/providers/mimo-free-provider.test.ts -76 tests/providers/mimo-token-plan-capacity.test.ts -133 tests/providers/mimo-token-plan-provider.test.ts -83 tests/providers/mimo-v26-catalog.test.ts -340 tests/providers/minimax-clients.test.ts -1592 tests/providers/minimax-combo-image-input.test.ts -132 tests/providers/minimax-quota.test.ts -98 tests/providers/minimax-reasoning-split.test.ts -155 tests/providers/mistral-image-limit.test.ts -195 tests/providers/mistral-reasoning-efforts.test.ts -371 tests/providers/mistral-recovery.test.ts -48 tests/providers/model-presets.test.ts -128 tests/providers/model-rename-migration.test.ts -151 tests/providers/model-roster-seed-repair.test.ts -90 tests/providers/modelflare-provider.test.ts -33 tests/providers/moonshot-developer-role.test.ts -59 tests/providers/moonshot-endpoints.test.ts +46 tests/gui/oauth-first-add-hint.test.ts +87 tests/gui/oauth-tos-warning.test.ts +508 tests/gui/platform-dialog-guard.test.ts +80 tests/gui/provider-payload.test.ts +104 tests/gui/provider-subscription-cli.test.ts +189 tests/gui/provider-workspace-auth.test.ts +129 tests/gui/provider-workspace-data.test.ts +82 tests/gui/provider-workspace-rail.test.ts +70 tests/gui/provider-workspace-state.test.ts +132 tests/gui/quota-bars-rows.test.ts +69 tests/gui/qwen-cloud-endpoints.test.ts +91 tests/gui/rate-limit-reset-credits.test.ts +58 tests/gui/routing-intelligence-ui.test.ts +60 tests/gui/routing-profile-editor-data.test.ts +36 tests/gui/standalone-build-script.test.ts +642 tests/gui/startup-health-ui.test.ts +155 tests/gui/tencent-siliconflow-providers.test.ts +114 tests/gui/vision-sidecar-timeout-bounds.test.ts +188 tests/gui/volcengine-providers.test.ts +104 tests/images/artifacts-prune.test.ts +99 tests/images/artifacts-ssrf.test.ts +76 tests/images/download-cap-default.test.ts +66 tests/images/download-connect-deadline-default.test.ts +170 tests/images/gemini-inline.test.ts +120 tests/images/loop-reasoning-replay.test.ts +135 tests/images/loop-terminal-refusal.test.ts +3185 tests/images/loop.test.ts +68 tests/images/pinned-https-get.test.ts +89 tests/images/plan.test.ts +57 tests/images/synthetic-tool.test.ts +116 tests/images/xai-client.test.ts +89 tests/images/z-fulfill.test.ts +374 tests/images/z-handler-activation.test.ts +457 tests/lab/core-lab-boundary.test.ts +351 tests/lab/core-link-boundary.test.ts +422 tests/lab/lab-activation.test.ts +227 tests/lab/lab-automation-coderabbit-regressions.test.ts +325 tests/lab/lab-automation-final-coderabbit-regressions.test.ts +199 tests/lab/lab-automation-ingwannu-regressions.test.ts +384 tests/lab/lab-automation-management-http.test.ts +48 tests/lab/lab-automation-persisted-cap-regression.test.ts +427 tests/lab/lab-automation-review-regressions.test.ts +442 tests/lab/lab-automation.test.ts +281 tests/lab/lab-community-evidence.test.ts +177 tests/lab/lab-community-filename-contract.test.ts +228 tests/lab/lab-community-mutation-lock.test.ts +175 tests/lab/lab-community-publisher-continuity.test.ts +173 tests/lab/lab-conformance-harness.test.ts +138 tests/lab/lab-conformance-runner-failures.test.ts +366 tests/lab/lab-evidence-ledger.test.ts +383 tests/lab/lab-evidence-sanitization.test.ts +166 tests/lab/lab-fabric-outcome-validation.test.ts +52 tests/lab/lab-fabric-persistence-boundary.test.ts +165 tests/lab/lab-fabric-producer-deadline.test.ts +95931 tests/lab/lab-fabric-task.test.ts +101 tests/lab/lab-installation-salt-cache.test.ts +829 tests/lab/lab-ledger-mutation-lock.test.ts +296 tests/lab/lab-live-pinned-timeouts.test.ts +197 tests/lab/lab-live-probe.test.ts +122 tests/lab/lab-live-receipt-integrity.test.ts +359 tests/lab/lab-live-review-regressions.test.ts +275 tests/lab/lab-live-sandbox.test.ts +232 tests/lab/lab-passive-production-evidence.test.ts +343 tests/lab/lab-passive-production-surfaces.test.ts +53 tests/lab/lab-paths-security.test.ts +190 tests/lab/lab-post-merge-hardening.test.ts +135 tests/lab/lab-post-merge-projection.test.ts +64 tests/lab/lab-private-file-consumer-recovery.test.ts +73 tests/lab/lab-private-file-durability.test.ts +170 tests/lab/lab-public-api-json.test.ts +143 tests/lab/lab-public-artifact-policy.test.ts +220 tests/lab/lab-public-coderabbit-regressions.test.ts +85 tests/lab/lab-public-core-contract.test.ts +147 tests/lab/lab-public-deep-review-regressions.test.ts +168 tests/lab/lab-public-evidence.test.ts +152 tests/lab/lab-public-export-transaction.test.ts +71 tests/lab/lab-public-file-safety.test.ts +172 tests/lab/lab-public-final-review-regressions.test.ts +160 tests/lab/lab-public-lifecycle-hardening.test.ts +57 tests/lab/lab-public-privacy-ipv6.test.ts +428 tests/lab/lab-public-provenance-recovery.test.ts +418 tests/lab/lab-public-review-fixes.test.ts +54 tests/lab/lab-public-route-registry.test.ts +81 tests/lab/lab-public-security-regressions.test.ts +327 tests/lab/lab-public-surfaces.test.ts +79 tests/lab/lab-public-wire-contract.test.ts +303 tests/lab/lab-read-filter-validation.test.ts +570 tests/lab/lab-read-surfaces.test.ts +856 tests/lab/link-child-ops-no-timer.test.ts +772 tests/lib/abort-idle-deadline.test.ts +47 tests/lib/acl-error-classification.test.ts +483 tests/lib/ambiguous-resend-composition.test.ts +54 tests/lib/ambiguous-resend-gate.test.ts +60 tests/lib/authorization-scheme.test.ts +68 tests/lib/bounded-file-read.test.ts +148 tests/lib/bun-runtime-preflight.test.ts +48 tests/lib/bun-stream-caps.test.ts +144 tests/lib/clearable-deadline.test.ts +99 tests/lib/client-error-body.test.ts +54 tests/lib/client-retry-after.test.ts +388 tests/lib/credential-redirect-guard.test.ts +59 tests/lib/debug.test.ts +70 tests/lib/definite-overflow-verdict.test.ts +52 tests/lib/developer-role-rejection.test.ts +157 tests/lib/execution-budget-permits.test.ts +112 tests/lib/failure-attribution.test.ts +72 tests/lib/failure-stage-model.test.ts +76 tests/lib/file-identity-callers.test.ts +58 tests/lib/file-identity.test.ts +55 tests/lib/fix-jsonc-cr-comments.test.ts +41 tests/lib/fix-jsonc-empty-comma.test.ts +50 tests/lib/fix-plain-data-own-keys.test.ts +51 tests/lib/fix-plain-data-shape.test.ts +65 tests/lib/fix-retry-release-timer.test.ts +119 tests/lib/local-chat-completion.test.ts +72 tests/lib/local-destinations.test.ts +55 tests/lib/local-upstream.test.ts +64 tests/lib/messages-sse-error-presentation.test.ts +3112 tests/lib/opaque-proxy-tunnel-protocol.test.ts +520 tests/lib/opaque-proxy-tunnel.test.ts +981 tests/lib/optional-desktop-upstream.test.ts +244 tests/lib/optional-shutdown-hooks.test.ts +97 tests/lib/pinned-http-content-coding.test.ts +1777 tests/lib/pinned-http.test.ts +338 tests/lib/plugin-loader.test.ts +56 tests/lib/plugin-upstream-hooks.test.ts +50 tests/lib/privacy-mask-account.test.ts +84 tests/lib/private-sqlite-path.test.ts +97 tests/lib/process-control-graceful.test.ts +52 tests/lib/process-control.test.ts +49 tests/lib/provider-egress.test.ts +56 tests/lib/reasoning-replay-scope-source.test.ts +350 tests/lib/redact.test.ts +75 tests/lib/remove-tree-helper.test.ts +45 tests/lib/self-launch-argv.test.ts +1263 tests/lib/socks5-fetch.test.ts +60 tests/lib/socks5-reader-lifecycle.test.ts +123 tests/lib/socks5-timeout-cleanup.test.ts +119 tests/lib/socks5-tls-lifecycle.test.ts +132 tests/lib/socks5-upload-lifecycle.test.ts +192 tests/lib/spend-ceiling-enforcement.test.ts +56 tests/lib/spend-contract-c.test.ts +93 tests/lib/spend-corruption-compat.test.ts +69 tests/lib/spend-experimental-history.test.ts +177 tests/lib/spend-ledger-file-journal.test.ts +1131 tests/lib/spend-ledger-owner.test.ts +305 tests/lib/spend-pool-continuity.test.ts +58 tests/lib/spend-reservation-ledger.test.ts +997 tests/lib/spend-seed-overflow.test.ts +58 tests/lib/spend-unbound-expiry.test.ts +66 tests/lib/spend-zero-config-compat.test.ts +61 tests/lib/stall-subprocess-exit.test.ts +57 tests/lib/stall-timeout.test.ts +48 tests/lib/standalone.test.ts +94 tests/lib/strict-semver.test.ts +46 tests/lib/synced-state-location.test.ts +88 tests/lib/system-restart-contract-security.test.ts +56 tests/lib/terminal-safe-text.test.ts +62 tests/lib/token-estimate.test.ts +50 tests/lib/transient-budget-scope-source.test.ts +89 tests/lib/transport-null-body.test.ts +49 tests/lib/upstream-condition.test.ts +176 tests/lib/upstream-error-message-fallback.test.ts +53 tests/lib/upstream-retry-zero-output.test.ts +14249 tests/lib/upstream-retry.test.ts +278 tests/lib/worker-embed-coverage.test.ts +55 tests/lib/worker-embed.test.ts +151 tests/lib/workflow-budget.test.ts +538 tests/oauth/adapter-event-oauth-failover.test.ts +752 tests/oauth/anthropic2-discovery-ownership.test.ts +4151 tests/oauth/chatgpt-device-auth.test.ts +76 tests/oauth/chatgpt-oauth.test.ts +120 tests/oauth/chatgpt-token-boundaries.test.ts +136 tests/oauth/chatgpt-token-expiry.test.ts +103 tests/oauth/claude-keychain-read.test.ts +10168 tests/oauth/dsh-login.test.ts +401 tests/oauth/generic-oauth-combo-account-cooldown.test.ts +430 tests/oauth/generic-oauth-failover.test.ts +443 tests/oauth/generic-oauth-refusal-composition.test.ts +368 tests/oauth/generic-session-affinity.test.ts +532 tests/oauth/key-login-live-update.test.ts +144 tests/oauth/key-login-preserves-model-costs.test.ts +54 tests/oauth/local-token-detect.test.ts +388 tests/oauth/oauth-account-attribution.test.ts +1167 tests/oauth/oauth-account-auto-pause-revision.test.ts +452 tests/oauth/oauth-account-auto-pause.test.ts +115 tests/oauth/oauth-account-id-collision.test.ts +262 tests/oauth/oauth-account-plans.test.ts +168 tests/oauth/oauth-account-quota-rank.test.ts +1091 tests/oauth/oauth-account-resume-if-healthy.test.ts +2202 tests/oauth/oauth-accounts-api.test.ts +355 tests/oauth/oauth-anthropic-identity.test.ts +403 tests/oauth/oauth-anthropic-instance-health.test.ts +1032 tests/oauth/oauth-anthropic-instance-multiprocess.test.ts +410 tests/oauth/oauth-anthropic-instance-refresh.test.ts +638 tests/oauth/oauth-anthropic-instance-registration.test.ts +288 tests/oauth/oauth-antigravity-risk.test.ts +53 tests/oauth/oauth-callback-binds.test.ts +71 tests/oauth/oauth-callback-server.test.ts +9611 tests/oauth/oauth-code-login.test.ts +144 tests/oauth/oauth-credential-siblings.test.ts +57 tests/oauth/oauth-device-code-contract.test.ts +220 tests/oauth/oauth-health.test.ts +638 tests/oauth/oauth-kiro-refresh-attention.test.ts +52 tests/oauth/oauth-log.test.ts +192 tests/oauth/oauth-login-cli-browser-launch.test.ts +5368 tests/oauth/oauth-login-cli-errors.test.ts +749 tests/oauth/oauth-login-cli-live-update.test.ts +138 tests/oauth/oauth-login-open-browser.test.ts +99 tests/oauth/oauth-login-summary.test.ts +667 tests/oauth/oauth-manual-code.test.ts +327 tests/oauth/oauth-meta-muse-login-diagnostics.test.ts +165 tests/oauth/oauth-open-browser-choice.test.ts +103 tests/oauth/oauth-open-url-result.test.ts +285 tests/oauth/oauth-provider-reconcile.test.ts +502 tests/oauth/oauth-public-surface.test.ts +298 tests/oauth/oauth-reauth-bind.test.ts +156 tests/oauth/oauth-reconcile-operator-maps.test.ts +169 tests/oauth/oauth-refresh-connection-refused.test.ts +833 tests/oauth/oauth-refresh-generic-lock.test.ts +3081 tests/oauth/oauth-refresh-lock-multiprocess.test.ts +614 tests/oauth/oauth-refresh-stale-capacity.test.ts +1656 tests/oauth/oauth-refresh.test.ts +331 tests/oauth/oauth-status-privacy.test.ts +1166 tests/oauth/oauth-store-multi.test.ts +99 tests/oauth/oauth-store-quota-isolation.test.ts +88 tests/oauth/oauth-upsert-paused-api-key.test.ts +226 tests/oauth/oauth-upsert-preserves-api-key.test.ts +63 tests/oauth/pool-kernel-generic-sweep.test.ts +220 tests/oauth/state-store-sweeper.test.ts +63 tests/oauth/workbuddy-login.test.ts +579 tests/providers/aistupidlevel-provider.test.ts +57 tests/providers/alibaba-region-backup.test.ts +100 tests/providers/alibaba-region-migration.test.ts +56 tests/providers/alibaba-region-startup.test.ts +72 tests/providers/alibaba-token-plan-developer-role.test.ts +365 tests/providers/alibaba-token-plan-responses-optin.test.ts +431 tests/providers/alibaba-token-plan-wire-defaults.test.ts +929 tests/providers/api-key-auto-pause-distribution.test.ts +135 tests/providers/api-key-catalog-authority.test.ts +53 tests/providers/api-key-selection-capture.test.ts +170 tests/providers/api-key-selection-cooldown.test.ts +143 tests/providers/aside-client.test.ts +60 tests/providers/auto-compact-budget.test.ts +159 tests/providers/azure-adapter.test.ts +64 tests/providers/azure-model-router-tool-schema.test.ts +248 tests/providers/azure-vendor-metadata.test.ts +141 tests/providers/baseten-provider.test.ts +371 tests/providers/cache-affinity.test.ts +392 tests/providers/cc-switch-import.test.ts +141 tests/providers/cheapaimodel-provider.test.ts +165 tests/providers/chutes-provider.test.ts +128 tests/providers/claude-chat-gateway-tool-schema.test.ts +1039 tests/providers/claude-cli-adapter.test.ts +721 tests/providers/claude-cli-client-http.test.ts +54 tests/providers/claude-cli-efficiency.test.ts +320 tests/providers/claude-cli-fixture-stdout-flush.test.ts +110 tests/providers/claude-cli-tool-capture.test.ts +350 tests/providers/claude-cli-usage-admission.test.ts +121 tests/providers/cline-pass-deepseek-v4-tool-replay.test.ts +116 tests/providers/cline-pass-provider.test.ts +185 tests/providers/cline-pass-reasoning-efforts.test.ts +55 tests/providers/cline-provider.test.ts +206 tests/providers/codebuddy-adapter.test.ts +59 tests/providers/codebuddy-live-acceptance.test.ts +151 tests/providers/codebuddy-live-models.test.ts +2903 tests/providers/codebuddy-mcp-server.test.ts +70 tests/providers/codebuddy-protocol.test.ts +283 tests/providers/codebuddy-tool-bridge-turn.test.ts +74 tests/providers/codebuddy-tool-bridge.test.ts +65 tests/providers/coding-agent-json-lines-scaling.test.ts +56 tests/providers/command-code-buffer-budget.test.ts +501 tests/providers/command-code-credit-failover.test.ts +822 tests/providers/command-code-credit-rotation.test.ts +347 tests/providers/command-code-efforts.test.ts +101 tests/providers/command-code-error-finish.test.ts +144 tests/providers/command-code-fakeip-discovery.test.ts +1020 tests/providers/command-code-plan-denial.test.ts +2176 tests/providers/command-code-project-context.test.ts +482 tests/providers/command-code-provider.test.ts +104 tests/providers/command-code-quota.test.ts +756 tests/providers/command-code-tool-schema.test.ts +533 tests/providers/command-code-tool-text-prose-split.test.ts +421 tests/providers/command-code-tool-text.test.ts +57 tests/providers/command-code-workspace-cache.test.ts +207 tests/providers/commandcode-provider.test.ts +52 tests/providers/context-cap-unknown-window.test.ts +106 tests/providers/context-window-seed-repair.test.ts +204 tests/providers/crusoe-provider.test.ts +279 tests/providers/cursor/cursor-adapter.test.ts +51 tests/providers/cursor/cursor-arg-normalize.test.ts +131 tests/providers/cursor/cursor-auto-tool-result-replay.test.ts +99 tests/providers/cursor/cursor-blob-claude-client-tools.test.ts +76 tests/providers/cursor/cursor-blob-integrity.test.ts +353 tests/providers/cursor/cursor-blob.test.ts +55 tests/providers/cursor/cursor-call-id.test.ts +118 tests/providers/cursor/cursor-cancel-provenance.test.ts +56 tests/providers/cursor/cursor-catalog.test.ts +43 tests/providers/cursor/cursor-claude-id.test.ts +181 tests/providers/cursor/cursor-continuation-invariants.test.ts +173 tests/providers/cursor/cursor-continuity-retention.test.ts +66 tests/providers/cursor/cursor-default-catalog-suppression.test.ts +107 tests/providers/cursor/cursor-desktop-exec.test.ts +60 tests/providers/cursor/cursor-discovery.test.ts +95 tests/providers/cursor/cursor-display-names.test.ts +789 tests/providers/cursor/cursor-effort-rows.test.ts +66 tests/providers/cursor/cursor-effort-suffix.test.ts +53 tests/providers/cursor/cursor-effort-table.test.ts +144 tests/providers/cursor/cursor-envelope-echo-retry.test.ts +140 tests/providers/cursor/cursor-eof-terminal.test.ts +75 tests/providers/cursor/cursor-errors.test.ts +52 tests/providers/cursor/cursor-exec-empty-result.test.ts +136 tests/providers/cursor/cursor-fast-listing.test.ts +74 tests/providers/cursor/cursor-fast-tier.test.ts +211 tests/providers/cursor/cursor-foreground-shell.test.ts +118 tests/providers/cursor/cursor-framing.test.ts +77 tests/providers/cursor/cursor-freeform-args.test.ts +219 tests/providers/cursor/cursor-h2-pool-shutdown.test.ts +2785 tests/providers/cursor/cursor-hardening.test.ts +126 tests/providers/cursor/cursor-http1-transport.test.ts +3013 tests/providers/cursor/cursor-images.test.ts +725 tests/providers/cursor/cursor-integration-status.test.ts +150 tests/providers/cursor/cursor-interaction-query.test.ts +46 tests/providers/cursor/cursor-kv-store.test.ts +47 tests/providers/cursor/cursor-live-smoke-gate.test.ts +215 tests/providers/cursor/cursor-live-transport.test.ts +55 tests/providers/cursor/cursor-local-installer.test.ts +653 tests/providers/cursor/cursor-local-models-schema.test.ts +198 tests/providers/cursor/cursor-mcp-manager.test.ts +455 tests/providers/cursor/cursor-mcp-stdio.test.ts +50 tests/providers/cursor/cursor-message-mapper.test.ts +75 tests/providers/cursor/cursor-native-exec-common.test.ts +123 tests/providers/cursor/cursor-native-exec-policy.test.ts +162 tests/providers/cursor/cursor-native-exec-shell.test.ts +364 tests/providers/cursor/cursor-native-exec.test.ts +81 tests/providers/cursor/cursor-native-grep-globs.test.ts +113 tests/providers/cursor/cursor-oauth-shell.test.ts +672 tests/providers/cursor/cursor-oauth.test.ts +71 tests/providers/cursor/cursor-pool.test.ts +87 tests/providers/cursor/cursor-protobuf-events.test.ts +140 tests/providers/cursor/cursor-repetition-breaker.test.ts +156 tests/providers/cursor/cursor-request-builder.test.ts +95 tests/providers/cursor/cursor-request-compat.test.ts +116 tests/providers/cursor/cursor-roster-account-scope.test.ts +67 tests/providers/cursor/cursor-silent-redirect.test.ts +129 tests/providers/cursor/cursor-static-catalog.test.ts +3522 tests/providers/cursor/cursor-stream-health.test.ts +106 tests/providers/cursor/cursor-structured-edit.test.ts +74 tests/providers/cursor/cursor-tool-arg-decoding.test.ts +72 tests/providers/cursor/cursor-tool-choice.test.ts +102 tests/providers/cursor/cursor-tool-continuation.test.ts +93 tests/providers/cursor/cursor-tool-definitions.test.ts +4003 tests/providers/cursor/cursor-tool-finalize-race.test.ts +120 tests/providers/cursor/cursor-tool-result-image.test.ts +249 tests/providers/cursor/cursor-tool-result-invocation.test.ts +110 tests/providers/cursor/cursor-tool-suspended-checkpoint.test.ts +148 tests/providers/cursor/cursor-tool-wording.test.ts +108 tests/providers/cursor/cursor-toolresult-normalize.test.ts +1856 tests/providers/cursor/cursor-transport-retry.test.ts +76 tests/providers/cursor/cursor-ultra-mode.test.ts +88 tests/providers/cursor/cursor-umbrella-rows.test.ts +39 tests/providers/cursor/cursor-uncallable-quarantine.test.ts +87 tests/providers/cursor/cursor-vision-wire-harness.test.ts +484 tests/providers/cyber-policy-error-fidelity.test.ts +171 tests/providers/deepinfra-provider.test.ts +49 tests/providers/deepseek-artifact-tool-schema.test.ts +94 tests/providers/deepseek-bare-tool-call-replay.test.ts +4324 tests/providers/deepseek-image-files.test.ts +668 tests/providers/deepseek-inbound-wire.test.ts +126 tests/providers/deepseek-quota-currency.test.ts +127 tests/providers/deepseek-reasoning-replay-gaps.test.ts +178 tests/providers/deepseek-reasoning-replay.test.ts +411 tests/providers/deepseek-responses-item-id-repair.test.ts +2127 tests/providers/devin-adapter-reset-wait.test.ts +204 tests/providers/devin-adapter.test.ts +169 tests/providers/devin-anthropic-signature-fallback.test.ts +235 tests/providers/devin-chat-wire-fixes.test.ts +72 tests/providers/devin-cli-authmode-migration.test.ts +89 tests/providers/devin-effort-ladder.test.ts +131 tests/providers/devin-family-resolution.test.ts +121 tests/providers/devin-hardening.test.ts +83 tests/providers/devin-image-passthrough.test.ts +166 tests/providers/devin-live-models.test.ts +129 tests/providers/devin-login.test.ts +180 tests/providers/devin-output-budget.test.ts +145 tests/providers/devin-prompt-cache.test.ts +76 tests/providers/devin-provider-merge-migration.test.ts +130 tests/providers/devin-quota.test.ts +187 tests/providers/devin-reasoning-continuation.test.ts +54 tests/providers/devin-stated-reset-hardening.test.ts +57 tests/providers/devin-stated-reset-retry.test.ts +78 tests/providers/devin-stream-deadline.test.ts +97 tests/providers/devin-stream-queue.test.ts +62 tests/providers/devin-trajectory.test.ts +170 tests/providers/digitalocean-scaleway-provider.test.ts +662 tests/providers/dsh-account.test.ts +214 tests/providers/exa-web-search.test.ts +297 tests/providers/explicit-key-pause-oauth-boundary.test.ts +89 tests/providers/fast-row-ingress.test.ts +221 tests/providers/featherless-provider.test.ts +131 tests/providers/flash-route-image-modalities.test.ts +561 tests/providers/forward-admission-separation.test.ts +51 tests/providers/free-directory-llmtr.test.ts +73 tests/providers/free-directory-runcrate.test.ts +584 tests/providers/github-copilot/github-copilot-account-origin.test.ts +2360 tests/providers/github-copilot/github-copilot-auto-runtime.test.ts +86 tests/providers/github-copilot/github-copilot-auto.test.ts +108 tests/providers/github-copilot/github-copilot-catalog-hints.test.ts +114 tests/providers/github-copilot/github-copilot-context-tier.test.ts +16078 tests/providers/github-copilot/github-copilot-oauth.test.ts +58 tests/providers/github-copilot/github-copilot-sse-rewrite.test.ts +254 tests/providers/github-copilot/github-copilot-stream-contract.test.ts +462 tests/providers/github-copilot/github-copilot-wire-defaults.test.ts +455 tests/providers/gpt61-terra-provider-rows.test.ts +164 tests/providers/gpt62-provider-rows.test.ts +62 tests/providers/haiku-5-5-catalog.test.ts +127 tests/providers/hyperbolic-provider.test.ts +542 tests/providers/initial-model-selection.test.ts +412 tests/providers/initial-selection-write-fence.test.ts +120 tests/providers/jev-provider.test.ts +114 tests/providers/kimi-coding-output-include.test.ts +370 tests/providers/kimi-monthly-quota.test.ts +136 tests/providers/kimi-oauth-identity.test.ts +136 tests/providers/kimi-responses-adjacency.test.ts +1132 tests/providers/kimi-responses-sibling-routes.test.ts +69 tests/providers/kiro/kiro-account-load.test.ts +125 tests/providers/kiro/kiro-account-quota.test.ts +4378 tests/providers/kiro/kiro-account-state-disk.test.ts +772 tests/providers/kiro/kiro-account-state-imports.test.ts +218 tests/providers/kiro/kiro-adapter.test.ts +264 tests/providers/kiro/kiro-auth-context-continuation.test.ts +105 tests/providers/kiro/kiro-auto-selection.test.ts +106 tests/providers/kiro/kiro-builder-id-profile.test.ts +53 tests/providers/kiro/kiro-calibration.test.ts +107 tests/providers/kiro/kiro-completion-retry-wording.test.ts +113 tests/providers/kiro/kiro-completion-with-real-tools.test.ts +137 tests/providers/kiro/kiro-content-filter.test.ts +97 tests/providers/kiro/kiro-device-builder.test.ts +175 tests/providers/kiro/kiro-device-iam.test.ts +235 tests/providers/kiro/kiro-device-social.test.ts +114 tests/providers/kiro/kiro-fallback-error-body.test.ts +2600 tests/providers/kiro/kiro-images.test.ts +1345 tests/providers/kiro/kiro-leased-responses.test.ts +47 tests/providers/kiro/kiro-metering-events.test.ts +99 tests/providers/kiro/kiro-metering-usage.test.ts +207 tests/providers/kiro/kiro-model-catalog.test.ts +130 tests/providers/kiro/kiro-model-preference.test.ts +233 tests/providers/kiro/kiro-oauth.test.ts +358 tests/providers/kiro/kiro-org-user-identity.test.ts +1537 tests/providers/kiro/kiro-pinned-effort-ultra.test.ts +501 tests/providers/kiro/kiro-pool-load-settings.test.ts +146 tests/providers/kiro/kiro-pool-rank.test.ts +115 tests/providers/kiro/kiro-quota-metrics.test.ts +116 tests/providers/kiro/kiro-reasoning-roundtrip.test.ts +1565 tests/providers/kiro/kiro-refusal-failover.test.ts +81 tests/providers/kiro/kiro-refusal.test.ts +100 tests/providers/kiro/kiro-remote-image.test.ts +577 tests/providers/kiro/kiro-retry.test.ts +174 tests/providers/kiro/kiro-review-regressions.test.ts +107 tests/providers/kiro/kiro-single-final.test.ts +297 tests/providers/kiro/kiro-stream.test.ts +155 tests/providers/kiro/kiro-structured-output-strict.test.ts +133 tests/providers/kiro/kiro-structured-output.test.ts +96 tests/providers/kiro/kiro-tool-byte-accounting.test.ts +134 tests/providers/kiro/kiro-tool-catalog.test.ts +545 tests/providers/kiro/kiro-transport-parity.test.ts +90 tests/providers/kiro/kiro-usage-quota.test.ts +113 tests/providers/kiro/kiro-usage-restart.test.ts +52 tests/providers/kiro/kiro-windows-cli-db-path.test.ts +51 tests/providers/kiro/kiro-windows-cli-executable-path.test.ts +91 tests/providers/kiro/kiro-wire-estimate.test.ts +177 tests/providers/meta-model-api-provider.test.ts +107 tests/providers/meta-muse-device.test.ts +5157 tests/providers/meta-muse-keychain.test.ts +95 tests/providers/meta-muse-login-order.test.ts +140 tests/providers/meta-muse-oauth.test.ts +142 tests/providers/meta-muse-plan-refusal.test.ts +107 tests/providers/meta-muse-wonder.test.ts +47 tests/providers/mimo-effort.test.ts +196 tests/providers/mimo-free-provider.test.ts +195 tests/providers/mimo-token-plan-capacity.test.ts +144 tests/providers/mimo-token-plan-provider.test.ts +182 tests/providers/mimo-v26-catalog.test.ts +507 tests/providers/minimax-clients.test.ts +484 tests/providers/minimax-combo-image-input.test.ts +156 tests/providers/minimax-quota.test.ts +140 tests/providers/minimax-reasoning-split.test.ts +241 tests/providers/mistral-budget-quota.test.ts +332 tests/providers/mistral-image-limit.test.ts +139 tests/providers/mistral-reasoning-efforts.test.ts +535 tests/providers/mistral-recovery.test.ts +363 tests/providers/model-discovery-skip-invalid-rows.test.ts +98 tests/providers/model-presets.test.ts +202 tests/providers/model-rename-migration.test.ts +170 tests/providers/model-roster-seed-repair.test.ts +227 tests/providers/modelflare-provider.test.ts +92 tests/providers/moonshot-developer-role.test.ts +63 tests/providers/moonshot-endpoints.test.ts 379 tests/providers/moonshot-tool-schema.test.ts -93 tests/providers/muse-key-quota.test.ts -891 tests/providers/muse-passive-quota-cache.test.ts -119 tests/providers/muse-passive-quota-observation.test.ts -98 tests/providers/muse-spark-web-search-compat.test.ts -31 tests/providers/muse-subscription-usage.test.ts -69 tests/providers/muse-tool-name-alias.test.ts -308 tests/providers/new-model-policy-runtime.test.ts -34 tests/providers/new-model-policy.test.ts -56 tests/providers/nous-oauth-live.test.ts -8144 tests/providers/nous-oauth.test.ts -184 tests/providers/novita-provider.test.ts -216 tests/providers/nscale-vultr-provider.test.ts -89 tests/providers/nvidia-nim-hardening.test.ts -31 tests/providers/ollama/ollama-native-cached-usage.test.ts -429 tests/providers/ollama/ollama-native-parser.test.ts -63 tests/providers/ollama/ollama-native-reasoning-wire.test.ts -65 tests/providers/ollama/ollama-native-scaling.test.ts -41 tests/providers/ollama/ollama-native-structured-output.test.ts -143 tests/providers/ollama/ollama-native-tool-continuations.test.ts -386 tests/providers/ollama/ollama-native-v4.test.ts -74 tests/providers/ollama/ollama-native.test.ts -464 tests/providers/ollama/ollama-show-enrichment-v7.test.ts -82 tests/providers/ollama/ollama-show-enrichment.test.ts -299 tests/providers/ollama/ollama-show-ignore-abort.test.ts -203 tests/providers/opencode-cli.test.ts -80 tests/providers/opencode-go-deepseek.test.ts -469 tests/providers/opencode-go-gemini-wire.test.ts -113 tests/providers/opencode-go-grok46-responses.test.ts -369 tests/providers/opencode-go-luna-wire.test.ts -228 tests/providers/opencode-go-model-protocols.test.ts -94 tests/providers/opencode-go-muse-context.test.ts -100 tests/providers/opencode-go-muse-vision.test.ts -57 tests/providers/opencode-go-quota.test.ts -1143 tests/providers/opencode-go-session-header.test.ts -500 tests/providers/opencode-management-transport.test.ts -30 tests/providers/opencode-muse-terminal-repair.test.ts -113 tests/providers/opencode-zen-deepseek-reasoning.test.ts -264 tests/providers/opencode-zen-gemini-wire.test.ts -43 tests/providers/opencode-zen-rate-limit.test.ts -44 tests/providers/opengateway-key-validation.test.ts -107 tests/providers/opengateway-provider.test.ts -152 tests/providers/openrouter-provider-routing.test.ts -68 tests/providers/openrouter-quota-reset-cooldown-4024.test.ts -130 tests/providers/opper-provider.test.ts -204 tests/providers/orcarouter-provider.test.ts -156 tests/providers/provider-account-quota-failure-reasons.test.ts -4483 tests/providers/provider-account-quota-persistence.test.ts -715 tests/providers/provider-account-quota.test.ts -73 tests/providers/provider-anthropic-instance-quota.test.ts -88 tests/providers/provider-anthropic-instance.test.ts -81 tests/providers/provider-anthropic-usage-windows.test.ts -82 tests/providers/provider-antigravity-effort-families.test.ts -160 tests/providers/provider-antigravity-family-catalog.test.ts -85 tests/providers/provider-antigravity-model-quota.test.ts -50 tests/providers/provider-antigravity-quota-retry.test.ts -1799 tests/providers/provider-antigravity-wire-snapshot.test.ts -529 tests/providers/provider-api-keys.test.ts -54 tests/providers/provider-capacity.test.ts -672 tests/providers/provider-completion-test-authority.test.ts -338 tests/providers/provider-completion-test-ingress.test.ts -362 tests/providers/provider-completion-test.test.ts -263 tests/providers/provider-config-batch-management.test.ts -50 tests/providers/provider-config-validation.test.ts -512 tests/providers/provider-connection-test.test.ts -69 tests/providers/provider-cost-overlay-config.test.ts -45 tests/providers/provider-discovery-log-suppression.test.ts -49 tests/providers/provider-egress-outbound.test.ts -52 tests/providers/provider-id-rewrite.test.ts -184 tests/providers/provider-input-modalities.test.ts -404 tests/providers/provider-key-store.test.ts -135 tests/providers/provider-live-models.test.ts -97 tests/providers/provider-model-aliases.test.ts -186 tests/providers/provider-model-discovery-contract.test.ts -39 tests/providers/provider-outbound-private-network.test.ts -515 tests/providers/provider-outbound.test.ts -79 tests/providers/provider-quota-abliteration.test.ts -82 tests/providers/provider-quota-claude-cli.test.ts -71 tests/providers/provider-quota-label-sanitize.test.ts -103 tests/providers/provider-quota-observed-marker.test.ts -85 tests/providers/provider-quota-ollama-cloud.test.ts -510 tests/providers/provider-quota.test.ts -231 tests/providers/provider-registry-parity.test.ts -46 tests/providers/provider-runtime-fetch.test.ts -65 tests/providers/provider-static-model-discovery.test.ts -44 tests/providers/provider-tls-profile.test.ts -260 tests/providers/qoder-adapter.test.ts -1509 tests/providers/qoder-cn-image-validation.test.ts -818 tests/providers/qoder-discovery-timeout.test.ts -65 tests/providers/qoder-image-input.test.ts -170 tests/providers/qoder-live-models.test.ts -110 tests/providers/qoder-mcp-server.test.ts -103 tests/providers/qoder-scaffold-guard.test.ts -34 tests/providers/qwen38-preserve-reasoning.test.ts -216 tests/providers/rate-limit-retry.test.ts -58 tests/providers/registry-transport-alias.test.ts -134 tests/providers/resolved-model-policy.test.ts -96 tests/providers/sambanova-nebius-provider.test.ts -125 tests/providers/sponsor-presets.test.ts -99 tests/providers/stepfun-provider.test.ts -161 tests/providers/tokenlab-protocols.test.ts -186 tests/providers/tokenlab-provider.test.ts -245 tests/providers/umans-provider.test.ts -10226 tests/providers/upstream-transient-retry.test.ts -61 tests/providers/vercel-gateway-provider-routing.test.ts -81 tests/providers/vision-classification-seed-repair.test.ts -102 tests/providers/volcengine-ark-assistant-content.test.ts -354 tests/providers/workbuddy-provider.test.ts -149 tests/providers/workbuddy-quota.test.ts -34 tests/providers/xai/grok-47-build-fast-metadata.test.ts -4231 tests/providers/xai/grok-47-fast-model-wire.test.ts -91 tests/providers/xai/grok-47-fast-model.test.ts -188 tests/providers/xai/grok-attribution.test.ts -240 tests/providers/xai/grok-config-inject.test.ts -80 tests/providers/xai/grok-config-write-lock.test.ts -279 tests/providers/xai/grok-coupon-claim.test.ts -89 tests/providers/xai/grok-coupon-reconcile.test.ts -198 tests/providers/xai/grok-effort-inject.test.ts -110 tests/providers/xai/grok-lifecycle.test.ts -595 tests/providers/xai/grok-management-api.test.ts -696 tests/providers/xai/grok-models-effort-list.test.ts -313 tests/providers/xai/grok-orphan-adoption.test.ts -66 tests/providers/xai/grok-reset-coupon-cli.test.ts -105 tests/providers/xai/grok-reset-coupons.test.ts -89 tests/providers/xai/grok-selection.test.ts -223 tests/providers/xai/grok-session-identity.test.ts -93 tests/providers/xai/grok-status.test.ts -196 tests/providers/xai/grok-sync.test.ts -157 tests/providers/xai/grok-writer-boundary.test.ts -87 tests/providers/xai/xai-additional-tools.test.ts -66 tests/providers/xai/xai-empty-catalog-tool-choice.test.ts -184 tests/providers/xai/xai-loaded-tool-provenance.test.ts -90 tests/providers/xai/xai-no-stop.test.ts -38 tests/providers/xai/xai-oauth-retry.test.ts -251 tests/providers/xai/xai-refresh-lock.test.ts -69 tests/providers/xai/xai-replay-provenance.test.ts -99 tests/providers/xai/xai-responses-adjacency.test.ts -56 tests/providers/xai/xai-tool-schema.test.ts -221 tests/providers/xai/xai-transport.test.ts -88 tests/providers/xai/xai-web-search-compat.test.ts -114 tests/providers/xai/xai-web-search.test.ts -68 tests/providers/zai-reasoning-replay.test.ts -327 tests/providers/zcode-client.test.ts -128 tests/providers/zed-argument-consistency.test.ts -35 tests/providers/zed-failure-relay.test.ts -437 tests/providers/zed-hosted-provider.test.ts -448 tests/providers/zed-lossless-arguments.test.ts -248 tests/providers/zed-openai-contract.test.ts -104 tests/providers/zed-retained-budget.test.ts -160 tests/providers/zhipu-bigmodel-provider.test.ts -76 tests/providers/zhipu-bigmodel-responses-quota.test.ts -548 tests/responses/agent-assertion-routes.test.ts -512 tests/responses/anthropic2-responses-parity.test.ts -44 tests/responses/apply-patch-envelope.test.ts -137 tests/responses/bare-echo-alias.test.ts -576 tests/responses/chat-anthropic-reasoning-details.test.ts -419 tests/responses/chat-completions-deferred-tools.test.ts -11246 tests/responses/chat-completions-endpoint.test.ts -537 tests/responses/chat-completions-pool-mode.test.ts -4473 tests/responses/chat-conversation-affinity.test.ts -7080 tests/responses/chat-error-body-normalization.test.ts -65 tests/responses/chat-error-collector-verdicts.test.ts -211 tests/responses/chat-inbound-developer-position.test.ts -54 tests/responses/chat-inbound-reasoning-none.test.ts -82 tests/responses/chat-inbound-reasoning-replay.test.ts -129 tests/responses/chat-inbound-tool-strict-defaults.test.ts -204 tests/responses/chat-incomplete-length-reason.test.ts -137 tests/responses/chat-inline-document-bytes.test.ts -542 tests/responses/chat-json-sse-fallback.test.ts -1275 tests/responses/chat-legacy-functions-combo.test.ts -347 tests/responses/chat-media-translation.test.ts -3398 tests/responses/chat-native-combo.test.ts -100 tests/responses/chat-native-decline-reason.test.ts -542 tests/responses/chat-native-developer-role.test.ts -154 tests/responses/chat-native-image-normalization.test.ts -33 tests/responses/chat-native-lenient-finish.test.ts -544 tests/responses/chat-native-mistral-content.test.ts -894 tests/responses/chat-native-reasoning-replay.test.ts -81 tests/responses/chat-native-reasoning-scope.test.ts -22900 tests/responses/chat-native-spend.test.ts -307 tests/responses/chat-native-sse-stall.test.ts -1702 tests/responses/chat-raw-reasoning-delivery.test.ts -52 tests/responses/chat-refusal-scope.test.ts -195 tests/responses/chat-refusal.test.ts -1188 tests/responses/chat-request-id-endpoint.test.ts -342 tests/responses/chat-responses-control-integration.test.ts -95 tests/responses/chat-responses-control-scope.test.ts -309 tests/responses/chat-sse-framing-guard.test.ts -42 tests/responses/chat-tool-choice-allowed-tools.test.ts -55 tests/responses/citation-markers.test.ts -2172 tests/responses/codex-0164-request-compat.test.ts -349 tests/responses/codex-installation-compact-empty.test.ts -314 tests/responses/codex-installation-failover.test.ts -438 tests/responses/codex-installation-turn-limit.test.ts -2061 tests/responses/codex-ws-handshake-validation.test.ts -138 tests/responses/codex-ws-handshake.test.ts -49 tests/responses/codex-ws-pool-contention.test.ts -214 tests/responses/combo-codex-ws-overload-failover.test.ts -688 tests/responses/combo-replay-refusal-attribution.test.ts -539 tests/responses/compact-key-selection.test.ts -11508 tests/responses/compact-transient-alternate.test.ts -114 tests/responses/compaction-continuation-note.test.ts -253 tests/responses/compaction-continuation-wire.test.ts -121 tests/responses/compaction-event-ownership.test.ts -220 tests/responses/compaction-history-framing.test.ts -257 tests/responses/compaction-portable-history.test.ts -121 tests/responses/compaction-progress.test.ts -69 tests/responses/continuation-dedup.test.ts -225 tests/responses/current-turn-tool-catalog-direct.test.ts -401 tests/responses/current-turn-tool-catalog-namespace.test.ts -51 tests/responses/custom-tool-compat.test.ts -205 tests/responses/direct-credit-renewal-ingress.test.ts -965 tests/responses/droid-reasoning-defaults.test.ts -542 tests/responses/empty-completion-core.test.ts +163 tests/providers/morph-ultra-provider.test.ts +57 tests/providers/muse-key-quota.test.ts +922 tests/providers/muse-passive-quota-cache.test.ts +148 tests/providers/muse-passive-quota-observation.test.ts +109 tests/providers/muse-spark-web-search-compat.test.ts +56 tests/providers/muse-subscription-usage.test.ts +119 tests/providers/muse-tool-name-alias.test.ts +272 tests/providers/new-model-policy-runtime.test.ts +55 tests/providers/new-model-policy.test.ts +85 tests/providers/nous-oauth-live.test.ts +8174 tests/providers/nous-oauth.test.ts +181 tests/providers/novita-provider.test.ts +148 tests/providers/nscale-vultr-provider.test.ts +185 tests/providers/nvidia-nim-hardening.test.ts +55 tests/providers/ollama/ollama-native-cached-usage.test.ts +358 tests/providers/ollama/ollama-native-parser.test.ts +107 tests/providers/ollama/ollama-native-reasoning-wire.test.ts +60 tests/providers/ollama/ollama-native-scaling.test.ts +64 tests/providers/ollama/ollama-native-structured-output.test.ts +194 tests/providers/ollama/ollama-native-tool-continuations.test.ts +372 tests/providers/ollama/ollama-native-v4.test.ts +116 tests/providers/ollama/ollama-native.test.ts +454 tests/providers/ollama/ollama-show-enrichment-v7.test.ts +142 tests/providers/ollama/ollama-show-enrichment.test.ts +312 tests/providers/ollama/ollama-show-ignore-abort.test.ts +340 tests/providers/opencode-cli.test.ts +96 tests/providers/opencode-go-deepseek.test.ts +433 tests/providers/opencode-go-gemini-wire.test.ts +179 tests/providers/opencode-go-grok46-responses.test.ts +653 tests/providers/opencode-go-luna-wire.test.ts +618 tests/providers/opencode-go-model-protocols.test.ts +125 tests/providers/opencode-go-muse-context.test.ts +106 tests/providers/opencode-go-muse-vision.test.ts +115 tests/providers/opencode-go-quota.test.ts +1727 tests/providers/opencode-go-session-header.test.ts +599 tests/providers/opencode-management-transport.test.ts +50 tests/providers/opencode-muse-terminal-repair.test.ts +116 tests/providers/opencode-zen-deepseek-reasoning.test.ts +382 tests/providers/opencode-zen-gemini-wire.test.ts +60 tests/providers/opencode-zen-rate-limit.test.ts +59 tests/providers/opengateway-key-validation.test.ts +161 tests/providers/opengateway-provider.test.ts +186 tests/providers/openrouter-provider-routing.test.ts +116 tests/providers/openrouter-quota-reset-cooldown-4024.test.ts +211 tests/providers/opper-provider.test.ts +266 tests/providers/orcarouter-provider.test.ts +95 tests/providers/passive-key-limits.test.ts +669 tests/providers/passive-key-observation.test.ts +183 tests/providers/provider-account-quota-failure-reasons.test.ts +4548 tests/providers/provider-account-quota-persistence.test.ts +497 tests/providers/provider-account-quota.test.ts +95 tests/providers/provider-alias-template.test.ts +105 tests/providers/provider-anthropic-instance-quota.test.ts +101 tests/providers/provider-anthropic-instance.test.ts +364 tests/providers/provider-anthropic-pool-capacity.test.ts +162 tests/providers/provider-anthropic-usage-windows.test.ts +50 tests/providers/provider-antigravity-effort-families.test.ts +208 tests/providers/provider-antigravity-family-catalog.test.ts +149 tests/providers/provider-antigravity-model-quota.test.ts +86 tests/providers/provider-antigravity-quota-retry.test.ts +2528 tests/providers/provider-antigravity-wire-snapshot.test.ts +732 tests/providers/provider-api-keys.test.ts +65 tests/providers/provider-capacity.test.ts +787 tests/providers/provider-completion-test-authority.test.ts +430 tests/providers/provider-completion-test-ingress.test.ts +437 tests/providers/provider-completion-test.test.ts +346 tests/providers/provider-config-batch-management.test.ts +67 tests/providers/provider-config-validation.test.ts +472 tests/providers/provider-connection-test.test.ts +115 tests/providers/provider-cost-overlay-config.test.ts +62 tests/providers/provider-discovery-log-suppression.test.ts +76 tests/providers/provider-egress-outbound.test.ts +72 tests/providers/provider-id-rewrite.test.ts +195 tests/providers/provider-input-modalities.test.ts +680 tests/providers/provider-key-store.test.ts +130 tests/providers/provider-live-models.test.ts +164 tests/providers/provider-model-aliases.test.ts +213 tests/providers/provider-model-discovery-contract.test.ts +60 tests/providers/provider-outbound-private-network.test.ts +656 tests/providers/provider-outbound.test.ts +120 tests/providers/provider-passive-wire-model.test.ts +114 tests/providers/provider-quota-abliteration.test.ts +121 tests/providers/provider-quota-claude-cli.test.ts +101 tests/providers/provider-quota-label-sanitize.test.ts +112 tests/providers/provider-quota-observed-marker.test.ts +127 tests/providers/provider-quota-ollama-cloud.test.ts +746 tests/providers/provider-quota.test.ts +381 tests/providers/provider-registry-parity.test.ts +66 tests/providers/provider-runtime-fetch.test.ts +111 tests/providers/provider-static-model-discovery.test.ts +76 tests/providers/provider-tls-profile.test.ts +379 tests/providers/qoder-adapter.test.ts +1183 tests/providers/qoder-cn-image-validation.test.ts +843 tests/providers/qoder-discovery-timeout.test.ts +79 tests/providers/qoder-image-input.test.ts +101 tests/providers/qoder-live-models.test.ts +197 tests/providers/qoder-mcp-server.test.ts +144 tests/providers/qoder-scaffold-guard.test.ts +57 tests/providers/qwen38-preserve-reasoning.test.ts +371 tests/providers/rate-limit-retry.test.ts +96 tests/providers/registry-transport-alias.test.ts +176 tests/providers/resolved-model-policy.test.ts +212 tests/providers/sambanova-nebius-provider.test.ts +210 tests/providers/sponsor-presets.test.ts +297 tests/providers/stepfun-provider.test.ts +282 tests/providers/tokenlab-protocols.test.ts +115 tests/providers/tokenlab-provider.test.ts +165 tests/providers/umans-provider.test.ts +10289 tests/providers/upstream-transient-retry.test.ts +106 tests/providers/vercel-gateway-provider-routing.test.ts +187 tests/providers/vision-classification-seed-repair.test.ts +67 tests/providers/volcengine-ark-assistant-content.test.ts +547 tests/providers/workbuddy-provider.test.ts +150 tests/providers/workbuddy-quota.test.ts +60 tests/providers/xai/grok-47-build-fast-metadata.test.ts +6607 tests/providers/xai/grok-47-fast-model-wire.test.ts +132 tests/providers/xai/grok-47-fast-model.test.ts +191 tests/providers/xai/grok-attribution.test.ts +295 tests/providers/xai/grok-config-inject.test.ts +115 tests/providers/xai/grok-config-write-lock.test.ts +419 tests/providers/xai/grok-coupon-claim.test.ts +138 tests/providers/xai/grok-coupon-reconcile.test.ts +225 tests/providers/xai/grok-effort-inject.test.ts +122 tests/providers/xai/grok-lifecycle.test.ts +865 tests/providers/xai/grok-management-api.test.ts +697 tests/providers/xai/grok-models-effort-list.test.ts +292 tests/providers/xai/grok-orphan-adoption.test.ts +100 tests/providers/xai/grok-reset-coupon-cli.test.ts +76 tests/providers/xai/grok-reset-coupons.test.ts +146 tests/providers/xai/grok-selection.test.ts +169 tests/providers/xai/grok-session-identity.test.ts +117 tests/providers/xai/grok-status.test.ts +156 tests/providers/xai/grok-sync.test.ts +171 tests/providers/xai/grok-writer-boundary.test.ts +125 tests/providers/xai/xai-additional-tools.test.ts +82 tests/providers/xai/xai-device-login.test.ts +115 tests/providers/xai/xai-empty-catalog-tool-choice.test.ts +388 tests/providers/xai/xai-loaded-tool-provenance.test.ts +114 tests/providers/xai/xai-no-stop.test.ts +66 tests/providers/xai/xai-oauth-retry.test.ts +197 tests/providers/xai/xai-refresh-lock.test.ts +149 tests/providers/xai/xai-replay-provenance.test.ts +113 tests/providers/xai/xai-responses-adjacency.test.ts +72 tests/providers/xai/xai-tool-schema.test.ts +165 tests/providers/xai/xai-transport.test.ts +127 tests/providers/xai/xai-web-search-compat.test.ts +157 tests/providers/xai/xai-web-search.test.ts +93 tests/providers/zai-reasoning-replay.test.ts +646 tests/providers/zcode-client.test.ts +269 tests/providers/zed-argument-consistency.test.ts +131 tests/providers/zed-failure-relay.test.ts +325 tests/providers/zed-hosted-provider.test.ts +459 tests/providers/zed-lossless-arguments.test.ts +189 tests/providers/zed-openai-contract.test.ts +332 tests/providers/zed-retained-budget.test.ts +167 tests/providers/zhipu-bigmodel-provider.test.ts +88 tests/providers/zhipu-bigmodel-responses-quota.test.ts +718 tests/responses/agent-assertion-routes.test.ts +758 tests/responses/anthropic2-responses-parity.test.ts +61 tests/responses/apply-patch-envelope.test.ts +182 tests/responses/bare-echo-alias.test.ts +606 tests/responses/chat-anthropic-reasoning-details.test.ts +522 tests/responses/chat-completions-deferred-tools.test.ts +11810 tests/responses/chat-completions-endpoint.test.ts +424 tests/responses/chat-completions-pool-mode.test.ts +441 tests/responses/chat-conversation-affinity.test.ts +6779 tests/responses/chat-error-body-normalization.test.ts +86 tests/responses/chat-error-collector-verdicts.test.ts +388 tests/responses/chat-inbound-developer-position.test.ts +56 tests/responses/chat-inbound-reasoning-none.test.ts +145 tests/responses/chat-inbound-reasoning-replay.test.ts +149 tests/responses/chat-inbound-tool-strict-defaults.test.ts +439 tests/responses/chat-incomplete-length-reason.test.ts +131 tests/responses/chat-inline-document-bytes.test.ts +520 tests/responses/chat-json-sse-fallback.test.ts +1469 tests/responses/chat-legacy-functions-combo.test.ts +418 tests/responses/chat-media-translation.test.ts +3109 tests/responses/chat-native-combo.test.ts +169 tests/responses/chat-native-decline-reason.test.ts +779 tests/responses/chat-native-developer-role.test.ts +192 tests/responses/chat-native-image-normalization.test.ts +63 tests/responses/chat-native-lenient-finish.test.ts +856 tests/responses/chat-native-mistral-content.test.ts +1362 tests/responses/chat-native-reasoning-replay.test.ts +96 tests/responses/chat-native-reasoning-scope.test.ts +23458 tests/responses/chat-native-spend.test.ts +293 tests/responses/chat-native-sse-stall.test.ts +1800 tests/responses/chat-raw-reasoning-delivery.test.ts +63 tests/responses/chat-refusal-scope.test.ts +266 tests/responses/chat-refusal.test.ts +1370 tests/responses/chat-request-id-endpoint.test.ts +436 tests/responses/chat-responses-control-integration.test.ts +126 tests/responses/chat-responses-control-scope.test.ts +403 tests/responses/chat-sse-framing-guard.test.ts +70 tests/responses/chat-tool-choice-allowed-tools.test.ts +301 tests/responses/citation-markers.test.ts +299 tests/responses/codex-0164-request-compat.test.ts +3465 tests/responses/codex-eager-tool-catalog.test.ts +322 tests/responses/codex-installation-compact-empty.test.ts +467 tests/responses/codex-installation-failover.test.ts +481 tests/responses/codex-installation-turn-limit.test.ts +2083 tests/responses/codex-ws-handshake-validation.test.ts +132 tests/responses/codex-ws-handshake.test.ts +81 tests/responses/codex-ws-pool-contention.test.ts +208 tests/responses/combo-codex-ws-overload-failover.test.ts +1152 tests/responses/combo-replay-refusal-attribution.test.ts +1828 tests/responses/combo-stream-attempt-timing.test.ts +531 tests/responses/compact-key-selection.test.ts +11200 tests/responses/compact-transient-alternate.test.ts +138 tests/responses/compaction-continuation-note.test.ts +324 tests/responses/compaction-continuation-wire.test.ts +120 tests/responses/compaction-event-ownership.test.ts +239 tests/responses/compaction-history-framing.test.ts +300 tests/responses/compaction-portable-history.test.ts +132 tests/responses/compaction-progress.test.ts +60 tests/responses/continuation-dedup.test.ts +258 tests/responses/current-turn-tool-catalog-direct.test.ts +287 tests/responses/current-turn-tool-catalog-namespace.test.ts +71 tests/responses/custom-tool-compat.test.ts +207 tests/responses/direct-credit-renewal-ingress.test.ts +1407 tests/responses/droid-reasoning-defaults.test.ts +824 tests/responses/empty-completion-core.test.ts 67 tests/responses/empty-completion-guard.test.ts -1166 tests/responses/empty-completion-hardening.test.ts -105 tests/responses/eventstream-decoder.test.ts -69 tests/responses/eventstream-fragmentation.test.ts -1417 tests/responses/explicit-empty-tool-catalog-history.test.ts -1799 tests/responses/explicit-empty-tool-catalog.test.ts -170 tests/responses/external-task-input-repair.test.ts -36 tests/responses/fix-eventstream-cancel-wait.test.ts -156 tests/responses/fresh-connection-optout.test.ts -134 tests/responses/graceful-max-output-tokens-exclusions.test.ts -538 tests/responses/graceful-max-output-tokens.test.ts -1687 tests/responses/incomplete-reason-normalization.test.ts -1181 tests/responses/jev-initial-effort-wire.test.ts -85 tests/responses/legacy-shell-compat.test.ts -159 tests/responses/local-checkpoint-routing.test.ts -446 tests/responses/local-upstream-deadlines.test.ts -133 tests/responses/messages-native-bridge-policy.test.ts -127 tests/responses/messages-native-eligibility.test.ts -107 tests/responses/messages-native-oauth-eligibility.test.ts -37 tests/responses/namespace-tool-compat.test.ts -313 tests/responses/native-compaction-gateway-credentials.test.ts -833 tests/responses/native-compaction-gateway-policy.test.ts -4710 tests/responses/native-compaction-gateway.test.ts -268 tests/responses/native-compaction-oauth.test.ts -1306 tests/responses/native-compaction-provenance.test.ts -195 tests/responses/opaque-blob-wrapped-rejection.test.ts -346 tests/responses/openai-responses-passthrough.test.ts -83 tests/responses/openai-responses-summary-none.test.ts -93 tests/responses/opengateway-completion-receipts.test.ts -31 tests/responses/parser-content-audio.test.ts -302 tests/responses/passthrough-abort.test.ts -3151 tests/responses/passthrough-deferred-tools.test.ts -70 tests/responses/passthrough-grok-upstream-envelope-echo.test.ts -219 tests/responses/passthrough-headers.test.ts -107 tests/responses/passthrough-media-type.test.ts -62 tests/responses/passthrough-override.test.ts -169 tests/responses/plaintext-v2-agent-messages.test.ts -324 tests/responses/pool-retry-client-metadata.test.ts -578 tests/responses/protocol-antigravity-direct-chat.test.ts -96 tests/responses/protocol-antigravity-direct-eligibility.test.ts -416 tests/responses/protocol-antigravity-direct-messages.test.ts -1339 tests/responses/protocol-argon-thought-boundary.test.ts -33 tests/responses/protocol-baseline.test.ts -49 tests/responses/protocol-chat-ir-parity.test.ts -37 tests/responses/protocol-contract.test.ts -234 tests/responses/protocol-direct-encoders-chat.test.ts -54 tests/responses/protocol-direct-encoders-local-upstream.test.ts -120 tests/responses/protocol-direct-encoders-messages.test.ts -45 tests/responses/protocol-direct-encoders-stall-disabled.test.ts -44 tests/responses/protocol-dto.test.ts -38 tests/responses/protocol-envelope.test.ts -37 tests/responses/protocol-features.test.ts -35 tests/responses/protocol-guard.test.ts -172 tests/responses/protocol-ingress-guard.test.ts -87 tests/responses/protocol-messages-ir-parity.test.ts -45 tests/responses/protocol-opaque-state.test.ts -37 tests/responses/protocol-path.test.ts -141 tests/responses/protocol-plan-snapshot.test.ts -36 tests/responses/protocol-plan.test.ts -113 tests/responses/protocol-shadow-plan.test.ts -28 tests/responses/protocol-trace.test.ts -35 tests/responses/provider-egress-fetch.test.ts -425 tests/responses/reasoning-archive-http.test.ts -423 tests/responses/reasoning-archive-ws.test.ts -112 tests/responses/reasoning-effort-summary-default.test.ts -213 tests/responses/reasoning-envelope.test.ts -109 tests/responses/reasoning-retention-quota.test.ts -1615 tests/responses/reasoning-retention-routing.test.ts -616 tests/responses/reasoning-retention-v2.test.ts -65 tests/responses/reasoning-retention.test.ts -619 tests/responses/refreshed-upstream-deadlines.test.ts -85 tests/responses/reserve-dispatch-ws.test.ts -107 tests/responses/responses-4546-incident-regression.test.ts -767 tests/responses/responses-account-auto-pause-wire-owner.test.ts -1389 tests/responses/responses-account-auto-pause.test.ts -73 tests/responses/responses-account-change-scrub.test.ts -3165 tests/responses/responses-account-label.test.ts -611 tests/responses/responses-alternate-main-cancellation.test.ts -360 tests/responses/responses-anthropic-billing-send-budget.test.ts -303 tests/responses/responses-anthropic-compaction-prefix.test.ts -637 tests/responses/responses-anthropic-fast-downgrade.test.ts -173 tests/responses/responses-anthropic-legal-history.test.ts -215 tests/responses/responses-anthropic-thinking-recovery.test.ts -878 tests/responses/responses-anthropic-thinking-signature-recovery.test.ts -1323 tests/responses/responses-auto-pause-replay-owner.test.ts -339 tests/responses/responses-azure-opaque-blob-recovery.test.ts -133 tests/responses/responses-bare-echo-helper-fence.test.ts -53 tests/responses/responses-call-id-linkage.test.ts -427 tests/responses/responses-canonical-nonstream.test.ts -66 tests/responses/responses-canonical-only-top-level-fields.test.ts -209 tests/responses/responses-chat-tool-call-content.test.ts -67 tests/responses/responses-chatgpt-web-replay-metadata.test.ts -119 tests/responses/responses-claude-preflight-lease.test.ts -33 tests/responses/responses-code-mode-goal-helpers.test.ts -154 tests/responses/responses-code-mode-mcp-direct.test.ts -49 tests/responses/responses-code-mode-patch-compile.test.ts -90 tests/responses/responses-code-mode-shell-compile.test.ts -2690 tests/responses/responses-cold-opaque-recovery.test.ts -129 tests/responses/responses-combo-bridge-usage.test.ts -470 tests/responses/responses-combo-exhausted-error.test.ts -281 tests/responses/responses-combo-fallback-off.test.ts -236 tests/responses/responses-combo-replay-principal.test.ts -470 tests/responses/responses-combo-run-turn-classified-failure.test.ts -6962 tests/responses/responses-compact-handoff-admission.test.ts -2762 tests/responses/responses-compaction-http-isolation.test.ts -3010 tests/responses/responses-compaction-override.test.ts -131 tests/responses/responses-compaction-policy-identity.test.ts -41 tests/responses/responses-compaction-recovery-policy.test.ts -6650 tests/responses/responses-compaction-recovery.test.ts -3613 tests/responses/responses-compaction-routing.test.ts -207 tests/responses/responses-compaction.test.ts -5933 tests/responses/responses-console-go-upload-retry.test.ts -2742 tests/responses/responses-context-overflow.test.ts -99 tests/responses/responses-continuation-boundaries.test.ts -118 tests/responses/responses-core-modules.test.ts -47 tests/responses/responses-custom-tool-guidance.test.ts -128 tests/responses/responses-custom-tool-historical-replay.test.ts -245 tests/responses/responses-custom-tool-repair-dispatch.test.ts -48 tests/responses/responses-custom-tool-repair.test.ts -208 tests/responses/responses-custom-tool-stream-consistency.test.ts -31 tests/responses/responses-default-namespace-emit-normalize.test.ts -651 tests/responses/responses-devin-401-replay.test.ts -505 tests/responses/responses-direct-chat-tool-choice.test.ts -50 tests/responses/responses-dispatch-receipt.test.ts -302 tests/responses/responses-fetch-helpers-boundary.test.ts -91 tests/responses/responses-field-backfill.test.ts -9712 tests/responses/responses-first-send-reservation.test.ts -195 tests/responses/responses-first-send-spend-policy.test.ts -476 tests/responses/responses-forward-client-headers-live.test.ts -116 tests/responses/responses-forward-client-headers.test.ts -68 tests/responses/responses-forward-dangling-call.test.ts -249 tests/responses/responses-forward-incomplete-quota.test.ts -67 tests/responses/responses-forward-output-cap.test.ts -72 tests/responses/responses-forward-posit-continuation.test.ts -71 tests/responses/responses-forward-prompt-envelope.test.ts -32 tests/responses/responses-forward-transport-baseurl.test.ts -191 tests/responses/responses-freeform-wrapper-keys.test.ts -154 tests/responses/responses-function-tool-repair.test.ts -4615 tests/responses/responses-grok-devin-preflight.test.ts -135 tests/responses/responses-hide-raw-reasoning.test.ts -245 tests/responses/responses-hosted-image-delivery.test.ts -56 tests/responses/responses-hosted-image-display.test.ts -212 tests/responses/responses-hosted-image-limits.test.ts -225 tests/responses/responses-hosted-send-hop.test.ts -376 tests/responses/responses-hosted-send-producer.test.ts -584 tests/responses/responses-hosted-send-reservation.test.ts -175 tests/responses/responses-hosted-send-round-parity.test.ts -190 tests/responses/responses-hosted-send-unsent-hop.test.ts -339 tests/responses/responses-hosted-send-ws.test.ts -86 tests/responses/responses-hosted-tool-declaration.test.ts -78 tests/responses/responses-hosted-tool-min-spread.test.ts -202 tests/responses/responses-image-gen-repair.test.ts -638 tests/responses/responses-inbound-store-default.test.ts -40 tests/responses/responses-item-id-repair.test.ts -31 tests/responses/responses-json-events.test.ts -41 tests/responses/responses-legacy-dotted-tool-name-repair.test.ts -382 tests/responses/responses-main-quota-observation.test.ts -212 tests/responses/responses-memory-models.test.ts -60 tests/responses/responses-mimo-envelope.test.ts -150 tests/responses/responses-muse-tool-choice.test.ts -306 tests/responses/responses-muse-tool-name-alias.test.ts -140 tests/responses/responses-native-compact-ocx-envelope.test.ts -196 tests/responses/responses-native-compact-search-history.test.ts -116 tests/responses/responses-native-item-extensions-compact.test.ts -91 tests/responses/responses-native-item-extensions.test.ts -519 tests/responses/responses-native-key-cooldown.test.ts -724 tests/responses/responses-native-main-refresh.test.ts -31 tests/responses/responses-native-output-identity.test.ts -557 tests/responses/responses-native-ultra-effort-wire.test.ts -1034 tests/responses/responses-oauth-refresh-capacity.test.ts -51 tests/responses/responses-ollama-codec.test.ts -5323 tests/responses/responses-opaque-blob-recovery.test.ts -38 tests/responses/responses-parser-agent-message.test.ts -47 tests/responses/responses-parser-malformed-content.test.ts -129 tests/responses/responses-parser.test.ts -85 tests/responses/responses-passthrough-transient-policy.test.ts -60 tests/responses/responses-phase-inference.test.ts -4676 tests/responses/responses-pool-401-refresh.test.ts -13437 tests/responses/responses-pool-overload-failover.test.ts -80 tests/responses/responses-pool-refresh-attribution.test.ts -427 tests/responses/responses-preview-main-read-fence.test.ts -311 tests/responses/responses-reasoning-effort-downgrade.test.ts -440 tests/responses/responses-reasoning-summary-passthrough.test.ts -189 tests/responses/responses-repeated-tool-outputs.test.ts -163 tests/responses/responses-replay-metadata-principal.test.ts -116 tests/responses/responses-request-compression.test.ts -307 tests/responses/responses-required-chat-tool.test.ts -57 tests/responses/responses-reset-replay.test.ts -2343 tests/responses/responses-retained-reasoning-stream-recovery.test.ts -88 tests/responses/responses-routed-web-search-fields.test.ts -309 tests/responses/responses-run-turn-key-pacing.test.ts -187 tests/responses/responses-run-turn-key-readmission.test.ts -438 tests/responses/responses-run-turn-web-search.test.ts -2022 tests/responses/responses-self-named-namespace-scrub.test.ts -6555 tests/responses/responses-send-budget-counts.test.ts -393 tests/responses/responses-send-budget-errors.test.ts -306 tests/responses/responses-shadow-intercept.test.ts -275 tests/responses/responses-show-thinking-summary.test.ts -679 tests/responses/responses-sidecar-context-overflow.test.ts -230 tests/responses/responses-sidecar-usage.test.ts -161 tests/responses/responses-skills-snapshot.test.ts -653 tests/responses/responses-snapshot-repair-server.test.ts -198 tests/responses/responses-snapshot-repair.test.ts -385 tests/responses/responses-snapshot-scaling.test.ts -216 tests/responses/responses-sparse-terminal-tool-scope.test.ts -1934 tests/responses/responses-spend-anchor.test.ts -93 tests/responses/responses-spend-capacity-guard.test.ts -353 tests/responses/responses-spend-contract-c.test.ts -134 tests/responses/responses-spend-ledger-wiring.test.ts -60 tests/responses/responses-spill-acl-recovery.test.ts -299 tests/responses/responses-spill-admission-headroom.test.ts -59 tests/responses/responses-spill-inspection.test.ts -48 tests/responses/responses-spill-orphan-sweep.test.ts -250 tests/responses/responses-spill-shutdown-clock.test.ts -39 tests/responses/responses-state-flush-race.test.ts -34 tests/responses/responses-state-snapshot-select.test.ts -68 tests/responses/responses-state-snapshot-stubs.test.ts -281 tests/responses/responses-state-store-false.test.ts -300 tests/responses/responses-state-write-amplification.test.ts -7146 tests/responses/responses-state.test.ts -584 tests/responses/responses-stateless-dangling-call-repair.test.ts -34 tests/responses/responses-stream-tool-events.test.ts -65 tests/responses/responses-terminal-repair.test.ts -155 tests/responses/responses-tool-conformance.test.ts -33 tests/responses/responses-tool-groups.test.ts -168 tests/responses/responses-tool-search-repair.test.ts -362 tests/responses/responses-translated-replay-principal.test.ts -18403 tests/responses/responses-translated-reset.test.ts -293 tests/responses/responses-undeclared-tool-guard-inbound.test.ts -937 tests/responses/responses-undeclared-tool-guard.test.ts -70 tests/responses/responses-url-citation-title-repair.test.ts -177 tests/responses/responses-usage-passthrough.test.ts -1078 tests/responses/responses-web-search-thinking-signature-recovery.test.ts -1210 tests/responses/responses-websocket-workflow-ceiling.test.ts -880 tests/responses/responses-workflow-send-ceiling.test.ts -303 tests/responses/responses-xai-request-compat.test.ts -212 tests/responses/shadow-intercept-target-lifecycle.test.ts -62 tests/responses/sse-carriage-return.test.ts -309 tests/responses/sse-client-frame-bounds.test.ts -369 tests/responses/sse-decoder.test.ts -219 tests/responses/sse-failed-tail.test.ts -426 tests/responses/sse-inspector-bounds.test.ts -63 tests/responses/sse-null-data-frame.test.ts -388 tests/responses/sse-payload-rewrite-continuation.test.ts -102 tests/responses/sse-payload-rewrite.test.ts -118 tests/responses/sse-rewrite-line-endings.test.ts -47 tests/responses/sse-unspaced-data-fields.test.ts -68 tests/responses/thought-signature-credential-scope.test.ts -160 tests/responses/turn-membership-ingress.test.ts -85 tests/responses/turn-membership.test.ts -39 tests/responses/visualization-directives.test.ts -499 tests/responses/ws-ambiguous-resend.test.ts -3953 tests/responses/ws-capacity-reclamation.test.ts -278 tests/responses/ws-capacity-tool-ownership.test.ts -51 tests/responses/ws-committed-liveness.test.ts -135 tests/responses/ws-endpoint.test.ts -217 tests/responses/ws-failure-stage.test.ts -390 tests/responses/ws-native-continuation-send-budget.test.ts -762 tests/responses/ws-native-injection.test.ts -238 tests/responses/ws-native-result-continuations.test.ts -1510 tests/responses/ws-native-steering.test.ts -224 tests/responses/ws-pre-output-refusal.test.ts -198 tests/responses/ws-replay-refusal-attribution.test.ts -318 tests/responses/ws-steering-completion.test.ts -268 tests/responses/ws-steering-smoke.test.ts -196 tests/responses/ws-steering-stability.test.ts -117 tests/responses/ws-upstream-reuse.test.ts -52 tests/responses/ws-upstream-socks5.test.ts -634 tests/responses/ws-upstream.test.ts -144 tests/routing/always-on-429-failover.test.ts -83 tests/routing/anthropic-quorum-cache.test.ts -38 tests/routing/cl01-claude-outbound-review-regressions.test.ts -43 tests/routing/cl01-openai-chat-review-regressions.test.ts -75 tests/routing/cl01-review-regressions.test.ts -83 tests/routing/codex-agent-role-models.test.ts -48 tests/routing/codex-role-auto-assign.test.ts -55 tests/routing/codex-role-capability-consent.test.ts -93 tests/routing/codex-role-capability-pages.test.ts -54 tests/routing/codex-role-capability-redirects.test.ts -55 tests/routing/codex-role-measured-ties.test.ts -38 tests/routing/codex-role-sizing.test.ts -160 tests/routing/combo-child-headers.test.ts -183 tests/routing/combo-description.test.ts -646 tests/routing/combo-management-api.test.ts -90 tests/routing/combo-required-tool-stream-preflight.test.ts -109 tests/routing/combo-stream-preflight.test.ts -148 tests/routing/combo-terminal-refusal.test.ts -231 tests/routing/combo-vision-enrollment.test.ts -114 tests/routing/compatibility-provider-equivalence.test.ts -43 tests/routing/destination-policy-resolved.test.ts -62 tests/routing/fallback-policy.test.ts -67 tests/routing/fastwire-characterization-routing.test.ts -347 tests/routing/fastwire-characterization-wire.test.ts -158 tests/routing/fastwire-observability.test.ts -91 tests/routing/fastwire-policy.test.ts -383 tests/routing/fastwire-response-authority.test.ts -56 tests/routing/jev-decision-destination.test.ts -315 tests/routing/jev-decision-model-config.test.ts -182 tests/routing/jev-decision-provider-combo.test.ts -130 tests/routing/jev-decision.test.ts -1050 tests/routing/jev-model-backend.test.ts -185 tests/routing/jev-quota-activation.test.ts -140 tests/routing/jev-quota-anthropic2.test.ts -229 tests/routing/jev-quota-antigravity.test.ts -134 tests/routing/jev-quota-codex-reset.test.ts -180 tests/routing/jev-quota-config.test.ts -404 tests/routing/jev-quota-core-boundary.test.ts -123 tests/routing/jev-quota-publication.test.ts -221 tests/routing/jev-quota-signals.test.ts -45 tests/routing/jev-service-exchange.test.ts -43 tests/routing/jev-session-pin.test.ts -141 tests/routing/jev-typesafe-golden.test.ts -95 tests/routing/policy-execution.test.ts -267 tests/routing/probe-lease-dispatch-wiring.test.ts -98 tests/routing/probe-lease.test.ts -117 tests/routing/resolved-model-policy-consumers.test.ts -45 tests/routing/router-anthropic-billing-failover.test.ts -149 tests/routing/router-blocked-cross-provider.test.ts -52 tests/routing/router-combo-failover-classification.test.ts -87 tests/routing/router-discarded-baseurl-warning.test.ts -77 tests/routing/router-template-baseurl.test.ts -76 tests/routing/router.test.ts -213 tests/routing/routing-analytics.test.ts -53 tests/routing/routing-capability-catalog.test.ts -117 tests/routing/routing-capability-model-matching.test.ts -38 tests/routing/routing-compatibility-auth-identity.test.ts -195 tests/routing/routing-compatibility-boundaries.test.ts -58 tests/routing/routing-compatibility-model-matching.test.ts -111 tests/routing/routing-compatibility.test.ts -57 tests/routing/routing-identity-domains.test.ts -213 tests/routing/routing-policy-dispatch-scope.test.ts -106 tests/routing/routing-policy-fallback-off.test.ts -293 tests/routing/routing-policy-fallback.test.ts -56 tests/routing/routing-policy-pool-quota.test.ts -272 tests/routing/routing-policy-surface-parity.test.ts -266 tests/routing/routing-profile-management-editor.test.ts -202 tests/routing/routing-profile.test.ts -90 tests/routing/subagent-context-staleness.test.ts -45 tests/routing/subagent-defaults.test.ts -4365 tests/routing/subagent-fallback-handle-responses.test.ts -34 tests/routing/subagent-fallback-preview-sites.test.ts -116 tests/routing/subagent-model-fallback-api.test.ts -121 tests/routing/subagent-model-fallback-off.test.ts -689 tests/routing/subagent-model-fallback.test.ts -88 tests/routing/subagent-roster-migration.test.ts -400 tests/routing/subagent-roster-retention.test.ts -71 tests/server/account-import-project-fallback.test.ts -199 tests/server/account-import.test.ts -2049 tests/server/account-pool-management-api.test.ts -105 tests/server/adapter-resolve.test.ts -150 tests/server/admitted-http-turn.test.ts -52 tests/server/advisor-routes.test.ts -119 tests/server/agent-assertion-auth.test.ts -187 tests/server/agent-task-recovery-cache.test.ts -427 tests/server/agent-task-recovery-combo.test.ts -189 tests/server/agent-task-recovery-fallback.test.ts -267 tests/server/agent-task-recovery-security.test.ts -11535 tests/server/agent-task-recovery.test.ts -187 tests/server/alias-management-api.test.ts -146 tests/server/anthropic2-management.test.ts -96 tests/server/api-access-endpoints.test.ts -904 tests/server/api-catalog-route.test.ts -226 tests/server/api-codex-log-guard-compact.test.ts -170 tests/server/api-codex-log-guard-protection.test.ts -140 tests/server/api-codex-log-guard.test.ts -944 tests/server/api-debug.test.ts -3066 tests/server/api-key-attribution.test.ts -121 tests/server/api-key-model-scope.test.ts -282 tests/server/api-key-scope-alpha-search.test.ts -101 tests/server/api-key-scope-audio.test.ts -325 tests/server/api-key-scope-images.test.ts -141 tests/server/api-key-scope-live.test.ts -1967 tests/server/api-keys-routes.test.ts -3463 tests/server/api-usage.test.ts -374 tests/server/aside-profiles-routes.test.ts -93 tests/server/audio-client.test.ts -686 tests/server/audio-dictation.test.ts -777 tests/server/audio-transcriptions.test.ts -504 tests/server/bounded-body.test.ts -117 tests/server/bridge-live-delivery.test.ts -214 tests/server/caller-session-identity.test.ts -386 tests/server/caller-session-ingress.test.ts -2479 tests/server/cancel-body-on-abort.test.ts -1030 tests/server/claude-intercept-integration.test.ts -152 tests/server/client-retry-after-sites.test.ts -392 tests/server/codex-agent-role-routes.test.ts -193 tests/server/codex-role-auto-assign-routes.test.ts -153 tests/server/codex-role-configured-credentials.test.ts -206 tests/server/codex-role-history-recovery.test.ts -438 tests/server/combo-loopback-metered-consent.test.ts -259 tests/server/combo-metered-consent.test.ts -53 tests/server/combo-requested-effort.test.ts -113 tests/server/companion-settings.test.ts -281 tests/server/config.test.ts -149 tests/server/consume-for-inspection-cancel.test.ts -411 tests/server/context-history-ownership.test.ts -305 tests/server/context-history.test.ts -293 tests/server/data-plane-admission-identity.test.ts -34 tests/server/debug-settings.test.ts -28 tests/server/decision-discovery.test.ts -211 tests/server/decision-routes.test.ts -308 tests/server/distributed-key-401.test.ts -164 tests/server/error-fidelity.test.ts -129 tests/server/errors-adapter-failure.test.ts -175 tests/server/fallback-routes.test.ts -511 tests/server/fetch-header-timeout.test.ts -228 tests/server/health-scoring.test.ts -473 tests/server/hub-usage.test.ts -595 tests/server/inbound-body-admission.test.ts -108 tests/server/inbound-body-budget.test.ts -61 tests/server/inference-attempt.test.ts -115 tests/server/inference-client-encoder-delivery.test.ts -81 tests/server/inference-client-wire.test.ts -96 tests/server/inference-final-log.test.ts -1800 tests/server/inference-send-budget.test.ts -98 tests/server/input-admission.test.ts -112 tests/server/jev-decision-scope.test.ts -140 tests/server/link-child-parity.test.ts -119 tests/server/link-enrollment-ephemeral-child.test.ts -221 tests/server/link-enrollment.test.ts -2545 tests/server/link-join-route.test.ts -450 tests/server/link-listener-admission.test.ts -151 tests/server/link-listener-lifecycle.test.ts -46 tests/server/link-listener-mutation.test.ts -6018 tests/server/link-management-relay.test.ts -433 tests/server/link-management-routes.test.ts -46 tests/server/live-call-bindings.test.ts -45 tests/server/live-native-calls.test.ts -183 tests/server/local-account-switch-capability.test.ts -284 tests/server/local-account-switch-ingress.test.ts -517 tests/server/local-aside-sync-capability.test.ts -2262 tests/server/local-control-socket.test.ts -34 tests/server/local-management-attestation.test.ts -64 tests/server/local-management-capability.test.ts -471 tests/server/local-management-direct-transport.test.ts -41 tests/server/local-provider-reload-client.test.ts -408 tests/server/local-read-response-proof.test.ts -625 tests/server/login-shell-path.test.ts -137 tests/server/logs-timezone.test.ts -142 tests/server/loopback-companion-client-targets.test.ts -73 tests/server/loopback-listener-admission.test.ts -2330 tests/server/loopback-listener-integration.test.ts -182 tests/server/management-account-auto-pause.test.ts -115 tests/server/management-anthropic-reset-grants.test.ts -204 tests/server/management-api-logs-metrics.test.ts -139 tests/server/management-api-logs-timing-basis.test.ts -245 tests/server/management-auto-review-auth.test.ts -108 tests/server/management-auto-review-settings.test.ts -544 tests/server/management-client-config-route.test.ts -200 tests/server/management-desktop-compatibility-routes.test.ts -130 tests/server/management-desktop-compatibility-runtime-routes.test.ts -180 tests/server/management-desktop-compatibility-settings.test.ts -325 tests/server/management-droid-reasoning-defaults.test.ts -379 tests/server/management-export-model-names.test.ts -510 tests/server/management-gcp-credential-input.test.ts -185 tests/server/management-google-tool-schema-policy.test.ts -222 tests/server/management-inference-port.test.ts -242 tests/server/management-integration-journal-delete.test.ts -829 tests/server/management-integration-routes.test.ts -1580 tests/server/management-metrics-export.test.ts -145 tests/server/management-model-roster-gather-race.test.ts -130 tests/server/management-model-roster.test.ts -54 tests/server/management-origin-tls.test.ts -201 tests/server/management-provider-atomicity.test.ts -1547 tests/server/management-provider-compat-carry.test.ts +1193 tests/responses/empty-completion-hardening.test.ts +53 tests/responses/eventstream-decoder.test.ts +100 tests/responses/eventstream-fragmentation.test.ts +1386 tests/responses/explicit-empty-tool-catalog-history.test.ts +2173 tests/responses/explicit-empty-tool-catalog.test.ts +196 tests/responses/external-task-input-repair.test.ts +54 tests/responses/fix-eventstream-cancel-wait.test.ts +245 tests/responses/fresh-connection-optout.test.ts +76 tests/responses/graceful-max-output-tokens-exclusions.test.ts +562 tests/responses/graceful-max-output-tokens.test.ts +2159 tests/responses/incomplete-reason-normalization.test.ts +1568 tests/responses/jev-initial-effort-wire.test.ts +61 tests/responses/legacy-shell-compat.test.ts +209 tests/responses/local-checkpoint-routing.test.ts +406 tests/responses/local-upstream-deadlines.test.ts +130 tests/responses/messages-native-bridge-policy.test.ts +195 tests/responses/messages-native-eligibility.test.ts +233 tests/responses/messages-native-oauth-eligibility.test.ts +686 tests/responses/model-custom-tool-capability.test.ts +61 tests/responses/namespace-tool-compat.test.ts +333 tests/responses/native-compaction-gateway-credentials.test.ts +1213 tests/responses/native-compaction-gateway-policy.test.ts +4119 tests/responses/native-compaction-gateway.test.ts +249 tests/responses/native-compaction-oauth.test.ts +1193 tests/responses/native-compaction-provenance.test.ts +145 tests/responses/opaque-blob-wrapped-rejection.test.ts +408 tests/responses/openai-responses-passthrough.test.ts +138 tests/responses/openai-responses-summary-none.test.ts +116 tests/responses/opengateway-completion-receipts.test.ts +49 tests/responses/parser-content-audio.test.ts +393 tests/responses/passthrough-abort.test.ts +4211 tests/responses/passthrough-deferred-tools.test.ts +192 tests/responses/passthrough-grok-upstream-envelope-echo.test.ts +345 tests/responses/passthrough-headers.test.ts +123 tests/responses/passthrough-media-type.test.ts +117 tests/responses/passthrough-override.test.ts +174 tests/responses/plaintext-v2-agent-messages.test.ts +434 tests/responses/pool-retry-client-metadata.test.ts +925 tests/responses/protocol-antigravity-direct-chat.test.ts +139 tests/responses/protocol-antigravity-direct-eligibility.test.ts +573 tests/responses/protocol-antigravity-direct-messages.test.ts +1278 tests/responses/protocol-argon-thought-boundary.test.ts +75 tests/responses/protocol-baseline.test.ts +74 tests/responses/protocol-chat-ir-parity.test.ts +60 tests/responses/protocol-contract.test.ts +149 tests/responses/protocol-direct-encoders-chat.test.ts +90 tests/responses/protocol-direct-encoders-local-upstream.test.ts +170 tests/responses/protocol-direct-encoders-messages.test.ts +68 tests/responses/protocol-direct-encoders-stall-disabled.test.ts +51 tests/responses/protocol-dto.test.ts +72 tests/responses/protocol-envelope.test.ts +60 tests/responses/protocol-features.test.ts +52 tests/responses/protocol-guard.test.ts +227 tests/responses/protocol-ingress-guard.test.ts +138 tests/responses/protocol-messages-ir-parity.test.ts +50 tests/responses/protocol-opaque-state.test.ts +102 tests/responses/protocol-path.test.ts +143 tests/responses/protocol-plan-snapshot.test.ts +49 tests/responses/protocol-plan.test.ts +134 tests/responses/protocol-shadow-plan.test.ts +57 tests/responses/protocol-trace.test.ts +72 tests/responses/provider-egress-fetch.test.ts +470 tests/responses/reasoning-archive-http.test.ts +600 tests/responses/reasoning-archive-ws.test.ts +177 tests/responses/reasoning-effort-summary-default.test.ts +245 tests/responses/reasoning-envelope.test.ts +128 tests/responses/reasoning-retention-quota.test.ts +677 tests/responses/reasoning-retention-routing.test.ts +561 tests/responses/reasoning-retention-v2.test.ts +134 tests/responses/reasoning-retention.test.ts +700 tests/responses/refreshed-upstream-deadlines.test.ts +135 tests/responses/reserve-dispatch-ws.test.ts +115 tests/responses/responses-4546-incident-regression.test.ts +956 tests/responses/responses-account-auto-pause-wire-owner.test.ts +1362 tests/responses/responses-account-auto-pause.test.ts +106 tests/responses/responses-account-change-scrub.test.ts +2936 tests/responses/responses-account-label.test.ts +569 tests/responses/responses-alternate-main-cancellation.test.ts +485 tests/responses/responses-anthropic-billing-send-budget.test.ts +296 tests/responses/responses-anthropic-compaction-prefix.test.ts +570 tests/responses/responses-anthropic-fast-downgrade.test.ts +753 tests/responses/responses-anthropic-image-context-default.test.ts +5300 tests/responses/responses-anthropic-image-context-recovery.test.ts +318 tests/responses/responses-anthropic-image-spend-parity.test.ts +309 tests/responses/responses-anthropic-legal-history.test.ts +232 tests/responses/responses-anthropic-per-message-effort.test.ts +124 tests/responses/responses-anthropic-thinking-recovery.test.ts +1149 tests/responses/responses-anthropic-thinking-signature-recovery.test.ts +356 tests/responses/responses-auto-pause-replay-owner.test.ts +403 tests/responses/responses-azure-opaque-blob-recovery.test.ts +156 tests/responses/responses-bare-echo-helper-fence.test.ts +75 tests/responses/responses-call-id-linkage.test.ts +1280 tests/responses/responses-canonical-nonstream.test.ts +109 tests/responses/responses-canonical-only-top-level-fields.test.ts +465 tests/responses/responses-chat-raw-summary.test.ts +357 tests/responses/responses-chat-tool-call-content.test.ts +103 tests/responses/responses-chatgpt-web-replay-metadata.test.ts +199 tests/responses/responses-claude-preflight-lease.test.ts +50 tests/responses/responses-code-mode-goal-helpers.test.ts +158 tests/responses/responses-code-mode-mcp-direct.test.ts +59 tests/responses/responses-code-mode-patch-compile.test.ts +116 tests/responses/responses-code-mode-shell-compile.test.ts +2642 tests/responses/responses-cold-opaque-recovery.test.ts +177 tests/responses/responses-combo-bridge-usage.test.ts +2018 tests/responses/responses-combo-estimated-usage-spend.test.ts +692 tests/responses/responses-combo-exhausted-error.test.ts +294 tests/responses/responses-combo-fallback-off.test.ts +268 tests/responses/responses-combo-replay-principal.test.ts +570 tests/responses/responses-combo-run-turn-classified-failure.test.ts +360 tests/responses/responses-combo-unavailable-cause.test.ts +6623 tests/responses/responses-compact-handoff-admission.test.ts +2777 tests/responses/responses-compaction-http-isolation.test.ts +912 tests/responses/responses-compaction-override.test.ts +176 tests/responses/responses-compaction-policy-identity.test.ts +55 tests/responses/responses-compaction-recovery-policy.test.ts +7007 tests/responses/responses-compaction-recovery.test.ts +2143 tests/responses/responses-compaction-routing.test.ts +282 tests/responses/responses-compaction.test.ts +6024 tests/responses/responses-console-go-upload-retry.test.ts +3443 tests/responses/responses-context-overflow.test.ts +113 tests/responses/responses-continuation-boundaries.test.ts +117 tests/responses/responses-core-modules.test.ts +63 tests/responses/responses-custom-tool-guidance.test.ts +171 tests/responses/responses-custom-tool-historical-replay.test.ts +319 tests/responses/responses-custom-tool-repair-dispatch.test.ts +64 tests/responses/responses-custom-tool-repair.test.ts +280 tests/responses/responses-custom-tool-stream-consistency.test.ts +61 tests/responses/responses-default-namespace-emit-normalize.test.ts +626 tests/responses/responses-devin-401-replay.test.ts +508 tests/responses/responses-direct-chat-tool-choice.test.ts +58 tests/responses/responses-dispatch-receipt.test.ts +206 tests/responses/responses-effort-history-fixtures.test.ts +130 tests/responses/responses-effort-history-state.test.ts +475 tests/responses/responses-estimated-usage.test.ts +301 tests/responses/responses-fetch-helpers-boundary.test.ts +100 tests/responses/responses-field-backfill.test.ts +9624 tests/responses/responses-first-send-reservation.test.ts +841 tests/responses/responses-first-send-spend-policy.test.ts +710 tests/responses/responses-forward-client-headers-live.test.ts +113 tests/responses/responses-forward-client-headers.test.ts +121 tests/responses/responses-forward-dangling-call.test.ts +280 tests/responses/responses-forward-incomplete-quota.test.ts +159 tests/responses/responses-forward-output-cap.test.ts +116 tests/responses/responses-forward-posit-continuation.test.ts +101 tests/responses/responses-forward-prompt-envelope.test.ts +58 tests/responses/responses-forward-transport-baseurl.test.ts +276 tests/responses/responses-freeform-wrapper-keys.test.ts +233 tests/responses/responses-function-tool-repair.test.ts +4774 tests/responses/responses-grok-devin-preflight.test.ts +226 tests/responses/responses-hide-raw-reasoning.test.ts +320 tests/responses/responses-hosted-image-delivery.test.ts +77 tests/responses/responses-hosted-image-display.test.ts +233 tests/responses/responses-hosted-image-limits.test.ts +516 tests/responses/responses-hosted-send-hop.test.ts +441 tests/responses/responses-hosted-send-producer.test.ts +553 tests/responses/responses-hosted-send-reservation.test.ts +331 tests/responses/responses-hosted-send-round-parity.test.ts +408 tests/responses/responses-hosted-send-unsent-hop.test.ts +265 tests/responses/responses-hosted-send-ws.test.ts +120 tests/responses/responses-hosted-tool-conditional.test.ts +114 tests/responses/responses-hosted-tool-declaration.test.ts +116 tests/responses/responses-hosted-tool-min-spread.test.ts +215 tests/responses/responses-image-gen-repair.test.ts +235 tests/responses/responses-inbound-store-default.test.ts +79 tests/responses/responses-item-id-repair.test.ts +56 tests/responses/responses-json-events.test.ts +61 tests/responses/responses-legacy-dotted-tool-name-repair.test.ts +646 tests/responses/responses-main-quota-observation.test.ts +336 tests/responses/responses-memory-models.test.ts +71 tests/responses/responses-mimo-envelope.test.ts +234 tests/responses/responses-muse-tool-choice.test.ts +271 tests/responses/responses-muse-tool-name-alias.test.ts +187 tests/responses/responses-native-compact-ocx-envelope.test.ts +201 tests/responses/responses-native-compact-search-history.test.ts +187 tests/responses/responses-native-item-extensions-compact.test.ts +133 tests/responses/responses-native-item-extensions.test.ts +637 tests/responses/responses-native-key-cooldown.test.ts +802 tests/responses/responses-native-main-refresh.test.ts +53 tests/responses/responses-native-output-identity.test.ts +2227 tests/responses/responses-native-sse-stall.test.ts +571 tests/responses/responses-native-ultra-effort-wire.test.ts +1431 tests/responses/responses-oauth-refresh-capacity.test.ts +1381 tests/responses/responses-offline-resend.test.ts +52 tests/responses/responses-ollama-codec.test.ts +5133 tests/responses/responses-opaque-blob-recovery.test.ts +68 tests/responses/responses-parser-agent-message.test.ts +105 tests/responses/responses-parser-malformed-content.test.ts +199 tests/responses/responses-parser.test.ts +2982 tests/responses/responses-passive-key-limits.test.ts +134 tests/responses/responses-passthrough-transient-policy.test.ts +59 tests/responses/responses-phase-inference.test.ts +4778 tests/responses/responses-pool-401-refresh.test.ts +13625 tests/responses/responses-pool-overload-failover.test.ts +151 tests/responses/responses-pool-refresh-attribution.test.ts +537 tests/responses/responses-preview-main-read-fence.test.ts +1021 tests/responses/responses-reasoning-effort-diagnostics.test.ts +1383 tests/responses/responses-reasoning-effort-downgrade.test.ts +328 tests/responses/responses-reasoning-summary-passthrough.test.ts +212 tests/responses/responses-repeated-tool-outputs.test.ts +285 tests/responses/responses-replay-metadata-principal.test.ts +134 tests/responses/responses-replay-owner-storage.test.ts +140 tests/responses/responses-request-compression.test.ts +391 tests/responses/responses-required-chat-tool.test.ts +356 tests/responses/responses-reset-replay-chained.test.ts +117 tests/responses/responses-reset-replay.test.ts +1117 tests/responses/responses-reset-selection-http.test.ts +387 tests/responses/responses-retained-reasoning-stream-recovery.test.ts +191 tests/responses/responses-routed-web-search-fields.test.ts +263 tests/responses/responses-run-turn-key-pacing.test.ts +273 tests/responses/responses-run-turn-key-readmission.test.ts +676 tests/responses/responses-run-turn-web-search.test.ts +248 tests/responses/responses-self-named-namespace-scrub.test.ts +6546 tests/responses/responses-send-budget-counts.test.ts +470 tests/responses/responses-send-budget-errors.test.ts +527 tests/responses/responses-shadow-intercept.test.ts +327 tests/responses/responses-show-thinking-summary.test.ts +1104 tests/responses/responses-sidecar-context-overflow.test.ts +371 tests/responses/responses-sidecar-usage.test.ts +325 tests/responses/responses-skills-snapshot.test.ts +850 tests/responses/responses-snapshot-repair-server.test.ts +173 tests/responses/responses-snapshot-repair.test.ts +388 tests/responses/responses-snapshot-scaling.test.ts +120 tests/responses/responses-sparse-terminal-tool-scope.test.ts +1845 tests/responses/responses-spend-anchor.test.ts +106 tests/responses/responses-spend-capacity-guard.test.ts +854 tests/responses/responses-spend-contract-c.test.ts +261 tests/responses/responses-spend-ledger-wiring.test.ts +99 tests/responses/responses-spill-acl-recovery.test.ts +252 tests/responses/responses-spill-admission-headroom.test.ts +93 tests/responses/responses-spill-inspection.test.ts +76 tests/responses/responses-spill-orphan-sweep.test.ts +312 tests/responses/responses-spill-shutdown-clock.test.ts +67 tests/responses/responses-state-flush-race.test.ts +53 tests/responses/responses-state-snapshot-select.test.ts +79 tests/responses/responses-state-snapshot-stubs.test.ts +283 tests/responses/responses-state-store-false.test.ts +219 tests/responses/responses-state-write-amplification.test.ts +7324 tests/responses/responses-state.test.ts +789 tests/responses/responses-stateless-dangling-call-repair.test.ts +59 tests/responses/responses-stream-tool-events.test.ts +125 tests/responses/responses-terminal-repair.test.ts +148 tests/responses/responses-tool-conformance.test.ts +54 tests/responses/responses-tool-groups.test.ts +231 tests/responses/responses-tool-search-repair.test.ts +524 tests/responses/responses-translated-replay-principal.test.ts +18050 tests/responses/responses-translated-reset.test.ts +387 tests/responses/responses-undeclared-tool-guard-inbound.test.ts +885 tests/responses/responses-undeclared-tool-guard.test.ts +111 tests/responses/responses-url-citation-title-repair.test.ts +200 tests/responses/responses-usage-passthrough.test.ts +1191 tests/responses/responses-web-search-thinking-signature-recovery.test.ts +1563 tests/responses/responses-websocket-workflow-ceiling.test.ts +1001 tests/responses/responses-workflow-send-ceiling.test.ts +130 tests/responses/responses-xai-request-compat.test.ts +429 tests/responses/search-empty-completion.test.ts +441 tests/responses/shadow-intercept-target-lifecycle.test.ts +71 tests/responses/sse-carriage-return.test.ts +242 tests/responses/sse-client-frame-bounds.test.ts +387 tests/responses/sse-decoder.test.ts +645 tests/responses/sse-failed-tail.test.ts +458 tests/responses/sse-inspector-bounds.test.ts +97 tests/responses/sse-null-data-frame.test.ts +401 tests/responses/sse-payload-rewrite-continuation.test.ts +116 tests/responses/sse-payload-rewrite.test.ts +139 tests/responses/sse-rewrite-line-endings.test.ts +71 tests/responses/sse-unspaced-data-fields.test.ts +2938 tests/responses/sse-untyped-credential-mask.test.ts +5628 tests/responses/stalled-reader-memory.test.ts +65 tests/responses/thought-signature-credential-scope.test.ts +370 tests/responses/turn-membership-ingress.test.ts +90 tests/responses/turn-membership.test.ts +94 tests/responses/visualization-directives.test.ts +564 tests/responses/ws-ambiguous-resend.test.ts +4785 tests/responses/ws-capacity-reclamation.test.ts +395 tests/responses/ws-capacity-tool-ownership.test.ts +63 tests/responses/ws-committed-liveness.test.ts +150 tests/responses/ws-endpoint.test.ts +110 tests/responses/ws-failure-stage.test.ts +454 tests/responses/ws-native-continuation-send-budget.test.ts +500 tests/responses/ws-native-injection.test.ts +362 tests/responses/ws-native-result-continuations.test.ts +1675 tests/responses/ws-native-steering.test.ts +174 tests/responses/ws-pre-output-refusal.test.ts +255 tests/responses/ws-replay-refusal-attribution.test.ts +374 tests/responses/ws-steering-completion.test.ts +159 tests/responses/ws-steering-smoke.test.ts +231 tests/responses/ws-steering-stability.test.ts +148 tests/responses/ws-upstream-reuse.test.ts +111 tests/responses/ws-upstream-socks5.test.ts +653 tests/responses/ws-upstream.test.ts +399 tests/routing/agy-acp-routing-policy.test.ts +320 tests/routing/always-on-429-failover.test.ts +131 tests/routing/anthropic-quorum-cache.test.ts +61 tests/routing/cl01-claude-outbound-review-regressions.test.ts +55 tests/routing/cl01-openai-chat-review-regressions.test.ts +173 tests/routing/cl01-review-regressions.test.ts +144 tests/routing/codex-agent-role-models.test.ts +59 tests/routing/codex-role-auto-assign.test.ts +60 tests/routing/codex-role-capability-consent.test.ts +86 tests/routing/codex-role-capability-pages.test.ts +57 tests/routing/codex-role-capability-redirects.test.ts +93 tests/routing/codex-role-measured-ties.test.ts +87 tests/routing/codex-role-sizing.test.ts +165 tests/routing/combo-child-headers.test.ts +1604 tests/routing/combo-cooldown-persistence.test.ts +171 tests/routing/combo-description.test.ts +242 tests/routing/combo-failure-transport-parity.test.ts +835 tests/routing/combo-management-api.test.ts +299 tests/routing/combo-required-tool-stream-preflight.test.ts +71 tests/routing/combo-selection-keepalive.test.ts +332 tests/routing/combo-stream-preflight.test.ts +128 tests/routing/combo-terminal-refusal.test.ts +181 tests/routing/combo-unoffered-tool-refusal.test.ts +396 tests/routing/combo-vision-enrollment.test.ts +130 tests/routing/compatibility-provider-equivalence.test.ts +62 tests/routing/destination-policy-resolved.test.ts +164 tests/routing/fallback-policy.test.ts +108 tests/routing/fastwire-characterization-routing.test.ts +461 tests/routing/fastwire-characterization-wire.test.ts +260 tests/routing/fastwire-observability.test.ts +311 tests/routing/fastwire-policy.test.ts +320 tests/routing/fastwire-response-authority.test.ts +64 tests/routing/jev-decision-destination.test.ts +377 tests/routing/jev-decision-model-config.test.ts +262 tests/routing/jev-decision-provider-combo.test.ts +132 tests/routing/jev-decision.test.ts +1075 tests/routing/jev-model-backend.test.ts +354 tests/routing/jev-quota-activation.test.ts +246 tests/routing/jev-quota-anthropic2.test.ts +242 tests/routing/jev-quota-antigravity.test.ts +205 tests/routing/jev-quota-codex-reset.test.ts +270 tests/routing/jev-quota-config.test.ts +648 tests/routing/jev-quota-core-boundary.test.ts +180 tests/routing/jev-quota-publication.test.ts +272 tests/routing/jev-quota-signals.test.ts +146 tests/routing/jev-service-exchange.test.ts +57 tests/routing/jev-session-pin.test.ts +57 tests/routing/jev-typesafe-golden.test.ts +125 tests/routing/policy-execution.test.ts +257 tests/routing/probe-lease-dispatch-wiring.test.ts +174 tests/routing/probe-lease.test.ts +129 tests/routing/resolved-model-policy-consumers.test.ts +5248 tests/routing/route-to-child-defaults.test.ts +4776 tests/routing/route-to-home-decisions.test.ts +7996 tests/routing/route-to-home-live-flags.test.ts +4258 tests/routing/route-to-home-native-truth.test.ts +182 tests/routing/route-to-home-off-review.test.ts +5047 tests/routing/route-to-home-sync-review.test.ts +146 tests/routing/route-to-sync-child.test.ts +55 tests/routing/router-anthropic-billing-failover.test.ts +160 tests/routing/router-blocked-cross-provider.test.ts +191 tests/routing/router-combo-failover-classification.test.ts +127 tests/routing/router-discarded-baseurl-warning.test.ts +101 tests/routing/router-template-baseurl.test.ts +122 tests/routing/router.test.ts +451 tests/routing/routing-analytics.test.ts +94 tests/routing/routing-capability-catalog.test.ts +289 tests/routing/routing-capability-model-matching.test.ts +53 tests/routing/routing-compatibility-auth-identity.test.ts +319 tests/routing/routing-compatibility-boundaries.test.ts +55 tests/routing/routing-compatibility-model-matching.test.ts +171 tests/routing/routing-compatibility.test.ts +70 tests/routing/routing-identity-domains.test.ts +285 tests/routing/routing-policy-dispatch-scope.test.ts +206 tests/routing/routing-policy-fallback-off.test.ts +446 tests/routing/routing-policy-fallback.test.ts +88 tests/routing/routing-policy-pool-quota.test.ts +316 tests/routing/routing-policy-surface-parity.test.ts +369 tests/routing/routing-profile-management-editor.test.ts +301 tests/routing/routing-profile.test.ts +115 tests/routing/subagent-context-staleness.test.ts +76 tests/routing/subagent-defaults.test.ts +2310 tests/routing/subagent-fallback-handle-responses.test.ts +92 tests/routing/subagent-fallback-preview-sites.test.ts +215 tests/routing/subagent-model-fallback-api.test.ts +288 tests/routing/subagent-model-fallback-off.test.ts +490 tests/routing/subagent-model-fallback.test.ts +136 tests/routing/subagent-roster-migration.test.ts +442 tests/routing/subagent-roster-retention.test.ts +123 tests/server/account-import-project-fallback.test.ts +141 tests/server/account-import.test.ts +4043 tests/server/account-pool-management-api.test.ts +218 tests/server/adapter-resolve.test.ts +111 tests/server/admitted-http-turn.test.ts +60 tests/server/advisor-routes.test.ts +110 tests/server/agent-assertion-auth.test.ts +344 tests/server/agent-task-recovery-cache.test.ts +475 tests/server/agent-task-recovery-combo.test.ts +244 tests/server/agent-task-recovery-fallback.test.ts +324 tests/server/agent-task-recovery-security.test.ts +11977 tests/server/agent-task-recovery.test.ts +128 tests/server/alias-management-api.test.ts +236 tests/server/anthropic2-management.test.ts +101 tests/server/api-access-endpoints.test.ts +1052 tests/server/api-catalog-route.test.ts +325 tests/server/api-codex-log-guard-compact.test.ts +236 tests/server/api-codex-log-guard-protection.test.ts +167 tests/server/api-codex-log-guard.test.ts +1163 tests/server/api-debug.test.ts +3644 tests/server/api-key-attribution.test.ts +154 tests/server/api-key-model-scope.test.ts +254 tests/server/api-key-scope-alpha-search.test.ts +235 tests/server/api-key-scope-audio.test.ts +236 tests/server/api-key-scope-images.test.ts +181 tests/server/api-key-scope-live.test.ts +3213 tests/server/api-keys-routes.test.ts +3683 tests/server/api-usage.test.ts +584 tests/server/aside-profiles-routes.test.ts +119 tests/server/audio-client.test.ts +1271 tests/server/audio-dictation.test.ts +1420 tests/server/audio-transcriptions.test.ts +591 tests/server/bounded-body.test.ts +135 tests/server/bridge-live-delivery.test.ts +6852 tests/server/cache-affinity-e2e.test.ts +250 tests/server/caller-session-identity.test.ts +615 tests/server/caller-session-ingress.test.ts +2624 tests/server/cancel-body-on-abort.test.ts +1064 tests/server/claude-intercept-integration.test.ts +280 tests/server/client-retry-after-sites.test.ts +406 tests/server/codex-agent-role-routes.test.ts +148 tests/server/codex-model-list-plaintext.test.ts +265 tests/server/codex-role-auto-assign-routes.test.ts +214 tests/server/codex-role-configured-credentials.test.ts +278 tests/server/codex-role-history-recovery.test.ts +666 tests/server/combo-loopback-metered-consent.test.ts +377 tests/server/combo-metered-consent.test.ts +99 tests/server/combo-requested-effort.test.ts +676 tests/server/combo-suggestion-routes.test.ts +203 tests/server/companion-settings.test.ts +493 tests/server/config.test.ts +219 tests/server/consume-for-inspection-cancel.test.ts +567 tests/server/context-history-ownership.test.ts +206 tests/server/context-history.test.ts +380 tests/server/data-plane-admission-identity.test.ts +52 tests/server/debug-settings.test.ts +94 tests/server/decision-discovery.test.ts +503 tests/server/decision-routes.test.ts +591 tests/server/developer-role-rejection-boundary.test.ts +441 tests/server/distributed-key-401.test.ts +256 tests/server/error-fidelity.test.ts +155 tests/server/errors-adapter-failure.test.ts +241 tests/server/fallback-routes.test.ts +538 tests/server/fetch-header-timeout.test.ts +324 tests/server/health-scoring.test.ts +1976 tests/server/hub-usage-windows.test.ts +759 tests/server/hub-usage.test.ts +925 tests/server/inbound-body-admission.test.ts +128 tests/server/inbound-body-budget.test.ts +132 tests/server/inbound-encoded-body-budget.test.ts +99 tests/server/inference-attempt.test.ts +208 tests/server/inference-client-encoder-delivery.test.ts +89 tests/server/inference-client-wire.test.ts +100 tests/server/inference-final-log.test.ts +1552 tests/server/inference-send-budget.test.ts +138 tests/server/input-admission.test.ts +171 tests/server/jev-decision-scope.test.ts +245 tests/server/link-activity-holds-routes.test.ts +269 tests/server/link-child-ops-routes.test.ts +168 tests/server/link-child-parity.test.ts +195 tests/server/link-child-policy-routes.test.ts +156 tests/server/link-confirm-pin.test.ts +187 tests/server/link-diagnostics-route.test.ts +240 tests/server/link-enrollment-ephemeral-child.test.ts +285 tests/server/link-enrollment-explicit-route.test.ts +578 tests/server/link-enrollment-operation.test.ts +295 tests/server/link-enrollment.test.ts +2548 tests/server/link-join-route.test.ts +820 tests/server/link-listener-admission.test.ts +333 tests/server/link-listener-lifecycle.test.ts +115 tests/server/link-listener-mutation.test.ts +6498 tests/server/link-management-relay.test.ts +802 tests/server/link-management-routes.test.ts +170 tests/server/link-operations-routes.test.ts +951 tests/server/link-recover.test.ts +868 tests/server/link-request-log-fields.test.ts +828 tests/server/link-revoke-operation.test.ts +172 tests/server/link-route-edit-exclusive.test.ts +145 tests/server/link-route-edit-retirement.test.ts +196 tests/server/link-route-edit.test.ts +224 tests/server/link-route-intent.test.ts +366 tests/server/link-route-proof-admission.test.ts +174 tests/server/link-traffic-status.test.ts +112 tests/server/link-websocket-drain.test.ts +551 tests/server/link-websocket-fingerprints.test.ts +240 tests/server/link-websocket-gate.test.ts +232 tests/server/link-websocket-holds.test.ts +595 tests/server/link-websocket-pump.test.ts +132 tests/server/link-websocket-traffic.test.ts +509 tests/server/link-websocket-transport-status.test.ts +1825 tests/server/link-websocket-upgrade.test.ts +93 tests/server/live-call-bindings.test.ts +75 tests/server/live-native-calls.test.ts +232 tests/server/local-account-switch-capability.test.ts +375 tests/server/local-account-switch-ingress.test.ts +621 tests/server/local-aside-sync-capability.test.ts +2217 tests/server/local-control-socket.test.ts +62 tests/server/local-management-attestation.test.ts +92 tests/server/local-management-capability.test.ts +569 tests/server/local-management-direct-transport.test.ts +65 tests/server/local-provider-reload-client.test.ts +430 tests/server/local-read-response-proof.test.ts +631 tests/server/login-shell-path.test.ts +170 tests/server/logs-timezone.test.ts +208 tests/server/loopback-companion-client-targets.test.ts +126 tests/server/loopback-listener-admission.test.ts +3062 tests/server/loopback-listener-integration.test.ts +266 tests/server/management-account-auto-pause.test.ts +171 tests/server/management-anthropic-reset-grants.test.ts +252 tests/server/management-api-logs-metrics.test.ts +213 tests/server/management-api-logs-timing-basis.test.ts +412 tests/server/management-auto-review-auth.test.ts +222 tests/server/management-auto-review-settings.test.ts +583 tests/server/management-client-config-route.test.ts +257 tests/server/management-desktop-compatibility-routes.test.ts +160 tests/server/management-desktop-compatibility-runtime-routes.test.ts +278 tests/server/management-desktop-compatibility-settings.test.ts +292 tests/server/management-droid-reasoning-defaults.test.ts +622 tests/server/management-export-model-names.test.ts +677 tests/server/management-gcp-credential-input.test.ts +253 tests/server/management-google-tool-schema-policy.test.ts +230 tests/server/management-inference-port.test.ts +385 tests/server/management-integration-journal-delete.test.ts +1375 tests/server/management-integration-routes.test.ts +2009 tests/server/management-metrics-export.test.ts +169 tests/server/management-model-roster-gather-race.test.ts +166 tests/server/management-model-roster.test.ts +56 tests/server/management-origin-tls.test.ts +232 tests/server/management-provider-atomicity.test.ts +2775 tests/server/management-provider-compat-carry.test.ts 167 tests/server/management-provider-context-inference.test.ts -452 tests/server/management-provider-hide-raw-reasoning.test.ts -305 tests/server/management-provider-pinsless-validation.test.ts -260 tests/server/management-provider-proto-override.test.ts -605 tests/server/management-provider-reasoning-lists.test.ts -142 tests/server/management-provider-request-pacing.test.ts -42 tests/server/management-provider-reset-replay.test.ts -585 tests/server/management-provider-responses-reasoning.test.ts -144 tests/server/management-provider-synthetic-max.test.ts -281 tests/server/management-provider-thinking-display.test.ts -217 tests/server/management-provider-upstream-websocket.test.ts -8267 tests/server/management-provider-validation.test.ts -318 tests/server/management-provider-verbosity.test.ts -390 tests/server/management-qoder-selector-state.test.ts -857 tests/server/management-route-registry.test.ts -603 tests/server/management-sidecar-anthropic-instance.test.ts -100 tests/server/management-workflow-budget-routes.test.ts -395 tests/server/memory-watchdog.test.ts -252 tests/server/messages-sse-error-filter.test.ts -374 tests/server/messages-sse-error-lifecycle.test.ts -285 tests/server/model-costs-management-api.test.ts -336 tests/server/model-costs-pricing-cache.test.ts -362 tests/server/model-costs-prompt-length-pricing.test.ts -142 tests/server/model-discovery-management-api.test.ts -260 tests/server/model-export-new-model-policy.test.ts -265 tests/server/model-settings-management-api.test.ts -45 tests/server/outbound-body-guard.test.ts -50 tests/server/owned-service-home.test.ts -70 tests/server/passive-route-linker.test.ts -275 tests/server/persistent-dashboard-admission.test.ts -419 tests/server/persistent-dashboard-consent.test.ts -260 tests/server/persistent-dashboard-session.test.ts -2100 tests/server/plaintext-v2-agent-messages-server.test.ts -975 tests/server/port-reclaim.test.ts -359 tests/server/ports.test.ts -905 tests/server/prefer-model-alias-ids.test.ts -838 tests/server/probe-timeout-env.test.ts -98 tests/server/protocol-provider-summary.test.ts -110 tests/server/protocol-routes.test.ts -98 tests/server/protocol-settings-route.test.ts -183 tests/server/protocol-trace-suppression.test.ts -347 tests/server/provider-account-quota-routes.test.ts -50 tests/server/provider-egress-management-validation.test.ts -223 tests/server/provider-send-path-import.test.ts -88 tests/server/proxy-env-macos.test.ts -52 tests/server/proxy-env.test.ts -203 tests/server/proxy-liveness-bind-scope.test.ts -57 tests/server/proxy-liveness-nonloopback-bind-proof.test.ts -82 tests/server/proxy-liveness-owner-evidence.test.ts -48 tests/server/proxy-liveness-package-tree-fence.test.ts -59 tests/server/proxy-liveness-recovery.test.ts -68 tests/server/proxy-liveness.test.ts -4805 tests/server/quota-pool-relay.test.ts -451 tests/server/readyz-features.test.ts -616 tests/server/relay-eager.test.ts -1405 tests/server/replay-refusal-parity.test.ts -306 tests/server/reserve-claude-policy.test.ts -1621 tests/server/reserve-ingress.test.ts -434 tests/server/response-log-inspection.test.ts -1683 tests/server/response-model-identity.test.ts -1253 tests/server/restart-replacement-not-ready.test.ts -84 tests/server/restart-replacement.test.ts -120 tests/server/retry-after-429.test.ts -39 tests/server/retry-delay-hardening.test.ts -141 tests/server/route-decision-trace.test.ts -143 tests/server/safe-response-headers.test.ts -2467 tests/server/served-by-header.test.ts -629 tests/server/server-403-permission-e2e.test.ts -315 tests/server/server-agent-task-recovery-replay.test.ts -394 tests/server/server-anthropic-billing-boundaries.test.ts -2233 tests/server/server-anthropic-billing.test.ts -2088 tests/server/server-antigravity-model-denial-recovery.test.ts -438 tests/server/server-antigravity-model-roster-routing.test.ts -155 tests/server/server-antigravity-verify-replay-scope.test.ts -492 tests/server/server-antigravity-web-search-validation.test.ts -212 tests/server/server-auth-localhost-bind.test.ts -1946 tests/server/server-auth-scoped-quota.test.ts -18989 tests/server/server-auth.test.ts -1018 tests/server/server-background-lifecycle.test.ts -358 tests/server/server-chat-error-body-evidence.test.ts -539 tests/server/server-chat-native-key-selection.test.ts -317 tests/server/server-cli-key-probe-admission.test.ts +755 tests/server/management-provider-forward-advisor-tool.test.ts +1146 tests/server/management-provider-hide-raw-reasoning.test.ts +689 tests/server/management-provider-model-discovery.test.ts +414 tests/server/management-provider-pinsless-validation.test.ts +383 tests/server/management-provider-proto-override.test.ts +756 tests/server/management-provider-reasoning-lists.test.ts +235 tests/server/management-provider-request-pacing.test.ts +56 tests/server/management-provider-reset-replay.test.ts +797 tests/server/management-provider-responses-reasoning.test.ts +311 tests/server/management-provider-synthetic-max.test.ts +524 tests/server/management-provider-thinking-display.test.ts +192 tests/server/management-provider-upstream-websocket.test.ts +6828 tests/server/management-provider-validation.test.ts +508 tests/server/management-provider-verbosity.test.ts +404 tests/server/management-qoder-selector-state.test.ts +552 tests/server/management-route-intent-native-errors.test.ts +480 tests/server/management-route-intent-native-review.test.ts +823 tests/server/management-route-registry.test.ts +620 tests/server/management-sidecar-anthropic-instance.test.ts +178 tests/server/management-workflow-budget-routes.test.ts +507 tests/server/memory-watchdog.test.ts +275 tests/server/messages-sse-error-filter.test.ts +407 tests/server/messages-sse-error-lifecycle.test.ts +323 tests/server/model-costs-management-api.test.ts +634 tests/server/model-costs-pricing-cache.test.ts +337 tests/server/model-costs-prompt-length-pricing.test.ts +177 tests/server/model-discovery-management-api.test.ts +346 tests/server/model-export-new-model-policy.test.ts +516 tests/server/model-settings-management-api.test.ts +105 tests/server/outbound-body-guard.test.ts +62 tests/server/owned-service-home.test.ts +61 tests/server/passive-route-linker.test.ts +466 tests/server/persistent-dashboard-admission.test.ts +599 tests/server/persistent-dashboard-consent.test.ts +291 tests/server/persistent-dashboard-session.test.ts +2422 tests/server/plaintext-v2-agent-messages-server.test.ts +978 tests/server/port-reclaim.test.ts +398 tests/server/ports.test.ts +1314 tests/server/prefer-model-alias-ids.test.ts +1182 tests/server/probe-timeout-env.test.ts +211 tests/server/protocol-provider-summary.test.ts +151 tests/server/protocol-routes.test.ts +174 tests/server/protocol-settings-route.test.ts +282 tests/server/protocol-trace-suppression.test.ts +209 tests/server/provider-account-quota-routes.test.ts +72 tests/server/provider-egress-management-validation.test.ts +178 tests/server/provider-send-path-import.test.ts +63 tests/server/proxy-env-macos.test.ts +97 tests/server/proxy-env.test.ts +395 tests/server/proxy-liveness-bind-scope.test.ts +318 tests/server/proxy-liveness-nonloopback-bind-proof.test.ts +124 tests/server/proxy-liveness-owner-evidence.test.ts +71 tests/server/proxy-liveness-package-tree-fence.test.ts +114 tests/server/proxy-liveness-recovery.test.ts +3847 tests/server/proxy-liveness-self-pid-record.test.ts +70 tests/server/proxy-liveness.test.ts +4973 tests/server/quota-pool-relay.test.ts +535 tests/server/readyz-features.test.ts +753 tests/server/relay-eager.test.ts +1970 tests/server/replay-refusal-parity.test.ts +538 tests/server/reserve-claude-policy.test.ts +731 tests/server/reserve-ingress-fixture-port-race.test.ts +2843 tests/server/reserve-ingress.test.ts +608 tests/server/response-log-inspection.test.ts +1701 tests/server/response-model-identity.test.ts +239 tests/server/response-replay-combo-identity.test.ts +619 tests/server/response-replay-ownership.test.ts +1297 tests/server/restart-replacement-not-ready.test.ts +110 tests/server/restart-replacement.test.ts +176 tests/server/retry-after-429.test.ts +63 tests/server/retry-delay-hardening.test.ts +257 tests/server/route-decision-trace.test.ts +201 tests/server/route-intent-watch-boundary.test.ts +97 tests/server/route-intent-watch-waiters.test.ts +211 tests/server/route-to-ephemeral.test.ts +162 tests/server/route-to-live-settings.test.ts +198 tests/server/route-to-policy-review.test.ts +253 tests/server/route-to-retirement-review.test.ts +238 tests/server/route-to-routes.test.ts +125 tests/server/safe-response-headers.test.ts +2080 tests/server/served-by-header.test.ts +702 tests/server/server-403-permission-e2e.test.ts +353 tests/server/server-agent-task-recovery-replay.test.ts +4329 tests/server/server-agy-acp.test.ts +582 tests/server/server-anthropic-billing-boundaries.test.ts +2271 tests/server/server-anthropic-billing.test.ts +2119 tests/server/server-antigravity-model-denial-recovery.test.ts +704 tests/server/server-antigravity-model-roster-routing.test.ts +167 tests/server/server-antigravity-verify-replay-scope.test.ts +942 tests/server/server-antigravity-web-search-validation.test.ts +403 tests/server/server-auth-localhost-bind.test.ts +1937 tests/server/server-auth-scoped-quota.test.ts +19085 tests/server/server-auth.test.ts +1514 tests/server/server-background-lifecycle.test.ts +560 tests/server/server-chat-error-body-evidence.test.ts +629 tests/server/server-chat-native-key-selection.test.ts +383 tests/server/server-cli-key-probe-admission.test.ts 60 tests/server/server-clickjacking-headers.test.ts -325 tests/server/server-combo-cooldown-fallback.test.ts -752 tests/server/server-combo-cooldown-recording.test.ts -9703 tests/server/server-combo-failover-e2e.test.ts -39 tests/server/server-combo-held-response.test.ts -676 tests/server/server-combo-plan-model-refusal.test.ts -124 tests/server/server-combo-quota-code-provenance.test.ts -3976 tests/server/server-combo-reasoning-replay-eligibility.test.ts -1266 tests/server/server-combo-required-tool-contract.test.ts -439 tests/server/server-combo-stream-hosted-tool-contract.test.ts -647 tests/server/server-combo-stream-required-tool.test.ts -345 tests/server/server-combo-stream-send-contract.test.ts -5361 tests/server/server-combo-tool-loop-continuation.test.ts -379 tests/server/server-combo-zero-output-failover.test.ts -719 tests/server/server-desktop-compatibility-startup.test.ts -647 tests/server/server-generic-oauth-affinity.test.ts -2887 tests/server/server-google-antigravity-oauth-401-replay.test.ts -434 tests/server/server-google-antigravity-oauth-429-budget.test.ts -67 tests/server/server-gui-bundle-freshness.test.ts -133 tests/server/server-images-bodyless-content-length.test.ts -203 tests/server/server-images-pool-admission.test.ts -6037 tests/server/server-images.test.ts -360 tests/server/server-jev-combo-e2e.test.ts -331 tests/server/server-jev-model-decision-e2e.test.ts -275 tests/server/server-jev-model-quota-budget.test.ts -178 tests/server/server-jev-session-pin.test.ts -5479 tests/server/server-key-failover-e2e.test.ts -1542 tests/server/server-kiro-completion-e2e.test.ts -191 tests/server/server-kiro-device-login.test.ts -543 tests/server/server-kiro-oauth-401-replay.test.ts -3361 tests/server/server-kiro-refusal-e2e.test.ts -754 tests/server/server-kiro-structured-output-e2e.test.ts -1726 tests/server/server-kiro-usage-log-e2e.test.ts -568 tests/server/server-live-cancel.test.ts -8818 tests/server/server-live-close.test.ts -675 tests/server/server-live-existing-call.test.ts -231 tests/server/server-live-frame-log.test.ts -1077 tests/server/server-live-realtime-fixtures.test.ts -6048 tests/server/server-live.test.ts -41 tests/server/server-loopback-host-gate.test.ts -1802 tests/server/server-management-auth.test.ts -263 tests/server/server-management-log-admission.test.ts -1157 tests/server/server-native-catalog-priority.test.ts -124 tests/server/server-native-final-log.test.ts -64 tests/server/server-native-reasoning-retention-merge.test.ts -296 tests/server/server-native-reasoning-retention.test.ts -670 tests/server/server-new-model-policy-arrival.test.ts -4743 tests/server/server-ollama-inbound-errors.test.ts -781 tests/server/server-ollama-inbound-lifecycle.test.ts -1395 tests/server/server-ollama-inbound.test.ts -113 tests/server/server-ollama-route-policy.test.ts -420 tests/server/server-opencode-go-goal-streaming.test.ts -1499 tests/server/server-rate-limit-retry-e2e.test.ts -893 tests/server/server-request-body-size.test.ts -1799 tests/server/server-search.test.ts -367 tests/server/server-startup-codex-off.test.ts -582 tests/server/server-startup-reconcile-resilience.test.ts -442 tests/server/server-stop-config-hardening.test.ts -153 tests/server/server-telemetry-profile-routes.test.ts -162 tests/server/server-telemetry-routes.test.ts -329 tests/server/server-terminal-refusal-wiring.test.ts -373 tests/server/server-workflow-budget-settings.test.ts -470 tests/server/server-xai-chat-reasoning-streaming.test.ts -369 tests/server/server-xai-header-parity.test.ts -720 tests/server/server-xai-oauth-401-replay.test.ts -564 tests/server/server-xai-responses-streaming.test.ts +492 tests/server/server-combo-cooldown-fallback.test.ts +929 tests/server/server-combo-cooldown-recording.test.ts +12315 tests/server/server-combo-failover-e2e.test.ts +56 tests/server/server-combo-held-response.test.ts +431 tests/server/server-combo-opaque-error-failover.test.ts +1157 tests/server/server-combo-plan-model-refusal.test.ts +174 tests/server/server-combo-quota-code-provenance.test.ts +4070 tests/server/server-combo-reasoning-replay-eligibility.test.ts +2227 tests/server/server-combo-required-tool-contract.test.ts +448 tests/server/server-combo-selection-keepalive.test.ts +595 tests/server/server-combo-stream-hosted-tool-contract.test.ts +936 tests/server/server-combo-stream-required-tool.test.ts +489 tests/server/server-combo-stream-send-contract.test.ts +5391 tests/server/server-combo-tool-loop-continuation.test.ts +1002 tests/server/server-combo-zero-output-failover.test.ts +521 tests/server/server-dashboard-trusted-proxy.test.ts +755 tests/server/server-desktop-compatibility-startup.test.ts +932 tests/server/server-generic-oauth-affinity.test.ts +13527 tests/server/server-google-antigravity-oauth-401-replay.test.ts +521 tests/server/server-google-antigravity-oauth-429-budget.test.ts +119 tests/server/server-gui-bundle-freshness.test.ts +212 tests/server/server-images-bodyless-content-length.test.ts +314 tests/server/server-images-pool-admission.test.ts +6222 tests/server/server-images.test.ts +431 tests/server/server-jev-combo-e2e.test.ts +315 tests/server/server-jev-model-decision-e2e.test.ts +513 tests/server/server-jev-model-quota-budget.test.ts +329 tests/server/server-jev-session-pin.test.ts +7145 tests/server/server-key-failover-e2e.test.ts +1525 tests/server/server-kiro-completion-e2e.test.ts +283 tests/server/server-kiro-device-login.test.ts +910 tests/server/server-kiro-oauth-401-replay.test.ts +4764 tests/server/server-kiro-refusal-e2e.test.ts +1093 tests/server/server-kiro-structured-output-e2e.test.ts +2444 tests/server/server-kiro-usage-log-e2e.test.ts +766 tests/server/server-live-cancel.test.ts +8838 tests/server/server-live-close.test.ts +500 tests/server/server-live-existing-call.test.ts +156 tests/server/server-live-frame-log.test.ts +1258 tests/server/server-live-realtime-fixtures.test.ts +5468 tests/server/server-live.test.ts +90 tests/server/server-loopback-host-gate.test.ts +2283 tests/server/server-management-auth.test.ts +441 tests/server/server-management-log-admission.test.ts +1643 tests/server/server-native-catalog-priority.test.ts +145 tests/server/server-native-final-log.test.ts +165 tests/server/server-native-reasoning-retention-merge.test.ts +232 tests/server/server-native-reasoning-retention.test.ts +1041 tests/server/server-new-model-policy-arrival.test.ts +5088 tests/server/server-ollama-inbound-errors.test.ts +1017 tests/server/server-ollama-inbound-lifecycle.test.ts +1754 tests/server/server-ollama-inbound.test.ts +206 tests/server/server-ollama-route-policy.test.ts +610 tests/server/server-opencode-go-goal-streaming.test.ts +1690 tests/server/server-rate-limit-retry-e2e.test.ts +1158 tests/server/server-request-body-size.test.ts +2213 tests/server/server-search.test.ts +479 tests/server/server-startup-codex-off.test.ts +586 tests/server/server-startup-reconcile-resilience.test.ts +646 tests/server/server-stop-config-hardening.test.ts +274 tests/server/server-telemetry-profile-routes.test.ts +228 tests/server/server-telemetry-routes.test.ts +496 tests/server/server-terminal-refusal-wiring.test.ts +240 tests/server/server-workflow-budget-settings.test.ts +479 tests/server/server-xai-chat-reasoning-streaming.test.ts +531 tests/server/server-xai-header-parity.test.ts +3078 tests/server/server-xai-oauth-401-replay.test.ts +823 tests/server/server-xai-responses-streaming.test.ts 153 tests/server/session-affinity.test.ts -361 tests/server/session-lane-recall-harness.test.ts -145 tests/server/sidebar-routes.test.ts -38 tests/server/sidebar-star-state.test.ts -98 tests/server/spend-instrumentation-log.test.ts -117 tests/server/spend-ledger-lifecycle.test.ts -275 tests/server/spend-ledger-owner-startup.test.ts -80 tests/server/startup-action-control-elevation.test.ts -150 tests/server/startup-action-control.test.ts -11807 tests/server/startup-health-packaged-probe.test.ts -56 tests/server/startup-prompt.test.ts -107 tests/server/stream-aborted-marker.test.ts -144 tests/server/subagent-model-force-api.test.ts -815 tests/server/system-env.test.ts -151 tests/server/system-restart-admission.test.ts -4236 tests/server/system-restart-ownership.test.ts -155 tests/server/system-restart.test.ts -114 tests/server/system-routes.test.ts -8360 tests/server/terminal-guard-server.test.ts -89 tests/server/terminal-guard.test.ts -560 tests/server/turn-state-handles-e2e.test.ts -4075 tests/server/turn-state-handles.test.ts -144 tests/server/update-async-routes.test.ts -105 tests/server/upstream-connect-error.test.ts -1693 tests/server/upstream-error-detail-boundaries.test.ts -43 tests/server/upstream-http-version.test.ts -498 tests/server/v1-hub-state.test.ts -330 tests/server/v2-agent-message-failfast.test.ts -136 tests/service/autostart-health.test.ts -1421 tests/service/connected-stop-capability-auth.test.ts -2070 tests/service/container-bootstrap.test.ts -67 tests/service/crash-guard.test.ts -218 tests/service/doctor-bun-install.test.ts -25214 tests/service/doctor-codex-envkey-readiness.test.ts -111 tests/service/doctor-oauth.test.ts -92 tests/service/doctor-provider-apikey.test.ts -31 tests/service/doctor-service-memory-contract.test.ts -85 tests/service/init-backup-cleanup.test.ts -5243 tests/service/init-eof.test.ts -53 tests/service/launchd-port-fallback.test.ts -409 tests/service/launchd-repair.test.ts -79 tests/service/live-service-manager-guard.test.ts -34 tests/service/managing-cli.test.ts -39 tests/service/ownership-mutation-lease-diagnostics.test.ts -65 tests/service/process-state.test.ts -246 tests/service/service-auth-qualified-localhost.test.ts -68 tests/service/service-child-ownership.test.ts -92 tests/service/service-claim.test.ts -137 tests/service/service-definition-escaping.test.ts -119 tests/service/service-desktop-login-registration.test.ts -92 tests/service/service-desktop-recovery.test.ts -45 tests/service/service-desktop-runtime-preflight.test.ts -83 tests/service/service-desktop-startup-health.test.ts -200 tests/service/service-desktop-startup-linux.test.ts -281 tests/service/service-desktop-startup.test.ts -195 tests/service/service-desktop-supervision-windows.test.ts -34 tests/service/service-handled-signal-exit.test.ts -47 tests/service/service-health-sentinel-launch.test.ts -60 tests/service/service-health-sentinel-linux.test.ts -54 tests/service/service-health-sentinel-policy.test.ts -7911 tests/service/service-health-sentinel-process.test.ts -411 tests/service/service-health-sentinel-runner.test.ts -77 tests/service/service-install-wrapper-cleanup.test.ts -1178 tests/service/service-log.test.ts -125 tests/service/service-multishell-path.test.ts -55 tests/service/service-ownership-compatibility.test.ts -197 tests/service/service-ownership-handover.test.ts -196 tests/service/service-ownership-state.test.ts -171 tests/service/service-pinned-homes.test.ts -31 tests/service/service-probe-docker.test.ts -74 tests/service/service-proxy-env.test.ts -144 tests/service/service-runtime-preflight.test.ts -198 tests/service/service-secrets.test.ts -269 tests/service/service-sqlite-home.test.ts -34 tests/service/service-start-environment.test.ts -198 tests/service/service-state-isolation.test.ts -2487 tests/service/service-status-json.test.ts -166 tests/service/service-stop-verification.test.ts -339 tests/service/service-tier-capability.test.ts -175 tests/service/service-wsl-home-ownership.test.ts -805 tests/service/service.test.ts -232 tests/service/shutdown-drain.test.ts -8888 tests/service/shutdown-launcher.test.ts -124 tests/service/stale-state-purge.test.ts -37 tests/service/standalone-service.test.ts -26314 tests/service/stop-deferred-teardown.test.ts -339 tests/service/stop-direct-fetch.test.ts -977 tests/service/stop-restoration-preflight.test.ts -3908 tests/service/stop-restore-history-ownership.test.ts -73 tests/service/systemd-install-cleanup-hardening.test.ts -189 tests/service/winsw.test.ts -3148 tests/storage/api-storage-cleanup.test.ts +707 tests/server/session-lane-recall-harness.test.ts +204 tests/server/sidebar-routes.test.ts +51 tests/server/sidebar-star-state.test.ts +134 tests/server/spend-instrumentation-log.test.ts +190 tests/server/spend-ledger-lifecycle.test.ts +748 tests/server/spend-ledger-owner-startup.test.ts +132 tests/server/startup-action-control-elevation.test.ts +227 tests/server/startup-action-control.test.ts +11751 tests/server/startup-health-packaged-probe.test.ts +68 tests/server/startup-prompt.test.ts +139 tests/server/stream-aborted-marker.test.ts +197 tests/server/subagent-model-force-api.test.ts +225 tests/server/system-env.test.ts +241 tests/server/system-restart-admission.test.ts +4166 tests/server/system-restart-ownership.test.ts +237 tests/server/system-restart.test.ts +225 tests/server/system-routes.test.ts +8481 tests/server/terminal-guard-server.test.ts +108 tests/server/terminal-guard.test.ts +651 tests/server/turn-state-handles-e2e.test.ts +1041 tests/server/turn-state-handles.test.ts +283 tests/server/update-async-routes.test.ts +89 tests/server/upstream-connect-error.test.ts +2378 tests/server/upstream-error-detail-boundaries.test.ts +55 tests/server/upstream-http-version.test.ts +994 tests/server/v1-hub-state.test.ts +437 tests/server/v2-agent-message-failfast.test.ts +218 tests/service/autostart-health.test.ts +1462 tests/service/connected-stop-capability-auth.test.ts +3055 tests/service/container-bootstrap.test.ts +172 tests/service/crash-guard.test.ts +316 tests/service/doctor-bun-install.test.ts +25270 tests/service/doctor-codex-envkey-readiness.test.ts +230 tests/service/doctor-oauth.test.ts +125 tests/service/doctor-provider-apikey.test.ts +57 tests/service/doctor-service-memory-contract.test.ts +116 tests/service/init-backup-cleanup.test.ts +7314 tests/service/init-eof.test.ts +131 tests/service/launchd-port-fallback.test.ts +1419 tests/service/launchd-repair.test.ts +121 tests/service/live-service-manager-guard.test.ts +49 tests/service/managing-cli.test.ts +57 tests/service/ownership-mutation-lease-diagnostics.test.ts +133 tests/service/process-state.test.ts +205 tests/service/service-auth-qualified-localhost.test.ts +53 tests/service/service-child-ownership.test.ts +127 tests/service/service-claim.test.ts +164 tests/service/service-definition-escaping.test.ts +158 tests/service/service-desktop-login-registration.test.ts +929 tests/service/service-desktop-recovery.test.ts +279 tests/service/service-desktop-runtime-preflight.test.ts +126 tests/service/service-desktop-startup-health.test.ts +260 tests/service/service-desktop-startup-linux.test.ts +189 tests/service/service-desktop-startup.test.ts +138 tests/service/service-desktop-supervision-windows.test.ts +57 tests/service/service-disconnected-client-restart.test.ts +73 tests/service/service-handled-signal-exit.test.ts +65 tests/service/service-health-sentinel-launch.test.ts +92 tests/service/service-health-sentinel-linux.test.ts +60 tests/service/service-health-sentinel-policy.test.ts +7977 tests/service/service-health-sentinel-process.test.ts +434 tests/service/service-health-sentinel-runner.test.ts +1767 tests/service/service-install-wrapper-cleanup.test.ts +1826 tests/service/service-log.test.ts +134 tests/service/service-multishell-path.test.ts +72 tests/service/service-ownership-compatibility.test.ts +1446 tests/service/service-ownership-handover.test.ts +326 tests/service/service-ownership-state.test.ts +195 tests/service/service-pinned-homes.test.ts +52 tests/service/service-probe-docker.test.ts +61 tests/service/service-proxy-env.test.ts +70 tests/service/service-restart-registration-guard.test.ts +57 tests/service/service-restart-replacement.test.ts +784 tests/service/service-runtime-preflight.test.ts +135 tests/service/service-scheduler-restart-cleanup.test.ts +38629 tests/service/service-scheduler-restart-respawn-refusal.test.ts +209 tests/service/service-secrets.test.ts +257 tests/service/service-sqlite-home.test.ts +69 tests/service/service-start-environment.test.ts +320 tests/service/service-state-isolation.test.ts +2576 tests/service/service-status-json.test.ts +159 tests/service/service-stop-verification.test.ts +496 tests/service/service-tier-capability.test.ts +261 tests/service/service-wsl-home-ownership.test.ts +1757 tests/service/service.test.ts +320 tests/service/shutdown-drain.test.ts +10228 tests/service/shutdown-launcher.test.ts +72 tests/service/stale-state-purge.test.ts +51 tests/service/standalone-service.test.ts +31870 tests/service/stop-deferred-teardown.test.ts +384 tests/service/stop-direct-fetch.test.ts +1137 tests/service/stop-restoration-preflight.test.ts +4995 tests/service/stop-restore-history-ownership.test.ts +57 tests/service/systemd-install-cleanup-hardening.test.ts +361 tests/service/winsw.test.ts +3279 tests/storage/api-storage-cleanup.test.ts 1925 tests/storage/api-storage-policy-already-running.test.ts -1615 tests/storage/api-storage-policy-mutation-busy.test.ts -1401 tests/storage/api-storage-policy-put-race.test.ts -1252 tests/storage/api-storage-policy-run.test.ts -684 tests/storage/api-storage-policy.test.ts -835 tests/storage/api-storage.test.ts -770 tests/storage/storage-cleanup.test.ts -6380 tests/storage/storage-mutation-race.test.ts -107 tests/storage/storage-policy-config-race.test.ts -1942 tests/storage/storage-policy-job-responsive.test.ts -134 tests/storage/storage-policy.test.ts -30 tests/storage/storage-restore-job-errors.test.ts -4946 tests/storage/storage-restore-job-responsive.test.ts -176 tests/storage/storage-scanner.test.ts -905 tests/storage/storage-worker-lifecycle.test.ts -28 tests/storage/storage-worker-os-join-settle.test.ts -4305 tests/storage/storage-worker-teardown-isolate.test.ts -443 tests/test-layout-tooling.test.ts -127 tests/test-layout.test.ts -38 tests/update/pnpm-command-isolation.test.ts -38 tests/update/update-badge.test.ts -77 tests/update/update-bounded-json.test.ts -7781 tests/update/update-bun-ownership-lease.test.ts -34 tests/update/update-candidate-id.test.ts -71 tests/update/update-capability-policy.test.ts -325 tests/update/update-checkpoint-codec.test.ts -119 tests/update/update-config-preflight.test.ts -197 tests/update/update-contracts.test.ts -66 tests/update/update-desktop-badge.test.ts -52 tests/update/update-desktop-owner.test.ts -62 tests/update/update-effect-authority.test.ts -121 tests/update/update-external-metadata.test.ts -105 tests/update/update-guarded-ops.test.ts -1002 tests/update/update-home-launcher.test.ts -59 tests/update/update-home-recovery.test.ts -144 tests/update/update-home-worker.test.ts -183 tests/update/update-job-supervised-restart.test.ts -300 tests/update/update-job.test.ts -39 tests/update/update-minisign.test.ts -43 tests/update/update-mise-launcher-target.test.ts -31 tests/update/update-mise-node-runtime.test.ts -284 tests/update/update-mise.test.ts -122 tests/update/update-mutation-boundaries.test.ts -48 tests/update/update-mutation-guard.test.ts -87 tests/update/update-mutation-scanner.test.ts -44 tests/update/update-notify.test.ts -45 tests/update/update-npm-allow-scripts.test.ts -378 tests/update/update-npm-cache-preflight.test.ts -52 tests/update/update-npm-invocation.test.ts -31 tests/update/update-npm-supervisor-exit.test.ts -35 tests/update/update-npm-timeout.test.ts -41 tests/update/update-orchestrated-apply.test.ts -47 tests/update/update-orchestrated-arguments.test.ts -63388 tests/update/update-orchestrated-entry.test.ts -43 tests/update/update-orchestrated-identity.test.ts -75 tests/update/update-orchestrated-plan.test.ts -3417 tests/update/update-orchestrated-session.test.ts -36 tests/update/update-orchestrated-token.test.ts -132 tests/update/update-pnpm.test.ts -59 tests/update/update-reclaim-authorizer.test.ts -75 tests/update/update-recovery-authority.test.ts -290 tests/update/update-recovery-boundaries.test.ts -64 tests/update/update-recovery-host-free.test.ts -283 tests/update/update-refresh.test.ts -35307 tests/update/update-restart-lease.test.ts -42 tests/update/update-root-snapshot.test.ts -43 tests/update/update-service-home-policy.test.ts -114 tests/update/update-service-home.test.ts -151 tests/update/update-signed-supply.test.ts -33 tests/update/update-signed-version.test.ts -137 tests/update/update-standalone.test.ts -1697 tests/update/update-stop-classification.test.ts -8144 tests/update/update-stop-first.test.ts -41 tests/update/update-supervised-recovery.test.ts -18823 tests/update/update-sync-mutex.test.ts -3143 tests/update/update-teardown-handover.test.ts -524 tests/update/update-transactional-leftovers.test.ts -144 tests/update/update-transactional.test.ts -1883 tests/update/update-tray-handoff.test.ts -163 tests/update/update-tree-ownership.test.ts -59 tests/update/update-trust-root.test.ts -41 tests/update/update-windows-wrapper-authority.test.ts -65 tests/update/update-worker-launch.test.ts -42 tests/usage/anthropic2-usage-attribution.test.ts -485 tests/usage/cache-diagnostic-caller-isolation.test.ts -180 tests/usage/cache-diagnostic-hook-compat.test.ts -517 tests/usage/cache-diagnostic.test.ts -268 tests/usage/cost-cap-unknown-evidence.test.ts -93 tests/usage/cost-scoring.test.ts -54 tests/usage/gpt61-terra-pricing.test.ts -50 tests/usage/jev-stats.test.ts -101 tests/usage/key-attribution.test.ts -198 tests/usage/quota-401-recovery-runtime.test.ts -63 tests/usage/quota-401-recovery.test.ts -3137 tests/usage/quota-pool.test.ts -77 tests/usage/quota-reset-account-key.test.ts -432 tests/usage/quota-reset-core-boundary.test.ts -41 tests/usage/quota-reset-detector.test.ts -42 tests/usage/quota-reset-notify-config.test.ts -389 tests/usage/quota-reset-notify.test.ts -482 tests/usage/quota-reset-observation.test.ts -1719 tests/usage/quota-reset-seen-store.test.ts -194 tests/usage/quota-scoring.test.ts -3232 tests/usage/request-decompress.test.ts -40 tests/usage/request-evidence.test.ts -1270 tests/usage/request-history-index.test.ts -3137 tests/usage/request-history-integrity.test.ts -1082 tests/usage/request-history-rebuild-worker.test.ts -98 tests/usage/request-log-attempt-identity.test.ts -74 tests/usage/request-log-conversation.test.ts -120 tests/usage/request-log-error-detail.test.ts -78 tests/usage/request-log-estimate-cap.test.ts -244 tests/usage/request-log-generation-window.test.ts -87 tests/usage/request-log-identity-bounds.test.ts -65 tests/usage/request-log-jev.test.ts -42 tests/usage/request-log-model-filter.test.ts -174 tests/usage/request-log-nonstream.test.ts -267 tests/usage/request-log-normalization.test.ts -97 tests/usage/request-log-protocol-trace.test.ts -88 tests/usage/request-log-served-model.test.ts -223 tests/usage/request-log.test.ts -136 tests/usage/request-outcome-agreement.test.ts -30 tests/usage/request-pacing-provenance.test.ts -199 tests/usage/request-pacing.test.ts -18687 tests/usage/upstream-failure-diagnostics.test.ts -283 tests/usage/usage-aggregate-cache.test.ts -34 tests/usage/usage-anthropic-fast-pricing.test.ts -53 tests/usage/usage-antigravity-55.test.ts -70 tests/usage/usage-attempt-delivery.test.ts -123 tests/usage/usage-client-attribution.test.ts -54 tests/usage/usage-cost.test.ts -42 tests/usage/usage-cursor-fast-pricing.test.ts -114 tests/usage/usage-debug.test.ts -38 tests/usage/usage-failure-fingerprint.test.ts -64 tests/usage/usage-failure-persistence.test.ts -34 tests/usage/usage-failure-projection.test.ts -7741 tests/usage/usage-filter-index.test.ts -53 tests/usage/usage-haiku-5-5-pricing.test.ts -86 tests/usage/usage-ledger-retention.test.ts -176 tests/usage/usage-ledger-scanner.test.ts -35 tests/usage/usage-log-ws-stage.test.ts -2567 tests/usage/usage-log.test.ts -172 tests/usage/usage-partly-measured-cost.test.ts -56 tests/usage/usage-prompt-length-pricing.test.ts -40 tests/usage/usage-provider-label.test.ts -211 tests/usage/usage-shape-extraction.test.ts -64 tests/usage/usage-snapshot-digest-reuse.test.ts -54 tests/usage/usage-spend-cache-provenance.test.ts -104 tests/usage/usage-summary.test.ts -62 tests/usage/usage-surfaces.test.ts -312 tests/usage/usage-telemetry-client.test.ts -116 tests/usage/usage-telemetry-collector-privacy.test.ts -110 tests/usage/usage-telemetry-collector-typecheck.test.ts -114 tests/usage/usage-telemetry-collector-worker.test.ts -287 tests/usage/usage-telemetry-core-boundary.test.ts -76 tests/usage/usage-telemetry-profile-collector.test.ts -45 tests/usage/usage-telemetry-profile-contract.test.ts -242 tests/usage/usage-telemetry-profile-lifecycle.test.ts -93 tests/usage/usage-telemetry-profile-sync.test.ts -36 tests/usage/usage-throughput.test.ts -37 tests/usage/usage-time-range.test.ts -2319 tests/usage/usage-timeline.test.ts -72 tests/usage/user-cost-overlay-coderabbit-regressions.test.ts -1216 tests/usage/user-cost-overlay-live-reconcile.test.ts -116 tests/usage/user-cost-overlay-provider-delete.test.ts -35 tests/videos/fulfill-video.test.ts -53 tests/videos/plan-video.test.ts -55 tests/videos/xai-video-client.test.ts -762 tests/vision/mistral-vision-sidecar.test.ts -134 tests/vision/sidecar-abort.test.ts -132 tests/vision/sidecar-auth.test.ts -70 tests/vision/sidecar-candidates.test.ts -394 tests/vision/sidecar-settings-vision-catalog.test.ts -179 tests/vision/sidecar-settings-vision-controls.test.ts -143 tests/vision/sidecar-settings-vision-filter.test.ts -174 tests/vision/sidecar-settings-web-search-gate.test.ts -259 tests/vision/sidecar-settings-web-search-off.test.ts -332 tests/vision/sidecar-settings-web-search-stream.test.ts -96 tests/vision/sidecar-tracker.test.ts -246 tests/vision/vision-anthropic-instance-sidecar.test.ts -224 tests/vision/vision-anthropic.test.ts -271 tests/vision/vision-backend-union.test.ts -114 tests/vision/vision-cache.test.ts -83 tests/vision/vision-custom-row-precedence.test.ts -64 tests/vision/vision-eligibility.test.ts -87 tests/vision/vision-fail-closed.test.ts -161 tests/vision/vision-reasoning-contract.test.ts -513 tests/vision/vision-routed.test.ts -960 tests/vision/vision-sidecar-e2e.test.ts -55 tests/vision/vision-text-only-predicate.test.ts -78 tests/web-search/devin-web-search.test.ts -116 tests/web-search/fix-search-frame-shapes.test.ts -33 tests/web-search/fix-search-orphan-source.test.ts -31 tests/web-search/fix-search-unicode-clamp.test.ts -49 tests/web-search/format-result.test.ts -158 tests/web-search/web-search-anthropic-instance.test.ts -2507 tests/web-search/web-search-anthropic.test.ts -280 tests/web-search/web-search-backend-union.test.ts -88 tests/web-search/web-search-bridge-replay.test.ts -76 tests/web-search/web-search-candidates.test.ts -69 tests/web-search/web-search-eof.test.ts -93 tests/web-search/web-search-forced-declaration.test.ts -94 tests/web-search/web-search-loop-error-usage.test.ts -79 tests/web-search/web-search-loop-iteration-usage.test.ts -112 tests/web-search/web-search-pacing-deadline.test.ts -62 tests/web-search/web-search-parse.test.ts -285 tests/web-search/web-search-passthrough-bridge.test.ts -4540 tests/web-search/web-search-progress-stream.test.ts -81 tests/web-search/web-search-recovery-kind.test.ts -1593 tests/web-search/web-search-retry-heartbeat.test.ts -263 tests/web-search/web-search-rotation-usage-attribution.test.ts -88 tests/web-search/web-search-run-turn-loop.test.ts -7291 tests/web-search/web-search-sidecar-429.test.ts -225 tests/web-search/web-search-sidecar-replay.test.ts -82 tests/web-search/web-search-sources.test.ts -200 tests/web-search/web-search-terminal-refusal.test.ts -343 tests/web-search/web-search-timeout-contract.test.ts -98 tests/web-search/web-search-timeout-plan.test.ts -5310 tests/web-search/web-search.test.ts -30 tests/windows/coding-agent-native-empty-argv.test.ts -35 tests/windows/tray-proxy-deadline.test.ts -2324 tests/windows/tray-proxy.test.ts -35 tests/windows/win-exec.test.ts -29 tests/windows/win-paths.test.ts -30 tests/windows/windows-acl-start-cost.test.ts -36 tests/windows/windows-atomic-replace.test.ts -68 tests/windows/windows-atomic-write-acl-rearm.test.ts -71 tests/windows/windows-codex-cli-job-store.test.ts -53 tests/windows/windows-config-read-acl-memo.test.ts -336 tests/windows/windows-config-root-async-writers.test.ts -52 tests/windows/windows-deploy-close-regressions.test.ts -291 tests/windows/windows-elevation-spawn.test.ts -35 tests/windows/windows-elevation.test.ts -72 tests/windows/windows-guarded-manager.test.ts -50 tests/windows/windows-lifecycle-root-acl.test.ts -44 tests/windows/windows-native-principal.test.ts -140 tests/windows/windows-popup-fix.test.ts -44 tests/windows/windows-process-priority.test.ts -67 tests/windows/windows-scheduler-errors.test.ts -109 tests/windows/windows-scheduler-install-verification.test.ts -42 tests/windows/windows-secret-acl-diagnostics.test.ts -47 tests/windows/windows-secret-acl-removal-flight.test.ts -356 tests/windows/windows-secret-acl.test.ts -120 tests/windows/windows-service-mutation-lock.test.ts -35 tests/windows/windows-service-wrappers.test.ts -25 tests/windows/windows-text-decoding.test.ts -51 tests/windows/windows-tray-restart-hardening.test.ts -52 tests/windows/windows-tray-run-limit.test.ts -1846 tests/windows/windows-tray.test.ts -72 tests/windows/windows-user-principal-nonascii.test.ts -49 tests/windows/windows-user-principal.test.ts -36 tests/windows/winsw-stop-hardening.test.ts +1595 tests/storage/api-storage-policy-mutation-busy.test.ts +1113 tests/storage/api-storage-policy-put-race.test.ts +1677 tests/storage/api-storage-policy-run.test.ts +806 tests/storage/api-storage-policy.test.ts +693 tests/storage/api-storage.test.ts +1043 tests/storage/storage-cleanup.test.ts +6589 tests/storage/storage-mutation-race.test.ts +122 tests/storage/storage-policy-config-race.test.ts +2250 tests/storage/storage-policy-job-responsive.test.ts +119 tests/storage/storage-policy.test.ts +104 tests/storage/storage-restore-job-errors.test.ts +5154 tests/storage/storage-restore-job-responsive.test.ts +219 tests/storage/storage-scanner.test.ts +975 tests/storage/storage-worker-lifecycle.test.ts +48 tests/storage/storage-worker-os-join-settle.test.ts +4437 tests/storage/storage-worker-teardown-isolate.test.ts +446 tests/test-layout-tooling.test.ts +132 tests/test-layout.test.ts +303 tests/update/pnpm-command-isolation.test.ts +64 tests/update/update-badge.test.ts +101 tests/update/update-bounded-json.test.ts +10869 tests/update/update-bun-ownership-lease.test.ts +52 tests/update/update-candidate-id.test.ts +86 tests/update/update-capability-policy.test.ts +323 tests/update/update-checkpoint-codec.test.ts +169 tests/update/update-config-preflight.test.ts +238 tests/update/update-contracts.test.ts +57 tests/update/update-desktop-badge.test.ts +50 tests/update/update-desktop-headless-acquire.test.ts +79 tests/update/update-desktop-headless-flow.test.ts +66 tests/update/update-desktop-headless-release.test.ts +53 tests/update/update-desktop-headless-runtime.test.ts +50 tests/update/update-desktop-headless-staging.test.ts +70 tests/update/update-desktop-owner.test.ts +66 tests/update/update-effect-authority.test.ts +177 tests/update/update-external-metadata.test.ts +57 tests/update/update-guarded-ops.test.ts +690 tests/update/update-home-launcher.test.ts +54 tests/update/update-home-recovery.test.ts +185 tests/update/update-home-worker.test.ts +163 tests/update/update-job-supervised-restart.test.ts +241 tests/update/update-job.test.ts +98 tests/update/update-minisign.test.ts +65 tests/update/update-mise-launcher-target.test.ts +55 tests/update/update-mise-node-runtime.test.ts +417 tests/update/update-mise.test.ts +136 tests/update/update-mutation-boundaries.test.ts +62 tests/update/update-mutation-guard.test.ts +123 tests/update/update-mutation-scanner.test.ts +118 tests/update/update-notify.test.ts +50 tests/update/update-npm-allow-scripts.test.ts +403 tests/update/update-npm-cache-preflight.test.ts +69 tests/update/update-npm-invocation.test.ts +60 tests/update/update-npm-supervisor-exit.test.ts +57 tests/update/update-npm-timeout.test.ts +84 tests/update/update-orchestrated-apply.test.ts +60 tests/update/update-orchestrated-arguments.test.ts +60699 tests/update/update-orchestrated-entry.test.ts +69 tests/update/update-orchestrated-identity.test.ts +78 tests/update/update-orchestrated-plan.test.ts +26091 tests/update/update-orchestrated-pnpm-entry.test.ts +22360 tests/update/update-orchestrated-pnpm-global-store-entry.test.ts +3329 tests/update/update-orchestrated-session.test.ts +46 tests/update/update-orchestrated-token.test.ts +603 tests/update/update-pnpm-global-store.test.ts +160 tests/update/update-pnpm.test.ts +85 tests/update/update-reclaim-authorizer.test.ts +69 tests/update/update-recovery-authority.test.ts +241 tests/update/update-recovery-boundaries.test.ts +45 tests/update/update-recovery-host-free.test.ts +293 tests/update/update-refresh.test.ts +35479 tests/update/update-restart-lease.test.ts +57 tests/update/update-root-snapshot.test.ts +47 tests/update/update-service-home-policy.test.ts +231 tests/update/update-service-home.test.ts +91 tests/update/update-signed-supply.test.ts +40 tests/update/update-signed-version.test.ts +122 tests/update/update-standalone.test.ts +1613 tests/update/update-stop-classification.test.ts +9093 tests/update/update-stop-first.test.ts +64 tests/update/update-supervised-recovery.test.ts +18724 tests/update/update-sync-mutex.test.ts +3894 tests/update/update-teardown-handover.test.ts +520 tests/update/update-transactional-leftovers.test.ts +210 tests/update/update-transactional.test.ts +1718 tests/update/update-tray-handoff.test.ts +997 tests/update/update-tree-ownership.test.ts +57 tests/update/update-trust-root.test.ts +98 tests/update/update-windows-installer-witness.test.ts +56 tests/update/update-windows-wrapper-authority.test.ts +76 tests/update/update-worker-launch.test.ts +61 tests/usage/anthropic2-usage-attribution.test.ts +749 tests/usage/cache-diagnostic-caller-isolation.test.ts +279 tests/usage/cache-diagnostic-hook-compat.test.ts +638 tests/usage/cache-diagnostic.test.ts +223 tests/usage/cost-cap-unknown-evidence.test.ts +122 tests/usage/cost-scoring.test.ts +116 tests/usage/gpt61-terra-pricing.test.ts +57 tests/usage/jev-stats.test.ts +123 tests/usage/key-attribution.test.ts +112 tests/usage/mistral-budget-reset-identity.test.ts +232 tests/usage/provider-failure-detail.test.ts +252 tests/usage/quota-401-recovery-runtime.test.ts +56 tests/usage/quota-401-recovery.test.ts +2491 tests/usage/quota-pool.test.ts +168 tests/usage/quota-reset-account-key.test.ts +410 tests/usage/quota-reset-core-boundary.test.ts +54 tests/usage/quota-reset-detector.test.ts +69 tests/usage/quota-reset-notify-config.test.ts +463 tests/usage/quota-reset-notify.test.ts +629 tests/usage/quota-reset-observation.test.ts +1708 tests/usage/quota-reset-seen-store.test.ts +147 tests/usage/quota-scoring.test.ts +632 tests/usage/request-body-log.test.ts +593 tests/usage/request-decompress-ratio.test.ts +2402 tests/usage/request-decompress.test.ts +50 tests/usage/request-evidence.test.ts +1736 tests/usage/request-history-index.test.ts +3542 tests/usage/request-history-integrity.test.ts +1446 tests/usage/request-history-rebuild-worker.test.ts +464 tests/usage/request-log-anthropic-account-tag.test.ts +157 tests/usage/request-log-attempt-identity.test.ts +206 tests/usage/request-log-conversation.test.ts +113 tests/usage/request-log-error-detail.test.ts +127 tests/usage/request-log-estimate-cap.test.ts +239 tests/usage/request-log-generation-window.test.ts +129 tests/usage/request-log-identity-bounds.test.ts +105 tests/usage/request-log-jev.test.ts +53 tests/usage/request-log-model-filter.test.ts +205 tests/usage/request-log-nonstream.test.ts +182 tests/usage/request-log-normalization.test.ts +201 tests/usage/request-log-protocol-trace.test.ts +106 tests/usage/request-log-served-model.test.ts +414 tests/usage/request-log.test.ts +157 tests/usage/request-outcome-agreement.test.ts +76 tests/usage/request-pacing-provenance.test.ts +211 tests/usage/request-pacing.test.ts +19337 tests/usage/upstream-failure-diagnostics.test.ts +520 tests/usage/usage-aggregate-cache.test.ts +62 tests/usage/usage-anthropic-fast-pricing.test.ts +62 tests/usage/usage-antigravity-55.test.ts +76 tests/usage/usage-attempt-delivery.test.ts +179 tests/usage/usage-client-attribution.test.ts +93 tests/usage/usage-cost.test.ts +52 tests/usage/usage-cursor-fast-pricing.test.ts +116 tests/usage/usage-debug.test.ts +67 tests/usage/usage-fable-5-2-pricing.test.ts +39 tests/usage/usage-failure-fingerprint.test.ts +114 tests/usage/usage-failure-persistence.test.ts +45 tests/usage/usage-failure-projection.test.ts +7700 tests/usage/usage-filter-index.test.ts +909 tests/usage/usage-filter-paging.test.ts +62 tests/usage/usage-haiku-5-5-pricing.test.ts +136 tests/usage/usage-ledger-retention.test.ts +507 tests/usage/usage-ledger-scanner.test.ts +49 tests/usage/usage-log-ws-stage.test.ts +2613 tests/usage/usage-log.test.ts +103 tests/usage/usage-partly-measured-cost.test.ts +55 tests/usage/usage-prompt-length-pricing.test.ts +57 tests/usage/usage-provider-label.test.ts +317 tests/usage/usage-shape-extraction.test.ts +93 tests/usage/usage-snapshot-digest-reuse.test.ts +63 tests/usage/usage-spend-cache-provenance.test.ts +153 tests/usage/usage-summary.test.ts +65 tests/usage/usage-surfaces.test.ts +387 tests/usage/usage-telemetry-client.test.ts +121 tests/usage/usage-telemetry-collector-privacy.test.ts +187 tests/usage/usage-telemetry-collector-typecheck.test.ts +142 tests/usage/usage-telemetry-collector-worker.test.ts +286 tests/usage/usage-telemetry-core-boundary.test.ts +85 tests/usage/usage-telemetry-profile-collector.test.ts +66 tests/usage/usage-telemetry-profile-contract.test.ts +227 tests/usage/usage-telemetry-profile-lifecycle.test.ts +110 tests/usage/usage-telemetry-profile-sync.test.ts +58 tests/usage/usage-throughput.test.ts +60 tests/usage/usage-time-range.test.ts +2517 tests/usage/usage-timeline.test.ts +105 tests/usage/user-cost-overlay-coderabbit-regressions.test.ts +1354 tests/usage/user-cost-overlay-live-reconcile.test.ts +124 tests/usage/user-cost-overlay-provider-delete.test.ts +59 tests/videos/fulfill-video.test.ts +122 tests/videos/plan-video.test.ts +95 tests/videos/video-outbound-destination.test.ts +122 tests/videos/video-provider.test.ts +97 tests/videos/xai-video-client.test.ts +1044 tests/vision/mistral-vision-sidecar.test.ts +180 tests/vision/sidecar-abort.test.ts +124 tests/vision/sidecar-auth.test.ts +116 tests/vision/sidecar-candidates.test.ts +377 tests/vision/sidecar-settings-vision-catalog.test.ts +231 tests/vision/sidecar-settings-vision-controls.test.ts +279 tests/vision/sidecar-settings-vision-filter.test.ts +354 tests/vision/sidecar-settings-web-search-gate.test.ts +410 tests/vision/sidecar-settings-web-search-off.test.ts +290 tests/vision/sidecar-settings-web-search-stream.test.ts +52 tests/vision/sidecar-tracker.test.ts +360 tests/vision/vision-anthropic-instance-sidecar.test.ts +212 tests/vision/vision-anthropic.test.ts +289 tests/vision/vision-backend-union.test.ts +147 tests/vision/vision-cache.test.ts +110 tests/vision/vision-custom-row-precedence.test.ts +118 tests/vision/vision-eligibility.test.ts +123 tests/vision/vision-fail-closed.test.ts +237 tests/vision/vision-reasoning-contract.test.ts +503 tests/vision/vision-routed.test.ts +1498 tests/vision/vision-sidecar-e2e.test.ts +204 tests/vision/vision-text-only-predicate.test.ts +152 tests/web-search/devin-web-search.test.ts +172 tests/web-search/fix-search-frame-shapes.test.ts +51 tests/web-search/fix-search-orphan-source.test.ts +46 tests/web-search/fix-search-unicode-clamp.test.ts +51 tests/web-search/format-result.test.ts +255 tests/web-search/web-search-anthropic-instance.test.ts +2697 tests/web-search/web-search-anthropic.test.ts +382 tests/web-search/web-search-backend-union.test.ts +180 tests/web-search/web-search-bridge-replay.test.ts +125 tests/web-search/web-search-candidates.test.ts +102 tests/web-search/web-search-eof.test.ts +112 tests/web-search/web-search-forced-declaration.test.ts +1389 tests/web-search/web-search-local-deadline-provenance.test.ts +140 tests/web-search/web-search-loop-error-usage.test.ts +146 tests/web-search/web-search-loop-iteration-usage.test.ts +142 tests/web-search/web-search-memory-citation.test.ts +147 tests/web-search/web-search-pacing-deadline.test.ts +69 tests/web-search/web-search-parse.test.ts +1426 tests/web-search/web-search-passthrough-bridge.test.ts +4602 tests/web-search/web-search-progress-stream.test.ts +103 tests/web-search/web-search-recovery-kind.test.ts +1639 tests/web-search/web-search-retry-heartbeat.test.ts +186 tests/web-search/web-search-rotation-usage-attribution.test.ts +97 tests/web-search/web-search-run-turn-loop.test.ts +7467 tests/web-search/web-search-sidecar-429.test.ts +375 tests/web-search/web-search-sidecar-replay.test.ts +71 tests/web-search/web-search-sources.test.ts +197 tests/web-search/web-search-terminal-refusal.test.ts +472 tests/web-search/web-search-timeout-contract.test.ts +101 tests/web-search/web-search-timeout-plan.test.ts +5376 tests/web-search/web-search.test.ts +54 tests/windows/coding-agent-native-empty-argv.test.ts +54 tests/windows/tray-proxy-deadline.test.ts +2319 tests/windows/tray-proxy.test.ts +60 tests/windows/win-exec.test.ts +42 tests/windows/win-paths.test.ts +52 tests/windows/windows-acl-start-cost.test.ts +49 tests/windows/windows-atomic-replace.test.ts +101 tests/windows/windows-atomic-write-acl-rearm.test.ts +4817 tests/windows/windows-checked-stop-live.test.ts +268 tests/windows/windows-checked-stop.test.ts +63 tests/windows/windows-cli-config-root-startup.test.ts +114 tests/windows/windows-codex-cli-job-store.test.ts +62 tests/windows/windows-config-read-acl-memo.test.ts +405 tests/windows/windows-config-root-async-writers.test.ts +161 tests/windows/windows-config-root-integration-writers.test.ts +65 tests/windows/windows-deploy-close-regressions.test.ts +403 tests/windows/windows-elevation-spawn.test.ts +70 tests/windows/windows-elevation.test.ts +65 tests/windows/windows-guarded-manager.test.ts +72 tests/windows/windows-lifecycle-root-acl.test.ts +58 tests/windows/windows-native-principal.test.ts +164 tests/windows/windows-popup-fix.test.ts +2582 tests/windows/windows-process-evidence.test.ts +51 tests/windows/windows-process-priority.test.ts +82 tests/windows/windows-scheduler-errors.test.ts +201 tests/windows/windows-scheduler-install-verification.test.ts +64 tests/windows/windows-secret-acl-diagnostics.test.ts +59 tests/windows/windows-secret-acl-removal-flight.test.ts +361 tests/windows/windows-secret-acl.test.ts +136 tests/windows/windows-service-mutation-lock.test.ts +389 tests/windows/windows-service-stop-wiring.test.ts +51 tests/windows/windows-service-wrappers.test.ts +99 tests/windows/windows-stop-binding.test.ts +165 tests/windows/windows-stop-callers.test.ts +604 tests/windows/windows-stop-confirm.test.ts +5271 tests/windows/windows-stop-ocx-stop.test.ts +45 tests/windows/windows-text-decoding.test.ts +84 tests/windows/windows-tray-restart-hardening.test.ts +50 tests/windows/windows-tray-run-limit.test.ts +1815 tests/windows/windows-tray.test.ts +48 tests/windows/windows-user-principal-nonascii.test.ts +91 tests/windows/windows-user-principal.test.ts +49 tests/windows/winsw-stop-hardening.test.ts From 8e8623bb78d041748aca876a26ea55b0fa182437 Mon Sep 17 00:00:00 2001 From: Epinephrine Date: Thu, 19 Nov 2026 14:07:39 +0900 Subject: [PATCH 3/9] ci: record reviewed timing table in release evidence Preserve the 26 historical evidence snapshots and append the current CI fingerprint set with the independently reviewed timing table blob. Keep every workflow, job requirement, shard count, and timeout unchanged. Validation: 69 release evidence/history/dispatch/resume/docs tests pass; release-evidence policy-check passes. --- .github/scripts/release-evidence-policy.json | 34 ++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/.github/scripts/release-evidence-policy.json b/.github/scripts/release-evidence-policy.json index 44115400e66..51c1f898f2b 100644 --- a/.github/scripts/release-evidence-policy.json +++ b/.github/scripts/release-evidence-policy.json @@ -806,5 +806,39 @@ "desktop/scripts/appimage-patchelf.py": "63e78ef74160bc48fbcdd882065f1d416db6d13c", "desktop/scripts/linux-packaged-e2e.ts": "9ca92352668ff881c85caea44a9b4747bedc7e2d" } + }, + { + "kind": "ci", + "version": 1, + "windowsShards": 14, + "files": { + ".github/workflows/ci.yml": "74f5dfb883786792c872c58f2311b0299818b702", + ".github/actions/setup-project-bun/action.yml": "cf28f6f9d4385d69784f4e3610914f6952ce789d", + ".github/scripts/release-evidence.cjs": "ace2b9006b2d58ef84ed0996b4e179ff4be15900", + ".github/scripts/release-evidence.test.cjs": "9cc686390e5c37d8e693b98d049e8b505d0273cf", + "scripts/ci/select-test-lane.sh": "b25836cb55f962d1ffd9e68ed00f45f8b45becc8", + "scripts/ci/windows-sensitive-diff.sh": "03495f256c671aff57e750febffe19ca7face6a1", + "scripts/ci/run-bun-test-batches.sh": "59b1783aadf8109c0fa2d37047ff0d90300aa267", + "scripts/ci/bun-crash-signatures.sh": "d34662ddd07864d97bed909135095db33fe42c9e", + "scripts/ci/bun-install-frozen.sh": "e6d7bc3aec044e12297c7c4c04015a33df0eb22b", + "scripts/ci/docker-smoke.ts": "4eea7637d8658156feeaa356c0c3086c00d75fa5", + "scripts/ci/test-durations.tsv": "a07f90e6098082e1452ea5cc075c801271321eca", + "scripts/ci/test-durations.windows.tsv": "523cef871c3e17fc0344c98fb15eef79feb04c84", + "scripts/test.ts": "5b73037fb54e685b1d3485ea664e82a1eb418606", + "scripts/lib/test-runner-bun.ts": "8763806104a851dbdefeea8cffe8d7dd8d1c8da1", + "scripts/test-temp-lock.ts": "ee83fb254b728de119028f52b9894bf52d7aea15", + "scripts/git-repository-env.ts": "267950490fffb4c48d9adb90bdcf5a873733b324", + "scripts/ci/run-changed-tests.sh": "9a54d3a5db9849bcbe0dd766954a840185419fa5", + "scripts/keyring-smoke.ts": "cd3be07ad57796172696dfa053ea1fb129f29365", + "scripts/privacy-scan.ts": "86314e891b45e49739b94c76cddd9e4cc2d4340f", + "scripts/structure-ssot.ts": "5b2d2918dae877fddfb16cdba6e89f0d10e82298", + "scripts/generate-ocx-skill-surface.ts": "155e866656ba2d71e8fd48adda857451caf16322", + "desktop/scripts/prepare-sidecar.ts": "20f7eec61f73635ea681e25f13dd850b62bb41e2", + "desktop/scripts/build-widget.sh": "38e0eb9d713804b603aa75c32383aa18ef01d06c", + "desktop/scripts/verify-macos-runtime.sh": "43f1a31375c6f6fe7dcafb9d96c231b98d1f6ba4", + "desktop/scripts/verify-linux-sidecar.sh": "c502bb5c8ba8346c722a8f5274f2274bb325a934", + "desktop/scripts/appimage-patchelf.py": "63e78ef74160bc48fbcdd882065f1d416db6d13c", + "desktop/scripts/linux-packaged-e2e.ts": "9ca92352668ff881c85caea44a9b4747bedc7e2d" + } } ] From 8e4d926feff87debfed6e2042154c7d0632cf369 Mon Sep 17 00:00:00 2001 From: Epinephrine Date: Thu, 19 Nov 2026 17:51:35 +0900 Subject: [PATCH 4/9] test: keep stop-owner registration independent of the service-stop follow-up --- scripts/test-layout/layout.json | 3 ++- tests/fixtures/test-layout-expected.json | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/scripts/test-layout/layout.json b/scripts/test-layout/layout.json index d554325218f..f9e70ba2795 100644 --- a/scripts/test-layout/layout.json +++ b/scripts/test-layout/layout.json @@ -1930,10 +1930,11 @@ "windows-acl-start-cost.test.ts": "windows", "windows-atomic-write-acl-rearm.test.ts": "windows", "windows-atomic-replace.test.ts": "windows", "windows-deploy-close-regressions.test.ts": "windows", + "windows-stop-owner-identity.test.ts": "windows", "windows-elevation-spawn.test.ts": "windows", "windows-elevation.test.ts": "windows", "windows-guarded-manager.test.ts": "windows", "windows-checked-stop.test.ts": "windows", "windows-stop-binding.test.ts": "windows", "windows-checked-stop-live.test.ts": "windows", "windows-service-stop-wiring.test.ts": "windows", - "windows-popup-fix.test.ts": "windows", "windows-stop-confirm.test.ts": "windows", "windows-process-evidence.test.ts": "windows", "windows-stop-owner-identity.test.ts": "windows", "windows-stop-callers.test.ts": "windows", "windows-stop-ocx-stop.test.ts": "windows", + "windows-popup-fix.test.ts": "windows", "windows-stop-confirm.test.ts": "windows", "windows-process-evidence.test.ts": "windows", "windows-stop-callers.test.ts": "windows", "windows-stop-ocx-stop.test.ts": "windows", "windows-process-priority.test.ts": "windows", "windows-scheduler-errors.test.ts": "windows", "windows-scheduler-install-verification.test.ts": "windows", "windows-lifecycle-root-acl.test.ts": "windows", diff --git a/tests/fixtures/test-layout-expected.json b/tests/fixtures/test-layout-expected.json index 75d22ed359b..b07e5a013fb 100644 --- a/tests/fixtures/test-layout-expected.json +++ b/tests/fixtures/test-layout-expected.json @@ -1615,10 +1615,11 @@ "windows-atomic-replace.test.ts": "windows", "windows-codex-cli-job-store.test.ts": "windows", "windows-deploy-close-regressions.test.ts": "windows", + "windows-stop-owner-identity.test.ts": "windows", "windows-elevation-spawn.test.ts": "windows", "windows-elevation.test.ts": "windows", "windows-guarded-manager.test.ts": "windows", "windows-checked-stop.test.ts": "windows", "windows-stop-binding.test.ts": "windows", "windows-checked-stop-live.test.ts": "windows", "windows-service-stop-wiring.test.ts": "windows", - "windows-popup-fix.test.ts": "windows", "windows-stop-confirm.test.ts": "windows", "windows-process-evidence.test.ts": "windows", "windows-stop-owner-identity.test.ts": "windows", "windows-stop-callers.test.ts": "windows", "windows-stop-ocx-stop.test.ts": "windows", + "windows-popup-fix.test.ts": "windows", "windows-stop-confirm.test.ts": "windows", "windows-process-evidence.test.ts": "windows", "windows-stop-callers.test.ts": "windows", "windows-stop-ocx-stop.test.ts": "windows", "windows-process-priority.test.ts": "windows", "windows-scheduler-errors.test.ts": "windows", "windows-scheduler-install-verification.test.ts": "windows", "windows-lifecycle-root-acl.test.ts": "windows", From 0ac89ad9d0e8c0c78c9ecd8404db85114df58316 Mon Sep 17 00:00:00 2001 From: luvs01 <27862058+luvs01@users.noreply.github.com> Date: Fri, 20 Nov 2026 16:42:44 +0900 Subject: [PATCH 5/9] test(link): report recovery phases when the Windows watchdog expires --- .../clients/client-link-stop-recovery.test.ts | 14 ++++++++-- .../client-link-stop-recovery-runner.ts | 26 +++++++++++++------ 2 files changed, 30 insertions(+), 10 deletions(-) diff --git a/tests/clients/client-link-stop-recovery.test.ts b/tests/clients/client-link-stop-recovery.test.ts index 66d4edf4951..f8de44e8c28 100644 --- a/tests/clients/client-link-stop-recovery.test.ts +++ b/tests/clients/client-link-stop-recovery.test.ts @@ -13,14 +13,24 @@ async function runRecovery(mode: string, scheduled = false, env = process.env, a env: { ...env, HOME: root, USERPROFILE: root, OPENCODEX_HOME: join(root, "ocx"), CODEX_HOME: join(root, "codex"), OPENCODEX_CLAUDE_DESKTOP_CONFIG_DIR: join(root, "claude-desktop"), OCX_SERVICE: "", OCX_SERVICE_MANAGED: "0" }, }); - const timeout = setTimeout(() => child.kill("SIGKILL"), 15_000); + let parentDeadlineReached = false; + const timeout = setTimeout(() => { + if (child.exitCode !== null) return; + parentDeadlineReached = true; + child.kill("SIGKILL"); + }, 15_000); try { const [exit, stdout, stderr] = await Promise.all([child.exited, new Response(child.stdout).text(), new Response(child.stderr).text()]); if (exit === 75 && stderr.trim() === "fixture-port-collision") { if (attempt >= 2) throw new Error("recovery fixture port collided three times"); return runRecovery(mode, scheduled, env, attempt + 1); } - expect(exit, stderr).toBe(0); + if (exit !== 0) { + const phases = stdout.split(/\r?\n/).filter(line => line.startsWith("recovery phase ")); + const status = parentDeadlineReached ? "parent requested termination at its 15s deadline" : "child exited"; + throw new Error([`Link recovery (${mode}): ${status}, exit ${exit}`, + ...(phases.length ? phases : ["no fixture phase reported"]), stderr.trimEnd()].filter(Boolean).join("\n")); + } expect(stderr).not.toContain("uncaughtException"); const line = stdout.split("\n").find(line => line.startsWith("{")); expect(line, stdout + stderr).toBeDefined(); diff --git a/tests/fixtures/client-link-stop-recovery-runner.ts b/tests/fixtures/client-link-stop-recovery-runner.ts index 7891634d719..ce6e725f61f 100644 --- a/tests/fixtures/client-link-stop-recovery-runner.ts +++ b/tests/fixtures/client-link-stop-recovery-runner.ts @@ -1,6 +1,6 @@ /** Real file recovery and bound restart; only replacement process launch is a loopback fixture. */ import { mock, spyOn } from "bun:test"; -import { mkdirSync, readFileSync, unlinkSync, writeFileSync } from "node:fs"; +import { mkdirSync, readFileSync, unlinkSync, writeFileSync, writeSync } from "node:fs"; import { dirname, join } from "node:path"; import { getDefaultConfig, saveConfig } from "../../src/config"; import { serviceApiTokenFingerprint, writeServiceApiTokenFile, readServiceApiTokenState } from "../../src/lib/service-secrets"; @@ -13,7 +13,13 @@ import { createSystemRestartCapability, SYSTEM_RESTART_CAPABILITY_HEADER, SYSTEM SYSTEM_RESTART_NONCE_HEADER, SYSTEM_RESTART_PATH } from "../../src/lib/system-restart-contract"; const options = JSON.parse(readFileSync(0, "utf8")) as { mode: string; scheduled?: boolean }; -let phase = "fixture setup"; +let phase: string; +function enterPhase(name: string): void { + phase = name; + // Flush before synchronous filesystem work so a parent timeout retains the last transition. + writeSync(1, `recovery phase ${Math.round(performance.now())}ms: ${name}\n`); +} +enterPhase("fixture setup"); const home = process.env.OPENCODEX_HOME!; mkdirSync(home, { recursive: true }); const lifecycle = await import("../../src/client/lifecycle-lock"); @@ -43,6 +49,7 @@ async function main() { const document = { version: 1 as const, home: { name: "fixture", version: "1" }, clients: Object.fromEntries(ROUTE_CLIENT_IDS.map(id => [id, { enabled: id === "pi" }])), sources: Object.fromEntries(ROUTE_CLIENT_IDS.map(id => [id, "default"])) } as import("../../src/link/route-intent").HomeRouteIntentDocument; + enterPhase("applying the file route"); const applied = await applyConnectedRouteIntent(expected, token, { document, stale: false, fetchedAt: "2026-11-16T00:00:00.000Z" }, { onlyClients: ["pi"], lifecycleLockDeps }, { fetchImpl: (async () => Response.json({ data: [{ id: "fixture/home-model" }] })) as typeof fetch }); if (applied?.outcomes.find(row => row.client === "pi")?.outcome !== "current") throw new Error("fixture apply failed"); @@ -73,6 +80,7 @@ async function main() { const replacement = await import("../../src/server/restart-replacement"); mock.module("../../src/server/restart-replacement", () => ({ ...replacement, spawnReplacementStart: async (request: { port: number }) => { spawned++; + enterPhase("binding the replacement listener"); // A successful bind proves the real Child listener released its port. No native coordinator, // provider request or external process participates in this replacement seam. const server = Bun.serve({ hostname: "127.0.0.1", port: request.port, fetch: () => Response.json({ role: "standalone" }) }); @@ -97,7 +105,7 @@ async function main() { const { startClientRuntime, scheduleStandaloneRecycle } = await import("../../src/client/runtime"); const { startMachineListener } = await import("../../src/client/machine-listener"); const { isAddrInUse } = await import("../../src/server/ports"); - phase = "starting the Child listener"; + enterPhase("starting the Child listener"); // Keep the selected port reserved while preparing the fixture and loading the runtime. await probe.stop(true); try { @@ -119,7 +127,7 @@ async function main() { } // The parent bounds setup; the existing phase watchdog starts only once the Child serves. setTimeout(() => { - console.error(`recovery fixture timed out (${options.mode}: ${phase})`); + console.error(`recovery fixture timed out 10s after listener startup (${options.mode}: ${phase})`); process.exit(1); }, 10_000).unref(); const pendingRecycle = options.mode === "signal-pending-recycle"; @@ -141,10 +149,12 @@ async function main() { [SYSTEM_RESTART_EXPECTED_PID_HEADER]: String(process.pid), [SYSTEM_RESTART_NONCE_HEADER]: nonce, [SYSTEM_RESTART_CAPABILITY_HEADER]: createSystemRestartCapability(runtime.attestationSecret!, nonce, "POST", SYSTEM_RESTART_PATH, process.pid, config.port), } }); - await response.arrayBuffer(); return response.status; + await response.arrayBuffer(); + if (response.status === 202) enterPhase("restart request accepted"); + return response.status; }; let finishStop: () => Promise = async () => {}; - phase = "observing the refused stop"; + enterPhase("observing the refused stop"); if (options.mode.startsWith("signal")) { // Queue and signal in one turn so the first timer is still pending at shutdown. if (pendingRecycle) { @@ -175,7 +185,7 @@ async function main() { } observations.beforeRecoveryAdmission = await restart(); observations.finishedMarker = readRuntimePort(process.pid)?.clientStopRequested; - phase = "disconnecting the Child"; + enterPhase("disconnecting the Child"); const { disconnectClient } = await import("../../src/client/connect"); await disconnectClient({ recoverConfig: true }, { lifecycleLockDeps }); const receiptPath = storePaths().disconnect; @@ -190,7 +200,7 @@ async function main() { if (options.mode === "missing-config") unlinkSync(join(home, "config.json")); if (options.mode === "new-connection") { config.client!.connectedAt = "2026-11-16T01:00:00.000Z"; saveConfig(config); } if (options.mode === "pending-connect") markClientConnectPending("b".repeat(64)); - phase = "observing restart or recycle after disconnect"; + enterPhase("observing restart or recycle after disconnect"); if (pendingRecycle) { observations.recoveryRecycleTimers = scheduleAndCountTimers(); if (observations.recoveryRecycleTimers === 0) { From 79e4b63894e522ea228132b783996deb1f325540 Mon Sep 17 00:00:00 2001 From: luvs01 <27862058+luvs01@users.noreply.github.com> Date: Fri, 20 Nov 2026 17:13:01 +0900 Subject: [PATCH 6/9] fix(link): defer periodic sync for a fenced listener generation --- src/client/runtime.ts | 10 +++-- src/client/sync-runtime.ts | 8 ++++ src/integrations/route-intent-tick.ts | 7 +++ structure/remote-link.md | 2 +- .../clients/route-intent-runtime-stop.test.ts | 21 ++++++++- tests/clients/route-intent-scheduler.test.ts | 45 +++++++++++++++++++ 6 files changed, 88 insertions(+), 5 deletions(-) diff --git a/src/client/runtime.ts b/src/client/runtime.ts index 23e03303673..0f1e50fe1ec 100644 --- a/src/client/runtime.ts +++ b/src/client/runtime.ts @@ -38,7 +38,7 @@ import { createLinkParityReporter, type LinkParityReporter } from "./link-parity import { restoreLinkClientRoutingBeforeExit } from "./stop-routing"; import { observeClientStopOwner } from "./stop-teardown-owner"; import { SUPERVISOR_MARKER_ENVS } from "../lib/supervisor-markers"; -import { markClientRuntimeStopping, markClientRuntimeStoppingWithRetry } from "./sync-runtime"; +import { isPublishedRuntimeStopping, markClientRuntimeStopping, markClientRuntimeStoppingWithRetry } from "./sync-runtime"; import { startRouteIntentTick, type RouteIntentTick } from "../integrations/route-intent-tick"; import { startRouteIntentWatch, type RouteIntentRuntimeWatch } from "./route-intent-watch"; import { runClientRecycleWithAdmission } from "./runtime-recycle"; @@ -431,13 +431,14 @@ export async function startClientRuntime( ...(supervisor ? { linkConnectionGeneration: () => supervisor.connectionGeneration() } : homeInitiated && link ? { linkConnectionGeneration: () => verifiedHomeConnection(link.linkId) } : {}), }, rollback === undefined ? io : { ...io, portWaitMs: rollback.portWaitMs, bindDeadlineAt: Date.now() + rollback.portWaitMs }); + const servingGeneration = randomUUID(); const publishRecord = (): void => { // A parent stop can arrive after restart admission. Never clear its fence on rollback; // a fresh process has another attestation identity and cannot inherit this request. if (rollback) observeExplicitStop(); writePid(process.pid); // A new generation refuses commits from syncs admitted before the failed restart. - writeRuntimePort({ ...clientRuntimeRecord(process.pid, boundPort, attestationSecret), servingGeneration: randomUUID(), + writeRuntimePort({ ...clientRuntimeRecord(process.pid, boundPort, attestationSecret), servingGeneration, clientLinkOwner }); }; const activate = (): void => { @@ -455,7 +456,10 @@ export async function startClientRuntime( if (linkMode && state.value.link && linkKey) { activeReporter = createLinkParityReporter({ connection: state.value, linkKey, runtimeStartedAt: CLIENT_RUNTIME_STARTED_AT }); activeReporter.start(); - const scheduler = startRouteIntentTick(state.value, { onApplied: () => activeReporter?.requestReport() }); + const scheduler = startRouteIntentTick(state.value, { + deferPeriodic: () => isPublishedRuntimeStopping({ pid: process.pid, port: boundPort, attestationSecret, servingGeneration }), + onApplied: () => activeReporter?.requestReport(), + }); activeRouteSync = scheduler; activeRouteWatch = startRouteIntentWatch(state.value, linkKey, { requestSync: () => scheduler.requestSync() }); } diff --git a/src/client/sync-runtime.ts b/src/client/sync-runtime.ts index 8aca45421ec..ab9500e0eeb 100644 --- a/src/client/sync-runtime.ts +++ b/src/client/sync-runtime.ts @@ -24,6 +24,14 @@ export function readSyncRuntime(): RuntimePortState | null { } catch { throw new ClientSyncRuntimeError("client_runtime_unverified"); } } +export function isPublishedRuntimeStopping( + expected: Required>, +): boolean { + const current = readSyncRuntime(); + return current?.clientStopping === true && current.pid === expected.pid && current.port === expected.port + && current.attestationSecret === expected.attestationSecret && current.servingGeneration === expected.servingGeneration; +} + /** Capture and recheck under C. Proven no-runtime sync keeps its existing offline behavior. */ export function clientSyncRuntimeGuard(): () => void { const expected = readSyncRuntime(); diff --git a/src/integrations/route-intent-tick.ts b/src/integrations/route-intent-tick.ts index 3469351c00f..69b2376bc88 100644 --- a/src/integrations/route-intent-tick.ts +++ b/src/integrations/route-intent-tick.ts @@ -3,6 +3,8 @@ import type { OcxClientConnectionConfig } from "../types"; export interface RouteIntentTickDeps { sync?: () => Promise; onApplied?: () => void | Promise; + /** True when this listener's stop fence already rules out a periodic apply. */ + deferPeriodic?: () => boolean; setTimer?: (callback: () => void, ms: number) => unknown; clearTimer?: (timer: unknown) => void; } @@ -32,6 +34,11 @@ export function startRouteIntentTick(connection: OcxClientConnectionConfig, deps do { queued = false; const batch = waiters.splice(0); + if (batch.length === 0 && deps.deferPeriodic) { + let deferred = false; + try { deferred = deps.deferPeriodic(); } catch { /* Let normal sync check uncertain state. */ } + if (deferred) { delay = 5_000; continue; } + } try { const result = await sync(); await deps.onApplied?.(); diff --git a/structure/remote-link.md b/structure/remote-link.md index 37b5a7583f0..19bb386e2ef 100644 --- a/structure/remote-link.md +++ b/structure/remote-link.md @@ -400,7 +400,7 @@ The authenticated `GET /v1/link-management/route-intent` is separate from the ma `src/server/index/route-intent-watch.ts` adds optional closed headers on that same GET: `x-ocx-route-intent-watch: 1` and an optional `x-ocx-route-intent-after` lowercase SHA-256 digest. A differing or absent digest returns immediately. A matching digest waits for a Home notification or at most 30 seconds, then repeats the listener's link-key admission against current policy (`serve-options.ts` passes a `readmit` callback; a key revoked during the wait is refused with 403 `link_key_required`), rechecks current link ownership and projects fresh policy. Successful reads advertise watch support in the same watch header; watch responses identify `changed`, `notified` or `timeout` in `x-ocx-route-intent-wake`. An unchanged timeout needs no apply, but an explicit notification and a changed digest still request sync. A peer without the new response header retains the previous conservative behavior. `src/link/route-intent-watch.ts` holds at most one waiter per link and 256 total in process memory; duplicate/capacity admission refuses, cancellation removes the waiter, and notification neither persists state nor acknowledges an apply. Home device mutations notify that link, default mutations notify every linked device, and Child-initiated explicit sync notifies an active waiter while returning `pending`; without a watcher it directs the caller to the Child or the next periodic tick. Conflict overwrite still requires explicit local Child authority. -`src/client/route-intent-watch.ts` exposes `startRouteIntentWatch(connection, key, { requestSync })` and `stop()`. Each GET uses the existing connection-bound relay, resolves a key getter afresh for rotation, pins the starting connection identity, refuses redirects and consumes at most 64 KiB with an 8 KiB response-header bound and a 40-second total read budget. A Home without watch support leaves reconciliation to the existing periodic tick. Failed reads retry after five seconds; immediately returning supported peers cannot create a tight loop. Watch notifications retain one pending apply while `requestSync` is busy and retry rejected applies. The runtime owner supplies the same serialized scheduler used by periodic sync, reports successful applies through the existing parity reporter, and stops the watcher with the runtime. Standalone recycle also stops the reporter, watch and tick before listener shutdown or replacement handoff; watch cancellation releases the outstanding Home read. The watch itself writes no client files or receipts and adds no Child-to-Home mutation endpoint. The periodic tick (`src/integrations/route-intent-tick.ts`) runs a full `syncConnectedClient` every 60 seconds even when nothing changed. Each apply first clears the Home proof record and writes a withdrawn receipt, because a failed or interrupted apply must not leave an earlier proof current, then rewrites both; unchanged writers make no client-file change, but the receipt and record are rewritten, and a parity report sent during that window carries the withdrawal until the next report. Avoiding the rewrite would mean knowing an apply changes nothing before running it, which the withdraw-first rule forbids. Native switches on a Child follow the Home: a local `ocx restore` is reverted by the next tick unless the person records `ocx route to codex off --local`. A tick can change the saved `selectedClients`, so `/api/machine/clients` reports the saved selection while it still belongs to the served connection (`src/client/machine-api.ts`). The tick does not restart the runtime after it applies changed Home Codex settings: the parity report keeps the runtime's real start time, so status shows that the runtime predates the apply, and `ocx sync` (or the Home fan-out) restarts it as before. +`src/client/route-intent-watch.ts` exposes `startRouteIntentWatch(connection, key, { requestSync })` and `stop()`. Each GET uses the existing connection-bound relay, resolves a key getter afresh for rotation, pins the starting connection identity, refuses redirects and consumes at most 64 KiB with an 8 KiB response-header bound and a 40-second total read budget. A Home without watch support leaves reconciliation to the existing periodic tick. A periodic tick defers for five seconds when its own published listener is marked stopping. Home-requested syncs still enter the normal queue and receive the result of the guarded sync. Failed reads retry after five seconds; immediately returning supported peers cannot create a tight loop. Watch notifications retain one pending apply while `requestSync` is busy and retry rejected applies. The runtime owner supplies the same serialized scheduler used by periodic sync, reports successful applies through the existing parity reporter, and stops the watcher with the runtime. Standalone recycle also stops the reporter, watch and tick before listener shutdown or replacement handoff; watch cancellation releases the outstanding Home read. The watch itself writes no client files or receipts and adds no Child-to-Home mutation endpoint. The periodic tick (`src/integrations/route-intent-tick.ts`) runs a full `syncConnectedClient` every 60 seconds even when nothing changed. Each apply first clears the Home proof record and writes a withdrawn receipt, because a failed or interrupted apply must not leave an earlier proof current, then rewrites both; unchanged writers make no client-file change, but the receipt and record are rewritten, and a parity report sent during that window carries the withdrawal until the next report. Avoiding the rewrite would mean knowing an apply changes nothing before running it, which the withdraw-first rule forbids. Native switches on a Child follow the Home: a local `ocx restore` is reverted by the next tick unless the person records `ocx route to codex off --local`. A tick can change the saved `selectedClients`, so `/api/machine/clients` reports the saved selection while it still belongs to the served connection (`src/client/machine-api.ts`). The tick does not restart the runtime after it applies changed Home Codex settings: the parity report keeps the runtime's real start time, so status shows that the runtime predates the apply, and `ocx sync` (or the Home fan-out) restarts it as before. The served roster a connected Child materializes from is the Home's own `GET /v1/models` list, so `loadConnectedRouteModels` (`src/integrations/route-intent-connected.ts`) reads each row's capability fields there — `capabilities.input_modalities`, `capabilities.context_length`/`max_output_tokens`, `supports_reasoning`, `supports_thinking_toggle`, `supports_reasoning_effort`, `default_thinking_enabled`, the `reasoning_effort` ladder (bare values or Grok's `{value, default}` options) and the top-level `context_window`/`context_length`/`max_output_tokens` mirrors — and maps them into `ExportModel`, the same projection `toExportModel` makes for `/api/models`. The row is remote input, so every value is validated: an integer window, a boolean axis, a modality from the exporters' vocabulary or a declared effort, with malformed entries dropped individually and nothing synthesized for a field the row omits. Without this the file integrations a Child materializes from Home intent (Pi, OpenCode and the rest) fell back to text-only with no reasoning controls. Fields the served row does not carry — `maxInputTokens`, `supports_reasoning_summaries` and `supports_tools` — stay absent and the exporters apply their own rules. The Grok adapter carries the ladder and its declared default into the Grok config, and the Desktop adapter passes each routed window, which decides `supports1m`. A combo row the route catalog does not list is accepted only as an expanded selector of a listed one, `--fast` or `--` as the Home's `/v1/models` publishes them, and takes that base's canonical key; an expanded selector whose base is unlisted is left out on its own, while any other unlisted combo still rejects the roster. Coverage: `tests/clients/route-intent-connected-capabilities.test.ts`. diff --git a/tests/clients/route-intent-runtime-stop.test.ts b/tests/clients/route-intent-runtime-stop.test.ts index c1221259f41..e68820f96b3 100644 --- a/tests/clients/route-intent-runtime-stop.test.ts +++ b/tests/clients/route-intent-runtime-stop.test.ts @@ -13,7 +13,7 @@ test("runtime recycle cancels its watch and tick before replacement handoff", () writeFileSync(fixture, ` import { test, expect, spyOn } from 'bun:test'; test('isolated recycle', async () => { - const { writeFileSync } = await import('node:fs'); + const { readFileSync, writeFileSync, unlinkSync } = await import('node:fs'); const { join } = await import('node:path'); const configApi = await import(${JSON.stringify(repoPath("src/config.ts"))}); const { serviceApiTokenFingerprint } = await import(${JSON.stringify(repoPath("src/lib/service-secrets.ts"))}); @@ -58,6 +58,25 @@ test("runtime recycle cancels its watch and tick before replacement handoff", () }})}); for(let i=0;i<100&&!active;i++)await Bun.sleep(5); expect(active).toBe(true); + const deferPeriodic = tick.mock.calls[0][1].deferPeriodic; + const file = join(process.env.OPENCODEX_HOME, 'runtime-port.json'); + const original = readFileSync(file); + const published = JSON.parse(original.toString()); + const stopping = { ...published, clientStopping: true }; + try { + expect(deferPeriodic()).toBe(false); + writeFileSync(file, JSON.stringify(stopping)); + expect(deferPeriodic()).toBe(true); + for (const change of [{ pid: published.pid + 1 }, { port: port === 1 ? 2 : 1 }, + { attestationSecret: 'A'.repeat(43) }, { servingGeneration: 'other' }, { servingGeneration: undefined }]) { + writeFileSync(file, JSON.stringify({ ...stopping, ...change })); + expect(deferPeriodic()).toBe(false); + } + writeFileSync(file, '{'); + expect(deferPeriodic).toThrow('client_runtime_unverified'); + unlinkSync(file); + expect(deferPeriodic()).toBe(false); + } finally { writeFileSync(file, original); } expect(clearClientConnection(config.client)).toBe('committed'); await runtime.recycleStandalone(serviceApiTokenFingerprint(token), { isDesktopSupervised:()=>false, diff --git a/tests/clients/route-intent-scheduler.test.ts b/tests/clients/route-intent-scheduler.test.ts index 7e98bb09103..2df566bcdc7 100644 --- a/tests/clients/route-intent-scheduler.test.ts +++ b/tests/clients/route-intent-scheduler.test.ts @@ -42,6 +42,51 @@ test("busy applies reject the request and retry on the short cadence without ove scheduler.stop(); }); +test("a retained stop defers periodic sync while Home requests keep their original result", async () => { + const timers: Array<{ run: () => void; ms: number }> = []; + let fenced = true, checks = 0, calls = 0, reports = 0; + const refusal = new Error("link_apply_busy"); + const scheduler = startRouteIntentTick(connection, { + deferPeriodic: () => { checks++; return fenced; }, + sync: async () => { calls++; if (fenced) throw refusal; }, + onApplied: () => { reports++; }, + setTimer: (run, ms) => { const timer = { run, ms }; timers.push(timer); return timer; }, + clearTimer: timer => { const i = timers.findIndex(entry => entry === timer); if (i >= 0) timers.splice(i, 1); }, + }); + const first = timers.shift()!; + expect(first.ms).toBe(2_000); + first.run(); await flush(); + expect([checks, calls, reports]).toEqual([1, 0, 0]); + expect(timers.map(timer => timer.ms)).toEqual([5_000]); + + await expect(scheduler.requestSync()).rejects.toBe(refusal); + await flush(); + expect([checks, calls, reports]).toEqual([1, 1, 0]); + expect(timers.map(timer => timer.ms)).toEqual([5_000]); + + fenced = false; + timers.shift()!.run(); await flush(); + expect([checks, calls, reports]).toEqual([2, 2, 1]); + expect(timers.map(timer => timer.ms)).toEqual([60_000]); + scheduler.stop(); + expect(timers).toHaveLength(0); +}); + +test("an inconclusive periodic fence check falls through to sync", async () => { + const timers: Array<{ run: () => void; ms: number }> = []; + let calls = 0, reports = 0; + const scheduler = startRouteIntentTick(connection, { + deferPeriodic: () => { throw new Error("runtime record unavailable"); }, + sync: async () => { calls++; }, + onApplied: () => { reports++; }, + setTimer: (run, ms) => { timers.push({ run, ms }); return timers.length; }, clearTimer: () => {}, + }); + timers.shift()!.run(); await flush(); + expect([calls, reports]).toEqual([1, 1]); + expect(timers.map(timer => timer.ms)).toEqual([60_000]); + scheduler.stop(); +}); + test("machine clients reports the saved selection a scheduled sync changed, only for the served connection", async () => { const { handleMachineApi } = await import("../../src/client/machine-api"); const state = { serverUrl: "http://127.0.0.1:22001", managementUrl: "http://127.0.0.1:22001", managementTransport: "direct" as const, From 456946c5f2386dc73e22cd7caac68eb5a20ad149 Mon Sep 17 00:00:00 2001 From: luvs01 <27862058+luvs01@users.noreply.github.com> Date: Fri, 20 Nov 2026 17:28:02 +0900 Subject: [PATCH 7/9] test(link): bind the scheduler to the generation stamped at publication --- src/client/runtime.ts | 3 ++- tests/cli/cli-client-start-fence.test.ts | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/src/client/runtime.ts b/src/client/runtime.ts index 0f1e50fe1ec..ace5c261520 100644 --- a/src/client/runtime.ts +++ b/src/client/runtime.ts @@ -431,13 +431,14 @@ export async function startClientRuntime( ...(supervisor ? { linkConnectionGeneration: () => supervisor.connectionGeneration() } : homeInitiated && link ? { linkConnectionGeneration: () => verifiedHomeConnection(link.linkId) } : {}), }, rollback === undefined ? io : { ...io, portWaitMs: rollback.portWaitMs, bindDeadlineAt: Date.now() + rollback.portWaitMs }); - const servingGeneration = randomUUID(); + let servingGeneration: string; const publishRecord = (): void => { // A parent stop can arrive after restart admission. Never clear its fence on rollback; // a fresh process has another attestation identity and cannot inherit this request. if (rollback) observeExplicitStop(); writePid(process.pid); // A new generation refuses commits from syncs admitted before the failed restart. + servingGeneration = randomUUID(); writeRuntimePort({ ...clientRuntimeRecord(process.pid, boundPort, attestationSecret), servingGeneration, clientLinkOwner }); }; diff --git a/tests/cli/cli-client-start-fence.test.ts b/tests/cli/cli-client-start-fence.test.ts index 59902fa4319..872ca1ce09d 100644 --- a/tests/cli/cli-client-start-fence.test.ts +++ b/tests/cli/cli-client-start-fence.test.ts @@ -141,7 +141,7 @@ describe("connected-client start ownership fence", () => { // released only once the first serve() returned, i.e. after publication. const serve = runtime.slice(runtime.indexOf("const serve = async"), runtime.indexOf("const stopServing")); // Each publication also stamps a fresh servingGeneration (restart sync fence, #8416). - expect(serve).toMatch(/writePid\(process\.pid\);\s*\n(?:\s*\/\/[^\n]*\n)*\s*writeRuntimePort\(\{ \.\.\.clientRuntimeRecord\(process\.pid, boundPort, attestationSecret\), servingGeneration: randomUUID\(\),\s+clientLinkOwner \}\);/); + expect(serve).toMatch(/writePid\(process\.pid\);\s*\n(?:\s*\/\/[^\n]*\n)*\s*servingGeneration = randomUUID\(\);\s*writeRuntimePort\(\{ \.\.\.clientRuntimeRecord\(process\.pid, boundPort, attestationSecret\), servingGeneration,\s+clientLinkOwner \}\);/); expect(runtime).toMatch(/await serve\(\);\s*\n\s*options\.afterPublish\?\.\(\);/); }); }); From 2d3a18a50de7aef0318fe5677dc9fdc165c5f0c1 Mon Sep 17 00:00:00 2001 From: luvs01 <27862058+luvs01@users.noreply.github.com> Date: Sat, 21 Nov 2026 12:03:10 +0900 Subject: [PATCH 8/9] test(link): isolate stop fixtures from other services and client profiles --- .../clients/client-link-stop-recovery.test.ts | 21 +++++++++++++++++-- .../client-link-stop-recovery-runner.ts | 6 ++++-- tests/fixtures/client-link-stop-runner.ts | 8 ++++--- tests/helpers/client-link-stop.ts | 5 ++--- tests/helpers/client-stop-fixture-home.ts | 15 +++++++++++++ 5 files changed, 45 insertions(+), 10 deletions(-) create mode 100644 tests/helpers/client-stop-fixture-home.ts diff --git a/tests/clients/client-link-stop-recovery.test.ts b/tests/clients/client-link-stop-recovery.test.ts index f8de44e8c28..8cab87d947f 100644 --- a/tests/clients/client-link-stop-recovery.test.ts +++ b/tests/clients/client-link-stop-recovery.test.ts @@ -5,13 +5,30 @@ import { join } from "node:path"; import { fixturePath, repoPath } from "../helpers/repo-root"; import { removeTreeWithRetry } from "../helpers/remove-tree"; import { runStop } from "../helpers/client-link-stop"; +import { stopFixtureEnv, unavailableFixtureHome } from "../helpers/client-stop-fixture-home"; + +test("stop fixtures keep Home traffic and integration state separate across children", async () => { + const first = unavailableFixtureHome(), second = unavailableFixtureHome(); + try { + expect(first.port).not.toBe(second.port); + for (const home of [first, second]) { + expect(home.url.hostname).toBe("127.0.0.1"); + expect((await fetch(home.url)).status).toBe(503); + } + const root = join(tmpdir(), "fixture-child"); + const inherited = { ...process.env, GROK_HOME: "suite-grok", CLAUDE_CONFIG_DIR: "suite-claude", + XDG_CONFIG_HOME: "suite-config", OCX_OWNER_REGISTRY_DIR: "suite-registry", OCX_SERVICE: "1" }; + expect(stopFixtureEnv(root, inherited)).toMatchObject({ GROK_HOME: join(root, ".grok"), + CLAUDE_CONFIG_DIR: join(root, ".claude"), XDG_CONFIG_HOME: join(root, ".config"), + OCX_OWNER_REGISTRY_DIR: join(root, "ocx", "ocx-homes"), OCX_SERVICE: "" }); + } finally { await Promise.all([first.stop(true), second.stop(true)]); } +}); async function runRecovery(mode: string, scheduled = false, env = process.env, attempt = 0): Promise> { const root = mkdtempSync(join(tmpdir(), "ocx-link-stop-recovery-")); const child = Bun.spawn([process.execPath, fixturePath("client-link-stop-recovery-runner.ts")], { cwd: repoPath(), stdin: new Blob([JSON.stringify({ mode, scheduled })]), stdout: "pipe", stderr: "pipe", - env: { ...env, HOME: root, USERPROFILE: root, OPENCODEX_HOME: join(root, "ocx"), CODEX_HOME: join(root, "codex"), - OPENCODEX_CLAUDE_DESKTOP_CONFIG_DIR: join(root, "claude-desktop"), OCX_SERVICE: "", OCX_SERVICE_MANAGED: "0" }, + env: stopFixtureEnv(root, env), }); let parentDeadlineReached = false; const timeout = setTimeout(() => { diff --git a/tests/fixtures/client-link-stop-recovery-runner.ts b/tests/fixtures/client-link-stop-recovery-runner.ts index ce6e725f61f..68238320662 100644 --- a/tests/fixtures/client-link-stop-recovery-runner.ts +++ b/tests/fixtures/client-link-stop-recovery-runner.ts @@ -2,6 +2,7 @@ import { mock, spyOn } from "bun:test"; import { mkdirSync, readFileSync, unlinkSync, writeFileSync, writeSync } from "node:fs"; import { dirname, join } from "node:path"; +import { unavailableFixtureHome } from "../helpers/client-stop-fixture-home"; import { getDefaultConfig, saveConfig } from "../../src/config"; import { serviceApiTokenFingerprint, writeServiceApiTokenFile, readServiceApiTokenState } from "../../src/lib/service-secrets"; import { readRuntimePort, type ClientStopOwner } from "../../src/config/process-state"; @@ -33,10 +34,11 @@ mock.module("../../src/client/lifecycle-lock", () => ({ ...lifecycle, async function main() { const token = `ocx_data_${"c".repeat(40)}`; const probe = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch: () => new Response(null) }); + const fixtureHome = unavailableFixtureHome(); const config = getDefaultConfig(); config.port = probe.port!; config.runtimeRole = "client"; - config.client = { serverUrl: "http://127.0.0.1:34567", managementUrl: "http://127.0.0.1:34567", managementTransport: "direct", transport: "link", - link: { tunnelPort: 34567, linkId: "lnk_0123456789abcdef" }, selectedClients: ["pi"], tokenEnv: "OPENCODEX_API_AUTH_TOKEN", + config.client = { serverUrl: fixtureHome.url.origin, managementUrl: fixtureHome.url.origin, managementTransport: "direct", transport: "link", + link: { tunnelPort: fixtureHome.port!, linkId: "lnk_0123456789abcdef" }, selectedClients: ["pi"], tokenEnv: "OPENCODEX_API_AUTH_TOKEN", apiKeyId: "fixture-client", tokenFingerprint: serviceApiTokenFingerprint(token), protocolVersion: 1, connectedAt: "2026-10-01T00:00:00.000Z" }; saveConfig(config); writeServiceApiTokenFile(token); const expected = structuredClone(config.client); diff --git a/tests/fixtures/client-link-stop-runner.ts b/tests/fixtures/client-link-stop-runner.ts index c442f767b4d..0f55b317e81 100644 --- a/tests/fixtures/client-link-stop-runner.ts +++ b/tests/fixtures/client-link-stop-runner.ts @@ -3,6 +3,7 @@ import { mock } from "bun:test"; import { Database } from "bun:sqlite"; import { existsSync, mkdirSync, readFileSync, statSync, symlinkSync, unlinkSync, writeFileSync } from "node:fs"; import { dirname, join } from "node:path"; +import { unavailableFixtureHome } from "../helpers/client-stop-fixture-home"; import { getDefaultConfig, prepareConfigMutationDatabasePathForWrite, saveConfig } from "../../src/config"; import { CODEX_CONFIG_PATH, CODEX_HOME, CODEX_PROFILE_PATH, DEFAULT_CATALOG_PATH } from "../../src/codex/paths"; import { JOURNAL_PATH, markJournalInjectedState, writeJournal } from "../../src/codex/journal"; @@ -73,14 +74,15 @@ mock.module("../../src/client/lifecycle-lock", () => ({ ...lifecycle, const token = `ocx_data_${"c".repeat(40)}`; const config = getDefaultConfig(); const probe = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch: () => new Response(null) }); +const fixtureHome = options.transport === "hub" ? undefined : unavailableFixtureHome(); config.port = probe.port!; await probe.stop(true); config.runtimeRole = "client"; config.client = { - serverUrl: options.transport === "hub" ? "https://hub.example.test" : "http://127.0.0.1:34567", - managementUrl: options.transport === "hub" ? "https://hub.example.test" : "http://127.0.0.1:34567", + serverUrl: fixtureHome?.url.origin ?? "https://hub.example.test", + managementUrl: fixtureHome?.url.origin ?? "https://hub.example.test", managementTransport: "direct", transport: options.transport ?? "link", - ...(options.transport === "hub" ? {} : { link: { tunnelPort: 34567, linkId: "lnk_0123456789abcdef" } }), + ...(fixtureHome ? { link: { tunnelPort: fixtureHome.port!, linkId: "lnk_0123456789abcdef" } } : {}), selectedClients: ["codex", ...(options.deferFileApply ? [] : options.fileClients ?? [])], tokenEnv: "OPENCODEX_API_AUTH_TOKEN", apiKeyId: "fixture-client", tokenFingerprint: serviceApiTokenFingerprint(token), protocolVersion: 1, connectedAt: "2026-10-01T00:00:00.000Z", }; diff --git a/tests/helpers/client-link-stop.ts b/tests/helpers/client-link-stop.ts index 3559a871037..bc4084fe100 100644 --- a/tests/helpers/client-link-stop.ts +++ b/tests/helpers/client-link-stop.ts @@ -4,13 +4,12 @@ import { tmpdir } from "node:os"; import { dirname, join } from "node:path"; import { fixturePath, repoPath } from "./repo-root"; import { removeTreeWithRetry } from "./remove-tree"; +import { stopFixtureEnv } from "./client-stop-fixture-home"; export async function runStop(options: Record) { const root = mkdtempSync(join(tmpdir(), "ocx-link-stop-")); const home = join(root, "ocx"); - const env = { ...process.env, HOME: root, USERPROFILE: root, OPENCODEX_HOME: home, - CODEX_HOME: join(root, "codex"), OPENCODEX_CLAUDE_DESKTOP_CONFIG_DIR: join(root, "claude-desktop"), - OCX_SERVICE: "", OCX_SERVICE_MANAGED: "0" }; + const env = stopFixtureEnv(root); let owner: Bun.Subprocess<"pipe", "pipe", "ignore"> | undefined; let child: Bun.Subprocess | undefined; const timeout = setTimeout(() => { diff --git a/tests/helpers/client-stop-fixture-home.ts b/tests/helpers/client-stop-fixture-home.ts new file mode 100644 index 00000000000..ce6cb4cdf70 --- /dev/null +++ b/tests/helpers/client-stop-fixture-home.ts @@ -0,0 +1,15 @@ +import { join } from "node:path"; + +export function stopFixtureEnv(root: string, inherited = process.env) { + return { ...inherited, HOME: root, USERPROFILE: root, OPENCODEX_HOME: join(root, "ocx"), CODEX_HOME: join(root, "codex"), + OPENCODEX_CLAUDE_DESKTOP_CONFIG_DIR: join(root, "claude-desktop"), CLAUDE_CONFIG_DIR: join(root, ".claude"), + GROK_HOME: join(root, ".grok"), XDG_CONFIG_HOME: join(root, ".config"), OCX_OWNER_REGISTRY_DIR: join(root, "ocx", "ocx-homes"), + OCX_SERVICE: "", OCX_SERVICE_MANAGED: "0" }; +} + +export function unavailableFixtureHome() { + const home = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch: () => new Response(null, { status: 503 }) }); + // Runtime watch requests stay inside this fixture. The Home must not keep its child process alive. + home.unref(); + return home; +} From 8de1bcf3edd8859724bd8e7b8b7ae98be1d08617 Mon Sep 17 00:00:00 2001 From: luvs01 <27862058+luvs01@users.noreply.github.com> Date: Sat, 21 Nov 2026 13:43:00 +0900 Subject: [PATCH 9/9] test(link): keep unreadable process identities unverified The recovery fixture now sends a missing creation-time sample through the same ownership decision used by normal samples. A missing identity must keep recovery fenced. A matching or mismatching observed identity retains its old result. Windows x64 with Bun 1.4.4: five isolated decisions checked before and after, and typecheck passed. The parent-unverified integration fixture reached its unchanged 15-second parent deadline during file-route setup, before the observer ran. Its Windows integration result remains open. --- tests/fixtures/client-link-stop-recovery-runner.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/tests/fixtures/client-link-stop-recovery-runner.ts b/tests/fixtures/client-link-stop-recovery-runner.ts index 68238320662..1ecdac7d906 100644 --- a/tests/fixtures/client-link-stop-recovery-runner.ts +++ b/tests/fixtures/client-link-stop-recovery-runner.ts @@ -99,9 +99,10 @@ async function main() { const observeOwner = owner.observeClientStopOwner; mock.module("../../src/client/stop-teardown-owner", () => ({ ...owner, observeClientStopOwner: (proof: ClientStopOwner) => { - if (options.mode === "parent-unverified") return "unverified"; if (proof.nonce === "malformed" || proof.startTime === "malformed") return observeOwner(proof); - return owner.readClientStopProcessStart(proof.pid) === proof.startTime ? "active" : "confirmed-stale"; + const observedStart = options.mode === "parent-unverified" ? undefined : owner.readClientStopProcessStart(proof.pid); + if (observedStart === undefined) return "unverified"; + return observedStart === proof.startTime ? "active" : "confirmed-stale"; }, })); const { startClientRuntime, scheduleStandaloneRecycle } = await import("../../src/client/runtime");