diff --git a/dev-docs/MISSIONS_NATIVE_CONTRACTS.md b/dev-docs/MISSIONS_NATIVE_CONTRACTS.md index 6c0fc1f51..e7c67703c 100644 --- a/dev-docs/MISSIONS_NATIVE_CONTRACTS.md +++ b/dev-docs/MISSIONS_NATIVE_CONTRACTS.md @@ -430,6 +430,12 @@ responses identify the reason, provenance, layer, discovered path, `openable` an in the existing global config-file inventory; environment refusals expose their source through the information tip. +An activation refusal before any document mutation, for an identity without an +existing intent, includes `notApplied: { requestID, expectedRevision }`. This exact +proof releases that local request for a fresh explicit Start after configuration +correction. A refusal after a document mutation attempt or for an existing intent +retains the original request and its explicit receipt recovery. + Native regression: `node --import tsx scripts/test-mission-experimental-settings-native.mjs `. It exercises real discovery/whole-block precedence/watcher acknowledgement and diff --git a/packages/server/src/server/routes/mission-schedule-activation.test.ts b/packages/server/src/server/routes/mission-schedule-activation.test.ts index 4405d1d56..e3acb5ffc 100644 --- a/packages/server/src/server/routes/mission-schedule-activation.test.ts +++ b/packages/server/src/server/routes/mission-schedule-activation.test.ts @@ -36,6 +36,7 @@ async function fixture(run: (f: any) => Promise) { launch: { timing: { kind: "every", intervalMs: 900_000 }, condition: null, ends: { at: null, afterMs: null, maxLaunches: null } }, }, Date.now(), () => true) let owned = true, current = true, lose = false + let afterPhase: ((action: string) => Promise) | undefined const connection: any = { endpoint: { url: "http://127.0.0.1:1234" }, assertCurrent() { if (!current) throw Error("retired") }, fetch: async () => Response.json(nativeScheduleContractFixture()), client: { location: { get: async () => ({ directory: project, project: { id: "project", canonical: project, directory: project } }) }, @@ -48,6 +49,7 @@ async function fixture(run: (f: any) => Promise) { documentActivation: async (input: any) => { phases.push(input.action) const result = await applyMissionDocumentActivation(documents, input, () => true, project) + await afterPhase?.(input.action) if (lose && input.action === "acknowledged" && input.scope === "project") { lose = false; throw Error("lost native reply") } return result } }), @@ -65,6 +67,7 @@ async function fixture(run: (f: any) => Promise) { const url = "/api/workspaces/w/missions/msn_scheduled/schedule-settings" const headers = { authorization: "Bearer fixture" }, payload = { requestID: "activate-original", expectedDocumentRevision: 0 } try { await run({ app, url, headers, payload, documents, values, phases, globalFile, projectFile, + afterPhase: (callback: typeof afterPhase) => { afterPhase = callback }, owned: (value: boolean) => { owned = value }, current: (value: boolean) => { current = value }, lose: () => { lose = true } }) } finally { await app.close(); await chmod(globalFile, 0o600).catch(() => {}); await rm(root, { recursive: true, force: true }) } } @@ -116,22 +119,48 @@ test("already ON creates an empty ready proof and a fresh preparation preserves assert.deepEqual(next.json().document, before) assert.equal(await readFile(f.projectFile, "utf8"), original) await writeFile(f.projectFile, '{"experimental":{"schedules":false}}') - const refused = await f.app.inject({ method: "POST", url: f.url, headers: f.headers, - payload: { requestID: "fresh-request", expectedDocumentRevision: before.revision } }) + const refused = await f.app.inject({ method: "POST", url: f.url, headers: f.headers, payload: f.payload }) assert.equal(refused.statusCode, 403, refused.body) assert.equal(refused.json().code, "schedule-activation-refused") + assert.equal(refused.json().notApplied, undefined, "the ready original identity remains retained") assert.deepEqual((await f.documents.read("msn_scheduled")).scheduleActivation, before.scheduleActivation) })) test("an explicit hidden global OFF returns its layer/path without editor authorization or writes", async () => fixture(async f => { await writeFile(f.globalFile, '{"experimental":{"schedules":false}}') await writeFile(f.projectFile, '{"experimental":{"schedules":true}}') + const before = await f.documents.read("msn_scheduled") + const files = await Promise.all([f.globalFile, f.projectFile].map(file => readFile(file, "utf8"))) const response = await f.app.inject({ method: "POST", url: f.url, headers: f.headers, payload: f.payload }) assert.equal(response.statusCode, 403, response.body) assert.equal(response.json().code, "schedule-activation-refused") assert.deepEqual(response.json().refusal, { reason: "explicit-off", provenance: "experimental-block", layer: "global", path: f.globalFile, openable: false }) - assert.equal((await f.documents.read("msn_scheduled")).scheduleActivation, null) + assert.deepEqual(response.json().notApplied, { requestID: f.payload.requestID, expectedRevision: 0 }) + assert.deepEqual(await f.documents.read("msn_scheduled"), before) + assert.deepEqual(f.phases, ["read"], "no mutation is attempted for a definitive refusal") + assert.deepEqual(await Promise.all([f.globalFile, f.projectFile].map(file => readFile(file, "utf8"))), files) + await writeFile(f.globalFile, '{"experimental":{"subagent_depth":2}}') + const next = await f.app.inject({ method: "POST", url: f.url, headers: f.headers, + payload: { requestID: "explicit-after-correction", expectedDocumentRevision: 0 } }) + assert.equal(next.statusCode, 200, next.body) + assert.equal(next.json().document.state, "paused") +})) + +test("OFF after intent preparation and on its exact retry retains uncertainty without no-effect proof", async () => fixture(async f => { + f.afterPhase(async (action: string) => { + if (action === "prepare") await writeFile(f.projectFile, '{"experimental":{"schedules":false}}') + }) + const response = await f.app.inject({ method: "POST", url: f.url, headers: f.headers, payload: f.payload }) + assert.equal(response.statusCode, 403, response.body) + assert.equal(response.json().code, "schedule-activation-refused") + assert.equal(response.json().notApplied, undefined) + const doc = await f.documents.read("msn_scheduled") + assert.equal(doc.scheduleActivation.requestID, f.payload.requestID) + assert.equal(doc.scheduleActivation.state, "failed") + const retry = await f.app.inject({ method: "POST", url: f.url, headers: f.headers, payload: f.payload }) + assert.equal(retry.statusCode, 403, retry.body) + assert.equal(retry.json().notApplied, undefined) })) test("a ready legacy two-target proof retains its original identity and digests on fresh preparation", async () => fixture(async f => { diff --git a/packages/server/src/server/routes/mission-schedule-activation.ts b/packages/server/src/server/routes/mission-schedule-activation.ts index c94d050db..a213e01fc 100644 --- a/packages/server/src/server/routes/mission-schedule-activation.ts +++ b/packages/server/src/server/routes/mission-schedule-activation.ts @@ -26,11 +26,13 @@ export function registerMissionScheduleActivation(app: FastifyInstance, deps: De ? { ...raw, expectedDocumentRevision: Number((raw as Record).expectedDocumentRevision) } : raw) if (!selected.success || !input.success) return reply.code(400).send({ error: "Invalid Mission activation request" }) const lifetime = requestAdmission(request, reply) + let noEffect = false try { const owned = await prepareMissionMapMutation({ manager: deps.workspaceManager, fence: deps.worktreeDeletionFence, workspaceID: selected.data.id, signal: lifetime.signal, wait: lifetime.wait }) return await owned.run(async (rpc, options) => { const guarded = { documentActivation: async (...args: Parameters) => { + if ((args[0] as { action?: unknown } | undefined)?.action !== "read") noEffect = false await owned.refresh() return rpc.documentActivation(...args) } } @@ -42,6 +44,7 @@ export function registerMissionScheduleActivation(app: FastifyInstance, deps: De return reply.code(409).send({ error: "Mission schedule preparation unavailable", code: "schedule-activation-unavailable" }) const previous = before.scheduleActivation const same = previous?.requestID === input.data.requestID && previous.expectedRevision === input.data.expectedDocumentRevision + noEffect = !same if (previous?.state === "ready" && (same || before.revision === input.data.expectedDocumentRevision)) { await deps.scheduleSettingsActivation.verify(selected.data.id, options.location, previous.authority) await owned.refresh() @@ -62,6 +65,7 @@ export function registerMissionScheduleActivation(app: FastifyInstance, deps: De await deps.scheduleSettingsActivation.apply(selected.data.id, options.location, intent, adapter.journal) return { document: await adapter.read() } } catch (error) { + if (noEffect && missionScheduleActivationRefusal(error)) throw error const code = error instanceof PluginControlsError ? `configuration-${error.kind}` : "configuration-unconfirmed" // This records metadata only. Attempt markers and successful writes // survive failure; an uncertain target is never rolled back/replayed. @@ -74,7 +78,8 @@ export function registerMissionScheduleActivation(app: FastifyInstance, deps: De ? error.kind === "forbidden" ? 403 : error.kind === "invalid" ? 400 : error.kind === "conflict" ? 409 : 503 : 503 const refusal = missionScheduleActivationRefusal(error) return reply.code(status).send({ error: "Mission schedule configuration remains unconfirmed", - code: refusal ? "schedule-activation-refused" : "schedule-activation-pending", ...(refusal ? { refusal } : {}) }) + code: refusal ? "schedule-activation-refused" : "schedule-activation-pending", ...(refusal ? { refusal, + ...(noEffect ? { notApplied: { requestID: input.data.requestID, expectedRevision: input.data.expectedDocumentRevision } } : {}) } : {}) }) } finally { lifetime.dispose() } }, }) diff --git a/packages/ui/src/components/mission-schedule-controls.ts b/packages/ui/src/components/mission-schedule-controls.ts index 4d339b932..fb6099c91 100644 --- a/packages/ui/src/components/mission-schedule-controls.ts +++ b/packages/ui/src/components/mission-schedule-controls.ts @@ -181,10 +181,13 @@ export function createMissionScheduleControls(props: { instanceId: string; proje if (current()) props.refresh() } catch (error) { if (error instanceof HttpResponseError && error.code === "schedule-activation-refused") { - const body = error.body as { refusal?: ActivationRefusal } | undefined + const body = error.body as { refusal?: ActivationRefusal; notApplied?: { requestID?: string; expectedRevision?: number } } | undefined + if (dispatched?.phase === "activation" && holds.get(key) === dispatched + && body?.notApplied?.requestID === dispatched.requestID && body.notApplied.expectedRevision === dispatched.expectedRevision) { + holds.delete(key); bump() + } if (current()) { setRefusal(body?.refusal); setFeedback("missions.scheduleList.activationRefused") } - // A refusal after dispatch may follow an attempted write. Keep the exact - // activation until an explicit receipt read proves its outcome. + // Without exact no-effect proof, preserve the original activation. } else if (dispatched?.phase === "activation" && error instanceof HttpResponseError && ["schedule-activation-conflict", "schedule-activation-unavailable"].includes(error.code ?? "") && holds.get(key) === dispatched) { holds.delete(key); bump() diff --git a/packages/ui/src/components/mission-schedule-list.tsx b/packages/ui/src/components/mission-schedule-list.tsx index f4fc55311..895e3e8c4 100644 --- a/packages/ui/src/components/mission-schedule-list.tsx +++ b/packages/ui/src/components/mission-schedule-list.tsx @@ -73,7 +73,8 @@ export function createMissionScheduleList(props: { instanceId: string; projectID enabled: () => props.enabled() && !list.error() && list.fresh(id), refreshVersion: () => props.refresh + revision(), refresh, onDeleted: () => props.onDeleted(id) }) const [expanded, expand] = createSignal(false) - const primary = () => (["pause", "resume", "play"] as const).find(action => doc().availableActions.includes(action)) + const primary = () => (["pause", "resume", "play"] as const).find(action => controls.pendingAction() === action) + ?? (["pause", "resume", "play"] as const).find(action => doc().availableActions.includes(action)) const action = (name: "play" | "resume" | "pause" | "stop" | "run-now") => ({ key: name, label: controls.label(name), disabled: !controls.capable(name), busy: controls.pendingAction() === name, onSelect: () => controls.act(name) }) const status = () => controls.progress() ?? (controls.held() ? controls.busy() ? undefined diff --git a/packages/ui/tests/browser/mission-schedule-list.test.ts b/packages/ui/tests/browser/mission-schedule-list.test.ts index 3dd6ab725..c979a143e 100644 --- a/packages/ui/tests/browser/mission-schedule-list.test.ts +++ b/packages/ui/tests/browser/mission-schedule-list.test.ts @@ -492,18 +492,28 @@ test("unselected unified passages prioritize their coordinator and descendant re } finally { await page.close() } }) -for (const action of ["Resume", "Run now"] as const) +for (const action of ["Start", "Pause", "Resume", "Run now"] as const) test(`${action} loads only its requested button and keeps Run now confirmation separate`, async () => { const page = await browser.newPage(), f = await setup(page, { seed: true }) const gate = deferred(), submitted = deferred() try { await f.change(doc => { - doc.firstPlayedAt = Date.now(); doc.state = "paused" + if (action !== "Start") doc.firstPlayedAt = Date.now() + doc.state = action === "Pause" ? "running" : "paused" doc.scheduleActivation = { requestID: "ready_activation", expectedRevision: 0, authority: "a".repeat(64), state: "ready", targets: [], effectiveOrigin: null } }) await page.evaluate(() => (window as any).missionFixture.refresh()); await select(page) await page.route("**/msn_schedule/schedule", async route => { - if (route.request().method() === "POST") { submitted.resolve(); await gate.promise } + if (route.request().method() === "POST") { + submitted.resolve(); await gate.promise + if (action !== "Run now") { + const request = route.request().postDataJSON() + f.posts.push(request) + const value = f.result() + return route.fulfill({ json: { ...value, pending: false, + document: { ...value.document, control: { ...request, pending: false } } } }) + } + } return route.fallback() }) await button(page, action).click() @@ -514,9 +524,21 @@ test(`${action} loads only its requested button and keeps Run now confirmation s await dialog.getByRole("button", { name: action, exact: true }).click() } await submitted.promise + if (action !== "Run now") { + const published = page.waitForResponse(async response => new URL(response.url()).pathname.endsWith("/missions/scheduled") + && (await response.json()).schedules?.some((row: any) => row.state === (action === "Pause" ? "paused" : "running"))) + await f.change(doc => { + if (action === "Start") { changes.play(doc, "early-publication", Date.now(), []); doc.synchronization = null } + else doc.state = action === "Pause" ? "paused" : "running" + }) + await page.evaluate(() => (window as any).missionFixture.refresh()) + await (await published).finished() + await page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)))) + } assert.equal(await button(page, action).getAttribute("aria-busy"), "true") assert.equal(await page.locator(".mission-action-bar [aria-busy=true]").count(), 1) - assert.equal(await page.locator(".mission-picker-selection-actions [role=status]").textContent(), action === "Resume" ? "Resuming…" : "Starting run…") + assert.equal(await page.locator(".mission-picker-selection-actions [role=status]").textContent(), action === "Resume" ? "Resuming…" + : action === "Start" ? "Starting…" : action === "Run now" ? "Starting run…" : "Saving…") gate.resolve() await page.waitForFunction(() => !document.querySelector(".mission-action-bar [aria-busy=true]")) assert.equal(f.posts.length, 1); assert.equal(f.activations.length, 0) @@ -595,6 +617,45 @@ test("structured server OFF after dispatch retains its exact activation and a fa } finally { await page.close() } }) +for (const proof of ["exact", "foreign-request", "foreign-revision"] as const) +test(`OFF refusal with ${proof} no-effect proof only releases the exact activation for explicit Start`, async () => { + const page = await browser.newPage(), f = await setup(page, { seed: true }) + let request: any, attempts = 0 + try { + await select(page) + await page.route("**/schedule-settings", async route => { + if (route.request().method() === "GET" || attempts++) return route.fallback() + request = route.request().postDataJSON() + return route.fulfill({ status: 403, json: { code: "schedule-activation-refused", + notApplied: { requestID: proof === "foreign-request" ? "other" : request.requestID, + expectedRevision: request.expectedDocumentRevision + (proof === "foreign-revision" ? 1 : 0) }, + refusal: { reason: "explicit-off", provenance: "environment", layer: "environment", openable: false } } }) + }) + const refused = page.waitForResponse(response => new URL(response.url()).pathname.endsWith("/schedule-settings") + && response.request().method() === "POST" && response.status() === 403) + await click(page, "Play"); await (await refused).finished() + await page.waitForFunction(() => !document.querySelector(".mission-action-bar [aria-busy=true]")) + assert.equal(f.doc.scheduleActivation, null) + assert.equal(f.posts.length, 0, "refusal never sends Play") + await page.evaluate(() => (window as any).missionFixture.refresh()) + if (proof === "exact") { + await button(page, "Start").and(page.locator(":enabled")).waitFor() + assert.equal(await button(page, "Refresh saved request").count(), 0) + assert.equal(f.posts.length, 0, "configuration correction and refresh never start Play") + await click(page, "Play") + await button(page, "Pause").and(page.locator(":enabled")).waitFor() + assert.equal(f.posts.filter(post => post.action === "play").length, 1) + assert.notEqual(f.activation?.requestID, request.requestID) + } else { + await button(page, "Refresh saved request").click() + await button(page, "Refresh saved request").and(page.locator(":enabled")).waitFor() + assert.equal(await button(page, "Start").isDisabled(), true) + assert.equal(f.posts.length, 0, "a negative receipt cannot release a mismatched proof") + } + assert.deepEqual(f.errors, []) + } finally { await page.close() } +}) + for (const scenario of ["control ACK", "recovered control", "activation ACK", "recovered activation"] as const) test(`confirmed publication barrier retains ${scenario} across stale inventory and remount`, async () => { const page = await browser.newPage(), activation = scenario.includes("activation")