From 4875a7f42b5eee6418b63475ddb0156fa6a973bd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pascal=20Andr=C3=A9?= Date: Thu, 5 Nov 2026 23:24:28 +0100 Subject: [PATCH 01/16] fix(missions): inherit user profiles in agent preparations Agent-created preparations now fill missing coordinator, role and task-mode choices from the user's Missions preferences. Explicit whole slots remain authoritative, including empty and agent-only selections, and both preparation tools return the recorded choices and their origins. Share the editor's pure defaults implementation with the server and read the owning backend's raw UI configuration over the authenticated bridge. Invalid or unreadable preferences fail with fixed actionable errors; native catalog and existing-coordinator checks remain authoritative. The editor's already-frozen create payloads are unchanged. Persist bounded pre-dispatch intentions and optional creation provenance through native RPC, journal and unified-document codecs. Retries preserve original inputs and choices across lost replies, restarts, preference changes and later editor updates. Uncertain preparation evidence survives subsequent prevalidation refusals, while an omitted Compare judge freezes the known coordinator model without completing explicit judge slots. Ordinary sessions are directed to the Missions editor. Validated shared defaults and UI contracts, authenticated preference failures, both tool responses, uncertain retries, Compare and historical mission compatibility. The extended Missions suite passed 1087 tests with two Windows skips at concurrency four; final targeted regressions passed 87 tests. Server/UI typechecks, native-plugin build invariants, the Missions bundle build and whitespace checks passed. --- .github/workflows/pr-build.yml | 1 + packages/server/src/missions/control-types.ts | 7 + packages/server/src/missions/control.ts | 134 ++++++++++--- .../src/missions/coordinator-actions.test.ts | 135 ++++++++++++- .../src/missions/creation-defaults.test.ts | 131 +++++++++++++ .../server/src/missions/creation-defaults.ts | 58 ++++++ .../src/missions/creation-intent.test.ts | 68 +++++++ .../server/src/missions/creation-intent.ts | 78 ++++++++ packages/server/src/missions/journal.ts | 9 +- .../src/missions/mission-document-one-time.ts | 1 + .../src/missions/mission-document-store.ts | 3 +- .../server/src/missions/mission-document.ts | 2 + packages/server/src/missions/model.ts | 3 + .../src/missions/profile-defaults.test.ts | 181 ++++++++++++++++++ .../server/src/missions/profile-defaults.ts | 122 ++++++++++++ .../server/src/missions/recovery-error.ts | 4 + packages/server/src/missions/rpc.ts | 3 + ...automation-plugin-profile-defaults.test.ts | 87 +++++++++ .../server/src/opencode/automation-plugin.ts | 28 ++- .../src/opencode/missions-plugin.test.ts | 67 ++++++- .../server/src/opencode/missions-plugin.ts | 21 +- .../src/opencode/missions/desktop-plugin.ts | 1 + .../src/server/routes/automation-plugin.ts | 6 +- .../routes/mission-creation-fence.test.ts | 83 +++++++- .../routes/mission-creation-pipeline.ts | 9 +- .../src/server/routes/mission-prepare.ts | 7 +- .../routes/mission-profile-defaults.test.ts | 87 +++++++++ .../server/routes/mission-profile-defaults.ts | 42 ++++ packages/ui/src/lib/mission-defaults.ts | 67 +------ .../tests/contracts/mission-defaults.test.ts | 35 ++++ 30 files changed, 1342 insertions(+), 138 deletions(-) create mode 100644 packages/server/src/missions/creation-defaults.test.ts create mode 100644 packages/server/src/missions/creation-defaults.ts create mode 100644 packages/server/src/missions/creation-intent.test.ts create mode 100644 packages/server/src/missions/creation-intent.ts create mode 100644 packages/server/src/missions/profile-defaults.test.ts create mode 100644 packages/server/src/missions/profile-defaults.ts create mode 100644 packages/server/src/opencode/automation-plugin-profile-defaults.test.ts create mode 100644 packages/server/src/server/routes/mission-profile-defaults.test.ts create mode 100644 packages/server/src/server/routes/mission-profile-defaults.ts create mode 100644 packages/ui/tests/contracts/mission-defaults.test.ts diff --git a/.github/workflows/pr-build.yml b/.github/workflows/pr-build.yml index 4b1122f391..5151c9c62d 100644 --- a/.github/workflows/pr-build.yml +++ b/.github/workflows/pr-build.yml @@ -427,6 +427,7 @@ jobs: packages/ui/src/stores/mission-store.test.ts packages/ui/src/stores/mission-task-pages.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/packages/server/src/missions/control-types.ts b/packages/server/src/missions/control-types.ts index c6bab3bb6a..b87f830daf 100644 --- a/packages/server/src/missions/control-types.ts +++ b/packages/server/src/missions/control-types.ts @@ -5,6 +5,7 @@ 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, MissionCreationDefaults, MissionCreationSelection } from "./creation-defaults" export interface NativeMissionSession extends MissionExecution { id: string @@ -124,6 +125,7 @@ export type MissionNativeReportAuthorization = (request: MissionNativeReportRequ }> export interface MissionInspection { + selection?: MissionCreationSelection mission: MissionMap | null actor: MissionActor | null templates: ReturnType @@ -135,6 +137,8 @@ export interface MissionInspection { } export interface MissionCreateInput extends MissionStartInput { + /** Original agent request and frozen preference provenance, supplied by the owning backend. */ + creationDefaults?: MissionCreationDefaults /** Optional short label (1–60 characters, trimmed). */ title?: string prepared?: boolean @@ -182,6 +186,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 +201,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?: MissionCreationDefaults requestID: string objective: string title?: string diff --git a/packages/server/src/missions/control.ts b/packages/server/src/missions/control.ts index 3209a308e0..d3bf1b6ba7 100644 --- a/packages/server/src/missions/control.ts +++ b/packages/server/src/missions/control.ts @@ -8,6 +8,8 @@ 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 MissionCreationDefaults } from "./creation-defaults" +import { MissionCreationIntents } from "./creation-intent" 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" @@ -70,6 +72,7 @@ import type { MissionDeleteInput, MissionReviseInput, MissionInspectInput, + MissionStartInput, MissionInspection, MissionProject, MissionPrepareRequest, @@ -93,6 +96,7 @@ export interface MissionNotificationRetryResult { export class MissionControl { private readonly journal: MissionJournal + private readonly creationIntents: MissionCreationIntents private lastTimestamp = 0 constructor(private readonly options: { @@ -116,6 +120,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) } async snapshot(): Promise { @@ -403,10 +408,43 @@ export class MissionControl { return this.mutate(() => this.createCurrent(request)) } - private compareCreationProfiles(template: MissionMap["template"], profiles?: MissionProfiles, coordinatorModel?: NativeMissionSession["model"]): MissionProfiles | undefined { + private compareCreationProfiles(template: MissionMap["template"], profiles?: MissionProfiles, coordinatorModel?: NativeMissionSession["model"], freeze = true): MissionProfiles | undefined { const error = template === "compare" && compareModelError(profiles) if (error) throw new MissionControlError(error, "invalid-execution") - return freezeCompareProfiles(template, profiles, coordinatorModel) + return freeze ? freezeCompareProfiles(template, profiles, coordinatorModel) : profiles + } + + private async resolveCreationInput(sessionID: string, input: T, missionID: string, conflict = "request-conflict", + coordinatorModel?: NativeMissionSession["model"], retainedIntent?: () => void): Promise { + const retained = await this.creationIntents.read(missionID, input, () => this.journal.event(missionID, this.eventID(missionID, "created")), conflict) + if (retained) { + retainedIntent?.() + return { ...input, profiles: retained.profiles, taskMode: retained.taskMode, creationDefaults: retained } + } + 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 new MissionControlError("Creation request ID was already used with a different mission", conflict) + retainedIntent?.() + return { ...input, profiles: frozen.profiles, taskMode: frozen.taskMode, creationDefaults: frozen } + } + const resolve = this.options.transport?.resolveCreationDefaults + // Internal journal-only consumers supply their own frozen profiles. Desktop + // tools always install the authenticated owning-backend resolver. + if (!resolve) return input + const request = missionCreationChoices(input) + const selection = parseMissionCreationSelection(input.template, await resolve(sessionID, { template: input.template, ...request, + ...(coordinatorModel === undefined ? {} : { coordinatorModel }) })) + return { ...input, profiles: selection.profiles, taskMode: selection.taskMode, creationDefaults: { request, ...selection } } + } + + 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 async createCurrent(input: MissionCreateInput): Promise<{ mission: MissionMap }> { @@ -419,7 +457,7 @@ 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) + input.profiles = this.compareCreationProfiles(input.template, input.profiles, undefined, !input.creationDefaults) 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 +473,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 +484,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. @@ -462,6 +502,15 @@ export class MissionControl { if (suppliedCoordinator && input.expectedCoordinatorLocation && !sameLocation(suppliedCoordinator.location, input.expectedCoordinatorLocation)) throw new MissionControlError("Coordinator moved from its admitted creation location", "foreign-session") + const proposed = input + input = await this.retainCreationInput(input, missionID) + if (!sameMissionProfiles(proposed.profiles, input.profiles) || proposed.taskMode !== input.taskMode) { + try { await this.options.validateProfiles?.(input.profiles, input.expectedCoordinatorLocation?.directory ?? this.options.project.location.directory, input.taskMode!) } + catch { throw new MissionControlError("Mission profiles do not match the owned native catalog", "invalid-execution") } + if (suppliedCoordinator && !matchesExecution(input.profiles?.coordinator, suppliedCoordinator)) + throw new MissionControlError("Coordinator does not have the requested native profile", "invalid-execution") + } + const reservedAt = this.timestamp(snapshot) const document = this.options.documents ? await prepareMissionOneTimeDocument(this.options.documents, this.options.project, missionID, input, input.coordinatorSessionID ?? missionCoordinatorSessionID(missionID, reservedAt), reservedAt, @@ -514,6 +563,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 +572,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) } } @@ -921,43 +972,53 @@ export class MissionControl { private async inspectCurrent(sessionID: string, input: MissionInspectInput, operationID: string): 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 = `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")) 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) { + const original = created?.type === "mission.created" && created.creationDefaults ? created : replay + const sameChoices = created?.type === "mission.created" && created.creationDefaults + ? sameMissionCreationChoices(created.creationDefaults.request, input.start) + : sameMissionProfiles(replay.profiles, this.compareCreationProfiles(input.start.template, input.start.profiles, replay.profiles?.roles?.comparator?.model)) + && (replay.taskMode ?? "native") === parseMissionTaskMode(input.start.taskMode) + if (original.template !== input.start.template || original.objective !== input.start.objective + || original.notes !== input.start.notes || !sameChoices) { throw new MissionControlError("Creation request ID was already used with a different mission", "request-conflict") } + 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) } + let resolved = await this.resolveCreationInput(sessionID, input.start, missionID, "request-conflict", caller.model) + const taskMode = parseMissionTaskMode(resolved.taskMode) + resolved.profiles = this.compareCreationProfiles(resolved.template, resolved.profiles, caller.model, !resolved.creationDefaults) + 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") } + resolved = await this.retainCreationInput(resolved, missionID) + input.start = { ...resolved, taskMode: parseMissionTaskMode(resolved.taskMode) } const event: MissionEvent = { version: MISSION_SCHEMA_VERSION, id: this.eventID(missionID, "created"), @@ -970,6 +1031,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 +1042,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) } @@ -1007,9 +1070,8 @@ export class MissionControl { async prepare(sessionID: string, input: MissionPrepareRequest): Promise<{ mission: MissionMap }> { await this.ownedRootSession(sessionID) 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") // 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)}` @@ -1017,18 +1079,39 @@ export class MissionControl { 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" && created.creationDefaults + ? sameMissionCreationChoices(created.creationDefaults.request, input) + : created.type === "mission.created" && (created.taskMode ?? "native") === (input.taskMode ?? "native") + && sameMissionProfiles(created.profiles, this.compareCreationProfiles(input.template, input.profiles)) 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") } 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 }) + let retainedIntent = false + input = await this.resolveCreationInput(sessionID, input, missionID, "prepare-conflict", undefined, () => { retainedIntent = true }) + input = { ...input, profiles: this.compareCreationProfiles(input.template, input.profiles, undefined, !input.creationDefaults) } + 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() + let result: unknown + try { result = await this.options.transport.prepare(sessionID, { ...structuredClone(input), requestID, missionID: source.id }) } + catch (error) { + if (retainedIntent && error instanceof MissionControlError && error.code === "prepare-refused") + throw new MissionControlError("The prepared mission's outcome is uncertain; retry with the same requestID", "prepare-uncertain") + throw error + } 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) { @@ -1722,6 +1805,7 @@ export class MissionControl { private inspection(mission: MissionMap, sessionID: string): MissionInspection { return { mission, + ...(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..cec1de900c 100644 --- a/packages/server/src/missions/coordinator-actions.test.ts +++ b/packages/server/src/missions/coordinator-actions.test.ts @@ -1,16 +1,18 @@ import assert from "node:assert/strict" import test from "node:test" -import { MissionControl } from "./control" +import { MissionControl, MissionControlError } from "./control" 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 +24,9 @@ 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; + 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,15 +38,16 @@ 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, 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("one replacement may merge several retired tasks; it names one of them as its lineage head", async () => { @@ -93,6 +97,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 +123,131 @@ 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"]) + 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 later preparation refusal preserves its original profile intention", 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) + assert.deepEqual(result.mission.creationDefaults?.profiles?.roles?.specialist, { agent: "worker-before" }) +}) + +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.deepEqual(first.mission?.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"), /differs from the requested native profile/) + 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("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..5dc27a0f42 --- /dev/null +++ b/packages/server/src/missions/creation-defaults.test.ts @@ -0,0 +1,131 @@ +import assert from "node:assert/strict" +import test from "node:test" +import Ajv from "ajv" +import { MissionControl } from "./control" +import type { MissionInputTransport, NativeMissionSession } from "./control-types" +import { missionCreationSelection, parseMissionCreationDefaults } from "./creation-defaults" +import type { MissionStorage } from "./journal" +import type { MissionJsonValue } from "./model" +import { NativeMissionDocumentStore, type MissionDocumentStorage } from "./mission-document-store" +import { resolveMissionCreationDefaults } from "./profile-defaults" +import { CODENOMAD_MISSIONS_RPC } from "./rpc" + +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, 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) => 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, get reads() { return reads }, get created() { return created }, + fail: () => { failJournal = true }, failBeforeDocument: () => { failDocument = true }, + invalidate: () => { preferences = null }, restart: () => { control = new MissionControl(options) } } +} + +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.deepEqual(document.oneTime?.creationDefaults, result.mission?.creationDefaults) + await f.documents.change(document.id, document.revision, () => true, next => { next.configuration.profiles = {} }) + assert.deepEqual(missionCreationSelection({ ...result.mission!, 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("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), /Journal write unavailable/) + assert.equal(f.reads, 1) + assert.equal(f.created, 1) + f.invalidate(); f.restart() + await assert.rejects(f.control.prepare(f.coordinator, { ...request, profiles: {} }), (error: any) => error.code === "prepare-conflict") + 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), /Document write unavailable/) + 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("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) +}) diff --git a/packages/server/src/missions/creation-defaults.ts b/packages/server/src/missions/creation-defaults.ts new file mode 100644 index 0000000000..bdb4029594 --- /dev/null +++ b/packages/server/src/missions/creation-defaults.ts @@ -0,0 +1,58 @@ +import { z } from "zod" +import type { MissionMap, MissionTemplateId } from "./model" +import { missionProfileRoles, missionProfilesInputSchema, missionProfilesSchema, sameMissionProfiles, validateMissionProfiles, type MissionProfiles } from "./playbook-profiles" +import { missionTaskModeInputSchema, missionTaskModeSchema, type MissionTaskMode } from "./task-execution-mode" + +const origin = z.enum(["explicit", "preference", "opencode-default"]) +export const missionCreationChoicesSchema = z.object({ profiles: missionProfilesInputSchema, taskMode: missionTaskModeInputSchema.optional() }).strict() +const originsSchema = z.object({ coordinator: origin, roles: z.record(z.string(), origin), taskMode: origin }).strict() +export const missionCreationDefaultsSchema = z.object({ request: missionCreationChoicesSchema, profiles: missionProfilesInputSchema, + taskMode: missionTaskModeInputSchema, origins: originsSchema }).strict() +const resolutionSchema = z.object({ profiles: missionProfilesInputSchema, taskMode: missionTaskModeInputSchema, origins: originsSchema }).strict() +export type MissionCreationChoices = z.infer +export type MissionCreationDefaults = z.infer +export type MissionCreationSelection = { profiles: MissionProfiles; taskMode: MissionTaskMode; origins: MissionCreationDefaults["origins"] } + +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: MissionCreationDefaults["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): MissionCreationDefaults { + 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 = resolutionSchema.parse(input) + validateOrigins(template, value.origins) + validateMissionProfiles(template, value.profiles) + if (!value.profiles?.coordinator || Object.keys(value.profiles.roles ?? {}).length !== missionProfileRoles[template].length) throw new Error("Incomplete Mission profile selection") + return value as MissionCreationSelection +} + +/** 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 }) +} + +const originWire = { type: "string", enum: ["explicit", "preference", "opencode-default"] } as const +export const missionCreationDefaultsWire = { + type: "object", properties: { + request: { type: "object", properties: { profiles: missionProfilesSchema, taskMode: missionTaskModeSchema }, additionalProperties: false }, + profiles: missionProfilesSchema, taskMode: missionTaskModeSchema, + origins: { type: "object", properties: { coordinator: originWire, taskMode: originWire, + roles: { type: "object", maxProperties: 6, 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..09dc87aaa0 --- /dev/null +++ b/packages/server/src/missions/creation-intent.test.ts @@ -0,0 +1,68 @@ +import assert from "node:assert/strict" +import test from "node:test" +import { MissionCreationIntents } from "./creation-intent" +import type { MissionStorage } from "./journal" +import type { MissionJsonValue } from "./model" +import { resolveMissionCreationDefaults } from "./profile-defaults" + +function fixture() { + const values = new Map() + 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, limit = 100 }) => { + const rows = [...values].filter(([key]) => key.startsWith(prefix)).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") } +} +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"), (error: any) => error.code === "prepare-conflict") + } + 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 < 128; index++) await f.intents.save(`msn_${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, 128) + await f.intents.settled("msn_0") + await f.intents.save("msn_over", request, defaults, missing, () => {}, "request-conflict") + assert.equal(f.values.size, 128) +}) + +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, () => assert.fail("Damaged evidence cannot fall back"), "request-conflict"), + (error: any) => error.code === "invalid-journal") + assert.deepEqual([...f.values], before) +}) diff --git a/packages/server/src/missions/creation-intent.ts b/packages/server/src/missions/creation-intent.ts new file mode 100644 index 0000000000..88808a58ad --- /dev/null +++ b/packages/server/src/missions/creation-intent.ts @@ -0,0 +1,78 @@ +import { z } from "zod" +import type { MissionStartInput } from "./control-types" +import { MissionControlError } from "./control-error" +import { missionCreationChoices, missionCreationChoicesSchema, parseMissionCreationDefaults, sameMissionCreationChoices, + type MissionCreationDefaults } from "./creation-defaults" +import { runMissionExclusive } from "./exclusive" +import type { MissionStorage } from "./journal" +import type { MissionEvent, MissionJsonValue } from "./model" + +type Request = MissionStartInput & { title?: string } +const requestSchema = missionCreationChoicesSchema.extend({ objective: z.string().min(1).max(20_000), + title: z.string().min(1).max(60).optional(), notes: z.string().max(20_000).optional(), + template: z.enum(["custom", "debug", "wayfinder", "delivery", "compare"]) }).strict() +const intentSchema = z.object({ version: z.literal(1), request: requestSchema, defaults: z.unknown() }).strict() +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: MissionCreationDefaults): Request => ({ + objective: input.objective, template: input.template, ...(input.title === undefined ? {} : { title: input.title }), + ...(input.notes === undefined ? {} : { notes: input.notes }), ...missionCreationChoices(defaults.request), +}) + +/** Durable, bounded pre-dispatch intentions. A missing document or lost RPC reply + * never permits resolving the same original request against new preferences. */ +export class MissionCreationIntents { + private readonly prefix: string + constructor(private readonly storage: MissionStorage, projectToken: string) { + this.prefix = `codenomad-missions/v2/creation-intents/${projectToken}/` + } + + private conflict(code: string): never { + throw new MissionControlError("Creation request ID was already used with a different mission", code) + } + + private async recorded(missionID: string, request: Request, conflict: string): Promise { + const raw = await this.storage.get(this.prefix + missionID) + if (raw === undefined) return undefined + let saved: z.infer, defaults: MissionCreationDefaults + try { + saved = intentSchema.parse(raw) + defaults = parseMissionCreationDefaults(saved.request.template, saved.defaults) + if (!sameMissionCreationChoices(saved.request, defaults.request)) throw new Error("Invalid original choices") + } catch { throw new MissionControlError("Mission creation intent is unreadable; existing data is retained", "invalid-journal") } + if (!sameRequest(saved.request, request)) this.conflict(conflict) + return 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) { + // Read the intent before its eventual receipt: publication precedes removal. + return await this.recorded(missionID, request, conflict) ?? this.fromEvent(await created(), request, conflict) + } + + save(missionID: string, input: Request, defaults: MissionCreationDefaults, created: () => Promise, + current: () => void, conflict: string): Promise { + const request = originalRequest(input, defaults) + return runMissionExclusive(this.prefix, async () => { + const saved = await this.read(missionID, request, created, conflict) + if (saved) return saved + const pending = await this.storage.scan({ prefix: this.prefix, limit: 129 }) + if (pending.entries.length >= 128 || pending.next) throw new MissionControlError("Unresolved Mission preparations reached their safety limit; resolve existing requests first", "creation-capacity") + current() + await this.storage.set(this.prefix + missionID, JSON.parse(JSON.stringify({ version: 1, request, defaults })) as MissionJsonValue, current) + return defaults + }) + } + + async settled(missionID: string): Promise { + // The durable creation event owns the original receipt. Failed cleanup + // retains redundant evidence and its capacity place. + try { await this.storage.remove?.(this.prefix + missionID) } catch { /* Retain the original intent. */ } + } +} 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/model.ts b/packages/server/src/missions/model.ts index ca7b0748c6..8ee787c261 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").MissionCreationDefaults 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").MissionCreationDefaults 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..103b96fc3b --- /dev/null +++ b/packages/server/src/missions/profile-defaults.test.ts @@ -0,0 +1,181 @@ +import assert from "node:assert/strict" +import { test } from "node:test" +import { missionProfileRoles, type MissionProfiles } from "./playbook-profiles" +import { MissionPreferencesError, resolveMissionCreationDefaults, type MissionProfileDefault } from "./profile-defaults" +import type { MissionTemplateId } from "./model" + +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("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("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's selected judge stays whole even when empty or agent-only", () => { + for (const comparator of [{}, { agent: "judge" }, specialist]) { + const explicit = resolveMissionCreationDefaults({ template: "compare", preferences, profiles: { roles: { comparator } } }) + assert.deepEqual(explicit.profiles.roles.comparator, comparator) + 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, comparator) + 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("an omitted Compare judge freezes a known coordinator model without completing selected judge slots", () => { + 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) + 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) + 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..bb73570b29 --- /dev/null +++ b/packages/server/src/missions/profile-defaults.ts @@ -0,0 +1,122 @@ +import { parseMissionProfiles, missionProfileRoles, freezeCompareProfiles, validateMissionProfiles, type MissionProfiles } from "./playbook-profiles" +import type { MissionTemplateId } from "./model" +import type { MissionExecution } from "./execution" +import { 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 } +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 class MissionPreferencesError extends Error { + readonly code = "mission-preferences-invalid" + constructor() { + super("Invalid mission profile defaults") + this.name = "MissionPreferencesError" + } +} + +export type MissionDefaultOrigin = "explicit" | "preference" | "opencode-default" +export interface MissionCreationDefaults { + profiles: Required + taskMode: MissionTaskMode + origins: { coordinator: MissionDefaultOrigin; roles: Record; taskMode: MissionDefaultOrigin } +} + +/** Resolve whole slots once, before creation; an empty slot deliberately selects native defaults. */ +export function resolveMissionCreationDefaults(input: { + template: MissionTemplateId + preferences: unknown + profiles?: MissionProfiles + taskMode?: MissionTaskMode + coordinatorModel?: MissionExecution["model"] +}): MissionCreationDefaults { + 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.execution = freezeCompareProfiles("compare", { coordinator: coordinator.execution }, input.coordinatorModel)?.roles?.comparator ?? {} + selected.origin = coordinator.origin + } + roles[role] = selected.execution + origins[role] = selected.origin + } + const preferredTaskMode = preferences.find(item => item.template === input.template)?.taskMode + ?? preferences.find(item => item.template === "all")?.taskMode + return structuredClone({ + profiles: { coordinator: coordinator.execution, roles }, + taskMode: parseMissionTaskMode(input.taskMode === undefined ? preferredTaskMode : input.taskMode), + origins: { coordinator: coordinator.origin, roles: origins, + taskMode: input.taskMode !== undefined ? "explicit" : preferredTaskMode !== undefined ? "preference" : "opencode-default" }, + }) +} diff --git a/packages/server/src/missions/recovery-error.ts b/packages/server/src/missions/recovery-error.ts index 8743fd29ea..29ccc8a500 100644 --- a/packages/server/src/missions/recovery-error.ts +++ b/packages/server/src/missions/recovery-error.ts @@ -12,6 +12,10 @@ const errors = { "prepare-refused": { status: 409, message: "The mission could not be prepared; nothing was created" }, "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: "Reload or correct the Missions preferences before creating a mission" }, + "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 { 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..311b4fac55 --- /dev/null +++ b/packages/server/src/opencode/automation-plugin-profile-defaults.test.ts @@ -0,0 +1,87 @@ +import assert from "node:assert/strict" +import { mkdtemp, rm } from "node:fs/promises" +import os from "node:os" +import path from "node:path" +import test from "node:test" +import Fastify from "fastify" +import { MissionControlError } from "../missions/control-error" +import { registerAutomationPluginRoute } from "../server/routes/automation-plugin" +import { AUTOMATION_BRIDGE_PATH, createAutomationBridgeRegistration, publishAutomationBridge, sendMissionInput } from "./automation-plugin" + +test("profile defaults preserve typed refusals through the authenticated bridge and require one owner", 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 + let failureCode: string | undefined + registerAutomationPluginRoute(app, { + authManager: { isLoopbackRequest: () => true }, bridgeToken: registration.token, nativeParent: {}, developerCdp: {}, + settings: { getRawConfigOwner: () => { + if (unreadable) throw new Error("secret preferences path") + return { settings: { missionProfileDefaults: preferences } } + } }, + workspaceManager: { + getSharedServiceClient: async () => ({ session: { get: async () => ({ location: { directory: "/repo" } }) } }), + list: () => [{ id: "owner" }], ownsLocation: async () => true, + }, + } 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 === "mission-input") { + posts++ + assert.equal(body.command.kind, "profile-defaults") + if (denied) return new Response(JSON.stringify({ error: "secret backend refusal" }), { status: 403 }) + if (failureCode) return new Response(JSON.stringify({ code: failureCode, error: "secret backend detail" }), { status: 409 }) + } + 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 = () => sendMissionInput("ses_owner", "profile-defaults", { template: "custom" }) + const unavailable = (error: unknown) => error instanceof MissionControlError + && error.code === "mission-preferences-unavailable" + && error.message === "Reload or correct the Missions preferences before creating a mission" + await assert.rejects(request(), unavailable, "zero owners must expose a preference refusal") + await assert.rejects(sendMissionInput("ses_owner", "prompt", {}), /exactly one owning/, "other commands keep their error") + + removals.push(await publishAutomationBridge(registration)) + const resolved = await request() as { taskMode: string } + assert.equal(resolved.taskMode, "native") + 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 + 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") + assert.equal(posts, before, "ambiguous ownership reads no preferences") +}) diff --git a/packages/server/src/opencode/automation-plugin.ts b/packages/server/src/opencode/automation-plugin.ts index c7b7e7f4b0..e46b39ba75 100644 --- a/packages/server/src/opencode/automation-plugin.ts +++ b/packages/server/src/opencode/automation-plugin.ts @@ -545,17 +545,25 @@ async function probeBrowserBridges( } 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) - if (response.status !== 200) { - const recovery = missionRecoveryError(response.body.code) - if (recovery && recovery.status === response.status) throw new MissionControlError(recovery.message, recovery.code) - throw new Error("CodeNomad could not admit the mission input; inspect ownership/environment and retry the same task") + kind: "prompt" | "synthetic" | "cleanup" | "lifecycle" | "create-root" | "prepare" | "task-sessions" | "interrupt" | "profile-defaults", input: unknown): Promise { + try { + // `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) + if (response.status !== 200) { + const recovery = missionRecoveryError(response.body.code) + if (recovery && recovery.status === response.status) throw new MissionControlError(recovery.message, recovery.code) + throw new Error("CodeNomad could not admit the mission input; inspect ownership/environment and retry the same task") + } + return response.body.result + } catch (error) { + if (kind === "profile-defaults" && !(error instanceof MissionControlError && missionRecoveryError(error.code))) { + const unavailable = missionRecoveryError("mission-preferences-unavailable")! + throw new MissionControlError(unavailable.message, unavailable.code) + } + throw error } - return response.body.result } export async function executeBrowserTool(sessionID: string, input: unknown) { diff --git a/packages/server/src/opencode/missions-plugin.test.ts b/packages/server/src/opencode/missions-plugin.test.ts index d43630bb96..a9ba5565a8 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,63 @@ 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.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([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..1e47d1b73c 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. Creation fills omitted profile slots and taskMode from the user's Missions preferences (type exception, then global); explicit slots win whole, including {}. It returns selection with saved profiles, taskMode and origins (explicit, preference, opencode-default), and refuses unreadable/invalid preferences. The existing coordinator must match the resolved profile. 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.", 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: what the Mission editor creates. Omitted profile slots and taskMode inherit the user's Missions preferences (type exception, then global); explicit slots win whole, including {}. Returns selection with saved profiles, taskMode and origins (explicit, preference, opencode-default); unreadable/invalid preferences refuse creation. It never starts; the user presses Play. Reuse the same requestID and original inputs to retry: saved choices stay frozen even if preferences change. Outside an active mission use the Missions editor. Find it later with mission.inspect({ list: true }) and read it with mission.inspect({ missionID }); you cannot control it.", 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) } : {}) }) }, }) }) @@ -629,8 +631,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: "Omitted coordinator/role slots inherit Missions preferences: type exception, then global (specialist for task roles). Each explicit slot replaces the preference whole; {} selects OpenCode defaults for that slot. profiles: {} inherits all slots. Invalid preferences refuse creation." }, + taskMode: { ...missionTaskModeSchema, description: "Explicit policy wins; omission inherits Missions preferences (type exception, then global), then native." }, }, required: ["requestID", "objective", "template"], additionalProperties: false, @@ -651,7 +653,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 +689,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: "Omitted coordinator/role slots inherit Missions preferences: type exception, then global (specialist for task roles). Explicit slots replace whole, including {} or agent-only. profiles: {} inherits all slots. Invalid preferences refuse creation." }, + 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 +773,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 +862,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..0c83cfcf91 100644 --- a/packages/server/src/opencode/missions/desktop-plugin.ts +++ b/packages/server/src/opencode/missions/desktop-plugin.ts @@ -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: (sessionID, input) => sendMissionInput(sessionID, "profile-defaults", input), 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/server/routes/automation-plugin.ts b/packages/server/src/server/routes/automation-plugin.ts index 4b79cfcabf..44689c0d1d 100644 --- a/packages/server/src/server/routes/automation-plugin.ts +++ b/packages/server/src/server/routes/automation-plugin.ts @@ -10,6 +10,7 @@ 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" @@ -28,7 +29,7 @@ interface AutomationPluginRouteDeps { workspaceManager: WorkspaceManager developerCdp: DeveloperCdp worktreeDeletionFence?: WorktreeDeletionFence - settings?: Pick + settings?: Pick & Partial> remoteDevices?: Pick } @@ -107,8 +108,9 @@ export function registerAutomationPluginRoute(app: FastifyInstance, deps: Automa if (!owned) return reply.code(404).send({ error: "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 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..64313e2280 100644 --- a/packages/server/src/server/routes/mission-creation-fence.test.ts +++ b/packages/server/src/server/routes/mission-creation-fence.test.ts @@ -9,6 +9,7 @@ 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 { 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 + 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 { @@ -92,11 +97,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) + if (error && error.status === response.statusCode) throw new MissionControlError(error.message, error.code) + 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 +121,14 @@ 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 }, loseAck: () => { lostAck = true }, failPublication: () => { failedPublication = true }, mismatchProfile: () => { wrongProfile = true }, transformRejection: (transform: (error: any) => any) => { rejectionTransform = transform }, @@ -240,7 +254,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 +273,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 +302,68 @@ 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 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-pipeline.ts b/packages/server/src/server/routes/mission-creation-pipeline.ts index 1fb72ddabc..fec13fa19b 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 { MissionCreationDefaults } 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") @@ -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-prepare.ts b/packages/server/src/server/routes/mission-prepare.ts index 1b1c540514..c10a4e16c8 100644 --- a/packages/server/src/server/routes/mission-prepare.ts +++ b/packages/server/src/server/routes/mission-prepare.ts @@ -11,12 +11,15 @@ 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 { parseMissionCreationDefaults } from "../../missions/creation-defaults" +import { 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"]), profiles: missionProfilesInputSchema, taskMode: missionTaskModeInputSchema.optional(), + creationDefaults: z.unknown().optional(), }).strict() }).strict() type Manager = MissionCreationPipelineManager & Pick @@ -47,13 +50,15 @@ export async function prepareCoordinatorMission(manager: Manager, fence: Worktre try { 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 (missionRecoveryRejection(error)) throw error if (!creation?.dispatched && error instanceof Error && error.message.startsWith("compare-models-")) - throw new MissionControlError(error.message, "prepare-refused") + throw new MissionControlError(error.message, error.message) // 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") 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..8ba73aa0ab --- /dev/null +++ b/packages/server/src/server/routes/mission-profile-defaults.test.ts @@ -0,0 +1,87 @@ +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" + +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" }) + } +}) + +test("profile default command validates all input before reading preferences", async t => { + const request = fixture(t, () => assert.fail("Invalid input must not read preferences")) + for (const input of [null, {}, { template: "other" }, { template: "custom", extra: true }, + { template: "custom", taskMode: "other" }, { template: "custom", coordinatorModel: { providerID: "p" } }, + { 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, "mission-preferences-invalid") + } + assert.equal((await request({ template: "custom" }, { extra: true })).json().code, "mission-preferences-invalid") +}) + +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: "Reload or correct the Missions preferences before creating a mission" }) + } +}) + +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..c8f9a485b3 --- /dev/null +++ b/packages/server/src/server/routes/mission-profile-defaults.ts @@ -0,0 +1,42 @@ +import { z } from "zod" +import { MissionControlError } from "../../missions/control-error" +import { missionProfilesInputSchema, validateMissionProfiles } from "../../missions/playbook-profiles" +import { resolveMissionCreationDefaults } from "../../missions/profile-defaults" +import { missionRecoveryError } from "../../missions/recovery-error" +import { missionTaskModeInputSchema } from "../../missions/task-execution-mode" +import { isPlainObject } from "../../settings/merge-patch" +import type { SettingsService } from "../../settings/service" +import { parseExecution } from "../../missions/execution" + +const commandSchema = z.object({ kind: z.literal("profile-defaults"), input: z.object({ + template: z.enum(["custom", "wayfinder", "debug", "delivery", "compare"]), + profiles: missionProfilesInputSchema, + taskMode: missionTaskModeInputSchema.optional(), + 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() }).strict() + +function refusal(code: "mission-preferences-invalid" | "mission-preferences-unavailable"): MissionControlError { + const error = missionRecoveryError(code)! + return new MissionControlError(error.message, error.code) +} + +/** 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 refusal("mission-preferences-invalid") + const { input } = parsed.data + try { validateMissionProfiles(input.template, input.profiles) } + catch { throw refusal("mission-preferences-invalid") } + 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 { throw refusal("mission-preferences-invalid") } +} diff --git a/packages/ui/src/lib/mission-defaults.ts b/packages/ui/src/lib/mission-defaults.ts index f3feb3eba0..d7e4e85643 100644 --- a/packages/ui/src/lib/mission-defaults.ts +++ b/packages/ui/src/lib/mission-defaults.ts @@ -1,66 +1 @@ -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 * from "../../../server/src/missions/profile-defaults" 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..5987dcb54a --- /dev/null +++ b/packages/ui/tests/contracts/mission-defaults.test.ts @@ -0,0 +1,35 @@ +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 { missionProfileRoles, missionRoleProfile } from "../../../server/src/missions/playbook-profiles" +import type { MissionTemplateId } from "../../../server/src/missions/model" + +test("the UI default API reexports the pure server implementation", () => { + assert.deepEqual(Object.keys(ui).sort(), Object.keys(server).sort()) + for (const key of Object.keys(server) as (keyof typeof server)[]) assert.equal(ui[key], server[key]) +}) + +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 } } }], + ] + for (const preferences of cases) for (const template of templates) { + const normalized = ui.normalizeMissionDefaults(preferences) + const draft = ui.missionDefaultsFor(normalized, template) + const result = server.resolveMissionCreationDefaults({ template, preferences }) + const roles = Object.fromEntries(missionProfileRoles[template].map(role => [role, + draft?.roles?.[role] ?? (role === "comparator" ? missionRoleProfile(template, draft, role) : undefined) ?? {}])) + assert.deepEqual(result.profiles, { coordinator: draft?.coordinator ?? {}, roles }, template) + assert.equal(result.taskMode, ui.missionTaskModeFor(normalized, template), template) + assert.deepEqual(ui.resolveMissionCreationDefaults({ template, preferences }), result) + } +}) From 3cb49205fc46db7b1f2f7270a1c85909a9362b22 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pascal=20Andr=C3=A9?= Date: Thu, 5 Nov 2026 23:34:11 +0100 Subject: [PATCH 02/16] docs(missions): explain inherited profiles for agent preparations Explain how agent-prepared missions inherit saved Missions preferences for omitted profile slots and task-session mode, while explicit slots remain authoritative as a whole. Cover saved selection origins, preference errors, frozen retries and the editor guidance outside an active mission. Align the developer reference and mission skill with the shared server/editor resolver and existing tool descriptions. Update public Missions help in all ten locales using the application labels, including the comparison judge's coordinator-model default. Validation: npm run test:help passed all 31 checks across 28 pages and 10 locales; git diff --check passed. --- .opencode/skills/codenomad-missions/SKILL.md | 20 +++++++++- dev-docs/MISSIONS.md | 40 +++++++++++++++++--- docs/help/de/missions.md | 4 ++ docs/help/en/missions.md | 4 ++ docs/help/es/missions.md | 4 ++ docs/help/fr/missions.md | 4 ++ docs/help/he/missions.md | 4 ++ docs/help/ja/missions.md | 4 ++ docs/help/ne/missions.md | 4 ++ docs/help/ru/missions.md | 4 ++ docs/help/tr/missions.md | 4 ++ docs/help/zh-Hans/missions.md | 4 ++ 12 files changed, 94 insertions(+), 6 deletions(-) diff --git a/.opencode/skills/codenomad-missions/SKILL.md b/.opencode/skills/codenomad-missions/SKILL.md index 254a952194..94f6c8a58b 100644 --- a/.opencode/skills/codenomad-missions/SKILL.md +++ b/.opencode/skills/codenomad-missions/SKILL.md @@ -16,9 +16,27 @@ 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. +For `mission.prepare` and `mission.inspect({ start })`, omitted coordinator/role +slots and `taskMode` inherit the user's Missions preferences: playbook exception, +then global defaults (the global specialist supplies task roles; the Compare judge +defaults to the coordinator's model). Each explicit profile slot wins whole: +`{}` selects OpenCode defaults for that slot, and an agent-only slot keeps its +native model default. `profiles: {}` inherits all slots. With absent preferences, +profiles use OpenCode defaults and task mode uses `native`. +Read the creation response's `selection.profiles`, `selection.taskMode` and +`selection.origins` to check the saved coordinator and every playbook role: +`explicit`, `preference` or `opencode-default` (the default Compare judge inherits +the coordinator's origin). Unreadable/invalid preferences refuse creation; report +the error and arrange recovery of the Missions preferences before retrying. +`inspect({ start })` requires the caller's existing coordinator profile to match +the resolved selection. For `prepare`, reuse the same requestID and original +inputs: saved choices stay frozen across retries and preference changes. +Outside an active mission, use the Missions editor in CodeNomad; never create an +intermediate mission merely to gain access to `mission.prepare`. + 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/MISSIONS.md b/dev-docs/MISSIONS.md index eab9c4e3e7..6df6fbb284 100644 --- a/dev-docs/MISSIONS.md +++ b/dev-docs/MISSIONS.md @@ -131,13 +131,43 @@ 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. + 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. Never + create an intermediate mission solely to prepare others. + + Both `mission.prepare` and `mission.inspect({ start })` resolve omitted + coordinator/role profiles and `taskMode` from the owning CodeNomad backend's + `ui.missionProfileDefaults`. The editor and server share + `missions/profile-defaults.ts`: 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. 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. + + Creation responses include `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 default Compare judge inherits the coordinator's origin + along with its model. 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. An unreadable + preference document or unavailable backend returns + `mission-preferences-unavailable`; invalid preferences return + `mission-preferences-invalid`. Both refuse creation and ask for preference + recovery, including when profiles were supplied explicitly. + 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. + journal's creation event and returns the saved mission or a conflict. Reuse the + same requestID and original inputs: a durable pre-dispatch intent retains the + chosen profiles, task mode and origins across uncertain attempts, preference + changes and restarts. `inspect({ start })` retains these choices under its + native invocation identity too. A held uncertain attempt is reported uncertain. 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 diff --git a/docs/help/de/missions.md b/docs/help/de/missions.md index 0a2a913482..4aa49030d4 100644 --- a/docs/help/de/missions.md +++ b/docs/help/de/missions.md @@ -20,6 +20,8 @@ Missionen verbinden einen dauerhaften Projektplan mit nativen OpenCode-Unterhalt Gespeicherte einmalige Missionen behalten ihre Ausführungssteuerung, ihren Aufgabenbaum, ihre Unterhaltungen und ihre Abschlussberichte. Bestehende tägliche Zeitpläne bleiben mit ihren täglichen Steuerelementen und [täglichen Zeitregeln](#existing-daily-schedules) aufgelistet. Wählen Sie den Eintrag und verwenden Sie die für dieses Objekt verfügbaren Steuerelemente. +Von einem Agenten vorbereitete Folgemissionen verwenden Ihre gespeicherten [Vorgaben für neue Missionen](#profiles) für ausgelassene Profile und Aufgabensitzungen. Verwenden Sie außerhalb einer aktiven Mission **Mission erstellen** im Missionsbereich. + ### Playbooks {#playbooks} Direkt unter dem Auswahlfeld **Playbook** steht eine einsätzige Beschreibung des ausgewählten Playbooks. **Details anzeigen** öffnet das ausgewählte Playbook im zentralen Leser: seine Schritte, seine Rollen und, am Ende eingeklappt, die genauen englischen Anweisungen, die seine Agenten erhalten. [Playbooks](playbooks.md) erklärt Schritte, Rollen und Fragen jedes Playbooks und was CodeNomad prüft. @@ -139,6 +141,8 @@ Jede **Modell**-Liste zeigt, was die **Modell**-Auswahl der Unterhaltung zeigt, 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. +Diese Vorgaben gelten auch, wenn ein Agent eine Mission vorbereitet: Jedes ausgelassene Koordinator- oder Rollenprofil verwendet zuerst die Playbook-Ausnahme, dann die globale Auswahl. Der globale Spezialist liefert die Aufgabenrollen; der Vergleichsrichter verwendet standardmäßig das Modell des Koordinators. Ein ausdrücklich angegebenes Profil hat als Ganzes Vorrang, auch bei OpenCode-Standardwerten oder einer reinen Agentenauswahl. Ausgelassene **Aufgabensitzungen** folgen derselben Reihenfolge, danach **Native Unteragenten**. Die Erstellungsantwort an den Agenten nennt die gespeicherten Profile, den Sitzungsmodus und die Herkunft jeder Auswahl: ausdrücklich, Vorgabe oder OpenCode-Standard. Unlesbare oder ungültige Vorgaben blockieren die Erstellung mit einer Fehlermeldung zur Korrektur oder zum Neuladen. Wiederholungen behalten die ursprünglich gespeicherte Auswahl auch bei geänderten Vorgaben bei. + ## Gespeicherten Auftrag wiederverwenden {#saved-briefs} 1. Öffnen Sie beim Erstellen **Optionen → Mit einem gespeicherten Auftrag beginnen** und wählen Sie den Auftrag. diff --git a/docs/help/en/missions.md b/docs/help/en/missions.md index 21992a096f..32fafb696f 100644 --- a/docs/help/en/missions.md +++ b/docs/help/en/missions.md @@ -18,6 +18,8 @@ Missions pair a durable project plan with native OpenCode conversations. The coo **Create saves a paused Mission.** Work and native calendars are armed only by Play. Creation belongs to the selected project/Location and records the requested profiles and task-session policy. Validation appears beside the affected field; a refusal that says nothing was sent keeps the draft for correction. A one-time coordinator can also prepare a separate follow-up: it appears as **Prepared** and starts from its own ▶ action. +Agent-prepared follow-ups use your saved [new mission defaults](#profiles) for omitted profiles and task-session choices. Outside an active mission, use **Create mission** in the Missions panel. + Saved one-time missions retain their execution controls, task tree, conversations and final reports. Existing daily schedules remain listed with their daily controls and [daily timing rules](#existing-daily-schedules). Select the entry and use the controls available for that object. ### Playbooks {#playbooks} @@ -135,6 +137,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. +These defaults also apply when an agent prepares a mission: each omitted coordinator or role profile uses the playbook exception, then the global choice; the global specialist supplies task roles, while the comparison judge defaults to the coordinator's model. An explicitly supplied profile wins as a whole, including an OpenCode-default choice or an agent-only choice. Omitted **Task sessions** uses the same preference order, then **Native subagents**. The agent's creation response lists the saved profiles, task-session mode and each choice's source: explicit, preference or OpenCode default. Unreadable or invalid preferences block creation with a recovery error. Retries retain the original saved choices even if you change the defaults. + 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 132d74fcec..5715a24a11 100644 --- a/docs/help/es/missions.md +++ b/docs/help/es/missions.md @@ -20,6 +20,8 @@ Las Misiones combinan un plan de proyecto duradero con conversaciones nativas de Las misiones puntuales guardadas conservan sus controles de ejecución, árbol de tareas, conversaciones e informes finales. Las programaciones diarias existentes siguen en la lista con sus controles diarios y sus [reglas horarias diarias](#existing-daily-schedules). Selecciona la entrada y usa los controles disponibles para ese objeto. +Los seguimientos preparados por un agente usan tus [valores para nuevas misiones](#profiles) guardados para los perfiles y las sesiones de tareas omitidos. Fuera de una misión activa, usa **Crear misión** en el panel Misiones. + ### Guiones {#playbooks} El selector **Guion** muestra justo debajo una descripción de una frase del guion seleccionado. **Ver detalles** abre el guion seleccionado en el lector central: sus pasos, sus roles y, plegadas al final, las instrucciones exactas en inglés que reciben sus agentes. [Guiones](playbooks.md) explica los pasos, roles y preguntas de cada guion, y lo que CodeNomad comprueba. @@ -139,6 +141,8 @@ Cada lista **Modelo** muestra lo mismo que el selector **Modelo** de la conversa 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. +Estos valores también se aplican cuando un agente prepara una misión: cada perfil de coordinador o rol omitido usa la excepción del guion y luego la elección global; el especialista global proporciona los roles de tareas, mientras que el juez de comparación usa por defecto el modelo del coordinador. Un perfil indicado explícitamente tiene prioridad en su totalidad, incluidos los valores de OpenCode o una elección de solo agente. **Sesiones de tareas** omitido sigue el mismo orden de preferencias y luego **Subagentes nativos**. La respuesta de creación al agente enumera los perfiles guardados, el modo de sesiones y el origen de cada elección: explícito, preferencia o valor predeterminado de OpenCode. Las preferencias ilegibles o inválidas bloquean la creación con un error que pide corregirlas o recargarlas. Los reintentos conservan las elecciones guardadas originales aunque cambies los valores predeterminados. + ## Reutilizar una descripción guardada {#saved-briefs} 1. Durante la creación, expande **Opciones → Empezar desde una descripción** y selecciona la descripción guardada. diff --git a/docs/help/fr/missions.md b/docs/help/fr/missions.md index cbc3ea62bd..44a77d8d12 100644 --- a/docs/help/fr/missions.md +++ b/docs/help/fr/missions.md @@ -20,6 +20,8 @@ Les Missions associent un plan de projet durable aux conversations natives OpenC Les missions ponctuelles enregistrées conservent leurs commandes d’exécution, leur arbre de tâches, leurs conversations et leurs rapports finaux. Les programmations quotidiennes existantes restent dans la liste avec leurs commandes quotidiennes et leurs [règles horaires quotidiennes](#existing-daily-schedules). Sélectionnez l’entrée et utilisez les commandes disponibles pour cet objet. +Les suites préparées par un agent utilisent vos [défauts des nouvelles missions](#profiles) enregistrés pour les profils et les sessions de tâches omis. Hors d'une mission active, utilisez **Créer une mission** dans le panneau Missions. + ### Scénarios {#playbooks} Le sélecteur **Scénario** affiche juste en dessous une description en une phrase du scénario sélectionné. **Voir les détails** ouvre le scénario sélectionné dans le lecteur central : ses étapes, ses rôles et, repliées à la fin, les instructions exactes en anglais que reçoivent ses agents. [Scénarios](playbooks.md) explique les étapes, les rôles et les questions de chaque scénario, ainsi que ce que CodeNomad vérifie. @@ -139,6 +141,8 @@ Chaque liste **Modèle** affiche ce qu’affiche le sélecteur **Modèle** de la 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. +Ces défauts s'appliquent aussi quand un agent prépare une mission : chaque profil de coordinateur ou de rôle omis utilise l'exception du scénario, puis le choix global ; le spécialiste global fournit les rôles de tâches, tandis que le juge de comparaison utilise par défaut le modèle du coordinateur. Un profil explicitement fourni prime en entier, y compris un choix de défauts OpenCode ou un agent seul. **Sessions des tâches** omis suit le même ordre de préférences, puis **Sous-agents natifs**. La réponse de création à l'agent donne les profils enregistrés, le mode des sessions de tâches et l'origine de chaque choix : explicite, préférence ou défaut OpenCode. Des préférences illisibles ou invalides bloquent la création avec une erreur demandant leur correction ou leur rechargement. Les réessais conservent les choix enregistrés à l'origine, même si vous modifiez les défauts. + ## Réutiliser une consigne enregistrée {#saved-briefs} 1. À la création, développez **Options → Partir d’une consigne** et sélectionnez la consigne enregistrée. diff --git a/docs/help/he/missions.md b/docs/help/he/missions.md index ff1d5e7d7f..f87f634c30 100644 --- a/docs/help/he/missions.md +++ b/docs/help/he/missions.md @@ -20,6 +20,8 @@ משימות חד־פעמיות שמורות שומרות על בקרות ההפעלה, עץ המשימות, השיחות והדוחות הסופיים שלהן. לוחות זמנים יומיים קיימים נשארים ברשימה עם הבקרות היומיות ועם [כללי התזמון היומי](#existing-daily-schedules). בחרו את הרשומה והשתמשו בבקרות הזמינות לאותו אובייקט. +משימות המשך שהכין סוכן משתמשות ב[ברירות המחדל למשימות חדשות](#profiles) השמורות שלכם עבור פרופילים ובחירות של שיחות משימות שהושמטו. מחוץ למשימה פעילה, השתמשו ב־**יצירת משימה** בחלונית המשימות. + ### מדריכי עבודה {#playbooks} הבורר **מדריך** מציג ישירות מתחתיו תיאור במשפט אחד של המדריך שנבחר. **הצגת פרטים** פותח את המדריך שנבחר בקורא המרכזי: השלבים, התפקידים ובסוף, במצב מקופל, ההנחיות המדויקות באנגלית שהסוכנים שלו מקבלים. [מדריכי עבודה](playbooks.md) מסביר את השלבים, התפקידים והשאלות של כל מדריך, ומה CodeNomad בודק. @@ -139,6 +141,8 @@ בחירה שנדחתה או שלא אושרה לעולם אינה נשלחת שוב: הערכים השמורים מוצגים שוב, ו־**טעינה מחדש** מופיעה רק כשאי אפשר לקרוא אותם. אם שינוי עומק אינו מאושר, הערך שלכם נשמר; השתמשו ב־**רענון עומק הפרויקט** לפני שינוי נוסף. אל תפרשו **עומק OpenCode האפקטיבי אינו ידוע** כאפס או כמושבת. +ברירות המחדל חלות גם כשסוכן מכין משימה: כל פרופיל מתאם או תפקיד שהושמט משתמש בחריג של מדריך העבודה, ואז בבחירה הגלובלית; המומחה הגלובלי מספק את תפקידי המטלות, ושופט ההשוואה משתמש כברירת מחדל במודל של המתאם. פרופיל שסופק במפורש מקבל עדיפות בשלמותו, גם בבחירת ברירות המחדל של OpenCode או סוכן בלבד. **שיחות משימות** שהושמטו משתמשות באותו סדר העדפות ואז ב־**תת־סוכנים מקוריים**. תשובת היצירה לסוכן מפרטת את הפרופילים השמורים, מצב השיחות ומקור כל בחירה: מפורש, העדפה או ברירת מחדל של OpenCode. העדפות פגומות או בלתי קריאות חוסמות יצירה עם שגיאה המבקשת לתקן או לטעון אותן מחדש. ניסיונות חוזרים שומרים על הבחירות המקוריות גם אם תשנו את ברירות המחדל. + ## שימוש חוזר בתקציר שמור {#saved-briefs} 1. ביצירה, הרחיבו **אפשרויות → להתחיל מתקציר** ובחרו את התקציר השמור. diff --git a/docs/help/ja/missions.md b/docs/help/ja/missions.md index 26a66b35ee..71a67a1f14 100644 --- a/docs/help/ja/missions.md +++ b/docs/help/ja/missions.md @@ -20,6 +20,8 @@ 保存済みの単発ミッションでは、実行操作、タスクツリー、会話、最終レポートが保持されます。既存の日次スケジュールは、日次の操作と [日次の時刻規則](#existing-daily-schedules) とともに一覧に残ります。項目を選び、その対象で利用できる操作を使用してください。 +エージェントが準備するフォローアップでは、省略されたプロファイルとタスクセッションに、保存済みの[新規ミッションの既定値](#profiles)を使用します。有効なミッションの外では、ミッションパネルの **ミッションを作成** を使用してください。 + ### プレイブック {#playbooks} **プレイブック** セレクターのすぐ下に、選択したプレイブックの 1 文の説明が表示されます。**詳細を表示** を選ぶと、選択したプレイブックが中央のリーダーに開き、手順、役割、そして末尾に折りたたまれた、エージェントが受け取る正確な英語の指示が表示されます。[プレイブック](playbooks.md) では、各プレイブックの手順、役割、質問と、CodeNomad が確認することを説明しています。 @@ -139,6 +141,8 @@ CodeNomad の実行中は、ミッションのコーディネーターやタス 拒否された選択や未確認の選択が再送されることはありません。保存済みの値が再び表示され、**再読み込み** はそれらを読み取れない場合にだけ表示されます。深さの変更が未確認の場合は入力した値が保持されるので、次の変更の前に **プロジェクトの深さを更新** を使用します。**OpenCode の有効な深さは不明** をゼロや無効と解釈しないでください。 +エージェントがミッションを準備する場合も、これらの既定値が適用されます。省略されたコーディネーターや役割のプロファイルには、プレイブックの例外、グローバルの選択の順で適用します。タスクの各役割にはグローバルのスペシャリストを使用し、比較の審査役には既定でコーディネーターのモデルを使用します。明示されたプロファイルは全体として優先され、OpenCode の既定値やエージェントのみの指定も含みます。省略された **タスクセッション** も同じ順で設定を適用し、最後に **ネイティブのサブエージェント** を使用します。エージェントへの作成応答には、保存されたプロファイル、タスクセッションのモード、各選択の出所(明示、設定、OpenCode の既定値)が表示されます。設定が読み取れない、または無効な場合は、修正や再読み込みを求めるエラーで作成を中断します。既定値を変更しても、再試行では元の保存済みの選択を保持します。 + ## 保存済みの概要を再利用する {#saved-briefs} 1. 作成画面で **オプション → 保存済みの概要から始める** を展開し、保存済みの概要を選びます。 diff --git a/docs/help/ne/missions.md b/docs/help/ne/missions.md index bf97e8a513..217779456a 100644 --- a/docs/help/ne/missions.md +++ b/docs/help/ne/missions.md @@ -20,6 +20,8 @@ सुरक्षित गरिएका एकपटकका मिशनहरूले कार्यान्वयन नियन्त्रण, कार्य वृक्ष, कुराकानी र अन्तिम प्रतिवेदन कायम राख्छन्। विद्यमान दैनिक तालिकाहरू दैनिक नियन्त्रण र [दैनिक समयका नियम](#existing-daily-schedules) सहित सूचीमा रहन्छन्। प्रविष्टि छानेर त्यस वस्तुमा उपलब्ध नियन्त्रण प्रयोग गर्नुहोस्। +एजेन्टले तयार गरेका अनुवर्ती मिसनमा छुटाइएका प्रोफाइल र कार्य सत्रका विकल्पका लागि तपाईंका सुरक्षित [नयाँ मिसनका पूर्वनिर्धारित मान](#profiles) प्रयोग हुन्छन्। सक्रिय मिसनबाहिर मिसन प्यानलको **मिसन सिर्जना गर्नुहोस्** प्रयोग गर्नुहोस्। + ### प्लेबुक {#playbooks} **प्लेबुक** selector को ठीक तल चयन गरिएको प्लेबुकको एक वाक्यको विवरण देखिन्छ। **विवरण हेर्नुहोस्** ले चयन गरिएको प्लेबुक केन्द्रीय reader मा खोल्छ: यसका चरण, भूमिका र अन्त्यमा फोल्ड गरिएका, यसका एजेन्टहरूले पाउने ठ्याक्कै अङ्ग्रेजी निर्देशन। [प्लेबुक](playbooks.md) ले प्रत्येक प्लेबुकका चरण, भूमिका र प्रश्न, र CodeNomad ले के जाँच्छ भनी व्याख्या गर्छ। @@ -139,6 +141,8 @@ CodeNomad चलिरहँदा, project का हरेक agent कुर अस्वीकृत वा अपुष्ट चयन कहिल्यै फेरि पठाइँदैन: सुरक्षित मान फेरि देखाइन्छन्, र ती पढ्न नसकिँदा मात्र **पुनः लोड** देखिन्छ। depth परिवर्तन अपुष्ट भए तपाईंको मान राखिन्छ; अर्को परिवर्तनअघि **परियोजनाको गहिराइ ताजा गर्नुहोस्** प्रयोग गर्नुहोस्। **OpenCode को प्रभावकारी गहिराइ अज्ञात** लाई शून्य वा disabled नमान्नुहोस्। +एजेन्टले मिसन तयार गर्दा पनि यी पूर्वनिर्धारित मान लागू हुन्छन्: छुटाइएको समन्वयकर्ता वा भूमिकाको प्रोफाइलमा पहिले प्लेबुकको अपवाद, त्यसपछि विश्वव्यापी चयन प्रयोग हुन्छ। कार्य भूमिकामा विश्वव्यापी विशेषज्ञ प्रयोग हुन्छ; तुलना गर्ने निर्णायकले पूर्वनिर्धारित रूपमा समन्वयकर्ताको मोडेल प्रयोग गर्छ। स्पष्ट रूपमा दिइएको प्रोफाइलले पूर्ण रूपमा प्राथमिकता पाउँछ, OpenCode का पूर्वनिर्धारित मान वा एजेन्ट मात्र रोजेको अवस्थामा पनि। छुटाइएको **कार्य सत्रहरू** मा उही प्राथमिकता क्रमपछि **नेटिभ उपएजेन्टहरू** प्रयोग हुन्छ। एजेन्टलाई फर्काइएको सिर्जना जवाफमा सुरक्षित प्रोफाइल, कार्य सत्रको मोड र हरेक चयनको स्रोत हुन्छ: स्पष्ट, प्राथमिकता वा OpenCode को पूर्वनिर्धारित मान। पढ्न नसकिने वा अमान्य प्राथमिकताले सुधार वा पुनः लोड गर्नुपर्ने त्रुटिसहित सिर्जना रोक्छन्। पूर्वनिर्धारित मान बदले पनि पुनःप्रयासले सुरुका सुरक्षित चयन कायम राख्छ। + ## सुरक्षित brief पुनःप्रयोग {#saved-briefs} 1. सिर्जनामा **विकल्पहरू → सुरक्षित विवरणबाट सुरु गर्नुहोस्** विस्तार गरी brief चयन गर्नुहोस्। diff --git a/docs/help/ru/missions.md b/docs/help/ru/missions.md index b04e07398c..bb5a025afc 100644 --- a/docs/help/ru/missions.md +++ b/docs/help/ru/missions.md @@ -20,6 +20,8 @@ Сохранённые разовые миссии сохраняют управление выполнением, дерево задач, разговоры и итоговые отчёты. Существующие ежедневные расписания остаются в списке со своими ежедневными элементами управления и [правилами ежедневного времени](#existing-daily-schedules). Выберите запись и используйте доступные для этого объекта элементы управления. +Подготовленные агентом продолжения используют сохранённые [настройки новых миссий](#profiles) для пропущенных профилей и выбора сессий задач. Вне активной миссии используйте **Создать миссию** на панели миссий. + ### Сценарии {#playbooks} Сразу под списком **Сценарий** показано описание выбранного сценария в одном предложении. **Подробнее** открывает выбранный сценарий в центральном просмотре: его шаги, роли и, свёрнутые в конце, точные инструкции на английском, которые получают его агенты. Страница [Сценарии](playbooks.md) объясняет шаги, роли и вопросы каждого сценария, а также то, что проверяет CodeNomad. @@ -139,6 +141,8 @@ Отклонённый или неподтверждённый выбор никогда не отправляется повторно: снова показываются сохранённые значения, а **Обновить** появляется, только если их не удаётся прочитать. Если изменение глубины не подтверждено, ваше значение сохраняется; используйте **Обновить глубину проекта** перед новым изменением. Не трактуйте **Действующая глубина OpenCode неизвестна** как ноль или отключение. +Эти настройки действуют и при подготовке миссии агентом: каждый пропущенный профиль координатора или роли использует исключение сценария, затем глобальный выбор; глобальный специалист задаёт профили ролей задач, а судья сравнения по умолчанию использует модель координатора. Явно указанный профиль имеет приоритет целиком, включая выбор значений OpenCode или только агента. Пропущенные **Сессии задач** следуют тому же порядку настроек, затем используют **Нативные субагенты**. Ответ агенту при создании содержит сохранённые профили, режим сессий задач и источник каждого выбора: явный, настройка или значение OpenCode по умолчанию. Нечитаемые или недопустимые настройки блокируют создание с ошибкой, предлагающей исправить или перезагрузить их. Повторные попытки сохраняют исходный выбор даже после изменения настроек по умолчанию. + ## Повторное использование описания {#saved-briefs} 1. При создании раскройте **Параметры → Начать с сохранённого описания** и выберите описание. diff --git a/docs/help/tr/missions.md b/docs/help/tr/missions.md index ae250ed1eb..d2077b6127 100644 --- a/docs/help/tr/missions.md +++ b/docs/help/tr/missions.md @@ -20,6 +20,8 @@ Görevler, kalıcı bir proje planını OpenCode'un kendi konuşmalarıyla birle Kayıtlı tek seferlik görevler yürütme kontrollerini, görev ağacını, konuşmalarını ve nihai raporlarını korur. Mevcut günlük zamanlamalar günlük kontrolleri ve [günlük zamanlama kurallarıyla](#existing-daily-schedules) listede kalır. Kaydı seçip o nesne için sunulan kontrolleri kullanın. +Bir ajanın hazırladığı devam görevleri, belirtilmeyen profiller ve görev oturumu seçimleri için kayıtlı [yeni görev varsayılanlarınızı](#profiles) kullanır. Etkin bir görevin dışında, Görevler panelindeki **Görev oluştur** eylemini kullanın. + ### İş akışı rehberleri {#playbooks} **Rehber** seçicisinin hemen altında seçili rehberin tek cümlelik açıklaması gösterilir. **Ayrıntıları gör**, seçili rehberi merkezi okuyucuda açar: adımlarını, rollerini ve sonda katlanmış olarak, ajanlarının aldığı tam İngilizce talimatları. [İş akışı rehberleri](playbooks.md) her rehberin adımlarını, rollerini ve sorularını ve CodeNomad'in neleri denetlediğini açıklar. @@ -139,6 +141,8 @@ Her **Model** listesi, konuşmanın **Model** seçicisinin gösterdiklerini ayn 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. +Bir ajan görev hazırlarken de bu varsayılanlar uygulanır: belirtilmeyen her koordinatör veya rol profili önce rehber istisnasını, ardından genel seçimi kullanır; genel uzman görev rollerini sağlar, karşılaştırma hakemi ise varsayılan olarak koordinatörün modelini kullanır. Açıkça verilen profil, OpenCode varsayılanı veya yalnızca ajan seçimi dahil, bütünüyle önceliklidir. Belirtilmeyen **Görev oturumları** aynı tercih sırasını, ardından **Yerel alt ajanlar** seçimini kullanır. Ajana dönen oluşturma yanıtı kayıtlı profilleri, görev oturumu modunu ve her seçimin kaynağını listeler: açık seçim, tercih veya OpenCode varsayılanı. Okunamayan veya geçersiz tercihler, düzeltme ya da yeniden yükleme isteyen bir hatayla oluşturmayı engeller. Varsayılanları değiştirseniz bile yeniden denemeler ilk kaydedilen seçimleri korur. + ## Kayıtlı bir özeti yeniden kullanın {#saved-briefs} 1. Oluşturma ekranında **Seçenekler → Kayıtlı bir özetle başla** bölümünü genişletip kayıtlı özeti seçin. diff --git a/docs/help/zh-Hans/missions.md b/docs/help/zh-Hans/missions.md index 94c829d8f0..3d173791e9 100644 --- a/docs/help/zh-Hans/missions.md +++ b/docs/help/zh-Hans/missions.md @@ -20,6 +20,8 @@ 已保存的一次性任务保留执行控制、任务树、对话和最终报告。现有每日日程仍列出其每日控制,并遵循[每日时间规则](#existing-daily-schedules)。请选择条目并使用该对象可用的控件。 +智能体准备的后续任务会将已保存的[新任务默认设置](#profiles)应用于省略的配置和任务会话选项。在活动任务之外,请使用任务面板中的**创建任务**。 + ### 剧本 {#playbooks} **剧本**选择器正下方会显示所选剧本的一句话说明。**查看详情**会在中央阅读器中打开所选剧本:其步骤、角色,以及折叠在末尾的、其代理收到的确切英文指令。[剧本](playbooks.md)说明每个剧本的步骤、角色和提问,以及 CodeNomad 检查的内容。 @@ -139,6 +141,8 @@ CodeNomad 运行期间,项目中的每个智能体对话(包括任务协调 被拒绝或未确认的选择绝不会重新发送:会重新显示已存储的值,只有在无法读取这些值时才会出现**重新加载**。如果深度更改未确认,你的值会保留;请先使用**刷新项目深度**,再进行其他更改。不要将 **OpenCode 有效深度未知**解释为零或禁用。 +智能体准备任务时也会应用这些默认设置:省略的协调者或角色配置先使用剧本例外,再使用全局选择;全局专家配置用于任务角色,比较裁判默认使用协调者的模型。显式提供的配置作为整体优先,包括选择 OpenCode 默认值或仅指定代理的情况。省略的**任务会话**采用相同的偏好顺序,最后使用**原生子代理**。返回给智能体的创建响应列出已保存的配置、任务会话模式及每项选择的来源:显式指定、偏好或 OpenCode 默认值。偏好无法读取或无效时,创建会被阻止,并返回要求修正或重新加载的错误。即使修改默认设置,重试也会保留最初保存的选择。 + ## 复用已保存简述 {#saved-briefs} 1. 创建时展开**选项 → 从已保存的简述开始**,选择已保存简述。 From 236609f20edbeaf33711f1d5d1633e69746693ff Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pascal=20Andr=C3=A9?= Date: Fri, 6 Nov 2026 00:09:31 +0100 Subject: [PATCH 03/16] fix(missions): align Compare judge inheritance with editor Apply the shared Compare profile freeze after resolving coordinator and role slots for agent preparations. A judge selected as an empty or agent-only profile now inherits the coordinator's known model just like the editor payload, while a judge's own model remains authoritative. Keep the chosen judge slot's explicit or preference origin, retain coordinator-origin inheritance for an omitted judge, and preserve frozen creation receipts across retries. The editor and its existing profile-freezing implementation are unchanged. Extend the CI contract to compare effective editor payloads after freezing, and cover both agent creation paths, slot origins and restart/retry stability. Update Missions documentation, the skill, tool descriptions and all ten help locales, including two translated playbook clarifications. Validation: independent QA edge script 5/5; targeted suites 119 passes and two Windows skips; profile UI suites 11/11; server and UI typechecks, Missions bundle build, native-plugin invariants 2/2 and whitespace checks passed. Offline help validation passed 28 pages across ten locales. The recurrence-reader path-sensitive assertion fails only when cwd contains profiles and passes all 24 tests from a neutral cwd. The extended Missions suite and isolated local-source Git test hit the existing local-source deadline; the full help suite exceeded 120 seconds after 17 passing tests. Neither unrelated test was modified. --- .opencode/skills/codenomad-missions/SKILL.md | 10 ++++-- dev-docs/MISSIONS.md | 10 ++++-- docs/help/de/missions.md | 2 +- docs/help/en/missions.md | 2 +- docs/help/es/missions.md | 2 +- docs/help/fr/missions.md | 2 +- docs/help/he/missions.md | 4 +-- docs/help/he/playbooks.md | 2 +- docs/help/ja/missions.md | 2 +- docs/help/ne/missions.md | 2 +- docs/help/ru/missions.md | 4 +-- docs/help/ru/playbooks.md | 2 +- docs/help/tr/missions.md | 2 +- docs/help/zh-Hans/missions.md | 2 +- .../src/missions/creation-defaults.test.ts | 32 +++++++++++++++++-- .../src/missions/profile-defaults.test.ts | 13 ++++---- .../server/src/missions/profile-defaults.ts | 5 ++- .../server/src/opencode/missions-plugin.ts | 8 ++--- .../tests/contracts/mission-defaults.test.ts | 29 ++++++++++++++--- 19 files changed, 96 insertions(+), 39 deletions(-) diff --git a/.opencode/skills/codenomad-missions/SKILL.md b/.opencode/skills/codenomad-missions/SKILL.md index 94f6c8a58b..c7beb7ff6f 100644 --- a/.opencode/skills/codenomad-missions/SKILL.md +++ b/.opencode/skills/codenomad-missions/SKILL.md @@ -21,12 +21,16 @@ slots and `taskMode` inherit the user's Missions preferences: playbook exception then global defaults (the global specialist supplies task roles; the Compare judge defaults to the coordinator's model). Each explicit profile slot wins whole: `{}` selects OpenCode defaults for that slot, and an agent-only slot keeps its -native model default. `profiles: {}` inherits all slots. With absent preferences, +native model default, except for the Compare judge: after slot selection, any +missing judge model inherits the known coordinator model, including explicit or +preference `{}` and agent-only slots; a judge's own model stays unchanged. +`profiles: {}` inherits all slots. With absent preferences, profiles use OpenCode defaults and task mode uses `native`. Read the creation response's `selection.profiles`, `selection.taskMode` and `selection.origins` to check the saved coordinator and every playbook role: -`explicit`, `preference` or `opencode-default` (the default Compare judge inherits -the coordinator's origin). Unreadable/invalid preferences refuse creation; report +`explicit`, `preference` or `opencode-default`. A chosen judge slot keeps its +explicit/preference origin even with an inherited model; an absent judge slot +inherits the coordinator's origin. Unreadable/invalid preferences refuse creation; report the error and arrange recovery of the Missions preferences before retrying. `inspect({ start })` requires the caller's existing coordinator profile to match the resolved selection. For `prepare`, reuse the same requestID and original diff --git a/dev-docs/MISSIONS.md b/dev-docs/MISSIONS.md index 6df6fbb284..158e2f1d05 100644 --- a/dev-docs/MISSIONS.md +++ b/dev-docs/MISSIONS.md @@ -145,15 +145,19 @@ refuse otherwise. Only one-time coordinators are offered and told about 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. An explicit `taskMode` wins over + leaves every slot eligible for preferences. After slot selection, Compare fills + any missing judge model from the known coordinator model through shared + `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. Creation responses include `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 default Compare judge inherits the coordinator's origin - along with its model. These are saved requested selectors; catalog validation and native + and task mode. 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. An unreadable diff --git a/docs/help/de/missions.md b/docs/help/de/missions.md index 4aa49030d4..dc7b503126 100644 --- a/docs/help/de/missions.md +++ b/docs/help/de/missions.md @@ -141,7 +141,7 @@ Jede **Modell**-Liste zeigt, was die **Modell**-Auswahl der Unterhaltung zeigt, 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. -Diese Vorgaben gelten auch, wenn ein Agent eine Mission vorbereitet: Jedes ausgelassene Koordinator- oder Rollenprofil verwendet zuerst die Playbook-Ausnahme, dann die globale Auswahl. Der globale Spezialist liefert die Aufgabenrollen; der Vergleichsrichter verwendet standardmäßig das Modell des Koordinators. Ein ausdrücklich angegebenes Profil hat als Ganzes Vorrang, auch bei OpenCode-Standardwerten oder einer reinen Agentenauswahl. Ausgelassene **Aufgabensitzungen** folgen derselben Reihenfolge, danach **Native Unteragenten**. Die Erstellungsantwort an den Agenten nennt die gespeicherten Profile, den Sitzungsmodus und die Herkunft jeder Auswahl: ausdrücklich, Vorgabe oder OpenCode-Standard. Unlesbare oder ungültige Vorgaben blockieren die Erstellung mit einer Fehlermeldung zur Korrektur oder zum Neuladen. Wiederholungen behalten die ursprünglich gespeicherte Auswahl auch bei geänderten Vorgaben bei. +Diese Vorgaben gelten auch, wenn ein Agent eine Mission vorbereitet: Jedes ausgelassene Koordinator- oder Rollenprofil verwendet zuerst die Playbook-Ausnahme, dann die globale Auswahl. Der globale Spezialist liefert die Aufgabenrollen; der Vergleichsrichter verwendet standardmäßig das Modell des Koordinators. Ein ausdrücklich angegebenes Profil hat als Ganzes Vorrang, auch bei OpenCode-Standardwerten oder einer reinen Agentenauswahl. Beim Richter wird ein fehlendes Modell anschließend durch das bekannte Koordinatormodell ergänzt, auch bei ausdrücklich gewählten oder gespeicherten OpenCode-Standardwerten oder reiner Agentenauswahl; sein eigenes Modell bleibt unverändert. Der Richter behält die Herkunft seines ausdrücklich gewählten oder gespeicherten Profils; ein ausgelassenes Richterprofil erbt die Herkunft des Koordinators. Ausgelassene **Aufgabensitzungen** folgen derselben Reihenfolge, danach **Native Unteragenten**. Die Erstellungsantwort an den Agenten nennt die gespeicherten Profile, den Sitzungsmodus und die Herkunft jeder Auswahl: ausdrücklich, Vorgabe oder OpenCode-Standard. Unlesbare oder ungültige Vorgaben blockieren die Erstellung mit einer Fehlermeldung zur Korrektur oder zum Neuladen. Wiederholungen behalten die ursprünglich gespeicherte Auswahl auch bei geänderten Vorgaben bei. ## Gespeicherten Auftrag wiederverwenden {#saved-briefs} diff --git a/docs/help/en/missions.md b/docs/help/en/missions.md index 32fafb696f..bb30313e1b 100644 --- a/docs/help/en/missions.md +++ b/docs/help/en/missions.md @@ -137,7 +137,7 @@ 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. -These defaults also apply when an agent prepares a mission: each omitted coordinator or role profile uses the playbook exception, then the global choice; the global specialist supplies task roles, while the comparison judge defaults to the coordinator's model. An explicitly supplied profile wins as a whole, including an OpenCode-default choice or an agent-only choice. Omitted **Task sessions** uses the same preference order, then **Native subagents**. The agent's creation response lists the saved profiles, task-session mode and each choice's source: explicit, preference or OpenCode default. Unreadable or invalid preferences block creation with a recovery error. Retries retain the original saved choices even if you change the defaults. +These defaults also apply when an agent prepares a mission: each omitted coordinator or role profile uses the playbook exception, then the global choice; the global specialist supplies task roles, while the comparison judge defaults to the coordinator's model. An explicitly supplied profile wins as a whole, including an OpenCode-default choice or an agent-only choice. For the judge, any missing model is then filled from the coordinator's known model, even with an explicit or saved OpenCode-default or agent-only choice; its own model stays unchanged. The judge keeps the source of its explicit or saved profile; an omitted judge profile inherits the coordinator's source. Omitted **Task sessions** uses the same preference order, then **Native subagents**. The agent's creation response lists the saved profiles, task-session mode and each choice's source: explicit, preference or OpenCode default. Unreadable or invalid preferences block creation with a recovery error. Retries retain the original saved choices even if you change the defaults. 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. diff --git a/docs/help/es/missions.md b/docs/help/es/missions.md index 5715a24a11..107fcc6ee1 100644 --- a/docs/help/es/missions.md +++ b/docs/help/es/missions.md @@ -141,7 +141,7 @@ Cada lista **Modelo** muestra lo mismo que el selector **Modelo** de la conversa 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. -Estos valores también se aplican cuando un agente prepara una misión: cada perfil de coordinador o rol omitido usa la excepción del guion y luego la elección global; el especialista global proporciona los roles de tareas, mientras que el juez de comparación usa por defecto el modelo del coordinador. Un perfil indicado explícitamente tiene prioridad en su totalidad, incluidos los valores de OpenCode o una elección de solo agente. **Sesiones de tareas** omitido sigue el mismo orden de preferencias y luego **Subagentes nativos**. La respuesta de creación al agente enumera los perfiles guardados, el modo de sesiones y el origen de cada elección: explícito, preferencia o valor predeterminado de OpenCode. Las preferencias ilegibles o inválidas bloquean la creación con un error que pide corregirlas o recargarlas. Los reintentos conservan las elecciones guardadas originales aunque cambies los valores predeterminados. +Estos valores también se aplican cuando un agente prepara una misión: cada perfil de coordinador o rol omitido usa la excepción del guion y luego la elección global; el especialista global proporciona los roles de tareas, mientras que el juez de comparación usa por defecto el modelo del coordinador. Un perfil indicado explícitamente tiene prioridad en su totalidad, incluidos los valores de OpenCode o una elección de solo agente. Para el juez, cualquier modelo ausente se completa después con el modelo conocido del coordinador, incluso con una elección explícita o guardada de valores de OpenCode o de solo agente; su propio modelo se mantiene. El juez conserva el origen de su perfil explícito o guardado; un perfil de juez omitido hereda el origen del coordinador. **Sesiones de tareas** omitido sigue el mismo orden de preferencias y luego **Subagentes nativos**. La respuesta de creación al agente enumera los perfiles guardados, el modo de sesiones y el origen de cada elección: explícito, preferencia o valor predeterminado de OpenCode. Las preferencias ilegibles o inválidas bloquean la creación con un error que pide corregirlas o recargarlas. Los reintentos conservan las elecciones guardadas originales aunque cambies los valores predeterminados. ## Reutilizar una descripción guardada {#saved-briefs} diff --git a/docs/help/fr/missions.md b/docs/help/fr/missions.md index 44a77d8d12..e5e41905e9 100644 --- a/docs/help/fr/missions.md +++ b/docs/help/fr/missions.md @@ -141,7 +141,7 @@ Chaque liste **Modèle** affiche ce qu’affiche le sélecteur **Modèle** de la 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. -Ces défauts s'appliquent aussi quand un agent prépare une mission : chaque profil de coordinateur ou de rôle omis utilise l'exception du scénario, puis le choix global ; le spécialiste global fournit les rôles de tâches, tandis que le juge de comparaison utilise par défaut le modèle du coordinateur. Un profil explicitement fourni prime en entier, y compris un choix de défauts OpenCode ou un agent seul. **Sessions des tâches** omis suit le même ordre de préférences, puis **Sous-agents natifs**. La réponse de création à l'agent donne les profils enregistrés, le mode des sessions de tâches et l'origine de chaque choix : explicite, préférence ou défaut OpenCode. Des préférences illisibles ou invalides bloquent la création avec une erreur demandant leur correction ou leur rechargement. Les réessais conservent les choix enregistrés à l'origine, même si vous modifiez les défauts. +Ces défauts s'appliquent aussi quand un agent prépare une mission : chaque profil de coordinateur ou de rôle omis utilise l'exception du scénario, puis le choix global ; le spécialiste global fournit les rôles de tâches, tandis que le juge de comparaison utilise par défaut le modèle du coordinateur. Un profil explicitement fourni prime en entier, y compris un choix de défauts OpenCode ou un agent seul. Pour le juge, tout modèle manquant est ensuite complété par le modèle connu du coordinateur, même avec un choix explicite ou enregistré de défauts OpenCode ou d'agent seul ; son propre modèle reste inchangé. Le juge conserve l'origine de son profil explicite ou enregistré ; un profil de juge omis hérite de l'origine du coordinateur. **Sessions des tâches** omis suit le même ordre de préférences, puis **Sous-agents natifs**. La réponse de création à l'agent donne les profils enregistrés, le mode des sessions de tâches et l'origine de chaque choix : explicite, préférence ou défaut OpenCode. Des préférences illisibles ou invalides bloquent la création avec une erreur demandant leur correction ou leur rechargement. Les réessais conservent les choix enregistrés à l'origine, même si vous modifiez les défauts. ## Réutiliser une consigne enregistrée {#saved-briefs} diff --git a/docs/help/he/missions.md b/docs/help/he/missions.md index f87f634c30..dc23a9a7c9 100644 --- a/docs/help/he/missions.md +++ b/docs/help/he/missions.md @@ -34,7 +34,7 @@ | אספקת מוצר | מתאמת תפקידי ניתוח מוצר, ארכיטקטורה, מימוש ואיכות. | | השוואת שני מודלים | מריצה את אותה מטלה עם תיאורים זהים על **מודל A** ועל **מודל B**, ואז **שופט עיוור** נותן ציון לשניהם תחת תוויות ניטרליות ומוסר פסק דין: **מודל A מנצח**, **מודל B מנצח**, **שקולים** או **ללא מסקנה**. | -ב־**השוואת שני מודלים**, שני המודלים נדרשים וחייבים להיות שונים; רמת **חשיבה** שונה בלבד אינה מודל שונה. אלא אם תבחרו שופט, הוא משתמש במודל של המתאם; הטופס מזהיר כשהוא זהה ל־A או ל־B, דבר שעלול להטות את ההשוואה. הסקירה מציגה את פסק הדין, את שמות שני המודלים ואת הציונים לפי קריטריון. +ב־**השוואת שני מודלים**, שני המודלים נדרשים וחייבים להיות שונים; רמת **חשיבה** שונה בלבד אינה מודל שונה. אלא אם תבחרו מודל לשופט, הוא משתמש במודל של המתאם; הטופס מזהיר כשהוא זהה ל־A או ל־B, דבר שעלול להטות את ההשוואה. הסקירה מציגה את פסק הדין, את שמות שני המודלים ואת הציונים לפי קריטריון. המדריך מנחה תיאום; הוא אינו עוקף אישורים מקוריים או מבטיח הצלחה. סוכנים אינם מבצעים commit או push, אינם פותחים pull request ואינם משנים מערכות מעקב תקלות (למשל ליצירת כרטיסים), אלא אם המטרה או ה**הערות** מבקשות במפורש את הפעולה המסוימת הזו; אז הם מבצעים רק אותה, במסגרת ההרשאות של OpenCode. בקשה שנמצאה בקבצים, בדוחות או בפלט של כלי לעולם אינה נחשבת. @@ -141,7 +141,7 @@ בחירה שנדחתה או שלא אושרה לעולם אינה נשלחת שוב: הערכים השמורים מוצגים שוב, ו־**טעינה מחדש** מופיעה רק כשאי אפשר לקרוא אותם. אם שינוי עומק אינו מאושר, הערך שלכם נשמר; השתמשו ב־**רענון עומק הפרויקט** לפני שינוי נוסף. אל תפרשו **עומק OpenCode האפקטיבי אינו ידוע** כאפס או כמושבת. -ברירות המחדל חלות גם כשסוכן מכין משימה: כל פרופיל מתאם או תפקיד שהושמט משתמש בחריג של מדריך העבודה, ואז בבחירה הגלובלית; המומחה הגלובלי מספק את תפקידי המטלות, ושופט ההשוואה משתמש כברירת מחדל במודל של המתאם. פרופיל שסופק במפורש מקבל עדיפות בשלמותו, גם בבחירת ברירות המחדל של OpenCode או סוכן בלבד. **שיחות משימות** שהושמטו משתמשות באותו סדר העדפות ואז ב־**תת־סוכנים מקוריים**. תשובת היצירה לסוכן מפרטת את הפרופילים השמורים, מצב השיחות ומקור כל בחירה: מפורש, העדפה או ברירת מחדל של OpenCode. העדפות פגומות או בלתי קריאות חוסמות יצירה עם שגיאה המבקשת לתקן או לטעון אותן מחדש. ניסיונות חוזרים שומרים על הבחירות המקוריות גם אם תשנו את ברירות המחדל. +ברירות המחדל חלות גם כשסוכן מכין משימה: כל פרופיל מתאם או תפקיד שהושמט משתמש בחריג של מדריך העבודה, ואז בבחירה הגלובלית; המומחה הגלובלי מספק את תפקידי המטלות, ושופט ההשוואה משתמש כברירת מחדל במודל של המתאם. פרופיל שסופק במפורש מקבל עדיפות בשלמותו, גם בבחירת ברירות המחדל של OpenCode או סוכן בלבד. אצל השופט, מודל חסר מושלם לאחר מכן מהמודל הידוע של המתאם, גם בבחירה מפורשת או שמורה של ברירות המחדל של OpenCode או של סוכן בלבד; מודל משלו נשאר ללא שינוי. השופט שומר על מקור הפרופיל המפורש או השמור שלו; פרופיל שופט שהושמט יורש את מקור המתאם. **שיחות משימות** שהושמטו משתמשות באותו סדר העדפות ואז ב־**תת־סוכנים מקוריים**. תשובת היצירה לסוכן מפרטת את הפרופילים השמורים, מצב השיחות ומקור כל בחירה: מפורש, העדפה או ברירת מחדל של OpenCode. העדפות פגומות או בלתי קריאות חוסמות יצירה עם שגיאה המבקשת לתקן או לטעון אותן מחדש. ניסיונות חוזרים שומרים על הבחירות המקוריות גם אם תשנו את ברירות המחדל. ## שימוש חוזר בתקציר שמור {#saved-briefs} diff --git a/docs/help/he/playbooks.md b/docs/help/he/playbooks.md index f2ca3a114c..44f7e892af 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 71a67a1f14..2b9720ba9c 100644 --- a/docs/help/ja/missions.md +++ b/docs/help/ja/missions.md @@ -141,7 +141,7 @@ CodeNomad の実行中は、ミッションのコーディネーターやタス 拒否された選択や未確認の選択が再送されることはありません。保存済みの値が再び表示され、**再読み込み** はそれらを読み取れない場合にだけ表示されます。深さの変更が未確認の場合は入力した値が保持されるので、次の変更の前に **プロジェクトの深さを更新** を使用します。**OpenCode の有効な深さは不明** をゼロや無効と解釈しないでください。 -エージェントがミッションを準備する場合も、これらの既定値が適用されます。省略されたコーディネーターや役割のプロファイルには、プレイブックの例外、グローバルの選択の順で適用します。タスクの各役割にはグローバルのスペシャリストを使用し、比較の審査役には既定でコーディネーターのモデルを使用します。明示されたプロファイルは全体として優先され、OpenCode の既定値やエージェントのみの指定も含みます。省略された **タスクセッション** も同じ順で設定を適用し、最後に **ネイティブのサブエージェント** を使用します。エージェントへの作成応答には、保存されたプロファイル、タスクセッションのモード、各選択の出所(明示、設定、OpenCode の既定値)が表示されます。設定が読み取れない、または無効な場合は、修正や再読み込みを求めるエラーで作成を中断します。既定値を変更しても、再試行では元の保存済みの選択を保持します。 +エージェントがミッションを準備する場合も、これらの既定値が適用されます。省略されたコーディネーターや役割のプロファイルには、プレイブックの例外、グローバルの選択の順で適用します。タスクの各役割にはグローバルのスペシャリストを使用し、比較の審査役には既定でコーディネーターのモデルを使用します。明示されたプロファイルは全体として優先され、OpenCode の既定値やエージェントのみの指定も含みます。審査役のモデルが未指定なら、その後で既知のコーディネーターのモデルを補います。明示または保存された OpenCode の既定値やエージェントのみの指定も対象で、審査役独自のモデルはそのまま保持します。審査役は明示または保存されたプロファイルの出所を保持し、審査役のプロファイル自体が省略された場合はコーディネーターの出所を継承します。省略された **タスクセッション** も同じ順で設定を適用し、最後に **ネイティブのサブエージェント** を使用します。エージェントへの作成応答には、保存されたプロファイル、タスクセッションのモード、各選択の出所(明示、設定、OpenCode の既定値)が表示されます。設定が読み取れない、または無効な場合は、修正や再読み込みを求めるエラーで作成を中断します。既定値を変更しても、再試行では元の保存済みの選択を保持します。 ## 保存済みの概要を再利用する {#saved-briefs} diff --git a/docs/help/ne/missions.md b/docs/help/ne/missions.md index 217779456a..9deab99d27 100644 --- a/docs/help/ne/missions.md +++ b/docs/help/ne/missions.md @@ -141,7 +141,7 @@ CodeNomad चलिरहँदा, project का हरेक agent कुर अस्वीकृत वा अपुष्ट चयन कहिल्यै फेरि पठाइँदैन: सुरक्षित मान फेरि देखाइन्छन्, र ती पढ्न नसकिँदा मात्र **पुनः लोड** देखिन्छ। depth परिवर्तन अपुष्ट भए तपाईंको मान राखिन्छ; अर्को परिवर्तनअघि **परियोजनाको गहिराइ ताजा गर्नुहोस्** प्रयोग गर्नुहोस्। **OpenCode को प्रभावकारी गहिराइ अज्ञात** लाई शून्य वा disabled नमान्नुहोस्। -एजेन्टले मिसन तयार गर्दा पनि यी पूर्वनिर्धारित मान लागू हुन्छन्: छुटाइएको समन्वयकर्ता वा भूमिकाको प्रोफाइलमा पहिले प्लेबुकको अपवाद, त्यसपछि विश्वव्यापी चयन प्रयोग हुन्छ। कार्य भूमिकामा विश्वव्यापी विशेषज्ञ प्रयोग हुन्छ; तुलना गर्ने निर्णायकले पूर्वनिर्धारित रूपमा समन्वयकर्ताको मोडेल प्रयोग गर्छ। स्पष्ट रूपमा दिइएको प्रोफाइलले पूर्ण रूपमा प्राथमिकता पाउँछ, OpenCode का पूर्वनिर्धारित मान वा एजेन्ट मात्र रोजेको अवस्थामा पनि। छुटाइएको **कार्य सत्रहरू** मा उही प्राथमिकता क्रमपछि **नेटिभ उपएजेन्टहरू** प्रयोग हुन्छ। एजेन्टलाई फर्काइएको सिर्जना जवाफमा सुरक्षित प्रोफाइल, कार्य सत्रको मोड र हरेक चयनको स्रोत हुन्छ: स्पष्ट, प्राथमिकता वा OpenCode को पूर्वनिर्धारित मान। पढ्न नसकिने वा अमान्य प्राथमिकताले सुधार वा पुनः लोड गर्नुपर्ने त्रुटिसहित सिर्जना रोक्छन्। पूर्वनिर्धारित मान बदले पनि पुनःप्रयासले सुरुका सुरक्षित चयन कायम राख्छ। +एजेन्टले मिसन तयार गर्दा पनि यी पूर्वनिर्धारित मान लागू हुन्छन्: छुटाइएको समन्वयकर्ता वा भूमिकाको प्रोफाइलमा पहिले प्लेबुकको अपवाद, त्यसपछि विश्वव्यापी चयन प्रयोग हुन्छ। कार्य भूमिकामा विश्वव्यापी विशेषज्ञ प्रयोग हुन्छ; तुलना गर्ने निर्णायकले पूर्वनिर्धारित रूपमा समन्वयकर्ताको मोडेल प्रयोग गर्छ। स्पष्ट रूपमा दिइएको प्रोफाइलले पूर्ण रूपमा प्राथमिकता पाउँछ, OpenCode का पूर्वनिर्धारित मान वा एजेन्ट मात्र रोजेको अवस्थामा पनि। निर्णायकको मोडेल छुटेको भए त्यसपछि समन्वयकर्ताको ज्ञात मोडेलबाट पूरा गरिन्छ, स्पष्ट वा सुरक्षित OpenCode पूर्वनिर्धारित मान वा एजेन्ट मात्रको चयनमा पनि; निर्णायकको आफ्नै मोडेल यथावत् रहन्छ। निर्णायकले आफ्नो स्पष्ट वा सुरक्षित प्रोफाइलको स्रोत कायम राख्छ; निर्णायकको प्रोफाइल नै छुटेको भए समन्वयकर्ताको स्रोत लिन्छ। छुटाइएको **कार्य सत्रहरू** मा उही प्राथमिकता क्रमपछि **नेटिभ उपएजेन्टहरू** प्रयोग हुन्छ। एजेन्टलाई फर्काइएको सिर्जना जवाफमा सुरक्षित प्रोफाइल, कार्य सत्रको मोड र हरेक चयनको स्रोत हुन्छ: स्पष्ट, प्राथमिकता वा OpenCode को पूर्वनिर्धारित मान। पढ्न नसकिने वा अमान्य प्राथमिकताले सुधार वा पुनः लोड गर्नुपर्ने त्रुटिसहित सिर्जना रोक्छन्। पूर्वनिर्धारित मान बदले पनि पुनःप्रयासले सुरुका सुरक्षित चयन कायम राख्छ। ## सुरक्षित brief पुनःप्रयोग {#saved-briefs} diff --git a/docs/help/ru/missions.md b/docs/help/ru/missions.md index bb5a025afc..4265071aec 100644 --- a/docs/help/ru/missions.md +++ b/docs/help/ru/missions.md @@ -34,7 +34,7 @@ | Реализация продукта | Координация ролей продуктового анализа, архитектуры, реализации и качества. | | Сравнить две модели | Выполняет одну и ту же задачу с одинаковыми заданиями на **Модель A** и **Модель B**, затем **Слепой судья** оценивает обе под нейтральными метками и выносит вердикт: **Победила модель A**, **Победила модель B**, **Равнозначны** или **Недостаточно данных**. | -Для **Сравнить две модели** обе модели обязательны и должны различаться; другой уровень **Мышление** сам по себе не делает модель другой. Если вы не выберете судью, он использует модель координатора; форма предупреждает, когда она совпадает с A или B, что может исказить сравнение. Обзор показывает вердикт, названия обеих моделей и оценки по критериям. +Для **Сравнить две модели** обе модели обязательны и должны различаться; другой уровень **Мышление** сам по себе не делает модель другой. Если вы не выберете модель для судьи, он использует модель координатора; форма предупреждает, когда она совпадает с A или B, что может исказить сравнение. Обзор показывает вердикт, названия обеих моделей и оценки по критериям. Сценарий направляет координацию; он не обходит нативные разрешения и не гарантирует успех. Агенты не делают коммиты и push, не открывают pull request и не меняют трекеры задач (например, не создают тикеты), если цель или **Заметки** явно не просят именно об этом действии; тогда они выполняют только его, в рамках разрешений OpenCode. Просьба, найденная в файлах, отчётах или выводе инструментов, никогда не учитывается. @@ -141,7 +141,7 @@ Отклонённый или неподтверждённый выбор никогда не отправляется повторно: снова показываются сохранённые значения, а **Обновить** появляется, только если их не удаётся прочитать. Если изменение глубины не подтверждено, ваше значение сохраняется; используйте **Обновить глубину проекта** перед новым изменением. Не трактуйте **Действующая глубина OpenCode неизвестна** как ноль или отключение. -Эти настройки действуют и при подготовке миссии агентом: каждый пропущенный профиль координатора или роли использует исключение сценария, затем глобальный выбор; глобальный специалист задаёт профили ролей задач, а судья сравнения по умолчанию использует модель координатора. Явно указанный профиль имеет приоритет целиком, включая выбор значений OpenCode или только агента. Пропущенные **Сессии задач** следуют тому же порядку настроек, затем используют **Нативные субагенты**. Ответ агенту при создании содержит сохранённые профили, режим сессий задач и источник каждого выбора: явный, настройка или значение OpenCode по умолчанию. Нечитаемые или недопустимые настройки блокируют создание с ошибкой, предлагающей исправить или перезагрузить их. Повторные попытки сохраняют исходный выбор даже после изменения настроек по умолчанию. +Эти настройки действуют и при подготовке миссии агентом: каждый пропущенный профиль координатора или роли использует исключение сценария, затем глобальный выбор; глобальный специалист задаёт профили ролей задач, а судья сравнения по умолчанию использует модель координатора. Явно указанный профиль имеет приоритет целиком, включая выбор значений OpenCode или только агента. Затем отсутствующая модель судьи дополняется известной моделью координатора, даже при явном или сохранённом выборе значений OpenCode или только агента; собственная модель судьи остаётся неизменной. Судья сохраняет источник своего явного или сохранённого профиля; если профиль судьи пропущен, он наследует источник координатора. Пропущенные **Сессии задач** следуют тому же порядку настроек, затем используют **Нативные субагенты**. Ответ агенту при создании содержит сохранённые профили, режим сессий задач и источник каждого выбора: явный, настройка или значение OpenCode по умолчанию. Нечитаемые или недопустимые настройки блокируют создание с ошибкой, предлагающей исправить или перезагрузить их. Повторные попытки сохраняют исходный выбор даже после изменения настроек по умолчанию. ## Повторное использование описания {#saved-briefs} diff --git a/docs/help/ru/playbooks.md b/docs/help/ru/playbooks.md index 51b4a01e9c..d994d7ce0a 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 d2077b6127..33246666fd 100644 --- a/docs/help/tr/missions.md +++ b/docs/help/tr/missions.md @@ -141,7 +141,7 @@ Her **Model** listesi, konuşmanın **Model** seçicisinin gösterdiklerini ayn 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. -Bir ajan görev hazırlarken de bu varsayılanlar uygulanır: belirtilmeyen her koordinatör veya rol profili önce rehber istisnasını, ardından genel seçimi kullanır; genel uzman görev rollerini sağlar, karşılaştırma hakemi ise varsayılan olarak koordinatörün modelini kullanır. Açıkça verilen profil, OpenCode varsayılanı veya yalnızca ajan seçimi dahil, bütünüyle önceliklidir. Belirtilmeyen **Görev oturumları** aynı tercih sırasını, ardından **Yerel alt ajanlar** seçimini kullanır. Ajana dönen oluşturma yanıtı kayıtlı profilleri, görev oturumu modunu ve her seçimin kaynağını listeler: açık seçim, tercih veya OpenCode varsayılanı. Okunamayan veya geçersiz tercihler, düzeltme ya da yeniden yükleme isteyen bir hatayla oluşturmayı engeller. Varsayılanları değiştirseniz bile yeniden denemeler ilk kaydedilen seçimleri korur. +Bir ajan görev hazırlarken de bu varsayılanlar uygulanır: belirtilmeyen her koordinatör veya rol profili önce rehber istisnasını, ardından genel seçimi kullanır; genel uzman görev rollerini sağlar, karşılaştırma hakemi ise varsayılan olarak koordinatörün modelini kullanır. Açıkça verilen profil, OpenCode varsayılanı veya yalnızca ajan seçimi dahil, bütünüyle önceliklidir. Hakemin eksik modeli daha sonra koordinatörün bilinen modeliyle tamamlanır; açık veya kayıtlı OpenCode varsayılanı ya da yalnızca ajan seçimi de buna dahildir, hakemin kendi modeli ise korunur. Hakem açık veya kayıtlı profilinin kaynağını korur; hakem profili belirtilmemişse koordinatörün kaynağını devralır. Belirtilmeyen **Görev oturumları** aynı tercih sırasını, ardından **Yerel alt ajanlar** seçimini kullanır. Ajana dönen oluşturma yanıtı kayıtlı profilleri, görev oturumu modunu ve her seçimin kaynağını listeler: açık seçim, tercih veya OpenCode varsayılanı. Okunamayan veya geçersiz tercihler, düzeltme ya da yeniden yükleme isteyen bir hatayla oluşturmayı engeller. Varsayılanları değiştirseniz bile yeniden denemeler ilk kaydedilen seçimleri korur. ## Kayıtlı bir özeti yeniden kullanın {#saved-briefs} diff --git a/docs/help/zh-Hans/missions.md b/docs/help/zh-Hans/missions.md index 3d173791e9..e68168c09b 100644 --- a/docs/help/zh-Hans/missions.md +++ b/docs/help/zh-Hans/missions.md @@ -141,7 +141,7 @@ CodeNomad 运行期间,项目中的每个智能体对话(包括任务协调 被拒绝或未确认的选择绝不会重新发送:会重新显示已存储的值,只有在无法读取这些值时才会出现**重新加载**。如果深度更改未确认,你的值会保留;请先使用**刷新项目深度**,再进行其他更改。不要将 **OpenCode 有效深度未知**解释为零或禁用。 -智能体准备任务时也会应用这些默认设置:省略的协调者或角色配置先使用剧本例外,再使用全局选择;全局专家配置用于任务角色,比较裁判默认使用协调者的模型。显式提供的配置作为整体优先,包括选择 OpenCode 默认值或仅指定代理的情况。省略的**任务会话**采用相同的偏好顺序,最后使用**原生子代理**。返回给智能体的创建响应列出已保存的配置、任务会话模式及每项选择的来源:显式指定、偏好或 OpenCode 默认值。偏好无法读取或无效时,创建会被阻止,并返回要求修正或重新加载的错误。即使修改默认设置,重试也会保留最初保存的选择。 +智能体准备任务时也会应用这些默认设置:省略的协调者或角色配置先使用剧本例外,再使用全局选择;全局专家配置用于任务角色,比较裁判默认使用协调者的模型。显式提供的配置作为整体优先,包括选择 OpenCode 默认值或仅指定代理的情况。随后,裁判缺失的模型会用协调者已知的模型补全,即使显式或已保存的选择为 OpenCode 默认值或仅指定代理;裁判自身已指定的模型保持不变。裁判保留其显式或已保存配置的来源;裁判配置整体省略时,继承协调者的来源。省略的**任务会话**采用相同的偏好顺序,最后使用**原生子代理**。返回给智能体的创建响应列出已保存的配置、任务会话模式及每项选择的来源:显式指定、偏好或 OpenCode 默认值。偏好无法读取或无效时,创建会被阻止,并返回要求修正或重新加载的错误。即使修改默认设置,重试也会保留最初保存的选择。 ## 复用已保存简述 {#saved-briefs} diff --git a/packages/server/src/missions/creation-defaults.test.ts b/packages/server/src/missions/creation-defaults.test.ts index 5dc27a0f42..4082ec1adc 100644 --- a/packages/server/src/missions/creation-defaults.test.ts +++ b/packages/server/src/missions/creation-defaults.test.ts @@ -9,6 +9,7 @@ import type { MissionJsonValue } from "./model" import { NativeMissionDocumentStore, type MissionDocumentStorage } from "./mission-document-store" import { resolveMissionCreationDefaults } from "./profile-defaults" import { CODENOMAD_MISSIONS_RPC } from "./rpc" +import { freezeCompareProfiles } from "./playbook-profiles" function fixture() { const values = new Map() @@ -52,11 +53,38 @@ function fixture() { }, } let control = new MissionControl(options) - return { get control() { return control }, coordinator, documents, values, get reads() { return reads }, get created() { return created }, + return { get control() { return control }, coordinator, documents, values, sessions, get reads() { return reads }, get created() { return created }, fail: () => { failJournal = true }, failBeforeDocument: () => { failDocument = true }, - invalidate: () => { preferences = null }, restart: () => { control = new MissionControl(options) } } + 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 = () => method === "prepare" ? f.control.prepare(f.coordinator, { ...request, requestID: "compare" }) + : f.control.inspect(f.coordinator, { start: request }, "compare") + const result = await create() + assert.ok(result.mission) + const selected = missionCreationSelection(result.mission) + 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(missionCreationSelection((await create()).mission!), 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() diff --git a/packages/server/src/missions/profile-defaults.test.ts b/packages/server/src/missions/profile-defaults.test.ts index 103b96fc3b..6a3777b431 100644 --- a/packages/server/src/missions/profile-defaults.test.ts +++ b/packages/server/src/missions/profile-defaults.test.ts @@ -108,14 +108,15 @@ test("Compare's missing judge inherits only the coordinator model and its origin assert.equal(withoutCoordinator.origins.roles.comparator, "opencode-default") }) -test("Compare's selected judge stays whole even when empty or agent-only", () => { +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 } } }) - assert.deepEqual(explicit.profiles.roles.comparator, 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, comparator) + assert.deepEqual(preferred.profiles.roles.comparator, expected) assert.equal(preferred.origins.roles.comparator, "preference") } }) @@ -152,7 +153,7 @@ test("legacy custom preferences migrate to all without changing the input", () = assert.deepEqual(legacy, snapshot) }) -test("an omitted Compare judge freezes a known coordinator model without completing selected judge slots", () => { +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, {}) @@ -160,11 +161,11 @@ test("an omitted Compare judge freezes a known coordinator model without complet 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) + 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) + assert.deepEqual(preference.profiles.roles.comparator, { ...comparator, model: { providerID: "p", id: "known" } }) assert.equal(preference.origins.roles.comparator, "preference") } }) diff --git a/packages/server/src/missions/profile-defaults.ts b/packages/server/src/missions/profile-defaults.ts index bb73570b29..55420fdc94 100644 --- a/packages/server/src/missions/profile-defaults.ts +++ b/packages/server/src/missions/profile-defaults.ts @@ -82,7 +82,7 @@ export interface MissionCreationDefaults { origins: { coordinator: MissionDefaultOrigin; roles: Record; taskMode: MissionDefaultOrigin } } -/** Resolve whole slots once, before creation; an empty slot deliberately selects native defaults. */ +/** Resolve whole slots, then freeze Compare's missing judge model against the coordinator. */ export function resolveMissionCreationDefaults(input: { template: MissionTemplateId preferences: unknown @@ -105,7 +105,6 @@ export function resolveMissionCreationDefaults(input: { 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.execution = freezeCompareProfiles("compare", { coordinator: coordinator.execution }, input.coordinatorModel)?.roles?.comparator ?? {} selected.origin = coordinator.origin } roles[role] = selected.execution @@ -114,7 +113,7 @@ export function resolveMissionCreationDefaults(input: { const preferredTaskMode = preferences.find(item => item.template === input.template)?.taskMode ?? preferences.find(item => item.template === "all")?.taskMode return structuredClone({ - profiles: { coordinator: coordinator.execution, roles }, + profiles: freezeCompareProfiles(input.template, { coordinator: coordinator.execution, roles }, input.coordinatorModel) as Required, taskMode: parseMissionTaskMode(input.taskMode === undefined ? preferredTaskMode : input.taskMode), origins: { coordinator: coordinator.origin, roles: origins, taskMode: input.taskMode !== undefined ? "explicit" : preferredTaskMode !== undefined ? "preference" : "opencode-default" }, diff --git a/packages/server/src/opencode/missions-plugin.ts b/packages/server/src/opencode/missions-plugin.ts index 1e47d1b73c..29796c5f31 100644 --- a/packages/server/src/opencode/missions-plugin.ts +++ b/packages/server/src/opencode/missions-plugin.ts @@ -381,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. Creation fills omitted profile slots and taskMode from the user's Missions preferences (type exception, then global); explicit slots win whole, including {}. It returns selection with saved profiles, taskMode and origins (explicit, preference, opencode-default), and refuses unreadable/invalid preferences. The existing coordinator must match the resolved profile. 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. Creation fills omitted profile slots and taskMode from the user's Missions preferences (type exception, then global); explicit slots win whole, including {} or agent-only. Compare then fills any missing judge model from the known coordinator model, including explicit/preference {} or agent-only slots; a judge's own model is preserved. A chosen judge slot keeps its origin; an absent slot inherits the coordinator's origin. It returns selection with saved profiles, taskMode and origins (explicit, preference, opencode-default), and refuses unreadable/invalid preferences. The existing coordinator must match the resolved profile. 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.", input: inspectSchema, options: { namespace: "mission", codemode: false }, execute: async (input, tool) => { @@ -507,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. Omitted profile slots and taskMode inherit the user's Missions preferences (type exception, then global); explicit slots win whole, including {}. Returns selection with saved profiles, taskMode and origins (explicit, preference, opencode-default); unreadable/invalid preferences refuse creation. It never starts; the user presses Play. Reuse the same requestID and original inputs to retry: saved choices stay frozen even if preferences change. Outside an active mission use the Missions editor. 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: what the Mission editor creates. Omitted profile slots and taskMode inherit the user's Missions preferences (type exception, then global); explicit slots win whole, including {} or agent-only. Compare then fills any missing judge model from the known coordinator model, including explicit/preference {} or agent-only slots; a judge's own model is preserved. A chosen judge slot keeps its origin; an absent slot inherits the coordinator's origin. Returns selection with saved profiles, taskMode and origins (explicit, preference, opencode-default); unreadable/invalid preferences refuse creation. It never starts; the user presses Play. Reuse the same requestID and original inputs to retry: saved choices stay frozen even if preferences change. Outside an active mission use the Missions editor. Find it later with mission.inspect({ list: true }) and read it with mission.inspect({ missionID }); you cannot control it.", input: prepareSchema, options: { namespace: "mission", codemode: false }, execute: async (input, tool) => { @@ -631,7 +631,7 @@ 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, description: "Omitted coordinator/role slots inherit Missions preferences: type exception, then global (specialist for task roles). Each explicit slot replaces the preference whole; {} selects OpenCode defaults for that slot. profiles: {} inherits all slots. Invalid preferences refuse creation." }, + profiles: { ...missionProfilesSchema, description: "Omitted coordinator/role slots inherit Missions preferences: type exception, then global (specialist for task roles). Each explicit slot replaces the preference whole; {} selects OpenCode defaults for that slot. Compare then fills any missing judge model from the known coordinator model, including explicit/preference {} or agent-only slots; a judge's own model is preserved. A chosen judge slot keeps its origin; an absent slot inherits the coordinator's origin. profiles: {} inherits all slots. Invalid preferences refuse creation." }, taskMode: { ...missionTaskModeSchema, description: "Explicit policy wins; omission inherits Missions preferences (type exception, then global), then native." }, }, required: ["requestID", "objective", "template"], @@ -689,7 +689,7 @@ 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, description: "Omitted coordinator/role slots inherit Missions preferences: type exception, then global (specialist for task roles). Explicit slots replace whole, including {} or agent-only. profiles: {} inherits all slots. Invalid preferences refuse creation." }, + profiles: { ...missionProfilesSchema, description: "Omitted coordinator/role slots inherit Missions preferences: type exception, then global (specialist for task roles). Explicit slots replace whole, including {} or agent-only. Compare then fills any missing judge model from the known coordinator model, including explicit/preference {} or agent-only slots; a judge's own model is preserved. A chosen judge slot keeps its origin; an absent slot inherits the coordinator's origin. profiles: {} inherits all slots. Invalid preferences refuse creation." }, 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"], diff --git a/packages/ui/tests/contracts/mission-defaults.test.ts b/packages/ui/tests/contracts/mission-defaults.test.ts index 5987dcb54a..c39ed0e942 100644 --- a/packages/ui/tests/contracts/mission-defaults.test.ts +++ b/packages/ui/tests/contracts/mission-defaults.test.ts @@ -2,7 +2,7 @@ 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 { missionProfileRoles, missionRoleProfile } from "../../../server/src/missions/playbook-profiles" +import { freezeCompareProfiles, missionProfileRoles } from "../../../server/src/missions/playbook-profiles" import type { MissionTemplateId } from "../../../server/src/missions/model" test("the UI default API reexports the pure server implementation", () => { @@ -21,15 +21,36 @@ test("UI creation defaults and server resolution agree for all five templates, i ...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 draft = ui.missionDefaultsFor(normalized, template) + const payload = freezeCompareProfiles(template, ui.missionDefaultsFor(normalized, template)) const result = server.resolveMissionCreationDefaults({ template, preferences }) const roles = Object.fromEntries(missionProfileRoles[template].map(role => [role, - draft?.roles?.[role] ?? (role === "comparator" ? missionRoleProfile(template, draft, role) : undefined) ?? {}])) - assert.deepEqual(result.profiles, { coordinator: draft?.coordinator ?? {}, roles }, template) + payload?.roles?.[role] ?? {}])) + assert.deepEqual(result.profiles, { coordinator: payload?.coordinator ?? {}, roles }, template) assert.equal(result.taskMode, ui.missionTaskModeFor(normalized, template), template) assert.deepEqual(ui.resolveMissionCreationDefaults({ template, preferences }), result) } }) + +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 draft = source === "preference" ? ui.missionDefaultsFor(ui.normalizeMissionDefaults(preferences), "compare") : profiles + const payload = freezeCompareProfiles("compare", draft) + 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) + } + } +}) From b9e16375ddc0120fb8be8f122c77df3bafbcb41e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pascal=20Andr=C3=A9?= Date: Fri, 6 Nov 2026 01:27:35 +0100 Subject: [PATCH 04/16] fix(missions): settle preparation choices and clarify defaults Definite preparation refusals must not consume all 128 retained-choice slots or turn an identical retry into an uncertain result. Release choices on certified no-effect outcomes, retain genuinely unknown attempts, and remove standalone intentions from inspect-start, whose journal and unified document already retain creation choices. Bound preparation-choice retention to 24 hours without renewing it on retries or expiring native-effect holds. Serialize dispatch for the same request, preserve prior uncertainty across local and backend preflight failures, and keep cleanup failures from replacing an authoritative success or refusal. Capacity errors and the current Missions documentation explain recovery and the distinction between retained choices and native authorization. Validate explicit profile roles before preference resolution and reserve the invalid-preferences error for the typed preference-document failure. Share one origin constant, selection type and task-mode resolver; distinguish creation metadata by name. Remove the circular editor assertion, trim repeated tool prose, align the nine translated help paragraphs with English, and explain coordinator-preference overrides without relaxing profile checks. Added regression coverage for 128 refusals, no-effect certificates, expiry, optional key removal, cleanup failures, uncertain preflight retries and inspect-start failures. The final focused suites passed 115 tests; both fresh independent reviews ended with zero findings. Server/UI typechecks, Missions build, native-plugin invariants 2/2, help tests 31/31 and whitespace checks passed. The full Missions suite ran 1044 tests with 1043 passes and the unchanged local-source Git deadline failure; no unrelated test or shared runtime was modified. --- .opencode/skills/codenomad-missions/SKILL.md | 22 +++- dev-docs/MISSIONS.md | 40 ++++-- docs/help/de/missions.md | 8 +- docs/help/es/missions.md | 8 +- docs/help/fr/missions.md | 8 +- docs/help/he/missions.md | 8 +- docs/help/ja/missions.md | 8 +- docs/help/ne/missions.md | 8 +- docs/help/ru/missions.md | 8 +- docs/help/tr/missions.md | 8 +- docs/help/zh-Hans/missions.md | 8 +- packages/server/src/missions/control-types.ts | 7 +- packages/server/src/missions/control.ts | 114 ++++++++++-------- .../src/missions/coordinator-actions.test.ts | 81 ++++++++++++- .../src/missions/creation-defaults.test.ts | 67 ++++++++-- .../server/src/missions/creation-defaults.ts | 19 +-- .../src/missions/creation-intent.test.ts | 55 ++++++++- .../server/src/missions/creation-intent.ts | 93 +++++++++++--- packages/server/src/missions/model.ts | 4 +- .../src/missions/profile-defaults.test.ts | 18 ++- .../server/src/missions/profile-defaults.ts | 28 +++-- .../server/src/missions/recovery-error.ts | 2 + ...automation-plugin-profile-defaults.test.ts | 4 + .../server/src/opencode/automation-plugin.ts | 13 +- .../server/src/opencode/missions-plugin.ts | 4 +- .../routes/mission-creation-fence.test.ts | 19 ++- .../server/routes/mission-creation-holds.ts | 9 ++ .../routes/mission-creation-pipeline.ts | 4 +- .../src/server/routes/mission-prepare.ts | 42 ++++--- .../routes/mission-profile-defaults.test.ts | 22 +++- .../server/routes/mission-profile-defaults.ts | 11 +- .../tests/contracts/mission-defaults.test.ts | 2 +- 32 files changed, 559 insertions(+), 193 deletions(-) diff --git a/.opencode/skills/codenomad-missions/SKILL.md b/.opencode/skills/codenomad-missions/SKILL.md index c7beb7ff6f..7d8e6f0910 100644 --- a/.opencode/skills/codenomad-missions/SKILL.md +++ b/.opencode/skills/codenomad-missions/SKILL.md @@ -33,8 +33,26 @@ explicit/preference origin even with an inherited model; an absent judge slot inherits the coordinator's origin. Unreadable/invalid preferences refuse creation; report the error and arrange recovery of the Missions preferences before retrying. `inspect({ start })` requires the caller's existing coordinator profile to match -the resolved selection. For `prepare`, reuse the same requestID and original -inputs: saved choices stay frozen across retries and preference changes. +the resolved selection. When a coordinator preference differs, pass +`profiles.coordinator` (for example `{}`) to override that preference; the existing +profile is still checked against the resolved selection. An explicit-profile +mismatch receives the generic native-profile error. + +For `prepare`, reuse the same requestID and original inputs; same-requestID +preparations are serialized. Its standalone intent retains choices for an unknown +outcome, releasing them on a positive result or a definitive no-effect refusal. +A retry's prevalidation refusal leaves an earlier attempt's uncertainty intact. +The project retains at most 128 unknown choices for 24 hours from first +reservation; retries preserve that deadline. An entry without a timestamp gets +one on its first read/prune and expires 24 hours later. At capacity, retry original +requestIDs to recover receipts and release slots, or wait for expiry. After expiry, +preferences may be read anew only with both creation event and document absent; +a positive receipt or saved document keeps its choices frozen. `inspect({ start })` +retains choices through its journal/document receipt under its native invocation +identity. Native holds and authorization keep their own settlement rules after +choice expiry. Check the mission and original conversation before using a new +requestID; never duplicate uncertain work or resume automatically after expiry. + Outside an active mission, use the Missions editor in CodeNomad; never create an intermediate mission merely to gain access to `mission.prepare`. diff --git a/dev-docs/MISSIONS.md b/dev-docs/MISSIONS.md index 158e2f1d05..606351eea6 100644 --- a/dev-docs/MISSIONS.md +++ b/dev-docs/MISSIONS.md @@ -140,7 +140,7 @@ refuse otherwise. Only one-time coordinators are offered and told about Both `mission.prepare` and `mission.inspect({ start })` resolve omitted coordinator/role profiles and `taskMode` from the owning CodeNomad backend's - `ui.missionProfileDefaults`. The editor and server share + `ui.settings.missionProfileDefaults`. The editor and server share `missions/profile-defaults.ts`: 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, @@ -160,18 +160,42 @@ refuse otherwise. Only one-time coordinators are offered and told about 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. An unreadable + 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. An unreadable preference document or unavailable backend returns `mission-preferences-unavailable`; invalid preferences return `mission-preferences-invalid`. Both refuse creation and ask for preference recovery, including when profiles were supplied explicitly. - 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. Reuse the - same requestID and original inputs: a durable pre-dispatch intent retains the - chosen profiles, task mode and origins across uncertain attempts, preference - changes and restarts. `inspect({ start })` retains these choices under its - native invocation identity too. A held uncertain attempt is reported uncertain. + 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. An + entry without a timestamp receives the current time on its first read or prune + and expires 24 hours later. At capacity, retry the original requestIDs to + recover completed preparations and release their slots, or wait for their + 24-hour retention to expire. + + 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. A held uncertain + attempt is reported uncertain. 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 diff --git a/docs/help/de/missions.md b/docs/help/de/missions.md index dc7b503126..46468e9283 100644 --- a/docs/help/de/missions.md +++ b/docs/help/de/missions.md @@ -18,10 +18,10 @@ Missionen verbinden einen dauerhaften Projektplan mit nativen OpenCode-Unterhalt **Erstellen speichert eine pausierte Mission.** Erst ▶ **Starten** aktiviert Arbeit und native Kalender. Die Erstellung gehört zum ausgewählten Projekt/zur ausgewählten Location und erfasst die angeforderten Profile und die Aufgabensitzungsrichtlinie. Validierung steht neben dem betroffenen Feld; eine Ablehnung mit dem Hinweis, dass nichts gesendet wurde, erhält den Entwurf zur Korrektur. Ein einmaliger Koordinator kann auch eine separate Folgemission vorbereiten: Sie erscheint als **Vorbereitet** und startet über ihre eigene ▶-Aktion. -Gespeicherte einmalige Missionen behalten ihre Ausführungssteuerung, ihren Aufgabenbaum, ihre Unterhaltungen und ihre Abschlussberichte. Bestehende tägliche Zeitpläne bleiben mit ihren täglichen Steuerelementen und [täglichen Zeitregeln](#existing-daily-schedules) aufgelistet. Wählen Sie den Eintrag und verwenden Sie die für dieses Objekt verfügbaren Steuerelemente. - Von einem Agenten vorbereitete Folgemissionen verwenden Ihre gespeicherten [Vorgaben für neue Missionen](#profiles) für ausgelassene Profile und Aufgabensitzungen. Verwenden Sie außerhalb einer aktiven Mission **Mission erstellen** im Missionsbereich. +Gespeicherte einmalige Missionen behalten ihre Ausführungssteuerung, ihren Aufgabenbaum, ihre Unterhaltungen und ihre Abschlussberichte. Bestehende tägliche Zeitpläne bleiben mit ihren täglichen Steuerelementen und [täglichen Zeitregeln](#existing-daily-schedules) aufgelistet. Wählen Sie den Eintrag und verwenden Sie die für dieses Objekt verfügbaren Steuerelemente. + ### Playbooks {#playbooks} Direkt unter dem Auswahlfeld **Playbook** steht eine einsätzige Beschreibung des ausgewählten Playbooks. **Details anzeigen** öffnet das ausgewählte Playbook im zentralen Leser: seine Schritte, seine Rollen und, am Ende eingeklappt, die genauen englischen Anweisungen, die seine Agenten erhalten. [Playbooks](playbooks.md) erklärt Schritte, Rollen und Fragen jedes Playbooks und was CodeNomad prüft. @@ -137,12 +137,12 @@ 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. +Diese Vorgaben gelten auch, wenn ein Agent eine Mission vorbereitet: Jedes ausgelassene Koordinator- oder Rollenprofil verwendet zuerst die Playbook-Ausnahme, dann die globale Auswahl. Der globale Spezialist liefert die Aufgabenrollen; der Vergleichsrichter verwendet standardmäßig das Modell des Koordinators. Ein ausdrücklich angegebenes Profil hat als Ganzes Vorrang, auch bei OpenCode-Standardwerten oder einer reinen Agentenauswahl. Beim Richter wird ein fehlendes Modell anschließend durch das bekannte Koordinatormodell ergänzt, auch bei ausdrücklich gewählten oder gespeicherten OpenCode-Standardwerten oder reiner Agentenauswahl; sein eigenes Modell bleibt unverändert. Der Richter behält die Herkunft seines ausdrücklich gewählten oder gespeicherten Profils; ein ausgelassenes Richterprofil erbt die Herkunft des Koordinators. Ausgelassene **Aufgabensitzungen** folgen derselben Reihenfolge, danach **Native Unteragenten**. Die Erstellungsantwort an den Agenten nennt die gespeicherten Profile, den Sitzungsmodus und die Herkunft jeder Auswahl: ausdrücklich, Vorgabe oder OpenCode-Standard. Unlesbare oder ungültige Vorgaben blockieren die Erstellung mit einer Fehlermeldung zur Korrektur oder zum Neuladen. Wiederholungen behalten die ursprünglich gespeicherte Auswahl auch bei geänderten Vorgaben bei. + 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. -Diese Vorgaben gelten auch, wenn ein Agent eine Mission vorbereitet: Jedes ausgelassene Koordinator- oder Rollenprofil verwendet zuerst die Playbook-Ausnahme, dann die globale Auswahl. Der globale Spezialist liefert die Aufgabenrollen; der Vergleichsrichter verwendet standardmäßig das Modell des Koordinators. Ein ausdrücklich angegebenes Profil hat als Ganzes Vorrang, auch bei OpenCode-Standardwerten oder einer reinen Agentenauswahl. Beim Richter wird ein fehlendes Modell anschließend durch das bekannte Koordinatormodell ergänzt, auch bei ausdrücklich gewählten oder gespeicherten OpenCode-Standardwerten oder reiner Agentenauswahl; sein eigenes Modell bleibt unverändert. Der Richter behält die Herkunft seines ausdrücklich gewählten oder gespeicherten Profils; ein ausgelassenes Richterprofil erbt die Herkunft des Koordinators. Ausgelassene **Aufgabensitzungen** folgen derselben Reihenfolge, danach **Native Unteragenten**. Die Erstellungsantwort an den Agenten nennt die gespeicherten Profile, den Sitzungsmodus und die Herkunft jeder Auswahl: ausdrücklich, Vorgabe oder OpenCode-Standard. Unlesbare oder ungültige Vorgaben blockieren die Erstellung mit einer Fehlermeldung zur Korrektur oder zum Neuladen. Wiederholungen behalten die ursprünglich gespeicherte Auswahl auch bei geänderten Vorgaben bei. - ## Gespeicherten Auftrag wiederverwenden {#saved-briefs} 1. Öffnen Sie beim Erstellen **Optionen → Mit einem gespeicherten Auftrag beginnen** und wählen Sie den Auftrag. diff --git a/docs/help/es/missions.md b/docs/help/es/missions.md index 107fcc6ee1..2909146258 100644 --- a/docs/help/es/missions.md +++ b/docs/help/es/missions.md @@ -18,10 +18,10 @@ Las Misiones combinan un plan de proyecto duradero con conversaciones nativas de **Crear guarda una Misión en pausa.** Solo ▶ **Iniciar** activa el trabajo y los calendarios nativos. La creación pertenece al proyecto/Location seleccionado y registra los perfiles solicitados y la política de sesiones de tareas. La validación aparece junto al campo afectado; un rechazo que indique que no se envió nada conserva el borrador para corregirlo. Un coordinador puntual también puede preparar un seguimiento independiente: aparece como **Preparada** y se inicia desde su propia acción ▶. -Las misiones puntuales guardadas conservan sus controles de ejecución, árbol de tareas, conversaciones e informes finales. Las programaciones diarias existentes siguen en la lista con sus controles diarios y sus [reglas horarias diarias](#existing-daily-schedules). Selecciona la entrada y usa los controles disponibles para ese objeto. - Los seguimientos preparados por un agente usan tus [valores para nuevas misiones](#profiles) guardados para los perfiles y las sesiones de tareas omitidos. Fuera de una misión activa, usa **Crear misión** en el panel Misiones. +Las misiones puntuales guardadas conservan sus controles de ejecución, árbol de tareas, conversaciones e informes finales. Las programaciones diarias existentes siguen en la lista con sus controles diarios y sus [reglas horarias diarias](#existing-daily-schedules). Selecciona la entrada y usa los controles disponibles para ese objeto. + ### Guiones {#playbooks} El selector **Guion** muestra justo debajo una descripción de una frase del guion seleccionado. **Ver detalles** abre el guion seleccionado en el lector central: sus pasos, sus roles y, plegadas al final, las instrucciones exactas en inglés que reciben sus agentes. [Guiones](playbooks.md) explica los pasos, roles y preguntas de cada guion, y lo que CodeNomad comprueba. @@ -137,12 +137,12 @@ 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. +Estos valores también se aplican cuando un agente prepara una misión: cada perfil de coordinador o rol omitido usa la excepción del guion y luego la elección global; el especialista global proporciona los roles de tareas, mientras que el juez de comparación usa por defecto el modelo del coordinador. Un perfil indicado explícitamente tiene prioridad en su totalidad, incluidos los valores de OpenCode o una elección de solo agente. Para el juez, cualquier modelo ausente se completa después con el modelo conocido del coordinador, incluso con una elección explícita o guardada de valores de OpenCode o de solo agente; su propio modelo se mantiene. El juez conserva el origen de su perfil explícito o guardado; un perfil de juez omitido hereda el origen del coordinador. **Sesiones de tareas** omitido sigue el mismo orden de preferencias y luego **Subagentes nativos**. La respuesta de creación al agente enumera los perfiles guardados, el modo de sesiones y el origen de cada elección: explícito, preferencia o valor predeterminado de OpenCode. Las preferencias ilegibles o inválidas bloquean la creación con un error que pide corregirlas o recargarlas. Los reintentos conservan las elecciones guardadas originales aunque cambies los valores predeterminados. + 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. -Estos valores también se aplican cuando un agente prepara una misión: cada perfil de coordinador o rol omitido usa la excepción del guion y luego la elección global; el especialista global proporciona los roles de tareas, mientras que el juez de comparación usa por defecto el modelo del coordinador. Un perfil indicado explícitamente tiene prioridad en su totalidad, incluidos los valores de OpenCode o una elección de solo agente. Para el juez, cualquier modelo ausente se completa después con el modelo conocido del coordinador, incluso con una elección explícita o guardada de valores de OpenCode o de solo agente; su propio modelo se mantiene. El juez conserva el origen de su perfil explícito o guardado; un perfil de juez omitido hereda el origen del coordinador. **Sesiones de tareas** omitido sigue el mismo orden de preferencias y luego **Subagentes nativos**. La respuesta de creación al agente enumera los perfiles guardados, el modo de sesiones y el origen de cada elección: explícito, preferencia o valor predeterminado de OpenCode. Las preferencias ilegibles o inválidas bloquean la creación con un error que pide corregirlas o recargarlas. Los reintentos conservan las elecciones guardadas originales aunque cambies los valores predeterminados. - ## Reutilizar una descripción guardada {#saved-briefs} 1. Durante la creación, expande **Opciones → Empezar desde una descripción** y selecciona la descripción guardada. diff --git a/docs/help/fr/missions.md b/docs/help/fr/missions.md index e5e41905e9..96f731b61b 100644 --- a/docs/help/fr/missions.md +++ b/docs/help/fr/missions.md @@ -18,10 +18,10 @@ Les Missions associent un plan de projet durable aux conversations natives OpenC **Créer enregistre une Mission en pause.** Seule l’action ▶ **Démarrer** arme le travail et les calendriers natifs. La création appartient au projet/à la Location sélectionné et enregistre les profils demandés et la politique des sessions de tâches. La validation apparaît près du champ concerné ; un refus indiquant que rien n’a été envoyé conserve le brouillon pour correction. Un coordinateur ponctuel peut aussi préparer une mission de suite distincte : elle apparaît comme **Préparée** et démarre depuis sa propre action ▶. -Les missions ponctuelles enregistrées conservent leurs commandes d’exécution, leur arbre de tâches, leurs conversations et leurs rapports finaux. Les programmations quotidiennes existantes restent dans la liste avec leurs commandes quotidiennes et leurs [règles horaires quotidiennes](#existing-daily-schedules). Sélectionnez l’entrée et utilisez les commandes disponibles pour cet objet. - Les suites préparées par un agent utilisent vos [défauts des nouvelles missions](#profiles) enregistrés pour les profils et les sessions de tâches omis. Hors d'une mission active, utilisez **Créer une mission** dans le panneau Missions. +Les missions ponctuelles enregistrées conservent leurs commandes d’exécution, leur arbre de tâches, leurs conversations et leurs rapports finaux. Les programmations quotidiennes existantes restent dans la liste avec leurs commandes quotidiennes et leurs [règles horaires quotidiennes](#existing-daily-schedules). Sélectionnez l’entrée et utilisez les commandes disponibles pour cet objet. + ### Scénarios {#playbooks} Le sélecteur **Scénario** affiche juste en dessous une description en une phrase du scénario sélectionné. **Voir les détails** ouvre le scénario sélectionné dans le lecteur central : ses étapes, ses rôles et, repliées à la fin, les instructions exactes en anglais que reçoivent ses agents. [Scénarios](playbooks.md) explique les étapes, les rôles et les questions de chaque scénario, ainsi que ce que CodeNomad vérifie. @@ -137,12 +137,12 @@ 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. +Ces défauts s'appliquent aussi quand un agent prépare une mission : chaque profil de coordinateur ou de rôle omis utilise l'exception du scénario, puis le choix global ; le spécialiste global fournit les rôles de tâches, tandis que le juge de comparaison utilise par défaut le modèle du coordinateur. Un profil explicitement fourni prime en entier, y compris un choix de défauts OpenCode ou un agent seul. Pour le juge, tout modèle manquant est ensuite complété par le modèle connu du coordinateur, même avec un choix explicite ou enregistré de défauts OpenCode ou d'agent seul ; son propre modèle reste inchangé. Le juge conserve l'origine de son profil explicite ou enregistré ; un profil de juge omis hérite de l'origine du coordinateur. **Sessions des tâches** omis suit le même ordre de préférences, puis **Sous-agents natifs**. La réponse de création à l'agent donne les profils enregistrés, le mode des sessions de tâches et l'origine de chaque choix : explicite, préférence ou défaut OpenCode. Des préférences illisibles ou invalides bloquent la création avec une erreur demandant leur correction ou leur rechargement. Les réessais conservent les choix enregistrés à l'origine, même si vous modifiez les défauts. + 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. -Ces défauts s'appliquent aussi quand un agent prépare une mission : chaque profil de coordinateur ou de rôle omis utilise l'exception du scénario, puis le choix global ; le spécialiste global fournit les rôles de tâches, tandis que le juge de comparaison utilise par défaut le modèle du coordinateur. Un profil explicitement fourni prime en entier, y compris un choix de défauts OpenCode ou un agent seul. Pour le juge, tout modèle manquant est ensuite complété par le modèle connu du coordinateur, même avec un choix explicite ou enregistré de défauts OpenCode ou d'agent seul ; son propre modèle reste inchangé. Le juge conserve l'origine de son profil explicite ou enregistré ; un profil de juge omis hérite de l'origine du coordinateur. **Sessions des tâches** omis suit le même ordre de préférences, puis **Sous-agents natifs**. La réponse de création à l'agent donne les profils enregistrés, le mode des sessions de tâches et l'origine de chaque choix : explicite, préférence ou défaut OpenCode. Des préférences illisibles ou invalides bloquent la création avec une erreur demandant leur correction ou leur rechargement. Les réessais conservent les choix enregistrés à l'origine, même si vous modifiez les défauts. - ## Réutiliser une consigne enregistrée {#saved-briefs} 1. À la création, développez **Options → Partir d’une consigne** et sélectionnez la consigne enregistrée. diff --git a/docs/help/he/missions.md b/docs/help/he/missions.md index dc23a9a7c9..fee284a4cc 100644 --- a/docs/help/he/missions.md +++ b/docs/help/he/missions.md @@ -18,10 +18,10 @@ **יצירה שומרת משימה מושהית.** רק פעולת ההפעלה מפעילה עבודה ולוחות זמנים מקוריים. היצירה שייכת לפרויקט/ל־Location שנבחרו ומתעדת את הפרופילים המבוקשים ואת מדיניות שיחות המטלות. האימות מופיע לצד השדה המתאים; סירוב שמציין שלא נשלח דבר שומר את הטיוטה לתיקון. מתאם חד־פעמי יכול גם להכין משימת המשך נפרדת: היא מופיעה כ־**מוכנה** ומתחילה מפעולת ▶ שלה. -משימות חד־פעמיות שמורות שומרות על בקרות ההפעלה, עץ המשימות, השיחות והדוחות הסופיים שלהן. לוחות זמנים יומיים קיימים נשארים ברשימה עם הבקרות היומיות ועם [כללי התזמון היומי](#existing-daily-schedules). בחרו את הרשומה והשתמשו בבקרות הזמינות לאותו אובייקט. - משימות המשך שהכין סוכן משתמשות ב[ברירות המחדל למשימות חדשות](#profiles) השמורות שלכם עבור פרופילים ובחירות של שיחות משימות שהושמטו. מחוץ למשימה פעילה, השתמשו ב־**יצירת משימה** בחלונית המשימות. +משימות חד־פעמיות שמורות שומרות על בקרות ההפעלה, עץ המשימות, השיחות והדוחות הסופיים שלהן. לוחות זמנים יומיים קיימים נשארים ברשימה עם הבקרות היומיות ועם [כללי התזמון היומי](#existing-daily-schedules). בחרו את הרשומה והשתמשו בבקרות הזמינות לאותו אובייקט. + ### מדריכי עבודה {#playbooks} הבורר **מדריך** מציג ישירות מתחתיו תיאור במשפט אחד של המדריך שנבחר. **הצגת פרטים** פותח את המדריך שנבחר בקורא המרכזי: השלבים, התפקידים ובסוף, במצב מקופל, ההנחיות המדויקות באנגלית שהסוכנים שלו מקבלים. [מדריכי עבודה](playbooks.md) מסביר את השלבים, התפקידים והשאלות של כל מדריך, ומה CodeNomad בודק. @@ -137,12 +137,12 @@ **ברירת מחדל מקורית** ו־**גלובלי** שונות: הראשונה מבקשת את ברירות המחדל של OpenCode עצמו, השנייה יורשת את הבחירה הגלובלית; בחירת ברירות מחדל מקוריות בהיקף של מדריך נשארת חריג מפורש. זמינות הקטלוג נבדקת; פרופיל מבוקש אינו הוכחה לפרופיל ששיחה משתמשת בו כרגע. אישורים מקוריים והעומק המוגדר עדיין שולטים בקריאות לעוזרים פנימיים בשני מצבי המטלות. +ברירות המחדל חלות גם כשסוכן מכין משימה: כל פרופיל מתאם או תפקיד שהושמט משתמש בחריג של מדריך העבודה, ואז בבחירה הגלובלית; המומחה הגלובלי מספק את תפקידי המטלות, ושופט ההשוואה משתמש כברירת מחדל במודל של המתאם. פרופיל שסופק במפורש מקבל עדיפות בשלמותו, גם בבחירת ברירות המחדל של OpenCode או סוכן בלבד. אצל השופט, מודל חסר מושלם לאחר מכן מהמודל הידוע של המתאם, גם בבחירה מפורשת או שמורה של ברירות המחדל של OpenCode או של סוכן בלבד; מודל משלו נשאר ללא שינוי. השופט שומר על מקור הפרופיל המפורש או השמור שלו; פרופיל שופט שהושמט יורש את מקור המתאם. **שיחות משימות** שהושמטו משתמשות באותו סדר העדפות ואז ב־**תת־סוכנים מקוריים**. תשובת היצירה לסוכן מפרטת את הפרופילים השמורים, מצב השיחות ומקור כל בחירה: מפורש, העדפה או ברירת מחדל של OpenCode. העדפות פגומות או בלתי קריאות חוסמות יצירה עם שגיאה המבקשת לתקן או לטעון אותן מחדש. ניסיונות חוזרים שומרים על הבחירות המקוריות גם אם תשנו את ברירות המחדל. + כל רשימת **מודל** מציגה את מה שמציג בורר **מודל** של השיחה, באותם שמות ומקובצת לפי ספק: מודלים מוסתרים אינם מופיעים, ובזמן שסינון למועדפים בלבד פעיל גם שאר המודלים אינם מופיעים (ראו [נראות מודלים, מועדפים וחשיבה](providers.md#models)). גם מודלים ללא תמיכה בכלים אינם מופיעים. מודל שמור שאינו ברשימה נשאר נבחר. **לא זמין** מסמן מודל שמור שהבורר אינו יכול להציע כעת: הוא חסר בקטלוג הנוכחי של הפרויקט, הוצא משימוש או אינו תומך בכלים. בחירה שנדחתה או שלא אושרה לעולם אינה נשלחת שוב: הערכים השמורים מוצגים שוב, ו־**טעינה מחדש** מופיעה רק כשאי אפשר לקרוא אותם. אם שינוי עומק אינו מאושר, הערך שלכם נשמר; השתמשו ב־**רענון עומק הפרויקט** לפני שינוי נוסף. אל תפרשו **עומק OpenCode האפקטיבי אינו ידוע** כאפס או כמושבת. -ברירות המחדל חלות גם כשסוכן מכין משימה: כל פרופיל מתאם או תפקיד שהושמט משתמש בחריג של מדריך העבודה, ואז בבחירה הגלובלית; המומחה הגלובלי מספק את תפקידי המטלות, ושופט ההשוואה משתמש כברירת מחדל במודל של המתאם. פרופיל שסופק במפורש מקבל עדיפות בשלמותו, גם בבחירת ברירות המחדל של OpenCode או סוכן בלבד. אצל השופט, מודל חסר מושלם לאחר מכן מהמודל הידוע של המתאם, גם בבחירה מפורשת או שמורה של ברירות המחדל של OpenCode או של סוכן בלבד; מודל משלו נשאר ללא שינוי. השופט שומר על מקור הפרופיל המפורש או השמור שלו; פרופיל שופט שהושמט יורש את מקור המתאם. **שיחות משימות** שהושמטו משתמשות באותו סדר העדפות ואז ב־**תת־סוכנים מקוריים**. תשובת היצירה לסוכן מפרטת את הפרופילים השמורים, מצב השיחות ומקור כל בחירה: מפורש, העדפה או ברירת מחדל של OpenCode. העדפות פגומות או בלתי קריאות חוסמות יצירה עם שגיאה המבקשת לתקן או לטעון אותן מחדש. ניסיונות חוזרים שומרים על הבחירות המקוריות גם אם תשנו את ברירות המחדל. - ## שימוש חוזר בתקציר שמור {#saved-briefs} 1. ביצירה, הרחיבו **אפשרויות → להתחיל מתקציר** ובחרו את התקציר השמור. diff --git a/docs/help/ja/missions.md b/docs/help/ja/missions.md index 2b9720ba9c..cb24513276 100644 --- a/docs/help/ja/missions.md +++ b/docs/help/ja/missions.md @@ -18,10 +18,10 @@ **作成すると一時停止中のミッションが保存されます。** 作業とネイティブカレンダーを有効にするのは再生操作だけです。作成は選択したプロジェクト/Location に属し、要求されたプロファイルとタスクセッションの方針を記録します。検証結果は該当項目の横に表示され、何も送信されなかったとする拒否では修正用の下書きが残ります。単発のコーディネーターが別のフォローアップを準備することもできます。**準備済み** と表示され、その項目自身の ▶ 操作で開始します。 -保存済みの単発ミッションでは、実行操作、タスクツリー、会話、最終レポートが保持されます。既存の日次スケジュールは、日次の操作と [日次の時刻規則](#existing-daily-schedules) とともに一覧に残ります。項目を選び、その対象で利用できる操作を使用してください。 - エージェントが準備するフォローアップでは、省略されたプロファイルとタスクセッションに、保存済みの[新規ミッションの既定値](#profiles)を使用します。有効なミッションの外では、ミッションパネルの **ミッションを作成** を使用してください。 +保存済みの単発ミッションでは、実行操作、タスクツリー、会話、最終レポートが保持されます。既存の日次スケジュールは、日次の操作と [日次の時刻規則](#existing-daily-schedules) とともに一覧に残ります。項目を選び、その対象で利用できる操作を使用してください。 + ### プレイブック {#playbooks} **プレイブック** セレクターのすぐ下に、選択したプレイブックの 1 文の説明が表示されます。**詳細を表示** を選ぶと、選択したプレイブックが中央のリーダーに開き、手順、役割、そして末尾に折りたたまれた、エージェントが受け取る正確な英語の指示が表示されます。[プレイブック](playbooks.md) では、各プレイブックの手順、役割、質問と、CodeNomad が確認することを説明しています。 @@ -137,12 +137,12 @@ CodeNomad の実行中は、ミッションのコーディネーターやタス **ネイティブの既定値** と **グローバル** は異なります。前者は OpenCode 自身の既定値を要求し、後者はグローバルの選択を継承します。プレイブックの範囲でネイティブの既定値を選ぶことは、引き続き明示的な例外になります。カタログ上の利用可否を確認しますが、要求したプロファイルは、会話が現在使用するプロファイルの証拠ではありません。どちらのタスクモードでも、内部ヘルパーの呼び出しにはネイティブ権限と設定済みの深さが適用されます。 +エージェントがミッションを準備する場合も、これらの既定値が適用されます。省略されたコーディネーターや役割のプロファイルには、プレイブックの例外、グローバルの選択の順で適用します。タスクの各役割にはグローバルのスペシャリストを使用し、比較の審査役には既定でコーディネーターのモデルを使用します。明示されたプロファイルは全体として優先され、OpenCode の既定値やエージェントのみの指定も含みます。審査役のモデルが未指定なら、その後で既知のコーディネーターのモデルを補います。明示または保存された OpenCode の既定値やエージェントのみの指定も対象で、審査役独自のモデルはそのまま保持します。審査役は明示または保存されたプロファイルの出所を保持し、審査役のプロファイル自体が省略された場合はコーディネーターの出所を継承します。省略された **タスクセッション** も同じ順で設定を適用し、最後に **ネイティブのサブエージェント** を使用します。エージェントへの作成応答には、保存されたプロファイル、タスクセッションのモード、各選択の出所(明示、設定、OpenCode の既定値)が表示されます。設定が読み取れない、または無効な場合は、修正や再読み込みを求めるエラーで作成を中断します。既定値を変更しても、再試行では元の保存済みの選択を保持します。 + 各 **モデル** リストには、会話の **モデル** セレクターと同じモデルが同じ名前でプロバイダーごとに表示されます。非表示のモデルは含まれず、お気に入りのみの絞り込みが有効な間はお気に入り以外のモデルも含まれません([モデルの表示、お気に入り、思考](providers.md#models) を参照)。ツールに対応していないモデルも含まれません。リストにない保存済みのモデルは選択されたまま残ります。**利用不可** は、プロジェクトの現在のカタログにない、非推奨である、またはツールに対応していないため、セレクターが現在提供できない保存済みのモデルに付きます。 拒否された選択や未確認の選択が再送されることはありません。保存済みの値が再び表示され、**再読み込み** はそれらを読み取れない場合にだけ表示されます。深さの変更が未確認の場合は入力した値が保持されるので、次の変更の前に **プロジェクトの深さを更新** を使用します。**OpenCode の有効な深さは不明** をゼロや無効と解釈しないでください。 -エージェントがミッションを準備する場合も、これらの既定値が適用されます。省略されたコーディネーターや役割のプロファイルには、プレイブックの例外、グローバルの選択の順で適用します。タスクの各役割にはグローバルのスペシャリストを使用し、比較の審査役には既定でコーディネーターのモデルを使用します。明示されたプロファイルは全体として優先され、OpenCode の既定値やエージェントのみの指定も含みます。審査役のモデルが未指定なら、その後で既知のコーディネーターのモデルを補います。明示または保存された OpenCode の既定値やエージェントのみの指定も対象で、審査役独自のモデルはそのまま保持します。審査役は明示または保存されたプロファイルの出所を保持し、審査役のプロファイル自体が省略された場合はコーディネーターの出所を継承します。省略された **タスクセッション** も同じ順で設定を適用し、最後に **ネイティブのサブエージェント** を使用します。エージェントへの作成応答には、保存されたプロファイル、タスクセッションのモード、各選択の出所(明示、設定、OpenCode の既定値)が表示されます。設定が読み取れない、または無効な場合は、修正や再読み込みを求めるエラーで作成を中断します。既定値を変更しても、再試行では元の保存済みの選択を保持します。 - ## 保存済みの概要を再利用する {#saved-briefs} 1. 作成画面で **オプション → 保存済みの概要から始める** を展開し、保存済みの概要を選びます。 diff --git a/docs/help/ne/missions.md b/docs/help/ne/missions.md index 9deab99d27..55698163f4 100644 --- a/docs/help/ne/missions.md +++ b/docs/help/ne/missions.md @@ -18,10 +18,10 @@ **सिर्जनाले विराममा रहेको मिसन बचत गर्छ।** चलाउने कार्यले मात्र काम र मूल पात्रो सक्रिय गर्छ। सिर्जना चयनित परियोजना/Location सँग सम्बन्धित हुन्छ र अनुरोध गरिएका प्रोफाइल तथा कार्य-सत्र नीति अभिलेख गर्छ। प्रमाणीकरण सम्बन्धित क्षेत्रछेउ देखिन्छ; केही पठाइएन भन्ने अस्वीकृतिले सुधारका लागि मस्यौदा राख्छ। एकपटकको समन्वयकर्ताले छुट्टै अनुवर्ती मिसन पनि तयार गर्न सक्छ: त्यो **तयार** का रूपमा देखिन्छ र आफ्नै ▶ कार्यबाट सुरु हुन्छ। -सुरक्षित गरिएका एकपटकका मिशनहरूले कार्यान्वयन नियन्त्रण, कार्य वृक्ष, कुराकानी र अन्तिम प्रतिवेदन कायम राख्छन्। विद्यमान दैनिक तालिकाहरू दैनिक नियन्त्रण र [दैनिक समयका नियम](#existing-daily-schedules) सहित सूचीमा रहन्छन्। प्रविष्टि छानेर त्यस वस्तुमा उपलब्ध नियन्त्रण प्रयोग गर्नुहोस्। - एजेन्टले तयार गरेका अनुवर्ती मिसनमा छुटाइएका प्रोफाइल र कार्य सत्रका विकल्पका लागि तपाईंका सुरक्षित [नयाँ मिसनका पूर्वनिर्धारित मान](#profiles) प्रयोग हुन्छन्। सक्रिय मिसनबाहिर मिसन प्यानलको **मिसन सिर्जना गर्नुहोस्** प्रयोग गर्नुहोस्। +सुरक्षित गरिएका एकपटकका मिशनहरूले कार्यान्वयन नियन्त्रण, कार्य वृक्ष, कुराकानी र अन्तिम प्रतिवेदन कायम राख्छन्। विद्यमान दैनिक तालिकाहरू दैनिक नियन्त्रण र [दैनिक समयका नियम](#existing-daily-schedules) सहित सूचीमा रहन्छन्। प्रविष्टि छानेर त्यस वस्तुमा उपलब्ध नियन्त्रण प्रयोग गर्नुहोस्। + ### प्लेबुक {#playbooks} **प्लेबुक** selector को ठीक तल चयन गरिएको प्लेबुकको एक वाक्यको विवरण देखिन्छ। **विवरण हेर्नुहोस्** ले चयन गरिएको प्लेबुक केन्द्रीय reader मा खोल्छ: यसका चरण, भूमिका र अन्त्यमा फोल्ड गरिएका, यसका एजेन्टहरूले पाउने ठ्याक्कै अङ्ग्रेजी निर्देशन। [प्लेबुक](playbooks.md) ले प्रत्येक प्लेबुकका चरण, भूमिका र प्रश्न, र CodeNomad ले के जाँच्छ भनी व्याख्या गर्छ। @@ -137,12 +137,12 @@ CodeNomad चलिरहँदा, project का हरेक agent कुर **नेटिभ पूर्वनिर्धारित** र **विश्वव्यापी** फरक हुन्: पहिलोले OpenCode का आफ्नै default माग्छ, दोस्रोले global चयन inherit गर्छ; playbook दायरामा native default रोज्नु स्पष्ट exception नै रहन्छ। catalogue उपलब्धता जाँचिन्छ; requested profile कुराकानीले अहिले प्रयोग गरिरहेको profile को प्रमाण होइन। दुवै task mode का internal helper मा native permission र configured depth लागू रहन्छन्। +एजेन्टले मिसन तयार गर्दा पनि यी पूर्वनिर्धारित मान लागू हुन्छन्: छुटाइएको समन्वयकर्ता वा भूमिकाको प्रोफाइलमा पहिले प्लेबुकको अपवाद, त्यसपछि विश्वव्यापी चयन प्रयोग हुन्छ। कार्य भूमिकामा विश्वव्यापी विशेषज्ञ प्रयोग हुन्छ; तुलना गर्ने निर्णायकले पूर्वनिर्धारित रूपमा समन्वयकर्ताको मोडेल प्रयोग गर्छ। स्पष्ट रूपमा दिइएको प्रोफाइलले पूर्ण रूपमा प्राथमिकता पाउँछ, OpenCode का पूर्वनिर्धारित मान वा एजेन्ट मात्र रोजेको अवस्थामा पनि। निर्णायकको मोडेल छुटेको भए त्यसपछि समन्वयकर्ताको ज्ञात मोडेलबाट पूरा गरिन्छ, स्पष्ट वा सुरक्षित OpenCode पूर्वनिर्धारित मान वा एजेन्ट मात्रको चयनमा पनि; निर्णायकको आफ्नै मोडेल यथावत् रहन्छ। निर्णायकले आफ्नो स्पष्ट वा सुरक्षित प्रोफाइलको स्रोत कायम राख्छ; निर्णायकको प्रोफाइल नै छुटेको भए समन्वयकर्ताको स्रोत लिन्छ। छुटाइएको **कार्य सत्रहरू** मा उही प्राथमिकता क्रमपछि **नेटिभ उपएजेन्टहरू** प्रयोग हुन्छ। एजेन्टलाई फर्काइएको सिर्जना जवाफमा सुरक्षित प्रोफाइल, कार्य सत्रको मोड र हरेक चयनको स्रोत हुन्छ: स्पष्ट, प्राथमिकता वा OpenCode को पूर्वनिर्धारित मान। पढ्न नसकिने वा अमान्य प्राथमिकताले सुधार वा पुनः लोड गर्नुपर्ने त्रुटिसहित सिर्जना रोक्छन्। पूर्वनिर्धारित मान बदले पनि पुनःप्रयासले सुरुका सुरक्षित चयन कायम राख्छ। + प्रत्येक **मोडेल** सूचीले कुराकानीको **मोडेल** selector ले देखाउने मोडेलहरू उही नाममा, provider अनुसार समूहबद्ध गरी देखाउँछ: लुकाइएका मोडेलहरू समावेश हुँदैनन्, र favorites-only filtering सक्रिय रहँदा अन्य मोडेलहरू पनि समावेश हुँदैनन् ([मोडेल दृश्यता, मनपर्ने र Thinking](providers.md#models) हेर्नुहोस्)। tool support नभएका मोडेलहरू पनि समावेश हुँदैनन्। सूचीबाहिरको saved मोडेल चयन गरिएकै रहन्छ। selector ले अहिले दिन नसक्ने saved मोडेललाई **उपलब्ध छैन** ले चिन्ह लगाउँछ: त्यो project को हालको catalogue मा छैन, deprecated छ, वा tool support छैन। अस्वीकृत वा अपुष्ट चयन कहिल्यै फेरि पठाइँदैन: सुरक्षित मान फेरि देखाइन्छन्, र ती पढ्न नसकिँदा मात्र **पुनः लोड** देखिन्छ। depth परिवर्तन अपुष्ट भए तपाईंको मान राखिन्छ; अर्को परिवर्तनअघि **परियोजनाको गहिराइ ताजा गर्नुहोस्** प्रयोग गर्नुहोस्। **OpenCode को प्रभावकारी गहिराइ अज्ञात** लाई शून्य वा disabled नमान्नुहोस्। -एजेन्टले मिसन तयार गर्दा पनि यी पूर्वनिर्धारित मान लागू हुन्छन्: छुटाइएको समन्वयकर्ता वा भूमिकाको प्रोफाइलमा पहिले प्लेबुकको अपवाद, त्यसपछि विश्वव्यापी चयन प्रयोग हुन्छ। कार्य भूमिकामा विश्वव्यापी विशेषज्ञ प्रयोग हुन्छ; तुलना गर्ने निर्णायकले पूर्वनिर्धारित रूपमा समन्वयकर्ताको मोडेल प्रयोग गर्छ। स्पष्ट रूपमा दिइएको प्रोफाइलले पूर्ण रूपमा प्राथमिकता पाउँछ, OpenCode का पूर्वनिर्धारित मान वा एजेन्ट मात्र रोजेको अवस्थामा पनि। निर्णायकको मोडेल छुटेको भए त्यसपछि समन्वयकर्ताको ज्ञात मोडेलबाट पूरा गरिन्छ, स्पष्ट वा सुरक्षित OpenCode पूर्वनिर्धारित मान वा एजेन्ट मात्रको चयनमा पनि; निर्णायकको आफ्नै मोडेल यथावत् रहन्छ। निर्णायकले आफ्नो स्पष्ट वा सुरक्षित प्रोफाइलको स्रोत कायम राख्छ; निर्णायकको प्रोफाइल नै छुटेको भए समन्वयकर्ताको स्रोत लिन्छ। छुटाइएको **कार्य सत्रहरू** मा उही प्राथमिकता क्रमपछि **नेटिभ उपएजेन्टहरू** प्रयोग हुन्छ। एजेन्टलाई फर्काइएको सिर्जना जवाफमा सुरक्षित प्रोफाइल, कार्य सत्रको मोड र हरेक चयनको स्रोत हुन्छ: स्पष्ट, प्राथमिकता वा OpenCode को पूर्वनिर्धारित मान। पढ्न नसकिने वा अमान्य प्राथमिकताले सुधार वा पुनः लोड गर्नुपर्ने त्रुटिसहित सिर्जना रोक्छन्। पूर्वनिर्धारित मान बदले पनि पुनःप्रयासले सुरुका सुरक्षित चयन कायम राख्छ। - ## सुरक्षित brief पुनःप्रयोग {#saved-briefs} 1. सिर्जनामा **विकल्पहरू → सुरक्षित विवरणबाट सुरु गर्नुहोस्** विस्तार गरी brief चयन गर्नुहोस्। diff --git a/docs/help/ru/missions.md b/docs/help/ru/missions.md index 4265071aec..2628c2587e 100644 --- a/docs/help/ru/missions.md +++ b/docs/help/ru/missions.md @@ -18,10 +18,10 @@ **Создание сохраняет приостановленную Миссию.** Работа и нативные календари активируются только кнопкой запуска. Создание относится к выбранному проекту/Location и записывает запрошенные профили и политику сессий задач. Проверка отображается рядом с соответствующим полем; отказ с указанием, что ничего не отправлено, сохраняет черновик для исправления. Координатор разовой миссии также может подготовить отдельное продолжение: оно появляется как **Подготовлена** и запускается собственным действием ▶. -Сохранённые разовые миссии сохраняют управление выполнением, дерево задач, разговоры и итоговые отчёты. Существующие ежедневные расписания остаются в списке со своими ежедневными элементами управления и [правилами ежедневного времени](#existing-daily-schedules). Выберите запись и используйте доступные для этого объекта элементы управления. - Подготовленные агентом продолжения используют сохранённые [настройки новых миссий](#profiles) для пропущенных профилей и выбора сессий задач. Вне активной миссии используйте **Создать миссию** на панели миссий. +Сохранённые разовые миссии сохраняют управление выполнением, дерево задач, разговоры и итоговые отчёты. Существующие ежедневные расписания остаются в списке со своими ежедневными элементами управления и [правилами ежедневного времени](#existing-daily-schedules). Выберите запись и используйте доступные для этого объекта элементы управления. + ### Сценарии {#playbooks} Сразу под списком **Сценарий** показано описание выбранного сценария в одном предложении. **Подробнее** открывает выбранный сценарий в центральном просмотре: его шаги, роли и, свёрнутые в конце, точные инструкции на английском, которые получают его агенты. Страница [Сценарии](playbooks.md) объясняет шаги, роли и вопросы каждого сценария, а также то, что проверяет CodeNomad. @@ -137,12 +137,12 @@ **Нативное значение по умолчанию** и **Глобально** различаются: первое запрашивает собственные значения OpenCode, второе наследует глобальный выбор; выбор нативных значений в области сценария остаётся явным исключением. Доступность каталога проверяется; запрошенный профиль не доказывает текущий профиль разговора. Нативные разрешения и настроенная глубина по-прежнему управляют внутренними вызовами помощников в обоих режимах задач. +Эти настройки действуют и при подготовке миссии агентом: каждый пропущенный профиль координатора или роли использует исключение сценария, затем глобальный выбор; глобальный специалист задаёт профили ролей задач, а судья сравнения по умолчанию использует модель координатора. Явно указанный профиль имеет приоритет целиком, включая выбор значений OpenCode или только агента. Затем отсутствующая модель судьи дополняется известной моделью координатора, даже при явном или сохранённом выборе значений OpenCode или только агента; собственная модель судьи остаётся неизменной. Судья сохраняет источник своего явного или сохранённого профиля; если профиль судьи пропущен, он наследует источник координатора. Пропущенные **Сессии задач** следуют тому же порядку настроек, затем используют **Нативные субагенты**. Ответ агенту при создании содержит сохранённые профили, режим сессий задач и источник каждого выбора: явный, настройка или значение OpenCode по умолчанию. Нечитаемые или недопустимые настройки блокируют создание с ошибкой, предлагающей исправить или перезагрузить их. Повторные попытки сохраняют исходный выбор даже после изменения настроек по умолчанию. + Каждый список **Модель** показывает то же, что переключатель **Модель** разговора, под теми же названиями и с группировкой по провайдерам: скрытые модели не показываются, а пока включена фильтрация только по избранному — и остальные модели (см. [Видимость моделей, избранное и мышление](providers.md#models)). Модели без поддержки инструментов тоже не показываются. Сохранённая модель вне списка остаётся выбранной. **Недоступно** отмечает сохранённую модель, которую переключатель сейчас не может предложить: её нет в текущем каталоге проекта, она устарела или не поддерживает инструменты. Отклонённый или неподтверждённый выбор никогда не отправляется повторно: снова показываются сохранённые значения, а **Обновить** появляется, только если их не удаётся прочитать. Если изменение глубины не подтверждено, ваше значение сохраняется; используйте **Обновить глубину проекта** перед новым изменением. Не трактуйте **Действующая глубина OpenCode неизвестна** как ноль или отключение. -Эти настройки действуют и при подготовке миссии агентом: каждый пропущенный профиль координатора или роли использует исключение сценария, затем глобальный выбор; глобальный специалист задаёт профили ролей задач, а судья сравнения по умолчанию использует модель координатора. Явно указанный профиль имеет приоритет целиком, включая выбор значений OpenCode или только агента. Затем отсутствующая модель судьи дополняется известной моделью координатора, даже при явном или сохранённом выборе значений OpenCode или только агента; собственная модель судьи остаётся неизменной. Судья сохраняет источник своего явного или сохранённого профиля; если профиль судьи пропущен, он наследует источник координатора. Пропущенные **Сессии задач** следуют тому же порядку настроек, затем используют **Нативные субагенты**. Ответ агенту при создании содержит сохранённые профили, режим сессий задач и источник каждого выбора: явный, настройка или значение OpenCode по умолчанию. Нечитаемые или недопустимые настройки блокируют создание с ошибкой, предлагающей исправить или перезагрузить их. Повторные попытки сохраняют исходный выбор даже после изменения настроек по умолчанию. - ## Повторное использование описания {#saved-briefs} 1. При создании раскройте **Параметры → Начать с сохранённого описания** и выберите описание. diff --git a/docs/help/tr/missions.md b/docs/help/tr/missions.md index 33246666fd..b68c2aa8e7 100644 --- a/docs/help/tr/missions.md +++ b/docs/help/tr/missions.md @@ -18,10 +18,10 @@ Görevler, kalıcı bir proje planını OpenCode'un kendi konuşmalarıyla birle **Oluştur, duraklatılmış bir Görev kaydeder.** İş ve yerel takvimler yalnızca başlatma eylemiyle etkinleştirilir. Oluşturma seçili proje/Location kapsamındadır ve istenen profillerle görev oturumu ilkesini kaydeder. Doğrulama ilgili alanın yanında görünür; hiçbir şey gönderilmediğini belirten bir ret, taslağı düzeltme için korur. Tek seferlik koordinatör ayrı bir devam görevi de hazırlayabilir: **Hazır** olarak görünür ve kendi ▶ eylemiyle başlar. -Kayıtlı tek seferlik görevler yürütme kontrollerini, görev ağacını, konuşmalarını ve nihai raporlarını korur. Mevcut günlük zamanlamalar günlük kontrolleri ve [günlük zamanlama kurallarıyla](#existing-daily-schedules) listede kalır. Kaydı seçip o nesne için sunulan kontrolleri kullanın. - Bir ajanın hazırladığı devam görevleri, belirtilmeyen profiller ve görev oturumu seçimleri için kayıtlı [yeni görev varsayılanlarınızı](#profiles) kullanır. Etkin bir görevin dışında, Görevler panelindeki **Görev oluştur** eylemini kullanın. +Kayıtlı tek seferlik görevler yürütme kontrollerini, görev ağacını, konuşmalarını ve nihai raporlarını korur. Mevcut günlük zamanlamalar günlük kontrolleri ve [günlük zamanlama kurallarıyla](#existing-daily-schedules) listede kalır. Kaydı seçip o nesne için sunulan kontrolleri kullanın. + ### İş akışı rehberleri {#playbooks} **Rehber** seçicisinin hemen altında seçili rehberin tek cümlelik açıklaması gösterilir. **Ayrıntıları gör**, seçili rehberi merkezi okuyucuda açar: adımlarını, rollerini ve sonda katlanmış olarak, ajanlarının aldığı tam İngilizce talimatları. [İş akışı rehberleri](playbooks.md) her rehberin adımlarını, rollerini ve sorularını ve CodeNomad'in neleri denetlediğini açıklar. @@ -137,12 +137,12 @@ 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. +Bir ajan görev hazırlarken de bu varsayılanlar uygulanır: belirtilmeyen her koordinatör veya rol profili önce rehber istisnasını, ardından genel seçimi kullanır; genel uzman görev rollerini sağlar, karşılaştırma hakemi ise varsayılan olarak koordinatörün modelini kullanır. Açıkça verilen profil, OpenCode varsayılanı veya yalnızca ajan seçimi dahil, bütünüyle önceliklidir. Hakemin eksik modeli daha sonra koordinatörün bilinen modeliyle tamamlanır; açık veya kayıtlı OpenCode varsayılanı ya da yalnızca ajan seçimi de buna dahildir, hakemin kendi modeli ise korunur. Hakem açık veya kayıtlı profilinin kaynağını korur; hakem profili belirtilmemişse koordinatörün kaynağını devralır. Belirtilmeyen **Görev oturumları** aynı tercih sırasını, ardından **Yerel alt ajanlar** seçimini kullanır. Ajana dönen oluşturma yanıtı kayıtlı profilleri, görev oturumu modunu ve her seçimin kaynağını listeler: açık seçim, tercih veya OpenCode varsayılanı. Okunamayan veya geçersiz tercihler, düzeltme ya da yeniden yükleme isteyen bir hatayla oluşturmayı engeller. Varsayılanları değiştirseniz bile yeniden denemeler ilk kaydedilen seçimleri korur. + 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. -Bir ajan görev hazırlarken de bu varsayılanlar uygulanır: belirtilmeyen her koordinatör veya rol profili önce rehber istisnasını, ardından genel seçimi kullanır; genel uzman görev rollerini sağlar, karşılaştırma hakemi ise varsayılan olarak koordinatörün modelini kullanır. Açıkça verilen profil, OpenCode varsayılanı veya yalnızca ajan seçimi dahil, bütünüyle önceliklidir. Hakemin eksik modeli daha sonra koordinatörün bilinen modeliyle tamamlanır; açık veya kayıtlı OpenCode varsayılanı ya da yalnızca ajan seçimi de buna dahildir, hakemin kendi modeli ise korunur. Hakem açık veya kayıtlı profilinin kaynağını korur; hakem profili belirtilmemişse koordinatörün kaynağını devralır. Belirtilmeyen **Görev oturumları** aynı tercih sırasını, ardından **Yerel alt ajanlar** seçimini kullanır. Ajana dönen oluşturma yanıtı kayıtlı profilleri, görev oturumu modunu ve her seçimin kaynağını listeler: açık seçim, tercih veya OpenCode varsayılanı. Okunamayan veya geçersiz tercihler, düzeltme ya da yeniden yükleme isteyen bir hatayla oluşturmayı engeller. Varsayılanları değiştirseniz bile yeniden denemeler ilk kaydedilen seçimleri korur. - ## Kayıtlı bir özeti yeniden kullanın {#saved-briefs} 1. Oluşturma ekranında **Seçenekler → Kayıtlı bir özetle başla** bölümünü genişletip kayıtlı özeti seçin. diff --git a/docs/help/zh-Hans/missions.md b/docs/help/zh-Hans/missions.md index e68168c09b..a07de5bb8f 100644 --- a/docs/help/zh-Hans/missions.md +++ b/docs/help/zh-Hans/missions.md @@ -18,10 +18,10 @@ **创建会保存已暂停的任务。**只有点击播放才会启动工作或启用原生日历。创建属于所选项目/Location,并记录请求的配置和任务会话策略。验证信息显示在相应字段旁;若拒绝信息说明未发送任何内容,草稿会保留供修改。一次性任务的协调者也可以准备单独的后续任务:它显示为**已准备**,通过自己的 ▶ 操作启动。 -已保存的一次性任务保留执行控制、任务树、对话和最终报告。现有每日日程仍列出其每日控制,并遵循[每日时间规则](#existing-daily-schedules)。请选择条目并使用该对象可用的控件。 - 智能体准备的后续任务会将已保存的[新任务默认设置](#profiles)应用于省略的配置和任务会话选项。在活动任务之外,请使用任务面板中的**创建任务**。 +已保存的一次性任务保留执行控制、任务树、对话和最终报告。现有每日日程仍列出其每日控制,并遵循[每日时间规则](#existing-daily-schedules)。请选择条目并使用该对象可用的控件。 + ### 剧本 {#playbooks} **剧本**选择器正下方会显示所选剧本的一句话说明。**查看详情**会在中央阅读器中打开所选剧本:其步骤、角色,以及折叠在末尾的、其代理收到的确切英文指令。[剧本](playbooks.md)说明每个剧本的步骤、角色和提问,以及 CodeNomad 检查的内容。 @@ -137,12 +137,12 @@ CodeNomad 运行期间,项目中的每个智能体对话(包括任务协调 **原生默认值**与**全局**不同:前者请求 OpenCode 自身的默认值,后者继承全局选择;在剧本范围中选择原生默认值仍是显式例外。会检查目录可用性;请求的配置不证明对话当前实际使用的配置。两种任务模式下,内部辅助调用仍受原生权限和配置深度约束。 +智能体准备任务时也会应用这些默认设置:省略的协调者或角色配置先使用剧本例外,再使用全局选择;全局专家配置用于任务角色,比较裁判默认使用协调者的模型。显式提供的配置作为整体优先,包括选择 OpenCode 默认值或仅指定代理的情况。随后,裁判缺失的模型会用协调者已知的模型补全,即使显式或已保存的选择为 OpenCode 默认值或仅指定代理;裁判自身已指定的模型保持不变。裁判保留其显式或已保存配置的来源;裁判配置整体省略时,继承协调者的来源。省略的**任务会话**采用相同的偏好顺序,最后使用**原生子代理**。返回给智能体的创建响应列出已保存的配置、任务会话模式及每项选择的来源:显式指定、偏好或 OpenCode 默认值。偏好无法读取或无效时,创建会被阻止,并返回要求修正或重新加载的错误。即使修改默认设置,重试也会保留最初保存的选择。 + 每个**模型**列表显示的内容与对话的**模型**选择器相同,名称一致并按提供商分组:不包含已隐藏的模型;启用仅收藏筛选时,也不包含其他模型(参见[模型可见性、收藏和思考](providers.md#models))。不支持工具的模型同样不包含。列表之外的已保存模型仍保持选中。选择器当前无法提供的已保存模型标记为**不可用**:它不在项目当前的目录中、已弃用或不支持工具。 被拒绝或未确认的选择绝不会重新发送:会重新显示已存储的值,只有在无法读取这些值时才会出现**重新加载**。如果深度更改未确认,你的值会保留;请先使用**刷新项目深度**,再进行其他更改。不要将 **OpenCode 有效深度未知**解释为零或禁用。 -智能体准备任务时也会应用这些默认设置:省略的协调者或角色配置先使用剧本例外,再使用全局选择;全局专家配置用于任务角色,比较裁判默认使用协调者的模型。显式提供的配置作为整体优先,包括选择 OpenCode 默认值或仅指定代理的情况。随后,裁判缺失的模型会用协调者已知的模型补全,即使显式或已保存的选择为 OpenCode 默认值或仅指定代理;裁判自身已指定的模型保持不变。裁判保留其显式或已保存配置的来源;裁判配置整体省略时,继承协调者的来源。省略的**任务会话**采用相同的偏好顺序,最后使用**原生子代理**。返回给智能体的创建响应列出已保存的配置、任务会话模式及每项选择的来源:显式指定、偏好或 OpenCode 默认值。偏好无法读取或无效时,创建会被阻止,并返回要求修正或重新加载的错误。即使修改默认设置,重试也会保留最初保存的选择。 - ## 复用已保存简述 {#saved-briefs} 1. 创建时展开**选项 → 从已保存的简述开始**,选择已保存简述。 diff --git a/packages/server/src/missions/control-types.ts b/packages/server/src/missions/control-types.ts index b87f830daf..7adf06da15 100644 --- a/packages/server/src/missions/control-types.ts +++ b/packages/server/src/missions/control-types.ts @@ -5,7 +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, MissionCreationDefaults, MissionCreationSelection } from "./creation-defaults" +import type { MissionCreationChoices, MissionCreationMetadata } from "./creation-defaults" +import type { MissionCreationSelection } from "./profile-defaults" export interface NativeMissionSession extends MissionExecution { id: string @@ -138,7 +139,7 @@ export interface MissionInspection { export interface MissionCreateInput extends MissionStartInput { /** Original agent request and frozen preference provenance, supplied by the owning backend. */ - creationDefaults?: MissionCreationDefaults + creationDefaults?: MissionCreationMetadata /** Optional short label (1–60 characters, trimmed). */ title?: string prepared?: boolean @@ -202,7 +203,7 @@ 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?: MissionCreationDefaults + 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 d3bf1b6ba7..6bf1078437 100644 --- a/packages/server/src/missions/control.ts +++ b/packages/server/src/missions/control.ts @@ -8,7 +8,7 @@ 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 MissionCreationDefaults } from "./creation-defaults" +import { missionCreationChoices, sameMissionCreationChoices, parseMissionCreationSelection, missionCreationSelection, type MissionCreationMetadata } from "./creation-defaults" import { MissionCreationIntents } from "./creation-intent" import type { MissionTaskPageResult, MissionTaskRequest } from "./mission-panel-map" import { missionPanelPage, missionPanelWindow, type MissionPanelPageRequest, type MissionPanelPageResult } from "./mission-panel-page" @@ -120,7 +120,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) + this.creationIntents = new MissionCreationIntents(options.storage, this.journal.projectToken, options.now) } async snapshot(): Promise { @@ -415,19 +415,14 @@ export class MissionControl { } private async resolveCreationInput(sessionID: string, input: T, missionID: string, conflict = "request-conflict", - coordinatorModel?: NativeMissionSession["model"], retainedIntent?: () => void): Promise { - const retained = await this.creationIntents.read(missionID, input, () => this.journal.event(missionID, this.eventID(missionID, "created")), conflict) - if (retained) { - retainedIntent?.() - return { ...input, profiles: retained.profiles, taskMode: retained.taskMode, creationDefaults: retained } - } + coordinatorModel?: NativeMissionSession["model"], fromDocument?: () => void): Promise { 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 new MissionControlError("Creation request ID was already used with a different mission", conflict) - retainedIntent?.() + fromDocument?.() return { ...input, profiles: frozen.profiles, taskMode: frozen.taskMode, creationDefaults: frozen } } const resolve = this.options.transport?.resolveCreationDefaults @@ -440,13 +435,19 @@ export class MissionControl { return { ...input, profiles: selection.profiles, taskMode: selection.taskMode, creationDefaults: { request, ...selection } } } - private async retainCreationInput(input: T, missionID: string, conflict = "request-conflict"): Promise { + 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 async createCurrent(input: MissionCreateInput): Promise<{ mission: MissionMap }> { input = structuredClone(input) input.taskMode = parseMissionTaskMode(input.taskMode) @@ -498,19 +499,10 @@ 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") - const proposed = input - input = await this.retainCreationInput(input, missionID) - if (!sameMissionProfiles(proposed.profiles, input.profiles) || proposed.taskMode !== input.taskMode) { - try { await this.options.validateProfiles?.(input.profiles, input.expectedCoordinatorLocation?.directory ?? this.options.project.location.directory, input.taskMode!) } - catch { throw new MissionControlError("Mission profiles do not match the owned native catalog", "invalid-execution") } - if (suppliedCoordinator && !matchesExecution(input.profiles?.coordinator, suppliedCoordinator)) - throw new MissionControlError("Coordinator does not have the requested native profile", "invalid-execution") - } - const reservedAt = this.timestamp(snapshot) const document = this.options.documents ? await prepareMissionOneTimeDocument(this.options.documents, this.options.project, missionID, input, input.coordinatorSessionID ?? missionCoordinatorSessionID(missionID, reservedAt), reservedAt, @@ -546,7 +538,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() @@ -1014,11 +1006,8 @@ export class MissionControl { 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") - } - resolved = await this.retainCreationInput(resolved, missionID) - input.start = { ...resolved, taskMode: parseMissionTaskMode(resolved.taskMode) } + if (!sameLocation(caller.location, fresh.location)) throw new MissionControlError("Coordinator moved from its admitted creation location", "invalid-execution") + if (!matchesExecution(input.start.profiles?.coordinator, fresh)) throw this.coordinatorProfileMismatch(resolved) const event: MissionEvent = { version: MISSION_SCHEMA_VERSION, id: this.eventID(missionID, "created"), @@ -1067,12 +1056,20 @@ 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. 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) 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. @@ -1095,29 +1092,50 @@ export class MissionControl { return { mission: saved } } await this.assertNotPurged(missionID) - let retainedIntent = false - input = await this.resolveCreationInput(sessionID, input, missionID, "prepare-conflict", undefined, () => { retainedIntent = true }) + let retained = await this.creationIntents.read(missionID, input, + () => this.journal.event(missionID, this.eventID(missionID, "created")), "prepare-conflict") + let retainedDocument = false + input = retained ? { ...input, profiles: retained.profiles, taskMode: retained.taskMode, creationDefaults: retained } + : await this.resolveCreationInput(sessionID, input, missionID, "prepare-conflict", undefined, () => { retainedDocument = true }) input = { ...input, profiles: this.compareCreationProfiles(input.template, input.profiles, undefined, !input.creationDefaults) } - 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() - let result: unknown - try { result = await this.options.transport.prepare(sessionID, { ...structuredClone(input), requestID, missionID: source.id }) } - catch (error) { - if (retainedIntent && error instanceof MissionControlError && error.code === "prepare-refused") + // 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 && error.code === "prepare-refused" + if (originalNoEffect || !retained && !retainedDocument && (!dispatched || refused)) { + await this.creationIntents.settled(missionID) + throw error + } throw new MissionControlError("The prepared mission's outcome is uncertain; retry with the same requestID", "prepare-uncertain") - throw error - } - 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 } + } + 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 } + }) } /** Advisory native evidence of a native task's own conversations; never settlement. */ diff --git a/packages/server/src/missions/coordinator-actions.test.ts b/packages/server/src/missions/coordinator-actions.test.ts index cec1de900c..5e438eab9d 100644 --- a/packages/server/src/missions/coordinator-actions.test.ts +++ b/packages/server/src/missions/coordinator-actions.test.ts @@ -1,6 +1,8 @@ import assert from "node:assert/strict" import test from "node:test" 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" @@ -25,6 +27,7 @@ class MemoryStorage implements MissionStorage { const coordinator = "ses_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" } }]]) @@ -41,7 +44,7 @@ function fixture(options: { transport?: Partial; humanGat 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, 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") => @@ -138,7 +141,7 @@ test("a prepare retry after a lost reply returns the saved hand-off without anot 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/) + 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 @@ -158,7 +161,7 @@ test("a prepare retry after a lost reply returns the saved hand-off without anot assert.equal(reads, resolvedReads, "conflicting requests also leave preferences unread") }) -test("a later preparation refusal preserves its original profile intention", async () => { +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: { @@ -176,8 +179,8 @@ test("a later preparation refusal preserves its original profile intention", asy const previousReads = reads worker = "worker-after" const result = await control.prepare(coordinator, request) - assert.equal(reads, previousReads) - assert.deepEqual(result.mission.creationDefaults?.profiles?.roles?.specialist, { agent: "worker-before" }) + 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 () => { @@ -206,7 +209,7 @@ test("inspect start freezes resolved choices and replays them after preference f 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"), /differs from the requested native profile/) + 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: { @@ -250,6 +253,72 @@ test("prepare outside a mission points to the editor without resolving preferenc 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("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 () => { const calls: unknown[] = [] let reply: unknown = { sessions: [{ sessionID: "ses_child", interrupted: true, settled: true, diff --git a/packages/server/src/missions/creation-defaults.test.ts b/packages/server/src/missions/creation-defaults.test.ts index 4082ec1adc..61329919a7 100644 --- a/packages/server/src/missions/creation-defaults.test.ts +++ b/packages/server/src/missions/creation-defaults.test.ts @@ -1,13 +1,13 @@ import assert from "node:assert/strict" import test from "node:test" import Ajv from "ajv" -import { MissionControl } from "./control" +import { MissionControl, MissionControlError } from "./control" import type { MissionInputTransport, NativeMissionSession } from "./control-types" -import { missionCreationSelection, parseMissionCreationDefaults } from "./creation-defaults" +import { missionCreationDefaultsSchema, missionCreationDefaultsWire, missionCreationSelection, parseMissionCreationDefaults } from "./creation-defaults" import type { MissionStorage } from "./journal" import type { MissionJsonValue } from "./model" import { NativeMissionDocumentStore, type MissionDocumentStorage } from "./mission-document-store" -import { resolveMissionCreationDefaults } from "./profile-defaults" +import { MISSION_DEFAULT_ORIGINS, resolveMissionCreationDefaults } from "./profile-defaults" import { CODENOMAD_MISSIONS_RPC } from "./rpc" import { freezeCompareProfiles } from "./playbook-profiles" @@ -16,7 +16,7 @@ function fixture() { const coordinator = "ses_coordinator" const sessions = new Map([[coordinator, { id: coordinator, agent: "lead", projectID: "project", location: { directory: "/repo" } }]]) - let failJournal = false, failDocument = false, reads = 0, created = 0 + 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)), @@ -40,8 +40,10 @@ function fixture() { 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) => control.create({ ...input, prepared: true, - preparedBy: { missionID: input.missionID, coordinatorSessionID: id } }), + 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, @@ -55,6 +57,7 @@ function fixture() { let control = new MissionControl(options) return { get control() { return control }, coordinator, documents, values, sessions, get reads() { return reads }, get created() { return created }, fail: () => { failJournal = true }, failBeforeDocument: () => { failDocument = true }, + refusePreparation: () => { refusePreparation = true }, setPreferences: (value: unknown) => { preferences = value }, invalidate: () => { preferences = null }, restart: () => { control = new MissionControl(options) } } } @@ -122,7 +125,7 @@ test("prepare recovers its frozen document before journal publication without re 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), /Journal write unavailable/) + 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() @@ -139,7 +142,7 @@ test("the pre-dispatch creation intention survives a failure before the first do 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), /Document write unavailable/) + 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() @@ -157,3 +160,51 @@ test("creation provenance validates its exact roles and leaves historical missio assert.throws(() => parseMissionCreationDefaults("custom", { ...metadata, origins: { ...metadata.origins, coordinator: "guessed" } })) assert.equal(missionCreationSelection({ profiles: {}, taskMode: "native" }), undefined) }) + +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)) + } +}) diff --git a/packages/server/src/missions/creation-defaults.ts b/packages/server/src/missions/creation-defaults.ts index bdb4029594..d1c2b5471b 100644 --- a/packages/server/src/missions/creation-defaults.ts +++ b/packages/server/src/missions/creation-defaults.ts @@ -1,17 +1,17 @@ import { z } from "zod" import type { MissionMap, MissionTemplateId } from "./model" -import { missionProfileRoles, missionProfilesInputSchema, missionProfilesSchema, sameMissionProfiles, validateMissionProfiles, type MissionProfiles } from "./playbook-profiles" -import { missionTaskModeInputSchema, missionTaskModeSchema, type MissionTaskMode } from "./task-execution-mode" +import { missionProfileRoles, missionProfilesInputSchema, missionProfilesSchema, sameMissionProfiles, validateMissionProfiles } from "./playbook-profiles" +import { missionTaskModeInputSchema, missionTaskModeSchema } from "./task-execution-mode" +import { MISSION_DEFAULT_ORIGINS, type MissionCreationSelection } from "./profile-defaults" -const origin = z.enum(["explicit", "preference", "opencode-default"]) +const origin = z.enum(MISSION_DEFAULT_ORIGINS) export const missionCreationChoicesSchema = z.object({ profiles: missionProfilesInputSchema, taskMode: missionTaskModeInputSchema.optional() }).strict() const originsSchema = z.object({ coordinator: origin, roles: z.record(z.string(), origin), taskMode: origin }).strict() export const missionCreationDefaultsSchema = z.object({ request: missionCreationChoicesSchema, profiles: missionProfilesInputSchema, taskMode: missionTaskModeInputSchema, origins: originsSchema }).strict() const resolutionSchema = z.object({ profiles: missionProfilesInputSchema, taskMode: missionTaskModeInputSchema, origins: originsSchema }).strict() export type MissionCreationChoices = z.infer -export type MissionCreationDefaults = z.infer -export type MissionCreationSelection = { profiles: MissionProfiles; taskMode: MissionTaskMode; origins: MissionCreationDefaults["origins"] } +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 }) }) @@ -20,13 +20,13 @@ export function sameMissionCreationChoices(left: MissionCreationChoices, right: return left.taskMode === right.taskMode && sameMissionProfiles(left.profiles, right.profiles) } -function validateOrigins(template: MissionTemplateId, origins: MissionCreationDefaults["origins"]) { +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): MissionCreationDefaults { +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 }) @@ -44,10 +44,11 @@ export function parseMissionCreationSelection(template: MissionTemplateId, input /** 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 }) + return structuredClone({ profiles: mission.creationDefaults.profiles as MissionCreationSelection["profiles"], + taskMode: mission.creationDefaults.taskMode, origins: mission.creationDefaults.origins }) } -const originWire = { type: "string", enum: ["explicit", "preference", "opencode-default"] } as const +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 }, diff --git a/packages/server/src/missions/creation-intent.test.ts b/packages/server/src/missions/creation-intent.test.ts index 09dc87aaa0..a04c094168 100644 --- a/packages/server/src/missions/creation-intent.test.ts +++ b/packages/server/src/missions/creation-intent.test.ts @@ -1,23 +1,24 @@ import assert from "node:assert/strict" import test from "node:test" -import { MissionCreationIntents } from "./creation-intent" +import { MissionCreationIntents, 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, limit = 100 }) => { - const rows = [...values].filter(([key]) => key.startsWith(prefix)).sort() + 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") } + 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: [] }) } @@ -62,7 +63,51 @@ test("damaged intent bytes stay intact and refuse before another preference read 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, () => assert.fail("Damaged evidence cannot fall back"), "request-conflict"), + 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 < 128; 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(2) + 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("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("an un-timestamped valid intention gets one bounded retention window", async () => { + const f = fixture() + f.values.set("codenomad-missions/v2/creation-intents/project/msn_old", { version: 1, request, defaults } as unknown as MissionJsonValue) + assert.deepEqual(await f.intents.read("msn_old", request, missing, "request-conflict"), defaults) + f.advance(MISSION_CREATION_INTENT_RETENTION_MS) + assert.equal(await f.intents.read("msn_old", request, missing, "request-conflict"), undefined) +}) + +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 index 88808a58ad..3457c20a8c 100644 --- a/packages/server/src/missions/creation-intent.ts +++ b/packages/server/src/missions/creation-intent.ts @@ -2,7 +2,7 @@ import { z } from "zod" import type { MissionStartInput } from "./control-types" import { MissionControlError } from "./control-error" import { missionCreationChoices, missionCreationChoicesSchema, parseMissionCreationDefaults, sameMissionCreationChoices, - type MissionCreationDefaults } from "./creation-defaults" + type MissionCreationMetadata } from "./creation-defaults" import { runMissionExclusive } from "./exclusive" import type { MissionStorage } from "./journal" import type { MissionEvent, MissionJsonValue } from "./model" @@ -11,19 +11,21 @@ type Request = MissionStartInput & { title?: string } const requestSchema = missionCreationChoicesSchema.extend({ objective: z.string().min(1).max(20_000), title: z.string().min(1).max(60).optional(), notes: z.string().max(20_000).optional(), template: z.enum(["custom", "debug", "wayfinder", "delivery", "compare"]) }).strict() -const intentSchema = z.object({ version: z.literal(1), request: requestSchema, defaults: z.unknown() }).strict() +const intentSchema = z.object({ version: z.literal(1), request: requestSchema, defaults: z.unknown(), + createdAt: z.number().finite().nonnegative().optional() }).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: MissionCreationDefaults): Request => ({ +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), }) -/** Durable, bounded pre-dispatch intentions. A missing document or lost RPC reply - * never permits resolving the same original request against new preferences. */ +/** 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) { + constructor(private readonly storage: MissionStorage, projectToken: string, private readonly now = Date.now) { this.prefix = `codenomad-missions/v2/creation-intents/${projectToken}/` } @@ -31,15 +33,18 @@ export class MissionCreationIntents { throw new MissionControlError("Creation request ID was already used with a different mission", code) } - private async recorded(missionID: string, request: Request, conflict: string): Promise { + private async recorded(missionID: string, request: Request, conflict: string): Promise { const raw = await this.storage.get(this.prefix + missionID) - if (raw === undefined) return undefined - let saved: z.infer, defaults: MissionCreationDefaults + if (raw === undefined || raw === null) return undefined + let saved: z.infer, defaults: MissionCreationMetadata try { saved = intentSchema.parse(raw) defaults = parseMissionCreationDefaults(saved.request.template, saved.defaults) if (!sameMissionCreationChoices(saved.request, defaults.request)) throw new Error("Invalid original choices") } catch { throw new MissionControlError("Mission creation intent is unreadable; existing data is retained", "invalid-journal") } + if (this.expired(saved.createdAt)) { await this.clear(missionID); return undefined } + if (saved.createdAt === undefined) await this.storage.set(this.prefix + missionID, + JSON.parse(JSON.stringify({ ...saved, createdAt: this.now() })) as MissionJsonValue) if (!sameRequest(saved.request, request)) this.conflict(conflict) return defaults } @@ -52,27 +57,75 @@ export class MissionCreationIntents { } async read(missionID: string, request: Request, created: () => Promise, conflict: string) { - // Read the intent before its eventual receipt: publication precedes removal. - return await this.recorded(missionID, request, conflict) ?? this.fromEvent(await created(), request, conflict) + return runMissionExclusive(this.prefix, () => this.readCurrent(missionID, request, created, conflict)) } - save(missionID: string, input: Request, defaults: MissionCreationDefaults, created: () => Promise, - current: () => void, conflict: string): Promise { + 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 createdAt !== undefined && (this.now() - createdAt >= MISSION_CREATION_INTENT_RETENTION_MS || createdAt > this.now()) + } + + 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 + const parsed = intentSchema.safeParse(entry.value) + let valid = parsed.success + if (parsed.success) { + try { + const defaults = parseMissionCreationDefaults(parsed.data.request.template, parsed.data.defaults) + valid = sameMissionCreationChoices(parsed.data.request, defaults.request) + } catch { valid = false } + } + if (!valid) throw new MissionControlError("Mission preparation storage is unreadable; existing data is retained", "invalid-journal") + if (parsed.success && valid && this.expired(parsed.data.createdAt)) await this.clear(entry.key.slice(this.prefix.length)) + else { + if (parsed.success && valid && parsed.data.createdAt === undefined) await this.storage.set(entry.key, + JSON.parse(JSON.stringify({ ...parsed.data, createdAt: this.now() })) as MissionJsonValue) + 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 () => { - const saved = await this.read(missionID, request, created, conflict) + current() + const saved = await this.readCurrent(missionID, request, created, conflict) if (saved) return saved - const pending = await this.storage.scan({ prefix: this.prefix, limit: 129 }) - if (pending.entries.length >= 128 || pending.next) throw new MissionControlError("Unresolved Mission preparations reached their safety limit; resolve existing requests first", "creation-capacity") + if (await this.activeCount() >= MISSION_CREATION_INTENT_LIMIT) throw new MissionControlError("128 Mission preparation choices are retained. Retry the original requestIDs to recover completed preparations, or wait up to 24 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 })) as MissionJsonValue, 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 { - // The durable creation event owns the original receipt. Failed cleanup - // retains redundant evidence and its capacity place. - try { await this.storage.remove?.(this.prefix + missionID) } catch { /* Retain the original intent. */ } + // 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/model.ts b/packages/server/src/missions/model.ts index 8ee787c261..2a423e5e5f 100644 --- a/packages/server/src/missions/model.ts +++ b/packages/server/src/missions/model.ts @@ -178,7 +178,7 @@ export interface MissionPlanChange { } export interface MissionMap { - creationDefaults?: import("./creation-defaults").MissionCreationDefaults + creationDefaults?: import("./creation-defaults").MissionCreationMetadata document?: import("./mission-document-one-time").MissionDocumentSummary version: typeof MISSION_SCHEMA_VERSION id: string @@ -307,7 +307,7 @@ interface MissionEventBase { } export interface MissionCreatedEvent extends MissionEventBase { - creationDefaults?: import("./creation-defaults").MissionCreationDefaults + creationDefaults?: import("./creation-defaults").MissionCreationMetadata type: "mission.created" projectCanonical: string title?: string diff --git a/packages/server/src/missions/profile-defaults.test.ts b/packages/server/src/missions/profile-defaults.test.ts index 6a3777b431..66d4ecaf78 100644 --- a/packages/server/src/missions/profile-defaults.test.ts +++ b/packages/server/src/missions/profile-defaults.test.ts @@ -1,7 +1,7 @@ import assert from "node:assert/strict" import { test } from "node:test" import { missionProfileRoles, type MissionProfiles } from "./playbook-profiles" -import { MissionPreferencesError, resolveMissionCreationDefaults, type MissionProfileDefault } from "./profile-defaults" +import { globalMissionTaskMode, missionTaskModeFor, MissionPreferencesError, resolveMissionCreationDefaults, type MissionProfileDefault } from "./profile-defaults" import type { MissionTemplateId } from "./model" const coordinator = { agent: "coordinator", model: { providerID: "p", id: "coordinator", variant: "high" } } @@ -94,6 +94,22 @@ test("task mode resolves explicit, template, global, then native with the matchi } }) +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 } }) diff --git a/packages/server/src/missions/profile-defaults.ts b/packages/server/src/missions/profile-defaults.ts index 55420fdc94..9f0cefce63 100644 --- a/packages/server/src/missions/profile-defaults.ts +++ b/packages/server/src/missions/profile-defaults.ts @@ -7,6 +7,8 @@ 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 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] @@ -47,11 +49,20 @@ export function validMissionDefaults(value: unknown): boolean { /** Type exception ?? global default ?? native. */ export function missionTaskModeFor(value: readonly MissionProfileDefault[], template: MissionTemplateId): MissionTaskMode { - return value.find(item => item.template === template)?.taskMode ?? globalMissionTaskMode(value) + return resolveTaskMode(value, template).taskMode } export function globalMissionTaskMode(value: readonly MissionProfileDefault[]): MissionTaskMode { - return value.find(item => item.template === "all")?.taskMode ?? "native" + 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. */ @@ -75,8 +86,7 @@ export class MissionPreferencesError extends Error { } } -export type MissionDefaultOrigin = "explicit" | "preference" | "opencode-default" -export interface MissionCreationDefaults { +export interface MissionCreationSelection { profiles: Required taskMode: MissionTaskMode origins: { coordinator: MissionDefaultOrigin; roles: Record; taskMode: MissionDefaultOrigin } @@ -89,7 +99,7 @@ export function resolveMissionCreationDefaults(input: { profiles?: MissionProfiles taskMode?: MissionTaskMode coordinatorModel?: MissionExecution["model"] -}): MissionCreationDefaults { +}): MissionCreationSelection { if (!validMissionDefaults(input.preferences)) throw new MissionPreferencesError() const preferences = normalizeMissionDefaults(input.preferences) const defaults = missionDefaultsFor(preferences, input.template) @@ -110,12 +120,10 @@ export function resolveMissionCreationDefaults(input: { roles[role] = selected.execution origins[role] = selected.origin } - const preferredTaskMode = preferences.find(item => item.template === input.template)?.taskMode - ?? preferences.find(item => item.template === "all")?.taskMode + const taskMode = resolveTaskMode(preferences, input.template, input.taskMode) return structuredClone({ profiles: freezeCompareProfiles(input.template, { coordinator: coordinator.execution, roles }, input.coordinatorModel) as Required, - taskMode: parseMissionTaskMode(input.taskMode === undefined ? preferredTaskMode : input.taskMode), - origins: { coordinator: coordinator.origin, roles: origins, - taskMode: input.taskMode !== undefined ? "explicit" : preferredTaskMode !== undefined ? "preference" : "opencode-default" }, + taskMode: taskMode.taskMode, + origins: { coordinator: coordinator.origin, roles: origins, taskMode: taskMode.origin }, }) } diff --git a/packages/server/src/missions/recovery-error.ts b/packages/server/src/missions/recovery-error.ts index 29ccc8a500..8ae47d40f8 100644 --- a/packages/server/src/missions/recovery-error.ts +++ b/packages/server/src/missions/recovery-error.ts @@ -3,6 +3,7 @@ import { MissionControlError } from "./control-error" // 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 requested profiles, taskMode or playbook before creating a mission" }, "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,6 +11,7 @@ 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" }, diff --git a/packages/server/src/opencode/automation-plugin-profile-defaults.test.ts b/packages/server/src/opencode/automation-plugin-profile-defaults.test.ts index 311b4fac55..655357a8d7 100644 --- a/packages/server/src/opencode/automation-plugin-profile-defaults.test.ts +++ b/packages/server/src/opencode/automation-plugin-profile-defaults.test.ts @@ -58,6 +58,8 @@ test("profile defaults preserve typed refusals through the authenticated bridge && error.code === "mission-preferences-unavailable" && error.message === "Reload or correct the Missions preferences before creating a mission" await assert.rejects(request(), unavailable, "zero owners must expose a preference refusal") + 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") removals.push(await publishAutomationBridge(registration)) @@ -83,5 +85,7 @@ test("profile defaults preserve typed refusals through the authenticated bridge 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") }) diff --git a/packages/server/src/opencode/automation-plugin.ts b/packages/server/src/opencode/automation-plugin.ts index e46b39ba75..b737c241ec 100644 --- a/packages/server/src/opencode/automation-plugin.ts +++ b/packages/server/src/opencode/automation-plugin.ts @@ -548,8 +548,17 @@ export async function sendMissionInput(sessionID: string, kind: "prompt" | "synthetic" | "cleanup" | "lifecycle" | "create-root" | "prepare" | "task-sessions" | "interrupt" | "profile-defaults", input: unknown): Promise { try { // `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") + let targets: DiscoveredBridgeRegistration[] + try { + 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") + } catch (error) { + if (kind === "prepare") { + const refusal = missionRecoveryError("prepare-refused")! + throw new MissionControlError(refusal.message, refusal.code) + } + throw error + } const response = await callBridge(targets[0], { mode: "mission-input", sessionID, command: { kind, input } }, REQUEST_TIMEOUT_MS) if (response.status !== 200) { const recovery = missionRecoveryError(response.body.code) diff --git a/packages/server/src/opencode/missions-plugin.ts b/packages/server/src/opencode/missions-plugin.ts index 29796c5f31..8d4ed66976 100644 --- a/packages/server/src/opencode/missions-plugin.ts +++ b/packages/server/src/opencode/missions-plugin.ts @@ -381,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. Creation fills omitted profile slots and taskMode from the user's Missions preferences (type exception, then global); explicit slots win whole, including {} or agent-only. Compare then fills any missing judge model from the known coordinator model, including explicit/preference {} or agent-only slots; a judge's own model is preserved. A chosen judge slot keeps its origin; an absent slot inherits the coordinator's origin. It returns selection with saved profiles, taskMode and origins (explicit, preference, opencode-default), and refuses unreadable/invalid preferences. The existing coordinator must match the resolved profile. 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. Creation uses Missions preferences for omitted choices and returns selection with saved profiles, taskMode and origins (explicit, preference, opencode-default); unreadable/invalid preferences refuse creation. The existing coordinator must match the resolved profile. 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.", input: inspectSchema, options: { namespace: "mission", codemode: false }, execute: async (input, tool) => { @@ -507,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. Omitted profile slots and taskMode inherit the user's Missions preferences (type exception, then global); explicit slots win whole, including {} or agent-only. Compare then fills any missing judge model from the known coordinator model, including explicit/preference {} or agent-only slots; a judge's own model is preserved. A chosen judge slot keeps its origin; an absent slot inherits the coordinator's origin. Returns selection with saved profiles, taskMode and origins (explicit, preference, opencode-default); unreadable/invalid preferences refuse creation. It never starts; the user presses Play. Reuse the same requestID and original inputs to retry: saved choices stay frozen even if preferences change. Outside an active mission use the Missions editor. 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: what the Mission editor creates. Creation uses Missions preferences for omitted choices and returns selection with saved profiles, taskMode and origins (explicit, preference, opencode-default); unreadable/invalid preferences refuse creation. It never starts; the user presses Play. Reuse the same requestID and original inputs to retry: saved choices stay frozen even if preferences change. Outside an active mission use the Missions editor. Find it later with mission.inspect({ list: true }) and read it with mission.inspect({ missionID }); you cannot control it.", input: prepareSchema, options: { namespace: "mission", codemode: false }, execute: async (input, tool) => { 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 64313e2280..b5d27d00f7 100644 --- a/packages/server/src/server/routes/mission-creation-fence.test.ts +++ b/packages/server/src/server/routes/mission-creation-fence.test.ts @@ -31,7 +31,7 @@ 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, documentCapabilities = true + 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 @@ -85,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)) @@ -129,6 +130,7 @@ async function fixture(useBridge = false, drainTimeout = 2_000) { 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 }, @@ -312,6 +314,21 @@ test("a lost prepare acknowledgement is reported uncertain, never as nothing cre } 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 { 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 fec13fa19b..efaa933896 100644 --- a/packages/server/src/server/routes/mission-creation-pipeline.ts +++ b/packages/server/src/server/routes/mission-creation-pipeline.ts @@ -13,7 +13,7 @@ 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 { MissionCreationDefaults } from "../../missions/creation-defaults" +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(), @@ -40,7 +40,7 @@ export async function prepareMissionCreation(input: { expectedProjectID?: string /** Trusted coordinator hand-off from the authenticated plugin bridge, never HTTP input. */ preparedBy?: { missionID: string; coordinatorSessionID: string } - creationDefaults?: MissionCreationDefaults + creationDefaults?: MissionCreationMetadata }) { const { manager, workspaceID, signal } = input const wait = input.wait ?? ((operation: Promise) => operation) diff --git a/packages/server/src/server/routes/mission-prepare.ts b/packages/server/src/server/routes/mission-prepare.ts index c10a4e16c8..4eb81e9aab 100644 --- a/packages/server/src/server/routes/mission-prepare.ts +++ b/packages/server/src/server/routes/mission-prepare.ts @@ -2,7 +2,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,7 +10,7 @@ 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 { parseMissionCreationDefaults } from "../../missions/creation-defaults" import { missionRecoveryRejection } from "../../missions/recovery-error" @@ -29,25 +29,26 @@ 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 new MissionControlError("The prepared mission's outcome is uncertain; retry with the same requestID", "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 new MissionControlError("The mission could not be prepared; nothing was created", "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 new MissionControlError("Only an active mission's coordinator may prepare a hand-off", "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) }), @@ -56,6 +57,9 @@ export async function prepareCoordinatorMission(manager: Manager, fence: Worktre ...(input.profiles === undefined ? {} : { profiles: input.profiles }), ...(input.taskMode === undefined ? {} : { taskMode: input.taskMode }) } }) return await creation.execute() } catch (error) { + if (creation && isMissionCreateNoEffectError(error, input.requestID, creation.missionID)) + throw new MissionControlError("The preparation request was refused without effects; correct the request and retry", "prepare-no-effect") + if (hasMissionPreparationHold(fence, input.requestID)) throw new MissionControlError("The prepared mission's outcome is uncertain; retry with the same requestID", "prepare-uncertain") if (missionRecoveryRejection(error)) throw error if (!creation?.dispatched && error instanceof Error && error.message.startsWith("compare-models-")) throw new MissionControlError(error.message, error.message) diff --git a/packages/server/src/server/routes/mission-profile-defaults.test.ts b/packages/server/src/server/routes/mission-profile-defaults.test.ts index 8ba73aa0ab..a70c2e602b 100644 --- a/packages/server/src/server/routes/mission-profile-defaults.test.ts +++ b/packages/server/src/server/routes/mission-profile-defaults.test.ts @@ -3,6 +3,7 @@ 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" function fixture(t: TestContext, read?: () => unknown) { const app = Fastify() @@ -53,21 +54,34 @@ test("invalid preference values fail closed with a fixed redacted code", async t 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 => { - const request = fixture(t, () => assert.fail("Invalid input must not read preferences")) + 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: { extra: true } }, + { 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, "mission-preferences-invalid") + 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, "mission-preferences-invalid") + assert.equal((await request({ template: "custom" }, { extra: true })).json().code, "invalid-execution") + assert.equal(reads, 0) +}) + +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 => { diff --git a/packages/server/src/server/routes/mission-profile-defaults.ts b/packages/server/src/server/routes/mission-profile-defaults.ts index c8f9a485b3..a93e4d4e9c 100644 --- a/packages/server/src/server/routes/mission-profile-defaults.ts +++ b/packages/server/src/server/routes/mission-profile-defaults.ts @@ -1,7 +1,7 @@ import { z } from "zod" import { MissionControlError } from "../../missions/control-error" import { missionProfilesInputSchema, validateMissionProfiles } from "../../missions/playbook-profiles" -import { resolveMissionCreationDefaults } from "../../missions/profile-defaults" +import { MissionPreferencesError, resolveMissionCreationDefaults } from "../../missions/profile-defaults" import { missionRecoveryError } from "../../missions/recovery-error" import { missionTaskModeInputSchema } from "../../missions/task-execution-mode" import { isPlainObject } from "../../settings/merge-patch" @@ -26,10 +26,10 @@ function refusal(code: "mission-preferences-invalid" | "mission-preferences-unav /** 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 refusal("mission-preferences-invalid") + if (!parsed.success) throw new MissionControlError("Correct the profile-defaults request: use a supported template, valid profiles and taskMode, and a complete coordinatorModel", "invalid-execution") const { input } = parsed.data try { validateMissionProfiles(input.template, input.profiles) } - catch { throw refusal("mission-preferences-invalid") } + catch { throw new MissionControlError("Correct profiles.roles to use roles from the selected playbook", "invalid-execution") } let preferences: unknown try { if (!settings?.getRawConfigOwner) throw new Error("Missing preference reader") @@ -38,5 +38,8 @@ export function readMissionProfileDefaults(settings: Partial Date: Fri, 6 Nov 2026 02:47:29 +0100 Subject: [PATCH 05/16] fix(missions): preserve standalone creation without backend preferences Plugin-only sessions must still prepare a mission through the ordinary model tool loop when no CodeNomad backend owns them. Resolve explicit inputs and OpenCode defaults only after proven owner absence, and record selection.preferences unavailable in the immutable creation provenance so retries retain the warning after a backend appears. Use strict preference discovery across local and WSL Windows registries. Ambiguous owners, unreadable registrations, failed probes and indeterminate directory authorization refuse instead of silently falling back. Typed missing-session replies and empty workspace inventories provide negative ownership evidence. Reuse one input codec at the producer and backend boundary, preserve explicit inputs and native coordinator/catalog checks, and keep prepare hand-offs behind the existing owning-backend creation fences. Extend schema, wire and projection handling for the optional warning, cover standalone tool creation and saved retries, and update tool descriptions, Missions documentation, the skill and all ten help locales. The native contract script and OpenCode sources are unchanged. Reproduced the CI assertion failure before the fix on isolated OpenCode 2.2.3 and 2.2.5. The unchanged contract now exits zero with all three gates on both runtimes; read-only fixture checks verify one mission and matching warning values in tool output, journal event and unified document. Focused suites passed 117 tests; both typechecks, Missions build, native-plugin invariants 2/2, help tests 31/31 and whitespace checks passed. The full Missions run passed 1043 of 1044 tests with the Git local-source deadline failure. Isolated origin/dev 30527e58 and branch tests both passed 10/10 with identical test/implementation hashes, so the baseline timeout was not reproduced or labelled confirmed pre-existing. --- .opencode/skills/codenomad-missions/SKILL.md | 10 +- dev-docs/MISSIONS.md | 20 ++- docs/help/de/missions.md | 2 + docs/help/en/missions.md | 2 + docs/help/es/missions.md | 2 + docs/help/fr/missions.md | 2 + docs/help/he/missions.md | 2 + docs/help/ja/missions.md | 2 + docs/help/ne/missions.md | 2 + docs/help/ru/missions.md | 2 + docs/help/tr/missions.md | 2 + docs/help/zh-Hans/missions.md | 2 + .../server/src/missions/creation-defaults.ts | 27 +++- .../server/src/missions/profile-defaults.ts | 1 + ...automation-plugin-profile-defaults.test.ts | 130 +++++++++++++++++- .../server/src/opencode/automation-plugin.ts | 46 +++++-- .../server/src/opencode/missions-plugin.ts | 4 +- .../src/server/routes/automation-plugin.ts | 39 ++++-- .../server/routes/mission-profile-defaults.ts | 18 +-- 19 files changed, 261 insertions(+), 54 deletions(-) diff --git a/.opencode/skills/codenomad-missions/SKILL.md b/.opencode/skills/codenomad-missions/SKILL.md index 7d8e6f0910..6d607420fc 100644 --- a/.opencode/skills/codenomad-missions/SKILL.md +++ b/.opencode/skills/codenomad-missions/SKILL.md @@ -30,8 +30,14 @@ Read the creation response's `selection.profiles`, `selection.taskMode` and `selection.origins` to check the saved coordinator and every playbook role: `explicit`, `preference` or `opencode-default`. A chosen judge slot keeps its explicit/preference origin even with an inherited model; an absent judge slot -inherits the coordinator's origin. Unreadable/invalid preferences refuse creation; report -the error and arrange recovery of the Missions preferences before retrying. +inherits the coordinator's origin. With no bridge presence or zero proven owning +backends, `inspect({ start })` uses explicit inputs and OpenCode defaults for omitted +choices (`native` task-mode fallback), returning `selection.preferences: "unavailable"` and only `explicit` +or `opencode-default` origins. Saved `creationDefaults.preferences: "unavailable"` +retains the warning on retries even after a backend appears. Multiple owners, +failed/incomplete backend discovery or unreadable/invalid preferences refuse +creation; report the error and arrange recovery before retrying. `mission.prepare` +requires an owning backend for fenced creation even with fallback profile choices. `inspect({ start })` requires the caller's existing coordinator profile to match the resolved selection. When a coordinator preference differs, pass `profiles.coordinator` (for example `{}`) to override that preference; the existing diff --git a/dev-docs/MISSIONS.md b/dev-docs/MISSIONS.md index 606351eea6..a8db2bc45b 100644 --- a/dev-docs/MISSIONS.md +++ b/dev-docs/MISSIONS.md @@ -164,11 +164,23 @@ refuse otherwise. Only one-time coordinators are offered and told about 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. An unreadable - preference document or unavailable backend returns + native-profile error. + + 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 + `creationDefaults.preferences: "unavailable"` 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`. Both refuse creation and ask for preference - recovery, including when profiles were supplied explicitly. + `mission-preferences-invalid`. These failures refuse creation and ask for + recovery, including when profiles were supplied explicitly. Discovery includes + the Windows registry under WSL. A typed missing-session reply or an empty backend + workspace inventory proves non-ownership. Directory-authorization failure with + open workspaces is indeterminate because Git/WSL read failures can yield false. + `mission.prepare` requires an owning backend for fenced creation even when + profile resolution can use the no-owner fallback. The requestID is scoped to the coordinator and mission. Preparations with the same requestID are serialized. Reuse that requestID and the original inputs: diff --git a/docs/help/de/missions.md b/docs/help/de/missions.md index 46468e9283..579c77bcf5 100644 --- a/docs/help/de/missions.md +++ b/docs/help/de/missions.md @@ -139,6 +139,8 @@ Das Speichern einer Tiefe erhält aktivierte native Zeitpläne in der Projektkon Diese Vorgaben gelten auch, wenn ein Agent eine Mission vorbereitet: Jedes ausgelassene Koordinator- oder Rollenprofil verwendet zuerst die Playbook-Ausnahme, dann die globale Auswahl. Der globale Spezialist liefert die Aufgabenrollen; der Vergleichsrichter verwendet standardmäßig das Modell des Koordinators. Ein ausdrücklich angegebenes Profil hat als Ganzes Vorrang, auch bei OpenCode-Standardwerten oder einer reinen Agentenauswahl. Beim Richter wird ein fehlendes Modell anschließend durch das bekannte Koordinatormodell ergänzt, auch bei ausdrücklich gewählten oder gespeicherten OpenCode-Standardwerten oder reiner Agentenauswahl; sein eigenes Modell bleibt unverändert. Der Richter behält die Herkunft seines ausdrücklich gewählten oder gespeicherten Profils; ein ausgelassenes Richterprofil erbt die Herkunft des Koordinators. Ausgelassene **Aufgabensitzungen** folgen derselben Reihenfolge, danach **Native Unteragenten**. Die Erstellungsantwort an den Agenten nennt die gespeicherten Profile, den Sitzungsmodus und die Herkunft jeder Auswahl: ausdrücklich, Vorgabe oder OpenCode-Standard. Unlesbare oder ungültige Vorgaben blockieren die Erstellung mit einer Fehlermeldung zur Korrektur oder zum Neuladen. Wiederholungen behalten die ursprünglich gespeicherte Auswahl auch bei geänderten Vorgaben bei. +Erstellt ein Agent mit `mission.inspect({ start })` eine pausierte Mission, während kein zuständiges CodeNomad-Backend vorhanden ist, verwendet er ausdrückliche Auswahlen und OpenCode-Standardwerte mit einer Warnung über nicht verfügbare Vorgaben. Wiederholungen behalten diese Warnung auch dann bei, wenn später ein Backend hinzukommt. Mehrere zuständige Backends oder ein registriertes zuständiges Backend, das fehlschlägt oder unerreichbar ist, blockieren die Erstellung. Mit `mission.prepare` vorbereitete Folgemissionen benötigen für die Erstellungsprüfungen ein zuständiges Backend. + 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 bb30313e1b..540dc94244 100644 --- a/docs/help/en/missions.md +++ b/docs/help/en/missions.md @@ -139,6 +139,8 @@ Saving a depth preserves enabled native schedules in the project configuration. These defaults also apply when an agent prepares a mission: each omitted coordinator or role profile uses the playbook exception, then the global choice; the global specialist supplies task roles, while the comparison judge defaults to the coordinator's model. An explicitly supplied profile wins as a whole, including an OpenCode-default choice or an agent-only choice. For the judge, any missing model is then filled from the coordinator's known model, even with an explicit or saved OpenCode-default or agent-only choice; its own model stays unchanged. The judge keeps the source of its explicit or saved profile; an omitted judge profile inherits the coordinator's source. Omitted **Task sessions** uses the same preference order, then **Native subagents**. The agent's creation response lists the saved profiles, task-session mode and each choice's source: explicit, preference or OpenCode default. Unreadable or invalid preferences block creation with a recovery error. Retries retain the original saved choices even if you change the defaults. +When an agent creates a paused mission with `mission.inspect({ start })` and no owning CodeNomad backend is present, it uses explicit choices and OpenCode defaults, with a preferences-unavailable warning. Retries retain that warning even if a backend later appears. Multiple owners or a registered owner that fails or cannot be reached block creation. Follow-ups prepared with `mission.prepare` require an owning backend for creation checks. + 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 2909146258..011238b30a 100644 --- a/docs/help/es/missions.md +++ b/docs/help/es/missions.md @@ -139,6 +139,8 @@ Guardar una profundidad conserva las programaciones nativas activadas en la conf Estos valores también se aplican cuando un agente prepara una misión: cada perfil de coordinador o rol omitido usa la excepción del guion y luego la elección global; el especialista global proporciona los roles de tareas, mientras que el juez de comparación usa por defecto el modelo del coordinador. Un perfil indicado explícitamente tiene prioridad en su totalidad, incluidos los valores de OpenCode o una elección de solo agente. Para el juez, cualquier modelo ausente se completa después con el modelo conocido del coordinador, incluso con una elección explícita o guardada de valores de OpenCode o de solo agente; su propio modelo se mantiene. El juez conserva el origen de su perfil explícito o guardado; un perfil de juez omitido hereda el origen del coordinador. **Sesiones de tareas** omitido sigue el mismo orden de preferencias y luego **Subagentes nativos**. La respuesta de creación al agente enumera los perfiles guardados, el modo de sesiones y el origen de cada elección: explícito, preferencia o valor predeterminado de OpenCode. Las preferencias ilegibles o inválidas bloquean la creación con un error que pide corregirlas o recargarlas. Los reintentos conservan las elecciones guardadas originales aunque cambies los valores predeterminados. +Cuando un agente crea una misión pausada con `mission.inspect({ start })` y no hay un backend de CodeNomad responsable, usa las elecciones explícitas y los valores predeterminados de OpenCode, con una advertencia de preferencias no disponibles. Los reintentos conservan esa advertencia aunque aparezca un backend más tarde. Varios responsables, o un responsable registrado que falla o no es accesible, bloquean la creación. Las misiones de seguimiento preparadas con `mission.prepare` requieren un backend responsable para las comprobaciones de creación. + 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 96f731b61b..69f1b50eb4 100644 --- a/docs/help/fr/missions.md +++ b/docs/help/fr/missions.md @@ -139,6 +139,8 @@ Enregistrer une profondeur préserve les programmations natives activées dans l Ces défauts s'appliquent aussi quand un agent prépare une mission : chaque profil de coordinateur ou de rôle omis utilise l'exception du scénario, puis le choix global ; le spécialiste global fournit les rôles de tâches, tandis que le juge de comparaison utilise par défaut le modèle du coordinateur. Un profil explicitement fourni prime en entier, y compris un choix de défauts OpenCode ou un agent seul. Pour le juge, tout modèle manquant est ensuite complété par le modèle connu du coordinateur, même avec un choix explicite ou enregistré de défauts OpenCode ou d'agent seul ; son propre modèle reste inchangé. Le juge conserve l'origine de son profil explicite ou enregistré ; un profil de juge omis hérite de l'origine du coordinateur. **Sessions des tâches** omis suit le même ordre de préférences, puis **Sous-agents natifs**. La réponse de création à l'agent donne les profils enregistrés, le mode des sessions de tâches et l'origine de chaque choix : explicite, préférence ou défaut OpenCode. Des préférences illisibles ou invalides bloquent la création avec une erreur demandant leur correction ou leur rechargement. Les réessais conservent les choix enregistrés à l'origine, même si vous modifiez les défauts. +Quand un agent crée une mission en pause avec `mission.inspect({ start })` sans backend CodeNomad propriétaire présent, il utilise les choix explicites et les défauts OpenCode, avec un avertissement indiquant que les préférences sont indisponibles. Les réessais conservent cet avertissement même si un backend apparaît ensuite. Plusieurs propriétaires, ou un propriétaire enregistré défaillant ou injoignable, bloquent la création. Les suivis préparés avec `mission.prepare` nécessitent un backend propriétaire pour les vérifications de création. + 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 fee284a4cc..5f18771fa6 100644 --- a/docs/help/he/missions.md +++ b/docs/help/he/missions.md @@ -139,6 +139,8 @@ ברירות המחדל חלות גם כשסוכן מכין משימה: כל פרופיל מתאם או תפקיד שהושמט משתמש בחריג של מדריך העבודה, ואז בבחירה הגלובלית; המומחה הגלובלי מספק את תפקידי המטלות, ושופט ההשוואה משתמש כברירת מחדל במודל של המתאם. פרופיל שסופק במפורש מקבל עדיפות בשלמותו, גם בבחירת ברירות המחדל של OpenCode או סוכן בלבד. אצל השופט, מודל חסר מושלם לאחר מכן מהמודל הידוע של המתאם, גם בבחירה מפורשת או שמורה של ברירות המחדל של OpenCode או של סוכן בלבד; מודל משלו נשאר ללא שינוי. השופט שומר על מקור הפרופיל המפורש או השמור שלו; פרופיל שופט שהושמט יורש את מקור המתאם. **שיחות משימות** שהושמטו משתמשות באותו סדר העדפות ואז ב־**תת־סוכנים מקוריים**. תשובת היצירה לסוכן מפרטת את הפרופילים השמורים, מצב השיחות ומקור כל בחירה: מפורש, העדפה או ברירת מחדל של OpenCode. העדפות פגומות או בלתי קריאות חוסמות יצירה עם שגיאה המבקשת לתקן או לטעון אותן מחדש. ניסיונות חוזרים שומרים על הבחירות המקוריות גם אם תשנו את ברירות המחדל. +כשסוכן יוצר משימה מושהית באמצעות `mission.inspect({ start })` ואין שרת CodeNomad אחראי, הוא משתמש בבחירות מפורשות ובברירות המחדל של OpenCode, עם אזהרה שההעדפות אינן זמינות. ניסיונות חוזרים שומרים על האזהרה גם אם שרת מופיע בהמשך. כמה שרתים אחראים, או שרת אחראי רשום שנכשל או שאינו נגיש, חוסמים יצירה. משימות המשך שמוכנות באמצעות `mission.prepare` דורשות שרת אחראי לבדיקות היצירה. + כל רשימת **מודל** מציגה את מה שמציג בורר **מודל** של השיחה, באותם שמות ומקובצת לפי ספק: מודלים מוסתרים אינם מופיעים, ובזמן שסינון למועדפים בלבד פעיל גם שאר המודלים אינם מופיעים (ראו [נראות מודלים, מועדפים וחשיבה](providers.md#models)). גם מודלים ללא תמיכה בכלים אינם מופיעים. מודל שמור שאינו ברשימה נשאר נבחר. **לא זמין** מסמן מודל שמור שהבורר אינו יכול להציע כעת: הוא חסר בקטלוג הנוכחי של הפרויקט, הוצא משימוש או אינו תומך בכלים. בחירה שנדחתה או שלא אושרה לעולם אינה נשלחת שוב: הערכים השמורים מוצגים שוב, ו־**טעינה מחדש** מופיעה רק כשאי אפשר לקרוא אותם. אם שינוי עומק אינו מאושר, הערך שלכם נשמר; השתמשו ב־**רענון עומק הפרויקט** לפני שינוי נוסף. אל תפרשו **עומק OpenCode האפקטיבי אינו ידוע** כאפס או כמושבת. diff --git a/docs/help/ja/missions.md b/docs/help/ja/missions.md index cb24513276..64642da769 100644 --- a/docs/help/ja/missions.md +++ b/docs/help/ja/missions.md @@ -139,6 +139,8 @@ CodeNomad の実行中は、ミッションのコーディネーターやタス エージェントがミッションを準備する場合も、これらの既定値が適用されます。省略されたコーディネーターや役割のプロファイルには、プレイブックの例外、グローバルの選択の順で適用します。タスクの各役割にはグローバルのスペシャリストを使用し、比較の審査役には既定でコーディネーターのモデルを使用します。明示されたプロファイルは全体として優先され、OpenCode の既定値やエージェントのみの指定も含みます。審査役のモデルが未指定なら、その後で既知のコーディネーターのモデルを補います。明示または保存された OpenCode の既定値やエージェントのみの指定も対象で、審査役独自のモデルはそのまま保持します。審査役は明示または保存されたプロファイルの出所を保持し、審査役のプロファイル自体が省略された場合はコーディネーターの出所を継承します。省略された **タスクセッション** も同じ順で設定を適用し、最後に **ネイティブのサブエージェント** を使用します。エージェントへの作成応答には、保存されたプロファイル、タスクセッションのモード、各選択の出所(明示、設定、OpenCode の既定値)が表示されます。設定が読み取れない、または無効な場合は、修正や再読み込みを求めるエラーで作成を中断します。既定値を変更しても、再試行では元の保存済みの選択を保持します。 +エージェントが `mission.inspect({ start })` で一時停止中のミッションを作成し、担当する CodeNomad バックエンドが存在しない場合は、明示した選択と OpenCode の既定値を使用し、設定を利用できない旨の警告を返します。後でバックエンドが現れても、再試行ではこの警告を保持します。担当が複数いる場合や、登録済みの担当で障害が発生した場合、または接続できない場合は、作成を中断します。`mission.prepare` による後続ミッションの準備には、作成時の確認を行う担当バックエンドが必要です。 + 各 **モデル** リストには、会話の **モデル** セレクターと同じモデルが同じ名前でプロバイダーごとに表示されます。非表示のモデルは含まれず、お気に入りのみの絞り込みが有効な間はお気に入り以外のモデルも含まれません([モデルの表示、お気に入り、思考](providers.md#models) を参照)。ツールに対応していないモデルも含まれません。リストにない保存済みのモデルは選択されたまま残ります。**利用不可** は、プロジェクトの現在のカタログにない、非推奨である、またはツールに対応していないため、セレクターが現在提供できない保存済みのモデルに付きます。 拒否された選択や未確認の選択が再送されることはありません。保存済みの値が再び表示され、**再読み込み** はそれらを読み取れない場合にだけ表示されます。深さの変更が未確認の場合は入力した値が保持されるので、次の変更の前に **プロジェクトの深さを更新** を使用します。**OpenCode の有効な深さは不明** をゼロや無効と解釈しないでください。 diff --git a/docs/help/ne/missions.md b/docs/help/ne/missions.md index 55698163f4..1f325a9d8d 100644 --- a/docs/help/ne/missions.md +++ b/docs/help/ne/missions.md @@ -139,6 +139,8 @@ CodeNomad चलिरहँदा, project का हरेक agent कुर एजेन्टले मिसन तयार गर्दा पनि यी पूर्वनिर्धारित मान लागू हुन्छन्: छुटाइएको समन्वयकर्ता वा भूमिकाको प्रोफाइलमा पहिले प्लेबुकको अपवाद, त्यसपछि विश्वव्यापी चयन प्रयोग हुन्छ। कार्य भूमिकामा विश्वव्यापी विशेषज्ञ प्रयोग हुन्छ; तुलना गर्ने निर्णायकले पूर्वनिर्धारित रूपमा समन्वयकर्ताको मोडेल प्रयोग गर्छ। स्पष्ट रूपमा दिइएको प्रोफाइलले पूर्ण रूपमा प्राथमिकता पाउँछ, OpenCode का पूर्वनिर्धारित मान वा एजेन्ट मात्र रोजेको अवस्थामा पनि। निर्णायकको मोडेल छुटेको भए त्यसपछि समन्वयकर्ताको ज्ञात मोडेलबाट पूरा गरिन्छ, स्पष्ट वा सुरक्षित OpenCode पूर्वनिर्धारित मान वा एजेन्ट मात्रको चयनमा पनि; निर्णायकको आफ्नै मोडेल यथावत् रहन्छ। निर्णायकले आफ्नो स्पष्ट वा सुरक्षित प्रोफाइलको स्रोत कायम राख्छ; निर्णायकको प्रोफाइल नै छुटेको भए समन्वयकर्ताको स्रोत लिन्छ। छुटाइएको **कार्य सत्रहरू** मा उही प्राथमिकता क्रमपछि **नेटिभ उपएजेन्टहरू** प्रयोग हुन्छ। एजेन्टलाई फर्काइएको सिर्जना जवाफमा सुरक्षित प्रोफाइल, कार्य सत्रको मोड र हरेक चयनको स्रोत हुन्छ: स्पष्ट, प्राथमिकता वा OpenCode को पूर्वनिर्धारित मान। पढ्न नसकिने वा अमान्य प्राथमिकताले सुधार वा पुनः लोड गर्नुपर्ने त्रुटिसहित सिर्जना रोक्छन्। पूर्वनिर्धारित मान बदले पनि पुनःप्रयासले सुरुका सुरक्षित चयन कायम राख्छ। +एजेन्टले `mission.inspect({ start })` बाट रोकिएको मिसन सिर्जना गर्दा जिम्मेवार CodeNomad backend उपस्थित छैन भने स्पष्ट चयन र OpenCode का पूर्वनिर्धारित मान प्रयोग हुन्छन्, र प्राथमिकता उपलब्ध नभएको चेतावनी फर्काइन्छ। पछि backend आए पनि पुनःप्रयासमा त्यो चेतावनी कायम रहन्छ। धेरै जिम्मेवार backend, वा दर्ता भएको जिम्मेवार backend असफल वा पहुँचबाहिर भएमा सिर्जना रोकिन्छ। `mission.prepare` बाट तयार गरिने पछिल्ला मिसनका सिर्जना जाँचका लागि जिम्मेवार backend आवश्यक हुन्छ। + प्रत्येक **मोडेल** सूचीले कुराकानीको **मोडेल** 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 2628c2587e..b44a5d016a 100644 --- a/docs/help/ru/missions.md +++ b/docs/help/ru/missions.md @@ -139,6 +139,8 @@ Эти настройки действуют и при подготовке миссии агентом: каждый пропущенный профиль координатора или роли использует исключение сценария, затем глобальный выбор; глобальный специалист задаёт профили ролей задач, а судья сравнения по умолчанию использует модель координатора. Явно указанный профиль имеет приоритет целиком, включая выбор значений OpenCode или только агента. Затем отсутствующая модель судьи дополняется известной моделью координатора, даже при явном или сохранённом выборе значений OpenCode или только агента; собственная модель судьи остаётся неизменной. Судья сохраняет источник своего явного или сохранённого профиля; если профиль судьи пропущен, он наследует источник координатора. Пропущенные **Сессии задач** следуют тому же порядку настроек, затем используют **Нативные субагенты**. Ответ агенту при создании содержит сохранённые профили, режим сессий задач и источник каждого выбора: явный, настройка или значение OpenCode по умолчанию. Нечитаемые или недопустимые настройки блокируют создание с ошибкой, предлагающей исправить или перезагрузить их. Повторные попытки сохраняют исходный выбор даже после изменения настроек по умолчанию. +Когда агент создаёт приостановленную миссию через `mission.inspect({ start })` без ответственного сервера CodeNomad, используются явные настройки и значения OpenCode по умолчанию с предупреждением о недоступности настроек. Повторные попытки сохраняют это предупреждение, даже если сервер появится позже. Несколько ответственных серверов либо сбой или недоступность зарегистрированного ответственного сервера блокируют создание. Подготовка последующих миссий через `mission.prepare` требует ответственного сервера для проверок создания. + Каждый список **Модель** показывает то же, что переключатель **Модель** разговора, под теми же названиями и с группировкой по провайдерам: скрытые модели не показываются, а пока включена фильтрация только по избранному — и остальные модели (см. [Видимость моделей, избранное и мышление](providers.md#models)). Модели без поддержки инструментов тоже не показываются. Сохранённая модель вне списка остаётся выбранной. **Недоступно** отмечает сохранённую модель, которую переключатель сейчас не может предложить: её нет в текущем каталоге проекта, она устарела или не поддерживает инструменты. Отклонённый или неподтверждённый выбор никогда не отправляется повторно: снова показываются сохранённые значения, а **Обновить** появляется, только если их не удаётся прочитать. Если изменение глубины не подтверждено, ваше значение сохраняется; используйте **Обновить глубину проекта** перед новым изменением. Не трактуйте **Действующая глубина OpenCode неизвестна** как ноль или отключение. diff --git a/docs/help/tr/missions.md b/docs/help/tr/missions.md index b68c2aa8e7..a2655d9140 100644 --- a/docs/help/tr/missions.md +++ b/docs/help/tr/missions.md @@ -139,6 +139,8 @@ Derinliği kaydetmek, proje yapılandırmasında etkin yerel zamanlamaları koru Bir ajan görev hazırlarken de bu varsayılanlar uygulanır: belirtilmeyen her koordinatör veya rol profili önce rehber istisnasını, ardından genel seçimi kullanır; genel uzman görev rollerini sağlar, karşılaştırma hakemi ise varsayılan olarak koordinatörün modelini kullanır. Açıkça verilen profil, OpenCode varsayılanı veya yalnızca ajan seçimi dahil, bütünüyle önceliklidir. Hakemin eksik modeli daha sonra koordinatörün bilinen modeliyle tamamlanır; açık veya kayıtlı OpenCode varsayılanı ya da yalnızca ajan seçimi de buna dahildir, hakemin kendi modeli ise korunur. Hakem açık veya kayıtlı profilinin kaynağını korur; hakem profili belirtilmemişse koordinatörün kaynağını devralır. Belirtilmeyen **Görev oturumları** aynı tercih sırasını, ardından **Yerel alt ajanlar** seçimini kullanır. Ajana dönen oluşturma yanıtı kayıtlı profilleri, görev oturumu modunu ve her seçimin kaynağını listeler: açık seçim, tercih veya OpenCode varsayılanı. Okunamayan veya geçersiz tercihler, düzeltme ya da yeniden yükleme isteyen bir hatayla oluşturmayı engeller. Varsayılanları değiştirseniz bile yeniden denemeler ilk kaydedilen seçimleri korur. +Bir ajan `mission.inspect({ start })` ile duraklatılmış bir görev oluştururken sorumlu CodeNomad arka ucu yoksa açık seçimler ve OpenCode varsayılanları kullanılır; tercihlerin kullanılamadığına dair bir uyarı döner. Daha sonra bir arka uç belirse bile yeniden denemeler bu uyarıyı korur. Birden fazla sorumlu arka uç ya da kayıtlı sorumlu arka ucun hata vermesi veya erişilememesi oluşturmayı engeller. `mission.prepare` ile hazırlanan takip görevleri, oluşturma denetimleri için sorumlu bir arka uç gerektirir. + 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 a07de5bb8f..e65db292e7 100644 --- a/docs/help/zh-Hans/missions.md +++ b/docs/help/zh-Hans/missions.md @@ -139,6 +139,8 @@ CodeNomad 运行期间,项目中的每个智能体对话(包括任务协调 智能体准备任务时也会应用这些默认设置:省略的协调者或角色配置先使用剧本例外,再使用全局选择;全局专家配置用于任务角色,比较裁判默认使用协调者的模型。显式提供的配置作为整体优先,包括选择 OpenCode 默认值或仅指定代理的情况。随后,裁判缺失的模型会用协调者已知的模型补全,即使显式或已保存的选择为 OpenCode 默认值或仅指定代理;裁判自身已指定的模型保持不变。裁判保留其显式或已保存配置的来源;裁判配置整体省略时,继承协调者的来源。省略的**任务会话**采用相同的偏好顺序,最后使用**原生子代理**。返回给智能体的创建响应列出已保存的配置、任务会话模式及每项选择的来源:显式指定、偏好或 OpenCode 默认值。偏好无法读取或无效时,创建会被阻止,并返回要求修正或重新加载的错误。即使修改默认设置,重试也会保留最初保存的选择。 +智能体通过 `mission.inspect({ start })` 创建暂停的任务时,如果没有所属的 CodeNomad 后端,会使用显式选择和 OpenCode 默认值,并返回偏好不可用的警告。即使后续出现后端,重试仍保留该警告。存在多个所属后端,或已注册的所属后端发生故障或无法访问时,创建会被阻止。通过 `mission.prepare` 准备后续任务需要所属后端执行创建检查。 + 每个**模型**列表显示的内容与对话的**模型**选择器相同,名称一致并按提供商分组:不包含已隐藏的模型;启用仅收藏筛选时,也不包含其他模型(参见[模型可见性、收藏和思考](providers.md#models))。不支持工具的模型同样不包含。列表之外的已保存模型仍保持选中。选择器当前无法提供的已保存模型标记为**不可用**:它不在项目当前的目录中、已弃用或不支持工具。 被拒绝或未确认的选择绝不会重新发送:会重新显示已存储的值,只有在无法读取这些值时才会出现**重新加载**。如果深度更改未确认,你的值会保留;请先使用**刷新项目深度**,再进行其他更改。不要将 **OpenCode 有效深度未知**解释为零或禁用。 diff --git a/packages/server/src/missions/creation-defaults.ts b/packages/server/src/missions/creation-defaults.ts index d1c2b5471b..50248db63d 100644 --- a/packages/server/src/missions/creation-defaults.ts +++ b/packages/server/src/missions/creation-defaults.ts @@ -3,13 +3,32 @@ 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, type MissionCreationSelection } from "./profile-defaults" +import { MissionControlError } from "./control-error" +import { parseExecution } from "./execution" const origin = z.enum(MISSION_DEFAULT_ORIGINS) export const missionCreationChoicesSchema = z.object({ profiles: missionProfilesInputSchema, taskMode: missionTaskModeInputSchema.optional() }).strict() +const defaultsInputSchema = missionCreationChoicesSchema.extend({ + template: z.enum(["custom", "wayfinder", "debug", "delivery", "compare"]), + 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("Correct the profile-defaults request: use a supported template, valid profiles and taskMode, and a complete coordinatorModel", "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 +} const originsSchema = z.object({ coordinator: origin, roles: z.record(z.string(), origin), taskMode: origin }).strict() +const preferencesSchema = z.literal("unavailable").optional() export const missionCreationDefaultsSchema = z.object({ request: missionCreationChoicesSchema, profiles: missionProfilesInputSchema, - taskMode: missionTaskModeInputSchema, origins: originsSchema }).strict() -const resolutionSchema = z.object({ profiles: missionProfilesInputSchema, taskMode: missionTaskModeInputSchema, origins: originsSchema }).strict() + taskMode: missionTaskModeInputSchema, origins: originsSchema, preferences: preferencesSchema }).strict() +const resolutionSchema = z.object({ profiles: missionProfilesInputSchema, taskMode: missionTaskModeInputSchema, + origins: originsSchema, preferences: preferencesSchema }).strict() export type MissionCreationChoices = z.infer export type MissionCreationMetadata = z.infer @@ -45,7 +64,8 @@ export function parseMissionCreationSelection(template: MissionTemplateId, input export function missionCreationSelection(mission: Pick): MissionCreationSelection | undefined { if (!mission.creationDefaults) return undefined return structuredClone({ profiles: mission.creationDefaults.profiles as MissionCreationSelection["profiles"], - taskMode: mission.creationDefaults.taskMode, origins: mission.creationDefaults.origins }) + 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 @@ -53,6 +73,7 @@ export const missionCreationDefaultsWire = { type: "object", properties: { request: { type: "object", properties: { profiles: missionProfilesSchema, taskMode: missionTaskModeSchema }, additionalProperties: false }, profiles: missionProfilesSchema, taskMode: missionTaskModeSchema, + preferences: { type: "string", enum: ["unavailable"] }, origins: { type: "object", properties: { coordinator: originWire, taskMode: originWire, roles: { type: "object", maxProperties: 6, additionalProperties: originWire } }, required: ["coordinator", "roles", "taskMode"], additionalProperties: false }, }, required: ["request", "profiles", "taskMode", "origins"], additionalProperties: false, diff --git a/packages/server/src/missions/profile-defaults.ts b/packages/server/src/missions/profile-defaults.ts index 9f0cefce63..b6644241df 100644 --- a/packages/server/src/missions/profile-defaults.ts +++ b/packages/server/src/missions/profile-defaults.ts @@ -87,6 +87,7 @@ export class MissionPreferencesError extends Error { } export interface MissionCreationSelection { + preferences?: "unavailable" profiles: Required taskMode: MissionTaskMode origins: { coordinator: MissionDefaultOrigin; roles: Record; taskMode: MissionDefaultOrigin } diff --git a/packages/server/src/opencode/automation-plugin-profile-defaults.test.ts b/packages/server/src/opencode/automation-plugin-profile-defaults.test.ts index 655357a8d7..98f2e76252 100644 --- a/packages/server/src/opencode/automation-plugin-profile-defaults.test.ts +++ b/packages/server/src/opencode/automation-plugin-profile-defaults.test.ts @@ -4,11 +4,14 @@ 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 { MissionControlError } from "../missions/control-error" import { registerAutomationPluginRoute } from "../server/routes/automation-plugin" -import { AUTOMATION_BRIDGE_PATH, createAutomationBridgeRegistration, publishAutomationBridge, sendMissionInput } from "./automation-plugin" +import { setupMissionsPlugin } from "./missions-plugin" +import { AUTOMATION_BRIDGE_PATH, automationBridgeDirectories, createAutomationBridgeRegistration, publishAutomationBridge, sendMissionInput } from "./automation-plugin" -test("profile defaults preserve typed refusals through the authenticated bridge and require one owner", async t => { +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 @@ -26,23 +29,38 @@ test("profile defaults preserve typed refusals through the authenticated bridge 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 + 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" | "http" | "malformed" | "unproven-negative" | undefined + let inventoryFailure = false let failureCode: string | 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 () => ({ location: { directory: "/repo" } }) } }), - list: () => [{ id: "owner" }], ownsLocation: async () => true, + 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 () => { if (ownershipFailure) throw new Error("Ownership unavailable"); 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 === "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") @@ -57,14 +75,89 @@ test("profile defaults preserve typed refusals through the authenticated bridge const unavailable = (error: unknown) => error instanceof MissionControlError && error.code === "mission-preferences-unavailable" && error.message === "Reload or correct the Missions preferences before creating a mission" - await assert.rejects(request(), unavailable, "zero owners must expose a preference refusal") + 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 sendMissionInput("ses_owner", "profile-defaults", { 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(sendMissionInput("ses_owner", "profile-defaults", { 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: (id, input) => sendMissionInput(id, "profile-defaults", input), + 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) + 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 beforeNegative = reads + owned = false + await assert.rejects(request(), unavailable, "a false authorization can hide failed Git or WSL reads") + 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 + for (probeFailure of ["network", "http", "malformed", "unproven-negative"] as const) await assert.rejects(request(), unavailable, "a registered backend failure refuses fallback") + 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" @@ -88,4 +181,29 @@ test("profile defaults preserve typed refusals through the authenticated bridge 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("strict WSL discovery cannot omit an unobserved Windows registry", () => { + const options = { platform: "linux" as const, env: { WSL_DISTRO_NAME: "fixture" }, home: "/fixture", windowsLocalAppData: null } + assert.deepEqual(automationBridgeDirectories(options), ["/fixture/.config/codenomad/automation-bridges"]) + assert.throws(() => automationBridgeDirectories({ ...options, strict: true }), /Windows mission backend discovery is unavailable/) + assert.deepEqual(automationBridgeDirectories({ ...options, windowsLocalAppData: "/mnt/c/fixture", strict: true }), [ + "/fixture/.config/codenomad/automation-bridges", "/mnt/c/fixture/CodeNomad/automation-bridges", + ]) +}) + +test("strict WSL discovery retries a failed cached Windows registry lookup", t => { + let attempts = 0 + const mocked = t.mock.method(childProcess, "execFileSync", () => { attempts++; throw new Error("Host lookup failed") }) + syncBuiltinESMExports() + t.after(() => { mocked.mock.restore(); syncBuiltinESMExports() }) + const options = { platform: "linux" as const, env: { WSL_DISTRO_NAME: "fixture" }, home: "/fixture" } + assert.deepEqual(automationBridgeDirectories(options), ["/fixture/.config/codenomad/automation-bridges"]) + assert.equal(attempts, 1) + assert.throws(() => automationBridgeDirectories({ ...options, strict: true }), /Windows mission backend discovery is unavailable/) + assert.equal(attempts, 2, "an old failed lookup is not reused as negative ownership evidence") }) diff --git a/packages/server/src/opencode/automation-plugin.ts b/packages/server/src/opencode/automation-plugin.ts index b737c241ec..1ef4da511a 100644 --- a/packages/server/src/opencode/automation-plugin.ts +++ b/packages/server/src/opencode/automation-plugin.ts @@ -7,6 +7,8 @@ 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 { parseMissionCreationDefaultsInput } from "../missions/creation-defaults" +import { resolveMissionCreationDefaults } from "../missions/profile-defaults" import { PAGE_ACTION_PROPERTIES, PAGE_ACTIONS, parsePageAction, type RefAction } from "../automation/page/parse" export const AUTOMATION_BRIDGE_PATH = "/api/opencode-plugin/automation" @@ -75,7 +77,8 @@ export function automationBridgeDirectories(options: { platform?: NodeJS.Platform env?: NodeJS.ProcessEnv home?: string - windowsLocalAppData?: string + windowsLocalAppData?: string | null + strict?: boolean } = {}): string[] { const platform = options.platform ?? process.platform const env = options.env ?? process.env @@ -87,14 +90,15 @@ export function automationBridgeDirectories(options: { ? paths.join(env.XDG_RUNTIME_DIR, "codenomad", "automation-bridges") : paths.join(home, ".config", "codenomad", "automation-bridges") if (platform !== "linux" || !env.WSL_DISTRO_NAME) return [primary] - const windowsLocalAppData = options.windowsLocalAppData ?? resolveWslWindowsLocalAppData() + const windowsLocalAppData = options.windowsLocalAppData !== undefined ? options.windowsLocalAppData : resolveWslWindowsLocalAppData(options.strict) + if (options.strict && !windowsLocalAppData) throw new Error("Windows mission backend discovery is unavailable") return windowsLocalAppData ? [...new Set([primary, path.posix.join(windowsLocalAppData, "CodeNomad", "automation-bridges")])] : [primary] } -function resolveWslWindowsLocalAppData(): string | undefined { - if (cachedWslWindowsLocalAppData !== undefined) return cachedWslWindowsLocalAppData ?? undefined +function resolveWslWindowsLocalAppData(strict = false): string | undefined { + if (cachedWslWindowsLocalAppData !== undefined && (!strict || cachedWslWindowsLocalAppData !== null)) return cachedWslWindowsLocalAppData ?? undefined try { const windowsPath = execFileSync("cmd.exe", ["/d", "/s", "/c", "echo %LOCALAPPDATA%"], { encoding: "utf8", @@ -289,9 +293,9 @@ export async function verifyHumanAnswerBridge(body: import("../missions/human-an return false } -async function registrations(pruneStale = true): Promise { +async function registrations(pruneStale = true, strict = false): Promise { const found: DiscoveredBridgeRegistration[] = [] - const directories = automationBridgeDirectories() + const directories = automationBridgeDirectories({ strict }) for (const [directoryIndex, directory] of directories.entries()) { let entries: Array<{ name: string; startedAt: number }> = [] const entryLimit = directoryIndex === 0 ? MAX_LOCAL_REGISTRY_FILES : MAX_REGISTRATIONS @@ -302,12 +306,14 @@ async function registrations(pruneStale = true): Promise 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) { + if (strict && (error as NodeJS.ErrnoException).code !== "ENOENT") throw error continue } entries.sort((left, right) => right.startedAt - left.startedAt) @@ -315,7 +321,10 @@ async function registrations(pruneStale = true): Promise undefined) continue @@ -324,6 +333,7 @@ async function registrations(pruneStale = true): 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) } @@ -525,15 +535,19 @@ async function probeBrowserBridges( sessionID: string, mode: "browser-claim" | "browser-probe", timeoutMs = PROBE_TIMEOUT_MS, - purpose?: "mission", + purpose?: "mission" | "mission-preferences", + strict = false, ): Promise { 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 { - return (await callBridge(registration, { mode, sessionID, ...(purpose ? { purpose } : {}) }, timeoutMs)).status === 200 - ? registration : undefined - } catch { + const response = await callBridge(registration, { mode, sessionID, ...(purpose ? { purpose } : {}) }, timeoutMs) + if (response.status === 200 && (!strict || (response.body.result as { available?: unknown } | undefined)?.available === true)) return registration + if (strict && !(response.status === 404 && response.body.code === "mission-not-owner")) throw new Error("Mission backend ownership is unavailable") + return undefined + } catch (error) { + if (strict) throw error return undefined } })) @@ -547,10 +561,16 @@ async function probeBrowserBridges( export async function sendMissionInput(sessionID: string, kind: "prompt" | "synthetic" | "cleanup" | "lifecycle" | "create-root" | "prepare" | "task-sessions" | "interrupt" | "profile-defaults", input: unknown): Promise { try { + const defaultsInput = kind === "profile-defaults" ? parseMissionCreationDefaultsInput(input) : undefined // `purpose` lets a backend without native browsers claim the session for dispatch only. let targets: DiscoveredBridgeRegistration[] try { - targets = await probeBrowserBridges(await registrations(), sessionID, "browser-claim", MISSION_PROBE_TIMEOUT_MS, "mission") + const strict = kind === "profile-defaults" + targets = await probeBrowserBridges(await registrations(true, strict), sessionID, "browser-claim", MISSION_PROBE_TIMEOUT_MS, + strict ? "mission-preferences" : "mission", strict) + if (defaultsInput && targets.length === 0) return { + ...resolveMissionCreationDefaults({ ...defaultsInput, preferences: undefined }), preferences: "unavailable", + } if (targets.length !== 1) throw new Error("Mission dispatch requires exactly one owning CodeNomad backend") } catch (error) { if (kind === "prepare") { diff --git a/packages/server/src/opencode/missions-plugin.ts b/packages/server/src/opencode/missions-plugin.ts index 8d4ed66976..1edb05d199 100644 --- a/packages/server/src/opencode/missions-plugin.ts +++ b/packages/server/src/opencode/missions-plugin.ts @@ -381,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. Creation uses Missions preferences for omitted choices and returns selection with saved profiles, taskMode and origins (explicit, preference, opencode-default); unreadable/invalid preferences refuse creation. The existing coordinator must match the resolved profile. 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. Creation uses Missions preferences for omitted choices and returns selection with saved profiles, taskMode and origins (explicit, preference, opencode-default). With no bridge presence or zero proven owning backends, start uses explicit inputs and OpenCode defaults, returning selection.preferences: 'unavailable'; saved creationDefaults retains this warning on retries even after a backend appears. Multiple owners, a failed/unreachable registered owner, or unreadable/invalid preferences refuse creation. The existing coordinator must match the resolved profile. 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.", input: inspectSchema, options: { namespace: "mission", codemode: false }, execute: async (input, tool) => { @@ -507,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. Creation uses Missions preferences for omitted choices and returns selection with saved profiles, taskMode and origins (explicit, preference, opencode-default); unreadable/invalid preferences refuse creation. It never starts; the user presses Play. Reuse the same requestID and original inputs to retry: saved choices stay frozen even if preferences change. Outside an active mission use the Missions editor. 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: what the Mission editor creates. Creation requires an owning CodeNomad backend for its fences, uses Missions preferences for omitted choices and returns selection with saved profiles, taskMode and origins (explicit, preference, opencode-default); multiple owners, a failed/unreachable registered owner, or unreadable/invalid preferences refuse creation. It never starts; the user presses Play. Reuse the same requestID and original inputs to retry: saved choices stay frozen even if preferences change. Outside an active mission use the Missions editor. Find it later with mission.inspect({ list: true }) and read it with mission.inspect({ missionID }); you cannot control it.", input: prepareSchema, options: { namespace: "mission", codemode: false }, execute: async (input, tool) => { diff --git a/packages/server/src/server/routes/automation-plugin.ts b/packages/server/src/server/routes/automation-plugin.ts index 44689c0d1d..9c4893ff20 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" @@ -15,7 +16,7 @@ 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 { missionRecoveryError, missionRecoveryRejection } from "../../missions/recovery-error" import { verifyMissionHumanAnswer } from "./mission-human-answer" import { verifyHumanRecurrenceRequest } from "./mission-recurrence-proof" import { BrowserPage } from "../../automation/browser-page" @@ -86,6 +87,12 @@ 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" + const preferenceUnavailable = () => { + const failure = missionRecoveryError("mission-preferences-unavailable")! + return reply.code(failure.status).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 @@ -96,16 +103,30 @@ 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, workspaceCount = 0 + try { + const workspaces = deps.workspaceManager.list() + workspaceCount = workspaces.length + owned = await lifetime.wait(Promise.any(workspaces.map(async workspace => { + try { if (await deps.workspaceManager.ownsLocation(workspace.id, location, undefined, signal)) 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() + // Directory authorization intentionally collapses some failed Git/WSL reads + // to false. With open workspaces that is not proof of absent ownership. + if (preferenceProbe && !owned && workspaceCount) return preferenceUnavailable() + if (!owned) return notOwner("Session is not owned by this CodeNomad instance") if (body.mode === "mission-input") { try { @@ -136,7 +157,7 @@ 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 } }) diff --git a/packages/server/src/server/routes/mission-profile-defaults.ts b/packages/server/src/server/routes/mission-profile-defaults.ts index a93e4d4e9c..fa090bd212 100644 --- a/packages/server/src/server/routes/mission-profile-defaults.ts +++ b/packages/server/src/server/routes/mission-profile-defaults.ts @@ -1,22 +1,12 @@ import { z } from "zod" import { MissionControlError } from "../../missions/control-error" -import { missionProfilesInputSchema, validateMissionProfiles } from "../../missions/playbook-profiles" +import { parseMissionCreationDefaultsInput } from "../../missions/creation-defaults" import { MissionPreferencesError, resolveMissionCreationDefaults } from "../../missions/profile-defaults" import { missionRecoveryError } from "../../missions/recovery-error" -import { missionTaskModeInputSchema } from "../../missions/task-execution-mode" import { isPlainObject } from "../../settings/merge-patch" import type { SettingsService } from "../../settings/service" -import { parseExecution } from "../../missions/execution" -const commandSchema = z.object({ kind: z.literal("profile-defaults"), input: z.object({ - template: z.enum(["custom", "wayfinder", "debug", "delivery", "compare"]), - profiles: missionProfilesInputSchema, - taskMode: missionTaskModeInputSchema.optional(), - 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() }).strict() +const commandSchema = z.object({ kind: z.literal("profile-defaults"), input: z.unknown() }).strict() function refusal(code: "mission-preferences-invalid" | "mission-preferences-unavailable"): MissionControlError { const error = missionRecoveryError(code)! @@ -27,9 +17,7 @@ function refusal(code: "mission-preferences-invalid" | "mission-preferences-unav export function readMissionProfileDefaults(settings: Partial> | undefined, command: unknown) { const parsed = commandSchema.safeParse(command) if (!parsed.success) throw new MissionControlError("Correct the profile-defaults request: use a supported template, valid profiles and taskMode, and a complete coordinatorModel", "invalid-execution") - const { input } = parsed.data - try { validateMissionProfiles(input.template, input.profiles) } - catch { throw new MissionControlError("Correct profiles.roles to use roles from the selected playbook", "invalid-execution") } + const input = parseMissionCreationDefaultsInput(parsed.data.input) let preferences: unknown try { if (!settings?.getRawConfigOwner) throw new Error("Missing preference reader") From 3061caa29341fcb560bd0a2279c9809552b40773 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pascal=20Andr=C3=A9?= Date: Fri, 6 Nov 2026 03:39:12 +0100 Subject: [PATCH 06/16] fix(missions): distinguish missing preferences from failed ownership reads An unrelated open CodeNomad workspace must not block standalone mission creation. Strict preference probes now distinguish clean non-ownership from physical, Git and WSL read failures while ordinary ownership consumers retain their existing behavior. Native inventory fallback verifies checkout absence when Git discovery fails, and strict probes reject degraded directory-only inventories, including cached ones, without changing normal no-Git conversations. When the coordinator, every template role and taskMode are explicit, resolve locally without a preference callback or backend probe. Preserve native catalog and coordinator checks, mark every origin explicit, and leave unobserved preference availability absent. Saved creation choices and standalone unavailable warnings remain immutable across retries. Treat stale endpoints as absent only on a proven refused connection. Windows interop requires curl's connection-refused diagnostic as well as exit 7, since the same exit also covers denied sockets; direct loopback probes bypass proxies and returned errors exclude verbose headers. Keep timeouts, HTTP/auth failures and unreadable live registrations as refusals. Local dead publishing PIDs provide safe absence evidence before parsing, and publisher cleanup preserves unreadable live registrations. Require intent timestamps and share one intent parser. Narrow the UI facade to editor helpers and types, retain behavioral editor/server parity checks, share template validation, recovery messages and profile descriptions, and replace line-number comments with effect/function references. Update Missions documentation, the skill and the ten help locales for the current selection and fallback rules. Two independent final reviews returned zero residual findings after fixing their additional unsafe-Git inventory and curl classification cases. Validation passed: 158 focused checks; final ownership/no-Git checks 47/47; bridge/WSL checks 17/17; sequential native Git regressions 4/4; full Missions suite 1047/1047 with no local-source deadline failure; both workspace typechecks; Missions and automation builds; native-plugin invariants 2/2; help 31/31 across 28 pages and ten locales; whitespace checks. The earlier broader Git launch exceeded its 60-second runner limit, then its sequential rerun passed. The unchanged native contract passed all three gates against isolated OpenCode 2.2.3 and 2.2.5. Read-only fixture verification confirmed exactly one mission, matching persisted unavailable-preferences metadata and the deployed bundle hash. No real missions, shared daemon, OpenCode source, merge or PR-description changes. --- .opencode/skills/codenomad-missions/SKILL.md | 18 +++- dev-docs/MISSIONS.md | 27 +++-- dev-docs/WORKTREE_SESSION_PLACEMENT.md | 1 + docs/help/de/missions.md | 4 +- docs/help/en/missions.md | 4 +- docs/help/es/missions.md | 4 +- docs/help/fr/missions.md | 4 +- docs/help/he/missions.md | 4 +- docs/help/ja/missions.md | 4 +- docs/help/ne/missions.md | 4 +- docs/help/ru/missions.md | 4 +- docs/help/tr/missions.md | 4 +- docs/help/zh-Hans/missions.md | 4 +- packages/server/src/missions/control.ts | 16 ++- .../src/missions/coordinator-actions.test.ts | 20 ++++ .../src/missions/creation-defaults.test.ts | 11 ++- .../server/src/missions/creation-defaults.ts | 6 +- .../src/missions/creation-intent.test.ts | 23 +++-- .../server/src/missions/creation-intent.ts | 48 ++++----- .../src/missions/profile-defaults.test.ts | 22 ++++- .../server/src/missions/profile-defaults.ts | 8 ++ ...automation-plugin-profile-defaults.test.ts | 98 +++++++++++++++++-- .../server/src/opencode/automation-plugin.ts | 27 +++-- .../src/opencode/connection-errors.test.ts | 15 +++ .../server/src/opencode/connection-errors.ts | 8 ++ .../server/src/opencode/missions-plugin.ts | 10 +- .../src/server/routes/automation-plugin.ts | 8 +- .../src/server/routes/mission-prepare.ts | 31 +++--- .../routes/mission-profile-defaults.test.ts | 8 ++ .../server/routes/mission-profile-defaults.ts | 4 +- .../native-worktree-fallback.test.ts | 84 ++++++++++++++++ .../server/src/workspaces/git-worktrees.ts | 14 ++- .../server/src/workspaces/manager.test.ts | 48 ++++++++- packages/server/src/workspaces/manager.ts | 27 +++-- .../server/src/workspaces/native-worktrees.ts | 14 ++- .../src/workspaces/opencode-cli-service.ts | 9 +- .../src/workspaces/worktree-directory.test.ts | 15 +++ .../src/workspaces/worktree-directory.ts | 22 ++++- packages/ui/src/lib/mission-defaults.ts | 4 +- .../tests/contracts/mission-defaults.test.ts | 7 +- 40 files changed, 538 insertions(+), 155 deletions(-) create mode 100644 packages/server/src/opencode/connection-errors.test.ts create mode 100644 packages/server/src/opencode/connection-errors.ts create mode 100644 packages/server/src/workspaces/__tests__/native-worktree-fallback.test.ts diff --git a/.opencode/skills/codenomad-missions/SKILL.md b/.opencode/skills/codenomad-missions/SKILL.md index 6d607420fc..c78f6b45cf 100644 --- a/.opencode/skills/codenomad-missions/SKILL.md +++ b/.opencode/skills/codenomad-missions/SKILL.md @@ -24,19 +24,28 @@ defaults to the coordinator's model). Each explicit profile slot wins whole: native model default, except for the Compare judge: after slot selection, any missing judge model inherits the known coordinator model, including explicit or preference `{}` and agent-only slots; a judge's own model stays unchanged. -`profiles: {}` inherits all slots. With absent preferences, +`profiles: {}` inherits all slots. 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. Unused unreadable or invalid preferences are irrelevant. Partial +or omitted selections read owning-backend preferences. With absent preferences, profiles use OpenCode defaults and task mode uses `native`. Read the creation response's `selection.profiles`, `selection.taskMode` and `selection.origins` to check the saved coordinator and every playbook role: `explicit`, `preference` or `opencode-default`. A chosen judge slot keeps its explicit/preference origin even with an inherited model; an absent judge slot -inherits the coordinator's origin. With no bridge presence or zero proven owning +inherits the coordinator's origin. 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), returning `selection.preferences: "unavailable"` and only `explicit` or `opencode-default` origins. Saved `creationDefaults.preferences: "unavailable"` retains the warning on retries even after a backend appears. Multiple owners, failed/incomplete backend discovery or unreadable/invalid preferences refuse -creation; report the error and arrange recovery before retrying. `mission.prepare` +creation; report the error and arrange recovery before retrying. A stale registration +with connection refused counts as absent; timeouts, HTTP/authentication errors and +unreadable registration state with indeterminate ownership refuse resolution. A +successful ownership read proving an unrelated project establishes non-ownership +even with other workspaces open; actual Git/WSL ownership-read failures refuse resolution. +`mission.prepare` requires an owning backend for fenced creation even with fallback profile choices. `inspect({ start })` requires the caller's existing coordinator profile to match the resolved selection. When a coordinator preference differs, pass @@ -49,8 +58,7 @@ preparations are serialized. Its standalone intent retains choices for an unknow outcome, releasing them on a positive result or a definitive no-effect refusal. A retry's prevalidation refusal leaves an earlier attempt's uncertainty intact. The project retains at most 128 unknown choices for 24 hours from first -reservation; retries preserve that deadline. An entry without a timestamp gets -one on its first read/prune and expires 24 hours later. At capacity, retry original +reservation; retries preserve that deadline. At capacity, retry original requestIDs to recover receipts and release slots, or wait for expiry. After expiry, preferences may be read anew only with both creation event and document absent; a positive receipt or saved document keeps its choices frozen. `inspect({ start })` diff --git a/dev-docs/MISSIONS.md b/dev-docs/MISSIONS.md index a8db2bc45b..acb72355d6 100644 --- a/dev-docs/MISSIONS.md +++ b/dev-docs/MISSIONS.md @@ -150,7 +150,12 @@ refuse otherwise. Only one-time coordinators are offered and told about `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. + `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. Unused + unreadable or invalid preferences are irrelevant. Partial or omitted selections + read the owning backend's preferences. Creation responses include `selection: { profiles, taskMode, origins }`: the saved coordinator and every role of the selected playbook, plus origins @@ -166,7 +171,7 @@ refuse otherwise. Only one-time coordinators are offered and told about check still applies. An explicit-profile mismatch keeps the generic native-profile error. - With no bridge presence or zero proven owning backends, `inspect({ start })` + 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 @@ -175,10 +180,15 @@ refuse otherwise. Only one-time coordinators are offered and told about backend discovery, or an unreadable preference document return `mission-preferences-unavailable`; invalid preferences return `mission-preferences-invalid`. These failures refuse creation and ask for - recovery, including when profiles were supplied explicitly. Discovery includes - the Windows registry under WSL. A typed missing-session reply or an empty backend - workspace inventory proves non-ownership. Directory-authorization failure with - open workspaces is indeterminate because Git/WSL read failures can yield false. + recovery. Discovery includes the Windows registry under WSL. A stale registration + whose connection is refused has no listener and counts as absent; timeouts, + HTTP/authentication failures and unreadable registration state with indeterminate + ownership refuse preference resolution. A local registration whose filename's + publishing PID is proven dead is absent even when its contents are unreadable; + cross-host PIDs require endpoint evidence. 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. `mission.prepare` requires an owning backend for fenced creation even when profile resolution can use the no-owner fallback. @@ -195,9 +205,8 @@ refuse otherwise. Only one-time coordinators are offered and told about 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. An - entry without a timestamp receives the current time on its first read or prune - and expires 24 hours later. At capacity, retry the original requestIDs to + 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. diff --git a/dev-docs/WORKTREE_SESSION_PLACEMENT.md b/dev-docs/WORKTREE_SESSION_PLACEMENT.md index 7384a36a4b..90b676569c 100644 --- a/dev-docs/WORKTREE_SESSION_PLACEMENT.md +++ b/dev-docs/WORKTREE_SESSION_PLACEMENT.md @@ -167,6 +167,7 @@ authorized workspace spelling before changing UI state. ## Agent conventions +- Preference authority probes use `ownsLocation(..., purpose, true)` for strict ownership: a successful read can establish a negative; physical-path, Git identity and WSL translation failures reject. Strict reads revalidate cached worktree paths, and Git filesystem discovery preserves verified checkout absence separately from ambiguous layouts or configured discovery. - 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. diff --git a/docs/help/de/missions.md b/docs/help/de/missions.md index 579c77bcf5..0f968d83d6 100644 --- a/docs/help/de/missions.md +++ b/docs/help/de/missions.md @@ -137,9 +137,9 @@ 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. -Diese Vorgaben gelten auch, wenn ein Agent eine Mission vorbereitet: Jedes ausgelassene Koordinator- oder Rollenprofil verwendet zuerst die Playbook-Ausnahme, dann die globale Auswahl. Der globale Spezialist liefert die Aufgabenrollen; der Vergleichsrichter verwendet standardmäßig das Modell des Koordinators. Ein ausdrücklich angegebenes Profil hat als Ganzes Vorrang, auch bei OpenCode-Standardwerten oder einer reinen Agentenauswahl. Beim Richter wird ein fehlendes Modell anschließend durch das bekannte Koordinatormodell ergänzt, auch bei ausdrücklich gewählten oder gespeicherten OpenCode-Standardwerten oder reiner Agentenauswahl; sein eigenes Modell bleibt unverändert. Der Richter behält die Herkunft seines ausdrücklich gewählten oder gespeicherten Profils; ein ausgelassenes Richterprofil erbt die Herkunft des Koordinators. Ausgelassene **Aufgabensitzungen** folgen derselben Reihenfolge, danach **Native Unteragenten**. Die Erstellungsantwort an den Agenten nennt die gespeicherten Profile, den Sitzungsmodus und die Herkunft jeder Auswahl: ausdrücklich, Vorgabe oder OpenCode-Standard. Unlesbare oder ungültige Vorgaben blockieren die Erstellung mit einer Fehlermeldung zur Korrektur oder zum Neuladen. Wiederholungen behalten die ursprünglich gespeicherte Auswahl auch bei geänderten Vorgaben bei. +Diese Vorgaben gelten auch, wenn ein Agent eine Mission vorbereitet: Jedes ausgelassene Koordinator- oder Rollenprofil verwendet zuerst die Playbook-Ausnahme, dann die globale Auswahl. Der globale Spezialist liefert die Aufgabenrollen; der Vergleichsrichter verwendet standardmäßig das Modell des Koordinators. Ein ausdrücklich angegebenes Profil hat als Ganzes Vorrang, auch bei OpenCode-Standardwerten oder einer reinen Agentenauswahl. Beim Richter wird ein fehlendes Modell anschließend durch das bekannte Koordinatormodell ergänzt, auch bei ausdrücklich gewählten oder gespeicherten OpenCode-Standardwerten oder reiner Agentenauswahl; sein eigenes Modell bleibt unverändert. Der Richter behält die Herkunft seines ausdrücklich gewählten oder gespeicherten Profils; ein ausgelassenes Richterprofil erbt die Herkunft des Koordinators. Ausgelassene **Aufgabensitzungen** folgen derselben Reihenfolge, danach **Native Unteragenten**. Die Erstellungsantwort an den Agenten nennt die gespeicherten Profile, den Sitzungsmodus und die Herkunft jeder Auswahl: ausdrücklich, Vorgabe oder OpenCode-Standard. Sind Koordinator, jede genaue Rolle des gewählten Playbooks und **Aufgabensitzungen** ausdrücklich angegeben, einschließlich `{}`-Profilen, werden Backend-Vorgaben vollständig übersprungen: Alle Herkünfte sind ausdrücklich, ihre Verfügbarkeit bleibt unbeobachtet. Ungenutzte unlesbare oder ungültige Vorgaben sind unerheblich. Teilweise oder ausgelassene Auswahlen lesen die Vorgaben des zuständigen Backends; unlesbare oder ungültige Vorgaben blockieren dann die Erstellung mit einer Fehlermeldung zur Korrektur oder zum Neuladen. Wiederholungen behalten die ursprünglich gespeicherte Auswahl auch bei geänderten Vorgaben bei. -Erstellt ein Agent mit `mission.inspect({ start })` eine pausierte Mission, während kein zuständiges CodeNomad-Backend vorhanden ist, verwendet er ausdrückliche Auswahlen und OpenCode-Standardwerte mit einer Warnung über nicht verfügbare Vorgaben. Wiederholungen behalten diese Warnung auch dann bei, wenn später ein Backend hinzukommt. Mehrere zuständige Backends oder ein registriertes zuständiges Backend, das fehlschlägt oder unerreichbar ist, blockieren die Erstellung. Mit `mission.prepare` vorbereitete Folgemissionen benötigen für die Erstellungsprüfungen ein zuständiges Backend. +Werden Vorgaben benötigt und ist kein zuständiges CodeNomad-Backend vorhanden, verwendet `mission.inspect({ start })` ausdrückliche Auswahlen und OpenCode-Standardwerte mit einer Warnung über nicht verfügbare Vorgaben. Wiederholungen behalten sie auch dann bei, wenn später ein Backend hinzukommt. Ein nachweislich projektfremdes Backend zählt auch bei anderen offenen Arbeitsbereichen als nicht zuständig. Eine veraltete Registrierung mit abgelehnter Verbindung zählt als abwesend. Mehrere zuständige Backends, tatsächliche Fehler beim Lesen der Zuständigkeit, Zeitüberschreitungen oder HTTP-/Authentifizierungsfehler blockieren die Auflösung der Vorgaben. Mit `mission.prepare` vorbereitete Folgemissionen benötigen für die Erstellungsprüfungen ein zuständiges Backend. 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. diff --git a/docs/help/en/missions.md b/docs/help/en/missions.md index 540dc94244..cf948dec15 100644 --- a/docs/help/en/missions.md +++ b/docs/help/en/missions.md @@ -137,9 +137,9 @@ 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. -These defaults also apply when an agent prepares a mission: each omitted coordinator or role profile uses the playbook exception, then the global choice; the global specialist supplies task roles, while the comparison judge defaults to the coordinator's model. An explicitly supplied profile wins as a whole, including an OpenCode-default choice or an agent-only choice. For the judge, any missing model is then filled from the coordinator's known model, even with an explicit or saved OpenCode-default or agent-only choice; its own model stays unchanged. The judge keeps the source of its explicit or saved profile; an omitted judge profile inherits the coordinator's source. Omitted **Task sessions** uses the same preference order, then **Native subagents**. The agent's creation response lists the saved profiles, task-session mode and each choice's source: explicit, preference or OpenCode default. Unreadable or invalid preferences block creation with a recovery error. Retries retain the original saved choices even if you change the defaults. +These defaults also apply when an agent prepares a mission: each omitted coordinator or role profile uses the playbook exception, then the global choice; the global specialist supplies task roles, while the comparison judge defaults to the coordinator's model. An explicitly supplied profile wins as a whole, including an OpenCode-default choice or an agent-only choice. For the judge, any missing model is then filled from the coordinator's known model, even with an explicit or saved OpenCode-default or agent-only choice; its own model stays unchanged. The judge keeps the source of its explicit or saved profile; an omitted judge profile inherits the coordinator's source. Omitted **Task sessions** uses the same preference order, then **Native subagents**. The agent's creation response lists the saved profiles, task-session mode and each choice's source: explicit, preference or OpenCode default. When the coordinator, every exact role of the selected playbook and **Task sessions** are explicit, including `{}` profile slots, backend preferences are skipped entirely: all sources are explicit and preference availability stays unobserved. Unused unreadable or invalid preferences are irrelevant. Partial or omitted selections read the owning backend's preferences; unreadable or invalid preferences then block creation with a recovery error. Retries retain the original saved choices even if you change the defaults. -When an agent creates a paused mission with `mission.inspect({ start })` and no owning CodeNomad backend is present, it uses explicit choices and OpenCode defaults, with a preferences-unavailable warning. Retries retain that warning even if a backend later appears. Multiple owners or a registered owner that fails or cannot be reached block creation. Follow-ups prepared with `mission.prepare` require an owning backend for creation checks. +When preferences are needed and no owning CodeNomad backend is present, `mission.inspect({ start })` uses explicit choices and OpenCode defaults, with a preferences-unavailable warning retained on retries even if a backend later appears. A backend proven unrelated to this project counts as a non-owner even with other workspaces open. A stale registration with connection refused counts as absent. Multiple owners, actual ownership-read failures, timeouts or HTTP/authentication errors block preference resolution. Follow-ups prepared with `mission.prepare` require an owning backend for creation checks. 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. diff --git a/docs/help/es/missions.md b/docs/help/es/missions.md index 011238b30a..9b439c24c3 100644 --- a/docs/help/es/missions.md +++ b/docs/help/es/missions.md @@ -137,9 +137,9 @@ 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. -Estos valores también se aplican cuando un agente prepara una misión: cada perfil de coordinador o rol omitido usa la excepción del guion y luego la elección global; el especialista global proporciona los roles de tareas, mientras que el juez de comparación usa por defecto el modelo del coordinador. Un perfil indicado explícitamente tiene prioridad en su totalidad, incluidos los valores de OpenCode o una elección de solo agente. Para el juez, cualquier modelo ausente se completa después con el modelo conocido del coordinador, incluso con una elección explícita o guardada de valores de OpenCode o de solo agente; su propio modelo se mantiene. El juez conserva el origen de su perfil explícito o guardado; un perfil de juez omitido hereda el origen del coordinador. **Sesiones de tareas** omitido sigue el mismo orden de preferencias y luego **Subagentes nativos**. La respuesta de creación al agente enumera los perfiles guardados, el modo de sesiones y el origen de cada elección: explícito, preferencia o valor predeterminado de OpenCode. Las preferencias ilegibles o inválidas bloquean la creación con un error que pide corregirlas o recargarlas. Los reintentos conservan las elecciones guardadas originales aunque cambies los valores predeterminados. +Estos valores también se aplican cuando un agente prepara una misión: cada perfil de coordinador o rol omitido usa la excepción del guion y luego la elección global; el especialista global proporciona los roles de tareas, mientras que el juez de comparación usa por defecto el modelo del coordinador. Un perfil indicado explícitamente tiene prioridad en su totalidad, incluidos los valores de OpenCode o una elección de solo agente. Para el juez, cualquier modelo ausente se completa después con el modelo conocido del coordinador, incluso con una elección explícita o guardada de valores de OpenCode o de solo agente; su propio modelo se mantiene. El juez conserva el origen de su perfil explícito o guardado; un perfil de juez omitido hereda el origen del coordinador. **Sesiones de tareas** omitido sigue el mismo orden de preferencias y luego **Subagentes nativos**. La respuesta de creación al agente enumera los perfiles guardados, el modo de sesiones y el origen de cada elección: explícito, preferencia o valor predeterminado de OpenCode. Si el coordinador, cada rol exacto del guion elegido y **Sesiones de tareas** son explícitos, incluidos los perfiles `{}`, se omiten por completo las preferencias del backend: todos los orígenes son explícitos y su disponibilidad queda sin observar. Las preferencias ilegibles o inválidas sin usar son irrelevantes. Las selecciones parciales u omitidas leen las preferencias del backend responsable; si son ilegibles o inválidas, bloquean entonces la creación con un error que pide corregirlas o recargarlas. Los reintentos conservan las elecciones guardadas originales aunque cambies los valores predeterminados. -Cuando un agente crea una misión pausada con `mission.inspect({ start })` y no hay un backend de CodeNomad responsable, usa las elecciones explícitas y los valores predeterminados de OpenCode, con una advertencia de preferencias no disponibles. Los reintentos conservan esa advertencia aunque aparezca un backend más tarde. Varios responsables, o un responsable registrado que falla o no es accesible, bloquean la creación. Las misiones de seguimiento preparadas con `mission.prepare` requieren un backend responsable para las comprobaciones de creación. +Cuando se necesitan preferencias y no hay un backend de CodeNomad responsable, `mission.inspect({ start })` usa las elecciones explícitas y los valores predeterminados de OpenCode, con una advertencia de preferencias no disponibles que se conserva al reintentar aunque aparezca un backend más tarde. Un backend cuya falta de relación con este proyecto está demostrada cuenta como no responsable, incluso con otros espacios abiertos. Un registro obsoleto cuya conexión se rechaza cuenta como ausente. Varios responsables, fallos reales al leer la titularidad, tiempos de espera agotados o errores HTTP/de autenticación bloquean la resolución de preferencias. Las misiones de seguimiento preparadas con `mission.prepare` requieren un backend responsable para las comprobaciones de creación. 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. diff --git a/docs/help/fr/missions.md b/docs/help/fr/missions.md index 69f1b50eb4..b7d7bbcf20 100644 --- a/docs/help/fr/missions.md +++ b/docs/help/fr/missions.md @@ -137,9 +137,9 @@ 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. -Ces défauts s'appliquent aussi quand un agent prépare une mission : chaque profil de coordinateur ou de rôle omis utilise l'exception du scénario, puis le choix global ; le spécialiste global fournit les rôles de tâches, tandis que le juge de comparaison utilise par défaut le modèle du coordinateur. Un profil explicitement fourni prime en entier, y compris un choix de défauts OpenCode ou un agent seul. Pour le juge, tout modèle manquant est ensuite complété par le modèle connu du coordinateur, même avec un choix explicite ou enregistré de défauts OpenCode ou d'agent seul ; son propre modèle reste inchangé. Le juge conserve l'origine de son profil explicite ou enregistré ; un profil de juge omis hérite de l'origine du coordinateur. **Sessions des tâches** omis suit le même ordre de préférences, puis **Sous-agents natifs**. La réponse de création à l'agent donne les profils enregistrés, le mode des sessions de tâches et l'origine de chaque choix : explicite, préférence ou défaut OpenCode. Des préférences illisibles ou invalides bloquent la création avec une erreur demandant leur correction ou leur rechargement. Les réessais conservent les choix enregistrés à l'origine, même si vous modifiez les défauts. +Ces défauts s'appliquent aussi quand un agent prépare une mission : chaque profil de coordinateur ou de rôle omis utilise l'exception du scénario, puis le choix global ; le spécialiste global fournit les rôles de tâches, tandis que le juge de comparaison utilise par défaut le modèle du coordinateur. Un profil explicitement fourni prime en entier, y compris un choix de défauts OpenCode ou un agent seul. Pour le juge, tout modèle manquant est ensuite complété par le modèle connu du coordinateur, même avec un choix explicite ou enregistré de défauts OpenCode ou d'agent seul ; son propre modèle reste inchangé. Le juge conserve l'origine de son profil explicite ou enregistré ; un profil de juge omis hérite de l'origine du coordinateur. **Sessions des tâches** omis suit le même ordre de préférences, puis **Sous-agents natifs**. La réponse de création à l'agent donne les profils enregistrés, le mode des sessions de tâches et l'origine de chaque choix : explicite, préférence ou défaut OpenCode. Si le coordinateur, chaque rôle exact du scénario choisi et **Sessions des tâches** sont explicites, y compris les profils `{}`, les préférences du backend sont entièrement ignorées : toutes les origines sont explicites et leur disponibilité reste inobservée. Des préférences inutilisées illisibles ou invalides sont sans effet. Une sélection partielle ou omise lit les préférences du backend propriétaire ; si elles sont illisibles ou invalides, la création est alors bloquée avec une erreur demandant leur correction ou leur rechargement. Les réessais conservent les choix enregistrés à l'origine, même si vous modifiez les défauts. -Quand un agent crée une mission en pause avec `mission.inspect({ start })` sans backend CodeNomad propriétaire présent, il utilise les choix explicites et les défauts OpenCode, avec un avertissement indiquant que les préférences sont indisponibles. Les réessais conservent cet avertissement même si un backend apparaît ensuite. Plusieurs propriétaires, ou un propriétaire enregistré défaillant ou injoignable, bloquent la création. Les suivis préparés avec `mission.prepare` nécessitent un backend propriétaire pour les vérifications de création. +Lorsque les préférences sont nécessaires et qu'aucun backend CodeNomad propriétaire n'est présent, `mission.inspect({ start })` utilise les choix explicites et les défauts OpenCode, avec un avertissement de préférences indisponibles conservé lors des réessais, même si un backend apparaît ensuite. Un backend dont l'absence de lien avec ce projet est établie compte comme non-propriétaire, même avec d'autres espaces ouverts. Un enregistrement périmé dont la connexion est refusée compte comme absent. Plusieurs propriétaires, un échec réel de lecture de propriété, un délai dépassé ou une erreur HTTP/d'authentification bloquent la résolution des préférences. Les suivis préparés avec `mission.prepare` nécessitent un backend propriétaire pour les vérifications de création. 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. diff --git a/docs/help/he/missions.md b/docs/help/he/missions.md index 5f18771fa6..42c8942665 100644 --- a/docs/help/he/missions.md +++ b/docs/help/he/missions.md @@ -137,9 +137,9 @@ **ברירת מחדל מקורית** ו־**גלובלי** שונות: הראשונה מבקשת את ברירות המחדל של OpenCode עצמו, השנייה יורשת את הבחירה הגלובלית; בחירת ברירות מחדל מקוריות בהיקף של מדריך נשארת חריג מפורש. זמינות הקטלוג נבדקת; פרופיל מבוקש אינו הוכחה לפרופיל ששיחה משתמשת בו כרגע. אישורים מקוריים והעומק המוגדר עדיין שולטים בקריאות לעוזרים פנימיים בשני מצבי המטלות. -ברירות המחדל חלות גם כשסוכן מכין משימה: כל פרופיל מתאם או תפקיד שהושמט משתמש בחריג של מדריך העבודה, ואז בבחירה הגלובלית; המומחה הגלובלי מספק את תפקידי המטלות, ושופט ההשוואה משתמש כברירת מחדל במודל של המתאם. פרופיל שסופק במפורש מקבל עדיפות בשלמותו, גם בבחירת ברירות המחדל של OpenCode או סוכן בלבד. אצל השופט, מודל חסר מושלם לאחר מכן מהמודל הידוע של המתאם, גם בבחירה מפורשת או שמורה של ברירות המחדל של OpenCode או של סוכן בלבד; מודל משלו נשאר ללא שינוי. השופט שומר על מקור הפרופיל המפורש או השמור שלו; פרופיל שופט שהושמט יורש את מקור המתאם. **שיחות משימות** שהושמטו משתמשות באותו סדר העדפות ואז ב־**תת־סוכנים מקוריים**. תשובת היצירה לסוכן מפרטת את הפרופילים השמורים, מצב השיחות ומקור כל בחירה: מפורש, העדפה או ברירת מחדל של OpenCode. העדפות פגומות או בלתי קריאות חוסמות יצירה עם שגיאה המבקשת לתקן או לטעון אותן מחדש. ניסיונות חוזרים שומרים על הבחירות המקוריות גם אם תשנו את ברירות המחדל. +ברירות המחדל חלות גם כשסוכן מכין משימה: כל פרופיל מתאם או תפקיד שהושמט משתמש בחריג של מדריך העבודה, ואז בבחירה הגלובלית; המומחה הגלובלי מספק את תפקידי המטלות, ושופט ההשוואה משתמש כברירת מחדל במודל של המתאם. פרופיל שסופק במפורש מקבל עדיפות בשלמותו, גם בבחירת ברירות המחדל של OpenCode או סוכן בלבד. אצל השופט, מודל חסר מושלם לאחר מכן מהמודל הידוע של המתאם, גם בבחירה מפורשת או שמורה של ברירות המחדל של OpenCode או של סוכן בלבד; מודל משלו נשאר ללא שינוי. השופט שומר על מקור הפרופיל המפורש או השמור שלו; פרופיל שופט שהושמט יורש את מקור המתאם. **שיחות משימות** שהושמטו משתמשות באותו סדר העדפות ואז ב־**תת־סוכנים מקוריים**. תשובת היצירה לסוכן מפרטת את הפרופילים השמורים, מצב השיחות ומקור כל בחירה: מפורש, העדפה או ברירת מחדל של OpenCode. כשהמתאם, כל תפקיד מדויק במדריך העבודה הנבחר ו־**שיחות משימות** מצוינים במפורש, כולל פרופילי `{}`, מדלגים לחלוטין על העדפות השרת: כל המקורות מפורשים וזמינות ההעדפות נשארת בלתי נבדקת. העדפות פגומות או בלתי קריאות שאינן בשימוש אינן משפיעות. בחירה חלקית או מושמטת קוראת את העדפות השרת האחראי; העדפות פגומות או בלתי קריאות חוסמות אז יצירה עם שגיאה המבקשת לתקן או לטעון אותן מחדש. ניסיונות חוזרים שומרים על הבחירות המקוריות גם אם תשנו את ברירות המחדל. -כשסוכן יוצר משימה מושהית באמצעות `mission.inspect({ start })` ואין שרת CodeNomad אחראי, הוא משתמש בבחירות מפורשות ובברירות המחדל של OpenCode, עם אזהרה שההעדפות אינן זמינות. ניסיונות חוזרים שומרים על האזהרה גם אם שרת מופיע בהמשך. כמה שרתים אחראים, או שרת אחראי רשום שנכשל או שאינו נגיש, חוסמים יצירה. משימות המשך שמוכנות באמצעות `mission.prepare` דורשות שרת אחראי לבדיקות היצירה. +כשהעדפות נדרשות ואין שרת CodeNomad אחראי, `mission.inspect({ start })` משתמש בבחירות מפורשות ובברירות המחדל של OpenCode, עם אזהרת העדפות לא זמינות שנשמרת בניסיונות חוזרים גם אם שרת מופיע בהמשך. שרת שהוכח שאינו קשור לפרויקט נחשב ללא אחראי גם כשסביבות עבודה אחרות פתוחות. רישום מיושן שהחיבור אליו נדחה נחשב לחסר. כמה שרתים אחראים, כשל ממשי בקריאת השיוך, חריגה מזמן ההמתנה או שגיאות HTTP/אימות חוסמים את בירור ההעדפות. משימות המשך שמוכנות באמצעות `mission.prepare` דורשות שרת אחראי לבדיקות היצירה. כל רשימת **מודל** מציגה את מה שמציג בורר **מודל** של השיחה, באותם שמות ומקובצת לפי ספק: מודלים מוסתרים אינם מופיעים, ובזמן שסינון למועדפים בלבד פעיל גם שאר המודלים אינם מופיעים (ראו [נראות מודלים, מועדפים וחשיבה](providers.md#models)). גם מודלים ללא תמיכה בכלים אינם מופיעים. מודל שמור שאינו ברשימה נשאר נבחר. **לא זמין** מסמן מודל שמור שהבורר אינו יכול להציע כעת: הוא חסר בקטלוג הנוכחי של הפרויקט, הוצא משימוש או אינו תומך בכלים. diff --git a/docs/help/ja/missions.md b/docs/help/ja/missions.md index 64642da769..2a68043123 100644 --- a/docs/help/ja/missions.md +++ b/docs/help/ja/missions.md @@ -137,9 +137,9 @@ CodeNomad の実行中は、ミッションのコーディネーターやタス **ネイティブの既定値** と **グローバル** は異なります。前者は OpenCode 自身の既定値を要求し、後者はグローバルの選択を継承します。プレイブックの範囲でネイティブの既定値を選ぶことは、引き続き明示的な例外になります。カタログ上の利用可否を確認しますが、要求したプロファイルは、会話が現在使用するプロファイルの証拠ではありません。どちらのタスクモードでも、内部ヘルパーの呼び出しにはネイティブ権限と設定済みの深さが適用されます。 -エージェントがミッションを準備する場合も、これらの既定値が適用されます。省略されたコーディネーターや役割のプロファイルには、プレイブックの例外、グローバルの選択の順で適用します。タスクの各役割にはグローバルのスペシャリストを使用し、比較の審査役には既定でコーディネーターのモデルを使用します。明示されたプロファイルは全体として優先され、OpenCode の既定値やエージェントのみの指定も含みます。審査役のモデルが未指定なら、その後で既知のコーディネーターのモデルを補います。明示または保存された OpenCode の既定値やエージェントのみの指定も対象で、審査役独自のモデルはそのまま保持します。審査役は明示または保存されたプロファイルの出所を保持し、審査役のプロファイル自体が省略された場合はコーディネーターの出所を継承します。省略された **タスクセッション** も同じ順で設定を適用し、最後に **ネイティブのサブエージェント** を使用します。エージェントへの作成応答には、保存されたプロファイル、タスクセッションのモード、各選択の出所(明示、設定、OpenCode の既定値)が表示されます。設定が読み取れない、または無効な場合は、修正や再読み込みを求めるエラーで作成を中断します。既定値を変更しても、再試行では元の保存済みの選択を保持します。 +エージェントがミッションを準備する場合も、これらの既定値が適用されます。省略されたコーディネーターや役割のプロファイルには、プレイブックの例外、グローバルの選択の順で適用します。タスクの各役割にはグローバルのスペシャリストを使用し、比較の審査役には既定でコーディネーターのモデルを使用します。明示されたプロファイルは全体として優先され、OpenCode の既定値やエージェントのみの指定も含みます。審査役のモデルが未指定なら、その後で既知のコーディネーターのモデルを補います。明示または保存された OpenCode の既定値やエージェントのみの指定も対象で、審査役独自のモデルはそのまま保持します。審査役は明示または保存されたプロファイルの出所を保持し、審査役のプロファイル自体が省略された場合はコーディネーターの出所を継承します。省略された **タスクセッション** も同じ順で設定を適用し、最後に **ネイティブのサブエージェント** を使用します。エージェントへの作成応答には、保存されたプロファイル、タスクセッションのモード、各選択の出所(明示、設定、OpenCode の既定値)が表示されます。コーディネーター、選択したプレイブックのすべての正確な役割、**タスクセッション** が明示されている場合は、`{}` のプロファイルも明示指定として数え、バックエンドの設定を完全に省略します。出所はすべて明示となり、設定の利用可否は未確認のままです。使用しない設定が読み取れない、または無効でも影響しません。一部または全体が省略された選択では担当バックエンドの設定を読み、読み取れない、または無効な場合は修正や再読み込みを求めるエラーで作成を中断します。既定値を変更しても、再試行では元の保存済みの選択を保持します。 -エージェントが `mission.inspect({ start })` で一時停止中のミッションを作成し、担当する CodeNomad バックエンドが存在しない場合は、明示した選択と OpenCode の既定値を使用し、設定を利用できない旨の警告を返します。後でバックエンドが現れても、再試行ではこの警告を保持します。担当が複数いる場合や、登録済みの担当で障害が発生した場合、または接続できない場合は、作成を中断します。`mission.prepare` による後続ミッションの準備には、作成時の確認を行う担当バックエンドが必要です。 +設定が必要で担当する CodeNomad バックエンドが存在しない場合、`mission.inspect({ start })` は明示した選択と OpenCode の既定値を使用し、設定を利用できない旨の警告を返します。後でバックエンドが現れても、再試行ではこの警告を保持します。このプロジェクトと無関係だと確認されたバックエンドは、ほかのワークスペースが開いていても担当外として扱います。接続が拒否される古い登録は不在として扱います。担当が複数いる場合、実際の所有関係の読み取り失敗、タイムアウト、HTTP・認証エラーでは設定の解決を中断します。`mission.prepare` による後続ミッションの準備には、作成時の確認を行う担当バックエンドが必要です。 各 **モデル** リストには、会話の **モデル** セレクターと同じモデルが同じ名前でプロバイダーごとに表示されます。非表示のモデルは含まれず、お気に入りのみの絞り込みが有効な間はお気に入り以外のモデルも含まれません([モデルの表示、お気に入り、思考](providers.md#models) を参照)。ツールに対応していないモデルも含まれません。リストにない保存済みのモデルは選択されたまま残ります。**利用不可** は、プロジェクトの現在のカタログにない、非推奨である、またはツールに対応していないため、セレクターが現在提供できない保存済みのモデルに付きます。 diff --git a/docs/help/ne/missions.md b/docs/help/ne/missions.md index 1f325a9d8d..491fa259fa 100644 --- a/docs/help/ne/missions.md +++ b/docs/help/ne/missions.md @@ -137,9 +137,9 @@ CodeNomad चलिरहँदा, project का हरेक agent कुर **नेटिभ पूर्वनिर्धारित** र **विश्वव्यापी** फरक हुन्: पहिलोले OpenCode का आफ्नै default माग्छ, दोस्रोले global चयन inherit गर्छ; playbook दायरामा native default रोज्नु स्पष्ट exception नै रहन्छ। catalogue उपलब्धता जाँचिन्छ; requested profile कुराकानीले अहिले प्रयोग गरिरहेको profile को प्रमाण होइन। दुवै task mode का internal helper मा native permission र configured depth लागू रहन्छन्। -एजेन्टले मिसन तयार गर्दा पनि यी पूर्वनिर्धारित मान लागू हुन्छन्: छुटाइएको समन्वयकर्ता वा भूमिकाको प्रोफाइलमा पहिले प्लेबुकको अपवाद, त्यसपछि विश्वव्यापी चयन प्रयोग हुन्छ। कार्य भूमिकामा विश्वव्यापी विशेषज्ञ प्रयोग हुन्छ; तुलना गर्ने निर्णायकले पूर्वनिर्धारित रूपमा समन्वयकर्ताको मोडेल प्रयोग गर्छ। स्पष्ट रूपमा दिइएको प्रोफाइलले पूर्ण रूपमा प्राथमिकता पाउँछ, OpenCode का पूर्वनिर्धारित मान वा एजेन्ट मात्र रोजेको अवस्थामा पनि। निर्णायकको मोडेल छुटेको भए त्यसपछि समन्वयकर्ताको ज्ञात मोडेलबाट पूरा गरिन्छ, स्पष्ट वा सुरक्षित OpenCode पूर्वनिर्धारित मान वा एजेन्ट मात्रको चयनमा पनि; निर्णायकको आफ्नै मोडेल यथावत् रहन्छ। निर्णायकले आफ्नो स्पष्ट वा सुरक्षित प्रोफाइलको स्रोत कायम राख्छ; निर्णायकको प्रोफाइल नै छुटेको भए समन्वयकर्ताको स्रोत लिन्छ। छुटाइएको **कार्य सत्रहरू** मा उही प्राथमिकता क्रमपछि **नेटिभ उपएजेन्टहरू** प्रयोग हुन्छ। एजेन्टलाई फर्काइएको सिर्जना जवाफमा सुरक्षित प्रोफाइल, कार्य सत्रको मोड र हरेक चयनको स्रोत हुन्छ: स्पष्ट, प्राथमिकता वा OpenCode को पूर्वनिर्धारित मान। पढ्न नसकिने वा अमान्य प्राथमिकताले सुधार वा पुनः लोड गर्नुपर्ने त्रुटिसहित सिर्जना रोक्छन्। पूर्वनिर्धारित मान बदले पनि पुनःप्रयासले सुरुका सुरक्षित चयन कायम राख्छ। +एजेन्टले मिसन तयार गर्दा पनि यी पूर्वनिर्धारित मान लागू हुन्छन्: छुटाइएको समन्वयकर्ता वा भूमिकाको प्रोफाइलमा पहिले प्लेबुकको अपवाद, त्यसपछि विश्वव्यापी चयन प्रयोग हुन्छ। कार्य भूमिकामा विश्वव्यापी विशेषज्ञ प्रयोग हुन्छ; तुलना गर्ने निर्णायकले पूर्वनिर्धारित रूपमा समन्वयकर्ताको मोडेल प्रयोग गर्छ। स्पष्ट रूपमा दिइएको प्रोफाइलले पूर्ण रूपमा प्राथमिकता पाउँछ, OpenCode का पूर्वनिर्धारित मान वा एजेन्ट मात्र रोजेको अवस्थामा पनि। निर्णायकको मोडेल छुटेको भए त्यसपछि समन्वयकर्ताको ज्ञात मोडेलबाट पूरा गरिन्छ, स्पष्ट वा सुरक्षित OpenCode पूर्वनिर्धारित मान वा एजेन्ट मात्रको चयनमा पनि; निर्णायकको आफ्नै मोडेल यथावत् रहन्छ। निर्णायकले आफ्नो स्पष्ट वा सुरक्षित प्रोफाइलको स्रोत कायम राख्छ; निर्णायकको प्रोफाइल नै छुटेको भए समन्वयकर्ताको स्रोत लिन्छ। छुटाइएको **कार्य सत्रहरू** मा उही प्राथमिकता क्रमपछि **नेटिभ उपएजेन्टहरू** प्रयोग हुन्छ। एजेन्टलाई फर्काइएको सिर्जना जवाफमा सुरक्षित प्रोफाइल, कार्य सत्रको मोड र हरेक चयनको स्रोत हुन्छ: स्पष्ट, प्राथमिकता वा OpenCode को पूर्वनिर्धारित मान। समन्वयकर्ता, छानिएको प्लेबुकका हरेक ठ्याक्कै भूमिका र **कार्य सत्रहरू** स्पष्ट भएमा, `{}` प्रोफाइलसमेत स्पष्ट मानी backend प्राथमिकता पूरै छोडिन्छ: सबै स्रोत स्पष्ट हुन्छन् र प्राथमिकताको उपलब्धता जाँच नगरिएकै रहन्छ। प्रयोग नभएका पढ्न नसकिने वा अमान्य प्राथमिकता असान्दर्भिक हुन्छन्। आंशिक वा छुटाइएका चयनले जिम्मेवार backend का प्राथमिकता पढ्छन्; त्यसबेला पढ्न नसकिने वा अमान्य प्राथमिकताले सुधार वा पुनः लोड गर्नुपर्ने त्रुटिसहित सिर्जना रोक्छन्। पूर्वनिर्धारित मान बदले पनि पुनःप्रयासले सुरुका सुरक्षित चयन कायम राख्छ। -एजेन्टले `mission.inspect({ start })` बाट रोकिएको मिसन सिर्जना गर्दा जिम्मेवार CodeNomad backend उपस्थित छैन भने स्पष्ट चयन र OpenCode का पूर्वनिर्धारित मान प्रयोग हुन्छन्, र प्राथमिकता उपलब्ध नभएको चेतावनी फर्काइन्छ। पछि backend आए पनि पुनःप्रयासमा त्यो चेतावनी कायम रहन्छ। धेरै जिम्मेवार backend, वा दर्ता भएको जिम्मेवार backend असफल वा पहुँचबाहिर भएमा सिर्जना रोकिन्छ। `mission.prepare` बाट तयार गरिने पछिल्ला मिसनका सिर्जना जाँचका लागि जिम्मेवार backend आवश्यक हुन्छ। +प्राथमिकता आवश्यक हुँदा जिम्मेवार CodeNomad backend उपस्थित छैन भने `mission.inspect({ start })` ले स्पष्ट चयन र OpenCode का पूर्वनिर्धारित मान प्रयोग गर्छ, र प्राथमिकता उपलब्ध नभएको चेतावनी फर्काउँछ। पछि backend आए पनि पुनःप्रयासमा त्यो चेतावनी कायम रहन्छ। यस परियोजनासँग असम्बन्धित प्रमाणित backend अरू कार्यक्षेत्र खुला हुँदा पनि जिम्मेवार मानिँदैन। जडान अस्वीकार भएको पुरानो दर्ता अनुपस्थित मानिन्छ। धेरै जिम्मेवार backend, स्वामित्व पढ्दाको वास्तविक असफलता, समयसीमा नाघ्नु वा HTTP/प्रमाणीकरण त्रुटिले प्राथमिकता निर्धारण रोक्छन्। `mission.prepare` बाट तयार गरिने पछिल्ला मिसनका सिर्जना जाँचका लागि जिम्मेवार backend आवश्यक हुन्छ। प्रत्येक **मोडेल** सूचीले कुराकानीको **मोडेल** selector ले देखाउने मोडेलहरू उही नाममा, provider अनुसार समूहबद्ध गरी देखाउँछ: लुकाइएका मोडेलहरू समावेश हुँदैनन्, र favorites-only filtering सक्रिय रहँदा अन्य मोडेलहरू पनि समावेश हुँदैनन् ([मोडेल दृश्यता, मनपर्ने र Thinking](providers.md#models) हेर्नुहोस्)। tool support नभएका मोडेलहरू पनि समावेश हुँदैनन्। सूचीबाहिरको saved मोडेल चयन गरिएकै रहन्छ। selector ले अहिले दिन नसक्ने saved मोडेललाई **उपलब्ध छैन** ले चिन्ह लगाउँछ: त्यो project को हालको catalogue मा छैन, deprecated छ, वा tool support छैन। diff --git a/docs/help/ru/missions.md b/docs/help/ru/missions.md index b44a5d016a..2493d54788 100644 --- a/docs/help/ru/missions.md +++ b/docs/help/ru/missions.md @@ -137,9 +137,9 @@ **Нативное значение по умолчанию** и **Глобально** различаются: первое запрашивает собственные значения OpenCode, второе наследует глобальный выбор; выбор нативных значений в области сценария остаётся явным исключением. Доступность каталога проверяется; запрошенный профиль не доказывает текущий профиль разговора. Нативные разрешения и настроенная глубина по-прежнему управляют внутренними вызовами помощников в обоих режимах задач. -Эти настройки действуют и при подготовке миссии агентом: каждый пропущенный профиль координатора или роли использует исключение сценария, затем глобальный выбор; глобальный специалист задаёт профили ролей задач, а судья сравнения по умолчанию использует модель координатора. Явно указанный профиль имеет приоритет целиком, включая выбор значений OpenCode или только агента. Затем отсутствующая модель судьи дополняется известной моделью координатора, даже при явном или сохранённом выборе значений OpenCode или только агента; собственная модель судьи остаётся неизменной. Судья сохраняет источник своего явного или сохранённого профиля; если профиль судьи пропущен, он наследует источник координатора. Пропущенные **Сессии задач** следуют тому же порядку настроек, затем используют **Нативные субагенты**. Ответ агенту при создании содержит сохранённые профили, режим сессий задач и источник каждого выбора: явный, настройка или значение OpenCode по умолчанию. Нечитаемые или недопустимые настройки блокируют создание с ошибкой, предлагающей исправить или перезагрузить их. Повторные попытки сохраняют исходный выбор даже после изменения настроек по умолчанию. +Эти настройки действуют и при подготовке миссии агентом: каждый пропущенный профиль координатора или роли использует исключение сценария, затем глобальный выбор; глобальный специалист задаёт профили ролей задач, а судья сравнения по умолчанию использует модель координатора. Явно указанный профиль имеет приоритет целиком, включая выбор значений OpenCode или только агента. Затем отсутствующая модель судьи дополняется известной моделью координатора, даже при явном или сохранённом выборе значений OpenCode или только агента; собственная модель судьи остаётся неизменной. Судья сохраняет источник своего явного или сохранённого профиля; если профиль судьи пропущен, он наследует источник координатора. Пропущенные **Сессии задач** следуют тому же порядку настроек, затем используют **Нативные субагенты**. Ответ агенту при создании содержит сохранённые профили, режим сессий задач и источник каждого выбора: явный, настройка или значение OpenCode по умолчанию. Если координатор, каждая точная роль выбранного сценария и **Сессии задач** заданы явно, включая профили `{}`, настройки сервера полностью пропускаются: все источники явные, а доступность настроек остаётся непроверенной. Неиспользуемые нечитаемые или недопустимые настройки не влияют на выбор. Частичный или пропущенный выбор читает настройки ответственного сервера; нечитаемые или недопустимые настройки тогда блокируют создание с ошибкой, предлагающей исправить или перезагрузить их. Повторные попытки сохраняют исходный выбор даже после изменения настроек по умолчанию. -Когда агент создаёт приостановленную миссию через `mission.inspect({ start })` без ответственного сервера CodeNomad, используются явные настройки и значения OpenCode по умолчанию с предупреждением о недоступности настроек. Повторные попытки сохраняют это предупреждение, даже если сервер появится позже. Несколько ответственных серверов либо сбой или недоступность зарегистрированного ответственного сервера блокируют создание. Подготовка последующих миссий через `mission.prepare` требует ответственного сервера для проверок создания. +Когда нужны настройки, а ответственного сервера CodeNomad нет, `mission.inspect({ start })` использует явный выбор и значения OpenCode по умолчанию с предупреждением о недоступности настроек. Повторные попытки сохраняют это предупреждение, даже если сервер появится позже. Сервер с доказанным отсутствием связи с этим проектом считается неответственным, даже если открыты другие рабочие пространства. Устаревшая регистрация с отказом в соединении считается отсутствующей. Несколько ответственных серверов, реальные ошибки чтения принадлежности, тайм-ауты или ошибки HTTP/аутентификации блокируют разрешение настроек. Подготовка последующих миссий через `mission.prepare` требует ответственного сервера для проверок создания. Каждый список **Модель** показывает то же, что переключатель **Модель** разговора, под теми же названиями и с группировкой по провайдерам: скрытые модели не показываются, а пока включена фильтрация только по избранному — и остальные модели (см. [Видимость моделей, избранное и мышление](providers.md#models)). Модели без поддержки инструментов тоже не показываются. Сохранённая модель вне списка остаётся выбранной. **Недоступно** отмечает сохранённую модель, которую переключатель сейчас не может предложить: её нет в текущем каталоге проекта, она устарела или не поддерживает инструменты. diff --git a/docs/help/tr/missions.md b/docs/help/tr/missions.md index a2655d9140..de0bc08a95 100644 --- a/docs/help/tr/missions.md +++ b/docs/help/tr/missions.md @@ -137,9 +137,9 @@ 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. -Bir ajan görev hazırlarken de bu varsayılanlar uygulanır: belirtilmeyen her koordinatör veya rol profili önce rehber istisnasını, ardından genel seçimi kullanır; genel uzman görev rollerini sağlar, karşılaştırma hakemi ise varsayılan olarak koordinatörün modelini kullanır. Açıkça verilen profil, OpenCode varsayılanı veya yalnızca ajan seçimi dahil, bütünüyle önceliklidir. Hakemin eksik modeli daha sonra koordinatörün bilinen modeliyle tamamlanır; açık veya kayıtlı OpenCode varsayılanı ya da yalnızca ajan seçimi de buna dahildir, hakemin kendi modeli ise korunur. Hakem açık veya kayıtlı profilinin kaynağını korur; hakem profili belirtilmemişse koordinatörün kaynağını devralır. Belirtilmeyen **Görev oturumları** aynı tercih sırasını, ardından **Yerel alt ajanlar** seçimini kullanır. Ajana dönen oluşturma yanıtı kayıtlı profilleri, görev oturumu modunu ve her seçimin kaynağını listeler: açık seçim, tercih veya OpenCode varsayılanı. Okunamayan veya geçersiz tercihler, düzeltme ya da yeniden yükleme isteyen bir hatayla oluşturmayı engeller. Varsayılanları değiştirseniz bile yeniden denemeler ilk kaydedilen seçimleri korur. +Bir ajan görev hazırlarken de bu varsayılanlar uygulanır: belirtilmeyen her koordinatör veya rol profili önce rehber istisnasını, ardından genel seçimi kullanır; genel uzman görev rollerini sağlar, karşılaştırma hakemi ise varsayılan olarak koordinatörün modelini kullanır. Açıkça verilen profil, OpenCode varsayılanı veya yalnızca ajan seçimi dahil, bütünüyle önceliklidir. Hakemin eksik modeli daha sonra koordinatörün bilinen modeliyle tamamlanır; açık veya kayıtlı OpenCode varsayılanı ya da yalnızca ajan seçimi de buna dahildir, hakemin kendi modeli ise korunur. Hakem açık veya kayıtlı profilinin kaynağını korur; hakem profili belirtilmemişse koordinatörün kaynağını devralır. Belirtilmeyen **Görev oturumları** aynı tercih sırasını, ardından **Yerel alt ajanlar** seçimini kullanır. Ajana dönen oluşturma yanıtı kayıtlı profilleri, görev oturumu modunu ve her seçimin kaynağını listeler: açık seçim, tercih veya OpenCode varsayılanı. Koordinatör, seçilen rehberin her tam rolü ve **Görev oturumları**, `{}` profilleri dahil açıkça verilirse arka uç tercihleri tamamen atlanır: tüm kaynaklar açık seçimdir ve tercih kullanılabilirliği gözlemlenmeden kalır. Kullanılmayan okunamayan veya geçersiz tercihler etkisizdir. Kısmi veya belirtilmeyen seçimler sorumlu arka ucun tercihlerini okur; okunamayan veya geçersiz tercihler bu durumda düzeltme ya da yeniden yükleme isteyen bir hatayla oluşturmayı engeller. Varsayılanları değiştirseniz bile yeniden denemeler ilk kaydedilen seçimleri korur. -Bir ajan `mission.inspect({ start })` ile duraklatılmış bir görev oluştururken sorumlu CodeNomad arka ucu yoksa açık seçimler ve OpenCode varsayılanları kullanılır; tercihlerin kullanılamadığına dair bir uyarı döner. Daha sonra bir arka uç belirse bile yeniden denemeler bu uyarıyı korur. Birden fazla sorumlu arka uç ya da kayıtlı sorumlu arka ucun hata vermesi veya erişilememesi oluşturmayı engeller. `mission.prepare` ile hazırlanan takip görevleri, oluşturma denetimleri için sorumlu bir arka uç gerektirir. +Tercihler gerektiğinde sorumlu CodeNomad arka ucu yoksa `mission.inspect({ start })` açık seçimleri ve OpenCode varsayılanlarını kullanır; tercihlerin kullanılamadığına dair uyarı, daha sonra bir arka uç belirse bile yeniden denemelerde korunur. Bu projeyle ilgisiz olduğu kanıtlanan arka uç, başka çalışma alanları açık olsa da sorumlu sayılmaz. Bağlantısı reddedilen eski kayıt yok sayılır. Birden fazla sorumlu arka uç, gerçek sahiplik okuma hataları, zaman aşımları veya HTTP/kimlik doğrulama hataları tercih çözümlemesini engeller. `mission.prepare` ile hazırlanan takip görevleri, oluşturma denetimleri için sorumlu bir arka uç gerektirir. 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. diff --git a/docs/help/zh-Hans/missions.md b/docs/help/zh-Hans/missions.md index e65db292e7..67136ffe86 100644 --- a/docs/help/zh-Hans/missions.md +++ b/docs/help/zh-Hans/missions.md @@ -137,9 +137,9 @@ CodeNomad 运行期间,项目中的每个智能体对话(包括任务协调 **原生默认值**与**全局**不同:前者请求 OpenCode 自身的默认值,后者继承全局选择;在剧本范围中选择原生默认值仍是显式例外。会检查目录可用性;请求的配置不证明对话当前实际使用的配置。两种任务模式下,内部辅助调用仍受原生权限和配置深度约束。 -智能体准备任务时也会应用这些默认设置:省略的协调者或角色配置先使用剧本例外,再使用全局选择;全局专家配置用于任务角色,比较裁判默认使用协调者的模型。显式提供的配置作为整体优先,包括选择 OpenCode 默认值或仅指定代理的情况。随后,裁判缺失的模型会用协调者已知的模型补全,即使显式或已保存的选择为 OpenCode 默认值或仅指定代理;裁判自身已指定的模型保持不变。裁判保留其显式或已保存配置的来源;裁判配置整体省略时,继承协调者的来源。省略的**任务会话**采用相同的偏好顺序,最后使用**原生子代理**。返回给智能体的创建响应列出已保存的配置、任务会话模式及每项选择的来源:显式指定、偏好或 OpenCode 默认值。偏好无法读取或无效时,创建会被阻止,并返回要求修正或重新加载的错误。即使修改默认设置,重试也会保留最初保存的选择。 +智能体准备任务时也会应用这些默认设置:省略的协调者或角色配置先使用剧本例外,再使用全局选择;全局专家配置用于任务角色,比较裁判默认使用协调者的模型。显式提供的配置作为整体优先,包括选择 OpenCode 默认值或仅指定代理的情况。随后,裁判缺失的模型会用协调者已知的模型补全,即使显式或已保存的选择为 OpenCode 默认值或仅指定代理;裁判自身已指定的模型保持不变。裁判保留其显式或已保存配置的来源;裁判配置整体省略时,继承协调者的来源。省略的**任务会话**采用相同的偏好顺序,最后使用**原生子代理**。返回给智能体的创建响应列出已保存的配置、任务会话模式及每项选择的来源:显式指定、偏好或 OpenCode 默认值。如果协调者、所选剧本的每个确切角色和**任务会话**均显式指定(包括 `{}` 配置槽位),则完全跳过后端偏好:所有来源均为显式指定,偏好可用性保持未观测状态。未使用的偏好即使无法读取或无效也不影响选择。部分指定或省略的选择仍读取所属后端的偏好;此时偏好无法读取或无效会阻止创建,并返回要求修正或重新加载的错误。即使修改默认设置,重试也会保留最初保存的选择。 -智能体通过 `mission.inspect({ start })` 创建暂停的任务时,如果没有所属的 CodeNomad 后端,会使用显式选择和 OpenCode 默认值,并返回偏好不可用的警告。即使后续出现后端,重试仍保留该警告。存在多个所属后端,或已注册的所属后端发生故障或无法访问时,创建会被阻止。通过 `mission.prepare` 准备后续任务需要所属后端执行创建检查。 +需要偏好且没有所属的 CodeNomad 后端时,`mission.inspect({ start })` 使用显式选择和 OpenCode 默认值,并返回偏好不可用的警告;即使后续出现后端,重试仍保留该警告。已证实与本项目无关的后端,即使打开了其他工作区,也算非所属后端。连接被拒绝的过期注册视为不存在。存在多个所属后端、实际的归属读取失败、超时或 HTTP/身份验证错误时,偏好解析会被阻止。通过 `mission.prepare` 准备后续任务需要所属后端执行创建检查。 每个**模型**列表显示的内容与对话的**模型**选择器相同,名称一致并按提供商分组:不包含已隐藏的模型;启用仅收藏筛选时,也不包含其他模型(参见[模型可见性、收藏和思考](providers.md#models))。不支持工具的模型同样不包含。列表之外的已保存模型仍保持选中。选择器当前无法提供的已保存模型标记为**不可用**:它不在项目当前的目录中、已弃用或不支持工具。 diff --git a/packages/server/src/missions/control.ts b/packages/server/src/missions/control.ts index 6bf1078437..c247f74e37 100644 --- a/packages/server/src/missions/control.ts +++ b/packages/server/src/missions/control.ts @@ -10,6 +10,7 @@ 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" @@ -426,12 +427,17 @@ export class MissionControl { return { ...input, profiles: frozen.profiles, taskMode: frozen.taskMode, creationDefaults: frozen } } const resolve = this.options.transport?.resolveCreationDefaults - // Internal journal-only consumers supply their own frozen profiles. Desktop - // tools always install the authenticated owning-backend resolver. - if (!resolve) return input const request = missionCreationChoices(input) - const selection = parseMissionCreationSelection(input.template, await resolve(sessionID, { template: input.template, ...request, - ...(coordinatorModel === undefined ? {} : { coordinatorModel }) })) + 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 + } return { ...input, profiles: selection.profiles, taskMode: selection.taskMode, creationDefaults: { request, ...selection } } } diff --git a/packages/server/src/missions/coordinator-actions.test.ts b/packages/server/src/missions/coordinator-actions.test.ts index 5e438eab9d..3566304a03 100644 --- a/packages/server/src/missions/coordinator-actions.test.ts +++ b/packages/server/src/missions/coordinator-actions.test.ts @@ -290,6 +290,26 @@ test("an explicit cross-playbook profile fails before reading user preferences", 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" }) + assert.deepEqual(result.mission!.creationDefaults?.origins, { coordinator: "explicit", roles: { specialist: "explicit" }, taskMode: "explicit" }) + assert.equal(result.mission!.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" } } }] }) } }) diff --git a/packages/server/src/missions/creation-defaults.test.ts b/packages/server/src/missions/creation-defaults.test.ts index 61329919a7..05fe18c696 100644 --- a/packages/server/src/missions/creation-defaults.test.ts +++ b/packages/server/src/missions/creation-defaults.test.ts @@ -3,13 +3,20 @@ 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 } from "./creation-defaults" +import { missionCreationDefaultsSchema, missionCreationDefaultsWire, missionCreationSelection, parseMissionCreationDefaults, parseMissionCreationDefaultsInput } 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, resolveMissionCreationDefaults } from "./profile-defaults" import { CODENOMAD_MISSIONS_RPC } from "./rpc" -import { freezeCompareProfiles } from "./playbook-profiles" +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() diff --git a/packages/server/src/missions/creation-defaults.ts b/packages/server/src/missions/creation-defaults.ts index 50248db63d..187e030f6d 100644 --- a/packages/server/src/missions/creation-defaults.ts +++ b/packages/server/src/missions/creation-defaults.ts @@ -7,9 +7,11 @@ import { MissionControlError } from "./control-error" import { parseExecution } from "./execution" const origin = z.enum(MISSION_DEFAULT_ORIGINS) +export const missionCreationTemplateSchema = z.enum(Object.keys(missionProfileRoles) as [MissionTemplateId, ...MissionTemplateId[]]) +export const MISSION_DEFAULTS_REQUEST_INVALID = "Correct the profile-defaults request: use a supported template, valid profiles and taskMode, and a complete coordinatorModel" export const missionCreationChoicesSchema = z.object({ profiles: missionProfilesInputSchema, taskMode: missionTaskModeInputSchema.optional() }).strict() const defaultsInputSchema = missionCreationChoicesSchema.extend({ - template: z.enum(["custom", "wayfinder", "debug", "delivery", "compare"]), + 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 } @@ -18,7 +20,7 @@ const defaultsInputSchema = missionCreationChoicesSchema.extend({ export function parseMissionCreationDefaultsInput(input: unknown) { const parsed = defaultsInputSchema.safeParse(input) - if (!parsed.success) throw new MissionControlError("Correct the profile-defaults request: use a supported template, valid profiles and taskMode, and a complete coordinatorModel", "invalid-execution") + 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 diff --git a/packages/server/src/missions/creation-intent.test.ts b/packages/server/src/missions/creation-intent.test.ts index a04c094168..6cc4fbc7d9 100644 --- a/packages/server/src/missions/creation-intent.test.ts +++ b/packages/server/src/missions/creation-intent.test.ts @@ -91,12 +91,23 @@ test("settled choices release capacity on adapters without key removal", async ( assert.equal([...f.values.values()].filter(value => value !== null).length, 1) }) -test("an un-timestamped valid intention gets one bounded retention window", async () => { - const f = fixture() - f.values.set("codenomad-missions/v2/creation-intents/project/msn_old", { version: 1, request, defaults } as unknown as MissionJsonValue) - assert.deepEqual(await f.intents.read("msn_old", request, missing, "request-conflict"), defaults) - f.advance(MISSION_CREATION_INTENT_RETENTION_MS) - assert.equal(await f.intents.read("msn_old", request, missing, "request-conflict"), undefined) +test("direct reads and capacity scans reject malformed intentions without changing retained bytes", 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) + const before = structuredClone([...f.values]) + await assert.rejects(f.intents.read("msn_invalid", request, missing, "request-conflict"), + (error: any) => error.code === "invalid-journal") + await assert.rejects(f.intents.save("msn_new", request, defaults, missing, () => {}, "request-conflict"), + (error: any) => error.code === "invalid-journal") + assert.deepEqual([...f.values], before) + } }) test("failed choice cleanup cannot replace an authoritative success or refusal", async () => { diff --git a/packages/server/src/missions/creation-intent.ts b/packages/server/src/missions/creation-intent.ts index 3457c20a8c..18f62cd117 100644 --- a/packages/server/src/missions/creation-intent.ts +++ b/packages/server/src/missions/creation-intent.ts @@ -1,7 +1,7 @@ import { z } from "zod" import type { MissionStartInput } from "./control-types" import { MissionControlError } from "./control-error" -import { missionCreationChoices, missionCreationChoicesSchema, parseMissionCreationDefaults, sameMissionCreationChoices, +import { missionCreationChoices, missionCreationChoicesSchema, missionCreationTemplateSchema, parseMissionCreationDefaults, sameMissionCreationChoices, type MissionCreationMetadata } from "./creation-defaults" import { runMissionExclusive } from "./exclusive" import type { MissionStorage } from "./journal" @@ -10,9 +10,9 @@ import type { MissionEvent, MissionJsonValue } from "./model" type Request = MissionStartInput & { title?: string } const requestSchema = missionCreationChoicesSchema.extend({ objective: z.string().min(1).max(20_000), title: z.string().min(1).max(60).optional(), notes: z.string().max(20_000).optional(), - template: z.enum(["custom", "debug", "wayfinder", "delivery", "compare"]) }).strict() + template: missionCreationTemplateSchema }).strict() const intentSchema = z.object({ version: z.literal(1), request: requestSchema, defaults: z.unknown(), - createdAt: z.number().finite().nonnegative().optional() }).strict() + 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 @@ -22,6 +22,15 @@ const originalRequest = (input: Request, defaults: MissionCreationMetadata): Req ...(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 @@ -36,17 +45,10 @@ export class MissionCreationIntents { 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 - let saved: z.infer, defaults: MissionCreationMetadata - try { - saved = intentSchema.parse(raw) - defaults = parseMissionCreationDefaults(saved.request.template, saved.defaults) - if (!sameMissionCreationChoices(saved.request, defaults.request)) throw new Error("Invalid original choices") - } catch { throw new MissionControlError("Mission creation intent is unreadable; existing data is retained", "invalid-journal") } + const saved = parseIntent(raw) if (this.expired(saved.createdAt)) { await this.clear(missionID); return undefined } - if (saved.createdAt === undefined) await this.storage.set(this.prefix + missionID, - JSON.parse(JSON.stringify({ ...saved, createdAt: this.now() })) as MissionJsonValue) if (!sameRequest(saved.request, request)) this.conflict(conflict) - return defaults + return saved.defaults } private fromEvent(event: MissionEvent | undefined, request: Request, conflict: string) { @@ -65,8 +67,8 @@ export class MissionCreationIntents { return this.fromEvent(await created(), request, conflict) ?? await this.recorded(missionID, request, conflict) } - private expired(createdAt?: number): boolean { - return createdAt !== undefined && (this.now() - createdAt >= MISSION_CREATION_INTENT_RETENTION_MS || createdAt > this.now()) + private expired(createdAt: number): boolean { + return this.now() - createdAt >= MISSION_CREATION_INTENT_RETENTION_MS || createdAt > this.now() } private async activeCount(): Promise { @@ -76,21 +78,9 @@ export class MissionCreationIntents { 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 - const parsed = intentSchema.safeParse(entry.value) - let valid = parsed.success - if (parsed.success) { - try { - const defaults = parseMissionCreationDefaults(parsed.data.request.template, parsed.data.defaults) - valid = sameMissionCreationChoices(parsed.data.request, defaults.request) - } catch { valid = false } - } - if (!valid) throw new MissionControlError("Mission preparation storage is unreadable; existing data is retained", "invalid-journal") - if (parsed.success && valid && this.expired(parsed.data.createdAt)) await this.clear(entry.key.slice(this.prefix.length)) - else { - if (parsed.success && valid && parsed.data.createdAt === undefined) await this.storage.set(entry.key, - JSON.parse(JSON.stringify({ ...parsed.data, createdAt: this.now() })) as MissionJsonValue) - if (++count >= MISSION_CREATION_INTENT_LIMIT) return count - } + const saved = parseIntent(entry.value) + 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 diff --git a/packages/server/src/missions/profile-defaults.test.ts b/packages/server/src/missions/profile-defaults.test.ts index 66d4ecaf78..56d58961f6 100644 --- a/packages/server/src/missions/profile-defaults.test.ts +++ b/packages/server/src/missions/profile-defaults.test.ts @@ -1,7 +1,7 @@ import assert from "node:assert/strict" import { test } from "node:test" import { missionProfileRoles, type MissionProfiles } from "./playbook-profiles" -import { globalMissionTaskMode, missionTaskModeFor, MissionPreferencesError, resolveMissionCreationDefaults, type MissionProfileDefault } from "./profile-defaults" +import { globalMissionTaskMode, hasExplicitMissionCreationChoices, missionTaskModeFor, MissionPreferencesError, resolveMissionCreationDefaults, type MissionProfileDefault } from "./profile-defaults" import type { MissionTemplateId } from "./model" const coordinator = { agent: "coordinator", model: { providerID: "p", id: "coordinator", variant: "high" } } @@ -9,6 +9,26 @@ const specialist = { agent: "worker", model: { providerID: "p", id: "worker", va const preferences: MissionProfileDefault[] = [{ template: "all", profiles: { coordinator, roles: { specialist } }, taskMode: "independent" }] const templates = Object.keys(missionProfileRoles) as MissionTemplateId[] +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 }), { diff --git a/packages/server/src/missions/profile-defaults.ts b/packages/server/src/missions/profile-defaults.ts index b6644241df..b176919e02 100644 --- a/packages/server/src/missions/profile-defaults.ts +++ b/packages/server/src/missions/profile-defaults.ts @@ -93,6 +93,14 @@ export interface MissionCreationSelection { origins: { coordinator: MissionDefaultOrigin; roles: Record; taskMode: MissionDefaultOrigin } } +/** 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 diff --git a/packages/server/src/opencode/automation-plugin-profile-defaults.test.ts b/packages/server/src/opencode/automation-plugin-profile-defaults.test.ts index 98f2e76252..15f5b7da92 100644 --- a/packages/server/src/opencode/automation-plugin-profile-defaults.test.ts +++ b/packages/server/src/opencode/automation-plugin-profile-defaults.test.ts @@ -1,11 +1,14 @@ import assert from "node:assert/strict" -import { mkdtemp, rm } from "node:fs/promises" +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 { registerAutomationPluginRoute } from "../server/routes/automation-plugin" import { setupMissionsPlugin } from "./missions-plugin" @@ -29,9 +32,9 @@ test("profile defaults distinguish absent owners from ambiguous, failed and unre 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 preferences: unknown = [], unreadable = false, denied = false, posts = 0, reads = 0, calls = 0, owned = true, ownershipFailure = false, noWorkspaces = false let sessionFailure: "missing" | "unavailable" | undefined - let probeFailure: "network" | "http" | "malformed" | "unproven-negative" | undefined + let probeFailure: "network" | "refused" | "timeout" | "http" | "malformed" | "unproven-negative" | undefined let inventoryFailure = false let failureCode: string | undefined registerAutomationPluginRoute(app, { @@ -48,15 +51,22 @@ test("profile defaults distinguish absent owners from ambiguous, failed and unre return { location: { directory: "/repo" } } } } }), list: () => { if (inventoryFailure) throw new Error("secret inventory failure"); return noWorkspaces ? [] : [{ id: "owner" }] }, - ownsLocation: async () => { if (ownershipFailure) throw new Error("Ownership unavailable"); return owned }, + ownsLocation: async (_id: string, _location: unknown, _client: unknown, _signal: AbortSignal, _purpose: string, strict: boolean) => { + if (strict) assert.equal(_purpose, "request") + 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) => { + calls++ 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 }) @@ -133,13 +143,27 @@ test("profile defaults distinguish absent owners from ambiguous, failed and unre 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 = 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 beforeNegative = reads owned = false - await assert.rejects(request(), unavailable, "a false authorization can hide failed Git or WSL reads") + 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 @@ -156,11 +180,21 @@ test("profile defaults distinguish absent owners from ambiguous, failed and unre inventoryFailure = true await assert.rejects(request(), unavailable) inventoryFailure = false - for (probeFailure of ["network", "http", "malformed", "unproven-negative"] as const) await assert.rejects(request(), unavailable, "a registered backend failure refuses fallback") + 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", "unproven-negative"] as const) await assert.rejects(request(), unavailable, "a registered backend failure refuses fallback") 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" + const beforeExplicit = posts + const callsBeforeExplicit = calls + const complete = await sendMissionInput("ses_owner", "profile-defaults", { template: "custom", + profiles: { coordinator: {}, roles: { specialist: {} } }, taskMode: "native" }) as any + assert.deepEqual(complete.origins, { coordinator: "explicit", roles: { specialist: "explicit" }, taskMode: "explicit" }) + assert.equal("preferences" in complete, false, "unused preference availability is not invented") + assert.equal(posts, beforeExplicit, "complete explicit choices do not reach the broken preference document") + assert.equal(calls, callsBeforeExplicit, "complete explicit choices skip every backend probe and request") 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 @@ -207,3 +241,55 @@ test("strict WSL discovery retries a failed cached Windows registry lookup", t = assert.throws(() => automationBridgeDirectories({ ...options, strict: true }), /Windows mission backend discovery is unavailable/) assert.equal(attempts, 2, "an old failed lookup is not reused as negative ownership evidence") }) + +test("WSL Windows probes ignore curl connection refusal but retain timeout, HTTP and auth refusals", 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" + 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") + const bytes = Buffer.from(JSON.stringify(registration)) + t.mock.method(childProcess, "execFileSync", () => "/fixture-windows") + t.mock.method(fs, "opendir", async (directory: string) => (async function* () { + if (directory.startsWith("/fixture-windows/")) yield { + name: `${registration.startedAt}-${registration.pid}-windows.json`, isFile: () => true, + } + })()) + t.mock.method(fs, "open", async () => ({ + 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[]) => { + 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 = () => sendMissionInput("ses_wsl", "profile-defaults", { 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") + } +}) diff --git a/packages/server/src/opencode/automation-plugin.ts b/packages/server/src/opencode/automation-plugin.ts index 1ef4da511a..bc342f4c71 100644 --- a/packages/server/src/opencode/automation-plugin.ts +++ b/packages/server/src/opencode/automation-plugin.ts @@ -8,7 +8,8 @@ import { MissionControlError } from "../missions/control-error" import { signNativeRecurrenceControl, type RecurrenceControlProofBody } from "../missions/recurrence-control-proof" import { missionRecoveryError } from "../missions/recovery-error" import { parseMissionCreationDefaultsInput } from "../missions/creation-defaults" -import { resolveMissionCreationDefaults } from "../missions/profile-defaults" +import { hasExplicitMissionCreationChoices, resolveMissionCreationDefaults } from "../missions/profile-defaults" +import { isConnectionRefused } from "./connection-errors" import { PAGE_ACTION_PROPERTIES, PAGE_ACTIONS, parsePageAction, type RefAction } from "../automation/page/parse" export const AUTOMATION_BRIDGE_PATH = "/api/opencode-plugin/automation" @@ -23,7 +24,7 @@ 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 | null | undefined @@ -177,7 +178,7 @@ function isProcessAlive(pid: number): boolean { process.kill(pid, 0) return true } catch (error) { - return (error as NodeJS.ErrnoException).code === "EPERM" + return (error as NodeJS.ErrnoException).code !== "ESRCH" } } @@ -222,8 +223,10 @@ async function pruneDeadLocalRegistrations(directory: string): Promise { entries.length = Math.min(entries.length, MAX_LOCAL_REGISTRY_FILES) for (const entry of entries) { const target = path.join(directory, entry.name) + const publishingPID = Number(REGISTRATION_NAME.exec(entry.name)![2]) const registration = await readRegistration(target) - if (!registration || !isProcessAlive(registration.pid)) await rm(target, { force: true }) + if (Number.isSafeInteger(publishingPID) && publishingPID > 0 && !isProcessAlive(publishingPID) + || registration && !isProcessAlive(registration.pid)) await rm(target, { force: true }) } } catch { // Registry cleanup is best effort; publication and discovery still proceed. @@ -320,6 +323,11 @@ async function registrations(pruneStale = true, strict = false): Promise 0 && !isProcessAlive(publishingPID)) { + if (pruneStale) await rm(target, { force: true }).catch(() => undefined) + continue + } const registration = await readRegistration(target) as DiscoveredBridgeRegistration | undefined if (!registration) { if (strict) throw new Error("Mission backend registration is unreadable") @@ -397,7 +405,8 @@ function callWindowsBridge( ): Promise<{ status: number; body: BridgeResponse }> { 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}`, @@ -439,7 +448,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 { @@ -547,6 +560,7 @@ async function probeBrowserBridges( 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 } @@ -562,6 +576,7 @@ export async function sendMissionInput(sessionID: string, kind: "prompt" | "synthetic" | "cleanup" | "lifecycle" | "create-root" | "prepare" | "task-sessions" | "interrupt" | "profile-defaults", input: unknown): Promise { try { const defaultsInput = kind === "profile-defaults" ? parseMissionCreationDefaultsInput(input) : undefined + if (defaultsInput && hasExplicitMissionCreationChoices(defaultsInput)) return resolveMissionCreationDefaults({ ...defaultsInput, preferences: undefined }) // `purpose` lets a backend without native browsers claim the session for dispatch only. let targets: DiscoveredBridgeRegistration[] try { 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/missions-plugin.ts b/packages/server/src/opencode/missions-plugin.ts index 1edb05d199..1cf14dfc59 100644 --- a/packages/server/src/opencode/missions-plugin.ts +++ b/packages/server/src/opencode/missions-plugin.ts @@ -381,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. Creation uses Missions preferences for omitted choices and returns selection with saved profiles, taskMode and origins (explicit, preference, opencode-default). With no bridge presence or zero proven owning backends, start uses explicit inputs and OpenCode defaults, returning selection.preferences: 'unavailable'; saved creationDefaults retains this warning on retries even after a backend appears. Multiple owners, a failed/unreachable registered owner, or unreadable/invalid preferences refuse creation. The existing coordinator must match the resolved profile. 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. Creation returns selection with saved profiles, taskMode and origins (explicit, preference, opencode-default). When preferences are needed, no bridge presence or zero proven owning backends uses explicit inputs and OpenCode defaults, returning selection.preferences: 'unavailable'; saved creationDefaults retains this warning on retries even after a backend appears. A stale registration with connection refused counts as absent; timeouts, HTTP/authentication errors and indeterminate discovery refuse preference resolution. A backend proven unrelated to this project counts as a non-owner even with other workspaces open. The existing coordinator must match the resolved profile. 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.", input: inspectSchema, options: { namespace: "mission", codemode: false }, execute: async (input, tool) => { @@ -507,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. Creation requires an owning CodeNomad backend for its fences, uses Missions preferences for omitted choices and returns selection with saved profiles, taskMode and origins (explicit, preference, opencode-default); multiple owners, a failed/unreachable registered owner, or unreadable/invalid preferences refuse creation. It never starts; the user presses Play. Reuse the same requestID and original inputs to retry: saved choices stay frozen even if preferences change. Outside an active mission use the Missions editor. 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: what the Mission editor creates. Creation requires an owning CodeNomad backend for its fences and returns selection with saved profiles, taskMode and origins (explicit, preference, opencode-default). It never starts; the user presses Play. Reuse the same requestID and original inputs to retry: saved choices stay frozen even if preferences change. Outside an active mission use the Missions editor. Find it later with mission.inspect({ list: true }) and read it with mission.inspect({ missionID }); you cannot control it.", input: prepareSchema, options: { namespace: "mission", codemode: false }, execute: async (input, tool) => { @@ -623,6 +623,8 @@ const interruptSchema = { additionalProperties: false, } +const MISSION_PROFILES_DESCRIPTION = "Omitted coordinator/role slots inherit Missions preferences: type exception, then global (specialist for task roles). Each explicit slot replaces the preference whole, including {} (OpenCode defaults) or agent-only. Compare then fills any missing judge model from the known coordinator model, including explicit/preference {} or agent-only slots; a judge's own model is preserved. A chosen judge slot keeps its origin; an absent slot inherits the coordinator's origin. profiles: {} inherits all slots. Supplying the coordinator, every exact role of the selected template and taskMode skips backend preferences entirely: all origins are explicit and preference availability stays unobserved; unused unreadable/invalid preferences are irrelevant. Partial or omitted selections read owning-backend preferences; multiple owners, failed/incomplete discovery or unreadable preferences refuse resolution, and invalid preferences refuse creation." + const prepareSchema = { type: "object", properties: { @@ -631,7 +633,7 @@ 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, description: "Omitted coordinator/role slots inherit Missions preferences: type exception, then global (specialist for task roles). Each explicit slot replaces the preference whole; {} selects OpenCode defaults for that slot. Compare then fills any missing judge model from the known coordinator model, including explicit/preference {} or agent-only slots; a judge's own model is preserved. A chosen judge slot keeps its origin; an absent slot inherits the coordinator's origin. profiles: {} inherits all slots. Invalid preferences refuse creation." }, + 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"], @@ -689,7 +691,7 @@ 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, description: "Omitted coordinator/role slots inherit Missions preferences: type exception, then global (specialist for task roles). Explicit slots replace whole, including {} or agent-only. Compare then fills any missing judge model from the known coordinator model, including explicit/preference {} or agent-only slots; a judge's own model is preserved. A chosen judge slot keeps its origin; an absent slot inherits the coordinator's origin. profiles: {} inherits all slots. Invalid preferences refuse creation." }, + 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"], diff --git a/packages/server/src/server/routes/automation-plugin.ts b/packages/server/src/server/routes/automation-plugin.ts index 9c4893ff20..6dc08cad87 100644 --- a/packages/server/src/server/routes/automation-plugin.ts +++ b/packages/server/src/server/routes/automation-plugin.ts @@ -109,12 +109,11 @@ export function registerAutomationPluginRoute(app: FastifyInstance, deps: Automa } // One validated owner is sufficient. Waiting for every unrelated inventory // can exceed the plugin's discovery deadline despite a ready local owner. - let owned: boolean, ownershipReadFailed = false, workspaceCount = 0 + let owned: boolean, ownershipReadFailed = false try { const workspaces = deps.workspaceManager.list() - workspaceCount = workspaces.length owned = await lifetime.wait(Promise.any(workspaces.map(async workspace => { - try { if (await deps.workspaceManager.ownsLocation(workspace.id, location, undefined, signal)) return true } + try { if (await deps.workspaceManager.ownsLocation(workspace.id, location, undefined, signal, "request", preferenceProbe)) return true } catch { ownershipReadFailed = true } throw new Error("Not an owner") }))).catch(() => false) @@ -123,9 +122,6 @@ export function registerAutomationPluginRoute(app: FastifyInstance, deps: Automa throw error } if (preferenceProbe && (signal.aborted || !owned && ownershipReadFailed)) return preferenceUnavailable() - // Directory authorization intentionally collapses some failed Git/WSL reads - // to false. With open workspaces that is not proof of absent ownership. - if (preferenceProbe && !owned && workspaceCount) return preferenceUnavailable() if (!owned) return notOwner("Session is not owned by this CodeNomad instance") if (body.mode === "mission-input") { diff --git a/packages/server/src/server/routes/mission-prepare.ts b/packages/server/src/server/routes/mission-prepare.ts index 4eb81e9aab..4af3ddbe06 100644 --- a/packages/server/src/server/routes/mission-prepare.ts +++ b/packages/server/src/server/routes/mission-prepare.ts @@ -11,19 +11,24 @@ import type { WorkspaceManager } from "../../workspaces/manager" import type { WorktreeDeletionFence } from "../../workspaces/worktree-session-evacuation" import { prepareMissionCreation, type MissionCreationPipelineManager } from "./mission-creation-pipeline" import { hasMissionPreparationHold, MissionCreationHoldError } from "./mission-creation-holds" -import { parseMissionCreationDefaults } from "../../missions/creation-defaults" -import { missionRecoveryRejection } from "../../missions/recovery-error" +import { missionCreationTemplateSchema, parseMissionCreationDefaults } from "../../missions/creation-defaults" +import { missionRecoveryError, 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 +function refusal(code: "prepare-refused" | "prepare-no-effect" | "prepare-conflict" | "prepare-uncertain"): MissionControlError { + const error = missionRecoveryError(code)! + return new MissionControlError(error.message, error.code) +} + /** A running coordinator's paused hand-off: the same prepared creation pipeline, * fences and holds as the UI editor, at the coordinator's own Location. Never Play. */ export async function prepareCoordinatorMission(manager: Manager, fence: WorktreeDeletionFence, coordinatorID: string, command: unknown, @@ -31,7 +36,7 @@ export async function prepareCoordinatorMission(manager: Manager, fence: Worktre const { input } = commandSchema.parse(command) let creation: Awaited> | undefined try { - if (hasMissionPreparationHold(fence, input.requestID)) throw new MissionControlError("The prepared mission's outcome is uncertain; retry with the same requestID", "prepare-uncertain") + 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") @@ -40,14 +45,14 @@ export async function prepareCoordinatorMission(manager: Manager, fence: Worktre || !await manager.ownsLocation(workspace.id, coordinator.location, connection.client)) throw new Error("Foreign coordinator") return { connection, workspace, coordinator } })).catch(() => undefined) - if (!owner) throw new MissionControlError("The mission could not be prepared; nothing was created", "prepare-refused") + 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 new MissionControlError("Only an active mission's coordinator may prepare a hand-off", "prepare-refused") + throw refusal("prepare-refused") } creation = await prepareMissionCreation({ manager, fence, workspaceID: workspace.id, signal, expectedProjectID: coordinator.projectID, preparedBy: { missionID: source.id, coordinatorSessionID: coordinatorID }, @@ -58,22 +63,22 @@ export async function prepareCoordinatorMission(manager: Manager, fence: Worktre return await creation.execute() } catch (error) { if (creation && isMissionCreateNoEffectError(error, input.requestID, creation.missionID)) - throw new MissionControlError("The preparation request was refused without effects; correct the request and retry", "prepare-no-effect") - if (hasMissionPreparationHold(fence, input.requestID)) throw new MissionControlError("The prepared mission's outcome is uncertain; retry with the same requestID", "prepare-uncertain") + 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 && error.message.startsWith("compare-models-")) throw new MissionControlError(error.message, error.message) // 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 index a70c2e602b..cf1b4d4b40 100644 --- a/packages/server/src/server/routes/mission-profile-defaults.test.ts +++ b/packages/server/src/server/routes/mission-profile-defaults.test.ts @@ -4,6 +4,7 @@ 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/creation-defaults" function fixture(t: TestContext, read?: () => unknown) { const app = Fastify() @@ -77,6 +78,13 @@ test("profile default command validates all input before reading preferences", a 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 } }) diff --git a/packages/server/src/server/routes/mission-profile-defaults.ts b/packages/server/src/server/routes/mission-profile-defaults.ts index fa090bd212..174434b201 100644 --- a/packages/server/src/server/routes/mission-profile-defaults.ts +++ b/packages/server/src/server/routes/mission-profile-defaults.ts @@ -1,6 +1,6 @@ import { z } from "zod" import { MissionControlError } from "../../missions/control-error" -import { parseMissionCreationDefaultsInput } from "../../missions/creation-defaults" +import { MISSION_DEFAULTS_REQUEST_INVALID, parseMissionCreationDefaultsInput } from "../../missions/creation-defaults" import { MissionPreferencesError, resolveMissionCreationDefaults } from "../../missions/profile-defaults" import { missionRecoveryError } from "../../missions/recovery-error" import { isPlainObject } from "../../settings/merge-patch" @@ -16,7 +16,7 @@ function refusal(code: "mission-preferences-invalid" | "mission-preferences-unav /** 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("Correct the profile-defaults request: use a supported template, valid profiles and taskMode, and a complete coordinatorModel", "invalid-execution") + if (!parsed.success) throw new MissionControlError(MISSION_DEFAULTS_REQUEST_INVALID, "invalid-execution") const input = parseMissionCreationDefaultsInput(parsed.data.input) let preferences: unknown try { 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..58ca74dfbf --- /dev/null +++ b/packages/server/src/workspaces/__tests__/native-worktree-fallback.test.ts @@ -0,0 +1,84 @@ +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 proves checkout absence before falling back, including strict manager 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 })) + const repo = path.join(root, "repo"), linked = path.join(root, "linked") + const nonGit = path.join(root, "non-git"), broken = path.join(root, "broken") + const emptyPath = path.join(root, "empty-path") + for (const directory of [nonGit, broken, emptyPath]) await mkdir(directory) + await writeFile(path.join(broken, ".git"), "invalid pointer\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) + 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")} + const { repo, linked, nonGit, broken } = ${JSON.stringify({ repo, linked, nonGit, broken })} + const missingGit = process.env.GIT_TEST_ASSUME_DIFFERENT_OWNER !== "1" + assert.throws(() => execFileSync("git", ["-C", repo, "rev-parse", "--show-toplevel"], { windowsHide: true, stdio: "pipe" }), + error => missingGit ? error.code === "ENOENT" : /dubious ownership/.test(String(error.stderr))) + const context = workspacePath => ({ client: {}, workspacePath, location: { directory: workspacePath }, toHost: async directory => directory }) + const expectedError = missingGit ? /Git ownership inventory unavailable/ : /Git checkout discovery failed/ + if (missingGit) { + for (const folder of [repo, broken]) { + const inventory = await listNativeWorktrees(context(folder)) + assert.equal(inventory.gitAvailable, false) + assert.equal(inventory.worktrees[0].directoryOnly, true) + } + } else { + await assert.rejects(listNativeWorktrees(context(repo)), expectedError) + await assert.rejects(listNativeWorktrees(context(broken)), /Invalid worktree Git directory/) + } + assert.deepEqual(await listNativeWorktrees(context(nonGit)), { + ...(missingGit ? { gitAvailable: false } : { isGitRepo: false }), + worktrees: [{ slug: "root", directory: nonGit, serviceDirectory: nonGit, kind: "root", ...(missingGit ? { directoryOnly: true } : {}) }], + }) + assert.equal(await sharesGitCommonDirectory(repo, linked, true), true) + 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(repo) + assert.equal(await manager.ownsLocation(workspace.id, { directory: repo }, undefined, undefined, "request", true), true) + for (const purpose of ["request", "event"]) for (const strict of [true, false, true]) { + const ownership = manager.ownsLocation(workspace.id, { directory: linked }, undefined, undefined, purpose, strict) + if (missingGit && !strict) assert.equal(await ownership, false) + else await assert.rejects(ownership, expectedError) + } + } finally { await manager.shutdown() } + console.log("PASS " + (missingGit ? "missing Git" : "unsafe-directory rejection")) + ` + for (const missingGit of [false, true]) { + const privateEnv = { ...env } + if (missingGit) { + for (const key of Object.keys(privateEnv)) if (key.toLowerCase() === "path") delete privateEnv[key] + privateEnv.PATH = emptyPath + } 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-worktrees.ts b/packages/server/src/workspaces/git-worktrees.ts index fb502f9f6d..ec99f54789 100644 --- a/packages/server/src/workspaces/git-worktrees.ts +++ b/packages/server/src/workspaces/git-worktrees.ts @@ -4,6 +4,7 @@ import { gitLocationOverridden, readGitCommonDirectory } from "./git-common-dire export { readCheckoutIdentity } from "./git-common-directory" import { runWorktreeGit as git } from "./git-process" import { GitRequiredError } from "./git-requirement" +import { discoverCheckoutCommonDirectory } from "../opencode/session-pruning/checkout-identity" export interface LogLike { debug?: (obj: any, msg?: string) => void @@ -27,11 +28,16 @@ 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.all([read(left), read(right)]) + return a !== undefined && a === b + } 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/manager.test.ts b/packages/server/src/workspaces/manager.test.ts index 9419097666..5b988f6d5a 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, undefined, "request", 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, undefined, "request", true), true) let registered = [repo, linked] let refreshes = 0 const client = { @@ -254,6 +256,50 @@ describe("workspace manager shared service lifecycle", () => { } finally { await manager.shutdown(); await rm(root, { recursive: true, force: true }) } }) + 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, undefined, "request", 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 }) } + }) + + 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, undefined, "request", 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 () => { const service = new ControlledSharedService() service.debugLocations = [ diff --git a/packages/server/src/workspaces/manager.ts b/packages/server/src/workspaces/manager.ts index e6c835e7cd..7e171dc8b9 100644 --- a/packages/server/src/workspaces/manager.ts +++ b/packages/server/src/workspaces/manager.ts @@ -298,33 +298,36 @@ export class WorkspaceManager { // `_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?: AbortSignal, purpose: "request" | "event" = "request", strict = false): 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" | "event" = "request", strict = false): 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), + realpath(directory).catch(error => { if (strict) throw error }), realpath(record.path).catch(error => { if (strict) throw error }), ]) 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 { @@ -457,15 +460,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), + realpath(hostDirectory).catch(error => { if (strict) throw error }), realpath(record.path).catch(error => { if (strict) throw error }), ]) // The explicitly opened folder is already authority. Do not require native // discovery (or a second connection) to authorize that exact local directory. @@ -481,11 +487,12 @@ 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, + strict, loadWorktrees: (refresh) => this.ownershipWorktrees(record.id, refresh, purpose), logger: this.options.logger, }) diff --git a/packages/server/src/workspaces/native-worktrees.ts b/packages/server/src/workspaces/native-worktrees.ts index c70032c4b1..eec4960685 100644 --- a/packages/server/src/workspaces/native-worktrees.ts +++ b/packages/server/src/workspaces/native-worktrees.ts @@ -7,6 +7,7 @@ import { locationRequestOptions } from "../opencode/compatibility/location" import { readCheckout, readCheckoutIdentity, readWorktreeAnnotations, createCheckoutRootVerifier, resolveRepoRoot, prepareWorktreeBranch, attachWorktreeBranch } from "./git-worktrees" import { ensureCodenomadGitExclude } from "./worktree-map" import { GitRequiredError } from "./git-requirement" +import { discoverCheckoutCommonDirectory } from "../opencode/session-pruning/checkout-identity" export interface NativeWorktreeContext { client: OpenCodeClient @@ -25,15 +26,20 @@ async function sameDirectory(left: string, right: string): Promise { export async function listNativeWorktrees(context: NativeWorktreeContext, options: { refresh?: boolean } = {}): Promise { const { client, location, workspacePath, toHost } = context - let isGitRepo: boolean + let isGitRepo = false + let gitUnavailable: GitRequiredError | undefined try { ;({ isGitRepo } = await resolveRepoRoot(workspacePath)) } catch (error) { if (!(error instanceof GitRequiredError)) throw error - // No repository claim or discovered sibling checkouts without Git. - return { gitAvailable: false, worktrees: [{ slug: "root", directory: workspacePath, serviceDirectory: location.directory, kind: "root", directoryOnly: true }] } + gitUnavailable = error + } + if (!isGitRepo) { + if (!gitUnavailable && await discoverCheckoutCommonDirectory(workspacePath) !== undefined) throw new Error("Git checkout discovery failed") + return { ...(gitUnavailable ? { gitAvailable: false } : { isGitRepo }), + worktrees: [{ slug: "root", directory: workspacePath, serviceDirectory: location.directory, kind: "root", + ...(gitUnavailable ? { directoryOnly: true } : {}) }] } } - if (!isGitRepo) return { isGitRepo, worktrees: [{ slug: "root", directory: workspacePath, serviceDirectory: location.directory, kind: "root" }] } const local = await readCheckout(workspacePath) const current = await client.location.get({ location: { directory: location.directory } }, locationRequestOptions(location)) const checkoutHost = await toHost(current.project.directory) diff --git a/packages/server/src/workspaces/opencode-cli-service.ts b/packages/server/src/workspaces/opencode-cli-service.ts index 25d0891a2e..1a4e2f1daf 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..bd5a2350fb 100644 --- a/packages/server/src/workspaces/worktree-directory.test.ts +++ b/packages/server/src/workspaces/worktree-directory.test.ts @@ -169,3 +169,18 @@ 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" }) +}) diff --git a/packages/server/src/workspaces/worktree-directory.ts b/packages/server/src/workspaces/worktree-directory.ts index f920275ef8..95e423dddd 100644 --- a/packages/server/src/workspaces/worktree-directory.ts +++ b/packages/server/src/workspaces/worktree-directory.ts @@ -181,16 +181,27 @@ 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) + const target = params.strict ? await realpath(params.directory) : await resolveDirectoryPath(params.directory) if (!target) return null - const find = (worktrees: WorktreeCacheEntry["worktrees"]) => worktrees + const find = async (worktrees: WorktreeCacheEntry["worktrees"]) => { + if (params.strict && worktrees.some(worktree => worktree.directoryOnly)) throw new Error("Git ownership inventory unavailable") + return (params.strict + ? await Promise.all(worktrees.map(async worktree => ({ + ...worktree, + normalizedDirectory: await realpath(worktree.directory), + worktreeDirectory: await realpath(worktree.worktreeDirectory), + }))) + : 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 (!params.strict && entry.resolvedDirectories.has(target)) return entry.resolvedDirectories.get(target)! + let match = await find(entry.worktrees) + if (worktreeCache.get(params.workspaceId) !== entry) return resolveOwnedWorktreePath(params) if (!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 @@ -198,8 +209,9 @@ export async function resolveOwnedWorktreePath(params: WorktreeSource & { if (worktreeCache.get(params.workspaceId) === entry) worktreeCache.delete(params.workspaceId) entry = await getCachedWorktrees(params, true) entry.refreshedOnMiss = true - match = find(entry.worktrees) + match = await find(entry.worktrees) } + if (worktreeCache.get(params.workspaceId) !== entry) return resolveOwnedWorktreePath(params) const resolved = match ? { slug: match.slug, directory: target, worktreeDirectory: match.worktreeDirectory } : null entry.resolvedDirectories.set(target, resolved) return resolved diff --git a/packages/ui/src/lib/mission-defaults.ts b/packages/ui/src/lib/mission-defaults.ts index d7e4e85643..f170c5b844 100644 --- a/packages/ui/src/lib/mission-defaults.ts +++ b/packages/ui/src/lib/mission-defaults.ts @@ -1 +1,3 @@ -export * from "../../../server/src/missions/profile-defaults" +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/contracts/mission-defaults.test.ts b/packages/ui/tests/contracts/mission-defaults.test.ts index 8929bf10d9..a84235c2ff 100644 --- a/packages/ui/tests/contracts/mission-defaults.test.ts +++ b/packages/ui/tests/contracts/mission-defaults.test.ts @@ -5,11 +5,6 @@ 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("the UI default API reexports the pure server implementation", () => { - assert.deepEqual(Object.keys(ui).sort(), Object.keys(server).sort()) - for (const key of Object.keys(server) as (keyof typeof server)[]) assert.equal(ui[key], server[key]) -}) - 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" } } @@ -26,7 +21,7 @@ test("UI creation defaults and server resolution agree for all five templates, i ]), ] for (const preferences of cases) for (const template of templates) { - // mission-editor.tsx:133 loads the draft; mission-creation-pipeline.ts:53 freezes its Compare payload. + // The mission editor's draft-loading effect resolves defaults; prepareMissionCreation freezes its Compare payload. const normalized = ui.normalizeMissionDefaults(preferences) const payload = freezeCompareProfiles(template, ui.missionDefaultsFor(normalized, template)) const result = server.resolveMissionCreationDefaults({ template, preferences }) From 9d1b7f37b5465f0a8e9c16134ca679375e7f2e48 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pascal=20Andr=C3=A9?= Date: Fri, 6 Nov 2026 04:49:05 +0100 Subject: [PATCH 07/16] fix(missions): isolate strict ownership from inventory fallback Ordinary worktree inventory, history and event routing must retain root-only fallback when Git reports no repository, including configured or ambiguous discovery. Preserve that fallback with an unverified-discovery marker and reject it only at strict ownership expansion, including cached inventories. Validate registered roots before omitting a missing projected folder in another checkout; missing registered roots and the opened root folder remain hard failures. Wait for both admitted Git identity reads before rejecting so Windows cleanup cannot race a remaining child, and give the targeted fixture bounded removal retries. Replace positional ownership flags with an options object and migrate callers while preserving their exact signals and event/request purposes. Update the browser admission fixture to forward the real AbortSignal through the SDK. Bound invalidation recovery to two retries and one final fresh read. Shared directory-cache promises represent one scan rather than another caller's recursive retry chain, so concurrent callers retain their own budgets. Bound the native inventory scan chain too, preserving last-good display snapshots, obsolete-response fencing and later recovery. Parse filename PID liveness once. Ignore malformed foreign Windows advertisements from WSL because they supply no usable current bridge contract, without probing foreign PIDs or deleting their files. Strict file-I/O failures and reachable endpoint failures remain refusals. Infer strict ownership from the preference probe purpose and separate preference resolution from generic mission dispatch while retaining definitive pre-dispatch preparation refusals. Derive retained-choice copy, role bounds, availability values and task-mode validation from shared constants and schemas. Extract the editor's effective profile composition into a pure helper used by the real editor and contract tests, keeping editable Compare judge inheritance separate from frozen payloads. Keep agent/user guidance actionable and document discovery and liveness details in developer documentation, updating the skill and all ten help locales. Two fresh independent reviewers returned zero residual findings after fixing their concurrent pending-adoption and browser-signal cases. Windows stability qualification passed ten runs and 70 critical tests with no EBUSY. Focused profile/discovery checks passed 69 tests; route checks 20; final cache checks 19; the real Chromium admission fixture passed all five scenarios. The complete workspace suite with targeted history/worktree routes passed 377 tests with one conditional WSL test skipped and no failures. The complete Missions suite passed 1054/1054 in a serial rerun; its initial parallel run hit the unchanged local-source Git deadline at line 73. No deadline, assertion or native qualification-script changes. Both workspace typechecks, Missions and automation builds, native-plugin build invariants 2/2, help 31/31 across 28 pages and ten locales, and whitespace checks passed. The unchanged native contract passed all three gates on isolated OpenCode 2.2.3 and 2.2.5; read-only fixture checks confirmed one mission and matching persisted unavailable-preferences metadata for the final bundle. No real missions, shared-daemon or OpenCode changes, merge, force-push or PR-description edits. --- .opencode/skills/codenomad-missions/SKILL.md | 22 ++- dev-docs/BROWSER_AUTOMATION.md | 6 +- dev-docs/MISSIONS.md | 20 ++- dev-docs/WORKTREE_SESSION_PLACEMENT.md | 3 +- docs/help/de/missions.md | 2 +- docs/help/en/missions.md | 2 +- docs/help/es/missions.md | 2 +- docs/help/fr/missions.md | 2 +- docs/help/he/missions.md | 2 +- docs/help/ja/missions.md | 2 +- docs/help/ne/missions.md | 2 +- docs/help/ru/missions.md | 2 +- docs/help/tr/missions.md | 2 +- docs/help/zh-Hans/missions.md | 2 +- packages/server/src/api-types.ts | 2 + .../src/missions/creation-defaults.test.ts | 33 ++++- .../server/src/missions/creation-defaults.ts | 8 +- .../src/missions/creation-intent.test.ts | 20 ++- .../server/src/missions/creation-intent.ts | 2 +- packages/server/src/missions/mission-roots.ts | 2 +- .../src/missions/profile-defaults.test.ts | 12 +- .../server/src/missions/profile-defaults.ts | 7 +- ...automation-plugin-profile-defaults.test.ts | 41 ++++-- .../server/src/opencode/automation-plugin.ts | 123 ++++++++++------- .../src/opencode/integrations/attachments.ts | 2 +- .../src/opencode/integrations/install.ts | 2 +- .../server/src/opencode/missions-plugin.ts | 4 +- .../src/opencode/missions/desktop-plugin.ts | 4 +- .../server/src/permissions/receipts.test.ts | 2 +- packages/server/src/permissions/receipts.ts | 4 +- ...stance-proxy-disconnect-diagnostic.test.ts | 2 +- packages/server/src/server/http-server.ts | 18 +-- .../src/server/routes/automation-plugin.ts | 2 +- .../src/server/routes/images-conversation.ts | 4 +- .../routes/mission-cleanup-admission.test.ts | 2 +- .../src/server/routes/mission-cleanup.ts | 6 +- .../routes/mission-creation-admission.ts | 4 +- .../routes/mission-creation-pipeline.ts | 6 +- .../src/server/routes/mission-human-answer.ts | 4 +- .../src/server/routes/mission-map-mutation.ts | 4 +- .../mission-recurrence-control-status.ts | 4 +- .../routes/mission-recurrence-create.ts | 8 +- .../routes/mission-recurrence-manual.ts | 4 +- .../mission-recurrence-play-preparation.ts | 6 +- .../server/routes/mission-recurrence-proof.ts | 2 +- .../server/routes/mission-root-creation.ts | 2 +- .../src/server/routes/mission-scheduled.ts | 2 +- .../src/server/routes/panel-extension-api4.ts | 6 +- .../src/server/routes/pending-requests.ts | 2 +- .../src/server/routes/provider-accounts.ts | 4 +- .../server/src/server/routes/session-goal.ts | 2 +- .../server/routes/session-history-ranked.ts | 6 +- .../routes/session-history-scope.test.ts | 33 +++++ .../server/routes/session-history-scope.ts | 2 +- .../__tests__/git-common-directory.test.ts | 31 ++++- .../native-worktree-fallback.test.ts | 72 ++++++---- .../server/src/workspaces/git-worktrees.ts | 6 +- .../instance-event-ownership.test.ts | 6 +- .../server/src/workspaces/instance-events.ts | 2 +- .../server/src/workspaces/manager.test.ts | 18 +-- packages/server/src/workspaces/manager.ts | 21 ++- .../server/src/workspaces/native-worktrees.ts | 5 +- .../src/workspaces/worktree-directory.test.ts | 129 ++++++++++++++++++ .../src/workspaces/worktree-directory.ts | 108 +++++++++------ .../src/workspaces/worktree-inventory.test.ts | 22 +++ .../src/workspaces/worktree-inventory.ts | 5 +- packages/ui/src/components/mission-editor.tsx | 16 ++- packages/ui/src/lib/mission-defaults.ts | 11 ++ .../http-admission-responsiveness.test.ts | 2 +- .../tests/contracts/mission-defaults.test.ts | 31 ++++- 70 files changed, 671 insertions(+), 288 deletions(-) create mode 100644 packages/server/src/server/routes/session-history-scope.test.ts diff --git a/.opencode/skills/codenomad-missions/SKILL.md b/.opencode/skills/codenomad-missions/SKILL.md index c78f6b45cf..63f6f07d7c 100644 --- a/.opencode/skills/codenomad-missions/SKILL.md +++ b/.opencode/skills/codenomad-missions/SKILL.md @@ -26,27 +26,21 @@ missing judge model inherits the known coordinator model, including explicit or preference `{}` and agent-only slots; a judge's own model stays unchanged. `profiles: {}` inherits all slots. 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. Unused unreadable or invalid preferences are irrelevant. Partial -or omitted selections read owning-backend preferences. With absent preferences, +as an explicit profile slot; all origins are `explicit`. Partial or omitted +selections read the owning CodeNomad backend's preferences. With absent preferences, profiles use OpenCode defaults and task mode uses `native`. Read the creation response's `selection.profiles`, `selection.taskMode` and `selection.origins` to check the saved coordinator and every playbook role: `explicit`, `preference` or `opencode-default`. A chosen judge slot keeps its explicit/preference origin even with an inherited model; an absent judge slot -inherits the coordinator's origin. When preferences are needed, with no bridge presence or zero proven owning -backends, `inspect({ start })` uses explicit inputs and OpenCode defaults for omitted +inherits the coordinator's origin. When preferences are needed and no owning +CodeNomad backend is present, `inspect({ start })` uses explicit inputs and OpenCode defaults for omitted choices (`native` task-mode fallback), returning `selection.preferences: "unavailable"` and only `explicit` or `opencode-default` origins. Saved `creationDefaults.preferences: "unavailable"` -retains the warning on retries even after a backend appears. Multiple owners, -failed/incomplete backend discovery or unreadable/invalid preferences refuse -creation; report the error and arrange recovery before retrying. A stale registration -with connection refused counts as absent; timeouts, HTTP/authentication errors and -unreadable registration state with indeterminate ownership refuse resolution. A -successful ownership read proving an unrelated project establishes non-ownership -even with other workspaces open; actual Git/WSL ownership-read failures refuse resolution. -`mission.prepare` -requires an owning backend for fenced creation even with fallback profile choices. +retains the warning on retries even after a backend appears. Ambiguous ownership +or unreadable/invalid preferences block inheritance: recover preferences or supply +the coordinator, every exact template role and `taskMode` explicitly. +`mission.prepare` requires an owning backend even with fully explicit choices. `inspect({ start })` requires the caller's existing coordinator profile to match the resolved selection. When a coordinator preference differs, pass `profiles.coordinator` (for example `{}`) to override that preference; the existing diff --git a/dev-docs/BROWSER_AUTOMATION.md b/dev-docs/BROWSER_AUTOMATION.md index aa0b912090..69698807cc 100644 --- a/dev-docs/BROWSER_AUTOMATION.md +++ b/dev-docs/BROWSER_AUTOMATION.md @@ -36,7 +36,11 @@ 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. +An active backend publishes an ephemeral registration with a per-process 256-bit token and removes it on graceful shutdown. Local discovery checks the publishing PID encoded in the filename before reading the file, so a proven-dead publisher is absent even with unreadable contents. Only `ESRCH` establishes a dead PID; other process-probe errors retain liveness conservatively. Best-effort pruning removes recognized local registrations only after a filename or parsed registration PID is proven dead. Foreign Windows files discovered from WSL stay in place, with liveness established through their endpoints. A refused connection establishes an absent listener; timeouts and HTTP/authentication failures retain indeterminate ownership. WSL skips unparseable Windows registrations, including unsupported schemas, oversized files and invalid URLs, because they supply no usable authenticated bridge endpoint or supported contract. Unreadable local registrations with live or indeterminate publishers refuse strict Mission discovery. + +Failed registration-file reads retain indeterminate ownership in strict discovery, including foreign Windows files: their contents may hold a valid current advertisement. + +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. `codenomad.act({ action: "restart" })` asks the host pinned by the latest successful inspection to relaunch gracefully, ignores the old registration, waits for the same native identity with a new run, re-inspects it for the invoking session and returns that inspection. It never switches to another worktree build. diff --git a/dev-docs/MISSIONS.md b/dev-docs/MISSIONS.md index acb72355d6..b3bc31ad36 100644 --- a/dev-docs/MISSIONS.md +++ b/dev-docs/MISSIONS.md @@ -180,17 +180,23 @@ refuse otherwise. Only one-time coordinators are offered and told about backend discovery, or an unreadable preference document return `mission-preferences-unavailable`; invalid preferences return `mission-preferences-invalid`. These failures refuse creation and ask for - recovery. Discovery includes the Windows registry under WSL. A stale registration - whose connection is refused has no listener and counts as absent; timeouts, - HTTP/authentication failures and unreadable registration state with indeterminate - ownership refuse preference resolution. A local registration whose filename's - publishing PID is proven dead is absent even when its contents are unreadable; - cross-host PIDs require endpoint evidence. A typed missing-session reply, an empty + recovery or fully explicit choices. Discovery includes the Windows registration + directory under WSL. A local registration whose filename's publishing PID is + proven dead is absent even when its contents are unreadable; unreadable state + with a live or indeterminate local publisher refuses resolution. A registration + whose endpoint refuses the connection is known absent. WSL skips unparseable + registrations in the Windows directory (including unsupported schemas, oversized + files and invalid URLs): they offer no usable authenticated bridge endpoint or + supported contract. Leave these foreign files in place. Windows PIDs belong to + their host namespace; valid Windows registrations require endpoint evidence. + Timeouts and HTTP/authentication failures from a valid endpoint leave ownership + indeterminate and refuse resolution. 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. `mission.prepare` requires an owning backend for fenced creation even when - profile resolution can use the no-owner fallback. + profile resolution can use the no-owner fallback. Fully explicit choices make + no preference request; preparation still requires its owning backend. The requestID is scoped to the coordinator and mission. Preparations with the same requestID are serialized. Reuse that requestID and the original inputs: diff --git a/dev-docs/WORKTREE_SESSION_PLACEMENT.md b/dev-docs/WORKTREE_SESSION_PLACEMENT.md index 90b676569c..3e52e6a199 100644 --- a/dev-docs/WORKTREE_SESSION_PLACEMENT.md +++ b/dev-docs/WORKTREE_SESSION_PLACEMENT.md @@ -167,8 +167,9 @@ authorized workspace spelling before changing UI state. ## Agent conventions -- Preference authority probes use `ownsLocation(..., purpose, true)` for strict ownership: a successful read can establish a negative; physical-path, Git identity and WSL translation failures reject. Strict reads revalidate cached worktree paths, and Git filesystem discovery preserves verified checkout absence separately from ambiguous layouts or configured discovery. +- 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. Shared inventory preserves the ordinary root-only result when Git reports a non-repository; `discoveryUnverified` marks ambiguous filesystem discovery, configured discovery and read failures for strict rejection, including cached snapshots. 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 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. + Directory-cache and native-inventory invalidations permit two automatic restarts, then one fresh read; another invalidation rejects that demand and permits a later retry. - 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 0f968d83d6..3878e231ad 100644 --- a/docs/help/de/missions.md +++ b/docs/help/de/missions.md @@ -139,7 +139,7 @@ Das Speichern einer Tiefe erhält aktivierte native Zeitpläne in der Projektkon Diese Vorgaben gelten auch, wenn ein Agent eine Mission vorbereitet: Jedes ausgelassene Koordinator- oder Rollenprofil verwendet zuerst die Playbook-Ausnahme, dann die globale Auswahl. Der globale Spezialist liefert die Aufgabenrollen; der Vergleichsrichter verwendet standardmäßig das Modell des Koordinators. Ein ausdrücklich angegebenes Profil hat als Ganzes Vorrang, auch bei OpenCode-Standardwerten oder einer reinen Agentenauswahl. Beim Richter wird ein fehlendes Modell anschließend durch das bekannte Koordinatormodell ergänzt, auch bei ausdrücklich gewählten oder gespeicherten OpenCode-Standardwerten oder reiner Agentenauswahl; sein eigenes Modell bleibt unverändert. Der Richter behält die Herkunft seines ausdrücklich gewählten oder gespeicherten Profils; ein ausgelassenes Richterprofil erbt die Herkunft des Koordinators. Ausgelassene **Aufgabensitzungen** folgen derselben Reihenfolge, danach **Native Unteragenten**. Die Erstellungsantwort an den Agenten nennt die gespeicherten Profile, den Sitzungsmodus und die Herkunft jeder Auswahl: ausdrücklich, Vorgabe oder OpenCode-Standard. Sind Koordinator, jede genaue Rolle des gewählten Playbooks und **Aufgabensitzungen** ausdrücklich angegeben, einschließlich `{}`-Profilen, werden Backend-Vorgaben vollständig übersprungen: Alle Herkünfte sind ausdrücklich, ihre Verfügbarkeit bleibt unbeobachtet. Ungenutzte unlesbare oder ungültige Vorgaben sind unerheblich. Teilweise oder ausgelassene Auswahlen lesen die Vorgaben des zuständigen Backends; unlesbare oder ungültige Vorgaben blockieren dann die Erstellung mit einer Fehlermeldung zur Korrektur oder zum Neuladen. Wiederholungen behalten die ursprünglich gespeicherte Auswahl auch bei geänderten Vorgaben bei. -Werden Vorgaben benötigt und ist kein zuständiges CodeNomad-Backend vorhanden, verwendet `mission.inspect({ start })` ausdrückliche Auswahlen und OpenCode-Standardwerte mit einer Warnung über nicht verfügbare Vorgaben. Wiederholungen behalten sie auch dann bei, wenn später ein Backend hinzukommt. Ein nachweislich projektfremdes Backend zählt auch bei anderen offenen Arbeitsbereichen als nicht zuständig. Eine veraltete Registrierung mit abgelehnter Verbindung zählt als abwesend. Mehrere zuständige Backends, tatsächliche Fehler beim Lesen der Zuständigkeit, Zeitüberschreitungen oder HTTP-/Authentifizierungsfehler blockieren die Auflösung der Vorgaben. Mit `mission.prepare` vorbereitete Folgemissionen benötigen für die Erstellungsprüfungen ein zuständiges Backend. +Werden Vorgaben benötigt und ist kein zuständiges CodeNomad-Backend vorhanden, verwendet `mission.inspect({ start })` ausdrückliche Auswahlen und OpenCode-Standardwerte. Die Warnung über nicht verfügbare Vorgaben bleibt bei Wiederholungen gespeichert, auch wenn später ein Backend hinzukommt. Ist die Zuständigkeit unklar oder sind Vorgaben unlesbar oder ungültig, stellen Sie den Zugriff auf die gespeicherten Vorgaben wieder her oder geben Sie Koordinator, jede Playbook-Rolle und **Aufgabensitzungen** ausdrücklich an. Mit `mission.prepare` vorbereitete Folgemissionen benötigen auch bei vollständig ausdrücklicher Auswahl ein zuständiges Backend. 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. diff --git a/docs/help/en/missions.md b/docs/help/en/missions.md index cf948dec15..238016b721 100644 --- a/docs/help/en/missions.md +++ b/docs/help/en/missions.md @@ -139,7 +139,7 @@ Saving a depth preserves enabled native schedules in the project configuration. These defaults also apply when an agent prepares a mission: each omitted coordinator or role profile uses the playbook exception, then the global choice; the global specialist supplies task roles, while the comparison judge defaults to the coordinator's model. An explicitly supplied profile wins as a whole, including an OpenCode-default choice or an agent-only choice. For the judge, any missing model is then filled from the coordinator's known model, even with an explicit or saved OpenCode-default or agent-only choice; its own model stays unchanged. The judge keeps the source of its explicit or saved profile; an omitted judge profile inherits the coordinator's source. Omitted **Task sessions** uses the same preference order, then **Native subagents**. The agent's creation response lists the saved profiles, task-session mode and each choice's source: explicit, preference or OpenCode default. When the coordinator, every exact role of the selected playbook and **Task sessions** are explicit, including `{}` profile slots, backend preferences are skipped entirely: all sources are explicit and preference availability stays unobserved. Unused unreadable or invalid preferences are irrelevant. Partial or omitted selections read the owning backend's preferences; unreadable or invalid preferences then block creation with a recovery error. Retries retain the original saved choices even if you change the defaults. -When preferences are needed and no owning CodeNomad backend is present, `mission.inspect({ start })` uses explicit choices and OpenCode defaults, with a preferences-unavailable warning retained on retries even if a backend later appears. A backend proven unrelated to this project counts as a non-owner even with other workspaces open. A stale registration with connection refused counts as absent. Multiple owners, actual ownership-read failures, timeouts or HTTP/authentication errors block preference resolution. Follow-ups prepared with `mission.prepare` require an owning backend for creation checks. +When preferences are needed and no owning CodeNomad backend is present, `mission.inspect({ start })` uses explicit choices and OpenCode defaults; its preferences-unavailable warning stays saved on retries even if a backend later appears. If ownership is ambiguous or preferences cannot be read or are invalid, restore access to the saved defaults or supply the coordinator, every playbook role and **Task sessions** explicitly. Follow-ups prepared with `mission.prepare` require an owning backend even with fully explicit choices. 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. diff --git a/docs/help/es/missions.md b/docs/help/es/missions.md index 9b439c24c3..54d558a97b 100644 --- a/docs/help/es/missions.md +++ b/docs/help/es/missions.md @@ -139,7 +139,7 @@ Guardar una profundidad conserva las programaciones nativas activadas en la conf Estos valores también se aplican cuando un agente prepara una misión: cada perfil de coordinador o rol omitido usa la excepción del guion y luego la elección global; el especialista global proporciona los roles de tareas, mientras que el juez de comparación usa por defecto el modelo del coordinador. Un perfil indicado explícitamente tiene prioridad en su totalidad, incluidos los valores de OpenCode o una elección de solo agente. Para el juez, cualquier modelo ausente se completa después con el modelo conocido del coordinador, incluso con una elección explícita o guardada de valores de OpenCode o de solo agente; su propio modelo se mantiene. El juez conserva el origen de su perfil explícito o guardado; un perfil de juez omitido hereda el origen del coordinador. **Sesiones de tareas** omitido sigue el mismo orden de preferencias y luego **Subagentes nativos**. La respuesta de creación al agente enumera los perfiles guardados, el modo de sesiones y el origen de cada elección: explícito, preferencia o valor predeterminado de OpenCode. Si el coordinador, cada rol exacto del guion elegido y **Sesiones de tareas** son explícitos, incluidos los perfiles `{}`, se omiten por completo las preferencias del backend: todos los orígenes son explícitos y su disponibilidad queda sin observar. Las preferencias ilegibles o inválidas sin usar son irrelevantes. Las selecciones parciales u omitidas leen las preferencias del backend responsable; si son ilegibles o inválidas, bloquean entonces la creación con un error que pide corregirlas o recargarlas. Los reintentos conservan las elecciones guardadas originales aunque cambies los valores predeterminados. -Cuando se necesitan preferencias y no hay un backend de CodeNomad responsable, `mission.inspect({ start })` usa las elecciones explícitas y los valores predeterminados de OpenCode, con una advertencia de preferencias no disponibles que se conserva al reintentar aunque aparezca un backend más tarde. Un backend cuya falta de relación con este proyecto está demostrada cuenta como no responsable, incluso con otros espacios abiertos. Un registro obsoleto cuya conexión se rechaza cuenta como ausente. Varios responsables, fallos reales al leer la titularidad, tiempos de espera agotados o errores HTTP/de autenticación bloquean la resolución de preferencias. Las misiones de seguimiento preparadas con `mission.prepare` requieren un backend responsable para las comprobaciones de creación. +Cuando se necesitan preferencias y no hay un backend de CodeNomad responsable, `mission.inspect({ start })` usa las elecciones explícitas y los valores predeterminados de OpenCode; la advertencia de preferencias no disponibles queda guardada al reintentar aunque aparezca un backend más tarde. Si la titularidad es ambigua o las preferencias son ilegibles o inválidas, restablece el acceso a los valores guardados o indica explícitamente el coordinador, cada rol del guion y **Sesiones de tareas**. Las misiones de seguimiento preparadas con `mission.prepare` requieren un backend responsable incluso con elecciones totalmente explícitas. 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. diff --git a/docs/help/fr/missions.md b/docs/help/fr/missions.md index b7d7bbcf20..6efae955f6 100644 --- a/docs/help/fr/missions.md +++ b/docs/help/fr/missions.md @@ -139,7 +139,7 @@ Enregistrer une profondeur préserve les programmations natives activées dans l Ces défauts s'appliquent aussi quand un agent prépare une mission : chaque profil de coordinateur ou de rôle omis utilise l'exception du scénario, puis le choix global ; le spécialiste global fournit les rôles de tâches, tandis que le juge de comparaison utilise par défaut le modèle du coordinateur. Un profil explicitement fourni prime en entier, y compris un choix de défauts OpenCode ou un agent seul. Pour le juge, tout modèle manquant est ensuite complété par le modèle connu du coordinateur, même avec un choix explicite ou enregistré de défauts OpenCode ou d'agent seul ; son propre modèle reste inchangé. Le juge conserve l'origine de son profil explicite ou enregistré ; un profil de juge omis hérite de l'origine du coordinateur. **Sessions des tâches** omis suit le même ordre de préférences, puis **Sous-agents natifs**. La réponse de création à l'agent donne les profils enregistrés, le mode des sessions de tâches et l'origine de chaque choix : explicite, préférence ou défaut OpenCode. Si le coordinateur, chaque rôle exact du scénario choisi et **Sessions des tâches** sont explicites, y compris les profils `{}`, les préférences du backend sont entièrement ignorées : toutes les origines sont explicites et leur disponibilité reste inobservée. Des préférences inutilisées illisibles ou invalides sont sans effet. Une sélection partielle ou omise lit les préférences du backend propriétaire ; si elles sont illisibles ou invalides, la création est alors bloquée avec une erreur demandant leur correction ou leur rechargement. Les réessais conservent les choix enregistrés à l'origine, même si vous modifiez les défauts. -Lorsque les préférences sont nécessaires et qu'aucun backend CodeNomad propriétaire n'est présent, `mission.inspect({ start })` utilise les choix explicites et les défauts OpenCode, avec un avertissement de préférences indisponibles conservé lors des réessais, même si un backend apparaît ensuite. Un backend dont l'absence de lien avec ce projet est établie compte comme non-propriétaire, même avec d'autres espaces ouverts. Un enregistrement périmé dont la connexion est refusée compte comme absent. Plusieurs propriétaires, un échec réel de lecture de propriété, un délai dépassé ou une erreur HTTP/d'authentification bloquent la résolution des préférences. Les suivis préparés avec `mission.prepare` nécessitent un backend propriétaire pour les vérifications de création. +Lorsque les préférences sont nécessaires et qu'aucun backend CodeNomad propriétaire n'est présent, `mission.inspect({ start })` utilise les choix explicites et les défauts OpenCode ; son avertissement de préférences indisponibles reste enregistré lors des réessais, même si un backend apparaît ensuite. Si le propriétaire est ambigu ou les préférences illisibles ou invalides, rétablissez l'accès aux défauts enregistrés ou indiquez explicitement le coordinateur, chaque rôle du scénario et **Sessions des tâches**. Les suivis préparés avec `mission.prepare` nécessitent un backend propriétaire, même avec des choix entièrement explicites. 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. diff --git a/docs/help/he/missions.md b/docs/help/he/missions.md index 42c8942665..f332338483 100644 --- a/docs/help/he/missions.md +++ b/docs/help/he/missions.md @@ -139,7 +139,7 @@ ברירות המחדל חלות גם כשסוכן מכין משימה: כל פרופיל מתאם או תפקיד שהושמט משתמש בחריג של מדריך העבודה, ואז בבחירה הגלובלית; המומחה הגלובלי מספק את תפקידי המטלות, ושופט ההשוואה משתמש כברירת מחדל במודל של המתאם. פרופיל שסופק במפורש מקבל עדיפות בשלמותו, גם בבחירת ברירות המחדל של OpenCode או סוכן בלבד. אצל השופט, מודל חסר מושלם לאחר מכן מהמודל הידוע של המתאם, גם בבחירה מפורשת או שמורה של ברירות המחדל של OpenCode או של סוכן בלבד; מודל משלו נשאר ללא שינוי. השופט שומר על מקור הפרופיל המפורש או השמור שלו; פרופיל שופט שהושמט יורש את מקור המתאם. **שיחות משימות** שהושמטו משתמשות באותו סדר העדפות ואז ב־**תת־סוכנים מקוריים**. תשובת היצירה לסוכן מפרטת את הפרופילים השמורים, מצב השיחות ומקור כל בחירה: מפורש, העדפה או ברירת מחדל של OpenCode. כשהמתאם, כל תפקיד מדויק במדריך העבודה הנבחר ו־**שיחות משימות** מצוינים במפורש, כולל פרופילי `{}`, מדלגים לחלוטין על העדפות השרת: כל המקורות מפורשים וזמינות ההעדפות נשארת בלתי נבדקת. העדפות פגומות או בלתי קריאות שאינן בשימוש אינן משפיעות. בחירה חלקית או מושמטת קוראת את העדפות השרת האחראי; העדפות פגומות או בלתי קריאות חוסמות אז יצירה עם שגיאה המבקשת לתקן או לטעון אותן מחדש. ניסיונות חוזרים שומרים על הבחירות המקוריות גם אם תשנו את ברירות המחדל. -כשהעדפות נדרשות ואין שרת CodeNomad אחראי, `mission.inspect({ start })` משתמש בבחירות מפורשות ובברירות המחדל של OpenCode, עם אזהרת העדפות לא זמינות שנשמרת בניסיונות חוזרים גם אם שרת מופיע בהמשך. שרת שהוכח שאינו קשור לפרויקט נחשב ללא אחראי גם כשסביבות עבודה אחרות פתוחות. רישום מיושן שהחיבור אליו נדחה נחשב לחסר. כמה שרתים אחראים, כשל ממשי בקריאת השיוך, חריגה מזמן ההמתנה או שגיאות HTTP/אימות חוסמים את בירור ההעדפות. משימות המשך שמוכנות באמצעות `mission.prepare` דורשות שרת אחראי לבדיקות היצירה. +כשהעדפות נדרשות ואין שרת CodeNomad אחראי, `mission.inspect({ start })` משתמש בבחירות מפורשות ובברירות המחדל של OpenCode; אזהרת ההעדפות הלא זמינות נשארת שמורה בניסיונות חוזרים גם אם שרת מופיע בהמשך. אם השיוך אינו ברור או שההעדפות אינן קריאות או תקינות, שחזרו את הגישה לברירות המחדל השמורות או ציינו במפורש את המתאם, כל תפקיד בתרחיש ואת **שיחות משימות**. משימות המשך שמוכנות באמצעות `mission.prepare` דורשות שרת אחראי גם כשהבחירות כולן מפורשות. כל רשימת **מודל** מציגה את מה שמציג בורר **מודל** של השיחה, באותם שמות ומקובצת לפי ספק: מודלים מוסתרים אינם מופיעים, ובזמן שסינון למועדפים בלבד פעיל גם שאר המודלים אינם מופיעים (ראו [נראות מודלים, מועדפים וחשיבה](providers.md#models)). גם מודלים ללא תמיכה בכלים אינם מופיעים. מודל שמור שאינו ברשימה נשאר נבחר. **לא זמין** מסמן מודל שמור שהבורר אינו יכול להציע כעת: הוא חסר בקטלוג הנוכחי של הפרויקט, הוצא משימוש או אינו תומך בכלים. diff --git a/docs/help/ja/missions.md b/docs/help/ja/missions.md index 2a68043123..013d1f9c13 100644 --- a/docs/help/ja/missions.md +++ b/docs/help/ja/missions.md @@ -139,7 +139,7 @@ CodeNomad の実行中は、ミッションのコーディネーターやタス エージェントがミッションを準備する場合も、これらの既定値が適用されます。省略されたコーディネーターや役割のプロファイルには、プレイブックの例外、グローバルの選択の順で適用します。タスクの各役割にはグローバルのスペシャリストを使用し、比較の審査役には既定でコーディネーターのモデルを使用します。明示されたプロファイルは全体として優先され、OpenCode の既定値やエージェントのみの指定も含みます。審査役のモデルが未指定なら、その後で既知のコーディネーターのモデルを補います。明示または保存された OpenCode の既定値やエージェントのみの指定も対象で、審査役独自のモデルはそのまま保持します。審査役は明示または保存されたプロファイルの出所を保持し、審査役のプロファイル自体が省略された場合はコーディネーターの出所を継承します。省略された **タスクセッション** も同じ順で設定を適用し、最後に **ネイティブのサブエージェント** を使用します。エージェントへの作成応答には、保存されたプロファイル、タスクセッションのモード、各選択の出所(明示、設定、OpenCode の既定値)が表示されます。コーディネーター、選択したプレイブックのすべての正確な役割、**タスクセッション** が明示されている場合は、`{}` のプロファイルも明示指定として数え、バックエンドの設定を完全に省略します。出所はすべて明示となり、設定の利用可否は未確認のままです。使用しない設定が読み取れない、または無効でも影響しません。一部または全体が省略された選択では担当バックエンドの設定を読み、読み取れない、または無効な場合は修正や再読み込みを求めるエラーで作成を中断します。既定値を変更しても、再試行では元の保存済みの選択を保持します。 -設定が必要で担当する CodeNomad バックエンドが存在しない場合、`mission.inspect({ start })` は明示した選択と OpenCode の既定値を使用し、設定を利用できない旨の警告を返します。後でバックエンドが現れても、再試行ではこの警告を保持します。このプロジェクトと無関係だと確認されたバックエンドは、ほかのワークスペースが開いていても担当外として扱います。接続が拒否される古い登録は不在として扱います。担当が複数いる場合、実際の所有関係の読み取り失敗、タイムアウト、HTTP・認証エラーでは設定の解決を中断します。`mission.prepare` による後続ミッションの準備には、作成時の確認を行う担当バックエンドが必要です。 +設定が必要で担当する CodeNomad バックエンドが存在しない場合、`mission.inspect({ start })` は明示した選択と OpenCode の既定値を使用します。設定を利用できない旨の警告は保存され、後でバックエンドが現れても再試行で保持されます。担当が曖昧な場合や設定が読み取れない、または無効な場合は、保存済みの既定値へのアクセスを復旧するか、コーディネーター、プレイブックの全役割、**タスクセッション**を明示してください。`mission.prepare` による後続ミッションの準備には、すべての選択を明示した場合も担当バックエンドが必要です。 各 **モデル** リストには、会話の **モデル** セレクターと同じモデルが同じ名前でプロバイダーごとに表示されます。非表示のモデルは含まれず、お気に入りのみの絞り込みが有効な間はお気に入り以外のモデルも含まれません([モデルの表示、お気に入り、思考](providers.md#models) を参照)。ツールに対応していないモデルも含まれません。リストにない保存済みのモデルは選択されたまま残ります。**利用不可** は、プロジェクトの現在のカタログにない、非推奨である、またはツールに対応していないため、セレクターが現在提供できない保存済みのモデルに付きます。 diff --git a/docs/help/ne/missions.md b/docs/help/ne/missions.md index 491fa259fa..a97afb62a0 100644 --- a/docs/help/ne/missions.md +++ b/docs/help/ne/missions.md @@ -139,7 +139,7 @@ CodeNomad चलिरहँदा, project का हरेक agent कुर एजेन्टले मिसन तयार गर्दा पनि यी पूर्वनिर्धारित मान लागू हुन्छन्: छुटाइएको समन्वयकर्ता वा भूमिकाको प्रोफाइलमा पहिले प्लेबुकको अपवाद, त्यसपछि विश्वव्यापी चयन प्रयोग हुन्छ। कार्य भूमिकामा विश्वव्यापी विशेषज्ञ प्रयोग हुन्छ; तुलना गर्ने निर्णायकले पूर्वनिर्धारित रूपमा समन्वयकर्ताको मोडेल प्रयोग गर्छ। स्पष्ट रूपमा दिइएको प्रोफाइलले पूर्ण रूपमा प्राथमिकता पाउँछ, OpenCode का पूर्वनिर्धारित मान वा एजेन्ट मात्र रोजेको अवस्थामा पनि। निर्णायकको मोडेल छुटेको भए त्यसपछि समन्वयकर्ताको ज्ञात मोडेलबाट पूरा गरिन्छ, स्पष्ट वा सुरक्षित OpenCode पूर्वनिर्धारित मान वा एजेन्ट मात्रको चयनमा पनि; निर्णायकको आफ्नै मोडेल यथावत् रहन्छ। निर्णायकले आफ्नो स्पष्ट वा सुरक्षित प्रोफाइलको स्रोत कायम राख्छ; निर्णायकको प्रोफाइल नै छुटेको भए समन्वयकर्ताको स्रोत लिन्छ। छुटाइएको **कार्य सत्रहरू** मा उही प्राथमिकता क्रमपछि **नेटिभ उपएजेन्टहरू** प्रयोग हुन्छ। एजेन्टलाई फर्काइएको सिर्जना जवाफमा सुरक्षित प्रोफाइल, कार्य सत्रको मोड र हरेक चयनको स्रोत हुन्छ: स्पष्ट, प्राथमिकता वा OpenCode को पूर्वनिर्धारित मान। समन्वयकर्ता, छानिएको प्लेबुकका हरेक ठ्याक्कै भूमिका र **कार्य सत्रहरू** स्पष्ट भएमा, `{}` प्रोफाइलसमेत स्पष्ट मानी backend प्राथमिकता पूरै छोडिन्छ: सबै स्रोत स्पष्ट हुन्छन् र प्राथमिकताको उपलब्धता जाँच नगरिएकै रहन्छ। प्रयोग नभएका पढ्न नसकिने वा अमान्य प्राथमिकता असान्दर्भिक हुन्छन्। आंशिक वा छुटाइएका चयनले जिम्मेवार backend का प्राथमिकता पढ्छन्; त्यसबेला पढ्न नसकिने वा अमान्य प्राथमिकताले सुधार वा पुनः लोड गर्नुपर्ने त्रुटिसहित सिर्जना रोक्छन्। पूर्वनिर्धारित मान बदले पनि पुनःप्रयासले सुरुका सुरक्षित चयन कायम राख्छ। -प्राथमिकता आवश्यक हुँदा जिम्मेवार CodeNomad backend उपस्थित छैन भने `mission.inspect({ start })` ले स्पष्ट चयन र OpenCode का पूर्वनिर्धारित मान प्रयोग गर्छ, र प्राथमिकता उपलब्ध नभएको चेतावनी फर्काउँछ। पछि backend आए पनि पुनःप्रयासमा त्यो चेतावनी कायम रहन्छ। यस परियोजनासँग असम्बन्धित प्रमाणित backend अरू कार्यक्षेत्र खुला हुँदा पनि जिम्मेवार मानिँदैन। जडान अस्वीकार भएको पुरानो दर्ता अनुपस्थित मानिन्छ। धेरै जिम्मेवार backend, स्वामित्व पढ्दाको वास्तविक असफलता, समयसीमा नाघ्नु वा HTTP/प्रमाणीकरण त्रुटिले प्राथमिकता निर्धारण रोक्छन्। `mission.prepare` बाट तयार गरिने पछिल्ला मिसनका सिर्जना जाँचका लागि जिम्मेवार backend आवश्यक हुन्छ। +प्राथमिकता आवश्यक हुँदा जिम्मेवार CodeNomad backend उपस्थित छैन भने `mission.inspect({ start })` ले स्पष्ट चयन र OpenCode का पूर्वनिर्धारित मान प्रयोग गर्छ। प्राथमिकता उपलब्ध नभएको चेतावनी सुरक्षित रहन्छ र पछि backend आए पनि पुनःप्रयासमा कायम रहन्छ। जिम्मेवारी अस्पष्ट भए वा प्राथमिकता पढ्न नसकिने वा अमान्य भए, सुरक्षित पूर्वनिर्धारित मानमा पहुँच पुनःस्थापित गर्नुहोस् वा समन्वयकर्ता, प्लेबुकका हरेक भूमिका र **कार्य सत्रहरू** स्पष्ट रूपमा दिनुहोस्। `mission.prepare` बाट पछिल्ला मिसन तयार गर्न सबै चयन स्पष्ट भए पनि जिम्मेवार backend आवश्यक हुन्छ। प्रत्येक **मोडेल** सूचीले कुराकानीको **मोडेल** selector ले देखाउने मोडेलहरू उही नाममा, provider अनुसार समूहबद्ध गरी देखाउँछ: लुकाइएका मोडेलहरू समावेश हुँदैनन्, र favorites-only filtering सक्रिय रहँदा अन्य मोडेलहरू पनि समावेश हुँदैनन् ([मोडेल दृश्यता, मनपर्ने र Thinking](providers.md#models) हेर्नुहोस्)। tool support नभएका मोडेलहरू पनि समावेश हुँदैनन्। सूचीबाहिरको saved मोडेल चयन गरिएकै रहन्छ। selector ले अहिले दिन नसक्ने saved मोडेललाई **उपलब्ध छैन** ले चिन्ह लगाउँछ: त्यो project को हालको catalogue मा छैन, deprecated छ, वा tool support छैन। diff --git a/docs/help/ru/missions.md b/docs/help/ru/missions.md index 2493d54788..a49d3928c3 100644 --- a/docs/help/ru/missions.md +++ b/docs/help/ru/missions.md @@ -139,7 +139,7 @@ Эти настройки действуют и при подготовке миссии агентом: каждый пропущенный профиль координатора или роли использует исключение сценария, затем глобальный выбор; глобальный специалист задаёт профили ролей задач, а судья сравнения по умолчанию использует модель координатора. Явно указанный профиль имеет приоритет целиком, включая выбор значений OpenCode или только агента. Затем отсутствующая модель судьи дополняется известной моделью координатора, даже при явном или сохранённом выборе значений OpenCode или только агента; собственная модель судьи остаётся неизменной. Судья сохраняет источник своего явного или сохранённого профиля; если профиль судьи пропущен, он наследует источник координатора. Пропущенные **Сессии задач** следуют тому же порядку настроек, затем используют **Нативные субагенты**. Ответ агенту при создании содержит сохранённые профили, режим сессий задач и источник каждого выбора: явный, настройка или значение OpenCode по умолчанию. Если координатор, каждая точная роль выбранного сценария и **Сессии задач** заданы явно, включая профили `{}`, настройки сервера полностью пропускаются: все источники явные, а доступность настроек остаётся непроверенной. Неиспользуемые нечитаемые или недопустимые настройки не влияют на выбор. Частичный или пропущенный выбор читает настройки ответственного сервера; нечитаемые или недопустимые настройки тогда блокируют создание с ошибкой, предлагающей исправить или перезагрузить их. Повторные попытки сохраняют исходный выбор даже после изменения настроек по умолчанию. -Когда нужны настройки, а ответственного сервера CodeNomad нет, `mission.inspect({ start })` использует явный выбор и значения OpenCode по умолчанию с предупреждением о недоступности настроек. Повторные попытки сохраняют это предупреждение, даже если сервер появится позже. Сервер с доказанным отсутствием связи с этим проектом считается неответственным, даже если открыты другие рабочие пространства. Устаревшая регистрация с отказом в соединении считается отсутствующей. Несколько ответственных серверов, реальные ошибки чтения принадлежности, тайм-ауты или ошибки HTTP/аутентификации блокируют разрешение настроек. Подготовка последующих миссий через `mission.prepare` требует ответственного сервера для проверок создания. +Когда нужны настройки, а ответственного сервера CodeNomad нет, `mission.inspect({ start })` использует явный выбор и значения OpenCode по умолчанию. Предупреждение о недоступности настроек остаётся сохранённым при повторных попытках, даже если сервер появится позже. Если принадлежность неоднозначна или настройки нечитаемы либо недопустимы, восстановите доступ к сохранённым настройкам или явно укажите координатора, каждую роль сценария и **Сессии задач**. Подготовка последующих миссий через `mission.prepare` требует ответственного сервера даже при полностью явном выборе. Каждый список **Модель** показывает то же, что переключатель **Модель** разговора, под теми же названиями и с группировкой по провайдерам: скрытые модели не показываются, а пока включена фильтрация только по избранному — и остальные модели (см. [Видимость моделей, избранное и мышление](providers.md#models)). Модели без поддержки инструментов тоже не показываются. Сохранённая модель вне списка остаётся выбранной. **Недоступно** отмечает сохранённую модель, которую переключатель сейчас не может предложить: её нет в текущем каталоге проекта, она устарела или не поддерживает инструменты. diff --git a/docs/help/tr/missions.md b/docs/help/tr/missions.md index de0bc08a95..a7f9579287 100644 --- a/docs/help/tr/missions.md +++ b/docs/help/tr/missions.md @@ -139,7 +139,7 @@ Derinliği kaydetmek, proje yapılandırmasında etkin yerel zamanlamaları koru Bir ajan görev hazırlarken de bu varsayılanlar uygulanır: belirtilmeyen her koordinatör veya rol profili önce rehber istisnasını, ardından genel seçimi kullanır; genel uzman görev rollerini sağlar, karşılaştırma hakemi ise varsayılan olarak koordinatörün modelini kullanır. Açıkça verilen profil, OpenCode varsayılanı veya yalnızca ajan seçimi dahil, bütünüyle önceliklidir. Hakemin eksik modeli daha sonra koordinatörün bilinen modeliyle tamamlanır; açık veya kayıtlı OpenCode varsayılanı ya da yalnızca ajan seçimi de buna dahildir, hakemin kendi modeli ise korunur. Hakem açık veya kayıtlı profilinin kaynağını korur; hakem profili belirtilmemişse koordinatörün kaynağını devralır. Belirtilmeyen **Görev oturumları** aynı tercih sırasını, ardından **Yerel alt ajanlar** seçimini kullanır. Ajana dönen oluşturma yanıtı kayıtlı profilleri, görev oturumu modunu ve her seçimin kaynağını listeler: açık seçim, tercih veya OpenCode varsayılanı. Koordinatör, seçilen rehberin her tam rolü ve **Görev oturumları**, `{}` profilleri dahil açıkça verilirse arka uç tercihleri tamamen atlanır: tüm kaynaklar açık seçimdir ve tercih kullanılabilirliği gözlemlenmeden kalır. Kullanılmayan okunamayan veya geçersiz tercihler etkisizdir. Kısmi veya belirtilmeyen seçimler sorumlu arka ucun tercihlerini okur; okunamayan veya geçersiz tercihler bu durumda düzeltme ya da yeniden yükleme isteyen bir hatayla oluşturmayı engeller. Varsayılanları değiştirseniz bile yeniden denemeler ilk kaydedilen seçimleri korur. -Tercihler gerektiğinde sorumlu CodeNomad arka ucu yoksa `mission.inspect({ start })` açık seçimleri ve OpenCode varsayılanlarını kullanır; tercihlerin kullanılamadığına dair uyarı, daha sonra bir arka uç belirse bile yeniden denemelerde korunur. Bu projeyle ilgisiz olduğu kanıtlanan arka uç, başka çalışma alanları açık olsa da sorumlu sayılmaz. Bağlantısı reddedilen eski kayıt yok sayılır. Birden fazla sorumlu arka uç, gerçek sahiplik okuma hataları, zaman aşımları veya HTTP/kimlik doğrulama hataları tercih çözümlemesini engeller. `mission.prepare` ile hazırlanan takip görevleri, oluşturma denetimleri için sorumlu bir arka uç gerektirir. +Tercihler gerektiğinde sorumlu CodeNomad arka ucu yoksa `mission.inspect({ start })` açık seçimleri ve OpenCode varsayılanlarını kullanır; tercihlerin kullanılamadığına dair uyarı kaydedilir ve daha sonra bir arka uç belirse bile yeniden denemelerde korunur. Sorumluluk belirsizse ya da tercihler okunamıyor veya geçersizse kayıtlı varsayılanlara erişimi düzeltin veya koordinatörü, rehberin her rolünü ve **Görev oturumları** seçimini açıkça belirtin. `mission.prepare` ile hazırlanan takip görevleri, tüm seçimler açıkça verilse bile sorumlu bir arka uç gerektirir. 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. diff --git a/docs/help/zh-Hans/missions.md b/docs/help/zh-Hans/missions.md index 67136ffe86..32c79cd7fc 100644 --- a/docs/help/zh-Hans/missions.md +++ b/docs/help/zh-Hans/missions.md @@ -139,7 +139,7 @@ CodeNomad 运行期间,项目中的每个智能体对话(包括任务协调 智能体准备任务时也会应用这些默认设置:省略的协调者或角色配置先使用剧本例外,再使用全局选择;全局专家配置用于任务角色,比较裁判默认使用协调者的模型。显式提供的配置作为整体优先,包括选择 OpenCode 默认值或仅指定代理的情况。随后,裁判缺失的模型会用协调者已知的模型补全,即使显式或已保存的选择为 OpenCode 默认值或仅指定代理;裁判自身已指定的模型保持不变。裁判保留其显式或已保存配置的来源;裁判配置整体省略时,继承协调者的来源。省略的**任务会话**采用相同的偏好顺序,最后使用**原生子代理**。返回给智能体的创建响应列出已保存的配置、任务会话模式及每项选择的来源:显式指定、偏好或 OpenCode 默认值。如果协调者、所选剧本的每个确切角色和**任务会话**均显式指定(包括 `{}` 配置槽位),则完全跳过后端偏好:所有来源均为显式指定,偏好可用性保持未观测状态。未使用的偏好即使无法读取或无效也不影响选择。部分指定或省略的选择仍读取所属后端的偏好;此时偏好无法读取或无效会阻止创建,并返回要求修正或重新加载的错误。即使修改默认设置,重试也会保留最初保存的选择。 -需要偏好且没有所属的 CodeNomad 后端时,`mission.inspect({ start })` 使用显式选择和 OpenCode 默认值,并返回偏好不可用的警告;即使后续出现后端,重试仍保留该警告。已证实与本项目无关的后端,即使打开了其他工作区,也算非所属后端。连接被拒绝的过期注册视为不存在。存在多个所属后端、实际的归属读取失败、超时或 HTTP/身份验证错误时,偏好解析会被阻止。通过 `mission.prepare` 准备后续任务需要所属后端执行创建检查。 +需要偏好且没有所属的 CodeNomad 后端时,`mission.inspect({ start })` 使用显式选择和 OpenCode 默认值;偏好不可用的警告会保存,即使后续出现后端,重试仍保留该警告。如果归属不明确,或偏好无法读取或无效,请恢复对已保存默认值的访问,或显式提供协调者、流程的每个角色和**任务会话**。通过 `mission.prepare` 准备后续任务需要所属后端,即使所有选择均已显式提供。 每个**模型**列表显示的内容与对话的**模型**选择器相同,名称一致并按提供商分组:不包含已隐藏的模型;启用仅收藏筛选时,也不包含其他模型(参见[模型可见性、收藏和思考](providers.md#models))。不支持工具的模型同样不包含。列表之外的已保存模型仍保持选中。选择器当前无法提供的已保存模型标记为**不可用**:它不在项目当前的目录中、已弃用或不支持工具。 diff --git a/packages/server/src/api-types.ts b/packages/server/src/api-types.ts index 7259e3e5e8..b3d2d14862 100644 --- a/packages/server/src/api-types.ts +++ b/packages/server/src/api-types.ts @@ -240,6 +240,8 @@ export interface WorktreeDescriptor { registeredDirectory?: string /** Degraded mode: only this exact physical directory authorizes sessions. */ directoryOnly?: boolean + /** Filesystem discovery could not verify Git checkout absence. Strict ownership rejects this snapshot. */ + discoveryUnverified?: boolean kind: WorktreeKind /** False for the opened folder and Git's main checkout. */ removable?: boolean diff --git a/packages/server/src/missions/creation-defaults.test.ts b/packages/server/src/missions/creation-defaults.test.ts index 05fe18c696..4e3f30939c 100644 --- a/packages/server/src/missions/creation-defaults.test.ts +++ b/packages/server/src/missions/creation-defaults.test.ts @@ -7,7 +7,7 @@ import { missionCreationDefaultsSchema, missionCreationDefaultsWire, missionCrea import type { MissionStorage } from "./journal" import type { MissionJsonValue } from "./model" import { NativeMissionDocumentStore, type MissionDocumentStorage } from "./mission-document-store" -import { MISSION_DEFAULT_ORIGINS, resolveMissionCreationDefaults } from "./profile-defaults" +import { MISSION_DEFAULT_ORIGINS, MISSION_PREFERENCES_UNAVAILABLE, resolveMissionCreationDefaults } from "./profile-defaults" import { CODENOMAD_MISSIONS_RPC } from "./rpc" import { freezeCompareProfiles, missionProfileRoles } from "./playbook-profiles" @@ -215,3 +215,34 @@ test("creation origin schemas share the resolver's exact origin set", () => { 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 index 187e030f6d..f8a9426d3d 100644 --- a/packages/server/src/missions/creation-defaults.ts +++ b/packages/server/src/missions/creation-defaults.ts @@ -2,7 +2,7 @@ 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, type MissionCreationSelection } from "./profile-defaults" +import { MISSION_DEFAULT_ORIGINS, MISSION_PREFERENCES_UNAVAILABLE, type MissionCreationSelection } from "./profile-defaults" import { MissionControlError } from "./control-error" import { parseExecution } from "./execution" @@ -26,7 +26,7 @@ export function parseMissionCreationDefaultsInput(input: unknown) { return parsed.data } const originsSchema = z.object({ coordinator: origin, roles: z.record(z.string(), origin), taskMode: origin }).strict() -const preferencesSchema = z.literal("unavailable").optional() +const preferencesSchema = z.literal(MISSION_PREFERENCES_UNAVAILABLE).optional() export const missionCreationDefaultsSchema = z.object({ request: missionCreationChoicesSchema, profiles: missionProfilesInputSchema, taskMode: missionTaskModeInputSchema, origins: originsSchema, preferences: preferencesSchema }).strict() const resolutionSchema = z.object({ profiles: missionProfilesInputSchema, taskMode: missionTaskModeInputSchema, @@ -75,8 +75,8 @@ export const missionCreationDefaultsWire = { type: "object", properties: { request: { type: "object", properties: { profiles: missionProfilesSchema, taskMode: missionTaskModeSchema }, additionalProperties: false }, profiles: missionProfilesSchema, taskMode: missionTaskModeSchema, - preferences: { type: "string", enum: ["unavailable"] }, + preferences: { type: "string", enum: [MISSION_PREFERENCES_UNAVAILABLE] }, origins: { type: "object", properties: { coordinator: originWire, taskMode: originWire, - roles: { type: "object", maxProperties: 6, additionalProperties: originWire } }, required: ["coordinator", "roles", "taskMode"], additionalProperties: false }, + 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 index 6cc4fbc7d9..7ee2bbe9e4 100644 --- a/packages/server/src/missions/creation-intent.test.ts +++ b/packages/server/src/missions/creation-intent.test.ts @@ -1,6 +1,6 @@ import assert from "node:assert/strict" import test from "node:test" -import { MissionCreationIntents, MISSION_CREATION_INTENT_RETENTION_MS } from "./creation-intent" +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" @@ -51,12 +51,18 @@ test("lost intent acknowledgement retains the original data and guards run befor test("pending intentions are bounded and settled evidence releases its capacity place", async () => { const f = fixture() - for (let index = 0; index < 128; index++) await f.intents.save(`msn_${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, 128) + 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, 128) + assert.equal(f.values.size, MISSION_CREATION_INTENT_LIMIT) }) test("damaged intent bytes stay intact and refuse before another preference read or write", async () => { @@ -70,11 +76,11 @@ test("damaged intent bytes stay intact and refuse before another preference read test("uncertain choices expire without extending their lifetime on an identical retry", async () => { const f = fixture() - for (let index = 0; index < 128; index++) await f.intents.save(`msn_${index}`, request, defaults, missing, () => {}, "request-conflict") + 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(2) + 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) diff --git a/packages/server/src/missions/creation-intent.ts b/packages/server/src/missions/creation-intent.ts index 18f62cd117..5849a3e72e 100644 --- a/packages/server/src/missions/creation-intent.ts +++ b/packages/server/src/missions/creation-intent.ts @@ -95,7 +95,7 @@ export class MissionCreationIntents { 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("128 Mission preparation choices are retained. Retry the original requestIDs to recover completed preparations, or wait up to 24 hours for these choices to expire. Check uncertain outcomes before creating replacements.", "creation-capacity") + 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 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/profile-defaults.test.ts b/packages/server/src/missions/profile-defaults.test.ts index 56d58961f6..f3dae3a3d3 100644 --- a/packages/server/src/missions/profile-defaults.test.ts +++ b/packages/server/src/missions/profile-defaults.test.ts @@ -1,14 +1,24 @@ import assert from "node:assert/strict" import { test } from "node:test" import { missionProfileRoles, type MissionProfiles } from "./playbook-profiles" -import { globalMissionTaskMode, hasExplicitMissionCreationChoices, missionTaskModeFor, MissionPreferencesError, resolveMissionCreationDefaults, type MissionProfileDefault } from "./profile-defaults" +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, {}])) diff --git a/packages/server/src/missions/profile-defaults.ts b/packages/server/src/missions/profile-defaults.ts index b176919e02..78a315fd4c 100644 --- a/packages/server/src/missions/profile-defaults.ts +++ b/packages/server/src/missions/profile-defaults.ts @@ -1,13 +1,14 @@ import { parseMissionProfiles, missionProfileRoles, freezeCompareProfiles, validateMissionProfiles, type MissionProfiles } from "./playbook-profiles" import type { MissionTemplateId } from "./model" import type { MissionExecution } from "./execution" -import { parseMissionTaskMode, type MissionTaskMode } from "./task-execution-mode" +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. @@ -21,7 +22,7 @@ export function normalizeMissionDefaults(value: unknown): MissionProfileDefault[ 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)) + || (entry.taskMode !== undefined && !missionTaskModeInputSchema.safeParse(entry.taskMode).success) || !scopes.includes(template) || result.some(item => item.template === template)) return [] try { const profiles = parseMissionProfiles(entry.profiles) @@ -87,7 +88,7 @@ export class MissionPreferencesError extends Error { } export interface MissionCreationSelection { - preferences?: "unavailable" + preferences?: typeof MISSION_PREFERENCES_UNAVAILABLE profiles: Required taskMode: MissionTaskMode origins: { coordinator: MissionDefaultOrigin; roles: Record; taskMode: MissionDefaultOrigin } diff --git a/packages/server/src/opencode/automation-plugin-profile-defaults.test.ts b/packages/server/src/opencode/automation-plugin-profile-defaults.test.ts index 15f5b7da92..1958130f82 100644 --- a/packages/server/src/opencode/automation-plugin-profile-defaults.test.ts +++ b/packages/server/src/opencode/automation-plugin-profile-defaults.test.ts @@ -12,7 +12,7 @@ import { PassThrough } from "node:stream" import { MissionControlError } from "../missions/control-error" import { registerAutomationPluginRoute } from "../server/routes/automation-plugin" import { setupMissionsPlugin } from "./missions-plugin" -import { AUTOMATION_BRIDGE_PATH, automationBridgeDirectories, createAutomationBridgeRegistration, publishAutomationBridge, sendMissionInput } from "./automation-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-")) @@ -51,8 +51,7 @@ test("profile defaults distinguish absent owners from ambiguous, failed and unre 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, _signal: AbortSignal, _purpose: string, strict: boolean) => { - if (strict) assert.equal(_purpose, "request") + ownsLocation: async (_id: string, _location: unknown, _client: unknown, { strict }: { strict?: boolean }) => { if (ownershipFailure) { if (strict) throw new Error("Ownership unavailable"); return false } return owned }, @@ -81,19 +80,19 @@ test("profile defaults distinguish absent owners from ambiguous, failed and unre headers: { "x-codenomad-automation-token": token! }, payload: body }) return new Response(response.body, { status: response.statusCode }) }) - const request = () => sendMissionInput("ses_owner", "profile-defaults", { template: "custom" }) + const request = () => resolveMissionProfileDefaults("ses_owner", { template: "custom" }) const unavailable = (error: unknown) => error instanceof MissionControlError && error.code === "mission-preferences-unavailable" && error.message === "Reload or correct the Missions preferences before creating a mission" 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 sendMissionInput("ses_owner", "profile-defaults", { template: "custom", profiles: { coordinator: { agent: "lead" } }, taskMode: "independent" }) as any + 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(sendMissionInput("ses_owner", "profile-defaults", { template: "debug", profiles: { roles: { specialist: {} } } }), + 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") @@ -120,7 +119,7 @@ test("profile defaults distinguish absent owners from ambiguous, failed and unre 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: (id, input) => sendMissionInput(id, "profile-defaults", input), + resolveCreationDefaults: resolveMissionProfileDefaults, prepare: (id, input) => sendMissionInput(id, "prepare", input), }) t.after(cleanup) @@ -189,7 +188,7 @@ test("profile defaults distinguish absent owners from ambiguous, failed and unre preferences = "secret-invalid-value" const beforeExplicit = posts const callsBeforeExplicit = calls - const complete = await sendMissionInput("ses_owner", "profile-defaults", { template: "custom", + const complete = await resolveMissionProfileDefaults("ses_owner", { template: "custom", profiles: { coordinator: {}, roles: { specialist: {} } }, taskMode: "native" }) as any assert.deepEqual(complete.origins, { coordinator: "explicit", roles: { specialist: "explicit" }, taskMode: "explicit" }) assert.equal("preferences" in complete, false, "unused preference availability is not invented") @@ -242,7 +241,7 @@ test("strict WSL discovery retries a failed cached Windows registry lookup", t = assert.equal(attempts, 2, "an old failed lookup is not reused as negative ownership evidence") }) -test("WSL Windows probes ignore curl connection refusal but retain timeout, HTTP and auth refusals", async t => { +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 }) @@ -257,18 +256,22 @@ test("WSL Windows probes ignore curl connection refusal but retain timeout, HTTP syncBuiltinESMExports() }) const registration = createAutomationBridgeRegistration("http://127.0.0.1:1") - const bytes = Buffer.from(JSON.stringify(registration)) + let bytes = Buffer.from(JSON.stringify(registration)), probes = 0, readFailed = false + t.mock.method(process, "kill", () => assert.fail("Windows publisher PIDs cannot be checked from WSL")) + t.mock.method(fs, "rm", async () => assert.fail("WSL leaves foreign advertisements to their publisher")) t.mock.method(childProcess, "execFileSync", () => "/fixture-windows") t.mock.method(fs, "opendir", async (directory: string) => (async function* () { if (directory.startsWith("/fixture-windows/")) yield { name: `${registration.startedAt}-${registration.pid}-windows.json`, isFile: () => true, } })()) - t.mock.method(fs, "open", async () => ({ - read: async (buffer: Buffer) => { bytes.copy(buffer); return { bytesRead: bytes.length } }, close: async () => {}, - })) + t.mock.method(fs, "open", async () => { + if (readFailed) throw Object.assign(new Error("Permission denied"), { code: "EACCES" }) + 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(), { @@ -282,7 +285,7 @@ test("WSL Windows probes ignore curl connection refusal but retain timeout, HTTP return child }) syncBuiltinESMExports() - const request = () => sendMissionInput("ses_wsl", "profile-defaults", { template: "custom" }) + 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", @@ -292,4 +295,14 @@ test("WSL Windows probes ignore curl connection refusal but retain timeout, HTTP ;({ 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") }) diff --git a/packages/server/src/opencode/automation-plugin.ts b/packages/server/src/opencode/automation-plugin.ts index bc342f4c71..eaee4f5a46 100644 --- a/packages/server/src/opencode/automation-plugin.ts +++ b/packages/server/src/opencode/automation-plugin.ts @@ -8,7 +8,7 @@ import { MissionControlError } from "../missions/control-error" import { signNativeRecurrenceControl, type RecurrenceControlProofBody } from "../missions/recurrence-control-proof" import { missionRecoveryError } from "../missions/recovery-error" import { parseMissionCreationDefaultsInput } from "../missions/creation-defaults" -import { hasExplicitMissionCreationChoices, resolveMissionCreationDefaults } from "../missions/profile-defaults" +import { hasExplicitMissionCreationChoices, 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" @@ -182,16 +182,30 @@ function isProcessAlive(pid: number): boolean { } } -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 && Number.isSafeInteger(pid) && pid > 0 && !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 (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" @@ -208,12 +222,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 @@ -223,10 +237,8 @@ async function pruneDeadLocalRegistrations(directory: string): Promise { entries.length = Math.min(entries.length, MAX_LOCAL_REGISTRY_FILES) for (const entry of entries) { const target = path.join(directory, entry.name) - const publishingPID = Number(REGISTRATION_NAME.exec(entry.name)![2]) const registration = await readRegistration(target) - if (Number.isSafeInteger(publishingPID) && publishingPID > 0 && !isProcessAlive(publishingPID) - || 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. @@ -296,19 +308,19 @@ export async function verifyHumanAnswerBridge(body: import("../missions/human-an return false } -async function registrations(pruneStale = true, strict = false): Promise { +async function registrations({ pruneStale = true, strict = false } = {}): Promise { const found: DiscoveredBridgeRegistration[] = [] const directories = automationBridgeDirectories({ strict }) for (const [directoryIndex, directory] of directories.entries()) { - 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) { 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) @@ -323,14 +335,15 @@ async function registrations(pruneStale = true, strict = false): Promise 0 && !isProcessAlive(publishingPID)) { + if (entry.deadPublisher) { if (pruneStale) await rm(target, { force: true }).catch(() => undefined) continue } - const registration = await readRegistration(target) as DiscoveredBridgeRegistration | undefined + const registration = await readRegistration(target, { throwReadErrors: strict }) as DiscoveredBridgeRegistration | undefined if (!registration) { - if (strict) throw new Error("Mission backend registration is unreadable") + // 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)) { @@ -349,7 +362,7 @@ async function registrations(pruneStale = true, strict = false): 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 { @@ -549,8 +562,8 @@ async function probeBrowserBridges( mode: "browser-claim" | "browser-probe", timeoutMs = PROBE_TIMEOUT_MS, purpose?: "mission" | "mission-preferences", - strict = false, ): Promise { + const strict = purpose === "mission-preferences" 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) => { @@ -572,42 +585,48 @@ 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" | "profile-defaults", input: unknown): Promise { +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) + 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 defaultsInput = kind === "profile-defaults" ? parseMissionCreationDefaultsInput(input) : undefined - if (defaultsInput && hasExplicitMissionCreationChoices(defaultsInput)) return resolveMissionCreationDefaults({ ...defaultsInput, preferences: undefined }) - // `purpose` lets a backend without native browsers claim the session for dispatch only. - let targets: DiscoveredBridgeRegistration[] - try { - const strict = kind === "profile-defaults" - targets = await probeBrowserBridges(await registrations(true, strict), sessionID, "browser-claim", MISSION_PROBE_TIMEOUT_MS, - strict ? "mission-preferences" : "mission", strict) - if (defaultsInput && targets.length === 0) return { - ...resolveMissionCreationDefaults({ ...defaultsInput, preferences: undefined }), preferences: "unavailable", - } - if (targets.length !== 1) throw new Error("Mission dispatch requires exactly one owning CodeNomad backend") - } catch (error) { - if (kind === "prepare") { - const refusal = missionRecoveryError("prepare-refused")! - throw new MissionControlError(refusal.message, refusal.code) - } - throw error - } - const response = await callBridge(targets[0], { 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) - throw new Error("CodeNomad could not admit the mission input; inspect ownership/environment and retry the same task") + const request = parseMissionCreationDefaultsInput(input) + if (hasExplicitMissionCreationChoices(request)) return resolveMissionCreationDefaults({ ...request, preferences: undefined }) + 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, } - return response.body.result + 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 + const unavailable = missionRecoveryError("mission-preferences-unavailable")! + throw new MissionControlError(unavailable.message, unavailable.code) + } +} + +export async function sendMissionInput(sessionID: string, + kind: "prompt" | "synthetic" | "cleanup" | "lifecycle" | "create-root" | "prepare" | "task-sessions" | "interrupt", input: unknown): Promise { + let targets: DiscoveredBridgeRegistration[] + try { + // A backend without native browsers can still claim the session for dispatch. + 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") } catch (error) { - if (kind === "profile-defaults" && !(error instanceof MissionControlError && missionRecoveryError(error.code))) { - const unavailable = missionRecoveryError("mission-preferences-unavailable")! - throw new MissionControlError(unavailable.message, unavailable.code) + if (kind === "prepare") { + const refusal = missionRecoveryError("prepare-refused")! + throw new MissionControlError(refusal.message, refusal.code) } throw error } + return callMissionInput(targets[0], sessionID, kind, input) } export async function executeBrowserTool(sessionID: string, input: unknown) { 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.ts b/packages/server/src/opencode/missions-plugin.ts index 1cf14dfc59..d18cd16475 100644 --- a/packages/server/src/opencode/missions-plugin.ts +++ b/packages/server/src/opencode/missions-plugin.ts @@ -381,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. Creation returns selection with saved profiles, taskMode and origins (explicit, preference, opencode-default). When preferences are needed, no bridge presence or zero proven owning backends uses explicit inputs and OpenCode defaults, returning selection.preferences: 'unavailable'; saved creationDefaults retains this warning on retries even after a backend appears. A stale registration with connection refused counts as absent; timeouts, HTTP/authentication errors and indeterminate discovery refuse preference resolution. A backend proven unrelated to this project counts as a non-owner even with other workspaces open. The existing coordinator must match the resolved profile. 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. Creation returns selection with saved profiles, taskMode and origins (explicit, preference, opencode-default). When preferences are needed and no owning CodeNomad backend is present, standalone creation uses explicit inputs and OpenCode defaults, returning selection.preferences: 'unavailable'; saved creationDefaults retains this warning on retries even after a backend appears. Ambiguous ownership or unreadable/invalid preferences block inheritance: recover preferences or supply the coordinator, every template role and taskMode explicitly. The existing coordinator must match the resolved profile. 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.", input: inspectSchema, options: { namespace: "mission", codemode: false }, execute: async (input, tool) => { @@ -623,7 +623,7 @@ const interruptSchema = { additionalProperties: false, } -const MISSION_PROFILES_DESCRIPTION = "Omitted coordinator/role slots inherit Missions preferences: type exception, then global (specialist for task roles). Each explicit slot replaces the preference whole, including {} (OpenCode defaults) or agent-only. Compare then fills any missing judge model from the known coordinator model, including explicit/preference {} or agent-only slots; a judge's own model is preserved. A chosen judge slot keeps its origin; an absent slot inherits the coordinator's origin. profiles: {} inherits all slots. Supplying the coordinator, every exact role of the selected template and taskMode skips backend preferences entirely: all origins are explicit and preference availability stays unobserved; unused unreadable/invalid preferences are irrelevant. Partial or omitted selections read owning-backend preferences; multiple owners, failed/incomplete discovery or unreadable preferences refuse resolution, and invalid preferences refuse creation." +const MISSION_PROFILES_DESCRIPTION = "Omitted coordinator/role slots inherit Missions preferences: type exception, then global (specialist for task roles). Each explicit slot replaces the preference whole, including {} (OpenCode defaults) or agent-only. Compare then fills any missing judge model from the known coordinator model, including explicit/preference {} or agent-only slots; a judge's own model is preserved. A chosen judge slot keeps its origin; an absent slot inherits the coordinator's origin. profiles: {} inherits all slots. Supplying the coordinator, every exact role of the selected template and taskMode skips preferences entirely; all origins are explicit. Partial or omitted selections inherit the owning CodeNomad backend's preferences. If ownership is ambiguous or preferences are unreadable/invalid, recover preferences or supply fully explicit choices." const prepareSchema = { type: "object", diff --git a/packages/server/src/opencode/missions/desktop-plugin.ts b/packages/server/src/opencode/missions/desktop-plugin.ts index 0c83cfcf91..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,7 +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: (sessionID, input) => sendMissionInput(sessionID, "profile-defaults", 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 00a42c22ea..fb4b497f30 100644 --- a/packages/server/src/permissions/receipts.test.ts +++ b/packages/server/src/permissions/receipts.test.ts @@ -112,7 +112,7 @@ test("initial connection and reconnect recover every loaded owned Location, incl const requested: string[] = [] let generation = 1 Object.assign(f.manager, { - ownsLocation: async (_id: string, location: { directory: string }, _client: unknown, _signal: unknown, purpose?: string) => { + ownsLocation: async (_id: string, location: { directory: string }, _client: unknown, { purpose }: { purpose?: string } = {}) => { if (purpose) assert.equal(purpose, "event") return directories.includes(location.directory) }, diff --git a/packages/server/src/permissions/receipts.ts b/packages/server/src/permissions/receipts.ts index 8184a88f10..ace267a288 100644 --- a/packages/server/src/permissions/receipts.ts +++ b/packages/server/src/permissions/receipts.ts @@ -116,7 +116,7 @@ export class PermissionReceipts { for (const value of locations) { if (!current()) return const location = readLocationRef(value) - if (!await this.manager.ownsLocation(event.instanceId, location, connection.client, undefined, "event")) continue + if (!await this.manager.ownsLocation(event.instanceId, location, connection.client, { purpose: "event" })) continue if (!current()) return const pending = await connection.client.permission.request.list({ location: { directory: location.directory } }, { ...locationRequestOptions(location), signal: AbortSignal.timeout(10_000), @@ -129,7 +129,7 @@ export class PermissionReceipts { try { session = await connection.client.session.get({ sessionID: request.sessionId }, { signal: AbortSignal.timeout(10_000) }) } catch (error) { if (isSessionNotFoundError(error)) continue; throw error } if (!current()) return - if (!await this.manager.ownsLocation(event.instanceId, session.location, connection.client, undefined, "event")) continue + if (!await this.manager.ownsLocation(event.instanceId, session.location, connection.client, { 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 15f21fbf6f..e1af8e3173 100644 --- a/packages/server/src/server/http-server.ts +++ b/packages/server/src/server/http-server.ts @@ -528,7 +528,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 } @@ -886,7 +886,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 } @@ -1117,7 +1117,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 } @@ -1176,7 +1176,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 }) @@ -1267,7 +1267,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?.() @@ -1432,7 +1432,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[]) { @@ -1516,7 +1516,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 @@ -1541,7 +1541,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" @@ -1555,7 +1555,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.ts b/packages/server/src/server/routes/automation-plugin.ts index 6dc08cad87..437e861b0c 100644 --- a/packages/server/src/server/routes/automation-plugin.ts +++ b/packages/server/src/server/routes/automation-plugin.ts @@ -113,7 +113,7 @@ export function registerAutomationPluginRoute(app: FastifyInstance, deps: Automa 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, "request", preferenceProbe)) return true } + 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) 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-pipeline.ts b/packages/server/src/server/routes/mission-creation-pipeline.ts index efaa933896..9e99ee5e9b 100644 --- a/packages/server/src/server/routes/mission-creation-pipeline.ts +++ b/packages/server/src/server/routes/mission-creation-pipeline.ts @@ -61,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 })) @@ -89,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) 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 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.test.ts b/packages/server/src/server/routes/session-history-scope.test.ts new file mode 100644 index 0000000000..d8c6e1ace4 --- /dev/null +++ b/packages/server/src/server/routes/session-history-scope.test.ts @@ -0,0 +1,33 @@ +import assert from "node:assert/strict" +import test from "node:test" +import Fastify from "fastify" +import type { OpenCodeClient } from "@opencode/client" +import type { WorktreeListResponse } from "../../api-types" +import type { WorkspaceManager } from "../../workspaces/manager" +import { WorktreeDeletionFence } from "../../workspaces/worktree-session-evacuation" +import { historyDirectories, ownedHistorySessions } from "./session-history-scope" +import { registerWorktreeRoutes } from "./worktrees" + +test("unverified root-only inventories remain available to ordinary history and worktree routes", async () => { + const inventory: WorktreeListResponse = { isGitRepo: false, worktrees: [ + { slug: "root", directory: "/repo", serviceDirectory: "/repo", kind: "root", discoveryUnverified: true }, + ] } + const manager = { + get: () => ({ id: "workspace" }), + getWorktrees: async () => inventory, + ownsLocation: async (_id: string, location: { directory: string }, _client?: unknown, options: { strict?: boolean } = {}) => { + assert.notEqual(options.strict, true, "ordinary history never requests strict preference authority") + return location.directory === "/repo" || location.directory.startsWith("/repo/") + }, + } + assert.deepEqual(await historyDirectories(manager, "workspace", "/repo"), ["/repo"]) + const sessions = [{ sessionID: "owned", directory: "/repo/nested" }, { sessionID: "foreign", directory: "/elsewhere" }] + assert.deepEqual(await ownedHistorySessions(manager, "workspace", {} as OpenCodeClient, sessions), [sessions[0]]) + const app = Fastify() + registerWorktreeRoutes(app, { workspaceManager: manager as unknown as WorkspaceManager, worktreeDeletionFence: new WorktreeDeletionFence() }) + try { + const response = await app.inject({ method: "GET", url: "/api/workspaces/workspace/worktrees" }) + assert.equal(response.statusCode, 200) + assert.deepEqual(response.json(), inventory) + } finally { await app.close() } +}) 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", 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 index 58ca74dfbf..9957ffa103 100644 --- a/packages/server/src/workspaces/__tests__/native-worktree-fallback.test.ts +++ b/packages/server/src/workspaces/__tests__/native-worktree-fallback.test.ts @@ -5,22 +5,27 @@ import { tmpdir } from "node:os" import path from "node:path" import test from "node:test" -test("native inventory proves checkout absence before falling back, including strict manager reads", async t => { +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 })) + 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, emptyPath]) await mkdir(directory) + 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" @@ -30,27 +35,39 @@ test("native inventory proves checkout absence before falling back, including st import { sharesGitCommonDirectory } from ${module("../git-worktrees.ts")} import { WorkspaceManager } from ${module("../manager.ts")} import { EventBus } from ${module("../../events/bus.ts")} - const { repo, linked, nonGit, broken } = ${JSON.stringify({ repo, linked, nonGit, broken })} - const missingGit = process.env.GIT_TEST_ASSUME_DIFFERENT_OWNER !== "1" - assert.throws(() => execFileSync("git", ["-C", repo, "rev-parse", "--show-toplevel"], { windowsHide: true, stdio: "pipe" }), - error => missingGit ? error.code === "ENOENT" : /dubious ownership/.test(String(error.stderr))) + 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 = missingGit ? /Git ownership inventory unavailable/ : /Git checkout discovery failed/ - if (missingGit) { - for (const folder of [repo, broken]) { - const inventory = await listNativeWorktrees(context(folder)) - assert.equal(inventory.gitAvailable, false) - assert.equal(inventory.worktrees[0].directoryOnly, true) + 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 } : { discoveryUnverified: 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 must reject the cached shared-inventory marker") + if (folder === (ceiling ? nested : repo)) { + assert.equal(Boolean(await resolveOwnedWorktreePath({ ...params, directory: folder + "/child" })), !missingGit) } - } else { - await assert.rejects(listNativeWorktrees(context(repo)), expectedError) - await assert.rejects(listNativeWorktrees(context(broken)), /Invalid worktree Git directory/) + 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 } : {}) }], + worktrees: [{ slug: "root", directory: nonGit, serviceDirectory: nonGit, kind: "root", + ...(missingGit ? { directoryOnly: true } : ceiling ? { discoveryUnverified: true } : {}) }], }) - assert.equal(await sharesGitCommonDirectory(repo, linked, true), true) + if (!ceiling) assert.equal(await sharesGitCommonDirectory(repo, linked, true), true) + else await assert.rejects(sharesGitCommonDirectory(repo, linked, true), /Git discovery is configured/) const manager = new WorkspaceManager({ rootDir: repo, settings: { getOwner: () => ({ environmentVariables: {} }) }, binaryResolver: { resolveDefault: () => ({ path: process.execPath, label: "fixture" }) }, @@ -59,22 +76,23 @@ test("native inventory proves checkout absence before falling back, including st validateLocation: async location => ({ ...location, project: { id: "fixture", directory: repo, canonical: repo } }) }, }) try { - const { workspace } = await manager.create(repo) - assert.equal(await manager.ownsLocation(workspace.id, { directory: repo }, undefined, undefined, "request", true), true) + 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, undefined, purpose, strict) - if (missingGit && !strict) assert.equal(await ownership, false) - else await assert.rejects(ownership, expectedError) + 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" : "unsafe-directory rejection")) + console.log("PASS " + (missingGit ? "missing Git" : ceiling ? "GIT_CEILING_DIRECTORIES" : "unsafe-directory fallback")) ` - for (const missingGit of [false, true]) { + for (const mode of ["unsafe", "missing", "ceiling"]) { const privateEnv = { ...env } - if (missingGit) { + if (mode === "missing") { for (const key of Object.keys(privateEnv)) if (key.toLowerCase() === "path") delete privateEnv[key] privateEnv.PATH = emptyPath - } else privateEnv.GIT_TEST_ASSUME_DIFFERENT_OWNER = "1" + } 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", }) diff --git a/packages/server/src/workspaces/git-worktrees.ts b/packages/server/src/workspaces/git-worktrees.ts index ec99f54789..ad5b97118a 100644 --- a/packages/server/src/workspaces/git-worktrees.ts +++ b/packages/server/src/workspaces/git-worktrees.ts @@ -32,8 +32,10 @@ export async function sharesGitCommonDirectory(left: string, right: string, stri try { // Strict discovery preserves verified absence separately from ambiguous/read failures. const read = strict ? discoverCheckoutCommonDirectory : readGitCommonDirectory - const [a, b] = await Promise.all([read(left), read(right)]) - return a !== undefined && a === b + 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 diff --git a/packages/server/src/workspaces/instance-event-ownership.test.ts b/packages/server/src/workspaces/instance-event-ownership.test.ts index 7f6084a8a6..c494939795 100644 --- a/packages/server/src/workspaces/instance-event-ownership.test.ts +++ b/packages/server/src/workspaces/instance-event-ownership.test.ts @@ -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 5b988f6d5a..7b58c7102f 100644 --- a/packages/server/src/workspaces/manager.test.ts +++ b/packages/server/src/workspaces/manager.test.ts @@ -192,11 +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, undefined, "request", true), 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, undefined, "request", true), true) + assert.equal(await manager.ownsLocation(workspace.id, { directory: linked }, undefined, { strict: true }), true) let registered = [repo, linked] let refreshes = 0 const client = { @@ -219,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 () => { @@ -249,11 +249,11 @@ 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.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 () => { @@ -266,14 +266,14 @@ describe("workspace manager shared service lifecycle", () => { 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, undefined, "request", strict) + 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 }) } + } 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 () => { @@ -288,7 +288,7 @@ describe("workspace manager shared service lifecycle", () => { }) try { const { workspace } = await manager.create(process.cwd()) - const owns = (strict: boolean) => manager.ownsLocation(workspace.id, { directory: "/mnt/d/workspace" }, undefined, undefined, "request", strict) + 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) @@ -731,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 7e171dc8b9..9ace9b820a 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 } +} + +export interface LocationOwnershipOptions { + signal?: AbortSignal + purpose?: "request" | "event" + strict?: boolean +} + interface SharedService { acquire?: () => Promise existingConnection?: () => import("./opencode-service").ServiceConnection | undefined @@ -296,10 +307,8 @@ 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. // Strict probes reject unreadable ownership instead of turning it into a negative. - async ownsLocation(id: string, location: LocationRef, _client?: OpenCodeClient, signal?: AbortSignal, purpose: "request" | "event" = "request", strict = false): Promise { + 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. @@ -318,7 +327,7 @@ export class WorkspaceManager { // Resolve aliases against the explicitly opened folder without spawning Git. if (!record.wslDistro) { const [target, root] = await Promise.all([ - realpath(directory).catch(error => { if (strict) throw error }), realpath(record.path).catch(error => { if (strict) throw error }), + ownershipRealpath(directory, strict), ownershipRealpath(record.path, strict), ]) if (target && target === root) return target } @@ -447,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 @@ -471,7 +480,7 @@ export class WorkspaceManager { return null } const [target, root] = await Promise.all([ - realpath(hostDirectory).catch(error => { if (strict) throw error }), realpath(record.path).catch(error => { if (strict) throw error }), + 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. diff --git a/packages/server/src/workspaces/native-worktrees.ts b/packages/server/src/workspaces/native-worktrees.ts index eec4960685..aa422a06e5 100644 --- a/packages/server/src/workspaces/native-worktrees.ts +++ b/packages/server/src/workspaces/native-worktrees.ts @@ -35,10 +35,11 @@ export async function listNativeWorktrees(context: NativeWorktreeContext, option gitUnavailable = error } if (!isGitRepo) { - if (!gitUnavailable && await discoverCheckoutCommonDirectory(workspacePath) !== undefined) throw new Error("Git checkout discovery failed") + const discoveryUnverified = !gitUnavailable && await discoverCheckoutCommonDirectory(workspacePath) + .then(common => common !== undefined, () => true) return { ...(gitUnavailable ? { gitAvailable: false } : { isGitRepo }), worktrees: [{ slug: "root", directory: workspacePath, serviceDirectory: location.directory, kind: "root", - ...(gitUnavailable ? { directoryOnly: true } : {}) }] } + ...(gitUnavailable ? { directoryOnly: true } : discoveryUnverified ? { discoveryUnverified: true } : {}) }] } } const local = await readCheckout(workspacePath) const current = await client.location.get({ location: { directory: location.directory } }, locationRequestOptions(location)) diff --git a/packages/server/src/workspaces/worktree-directory.test.ts b/packages/server/src/workspaces/worktree-directory.test.ts index bd5a2350fb..ea87cf680a 100644 --- a/packages/server/src/workspaces/worktree-directory.test.ts +++ b/packages/server/src/workspaces/worktree-directory.test.ts @@ -184,3 +184,132 @@ test("strict ownership revalidates cached fallback paths and propagates realpath 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) + 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, + 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: path.join(temp, "foreign"), + 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("concurrent pending-scan handoffs retain each ownership demand's retry budget", async t => { + const temp = mkdtempSync(path.join(tmpdir(), "codenomad-directory-handoffs-")) + const releases: Array<() => void> = [] + const reads: Promise[] = [] + const outcomes: Array<{ status: "fulfilled" | "rejected"; completed: number; result: unknown }> = [] + let active = 0, completed = 0 + let draining = false, started = () => {} + t.after(async () => { + draining = true + for (const release of releases) release() + await Promise.allSettled(reads) + invalidateWorktreeCache(temp) + rmSync(temp, { recursive: true, force: true }) + }) + const params = { + workspaceId: temp, workspacePath: temp, directory: temp, + loadWorktrees: async () => { + active++ + try { + const index = releases.length + if (!draining) await new Promise(resolve => { releases.push(resolve); started() }) + completed++ + return draining || index === 7 ? [{ slug: "root", directory: temp, kind: "root" as const }] : [] + } finally { active-- } + }, + } + for (let i = 0; i < 8; i++) { + const scanStarted = new Promise(resolve => { started = resolve }) + invalidateWorktreeCache(temp) + reads.push(resolveOwnedWorktreePath(params).then( + result => { outcomes[i] = { status: "fulfilled", completed, result } }, + result => { outcomes[i] = { status: "rejected", completed, result } }, + )) + await scanStarted + assert.equal(releases.length, i + 1, "each new caller starts its invalidation's shared scan") + if (i > 0) { + releases[i - 1]() + await new Promise(resolve => setImmediate(resolve)) + } + } + releases[7]() + await Promise.all(reads) + assert.equal(outcomes[0]?.status, "rejected", "the original demand cannot adopt eight callers' independent budgets") + assert.equal(outcomes[0].completed, 4, "the original demand settles after its fourth invalid scan") + assert.match(String(outcomes[0].result), /inventory changed repeatedly/) + assert.equal(active, 0, "every admitted loader has settled before cleanup") + assert.ok(outcomes.slice(0, 4).every(outcome => outcome.status === "rejected")) + assert.ok(outcomes.slice(4).every(outcome => outcome.status === "fulfilled")) +}) diff --git a/packages/server/src/workspaces/worktree-directory.ts b/packages/server/src/workspaces/worktree-directory.ts index 95e423dddd..713d0aec54 100644 --- a/packages/server/src/workspaces/worktree-directory.ts +++ b/packages/server/src/workspaces/worktree-directory.ts @@ -8,13 +8,18 @@ type WorktreeSource = { loadWorktrees: (refresh?: boolean) => Promise + worktrees: Array<{ slug: string; directory: string; normalizedDirectory: string; worktreeDirectory: string; directoryOnly?: boolean; discoveryUnverified?: 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 }): boolean { + if (budget.restarts >= 3) throw new Error("Worktree ownership inventory changed repeatedly") + return ++budget.restarts === 3 +} async function normalizeDirectoryPath(directory: string): Promise { const trimmed = (directory ?? "").trim() @@ -29,6 +34,7 @@ async function normalizeDirectoryPath(directory: string): Promise { async function getCachedWorktrees( params: WorktreeSource & { workspaceId: string; workspacePath: string; logger?: LogLike }, refresh = false, + budget = { restarts: 0 }, ): Promise { const cached = worktreeCache.get(params.workspaceId) const now = Date.now() @@ -36,38 +42,39 @@ async function getCachedWorktrees( 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) - try { - return await load - } finally { - if (worktreeLoads.get(params.workspaceId) === load) worktreeLoads.delete(params.workspaceId) + let load = worktreeLoads.get(params.workspaceId) + if (!load) { + let scan!: Promise + scan = (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, + discoveryUnverified: wt.discoveryUnverified, + })), + ), + resolvedDirectories: new Map(), + } + // Share one scan, never another caller's retry chain or budget. + if (worktreeLoads.get(params.workspaceId) !== scan) return null + worktreeCache.set(params.workspaceId, entry) + return entry + })().finally(() => { + if (worktreeLoads.get(params.workspaceId) === scan) worktreeLoads.delete(params.workspaceId) + }) + worktreeLoads.set(params.workspaceId, scan) + load = scan } + const entry = await load + if (entry && worktreeCache.get(params.workspaceId) === entry) return entry + return getCachedWorktrees(params, restartWorktreeRead(budget), budget) } export function invalidateWorktreeCache(workspaceId?: string): void { @@ -183,35 +190,46 @@ export async function resolveOwnedWorktreePath(params: WorktreeSource & { directory: string strict?: boolean logger?: LogLike -}): Promise<{ slug: string; directory: string; worktreeDirectory: string } | null> { +}, budget = { restarts: 0 }): 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 = async (worktrees: WorktreeCacheEntry["worktrees"]) => { - if (params.strict && worktrees.some(worktree => worktree.directoryOnly)) throw new Error("Git ownership inventory unavailable") + if (params.strict && worktrees.some(worktree => worktree.directoryOnly || worktree.discoveryUnverified)) throw new Error("Git ownership inventory unavailable") return (params.strict - ? await Promise.all(worktrees.map(async worktree => ({ - ...worktree, - normalizedDirectory: await realpath(worktree.directory), - worktreeDirectory: await realpath(worktree.worktreeDirectory), - }))) + ? (await Promise.all(worktrees.map(async worktree => { + const worktreeDirectory = await realpath(worktree.worktreeDirectory) + try { + return { ...worktree, worktreeDirectory, normalizedDirectory: await realpath(worktree.directory) } + } catch (error) { + // A nested project folder may exist in only some registered checkouts. + if ((error as NodeJS.ErrnoException).code === "ENOENT" && worktree.slug !== "root" && worktree.directory !== worktree.worktreeDirectory) return null + throw error + } + }))).filter((worktree): worktree is NonNullable => worktree !== null) : 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) + let entry = await getCachedWorktrees(params, budget.restarts === 3, budget) if (!params.strict && entry.resolvedDirectories.has(target)) return entry.resolvedDirectories.get(target)! let match = await find(entry.worktrees) - if (worktreeCache.get(params.workspaceId) !== entry) return resolveOwnedWorktreePath(params) - if (!entry.refreshedOnMiss && (!match || (match.slug === "root" && match.normalizedDirectory !== target))) { + if (worktreeCache.get(params.workspaceId) !== entry) { + restartWorktreeRead(budget) + return resolveOwnedWorktreePath(params, budget) + } + if (budget.restarts < 3 && !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 = await find(entry.worktrees) } - if (worktreeCache.get(params.workspaceId) !== entry) return resolveOwnedWorktreePath(params) + if (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) return resolved diff --git a/packages/server/src/workspaces/worktree-inventory.test.ts b/packages/server/src/workspaces/worktree-inventory.test.ts index c32e100875..eba986f5a5 100644 --- a/packages/server/src/workspaces/worktree-inventory.test.ts +++ b/packages/server/src/workspaces/worktree-inventory.test.ts @@ -115,6 +115,28 @@ 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") + 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("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..85c71b7efe 100644 --- a/packages/server/src/workspaces/worktree-inventory.ts +++ b/packages/server/src/workspaces/worktree-inventory.ts @@ -57,7 +57,7 @@ export class WorktreeInventory { this.entries.delete(id) } - private load(id: string, entry: Entry): Promise { + private load(id: string, entry: Entry, restarts = 0): Promise { if (entry.pending) return entry.pending const revision = entry.revision const previous = entry.value @@ -66,8 +66,9 @@ export class WorktreeInventory { if (revision !== entry.revision) { // A mutation overtook the scan. Serialize one trailing validation rather // than publishing obsolete data or starting overlapping Git process fans. + if (restarts >= 3) throw new Error("Worktree ownership inventory changed repeatedly") entry.pending = undefined - return this.load(id, entry) + return this.load(id, entry, restarts + 1) } entry.value = value entry.expiresAt = this.now() + MAX_AGE_MS diff --git a/packages/ui/src/components/mission-editor.tsx b/packages/ui/src/components/mission-editor.tsx index 40ec25e342..eba7c55d92 100644 --- a/packages/ui/src/components/mission-editor.tsx +++ b/packages/ui/src/components/mission-editor.tsx @@ -1,6 +1,6 @@ import { For, Show, createEffect, createMemo, createSignal, createUniqueId, onCleanup } from "solid-js" import type { MissionPanelMap } from "../../../server/src/api-types" -import { compareModelError, freezeCompareProfiles, sameCompareModel, type MissionProfiles } from "../../../server/src/missions/playbook-profiles" +import { compareModelError, sameCompareModel, type MissionProfiles } from "../../../server/src/missions/playbook-profiles" import { serverApi } from "../lib/api-client" import { useI18n } from "../lib/i18n" import { deletionErrorKey, missionCleanupPending, MissionDeletionError } from "../lib/mission-cleanup" @@ -12,7 +12,7 @@ import { copyMissionProfiles, holdMissionCreation, missionCreationHold, missionC import { MissionProfileControls } from "./mission-profile-controls" import { missionProfileRoles, profilesForTemplate } from "./mission-profile-controls-data" import { useConfig } from "../stores/preferences" -import { missionDefaultsFor, missionTaskModeFor, normalizeMissionDefaults, type MissionTaskMode } from "../lib/mission-defaults" +import { effectiveMissionProfiles, missionTaskModeFor, normalizeMissionDefaults, type MissionTaskMode } from "../lib/mission-defaults" import type { MissionProfileDefault } from "../lib/mission-defaults" import { retainSubmittedMissionModel, submittedMissionModel, type UserMissionModel } from "../lib/mission-model-library" import { MissionBriefPicker, MissionBriefSave } from "./mission-model-library" @@ -117,7 +117,7 @@ export function MissionEditor(props: { const [defaultsRefreshing, setDefaultsRefreshing] = createSignal(false) const [defaultsFailed, setDefaultsFailed] = createSignal(false) const creationReady = () => defaultsReady() && (kind !== "create" || Boolean(held || recurrenceHold) || config.isUiConfigLoaded()) - const effectiveProfiles = () => freezeCompareProfiles(template(), profiles()) + const effectiveProfiles = () => effectiveMissionProfiles(template(), { profiles: profiles() }).payload const compareError = () => template() === "compare" ? compareModelError(profiles()) : undefined const judgeWarning = () => template() === "compare" && ["model-a", "model-b"].some(role => sameCompareModel(effectiveProfiles()?.roles?.comparator?.model, profiles()?.roles?.[role]?.model)) @@ -130,7 +130,7 @@ export function MissionEditor(props: { createEffect(() => { if (defaultsReady() || !config.isUiConfigLoaded() || !config.missionDefaultsValid()) return const loaded = normalizeMissionDefaults(config.preferences().missionProfileDefaults) - setDefaults(loaded); setProfiles(missionDefaultsFor(loaded, template())); setTaskMode(missionTaskModeFor(loaded, template())) + setDefaults(loaded); setProfiles(effectiveMissionProfiles(template(), { defaults: loaded }).draft); setTaskMode(missionTaskModeFor(loaded, template())) setDefaultsReady(true) }) const [recurrenceUncertain, setUncertain] = createSignal(Boolean(recurrenceHold)) @@ -241,7 +241,7 @@ export function MissionEditor(props: { if (!current()) return if (!config.missionDefaultsValid()) throw new Error("Invalid mission defaults") const loaded = normalizeMissionDefaults(config.preferences().missionProfileDefaults) - setDefaults(loaded); setProfiles(missionDefaultsFor(loaded, template())); setTaskMode(missionTaskModeFor(loaded, template())) + setDefaults(loaded); setProfiles(effectiveMissionProfiles(template(), { defaults: loaded }).draft); setTaskMode(missionTaskModeFor(loaded, template())) setCustomProfiles(false); setCustomTaskMode(false); setDefaultsReady(true) } catch { if (current()) setDefaultsFailed(true) } finally { if (current()) setDefaultsRefreshing(false) } @@ -435,14 +435,16 @@ export function MissionEditor(props: { setObjective(model.objective); setTitleOverride(undefined); setNotes(model.notes); setTemplate(model.template); setSelectedModel({ id: model.id, name: model.name }) setCustomProfiles(model.profiles !== undefined) setCustomTaskMode(model.taskMode !== undefined); setTaskMode(model.taskMode ?? missionTaskModeFor(defaults(), model.template)) - setProfiles(model.profiles === undefined ? missionDefaultsFor(defaults(), model.template) : copyMissionProfiles(model.profiles)) + setProfiles(effectiveMissionProfiles(model.template, model.profiles === undefined + ? { defaults: defaults() } : { profiles: copyMissionProfiles(model.profiles) }).draft) }} /> {/* The selected playbook's one-sentence description stays visible under its selector. */}