Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion apps/server/src/links/LinkMoves.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
149 changes: 144 additions & 5 deletions apps/server/src/orchestration/decider.threadMoves.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import {
CommandId,
CommandRunId,
EnvironmentId,
EventId,
MessageId,
Expand Down Expand Up @@ -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<string, unknown> = {}) =>
(
await apply(await seeded(), {
type: "thread.import",
Expand Down Expand Up @@ -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,
Expand All @@ -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<string, unknown> = {}): OrchestrationCommand =>
({
type: "thread.turn.start",
Expand Down Expand Up @@ -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")));
Expand All @@ -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) }),
);
Expand All @@ -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)", () => {
Expand Down
17 changes: 5 additions & 12 deletions apps/server/src/orchestration/decider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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,
},
};
Expand Down
42 changes: 41 additions & 1 deletion apps/server/src/orchestration/linkFence.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,54 @@
* 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<OrchestrationThread, "remoteOrigin" | "movedFrom">;

/** Whether the thread works behind the fence. */
export const isLinkFenced = (thread: LinkFencedThread): boolean =>
(thread.remoteOrigin ?? null) !== null || thread.movedFrom?.fenced === true;

type TurnStartCommand = Extract<OrchestrationCommand, { readonly type: "thread.turn.start" }>;

/**
* 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<OrchestrationThread, "movedFrom" | "messages" | "queuedFollowUps">,
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
Expand Down
11 changes: 9 additions & 2 deletions apps/server/src/orchestration/threadMoveDecisions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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({
Expand Down
4 changes: 2 additions & 2 deletions docs/design/fleet.md
Original file line number Diff line number Diff line change
Expand Up @@ -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."

Expand Down
10 changes: 3 additions & 7 deletions packages/contracts/src/orchestration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
});

Expand Down Expand Up @@ -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,
Expand Down
Loading