From 5d29fa89e0b259c10d78354ff8fca50ce32f2066 Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Tue, 17 Nov 2026 15:30:34 -0500 Subject: [PATCH] fix(server): a moved thread's fence lifts only for a message a person sent from the app The fence lifted for any turn without an automatic marker, so command output delivered after the agent went idle, or an auto-fix requeued behind a continue, could lift it. It now lifts only when the message carries sentFrom, which only the server sets from the connection's sign-in, and isn't imported or written for the move; imported queued messages lose any peer-supplied sentFrom. keepsMoveFence is gone, since it only patched the old rule. Found in the outside review of #977. --- apps/server/src/links/LinkMoves.ts | 2 +- .../Layers/ProjectionPipeline.test.ts | 2 + .../Layers/ProviderCommandReactor.test.ts | 2 + .../Layers/PullRequestAutomationWatcher.ts | 2 - .../orchestration/decider.threadMoves.test.ts | 149 +++++++++++++++++- apps/server/src/orchestration/decider.ts | 17 +- apps/server/src/orchestration/linkFence.ts | 42 ++++- .../src/orchestration/threadMoveDecisions.ts | 11 +- docs/design/fleet.md | 4 +- packages/contracts/src/orchestration.ts | 10 +- 10 files changed, 209 insertions(+), 32 deletions(-) diff --git a/apps/server/src/links/LinkMoves.ts b/apps/server/src/links/LinkMoves.ts index cfe85bb91..160f00ad9 100644 --- a/apps/server/src/links/LinkMoves.ts +++ b/apps/server/src/links/LinkMoves.ts @@ -2053,7 +2053,7 @@ const make = Effect.gen(function* () { (attachment) => input.attachments.get(attachment.id) ?? attachment, ), ...(entry.composer !== undefined ? { composer: entry.composer } : {}), - ...(entry.sentFrom !== undefined ? { sentFrom: entry.sentFrom } : {}), + // Not `sentFrom`: only this server stamps it (decideThreadImport drops one too). runtimeMode: input.runtimeMode, interactionMode: input.interactionMode, createdAt: entry.createdAt, diff --git a/apps/server/src/orchestration/Layers/ProjectionPipeline.test.ts b/apps/server/src/orchestration/Layers/ProjectionPipeline.test.ts index 94f1ef392..fe8d47eef 100644 --- a/apps/server/src/orchestration/Layers/ProjectionPipeline.test.ts +++ b/apps/server/src/orchestration/Layers/ProjectionPipeline.test.ts @@ -2737,6 +2737,8 @@ engineLayer("OrchestrationProjectionPipeline via engine dispatch", (it) => { }, runtimeMode: "approval-required", interactionMode: "default", + // Stamped from the app's sign-in, as the server does for a person's send. + sentFrom: { kind: "computer", place: "here" }, createdAt, }); const lifted = yield* movedFromNow(); diff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts index 33101e5c3..d7057b1c5 100644 --- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts +++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts @@ -3493,6 +3493,8 @@ describe("ProviderCommandReactor", () => { message: { messageId: asMessageId("user-here"), role: "user", text: "go", attachments: [] }, interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, runtimeMode: "full-access", + // Stamped from the app's sign-in, as the server does for a person's send. + sentFrom: { kind: "computer", place: "here" }, createdAt: now, }); await waitFor( diff --git a/apps/server/src/orchestration/Layers/PullRequestAutomationWatcher.ts b/apps/server/src/orchestration/Layers/PullRequestAutomationWatcher.ts index 069cb4b91..cedead440 100644 --- a/apps/server/src/orchestration/Layers/PullRequestAutomationWatcher.ts +++ b/apps/server/src/orchestration/Layers/PullRequestAutomationWatcher.ts @@ -604,8 +604,6 @@ const makePullRequestAutomationWatcher = (options?: PullRequestAutomationWatcher modelSelection: input.thread.modelSelection, runtimeMode: input.thread.runtimeMode, interactionMode: input.thread.interactionMode, - // Its message is ours, not the user's: a moved thread stays fenced. - keepsMoveFence: true, createdAt, }) .pipe( diff --git a/apps/server/src/orchestration/decider.threadMoves.test.ts b/apps/server/src/orchestration/decider.threadMoves.test.ts index 26c27dba4..4ef880868 100644 --- a/apps/server/src/orchestration/decider.threadMoves.test.ts +++ b/apps/server/src/orchestration/decider.threadMoves.test.ts @@ -1,5 +1,6 @@ import { CommandId, + CommandRunId, EnvironmentId, EventId, MessageId, @@ -1428,7 +1429,9 @@ describe("a move carries what its thread had going (Part 3e)", () => { describe("what a moved thread is trusted with (Part 3e, security changes)", () => { const ARRIVED = ThreadId.make("thread-arrived-fenced"); const PULL_REQUEST = { number: 212, url: "https://github.com/acme/w/pull/212" }; - const imported = async () => + /** Where the server says a person's message came from (withMessageSentFrom). */ + const AT_THIS_COMPUTER = { kind: "computer", place: "here" } as const; + const imported = async (extra: Record = {}) => ( await apply(await seeded(), { type: "thread.import", @@ -1463,6 +1466,8 @@ describe("what a moved thread is trusted with (Part 3e, security changes)", () = messageId: MessageId.make("q-there"), text: "and then this", attachments: [], + // The other computer's word for where it was sent from. + sentFrom: AT_THIS_COMPUTER, runtimeMode: "auto", interactionMode: "default", createdAt: now, @@ -1474,8 +1479,28 @@ describe("what a moved thread is trusted with (Part 3e, security changes)", () = left: [], }, createdAt: now, - }) + ...extra, + } as OrchestrationCommand) ).model; + /** Arrived with nothing queued, so each case queues its own message. */ + const importedEmpty = () => imported({ queuedFollowUps: [], arrival: undefined }); + const withSession = ( + model: OrchestrationReadModel, + status: OrchestrationSession["status"], + activeTurnId: TurnId | null = null, + ) => + project(model, "thread.session-set", { + threadId: ARRIVED, + session: { + threadId: ARRIVED, + status, + providerName: "codex", + runtimeMode: "auto", + activeTurnId, + lastError: null, + updatedAt: now, + }, + }); const userTurn = (extra: Record = {}): OrchestrationCommand => ({ type: "thread.turn.start", @@ -1531,6 +1556,10 @@ describe("what a moved thread is trusted with (Part 3e, security changes)", () = it("the arrival and the move's queued messages leave the fence up; the user's own message here lifts it", async () => { let model = await imported(); expect(threadOf(model, ARRIVED).movedFrom?.fenced).toBe(true); + // Only this server says where a message came from: the other computer's word is dropped. + expect( + threadOf(model, ARRIVED).queuedFollowUps?.find((entry) => entry.messageId === "q-there"), + ).not.toHaveProperty("sentFrom"); // The arrival kick, then the user's message from there. let refusal: string | null; ({ model, refusal } = await apply(model, sendQueued("m-arrival"))); @@ -1557,8 +1586,9 @@ describe("what a moved thread is trusted with (Part 3e, security changes)", () = expect(threadOf(model, ARRIVED).queuedFollowUps ?? []).toHaveLength(0); expect(threadOf(model, ARRIVED).movedFrom?.fenced).toBe(true); - // Pull request auto-fix, and a restart's resume, are Threadlines' words, not the user's. - for (const extra of [{ keepsMoveFence: true }, { trigger: "serverRestart" }]) { + // Pull request auto-fix (no device, as Threadlines sends it) and a + // restart's resume are not a person here. + for (const extra of [{}, { trigger: "serverRestart", sentFrom: AT_THIS_COMPUTER }]) { const decided = await Effect.runPromise( decideOrchestrationCommand({ readModel: model, command: userTurn(extra) }), ); @@ -1567,11 +1597,120 @@ describe("what a moved thread is trusted with (Part 3e, security changes)", () = expect(requested?.payload).not.toHaveProperty("liftsMoveFence"); } - ({ model } = await apply(model, userTurn())); + ({ model } = await apply(model, userTurn({ sentFrom: AT_THIS_COMPUTER }))); expect(threadOf(model, ARRIVED).movedFrom?.fenced).toBeUndefined(); // The rest of where it came from stays. expect(threadOf(model, ARRIVED).movedFrom).toMatchObject({ label: "Mac mini" }); }); + + it("a person's queued message lifts the fence once it is sent", async () => { + const turn = TurnId.make("turn-busy"); + let model = await withSession(await importedEmpty(), "running", turn); + let refusal: string | null; + ({ model, refusal } = await apply(model, { + type: "thread.follow-up.submit", + commandId: nextCommandId(), + threadId: ARRIVED, + turnId: turn, + message: { + messageId: MessageId.make("m-when-done"), + role: "user", + text: "Then this", + attachments: [], + }, + delivery: "queue", + composer: "typed", + sentFrom: AT_THIS_COMPUTER, + createdAt: now, + })); + expect(refusal).toBeNull(); + model = await withSession(model, "ready"); + ({ model, refusal } = await apply(model, sendQueued("m-when-done"))); + expect(refusal).toBeNull(); + expect(threadOf(model, ARRIVED).movedFrom?.fenced).toBeUndefined(); + }); + + it("command output sent once the agent is idle leaves the fence up", async () => { + let model = await withSession(await importedEmpty(), "ready"); + model = await project(model, "thread.command-run-started", { + threadId: ARRIVED, + run: { + runId: "run-1", + terminalId: "terminal-run", + mode: "run", + dialect: "posix", + command: "pnpm test", + source: { kind: "request", requestId: "request-1" }, + turnId: "turn-asked", + participantId: null, + cwd: "/worktrees/moved-fenced", + autoSend: true, + }, + createdAt: now, + }); + let refusal: string | null; + ({ model, refusal } = await apply(model, { + type: "thread.command-run.deliver-output", + commandId: nextCommandId(), + threadId: ARRIVED, + runId: CommandRunId.make("run-1"), + automatic: true, + message: { messageId: MessageId.make("command-output:run-1"), text: "I ran pnpm test" }, + createdAt: now, + })); + expect(refusal).toBeNull(); + expect(threadOf(model, ARRIVED).queuedFollowUps).toMatchObject([ + { messageId: "command-output:run-1" }, + ]); + ({ model, refusal } = await apply(model, sendQueued("command-output:run-1"))); + expect(refusal).toBeNull(); + expect(threadOf(model, ARRIVED).messages.at(-1)).toMatchObject({ + id: "command-output:run-1", + }); + expect(threadOf(model, ARRIVED).movedFrom?.fenced).toBe(true); + }); + + it("pull request auto-fix that waited behind a continue leaves the fence up when it starts alone", async () => { + let model = await withSession(await importedEmpty(), "ready"); + let refusal: string | null; + // A restart's continue, still starting. + ({ model, refusal } = await apply( + model, + userTurn({ + message: { + messageId: MessageId.make("m-continue"), + role: "user", + text: "Continue where you left off.", + attachments: [], + }, + trigger: "serverRestart", + }), + )); + expect(refusal).toBeNull(); + // Auto-fix's turn, as the watcher sends it: it overtakes the continue and waits. + ({ model, refusal } = await apply( + model, + userTurn({ + message: { + messageId: MessageId.make("m-auto-fix"), + role: "user", + text: "Fix the failing check", + attachments: [], + }, + modelSelection, + }), + )); + expect(refusal).toBeNull(); + expect(threadOf(model, ARRIVED).queuedFollowUps).toMatchObject([ + { messageId: "m-auto-fix", overtakes: "m-continue" }, + ]); + // The continue never started; the auto-fix goes as its own turn. + model = await withSession(model, "ready"); + ({ model, refusal } = await apply(model, sendQueued("m-auto-fix"))); + expect(refusal).toBeNull(); + expect(threadOf(model, ARRIVED).queuedFollowUps ?? []).toHaveLength(0); + expect(threadOf(model, ARRIVED).movedFrom?.fenced).toBe(true); + }); }); describe("a moved thread that moves on, or edits its goal before its agent knows it (Part 3e)", () => { diff --git a/apps/server/src/orchestration/decider.ts b/apps/server/src/orchestration/decider.ts index b22b9083d..8aad8d2cd 100644 --- a/apps/server/src/orchestration/decider.ts +++ b/apps/server/src/orchestration/decider.ts @@ -114,6 +114,7 @@ import { withinModeCeiling, } from "./childThreadDecisions.ts"; import { childDeliveryForQuietCandidate } from "./childThreadDelivery.ts"; +import { turnLiftsMoveFence } from "./linkFence.ts"; import { projectEvent } from "./projector.ts"; import { checkoutSelectedEvents, leavesLentWorktree, movesCheckout } from "./threadCheckout.ts"; import { canReplaceThreadTitle } from "./threadTitle.ts"; @@ -3456,18 +3457,10 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" ...(command.scheduledTaskId !== undefined ? { scheduledTaskId: command.scheduledTaskId } : {}), - // The user's own message on a thread that moved here fenced: they - // take it over (docs/design/fleet.md, Part 3e). A queued message the - // move carried, or one Threadlines wrote, never does (see - // thread.follow-up.send-queued). - ...(targetThread.movedFrom?.fenced === true && - command.fromThread === undefined && - command.fromOutside === undefined && - command.scheduledTaskId === undefined && - command.trigger === undefined && - command.keepsMoveFence !== true - ? { liftsMoveFence: true as const } - : {}), + // A person's own message on a thread that moved here fenced: they + // take it over (docs/design/fleet.md, Part 3e). Only a message + // proven theirs does (turnLiftsMoveFence). + ...(turnLiftsMoveFence(targetThread, command) ? { liftsMoveFence: true as const } : {}), createdAt: command.createdAt, }, }; diff --git a/apps/server/src/orchestration/linkFence.ts b/apps/server/src/orchestration/linkFence.ts index f73e5eefb..8c95c45a8 100644 --- a/apps/server/src/orchestration/linkFence.ts +++ b/apps/server/src/orchestration/linkFence.ts @@ -7,7 +7,7 @@ * message the user sends here starts a turn in it. Every place the fence * applies asks this one rule. */ -import type { OrchestrationThread } from "@threadlines/contracts"; +import type { MessageId, OrchestrationCommand, OrchestrationThread } from "@threadlines/contracts"; export type LinkFencedThread = Pick; @@ -15,6 +15,46 @@ export type LinkFencedThread = Pick (thread.remoteOrigin ?? null) !== null || thread.movedFrom?.fenced === true; +type TurnStartCommand = Extract; + +/** + * Whether a turn start lifts a moved thread's fence: only one whose message a + * person sent from the app, which `sentFrom` proves (the server alone stamps + * it, from the connection's sign-in; see withMessageSentFrom). An allow-list, + * so whatever else starts a turn (command output, pull request auto-fix, a + * restart or usage-limit continue, a retry, another thread, an outside agent, + * a scheduled task) carries no `sentFrom` and leaves the fence up. A message + * the move carried (`imported`) or Threadlines wrote for it (`afterMove`) + * never lifts it either, whatever it carries. + */ +export function turnLiftsMoveFence( + thread: Pick, + command: Pick< + TurnStartCommand, + "sentFrom" | "fromThread" | "fromOutside" | "scheduledTaskId" | "trigger" + > & { readonly message: { readonly messageId: MessageId } }, +): boolean { + if (thread.movedFrom?.fenced !== true || command.sentFrom === undefined) return false; + if ( + command.fromThread !== undefined || + command.fromOutside !== undefined || + command.scheduledTaskId !== undefined || + command.trigger !== undefined + ) { + return false; + } + const messageId = command.message.messageId; + const carried = (entry: { + readonly imported?: true | undefined; + readonly afterMove?: true | undefined; + }) => entry.imported === true || entry.afterMove === true; + return ( + !(thread.queuedFollowUps ?? []).some( + (entry) => entry.messageId === messageId && carried(entry), + ) && !thread.messages.some((message) => message.id === messageId && carried(message)) + ); +} + /** Why a fenced thread's agent can't use `tools` ("thread tools", "schedule tools"), in its words. */ export function linkFenceRefusal(thread: LinkFencedThread, tools: string): string { return (thread.remoteOrigin ?? null) !== null diff --git a/apps/server/src/orchestration/threadMoveDecisions.ts b/apps/server/src/orchestration/threadMoveDecisions.ts index 37e2c6810..5a8e6183b 100644 --- a/apps/server/src/orchestration/threadMoveDecisions.ts +++ b/apps/server/src/orchestration/threadMoveDecisions.ts @@ -1270,8 +1270,15 @@ function importedState( }, ] : []), - // Sent there by the user, but here by the move: no turn of theirs lifts the fence. - ...(command.queuedFollowUps ?? []).map((entry) => ({ ...entry, imported: true as const })), + // Sent there by the user, but here by the move: no turn of theirs lifts + // the fence. The other computer said where it was sent from, and only + // this server stamps that (MessageSentFrom), so it is dropped. + ...(command.queuedFollowUps ?? []).map( + ({ sentFrom: _peerSaid, ...entry }): OrchestrationQueuedFollowUp => ({ + ...entry, + imported: true as const, + }), + ), ]; for (const followUp of queue) { events.push({ diff --git a/docs/design/fleet.md b/docs/design/fleet.md index 9578435ed..b79f2638b 100644 --- a/docs/design/fleet.md +++ b/docs/design/fleet.md @@ -1288,8 +1288,8 @@ These win over everything above in Part 3e. What a move carries came from anothe - the schedule tools; - continuing it on a schedule. - Work still picks up on arrival as the link's permission allows, fenced. Its mode stays capped by the link's access ceiling, as before. - - **The fence lifts** when a message the user sent on this computer starts a turn in the thread: `liftsMoveFence` on that `thread.turn-start-requested`, which clears `fenced` in every projection. A restart keeps whatever the projection holds. - - **What doesn't lift it:** the arrival message, queued messages the move carried (`imported` on the queued entry), and anything Threadlines or an agent sends: another thread, an outside assistant, a scheduled task, a restart or usage-limit resume, pull request auto-fix (`keepsMoveFence`). + - **The fence lifts** when a message a person sent from the app starts a turn in the thread, directly or from the queue ("send when done"): `liftsMoveFence` on that `thread.turn-start-requested`, which clears `fenced` in every projection. A restart keeps whatever the projection holds. The rule is an allow-list (`turnLiftsMoveFence` in `linkFence.ts`): the message must carry `sentFrom`, which only this server stamps from the connection's sign-in, so nothing Threadlines writes can lift it by forgetting a marker. + - **What doesn't lift it:** the arrival message (`afterMove`), queued messages the move carried (`imported` on the queued entry; the other computer's `sentFrom` on them is dropped at import), and anything Threadlines or an agent sends: command output, another thread, an outside assistant, a scheduled task, a restart or usage-limit resume, a retry, pull request auto-fix. A device the server can't name (no `sentFrom`) can't lift it either. - A session started fenced is restarted with resume at the next start after the lift, so the agent gets its tools. - The "Moved here" line says it: "Its agent can't use other threads, rooms or schedules here until you send it a message." diff --git a/packages/contracts/src/orchestration.ts b/packages/contracts/src/orchestration.ts index 54d0d1e7f..a832684ef 100644 --- a/packages/contracts/src/orchestration.ts +++ b/packages/contracts/src/orchestration.ts @@ -3845,11 +3845,6 @@ export const ThreadTurnStartCommand = Schema.Struct({ trigger: Schema.optional(MessageTrigger), /** Server only: a scheduled or event task's run sent it (see ThreadTurnStartRequestedPayload). */ scheduledTaskId: Schema.optional(ScheduledTaskId), - /** - * Server only: Threadlines wrote it (pull request auto-fix), not the user, - * so it doesn't lift a moved thread's fence (ThreadMovedFrom.fenced). - */ - keepsMoveFence: Schema.optional(Schema.Literal(true)), createdAt: IsoDateTime, }); @@ -6321,8 +6316,9 @@ export const ThreadTurnStartRequestedPayload = Schema.Struct({ */ scheduledTaskId: Schema.optional(ScheduledTaskId), /** - * The user's own message on this computer starts this turn in a thread - * that moved here fenced (ThreadMovedFrom.fenced): the fence lifts. + * A person's own message, sent from the app (its `sentFrom`), starts this + * turn in a thread that moved here fenced (ThreadMovedFrom.fenced): the + * fence lifts. */ liftsMoveFence: Schema.optional(Schema.Literal(true)), createdAt: IsoDateTime,