diff --git a/.github/scripts/binary-build-order.test.cjs b/.github/scripts/binary-build-order.test.cjs index 2b61b5f944..c7edd8d7f9 100644 --- a/.github/scripts/binary-build-order.test.cjs +++ b/.github/scripts/binary-build-order.test.cjs @@ -32,7 +32,7 @@ test("PR builds and both release channels share the ordering without bypassing P assert.equal(workflow("release.yml").jobs.release.uses, "./.github/workflows/reusable-release.yml") assert.deepEqual(pr.needs, [ "authorize", "tests", "tests-browser", "tests-tauri-windows", "tests-opencode-compatibility", - "tests-session-pruning-native", "tests-runtime-contracts", "tests-tauri-macos", + "tests-session-pruning-native", "tests-runtime-contracts", "tests-tauri-macos", "tests-tauri-webkit", ]) assert.equal(pr.with.upload, false) assert.equal(pr.with.set_versions, false) diff --git a/.github/workflows/pr-build.yml b/.github/workflows/pr-build.yml index ef22dc9a77..15cb8c1fa9 100644 --- a/.github/workflows/pr-build.yml +++ b/.github/workflows/pr-build.yml @@ -508,6 +508,7 @@ jobs: packages/ui/src/stores/mission-task-pages.test.ts packages/ui/src/stores/mission-task-seen.test.ts packages/ui/tests/contracts/mission-task-page-read.test.ts + packages/ui/tests/contracts/mission-defaults.test.ts packages/ui/src/lib/native/preferences-window.test.ts packages/ui/src/components/mission-briefing-locales.test.ts packages/ui/src/components/mission-briefing-model.test.ts diff --git a/.opencode/skills/codenomad-missions/SKILL.md b/.opencode/skills/codenomad-missions/SKILL.md index 254a952194..646074deed 100644 --- a/.opencode/skills/codenomad-missions/SKILL.md +++ b/.opencode/skills/codenomad-missions/SKILL.md @@ -16,9 +16,11 @@ Prefer ordinary native delegation for bounded work. Use a mission only when the 7. Finish through `mission.report({ final: true, ... })` only when the objective is actually met. Retired work never counts as success; retiring does not interrupt admitted native execution, which can finish on its own or be stopped with `mission.interrupt` when eligible; playbook proof requirements still apply. A retired native task takes no coordinator readout; record what it returned under its replacement or in the final report. Admitted retired work settles through its actor's terminal report or an observed native end. Use `mission.inspect({ catalog: true })` before selecting a native execution profile. +Follow the [creation and retry discipline](../../../dev-docs/MISSIONS.md#mission-profile-selection-and-creation-recovery). + The mission `role` is independent of `execution.agent`. To pin execution, pass `execution: { agent: "catalog-agent-id", model: { providerID: "catalog-provider", id: "catalog-model", variant: "optional-catalog-variant" } }`. -Repeat the same selection when retrying a task. Omitted fields use native defaults. +Repeat the same selection when retrying a task. Omitted task execution fields use native defaults. Native tasks accept subagent/all agents; independent roots and tasks stored without an execution mode accept primary/all agents. Each child owns its bounded assignment and may recursively decompose independent subtasks when useful, integrating actual returned diff --git a/dev-docs/BROWSER_AUTOMATION.md b/dev-docs/BROWSER_AUTOMATION.md index 9a98958e39..17a1c4cc01 100644 --- a/dev-docs/BROWSER_AUTOMATION.md +++ b/dev-docs/BROWSER_AUTOMATION.md @@ -18,6 +18,18 @@ Browser previews are an ordinary desktop feature and must work in user projects The bridge is loopback-only, token-authenticated, bounded, and session-location gated. +An active backend publishes an ephemeral registration with a per-process 256-bit +token and removes it on graceful shutdown. All bridge discovery checks the +filename's publishing PID before reading the file: PIDs outside 1–2³¹−1 and +`ESRCH` establish absence; other process-probe errors retain liveness +conservatively. Best-effort pruning removes recognized local registrations whose +filename or parsed PID establishes absence. A file removed between enumeration +and open is absent. Windows PIDs belong to their host namespace, so WSL discovery +uses endpoint evidence for Windows registrations and leaves their files in place. +Windows path lookup is asynchronous, shares an in-flight lookup for the effective +distro/PATH, and ordinary discovery retains its cached result. Missions' strict +ownership and retry rules are in the [creation recovery contract](MISSIONS.md#mission-profile-selection-and-creation-recovery). + ## Desktop instrumentation At normal startup, native instrumentation prepares the current CodeNomad desktop process for agent feedback. It never launches or owns another CodeNomad process and never starts, stops or replaces the shared OpenCode daemon. @@ -36,7 +48,7 @@ Windows Tauri (`packages/tauri-app/src-tauri/src/developer_mode.rs`): Packaged Electron main/preload/renderer, UI and server builds emit source maps. Local hosts sanitize inherited debugging flags; isolated remote-window profiles run without local instrumentation. Windows WebView2 is the supported Tauri CDP host. `packages/server/src/developer-cdp.ts` (`DeveloperCdp`) is the shared CDP controller and `opencode/automation-plugin.ts` the OpenCode adapter. `.opencode/skills/codenomad-automation/SKILL.md` holds the inspect, edit, build, relaunch, reconnect and evidence workflow. -An active backend publishes an ephemeral registration with a per-process 256-bit token and removes it on graceful shutdown. Tool definitions captured earlier still go through execution-time checks, which refuse calls after backend shutdown or when the inspected native window, run or document changed; selecting another project or conversation keeps them valid. A WSL OpenCode plugin also discovers Windows registrations and reaches the Windows-only loopback listener through Windows interop under default WSL2 NAT. Provisioning migrates only recognizable generated entries and never overwrites a user-authored plugin. +Tool definitions captured earlier still go through execution-time checks, which refuse calls after backend shutdown or when the inspected native window, run or document changed; selecting another project or conversation keeps them valid. A WSL OpenCode plugin also discovers the Windows registration directory and reaches the Windows-only loopback listener through Windows interop under default WSL2 NAT. Its `curl.exe` requests use `--noproxy "*"` to bypass inherited proxies for that authenticated loopback endpoint. Provisioning migrates only recognizable generated entries and never overwrites a user-authored plugin. Windows registry-path discovery in WSL uses asynchronous interop with bounded commands. Memory admission cancellation reaches both discovery commands and registry scans; diff --git a/dev-docs/MISSIONS.md b/dev-docs/MISSIONS.md index 5a048c610f..5b1bb1ab55 100644 --- a/dev-docs/MISSIONS.md +++ b/dev-docs/MISSIONS.md @@ -131,13 +131,12 @@ refuse otherwise. Only one-time coordinators are offered and told about honestly, and an empty result notes that only canonical assignments are visible. - `mission.prepare` creates a paused one-time hand-off through the same `prepareMissionCreation` pipeline, holds and fences as the editor, at the - coordinator's Location. It never starts. The trusted `preparedBy` + coordinator's Location. The user starts it with Play. The trusted `preparedBy` (`{ missionId, coordinatorSessionId }`) gives that coordinator read-only - visibility (`inspect({ missionID })`, `inspect({ list: true })`), never control. - The requestID is scoped to the coordinator and mission. A retry first reads the - journal's creation event and returns the saved mission (or a conflict) without - another backend call; a held uncertain attempt is reported uncertain, never as - nothing created. + visibility (`inspect({ missionID })`, `inspect({ list: true })`). An active + one-time coordinator can prepare hand-offs; a caller outside an active mission + receives `mission-not-found` with guidance to use the Missions editor. Follow + the [creation and retry discipline](#mission-profile-selection-and-creation-recovery). The human-answer gate's `discover` finds fresh children of the expected parent whose `subagent` call carried the exact assignment prompt, and the coordinator's @@ -158,6 +157,119 @@ candidates from free text, titles or timing. different summary when the latest automatic briefing is still the last event. One replacement task may merge several retired tasks; it names one of them in `replacesTaskKey`. +## Mission profile selection and creation recovery + +Both `mission.prepare` and `mission.inspect({ start })` resolve omitted +coordinator/role profiles and `taskMode` from the owning CodeNomad backend's +`ui.settings.missionProfileDefaults`. The editor and server share +`missions/profile-defaults.ts` and `freezeCompareProfiles`: a playbook's slot +overrides the global `all` slot; the global `specialist` supplies task roles, +with the Compare judge using the coordinator's model by default. Each supplied +profile slot wins whole, including `{}` (OpenCode defaults) or an agent-only +profile; `profiles: {}` leaves every slot eligible for preferences. After slot +selection, Compare fills any missing judge model from the known coordinator +model through `freezeCompareProfiles`, including explicit/preference `{}` or +agent-only slots; a judge's own model stays unchanged. An explicit `taskMode` +wins over the playbook preference, then the global preference; the final fallback +is `native`. Missing profile preferences fall back to OpenCode defaults. +Supplying the coordinator, every exact role of the selected template and +`taskMode` skips backend preferences entirely; `{}` counts as an explicit profile +slot. All origins are `explicit`, and preference availability stays unobserved. +Partial or omitted selections read the owning backend's preferences. + +Preparation tool replies and inspections with creation metadata expose +`selection: { profiles, taskMode, origins }`: the saved coordinator and every +role of the selected playbook, plus origins `explicit`, `preference` or +`opencode-default` for the coordinator, each role and task mode. The journal, +document and authoritative backend snapshot retain `creationDefaults`, including +the original request, for replay; tool replies project that metadata only as +`selection`. A chosen Compare judge slot retains its explicit/preference origin +even when its model is inherited; an absent judge slot inherits the coordinator's +origin. These are saved requested selectors; catalog validation and native +execution checks establish availability and actual execution separately. +`inspect({ start })` uses the caller as coordinator and requires its existing +native profile to match the resolved coordinator selection. A mismatch whose +coordinator origin is `preference` advises passing `profiles.coordinator` +(for example `{}`) to override that preference; the existing native-profile +check still applies. An explicit-profile mismatch keeps the generic +native-profile error. + +`inspect({ start })` reads preferences before entering the project mutation +lane. Admission rereads creation events and document defaults under that lane; +already recorded choices win over concurrent preference results. Document-mode +replay rechecks the coordinator Location and original creation digest. + +When preferences are needed, with no bridge presence or zero proven owning +backends, `inspect({ start })` uses explicit inputs and OpenCode defaults for +omitted choices (`native` task-mode fallback), with origins `explicit` or +`opencode-default` and `selection.preferences: "unavailable"`. The saved metadata +retains that warning on retries, including after a backend appears. Multiple +owning backends, failed or incomplete backend discovery, or an unreadable +preference document return `mission-preferences-unavailable`; invalid preferences +return `mission-preferences-invalid`. Restore backend discovery and session +ownership, then reload preferences, or supply fully explicit choices. + +Strict discovery follows the shared [registration liveness and pruning rules](BROWSER_AUTOMATION.md#integration-and-shared-bridge). +Unreadable registrations with a live or indeterminate local publisher retain +indeterminate ownership and refuse resolution. WSL skips unparseable Windows +registrations (unsupported schemas, oversized files and invalid URLs): they offer +no usable authenticated endpoint or supported contract. Valid Windows +registrations require endpoint evidence. A refused +connection establishes absence; timeouts and HTTP/authentication failures leave +ownership indeterminate. A typed missing-session reply, an empty backend workspace +inventory or a successful ownership read proving an unrelated project establishes +non-ownership, including with other workspaces open. Actual Git/WSL ownership-read +failures remain indeterminate and refuse resolution. + +Missing Windows interop executables (`ENOENT`/`ENOEXEC` from `cmd.exe` or +`wslpath`) establish absence of reachable Windows backends for that WSL process; +local discovery continues. Timeouts, failed commands and uncertain path results +refuse strict discovery. Strict requests retry failed path lookups after two +seconds. Legacy backends without +negative ownership proof or preference-command support return +`mission-preferences-update-required`: update CodeNomad before inheriting defaults. +A live backend's preferences stay protected by this refusal. + +`mission.prepare` requires an owning backend for fenced creation even when profile +resolution can use the no-owner fallback. Fully explicit choices make no preference +request; preparation still requires its owning backend. Before sending creation +provenance, preparation requires the backend's positive `missionCreationDefaults` +capability. Missing support returns the update-required refusal before dispatch +and releases only newly reserved choices; previous uncertain outcomes remain retained. + +The requestID is scoped to the coordinator and mission. Preparations with the +same requestID are serialized. Reuse that requestID and the original inputs: +a retry first reads the saved creation event/document and returns the saved +mission or a conflict. `mission.prepare` alone reserves a standalone durable +pre-dispatch intent for the chosen profiles, task mode and origins across +uncertain attempts, preference changes and restarts. `inspect({ start })` +retains its choices through its journal/document receipt under the native +invocation identity. + +A positive preparation result or a definitive refusal proving that the attempt +had no effect releases its retained choices. An unknown outcome keeps them; a +retry refused during prevalidation leaves the preceding attempt's uncertainty +intact. At most 128 unknown preparation choices are retained per project, each +for 24 hours from its first reservation; retries preserve that deadline. At +capacity, retry the original requestIDs to recover completed preparations and +release their slots, or wait for their 24-hour retention to expire. + +Capacity scans skip unreadable intent entries while preserving their bytes. +Retrying that exact requestID still refuses unreadable evidence, preventing +replay of a possibly dispatched preparation; unrelated requests remain usable. + +A clock rollback keeps future-dated intents fresh until their stored creation +time has aged through the retention window; retries reuse their saved choices. + +After expiry, preferences may be read anew only when the creation event and +document are both absent. A positive receipt or saved document keeps its +choices frozen. Expiry affects retained choices alone; native holds and +authorization keep their own settlement rules. Check the mission and original +conversation before choosing a new requestID for an uncertain outcome. Never +duplicate uncertain work or resume automatically after expiry. Never create an +intermediate mission solely to access `mission.prepare`. A held uncertain attempt +is reported uncertain. + ## Human questions and decisions Only the coordinator talks to the human. Every assignment prompt and helper policy diff --git a/dev-docs/WORKTREE_SESSION_PLACEMENT.md b/dev-docs/WORKTREE_SESSION_PLACEMENT.md index f7af018fd1..51f93d2049 100644 --- a/dev-docs/WORKTREE_SESSION_PLACEMENT.md +++ b/dev-docs/WORKTREE_SESSION_PLACEMENT.md @@ -174,7 +174,9 @@ authorized workspace spelling before changing UI state. ## Agent conventions +- Preference authority probes use `ownsLocation(id, location, client, { signal, purpose, strict: true })`: a successful read can establish a negative; physical-path, Git identity and WSL translation failures reject. Ordinary inventory preserves root-only fallback when Git reports a non-repository. Only strict ownership qualifies a cached fallback's checkout absence through filesystem discovery; its qualification state stays inside the ownership cache. Git-unavailable inventory retains its exact-folder `directoryOnly` authority. Strict reads validate each registered checkout root before omitting a missing projected project subfolder; registered-root and opened-root failures reject. Concurrent Git identity preflights retain all admitted reads through settlement. - Event ownership uses registered-only native worktree snapshots, isolated from display/request discovery scans (`ownsDirectory` / `ownsLocation` with the `event` purpose). Never run native strategy refresh from routing or join its pending inventory. Keep physical Git identity, nested-folder/WSL projection, native registration, invalidation and disposal checks shared with ordinary ownership; ordinary requests and explicit worktree discovery retain refresh semantics. Regression: `instance-event-ownership.test.ts` and the isolated native worktree fixture. - Worktree discovery/create/remove use `workspaces/native-worktrees.ts` and the native OpenCode worktree API. CodeNomad supplies the `.codenomad/worktrees` default, named-branch policy and verified family transactions. Git common-directory identity scopes the native inventory to the opened local repository; opaque worktree identifiers are separate from mutable branch labels. Validate through `scripts/test-opencode-location-native.mjs` with an isolated CLI and `tests/browser/worktrees.test.ts` for selector gestures. - Worktree inventory snapshots live in `workspaces/worktree-inventory.ts`: display reads serve cached data and lazily revalidate, directory authorization uses validated reads, and family transactions force fresh reads. Invalidation retains display data and fences pending scans; `workspace.worktreesChanged` refreshes UI consumers after a changed snapshot is published. Keep selector opening independent of refresh completion and suppress duplicate selection events during inventory reconciliation. + Strict directory-cache and native-inventory reads permit two automatic restarts, then one fresh read; another invalidation rejects that demand and permits a later retry. Ordinary readers keep trailing reloads until a current scan settles. Pending strict demands have their own retry budget while sharing native single-scan work and validated snapshots with ordinary readers. - Worktree branch/HEAD annotations use one NUL-delimited Git worktree snapshot, intersected with native inventory and verified Git identities; effective checkout roots must respect Git configuration as well as administrative backlinks. Pending move targets belong to the store's instance/family request identity and survive selector navigation/remounts until native reconciliation settles. diff --git a/docs/help/de/missions.md b/docs/help/de/missions.md index eb0cc4d2ac..29386e06a1 100644 --- a/docs/help/de/missions.md +++ b/docs/help/de/missions.md @@ -136,6 +136,8 @@ Das Speichern einer Tiefe erhält aktivierte native Zeitpläne in der Projektkon **Nativer Standard** und **Global** unterscheiden sich: Ersteres fordert die eigenen Standards von OpenCode an, Letzteres erbt die globale Auswahl; native Standards in einem Playbook-Bereich zu wählen bleibt eine ausdrückliche Ausnahme. Katalogverfügbarkeit wird geprüft; ein angefordertes Profil beweist nicht das aktuell verwendete Profil einer Unterhaltung. Native Berechtigungen und konfigurierte Tiefe regeln interne Helferaufrufe weiterhin in beiden Aufgabenmodi. +Von Agenten gestartete Missionen verwenden **Vorgaben für neue Missionen** für ausgelassene Angaben, wenn das Projekt in CodeNomad geöffnet ist. Ist CodeNomad geschlossen oder das Projekt dort nicht geöffnet, verwenden sie dafür die eigenen Standardwerte von OpenCode. Ausdrückliche Angaben des Agenten haben Vorrang, und Wiederholungen behalten die ursprüngliche Auswahl auch nach Änderungen der Vorgaben bei. Kann CodeNomad Ihre Vorgaben lesen, sind sie aber ungültig, wird die Erstellung bis zu ihrer Korrektur verweigert. + Jede **Modell**-Liste zeigt, was die **Modell**-Auswahl der Unterhaltung zeigt, unter denselben Namen und nach Anbieter gruppiert: Ausgeblendete Modelle fehlen und, solange der Nur-Favoriten-Filter aktiv ist, auch die übrigen Modelle (siehe [Modellsichtbarkeit, Favoriten und Denken](providers.md#models)). Modelle ohne Werkzeugunterstützung fehlen ebenfalls. Ein gespeichertes Modell außerhalb der Liste bleibt ausgewählt. **Nicht verfügbar** kennzeichnet ein gespeichertes Modell, das die Auswahl derzeit nicht anbieten kann: Es fehlt im aktuellen Katalog des Projekts, ist veraltet oder unterstützt keine Werkzeuge. Eine abgelehnte oder unbestätigte Auswahl wird nie erneut gesendet: Die gespeicherten Werte werden wieder angezeigt, und **Neu laden** erscheint nur, wenn sie nicht gelesen werden können. Ist eine Tiefenänderung unbestätigt, bleibt Ihr Wert erhalten; verwenden Sie vor einer weiteren Änderung **Tiefe dieses Projekts aktualisieren**. Interpretieren Sie **Effektive OpenCode-Tiefe unbekannt** nicht als null oder deaktiviert. diff --git a/docs/help/en/missions.md b/docs/help/en/missions.md index 652b775452..f642195f3c 100644 --- a/docs/help/en/missions.md +++ b/docs/help/en/missions.md @@ -136,6 +136,8 @@ Saving a depth preserves enabled native schedules in the project configuration. **Native default** and **Global** are different: the former requests OpenCode's own defaults, the latter inherits the global choice; choosing native defaults in a playbook scope remains an explicit exception. Catalog availability is checked; a requested profile is not proof of the profile a conversation currently uses. Native permissions and configured depth still govern internal helper calls in either task mode. +Missions started by agents use **New mission defaults** for anything the agent leaves out when the project is open in CodeNomad. While CodeNomad is closed or the project is not open in it, they use OpenCode's own defaults for those choices. Explicit agent choices win, and retries keep the original choices even after you change the defaults. If CodeNomad can read your defaults but they are invalid, creation is refused until you correct them. + Each **Model** list shows what the conversation's **Model** selector shows, under the same names and grouped by provider: hidden models are left out and, while favorites-only filtering is on, so are the other models (see [Model visibility, favorites and Thinking](providers.md#models)). Models without tool support are left out too. A saved model outside the list stays selected. **Unavailable** marks a saved model the selector cannot offer now: it is missing from the project's current catalog, deprecated, or has no tool support. A refused or unconfirmed choice is never resent: the stored values are shown again, and **Reload** appears only when they cannot be read. If a depth change is unconfirmed, your value is kept; use **Refresh project depth** before another change. Do not interpret **OpenCode effective depth unknown** as zero or disabled. diff --git a/docs/help/es/missions.md b/docs/help/es/missions.md index 93e363b2fd..27204237c7 100644 --- a/docs/help/es/missions.md +++ b/docs/help/es/missions.md @@ -136,6 +136,8 @@ Guardar una profundidad conserva las programaciones nativas activadas en la conf **Valor nativo predeterminado** y **Global** son distintos: el primero solicita los valores predeterminados propios de OpenCode; el segundo hereda la elección global; elegir los valores nativos en el ámbito de un guion sigue siendo una excepción explícita. Se comprueba la disponibilidad del catálogo; un perfil solicitado no demuestra qué perfil usa actualmente una conversación. Los permisos nativos y la profundidad configurada siguen rigiendo las llamadas a ayudantes internos en ambos modos de tareas. +Las misiones iniciadas por agentes usan **Valores para nuevas misiones** para lo que el agente omita cuando el proyecto está abierto en CodeNomad. Si CodeNomad está cerrado o el proyecto no está abierto en él, usan los valores propios de OpenCode para esas opciones. Las elecciones explícitas del agente tienen prioridad y los reintentos conservan las originales aunque cambies los valores predeterminados. Si CodeNomad puede leer tus valores pero no son válidos, se rechaza la creación hasta que los corrijas. + Cada lista **Modelo** muestra lo mismo que el selector **Modelo** de la conversación, con los mismos nombres y agrupado por proveedor: se omiten los modelos ocultos y, mientras el filtrado de solo favoritos está activo, también los demás modelos (consulta [Visibilidad de modelos, favoritos y Razonamiento](providers.md#models)). También se omiten los modelos sin compatibilidad con herramientas. Un modelo guardado fuera de la lista sigue seleccionado. **No disponible** marca un modelo guardado que el selector no puede ofrecer ahora: falta en el catálogo actual del proyecto, está obsoleto o no admite herramientas. Una elección rechazada o sin confirmar nunca se reenvía: se vuelven a mostrar los valores guardados, y **Recargar** solo aparece cuando no se pueden leer. Si un cambio de profundidad no está confirmado, tu valor se conserva; usa **Actualizar profundidad del proyecto** antes de otro cambio. No interpretes **Profundidad efectiva de OpenCode desconocida** como cero o desactivada. diff --git a/docs/help/fr/missions.md b/docs/help/fr/missions.md index 25b5cef835..d4bb10ae97 100644 --- a/docs/help/fr/missions.md +++ b/docs/help/fr/missions.md @@ -136,6 +136,8 @@ Enregistrer une profondeur préserve les programmations natives activées dans l **Valeur native par défaut** et **Global** diffèrent : le premier demande les valeurs par défaut propres à OpenCode, le second hérite du choix global ; choisir les valeurs natives par défaut dans la portée d’un scénario reste une exception explicite. La disponibilité du catalogue est vérifiée ; un profil demandé ne prouve pas celui qu’utilise actuellement une conversation. Les autorisations natives et la profondeur configurée régissent toujours les appels d’assistants internes dans les deux modes de tâches. +Les missions lancées par un agent utilisent **Défauts des nouvelles missions** pour les choix omis lorsque le projet est ouvert dans CodeNomad. Lorsque CodeNomad est fermé ou que le projet n'y est pas ouvert, elles utilisent les valeurs par défaut d'OpenCode pour ces choix. Les choix explicites de l'agent priment, et les réessais conservent les choix d'origine même après une modification des défauts. Si CodeNomad peut lire vos défauts mais qu'ils sont invalides, la création est refusée jusqu'à leur correction. + Chaque liste **Modèle** affiche ce qu’affiche le sélecteur **Modèle** de la conversation, sous les mêmes noms et groupé par fournisseur : les modèles masqués en sont exclus et, tant que le filtrage limité aux favoris est actif, les autres modèles aussi (voir [Visibilité des modèles, favoris et Réflexion](providers.md#models)). Les modèles sans prise en charge des outils sont également exclus. Un modèle enregistré absent de la liste reste sélectionné. **Indisponible** signale un modèle enregistré que le sélecteur ne peut pas proposer actuellement : il est absent du catalogue actuel du projet, obsolète ou sans prise en charge des outils. Un choix refusé ou non confirmé n’est jamais renvoyé : les valeurs enregistrées sont réaffichées, et **Recharger** n’apparaît que lorsqu’elles ne peuvent pas être lues. Si un changement de profondeur n’est pas confirmé, votre valeur est conservée ; utilisez **Actualiser la profondeur du projet** avant un autre changement. N’interprétez pas **Profondeur OpenCode effective inconnue** comme zéro ou désactivée. diff --git a/docs/help/he/missions.md b/docs/help/he/missions.md index 08ffd735c6..e81ad647a8 100644 --- a/docs/help/he/missions.md +++ b/docs/help/he/missions.md @@ -136,6 +136,8 @@ **ברירת מחדל מקורית** ו־**גלובלי** שונות: הראשונה מבקשת את ברירות המחדל של OpenCode עצמו, השנייה יורשת את הבחירה הגלובלית; בחירת ברירות מחדל מקוריות בהיקף של מדריך נשארת חריג מפורש. זמינות הקטלוג נבדקת; פרופיל מבוקש אינו הוכחה לפרופיל ששיחה משתמשת בו כרגע. אישורים מקוריים והעומק המוגדר עדיין שולטים בקריאות לעוזרים פנימיים בשני מצבי המטלות. +משימות שסוכנים מתחילים משתמשות ב־**ברירות מחדל למשימות חדשות** לבחירות שהסוכן משמיט כשהפרויקט פתוח ב־CodeNomad. כש־CodeNomad סגור או שהפרויקט אינו פתוח בו, הן משתמשות בברירות המחדל של OpenCode לבחירות האלה. בחירות מפורשות של הסוכן מקבלות עדיפות, וניסיונות חוזרים שומרים על הבחירות המקוריות גם אחרי שינוי ברירות המחדל. אם CodeNomad יכול לקרוא את ברירות המחדל שלכם אך הן אינן תקינות, היצירה נחסמת עד לתיקונן. + כל רשימת **מודל** מציגה את מה שמציג בורר **מודל** של השיחה, באותם שמות ומקובצת לפי ספק: מודלים מוסתרים אינם מופיעים, ובזמן שסינון למועדפים בלבד פעיל גם שאר המודלים אינם מופיעים (ראו [נראות מודלים, מועדפים וחשיבה](providers.md#models)). גם מודלים ללא תמיכה בכלים אינם מופיעים. מודל שמור שאינו ברשימה נשאר נבחר. **לא זמין** מסמן מודל שמור שהבורר אינו יכול להציע כעת: הוא חסר בקטלוג הנוכחי של הפרויקט, הוצא משימוש או אינו תומך בכלים. בחירה שנדחתה או שלא אושרה לעולם אינה נשלחת שוב: הערכים השמורים מוצגים שוב, ו־**טעינה מחדש** מופיעה רק כשאי אפשר לקרוא אותם. אם שינוי עומק אינו מאושר, הערך שלכם נשמר; השתמשו ב־**רענון עומק הפרויקט** לפני שינוי נוסף. אל תפרשו **עומק OpenCode האפקטיבי אינו ידוע** כאפס או כמושבת. diff --git a/docs/help/he/playbooks.md b/docs/help/he/playbooks.md index dc56737500..8f904f3f74 100644 --- a/docs/help/he/playbooks.md +++ b/docs/help/he/playbooks.md @@ -258,7 +258,7 @@ ### מה CodeNomad בודק {#compare-checks} -- ביצירה, **מודל A** ו־**מודל B** נדרשים וחייבים להיות מודלים שונים; רמת **חשיבה** שונה בלבד אינה מודל שונה. אלא אם תבחרו שופט, הוא משתמש במודל של המתאם, שנקבע ביצירה; הטופס מזהיר כשהוא זהה ל־A או ל־B. +- ביצירה, **מודל A** ו־**מודל B** נדרשים וחייבים להיות מודלים שונים; רמת **חשיבה** שונה בלבד אינה מודל שונה. אלא אם תבחרו מודל לשופט, הוא משתמש במודל של המתאם, שנקבע ביצירה; הטופס מזהיר כשהוא זהה ל־A או ל־B. - רק שלושת התפקידים של השוואת שני מודלים מתקבלים. כל הרצה והשופט חייבים להתחיל בשיחה חדשה, הרצה אינה יכולה לשנות את המודל של התפקיד שלה, יש הרצה פעילה אחת לכל מודל, ושני התיאורים חייבים להיות זהים בייט לבייט. - רק השופט רשאי לצרף דוח מובנה, והוא חייב להפנות להרצות A ו־B שהושלמו בסדר הזה, לתת לכל קריטריון ציון אחד מ־0 עד 10 עם ראיה אחת לפחות, ולתת אחד מארבעת פסקי הדין. - המשימה מסתיימת רק עם מטלות A, B והשופט שהושלמו והשוואה תקינה. diff --git a/docs/help/ja/missions.md b/docs/help/ja/missions.md index 46ad0ed41b..5573e1e8d9 100644 --- a/docs/help/ja/missions.md +++ b/docs/help/ja/missions.md @@ -136,6 +136,8 @@ CodeNomad の実行中は、ミッションのコーディネーターやタス **ネイティブの既定値** と **グローバル** は異なります。前者は OpenCode 自身の既定値を要求し、後者はグローバルの選択を継承します。プレイブックの範囲でネイティブの既定値を選ぶことは、引き続き明示的な例外になります。カタログ上の利用可否を確認しますが、要求したプロファイルは、会話が現在使用するプロファイルの証拠ではありません。どちらのタスクモードでも、内部ヘルパーの呼び出しにはネイティブ権限と設定済みの深さが適用されます。 +エージェントが開始するミッションでは、プロジェクトが CodeNomad で開かれている場合、省略した項目に **新規ミッションの既定値** を使用します。CodeNomad が閉じている、またはプロジェクトが開かれていない場合は、その項目に OpenCode 自身の既定値を使用します。エージェントの明示的な選択が優先され、既定値を変更しても再試行では元の選択を保持します。CodeNomad が既定値を読み取れても内容が無効な場合は、修正するまで作成できません。 + 各 **モデル** リストには、会話の **モデル** セレクターと同じモデルが同じ名前でプロバイダーごとに表示されます。非表示のモデルは含まれず、お気に入りのみの絞り込みが有効な間はお気に入り以外のモデルも含まれません([モデルの表示、お気に入り、思考](providers.md#models) を参照)。ツールに対応していないモデルも含まれません。リストにない保存済みのモデルは選択されたまま残ります。**利用不可** は、プロジェクトの現在のカタログにない、非推奨である、またはツールに対応していないため、セレクターが現在提供できない保存済みのモデルに付きます。 拒否された選択や未確認の選択が再送されることはありません。保存済みの値が再び表示され、**再読み込み** はそれらを読み取れない場合にだけ表示されます。深さの変更が未確認の場合は入力した値が保持されるので、次の変更の前に **プロジェクトの深さを更新** を使用します。**OpenCode の有効な深さは不明** をゼロや無効と解釈しないでください。 diff --git a/docs/help/ne/missions.md b/docs/help/ne/missions.md index 6bb1fc3f6e..a45917ccb1 100644 --- a/docs/help/ne/missions.md +++ b/docs/help/ne/missions.md @@ -136,6 +136,8 @@ CodeNomad चलिरहँदा, project का हरेक agent कुर **नेटिभ पूर्वनिर्धारित** र **विश्वव्यापी** फरक हुन्: पहिलोले OpenCode का आफ्नै default माग्छ, दोस्रोले global चयन inherit गर्छ; playbook दायरामा native default रोज्नु स्पष्ट exception नै रहन्छ। catalogue उपलब्धता जाँचिन्छ; requested profile कुराकानीले अहिले प्रयोग गरिरहेको profile को प्रमाण होइन। दुवै task mode का internal helper मा native permission र configured depth लागू रहन्छन्। +परियोजना CodeNomad मा खुला हुँदा एजेन्टले सुरु गरेका मिसनले उसले नदिएका विकल्पका लागि **नयाँ मिसनका पूर्वनिर्धारित मान** प्रयोग गर्छन्। CodeNomad बन्द हुँदा वा परियोजना त्यसमा खुला नहुँदा ती विकल्पका लागि OpenCode कै पूर्वनिर्धारित मान प्रयोग हुन्छन्। एजेन्टका स्पष्ट विकल्पले प्राथमिकता पाउँछन् र पूर्वनिर्धारित मान बदले पनि पुनःप्रयासमा सुरुका विकल्प कायम रहन्छन्। CodeNomad ले तपाईंका पूर्वनिर्धारित मान पढ्न सके पनि तिनीहरू अमान्य भए, नसच्याएसम्म सिर्जना रोकिन्छ। + प्रत्येक **मोडेल** सूचीले कुराकानीको **मोडेल** selector ले देखाउने मोडेलहरू उही नाममा, provider अनुसार समूहबद्ध गरी देखाउँछ: लुकाइएका मोडेलहरू समावेश हुँदैनन्, र favorites-only filtering सक्रिय रहँदा अन्य मोडेलहरू पनि समावेश हुँदैनन् ([मोडेल दृश्यता, मनपर्ने र Thinking](providers.md#models) हेर्नुहोस्)। tool support नभएका मोडेलहरू पनि समावेश हुँदैनन्। सूचीबाहिरको saved मोडेल चयन गरिएकै रहन्छ। selector ले अहिले दिन नसक्ने saved मोडेललाई **उपलब्ध छैन** ले चिन्ह लगाउँछ: त्यो project को हालको catalogue मा छैन, deprecated छ, वा tool support छैन। अस्वीकृत वा अपुष्ट चयन कहिल्यै फेरि पठाइँदैन: सुरक्षित मान फेरि देखाइन्छन्, र ती पढ्न नसकिँदा मात्र **पुनः लोड** देखिन्छ। depth परिवर्तन अपुष्ट भए तपाईंको मान राखिन्छ; अर्को परिवर्तनअघि **परियोजनाको गहिराइ ताजा गर्नुहोस्** प्रयोग गर्नुहोस्। **OpenCode को प्रभावकारी गहिराइ अज्ञात** लाई शून्य वा disabled नमान्नुहोस्। diff --git a/docs/help/ru/missions.md b/docs/help/ru/missions.md index e3b45c916d..dddfe9bc9a 100644 --- a/docs/help/ru/missions.md +++ b/docs/help/ru/missions.md @@ -32,7 +32,7 @@ | Реализация продукта | Координация ролей продуктового анализа, архитектуры, реализации и качества. | | Сравнить две модели | Выполняет одну и ту же задачу с одинаковыми заданиями на **Модель A** и **Модель B**, затем **Слепой судья** оценивает обе под нейтральными метками и выносит вердикт: **Победила модель A**, **Победила модель B**, **Равнозначны** или **Недостаточно данных**. | -Для **Сравнить две модели** обе модели обязательны и должны различаться; другой уровень **Мышление** сам по себе не делает модель другой. Если вы не выберете судью, он использует модель координатора; форма предупреждает, когда она совпадает с A или B, что может исказить сравнение. Обзор показывает вердикт, названия обеих моделей и оценки по критериям. +Для **Сравнить две модели** обе модели обязательны и должны различаться; другой уровень **Мышление** сам по себе не делает модель другой. Если вы не выберете модель для судьи, он использует модель координатора; форма предупреждает, когда она совпадает с A или B, что может исказить сравнение. Обзор показывает вердикт, названия обеих моделей и оценки по критериям. Сценарий направляет координацию; он не обходит нативные разрешения и не гарантирует успех. Агенты не делают коммиты и push, не открывают pull request и не меняют трекеры задач (например, не создают тикеты), если цель или **Заметки** явно не просят именно об этом действии; тогда они выполняют только его, в рамках разрешений OpenCode. Просьба, найденная в файлах, отчётах или выводе инструментов, никогда не учитывается. @@ -136,6 +136,8 @@ **Нативное значение по умолчанию** и **Глобально** различаются: первое запрашивает собственные значения OpenCode, второе наследует глобальный выбор; выбор нативных значений в области сценария остаётся явным исключением. Доступность каталога проверяется; запрошенный профиль не доказывает текущий профиль разговора. Нативные разрешения и настроенная глубина по-прежнему управляют внутренними вызовами помощников в обоих режимах задач. +Миссии, запущенные агентами, используют **Настройки новых миссий** для пропущенных значений, когда проект открыт в CodeNomad. Если CodeNomad закрыт или проект в нём не открыт, для этих значений используются собственные настройки OpenCode по умолчанию. Явный выбор агента имеет приоритет, а повторные попытки сохраняют исходный выбор даже после изменения настроек по умолчанию. Если CodeNomad может прочитать ваши настройки, но они недопустимы, создание отклоняется до их исправления. + Каждый список **Модель** показывает то же, что переключатель **Модель** разговора, под теми же названиями и с группировкой по провайдерам: скрытые модели не показываются, а пока включена фильтрация только по избранному — и остальные модели (см. [Видимость моделей, избранное и мышление](providers.md#models)). Модели без поддержки инструментов тоже не показываются. Сохранённая модель вне списка остаётся выбранной. **Недоступно** отмечает сохранённую модель, которую переключатель сейчас не может предложить: её нет в текущем каталоге проекта, она устарела или не поддерживает инструменты. Отклонённый или неподтверждённый выбор никогда не отправляется повторно: снова показываются сохранённые значения, а **Обновить** появляется, только если их не удаётся прочитать. Если изменение глубины не подтверждено, ваше значение сохраняется; используйте **Обновить глубину проекта** перед новым изменением. Не трактуйте **Действующая глубина OpenCode неизвестна** как ноль или отключение. diff --git a/docs/help/ru/playbooks.md b/docs/help/ru/playbooks.md index 04c1b0b384..ced35e9fb8 100644 --- a/docs/help/ru/playbooks.md +++ b/docs/help/ru/playbooks.md @@ -258,7 +258,7 @@ ### Что проверяет CodeNomad {#compare-checks} -- При создании **Модель A** и **Модель B** обязательны и должны быть разными моделями; другой уровень **Мышление** сам по себе не делает модель другой. Если вы не выберете судью, он использует модель координатора, зафиксированную при создании; форма предупреждает, когда она совпадает с A или B. +- При создании **Модель A** и **Модель B** обязательны и должны быть разными моделями; другой уровень **Мышление** сам по себе не делает модель другой. Если вы не выберете модель для судьи, он использует модель координатора, зафиксированную при создании; форма предупреждает, когда она совпадает с A или B. - Принимаются только три роли сценария Сравнить две модели. Каждый запуск и судья должны начинаться в новом разговоре, запуск не может сменить модель своей роли, для каждой модели есть только один активный запуск, а оба задания должны совпадать байт в байт. - Структурированный отчёт может приложить только судья; он должен ссылаться на завершённые запуски A и B в этом порядке, оценить каждый критерий один раз от 0 до 10 хотя бы с одним доказательством и дать один из четырёх вердиктов. - Миссия завершается только с выполненными задачами A, B и судьи и корректным сравнением. diff --git a/docs/help/tr/missions.md b/docs/help/tr/missions.md index e19a44e790..e5eabf6f3a 100644 --- a/docs/help/tr/missions.md +++ b/docs/help/tr/missions.md @@ -136,6 +136,8 @@ Derinliği kaydetmek, proje yapılandırmasında etkin yerel zamanlamaları koru **Yerel varsayılan** ile **Genel** farklıdır: ilki OpenCode'un kendi varsayılanlarını ister, ikincisi genel seçimi devralır; bir rehber kapsamında yerel varsayılanları seçmek açık bir istisna olarak kalır. Katalog kullanılabilirliği kontrol edilir; istenen profil, bir konuşmanın o anda kullandığı profilin kanıtı değildir. Her iki görev modunda da dahili yardımcı çağrılarını OpenCode izinleri ve yapılandırılmış derinlik yönetir. +Ajanların başlattığı görevler, proje CodeNomad'da açıkken ajanın belirtmediği seçenekler için **Yeni görev varsayılanları** ayarını kullanır. CodeNomad kapalıysa veya proje CodeNomad'da açık değilse bu seçenekler için OpenCode'un kendi varsayılanları kullanılır. Ajanın açık seçimleri önceliklidir ve varsayılanları değiştirseniz bile yeniden denemeler ilk seçimleri korur. CodeNomad varsayılanlarınızı okuyabiliyor ancak bunlar geçersizse düzeltene kadar oluşturma reddedilir. + Her **Model** listesi, konuşmanın **Model** seçicisinin gösterdiklerini aynı adlarla ve sağlayıcıya göre gruplanmış olarak gösterir: gizlenen modeller yer almaz ve yalnızca favorilere yönelik filtreleme açıkken diğer modeller de yer almaz (bkz. [Model görünürlüğü, favoriler ve Düşünme](providers.md#models)). Araç desteği olmayan modeller de yer almaz. Liste dışındaki kayıtlı bir model seçili kalır. **Kullanılamıyor**, seçicinin şu anda sunamadığı kayıtlı bir modeli işaretler: model projenin güncel kataloğunda yoktur, kullanımdan kaldırılmıştır veya araç desteği yoktur. Reddedilen veya doğrulanmayan bir seçim asla yeniden gönderilmez: kayıtlı değerler yeniden gösterilir ve **Yeniden yükle** yalnızca bu değerler okunamadığında görünür. Bir derinlik değişikliği doğrulanmadıysa değeriniz korunur; başka bir değişiklik yapmadan önce **Proje derinliğini yenile** eylemini kullanın. **Etkin OpenCode derinliği bilinmiyor** durumunu sıfır veya devre dışı olarak yorumlamayın. diff --git a/docs/help/zh-Hans/missions.md b/docs/help/zh-Hans/missions.md index fdc739ce37..a386fc2f64 100644 --- a/docs/help/zh-Hans/missions.md +++ b/docs/help/zh-Hans/missions.md @@ -136,6 +136,8 @@ CodeNomad 运行期间,项目中的每个智能体对话(包括任务协调 **原生默认值**与**全局**不同:前者请求 OpenCode 自身的默认值,后者继承全局选择;在剧本范围中选择原生默认值仍是显式例外。会检查目录可用性;请求的配置不证明对话当前实际使用的配置。两种任务模式下,内部辅助调用仍受原生权限和配置深度约束。 +项目在 CodeNomad 中打开时,智能体启动的任务会将**新任务默认设置**应用于省略的选项。CodeNomad 关闭或项目未在其中打开时,这些选项会使用 OpenCode 自身的默认值。智能体明确指定的选项优先,即使您修改默认设置,重试也会保留最初的选择。如果 CodeNomad 能读取您的默认设置但内容无效,创建将被拒绝,直到您修正设置。 + 每个**模型**列表显示的内容与对话的**模型**选择器相同,名称一致并按提供商分组:不包含已隐藏的模型;启用仅收藏筛选时,也不包含其他模型(参见[模型可见性、收藏和思考](providers.md#models))。不支持工具的模型同样不包含。列表之外的已保存模型仍保持选中。选择器当前无法提供的已保存模型标记为**不可用**:它不在项目当前的目录中、已弃用或不支持工具。 被拒绝或未确认的选择绝不会重新发送:会重新显示已存储的值,只有在无法读取这些值时才会出现**重新加载**。如果深度更改未确认,你的值会保留;请先使用**刷新项目深度**,再进行其他更改。不要将 **OpenCode 有效深度未知**解释为零或禁用。 diff --git a/packages/server/src/missions/control-error.ts b/packages/server/src/missions/control-error.ts index 29fbec4403..c3daf92c4c 100644 --- a/packages/server/src/missions/control-error.ts +++ b/packages/server/src/missions/control-error.ts @@ -1,3 +1,5 @@ +export const MISSION_CREATION_REQUEST_CONFLICT = "Creation request ID was already used with a different mission" + export class MissionControlError extends Error { constructor(message: string, readonly code: string) { super(message) @@ -21,7 +23,7 @@ export class MissionCreateNoEffectError extends MissionControlError { readonly noEffect: { requestID: string; missionID: string } constructor(requestID: string, missionID: string) { - super("Creation request ID was already used with a different mission", "request-conflict") + super(MISSION_CREATION_REQUEST_CONFLICT, "request-conflict") this.noEffect = { requestID, missionID } } } diff --git a/packages/server/src/missions/control-types.ts b/packages/server/src/missions/control-types.ts index c6bab3bb6a..69e1f76cb5 100644 --- a/packages/server/src/missions/control-types.ts +++ b/packages/server/src/missions/control-types.ts @@ -5,6 +5,8 @@ import type { MissionActor, MissionJsonValue, MissionMap, MissionReportOutcome, import type { TaskContractReference } from "./task-declaration" import type { MissionRecipe, missionRecipeCatalog } from "./recipes" import type { MissionProfiles } from "./playbook-profiles" +import type { MissionCreationChoices, MissionCreationMetadata } from "./creation-defaults" +import type { MissionCreationSelection } from "./profile-defaults" export interface NativeMissionSession extends MissionExecution { id: string @@ -124,7 +126,8 @@ export type MissionNativeReportAuthorization = (request: MissionNativeReportRequ }> export interface MissionInspection { - mission: MissionMap | null + selection?: MissionCreationSelection + mission: Omit | null actor: MissionActor | null templates: ReturnType playbook?: MissionRecipe @@ -135,6 +138,8 @@ export interface MissionInspection { } export interface MissionCreateInput extends MissionStartInput { + /** Original agent request and frozen preference provenance, supplied by the owning backend. */ + creationDefaults?: MissionCreationMetadata /** Optional short label (1–60 characters, trimmed). */ title?: string prepared?: boolean @@ -182,6 +187,7 @@ export interface MissionReviseInput { } export interface MissionInputTransport { + resolveCreationDefaults?(sessionID: string, input: MissionCreationChoices & { template: MissionTemplateId; coordinatorModel?: MissionExecution["model"] }): Promise lifecycle?(coordinatorID: string, input: { missionID: string; operationID: string; sessionID: string; startText?: string; recurrence?: import("./lifecycle-model").MissionLifecycleInput["recurrence"] }): Promise @@ -196,6 +202,8 @@ export interface MissionInputTransport { /** A coordinator's paused hand-off mission: what the Mission editor submits, never Play. */ export interface MissionPrepareRequest { + /** Trusted resolved creation metadata, carried only through the backend transport. */ + creationDefaults?: MissionCreationMetadata requestID: string objective: string title?: string diff --git a/packages/server/src/missions/control.ts b/packages/server/src/missions/control.ts index 3209a308e0..ac03866af8 100644 --- a/packages/server/src/missions/control.ts +++ b/packages/server/src/missions/control.ts @@ -8,6 +8,9 @@ import { MISSION_LIST_MAX_INCLUDE, missionSummary } from "./mission-summary" import { readMissionContent, type MissionContentRequest, type MissionContentResult } from "./mission-content" import type { MissionIndexHints, MissionJournalIndex } from "./journal-index" import { compactMissionMap, missionTaskPage } from "./mission-compact-map" +import { missionCreationChoices, sameMissionCreationChoices, parseMissionCreationSelection, missionCreationSelection, type MissionCreationMetadata } from "./creation-defaults" +import { MissionCreationIntents } from "./creation-intent" +import { hasExplicitMissionCreationChoices, resolveMissionCreationDefaults, type MissionCreationSelection } from "./profile-defaults" import type { MissionTaskPageResult, MissionTaskRequest } from "./mission-panel-map" import { missionPanelPage, missionPanelWindow, type MissionPanelPageRequest, type MissionPanelPageResult } from "./mission-panel-page" import { projectMissionPanel } from "./mission-panel-projection" @@ -40,7 +43,8 @@ import { runMissionExclusive } from "./exclusive" import { matchesExecution, sameExecution } from "./execution" import { sameLocation } from "../opencode/compatibility/location" import { missionRecoveryInput, type MissionRecoveryInput } from "./recovery-input" -import { MissionControlError, MissionCreateNoEffectError, humanDecisionRequired } from "./control-error" +import { missionRecoveryControlError } from "./recovery-error" +import { MISSION_CREATION_REQUEST_CONFLICT, MissionControlError, MissionCreateNoEffectError, humanDecisionRequired } from "./control-error" import { claimedDecisionFields, coordinatorAskedAnswer, coordinatorDecision, decisionInvocationUnavailable, decisionOutcomeRequired, decisionQuestionUnbound, receiptMatches, type CoordinatorAskedAnswer, type MissionDecisionProof } from "./decision-gate" import { decisionQuestionTag, fieldDecisionTag } from "./decision-question-tag" @@ -70,6 +74,7 @@ import type { MissionDeleteInput, MissionReviseInput, MissionInspectInput, + MissionStartInput, MissionInspection, MissionProject, MissionPrepareRequest, @@ -93,6 +98,7 @@ export interface MissionNotificationRetryResult { export class MissionControl { private readonly journal: MissionJournal + private readonly creationIntents: MissionCreationIntents private lastTimestamp = 0 constructor(private readonly options: { @@ -116,6 +122,7 @@ export class MissionControl { documentReads?: MissionDocumentAccess }) { this.journal = new MissionJournal(options.storage, options.project.id, options.project.canonical, options.now, options.journalIndex) + this.creationIntents = new MissionCreationIntents(options.storage, this.journal.projectToken, options.now) } async snapshot(): Promise { @@ -403,10 +410,60 @@ export class MissionControl { return this.mutate(() => this.createCurrent(request)) } - private compareCreationProfiles(template: MissionMap["template"], profiles?: MissionProfiles, coordinatorModel?: NativeMissionSession["model"]): MissionProfiles | undefined { + private assertCompareCreation(template: MissionMap["template"], profiles?: MissionProfiles): void { const error = template === "compare" && compareModelError(profiles) if (error) throw new MissionControlError(error, "invalid-execution") - return freezeCompareProfiles(template, profiles, coordinatorModel) + } + + private async savedCreationInput(input: T, missionID: string, conflict: string) { + const frozen = await this.options.documents?.(async store => { + const doc = await store.read(missionID) + return doc && !("deletedAt" in doc) ? doc.oneTime?.creationDefaults : undefined + }) + if (frozen) { + if (!sameMissionCreationChoices(frozen.request, input)) throw conflict === "prepare-conflict" + ? missionRecoveryControlError("prepare-conflict") : new MissionControlError(MISSION_CREATION_REQUEST_CONFLICT, conflict) + return { input: { ...input, profiles: frozen.profiles, taskMode: frozen.taskMode, creationDefaults: frozen }, fromDocument: true } + } + } + + private async resolveCreationInput(sessionID: string, input: T, missionID: string, conflict = "request-conflict", + coordinatorModel?: NativeMissionSession["model"]): Promise<{ input: T & { creationDefaults?: MissionCreationMetadata }; fromDocument: boolean }> { + const saved = await this.savedCreationInput(input, missionID, conflict) + if (saved) return saved + const resolve = this.options.transport?.resolveCreationDefaults + const request = missionCreationChoices(input) + let selection: MissionCreationSelection + if (hasExplicitMissionCreationChoices(input)) { + selection = resolveMissionCreationDefaults({ template: input.template, ...request, coordinatorModel, preferences: undefined }) + } else if (resolve) { + selection = parseMissionCreationSelection(input.template, await resolve(sessionID, { template: input.template, ...request, + ...(coordinatorModel === undefined ? {} : { coordinatorModel }) })) + } else { + // Internal journal-only consumers supply their own frozen profiles. + return { input, fromDocument: false } + } + return { input: { ...input, profiles: selection.profiles, taskMode: selection.taskMode, creationDefaults: { request, ...selection } }, fromDocument: false } + } + + private async retainCreationInput(input: T, missionID: string, conflict = "request-conflict"): Promise { + if (!input.creationDefaults) return input + const saved = await this.creationIntents.save(missionID, input, input.creationDefaults, + () => this.journal.event(missionID, this.eventID(missionID, "created")), () => this.assertActive(), conflict) + return { ...input, profiles: saved.profiles, taskMode: saved.taskMode, creationDefaults: saved } + } + + private coordinatorProfileMismatch(input: { creationDefaults?: MissionCreationMetadata }): MissionControlError { + return new MissionControlError(input.creationDefaults?.origins.coordinator === "preference" + ? "Coordinator differs from the profile selected by Missions preferences. Pass profiles.coordinator (for example {}) to override that preference." + : "Coordinator does not have the requested native profile", "invalid-execution") + } + + private sameCreationChoices(saved: Pick, input: MissionStartInput, + coordinatorModel?: NativeMissionSession["model"]): boolean { + return saved.creationDefaults ? sameMissionCreationChoices(saved.creationDefaults.request, input) + : sameMissionProfiles(saved.profiles, freezeCompareProfiles(input.template, input.profiles, coordinatorModel)) + && (saved.taskMode ?? "native") === parseMissionTaskMode(input.taskMode) } private async createCurrent(input: MissionCreateInput): Promise<{ mission: MissionMap }> { @@ -419,7 +476,8 @@ export class MissionControl { } try { input.profiles = parseMissionProfiles(input.profiles); validateMissionProfiles(input.template, input.profiles) } catch { throw new MissionControlError("Invalid Mission profile selection", "invalid-execution") } - input.profiles = this.compareCreationProfiles(input.template, input.profiles) + this.assertCompareCreation(input.template, input.profiles) + if (!input.creationDefaults) input.profiles = freezeCompareProfiles(input.template, input.profiles) const missionID = `msn_${stableToken(`${this.options.project.id}\0${input.requestID}`, 24)}` const eventID = this.eventID(missionID, "created") const existingEvent = await this.journal.event(missionID, eventID) @@ -435,6 +493,7 @@ export class MissionControl { || !sameMissionProfiles(existingEvent.profiles, input.profiles) || (existingEvent.taskMode ?? "native") !== input.taskMode || !isDeepStrictEqual(existingEvent.preparedBy, input.preparedBy) + || !isDeepStrictEqual(existingEvent.creationDefaults, input.creationDefaults) || (input.coordinatorSessionID !== undefined && existingEvent.coordinator.sessionID !== input.coordinatorSessionID)) { // Healthy original creation evidence rejects the changed request before // coordinator lookup/creation, profile writes or journal publication. @@ -445,6 +504,7 @@ export class MissionControl { throw new MissionControlError("Coordinator moved from its admitted creation location", "foreign-session") } if (this.options.documents && existing.document) await requireMissionOneTimeDocument(this.options.documents, existing.id, existing.coordinatorSessionId, input) + if (existingEvent.creationDefaults) await this.creationIntents.settled(missionID) return { mission: existing } } // Read after the creation event: a purge records the deletion before removing it. @@ -458,7 +518,7 @@ export class MissionControl { throw new MissionControlError("Coordinator session already belongs to an active mission", "already-member") } if (suppliedCoordinator && !matchesExecution(input.profiles?.coordinator, suppliedCoordinator)) - throw new MissionControlError("Coordinator does not have the requested native profile", "invalid-execution") + throw this.coordinatorProfileMismatch(input) if (suppliedCoordinator && input.expectedCoordinatorLocation && !sameLocation(suppliedCoordinator.location, input.expectedCoordinatorLocation)) throw new MissionControlError("Coordinator moved from its admitted creation location", "foreign-session") @@ -497,7 +557,7 @@ export class MissionControl { } if (!matchesExecution(input.profiles?.coordinator, coordinator)) { - throw new MissionControlError("Coordinator does not have the requested native profile", "invalid-execution") + throw this.coordinatorProfileMismatch(input) } const createdAt = this.timestamp(snapshot) this.assertActive() @@ -514,6 +574,7 @@ export class MissionControl { template: input.template, taskMode: input.taskMode, ...(input.profiles === undefined ? {} : { profiles: input.profiles }), + ...(input.creationDefaults === undefined ? {} : { creationDefaults: input.creationDefaults }), requestID: input.requestID, ...(input.prepared === undefined ? {} : { prepared: input.prepared }), ...(input.preparedBy === undefined ? {} : { preparedBy: { ...input.preparedBy } }), @@ -522,6 +583,7 @@ export class MissionControl { }) snapshot = await this.snapshot() await this.emitChanged(missionID, snapshot) + if (input.creationDefaults) await this.creationIntents.settled(missionID) return { mission: this.requireMission(snapshot, missionID) } } @@ -907,9 +969,31 @@ export class MissionControl { }) } - inspect(sessionID: string, input: MissionInspectInput, operationID: string): Promise { + private async inspectCreationIdentity(sessionID: string, operationID: string) { + const requestID = `native_${stableToken(`${sessionID}\0${operationID}`, 48)}` + const journalID = `msn_${stableToken(`${this.options.project.id}\0${sessionID}\0${operationID}`, 24)}` + const journalCreated = await this.journal.event(journalID, this.eventID(journalID, "created")) + const journalDeleted = !journalCreated && await this.journal.deletionRecord(journalID) + const missionID = this.options.documents && !journalCreated && !journalDeleted + ? `msn_${stableToken(`${this.options.project.id}\0${requestID}`, 24)}` : journalID + const created = missionID === journalID ? journalCreated : await this.journal.event(missionID, this.eventID(missionID, "created")) + return { requestID, missionID, created } + } + + async inspect(sessionID: string, input: MissionInspectInput, operationID: string): Promise { + input = structuredClone(input) if (!input.start) return this.inspectCurrent(sessionID, input, operationID) - return this.mutate(() => this.inspectCurrent(sessionID, input, operationID)) + try { input.start.profiles = parseMissionProfiles(input.start.profiles); validateMissionProfiles(input.start.template, input.start.profiles) } + catch { throw new MissionControlError("Invalid Mission profile selection", "invalid-execution") } + const caller = await this.ownedRootSession(sessionID) + const { missionID, created } = await this.inspectCreationIdentity(sessionID, operationID) + await this.assertNotPurged(missionID) + // Preference discovery can wait on another backend; it never owns the project's mutation lane. + let selected: (MissionStartInput & { creationDefaults?: MissionCreationMetadata }) | undefined, preferenceError: unknown + try { if (!created) selected = (await this.resolveCreationInput(sessionID, input.start, missionID, "request-conflict", caller.model)).input } + catch (error) { preferenceError = error } + return this.mutate(() => this.inspectCurrent(sessionID, input, operationID, + { input: selected, preferenceError, location: caller.location })) } /** The caller's owned root, read afresh with the root and project checks of every @@ -918,46 +1002,58 @@ export class MissionControl { return this.ownedRootSession(sessionID) } - private async inspectCurrent(sessionID: string, input: MissionInspectInput, operationID: string): Promise { + private async inspectCurrent(sessionID: string, input: MissionInspectInput, operationID: string, + selected?: { input?: MissionStartInput & { creationDefaults?: MissionCreationMetadata }; preferenceError?: unknown; location: NativeMissionSession["location"] }): Promise { input = structuredClone(input) const caller = await this.ownedRootSession(sessionID) - if (input.start && this.options.documents) { - const journalID = `msn_${stableToken(`${this.options.project.id}\0${sessionID}\0${operationID}`, 24)}` - if (!await this.journal.event(journalID, this.eventID(journalID, "created")) && !await this.journal.deletionRecord(journalID)) { - const result = await this.createCurrent({ ...input.start, - profiles: this.compareCreationProfiles(input.start.template, input.start.profiles, caller.model), - requestID: `native_${stableToken(`${sessionID}\0${operationID}`, 48)}`, prepared: true, - coordinatorSessionID: sessionID, expectedCoordinatorLocation: caller.location }) - return this.inspection(result.mission, sessionID) - } - } if (input.start) { // Creation keeps the authoritative full read: replay, membership refusal, timestamp. let snapshot = await this.snapshot() - input.start.taskMode = parseMissionTaskMode(input.start.taskMode) - try { input.start.profiles = parseMissionProfiles(input.start.profiles); validateMissionProfiles(input.start.template, input.start.profiles) } - catch { throw new MissionControlError("Invalid Mission profile selection", "invalid-execution") } - const missionID = `msn_${stableToken(`${this.options.project.id}\0${sessionID}\0${operationID}`, 24)}` + const { requestID, missionID, created } = await this.inspectCreationIdentity(sessionID, operationID) const replay = snapshot.missions.find((mission) => mission.id === missionID) - input.start.profiles = this.compareCreationProfiles(input.start.template, input.start.profiles, - replay ? replay.profiles?.roles?.comparator?.model : caller.model) if (replay) { - if (replay.template !== input.start.template || replay.objective !== input.start.objective - || replay.notes !== input.start.notes || !sameMissionProfiles(replay.profiles, input.start.profiles) - || (replay.taskMode ?? "native") !== input.start.taskMode) { - throw new MissionControlError("Creation request ID was already used with a different mission", "request-conflict") + const original = created?.type === "mission.created" && created.creationDefaults ? created : replay + const sameChoices = this.sameCreationChoices(original, input.start, replay.profiles?.roles?.comparator?.model) + if (original.template !== input.start.template || original.objective !== input.start.objective + || original.notes !== input.start.notes || !sameChoices) { + throw new MissionControlError(MISSION_CREATION_REQUEST_CONFLICT, "request-conflict") + } + if (this.options.documents && created?.type === "mission.created") { + if (!sameLocation(created.coordinator.location, caller.location)) throw new MissionControlError("Coordinator moved from its admitted creation location", "foreign-session") + await requireMissionOneTimeDocument(this.options.documents, missionID, sessionID, { + ...input.start, requestID, prepared: true, coordinatorSessionID: sessionID, expectedCoordinatorLocation: caller.location, + profiles: created.profiles, taskMode: created.taskMode ?? "native", + ...(created.creationDefaults ? { creationDefaults: created.creationDefaults } : {}), + }) } + if (created?.type === "mission.created" && created.creationDefaults) await this.creationIntents.settled(missionID) return this.inspection(replay, sessionID) } + if (created) throw new MissionControlError("Mission was deleted and cannot be recreated", "mission-deleted") await this.assertNotPurged(missionID) const active = this.membership(snapshot, sessionID) if (active?.status === "active" || active?.control?.pending.includes(sessionID)) throw new MissionControlError("This session already belongs to an active mission", "already-member") - try { await this.options.validateProfiles?.(input.start.profiles, caller.location.directory, input.start.taskMode) } + const saved = await this.savedCreationInput(input.start, missionID, "request-conflict") + let resolved = saved?.input ?? selected?.input + if (!resolved) { + if (selected?.preferenceError !== undefined) throw selected.preferenceError + throw new MissionControlError("Creation choices changed; retry the same request", "request-conflict") + } + if (selected && !sameLocation(selected.location, caller.location)) throw new MissionControlError("Coordinator moved from its admitted creation location", "foreign-session") + const taskMode = parseMissionTaskMode(resolved.taskMode) + this.assertCompareCreation(resolved.template, resolved.profiles) + if (!resolved.creationDefaults) resolved.profiles = freezeCompareProfiles(resolved.template, resolved.profiles, caller.model) + input.start = { ...resolved, taskMode } + if (this.options.documents) { + const result = await this.createCurrent({ ...resolved, taskMode, requestID, prepared: true, + coordinatorSessionID: sessionID, expectedCoordinatorLocation: caller.location }) + return this.inspection(result.mission, sessionID) + } + try { await this.options.validateProfiles?.(input.start.profiles, caller.location.directory, taskMode) } catch { throw new MissionControlError("Mission profiles do not match the owned native catalog", "invalid-execution") } const fresh = await this.ownedRootSession(sessionID) - if (!sameLocation(caller.location, fresh.location) || !matchesExecution(input.start.profiles?.coordinator, fresh)) { - throw new MissionControlError("Coordinator moved or differs from the requested native profile", "invalid-execution") - } + if (!sameLocation(caller.location, fresh.location)) throw new MissionControlError("Coordinator moved from its admitted creation location", "foreign-session") + if (!matchesExecution(input.start.profiles?.coordinator, fresh)) throw this.coordinatorProfileMismatch(resolved) const event: MissionEvent = { version: MISSION_SCHEMA_VERSION, id: this.eventID(missionID, "created"), @@ -970,6 +1066,7 @@ export class MissionControl { template: input.start.template, taskMode: input.start.taskMode, ...(input.start.profiles === undefined ? {} : { profiles: input.start.profiles }), + ...(resolved.creationDefaults === undefined ? {} : { creationDefaults: resolved.creationDefaults }), coordinator: { sessionID, title: caller.title ?? "Mission coordinator", @@ -980,6 +1077,7 @@ export class MissionControl { await this.journal.append(event) snapshot = await this.snapshot() await this.emitChanged(missionID, snapshot) + if (resolved.creationDefaults) await this.creationIntents.settled(missionID) return this.inspection(this.requireMission(snapshot, missionID), sessionID) } @@ -1004,37 +1102,85 @@ export class MissionControl { /** A paused one-time hand-off through the backend's UI creation pipeline and fences. * Never Play: the human starts it. The caller may read it later, never control it. */ - async prepare(sessionID: string, input: MissionPrepareRequest): Promise<{ mission: MissionMap }> { + prepare(sessionID: string, input: MissionPrepareRequest): Promise<{ mission: MissionMap }> { + return this.prepareCurrent(sessionID, structuredClone(input)) + } + + private async prepareCurrent(sessionID: string, input: MissionPrepareRequest): Promise<{ mission: MissionMap }> { await this.ownedRootSession(sessionID) + try { input.profiles = parseMissionProfiles(input.profiles); validateMissionProfiles(input.template, input.profiles) } + catch { throw new MissionControlError("Invalid Mission profile selection", "invalid-execution") } + const originalInput = structuredClone(input) const source = this.membership(await this.snapshot(), sessionID) - if (!source || source.status !== "active") throw new MissionControlError("No active mission is associated with this session", "mission-not-found") + if (!source || source.status !== "active") throw new MissionControlError("No active mission is associated with this session. Use the Missions editor in CodeNomad to prepare a mission; do not create a mission only to prepare others.", "mission-not-found") this.assertCoordinator(source, sessionID) - input = { ...input, profiles: this.compareCreationProfiles(input.template, input.profiles) } if (!this.options.transport?.prepare) throw new MissionControlError(BACKEND_ACTION_UNAVAILABLE, "prepare-unavailable") + const sendPreparation = this.options.transport.prepare.bind(this.options.transport) // Scoped to this coordinator and mission: another coordinator's requestID never replays into it. const requestID = `prepare_${stableToken(`${source.id}\0${sessionID}\0${input.requestID}`, 24)}` // A retry after a lost or uncertain reply finds the saved creation instead of asking the backend again. const missionID = `msn_${stableToken(`${this.options.project.id}\0${requestID}`, 24)}` const created = await this.journal.event(missionID, this.eventID(missionID, "created")) if (created) { + const sameChoices = created.type === "mission.created" && this.sameCreationChoices(created, input) if (created.type !== "mission.created" || created.prepared !== true || created.objective !== input.objective || created.title !== input.title || created.notes !== input.notes || created.template !== input.template - || (created.taskMode ?? "native") !== (input.taskMode ?? "native") || !sameMissionProfiles(created.profiles, input.profiles) + || !sameChoices || created.preparedBy?.missionID !== source.id || created.preparedBy.coordinatorSessionID !== sessionID) { - throw new MissionControlError("This requestID already prepared a different mission", "prepare-conflict") + throw missionRecoveryControlError("prepare-conflict") } const saved = (await this.snapshot()).missions.find(mission => mission.id === missionID) if (!saved) throw new MissionControlError("Mission was deleted and cannot be recreated", "mission-deleted") + if (created.creationDefaults) await this.creationIntents.settled(missionID) return { mission: saved } } await this.assertNotPurged(missionID) - const result = await this.options.transport.prepare(sessionID, { ...structuredClone(input), requestID, missionID: source.id }) - const returnedID = (result as { mission?: { id?: unknown } } | undefined)?.mission?.id - const mission = returnedID === missionID ? (await this.snapshot()).missions.find(mission => mission.id === missionID) : undefined - if (!mission || mission.preparedBy?.coordinatorSessionId !== sessionID || mission.preparedBy.missionId !== source.id) { - throw new MissionControlError("The prepared mission's outcome is uncertain; retry with the same requestID", "prepare-uncertain") - } - return { mission } + let retained = await this.creationIntents.read(missionID, input, + () => this.journal.event(missionID, this.eventID(missionID, "created")), "prepare-conflict") + const resolved = retained ? { input: { ...input, profiles: retained.profiles, taskMode: retained.taskMode, creationDefaults: retained }, fromDocument: false } + : await this.resolveCreationInput(sessionID, input, missionID, "prepare-conflict") + const retainedDocument = resolved.fromDocument + input = resolved.input + this.assertCompareCreation(input.template, input.profiles) + if (!input.creationDefaults) input.profiles = freezeCompareProfiles(input.template, input.profiles) + // Native effects for one request stay single-flight; independent preference + // reads can complete concurrently before the first choice is reserved. + return runMissionExclusive(`prepare:${this.journal.projectToken}:${sessionID}:${originalInput.requestID}`, async () => { + if (await this.journal.event(missionID, this.eventID(missionID, "created"))) return this.prepareCurrent(sessionID, originalInput) + retained = await this.creationIntents.read(missionID, originalInput, + () => this.journal.event(missionID, this.eventID(missionID, "created")), "prepare-conflict") + if (retained) input = { ...input, profiles: retained.profiles, taskMode: retained.taskMode, creationDefaults: retained } + let dispatched = false + let result: unknown + try { + if (input.creationDefaults) { + const caller = await this.ownedRootSession(sessionID) + try { await this.options.validateProfiles?.(input.profiles, caller.location.directory, parseMissionTaskMode(input.taskMode)) } + catch { throw new MissionControlError("Mission profiles do not match the owned native catalog", "invalid-execution") } + input = await this.retainCreationInput(input, missionID, "prepare-conflict") + } + this.assertActive() + dispatched = true + result = await sendPreparation(sessionID, { ...structuredClone(input), requestID, missionID: source.id }) + } catch (error) { + if (error instanceof MissionControlError && ["prepare-conflict", "request-conflict"].includes(error.code) + && !(error instanceof MissionCreateNoEffectError)) throw error + const originalNoEffect = error instanceof MissionCreateNoEffectError && error.noEffect.requestID === requestID && error.noEffect.missionID === missionID + || error instanceof MissionControlError && error.code === "prepare-no-effect" + const refused = error instanceof MissionControlError && ["prepare-refused", "mission-preferences-update-required"].includes(error.code) + if (originalNoEffect || !retained && !retainedDocument && (!dispatched || refused)) { + await this.creationIntents.settled(missionID) + throw error + } + throw missionRecoveryControlError("prepare-uncertain") + } + const returnedID = (result as { mission?: { id?: unknown } } | undefined)?.mission?.id + const mission = returnedID === missionID ? (await this.snapshot()).missions.find(mission => mission.id === missionID) : undefined + if (!mission || mission.preparedBy?.coordinatorSessionId !== sessionID || mission.preparedBy.missionId !== source.id) { + throw missionRecoveryControlError("prepare-uncertain") + } + return { mission } + }) } /** Advisory native evidence of a native task's own conversations; never settlement. */ @@ -1720,8 +1866,10 @@ export class MissionControl { } private inspection(mission: MissionMap, sessionID: string): MissionInspection { + const { creationDefaults: _creationDefaults, ...view } = mission return { - mission, + mission: view, + ...(mission.creationDefaults ? { selection: missionCreationSelection(mission) } : {}), actor: mission.actors.find((candidate) => candidate.sessionId === sessionID) ?? null, templates: missionRecipeCatalog(), playbook: getMissionRecipe(mission.template, mission.taskMode), diff --git a/packages/server/src/missions/coordinator-actions.test.ts b/packages/server/src/missions/coordinator-actions.test.ts index ccd3f853b5..17761dc718 100644 --- a/packages/server/src/missions/coordinator-actions.test.ts +++ b/packages/server/src/missions/coordinator-actions.test.ts @@ -1,16 +1,20 @@ import assert from "node:assert/strict" import test from "node:test" -import { MissionControl } from "./control" +import { MissionControl, MissionControlError } from "./control" +import { MissionCreateNoEffectError } from "./control-error" +import { stableToken } from "./receipt-identity" import type { MissionInputTransport, MissionSessionAdapter, NativeMissionSession } from "./control-types" import type { HumanDecisionCandidate, HumanDecisionDiscovery, NativeHumanAnswerGate } from "./human-answer" import type { MissionStorage } from "./journal" import type { MissionJsonValue, MissionTask } from "./model" import { liveContinuations } from "./coordinator-actions" +import { resolveMissionCreationDefaults } from "./profile-defaults" class MemoryStorage implements MissionStorage { readonly values = new Map() async get(key: string) { return this.values.get(key) } async set(key: string, value: MissionJsonValue) { this.values.set(key, structuredClone(value)) } + async remove(key: string) { this.values.delete(key) } async scan(options: { prefix: string; after?: string; limit?: number }) { const keys = [...this.values.keys()].filter(key => key.startsWith(options.prefix)).sort() const start = options.after ? Math.max(0, keys.findIndex(key => key > options.after!)) : 0 @@ -22,8 +26,10 @@ class MemoryStorage implements MissionStorage { const coordinator = "ses_coordinator" -function fixture(options: { transport?: Partial; humanGate?: NativeHumanAnswerGate } = {}) { - const sessions = new Map([[coordinator, +function fixture(options: { transport?: Partial; humanGate?: NativeHumanAnswerGate; + validateProfiles?: ConstructorParameters[0]["validateProfiles"]; + storage?: MemoryStorage; sessions?: Map } = {}) { + const sessions = options.sessions ?? new Map([[coordinator, { id: coordinator, projectID: "project-1", title: "Coordinator", location: { directory: "/repo" } }]]) const adapter: MissionSessionAdapter = { get: async ({ sessionID }) => { const session = sessions.get(sessionID); if (!session) throw new Error("not found"); return session }, @@ -35,17 +41,63 @@ function fixture(options: { transport?: Partial; humanGat prompt: async () => {}, synthetic: async () => {}, } let now = 1_000 + const storage = options.storage ?? new MemoryStorage() const transport = options.transport && { prompt: async () => {}, synthetic: async () => {}, ...options.transport } as MissionInputTransport const control = new MissionControl({ project: { id: "project-1", canonical: "/repo", location: { directory: "/repo" } }, - storage: new MemoryStorage(), sessions: adapter, transport, humanGate: options.humanGate, now: () => now++ }) + storage, sessions: adapter, transport, validateProfiles: options.validateProfiles, humanGate: options.humanGate, now: () => now++ }) const start = async (template: "wayfinder" | "custom" = "wayfinder") => (await control.inspect(coordinator, { start: { objective: "Chart the pilot", template } }, "start")).mission! const declare = (taskKey: string, role = "research") => control.declare(coordinator, { taskKey, title: `Task ${taskKey}`, brief: "Bounded work", role, blockedBy: [] }) const current = async () => (await control.snapshot()).missions.find(mission => mission.coordinatorSessionId === coordinator)! - return { control, sessions, start, declare, current } + return { control, sessions, storage, start, declare, current } } +test("a stalled inspect-start preference read never holds the project's mutation lock", async () => { + let started!: () => void, release!: (value: ReturnType) => void + const reading = new Promise(resolve => { started = resolve }) + const preferences = new Promise>(resolve => { release = resolve }) + const f = fixture({ transport: { resolveCreationDefaults: async () => { started(); return preferences } } }) + const source = (await f.control.create({ requestID: "source", objective: "Source", template: "custom", coordinatorSessionID: coordinator })).mission + f.sessions.set("ses_waiting", { id: "ses_waiting", projectID: "project-1", location: { directory: "/repo" } }) + const inspect = f.control.inspect("ses_waiting", { start: { objective: "Waiting", template: "custom" } }, "waiting") + await reading + let timer: ReturnType | undefined + try { + const changed = await Promise.race([ + f.control.update({ missionID: source.id, requestID: "unrelated-edit", expectedRevision: source.revision, objective: "Still responsive" }), + new Promise((_, reject) => { timer = setTimeout(() => reject(new Error("Preference I/O held the project mutation lock")), 2_000) }), + ]) + assert.equal(changed.mission.objective, "Still responsive") + } finally { + clearTimeout(timer) + release(resolveMissionCreationDefaults({ template: "custom", preferences: [] })) + await inspect + } +}) + +test("a coordinator moving during the final creation preflight is a foreign-session refusal", async () => { + const sessions = new Map([[coordinator, + { id: coordinator, projectID: "project-1", location: { directory: "/repo" } }]]) + const f = fixture({ sessions, validateProfiles: async () => { + sessions.set(coordinator, { ...sessions.get(coordinator)!, location: { directory: "/repo/moved" } }) + } }) + await assert.rejects(f.start("custom"), (error: unknown) => error instanceof MissionControlError + && error.code === "foreign-session" && error.message === "Coordinator moved from its admitted creation location") + assert.equal(f.storage.values.size, 0) +}) + +test("explicit prepare capability refusals release newly recorded choices", async () => { + const f = fixture({ transport: { prepare: async () => { throw new MissionControlError("Update CodeNomad", "mission-preferences-update-required") } } }) + await f.control.create({ requestID: "source", objective: "Source", template: "custom", coordinatorSessionID: coordinator }) + for (let i = 0; i < 2; i++) { + await assert.rejects(f.control.prepare(coordinator, { requestID: "old-backend", objective: "Hand-off", template: "custom", + profiles: { coordinator: {}, roles: { specialist: {} } }, taskMode: "native" }), + (error: unknown) => error instanceof MissionControlError && error.code === "mission-preferences-update-required") + assert.equal([...f.storage.values.keys()].some(key => key.includes("/creation-intents/")), false) + } +}) + test("one replacement may merge several retired tasks; it names one of them as its lineage head", async () => { const f = fixture() await f.start() @@ -93,6 +145,7 @@ test("prepare creates a paused hand-off through the backend; its coordinator may const f = fixture({ transport: { prepare: async (coordinatorID, input) => { requests.push(input) return control.create({ prepared: true, requestID: input.requestID, objective: input.objective, template: input.template, + profiles: input.profiles, creationDefaults: input.creationDefaults, taskMode: input.taskMode, preparedBy: { missionID: input.missionID, coordinatorSessionID: coordinatorID } }) } } }) control = f.control @@ -118,21 +171,219 @@ test("prepare creates a paused hand-off through the backend; its coordinator may }) test("a prepare retry after a lost reply returns the saved hand-off without another backend call", async () => { - let control!: MissionControl, calls = 0 - const f = fixture({ transport: { prepare: async (coordinatorID, input) => { + let control!: MissionControl, calls = 0, reads = 0 + let preferences: unknown = [{ template: "all", profiles: { roles: { specialist: { agent: "worker" } } }, taskMode: "independent" }] + const transport: Partial = { + resolveCreationDefaults: async (_sessionID, input) => { reads++; return resolveMissionCreationDefaults({ ...input, preferences }) }, + prepare: async (coordinatorID, input) => { calls++ await control.create({ prepared: true, requestID: input.requestID, objective: input.objective, template: input.template, + profiles: input.profiles, creationDefaults: input.creationDefaults, taskMode: input.taskMode, preparedBy: { missionID: input.missionID, coordinatorSessionID: coordinatorID } }) throw new Error("Bridge reply lost") - } } }) + } } + const f = fixture({ transport }) control = f.control await f.start() const request = { requestID: "pilot", objective: "Run the pilot", template: "custom" as const } - await assert.rejects(control.prepare(coordinator, request), /reply lost/) - const { mission } = await control.prepare(coordinator, request) - assert.deepEqual([calls, mission.runState, mission.objective], [1, "prepared", "Run the pilot"]) + await assert.rejects(control.prepare(coordinator, request), (error: any) => error.code === "prepare-uncertain") + const before = structuredClone([...f.storage.values]) + const frozen = resolveMissionCreationDefaults({ template: "custom", preferences }) + const resolvedReads = reads + for (preferences of [[], { invalid: true }]) { + control = fixture({ transport, storage: f.storage, sessions: f.sessions }).control + const { mission } = await control.prepare(coordinator, request) + assert.deepEqual([calls, reads, mission.runState, mission.objective], [1, resolvedReads, "prepared", "Run the pilot"]) + assert.deepEqual(mission.profiles, frozen.profiles) + assert.equal(mission.taskMode, "independent") + assert.deepEqual(mission.creationDefaults, { request: {}, ...frozen }) + assert.deepEqual([...f.storage.values], before) + } await assert.rejects(control.prepare(coordinator, { ...request, objective: "A different pilot" }), /already prepared a different mission/) + await assert.rejects(control.prepare(coordinator, { ...request, profiles: {} }), /already prepared a different mission/) + await assert.rejects(control.prepare(coordinator, { ...request, taskMode: "independent" }), /already prepared a different mission/) + assert.equal(calls, 1) + assert.equal(reads, resolvedReads, "conflicting requests also leave preferences unread") +}) + +test("a definite refusal releases its choice and the same request can use corrected preferences", async () => { + let control!: MissionControl, refused = false, reads = 0 + let worker = "worker-before" + const f = fixture({ transport: { + resolveCreationDefaults: async (_id, input) => { reads++; return resolveMissionCreationDefaults({ ...input, + preferences: [{ template: "all", profiles: { roles: { specialist: { agent: worker } } } }] }) }, + prepare: async (coordinatorID, input) => { + if (!refused) { refused = true; throw new MissionControlError("Nothing created", "prepare-refused") } + return control.create({ ...input, prepared: true, preparedBy: { missionID: input.missionID, coordinatorSessionID: coordinatorID } }) + }, + } }) + control = f.control + await f.start() + const request = { requestID: "refused", objective: "Pilot", template: "custom" as const } + await assert.rejects(control.prepare(coordinator, request), /Nothing created/) + const previousReads = reads + worker = "worker-after" + const result = await control.prepare(coordinator, request) + assert.equal(reads, previousReads + 1) + assert.deepEqual(result.mission.creationDefaults?.profiles?.roles?.specialist, { agent: "worker-after" }) +}) + +test("inspect start freezes resolved choices and replays them after preference failure and reinstantiation", async () => { + let preferences: unknown = [{ template: "all", profiles: { coordinator: { agent: "lead" }, roles: { specialist: { agent: "worker" } } }, taskMode: "independent" }] + let reads = 0 + const transport: Partial = { resolveCreationDefaults: async (_sessionID, input) => { + reads++; return resolveMissionCreationDefaults({ ...input, preferences }) + } } + const f = fixture({ transport }) + f.sessions.set(coordinator, { ...f.sessions.get(coordinator)!, agent: "lead" }) + const start = { objective: "Frozen selection", template: "custom" as const } + const first = await f.control.inspect(coordinator, { start }, "frozen-start") + const selection = resolveMissionCreationDefaults({ ...start, preferences }) + assert.deepEqual(first.selection, selection) + assert.equal("creationDefaults" in first.mission!, false) + assert.deepEqual((await f.control.snapshot()).missions[0].creationDefaults, { request: {}, ...selection }) + const before = structuredClone([...f.storage.values]) + preferences = { invalid: true } + const restarted = fixture({ transport, storage: f.storage, sessions: f.sessions }).control + assert.deepEqual(await restarted.inspect(coordinator, { start }, "frozen-start"), first) + await assert.rejects(restarted.inspect(coordinator, { start: { ...start, profiles: {} } }, "frozen-start"), /different mission/) + await assert.rejects(restarted.inspect(coordinator, { start: { ...start, taskMode: "independent" } }, "frozen-start"), /different mission/) + assert.equal(reads, 1) + assert.deepEqual([...f.storage.values], before) +}) + +test("resolved coordinator mismatches and identical preferred Compare models fail before persistence or prepare", async () => { + const preferences = [{ template: "all", profiles: { coordinator: { agent: "lead" } } }] + const f = fixture({ transport: { resolveCreationDefaults: async (_sessionID, input) => resolveMissionCreationDefaults({ ...input, preferences }) } }) + await assert.rejects(f.control.inspect(coordinator, { start: { objective: "Mismatch", template: "custom" } }, "mismatch"), /Missions preferences.*profiles\.coordinator.*\{\}/) + assert.equal(f.storage.values.size, 0) + const model = { providerID: "p", id: "same" } + const compare = fixture({ transport: { + resolveCreationDefaults: async (_sessionID, input) => resolveMissionCreationDefaults({ ...input, preferences: [ + { template: "compare", profiles: { roles: { "model-a": { model }, "model-b": { model } } } }, + ] }), + prepare: async () => assert.fail("Invalid Compare must never reach preparation"), + } }) + await assert.rejects(compare.control.inspect(coordinator, { start: { objective: "Compare", template: "compare" } }, "compare"), /compare-models-identical/) + assert.equal(compare.storage.values.size, 0) + await compare.start("custom") + const before = structuredClone([...compare.storage.values]) + await assert.rejects(compare.control.prepare(coordinator, { requestID: "compare", objective: "Compare", template: "compare" }), /compare-models-identical/) + assert.deepEqual([...compare.storage.values], before) +}) + +test("inspect Compare freezes the known coordinator model for an omitted judge across native model changes", async () => { + let reads = 0 + const f = fixture({ transport: { resolveCreationDefaults: async (_id, input) => { + reads++; return resolveMissionCreationDefaults({ ...input, preferences: [] }) + } } }) + f.sessions.get(coordinator)!.model = { providerID: "p", id: "coordinator-x", variant: "default" } + const start = { objective: "Compare", template: "compare" as const, profiles: { roles: { + "model-a": { model: { providerID: "p", id: "a" } }, "model-b": { model: { providerID: "p", id: "b" } }, + } } } + const result = await f.control.inspect(coordinator, { start }, "known-coordinator") + assert.deepEqual(result.selection?.profiles.roles?.comparator, { model: { providerID: "p", id: "coordinator-x" } }) + assert.equal(result.selection?.origins.roles.comparator, "opencode-default") + f.sessions.get(coordinator)!.model = { providerID: "p", id: "native-default-y" } + assert.deepEqual((await f.control.inspect(coordinator, { start }, "known-coordinator")).selection, result.selection) + assert.equal(reads, 1) +}) + +test("prepare outside a mission points to the editor without resolving preferences or creating anything", async () => { + const f = fixture({ transport: { + resolveCreationDefaults: async () => assert.fail("No preference read outside a mission"), + prepare: async () => assert.fail("No preparation outside a mission"), + } }) + await assert.rejects(f.control.prepare(coordinator, { requestID: "pilot", objective: "Pilot", template: "custom" }), /Missions editor.*do not create a mission only to prepare others/) + assert.equal(f.storage.values.size, 0) + assert.equal(f.sessions.size, 1) +}) + +test("128 definite preparation refusals leave capacity available for the next request", async () => { + for (const certificate of [false, true]) { + let control!: MissionControl, refuse = true + const f = fixture({ transport: { + resolveCreationDefaults: async (_id, input) => resolveMissionCreationDefaults({ ...input, preferences: [] }), + prepare: async (id, input) => { + if (refuse) { + if (certificate) throw new MissionCreateNoEffectError(input.requestID, `msn_${stableToken(`project-1\0${input.requestID}`, 24)}`) + throw new MissionControlError("Nothing created", "prepare-refused") + } + return control.create({ ...input, prepared: true, preparedBy: { missionID: input.missionID, coordinatorSessionID: id } }) + }, + } }) + control = f.control + await f.start("custom") + for (let index = 0; index < 128; index++) { + await assert.rejects(control.prepare(coordinator, { requestID: `refused-${index}`, objective: "Pilot", template: "custom" }), + (error: any) => error.code === (certificate ? "request-conflict" : "prepare-refused")) + } + assert.equal([...f.storage.values.keys()].filter(key => key.includes("/creation-intents/")).length, 0) + refuse = false + assert.equal((await control.prepare(coordinator, { requestID: "allowed", objective: "Pilot", template: "custom" })).mission.runState, "prepared") + } +}) + +test("an explicit cross-playbook profile fails before reading user preferences", async () => { + const f = fixture({ transport: { + resolveCreationDefaults: async () => assert.fail("The agent must correct its own input first"), + prepare: async () => assert.fail("Invalid input cannot reach preparation"), + } }) + await f.control.create({ requestID: "source", objective: "Source", template: "custom", coordinatorSessionID: coordinator }) + const before = structuredClone([...f.storage.values]) + await assert.rejects(f.control.prepare(coordinator, { requestID: "bad", objective: "Debug", template: "debug", profiles: { roles: { specialist: {} } } }), + (error: any) => error.code === "invalid-execution" && !/preferences/.test(error.message)) + assert.deepEqual([...f.storage.values], before) +}) + +test("both creation tools bypass preferences when every slot and the task policy are explicit", async () => { + for (const method of ["inspect", "prepare"] as const) { + let control!: MissionControl, prepares = 0 + const f = fixture({ transport: { + resolveCreationDefaults: async () => assert.fail("Unused preferences must not be read"), + prepare: async (id, input) => { prepares++; return control.create({ ...input, prepared: true, + preparedBy: { missionID: input.missionID, coordinatorSessionID: id } }) }, + } }) + control = f.control + if (method === "prepare") await control.create({ requestID: "source", objective: "Source", template: "custom", coordinatorSessionID: coordinator }) + const input = { objective: "Explicit", template: "custom" as const, taskMode: "native" as const, + profiles: { coordinator: {}, roles: { specialist: {} } } } + const result = method === "inspect" ? await control.inspect(coordinator, { start: input }, "explicit") + : await control.prepare(coordinator, { ...input, requestID: "explicit" }) + const saved = (await control.snapshot()).missions.find(mission => mission.id === result.mission!.id)! + assert.deepEqual(saved.creationDefaults?.origins, { coordinator: "explicit", roles: { specialist: "explicit" }, taskMode: "explicit" }) + assert.equal(saved.creationDefaults?.preferences, undefined) + assert.equal(prepares, method === "prepare" ? 1 : 0, "only hand-off creation still requires its backend") + } +}) + +test("an explicit empty coordinator slot overrides a mismatching coordinator preference", async () => { + const f = fixture({ transport: { resolveCreationDefaults: async (_id, input) => resolveMissionCreationDefaults({ ...input, + preferences: [{ template: "all", profiles: { coordinator: { agent: "other" } } }] }) } }) + const result = await f.control.inspect(coordinator, { start: { objective: "Explicit default", template: "custom", profiles: { coordinator: {} } } }, "override") + assert.deepEqual(result.selection?.profiles.coordinator, {}) + assert.equal(result.selection?.origins.coordinator, "explicit") +}) + +test("a failed local catalog preflight cannot relabel an earlier unknown preparation", async () => { + let failCatalog = false, calls = 0, reads = 0 + const f = fixture({ + validateProfiles: async () => { if (failCatalog) throw new Error("Catalog unavailable") }, + transport: { + resolveCreationDefaults: async (_id, input) => { reads++; return resolveMissionCreationDefaults({ ...input, preferences: [] }) }, + prepare: async () => { calls++; throw new MissionControlError("Unknown native outcome", "prepare-uncertain") }, + }, + }) + await f.start("custom") + const request = { requestID: "unknown", objective: "Pilot", template: "custom" as const } + await assert.rejects(f.control.prepare(coordinator, request), (error: any) => error.code === "prepare-uncertain") + const previousReads = reads + failCatalog = true + await assert.rejects(f.control.prepare(coordinator, request), (error: any) => error.code === "prepare-uncertain") + await assert.rejects(f.control.prepare(coordinator, { ...request, objective: "Another pilot" }), (error: any) => error.code === "prepare-conflict") + assert.equal(reads, previousReads) assert.equal(calls, 1) + assert.equal([...f.storage.values.keys()].filter(key => key.includes("/creation-intents/")).length, 1) }) test("a retired native task's conversations are observed and stopped only through validated bridge replies", async () => { diff --git a/packages/server/src/missions/creation-defaults.test.ts b/packages/server/src/missions/creation-defaults.test.ts new file mode 100644 index 0000000000..151e3837a4 --- /dev/null +++ b/packages/server/src/missions/creation-defaults.test.ts @@ -0,0 +1,332 @@ +import assert from "node:assert/strict" +import test from "node:test" +import Ajv from "ajv" +import { MissionControl, MissionControlError } from "./control" +import type { MissionInputTransport, NativeMissionSession } from "./control-types" +import { missionCreationDefaultsSchema, missionCreationDefaultsWire, missionCreationSelection, parseMissionCreationDefaults, parseMissionCreationDefaultsInput, parseMissionCreationSelection } from "./creation-defaults" +import type { MissionStorage } from "./journal" +import type { MissionJsonValue } from "./model" +import { NativeMissionDocumentStore, type MissionDocumentStorage } from "./mission-document-store" +import { MISSION_DEFAULT_ORIGINS, MISSION_PREFERENCES_UNAVAILABLE, resolveMissionCreationDefaults } from "./profile-defaults" +import { CODENOMAD_MISSIONS_RPC } from "./rpc" +import { freezeCompareProfiles, missionProfileRoles } from "./playbook-profiles" + +test("creation default requests accept exactly the shared playbook keys", () => { + for (const template of Object.keys(missionProfileRoles)) assert.equal(parseMissionCreationDefaultsInput({ template }).template, template) + for (const template of ["other", "all", "toString", "__proto__", null]) { + assert.throws(() => parseMissionCreationDefaultsInput({ template }), (error: any) => error.code === "invalid-execution") + } +}) + +function fixture() { + const values = new Map() + const coordinator = "ses_coordinator" + const sessions = new Map([[coordinator, + { id: coordinator, agent: "lead", projectID: "project", location: { directory: "/repo" } }]]) + let failJournal = false, failDocument = false, refusePreparation = false, reads = 0, created = 0 + let preferences: unknown = [{ template: "all", profiles: { coordinator: { agent: "lead" }, roles: { specialist: { agent: "worker" } } } }] + const storage: MissionStorage & MissionDocumentStorage = { + get: async key => structuredClone(values.get(key)), + set: async (key, value) => { + if (failJournal && value && typeof value === "object" && "type" in value && value.type === "mission.created") { + failJournal = false; throw new Error("Journal write unavailable") + } + values.set(key, structuredClone(value)) + }, + compareAndSet: async (key, value, expected, current) => { + current() + if (failDocument) { failDocument = false; throw new Error("Document write unavailable") } + assert.equal((values.get(key) as { revision?: number } | undefined)?.revision ?? null, expected) + values.set(key, structuredClone(value)) + }, + scan: async ({ prefix }) => ({ entries: [...values].filter(([key]) => key.startsWith(prefix)).sort(([a], [b]) => a.localeCompare(b)) + .map(([key, value]) => ({ key, value: structuredClone(value) })) }), + } + const documents = new NativeMissionDocumentStore(storage, "project", "/repo") + const access = (use: (store: NativeMissionDocumentStore) => Promise) => use(documents) + const transport: MissionInputTransport = { + prompt: async () => assert.fail("Creation never prompts"), synthetic: async () => assert.fail("Creation never resumes"), + resolveCreationDefaults: async (_id, input) => { reads++; return resolveMissionCreationDefaults({ ...input, preferences }) }, + prepare: async (id, input) => { + if (refusePreparation) throw new MissionControlError("Nothing created by this call", "prepare-refused") + return control.create({ ...input, prepared: true, preparedBy: { missionID: input.missionID, coordinatorSessionID: id } }) + }, + } + const options: ConstructorParameters[0] = { + project: { id: "project", canonical: "/repo", location: { directory: "/repo" } }, storage, + documents: access, documentReads: access, transport, now: () => 1_790_000_000_000, + sessions: { + get: async ({ sessionID }) => { const session = sessions.get(sessionID); if (!session) throw new Error("Missing"); return session }, + create: async input => { created++; const session = { ...input, projectID: "project" }; sessions.set(session.id, session); return session }, + prompt: async () => assert.fail("Creation never prompts"), synthetic: async () => assert.fail("Creation never resumes"), + }, + } + let control = new MissionControl(options) + return { get control() { return control }, coordinator, documents, values, sessions, get reads() { return reads }, get created() { return created }, + transport, fail: () => { failJournal = true }, failBeforeDocument: () => { failDocument = true }, + refusePreparation: () => { refusePreparation = true }, + setPreferences: (value: unknown) => { preferences = value }, invalidate: () => { preferences = null }, restart: () => { control = new MissionControl(options) } } +} + +test("both agent creation paths store the editor's effective Compare judge and freeze the selected slot's origin", async () => { + const model = { providerID: "p", id: "coordinator" } + for (const method of ["prepare", "inspect"] as const) for (const origin of ["explicit", "preference"] as const) { + for (const comparator of [{}, { agent: "judge" }, { agent: "judge", model: { providerID: "p", id: "own" } }]) { + const f = fixture() + f.sessions.get(f.coordinator)!.model = model + if (method === "prepare") await f.control.create({ requestID: "source", objective: "Source", template: "custom", coordinatorSessionID: f.coordinator }) + const profiles = { coordinator: { model }, roles: { "model-a": { model: { providerID: "p", id: "a" } }, + "model-b": { model: { providerID: "p", id: "b" } }, comparator } } + f.setPreferences(origin === "preference" ? [{ template: "compare", profiles }] : []) + const request = { objective: "Compare", template: "compare" as const, ...(origin === "explicit" ? { profiles } : {}) } + const create = async () => { + if (method === "inspect") return f.control.inspect(f.coordinator, { start: request }, "compare") + const { mission } = await f.control.prepare(f.coordinator, { ...request, requestID: "compare" }) + return { mission, selection: missionCreationSelection(mission) } + } + const result = await create() + assert.ok(result.mission) + const selected = result.selection + assert.deepEqual(result.mission.profiles, freezeCompareProfiles("compare", profiles)) + assert.deepEqual(selected?.profiles, result.mission.profiles) + assert.equal(selected?.origins.roles.comparator, origin) + const reads = f.reads + f.invalidate(); f.restart() + assert.deepEqual((await create()).selection, selected) + assert.equal(f.reads, reads, "the completed judge model is retained without another preference read") + } + } +}) + +test("inspect start recovers frozen preferences from its document before a missing creation event", async () => { + const f = fixture(), start = { objective: "Frozen document", template: "custom" as const } + f.fail() + await assert.rejects(f.control.inspect(f.coordinator, { start }, "inspect-create"), /Journal write unavailable/) + assert.equal(f.reads, 1) + f.invalidate(); f.restart() + await assert.rejects(f.control.inspect(f.coordinator, { start: { ...start, profiles: {} } }, "inspect-create"), /different mission/) + const result = await f.control.inspect(f.coordinator, { start }, "inspect-create") + assert.equal(result.mission?.runState, "prepared") + assert.deepEqual(result.selection?.profiles.roles, { specialist: { agent: "worker" } }) + assert.equal(result.selection?.origins.roles.specialist, "preference") + assert.equal(f.reads, 1, "even invalid current preferences are unread on recovery") + const ajv = new Ajv({ allErrors: true }) + const validate = ajv.compile(CODENOMAD_MISSIONS_RPC.methods.create.output) + assert.ok(validate({ mission: result.mission }), JSON.stringify(validate.errors)) + const document = await f.documents.read(result.mission!.id) + assert.ok(document && !("deletedAt" in document)) + assert.equal("creationDefaults" in result.mission!, false, "inspection exposes only the documented selection") + assert.deepEqual(missionCreationSelection({ creationDefaults: document.oneTime?.creationDefaults }), result.selection) + await f.documents.change(document.id, document.revision, () => true, next => { next.configuration.profiles = {} }) + assert.deepEqual(missionCreationSelection({ creationDefaults: document.oneTime?.creationDefaults, profiles: {}, taskMode: "independent" }), result.selection, + "the creation receipt keeps its original selection after profile edits") + await assert.rejects(f.documents.change(document.id, document.revision + 1, () => true, next => { + next.oneTime!.creationDefaults!.origins.coordinator = "explicit" + }), /progress is monotone/, "creation provenance is immutable") + await f.control.update({ missionID: result.mission!.id, objective: "Human-edited objective", requestID: "edit", + expectedRevision: result.mission!.revision }) + const replay = await f.control.inspect(f.coordinator, { start }, "inspect-create") + assert.equal(replay.mission?.objective, "Human-edited objective") + assert.deepEqual(replay.selection, result.selection, "replay matches the original creation rather than later editor fields") + assert.equal(f.reads, 1) +}) + +test("inspect preflight races retain the first published event or frozen document choices", async () => { + for (const journalFails of [false, true]) for (const preferencesFail of [false, true]) { + const f = fixture() + const gates: Array<() => void> = [] + let started!: () => void + const both = new Promise(resolve => { started = resolve }) + f.transport.resolveCreationDefaults = async (_id, input) => { + const agent = gates.length === 0 ? "first" : "second" + await new Promise(resolve => { gates.push(resolve); if (gates.length === 2) started() }) + if (agent === "second" && preferencesFail) throw new Error("Preferences became unavailable") + return resolveMissionCreationDefaults({ ...input, preferences: [{ template: "all", profiles: { + coordinator: { agent: "lead" }, roles: { specialist: { agent } }, + } }] }) + } + const request = { start: { objective: "Concurrent", template: "custom" as const } } + if (journalFails) f.fail() + const first = f.control.inspect(f.coordinator, request, "same-operation") + const firstOutcome = first.catch(error => error) + const second = f.control.inspect(f.coordinator, request, "same-operation") + await both + gates[0]() + if (journalFails) assert.match(String(await firstOutcome), /Journal write unavailable/) + else await first + gates[1]() + assert.equal((await second).selection?.profiles.roles.specialist.agent, "first") + } +}) + +test("document-mode inspect replay rejects moved coordinators and altered creation digests", async () => { + const f = fixture(), request = { start: { objective: "Replay", template: "custom" as const } } + await f.control.inspect(f.coordinator, request, "replay") + f.sessions.get(f.coordinator)!.location = { directory: "/repo/other" } + await assert.rejects(f.control.inspect(f.coordinator, request, "replay"), (error: any) => error.code === "foreign-session") + f.sessions.get(f.coordinator)!.location = { directory: "/repo" } + const entry = [...f.values].find(([, value]) => value && typeof value === "object" && "oneTime" in value)! + const damaged = structuredClone(entry[1]) as any + damaged.oneTime.creationDigest = "0".repeat(64) + f.values.set(entry[0], damaged) + await assert.rejects(f.control.inspect(f.coordinator, request, "replay"), (error: any) => error.code === "request-conflict") +}) + +test("prepare recovers its frozen document before journal publication without rereading preferences", async () => { + const f = fixture() + await f.control.create({ requestID: "source", objective: "Source", template: "custom", coordinatorSessionID: f.coordinator }) + const request = { requestID: "pilot", objective: "Pilot", template: "custom" as const } + f.fail() + await assert.rejects(f.control.prepare(f.coordinator, request), (error: any) => error.code === "prepare-uncertain") + assert.equal(f.reads, 1) + assert.equal(f.created, 1) + f.invalidate(); f.restart() + await assert.rejects(f.control.prepare(f.coordinator, { ...request, profiles: {} }), { code: "prepare-conflict", message: "This requestID already prepared a different mission" }) + const result = await f.control.prepare(f.coordinator, request) + assert.deepEqual(result.mission.profiles?.roles, { specialist: { agent: "worker" } }) + assert.equal(result.mission.creationDefaults?.origins.coordinator, "preference") + assert.equal(f.reads, 1) + assert.equal(f.created, 1, "retry reuses the same unprompted root") +}) + +test("the pre-dispatch creation intention survives a failure before the first document and reinstantiation", async () => { + const f = fixture() + await f.control.create({ requestID: "source", objective: "Source", template: "custom", coordinatorSessionID: f.coordinator }) + const request = { requestID: "before-document", objective: "Pilot", template: "custom" as const } + f.failBeforeDocument() + await assert.rejects(f.control.prepare(f.coordinator, request), (error: any) => error.code === "prepare-uncertain") + assert.equal(f.reads, 1) + assert.equal(f.created, 0) + f.invalidate(); f.restart() + const result = await f.control.prepare(f.coordinator, request) + assert.deepEqual(result.mission.profiles?.roles, { specialist: { agent: "worker" } }) + assert.equal(f.reads, 1) + assert.equal(f.created, 1) +}) + +test("a damaged retained preparation leaves other requests usable and its own ID blocked", async () => { + const f = fixture() + await f.control.create({ requestID: "source", objective: "Source", template: "custom", coordinatorSessionID: f.coordinator }) + const damagedRequest = { requestID: "damaged", objective: "Uncertain preparation", template: "custom" as const } + f.failBeforeDocument() + await assert.rejects(f.control.prepare(f.coordinator, damagedRequest), (error: any) => error.code === "prepare-uncertain") + const key = [...f.values.keys()].find(key => key.includes("/creation-intents/"))! + assert.ok(key) + const damaged = { version: 1 } + f.values.set(key, damaged) + const unaffected = await f.control.prepare(f.coordinator, { requestID: "unaffected", objective: "Other preparation", template: "custom" }) + assert.equal(unaffected.mission.runState, "prepared") + const reads = f.reads, roots = f.created + await assert.rejects(f.control.prepare(f.coordinator, damagedRequest), (error: any) => error.code === "invalid-journal") + assert.equal(f.reads, reads) + assert.equal(f.created, roots) + assert.deepEqual(f.values.get(key), damaged) +}) + +test("creation provenance validates its exact roles and leaves historical missions absent", () => { + const selected = resolveMissionCreationDefaults({ template: "custom", preferences: [] }) + const metadata = { request: {}, ...selected } + assert.deepEqual(parseMissionCreationDefaults("custom", metadata), metadata) + assert.throws(() => parseMissionCreationDefaults("debug", metadata)) + assert.throws(() => parseMissionCreationDefaults("custom", { ...metadata, origins: { ...metadata.origins, coordinator: "guessed" } })) + assert.equal(missionCreationSelection({ profiles: {}, taskMode: "native" }), undefined) +}) + +test("transport selections and durable defaults require complete profiles and exact playbook roles", () => { + for (const template of Object.keys(missionProfileRoles) as (keyof typeof missionProfileRoles)[]) { + const selected = resolveMissionCreationDefaults({ template, preferences: [] }) + assert.deepEqual(parseMissionCreationSelection(template, selected), selected) + for (const profiles of [undefined, {}, { coordinator: {} }, { roles: selected.profiles.roles }, + { ...selected.profiles, roles: {} }, { ...selected.profiles, roles: { ...selected.profiles.roles, unknown: {} } }, + ...missionProfileRoles[template].map(removed => ({ ...selected.profiles, + roles: Object.fromEntries(Object.entries(selected.profiles.roles).filter(([role]) => role !== removed)) }))]) { + const partial = { ...selected, profiles } + assert.throws(() => parseMissionCreationSelection(template, partial)) + assert.throws(() => parseMissionCreationDefaults(template, { request: {}, ...partial })) + } + const foreign = template === "custom" ? "developer" : "specialist" + assert.throws(() => parseMissionCreationSelection(template, { ...selected, + profiles: { ...selected.profiles, roles: { ...selected.profiles.roles, [foreign]: {} } } })) + assert.throws(() => parseMissionCreationSelection(template, { ...selected, + origins: { ...selected.origins, roles: {} } })) + } +}) + +test("inspect start creates no standalone intention on mismatch, document refusal or journal failure", async () => { + const f = fixture() + const start = { objective: "Inspect", template: "custom" as const } + f.setPreferences([{ template: "all", profiles: { coordinator: { agent: "different" } } }]) + await assert.rejects(f.control.inspect(f.coordinator, { start }, "mismatch"), /Missions preferences.*profiles\.coordinator/) + f.setPreferences([]) + f.failBeforeDocument() + await assert.rejects(f.control.inspect(f.coordinator, { start }, "document"), /Document write unavailable/) + f.fail() + await assert.rejects(f.control.inspect(f.coordinator, { start }, "journal"), /Journal write unavailable/) + await assert.rejects(f.control.inspect(f.coordinator, { start: { ...start, objective: "Conflict" } }, "journal"), (error: any) => error.code === "request-conflict") + assert.equal([...f.values.keys()].filter(key => key.includes("/creation-intents/")).length, 0) +}) + +test("a retained document preserves uncertainty after the standalone choices expire", async () => { + const f = fixture() + await f.control.create({ requestID: "source", objective: "Source", template: "custom", coordinatorSessionID: f.coordinator }) + const request = { requestID: "document-retry", objective: "Pilot", template: "custom" as const } + f.fail() + await assert.rejects(f.control.prepare(f.coordinator, request), (error: any) => error.code === "prepare-uncertain") + for (const [key, value] of f.values) if (key.includes("/creation-intents/") && value && typeof value === "object" && !Array.isArray(value)) { + f.values.set(key, { ...value, createdAt: 0 }) + } + const reads = f.reads, roots = f.created + f.invalidate(); f.refusePreparation() + await assert.rejects(f.control.prepare(f.coordinator, request), (error: any) => error.code === "prepare-uncertain") + assert.equal(f.reads, reads) + assert.equal(f.created, roots) + assert.equal([...f.values.keys()].filter(key => key.includes("/creation-intents/")).length, 1) +}) + +test("creation origin schemas share the resolver's exact origin set", () => { + const schema = missionCreationDefaultsSchema.shape.origins.shape + const wire = missionCreationDefaultsWire.properties.origins.properties + for (const origins of [schema.coordinator.options, schema.taskMode.options, schema.roles.valueSchema.options, + wire.coordinator.enum, wire.taskMode.enum, wire.roles.additionalProperties.enum]) { + assert.deepEqual(origins, MISSION_DEFAULT_ORIGINS) + } + const validate = new Ajv().compile(missionCreationDefaultsWire) + const selection = resolveMissionCreationDefaults({ template: "custom", preferences: [] }) + for (const origin of [...MISSION_DEFAULT_ORIGINS, "guessed"]) { + const metadata = { request: {}, ...selection, origins: { coordinator: origin, taskMode: origin, roles: { specialist: origin } } } + const valid = origin !== "guessed" + assert.equal(missionCreationDefaultsSchema.safeParse(metadata).success, valid) + assert.equal(validate(metadata), valid, JSON.stringify(validate.errors)) + } +}) + +test("creation wire origins fit every playbook and reject more than the largest role list", () => { + const rolesWire = missionCreationDefaultsWire.properties.origins.properties.roles + const maximum = Math.max(...Object.values(missionProfileRoles).map(roles => roles.length)) + assert.equal(rolesWire.maxProperties, maximum) + const validate = new Ajv().compile(missionCreationDefaultsWire) + for (const template of Object.keys(missionProfileRoles) as (keyof typeof missionProfileRoles)[]) { + const metadata = { request: {}, ...resolveMissionCreationDefaults({ template, preferences: [] }) } + assert.ok(validate(metadata), JSON.stringify(validate.errors)) + assert.deepEqual(parseMissionCreationDefaults(template, metadata), metadata) + const extra = { ...metadata, origins: { ...metadata.origins, roles: { ...metadata.origins.roles, unknown: "explicit" } } } + assert.throws(() => parseMissionCreationDefaults(template, extra)) + } + const validateRoles = new Ajv().compile(rolesWire) + const roles = Object.fromEntries(Array.from({ length: maximum }, (_, index) => [`role-${index}`, "explicit"])) + assert.ok(validateRoles(roles)) + assert.equal(validateRoles({ ...roles, extra: "explicit" }), false) +}) + +test("creation preference availability has one shared schema and wire value", () => { + const validate = new Ajv().compile(missionCreationDefaultsWire) + const metadata = { request: {}, ...resolveMissionCreationDefaults({ template: "custom", preferences: [] }) } + assert.equal(missionCreationDefaultsSchema.shape.preferences.unwrap().value, MISSION_PREFERENCES_UNAVAILABLE) + assert.deepEqual(missionCreationDefaultsWire.properties.preferences.enum, [MISSION_PREFERENCES_UNAVAILABLE]) + for (const preferences of [undefined, MISSION_PREFERENCES_UNAVAILABLE, "available", "", null]) { + const input = { ...metadata, ...(preferences === undefined ? {} : { preferences }) } + const valid = preferences === undefined || preferences === MISSION_PREFERENCES_UNAVAILABLE + assert.equal(missionCreationDefaultsSchema.safeParse(input).success, valid) + assert.equal(validate(input), valid, JSON.stringify(validate.errors)) + } +}) diff --git a/packages/server/src/missions/creation-defaults.ts b/packages/server/src/missions/creation-defaults.ts new file mode 100644 index 0000000000..87bda873c2 --- /dev/null +++ b/packages/server/src/missions/creation-defaults.ts @@ -0,0 +1,76 @@ +import { z } from "zod" +import type { MissionMap, MissionTemplateId } from "./model" +import { missionProfileRoles, missionProfilesInputSchema, missionProfilesSchema, sameMissionProfiles, validateMissionProfiles } from "./playbook-profiles" +import { missionTaskModeInputSchema, missionTaskModeSchema } from "./task-execution-mode" +import { MISSION_DEFAULT_ORIGINS, MISSION_PREFERENCES_UNAVAILABLE, missionCreationSelectionSchema, type MissionCreationSelection } from "./profile-defaults" +import { MissionControlError } from "./control-error" +import { parseExecution } from "./execution" +import { MISSION_DEFAULTS_REQUEST_INVALID } from "./recovery-error" + +export const missionCreationTemplateSchema = z.enum(Object.keys(missionProfileRoles) as [MissionTemplateId, ...MissionTemplateId[]]) +export const missionCreationChoicesSchema = z.object({ profiles: missionProfilesInputSchema, taskMode: missionTaskModeInputSchema.optional() }).strict() +const defaultsInputSchema = missionCreationChoicesSchema.extend({ + template: missionCreationTemplateSchema, + coordinatorModel: z.unknown().transform((model, context) => { + try { return parseExecution({ model })?.model } + catch { context.addIssue({ code: "custom", message: "Invalid coordinator model" }); return z.NEVER } + }).optional(), +}).strict() + +export function parseMissionCreationDefaultsInput(input: unknown) { + const parsed = defaultsInputSchema.safeParse(input) + if (!parsed.success) throw new MissionControlError(MISSION_DEFAULTS_REQUEST_INVALID, "invalid-execution") + try { validateMissionProfiles(parsed.data.template, parsed.data.profiles) } + catch { throw new MissionControlError("Correct profiles.roles to use roles from the selected playbook", "invalid-execution") } + return parsed.data +} +export const missionCreationDefaultsSchema = missionCreationSelectionSchema.extend({ request: missionCreationChoicesSchema }).strict() +export type MissionCreationChoices = z.infer +export type MissionCreationMetadata = z.infer + +export function missionCreationChoices(input: MissionCreationChoices): MissionCreationChoices { + return structuredClone({ ...(input.profiles === undefined ? {} : { profiles: input.profiles }), ...(input.taskMode === undefined ? {} : { taskMode: input.taskMode }) }) +} +export function sameMissionCreationChoices(left: MissionCreationChoices, right: MissionCreationChoices): boolean { + return left.taskMode === right.taskMode && sameMissionProfiles(left.profiles, right.profiles) +} + +function validateOrigins(template: MissionTemplateId, origins: MissionCreationSelection["origins"]) { + const roles: readonly string[] = missionProfileRoles[template] + if (Object.keys(origins.roles).length !== roles.length || roles.some(role => origins.roles[role] === undefined)) throw new Error("Invalid Mission profile origins") +} + +/** Trusted transport and durable journal use the same bounded selector codec. */ +export function parseMissionCreationDefaults(template: MissionTemplateId, input: unknown): MissionCreationMetadata { + const value = missionCreationDefaultsSchema.parse(input) + validateMissionProfiles(template, value.request.profiles) + parseMissionCreationSelection(template, { profiles: value.profiles, taskMode: value.taskMode, origins: value.origins }) + return value +} + +export function parseMissionCreationSelection(template: MissionTemplateId, input: unknown): MissionCreationSelection { + const value = missionCreationSelectionSchema.parse(input) + validateOrigins(template, value.origins) + validateMissionProfiles(template, value.profiles) + if (Object.keys(value.profiles.roles).length !== missionProfileRoles[template].length) throw new Error("Incomplete Mission profile selection") + return value +} + +/** Historical missions retain absent provenance; reads never consult preferences. */ +export function missionCreationSelection(mission: Pick): MissionCreationSelection | undefined { + if (!mission.creationDefaults) return undefined + return structuredClone({ profiles: mission.creationDefaults.profiles, + taskMode: mission.creationDefaults.taskMode, origins: mission.creationDefaults.origins, + ...(mission.creationDefaults.preferences === undefined ? {} : { preferences: mission.creationDefaults.preferences }) }) +} + +const originWire = { type: "string", enum: MISSION_DEFAULT_ORIGINS } as const +export const missionCreationDefaultsWire = { + type: "object", properties: { + request: { type: "object", properties: { profiles: missionProfilesSchema, taskMode: missionTaskModeSchema }, additionalProperties: false }, + profiles: missionProfilesSchema, taskMode: missionTaskModeSchema, + preferences: { type: "string", enum: [MISSION_PREFERENCES_UNAVAILABLE] }, + origins: { type: "object", properties: { coordinator: originWire, taskMode: originWire, + roles: { type: "object", maxProperties: Math.max(...Object.values(missionProfileRoles).map(roles => roles.length)), additionalProperties: originWire } }, required: ["coordinator", "roles", "taskMode"], additionalProperties: false }, + }, required: ["request", "profiles", "taskMode", "origins"], additionalProperties: false, +} as const diff --git a/packages/server/src/missions/creation-intent.test.ts b/packages/server/src/missions/creation-intent.test.ts new file mode 100644 index 0000000000..db06789bc2 --- /dev/null +++ b/packages/server/src/missions/creation-intent.test.ts @@ -0,0 +1,148 @@ +import assert from "node:assert/strict" +import test from "node:test" +import { MissionCreationIntents, MISSION_CREATION_INTENT_LIMIT, MISSION_CREATION_INTENT_RETENTION_MS } from "./creation-intent" +import type { MissionStorage } from "./journal" +import type { MissionJsonValue } from "./model" +import { resolveMissionCreationDefaults } from "./profile-defaults" + +function fixture() { + const values = new Map() + let now = Date.now() + const storage: MissionStorage = { + get: async key => structuredClone(values.get(key)), + set: async (key, value, current) => { current?.(); values.set(key, structuredClone(value)) }, + remove: async key => { values.delete(key) }, + scan: async ({ prefix, after, limit = 100 }) => { + const rows = [...values].filter(([key]) => key.startsWith(prefix) && (after === undefined || key > after)).sort() + return { entries: rows.slice(0, limit).map(([key, value]) => ({ key, value })), + ...(rows.length > limit ? { next: rows[limit - 1][0] } : {}) } + }, + } + return { values, storage, intents: new MissionCreationIntents(storage, "project", () => now), advance: (ms: number) => { now += ms } } +} +const request = { objective: "Prepare", template: "custom" as const } +const defaults = { request: {}, ...resolveMissionCreationDefaults({ ...request, preferences: [] }) } +const missing = async () => undefined + +test("pre-dispatch intentions replay original whole choices across instances and refuse real request changes", async () => { + const f = fixture() + await f.intents.save("msn_first", request, defaults, missing, () => {}, "prepare-conflict") + const changed = { request: {}, ...resolveMissionCreationDefaults({ ...request, + preferences: [{ template: "all", profiles: { coordinator: { agent: "different" } } }] }) } + const restarted = new MissionCreationIntents(f.storage, "project") + assert.deepEqual(await restarted.save("msn_first", request, changed, missing, () => {}, "prepare-conflict"), defaults) + const before = structuredClone([...f.values]) + for (const other of [{ ...request, objective: "Other" }, { ...request, profiles: {} }, { ...request, taskMode: "native" as const }]) { + await assert.rejects(restarted.read("msn_first", other, missing, "prepare-conflict"), { code: "prepare-conflict", message: "This requestID already prepared a different mission" }) + } + assert.deepEqual([...f.values], before) +}) + +test("lost intent acknowledgement retains the original data and guards run before publication", async () => { + const f = fixture(), set = f.storage.set + f.storage.set = async (...args) => { await set(...args); throw new Error("Acknowledgement lost") } + await assert.rejects(f.intents.save("msn_lost", request, defaults, missing, () => {}, "request-conflict"), /Acknowledgement lost/) + assert.deepEqual(await f.intents.read("msn_lost", request, missing, "request-conflict"), defaults) + f.storage.set = set + const before = structuredClone([...f.values]) + await assert.rejects(f.intents.save("msn_denied", request, defaults, missing, () => { throw new Error("Retired") }, "request-conflict"), /Retired/) + assert.deepEqual([...f.values], before) +}) + +test("pending intentions are bounded and settled evidence releases its capacity place", async () => { + const f = fixture() + for (let index = 0; index < MISSION_CREATION_INTENT_LIMIT; index++) await f.intents.save(`msn_${index}`, request, defaults, missing, () => {}, "request-conflict") + assert.deepEqual(await f.intents.save("msn_0", request, defaults, missing, () => {}, "request-conflict"), defaults, "an exact retry works at capacity") + await assert.rejects(f.intents.save("msn_over", request, defaults, missing, () => {}, "request-conflict"), (error: any) => { + assert.equal(error.code, "creation-capacity") + assert.ok(error.message.startsWith(`${MISSION_CREATION_INTENT_LIMIT} Mission preparation choices are retained.`)) + assert.ok(error.message.includes(`up to ${MISSION_CREATION_INTENT_RETENTION_MS / (60 * 60 * 1_000)} hours`)) + return true + }) + assert.equal(f.values.size, MISSION_CREATION_INTENT_LIMIT) + await f.intents.settled("msn_0") + await f.intents.save("msn_over", request, defaults, missing, () => {}, "request-conflict") + assert.equal(f.values.size, MISSION_CREATION_INTENT_LIMIT) +}) + +test("damaged intent bytes stay intact and refuse before another preference read or write", async () => { + const f = fixture() + f.values.set("codenomad-missions/v2/creation-intents/project/msn_damaged", { version: 1 }) + const before = structuredClone([...f.values]) + await assert.rejects(f.intents.read("msn_damaged", request, missing, "request-conflict"), + (error: any) => error.code === "invalid-journal") + assert.deepEqual([...f.values], before) +}) + +test("uncertain choices expire without extending their lifetime on an identical retry", async () => { + const f = fixture() + for (let index = 0; index < MISSION_CREATION_INTENT_LIMIT; index++) await f.intents.save(`msn_${index}`, request, defaults, missing, () => {}, "request-conflict") + f.advance(MISSION_CREATION_INTENT_RETENTION_MS - 1) + assert.deepEqual(await f.intents.read("msn_0", request, missing, "request-conflict"), defaults) + await f.intents.save("msn_0", request, defaults, missing, () => {}, "request-conflict") + f.advance(1) + await f.intents.save("msn_new", request, defaults, missing, () => {}, "request-conflict") + assert.equal(f.values.size, 1) + assert.equal(await f.intents.read("msn_0", request, missing, "request-conflict"), undefined) +}) + +test("clock rollback keeps recorded choices fresh instead of replaying preference resolution", async () => { + const f = fixture() + await f.intents.save("msn_clock", request, defaults, missing, () => {}, "request-conflict") + const before = structuredClone([...f.values]) + f.advance(-60_000) + assert.deepEqual(await f.intents.read("msn_clock", request, missing, "request-conflict"), defaults) + const changed = { ...defaults, taskMode: "independent" as const } + assert.deepEqual(await f.intents.save("msn_clock", request, changed, missing, () => {}, "request-conflict"), defaults) + assert.deepEqual([...f.values], before) +}) + +test("settled choices release capacity on adapters without key removal", async () => { + const f = fixture() + f.storage.remove = undefined + for (let index = 0; index < 150; index++) { + await f.intents.save(`msn_${index}`, request, defaults, missing, () => {}, "request-conflict") + await f.intents.settled(`msn_${index}`) + } + await f.intents.save("msn_new", request, defaults, missing, () => {}, "request-conflict") + assert.equal([...f.values.values()].filter(value => value !== null).length, 1) +}) + +test("capacity scans skip damaged intentions while their exact IDs retain uncertainty", async () => { + for (const invalid of [ + { version: 1, request, defaults }, + { version: 1, request, defaults, createdAt: -1 }, + { version: 1, request: { ...request, template: "other" }, defaults, createdAt: Date.now() }, + { version: 1, request, defaults: { ...defaults, origins: {} }, createdAt: Date.now() }, + { version: 1, request, defaults: { ...defaults, request: { profiles: {} } }, createdAt: Date.now() }, + ]) { + const f = fixture() + f.values.set("codenomad-missions/v2/creation-intents/project/msn_invalid", invalid as unknown as MissionJsonValue) + await assert.rejects(f.intents.read("msn_invalid", request, missing, "request-conflict"), + (error: any) => error.code === "invalid-journal") + assert.deepEqual(await f.intents.save("msn_new", request, defaults, missing, () => {}, "request-conflict"), defaults) + await assert.rejects(f.intents.save("msn_invalid", request, defaults, missing, () => {}, "request-conflict"), + (error: any) => error.code === "invalid-journal") + assert.deepEqual(f.values.get("codenomad-missions/v2/creation-intents/project/msn_invalid"), invalid, + "a damaged reservation is neither expired, discarded nor overwritten") + for (let index = 1; index < MISSION_CREATION_INTENT_LIMIT; index++) { + await f.intents.save(`msn_valid_${index}`, request, defaults, missing, () => {}, "request-conflict") + } + await assert.rejects(f.intents.save("msn_over", request, defaults, missing, () => {}, "request-conflict"), + (error: any) => error.code === "creation-capacity") + assert.equal(f.values.size, MISSION_CREATION_INTENT_LIMIT + 1, "only usable reservations spend capacity") + } +}) + +test("failed choice cleanup cannot replace an authoritative success or refusal", async () => { + const f = fixture(), remove = f.storage.remove, set = f.storage.set + await f.intents.save("msn_done", request, defaults, missing, () => {}, "request-conflict") + const before = structuredClone([...f.values]) + f.storage.remove = async () => { throw new Error("Removal unavailable") } + f.storage.set = async (key, value, current) => { if (value === null) throw new Error("Clear unavailable"); await set(key, value, current) } + await f.intents.settled("msn_done") + assert.deepEqual([...f.values], before, "retention age is preserved while cleanup is unavailable") + f.storage.remove = remove; f.storage.set = set + await f.intents.settled("msn_done") + assert.equal(f.values.size, 0) +}) diff --git a/packages/server/src/missions/creation-intent.ts b/packages/server/src/missions/creation-intent.ts new file mode 100644 index 0000000000..fb1e00342a --- /dev/null +++ b/packages/server/src/missions/creation-intent.ts @@ -0,0 +1,126 @@ +import { z } from "zod" +import type { MissionStartInput } from "./control-types" +import { MISSION_CREATION_REQUEST_CONFLICT, MissionControlError } from "./control-error" +import { missionCreationChoices, missionCreationChoicesSchema, missionCreationTemplateSchema, parseMissionCreationDefaults, sameMissionCreationChoices, + type MissionCreationMetadata } from "./creation-defaults" +import { runMissionExclusive } from "./exclusive" +import type { MissionStorage } from "./journal" +import type { MissionEvent, MissionJsonValue } from "./model" +import { MISSION_TITLE_MAX } from "./mission-title" +import { missionRecoveryControlError } from "./recovery-error" + +type Request = MissionStartInput & { title?: string } +const requestSchema = missionCreationChoicesSchema.extend({ objective: z.string().min(1).max(20_000), + title: z.string().min(1).max(MISSION_TITLE_MAX).optional(), notes: z.string().max(20_000).optional(), + template: missionCreationTemplateSchema }).strict() +const intentSchema = z.object({ version: z.literal(1), request: requestSchema, defaults: z.unknown(), + createdAt: z.number().finite().nonnegative() }).strict() +export const MISSION_CREATION_INTENT_RETENTION_MS = 24 * 60 * 60 * 1_000 +export const MISSION_CREATION_INTENT_LIMIT = 128 +const sameRequest = (left: Request, right: Request) => left.objective === right.objective && left.title === right.title + && left.notes === right.notes && left.template === right.template && sameMissionCreationChoices(left, right) +const originalRequest = (input: Request, defaults: MissionCreationMetadata): Request => ({ + objective: input.objective, template: input.template, ...(input.title === undefined ? {} : { title: input.title }), + ...(input.notes === undefined ? {} : { notes: input.notes }), ...missionCreationChoices(defaults.request), +}) + +function parseIntent(raw: unknown) { + try { + const saved = intentSchema.parse(raw) + const defaults = parseMissionCreationDefaults(saved.request.template, saved.defaults) + if (!sameMissionCreationChoices(saved.request, defaults.request)) throw new Error("Invalid original choices") + return { ...saved, defaults } + } catch { throw new MissionControlError("Mission creation intent is unreadable; existing data is retained", "invalid-journal") } +} + +/** Retained preparation choices, separate from the backend's native-effect holds. */ +export class MissionCreationIntents { + private readonly prefix: string + constructor(private readonly storage: MissionStorage, projectToken: string, private readonly now = Date.now) { + this.prefix = `codenomad-missions/v2/creation-intents/${projectToken}/` + } + + private conflict(code: string): never { + if (code === "prepare-conflict") throw missionRecoveryControlError("prepare-conflict") + throw new MissionControlError(MISSION_CREATION_REQUEST_CONFLICT, code) + } + + private async recorded(missionID: string, request: Request, conflict: string): Promise { + const raw = await this.storage.get(this.prefix + missionID) + if (raw === undefined || raw === null) return undefined + const saved = parseIntent(raw) + if (this.expired(saved.createdAt)) { await this.clear(missionID); return undefined } + if (!sameRequest(saved.request, request)) this.conflict(conflict) + return saved.defaults + } + + private fromEvent(event: MissionEvent | undefined, request: Request, conflict: string) { + if (event?.type !== "mission.created" || !event.creationDefaults) return undefined + const original = originalRequest(event, event.creationDefaults) + if (!sameRequest(original, request)) this.conflict(conflict) + return event.creationDefaults + } + + async read(missionID: string, request: Request, created: () => Promise, conflict: string) { + return runMissionExclusive(this.prefix, () => this.readCurrent(missionID, request, created, conflict)) + } + + private async readCurrent(missionID: string, request: Request, created: () => Promise, conflict: string) { + // A positive receipt survives expiry and cleanup of the retained choices. + return this.fromEvent(await created(), request, conflict) ?? await this.recorded(missionID, request, conflict) + } + + private expired(createdAt: number): boolean { + return this.now() - createdAt >= MISSION_CREATION_INTENT_RETENTION_MS + } + + private async activeCount(): Promise { + let after: string | undefined, count = 0 + do { + const page = await this.storage.scan({ prefix: this.prefix, after, limit: MISSION_CREATION_INTENT_LIMIT + 1 }) + for (const entry of page.entries) { + if (!entry.key.startsWith(this.prefix) || after !== undefined && entry.key <= after) throw new MissionControlError("Mission preparation storage is unreadable", "invalid-journal") + if (entry.value === null) continue + let saved: ReturnType + try { saved = parseIntent(entry.value) } + catch { continue } // Keep damaged evidence intact; a direct read of its ID still refuses. + if (this.expired(saved.createdAt)) await this.clear(entry.key.slice(this.prefix.length)) + else if (++count >= MISSION_CREATION_INTENT_LIMIT) return count + } + if (page.next !== undefined && (page.next === after || !page.entries.length)) throw new MissionControlError("Mission preparation storage is unreadable", "invalid-journal") + after = page.next + } while (after) + return count + } + + save(missionID: string, input: Request, defaults: MissionCreationMetadata, created: () => Promise, + current: () => void, conflict: string): Promise { + const request = originalRequest(input, defaults) + return runMissionExclusive(this.prefix, async () => { + current() + const saved = await this.readCurrent(missionID, request, created, conflict) + if (saved) return saved + if (await this.activeCount() >= MISSION_CREATION_INTENT_LIMIT) throw new MissionControlError(`${MISSION_CREATION_INTENT_LIMIT} Mission preparation choices are retained. Retry the original requestIDs to recover completed preparations, or wait up to ${MISSION_CREATION_INTENT_RETENTION_MS / (60 * 60 * 1_000)} hours for these choices to expire. Check uncertain outcomes before creating replacements.`, "creation-capacity") + current() + await this.storage.set(this.prefix + missionID, JSON.parse(JSON.stringify({ version: 1, request, defaults, createdAt: this.now() })) as MissionJsonValue, current) + return defaults + }) + } + + async settled(missionID: string): Promise { + // Cleanup of retained choices cannot replace an authoritative success/refusal. + // A failed cleanup keeps its timestamp, so later retries or expiry can reclaim it. + try { await runMissionExclusive(this.prefix, () => this.clear(missionID)) } catch { /* Retain until storage recovers. */ } + } + + private async clear(missionID: string): Promise { + const key = this.prefix + missionID + const value = await this.storage.get(key) + if (value === undefined || value === null) return + try { + if (this.storage.remove) { await this.storage.remove(key); return } + } catch { /* A cleared marker also releases capacity when key removal fails. */ } + // ponytail: adapters without remove retain null markers; provide remove if scan cost matters. + await this.storage.set(key, null) + } +} diff --git a/packages/server/src/missions/journal.ts b/packages/server/src/missions/journal.ts index 876e109fd9..ede0a545b5 100644 --- a/packages/server/src/missions/journal.ts +++ b/packages/server/src/missions/journal.ts @@ -24,6 +24,7 @@ import { parseExecutionMode } from "./task-execution-mode" import { hasInvalidReportNotificationHistory, parseNativeBinding, parseNativeCall } from "./native-report-provenance" import { parseMissionNativeAcknowledgement } from "./lifecycle-schema" import { parseMissionProfiles, validateMissionProfiles } from "./playbook-profiles" +import { parseMissionCreationDefaults } from "./creation-defaults" import { parseMissionTitle } from "./mission-title" import { missionTaskModeInputSchema } from "./task-execution-mode" import { parseNativeCallObservation } from "./native-call-observation" @@ -524,8 +525,11 @@ export function parseMissionEvent(input: unknown): MissionEvent | undefined { if (preparedBy !== undefined && (!record(preparedBy) || !onlyFields(preparedBy, ["missionID", "coordinatorSessionID"]) || !text(preparedBy.missionID, MAX_SHORT_TEXT) || !text(preparedBy.coordinatorSessionID, MAX_SHORT_TEXT))) return undefined if (input.taskMode !== undefined && !missionTaskModeInputSchema.safeParse(input.taskMode).success) return undefined - let profiles - try { profiles = parseMissionProfiles(input.profiles); validateMissionProfiles(templateID, profiles) } + let profiles, creationDefaults + try { + profiles = parseMissionProfiles(input.profiles); validateMissionProfiles(templateID, profiles) + if (input.creationDefaults !== undefined) creationDefaults = parseMissionCreationDefaults(templateID, input.creationDefaults) + } catch { return undefined } return { ...eventBase(input), @@ -537,6 +541,7 @@ export function parseMissionEvent(input: unknown): MissionEvent | undefined { template: templateID, ...(input.taskMode === undefined ? {} : { taskMode: missionTaskModeInputSchema.parse(input.taskMode) }), ...(profiles === undefined ? {} : { profiles }), + ...(creationDefaults === undefined ? {} : { creationDefaults }), coordinator: { sessionID: input.coordinator.sessionID, title: input.coordinator.title, diff --git a/packages/server/src/missions/mission-document-one-time.ts b/packages/server/src/missions/mission-document-one-time.ts index e5fd07efae..060148d941 100644 --- a/packages/server/src/missions/mission-document-one-time.ts +++ b/packages/server/src/missions/mission-document-one-time.ts @@ -51,6 +51,7 @@ export async function prepareMissionOneTimeDocument(access: MissionDocumentAcces profileID: null, executionHost: null, roots: [{ mode: "directory-only", directory: location.directory }], watchedConversationIDs: [], launch: { timing: { kind: "immediate" }, condition: null, ends: { maxLaunches: null, afterMs: null, at: null } }, }, createdAt, current, { creationRequestID: input.requestID, creationDigest: digest, + ...(input.creationDefaults === undefined ? {} : { creationDefaults: input.creationDefaults }), coordinatorSessionID, location: { ...location }, firstPlay: null }) }) } diff --git a/packages/server/src/missions/mission-document-store.ts b/packages/server/src/missions/mission-document-store.ts index 8bcb56d74c..dbb2db17ba 100644 --- a/packages/server/src/missions/mission-document-store.ts +++ b/packages/server/src/missions/mission-document-store.ts @@ -122,7 +122,8 @@ export class NativeMissionDocumentStore { || doc.configurationGeneration < previous.configurationGeneration || doc.timeGeneration < previous.timeGeneration || previous.everCreatedTask && !doc.everCreatedTask || previous.deletion && canonicalAuthority(doc.deletion) !== canonicalAuthority(previous.deletion) || previous.oneTime && (!doc.oneTime || doc.oneTime.creationRequestID !== previous.oneTime.creationRequestID - || doc.oneTime.creationDigest !== previous.oneTime.creationDigest || canonicalAuthority(doc.oneTime.location) !== canonicalAuthority(previous.oneTime.location)) + || doc.oneTime.creationDigest !== previous.oneTime.creationDigest || canonicalAuthority(doc.oneTime.location) !== canonicalAuthority(previous.oneTime.location) + || canonicalAuthority(doc.oneTime.creationDefaults ?? null) !== canonicalAuthority(previous.oneTime.creationDefaults ?? null)) || previous.oneTime?.firstPlay?.acknowledgement && canonicalAuthority(previous.oneTime.firstPlay.acknowledgement, MISSION_DOCUMENT_MAX_BYTES) !== canonicalAuthority(doc.oneTime?.firstPlay?.acknowledgement ?? null, MISSION_DOCUMENT_MAX_BYTES) || previous.oneTime?.firstPlay && previous.oneTime.firstPlay.inputText !== doc.oneTime?.firstPlay?.inputText diff --git a/packages/server/src/missions/mission-document.ts b/packages/server/src/missions/mission-document.ts index d89a00c7d9..0bea6eac3e 100644 --- a/packages/server/src/missions/mission-document.ts +++ b/packages/server/src/missions/mission-document.ts @@ -5,6 +5,7 @@ import { missionCoordinatorSessionID, isMissionCoordinatorSession } from "./sess import { parseMissionNativeAcknowledgement } from "./lifecycle-schema" import { missionCalendarOwnerSchema } from "./mission-calendar-owner-state" import { MISSION_LIFECYCLE_TEXT_LIMIT } from "./lifecycle-input" +import { missionCreationDefaultsSchema } from "./creation-defaults" import { documentCounter, documentID, documentTimestamp, nativeDocumentID, missionConfigurationSchema, missionLaunchLimit, missionLaunchModel, missionSlotEndsAt, requiresMissionCalendar, MISSION_DOCUMENT_MAX_BYTES, @@ -37,6 +38,7 @@ export const missionScheduleActivationSchema = z.object({ requestID, expectedRev }).strict().refine(value => value.state !== "ready" || value.targets.every(target => target.acknowledged) && value.effectiveOrigin !== undefined) export type MissionScheduleActivation = z.infer const oneTime = z.object({ creationRequestID: requestID, creationDigest: digest, coordinatorSessionID: nativeDocumentID, + creationDefaults: missionCreationDefaultsSchema.optional(), location: z.object({ directory: z.string().min(1).max(4096), workspaceID: nativeDocumentID.optional() }).strict(), firstPlay: z.object({ requestID, expectedRevision: documentCounter.positive(), operationID: nativeDocumentID, messageID: nativeDocumentID, requestedAt: documentTimestamp, admittedAt: documentTimestamp.nullable(), diff --git a/packages/server/src/missions/mission-roots.ts b/packages/server/src/missions/mission-roots.ts index 507e06dcca..900f28fcd8 100644 --- a/packages/server/src/missions/mission-roots.ts +++ b/packages/server/src/missions/mission-roots.ts @@ -33,7 +33,7 @@ export class CanonicalMissionRoots { private async resolveConnection(location: MissionLocation, connection: ServiceConnection | undefined, purpose: "request" | "event" = "request", signal?: AbortSignal): Promise { if ("workspaceID" in location || !connection - || !await this.manager.ownsLocation(this.workspaceID, location, connection.client, signal, purpose)) rejectAuthority("binding-mismatch") + || !await this.manager.ownsLocation(this.workspaceID, location, connection.client, { signal, purpose })) rejectAuthority("binding-mismatch") const hostPath = await this.manager.getHostPathForServicePath(this.workspaceID, location.directory) // No guessed WSL translation or independent Windows claim for Linux roots. if (!hostPath || identity(hostPath) !== identity(location.directory)) rejectAuthority("observation-unavailable") diff --git a/packages/server/src/missions/model.ts b/packages/server/src/missions/model.ts index ca7b0748c6..2a423e5e5f 100644 --- a/packages/server/src/missions/model.ts +++ b/packages/server/src/missions/model.ts @@ -178,6 +178,7 @@ export interface MissionPlanChange { } export interface MissionMap { + creationDefaults?: import("./creation-defaults").MissionCreationMetadata document?: import("./mission-document-one-time").MissionDocumentSummary version: typeof MISSION_SCHEMA_VERSION id: string @@ -306,6 +307,7 @@ interface MissionEventBase { } export interface MissionCreatedEvent extends MissionEventBase { + creationDefaults?: import("./creation-defaults").MissionCreationMetadata type: "mission.created" projectCanonical: string title?: string @@ -949,6 +951,7 @@ function reduceMission(events: readonly MissionEvent[], discarded: { count: numb template: created.template, taskMode: created.taskMode ?? "native", ...(created.profiles === undefined ? {} : { profiles: structuredClone(created.profiles) }), + ...(created.creationDefaults === undefined ? {} : { creationDefaults: structuredClone(created.creationDefaults) }), status, ...lifecycle, ...(hasInvalidReportNotificationHistory(events) ? { notificationUnavailable: true } : {}), diff --git a/packages/server/src/missions/profile-defaults.test.ts b/packages/server/src/missions/profile-defaults.test.ts new file mode 100644 index 0000000000..f3dae3a3d3 --- /dev/null +++ b/packages/server/src/missions/profile-defaults.test.ts @@ -0,0 +1,228 @@ +import assert from "node:assert/strict" +import { test } from "node:test" +import { missionProfileRoles, type MissionProfiles } from "./playbook-profiles" +import { globalMissionTaskMode, hasExplicitMissionCreationChoices, missionTaskModeFor, MissionPreferencesError, normalizeMissionDefaults, resolveMissionCreationDefaults, validMissionDefaults, type MissionProfileDefault } from "./profile-defaults" +import type { MissionTemplateId } from "./model" +import { missionTaskModeInputSchema } from "./task-execution-mode" + +const coordinator = { agent: "coordinator", model: { providerID: "p", id: "coordinator", variant: "high" } } +const specialist = { agent: "worker", model: { providerID: "p", id: "worker", variant: "low" } } +const preferences: MissionProfileDefault[] = [{ template: "all", profiles: { coordinator, roles: { specialist } }, taskMode: "independent" }] +const templates = Object.keys(missionProfileRoles) as MissionTemplateId[] + +test("preference task modes use the creation input schema while omission stays absent", () => { + for (const taskMode of [undefined, ...missionTaskModeInputSchema.options, null, "automatic", 0, true, {}, []]) { + const entry = { template: "all", profiles: {}, ...(taskMode === undefined ? {} : { taskMode }) } + const valid = taskMode === undefined || missionTaskModeInputSchema.safeParse(taskMode).success + assert.equal(validMissionDefaults([entry]), valid) + assert.deepEqual(normalizeMissionDefaults([entry]), valid ? [entry] : []) + } +}) + +test("explicit creation choices require the coordinator, every playbook role and task mode, including empty slots", () => { + for (const template of templates) { + const roles = Object.fromEntries(missionProfileRoles[template].map(role => [role, {}])) + const profiles = { coordinator: {}, roles } + for (const taskMode of ["native", "independent"] as const) { + const input = { template, profiles, taskMode } + assert.equal(hasExplicitMissionCreationChoices(input), true) + assert.equal(hasExplicitMissionCreationChoices({ ...input, profiles: undefined }), false) + assert.equal(hasExplicitMissionCreationChoices({ ...input, profiles: {} }), false) + assert.equal(hasExplicitMissionCreationChoices({ ...input, profiles: { roles } }), false) + assert.equal(hasExplicitMissionCreationChoices({ ...input, profiles: { coordinator: {} } }), false) + assert.equal(hasExplicitMissionCreationChoices({ ...input, taskMode: undefined }), false) + for (const role of missionProfileRoles[template]) { + const partial = Object.fromEntries(Object.entries(roles).filter(([key]) => key !== role)) + assert.equal(hasExplicitMissionCreationChoices({ ...input, profiles: { ...profiles, roles: partial } }), false) + } + } + } +}) + +test("missing preferences resolve complete native profiles and origins for every template", () => { + for (const template of templates) for (const preferences of [undefined, []]) { + assert.deepEqual(resolveMissionCreationDefaults({ template, preferences }), { + profiles: { coordinator: {}, roles: Object.fromEntries(missionProfileRoles[template].map(role => [role, {}])) }, + taskMode: "native", + origins: { coordinator: "opencode-default", taskMode: "opencode-default", + roles: Object.fromEntries(missionProfileRoles[template].map(role => [role, "opencode-default"])) }, + }) + } +}) + +test("global specialist expands only to the exact template roles, except the Compare judge", () => { + for (const template of templates) { + const result = resolveMissionCreationDefaults({ template, preferences }) + assert.deepEqual(result.profiles.coordinator, coordinator) + assert.deepEqual(Object.keys(result.profiles.roles), missionProfileRoles[template]) + for (const role of missionProfileRoles[template]) { + assert.deepEqual(result.profiles.roles[role], role === "comparator" ? { model: coordinator.model } : specialist) + assert.equal(result.origins.roles[role], "preference") + } + assert.equal(result.origins.coordinator, "preference") + assert.equal(result.taskMode, "independent") + assert.equal(result.origins.taskMode, "preference") + } +}) + +test("partial preferences and explicit profiles leave only missing slots on defaults", () => { + const result = resolveMissionCreationDefaults({ template: "wayfinder", + preferences: [{ template: "wayfinder", profiles: { roles: { research: specialist } } }], + profiles: { coordinator: { agent: "explicit" }, roles: { prototype: specialist } }, + }) + assert.deepEqual(result.profiles, { coordinator: { agent: "explicit" }, + roles: { cartographer: {}, research: specialist, prototype: specialist, grilling: {}, decision: {} } }) + assert.deepEqual(result.origins, { coordinator: "explicit", taskMode: "opencode-default", + roles: { cartographer: "opencode-default", research: "preference", prototype: "explicit", grilling: "opencode-default", decision: "opencode-default" } }) +}) + +test("explicit empty and agent-only selections replace whole slots; empty profile containers inherit", () => { + const baseline = resolveMissionCreationDefaults({ template: "debug", preferences }) + for (const profiles of [{}, { roles: {} }]) { + assert.deepEqual(resolveMissionCreationDefaults({ template: "debug", preferences, profiles }), baseline) + } + for (const selection of [{}, { agent: "explicit" }]) { + const result = resolveMissionCreationDefaults({ template: "debug", preferences, + profiles: { coordinator: selection, roles: { validator: selection } } }) + assert.deepEqual(result.profiles.coordinator, selection) + assert.deepEqual(result.profiles.roles.validator, selection) + assert.deepEqual(result.profiles.roles.implementer, specialist) + assert.equal(result.origins.coordinator, "explicit") + assert.equal(result.origins.roles.validator, "explicit") + assert.equal(result.origins.roles.implementer, "preference") + } +}) + +test("template preferences override global whole slots while empty containers inherit", () => { + for (const selection of [{}, { agent: "typed" }]) { + const result = resolveMissionCreationDefaults({ template: "debug", preferences: [...preferences, + { template: "debug", profiles: { coordinator: selection, roles: { validator: selection } }, taskMode: "native" }] }) + assert.deepEqual(result.profiles.coordinator, selection) + assert.deepEqual(result.profiles.roles.validator, selection) + assert.deepEqual(result.profiles.roles.implementer, specialist) + assert.equal(result.taskMode, "native") + assert.equal(result.origins.coordinator, "preference") + assert.equal(result.origins.roles.validator, "preference") + assert.equal(result.origins.taskMode, "preference") + } + assert.deepEqual(resolveMissionCreationDefaults({ template: "debug", preferences: [...preferences, + { template: "debug", profiles: {} }] }), resolveMissionCreationDefaults({ template: "debug", preferences })) + const custom = resolveMissionCreationDefaults({ template: "custom", preferences: [...preferences, + { template: "custom", profiles: { roles: { specialist: {} } } }] }) + assert.deepEqual(custom.profiles.roles.specialist, {}) +}) + +test("task mode resolves explicit, template, global, then native with the matching origin", () => { + for (const taskMode of ["native", "independent"] as const) { + const result = resolveMissionCreationDefaults({ template: "debug", preferences, taskMode }) + assert.equal(result.taskMode, taskMode) + assert.equal(result.origins.taskMode, "explicit") + const typed = resolveMissionCreationDefaults({ template: "debug", preferences: [...preferences, + { template: "debug", profiles: {}, taskMode }] }) + assert.equal(typed.taskMode, taskMode) + assert.equal(typed.origins.taskMode, "preference") + } +}) + +test("editor task-mode helpers match creation selection through template, global and native fallbacks", () => { + for (const global of [undefined, "native", "independent"] as const) { + for (const specific of [undefined, "native", "independent"] as const) { + const preferences: MissionProfileDefault[] = [ + { template: "all", profiles: {}, taskMode: global }, { template: "debug", profiles: {}, taskMode: specific }, + ] + const selected = resolveMissionCreationDefaults({ template: "debug", preferences }) + assert.equal(selected.taskMode, specific ?? global ?? "native") + assert.equal(selected.origins.taskMode, specific !== undefined || global !== undefined ? "preference" : "opencode-default") + assert.equal(missionTaskModeFor(preferences, "debug"), selected.taskMode) + assert.equal(globalMissionTaskMode(preferences), global ?? "native") + assert.equal(missionTaskModeFor(preferences, "wayfinder"), globalMissionTaskMode(preferences)) + } + } +}) + +test("Compare's missing judge inherits only the coordinator model and its origin", () => { + for (const selection of [coordinator, {}, { agent: "coordinator-only" }]) { + const result = resolveMissionCreationDefaults({ template: "compare", preferences, profiles: { coordinator: selection } }) + assert.deepEqual(result.profiles.roles.comparator, "model" in selection ? { model: selection.model } : {}) + assert.equal(result.origins.roles.comparator, "explicit") + assert.deepEqual(result.profiles.roles["model-a"], specialist) + assert.deepEqual(result.profiles.roles["model-b"], specialist) + } + const withoutCoordinator = resolveMissionCreationDefaults({ template: "compare", + preferences: [{ template: "all", profiles: { roles: { specialist } } }] }) + assert.deepEqual(withoutCoordinator.profiles.roles.comparator, {}) + assert.equal(withoutCoordinator.origins.roles.comparator, "opencode-default") +}) + +test("Compare fills a selected judge's missing model while retaining the slot's agent and origin", () => { + for (const comparator of [{}, { agent: "judge" }, specialist]) { + const explicit = resolveMissionCreationDefaults({ template: "compare", preferences, profiles: { roles: { comparator } } }) + const expected = { ...comparator, model: "model" in comparator ? comparator.model : coordinator.model } + assert.deepEqual(explicit.profiles.roles.comparator, expected) + assert.equal(explicit.origins.roles.comparator, "explicit") + const preferred = resolveMissionCreationDefaults({ template: "compare", preferences: [...preferences, + { template: "compare", profiles: { roles: { comparator } } }] }) + assert.deepEqual(preferred.profiles.roles.comparator, expected) + assert.equal(preferred.origins.roles.comparator, "preference") + } +}) + +test("invalid raw preferences throw a typed error before normalization or explicit overrides", () => { + const valid = { template: "all", profiles: { coordinator } } + for (const preferences of [null, {}, false, "bad", [null], [valid, valid], + [{ template: "unknown", profiles: {} }], [{ template: "debug" }], + [{ template: "all", profiles: {}, extra: true }], [{ template: "all", profiles: {}, taskMode: "bad" }], + [{ template: "all", profiles: { coordinator: { model: { providerID: "p" } } } }], + [{ template: "all", profiles: { roles: { research: specialist } } }], + [{ template: "debug", profiles: { roles: { decision: specialist } } }], + [{ template: "all", profiles: { coordinator: { apiKey: "invalid" } } }], Array(7).fill(valid)]) { + assert.throws(() => resolveMissionCreationDefaults({ template: "debug", preferences, profiles: { coordinator }, taskMode: "native" }), + error => error instanceof Error && error instanceof MissionPreferencesError && error.code === "mission-preferences-invalid") + } +}) + +test("explicit profiles and task modes retain strict boundary validation", () => { + for (const profiles of [null, { coordinator: null }, { roles: { decision: specialist } }, { extra: true }]) { + assert.throws(() => resolveMissionCreationDefaults({ template: "debug", preferences, profiles: profiles as MissionProfiles })) + } + for (const taskMode of [null, "bad", false]) { + assert.throws(() => resolveMissionCreationDefaults({ template: "debug", preferences, taskMode: taskMode as "native" })) + } +}) + +test("legacy custom preferences migrate to all without changing the input", () => { + const legacy = [{ ...preferences[0], template: "custom" }] + const snapshot = structuredClone(legacy) + for (const template of templates) { + assert.deepEqual(resolveMissionCreationDefaults({ template, preferences: legacy }), resolveMissionCreationDefaults({ template, preferences })) + } + assert.deepEqual(legacy, snapshot) +}) + +test("Compare fills omitted, explicit and preferred judge models from a known native coordinator", () => { + const coordinatorModel = { providerID: "p", id: "known", variant: "default" } + const inherited = resolveMissionCreationDefaults({ template: "compare", preferences: [], coordinatorModel }) + assert.deepEqual(inherited.profiles.coordinator, {}) + assert.deepEqual(inherited.profiles.roles.comparator, { model: { providerID: "p", id: "known" } }) + assert.equal(inherited.origins.roles.comparator, "opencode-default") + for (const comparator of [{}, { agent: "judge" }]) { + const explicit = resolveMissionCreationDefaults({ template: "compare", preferences: [], coordinatorModel, profiles: { roles: { comparator } } }) + assert.deepEqual(explicit.profiles.roles.comparator, { ...comparator, model: { providerID: "p", id: "known" } }) + assert.equal(explicit.origins.roles.comparator, "explicit") + const preference = resolveMissionCreationDefaults({ template: "compare", coordinatorModel, + preferences: [{ template: "compare", profiles: { roles: { comparator } } }] }) + assert.deepEqual(preference.profiles.roles.comparator, { ...comparator, model: { providerID: "p", id: "known" } }) + assert.equal(preference.origins.roles.comparator, "preference") + } +}) + +test("every resolution is an independent copy of preferences and explicit inputs", () => { + const input = { template: "compare" as const, preferences: structuredClone(preferences), profiles: { coordinator: structuredClone(coordinator) } } + const snapshot = structuredClone(input) + const first = resolveMissionCreationDefaults(input), second = resolveMissionCreationDefaults(input) + first.profiles.coordinator.model!.id = "changed" + first.profiles.roles["model-a"].model!.variant = "changed" + first.origins.roles.comparator = "opencode-default" + assert.deepEqual(input, snapshot) + assert.deepEqual(second, resolveMissionCreationDefaults(input)) +}) diff --git a/packages/server/src/missions/profile-defaults.ts b/packages/server/src/missions/profile-defaults.ts new file mode 100644 index 0000000000..8f19db0030 --- /dev/null +++ b/packages/server/src/missions/profile-defaults.ts @@ -0,0 +1,147 @@ +import { z } from "zod" +import { parseMissionProfiles, missionProfilesInputSchema, missionProfileRoles, freezeCompareProfiles, validateMissionProfiles, type MissionProfiles } from "./playbook-profiles" +import type { MissionTemplateId } from "./model" +import type { MissionExecution } from "./execution" +import { missionTaskModeInputSchema, parseMissionTaskMode, type MissionTaskMode } from "./task-execution-mode" + +export type { MissionTaskMode } from "./task-execution-mode" +/** `all` is the global default; a mission type entry is an exception overriding it. */ +export type MissionDefaultScope = "all" | MissionTemplateId +export interface MissionProfileDefault { template: MissionDefaultScope; profiles: MissionProfiles; taskMode?: MissionTaskMode } +export const MISSION_DEFAULT_ORIGINS = ["explicit", "preference", "opencode-default"] as const +export const MISSION_PREFERENCES_UNAVAILABLE = "unavailable" +export type MissionDefaultOrigin = typeof MISSION_DEFAULT_ORIGINS[number] +const scopes: MissionDefaultScope[] = ["all", "custom", "debug", "wayfinder", "delivery", "compare"] +// The global default carries one task profile, like the Flexible specialist. +const scopeRoles = (scope: MissionDefaultScope): readonly string[] => missionProfileRoles[scope === "all" ? "custom" : scope] + +/** Preferences carry selectors only, never credentials, execution authority or sessions. */ +export function normalizeMissionDefaults(value: unknown): MissionProfileDefault[] { + if (!Array.isArray(value) || value.length > scopes.length) return [] + const result: MissionProfileDefault[] = [] + for (const entry of value) { + if (!entry || typeof entry !== "object" || Array.isArray(entry)) return [] + const template = entry.template as MissionDefaultScope + if (Object.keys(entry).some(key => !["template", "profiles", "taskMode"].includes(key)) + || (entry.taskMode !== undefined && !missionTaskModeInputSchema.safeParse(entry.taskMode).success) + || !scopes.includes(template) || result.some(item => item.template === template)) return [] + try { + const profiles = parseMissionProfiles(entry.profiles) + if (!profiles || Object.keys(profiles.roles ?? {}).some(role => !scopeRoles(template).includes(role))) return [] + result.push({ template, profiles, ...(entry.taskMode === undefined ? {} : { taskMode: entry.taskMode }) }) + } catch { return [] } + } + // Before the explicit global entry existed, the Flexible entry was the global base: + // read it as such so no saved choice changes meaning; the next save writes `all`. + const legacy = result.find(item => item.template === "custom") + if (legacy && !result.some(item => item.template === "all")) legacy.template = "all" + return result +} + +/** Document to write: a Flexible exception always travels with the explicit global + * entry, so the legacy decoding above never turns it into the global default. */ +export function encodeMissionDefaults(value: readonly MissionProfileDefault[]): MissionProfileDefault[] { + const flexibleOnly = value.some(item => item.template === "custom") && !value.some(item => item.template === "all") + return normalizeMissionDefaults(flexibleOnly ? [{ template: "all", profiles: {} }, ...value] : value) +} + +export function validMissionDefaults(value: unknown): boolean { + return value === undefined || (Array.isArray(value) && (value.length === 0 || normalizeMissionDefaults(value).length === value.length)) +} + +/** Type exception ?? global default ?? native. */ +export function missionTaskModeFor(value: readonly MissionProfileDefault[], template: MissionTemplateId): MissionTaskMode { + return resolveTaskMode(value, template).taskMode +} + +export function globalMissionTaskMode(value: readonly MissionProfileDefault[]): MissionTaskMode { + return resolveTaskMode(value, "all").taskMode +} + +function resolveTaskMode(value: readonly MissionProfileDefault[], template: MissionDefaultScope, explicit?: MissionTaskMode): { + taskMode: MissionTaskMode; origin: MissionDefaultOrigin +} { + const preferred = value.find(item => item.template === template)?.taskMode + ?? (template === "all" ? undefined : value.find(item => item.template === "all")?.taskMode) + return { taskMode: parseMissionTaskMode(explicit === undefined ? preferred : explicit), + origin: explicit !== undefined ? "explicit" : preferred !== undefined ? "preference" : "opencode-default" } +} + +/** Resolve a copy when the creation form opens. Existing missions never consult defaults. */ +export function missionDefaultsFor(value: readonly MissionProfileDefault[], template: MissionTemplateId, exceptions = true): MissionProfiles | undefined { + const base = value.find(item => item.template === "all")?.profiles + const specific = exceptions ? value.find(item => item.template === template)?.profiles : undefined + const coordinator = specific?.coordinator ?? base?.coordinator + const roles = Object.fromEntries(missionProfileRoles[template].flatMap(role => { + const execution = specific?.roles?.[role] ?? (template === "compare" && role === "comparator" ? undefined : base?.roles?.specialist) + return execution ? [[role, execution]] : [] + })) + if (!coordinator && !Object.keys(roles).length) return undefined + return structuredClone({ ...(coordinator ? { coordinator } : {}), ...(Object.keys(roles).length ? { roles } : {}) }) +} + +export class MissionPreferencesError extends Error { + readonly code = "mission-preferences-invalid" + constructor() { + super("Invalid mission profile defaults") + this.name = "MissionPreferencesError" + } +} + +const origin = z.enum(MISSION_DEFAULT_ORIGINS) +export const missionCreationSelectionSchema = z.object({ + profiles: missionProfilesInputSchema.transform((profiles, context) => { + if (profiles?.coordinator === undefined || profiles.roles === undefined) { + context.addIssue({ code: "custom", message: "Incomplete Mission profile selection" }); return z.NEVER + } + return { coordinator: profiles.coordinator, roles: profiles.roles } + }), + taskMode: missionTaskModeInputSchema, + origins: z.object({ coordinator: origin, roles: z.record(z.string(), origin), taskMode: origin }).strict(), + preferences: z.literal(MISSION_PREFERENCES_UNAVAILABLE).optional(), +}).strict() +export type MissionCreationSelection = z.infer + +/** Whole explicit slots and an explicit policy leave nothing for preferences to supply. */ +export function hasExplicitMissionCreationChoices(input: { + template: MissionTemplateId; profiles?: MissionProfiles; taskMode?: MissionTaskMode +}): boolean { + return input.taskMode !== undefined && input.profiles?.coordinator !== undefined + && missionProfileRoles[input.template].every(role => input.profiles?.roles?.[role] !== undefined) +} + +/** Resolve whole slots, then freeze Compare's missing judge model against the coordinator. */ +export function resolveMissionCreationDefaults(input: { + template: MissionTemplateId + preferences: unknown + profiles?: MissionProfiles + taskMode?: MissionTaskMode + coordinatorModel?: MissionExecution["model"] +}): MissionCreationSelection { + if (!validMissionDefaults(input.preferences)) throw new MissionPreferencesError() + const preferences = normalizeMissionDefaults(input.preferences) + const defaults = missionDefaultsFor(preferences, input.template) + const explicit = parseMissionProfiles(input.profiles) + validateMissionProfiles(input.template, explicit) + const slot = (requested?: MissionExecution, preferred?: MissionExecution): { execution: MissionExecution; origin: MissionDefaultOrigin } => ({ + execution: requested ?? preferred ?? {}, + origin: requested !== undefined ? "explicit" : preferred !== undefined ? "preference" : "opencode-default", + }) + const coordinator = slot(explicit?.coordinator, defaults?.coordinator) + const roles: Record = {} + const origins: Record = {} + for (const role of missionProfileRoles[input.template]) { + const selected = slot(explicit?.roles?.[role], defaults?.roles?.[role]) + if (input.template === "compare" && role === "comparator" && selected.origin === "opencode-default") { + selected.origin = coordinator.origin + } + roles[role] = selected.execution + origins[role] = selected.origin + } + const taskMode = resolveTaskMode(preferences, input.template, input.taskMode) + return missionCreationSelectionSchema.parse({ + profiles: freezeCompareProfiles(input.template, { coordinator: coordinator.execution, roles }, input.coordinatorModel), + taskMode: taskMode.taskMode, + origins: { coordinator: coordinator.origin, roles: origins, taskMode: taskMode.origin }, + }) +} diff --git a/packages/server/src/missions/recovery-error.test.ts b/packages/server/src/missions/recovery-error.test.ts index 8f16aa1cff..175dc0b86a 100644 --- a/packages/server/src/missions/recovery-error.test.ts +++ b/packages/server/src/missions/recovery-error.test.ts @@ -1,7 +1,7 @@ import assert from "node:assert/strict" import test from "node:test" import { MissionControlError } from "./control-error" -import { missionRecoveryError, missionRecoveryRejection } from "./recovery-error" +import { MISSION_DEFAULTS_REQUEST_INVALID, missionRecoveryControlError, missionRecoveryError, missionRecoveryRejection } from "./recovery-error" test("only allowlisted recovery errors cross the bridge, with fixed redacted text", () => { const safe = missionRecoveryRejection(new MissionControlError("secret native request", "recovery-busy")) @@ -12,3 +12,12 @@ test("only allowlisted recovery errors cross the bridge, with fixed redacted tex assert.equal(missionRecoveryRejection(new MissionControlError("secret", "foreign-session")), undefined) for (const value of ["toString", "__proto__", null, {}, 503]) assert.equal(missionRecoveryError(value), undefined) }) + +test("command validation is generic except for its exact allowlisted preference request guidance", () => { + const generic = missionRecoveryControlError("invalid-execution", "secret backend details") + assert.ok(!generic.message.includes("creating a mission")) + assert.ok(!generic.message.includes("secret")) + const error = missionRecoveryControlError("invalid-execution", MISSION_DEFAULTS_REQUEST_INVALID) + assert.equal(error.message, MISSION_DEFAULTS_REQUEST_INVALID) + assert.equal(missionRecoveryRejection(error)?.message, MISSION_DEFAULTS_REQUEST_INVALID) +}) diff --git a/packages/server/src/missions/recovery-error.ts b/packages/server/src/missions/recovery-error.ts index 8743fd29ea..5e081d704b 100644 --- a/packages/server/src/missions/recovery-error.ts +++ b/packages/server/src/missions/recovery-error.ts @@ -1,8 +1,11 @@ import { MissionControlError } from "./control-error" +export const MISSION_DEFAULTS_REQUEST_INVALID = "Correct the profile-defaults request: use a supported template, valid profiles and taskMode, and a complete coordinatorModel" + // Only fixed, non-sensitive recovery and coordinator-action failures may cross the desktop bridge. // Never pass native messages, request bodies or environment errors through it. const errors = { + "invalid-execution": { status: 409, message: "Correct the mission command, profiles or taskMode" }, "recovery-busy": { status: 409, message: "Native work or a wait prevents targeted recovery" }, "recovery-unknown": { status: 503, message: "Native activity is unknown; recovery was not admitted" }, "recovery-conflict": { status: 409, message: "Mission changed; reload before targeted recovery" }, @@ -10,15 +13,27 @@ const errors = { "task-not-retired": { status: 409, message: "Retire the task with mission.revise before stopping its work" }, "task-reused": { status: 409, message: "An open task continues this task's conversation; retire that task first" }, "prepare-refused": { status: 409, message: "The mission could not be prepared; nothing was created" }, + "prepare-no-effect": { status: 409, message: "The preparation request was refused without effects; correct the request and retry" }, "prepare-conflict": { status: 409, message: "This requestID already prepared a different mission" }, "prepare-uncertain": { status: 409, message: "The prepared mission's outcome is uncertain; retry with the same requestID" }, + "mission-preferences-invalid": { status: 409, message: "Correct the Missions preferences before creating a mission" }, + "mission-preferences-unavailable": { status: 503, message: "CodeNomad backend discovery, ownership or preference reading failed; restore the backend and reload Missions preferences" }, + "mission-preferences-update-required": { status: 503, message: "Update CodeNomad before using Missions preferences" }, + "compare-models-required": { status: 409, message: "Choose model-a and model-b profiles with explicit models before creating a Compare mission" }, + "compare-models-identical": { status: 409, message: "Choose different models for the model-a and model-b profiles before creating a Compare mission" }, } as const -export function missionRecoveryError(code: unknown): { code: string; status: number; message: string } | undefined { +export function missionRecoveryError(code: unknown, message?: unknown): { code: keyof typeof errors; status: number; message: string } | undefined { if (typeof code !== "string" || !Object.prototype.hasOwnProperty.call(errors, code)) return - return { code, ...errors[code as keyof typeof errors] } + const key = code as keyof typeof errors + return { code: key, ...errors[key], ...(key === "invalid-execution" && message === MISSION_DEFAULTS_REQUEST_INVALID ? { message } : {}) } +} + +export function missionRecoveryControlError(code: keyof typeof errors, message?: unknown): MissionControlError { + const failure = missionRecoveryError(code, message)! + return new MissionControlError(failure.message, failure.code) } export function missionRecoveryRejection(error: unknown) { - return error instanceof MissionControlError ? missionRecoveryError(error.code) : undefined + return error instanceof MissionControlError ? missionRecoveryError(error.code, error.message) : undefined } diff --git a/packages/server/src/missions/rpc.ts b/packages/server/src/missions/rpc.ts index 2b6f0a3b9b..e00cc886fc 100644 --- a/packages/server/src/missions/rpc.ts +++ b/packages/server/src/missions/rpc.ts @@ -1,5 +1,6 @@ import { executionSchema } from "./execution" import { missionProfilesSchema } from "./playbook-profiles" +import { missionCreationDefaultsWire } from "./creation-defaults" import { missionTaskModeSchema } from "./task-execution-mode" import { missionMutationErrors } from "./rpc-errors" import { lifecycleInputSchema, lifecycleOperationSchema } from "./lifecycle-schema" @@ -84,6 +85,7 @@ const mission = { notes: { type: "string" }, template: { type: "string", enum: ["custom", "debug", "wayfinder", "delivery", "compare"] }, profiles: missionProfilesSchema, + creationDefaults: missionCreationDefaultsWire, taskMode: missionTaskModeSchema, status: { type: "string", enum: ["active", "completed", "failed", "stopped"] }, runState: { type: "string", enum: ["prepared", "running", "paused", "stopped"] }, @@ -463,6 +465,7 @@ export const CODENOMAD_MISSIONS_RPC = { coordinatorSessionID: { type: "string", minLength: 1, maxLength: 240 } }, required: ["missionID", "coordinatorSessionID"], additionalProperties: false }, profiles: missionProfilesSchema, + creationDefaults: missionCreationDefaultsWire, taskMode: missionTaskModeSchema, }, required: ["requestID", "objective", "template"], additionalProperties: false, }, diff --git a/packages/server/src/opencode/automation-plugin-profile-defaults.test.ts b/packages/server/src/opencode/automation-plugin-profile-defaults.test.ts new file mode 100644 index 0000000000..b2b0d75b5a --- /dev/null +++ b/packages/server/src/opencode/automation-plugin-profile-defaults.test.ts @@ -0,0 +1,433 @@ +import assert from "node:assert/strict" +import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises" +import os from "node:os" +import path from "node:path" +import test from "node:test" +import Fastify from "fastify" +import childProcess from "node:child_process" +import { syncBuiltinESMExports } from "node:module" +import fs from "node:fs/promises" +import { EventEmitter } from "node:events" +import { PassThrough } from "node:stream" +import { MissionControlError } from "../missions/control-error" +import { MISSION_DEFAULTS_REQUEST_INVALID } from "../missions/recovery-error" +import { registerAutomationPluginRoute } from "../server/routes/automation-plugin" +import { setupMissionsPlugin } from "./missions-plugin" +import { AUTOMATION_BRIDGE_PATH, automationBridgeDirectories, createAutomationBridgeRegistration, publishAutomationBridge, resolveMissionProfileDefaults, sendMissionInput } from "./automation-plugin" + +test("profile defaults distinguish absent owners from ambiguous, failed and unreadable owners", async t => { + const root = await mkdtemp(path.join(os.tmpdir(), "codenomad-profile-default-bridge-")) + const previous = { LOCALAPPDATA: process.env.LOCALAPPDATA, XDG_RUNTIME_DIR: process.env.XDG_RUNTIME_DIR, WSL_DISTRO_NAME: process.env.WSL_DISTRO_NAME } + process.env.LOCALAPPDATA = root + process.env.XDG_RUNTIME_DIR = root + delete process.env.WSL_DISTRO_NAME + const app = Fastify() + const removals: Array<() => Promise> = [] + t.after(async () => { + await app.close() + await Promise.all(removals.map(remove => remove())) + for (const [key, value] of Object.entries(previous)) { + if (value === undefined) delete process.env[key] + else process.env[key] = value + } + await rm(root, { recursive: true, force: true }) + }) + const registration = createAutomationBridgeRegistration("http://127.0.0.1:54321") + let preferences: unknown = [], unreadable = false, denied = false, posts = 0, reads = 0, owned = true, ownershipFailure = false, noWorkspaces = false + let sessionFailure: "missing" | "unavailable" | undefined + let probeFailure: "network" | "refused" | "timeout" | "http" | "malformed" | "unproven-negative" | undefined + let inventoryFailure = false + let failureCode: string | undefined + let bridgeError = "secret backend detail", legacy = false, backendFailure = false + let postOwnership: "lost" | "failed" | undefined + registerAutomationPluginRoute(app, { + authManager: { isLoopbackRequest: () => true }, bridgeToken: registration.token, nativeParent: {}, developerCdp: {}, + settings: { getRawConfigOwner: () => { + reads++ + if (unreadable) throw new Error("secret preferences path") + return { settings: { missionProfileDefaults: preferences } } + } }, + workspaceManager: { + getSharedServiceClient: async () => ({ session: { get: async () => { + if (sessionFailure === "missing") throw Object.assign(new Error("Not found"), { _tag: "SessionNotFoundError", sessionID: "ses_owner" }) + if (sessionFailure) throw new Error("secret native error") + return { location: { directory: "/repo" } } + } } }), + list: () => { if (inventoryFailure) throw new Error("secret inventory failure"); return noWorkspaces ? [] : [{ id: "owner" }] }, + ownsLocation: async (_id: string, _location: unknown, _client: unknown, { strict }: { strict?: boolean }) => { + if (ownershipFailure) { if (strict) throw new Error("Ownership unavailable"); return false } + return owned + }, + }, + } as never) + t.mock.method(globalThis, "fetch", async (_url: unknown, options: RequestInit) => { + const body = JSON.parse(String(options.body)) + const token = new Headers(options.headers).get("x-codenomad-automation-token") + if (token !== registration.token) return new Response(JSON.stringify({ result: { available: true } }), { status: 200 }) + if (body.mode === "browser-claim") { + if (probeFailure === "network") throw new Error("secret network error") + if (probeFailure === "refused") throw Object.assign(new TypeError("fetch failed"), { cause: Object.assign(new Error("refused"), { code: "ECONNREFUSED" }) }) + if (probeFailure === "timeout") throw Object.assign(new Error("deadline"), { code: "ETIMEDOUT" }) + if (probeFailure === "http") return new Response(JSON.stringify({ error: "secret backend error" }), { status: 503 }) + if (probeFailure === "malformed") return new Response(JSON.stringify({ result: {} }), { status: 200 }) + if (probeFailure === "unproven-negative") return new Response(JSON.stringify({ error: "Session not found" }), { status: 404 }) + } + if (body.mode === "mission-input") { + posts++ + assert.equal(body.command.kind, "profile-defaults") + if (denied) return new Response(JSON.stringify({ error: "secret backend refusal" }), { status: 403 }) + if (legacy) return new Response(JSON.stringify({ error: "Unknown mission command" }), { status: 400 }) + if (backendFailure) return new Response(JSON.stringify({ error: "secret backend reader failure" }), { status: 502 }) + if (failureCode) return new Response(JSON.stringify({ code: failureCode, error: bridgeError }), { status: 409 }) + } + if (body.mode === "mission-input" && postOwnership) { + owned = postOwnership !== "lost" + ownershipFailure = postOwnership === "failed" + } + const response = await app.inject({ method: "POST", url: AUTOMATION_BRIDGE_PATH, + headers: { "x-codenomad-automation-token": token! }, payload: body }) + return new Response(response.body, { status: response.statusCode }) + }) + const request = () => resolveMissionProfileDefaults("ses_owner", { template: "custom" }) + const unavailable = (error: unknown) => error instanceof MissionControlError + && error.code === "mission-preferences-unavailable" + && error.message === "CodeNomad backend discovery, ownership or preference reading failed; restore the backend and reload Missions preferences" + const fallback = { profiles: { coordinator: {}, roles: { specialist: {} } }, taskMode: "native", + origins: { coordinator: "opencode-default", roles: { specialist: "opencode-default" }, taskMode: "opencode-default" }, preferences: "unavailable" } + assert.deepEqual(await request(), fallback, "without a registered owner, the tool reports its explicit fallback") + const explicit = await resolveMissionProfileDefaults("ses_owner", { template: "custom", profiles: { coordinator: { agent: "lead" } }, taskMode: "independent" }) as any + assert.deepEqual(explicit.profiles.coordinator, { agent: "lead" }) + assert.equal(explicit.origins.coordinator, "explicit") + assert.equal(explicit.origins.taskMode, "explicit") + assert.equal(explicit.preferences, "unavailable") + await assert.rejects(resolveMissionProfileDefaults("ses_owner", { template: "debug", profiles: { roles: { specialist: {} } } }), + (error: unknown) => error instanceof MissionControlError && error.code === "invalid-execution") + await assert.rejects(sendMissionInput("ses_owner", "prepare", {}), (error: unknown) => error instanceof MissionControlError + && error.code === "prepare-refused", "a prepare with no owner has not been dispatched") + await assert.rejects(sendMissionInput("ses_owner", "prompt", {}), /exactly one owning/, "other commands keep their error") + + const values = new Map(), tools = new Map() + let handlers: any + const cleanup = await setupMissionsPlugin({ + location: { directory: "/standalone", project: { id: "standalone", canonical: "/standalone" } }, + storage: { + get: async (key: string) => structuredClone(values.get(key)), + set: async (key: string, value: unknown) => { values.set(key, structuredClone(value)) }, + remove: async (key: string) => { values.delete(key) }, + scan: async ({ prefix }: { prefix: string }) => ({ entries: [...values].filter(([key]) => key.startsWith(prefix)).map(([key, value]) => ({ key, value })) }), + }, + session: { + get: async ({ sessionID }: { sessionID: string }) => ({ id: sessionID, agent: "lead", projectID: "standalone", location: { directory: "/standalone" } }), + create: async () => assert.fail("Standalone inspect attaches its caller"), + prompt: async () => assert.fail("Creation never prompts"), synthetic: async () => assert.fail("Creation never resumes"), + hook: async () => ({ dispose: async () => {} }), + }, + agent: { list: async () => ({ data: [{ id: "lead", mode: "primary" }] }) }, model: { list: async () => ({ data: [] }) }, + tool: { transform: async (callback: any) => { callback({ namespace() {}, add(tool: any) { tools.set(tool.name, tool) } }); return { dispose: async () => {} } } }, + rpc: { register: async (_definition: unknown, registered: unknown) => { handlers = registered; return { dispose: async () => {}, events: { emit: async () => {} } } } }, + } as never, { + prompt: async () => assert.fail("Creation never prompts"), synthetic: async () => assert.fail("Creation never resumes"), + resolveCreationDefaults: resolveMissionProfileDefaults, + prepare: (id, input) => sendMissionInput(id, "prepare", input), + }) + t.after(cleanup) + const toolContext = { sessionID: "ses_standalone", messageID: "msg_standalone", id: "standalone-start", progress: async () => {} } + const start = { start: { objective: "Standalone creation", template: "custom" } } + const started = JSON.parse((await tools.get("inspect").execute(start, toolContext)).content) + assert.deepEqual(started.selection, fallback) + const saved = (await handlers.snapshot()).missions[0] + assert.equal(saved.creationDefaults.preferences, "unavailable") + const explicitContext = { ...toolContext, sessionID: "ses_explicit", id: "explicit-start" } + const explicitStart = { start: { objective: "Explicit standalone", template: "custom", profiles: { coordinator: { agent: "lead" } }, taskMode: "independent" } } + const explicitCreated = JSON.parse((await tools.get("inspect").execute(explicitStart, explicitContext)).content) + assert.equal(explicitCreated.selection.preferences, "unavailable") + assert.deepEqual(explicitCreated.selection.profiles.coordinator, { agent: "lead" }) + assert.equal(explicitCreated.selection.origins.coordinator, "explicit") + assert.equal(explicitCreated.selection.origins.taskMode, "explicit") + assert.equal((await handlers.snapshot()).missions.find((mission: any) => mission.id === explicitCreated.mission.id).creationDefaults.preferences, "unavailable") + await assert.rejects(tools.get("prepare").execute({ requestID: "no-backend", objective: "Handoff", template: "custom" }, toolContext), + (error: unknown) => error instanceof MissionControlError && error.code === "prepare-refused") + assert.equal((await handlers.snapshot()).missions.length, 2, "backend-less hand-offs remain unavailable") + assert.equal([...values.keys()].some(key => key.includes("/creation-intents/")), false) + + const registry = (await automationBridgeDirectories())[0] + await mkdir(registry, { recursive: true }) + const deadFile = path.join(registry, `${Date.now()}-2147483647-dead.json`) + await writeFile(deadFile, "{unreadable") + assert.deepEqual(await request(), fallback, "a dead publishing pid is absent even when its registration cannot be parsed") + await assert.rejects(readFile(deadFile), (error: any) => error.code === "ENOENT") + const liveFile = path.join(registry, `${Date.now()}-${process.pid}-unknown.json`) + await writeFile(liveFile, "{unreadable") + await assert.rejects(request(), unavailable, "an unreadable live publisher cannot safely be ignored") + const unpublish = await publishAutomationBridge(registration) + try { assert.equal(await readFile(liveFile, "utf8"), "{unreadable", "another publisher's cleanup preserves unreadable live registrations") } + finally { await unpublish() } + await rm(liveFile) + + removals.push(await publishAutomationBridge(registration)) + const resolved = await request() as { taskMode: string } + assert.equal(resolved.taskMode, "native") + assert.equal("preferences" in resolved, false, "readable owner preferences need no unavailable warning") + const beforeRace = reads + for (postOwnership of ["lost", "failed"] as const) { + await assert.rejects(request(), unavailable, "ownership changing after the strict claim is not an old-backend error") + owned = true; ownershipFailure = false + } + postOwnership = undefined + assert.equal(reads, beforeRace, "failed command authorization never reads settings") + const beforeNegative = reads + owned = false + assert.deepEqual(await request(), fallback, "clean non-ownership remains negative proof while unrelated workspaces are open") + noWorkspaces = true + assert.deepEqual(await request(), fallback, "a backend with no open workspace cannot own this session") + noWorkspaces = false + owned = true + sessionFailure = "missing" + assert.deepEqual(await request(), fallback, "a typed native missing-session reply proves this backend is not an owner") + assert.equal(reads, beforeNegative) + sessionFailure = "unavailable" + await assert.rejects(request(), unavailable, "a failed session lookup cannot prove that no owner exists") + sessionFailure = undefined + ownershipFailure = true + await assert.rejects(request(), unavailable) + ownershipFailure = false + inventoryFailure = true + await assert.rejects(request(), unavailable) + inventoryFailure = false + probeFailure = "refused" + assert.deepEqual(await request(), fallback, "a stale Windows or local registration with no listener is absent") + for (probeFailure of ["network", "timeout", "http", "malformed"] as const) await assert.rejects(request(), unavailable, "a registered backend failure refuses fallback") + probeFailure = "unproven-negative" + await assert.rejects(request(), (error: unknown) => error instanceof MissionControlError && error.code === "mission-preferences-update-required") + probeFailure = undefined + preferences = [{ template: "all", profiles: {}, taskMode: "independent" }] + assert.equal((await request() as { taskMode: string }).taskMode, "independent", "the next bridge call reads fresh preferences") + preferences = "secret-invalid-value" + await assert.rejects(request(), (error: unknown) => error instanceof MissionControlError + && error.code === "mission-preferences-invalid" && error.message === "Correct the Missions preferences before creating a mission") + unreadable = true + await assert.rejects(request(), unavailable) + unreadable = false + denied = true + await assert.rejects(request(), unavailable, "untyped backend refusals must also remain fixed") + denied = false + for (const code of ["compare-models-required", "compare-models-identical"]) { + failureCode = code + await assert.rejects(request(), (error: unknown) => error instanceof MissionControlError + && error.code === code && error.message.startsWith("Choose ") && !error.message.includes("secret")) + } + failureCode = undefined + legacy = true + await assert.rejects(request(), (error: unknown) => error instanceof MissionControlError + && error.code === "mission-preferences-update-required" && error.message.includes("Update CodeNomad"), + "a legacy owner cannot be discarded without silently losing its preferences") + legacy = false + backendFailure = true + await assert.rejects(request(), unavailable, "a current backend's reader failure is unavailable, not an upgrade requirement") + backendFailure = false + failureCode = "invalid-execution" + bridgeError = MISSION_DEFAULTS_REQUEST_INVALID + await assert.rejects(request(), (error: unknown) => error instanceof MissionControlError && error.message === MISSION_DEFAULTS_REQUEST_INVALID) + failureCode = undefined + bridgeError = "secret backend detail" + const before = posts + removals.push(await publishAutomationBridge(createAutomationBridgeRegistration("http://127.0.0.1:54322"))) + await assert.rejects(request(), unavailable, "multiple owners must expose the same fixed preference refusal") + await assert.rejects(sendMissionInput("ses_owner", "prepare", {}), (error: unknown) => error instanceof MissionControlError + && error.code === "prepare-refused", "an ambiguous prepare has not been dispatched") + assert.equal(posts, before, "ambiguous ownership reads no preferences") + assert.deepEqual(JSON.parse((await tools.get("inspect").execute(start, toolContext)).content).selection, fallback, + "a saved standalone warning is stable even after backends appear and become ambiguous") + assert.deepEqual(JSON.parse((await tools.get("inspect").execute(explicitStart, explicitContext)).content).selection, explicitCreated.selection) + assert.equal(posts, before, "the saved creation is returned without another preference request") +}) + +test("prepare never dispatches creation provenance to either legacy backend path", async t => { + const root = await mkdtemp(path.join(os.tmpdir(), "codenomad-prepare-capability-")) + const previous = { LOCALAPPDATA: process.env.LOCALAPPDATA, XDG_RUNTIME_DIR: process.env.XDG_RUNTIME_DIR, WSL_DISTRO_NAME: process.env.WSL_DISTRO_NAME } + process.env.LOCALAPPDATA = root; process.env.XDG_RUNTIME_DIR = root; delete process.env.WSL_DISTRO_NAME + const remove = await publishAutomationBridge(createAutomationBridgeRegistration("http://127.0.0.1:54329")) + t.after(async () => { + await remove() + for (const [key, value] of Object.entries(previous)) { if (value === undefined) delete process.env[key]; else process.env[key] = value } + await rm(root, { recursive: true, force: true }) + }) + let mode: "old-desktop" | "old-host" | "current" = "old-desktop", posts = 0 + t.mock.method(globalThis, "fetch", async (_url: unknown, options: RequestInit) => { + const body = JSON.parse(String(options.body)) + if (body.mode === "browser-claim") { + assert.equal(body.purpose, "mission-prepare") + return mode === "old-host" ? new Response(JSON.stringify({ error: "Browser automation is unavailable in this host" }), { status: 404 }) + : new Response(JSON.stringify({ result: { available: true, ...(mode === "current" ? { missionCreationDefaults: true } : {}) } })) + } + posts++ + return new Response(JSON.stringify({ result: { admitted: true } })) + }) + for (mode of ["old-desktop", "old-host"] as const) { + await assert.rejects(sendMissionInput("ses_prepare", "prepare", { creationDefaults: {} }), + (error: unknown) => error instanceof MissionControlError && error.code === "mission-preferences-update-required") + assert.equal(posts, 0, "no old strict prepare schema can observe the unknown field") + } + mode = "current" + assert.deepEqual(await sendMissionInput("ses_prepare", "prepare", { creationDefaults: {} }), { admitted: true }) + assert.equal(posts, 1) +}) + +test("strict WSL discovery cannot omit an unobserved Windows registry", async () => { + const options = { platform: "linux" as const, env: { WSL_DISTRO_NAME: "fixture" }, home: "/fixture", windowsLocalAppData: null } + assert.deepEqual(await automationBridgeDirectories(options), ["/fixture/.config/codenomad/automation-bridges"]) + await assert.rejects(automationBridgeDirectories({ ...options, strict: true }), /Windows mission backend discovery is unavailable/) + assert.deepEqual(await automationBridgeDirectories({ ...options, windowsLocalAppData: "/mnt/c/fixture", strict: true }), [ + "/fixture/.config/codenomad/automation-bridges", "/mnt/c/fixture/CodeNomad/automation-bridges", + ]) +}) + +test("strict WSL discovery caches a failed lookup briefly, then retries", async t => { + let attempts = 0, now = 10_000 + t.mock.method(Date, "now", () => now) + t.mock.method(childProcess, "execFile", (_file: string, _args: string[], _options: unknown, callback: (error: Error) => void) => { attempts++; callback(new Error("Host lookup failed")) }) + syncBuiltinESMExports() + t.after(() => { t.mock.restoreAll(); syncBuiltinESMExports() }) + const options = { platform: "linux" as const, env: { WSL_DISTRO_NAME: "fixture-cache" }, home: "/fixture" } + assert.deepEqual(await automationBridgeDirectories(options), ["/fixture/.config/codenomad/automation-bridges"]) + assert.equal(attempts, 1) + await assert.rejects(automationBridgeDirectories({ ...options, strict: true }), /Windows mission backend discovery is unavailable/) + assert.equal(attempts, 1, "uncertainty stays a refusal without repeated launches") + now += 2_001 + assert.deepEqual(await automationBridgeDirectories(options), ["/fixture/.config/codenomad/automation-bridges"]) + assert.equal(attempts, 1, "ordinary discovery retains its failed lookup without retrying") + await assert.rejects(automationBridgeDirectories({ ...options, strict: true }), /Windows mission backend discovery is unavailable/) + assert.equal(attempts, 2) +}) + +test("Windows discovery keys and launches use the effective environment", async t => { + let calls = 0 + t.mock.method(childProcess, "execFile", (file: string, _args: string[], options: { env: NodeJS.ProcessEnv }, callback: (error: null, stdout: string) => void) => { + calls++ + callback(null, file === "cmd.exe" ? "C:/fixture" : `${options.env.PATH}/windows`) + }) + syncBuiltinESMExports() + t.after(() => { t.mock.restoreAll(); syncBuiltinESMExports() }) + for (const PATH of ["/first", "/second"]) { + const options = { platform: "linux" as const, env: { WSL_DISTRO_NAME: "fixture-path", PATH }, home: "/fixture", strict: true } + assert.deepEqual(await automationBridgeDirectories(options), ["/fixture/.config/codenomad/automation-bridges", `${PATH}/windows/CodeNomad/automation-bridges`]) + await automationBridgeDirectories(options) + } + assert.equal(calls, 4, "each effective PATH has one lookup and one translation") +}) + +test("parallel Windows discovery yields the event loop and shares one asynchronous lookup", async t => { + let calls = 0, release!: () => void + t.mock.method(childProcess, "execFile", (file: string, _args: string[], _options: unknown, callback: (error: null, stdout: string) => void) => { + calls++ + if (file === "cmd.exe") release = () => callback(null, "C:/fixture") + else callback(null, "/fixture-windows") + }) + syncBuiltinESMExports() + t.after(() => { t.mock.restoreAll(); syncBuiltinESMExports() }) + const options = { platform: "linux" as const, env: { WSL_DISTRO_NAME: "fixture-coalesced" }, home: "/fixture", strict: true } + const first = automationBridgeDirectories(options), second = automationBridgeDirectories(options) + assert.equal(calls, 1) + await new Promise(resolve => setImmediate(resolve)) + assert.equal(calls, 1, "other event-loop work runs before the slow command returns") + release() + assert.deepEqual(await first, await second) + assert.equal(calls, 2, "one cmd lookup and one translation serve both callers") +}) + +test("unavailable Windows interop proves absence, while uncertain launches still refuse", async t => { + const options = { platform: "linux" as const, env: { WSL_DISTRO_NAME: "fixture-launch" }, home: "/fixture" } + let missing = "cmd.exe", code = "ENOENT", now = 20_000 + t.mock.method(Date, "now", () => now) + t.mock.method(childProcess, "execFile", (command: string, _args: string[], _options: unknown, callback: (error: Error | null, stdout?: string) => void) => { + if (command === missing) callback(Object.assign(new Error("fixture launch failure"), { code })) + else callback(null, "C:/fixture") + }) + syncBuiltinESMExports() + t.after(() => { t.mock.restoreAll(); syncBuiltinESMExports() }) + for (missing of ["cmd.exe", "wslpath"]) for (code of ["ENOENT", "ENOEXEC"]) { + now += 2_001 + assert.deepEqual(await automationBridgeDirectories({ ...options, strict: true }), ["/fixture/.config/codenomad/automation-bridges"]) + } + code = "ETIMEDOUT" + now += 2_001 + await assert.rejects(automationBridgeDirectories({ ...options, strict: true }), /Windows mission backend discovery is unavailable/) +}) + +test("WSL Windows discovery skips unusable advertisements and refused endpoints, retaining live failures", async t => { + const platform = Object.getOwnPropertyDescriptor(process, "platform")! + const previous = { WSL_DISTRO_NAME: process.env.WSL_DISTRO_NAME, XDG_RUNTIME_DIR: process.env.XDG_RUNTIME_DIR } + Object.defineProperty(process, "platform", { value: "linux", configurable: true }) + process.env.WSL_DISTRO_NAME = "fixture-advertisements" + process.env.XDG_RUNTIME_DIR = "/fixture-linux" + t.after(() => { + Object.defineProperty(process, "platform", platform) + for (const [key, value] of Object.entries(previous)) { + if (value === undefined) delete process.env[key]; else process.env[key] = value + } + t.mock.restoreAll() + syncBuiltinESMExports() + }) + const registration = createAutomationBridgeRegistration("http://127.0.0.1:1") + let bytes = Buffer.from(JSON.stringify(registration)), probes = 0, readFailed = false, readCode = "EACCES" + let local = false, filePID = registration.pid, pruned = 0 + t.mock.method(process, "kill", (pid: number) => { + assert.ok(local && pid <= 0x7fffffff, "only representable local PIDs may be probed") + return true + }) + t.mock.method(fs, "rm", async () => { assert.ok(local, "WSL leaves foreign advertisements to their publisher"); pruned++ }) + t.mock.method(childProcess, "execFile", (_file: string, _args: string[], _options: unknown, callback: (error: null, stdout: string) => void) => callback(null, "/fixture-windows")) + t.mock.method(fs, "opendir", async (directory: string) => (async function* () { + if (directory.startsWith(local ? "/fixture-linux/" : "/fixture-windows/")) yield { + name: `${registration.startedAt}-${filePID}-windows.json`, isFile: () => true, + } + })()) + t.mock.method(fs, "open", async () => { + if (readFailed) throw Object.assign(new Error("fixture file read failure"), { code: readCode }) + return { read: async (buffer: Buffer) => { bytes.copy(buffer); return { bytesRead: bytes.length } }, close: async () => {} } + }) + let exit = 7, status = 0, diagnostic = "* connect to 127.0.0.1 port 1 failed: Connection refused" + t.mock.method(childProcess, "spawn", (command: string, args: string[]) => { + probes++ + assert.equal(command, "curl.exe") + assert.deepEqual(args.slice(args.indexOf("--noproxy"), args.indexOf("--noproxy") + 2), ["--noproxy", "*"]) + const child = Object.assign(new EventEmitter(), { + stdin: new PassThrough(), stdout: new PassThrough(), stderr: new PassThrough(), kill: () => true, + }) + child.stdin.on("finish", () => setImmediate(() => { + child.stderr.write(diagnostic) + child.stdout.write(`${JSON.stringify({ error: "fixture refusal" })}\n${status}`) + child.emit("close", exit) + })) + return child + }) + syncBuiltinESMExports() + const request = () => resolveMissionProfileDefaults("ses_wsl", { template: "custom" }) + assert.equal((await request() as any).preferences, "unavailable", "curl's connection-refused diagnostic proves no Windows listener") + for (diagnostic of ["* connect to 127.0.0.1 port 1 failed: Permission denied (10013)", "curl: (7) Could not connect to server"]) { + await assert.rejects(request(), (error: unknown) => error instanceof MissionControlError && error.code === "mission-preferences-unavailable", + "curl exit 7 without a refusal diagnostic leaves ownership indeterminate") + } + for (const failure of [{ exit: 28, status: 0 }, { exit: 0, status: 503 }, { exit: 0, status: 401 }]) { + ;({ exit, status } = failure) + await assert.rejects(request(), (error: unknown) => error instanceof MissionControlError && error.code === "mission-preferences-unavailable") + } + const beforeInvalid = probes + for (const value of [JSON.stringify({ ...registration, version: 0 }), "x".repeat(4097), + JSON.stringify({ ...registration, url: "http://example.invalid" }), "{unparseable"]) { + bytes = Buffer.from(value) + assert.equal((await request() as any).preferences, "unavailable", "an unusable foreign advertisement supplies no current bridge contract") + } + assert.equal(probes, beforeInvalid, "unusable advertisements never select a bridge or admit work") + readFailed = true + await assert.rejects(request(), (error: unknown) => error instanceof MissionControlError && error.code === "mission-preferences-unavailable", + "a failed file read may hide a valid owner and stays distinct from malformed foreign content") + readCode = "ENOENT" + assert.equal((await request() as any).preferences, "unavailable", "a vanished Windows file is absent") + local = true + assert.equal((await request() as any).preferences, "unavailable", "a vanished local file is absent") + assert.equal(pruned, 0) + filePID = 0x80000000 + assert.equal((await request() as any).preferences, "unavailable", "an unrepresentable PID cannot keep an advertisement alive") + assert.equal(pruned, 1) +}) diff --git a/packages/server/src/opencode/automation-plugin.test.ts b/packages/server/src/opencode/automation-plugin.test.ts index 930e801822..a8ed8b4756 100644 --- a/packages/server/src/opencode/automation-plugin.test.ts +++ b/packages/server/src/opencode/automation-plugin.test.ts @@ -241,8 +241,8 @@ test("registers developer tools while execution remains session-gated", async () assert.deepEqual(tools, ["inspect", "act", "screenshot"]) }) -test("discovers the Windows bridge registry from a WSL plugin", () => { - assert.deepEqual(automationBridgeDirectories({ +test("discovers the Windows bridge registry from a WSL plugin", async () => { + assert.deepEqual(await automationBridgeDirectories({ platform: "linux", env: { WSL_DISTRO_NAME: "Ubuntu", XDG_RUNTIME_DIR: "/run/user/1000" }, home: "/home/dev", @@ -276,7 +276,7 @@ test("slow WSL registry discovery stays cancellable, retries cancellation and ca return {} as never }) as unknown as typeof childProcess.execFile) syncBuiltinESMExports() - const expected = automationBridgeDirectories({ ...options, windowsLocalAppData: "/mnt/c/Users/dev/AppData/Local" }) + const expected = await automationBridgeDirectories({ ...options, windowsLocalAppData: "/mnt/c/Users/dev/AppData/Local" }) assert.deepEqual(await discoverAutomationBridgeDirectories(undefined, options), expected) assert.deepEqual(await discoverAutomationBridgeDirectories(undefined, options), expected) assert.equal(calls, 3, "successful Windows discovery is cached across demands") diff --git a/packages/server/src/opencode/automation-plugin.ts b/packages/server/src/opencode/automation-plugin.ts index 2c83a55faf..a5a4388a37 100644 --- a/packages/server/src/opencode/automation-plugin.ts +++ b/packages/server/src/opencode/automation-plugin.ts @@ -6,7 +6,10 @@ import path from "node:path" import type { Plugin } from "@opencode/plugin" import { MissionControlError } from "../missions/control-error" import { signNativeRecurrenceControl, type RecurrenceControlProofBody } from "../missions/recurrence-control-proof" -import { missionRecoveryError } from "../missions/recovery-error" +import { missionRecoveryControlError, missionRecoveryError } from "../missions/recovery-error" +import { parseMissionCreationDefaultsInput } from "../missions/creation-defaults" +import { MISSION_PREFERENCES_UNAVAILABLE, resolveMissionCreationDefaults } from "../missions/profile-defaults" +import { isConnectionRefused } from "./connection-errors" import { PAGE_ACTION_PROPERTIES, PAGE_ACTIONS, parsePageAction, type RefAction } from "../automation/page/parse" import { MemoryError } from "../memory/model" import type { MemoryErrorCode } from "../memory/model" @@ -24,9 +27,11 @@ const MAX_LOCAL_REGISTRY_FILES = 4096 const MAX_REGISTRATION_BYTES = 4 * 1024 const MAX_BRIDGE_RESPONSE_BYTES = 8 * 1024 * 1024 const PROBE_CONCURRENCY = 4 -const REGISTRATION_NAME = /^(\d+)-\d+-[A-Za-z0-9_-]+\.json$/ +const REGISTRATION_NAME = /^(\d+)-(\d+)-[A-Za-z0-9_-]+\.json$/ const WINDOWS_INTEROP = Symbol("windowsInterop") -let cachedWslWindowsLocalAppData: string | undefined +type WindowsDiscovery = string | false | null +let cachedWslWindowsLocalAppData: { key: string; value: WindowsDiscovery; expiresAt: number } | undefined +let pendingWslWindowsLocalAppData: { key: string; promise: Promise } | undefined export type DeveloperAction = | { action: "inspect"; ref?: string; query?: string } @@ -71,60 +76,75 @@ interface ProbedBridge { type DiscoveredBridgeRegistration = AutomationBridgeRegistration & { [WINDOWS_INTEROP]?: true } -export function automationBridgeDirectory(): string { - return automationBridgeDirectories()[0] -} - -export function automationBridgeDirectories(options: { +type BridgeDirectoryOptions = { platform?: NodeJS.Platform env?: NodeJS.ProcessEnv home?: string - windowsLocalAppData?: string -} = {}): string[] { + windowsLocalAppData?: WindowsDiscovery + strict?: boolean +} + +export function automationBridgeDirectory(options: BridgeDirectoryOptions = {}): string { const platform = options.platform ?? process.platform const env = options.env ?? process.env const paths = platform === "win32" ? path.win32 : path.posix const home = options.home ?? os.homedir() - const primary = platform === "win32" && env.LOCALAPPDATA + return platform === "win32" && env.LOCALAPPDATA ? paths.join(env.LOCALAPPDATA, "CodeNomad", "automation-bridges") : env.XDG_RUNTIME_DIR ? paths.join(env.XDG_RUNTIME_DIR, "codenomad", "automation-bridges") : paths.join(home, ".config", "codenomad", "automation-bridges") +} + +export async function automationBridgeDirectories(options: BridgeDirectoryOptions = {}): Promise { + const platform = options.platform ?? process.platform + const env = options.env ?? process.env + const primary = automationBridgeDirectory(options) if (platform !== "linux" || !env.WSL_DISTRO_NAME) return [primary] - const windowsLocalAppData = options.windowsLocalAppData + const windowsLocalAppData = options.windowsLocalAppData !== undefined ? options.windowsLocalAppData : await resolveWslWindowsLocalAppData(env, { strict: options.strict }) + if (options.strict && !windowsLocalAppData && windowsLocalAppData !== false) throw new Error("Windows mission backend discovery is unavailable") return windowsLocalAppData ? [...new Set([primary, path.posix.join(windowsLocalAppData, "CodeNomad", "automation-bridges")])] : [primary] } -export async function discoverAutomationBridgeDirectories(signal?: AbortSignal, - options: Parameters[0] = {}): Promise { +export async function discoverAutomationBridgeDirectories(signal?: AbortSignal, options: BridgeDirectoryOptions = {}): Promise { signal?.throwIfAborted() - if ((options.platform ?? process.platform) !== "linux" || !(options.env ?? process.env).WSL_DISTRO_NAME) - return automationBridgeDirectories(options) - const windowsLocalAppData = options.windowsLocalAppData ?? await resolveWslWindowsLocalAppData(signal) + const env = options.env ?? process.env + if ((options.platform ?? process.platform) !== "linux" || !env.WSL_DISTRO_NAME) return automationBridgeDirectories(options) + const windowsLocalAppData = options.windowsLocalAppData !== undefined ? options.windowsLocalAppData + : await resolveWslWindowsLocalAppData(env, { strict: options.strict, signal, cacheFailures: false }) signal?.throwIfAborted() return automationBridgeDirectories({ ...options, windowsLocalAppData }) } -async function resolveWslWindowsLocalAppData(signal?: AbortSignal): Promise { - if (cachedWslWindowsLocalAppData !== undefined) return cachedWslWindowsLocalAppData - const command = (file: string, args: string[]) => new Promise((resolve, reject) => { - execFile(file, args, { encoding: "utf8", timeout: 2_000, windowsHide: true, maxBuffer: MAX_REGISTRATION_BYTES, signal }, - (error, stdout) => error ? reject(error) : resolve(stdout.trim())) - }) - try { - const windowsPath = await command("cmd.exe", ["/d", "/s", "/c", "echo %LOCALAPPDATA%"]) - signal?.throwIfAborted() - const translated = await command("wslpath", ["-u", windowsPath]) - signal?.throwIfAborted() - if (path.posix.isAbsolute(translated)) cachedWslWindowsLocalAppData = translated - } catch { - signal?.throwIfAborted() - // Interop can become available later; retain only a qualified path. - return undefined - } - return cachedWslWindowsLocalAppData +function windowsDiscoveryOutput(file: string, args: string[], env: NodeJS.ProcessEnv, signal?: AbortSignal): Promise { + return new Promise((resolve, reject) => execFile(file, args, { env, signal, encoding: "utf8", timeout: 2_000, maxBuffer: MAX_REGISTRATION_BYTES, windowsHide: true }, + (error, stdout) => error ? reject(error) : resolve(stdout.trim()))) +} + +function resolveWslWindowsLocalAppData(env: NodeJS.ProcessEnv, { strict = false, signal, cacheFailures = true }: { strict?: boolean; signal?: AbortSignal; cacheFailures?: boolean } = {}): Promise { + const key = `${env.WSL_DISTRO_NAME}\0${env.PATH}` + if (cachedWslWindowsLocalAppData?.key === key && (typeof cachedWslWindowsLocalAppData.value === "string" + || cacheFailures && (!strict || cachedWslWindowsLocalAppData.expiresAt > Date.now()))) return Promise.resolve(cachedWslWindowsLocalAppData.value) + if (cacheFailures && !signal && pendingWslWindowsLocalAppData?.key === key) return pendingWslWindowsLocalAppData.promise + const promise = (async (): Promise => { + try { + const windowsPath = await windowsDiscoveryOutput("cmd.exe", ["/d", "/s", "/c", "echo %LOCALAPPDATA%"], env, signal) + signal?.throwIfAborted() + const translated = await windowsDiscoveryOutput("wslpath", ["-u", windowsPath], env, signal) + signal?.throwIfAborted() + return path.posix.isAbsolute(translated) ? translated : null + } catch (error) { + signal?.throwIfAborted() + return ["ENOENT", "ENOEXEC"].includes((error as NodeJS.ErrnoException).code ?? "") ? false : null + } + })().then(value => { + if (cacheFailures || typeof value === "string") cachedWslWindowsLocalAppData = { key, value, expiresAt: typeof value === "string" ? Infinity : Date.now() + 2_000 } + return value + }).finally(() => { if (pendingWslWindowsLocalAppData?.promise === promise) pendingWslWindowsLocalAppData = undefined }) + if (cacheFailures && !signal) pendingWslWindowsLocalAppData = { key, promise } + return promise } export function createAutomationBridgeRegistration(url: string): AutomationBridgeRegistration { @@ -184,24 +204,40 @@ async function writeAtomic(target: string, content: string): Promise { } function isProcessAlive(pid: number): boolean { + if (!Number.isInteger(pid) || pid <= 0 || pid > 0x7fffffff) return false try { process.kill(pid, 0) return true } catch (error) { - return (error as NodeJS.ErrnoException).code === "EPERM" + return (error as NodeJS.ErrnoException).code !== "ESRCH" } } -async function readRegistration(target: string): Promise { +function registrationFile(name: string, local: boolean) { + const match = REGISTRATION_NAME.exec(name) + if (!match) return undefined + const pid = Number(match[2]) + return { name, startedAt: Number(match[1]), deadPublisher: local && !isProcessAlive(pid) } +} + +type RegistrationFile = NonNullable> + +async function readRegistration(target: string, { throwReadErrors = false } = {}): Promise { + const buffer = Buffer.alloc(MAX_REGISTRATION_BYTES + 1) + let bytesRead = 0 try { const file = await open(target, "r") - const buffer = Buffer.alloc(MAX_REGISTRATION_BYTES + 1) - let bytesRead = 0 try { bytesRead = (await file.read(buffer, 0, buffer.length, 0)).bytesRead } finally { await file.close() } + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") return null + if (throwReadErrors) throw error + return undefined + } + try { if (bytesRead > MAX_REGISTRATION_BYTES) return undefined const value = JSON.parse(buffer.subarray(0, bytesRead).toString("utf8")) as Partial if (value.version !== 1 || typeof value.url !== "string" || typeof value.token !== "string" @@ -218,12 +254,12 @@ async function readRegistration(target: string): Promise { try { const stream = await opendir(directory) - const entries: Array<{ name: string; startedAt: number }> = [] + const entries: RegistrationFile[] = [] for await (const entry of stream) { if (!entry.isFile()) continue - const match = REGISTRATION_NAME.exec(entry.name) - if (!match) continue - entries.push({ name: entry.name, startedAt: Number(match[1]) }) + const file = registrationFile(entry.name, true) + if (!file) continue + entries.push(file) if (entries.length > MAX_LOCAL_REGISTRY_FILES * 2) { entries.sort((left, right) => right.startedAt - left.startedAt) entries.length = MAX_LOCAL_REGISTRY_FILES @@ -234,7 +270,7 @@ async function pruneDeadLocalRegistrations(directory: string): Promise { for (const entry of entries) { const target = path.join(directory, entry.name) const registration = await readRegistration(target) - if (!registration || !isProcessAlive(registration.pid)) await rm(target, { force: true }) + if (entry.deadPublisher || registration && !isProcessAlive(registration.pid)) await rm(target, { force: true }) } } catch { // Registry cleanup is best effort; publication and discovery still proceed. @@ -304,28 +340,30 @@ export async function verifyHumanAnswerBridge(body: import("../missions/human-an return false } -async function registrations(pruneStale = true, signal?: AbortSignal): Promise { +async function registrations({ pruneStale = true, strict = false } = {}, signal?: AbortSignal): Promise { const found: DiscoveredBridgeRegistration[] = [] - const directories = await discoverAutomationBridgeDirectories(signal) + const directories = signal ? await discoverAutomationBridgeDirectories(signal, { strict }) : await automationBridgeDirectories({ strict }) for (const [directoryIndex, directory] of directories.entries()) { signal?.throwIfAborted() - let entries: Array<{ name: string; startedAt: number }> = [] + let entries: RegistrationFile[] = [] const entryLimit = directoryIndex === 0 ? MAX_LOCAL_REGISTRY_FILES : MAX_REGISTRATIONS try { const stream = await opendir(directory) for await (const entry of stream) { signal?.throwIfAborted() if (!entry.isFile()) continue - const match = REGISTRATION_NAME.exec(entry.name) - if (!match) continue - entries.push({ name: entry.name, startedAt: Number(match[1]) }) + const file = registrationFile(entry.name, directoryIndex === 0) + if (!file) continue + entries.push(file) + if (strict && entries.length > entryLimit) throw new Error("Mission backend discovery exceeded its bound") if (entries.length > entryLimit * 2) { entries.sort((left, right) => right.startedAt - left.startedAt) entries.length = entryLimit } } - } catch { + } catch (error) { signal?.throwIfAborted() + if (strict && (error as NodeJS.ErrnoException).code !== "ENOENT") throw error continue } entries.sort((left, right) => right.startedAt - left.startedAt) @@ -333,8 +371,18 @@ async function registrations(pruneStale = true, signal?: AbortSignal): Promise undefined) + continue + } + const registration = await readRegistration(target, { throwReadErrors: strict }) as DiscoveredBridgeRegistration | null | undefined + if (registration === null) continue + if (!registration) { + // A malformed foreign advertisement supplies no usable bridge contract. + // Its PID belongs to Windows; preserve the file for its own publisher. + if (strict && directoryIndex === 0) throw new Error("Mission backend registration is unreadable") + continue + } if (directoryIndex === 0 && !isProcessAlive(registration.pid)) { if (pruneStale) await rm(target, { force: true }).catch(() => undefined) continue @@ -343,6 +391,7 @@ async function registrations(pruneStale = true, signal?: AbortSignal): Promise MAX_REGISTRATIONS) throw new Error("Mission backend discovery exceeded its bound") return found.sort((left, right) => right.startedAt - left.startedAt).slice(0, MAX_REGISTRATIONS) } @@ -350,7 +399,7 @@ async function registrations(pruneStale = true, signal?: AbortSignal): Promise { if (!/^[a-f0-9]{64}$/.test(proof)) return false - for (const registration of await registrations(false)) { + for (const registration of await registrations({ pruneStale: false })) { const digest = Buffer.from(signNativeRecurrenceControl(body, registration.token), "hex") if (!timingSafeEqual(digest, Buffer.from(proof, "hex"))) continue try { @@ -410,7 +459,8 @@ function callWindowsBridge( signal?.throwIfAborted() return new Promise((resolve, reject) => { const child = spawn("curl.exe", [ - "--silent", "--show-error", "--max-time", String(timeoutMs / 1_000), + "--verbose", "--silent", "--show-error", "--max-time", String(timeoutMs / 1_000), + "--noproxy", "*", "--request", "POST", "--header", "content-type: application/json", "--header", `x-codenomad-automation-token: ${registration.token}`, @@ -456,7 +506,11 @@ function callWindowsBridge( const separator = output.lastIndexOf("\n") const status = separator >= 0 ? Number(output.slice(separator + 1)) : NaN if (code !== 0 || !Number.isInteger(status)) { - reject(new Error(Buffer.concat(stderr).toString("utf8").trim() || "Windows native automation bridge request failed")) + // Curl's exit 7 also covers denied sockets. Its connect diagnostic proves + // refusal; keep verbose headers/private tokens out of the returned error. + const refused = code === 7 && /\bfailed: Connection refused\b/i.test(Buffer.concat(stderr).toString("utf8")) + const error = new Error("Windows native automation bridge request failed") + reject(refused ? Object.assign(error, { code: "ECONNREFUSED" }) : error) return } try { @@ -552,15 +606,25 @@ async function probeBrowserBridges( sessionID: string, mode: "browser-claim" | "browser-probe", timeoutMs = PROBE_TIMEOUT_MS, - purpose?: "mission", + purpose?: "mission" | "mission-preferences" | "mission-prepare", ): Promise { + const strict = purpose === "mission-preferences" || purpose === "mission-prepare" const found: DiscoveredBridgeRegistration[] = [] for (let index = 0; index < active.length && found.length < 2; index += PROBE_CONCURRENCY) { const batch = await Promise.all(active.slice(index, index + PROBE_CONCURRENCY).map(async (registration) => { try { const response = await callBridge(registration, { mode, sessionID, ...(purpose ? { purpose } : {}) }, timeoutMs) - return response.status === 200 ? registration : undefined - } catch { + const result = response.body.result as { available?: unknown; missionCreationDefaults?: unknown } | undefined + if (response.status === 200 && (!strict || result?.available === true)) { + if (purpose === "mission-prepare" && result?.missionCreationDefaults !== true) throw missionRecoveryControlError("mission-preferences-update-required") + return registration + } + if (strict && response.status === 404 && response.body.code === undefined) throw missionRecoveryControlError("mission-preferences-update-required") + if (strict && !(response.status === 404 && response.body.code === "mission-not-owner")) throw new Error("Mission backend ownership is unavailable") + return undefined + } catch (error) { + if (isConnectionRefused(error)) return undefined + if (strict) throw error return undefined } })) @@ -571,20 +635,54 @@ async function probeBrowserBridges( return found.slice(0, 2) } -export async function sendMissionInput(sessionID: string, - kind: "prompt" | "synthetic" | "cleanup" | "lifecycle" | "create-root" | "prepare" | "task-sessions" | "interrupt", input: unknown): Promise { - // `purpose` lets a backend without native browsers claim the session for dispatch only. - const targets = await probeBrowserBridges(await registrations(), sessionID, "browser-claim", MISSION_PROBE_TIMEOUT_MS, "mission") - if (targets.length !== 1) throw new Error("Mission dispatch requires exactly one owning CodeNomad backend") - const response = await callBridge(targets[0], { mode: "mission-input", sessionID, command: { kind, input } }, REQUEST_TIMEOUT_MS) +async function callMissionInput(target: DiscoveredBridgeRegistration, sessionID: string, kind: string, input: unknown): Promise { + const response = await callBridge(target, { mode: "mission-input", sessionID, command: { kind, input } }, REQUEST_TIMEOUT_MS) if (response.status !== 200) { - const recovery = missionRecoveryError(response.body.code) - if (recovery && recovery.status === response.status) throw new MissionControlError(recovery.message, recovery.code) + const recovery = missionRecoveryError(response.body.code, response.body.error) + if (recovery && recovery.status === response.status) throw missionRecoveryControlError(recovery.code, response.body.error) + if (kind === "profile-defaults" && response.body.code === "mission-not-owner") throw missionRecoveryControlError("mission-preferences-unavailable") + if (kind === "profile-defaults" && [400, 404, 405, 501].includes(response.status)) { + throw missionRecoveryControlError("mission-preferences-update-required") + } throw new Error("CodeNomad could not admit the mission input; inspect ownership/environment and retry the same task") } return response.body.result } +export async function resolveMissionProfileDefaults(sessionID: string, input: unknown): Promise { + try { + const request = parseMissionCreationDefaultsInput(input) + const targets = await probeBrowserBridges(await registrations({ strict: true }), sessionID, "browser-claim", MISSION_PROBE_TIMEOUT_MS, "mission-preferences") + if (targets.length === 0) return { + ...resolveMissionCreationDefaults({ ...request, preferences: undefined }), preferences: MISSION_PREFERENCES_UNAVAILABLE, + } + if (targets.length !== 1) throw new Error("Mission preferences require exactly one owning CodeNomad backend") + return await callMissionInput(targets[0], sessionID, "profile-defaults", input) + } catch (error) { + if (error instanceof MissionControlError && missionRecoveryError(error.code)) throw error + throw missionRecoveryControlError("mission-preferences-unavailable") + } +} + +export async function sendMissionInput(sessionID: string, + kind: "prompt" | "synthetic" | "cleanup" | "lifecycle" | "create-root" | "prepare" | "task-sessions" | "interrupt", input: unknown): Promise { + let targets: DiscoveredBridgeRegistration[] + const requiresDefaults = kind === "prepare" && Boolean(input && typeof input === "object" && "creationDefaults" in input && input.creationDefaults !== undefined) + try { + // A backend without native browsers can still claim the session for dispatch. + targets = await probeBrowserBridges(await registrations({ strict: requiresDefaults }), sessionID, "browser-claim", MISSION_PROBE_TIMEOUT_MS, + requiresDefaults ? "mission-prepare" : "mission") + if (targets.length !== 1) throw new Error("Mission dispatch requires exactly one owning CodeNomad backend") + } catch (error) { + if (error instanceof MissionControlError && error.code === "mission-preferences-update-required") throw error + if (kind === "prepare") { + throw missionRecoveryControlError("prepare-refused") + } + throw error + } + return callMissionInput(targets[0], sessionID, kind, input) +} + /** Discover independently of desktop capabilities; never pick between owning backends. */ export async function sendMemoryInput(sessionID: string, command: MemoryOperation, signal?: AbortSignal): Promise { return sendMemoryBridge(sessionID, "memory-input", command, signal) as Promise @@ -596,7 +694,7 @@ export async function requestMemoryContext(sessionID: string, signal?: AbortSign async function sendMemoryBridge(sessionID: string, mode: "memory-input" | "memory-context", command?: MemoryOperation, signal?: AbortSignal): Promise { signal?.throwIfAborted() - const active = await registrations(true, signal) + const active = await registrations({}, signal) signal?.throwIfAborted() const targets: DiscoveredBridgeRegistration[] = [] let unowned = 0 diff --git a/packages/server/src/opencode/connection-errors.test.ts b/packages/server/src/opencode/connection-errors.test.ts new file mode 100644 index 0000000000..4a419c1d32 --- /dev/null +++ b/packages/server/src/opencode/connection-errors.test.ts @@ -0,0 +1,15 @@ +import assert from "node:assert/strict" +import test from "node:test" +import { isConnectionRefused } from "./connection-errors" + +test("only explicit refused connections prove endpoint absence", () => { + const refused = { code: "ECONNREFUSED" } + assert.equal(isConnectionRefused(refused), true) + assert.equal(isConnectionRefused({ code: "ConnectionRefused" }), true) + assert.equal(isConnectionRefused({ cause: refused }), true) + assert.equal(isConnectionRefused(new AggregateError([refused, { cause: refused }], "unavailable")), true) + for (const error of [null, "ECONNREFUSED", new Error("ECONNREFUSED"), { code: "ETIMEDOUT" }, + new AggregateError([refused, { code: "ETIMEDOUT" }], "incomplete"), { code: "EACCES" }]) { + assert.equal(isConnectionRefused(error), false) + } +}) diff --git a/packages/server/src/opencode/connection-errors.ts b/packages/server/src/opencode/connection-errors.ts new file mode 100644 index 0000000000..079351d4ea --- /dev/null +++ b/packages/server/src/opencode/connection-errors.ts @@ -0,0 +1,8 @@ +/** Only a refused connection proves that the selected endpoint has no listener. */ +export function isConnectionRefused(error: unknown): boolean { + if (!error || typeof error !== "object") return false + const value = error as { code?: unknown; cause?: unknown; errors?: unknown } + if (value.code === "ECONNREFUSED" || value.code === "ConnectionRefused") return true + if (Array.isArray(value.errors) && value.errors.length) return value.errors.every(isConnectionRefused) + return value.cause !== undefined && value.cause !== error && isConnectionRefused(value.cause) +} diff --git a/packages/server/src/opencode/integrations/attachments.ts b/packages/server/src/opencode/integrations/attachments.ts index 6328e505ca..8bc24be0c7 100644 --- a/packages/server/src/opencode/integrations/attachments.ts +++ b/packages/server/src/opencode/integrations/attachments.ts @@ -156,7 +156,7 @@ export class IntegrationAttachments { context.signal.throwIfAborted() context.connection.assertCurrent() if (context.location.workspaceID !== undefined || !await this.deps.workspaceManager.ownsLocation( - context.workspaceId, context.location, context.connection.client, context.signal, + context.workspaceId, context.location, context.connection.client, { signal: context.signal }, )) throw new IntegrationAttachmentError("forbidden") context.signal.throwIfAborted() context.connection.assertCurrent() diff --git a/packages/server/src/opencode/integrations/install.ts b/packages/server/src/opencode/integrations/install.ts index 912199379c..e64c20900f 100644 --- a/packages/server/src/opencode/integrations/install.ts +++ b/packages/server/src/opencode/integrations/install.ts @@ -62,7 +62,7 @@ export class IntegrationInstaller { private async authorize(workspaceId: string, location: PluginControlLocation, connection: ServiceConnection, signal?: AbortSignal) { signal?.throwIfAborted() connection.assertCurrent() - if (!await this.deps.workspaceManager.ownsLocation(workspaceId, location, connection.client, signal)) { + if (!await this.deps.workspaceManager.ownsLocation(workspaceId, location, connection.client, { signal })) { throw new IntegrationInstallError("forbidden") } signal?.throwIfAborted() diff --git a/packages/server/src/opencode/missions-plugin.test.ts b/packages/server/src/opencode/missions-plugin.test.ts index d43630bb96..282a7b8b5c 100644 --- a/packages/server/src/opencode/missions-plugin.test.ts +++ b/packages/server/src/opencode/missions-plugin.test.ts @@ -5,7 +5,8 @@ import { parseDelegateInput, parseInspectInput, parseReportInput, parseReviseInp import { buildAssignmentPrompt } from "../missions/recipes" import type { MissionJsonValue, MissionMap } from "../missions/model" import type { MissionsPluginContext } from "./missions-plugin" -import type { NativeMissionSession } from "../missions/control-types" +import type { MissionInputTransport, NativeMissionSession } from "../missions/control-types" +import { resolveMissionCreationDefaults } from "../missions/profile-defaults" import { NativeMissionDocumentStore, type MissionDocumentStorage } from "../missions/mission-document-store" import { canonicalAuthority } from "../missions/authority-protocol" @@ -14,7 +15,7 @@ test("validates the compact mission tool contracts", () => { assert.equal(parseInspectInput({ start: { objective: "Bounded comparison", template } }).start!.template, template) } assert.deepEqual(parseInspectInput({ start: { objective: "Fix it", template: "debug" } }), { - start: { objective: "Fix it", template: "debug", notes: undefined, taskMode: "native" }, + start: { objective: "Fix it", template: "debug", notes: undefined }, missionID: undefined, }) assert.deepEqual(parseDelegateInput({ taskKey: "review-spec", title: "Review", brief: "Check spec", role: "review-spec" }), { @@ -110,9 +111,10 @@ test("registers seven tools, typed snapshot RPC, and role context", async () => const inspect = tools.find((tool) => tool.name === "inspect")! assert.deepEqual((inspect as any).input.properties.start.properties.template.enum, ["custom", "debug", "wayfinder", "delivery", "compare"]) assert.match((tools.find(tool => tool.name === "report") as any).input.properties.artifact.description, /Compare comparator.*version 1 comparison/) - await inspect.execute({ start: { objective: "Coordinate", template: "custom" } }, { + const started = JSON.parse((await inspect.execute({ start: { objective: "Coordinate", template: "custom" } }, { sessionID: "ses_coordinator", messageID: "msg_1", id: "call_1", progress: async () => {}, - }) + })).content) + assert.equal("selection" in started, false, "historical creation without a resolver invents no origins") const snapshot = await snapshotHandler!() as { missions: Array> } assert.equal(snapshot.missions.length, 1) assert.equal("notes" in snapshot.missions[0], false) @@ -242,6 +244,65 @@ test("registers seven tools, typed snapshot RPC, and role context", async () => }), /no longer available/) }) +test("inspect start and prepare return frozen profiles, task mode and origins without rereading defaults", async () => { + const values = new Map(), sessions = new Map([["ses_coordinator", { + id: "ses_coordinator", projectID: "project-1", location: { directory: "/repo" }, + }]]) + const tools = new Map }>() + let handlers: any, reads = 0, preparations = 0 + let preferences: unknown = [{ template: "all", profiles: { coordinator: { agent: "lead" }, roles: { specialist: { agent: "worker" } } }, taskMode: "independent" }] + const transport: MissionInputTransport = { + prompt: async () => assert.fail("Creation never prompts"), synthetic: async () => assert.fail("Creation never resumes"), + resolveCreationDefaults: async (_sessionID, input) => { reads++; return resolveMissionCreationDefaults({ ...input, preferences }) }, + prepare: async (sessionID, input) => { + preparations++ + return handlers.create({ ...input, prepared: true, preparedBy: { missionID: input.missionID, coordinatorSessionID: sessionID } }) + }, + } + const cleanup = await setupMissionsPlugin({ + location: { directory: "/repo", project: { id: "project-1", canonical: "/repo" } }, + storage: { + get: async (key: string) => values.get(key), + set: async (key: string, value: unknown) => { values.set(key, structuredClone(value)) }, + scan: async ({ prefix }: { prefix: string }) => ({ entries: [...values].filter(([key]) => key.startsWith(prefix)).map(([key, value]) => ({ key, value })) }), + }, + session: { + get: async ({ sessionID }: { sessionID: string }) => { const session = sessions.get(sessionID); if (!session) throw new Error("Absent"); return session }, + create: async (input: any) => { const session = { ...input, projectID: "project-1" }; sessions.set(session.id, session); return session }, + prompt: async () => assert.fail("Creation never prompts"), synthetic: async () => assert.fail("Creation never resumes"), + hook: async () => ({ dispose: async () => {} }), + }, + agent: { list: async () => ({ data: ["lead", "worker"].map(id => ({ id, mode: "all" })) }) }, + model: { list: async () => ({ data: [] }) }, + tool: { transform: async (callback: any) => { callback({ namespace() {}, add(tool: any) { tools.set(tool.name, tool) } }); return { dispose: async () => {} } } }, + rpc: { register: async (_definition: unknown, value: unknown) => { handlers = value; return { dispose: async () => {}, events: { emit: async () => {} } } } }, + } as never, transport) + const call = async (name: string, input: unknown, id = name) => JSON.parse((await tools.get(name)!.execute(input, { + sessionID: "ses_coordinator", messageID: `msg_${id}`, id: `call_${id}`, progress: async () => {}, + })).content) + try { + const start = { objective: "Coordinate", template: "custom" as const, profiles: { coordinator: {} } } + const started = await call("inspect", { start }, "start") + assert.deepEqual(started.selection, resolveMissionCreationDefaults({ ...start, preferences })) + assert.equal("creationDefaults" in started.mission, false, "tool replies expose the selection without its private replay request") + assert.deepEqual(started.selection.origins, { coordinator: "explicit", roles: { specialist: "preference" }, taskMode: "preference" }) + const request = { requestID: "pilot", objective: "Pilot", template: "custom" as const } + const prepared = await call("prepare", request) + assert.deepEqual(prepared.selection, resolveMissionCreationDefaults({ ...request, preferences })) + assert.deepEqual(Object.keys(prepared).sort(), ["disposition", "missionID", "status", "runState", "revision", "selection"].sort()) + assert.deepEqual([prepared.disposition, prepared.runState, prepared.selection.profiles.coordinator], ["prepared", "prepared", { agent: "lead" }]) + const bytes = structuredClone([...values]) + preferences = { invalid: true } + assert.deepEqual(await call("inspect", { start }, "start"), started) + assert.deepEqual(await call("prepare", request), prepared) + assert.equal(reads, 2) + assert.equal(preparations, 1) + assert.deepEqual([...values], bytes) + assert.deepEqual((await call("inspect", { missionID: prepared.missionID })).selection, prepared.selection) + assert.equal(reads, 2, "ordinary reads retain stored provenance") + } finally { await cleanup() } +}) + for (const workspaceID of [undefined, "workspace-1"]) { test(`RPC create persists the fallback location with workspaceID ${workspaceID ?? "absent"}`, async () => { const values = new Map(), sessions = new Map() diff --git a/packages/server/src/opencode/missions-plugin.ts b/packages/server/src/opencode/missions-plugin.ts index 8ee14eafbd..e2bba90ade 100644 --- a/packages/server/src/opencode/missions-plugin.ts +++ b/packages/server/src/opencode/missions-plugin.ts @@ -18,6 +18,7 @@ import type { } from "../missions/control-types" import { MISSION_SCHEMA_VERSION, type MissionEvent, type MissionJsonValue, type MissionMap, type MissionTemplateId } from "../missions/model" import { parseMissionEvent } from "../missions/journal" +import { parseMissionCreationDefaults, missionCreationSelection } from "../missions/creation-defaults" import { missionPausedInstruction } from "../missions/lifecycle-model" import { CODENOMAD_MISSIONS_RPC } from "../missions/rpc" import { executionSchema, parseExecution } from "../missions/execution" @@ -380,7 +381,7 @@ export async function setupMissionsBusiness(context: MissionsPluginContext, }) add({ name: "inspect", - description: "Inspect the caller's durable mission map and optional native catalog, or prepare a paused custom, debugging, Wayfinder, product delivery, or two-model comparison mission. The user presses Play in CodeNomad before Mission work begins; creation never sends a coordinator prompt. Compare requires different model-a/model-b profiles and always a blind judge. Pass taskKey to read only that task with its revision, frontier, contract, exact current assignmentPrompt, observed native conversations and any qualifying human answers instead of the full map. A map too large for one result lists its tasks in pages: follow taskPage.nextTaskOffset with taskOffset. Any value too large for one result is replaced by { omittedCharacters, read }: pass read as the whole input to read that value in slices, following each slice's next. Pass list: true to find your missions and prepared hand-offs; missionID also reads a hand-off you prepared.", + description: "Inspect the caller's durable mission map and optional native catalog, or prepare a paused custom, debugging, Wayfinder, product delivery, or two-model comparison mission. Inspection includes saved selection (profiles, taskMode and explicit/preference/opencode-default origins) when creation metadata exists. These are requested choices; check the catalog for availability. selection.preferences: 'unavailable' warns that omitted choices used OpenCode defaults. Recover preference/ownership errors or supply the coordinator, every template role and taskMode explicitly; update CodeNomad when requested. The starting coordinator must match the resolved profile. Creation never sends a coordinator prompt. The user presses Play in CodeNomad before Mission work begins. Compare requires different model-a/model-b profiles and always a blind judge. Pass taskKey to read only that task with its revision, frontier, contract, exact current assignmentPrompt, observed native conversations and any qualifying human answers. Follow taskPage.nextTaskOffset with taskOffset for more tasks. For { omittedCharacters, read }, pass read as the whole input and follow each slice's next. Pass list: true to find your missions and prepared hand-offs; missionID also reads a hand-off you prepared.", input: inspectSchema, options: { namespace: "mission", codemode: false }, execute: async (input, tool) => { @@ -506,7 +507,7 @@ export async function setupMissionsBusiness(context: MissionsPluginContext, }) add({ name: "prepare", - description: "Coordinator only: prepare a separate paused one-time mission, such as a pilot hand-off, from an objective, optional title and notes, a template, profiles and task mode: what the Mission editor creates. It never starts; the user presses Play. Reuse the same requestID to retry. Find it later with mission.inspect({ list: true }) and read it with mission.inspect({ missionID }); you cannot control it.", + description: "Coordinator only: prepare a separate paused one-time mission, such as a pilot hand-off, from an objective, optional title and notes, a template, profiles and task mode. Keep the owning CodeNomad backend available. Read selection for saved requested profiles, taskMode and explicit/preference/opencode-default origins; inspection includes that saved selection when creation metadata exists. The user starts it with Play; you cannot control it. Reuse the same requestID and original inputs to retry; saved choices stay frozen if preferences change. Outside an active mission use the Missions editor. Find it with mission.inspect({ list: true }) and read it with mission.inspect({ missionID }).", input: prepareSchema, options: { namespace: "mission", codemode: false }, execute: async (input, tool) => { @@ -516,7 +517,8 @@ export async function setupMissionsBusiness(context: MissionsPluginContext, selected.current() const { mission } = await executeMissionBusiness(selected, control => control.prepare(tool.sessionID, parsePrepareInput(input))) return textResult({ disposition: "prepared", missionID: mission.id, ...(mission.title === undefined ? {} : { title: mission.title }), - status: mission.status, ...(mission.runState === undefined ? {} : { runState: mission.runState }), revision: mission.revision }) + status: mission.status, ...(mission.runState === undefined ? {} : { runState: mission.runState }), revision: mission.revision, + ...(mission.creationDefaults ? { selection: missionCreationSelection(mission) } : {}) }) }, }) }) @@ -621,6 +623,8 @@ const interruptSchema = { additionalProperties: false, } +const MISSION_PROFILES_DESCRIPTION = "Omit coordinator/role slots to inherit Missions preferences: playbook exception, then global (specialist for task roles). Each supplied slot wins whole: {} selects OpenCode defaults; agent-only keeps its native model default. Compare fills a missing judge model from the known coordinator model. profiles: {} inherits all slots. To bypass preferences, supply the coordinator, every exact template role and taskMode. Check saved selection and origins in the response or later inspection." + const prepareSchema = { type: "object", properties: { @@ -629,8 +633,8 @@ const prepareSchema = { title: { type: "string", minLength: 1, maxLength: MISSION_TITLE_MAX }, notes: { type: "string", maxLength: 20_000 }, template: { type: "string", enum: ["custom", "debug", "wayfinder", "delivery", "compare"] }, - profiles: missionProfilesSchema, - taskMode: missionTaskModeSchema, + profiles: { ...missionProfilesSchema, description: MISSION_PROFILES_DESCRIPTION }, + taskMode: { ...missionTaskModeSchema, description: "Explicit policy wins; omission inherits Missions preferences (type exception, then global), then native." }, }, required: ["requestID", "objective", "template"], additionalProperties: false, @@ -651,7 +655,7 @@ export function parsePrepareInput(input: unknown): MissionPrepareRequest { ...(value.title === undefined ? {} : { title: missionTitle(value.title) }), ...(value.notes === undefined ? {} : { notes: optionalBodyText(value.notes, "notes", 20_000) }), template, - taskMode: parseMissionTaskMode(value.taskMode), + ...(value.taskMode === undefined ? {} : { taskMode: parseMissionTaskMode(value.taskMode) }), ...(value.profiles === undefined ? {} : { profiles: parseMissionProfiles(value.profiles) }), } } @@ -687,8 +691,8 @@ const inspectSchema = { objective: { type: "string", minLength: 1, maxLength: 20_000 }, template: { type: "string", enum: ["custom", "debug", "wayfinder", "delivery", "compare"] }, notes: { type: "string", maxLength: 20_000 }, - profiles: missionProfilesSchema, - taskMode: { ...missionTaskModeSchema, description: "Declared task policy for this new mission only; omitted defaults to native. Independent requires explicit reasoned independent declarations, not a native-helper ban or new-root authorization." }, + profiles: { ...missionProfilesSchema, description: MISSION_PROFILES_DESCRIPTION }, + taskMode: { ...missionTaskModeSchema, description: "Declared task policy for this new mission only; omission inherits Missions preferences (type exception, then global), then native. Independent requires explicit reasoned independent declarations, not a native-helper ban or new-root authorization." }, }, required: ["objective", "template"], additionalProperties: false, @@ -771,7 +775,7 @@ export function parseInspectInput(input: unknown): MissionInspectInput & { start: { objective: requiredText(start.objective, "start.objective", 20_000), template, - taskMode: parseMissionTaskMode(start.taskMode), + ...(start.taskMode === undefined ? {} : { taskMode: parseMissionTaskMode(start.taskMode) }), notes: optionalText(start.notes, "start.notes", 20_000), ...(start.profiles === undefined ? {} : { profiles: parseMissionProfiles(start.profiles) }), }, @@ -860,6 +864,7 @@ function parseCreateMissionInput(input: unknown): MissionCreateInput { notes: optionalBodyText(value.notes, "notes", 20_000), template, taskMode: parseMissionTaskMode(value.taskMode), + ...(value.creationDefaults === undefined ? {} : { creationDefaults: parseMissionCreationDefaults(template, value.creationDefaults) }), ...(value.profiles === undefined ? {} : { profiles: parseMissionProfiles(value.profiles) }), coordinatorSessionID: optionalText(value.coordinatorSessionID, "coordinatorSessionID", 240), ...(value.expectedCoordinatorLocation === undefined ? {} : { expectedCoordinatorLocation: readLocationRef(value.expectedCoordinatorLocation) }), diff --git a/packages/server/src/opencode/missions/desktop-plugin.ts b/packages/server/src/opencode/missions/desktop-plugin.ts index 562aa3d6e7..08ee829a25 100644 --- a/packages/server/src/opencode/missions/desktop-plugin.ts +++ b/packages/server/src/opencode/missions/desktop-plugin.ts @@ -3,7 +3,7 @@ import type { NativeMissionSession } from "../../missions/control-types" import { followPresence } from "../desktop-plugin-presence" import { setupMissionsBusiness, setupMissionsPlugin, type MissionBusinessRoute } from "../missions-plugin" import { selectNativePassageBusiness, prepareNativePassageSession, retireNativePassageBusiness } from "./native-passage-business" -import { sendMissionInput } from "../automation-plugin" +import { resolveMissionProfileDefaults, sendMissionInput } from "../automation-plugin" import { isCleanupReason } from "../../missions/cleanup-projection" import { MissionJournal } from "../../missions/journal" import { MissionJournalIndex } from "../../missions/journal-index" @@ -42,6 +42,7 @@ export function desktopPlugin(presenceDirectory: string | readonly string[], hum synthetic: (coordinatorID, input) => sendMissionInput(coordinatorID, "synthetic", input), lifecycle: (coordinatorID, input) => sendMissionInput(coordinatorID, "lifecycle", input), prepare: (coordinatorID, input) => sendMissionInput(coordinatorID, "prepare", input), + resolveCreationDefaults: resolveMissionProfileDefaults, observeTask: (coordinatorID, input) => sendMissionInput(coordinatorID, "task-sessions", input), interruptTask: (coordinatorID, input) => sendMissionInput(coordinatorID, "interrupt", input), cleanup: async (coordinatorID, input) => { diff --git a/packages/server/src/permissions/receipts.test.ts b/packages/server/src/permissions/receipts.test.ts index da0a5fc78a..a12d43c27e 100644 --- a/packages/server/src/permissions/receipts.test.ts +++ b/packages/server/src/permissions/receipts.test.ts @@ -162,8 +162,12 @@ test("initial connection and reconnect recover every loaded owned Location, incl if (++captures % directories.length === 0) captured() } }) Object.assign(f.manager, { - ownsLocation: async (_id: string, location: { directory: string }, _client: unknown, _signal: unknown, purpose?: string) => { - if (purpose) assert.equal(purpose, "event") + ownsLocation: async (_id: string, location: { directory: string }, _client: unknown, { purpose, signal }: { purpose?: string; signal?: AbortSignal } = {}) => { + if (purpose) { + assert.equal(purpose, "event") + assert.ok(signal instanceof AbortSignal) + assert.equal(signal.aborted, false) + } return directories.includes(location.directory) }, }) diff --git a/packages/server/src/permissions/receipts.ts b/packages/server/src/permissions/receipts.ts index 22b86196a9..8bcb24a400 100644 --- a/packages/server/src/permissions/receipts.ts +++ b/packages/server/src/permissions/receipts.ts @@ -139,7 +139,7 @@ export class PermissionReceipts { for (const value of locations) { if (!current()) return const location = readLocationRef(value) - if (!await this.recoveryRead(signal, () => this.manager.ownsLocation(event.instanceId, location, connection.client, signal, "event"))) continue + if (!await this.recoveryRead(signal, () => this.manager.ownsLocation(event.instanceId, location, connection.client, { signal, purpose: "event" }))) continue if (!current()) return const pending = await connection.client.permission.request.list({ location: { directory: location.directory } }, { ...locationRequestOptions(location), ...options(), @@ -152,7 +152,7 @@ export class PermissionReceipts { try { session = await connection.client.session.get({ sessionID: request.sessionId }, options()) } catch (error) { if (isSessionNotFoundError(error)) continue; throw error } if (!current()) return - if (!await this.recoveryRead(signal, () => this.manager.ownsLocation(event.instanceId, session.location, connection.client, signal, "event"))) continue + if (!await this.recoveryRead(signal, () => this.manager.ownsLocation(event.instanceId, session.location, connection.client, { signal, purpose: "event" }))) continue if (!current()) return await this.store.capture(scope, request) } diff --git a/packages/server/src/server/__tests__/instance-proxy-disconnect-diagnostic.test.ts b/packages/server/src/server/__tests__/instance-proxy-disconnect-diagnostic.test.ts index e6962c2f96..255004a58f 100644 --- a/packages/server/src/server/__tests__/instance-proxy-disconnect-diagnostic.test.ts +++ b/packages/server/src/server/__tests__/instance-proxy-disconnect-diagnostic.test.ts @@ -101,7 +101,7 @@ async function harness(phase: Phase, nativePreflight = false) { return {} }, ownsDirectory: async () => true, - ownsLocation: async (_id: string, _location: unknown, _client?: unknown, requestSignal?: AbortSignal) => { + ownsLocation: async (_id: string, _location: unknown, _client?: unknown, { signal: requestSignal }: { signal?: AbortSignal } = {}) => { await hold("ownership", requestSignal) return true }, diff --git a/packages/server/src/server/http-server.ts b/packages/server/src/server/http-server.ts index a4450736cb..0ebfc013f6 100644 --- a/packages/server/src/server/http-server.ts +++ b/packages/server/src/server/http-server.ts @@ -568,7 +568,7 @@ export interface InstanceProxyWorkspaceManager { getSharedServiceClient(): Promise getSessionEnvironment(id: string, signal?: AbortSignal): Promise> desktopPluginsReady?(): Promise - ownsLocation(id: string, location: LocationRef, client?: OpenCodeClient, signal?: AbortSignal): ReturnType + ownsLocation: WorkspaceManager["ownsLocation"] ownsDirectory(id: string, directory: string): Promise ownsPath(id: string, candidate: string): Promise } @@ -965,7 +965,7 @@ async function proxyWorkspaceAdmission(args: InstanceProxyRequestArgs, admission const entries = await Promise.all(Object.entries(active).map(async ([sessionId, status]) => { try { const session = await wait(client.session.get({ sessionID: sessionId }, { signal })) - return await wait(workspaceManager.ownsLocation(workspaceId, session.location, client, signal)) ? [sessionId, status] as const : null + return await wait(workspaceManager.ownsLocation(workspaceId, session.location, client, { signal })) ? [sessionId, status] as const : null } catch { return null } @@ -1196,7 +1196,7 @@ async function proxyWorkspaceAdmission(args: InstanceProxyRequestArgs, admission } if (!isSessionNotFoundError(error)) throw error } - if (session && !(await wait(workspaceManager.ownsLocation(workspaceId, session.location, await clientForRequest(), signal)))) { + if (session && !(await wait(workspaceManager.ownsLocation(workspaceId, session.location, await clientForRequest(), { signal })))) { reply.code(403).send({ error: "Session does not belong to workspace" }) return } @@ -1255,7 +1255,7 @@ async function proxyWorkspaceAdmission(args: InstanceProxyRequestArgs, admission const fresh = await wait(client.session.get({ sessionID: session.id }, { signal })) current() if (fresh.id !== session.id || !sameLocation(readLocationRef(fresh.location), readLocationRef(session.location)) - || !await wait(workspaceManager.ownsLocation(workspaceId, fresh.location, client, signal))) { + || !await wait(workspaceManager.ownsLocation(workspaceId, fresh.location, client, { signal }))) { throw new MissionScheduleInputError(403) } assertOrdinaryMissionScheduleBody({ metadata: fresh.metadata }) @@ -1349,7 +1349,7 @@ async function proxyWorkspaceAdmission(args: InstanceProxyRequestArgs, admission const current = await connection.client.session.get({ sessionID: sessionId! }, { signal }) return workspaceManager.get(workspaceId) === workspace && directory === authorizedSessionDirectory && current.location.directory === authorizedSessionDirectory - && await workspaceManager.ownsLocation(workspaceId, current.location, connection.client, signal) + && await workspaceManager.ownsLocation(workspaceId, current.location, connection.client, { signal }) })) } catch (error) { releaseMutation?.() @@ -1514,7 +1514,7 @@ async function allDirectoriesOwned(manager: InstanceProxyWorkspaceManager, works async function allLocationsOwned(manager: InstanceProxyWorkspaceManager, workspaceId: string, locations: LocationRef[], client?: OpenCodeClient, signal?: AbortSignal) { const unique = new Map(locations.map((location) => [JSON.stringify([location.directory, location.workspaceID]), location])) - return (await Promise.all([...unique.values()].map((location) => manager.ownsLocation(workspaceId, location, client, signal)))).every(Boolean) + return (await Promise.all([...unique.values()].map((location) => manager.ownsLocation(workspaceId, location, client, { signal })))).every(Boolean) } async function allPathsOwned(manager: InstanceProxyWorkspaceManager, workspaceId: string, paths: string[]) { @@ -1598,7 +1598,7 @@ async function authorizeSessionList( if (ownership !== "allowed") return ownership if (!(await readGitStatus()).available) { signal?.throwIfAborted() - if (directory && !await manager.ownsLocation(workspaceId, { directory }, client, signal)) return "foreign" + if (directory && !await manager.ownsLocation(workspaceId, { directory }, client, { signal })) return "foreign" // Narrow the initial query, preserving native directory-scoped pagination. // Unlike a project cursor this request has no already-established scope. const root = manager.getServiceDirectory?.(workspaceId) ?? manager.get(workspaceId)?.path @@ -1623,7 +1623,7 @@ async function ownsSessionListScope( ): Promise<"allowed" | "foreign"> { signal?.throwIfAborted() if (scope.directory) { - const owned = await manager.ownsLocation(workspaceId, { directory: scope.directory }, client, signal) + const owned = await manager.ownsLocation(workspaceId, { directory: scope.directory }, client, { signal }) return owned ? "allowed" : "foreign" } if (!scope.project) return "foreign" @@ -1637,7 +1637,7 @@ async function ownsSessionListScope( : /^[A-Za-z]:[\\/]|^\\\\/.test(project.canonical) ? path.win32.resolve(project.canonical, scope.subpath) : path.posix.resolve(project.canonical, scope.subpath) - const owned = await manager.ownsLocation(workspaceId, { directory }, client, signal) + const owned = await manager.ownsLocation(workspaceId, { directory }, client, { signal }) return owned ? "allowed" : "foreign" } diff --git a/packages/server/src/server/routes/automation-plugin.test.ts b/packages/server/src/server/routes/automation-plugin.test.ts index d937ae7454..01df60291e 100644 --- a/packages/server/src/server/routes/automation-plugin.test.ts +++ b/packages/server/src/server/routes/automation-plugin.test.ts @@ -233,6 +233,35 @@ test("WebKit browser claims, probes and native actions succeed independently of } }) +test("Mission preference and preparation claims remain available without browser automation", async t => { + const app = Fastify({ logger: false }) + t.after(() => app.close()) + const strictReads: boolean[] = [] + registerAutomationPluginRoute(app, { + authManager: { isLoopbackRequest: () => true }, bridgeToken: "secret", + nativeParent: { available: true, browserAutomationUnavailable: true }, + workspaceManager: { + getSharedServiceClient: async () => ({ session: { get: async () => ({ location: { directory: "/repo" } }) } }), + list: () => [{ id: "owner" }], + ownsLocation: async (_id: string, _location: unknown, _client: unknown, options: { strict: boolean }) => { + strictReads.push(options.strict) + return true + }, + }, + } as never) + for (const purpose of ["mission-preferences", "mission-prepare"]) { + const response = await app.inject({ method: "POST", url: AUTOMATION_BRIDGE_PATH, + headers: { "x-codenomad-automation-token": "secret" }, payload: { mode: "browser-claim", sessionID: "owned", purpose } }) + assert.equal(response.statusCode, 200, purpose) + assert.deepEqual(response.json(), { result: { available: true, missionCreationDefaults: true } }) + } + const browser = await app.inject({ method: "POST", url: AUTOMATION_BRIDGE_PATH, + headers: { "x-codenomad-automation-token": "secret" }, payload: { mode: "browser-claim", sessionID: "owned" } }) + assert.equal(browser.statusCode, 409) + assert.equal(browser.json().code, "unsupported") + assert.deepEqual(strictReads, [true, true, false]) +}) + test("a backend without a desktop host claims owned sessions for Mission dispatch only", async () => { const app = Fastify({ logger: false }) const nativeCalls: string[] = [] diff --git a/packages/server/src/server/routes/automation-plugin.ts b/packages/server/src/server/routes/automation-plugin.ts index 234f4f5066..615dd7f4da 100644 --- a/packages/server/src/server/routes/automation-plugin.ts +++ b/packages/server/src/server/routes/automation-plugin.ts @@ -1,4 +1,5 @@ import { timingSafeEqual } from "node:crypto" +import { isSessionNotFoundError } from "@opencode/client" import type { FastifyInstance, FastifyRequest } from "fastify" import type { AuthManager } from "../../auth/manager" import type { DeveloperCdp } from "../../developer-cdp" @@ -10,11 +11,12 @@ import type { WorktreeDeletionFence } from "../../workspaces/worktree-session-ev import { admitMissionInput } from "./mission-input" import { createManagedMissionRoot } from "./mission-root-creation" import { prepareCoordinatorMission } from "./mission-prepare" +import { readMissionProfileDefaults } from "./mission-profile-defaults" import { interruptMissionTask, observeMissionTask } from "./mission-task-native" import { requestAdmission } from "../request-admission" import { MissionCreationHoldError } from "./mission-creation-holds" import { DeveloperInspectionTargets } from "../../automation/developer-inspection-targets" -import { missionRecoveryRejection } from "../../missions/recovery-error" +import { missionRecoveryControlError, missionRecoveryRejection } from "../../missions/recovery-error" import { verifyMissionHumanAnswer } from "./mission-human-answer" import { verifyHumanRecurrenceRequest } from "./mission-recurrence-proof" import { BrowserPage } from "../../automation/browser-page" @@ -31,7 +33,7 @@ interface AutomationPluginRouteDeps { workspaceManager: WorkspaceManager developerCdp: DeveloperCdp worktreeDeletionFence?: WorktreeDeletionFence - settings?: Pick + settings?: Pick & Partial> remoteDevices?: Pick memory?: MemoryService } @@ -108,6 +110,13 @@ export function registerAutomationPluginRoute(app: FastifyInstance, deps: Automa // Lifecycle Pause/Stop and a retired task's interrupt walk and interrupt whole native // subagent families; they stay below the plugin's 95 s bridge timeout. const commandKind = body?.command && typeof body.command === "object" && "kind" in body.command ? body.command.kind : undefined + const preferenceProbe = body.mode === "browser-claim" && (body.purpose === "mission-preferences" || body.purpose === "mission-prepare") + || body.mode === "mission-input" && commandKind === "profile-defaults" + const preferenceUnavailable = () => { + const failure = missionRecoveryControlError("mission-preferences-unavailable") + return reply.code(503).send({ error: failure.message, code: failure.code }) + } + const notOwner = (error: string) => reply.code(404).send({ error, ...(preferenceProbe ? { code: "mission-not-owner" } : {}) }) const lifecycle = commandKind === "lifecycle" || commandKind === "interrupt" const signal = body.mode === "mission-input" ? AbortSignal.any([lifetime.signal, AbortSignal.timeout(lifecycle ? 85_000 : 30_000)]) : lifetime.signal @@ -118,20 +127,31 @@ export function registerAutomationPluginRoute(app: FastifyInstance, deps: Automa const client = await lifetime.wait(deps.workspaceManager.getSharedServiceClient()) signal.throwIfAborted() location = (await lifetime.wait(client.session.get({ sessionID: body.sessionID }, { signal }))).location - } catch { - return reply.code(404).send({ error: "Session not found" }) + } catch (error) { + if (preferenceProbe && (signal.aborted || !isSessionNotFoundError(error))) return preferenceUnavailable() + return notOwner("Session not found") } // One validated owner is sufficient. Waiting for every unrelated inventory // can exceed the plugin's discovery deadline despite a ready local owner. - const owned = await lifetime.wait(Promise.any(deps.workspaceManager.list().map(async workspace => { - if (!await deps.workspaceManager.ownsLocation(workspace.id, location, undefined, signal)) throw new Error("Not an owner") - return true - }))).catch(() => false) - if (!owned) return reply.code(404).send({ error: "Session is not owned by this CodeNomad instance" }) + let owned: boolean, ownershipReadFailed = false + try { + const workspaces = deps.workspaceManager.list() + owned = await lifetime.wait(Promise.any(workspaces.map(async workspace => { + try { if (await deps.workspaceManager.ownsLocation(workspace.id, location, undefined, { signal, strict: preferenceProbe })) return true } + catch { ownershipReadFailed = true } + throw new Error("Not an owner") + }))).catch(() => false) + } catch (error) { + if (preferenceProbe) return preferenceUnavailable() + throw error + } + if (preferenceProbe && (signal.aborted || !owned && ownershipReadFailed)) return preferenceUnavailable() + if (!owned) return notOwner("Session is not owned by this CodeNomad instance") if (body.mode === "mission-input") { - if (!deps.worktreeDeletionFence) return reply.code(503).send({ error: "Mission dispatch unavailable" }) try { + if (commandKind === "profile-defaults") return reply.send({ result: readMissionProfileDefaults(deps.settings, body.command) }) + if (!deps.worktreeDeletionFence) return reply.code(503).send({ error: "Mission dispatch unavailable" }) // Journal-keyed creation capability of the owning backend. Durable // admission does not use this bridge or gain a new native API fallback. const fence = deps.worktreeDeletionFence @@ -153,7 +173,7 @@ export function registerAutomationPluginRoute(app: FastifyInstance, deps: Automa } } - if (["browser-claim", "browser-probe", "browser-execute"].includes(String(body.mode)) && !(body.mode === "browser-claim" && body.purpose === "mission") + if (["browser-claim", "browser-probe", "browser-execute"].includes(String(body.mode)) && !preferenceProbe && !(body.mode === "browser-claim" && body.purpose === "mission") && deps.nativeParent.browserAutomationUnavailable) { return reply.code(409).send({ code: "unsupported", error: "Browser automation is unavailable in this host" }) } @@ -162,10 +182,10 @@ export function registerAutomationPluginRoute(app: FastifyInstance, deps: Automa // Without a desktop host this backend owns sessions only for Mission // dispatch; claiming browsers too would hand the browser tools an owner // that cannot open a page, or make a desktop owner ambiguous. - if (!deps.nativeParent.available && body.purpose !== "mission") { + if (!deps.nativeParent.available && body.purpose !== "mission" && !preferenceProbe) { return reply.code(404).send({ error: "Browser automation is unavailable in this host" }) } - return reply.send({ result: { available: true } }) + return reply.send({ result: { available: true, ...(preferenceProbe ? { missionCreationDefaults: true } : {}) } }) } if (body.mode === "browser-probe") { try { diff --git a/packages/server/src/server/routes/images-conversation.ts b/packages/server/src/server/routes/images-conversation.ts index aecdcac72b..eb7483fffa 100644 --- a/packages/server/src/server/routes/images-conversation.ts +++ b/packages/server/src/server/routes/images-conversation.ts @@ -36,7 +36,7 @@ export async function resolveImagesConversationAt(deps: ImagesConversationRouteD const manager = deps.workspaceManager // Authorize the caller's directory before any OpenCode request: reading a // Location boots its services (configuration discovery, plugins). - if (!await manager.ownsLocation(workspaceId, { directory }, undefined, options.signal)) return "denied" + if (!await manager.ownsLocation(workspaceId, { directory }, undefined, { signal: options.signal })) return "denied" const identity = await manager.getWorktreeIdentityForPath(workspaceId, directory) if (!identity) return "denied" const release = deps.worktreeDeletionFence.enter([identity]) @@ -53,7 +53,7 @@ export async function resolveImagesConversationAt(deps: ImagesConversationRouteD const location = await client.location.get({ location: { directory } }, { signal: options.signal ? AbortSignal.any([read, options.signal]) : read }) .then(readLocationRef, () => undefined) options.signal?.throwIfAborted() - if (!location || location.directory !== directory || !await manager.ownsLocation(workspaceId, location, client, options.signal)) return "denied" + if (!location || location.directory !== directory || !await manager.ownsLocation(workspaceId, location, client, { signal: options.signal })) return "denied" let result: ImagesConversationResponse try { const timeout = AbortSignal.timeout(options.rpcTimeoutMs ?? 15_000) diff --git a/packages/server/src/server/routes/mission-cleanup-admission.test.ts b/packages/server/src/server/routes/mission-cleanup-admission.test.ts index 24d8d55b86..58c86d76e3 100644 --- a/packages/server/src/server/routes/mission-cleanup-admission.test.ts +++ b/packages/server/src/server/routes/mission-cleanup-admission.test.ts @@ -67,7 +67,7 @@ async function fixture(label: string) { const manager = { list: () => [{ id: "workspace" }], getSharedServiceClient: async () => client, getSharedServiceConnection: async () => { acquisitions++; return connection }, - ownsLocation: async (_id: string, location: { directory: string }, ownedClient?: unknown, signal?: AbortSignal) => { + ownsLocation: async (_id: string, location: { directory: string }, ownedClient?: unknown, { signal }: { signal?: AbortSignal } = {}) => { if (ownedClient) assert.equal(ownedClient, client) await state.ownerHook(location.directory) signal?.throwIfAborted() diff --git a/packages/server/src/server/routes/mission-cleanup.ts b/packages/server/src/server/routes/mission-cleanup.ts index be9116089a..d07d9b257f 100644 --- a/packages/server/src/server/routes/mission-cleanup.ts +++ b/packages/server/src/server/routes/mission-cleanup.ts @@ -23,7 +23,7 @@ export async function cleanupMissionSession(manager: Manager, fence: WorktreeDel if (!connection) throw new Error("Workspace unavailable") const coordinator = await connection.client.session.get({ sessionID: coordinatorID }, { signal }) if (coordinator.id !== coordinatorID || coordinator.parentID - || !await manager.ownsLocation(workspace.id, coordinator.location, connection.client, signal)) throw new Error("Foreign coordinator") + || !await manager.ownsLocation(workspace.id, coordinator.location, connection.client, { signal })) throw new Error("Foreign coordinator") signal.throwIfAborted(); connection.assertCurrent() return { workspace, connection, coordinator } })).catch(() => undefined) @@ -36,7 +36,7 @@ export async function cleanupMissionSession(manager: Manager, fence: WorktreeDel if (!target) return { outcome: "retained" as const } if (target.sessionID !== input.sessionID || target.missionID !== input.missionID || target.coordinatorSessionID !== coordinatorID || target.sessionID === coordinatorID || target.projectID !== coordinator.projectID - || !await manager.ownsLocation(workspace.id, target.location, client, signal)) throw new Error("Foreign cleanup target") + || !await manager.ownsLocation(workspace.id, target.location, client, { signal })) throw new Error("Foreign cleanup target") const identities = await Promise.all([coordinator.location, target.location].map(location => manager.getWorktreeIdentityForPath(workspace.id, location.directory))) if (identities.some(identity => !identity)) throw new Error("Missing mission worktree") const release = fence.enter(identities as string[]) @@ -49,7 +49,7 @@ export async function cleanupMissionSession(manager: Manager, fence: WorktreeDel if (currentCoordinator.id !== coordinatorID || currentCoordinator.parentID || currentCoordinator.projectID !== coordinator.projectID || !sameLocation(currentCoordinator.location, coordinator.location)) throw new Error("Coordinator moved") const owned = await Promise.all([coordinator.location, target.location].map(location => - manager.ownsLocation(workspace.id, location, client, signal))) + manager.ownsLocation(workspace.id, location, client, { signal }))) // A shared daemon can remain current after this workspace loses ownership. // Validate both ORIGINAL admitted locations, never adopt a replacement. assertCurrent() diff --git a/packages/server/src/server/routes/mission-creation-admission.ts b/packages/server/src/server/routes/mission-creation-admission.ts index 1518015c08..6f93b168c1 100644 --- a/packages/server/src/server/routes/mission-creation-admission.ts +++ b/packages/server/src/server/routes/mission-creation-admission.ts @@ -16,7 +16,7 @@ export async function admitMissionCreationLocations(manager: MissionCreationMana workspaceID: string, connection: ServiceConnection, locations: readonly LocationRef[], signal: AbortSignal, operation?: MissionCreationOperation) { const resolve = async (location: LocationRef) => { - if (!manager.get(workspaceID) || !await manager.ownsLocation(workspaceID, location, connection.client, signal)) { + if (!manager.get(workspaceID) || !await manager.ownsLocation(workspaceID, location, connection.client, { signal })) { throw new MissionControlError("Mission creation location is not owned", "foreign-session") } const directory = await manager.getServiceDirectoryForPath(workspaceID, location.directory) @@ -72,7 +72,7 @@ export async function prepareMissionRootCreationLocation(input: { ...locationRequestOptions(input.rootLocation), signal, }) if (resolved.project.id !== input.projectID || !sameLocation(resolved, { directory }) - || !await manager.ownsLocation(workspaceID, resolved, connection.client, signal)) { + || !await manager.ownsLocation(workspaceID, resolved, connection.client, { signal })) { throw new MissionControlError("Foreign effective mission root location", "foreign-session") } await assertCurrent() diff --git a/packages/server/src/server/routes/mission-creation-fence.test.ts b/packages/server/src/server/routes/mission-creation-fence.test.ts index da31885785..fba9241225 100644 --- a/packages/server/src/server/routes/mission-creation-fence.test.ts +++ b/packages/server/src/server/routes/mission-creation-fence.test.ts @@ -8,7 +8,8 @@ import { AUTOMATION_BRIDGE_PATH } from "../../opencode/automation-plugin" import { setupMissionsPlugin } from "../../opencode/missions-plugin" import { WorktreeDeletionFence } from "../../workspaces/worktree-session-evacuation" import { prepareMissionCreation } from "./mission-creation-pipeline" -import { missionRecoveryError } from "../../missions/recovery-error" +import { missionRecoveryControlError, missionRecoveryError } from "../../missions/recovery-error" +import { MissionControlError } from "../../missions/control-error" const directory = "C:/private-fixture/worktree" const physical = "C:/private-fixture/physical" @@ -30,7 +31,8 @@ async function fixture(useBridge = false, drainTimeout = 2_000) { const fence = new WorktreeDeletionFence(drainTimeout) const storage = new Map(), sessions = new Map(), tools = new Map() let handlers: any, creates = 0, writes = 0, current = true, rpcCreates = 0 - let lostAck = false, failedPublication = false, wrongProfile = false + let lostAck = false, failedPublication = false, wrongProfile = false, documentCapabilities = true, failedIntentCleanup = false + let preferences: unknown, preferenceReads = 0 let rejectionTransform: ((error: any) => any) | undefined let creationGate: ReturnType | undefined, publicationGate: ReturnType | undefined let settlementGate: ReturnType | undefined, foreignRoot = false, nativeDirectory = directory @@ -55,7 +57,10 @@ async function fixture(useBridge = false, drainTimeout = 2_000) { session, location: { get: async () => ({ directory: nativeDirectory, project: { id: projectID } }) }, plugin: { list: async () => ({ data: [{ id: "codenomad.missions", state: { status: "active" } }] }) }, rpc: () => new Proxy({}, { get: (_, method) => async (input: any) => { - if (method === "documentCapabilities") return { version: 1 } + if (method === "documentCapabilities") { + if (!documentCapabilities) throw new Error("Document capabilities unavailable") + return { version: 1 } + } if (method === "snapshot" && creates && settlementGate) { settlementStarted.resolve(); await settlementGate.promise } if (method === "create") rpcCreates++ try { @@ -80,6 +85,7 @@ async function fixture(useBridge = false, drainTimeout = 2_000) { const context: any = { location: { directory, project: { id: projectID, canonical: directory } }, session, storage: { get: async (key: string) => structuredClone(storage.get(key)), set: async (key: string, value: any) => { + if (failedIntentCleanup && key.includes("/creation-intents/") && value === null) throw new Error("Intention cleanup unavailable") publicationStarted.resolve(); await publicationGate?.promise if (failedPublication) throw new Error("Publication unavailable") writes++; storage.set(key, structuredClone(value)) @@ -92,11 +98,16 @@ async function fixture(useBridge = false, drainTimeout = 2_000) { const bridge = async (sessionID: string, kind: string, input: unknown) => { const response = await app.inject({ method: "POST", url: AUTOMATION_BRIDGE_PATH, headers: { "x-codenomad-automation-token": "private-token" }, payload: { mode: "mission-input", sessionID, command: { kind, input } } }) - if (response.statusCode !== 200) throw new Error(missionRecoveryError(response.json().code)?.message ?? response.json().error) + if (response.statusCode !== 200) { + const error = missionRecoveryError(response.json().code, response.json().error) + if (error && error.status === response.statusCode) throw missionRecoveryControlError(error.code, response.json().error) + throw new Error(response.json().error) + } return response.json().result } const transport = { prompt: async () => ({}), synthetic: async () => ({}), + resolveCreationDefaults: (sessionID: string, input: unknown) => bridge(sessionID, "profile-defaults", input), prepare: (sessionID: string, input: unknown) => bridge(sessionID, "prepare", input), } const creationLifetime = new AbortController() @@ -111,10 +122,15 @@ async function fixture(useBridge = false, drainTimeout = 2_000) { }) registerMissionRoutes(app, { workspaceManager: manager, worktreeDeletionFence: fence }) registerAutomationPluginRoute(app, { workspaceManager: manager, worktreeDeletionFence: fence, bridgeToken: "private-token", + settings: { getRawConfigOwner: (owner: string) => { assert.equal(owner, "ui"); preferenceReads++; return { settings: { missionProfileDefaults: preferences } } } }, authManager: { isLoopbackRequest: () => true }, nativeParent: {}, developerCdp: {} } as any) return { app, fence, sessions, storage, tools, handlers, manager, context, creationStarted, publicationStarted, settlementStarted, track, get creates() { return creates }, get writes() { return writes }, get rpcCreates() { return rpcCreates }, + get preferenceReads() { return preferenceReads }, + setPreferences: (value: unknown) => { preferences = value }, + setDocumentCapabilities: (value: boolean) => { documentCapabilities = value }, + failIntentCleanup: () => { failedIntentCleanup = true }, loseAck: () => { lostAck = true }, failPublication: () => { failedPublication = true }, mismatchProfile: () => { wrongProfile = true }, transformRejection: (transform: (error: any) => any) => { rejectionTransform = transform }, @@ -240,7 +256,7 @@ async function specialist(f: Awaited>) { const result = await f.tools.get("inspect").execute({ start: { objective: "Test", template: "custom" } }, { sessionID: coordinator.id, id: "inspect", progress: async () => {}, }) - return { coordinator, mission: JSON.parse(result.content).mission } + return { coordinator, ...JSON.parse(result.content) } } function delegate(f: Awaited>) { return f.track(f.tools.get("delegate").execute({ taskKey: "work", title: "Work", brief: "Test", role: "worker", @@ -259,6 +275,8 @@ test("a coordinator prepares a paused hand-off through the bridge's fenced creat const prepare = (objective = "Pilot the chosen seam") => tool("prepare", { requestID: "pilot", objective, template: "custom" }) const prepared = JSON.parse((await prepare()).content) assert.deepEqual([prepared.disposition, prepared.status, prepared.runState], ["prepared", "active", "prepared"]) + assert.deepEqual(prepared.selection, { profiles: { coordinator: {}, roles: { specialist: {} } }, taskMode: "native", + origins: { coordinator: "opencode-default", roles: { specialist: "opencode-default" }, taskMode: "opencode-default" } }) const handoff = (await f.handlers.snapshot()).missions.find((mission: any) => mission.id === prepared.missionID) assert.deepEqual(handoff.preparedBy, { missionId: source.id, coordinatorSessionId: coordinator.id }) assert.notEqual(handoff.coordinatorSessionId, coordinator.id) @@ -286,11 +304,83 @@ test("a lost prepare acknowledgement is reported uncertain, never as nothing cre f.loseAck() await assert.rejects(prepare(), /outcome is uncertain; retry with the same requestID/) const saved = (await f.handlers.snapshot()).missions.find((mission: any) => mission.preparedBy?.coordinatorSessionId === coordinator.id) - assert.equal(JSON.parse((await prepare()).content).missionID, saved.id) + const reads = f.preferenceReads + f.setPreferences({ invalid: true }) + const replay = JSON.parse((await prepare()).content) + assert.equal(replay.missionID, saved.id) + assert.deepEqual(replay.selection, { profiles: saved.profiles, taskMode: saved.taskMode, origins: saved.creationDefaults.origins }) + assert.equal(f.preferenceReads, reads, "invalid current preferences cannot invalidate a saved creation") assert.equal(f.rpcCreates, 1, "the retry never asks for a second creation") } finally { await f.close() } }) +test("an intention cleanup failure preserves creation success and releases the native admission hold", async () => { + const f = await fixture() + try { + const { coordinator } = await specialist(f) + f.failIntentCleanup() + const prepare = () => f.tools.get("prepare").execute({ requestID: "cleanup", objective: "Pilot", template: "custom" }, + { sessionID: coordinator.id, id: "cleanup-prepare", progress: async () => {} }) + const first = JSON.parse((await prepare()).content) + assert.equal(first.disposition, "prepared") + assert.deepEqual(JSON.parse((await prepare()).content), first) + assert.equal(f.rpcCreates, 1) + assert.equal(await f.fence.run(physical, [physical], async () => "released"), "released") + } finally { await assert.rejects(f.close(), /Intention cleanup unavailable/) } +}) + +test("an uncertain prepare before any creation document retains its original selection across preference changes", async () => { + const f = await fixture() + try { + const { coordinator } = await specialist(f) + f.setPreferences([{ template: "all", profiles: { coordinator: { agent: "fixture" } }, taskMode: "independent" }]) + const request = { requestID: "uncertain-profile", objective: "Uncertain pilot", template: "custom" } + const prepare = (input = request) => f.tools.get("prepare").execute(input, { + sessionID: coordinator.id, id: "prepare-uncertain-profile", progress: async () => {}, + }) + f.returnChild() + await assert.rejects(prepare(), /outcome is uncertain/) + assert.equal((await f.handlers.snapshot()).missions.some((mission: any) => mission.preparedBy), false) + const reads = f.preferenceReads, bytes = structuredClone([...f.storage]) + f.setDocumentCapabilities(false) + await assert.rejects(prepare(), (error: any) => error.code === "prepare-uncertain") + assert.equal(f.preferenceReads, reads) + assert.deepEqual([...f.storage], bytes, "a later prevalidation refusal cannot erase the original uncertain intention") + f.setDocumentCapabilities(true) + for (const preferences of [[], { invalid: true }]) { + f.setPreferences(preferences) + await assert.rejects(prepare(), /outcome is uncertain/) + assert.equal(f.preferenceReads, reads) + assert.equal(f.rpcCreates, 1, "the original uncertain hold never permits a replay") + assert.deepEqual([...f.storage], bytes) + } + await assert.rejects(prepare({ ...request, objective: "Another pilot" }), /different mission/) + assert.equal(f.creates, 1) + } finally { await f.close() } +}) + +test("the bridge resolves owner preferences once and returns the frozen tool selection on replay", async () => { + const f = await fixture() + try { + const { coordinator, selection } = await specialist(f) + assert.deepEqual(selection, { profiles: { coordinator: {}, roles: { specialist: {} } }, taskMode: "native", + origins: { coordinator: "opencode-default", roles: { specialist: "opencode-default" }, taskMode: "opencode-default" } }) + f.setPreferences([{ template: "all", profiles: { coordinator: { agent: "fixture" }, roles: { specialist: {} } }, taskMode: "independent" }]) + const request = { requestID: "preferred", objective: "Owner choices", template: "custom" } + const prepare = (input = request) => f.tools.get("prepare").execute(input, { sessionID: coordinator.id, id: "prepare-preferred", progress: async () => {} }) + const first = JSON.parse((await prepare()).content) + assert.deepEqual(first.selection, { profiles: { coordinator: { agent: "fixture" }, roles: { specialist: {} } }, taskMode: "independent", + origins: { coordinator: "preference", roles: { specialist: "preference" }, taskMode: "preference" } }) + const reads = f.preferenceReads, bytes = structuredClone([...f.storage]) + f.setPreferences([{ template: "all", profiles: {}, taskMode: "native" }]) + assert.deepEqual(JSON.parse((await prepare()).content), first) + await assert.rejects(prepare({ ...request, objective: "Conflict" }), /already prepared a different mission/) + assert.equal(f.preferenceReads, reads) + assert.equal(f.rpcCreates, 1) + assert.deepEqual([...f.storage], bytes) + } finally { await f.close() } +}) + test("human coordinator creation fails before native creation and publication under the physical deletion fence", async () => { const f = await fixture(), held = deferred() const deletion = f.fence.run(physical, [physical], () => held.promise) diff --git a/packages/server/src/server/routes/mission-creation-holds.ts b/packages/server/src/server/routes/mission-creation-holds.ts index 7f6f0fbb8d..b9d1bb5acf 100644 --- a/packages/server/src/server/routes/mission-creation-holds.ts +++ b/packages/server/src/server/routes/mission-creation-holds.ts @@ -1,6 +1,7 @@ import { createHash } from "node:crypto" import type { ServiceConnection } from "../../workspaces/opencode-service" import type { WorktreeDeletionFence } from "../../workspaces/worktree-session-evacuation" +import { stableToken } from "../../missions/receipt-identity" export interface MissionCreationOperation { key: string @@ -23,6 +24,14 @@ const CAPACITY = 128 // human-answer consumer may settle only its exact original native receipt. const held = new WeakMap>() +/** A later preflight refusal cannot settle this earlier native write. */ +export function hasMissionPreparationHold(fence: WorktreeDeletionFence, requestID: string): boolean { + return [...held.get(fence)?.values() ?? []].some(({ binding }) => { + const missionID = `msn_${stableToken(`${binding.projectID}\0${requestID}`, 24)}` + return binding.missionID === missionID && binding.key === `human:${binding.projectID}:${missionID}` + }) +} + export class MissionCreationHoldError extends Error { constructor(readonly code: "creation-uncertain" | "creation-conflict" | "creation-capacity") { super(code === "creation-uncertain" ? "Mission creation settlement is unknown; deletion remains blocked" diff --git a/packages/server/src/server/routes/mission-creation-pipeline.ts b/packages/server/src/server/routes/mission-creation-pipeline.ts index 1fb72ddabc..9e99ee5e9b 100644 --- a/packages/server/src/server/routes/mission-creation-pipeline.ts +++ b/packages/server/src/server/routes/mission-creation-pipeline.ts @@ -13,12 +13,13 @@ import { locationRequestOptions, sameLocation } from "../../opencode/compatibili import { assertSynchronousAuthorityGuard } from "../../missions/authority-synchronous" import { admitMissionCreationLocations } from "./mission-creation-admission" import { MissionCreationHoldError, missionCreationDigest } from "./mission-creation-holds" +import type { MissionCreationMetadata } from "../../missions/creation-defaults" export const missionCreationRequestSchema = z.object({ objective: z.string().trim().min(1).max(20_000), title: z.string().trim().min(1).max(MISSION_TITLE_MAX).regex(MISSION_TITLE_PATTERN).optional(), notes: z.string().max(20_000).optional(), template: z.enum(["custom", "wayfinder", "debug", "delivery", "compare"]), coordinatorSessionId: z.string().trim().min(1).max(240).optional(), directory: z.string().trim().min(1).max(4_096).optional(), requestId: z.string().trim().min(1).max(128), - profiles: missionProfilesInputSchema, taskMode: missionTaskModeInputSchema.default("native"), + profiles: missionProfilesInputSchema, taskMode: missionTaskModeInputSchema.optional(), }).strict() export type MissionCreationPipelineManager = Pick(operation: Promise) => operation) @@ -48,7 +50,7 @@ export async function prepareMissionCreation(input: { const request = parsed.data const compareError = request.template === "compare" && compareModelError(request.profiles) if (compareError) throw new MissionCreationPreparationError(400, compareError) - request.profiles = freezeCompareProfiles(request.template, request.profiles) + if (!input.creationDefaults) request.profiles = freezeCompareProfiles(request.template, request.profiles) try { validateMissionProfiles(request.template, request.profiles) } catch { throw new MissionCreationPreparationError(400, "Invalid mission creation request") } if (!input.fence) throw new MissionCreationPreparationError(503, "Mission creation unavailable") @@ -59,14 +61,14 @@ export async function prepareMissionCreation(input: { if (!connection) throw new MissionCreationPreparationError(503, "Mission plugin unavailable") const client = connection.client let location = request.directory ? { directory: request.directory } : base - if (!await wait(manager.ownsLocation(workspaceID, location, client, signal))) { + if (!await wait(manager.ownsLocation(workspaceID, location, client, { signal }))) { throw new MissionCreationPreparationError(403, "Mission directory does not belong to workspace") } const directory = await wait(manager.getServiceDirectoryForPath(workspaceID, location.directory)) if (!directory) throw new MissionCreationPreparationError(503, "Mission plugin unavailable") location = { directory } const resolved = await wait(client.location.get({ location }, { ...locationRequestOptions(location), signal })) - if (!sameLocation(location, resolved) || !await wait(manager.ownsLocation(workspaceID, resolved, client, signal))) { + if (!sameLocation(location, resolved) || !await wait(manager.ownsLocation(workspaceID, resolved, client, { signal }))) { throw new MissionCreationPreparationError(403, "Native mission location differs from owned directory") } const baseResolved = await wait(client.location.get({ location: { directory: base.directory } }, { ...locationRequestOptions(base), signal })) @@ -87,7 +89,7 @@ export async function prepareMissionCreation(input: { if (request.coordinatorSessionId) { const coordinator = await wait(client.session.get({ sessionID: request.coordinatorSessionId }, { signal })) if (coordinator.id !== request.coordinatorSessionId || coordinator.parentID || coordinator.projectID !== projectID - || !await wait(manager.ownsLocation(workspaceID, coordinator.location, client, signal))) { + || !await wait(manager.ownsLocation(workspaceID, coordinator.location, client, { signal }))) { throw new MissionCreationPreparationError(403, "Coordinator session does not belong to workspace project") } locations.push(coordinator.location) @@ -102,8 +104,9 @@ export async function prepareMissionCreation(input: { const nativeInput = { prepared: true, requestID: request.requestId, objective: request.objective, ...(request.title === undefined ? {} : { title: request.title }), - ...(request.notes === undefined ? {} : { notes: request.notes }), template: request.template, taskMode: request.taskMode, + ...(request.notes === undefined ? {} : { notes: request.notes }), template: request.template, taskMode: request.taskMode ?? "native", ...(request.profiles === undefined ? {} : { profiles: request.profiles }), + ...(input.creationDefaults === undefined ? {} : { creationDefaults: input.creationDefaults }), ...(request.coordinatorSessionId ? { coordinatorSessionID: request.coordinatorSessionId } : {}), expectedCoordinatorLocation: locations.at(-1)!, ...(input.preparedBy === undefined ? {} : { preparedBy: { ...input.preparedBy } }), diff --git a/packages/server/src/server/routes/mission-human-answer.ts b/packages/server/src/server/routes/mission-human-answer.ts index c7d1910a9f..a6b47ff0e8 100644 --- a/packages/server/src/server/routes/mission-human-answer.ts +++ b/packages/server/src/server/routes/mission-human-answer.ts @@ -76,7 +76,7 @@ async function prepareMissionHumanAnswer(request: FastifyRequest, workspaceID: s if (seen.has(id)) throw new Error("Human answer ancestry cycle") seen.add(id) const session = await client.session.get({ sessionID: id }, { signal }) - if (session.id !== id || !await deps.manager.ownsLocation(workspaceID, session.location, client, signal) + if (session.id !== id || !await deps.manager.ownsLocation(workspaceID, session.location, client, { signal }) || ownedLocation && !sameLocation(session.location, ownedLocation)) { throw new Error("Human answer session changed") } @@ -137,7 +137,7 @@ export async function verifyMissionHumanAnswer(raw: unknown, deps: Omit { + const model = { model: { providerID: "fixture", id: "same" } } + for (const code of ["compare-models-required", "compare-models-identical", "compare-models-private-detail"] as const) { + const manager = { + list: () => [{ id: "workspace" }], + ownsLocation: async () => true, + getSharedServiceConnection: async () => ({ client: { + session: { get: async () => ({ id: "coordinator", projectID: "project", location: { directory: "/fixture" } }) }, + rpc: () => ({ snapshot: async () => { + if (code === "compare-models-private-detail") throw new Error(code) + return { projectID: "project", missions: [{ id: "source", coordinatorSessionId: "coordinator", status: "active" }] } + } }), + } }), + } + const expected = missionRecoveryControlError(code === "compare-models-private-detail" ? "prepare-refused" : code) + await assert.rejects(prepareCoordinatorMission(manager as never, new WorktreeDeletionFence(), "coordinator", { + kind: "prepare", input: { missionID: "source", requestID: "private-comparison", objective: "Compare", template: "compare", + ...(code === "compare-models-identical" ? { profiles: { roles: { "model-a": model, "model-b": model } } } : {}) }, + }, new AbortController().signal), { code: expected.code, message: expected.message }) + } +}) diff --git a/packages/server/src/server/routes/mission-prepare.ts b/packages/server/src/server/routes/mission-prepare.ts index 1b1c540514..eafd7c87c2 100644 --- a/packages/server/src/server/routes/mission-prepare.ts +++ b/packages/server/src/server/routes/mission-prepare.ts @@ -1,8 +1,7 @@ import { z } from "zod" import { CODENOMAD_MISSIONS_RPC } from "../../missions/rpc" import type { MissionMap, MissionSnapshot } from "../../missions/model" -import { MissionControlError } from "../../missions/control-error" -import { readMissionMutationError } from "../../missions/rpc-errors" +import { isMissionCreateNoEffectError, readMissionMutationError } from "../../missions/rpc-errors" import { missionProfilesInputSchema } from "../../missions/playbook-profiles" import { missionTaskModeInputSchema } from "../../missions/task-execution-mode" import { MISSION_TITLE_MAX } from "../../missions/mission-title" @@ -10,13 +9,16 @@ import { locationRequestOptions } from "../../opencode/compatibility/location" import type { WorkspaceManager } from "../../workspaces/manager" import type { WorktreeDeletionFence } from "../../workspaces/worktree-session-evacuation" import { prepareMissionCreation, type MissionCreationPipelineManager } from "./mission-creation-pipeline" -import { MissionCreationHoldError } from "./mission-creation-holds" +import { hasMissionPreparationHold, MissionCreationHoldError } from "./mission-creation-holds" +import { missionCreationTemplateSchema, parseMissionCreationDefaults } from "../../missions/creation-defaults" +import { missionRecoveryControlError as refusal, missionRecoveryRejection } from "../../missions/recovery-error" const commandSchema = z.object({ kind: z.literal("prepare"), input: z.object({ missionID: z.string().min(1).max(100), requestID: z.string().min(1).max(128), objective: z.string().min(1).max(20_000), title: z.string().min(1).max(MISSION_TITLE_MAX).optional(), - notes: z.string().max(20_000).optional(), template: z.enum(["custom", "wayfinder", "debug", "delivery", "compare"]), + notes: z.string().max(20_000).optional(), template: missionCreationTemplateSchema, profiles: missionProfilesInputSchema, taskMode: missionTaskModeInputSchema.optional(), + creationDefaults: z.unknown().optional(), }).strict() }).strict() type Manager = MissionCreationPipelineManager & Pick @@ -26,45 +28,53 @@ type Manager = MissionCreationPipelineManager & Pick export async function prepareCoordinatorMission(manager: Manager, fence: WorktreeDeletionFence, coordinatorID: string, command: unknown, signal: AbortSignal): Promise<{ mission: MissionMap }> { const { input } = commandSchema.parse(command) - const owner = await Promise.any(manager.list().map(async workspace => { - const connection = await manager.getSharedServiceConnection(workspace.id) - if (!connection) throw new Error("Workspace unavailable") - const coordinator = await connection.client.session.get({ sessionID: coordinatorID }, { signal }) - if (coordinator.id !== coordinatorID || coordinator.parentID - || !await manager.ownsLocation(workspace.id, coordinator.location, connection.client)) throw new Error("Foreign coordinator") - return { connection, workspace, coordinator } - })).catch(() => undefined) - if (!owner) throw new Error("Missing mission owner") - const { connection, workspace, coordinator } = owner - const snapshot = await connection.client.rpc(CODENOMAD_MISSIONS_RPC).snapshot({}, { - location: { directory: coordinator.location.directory }, ...locationRequestOptions(coordinator.location), signal, - }) as MissionSnapshot - const source = snapshot.missions.find(mission => mission.id === input.missionID) - if (!source || snapshot.projectID !== coordinator.projectID || source.coordinatorSessionId !== coordinatorID || source.status !== "active") { - throw new MissionControlError("Only an active mission's coordinator may prepare a hand-off", "prepare-refused") - } let creation: Awaited> | undefined try { + if (hasMissionPreparationHold(fence, input.requestID)) throw refusal("prepare-uncertain") + const owner = await Promise.any(manager.list().map(async workspace => { + const connection = await manager.getSharedServiceConnection(workspace.id) + if (!connection) throw new Error("Workspace unavailable") + const coordinator = await connection.client.session.get({ sessionID: coordinatorID }, { signal }) + if (coordinator.id !== coordinatorID || coordinator.parentID + || !await manager.ownsLocation(workspace.id, coordinator.location, connection.client)) throw new Error("Foreign coordinator") + return { connection, workspace, coordinator } + })).catch(() => undefined) + if (!owner) throw refusal("prepare-refused") + const { connection, workspace, coordinator } = owner + const snapshot = await connection.client.rpc(CODENOMAD_MISSIONS_RPC).snapshot({}, { + location: { directory: coordinator.location.directory }, ...locationRequestOptions(coordinator.location), signal, + }) as MissionSnapshot + const source = snapshot.missions.find(mission => mission.id === input.missionID) + if (!source || snapshot.projectID !== coordinator.projectID || source.coordinatorSessionId !== coordinatorID || source.status !== "active") { + throw refusal("prepare-refused") + } creation = await prepareMissionCreation({ manager, fence, workspaceID: workspace.id, signal, expectedProjectID: coordinator.projectID, preparedBy: { missionID: source.id, coordinatorSessionID: coordinatorID }, + ...(input.creationDefaults === undefined ? {} : { creationDefaults: parseMissionCreationDefaults(input.template, input.creationDefaults) }), request: { requestId: input.requestID, objective: input.objective, template: input.template, directory: coordinator.location.directory, ...(input.title === undefined ? {} : { title: input.title }), ...(input.notes === undefined ? {} : { notes: input.notes }), ...(input.profiles === undefined ? {} : { profiles: input.profiles }), ...(input.taskMode === undefined ? {} : { taskMode: input.taskMode }) } }) return await creation.execute() } catch (error) { - if (!creation?.dispatched && error instanceof Error && error.message.startsWith("compare-models-")) - throw new MissionControlError(error.message, "prepare-refused") + if (creation && isMissionCreateNoEffectError(error, input.requestID, creation.missionID)) + throw refusal("prepare-no-effect") + if (hasMissionPreparationHold(fence, input.requestID)) throw refusal("prepare-uncertain") + if (missionRecoveryRejection(error)) throw error + if (!creation?.dispatched && error instanceof Error) { + if (error.message === "compare-models-required") throw refusal("compare-models-required") + if (error.message === "compare-models-identical") throw refusal("compare-models-identical") + } // An earlier uncertain attempt with this identity stays held: never claim nothing exists. if (error instanceof MissionCreationHoldError) { - if (error.code === "creation-conflict") throw new MissionControlError("This requestID already prepared a different mission", "prepare-conflict") - if (error.code === "creation-uncertain") throw new MissionControlError("The prepared mission's outcome is uncertain; retry with the same requestID", "prepare-uncertain") + if (error.code === "creation-conflict") throw refusal("prepare-conflict") + if (error.code === "creation-uncertain") throw refusal("prepare-uncertain") } // Only a refusal before the native create proves nothing was created. const code = readMissionMutationError(error)?.code - if (!creation?.dispatched) throw new MissionControlError("The mission could not be prepared; nothing was created", "prepare-refused") + if (!creation?.dispatched) throw refusal("prepare-refused") if (code === "request-conflict") { - throw new MissionControlError("This requestID already prepared a different mission", "prepare-conflict") + throw refusal("prepare-conflict") } - throw new MissionControlError("The prepared mission's outcome is uncertain; retry with the same requestID", "prepare-uncertain") + throw refusal("prepare-uncertain") } finally { creation?.dispose() } } diff --git a/packages/server/src/server/routes/mission-profile-defaults.test.ts b/packages/server/src/server/routes/mission-profile-defaults.test.ts new file mode 100644 index 0000000000..ea31902934 --- /dev/null +++ b/packages/server/src/server/routes/mission-profile-defaults.test.ts @@ -0,0 +1,109 @@ +import assert from "node:assert/strict" +import test, { type TestContext } from "node:test" +import Fastify from "fastify" +import { AUTOMATION_BRIDGE_PATH } from "../../opencode/automation-plugin" +import { registerAutomationPluginRoute } from "./automation-plugin" +import { readMissionProfileDefaults } from "./mission-profile-defaults" +import { MISSION_DEFAULTS_REQUEST_INVALID } from "../../missions/recovery-error" + +function fixture(t: TestContext, read?: () => unknown) { + const app = Fastify() + t.after(() => app.close()) + registerAutomationPluginRoute(app, { + authManager: { isLoopbackRequest: () => true }, bridgeToken: "fixture", nativeParent: {}, developerCdp: {}, + settings: { getProfileScope: () => assert.fail("Profile scope is unrelated"), ...(read ? { getRawConfigOwner: (owner: string) => { + assert.equal(owner, "ui") + return read() + } } : {}) }, + workspaceManager: { + getSharedServiceClient: async () => ({ session: { get: async () => ({ location: { directory: "/repo" } }) } }), + list: () => [{ id: "owner" }], ownsLocation: async () => true, + }, + } as never) + return (input: unknown = { template: "custom" }, extraCommand = {}) => app.inject({ + method: "POST", url: AUTOMATION_BRIDGE_PATH, headers: { "x-codenomad-automation-token": "fixture" }, + payload: { mode: "mission-input", sessionID: "ses_owner", command: { kind: "profile-defaults", input, ...extraCommand } }, + }) +} + +test("profile defaults read missing and empty preferences freshly without a dispatch fence", async t => { + let owner: unknown = {}, reads = 0 + const request = fixture(t, () => { reads++; return owner }) + const native = { profiles: { coordinator: {}, roles: { specialist: {} } }, taskMode: "native", + origins: { coordinator: "opencode-default", roles: { specialist: "opencode-default" }, taskMode: "opencode-default" } } + assert.deepEqual((await request()).json(), { result: native }) + owner = { settings: { missionProfileDefaults: [] } } + assert.deepEqual((await request()).json(), { result: native }) + owner = { settings: { missionProfileDefaults: [{ template: "all", profiles: { coordinator: { agent: "general" } }, taskMode: "independent" }] } } + const preferred = await request() + assert.equal(preferred.statusCode, 200) + assert.equal(preferred.json().result.profiles.coordinator.agent, "general") + assert.equal(preferred.json().result.taskMode, "independent") + assert.equal(preferred.json().result.origins.coordinator, "preference") + const explicit = await request({ template: "custom", profiles: { coordinator: {} }, taskMode: "native" }) + assert.deepEqual(explicit.json().result.profiles.coordinator, {}) + assert.equal(explicit.json().result.origins.coordinator, "explicit") + assert.equal(explicit.json().result.origins.taskMode, "explicit") + assert.equal(reads, 4) +}) + +test("invalid preference values fail closed with a fixed redacted code", async t => { + let preferences: unknown + const request = fixture(t, () => ({ settings: { missionProfileDefaults: preferences } })) + for (preferences of [null, {}, "secret-provider-token", [{ template: "other", profiles: {} }], + [{ template: "all", profiles: {}, taskMode: "other" }]]) { + const response = await request() + assert.equal(response.statusCode, 409) + assert.deepEqual(response.json(), { code: "mission-preferences-invalid", error: "Correct the Missions preferences before creating a mission" }) + const explicit = await request({ template: "custom", profiles: { coordinator: {} }, taskMode: "native" }) + assert.equal(explicit.json().code, "mission-preferences-invalid") + } +}) + +test("profile default command validates all input before reading preferences", async t => { + let reads = 0 + const request = fixture(t, () => { reads++; return { settings: { missionProfileDefaults: null } } }) + for (const input of [null, {}, { template: "other" }, { template: "custom", extra: true }, + { template: "custom", taskMode: "other" }, { template: "custom", coordinatorModel: { providerID: "p" } }, + { template: "custom", profiles: null }, { template: "custom", profiles: { extra: true } }, + { template: "custom", profiles: { roles: { developer: {} } } }, + { template: "custom", profiles: { coordinator: { model: { providerID: "p" } } } }]) { + const response = await request(input) + assert.equal(response.statusCode, 409) + assert.equal(response.json().code, "invalid-execution") + assert.match(response.json().error, /profiles|taskMode|playbook/i) + assert.doesNotMatch(response.json().error, /preferences/i) + } + assert.equal((await request({ template: "custom" }, { extra: true })).json().code, "invalid-execution") + assert.equal(reads, 0) +}) + +test("invalid command and selector requests share actionable validation copy", () => { + for (const command of [{ kind: "profile-defaults", extra: true }, { kind: "profile-defaults", input: { template: "other" } }]) { + assert.throws(() => readMissionProfileDefaults(undefined, command), (error: any) => + error.code === "invalid-execution" && error.message === MISSION_DEFAULTS_REQUEST_INVALID) + } +}) + +test("profile resolution preserves unexpected errors rather than labelling them invalid preferences", () => { + const failure = Object.assign(new Error("Unexpected resolver failure"), { name: "MissionPreferencesError", code: "mission-preferences-invalid" }) + const preferences = new Proxy([], { get() { throw failure } }) + assert.throws(() => readMissionProfileDefaults({ getRawConfigOwner: () => ({ settings: { missionProfileDefaults: preferences } }) } as never, + { kind: "profile-defaults", input: { template: "custom" } }), error => error === failure) +}) + +test("missing or unreadable preference readers expose only the fixed unavailable error", async t => { + for (const read of [undefined, () => ({ settings: null }), () => { throw new Error("secret /private/config.yaml") }]) { + const response = await fixture(t, read)() + assert.equal(response.statusCode, 503) + assert.deepEqual(response.json(), { code: "mission-preferences-unavailable", error: "CodeNomad backend discovery, ownership or preference reading failed; restore the backend and reload Missions preferences" }) + } +}) + +test("profile resolution leaves Compare validation to mission control", async t => { + const response = await fixture(t, () => ({}))({ template: "compare" }) + assert.equal(response.statusCode, 200) + assert.deepEqual(response.json().result.profiles.roles, { "model-a": {}, "model-b": {}, comparator: {} }) + const known = await fixture(t, () => ({}))({ template: "compare", coordinatorModel: { providerID: "p", id: "known", variant: "default" } }) + assert.deepEqual(known.json().result.profiles.roles.comparator, { model: { providerID: "p", id: "known" } }) +}) diff --git a/packages/server/src/server/routes/mission-profile-defaults.ts b/packages/server/src/server/routes/mission-profile-defaults.ts new file mode 100644 index 0000000000..63052ed3aa --- /dev/null +++ b/packages/server/src/server/routes/mission-profile-defaults.ts @@ -0,0 +1,28 @@ +import { z } from "zod" +import { MissionControlError } from "../../missions/control-error" +import { parseMissionCreationDefaultsInput } from "../../missions/creation-defaults" +import { MissionPreferencesError, resolveMissionCreationDefaults } from "../../missions/profile-defaults" +import { MISSION_DEFAULTS_REQUEST_INVALID, missionRecoveryControlError as refusal } from "../../missions/recovery-error" +import { isPlainObject } from "../../settings/merge-patch" +import type { SettingsService } from "../../settings/service" + +const commandSchema = z.object({ kind: z.literal("profile-defaults"), input: z.unknown() }).strict() + +/** Read the UI owner's raw document afresh for each creation; never persist resolved choices. */ +export function readMissionProfileDefaults(settings: Partial> | undefined, command: unknown) { + const parsed = commandSchema.safeParse(command) + if (!parsed.success) throw new MissionControlError(MISSION_DEFAULTS_REQUEST_INVALID, "invalid-execution") + const input = parseMissionCreationDefaultsInput(parsed.data.input) + let preferences: unknown + try { + if (!settings?.getRawConfigOwner) throw new Error("Missing preference reader") + const owner = settings.getRawConfigOwner("ui") + if (owner.settings !== undefined && !isPlainObject(owner.settings)) throw new Error("Invalid settings owner") + preferences = isPlainObject(owner.settings) ? owner.settings.missionProfileDefaults : undefined + } catch { throw refusal("mission-preferences-unavailable") } + try { return resolveMissionCreationDefaults({ ...input, preferences }) } + catch (error) { + if (error instanceof MissionPreferencesError) throw refusal("mission-preferences-invalid") + throw error + } +} diff --git a/packages/server/src/server/routes/mission-recurrence-control-status.ts b/packages/server/src/server/routes/mission-recurrence-control-status.ts index 2e00100909..0220860da0 100644 --- a/packages/server/src/server/routes/mission-recurrence-control-status.ts +++ b/packages/server/src/server/routes/mission-recurrence-control-status.ts @@ -51,7 +51,7 @@ export function registerMissionRecurrenceControlStatus(app: FastifyInstance, dep || recurrenceHumanSession(request, deps)?.sessionId !== session.sessionId) throw new Error("Control read changed") } const location = { directory }, signal = AbortSignal.any([lifetime.signal, AbortSignal.timeout(10_000)]) - if (!heldRead && !await lifetime.wait(deps.manager.ownsLocation(id, location, connection.client, signal))) return reply.code(403).send({ error: "Foreign Location" }) + if (!heldRead && !await lifetime.wait(deps.manager.ownsLocation(id, location, connection.client, { signal }))) return reply.code(403).send({ error: "Foreign Location" }) current() // Only an exact permit this backend holds may carry its own expired proof time. const read = { ...input.data, ...(heldRead || replacedRead ? recurrenceHoldProofHint(deps.fence, id, input.data) : {}) } @@ -59,7 +59,7 @@ export function registerMissionRecurrenceControlStatus(app: FastifyInstance, dep location, ...locationRequestOptions(location), signal, })) current() - if (!heldRead && !await lifetime.wait(deps.manager.ownsLocation(id, location, connection.client, signal))) throw new Error("Location changed") + if (!heldRead && !await lifetime.wait(deps.manager.ownsLocation(id, location, connection.client, { signal }))) throw new Error("Location changed") current() const result = recurrenceControlStatusSchema.parse(raw) if (result.scheduleID !== input.data.scheduleID || result.requestID !== input.data.requestID diff --git a/packages/server/src/server/routes/mission-recurrence-create.ts b/packages/server/src/server/routes/mission-recurrence-create.ts index 5d240937fc..44eaf48c4c 100644 --- a/packages/server/src/server/routes/mission-recurrence-create.ts +++ b/packages/server/src/server/routes/mission-recurrence-create.ts @@ -108,7 +108,7 @@ export function registerMissionRecurrenceCreate(app: FastifyInstance, deps: { wo } } const client = connection.client, requested = input.directory ? { directory: input.directory } : base - if (!await lifetime.wait(manager.ownsLocation(workspaceID, requested, client, lifetime.signal))) { + if (!await lifetime.wait(manager.ownsLocation(workspaceID, requested, client, { signal: lifetime.signal }))) { return reply.code(403).send({ error: "Recurrence directory is not owned" }) } const directory = await lifetime.wait(manager.getServiceDirectoryForPath(workspaceID, requested.directory)) @@ -119,7 +119,7 @@ export function registerMissionRecurrenceCreate(app: FastifyInstance, deps: { wo client.location.get({ location: { directory: base.directory } }, { ...locationRequestOptions(base), signal: lifetime.signal }), ])) check() - if (!sameLocation(resolved, location) || !await lifetime.wait(manager.ownsLocation(workspaceID, resolved, client, lifetime.signal)) + if (!sameLocation(resolved, location) || !await lifetime.wait(manager.ownsLocation(workspaceID, resolved, client, { signal: lifetime.signal })) || resolved.project.id !== baseResolved.project.id || resolved.project.canonical !== baseResolved.project.canonical) { return reply.code(403).send({ error: "Recurrence project is not owned" }) } @@ -144,7 +144,7 @@ export function registerMissionRecurrenceCreate(app: FastifyInstance, deps: { wo check() if (session.id !== sessionID || session.projectID !== resolved.project.id || !sameLocation(session.location, location) - || !await manager.ownsLocation(workspaceID, session.location, client, lifetime.signal)) return false + || !await manager.ownsLocation(workspaceID, session.location, client, { signal: lifetime.signal })) return false check() } return true @@ -172,7 +172,7 @@ export function registerMissionRecurrenceCreate(app: FastifyInstance, deps: { wo manager.getWorktreeIdentityForPath(workspaceID, directory), ]) if (canonicalAuthority(currentRoot) !== canonicalAuthority(root) || currentCheckout !== physicalCheckout - || !await manager.ownsLocation(workspaceID, location, client, lifetime.signal) + || !await manager.ownsLocation(workspaceID, location, client, { signal: lifetime.signal }) || !readCurrent()) throw new Error("Recurrence physical root changed") check() } diff --git a/packages/server/src/server/routes/mission-recurrence-manual.ts b/packages/server/src/server/routes/mission-recurrence-manual.ts index d25e9469fd..bc9696ee2f 100644 --- a/packages/server/src/server/routes/mission-recurrence-manual.ts +++ b/packages/server/src/server/routes/mission-recurrence-manual.ts @@ -40,13 +40,13 @@ export function registerMissionRecurrenceManual(app: FastifyInstance, deps: Para || !sameLocation(deps.manager.getServiceLocation(request.params.id) ?? { directory: "" }, base) || recurrenceHumanSession(request, deps)?.sessionId !== session.sessionId) throw new Error("Manual status changed") } - if (!await lifetime.wait(deps.manager.ownsLocation(request.params.id, location, connection.client, lifetime.signal))) throw new Error("Foreign Location") + if (!await lifetime.wait(deps.manager.ownsLocation(request.params.id, location, connection.client, { signal: lifetime.signal }))) throw new Error("Foreign Location") current() const result = recurrenceManualResultSchema.parse(await lifetime.wait(connection.client.rpc(CODENOMAD_MISSIONS_RPC).recurrenceRunNowStatus({ ...input.data, ...hint }, { location, ...locationRequestOptions(location), signal: lifetime.signal }))) current() if (result.scheduleID !== input.data.scheduleID || result.requestID !== input.data.requestID || result.expectedRevision !== input.data.expectedRevision - || !sameLocation(result.location, location) || !await lifetime.wait(deps.manager.ownsLocation(request.params.id, location, connection.client, lifetime.signal))) throw new Error("Foreign manual status") + || !sameLocation(result.location, location) || !await lifetime.wait(deps.manager.ownsLocation(request.params.id, location, connection.client, { signal: lifetime.signal }))) throw new Error("Foreign manual status") current() if (result.outcome !== "unknown") { const owner = recurrenceControlHeldElsewhere(deps.fence, request.params.id, identity, connection) diff --git a/packages/server/src/server/routes/mission-recurrence-play-preparation.ts b/packages/server/src/server/routes/mission-recurrence-play-preparation.ts index 6bf960bbbf..8be6ad91b5 100644 --- a/packages/server/src/server/routes/mission-recurrence-play-preparation.ts +++ b/packages/server/src/server/routes/mission-recurrence-play-preparation.ts @@ -49,12 +49,12 @@ export async function prepareHumanRecurrenceControl(request: FastifyRequest, wor return true } const client = connection.client - if (!await deps.manager.ownsLocation(workspaceID, { directory }, client, signal)) throw new Error("Location is not owned") + if (!await deps.manager.ownsLocation(workspaceID, { directory }, client, { signal })) throw new Error("Location is not owned") const location = await client.location.get({ location: { directory } }, { signal }) const baseInfo = await client.location.get({ location: { directory: base.directory } }, { ...locationRequestOptions(base), signal }) current() if (location.project.id !== baseInfo.project.id || location.project.canonical !== baseInfo.project.canonical - || !sameLocation(location, { directory }) || !await deps.manager.ownsLocation(workspaceID, location, client, signal)) throw new Error("Foreign native Location") + || !sameLocation(location, { directory }) || !await deps.manager.ownsLocation(workspaceID, location, client, { signal })) throw new Error("Foreign native Location") const checkout = await deps.manager.getWorktreeIdentityForPath(workspaceID, directory) if (!checkout) throw new Error("Checkout unavailable") const physicalRoot = await resolveRecurrenceRoot(deps.manager, workspaceID, directory, location.project.canonical, distro) @@ -95,7 +95,7 @@ export async function prepareHumanRecurrenceControl(request: FastifyRequest, wor current() if (await deps.manager.getWorktreeIdentityForPath(workspaceID, directory) !== checkout || canonicalAuthority(await resolveRecurrenceRoot(deps.manager, workspaceID, directory, location.project.canonical, distro)) !== canonicalAuthority(physicalRoot) - || !await deps.manager.ownsLocation(workspaceID, location, client, signal)) throw new Error("Physical root changed") + || !await deps.manager.ownsLocation(workspaceID, location, client, { signal })) throw new Error("Physical root changed") current() } const yaml = deps.settings.configYamlPathForAuthority(), executionHost = distro ? `wsl:${distro}` : "local" diff --git a/packages/server/src/server/routes/mission-recurrence-proof.ts b/packages/server/src/server/routes/mission-recurrence-proof.ts index aa0b27887f..1ae839aeea 100644 --- a/packages/server/src/server/routes/mission-recurrence-proof.ts +++ b/packages/server/src/server/routes/mission-recurrence-proof.ts @@ -62,7 +62,7 @@ export async function verifyHumanRecurrenceRequest(input: unknown, deps: { const distro = deps.manager.getServiceWslDistro(body.workspaceID) if (body.profileSource.executionHost !== (distro ? `wsl:${distro}` : "local")) throw new Error("Recurrence execution host changed") const connection = await deps.manager.getSharedServiceConnection(body.workspaceID) - if (!workspace || !connection || !await deps.manager.ownsLocation(body.workspaceID, body.location, connection.client, signal)) throw new Error("Recurrence owner unavailable") + if (!workspace || !connection || !await deps.manager.ownsLocation(body.workspaceID, body.location, connection.client, { signal })) throw new Error("Recurrence owner unavailable") const location = await connection.client.location.get({ location: { directory: body.location.directory } }, { signal }) connection.assertCurrent(); signal.throwIfAborted() if (!sameLocation(location, body.location) || deps.manager.get(body.workspaceID) !== workspace diff --git a/packages/server/src/server/routes/mission-recurrence-reader.test.ts b/packages/server/src/server/routes/mission-recurrence-reader.test.ts index a617ae3ab9..8cc4c8a7a4 100644 --- a/packages/server/src/server/routes/mission-recurrence-reader.test.ts +++ b/packages/server/src/server/routes/mission-recurrence-reader.test.ts @@ -176,7 +176,7 @@ test("sealed native archived reader preserves exact paged Markdown, report/evide assert.ok(page.sections.length <= 32) assert.equal(f.validateOutput(page), true) const output = JSON.stringify(page) - for (const secret of ["PRIVATE_STANDING_PROMPT", "private_model", "private_provider", "private_agent", "private_profile", "private_host", "ses_private_watch", "profiles", "publication", "consigne"]) assert.ok(!output.includes(secret), secret) + for (const secret of ["PRIVATE_STANDING_PROMPT", "private_model", "private_provider", "private_agent", "private_profile", "private_host", "ses_private_watch", '"profiles":', '"publication":', '"consigne":']) assert.ok(!output.includes(secret), secret) } if (section.text === f.finalSummary) { assert.equal(pages[0].sourceText.length, 8_999, "do not split an astral character at a page boundary") diff --git a/packages/server/src/server/routes/mission-root-creation.ts b/packages/server/src/server/routes/mission-root-creation.ts index 901912094a..5f6dcc7092 100644 --- a/packages/server/src/server/routes/mission-root-creation.ts +++ b/packages/server/src/server/routes/mission-root-creation.ts @@ -30,7 +30,7 @@ export async function createManagedMissionRoot(manager: Manager, fence: Worktree if (!connection) throw new Error("Workspace unavailable") const coordinator = await connection.client.session.get({ sessionID: coordinatorID }, { signal }) if (coordinator.id !== coordinatorID || coordinator.parentID - || !await manager.ownsLocation(workspace.id, coordinator.location, connection.client, signal)) throw new Error("Foreign coordinator") + || !await manager.ownsLocation(workspace.id, coordinator.location, connection.client, { signal })) throw new Error("Foreign coordinator") return { workspace, connection, coordinator } })).catch(() => undefined) if (!owner) throw new Error("Missing mission creation owner") diff --git a/packages/server/src/server/routes/mission-scheduled.ts b/packages/server/src/server/routes/mission-scheduled.ts index 905d4c729a..3c48e0e051 100644 --- a/packages/server/src/server/routes/mission-scheduled.ts +++ b/packages/server/src/server/routes/mission-scheduled.ts @@ -166,7 +166,7 @@ export function registerMissionScheduled(app: FastifyInstance, deps: Deps) { }, refresh: async () => { check(owned) - if (!await manager.ownsLocation(selected.data.id, location, client, lifetime.signal)) throw new Error("Mission schedule Location changed") + if (!await manager.ownsLocation(selected.data.id, location, client, { signal: lifetime.signal })) throw new Error("Mission schedule Location changed") const owner = await readRecurrenceHoldOwner(manager, selected.data.id, workspace, location.directory, client, lifetime.signal) check(owned) if (!owner) throw new Error("Mission schedule physical owner unavailable") diff --git a/packages/server/src/server/routes/panel-extension-api4.ts b/packages/server/src/server/routes/panel-extension-api4.ts index 730870f8a8..eec7263328 100644 --- a/packages/server/src/server/routes/panel-extension-api4.ts +++ b/packages/server/src/server/routes/panel-extension-api4.ts @@ -107,7 +107,7 @@ export function registerPanelExtensionApi4Routes(app: FastifyInstance, deps: Pan /** The session, when its Location belongs to the workspace. */ const ownedSession = async (instanceId: string, client: OpenCodeClient, sessionID: string, signal: AbortSignal) => { const session = await client.session.get({ sessionID }, { signal: bounded(signal) }) - if (!await manager.ownsLocation(instanceId, session.location, client, signal)) throw new Refused(403) + if (!await manager.ownsLocation(instanceId, session.location, client, { signal })) throw new Refused(403) return session } /** Fences the answer on the session still being owned at the same Location after every read. */ @@ -118,7 +118,7 @@ export function registerPanelExtensionApi4Routes(app: FastifyInstance, deps: Pan }) const fenceLocation = (context: RouteContext, instanceId: string, client: OpenCodeClient, directory: string) => context.fence(`location:${directory}`, async () => { - if (!await manager.ownsLocation(instanceId, { directory }, client, context.signal)) throw new Refused(403) + if (!await manager.ownsLocation(instanceId, { directory }, client, { signal: context.signal })) throw new Refused(403) }) const sessionRpc = async (context: RouteContext, instanceId: string, sessionID: string, method: string, input: Record) => { const connection = await connect(instanceId) @@ -152,7 +152,7 @@ export function registerPanelExtensionApi4Routes(app: FastifyInstance, deps: Pan const client = connection.client const session = input.sessionID ? await ownedSession(input.instanceId, client, input.sessionID, context.signal) : undefined const location = session ? readLocationRef(session.location) : input.directory ? { directory: input.directory } : undefined - if (!location || !await manager.ownsLocation(input.instanceId, location, client, context.signal)) throw new Refused(403) + if (!location || !await manager.ownsLocation(input.instanceId, location, client, { signal: context.signal })) throw new Refused(403) if (input.sessionID) fenceSession(context, input.instanceId, client, input.sessionID, location) else fenceLocation(context, input.instanceId, client, location.directory) return readPanelImagesStatus({ imageSettings: deps.imageSettings, client }, input.instanceId, location, session, bounded(context.signal)) diff --git a/packages/server/src/server/routes/pending-requests.ts b/packages/server/src/server/routes/pending-requests.ts index bf344c0d36..057fb50a3e 100644 --- a/packages/server/src/server/routes/pending-requests.ts +++ b/packages/server/src/server/routes/pending-requests.ts @@ -352,7 +352,7 @@ export function registerPendingRequestRoutes(app: FastifyInstance, deps: Pending // capability verification; malformed native data above fails the batch. const owned = await (async () => snapshot.location.workspaceID === undefined && nativePath.isAbsolute(snapshot.location.directory) && await manager.getServiceDirectoryForPath(id, snapshot.location.directory) === entry.directory - && await manager.ownsLocation(id, snapshot.location, connection.client, signal))().catch((error) => { + && await manager.ownsLocation(id, snapshot.location, connection.client, { signal }))().catch((error) => { isolate(error) return undefined }) diff --git a/packages/server/src/server/routes/provider-accounts.ts b/packages/server/src/server/routes/provider-accounts.ts index cd7d0500d5..91e149c25e 100644 --- a/packages/server/src/server/routes/provider-accounts.ts +++ b/packages/server/src/server/routes/provider-accounts.ts @@ -33,7 +33,7 @@ export function registerProviderAccountsRoutes(app: FastifyInstance, deps: Deps) const connection = await manager.getSharedServiceConnection(id) if (!connection) return reply.code(503).send({ error: "Provider accounts unavailable" }) const directory = await manager.getServiceDirectoryForPath(id, input.data.directory) - if (!directory || !await manager.ownsLocation(id, { directory }, connection.client, signal)) { + if (!directory || !await manager.ownsLocation(id, { directory }, connection.client, { signal })) { return reply.code(403).send({ error: "Location does not belong to workspace" }) } if (method === "PUT") { @@ -43,7 +43,7 @@ export function registerProviderAccountsRoutes(app: FastifyInstance, deps: Deps) if (!release) return reply.code(409).send({ error: "Worktree deletion in progress" }) } const snapshot = await deps.accounts.snapshot(connection, directory, integrationID, signal) - if (manager.get(id) !== workspace || !await manager.ownsLocation(id, { directory }, connection.client, signal)) { + if (manager.get(id) !== workspace || !await manager.ownsLocation(id, { directory }, connection.client, { signal })) { return reply.code(403).send({ error: "Location does not belong to workspace" }) } signal.throwIfAborted(); connection.assertCurrent() diff --git a/packages/server/src/server/routes/session-goal.ts b/packages/server/src/server/routes/session-goal.ts index aa654e5b61..0d91d4f856 100644 --- a/packages/server/src/server/routes/session-goal.ts +++ b/packages/server/src/server/routes/session-goal.ts @@ -40,7 +40,7 @@ export function registerSessionGoalRoute(app: FastifyInstance, deps: SessionGoal const session = await client.session.get({ sessionID }, { signal }).catch(() => undefined) if (!session) return reply.code(404).send({ error: "Session not found" }) const location = readLocationRef(session.location) - if (!await manager.ownsLocation(request.params.id, location, client, signal)) return reply.code(403).send({ error: "Session does not belong to workspace" }) + if (!await manager.ownsLocation(request.params.id, location, client, { signal })) return reply.code(403).send({ error: "Session does not belong to workspace" }) let result: SessionGoalResponse try { const response = await client.rpc.call({ rpcID: GOAL_RPC_ID, method: "get", input: { sessionID }, location: { directory: location.directory } }, diff --git a/packages/server/src/server/routes/session-history-ranked.ts b/packages/server/src/server/routes/session-history-ranked.ts index 5231b30d8d..85770fdae5 100644 --- a/packages/server/src/server/routes/session-history-ranked.ts +++ b/packages/server/src/server/routes/session-history-ranked.ts @@ -44,7 +44,7 @@ export function registerRankedHistoryRoute(app: FastifyInstance, deps: HistoryRo } current() await manager.desktopPluginsReady(); current() - if (!await manager.ownsLocation(id, base, client, signal)) return reply.code(403).send({ error: "History location does not belong to workspace" }) + if (!await manager.ownsLocation(id, base, client, { signal })) return reply.code(403).send({ error: "History location does not belong to workspace" }) current() if (unsupported.has(connection)) return { status: "unsupported" } const directories = await historyDirectories(manager, id, base.directory); current() @@ -69,7 +69,7 @@ export function registerRankedHistoryRoute(app: FastifyInstance, deps: HistoryRo if (continuation && !cursor) continue const location = directory === base.directory ? base : readLocationRef(await client.location.get({ location: { directory } }, { ...locationRequestOptions({ directory }), signal })) current() - if (location.directory !== directory || !await manager.ownsLocation(id, location, client, signal)) return reply.code(403).send({ error: "History location does not belong to workspace" }) + if (location.directory !== directory || !await manager.ownsLocation(id, location, client, { signal })) return reply.code(403).send({ error: "History location does not belong to workspace" }) current() let response try { @@ -120,7 +120,7 @@ export function registerRankedHistoryRoute(app: FastifyInstance, deps: HistoryRo const sessions = await ownedHistorySessions(manager, id, client, [...owners.values()], undefined, current, signal) if (sessions.length !== owners.size) exclusions.add("foreign_directory") const finalIDs = new Set(sessions.map(owner => owner.sessionID)) - if (!await manager.ownsLocation(id, base, client, signal)) throw new Error("History ownership changed") + if (!await manager.ownsLocation(id, base, client, { signal })) throw new Error("History ownership changed") current() const scanned = sessions.reduce((sum, owner) => sum + owner.scanned, 0) const examinedBefore = continuation?.examined ?? 0 diff --git a/packages/server/src/server/routes/session-history-scope.ts b/packages/server/src/server/routes/session-history-scope.ts index ce14df08fd..19cd1c0c6a 100644 --- a/packages/server/src/server/routes/session-history-scope.ts +++ b/packages/server/src/server/routes/session-history-scope.ts @@ -19,7 +19,7 @@ export async function ownedHistorySessions { `ownership at ${foregroundIndex} waited behind all display reads (last at ${lastDisplayIndex})`) }) }) + +test("strict common-directory rejection retains both admitted filesystem reads until settlement", async t => { + const failure = new Error("unreadable ownership probe") + let release!: () => void + const held = new Promise((_resolve, reject) => { release = () => reject(new Error("second probe settled")) }) + const original = fs.realpath + const mock = t.mock.method(fs, "realpath", ((directory: string, ...args: unknown[]) => { + if (directory === "unreadable-probe") return Promise.reject(failure) + if (directory === "held-probe") return held + return (original as (...args: unknown[]) => unknown)(directory, ...args) + }) as typeof fs.realpath) + syncBuiltinESMExports() + try { + let settled = false + const read = sharesGitCommonDirectory("unreadable-probe", "held-probe", { strict: true }) + .finally(() => { settled = true }) + const rejected = assert.rejects(read, error => error === failure) + await new Promise(resolve => setImmediate(resolve)) + assert.equal(settled, false, "the first error cannot release custody of the second read") + release() + await rejected + } finally { + release() + mock.mock.restore() + syncBuiltinESMExports() + } +}) diff --git a/packages/server/src/workspaces/__tests__/native-worktree-fallback.test.ts b/packages/server/src/workspaces/__tests__/native-worktree-fallback.test.ts new file mode 100644 index 0000000000..ad4494b198 --- /dev/null +++ b/packages/server/src/workspaces/__tests__/native-worktree-fallback.test.ts @@ -0,0 +1,102 @@ +import assert from "node:assert/strict" +import { execFileSync } from "node:child_process" +import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises" +import { tmpdir } from "node:os" +import path from "node:path" +import test from "node:test" + +test("native inventory preserves root fallback while strict readers reject unverified discovery, including cached reads", async t => { + const parent = process.platform === "win32" ? path.join(tmpdir(), "opencode") : tmpdir() + await mkdir(parent, { recursive: true }) + const root = await mkdtemp(path.join(parent, "native-worktree-fallback-")) + t.after(() => rm(root, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 })) + const repo = path.join(root, "repo"), linked = path.join(root, "linked") + const nonGit = path.join(root, "non-git"), broken = path.join(root, "broken") + const marker = path.join(root, "marker"), missingAdmin = path.join(root, "missing-admin") + const nested = path.join(repo, "nested") + const emptyPath = path.join(root, "empty-path") + for (const directory of [nonGit, broken, marker, missingAdmin, emptyPath]) await mkdir(directory) + await writeFile(path.join(broken, ".git"), "invalid pointer\n") + await writeFile(path.join(marker, "HEAD"), "stray marker\n") + await writeFile(path.join(missingAdmin, ".git"), "gitdir: missing\n") + const env = Object.fromEntries(Object.entries(process.env).filter(([key]) => !/^GIT_/i.test(key))) + Object.assign(env, { GIT_CONFIG_NOSYSTEM: "1", GIT_CONFIG_GLOBAL: path.join(root, "private-gitconfig"), GIT_CONFIG_COUNT: "0" }) + const git = (...args: string[]) => execFileSync("git", args, { env, windowsHide: true, stdio: "pipe" }) + git("init", "--initial-branch=main", repo) + git("-C", repo, "-c", "user.name=Test", "-c", "user.email=test@example.invalid", "commit", "--allow-empty", "-m", "fixture") + git("-C", repo, "worktree", "add", "--detach", linked) + await mkdir(nested) + const module = (relative: string) => JSON.stringify(new URL(relative, import.meta.url).href) + const script = ` + import assert from "node:assert/strict" + import { execFileSync } from "node:child_process" + import pino from "pino" + import { listNativeWorktrees } from ${module("../native-worktrees.ts")} + import { sharesGitCommonDirectory } from ${module("../git-worktrees.ts")} + import { WorkspaceManager } from ${module("../manager.ts")} + import { EventBus } from ${module("../../events/bus.ts")} + import { resolveOwnedWorktreePath, invalidateWorktreeCache } from ${module("../worktree-directory.ts")} + const { repo, linked, nonGit, broken, marker, missingAdmin, nested } = ${JSON.stringify({ repo, linked, nonGit, broken, marker, missingAdmin, nested })} + const ceiling = Boolean(process.env.GIT_CEILING_DIRECTORIES) + const missingGit = !ceiling && process.env.GIT_TEST_ASSUME_DIFFERENT_OWNER !== "1" + assert.throws(() => execFileSync("git", ["-C", ceiling ? nested : repo, "rev-parse", "--show-toplevel"], { windowsHide: true, stdio: "pipe" }), + error => missingGit ? error.code === "ENOENT" : ceiling ? /not a git repository/.test(String(error.stderr)) : /dubious ownership/.test(String(error.stderr))) + const context = workspacePath => ({ client: {}, workspacePath, location: { directory: workspacePath }, toHost: async directory => directory }) + const expectedError = /Git ownership inventory unavailable/ + for (const folder of [ceiling ? nested : repo, broken, marker, missingAdmin]) { + const inventory = await listNativeWorktrees(context(folder)) + assert.deepEqual(inventory, { + ...(missingGit ? { gitAvailable: false } : { isGitRepo: false }), + worktrees: [{ slug: "root", directory: folder, serviceDirectory: folder, kind: "root", + ...(missingGit ? { directoryOnly: true } : {}) }], + }) + let reads = 0 + const params = { workspaceId: folder, workspacePath: folder, directory: folder, + loadWorktrees: async () => { reads++; return inventory.worktrees } } + assert.equal((await resolveOwnedWorktreePath(params)).slug, "root") + for (let i = 0; i < 2; i++) await assert.rejects(resolveOwnedWorktreePath({ ...params, strict: true }), expectedError) + assert.equal(reads, 1, "strict readers qualify cached fallback without changing the public inventory") + if (folder === (ceiling ? nested : repo)) { + assert.equal(Boolean(await resolveOwnedWorktreePath({ ...params, directory: folder + "/child" })), !missingGit) + } + invalidateWorktreeCache(folder) + } + assert.deepEqual(await listNativeWorktrees(context(nonGit)), { + ...(missingGit ? { gitAvailable: false } : { isGitRepo: false }), + worktrees: [{ slug: "root", directory: nonGit, serviceDirectory: nonGit, kind: "root", + ...(missingGit ? { directoryOnly: true } : {}) }], + }) + if (!ceiling) assert.equal(await sharesGitCommonDirectory(repo, linked, { strict: true }), true) + else await assert.rejects(sharesGitCommonDirectory(repo, linked, { strict: true }), /Git discovery is configured/) + const manager = new WorkspaceManager({ rootDir: repo, + settings: { getOwner: () => ({ environmentVariables: {} }) }, + binaryResolver: { resolveDefault: () => ({ path: process.execPath, label: "fixture" }) }, + eventBus: new EventBus(), logger: pino({ level: "silent" }), + sharedService: { headers: async () => ({}), client: async () => ({}), shutdown: async () => {}, + validateLocation: async location => ({ ...location, project: { id: "fixture", directory: repo, canonical: repo } }) }, + }) + try { + const { workspace } = await manager.create(ceiling ? nested : repo) + assert.equal(await manager.ownsLocation(workspace.id, { directory: workspace.path }, undefined, { strict: true }), true) + for (const purpose of ["request", "event"]) for (const strict of [true, false, true]) { + const ownership = manager.ownsLocation(workspace.id, { directory: linked }, undefined, { purpose, strict }) + if (!strict) assert.equal(await ownership, false) + else await assert.rejects(ownership, ceiling ? /Git discovery is configured/ : expectedError) + } + } finally { await manager.shutdown() } + console.log("PASS " + (missingGit ? "missing Git" : ceiling ? "GIT_CEILING_DIRECTORIES" : "unsafe-directory fallback")) + ` + for (const mode of ["unsafe", "missing", "ceiling"]) { + const privateEnv = { ...env } + if (mode === "missing") { + for (const key of Object.keys(privateEnv)) if (key.toLowerCase() === "path") delete privateEnv[key] + privateEnv.PATH = emptyPath + } else if (mode === "ceiling") privateEnv.GIT_CEILING_DIRECTORIES = repo + else privateEnv.GIT_TEST_ASSUME_DIFFERENT_OWNER = "1" + const output = execFileSync(process.execPath, ["--import", "tsx", "--input-type=module", "-e", script], { + env: privateEnv, windowsHide: true, encoding: "utf8", timeout: 20_000, stdio: "pipe", + }) + assert.match(output, /PASS/) + t.diagnostic(output.trim()) + } +}) diff --git a/packages/server/src/workspaces/git-common-directory.ts b/packages/server/src/workspaces/git-common-directory.ts index bd297c794a..e67cbf1b77 100644 --- a/packages/server/src/workspaces/git-common-directory.ts +++ b/packages/server/src/workspaces/git-common-directory.ts @@ -1,7 +1,7 @@ import { realpath } from "node:fs/promises" import { runWorktreeGit } from "./git-process" import { readCheckoutCommonDirectory } from "../opencode/session-pruning/checkout-identity" -export { readCheckoutIdentity, gitLocationOverridden } from "../opencode/session-pruning/checkout-identity" +export { readCheckoutIdentity, discoverCheckoutCommonDirectory, gitLocationOverridden } from "../opencode/session-pruning/checkout-identity" const pending = new Map>() diff --git a/packages/server/src/workspaces/git-worktrees.ts b/packages/server/src/workspaces/git-worktrees.ts index e89e0b4b40..4c25b55a4e 100644 --- a/packages/server/src/workspaces/git-worktrees.ts +++ b/packages/server/src/workspaces/git-worktrees.ts @@ -1,6 +1,6 @@ import path from "node:path" import { readFile, realpath, stat } from "node:fs/promises" -import { gitLocationOverridden, readGitCommonDirectory } from "./git-common-directory" +import { discoverCheckoutCommonDirectory, gitLocationOverridden, readGitCommonDirectory } from "./git-common-directory" export { readCheckoutIdentity } from "./git-common-directory" import { runWorktreeGit as git } from "./git-process" import { GitRequiredError } from "./git-requirement" @@ -27,11 +27,18 @@ export async function isGitAvailable(folder: string): Promise { // A different physical common directory cannot belong to this local repository, // even when independent clones share OpenCode's project ID. This is only a // negative preflight; a match still requires the native worktree inventory. -export async function sharesGitCommonDirectory(left: string, right: string): Promise { +export async function sharesGitCommonDirectory(left: string, right: string, { strict = false } = {}): Promise { try { - const [a, b] = await Promise.all([readGitCommonDirectory(left), readGitCommonDirectory(right)]) - return a === b - } catch { return false } + // Strict discovery preserves verified absence separately from ambiguous/read failures. + const read = strict ? discoverCheckoutCommonDirectory : readGitCommonDirectory + const [a, b] = await Promise.allSettled([read(left), read(right)]) + if (a.status === "rejected") throw a.reason + if (b.status === "rejected") throw b.reason + return a.value !== undefined && a.value === b.value + } catch (error) { + if (strict) throw error + return false + } } // Git annotations and branch policy, not another worktree registry. Native diff --git a/packages/server/src/workspaces/instance-event-ownership.test.ts b/packages/server/src/workspaces/instance-event-ownership.test.ts index 7f6084a8a6..2f33f65c47 100644 --- a/packages/server/src/workspaces/instance-event-ownership.test.ts +++ b/packages/server/src/workspaces/instance-event-ownership.test.ts @@ -115,7 +115,7 @@ test("registered-only event ownership retains clone, nested-folder, alias and in assert.equal(await owns(linked), false, "a nested opening must not grant the whole sibling checkout") assert.equal(await owns(path.join(clone, "nested")), false, "native project IDs cannot authorize an independent physical clone") assert.equal(refreshes, 0) - assert.equal(await manager.getServiceDirectoryForPath(workspace.id, path.join(alias, "nested"), "event"), realpathSync(path.join(linked, "nested"))) + assert.equal(await manager.getServiceDirectoryForPath(workspace.id, path.join(alias, "nested"), { purpose: "event" }), realpathSync(path.join(linked, "nested"))) // Even if the files remain present, removal from the native registration is // sufficient to revoke membership after a worktree event/mutation fence. registered = [repo, clone] @@ -169,13 +169,13 @@ test("cold registered-only ownership after cancellation never acquires or provis const cancelled = new AbortController() cancelled.abort(new Error("cancelled observation")) const target = path.join(linked, "nested") - await assert.rejects(manager.ownsLocation(workspace.id, { directory: target }, undefined, cancelled.signal, "event"), /cancelled observation/) - assert.equal(await manager.ownsLocation(workspace.id, { directory: target }, undefined, undefined, "event"), true) + await assert.rejects(manager.ownsLocation(workspace.id, { directory: target }, undefined, { signal: cancelled.signal, purpose: "event" }), /cancelled observation/) + assert.equal(await manager.ownsLocation(workspace.id, { directory: target }, undefined, { purpose: "event" }), true) assert.equal(await manager.getWorktreeIdentityForPath(workspace.id, target, "event"), canonicalWorktreeIdentity(linked)) assert.deepEqual([discoveries, starts, preparations, constructions, refreshes], [1, 0, 1, 1, 0]) service.invalidate() manager.invalidateWorktrees("blocking") - await assert.rejects(manager.ownsLocation(workspace.id, { directory: target }, undefined, undefined, "event"), /no existing connection/) + await assert.rejects(manager.ownsLocation(workspace.id, { directory: target }, undefined, { purpose: "event" }), /no existing connection/) await assert.rejects(manager.getWorktreeIdentityForPath(workspace.id, target, "event"), /no existing connection/) assert.throws(connection.assertCurrent, /connection changed/) assert.deepEqual([discoveries, starts, preparations, constructions, refreshes], [1, 0, 1, 1, 0]) diff --git a/packages/server/src/workspaces/instance-events.ts b/packages/server/src/workspaces/instance-events.ts index 94831a28b6..0760bea510 100644 --- a/packages/server/src/workspaces/instance-events.ts +++ b/packages/server/src/workspaces/instance-events.ts @@ -355,7 +355,7 @@ export class InstanceEventBridge { const resolve = () => location.workspaceID === undefined ? this.options.workspaceManager.ownsDirectory(instanceId, location.directory, "event") - : this.options.workspaceManager.ownsLocation(instanceId, location, undefined, signal, "event") + : this.options.workspaceManager.ownsLocation(instanceId, location, undefined, { signal, purpose: "event" }) const owns = Promise.resolve().then(resolve).catch(() => current() ? resolve() : false) const entry = { expiresAt: Number.POSITIVE_INFINITY, owns } this.locationOwners.set(key, entry) diff --git a/packages/server/src/workspaces/manager.test.ts b/packages/server/src/workspaces/manager.test.ts index 9419097666..0c34094e26 100644 --- a/packages/server/src/workspaces/manager.test.ts +++ b/packages/server/src/workspaces/manager.test.ts @@ -1,7 +1,7 @@ import assert from "node:assert/strict" import os from "node:os" import path from "node:path" -import { mkdir, mkdtemp, realpath, rm } from "node:fs/promises" +import { mkdir, mkdtemp, realpath, rm, writeFile } from "node:fs/promises" import { describe, it } from "node:test" import { execFileSync } from "node:child_process" import type { LocationRef, OpenCodeClient, OpenCodeEvent } from "@opencode/client" @@ -192,9 +192,11 @@ describe("workspace manager shared service lifecycle", () => { } assert.equal(await manager.ownsDirectory(workspace.id, clone), false) assert.equal(await manager.ownsLocation(workspace.id, { directory: clone }), false) + assert.equal(await manager.ownsLocation(workspace.id, { directory: clone }, undefined, { strict: true }), false) assert.equal(scans, 0) assert.equal(await manager.ownsDirectory(workspace.id, linked), true) assert.equal(scans, 1) + assert.equal(await manager.ownsLocation(workspace.id, { directory: linked }, undefined, { strict: true }), true) let registered = [repo, linked] let refreshes = 0 const client = { @@ -217,7 +219,7 @@ describe("workspace manager shared service lifecycle", () => { assert.equal(await manager.getWorktreeIdentityForPath(workspace.id, linked, "event"), undefined) assert.equal(refreshes, 0, "event identity must remain registered-only after invalidation") assert.equal(scans, 1) - } finally { await manager.shutdown(); await rm(root, { recursive: true, force: true }) } + } finally { await manager.shutdown(); await rm(root, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }) } }) it("owns a checkout of another repository nested inside the opened folder, under the root's identity", async () => { @@ -247,11 +249,55 @@ describe("workspace manager shared service lifecycle", () => { service.client = async () => client // Pending recovery follows this ownership; it must match prompts and live events. for (const purpose of ["request", "event"] as const) { - assert.equal(await manager.ownsLocation(workspace.id, { directory: nested }, undefined, undefined, purpose), true) - assert.equal(await manager.getServiceDirectoryForPath(workspace.id, nested, purpose), await realpath(nested)) + assert.equal(await manager.ownsLocation(workspace.id, { directory: nested }, undefined, { purpose }), true) + assert.equal(await manager.getServiceDirectoryForPath(workspace.id, nested, { purpose }), await realpath(nested)) assert.equal(await manager.getWorktreeIdentityForPath(workspace.id, nested, purpose), canonicalWorktreeIdentity(await realpath(repo))) } - } finally { await manager.shutdown(); await rm(root, { recursive: true, force: true }) } + } finally { await manager.shutdown(); await rm(root, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }) } + }) + + it("distinguishes proven unrelated ownership from physical and Git identity read failures", async () => { + const temp = await mkdtemp(path.join(os.tmpdir(), "codenomad-strict-owner-")) + const root = path.join(temp, "repo") + const unrelated = path.join(temp, "unrelated") + const { manager } = createHarness() + try { + execFileSync("git", ["init", root], { stdio: "pipe", windowsHide: true }) + await mkdir(unrelated) + const { workspace } = await manager.create(root) + manager.getWorktrees = async () => { throw new Error("unexpected ownership expansion") } + const owns = (directory: string, strict = true) => manager.ownsLocation(workspace.id, { directory }, undefined, { strict }) + assert.equal(await owns(root), true) + assert.equal(await owns(unrelated), false, "absence of a checkout is a proven negative") + await assert.rejects(owns(path.join(temp, "missing")), { code: "ENOENT" }) + await writeFile(path.join(root, ".git", "commondir"), "missing-common-directory\n") + assert.equal(await owns(unrelated, false), false, "ordinary boolean consumers retain their fallback") + await assert.rejects(owns(unrelated), { code: "ENOENT" }) + } finally { await manager.shutdown(); await rm(temp, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }) } + }) + + it("rejects failed WSL host and service translations in strict ownership reads", async () => { + let translateHost = true + let translateService = true + const { manager } = createHarness(new ControlledSharedService(), { + platform: "win32", + binaryResolver: { resolveDefault: () => ({ path: String.raw`\\wsl.localhost\Ubuntu\home\dev\opencode`, label: "OpenCode V2" }) }, + wslServiceDirectoryResolver: () => translateService ? "/mnt/d/workspace" : null, + wslHostDirectoryResolver: () => translateHost ? process.cwd() : null, + wslServiceLifecycleFactory: () => ({ discover: async () => undefined, ensure: async () => ({ url: "http://127.0.0.1:4321" }) }), + }) + try { + const { workspace } = await manager.create(process.cwd()) + const owns = (strict: boolean) => manager.ownsLocation(workspace.id, { directory: "/mnt/d/workspace" }, undefined, { strict }) + assert.equal(await owns(true), true) + translateHost = false + assert.equal(await owns(false), false) + await assert.rejects(owns(true), /WSL host directory translation unavailable/) + translateHost = true + translateService = false + assert.equal(await owns(false), false) + await assert.rejects(owns(true), /WSL service directory translation unavailable/) + } finally { await manager.shutdown() } }) it("validates native directory ownership and rejects removed workspace selectors", async () => { @@ -685,7 +731,7 @@ describe("workspace manager shared service lifecycle", () => { await assert.rejects(() => harness.manager.reserveWorktreeDeletion(worktree), /open as another workspace/) await harness.manager.delete(workspace.id) } finally { - await rm(temp, { recursive: true, force: true }) + await rm(temp, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }) } }) diff --git a/packages/server/src/workspaces/manager.ts b/packages/server/src/workspaces/manager.ts index 4c059069ff..9d4f093cc9 100644 --- a/packages/server/src/workspaces/manager.ts +++ b/packages/server/src/workspaces/manager.ts @@ -46,6 +46,17 @@ const MAX_ACTIVE_WORKSPACE_CREATIONS = 32 const WORKSPACE_STATE = Symbol("workspaceState") type ManagerTimeout = number | NodeJS.Timeout +async function ownershipRealpath(directory: string, strict = false): Promise { + try { return await realpath(directory) } + catch (error) { if (strict) throw error } +} + +interface LocationOwnershipOptions { + signal?: AbortSignal + purpose?: "request" | "event" + strict?: boolean +} + interface SharedService { acquire?: () => Promise existingConnection?: () => import("./opencode-service").ServiceConnection | undefined @@ -296,35 +307,36 @@ export class WorkspaceManager { return Boolean(hostDirectory && await this.ownsHostDirectory(record, hostDirectory, purpose)) } - // `_client` is retained for callers' pinned-connection signature; directory - // ownership needs no native request. - async ownsLocation(id: string, location: LocationRef, _client?: OpenCodeClient, signal?: AbortSignal, purpose: "request" | "event" = "request"): Promise { + // Strict probes reject unreadable ownership instead of turning it into a negative. + async ownsLocation(id: string, location: LocationRef, _client?: OpenCodeClient, { signal, purpose = "request", strict = false }: LocationOwnershipOptions = {}): Promise { signal?.throwIfAborted() // OpenCode V2 identifies locations by directory; a retired workspace selector // is never authorized, whatever directory it names. if (location.workspaceID !== undefined) return false const record = this.workspaces.get(id) if (!record?.[WORKSPACE_STATE].published) return false - const directory = await this.getServiceDirectoryForPath(id, location.directory, purpose) + const directory = await this.getServiceDirectoryForPath(id, location.directory, { purpose, strict }) signal?.throwIfAborted() return Boolean(directory) } - async getServiceDirectoryForPath(id: string, directory: string, purpose: "request" | "event" = "request"): Promise { + async getServiceDirectoryForPath(id: string, directory: string, { purpose = "request", strict = false }: Pick = {}): Promise { const record = this.workspaces.get(id) if (!record?.[WORKSPACE_STATE].published) return undefined // Directory authorization does not need the checkout's Git mutation identity. // Resolve aliases against the explicitly opened folder without spawning Git. if (!record.wslDistro) { const [target, root] = await Promise.all([ - realpath(directory).catch(() => undefined), realpath(record.path).catch(() => undefined), + ownershipRealpath(directory, strict), ownershipRealpath(record.path, strict), ]) if (target && target === root) return target } - const owned = await this.resolveOwnedWorktree(record, directory, purpose) + const owned = await this.resolveOwnedWorktree(record, directory, purpose, strict) if (!owned) return undefined if (!record.wslDistro) return owned.directory - return await this.resolveWslServiceDirectory(owned.directory, record.wslDistro, DEFAULT_LAUNCH_TIMEOUT_MS) ?? undefined + const translated = await this.resolveWslServiceDirectory(owned.directory, record.wslDistro, DEFAULT_LAUNCH_TIMEOUT_MS) + if (strict && !translated) throw new Error("WSL service directory translation unavailable") + return translated ?? undefined } async getWorktreeIdentityForPath(id: string, directory: string, purpose: "request" | "event" = "request"): Promise { @@ -410,11 +422,11 @@ export class WorkspaceManager { now: () => this.now(), }) - private async ownershipWorktrees(id: string, refresh: boolean | undefined, purpose: "request" | "event") { + private async ownershipWorktrees(id: string, refresh: boolean | undefined, purpose: "request" | "event", strict = false) { const mode = refresh ? "fresh" : "validated" return (await (purpose === "event" - ? this.eventWorktreeInventory.read(id, mode) - : this.getWorktrees(id, mode))).worktrees + ? this.eventWorktreeInventory.read(id, mode, { strict }) + : strict ? this.worktreeInventory.read(id, mode, { strict }) : this.getWorktrees(id, mode))).worktrees } invalidateWorktrees(mode: "lazy" | "blocking" = "lazy"): void { @@ -444,7 +456,7 @@ export class WorkspaceManager { private async ownsHostDirectory(record: WorkspaceRecord, directory: string, purpose: "request" | "event" = "request"): Promise { const [target, root] = await Promise.all([ - realpath(directory).catch(() => undefined), realpath(record.path).catch(() => undefined), + ownershipRealpath(directory), ownershipRealpath(record.path), ]) if (target && target === root) return true if (target && root && !isPathWithinWorktree(root, target) && !await sharesGitCommonDirectory(root, target)) return false @@ -457,15 +469,18 @@ export class WorkspaceManager { })) !== null } - private async resolveOwnedWorktree(record: WorkspaceRecord, directory: string, purpose: "request" | "event" = "request") { + private async resolveOwnedWorktree(record: WorkspaceRecord, directory: string, purpose: "request" | "event" = "request", strict = false) { const hostDirectory = record.wslDistro ? isWindowsHostPath(directory) ? directory : await this.resolveWslHostDirectory(directory, record.wslDistro, DEFAULT_LAUNCH_TIMEOUT_MS) : directory - if (!hostDirectory) return null + if (!hostDirectory) { + if (strict) throw new Error("WSL host directory translation unavailable") + return null + } const [target, root] = await Promise.all([ - realpath(hostDirectory).catch(() => undefined), realpath(record.path).catch(() => undefined), + ownershipRealpath(hostDirectory, strict), ownershipRealpath(record.path, strict), ]) // The explicitly opened folder is already authority. Do not require native // discovery (or a second connection) to authorize that exact local directory. @@ -481,12 +496,13 @@ export class WorkspaceManager { return { slug: "root", directory: target, worktreeDirectory: root } } } - if (target && root && !isPathWithinWorktree(root, target) && !await sharesGitCommonDirectory(root, target)) return null + if (target && root && !isPathWithinWorktree(root, target) && !await sharesGitCommonDirectory(root, target, { strict })) return null return resolveOwnedWorktreePath({ workspaceId: purpose === "event" ? `event:${record.id}` : record.id, workspacePath: record.path, directory: hostDirectory, - loadWorktrees: (refresh) => this.ownershipWorktrees(record.id, refresh, purpose), + strict, + loadWorktrees: (refresh) => this.ownershipWorktrees(record.id, refresh, purpose, strict), logger: this.options.logger, }) } diff --git a/packages/server/src/workspaces/opencode-cli-service.ts b/packages/server/src/workspaces/opencode-cli-service.ts index 8941633a2d..c881635feb 100644 --- a/packages/server/src/workspaces/opencode-cli-service.ts +++ b/packages/server/src/workspaces/opencode-cli-service.ts @@ -8,6 +8,7 @@ import type { OpenCodeServiceLifecycle } from "./opencode-service" import type { SpawnSpec } from "./spawn" import { rememberRuntime, runtimeIdentity } from "../opencode/compatibility/runtime" import { readNativeServiceRegistration } from "./native-service-registration" +import { isConnectionRefused } from "../opencode/connection-errors" export const MAX_SERVICE_OUTPUT_BYTES = 64 * 1024 const MAX_ERROR_CHARS = 1_024 @@ -278,14 +279,6 @@ class RefusedServiceConnection extends Error { constructor(message?: string) { super(message ?? "Cannot reach OpenCode service: connection refused") } } -function isConnectionRefused(error: unknown): boolean { - if (!error || typeof error !== "object") return false - const value = error as { code?: unknown; cause?: unknown; errors?: unknown } - if (value.code === "ECONNREFUSED") return true - if (Array.isArray(value.errors) && value.errors.length) return value.errors.every(isConnectionRefused) - return value.cause !== undefined && value.cause !== error && isConnectionRefused(value.cause) -} - function isServiceStatusResponse(value: unknown): boolean { if (!value || typeof value !== "object") return false const status = value as { version?: unknown; pid?: unknown; urls?: unknown } diff --git a/packages/server/src/workspaces/worktree-directory.test.ts b/packages/server/src/workspaces/worktree-directory.test.ts index a664cf5c7b..e86005bdef 100644 --- a/packages/server/src/workspaces/worktree-directory.test.ts +++ b/packages/server/src/workspaces/worktree-directory.test.ts @@ -2,12 +2,14 @@ import assert from "node:assert/strict" import { execFileSync } from "node:child_process" import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from "node:fs" import { realpath } from "node:fs/promises" +import fs from "node:fs/promises" +import { syncBuiltinESMExports } from "node:module" import { tmpdir } from "node:os" import path from "node:path" import { test } from "node:test" import { invalidateWorktreeCache, isPathWithinWorktree, resolveOwnedWorktreePath } from "./worktree-directory" import { fixtureCatalogue } from "./__tests__/native-worktree-fixture" -import { WorktreeInventory } from "./worktree-inventory" +import { WORKTREE_OWNERSHIP_RESTART_LIMIT, WorktreeInventory } from "./worktree-inventory" test("concurrent ownership misses share a refresh and cache negative results until invalidation", async (t) => { const temp = mkdtempSync(path.join(tmpdir(), "codenomad-inventory-misses-")) @@ -169,3 +171,290 @@ test("an invalidated directory load cannot return obsolete ownership to its awai release() assert.equal(await read, null) }) + +test("strict ownership revalidates cached fallback paths and propagates realpath failures", async t => { + const temp = mkdtempSync(path.join(tmpdir(), "codenomad-strict-directory-")) + t.after(() => { invalidateWorktreeCache(temp); rmSync(temp, { recursive: true, force: true }) }) + const root = path.join(temp, "root") + const missing = path.join(temp, "missing") + mkdirSync(root) + const params = { + workspaceId: temp, workspacePath: root, directory: root, + loadWorktrees: async () => [{ slug: "root", directory: missing, kind: "root" as const }], + } + assert.equal(await resolveOwnedWorktreePath(params), null) + await assert.rejects(resolveOwnedWorktreePath({ ...params, strict: true }), { code: "ENOENT" }) + await assert.rejects(resolveOwnedWorktreePath({ ...params, directory: missing, strict: true }), { code: "ENOENT" }) +}) + +test("strict ownership skips a missing projected project folder only after validating its registered root", async t => { + const temp = mkdtempSync(path.join(tmpdir(), "codenomad-strict-projection-")) + t.after(() => { invalidateWorktreeCache(temp); rmSync(temp, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }) }) + const root = path.join(temp, "repo"), linked = path.join(temp, "linked") + const project = path.join(root, "packages", "app") + const projected = path.join(linked, "packages", "app") + execFileSync("git", ["init", "--initial-branch=main", root], { windowsHide: true, stdio: "pipe" }) + execFileSync("git", ["-C", root, "-c", "user.name=Test", "-c", "user.email=test@example.invalid", "commit", "--allow-empty", "-m", "fixture"], { windowsHide: true, stdio: "pipe" }) + execFileSync("git", ["-C", root, "worktree", "add", "--detach", linked], { windowsHide: true, stdio: "pipe" }) + mkdirSync(project, { recursive: true }) + let reads = 0 + const worktrees = (await fixtureCatalogue(project, [root, linked])).worktrees + assert.ok(worktrees.some(entry => entry.directory === projected), "native inventory includes the absent projection") + const params = { workspaceId: temp, workspacePath: project, directory: project, + loadWorktrees: async () => { reads++; return worktrees } } + assert.equal((await resolveOwnedWorktreePath({ ...params, strict: true }))?.slug, "root") + assert.equal((await resolveOwnedWorktreePath({ ...params, strict: true }))?.slug, "root", "warm strict read skips the missing projection") + assert.equal(reads, 1) + writeFileSync(path.join(linked, "packages"), "a file on this branch\n") + assert.equal((await resolveOwnedWorktreePath({ ...params, strict: true }))?.slug, "root", "an intermediate file also proves the sibling projection unavailable") + invalidateWorktreeCache(temp) + assert.equal((await resolveOwnedWorktreePath({ ...params, strict: true }))?.slug, "root", "fresh strict reads skip non-directory sibling projections") + rmSync(linked, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }) + await assert.rejects(resolveOwnedWorktreePath({ ...params, strict: true }), { code: "ENOENT" }, "the missing registered root remains a hard error") +}) + +test("strict ownership rejects a missing root project folder even when its registered checkout exists", async t => { + const temp = mkdtempSync(path.join(tmpdir(), "codenomad-strict-root-projection-")) + t.after(() => { invalidateWorktreeCache(temp); rmSync(temp, { recursive: true, force: true }) }) + const project = path.join(temp, "project"), target = path.join(temp, "target") + mkdirSync(project) + mkdirSync(target) + let reads = 0 + const params = { + workspaceId: temp, workspacePath: project, directory: project, + loadWorktrees: async () => { + reads++ + return [ + { slug: "root", directory: project, registeredDirectory: temp, kind: "root" as const }, + { slug: "linked", directory: target, registeredDirectory: target, kind: "worktree" as const }, + ] + }, + } + assert.equal((await resolveOwnedWorktreePath({ ...params, strict: true }))?.slug, "root") + rmSync(project, { recursive: true }) + await assert.rejects(resolveOwnedWorktreePath({ ...params, directory: target, strict: true }), { code: "ENOENT" }, + "a missing opened-folder projection must reject even when the target and registered checkout still exist") + assert.equal(reads, 1, "strict validation checks the cached root projection") +}) + +test("repeated directory-cache invalidations have two retries and one final fresh read", async t => { + const temp = mkdtempSync(path.join(tmpdir(), "codenomad-directory-retry-bound-")) + t.after(() => { invalidateWorktreeCache(temp); rmSync(temp, { recursive: true, force: true }) }) + const refreshes: boolean[] = [] + await assert.rejects(resolveOwnedWorktreePath({ + workspaceId: temp, workspacePath: temp, directory: temp, strict: true, + loadWorktrees: async (refresh = false) => { + refreshes.push(refresh) + await Promise.resolve() + invalidateWorktreeCache(temp) + return [{ slug: "root", directory: temp, kind: "root" }] + }, + }), /inventory changed repeatedly/) + assert.deepEqual(refreshes, [false, false, false, true]) + refreshes.length = 0 + const absent = await resolveOwnedWorktreePath({ + workspaceId: temp, workspacePath: temp, directory: temp, strict: true, + loadWorktrees: async (refresh = false) => { + refreshes.push(refresh) + await Promise.resolve() + if (refreshes.length < 4) invalidateWorktreeCache(temp) + return [] + }, + }) + assert.equal(absent, null) + assert.deepEqual(refreshes, [false, false, false, true], "the final fresh miss needs no fifth read") + invalidateWorktreeCache(temp) + assert.equal((await resolveOwnedWorktreePath({ + workspaceId: temp, workspacePath: temp, directory: temp, + loadWorktrees: async () => [{ slug: "root", directory: temp, kind: "root" }], + }))?.slug, "root", "a later stable demand can recover") +}) + +test("the strict final fresh read bypasses a warm ordinary negative cache", async t => { + const temp = mkdtempSync(path.join(tmpdir(), "codenomad-final-fresh-")) + t.after(() => { invalidateWorktreeCache(temp); rmSync(temp, { recursive: true, force: true }) }) + const root = path.join(temp, "root"), linked = path.join(temp, "linked") + mkdirSync(root); mkdirSync(linked) + let added = false + const refreshes: boolean[] = [] + const params = { workspaceId: temp, workspacePath: root, directory: linked, + loadWorktrees: async (refresh = false) => { + refreshes.push(refresh) + return [{ slug: "root", directory: root, kind: "root" as const }, + ...(added ? [{ slug: "linked", directory: linked, kind: "worktree" as const }] : [])] + } } + assert.equal(await resolveOwnedWorktreePath(params), null) + added = true + assert.equal((await resolveOwnedWorktreePath({ ...params, strict: true }, { restarts: WORKTREE_OWNERSHIP_RESTART_LIMIT }))?.slug, "linked") + assert.equal((await resolveOwnedWorktreePath(params))?.slug, "linked", "ordinary callers cannot inherit a stale final-read negative") + assert.deepEqual(refreshes, [false, true, true]) +}) + +test("the final strict fresh read never joins an in-flight validated scan", async t => { + const temp = mkdtempSync(path.join(tmpdir(), "codenomad-final-scan-")) + const root = path.join(temp, "root"), linked = path.join(temp, "linked") + mkdirSync(root); mkdirSync(linked) + let release!: () => void, started!: () => void, reached!: () => void + const held = new Promise(resolve => { release = resolve }) + const scanning = new Promise(resolve => { started = resolve }) + const finalTarget = new Promise(resolve => { reached = resolve }) + const reads: Promise[] = [], refreshes: boolean[] = [] + const actualRealpath = fs.realpath + t.mock.method(fs, "realpath", async (directory: string) => { + const result = await actualRealpath(directory) + if (directory === linked) reached() + return result + }) + syncBuiltinESMExports() + t.after(async () => { + release(); await Promise.allSettled(reads) + t.mock.restoreAll(); syncBuiltinESMExports() + invalidateWorktreeCache(temp); rmSync(temp, { recursive: true, force: true }) + }) + const params = { workspaceId: temp, workspacePath: root, strict: true, + loadWorktrees: async (refresh = false) => { + refreshes.push(refresh) + if (!refresh) { started(); await held } + return [{ slug: "root", directory: root, kind: "root" as const }, + ...(refresh ? [{ slug: "linked", directory: linked, kind: "worktree" as const }] : [])] + } } + const other = resolveOwnedWorktreePath({ ...params, directory: root }); reads.push(other) + await scanning + const finalRead = resolveOwnedWorktreePath({ ...params, directory: linked }, { restarts: WORKTREE_OWNERSHIP_RESTART_LIMIT }); reads.push(finalRead) + await finalTarget + await new Promise(resolve => setImmediate(resolve)) + assert.deepEqual(refreshes, [false, true], "the final demand starts a fresh scan while the validated scan remains held") + assert.equal((await finalRead)?.slug, "linked") + release() + assert.equal((await other)?.slug, "root") + assert.equal((await resolveOwnedWorktreePath({ ...params, strict: false, directory: linked }))?.slug, "linked") +}) + +test("ordinary ownership preserves trailing reloads beyond four invalidations", async t => { + const temp = mkdtempSync(path.join(tmpdir(), "codenomad-ordinary-reloads-")) + t.after(() => { invalidateWorktreeCache(temp); rmSync(temp, { recursive: true, force: true }) }) + let reads = 0 + const result = await resolveOwnedWorktreePath({ workspaceId: temp, workspacePath: temp, directory: temp, + loadWorktrees: async () => { + await Promise.resolve() + if (++reads <= 4) invalidateWorktreeCache(temp) + return [{ slug: "root", directory: temp, kind: "root" }] + } }) + assert.equal(result?.slug, "root") + assert.equal(reads, 5) +}) + +test("ordinary synchronous loader invalidation preserves the baseline successive-call load counts", async t => { + const temp = mkdtempSync(path.join(tmpdir(), "codenomad-ordinary-sync-invalidation-")) + t.after(() => { invalidateWorktreeCache(temp); rmSync(temp, { recursive: true, force: true }) }) + const refreshes: boolean[] = [] + const params = { workspaceId: temp, workspacePath: temp, directory: temp, + loadWorktrees: async (refresh = false) => { + refreshes.push(refresh) + if (refreshes.length <= 6) invalidateWorktreeCache(temp) + return [{ slug: "root", directory: temp, kind: "root" as const }] + } } + const loads: number[] = [] + for (let i = 0; i < 3; i++) { + assert.equal((await resolveOwnedWorktreePath(params))?.slug, "root") + loads.push(refreshes.length) + } + assert.deepEqual(loads, [1, 1, 1]) + assert.deepEqual(refreshes, [false]) +}) + +test("strict synchronous loader invalidation remains fenced and bounded", async t => { + const temp = mkdtempSync(path.join(tmpdir(), "codenomad-strict-sync-invalidation-")) + t.after(() => { invalidateWorktreeCache(temp); rmSync(temp, { recursive: true, force: true }) }) + const refreshes: boolean[] = [] + await assert.rejects(resolveOwnedWorktreePath({ workspaceId: temp, workspacePath: temp, directory: temp, strict: true, + loadWorktrees: async (refresh = false) => { + refreshes.push(refresh) + invalidateWorktreeCache(temp) + return [{ slug: "root", directory: temp, kind: "root" }] + } }), /inventory changed repeatedly/) + assert.deepEqual(refreshes, [false, false, false, true]) +}) + +test("strict ownership stays bounded while an ordinary demand keeps trailing native scans", async t => { + const temp = mkdtempSync(path.join(tmpdir(), "codenomad-mixed-ownership-")) + const snapshot = { worktrees: [{ slug: "root", directory: temp, kind: "root" as const }] } + const scans: Array<(value: typeof snapshot) => void> = [] + let started = () => {}, draining = false, readers = 0 + const inventory = new WorktreeInventory({ load: async () => { + if (draining) return snapshot + return new Promise(resolve => { scans.push(resolve); started() }) + }, changed() {}, failed() {} }) + const params = (strict: boolean) => ({ workspaceId: temp, workspacePath: temp, directory: temp, strict, + loadWorktrees: async () => { readers++; started(); return (await inventory.read(temp, "validated", { strict })).worktrees } }) + const ordinary = resolveOwnedWorktreePath(params(false)) + const strict = resolveOwnedWorktreePath(params(true)) + const rejected = assert.rejects(strict, /inventory changed repeatedly/) + t.after(async () => { + draining = true + for (const resolve of scans) resolve(snapshot) + await Promise.allSettled([ordinary, strict]) + invalidateWorktreeCache(temp) + rmSync(temp, { recursive: true, force: true }) + }) + while (readers < 2) await new Promise(resolve => { started = resolve }) + for (let i = 0; i < 4; i++) { + while (scans.length < i + 1) await new Promise(resolve => { started = resolve }) + assert.equal(scans.length, i + 1, "both readers share one native scan") + inventory.invalidate(temp) + invalidateWorktreeCache(temp) + scans[i](snapshot) + } + await rejected + while (scans.length < 5) await new Promise(resolve => { started = resolve }) + assert.equal(scans.length, 5) + scans[4](snapshot) + assert.equal((await ordinary)?.slug, "root") +}) + +test("concurrent pending-scan handoffs retain each ownership demand's retry budget", async t => { + const temp = mkdtempSync(path.join(tmpdir(), "codenomad-directory-handoffs-")) + const snapshot = [{ slug: "root", directory: temp, registeredDirectory: temp, kind: "worktree" as const }] + const scans: Array<{ generation: number; release(value: typeof snapshot): void }> = [] + const reads: Promise[] = [] + const outcomes: Array<{ status: "fulfilled" | "rejected"; generation: number; result: unknown }> = [] + let active = 0, generation = 0, draining = false + t.mock.method(fs, "realpath", async (directory: string) => directory) + syncBuiltinESMExports() + t.after(async () => { + draining = true + for (const scan of scans) scan.release(snapshot) + await Promise.allSettled(reads) + t.mock.restoreAll(); syncBuiltinESMExports() + invalidateWorktreeCache(temp) + rmSync(temp, { recursive: true, force: true }) + }) + const params = { + workspaceId: temp, workspacePath: temp, directory: temp, strict: true, + loadWorktrees: async () => { + active++ + try { + return draining ? snapshot : await new Promise(release => { scans.push({ generation, release }) }) + } finally { active-- } + }, + } + for (let i = 0; i < 8; i++) { + generation = i + invalidateWorktreeCache(temp) + reads.push(resolveOwnedWorktreePath(params).then( + result => { outcomes[i] = { status: "fulfilled", generation, result } }, + result => { outcomes[i] = { status: "rejected", generation, result } }, + )) + await new Promise(resolve => setImmediate(resolve)) + for (const scan of scans.filter(scan => scan.generation < generation)) scan.release([]) + await new Promise(resolve => setImmediate(resolve)) + } + draining = true + for (const scan of scans) scan.release(snapshot) + await Promise.all(reads) + assert.equal(outcomes[0]?.status, "rejected", "the original demand cannot adopt eight callers' independent budgets") + assert.ok(outcomes[0].generation <= 4, "the original demand settles within four invalidated generations") + assert.match(String(outcomes[0].result), /inventory changed repeatedly/) + assert.equal(active, 0, "every admitted loader has settled before cleanup") + assert.equal(outcomes.at(-1)?.status, "fulfilled", "a later stable demand can recover") +}) diff --git a/packages/server/src/workspaces/worktree-directory.ts b/packages/server/src/workspaces/worktree-directory.ts index f920275ef8..f8304352bc 100644 --- a/packages/server/src/workspaces/worktree-directory.ts +++ b/packages/server/src/workspaces/worktree-directory.ts @@ -2,19 +2,27 @@ import { lstat, realpath } from "fs/promises" import path from "node:path" import type { LogLike } from "./git-worktrees" import type { WorktreeDescriptor } from "../api-types" +import { discoverCheckoutCommonDirectory } from "./git-common-directory" +import { WORKTREE_OWNERSHIP_RESTART_LIMIT } from "./worktree-inventory" type WorktreeSource = { loadWorktrees: (refresh?: boolean) => Promise } type WorktreeCacheEntry = { expiresAt: number refreshedOnMiss: boolean - worktrees: Array<{ slug: string; directory: string; normalizedDirectory: string; worktreeDirectory: string; directoryOnly?: boolean }> + worktrees: Array<{ slug: string; directory: string; normalizedDirectory: string; worktreeDirectory: string; directoryOnly?: boolean; verifyCheckoutAbsence: boolean }> resolvedDirectories: Map } const WORKTREE_CACHE_TTL_MS = 10_000 const worktreeCache = new Map() -const worktreeLoads = new Map>() +const worktreeLoads = new Map>() + +function restartWorktreeRead(budget?: { restarts: number }): void { + if (!budget) return + if (budget.restarts >= WORKTREE_OWNERSHIP_RESTART_LIMIT) throw new Error("Worktree ownership inventory changed repeatedly") + budget.restarts++ +} async function normalizeDirectoryPath(directory: string): Promise { const trimmed = (directory ?? "").trim() @@ -27,46 +35,62 @@ async function normalizeDirectoryPath(directory: string): Promise { } async function getCachedWorktrees( - params: WorktreeSource & { workspaceId: string; workspacePath: string; logger?: LogLike }, + params: WorktreeSource & { workspaceId: string; workspacePath: string; logger?: LogLike; strict?: boolean }, refresh = false, + budget = params.strict ? { restarts: 0 } : undefined, ): Promise { + if (params.strict && budget?.restarts === WORKTREE_OWNERSHIP_RESTART_LIMIT) worktreeCache.delete(params.workspaceId) const cached = worktreeCache.get(params.workspaceId) const now = Date.now() if (cached && cached.expiresAt > now) { return cached } - const pending = worktreeLoads.get(params.workspaceId) - if (pending) return pending - - let load!: Promise - load = (async () => { - const worktrees = await params.loadWorktrees(refresh) - const entry: WorktreeCacheEntry = { - expiresAt: Date.now() + WORKTREE_CACHE_TTL_MS, - refreshedOnMiss: false, - worktrees: await Promise.all( - worktrees.map(async (wt) => ({ - slug: wt.slug, - directory: wt.directory, - normalizedDirectory: await normalizeDirectoryPath(wt.directory), - worktreeDirectory: await normalizeDirectoryPath(wt.registeredDirectory ?? wt.directory), - directoryOnly: wt.directoryOnly, - })), - ), - resolvedDirectories: new Map(), - } - // A native snapshot update or mutation can invalidate during load/realpath. - // Never return the obsolete ownership to callers already awaiting this load. - if (worktreeLoads.get(params.workspaceId) !== load) return getCachedWorktrees(params) - worktreeCache.set(params.workspaceId, entry) - return entry - })() - worktreeLoads.set(params.workspaceId, load) + // Strict demands never inherit an ordinary caller's unbounded trailing reads. + // Both channels share the last validated snapshot and native single-scan work. + const loadKey = params.strict ? `${params.workspaceId}\0strict${refresh ? ":fresh" : ""}` : params.workspaceId + let load = worktreeLoads.get(loadKey) + if (!params.strict && load) return load as Promise + if (!load) { + let scan!: Promise + scan = (async () => { + const worktrees = await (params.strict ? Promise.resolve().then(() => params.loadWorktrees(refresh)) : params.loadWorktrees(refresh)) + const entry: WorktreeCacheEntry = { + expiresAt: Date.now() + WORKTREE_CACHE_TTL_MS, + refreshedOnMiss: false, + worktrees: await Promise.all( + worktrees.map(async (wt) => ({ + slug: wt.slug, + directory: wt.directory, + normalizedDirectory: await normalizeDirectoryPath(wt.directory), + worktreeDirectory: await normalizeDirectoryPath(wt.registeredDirectory ?? wt.directory), + directoryOnly: wt.directoryOnly, + verifyCheckoutAbsence: wt.kind === "root" && !wt.registeredDirectory && !wt.directoryOnly, + })), + ), + resolvedDirectories: new Map(), + } + if (worktreeLoads.get(loadKey) !== scan) return params.strict ? null : getCachedWorktrees(params) + // Strict callers share one scan, never another caller's retry chain or budget. + if (params.strict && worktreeCache.get(params.workspaceId) !== cached) return null + worktreeCache.set(params.workspaceId, entry) + return entry + })() + if (params.strict) scan = scan.finally(() => { + if (worktreeLoads.get(loadKey) === scan) worktreeLoads.delete(loadKey) + }) + worktreeLoads.set(loadKey, scan) + load = scan + } try { - return await load + const entry = await load + if (!params.strict) return entry! + if (entry && worktreeCache.get(params.workspaceId) === entry) return entry + restartWorktreeRead(budget) + const finalFreshRead = budget?.restarts === WORKTREE_OWNERSHIP_RESTART_LIMIT + return getCachedWorktrees(params, finalFreshRead, budget) } finally { - if (worktreeLoads.get(params.workspaceId) === load) worktreeLoads.delete(params.workspaceId) + if (!params.strict && worktreeLoads.get(loadKey) === load) worktreeLoads.delete(loadKey) } } @@ -77,6 +101,8 @@ export function invalidateWorktreeCache(workspaceId?: string): void { } else { worktreeCache.delete(workspaceId) worktreeLoads.delete(workspaceId) + worktreeLoads.delete(`${workspaceId}\0strict`) + worktreeLoads.delete(`${workspaceId}\0strict:fresh`) } } @@ -181,24 +207,50 @@ export async function resolveOwnedWorktreePath(params: WorktreeSource & { workspaceId: string workspacePath: string directory: string + strict?: boolean logger?: LogLike -}): Promise<{ slug: string; directory: string; worktreeDirectory: string } | null> { - const target = await resolveDirectoryPath(params.directory) +}, budget = params.strict ? { restarts: 0 } : undefined): Promise<{ slug: string; directory: string; worktreeDirectory: string } | null> { + const target = params.strict ? await realpath(params.directory) : await resolveDirectoryPath(params.directory) if (!target) return null const find = (worktrees: WorktreeCacheEntry["worktrees"]) => worktrees .filter((worktree) => worktree.directoryOnly ? worktree.normalizedDirectory === target : isPathWithinWorktree(worktree.normalizedDirectory, target)) .sort((left, right) => right.normalizedDirectory.length - left.normalizedDirectory.length)[0] - let entry = await getCachedWorktrees(params) - if (entry.resolvedDirectories.has(target)) return entry.resolvedDirectories.get(target)! - let match = find(entry.worktrees) - if (!entry.refreshedOnMiss && (!match || (match.slug === "root" && match.normalizedDirectory !== target))) { + const findStrict = async (worktrees: WorktreeCacheEntry["worktrees"]) => { + if (worktrees.some(worktree => worktree.directoryOnly)) throw new Error("Git ownership inventory unavailable") + return find((await Promise.all(worktrees.map(async worktree => { + const worktreeDirectory = await realpath(worktree.worktreeDirectory) + if (worktree.verifyCheckoutAbsence && !await discoverCheckoutCommonDirectory(worktreeDirectory).then(common => common === undefined, () => false)) { + throw new Error("Git ownership inventory unavailable") + } + try { + return { ...worktree, worktreeDirectory, normalizedDirectory: await realpath(worktree.directory) } + } catch (error) { + // A nested project folder may exist in only some registered checkouts. + if (["ENOENT", "ENOTDIR"].includes((error as NodeJS.ErrnoException).code ?? "") && worktree.slug !== "root" && worktree.directory !== worktree.worktreeDirectory) return null + throw error + } + }))).filter((worktree): worktree is NonNullable => worktree !== null)) + } + const finalFreshRead = budget?.restarts === WORKTREE_OWNERSHIP_RESTART_LIMIT + let entry = await getCachedWorktrees(params, finalFreshRead, budget) + if (!params.strict && entry.resolvedDirectories.has(target)) return entry.resolvedDirectories.get(target)! + let match = params.strict ? await findStrict(entry.worktrees) : find(entry.worktrees) + if (params.strict && worktreeCache.get(params.workspaceId) !== entry) { + restartWorktreeRead(budget) + return resolveOwnedWorktreePath(params, budget) + } + if (budget?.restarts !== WORKTREE_OWNERSHIP_RESTART_LIMIT && !entry.refreshedOnMiss && (!match || (match.slug === "root" && match.normalizedDirectory !== target))) { // Refresh once for this cache lifetime, including sequential misses from // distinct foreign event locations. Otherwise every miss discards the last // negative result and stalls the serial native event bridge on inventory I/O. if (worktreeCache.get(params.workspaceId) === entry) worktreeCache.delete(params.workspaceId) - entry = await getCachedWorktrees(params, true) + entry = await getCachedWorktrees(params, true, budget) entry.refreshedOnMiss = true - match = find(entry.worktrees) + match = params.strict ? await findStrict(entry.worktrees) : find(entry.worktrees) + } + if (params.strict && worktreeCache.get(params.workspaceId) !== entry) { + restartWorktreeRead(budget) + return resolveOwnedWorktreePath(params, budget) } const resolved = match ? { slug: match.slug, directory: target, worktreeDirectory: match.worktreeDirectory } : null entry.resolvedDirectories.set(target, resolved) diff --git a/packages/server/src/workspaces/worktree-inventory.test.ts b/packages/server/src/workspaces/worktree-inventory.test.ts index c32e100875..362327f588 100644 --- a/packages/server/src/workspaces/worktree-inventory.test.ts +++ b/packages/server/src/workspaces/worktree-inventory.test.ts @@ -115,6 +115,42 @@ it("fences a scan overtaken by a mutation and serializes a trailing validation", assert.deepEqual(f.changes, ["repo"]) }) +it("bounds repeatedly invalidated scans and permits a later stable demand", async () => { + const f = fixture() + await seed(f) + const read = f.cache.read("repo", "fresh", { strict: true }) + const rejected = assert.rejects(read, /inventory changed repeatedly/) + for (let i = 1; i <= 4; i++) { + await turn() + assert.equal(f.scans.length, i + 1) + f.cache.invalidate("repo") + f.scans[i].resolve(snapshot("obsolete")) + } + await rejected + assert.equal(f.scans.length, 5, "two restarts and one final fresh scan after the initial demand") + assert.deepEqual(f.changes, [], "obsolete scans preserve the last good display") + assert.deepEqual(await f.cache.read("repo"), snapshot("main")) + const recovered = f.cache.read("repo", "validated") + await turn() + f.scans[5].resolve(snapshot("recovered")) + assert.deepEqual(await recovered, snapshot("recovered")) + assert.deepEqual(f.changes, ["repo"]) +}) + +it("ordinary inventory keeps trailing reloads beyond the strict budget", async () => { + const f = fixture() + const read = f.cache.read("repo", "validated") + for (let i = 0; i < 4; i++) { + await turn() + f.cache.invalidate("repo") + f.scans[i].resolve(snapshot("obsolete")) + } + await turn() + assert.equal(f.scans.length, 5) + f.scans[4].resolve(snapshot("current")) + assert.deepEqual(await read, snapshot("current")) +}) + it("keeps the last good display snapshot on failure with demand-driven retry backoff", async () => { const f = fixture() await seed(f) diff --git a/packages/server/src/workspaces/worktree-inventory.ts b/packages/server/src/workspaces/worktree-inventory.ts index 2a04a3dc93..4afdaa0e3a 100644 --- a/packages/server/src/workspaces/worktree-inventory.ts +++ b/packages/server/src/workspaces/worktree-inventory.ts @@ -7,10 +7,11 @@ type Entry = { retryAt: number revision: number requireValidation?: boolean - pending?: Promise + pending?: Promise } const MAX_AGE_MS = 10_000 +export const WORKTREE_OWNERSHIP_RESTART_LIMIT = 3 /** Demand-driven inventory: display reads keep the last snapshot while refreshing. * Directory authorization waits for validation; family transactions force a scan. @@ -26,7 +27,7 @@ export class WorktreeInventory { now?: () => number }) {} - async read(id: string, mode: ReadMode = "cached"): Promise { + async read(id: string, mode: ReadMode = "cached", { strict = false } = {}): Promise { let entry = this.entries.get(id) if (!entry) { entry = { expiresAt: 0, retryAt: 0, revision: 0 } @@ -35,10 +36,10 @@ export class WorktreeInventory { const now = this.now() if (mode !== "fresh" && entry.value && entry.expiresAt > now) return entry.value if (mode === "cached" && entry.value && !entry.requireValidation) { - if (!entry.pending && entry.retryAt <= now) void this.load(id, entry).catch(error => this.options.failed(id, error)) + if (!entry.pending && entry.retryAt <= now) void this.validated(id, entry).catch(error => this.options.failed(id, error)) return entry.value } - return this.load(id, entry) + return this.validated(id, entry, strict) } // Invalidation is lazy: retain the display snapshot, but fence any running scan. @@ -57,17 +58,24 @@ export class WorktreeInventory { this.entries.delete(id) } - private load(id: string, entry: Entry): Promise { + private async validated(id: string, entry: Entry, strict = false): Promise { + for (let invalidated = 0; ; invalidated++) { + const value = await this.load(id, entry) + if (value) return value + if (strict && invalidated >= WORKTREE_OWNERSHIP_RESTART_LIMIT) throw new Error("Worktree ownership inventory changed repeatedly") + } + } + + private load(id: string, entry: Entry): Promise { if (entry.pending) return entry.pending const revision = entry.revision const previous = entry.value - const task = Promise.resolve().then(() => this.options.load(id)).then(async value => { + const task = Promise.resolve().then(() => this.options.load(id)).then(value => { if (this.entries.get(id) !== entry) throw new Error("Workspace inventory was disposed") if (revision !== entry.revision) { // A mutation overtook the scan. Serialize one trailing validation rather // than publishing obsolete data or starting overlapping Git process fans. - entry.pending = undefined - return this.load(id, entry) + return null } entry.value = value entry.expiresAt = this.now() + MAX_AGE_MS diff --git a/packages/tauri-app/Cargo.lock b/packages/tauri-app/Cargo.lock index b446603b60..d47030c966 100644 --- a/packages/tauri-app/Cargo.lock +++ b/packages/tauri-app/Cargo.lock @@ -2515,7 +2515,7 @@ dependencies = [ "png", "serde", "thiserror 2.0.18", - "windows-sys 0.60.2", + "windows-sys 0.61.2", ] [[package]] @@ -3995,7 +3995,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" dependencies = [ "libc", - "windows-sys 0.60.2", + "windows-sys 0.61.2", ] [[package]] @@ -4989,7 +4989,7 @@ dependencies = [ "png", "serde", "thiserror 2.0.18", - "windows-sys 0.60.2", + "windows-sys 0.61.2", ] [[package]] @@ -5024,7 +5024,7 @@ checksum = "f2f6fb2847f6742cd76af783a2a2c49e9375d0a111c7bef6f71cd9e738c72d6e" dependencies = [ "memoffset", "tempfile", - "windows-sys 0.60.2", + "windows-sys 0.61.2", ] [[package]] @@ -5473,7 +5473,7 @@ dependencies = [ "objc2-foundation", "objc2-quartz-core", "raw-window-handle", - "windows-sys 0.60.2", + "windows-sys 0.61.2", "windows-version", ] diff --git a/packages/ui/src/components/instance/shell/right-panel/core-plugin.test.ts b/packages/ui/src/components/instance/shell/right-panel/core-plugin.test.ts index 5a7bbadbc4..61e72e44f6 100644 --- a/packages/ui/src/components/instance/shell/right-panel/core-plugin.test.ts +++ b/packages/ui/src/components/instance/shell/right-panel/core-plugin.test.ts @@ -1,18 +1,26 @@ import assert from "node:assert/strict" +import { registerHooks } from "node:module" import { it } from "node:test" -import { createCoreRightPanelModule, createCoreStatusSectionManifest } from "./core-plugin" -it("defines built-in tabs and status sections without a plugin loading layer", () => { - const render = () => undefined as any - const summary = () => undefined as any - const module = createCoreRightPanelModule({ renderFilesTab: render, renderStatusTab: render }) - const sections = createCoreStatusSectionManifest({ renderTokens: render, renderTokensSummary: summary, renderYoloModeSection: render, - renderProviderUsage: render, renderBackgroundProcesses: render, renderMcpStatus: render, renderPluginStatus: render }) - assert.deepEqual(module.tabs?.map(entry => entry.id), ["files", "status"]) - assert.equal(module.tabs?.find(entry => entry.id === "status")?.alwaysVisible, true) - assert.deepEqual(sections.statusSections?.map(entry => entry.id), ["tokens", "yolo-mode", "provider-usage", "background-processes", "mcp", "plugins"]) - assert.equal(module.tabs?.every(entry => entry.render === render), true) - assert.equal(sections.statusSections?.every(entry => entry.render === render), true) - assert.equal(sections.statusSections?.find(entry => entry.id === "tokens")?.renderSummary, summary) - assert.equal(sections.statusSections?.filter(entry => entry.id !== "tokens").every(entry => !entry.renderSummary), true) +it("defines built-in tabs and status sections without a plugin loading layer", async () => { + const hooks = registerHooks({ resolve(specifier, context, next) { + if (specifier === "lucide-solid") return { url: "data:text/javascript,export const Info = () => null", shortCircuit: true } + return next(specifier, context) + } }) + try { + const { createCoreRightPanelModule, createCoreStatusSectionManifest } = await import("./core-plugin") + const render = () => undefined as any + const summary = () => undefined as any + const module = createCoreRightPanelModule({ renderFilesTab: render, renderStatusTab: render }) + const sections = createCoreStatusSectionManifest({ renderTokens: render, renderTokensSummary: summary, renderYoloModeSection: render, + renderProviderUsage: render, renderBackgroundProcesses: render, renderMcpStatus: render, renderPluginStatus: render }) + assert.deepEqual(module.tabs?.map(entry => entry.id), ["files", "status"]) + assert.equal(module.tabs?.find(entry => entry.id === "status")?.alwaysVisible, true) + assert.deepEqual(sections.statusSections?.map(entry => entry.id), ["tokens", "yolo-mode", "provider-usage", "background-processes", "mcp", "plugins"]) + assert.equal(module.tabs?.every(entry => entry.render === render), true) + assert.equal(sections.statusSections?.every(entry => entry.render === render), true) + assert.equal(sections.statusSections?.every(entry => typeof entry.renderInfo === "function"), true) + assert.equal(sections.statusSections?.find(entry => entry.id === "tokens")?.renderSummary, summary) + assert.equal(sections.statusSections?.filter(entry => entry.id !== "tokens").every(entry => !entry.renderSummary), true) + } finally { hooks.deregister() } }) diff --git a/packages/ui/src/lib/mission-defaults.ts b/packages/ui/src/lib/mission-defaults.ts index f3feb3eba0..f170c5b844 100644 --- a/packages/ui/src/lib/mission-defaults.ts +++ b/packages/ui/src/lib/mission-defaults.ts @@ -1,66 +1,3 @@ -import { parseMissionProfiles, missionProfileRoles, type MissionProfiles } from "../../../server/src/missions/playbook-profiles" -import type { MissionTemplateId } from "../../../server/src/missions/model" - -export type MissionTaskMode = "native" | "independent" -/** `all` is the global default; a mission type entry is an exception overriding it. */ -export type MissionDefaultScope = "all" | MissionTemplateId -export interface MissionProfileDefault { template: MissionDefaultScope; profiles: MissionProfiles; taskMode?: MissionTaskMode } -const scopes: MissionDefaultScope[] = ["all", "custom", "debug", "wayfinder", "delivery", "compare"] -// The global default carries one task profile, like the Flexible specialist. -const scopeRoles = (scope: MissionDefaultScope): readonly string[] => missionProfileRoles[scope === "all" ? "custom" : scope] - -/** Preferences carry selectors only, never credentials, execution authority or sessions. */ -export function normalizeMissionDefaults(value: unknown): MissionProfileDefault[] { - if (!Array.isArray(value) || value.length > scopes.length) return [] - const result: MissionProfileDefault[] = [] - for (const entry of value) { - if (!entry || typeof entry !== "object" || Array.isArray(entry)) return [] - const template = entry.template as MissionDefaultScope - if (Object.keys(entry).some(key => !["template", "profiles", "taskMode"].includes(key)) - || (entry.taskMode !== undefined && !["native", "independent"].includes(entry.taskMode)) - || !scopes.includes(template) || result.some(item => item.template === template)) return [] - try { - const profiles = parseMissionProfiles(entry.profiles) - if (!profiles || Object.keys(profiles.roles ?? {}).some(role => !scopeRoles(template).includes(role))) return [] - result.push({ template, profiles, ...(entry.taskMode === undefined ? {} : { taskMode: entry.taskMode }) }) - } catch { return [] } - } - // Before the explicit global entry existed, the Flexible entry was the global base: - // read it as such so no saved choice changes meaning; the next save writes `all`. - const legacy = result.find(item => item.template === "custom") - if (legacy && !result.some(item => item.template === "all")) legacy.template = "all" - return result -} - -/** Document to write: a Flexible exception always travels with the explicit global - * entry, so the legacy decoding above never turns it into the global default. */ -export function encodeMissionDefaults(value: readonly MissionProfileDefault[]): MissionProfileDefault[] { - const flexibleOnly = value.some(item => item.template === "custom") && !value.some(item => item.template === "all") - return normalizeMissionDefaults(flexibleOnly ? [{ template: "all", profiles: {} }, ...value] : value) -} - -export function validMissionDefaults(value: unknown): boolean { - return value === undefined || (Array.isArray(value) && (value.length === 0 || normalizeMissionDefaults(value).length === value.length)) -} - -/** Type exception ?? global default ?? native. */ -export function missionTaskModeFor(value: readonly MissionProfileDefault[], template: MissionTemplateId): MissionTaskMode { - return value.find(item => item.template === template)?.taskMode ?? globalMissionTaskMode(value) -} - -export function globalMissionTaskMode(value: readonly MissionProfileDefault[]): MissionTaskMode { - return value.find(item => item.template === "all")?.taskMode ?? "native" -} - -/** Resolve a copy when the creation form opens. Existing missions never consult defaults. */ -export function missionDefaultsFor(value: readonly MissionProfileDefault[], template: MissionTemplateId, exceptions = true): MissionProfiles | undefined { - const base = value.find(item => item.template === "all")?.profiles - const specific = exceptions ? value.find(item => item.template === template)?.profiles : undefined - const coordinator = specific?.coordinator ?? base?.coordinator - const roles = Object.fromEntries(missionProfileRoles[template].flatMap(role => { - const execution = specific?.roles?.[role] ?? (template === "compare" && role === "comparator" ? undefined : base?.roles?.specialist) - return execution ? [[role, execution]] : [] - })) - if (!coordinator && !Object.keys(roles).length) return undefined - return structuredClone({ ...(coordinator ? { coordinator } : {}), ...(Object.keys(roles).length ? { roles } : {}) }) -} +export { encodeMissionDefaults, globalMissionTaskMode, missionDefaultsFor, missionTaskModeFor, + normalizeMissionDefaults, validMissionDefaults } from "../../../server/src/missions/profile-defaults" +export type { MissionDefaultScope, MissionProfileDefault, MissionTaskMode } from "../../../server/src/missions/profile-defaults" diff --git a/packages/ui/tests/browser/automation-preview-preparation.test.ts b/packages/ui/tests/browser/automation-preview-preparation.test.ts new file mode 100644 index 0000000000..ab686c9808 --- /dev/null +++ b/packages/ui/tests/browser/automation-preview-preparation.test.ts @@ -0,0 +1,169 @@ +import assert from "node:assert/strict" +import { readFileSync } from "node:fs" +import { test } from "node:test" +import vm from "node:vm" + +// Runs the real Electron preview fixture's preparation against fake Electron objects and a fake clock. +const FIXTURE = readFileSync(new URL("fixtures/automation-preview-electron.cjs", import.meta.url), "utf8") +const GUEST_URL = "http://127.0.0.1:1/" +const PENDING = ["UnknownVizError", "VizSentEmptyBitmap", "Current display surface not available for capture"] + +type Capture = { resolve(image: { isEmpty(): boolean }): void; reject(error: Error): void } + +function prepare() { + let now = 0, nextTimer = 0 + const timers = new Map void }>() + const handlers = new Map void>() + const captures: Capture[] = [] + let inFlight = 0, maxInFlight = 0, focusedWindow: object | null = null + const owner = { visible: false, focused: false } + const guest = { + id: 7, url: GUEST_URL, destroyed: false, + on: (event: string, handler: () => void) => { handlers.set(event, handler) }, + getURL: () => guest.url, isLoading: () => false, isDestroyed: () => guest.destroyed, + capturePage: (rect: unknown, options: unknown) => { + assert.equal(JSON.stringify([rect, options]), JSON.stringify([{ x: 0, y: 0, width: 1, height: 1 }, { stayHidden: true }])) + inFlight++; maxInFlight = Math.max(maxInFlight, inFlight) + return new Promise((resolve, reject) => { captures.push({ resolve, reject }) }).finally(() => { inFlight-- }) + }, + } + let attach: ((event: unknown, contents: unknown) => void) | undefined + class BrowserWindow { + static getFocusedWindow = () => focusedWindow + webContents = { on: (_event: string, handler: typeof attach) => { attach = handler }, isFocused: () => false } + isVisible = () => owner.visible + isFocused = () => owner.focused + isDestroyed = () => false + loadURL = async () => {} + } + const electron = { app: { setPath() {}, whenReady: () => Promise.resolve(), on() {} }, BrowserWindow } + const bundle = { + BrowserController: class { observeGuest() {} register() {} }, + BrowserPage: class { execute() {} }, + handleNativeBrowserRequest() {}, + } + const context = vm.createContext({ + require: (name: string) => name === "electron" ? electron : name === "bundle" ? bundle : assert.fail(`unexpected require ${name}`), + process: { env: { CODENOMAD_TEST_AUTOMATION_BUNDLE: "bundle", CODENOMAD_TEST_GUEST_URL: GUEST_URL } }, + performance: { now: () => now }, + setTimeout: (run: () => void, ms: number) => { const id = ++nextTimer; timers.set(id, { at: now + ms, run }); return id }, + clearTimeout: (id: number) => { timers.delete(id) }, + globalThis: {} as Record, + }) + context.globalThis = context + vm.runInContext(FIXTURE, context) + const settle = () => new Promise(resolve => setImmediate(resolve)) + const advance = async (ms: number) => { + const target = now + ms + for (;;) { + await settle() + const due = [...timers.entries()].filter(([, timer]) => timer.at <= target).sort((a, b) => a[1].at - b[1].at)[0] + if (!due) break + timers.delete(due[0]); now = due[1].at; due[1].run() + } + now = target + await settle() + } + return { + owner, guest, captures, timers, advance, settle, + setFocusedWindow: (value: object | null) => { focusedWindow = value }, + maxInFlight: () => maxInFlight, + load: () => handlers.get("did-stop-loading")!(), + async start(loaded = true) { + await settle() + attach!({}, guest) + const outcome = { done: false, value: undefined as any, error: undefined as Error | undefined } + ;(context.automationPreview.ready() as Promise).then(value => { outcome.value = value }, error => { outcome.error = error }) + .finally(() => { outcome.done = true }) + if (loaded) handlers.get("did-stop-loading")!() + await settle() + return outcome + }, + } +} + +const hidden = { visible: false, focused: false, focusedWindow: false } + +test("preparation retries only a pending surface, one capture at a time, until a non-empty capture", async () => { + const fixture = prepare() + const outcome = await fixture.start() + for (const message of PENDING) { fixture.captures.at(-1)!.reject(new Error(message)); await fixture.advance(50) } + fixture.captures.at(-1)!.resolve({ isEmpty: () => true }); await fixture.advance(50) + fixture.captures.at(-1)!.resolve({ isEmpty: () => false }); await fixture.settle() + assert.deepEqual(JSON.parse(JSON.stringify(outcome.value)), { loaded: true, rendered: true, before: hidden, after: hidden, captures: 5 }) + assert.equal(fixture.maxInFlight(), 1) + assert.equal(fixture.timers.size, 0, "no preparation timer outlives it") +}) + +test("any other capture error fails at once", async () => { + for (const message of ["Frame Gone", "Timeout", "EmbeddingTokenChanged", "Unknown", "Not implemented"]) { + const fixture = prepare() + const outcome = await fixture.start() + fixture.captures[0].reject(new Error(message)); await fixture.settle() + assert.equal(outcome.error?.message, message) + assert.equal(fixture.captures.length, 1) + assert.equal(fixture.timers.size, 0) + } +}) + +test("a capture that settles after the guest navigated, was destroyed or its window gained focus is refused", async () => { + const changes: Array<[string, (fixture: ReturnType) => void, RegExp]> = [ + ["navigation", fixture => { fixture.guest.url = `${GUEST_URL}late` }, /guest left/], + ["destruction", fixture => { fixture.guest.destroyed = true }, /guest was destroyed/], + ["window focus", fixture => { fixture.owner.focused = true }, /visible or focused/], + ["window shown", fixture => { fixture.owner.visible = true }, /visible or focused/], + ["application focus", fixture => { fixture.setFocusedWindow({}) }, /visible or focused/], + ] + for (const [name, change, expected] of changes) { + const fixture = prepare() + const outcome = await fixture.start() + change(fixture) + fixture.captures[0].resolve({ isEmpty: () => false }); await fixture.settle() + assert.match(String(outcome.error?.message), expected, name) + assert.equal(outcome.value, undefined, name) + } +}) + +test("one 10 s budget covers loading and capturing, including a load or capture that never settles", async () => { + const unloaded = prepare() + const waiting = await unloaded.start(false) + await unloaded.advance(9_999) + assert.equal(waiting.done, false) + await unloaded.advance(1) + assert.match(String(waiting.error?.message), /the guest did not load within 10000 ms/) + assert.equal(unloaded.captures.length, 0) + + const late = prepare() + const outcome = await late.start(false) + await late.advance(9_900) + late.load(); await late.settle() + assert.equal(late.captures.length, 1) + await late.advance(99) + assert.equal(outcome.done, false) + await late.advance(1) + assert.match(String(outcome.error?.message), /a guest capture did not settle within 10000 ms/) + assert.equal(late.timers.size, 0) + + const unhandled: unknown[] = [] + const record = (reason: unknown) => { unhandled.push(reason) } + process.on("unhandledRejection", record) + try { + late.captures[0].reject(new Error("Frame Gone")) + await late.settle(); await late.settle() + assert.deepEqual(unhandled, [], "a capture failing after the budget is not an unhandled rejection") + } finally { + process.off("unhandledRejection", record) + } +}) + +test("a surface that stays pending fails at the budget without a capture in flight beyond it", async () => { + const fixture = prepare() + const outcome = await fixture.start() + while (!outcome.done) { + fixture.captures.at(-1)!.reject(new Error("UnknownVizError")) + await fixture.advance(50) + } + assert.match(String(outcome.error?.message), /no rendered guest surface within 10000 ms/) + assert.equal(fixture.maxInFlight(), 1) + assert.equal(fixture.timers.size, 0) +}) diff --git a/packages/ui/tests/browser/automation-preview.test.ts b/packages/ui/tests/browser/automation-preview.test.ts index 618415169e..b994eb5cbc 100644 --- a/packages/ui/tests/browser/automation-preview.test.ts +++ b/packages/ui/tests/browser/automation-preview.test.ts @@ -56,7 +56,11 @@ test("the shared engine drives a real Electron preview through the guarded nativ // The guest must load before a snapshot; no installed app or foreground window is involved. const page = await running.firstWindow() await page.waitForFunction(() => Boolean(document.querySelector("webview"))) - assert.equal(await running.evaluate(() => (globalThis as any).automationPreview.ready()), true) + const hiddenOwner = { visible: false, focused: false, focusedWindow: false } + const { captures, ...prepared } = await running.evaluate(() => (globalThis as any).automationPreview.ready()) + assert.deepEqual(prepared, { loaded: true, rendered: true, before: hiddenOwner, after: hiddenOwner }, + "the guest renders before any input while its window stays hidden and unfocused") + assert.ok(captures >= 1) assert.equal((await execute({ action: "wait", text: "Title", gone: false, timeout: 15000 })).found, true, "the actual guest document is loaded before taking accessibility refs") const outline = String((await execute({ action: "snapshot" })).snapshot) diff --git a/packages/ui/tests/browser/automation-webkit-geometry.test.ts b/packages/ui/tests/browser/automation-webkit-geometry.test.ts index 4af3bb9ba1..f1e3ae1494 100644 --- a/packages/ui/tests/browser/automation-webkit-geometry.test.ts +++ b/packages/ui/tests/browser/automation-webkit-geometry.test.ts @@ -2,7 +2,7 @@ import assert from "node:assert/strict" import { test } from "node:test" import { readFileSync } from "node:fs" import { chromium, webkit } from "playwright" -import { armFixtureNavigationBudget } from "./mission-panel-route" +import { armFixtureNavigationBudget } from "./fixture-navigation-budget" import { nativeDriver } from "../../../server/src/automation/page/native-driver" import { performAction } from "../../../server/src/automation/page/actions" import { aim } from "../../../server/src/automation/page/input" diff --git a/packages/ui/tests/browser/automation-webkit-page.test.ts b/packages/ui/tests/browser/automation-webkit-page.test.ts index 11855789bf..cdacb4c850 100644 --- a/packages/ui/tests/browser/automation-webkit-page.test.ts +++ b/packages/ui/tests/browser/automation-webkit-page.test.ts @@ -2,7 +2,7 @@ import assert from "node:assert/strict" import { test } from "node:test" import { readFileSync } from "node:fs" import { chromium } from "playwright" -import { armFixtureNavigationBudget } from "./mission-panel-route" +import { armFixtureNavigationBudget } from "./fixture-navigation-budget" import { CLOSED_SHADOW_HOOK } from "../../../server/src/automation/page/webkit/hook" import { declaration } from "../../../server/src/automation/page/functions" import { nativeDriver } from "../../../server/src/automation/page/native-driver" diff --git a/packages/ui/tests/browser/fixture-exemptions.ts b/packages/ui/tests/browser/fixture-exemptions.ts index 65cbde4812..c33770328f 100644 --- a/packages/ui/tests/browser/fixture-exemptions.ts +++ b/packages/ui/tests/browser/fixture-exemptions.ts @@ -6,6 +6,7 @@ export const exemptions: Record = { "auth-recovery.test.ts": "stateful SSE middleware driven by the test", "automation-forms.test.ts": "electron automation harness; its machine-specific a11y flakiness pre-dates the daemon", "automation-input.test.ts": "served by a self-hosting harness or inline server that owns its Vite server", + "automation-preview-preparation.test.ts": "mocked Electron preparation; no fixture page", "automation-preview.test.ts": "electron fixture: runs a real Electron host with its own inline Vite define overrides", "automation-webkit-geometry.test.ts": "self-contained inline documents; no HTTP fixture server", "automation-webkit-page.test.ts": "self-contained data URL document; no HTTP fixture server", diff --git a/packages/ui/tests/browser/fixtures/automation-preview-electron.cjs b/packages/ui/tests/browser/fixtures/automation-preview-electron.cjs index 1bf6eaede8..6d3ebea46e 100644 --- a/packages/ui/tests/browser/fixtures/automation-preview-electron.cjs +++ b/packages/ui/tests/browser/fixtures/automation-preview-electron.cjs @@ -1,7 +1,46 @@ // No application profile, backend or visible desktop window. The production controller's // ownership/registration checks still run; visibility is supplied by this fixture explicitly. +// Production drives visible previews; this hidden fixture prepares its guest's rendered surface first. const { app, BrowserWindow } = require("electron") app.setPath("userData", process.env.CODENOMAD_TEST_PROFILE) + +const PREPARATION_MS = 10_000 +const PROBE_INTERVAL_MS = 50 +const PENDING_SURFACE = new Set(["Current display surface not available for capture", "UnknownVizError", "VizSentEmptyBitmap"]) + +function withinBudget(promise, deadline, failure) { + let timer + return Promise.race([ + promise, + new Promise((_resolve, reject) => { + timer = setTimeout(() => reject(new Error(`Preview preparation: ${failure} within ${PREPARATION_MS} ms`)), Math.max(0, deadline - performance.now())) + }), + ]).finally(() => clearTimeout(timer)) +} + +function assertPrepared(target, owner, expectedUrl, deadline) { + if (target.isDestroyed()) throw new Error("Preview preparation: the guest was destroyed") + if (target.getURL() !== expectedUrl) throw new Error(`Preview preparation: the guest left ${expectedUrl}`) + const state = ownerState(owner) + if (state.visible || state.focused || state.focusedWindow) throw new Error("Preview preparation: the window became visible or focused") + if (performance.now() >= deadline) throw new Error(`Preview preparation: no rendered guest surface within ${PREPARATION_MS} ms`) +} + +async function awaitHiddenSurface(target, owner, expectedUrl, deadline) { + for (let captures = 1; ; captures++) { + assertPrepared(target, owner, expectedUrl, deadline) + const outcome = await withinBudget(target.capturePage({ x: 0, y: 0, width: 1, height: 1 }, { stayHidden: true }) + .then(image => ({ image }), error => ({ error })), deadline, "a guest capture did not settle") + assertPrepared(target, owner, expectedUrl, deadline) + if (outcome.image && !outcome.image.isEmpty()) return captures + if (outcome.error && !PENDING_SURFACE.has(outcome.error.message)) throw outcome.error + await new Promise(resolve => setTimeout(resolve, Math.min(PROBE_INTERVAL_MS, Math.max(0, deadline - performance.now())))) + } +} + +function ownerState(owner) { + return { visible: owner.isVisible(), focused: owner.isFocused(), focusedWindow: BrowserWindow.getFocusedWindow() !== null } +} app.whenReady().then(async () => { const { BrowserController, BrowserPage, handleNativeBrowserRequest } = require(process.env.CODENOMAD_TEST_AUTOMATION_BUNDLE) const window = new BrowserWindow({ show: false, width: 900, height: 700, @@ -29,7 +68,13 @@ app.whenReady().then(async () => { execute: action => browser.execute("fixture-session", action), navigate: url => controller.execute("fixture-session", { action: "navigate", url }), visible: value => { visible = value }, - ready: async () => { await guestLoaded; return Boolean(guest && !guest.isLoading()) }, + ready: async () => { + const deadline = performance.now() + PREPARATION_MS + await withinBudget(guestLoaded, deadline, "the guest did not load") + const before = ownerState(window) + const captures = await awaitHiddenSurface(guest, window, process.env.CODENOMAD_TEST_GUEST_URL, deadline) + return { loaded: !guest.isLoading(), rendered: true, before, after: ownerState(window), captures } + }, } const html = `` await window.loadURL(`data:text/html,${encodeURIComponent(html)}`) diff --git a/packages/ui/tests/browser/http-admission-responsiveness.test.ts b/packages/ui/tests/browser/http-admission-responsiveness.test.ts index afbee9e33a..04f17ebf0c 100644 --- a/packages/ui/tests/browser/http-admission-responsiveness.test.ts +++ b/packages/ui/tests/browser/http-admission-responsiveness.test.ts @@ -108,7 +108,7 @@ async function harness() { getWorktreeIdentityForPath: async () => "/fixture", getSessionEnvironment: async () => ({}), ownsDirectory: async (_id: string, directory: string) => directory === "/fixture", - ownsLocation: async (_id: string, location: { directory: string }, _client: unknown, signal?: AbortSignal) => + ownsLocation: async (_id: string, location: { directory: string }, _client: unknown, { signal }: { signal?: AbortSignal } = {}) => location.directory === "/fixture" && (await native.location.get({ location }, { signal })).directory === "/fixture", } as unknown as InstanceProxyWorkspaceManager const backend = Fastify({ forceCloseConnections: true }) diff --git a/packages/ui/tests/browser/mission-actions.ts b/packages/ui/tests/browser/mission-actions.ts index d7d6902fc2..5cf5a5e2cc 100644 --- a/packages/ui/tests/browser/mission-actions.ts +++ b/packages/ui/tests/browser/mission-actions.ts @@ -1,4 +1,4 @@ -import type { ElementHandle, Locator, Page } from "playwright" +import type { Locator, Page } from "playwright" /** Exercise a `MissionListItem` action through its inline or measured-overflow presentation * (cleanup receipts and other shared list rows; the Mission picker has no row menus). */ @@ -60,9 +60,9 @@ export async function selectMission(page: Page, title: string | RegExp): Promise const entry = await inlineMissionEntry(page, title) // Often the first wait after navigation: allow for a cold page boot late in a long serial run. await entry.waitFor({ timeout: 60_000 }) - // Held as an element: rows are keyed, but a refresh may retitle the row once it is selected. - const row = (await entry.locator("xpath=..").elementHandle())! - if (await entry.getAttribute("aria-current") !== "true") await entry.click() + // A refresh may retitle or replace the row after selection. Retain its identity, not its DOM node. + const row = await stableMissionRow(entry), select = row.locator(".mission-row-select") + if (await select.getAttribute("aria-current") !== "true") await select.click() // Like the session list, a click only selects: its chevron expands the row, showing its detail. // A Mission whose plan holds no task has no chevron: its (empty) detail stays folded. const leaf = await expandRowElement(row) === "leaf" @@ -75,14 +75,22 @@ export async function selectMission(page: Page, title: string | RegExp): Promise * "leaf" when the row has no chevron (a Mission without tasks). */ export async function expandRow(select: Locator): Promise<"expanded" | "leaf"> { await select.waitFor({ state: "attached" }) - return expandRowElement((await select.locator("xpath=..").elementHandle())!) + return expandRowElement(await stableMissionRow(select)) } -/** `expandRow` on a row's `.session-item-base` element. */ -async function expandRowElement(row: ElementHandle): Promise<"expanded" | "leaf"> { - const chevron = await row.$(".session-item-expander:not(.session-item-expander--spacer)") - if (!chevron) return "leaf" +async function stableMissionRow(select: Locator): Promise { + const key = await select.locator("xpath=ancestor::*[@data-mission-key][1]").getAttribute("data-mission-key") + if (!key) throw new Error("Mission row identity unavailable") + return missionRows(select.page()).locator(`[data-mission-key=${JSON.stringify(key)}]`) +} + +/** `expandRow` on an identity-bound row locator, including across passive replacement. */ +async function expandRowElement(row: Locator): Promise<"expanded" | "leaf"> { + const chevron = row.locator(".session-item-expander") + await chevron.waitFor({ state: "attached" }) + if ((await chevron.getAttribute("class"))?.includes("session-item-expander--spacer")) return "leaf" if (await chevron.getAttribute("aria-expanded") !== "true") await chevron.click() + await row.locator('.session-item-expander[aria-expanded="true"]').waitFor() return "expanded" } diff --git a/packages/ui/tests/browser/settings-info-tip.test.ts b/packages/ui/tests/browser/settings-info-tip.test.ts index 678b754fa7..6d2889079c 100644 --- a/packages/ui/tests/browser/settings-info-tip.test.ts +++ b/packages/ui/tests/browser/settings-info-tip.test.ts @@ -29,10 +29,12 @@ async function setup(page: Page, host = "web", context = "remote") { w.opened = [] w.attempts = 0 w.failOpen = false + w.holdOpen = false window.open = (...args) => { w.attempts++; if (w.failOpen) throw new Error("opener failure"); w.opened.push(args); return null } w.__TAURI_INTERNALS__ = { invoke: async (command, args) => { if (command === "open_external_url") { w.attempts++ + if (w.holdOpen) await new Promise(resolve => { w.releaseOpen = resolve }) if (w.failOpen) throw new Error("opener failure") w.opened.push([command, args]) } @@ -65,7 +67,15 @@ for (const [host, context] of [["web", "remote"], ["electron", "local"], ["tauri assert.deepEqual(await opened(page), [0, 1].map(() => `${base}en/settings.html#keep-computer-awake`)) assert.equal(await page.locator(".settings-choice-row input").isChecked(), false) assert.deepEqual(await page.evaluate(() => [(window as any).fixture.changed(), (window as any).fixture.leaked()]), [0, 0]) + const native = host === "tauri" && context !== "remote" + if (native) await page.evaluate(() => { (window as any).holdOpen = true }) await page.locator("summary [role=link]").click() + if (native) { + await page.waitForFunction(() => typeof (window as any).releaseOpen === "function") + assert.equal((await opened(page)).length, 2, "native admission alone is not an opening receipt") + await page.evaluate(() => (window as any).releaseOpen()) + } + await page.waitForFunction(() => (window as any).opened.length === 3) assert.equal(await page.locator("details").getAttribute("open"), null) assert.equal((await opened(page)).at(-1), `${base}en/opencode.html#session-environment`) assert.equal(page.url(), url) diff --git a/packages/ui/tests/contracts/mission-defaults.test.ts b/packages/ui/tests/contracts/mission-defaults.test.ts new file mode 100644 index 0000000000..9730c8332c --- /dev/null +++ b/packages/ui/tests/contracts/mission-defaults.test.ts @@ -0,0 +1,71 @@ +import assert from "node:assert/strict" +import { test } from "node:test" +import * as server from "../../../server/src/missions/profile-defaults" +import * as ui from "../../src/lib/mission-defaults" +import { freezeCompareProfiles, missionProfileRoles } from "../../../server/src/missions/playbook-profiles" +import type { MissionTemplateId } from "../../../server/src/missions/model" + +test("UI creation defaults and server resolution agree for all five templates, including the inherited Compare judge", () => { + const coordinator = { agent: "coordinator", model: { providerID: "p", id: "coordinator", variant: "high" } } + const specialist = { agent: "worker", model: { providerID: "p", id: "worker" } } + const templates = Object.keys(missionProfileRoles) as MissionTemplateId[] + const cases: unknown[] = [undefined, [], + [{ template: "all", profiles: { coordinator, roles: { specialist } }, taskMode: "independent" }], + [{ template: "custom", profiles: { coordinator, roles: { specialist } }, taskMode: "independent" }], + [{ template: "all", profiles: { coordinator, roles: { specialist } }, taskMode: "independent" }, + ...templates.map(template => ({ template, profiles: { coordinator: { agent: "typed" }, + roles: { [missionProfileRoles[template][0]]: {} } }, taskMode: "native" }))], + [{ template: "all", profiles: { coordinator } }, { template: "compare", profiles: { roles: { comparator: specialist } } }], + ...[{}, { agent: "judge" }].map(comparator => [ + { template: "all", profiles: { coordinator } }, { template: "compare", profiles: { roles: { comparator } } }, + ]), + ] + for (const preferences of cases) for (const template of templates) { + const normalized = ui.normalizeMissionDefaults(preferences) + const payload = freezeCompareProfiles(template, ui.missionDefaultsFor(normalized, template)) + const result = server.resolveMissionCreationDefaults({ template, preferences }) + const roles = Object.fromEntries(missionProfileRoles[template].map(role => [role, + payload?.roles?.[role] ?? {}])) + assert.deepEqual(result.profiles, { coordinator: payload?.coordinator ?? {}, roles }, template) + assert.equal(result.taskMode, ui.missionTaskModeFor(normalized, template), template) + } +}) + +test("effective editor and server Compare payloads agree for explicit and preferred judge slots", () => { + const coordinator = { model: { providerID: "p", id: "coordinator", variant: "high" } } + const runs = { "model-a": { model: { providerID: "p", id: "a" } }, "model-b": { model: { providerID: "p", id: "b" } } } + for (const comparator of [{}, { agent: "judge" }, { agent: "judge", model: { providerID: "p", id: "own" } }]) { + for (const source of ["explicit", "preference"] as const) { + const profiles = { coordinator, roles: { ...runs, comparator } } + const preferences = source === "preference" ? [{ template: "compare", profiles }] : [] + const payload = freezeCompareProfiles("compare", source === "preference" + ? ui.missionDefaultsFor(ui.normalizeMissionDefaults(preferences), "compare") : profiles) + const resolved = server.resolveMissionCreationDefaults({ template: "compare", preferences, + ...(source === "explicit" ? { profiles } : {}) }) + assert.deepEqual(resolved.profiles, payload) + assert.equal(resolved.origins.roles.comparator, source) + assert.deepEqual(resolved.profiles.roles.comparator.model, comparator.model ?? coordinator.model) + } + } +}) + +test("editor defaults keep the judge inherited while explicit whole drafts never reapply preferences", () => { + const coordinator = { model: { providerID: "p", id: "coordinator" } } + for (const comparator of [undefined, {}, { agent: "judge" }, { model: { providerID: "p", id: "own" } }]) { + const preferences = ui.normalizeMissionDefaults([{ template: "all", profiles: { coordinator } }, + { template: "compare", profiles: { roles: comparator === undefined ? {} : { comparator } } }]) + const before = structuredClone(preferences) + const draft = ui.missionDefaultsFor(preferences, "compare") + const payload = freezeCompareProfiles("compare", draft) + assert.ok(draft) + assert.deepEqual(draft.roles?.comparator, comparator, "loading keeps the judge's editable slot unfrozen") + draft.coordinator = { model: { providerID: "p", id: "changed" } } + const updated = freezeCompareProfiles("compare", draft) + assert.deepEqual(updated?.roles?.comparator?.model, comparator?.model ?? draft.coordinator.model) + assert.deepEqual(payload?.roles?.comparator?.model, comparator?.model ?? coordinator.model, "earlier payloads remain frozen") + assert.deepEqual(preferences, before) + } + for (const profiles of [undefined, {}, { coordinator: {} }, { roles: { comparator: {} } }]) { + assert.deepEqual(freezeCompareProfiles("compare", profiles), profiles, "explicit empty choices stay empty without a known coordinator model") + } +}) diff --git a/scripts/test-missions-native.mjs b/scripts/test-missions-native.mjs index 54abce5160..8295cc424e 100644 --- a/scripts/test-missions-native.mjs +++ b/scripts/test-missions-native.mjs @@ -147,7 +147,7 @@ try { await mkdir(fixturePlugin) // Test-only RPC drives the actual registered tool executors without relying on LLM decisions. await writeFile(path.join(fixturePlugin, "index.ts"), `import { Plugin, Rpc } from '@opencode/plugin/effect' - import { Effect } from 'effect' + import { Cause, Effect } from 'effect' export default Plugin.define({ id: 'missions.fixture', effect: Effect.fn(function*(ctx) { yield* ctx.session.hook('http.request', event => Effect.sync(() => { event.request.headers.set('x-fixture-kind', event.kind) @@ -158,7 +158,8 @@ try { const tool = (yield* ctx.tool.list()).find(tool => tool.id === 'mission_' + input.tool) if (!tool) throw new Error('Mission tool unavailable') const result = yield* tool.execute(input.input, { sessionID: input.sessionID, agent: 'build', messageID: 'msg_fixture', - id: input.callID, progress: () => Effect.void, signal }) + id: input.callID, progress: () => Effect.void, signal }).pipe(Effect.catchCause(cause => + Effect.succeed({ content: JSON.stringify({ fixtureToolError: Cause.pretty(cause) }) }))) return result.content }), panelShape: input => Effect.succeed(input) }) }) })`) @@ -182,8 +183,12 @@ try { receipt.runtime = { version: info.version, pid: info.pid, url } rememberRuntime(endpoint, { version: info.version, pid: info.pid, discovery: "info" }) let variables = { MISSION_FIXTURE: "first" } + let preferenceReads = 0, uiPreferences = {} + const settings = { getOwner: () => ({ environmentVariables: variables }), + getRawConfigOwner: owner => { assert.equal(owner, "ui"); preferenceReads++; return structuredClone(uiPreferences) }, + readEnvironmentForAdmission: async () => ({ ...variables }) } manager = new WorkspaceManager({ rootDir: root, logger: pino({ level: "silent" }), eventBus: new EventBus(), - settings: { getOwner: () => ({ environmentVariables: variables }), readEnvironmentForAdmission: async () => ({ ...variables }) }, + settings, binaryResolver: { resolveDefault: () => ({ path: cli, label: "Isolated missions" }) }, hostServiceLifecycleFactory: () => ({ discover: async () => endpoint, ensure: async () => endpoint }), }) @@ -223,7 +228,7 @@ try { const worktreeDeletionFence = new WorktreeDeletionFence() registerMissionRoutes(bridge, { workspaceManager: manager, worktreeDeletionFence, auth }) registerAutomationPluginRoute(bridge, { workspaceManager: manager, worktreeDeletionFence, - authManager: auth, bridgeToken: registration.token, nativeParent: {}, developerCdp: {} }) + authManager: auth, settings, bridgeToken: registration.token, nativeParent: {}, developerCdp: {} }) await bridge.listen({ host: "127.0.0.1", port: 0 }) registration.url = `http://127.0.0.1:${bridge.server.address().port}/api/opencode-plugin/automation` removeBridge = await publishAutomationBridge(registration) @@ -274,11 +279,78 @@ try { // Mission tools return compact readouts; checks below read the resulting map from the native snapshot. const invoke = async (tool, input, sessionID = coordinator.id, callID = `fixture-${tool}`) => { const result = JSON.parse(await client.rpc(invocation).invoke({ tool, input, sessionID, callID }, { location })) + if (typeof result.fixtureToolError === "string") throw new Error(result.fixtureToolError) if (result.missionID === undefined) return result const { missions } = await client.rpc(CODENOMAD_MISSIONS_RPC).snapshot({}, { location }) - return { ...result, mission: missions.find(mission => mission.id === result.missionID) } + const mission = missions.find(mission => mission.id === result.missionID) + if (mission) delete mission.creationDefaults + return { ...result, mission } + } + stage = "nonempty owning-backend creation preferences" + { + const caller = await client.session.create({ location, title: "Private preference preflight", agent: "build", + model: { providerID: "fixture", id: "fixture" } }) + const profiles = { coordinator: { agent: "build", model: { providerID: "fixture", id: "fixture" } }, + roles: { specialist: { agent: "reviewer", model: { providerID: "fixture", id: "selected", variant: "careful" } } } } + const preferred = { template: "all", profiles, taskMode: "independent" } + uiPreferences = { settings: { missionProfileDefaults: [{ ...preferred, profiles: { ...profiles, coordinator: { agent: "reviewer" } } }] } } + const before = await client.rpc(CODENOMAD_MISSIONS_RPC).snapshot({}, { location }) + const { DatabaseSync } = await import("node:sqlite") + const database = new DatabaseSync(process.env.OPENCODE_DB, { readOnly: true }) + try { + database.exec("PRAGMA busy_timeout = 10000") + const rows = () => database.prepare("SELECT key, value FROM kv WHERE key LIKE ? ORDER BY key").all("%codenomad-missions/%") + const retained = rows(), reads = preferenceReads, turns = requests.length + await assert.rejects(invoke("inspect", { start: { objective: "Refuse coordinator mismatch", template: "custom" } }, + caller.id, "preferences-mismatch"), /Coordinator differs from the profile selected by Missions preferences\. Pass profiles\.coordinator \(for example \{\}\) to override that preference\./) + assert.ok(preferenceReads > reads, "The mismatch was resolved against nonempty owner preferences") + const after = await client.rpc(CODENOMAD_MISSIONS_RPC).snapshot({}, { location }) + assert.deepEqual({ ...after, generatedAt: before.generatedAt }, before) + assert.deepEqual(rows(), retained, "Coordinator mismatch writes no creation event, document or retained intent") + assert.equal(requests.length, turns, "Coordinator mismatch admits no provider turn") + } finally { database.close() } + uiPreferences = { settings: { missionProfileDefaults: [preferred] } } + const start = { objective: "Persist owning-backend preferences", template: "custom" } + const selected = await invoke("inspect", { start }, caller.id, "preferences-create") + const origins = { coordinator: "preference", roles: { specialist: "preference" }, taskMode: "preference" } + const selection = { profiles, taskMode: "independent", origins } + assert.deepEqual(selected.selection, selection) + assert.equal("creationDefaults" in selected.mission, false) + await play(selected.mission) + const prepared = await invoke("prepare", { requestID: "preferences-handoff", objective: "Preferred hand-off", template: "custom" }, + caller.id, "preferences-prepare") + assert.deepEqual(prepared.selection, selection) + assert.equal("creationDefaults" in prepared.mission, false) + const saved = await client.rpc(CODENOMAD_MISSIONS_RPC).snapshot({}, { location }) + for (const result of [selected, prepared]) { + const mission = saved.missions.find(mission => mission.id === result.mission.id) + assert.deepEqual(mission.profiles, profiles) + assert.equal(mission.taskMode, "independent") + assert.deepEqual(mission.creationDefaults, { request: {}, ...selection }) + assert.deepEqual(mission.creationDefaults.origins, origins) + assert.equal([mission.creationDefaults.origins.coordinator, ...Object.values(mission.creationDefaults.origins.roles), + mission.creationDefaults.origins.taskMode].filter(origin => origin === "preference").length, 3) + } + uiPreferences = {} + const reads = preferenceReads + assert.deepEqual((await invoke("inspect", { start }, caller.id, "preferences-create")).selection, selection) + assert.deepEqual((await invoke("prepare", { requestID: "preferences-handoff", objective: "Preferred hand-off", template: "custom" }, + caller.id, "preferences-prepare")).selection, selection) + assert.equal(preferenceReads, reads, "Saved provenance and choices replay without consulting changed preferences") + const finished = await invoke("report", { missionID: selected.mission.id, outcome: "completed", summary: "Preferences verified", final: true }, + caller.id, "preferences-finish") + assert.equal(finished.mission.status, "completed") + for (const mission of [prepared.mission, finished.mission]) { + const deletion = { missionID: mission.id, requestID: `preferences-delete-${mission.id}`, expectedRevision: mission.revision } + assertDocumentDeletion(await client.rpc(CODENOMAD_MISSIONS_RPC).delete(deletion, { location }), deletion, mission.objective) + } + assert.equal((await client.rpc(CODENOMAD_MISSIONS_RPC).snapshot({}, { location })).missions.length, before.missions.length) + gate("nonempty owner preferences: coordinator mismatch has no effects, both creation paths persist profiles/policy/provenance and replay frozen choices") } const inspected = await invoke("inspect", { catalog: true, start: { objective: "Native integration", template: "custom" } }) + assert.equal(inspected.selection.preferences, undefined, "The owning fixture backend supplied readable preferences") + assert.ok(preferenceReads > 0, "Agent creation exercised the owning backend's raw UI reader") + assert.equal(inspected.selection.origins.coordinator, "opencode-default") assert(inspected.catalog.agents.some(agent => agent.id === "reviewer")) assert(inspected.catalog.models.some(model => model.id === "selected" && model.variants.includes("careful"))) gate("native catalog and configured variant discovery")