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
18 changes: 15 additions & 3 deletions apps/server/src/delivery/BoardConversation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,10 @@ const Detail = Schema.Struct({
conversation: Schema.optional(
Schema.NullOr(
Schema.Struct({
// The marker of an engine that scopes activity to its source (spec 6a amendment): this
// server's resume floor is its own entry in `sourceFloors`. An older engine serves neither.
sourceScoped: Schema.optional(Schema.Boolean),
sourceFloors: Schema.optional(Schema.Record(Schema.String, Schema.Number)),
latest: Schema.optional(
Schema.Array(Schema.Struct({ seq: Schema.Number, setBy: Schema.String })),
),
Expand Down Expand Up @@ -219,9 +223,17 @@ export const make = Effect.gen(function* () {
else {
const read = yield* detail();
if (Option.isNone(read)) return;
const latest = read.value.conversation?.latest?.[0];
if (latest && latest.setBy !== context.environmentId) return;
floor = latest?.seq ?? -1;
const mirrored = read.value.conversation;
if (mirrored?.sourceScoped === true && mirrored.sourceFloors !== undefined) {
// No entry is no floor: the first eligible item goes.
floor = mirrored.sourceFloors[context.environmentId] ?? -1;
} else {
// An engine before the amendment orders by one seq across sources, so another
// environment's latest row is a floor this server's seqs cannot be compared with.
const latest = mirrored?.latest?.[0];
if (latest && latest.setBy !== context.environmentId) return;
floor = latest?.seq ?? -1;
}
}
floors.set(scanKey, floor);
}
Expand Down
63 changes: 63 additions & 0 deletions apps/server/src/delivery/BoardTaskThreads.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -816,6 +816,69 @@ it.effect("mirrors each conversation event once, across a restart and a replaced
}).pipe(Effect.provide(deliveryLayer(engine, "board-threads-mirror-")));
});

const ownSeqs = (engine: ScratchEngine) =>
engine
.activityOf("task-7")
.filter((row) => row.setBy === ENVIRONMENT)
.map((row) => row.seq);

it.effect("mirrors beside another environment on a scoped engine, from its own floor", () => {
const engine = board({ sourceScoped: true });
engine.addTask({ id: "task-7" });
const store = threadStore();
return Effect.gen(function* () {
const first = yield* service(store);
yield* first.reconcile();
engine.writeLink("task-7", { environmentId: OTHER, threadId: THEIRS, setBy: OTHER });
engine.ingestFrom("task-7", { seq: 1, setBy: OTHER });
engine.ingestFrom("task-7", { seq: 90, setBy: OTHER });
engine.writeLink("task-7", {
environmentId: ENVIRONMENT,
threadId: THREAD,
setBy: ENVIRONMENT,
});
store.say(THREAD, "m-1", "One", "system");
store.say(THREAD, "m-2", "Two", "system");
yield* (yield* service(store)).reconcile();
assert.deepEqual(ownSeqs(engine), [1, 2]);
// The same seq from two sources is kept twice.
assert.deepEqual(
engine
.activityOf("task-7")
.filter((row) => row.seq === 1)
.map((row) => row.setBy)
.toSorted(),
[ENVIRONMENT, OTHER].toSorted(),
);
// A restarted server resumes from its own entry in the floors (2), never the other's (90).
store.say(THREAD, "m-3", "Three", "system");
const before = ingests(engine);
yield* (yield* service(store)).reconcile();
assert.deepEqual(ownSeqs(engine), [1, 2, 3]);
assert.equal(ingests(engine), before + 1);
}).pipe(Effect.provide(deliveryLayer(engine, "board-threads-scoped-")));
});

it.effect("stays paused beside another source on an older engine, then resumes", () => {
const engine = board();
engine.addTask({ id: "task-7" });
const store = threadStore();
return Effect.gen(function* () {
const threads = yield* service(store);
yield* threads.reconcile();
engine.ingestFrom("task-7", { seq: 7, setBy: OTHER });
store.say(THREAD, "m-1", "One", "system");
// Without the marker the other source's row would be taken for this one's floor.
yield* threads.reconcile();
yield* threads.reconcile();
assert.equal(ingests(engine), 0);
// The engine is installed under the running server: the pause lifts, from no floor.
engine.setSourceScoped(true);
yield* threads.reconcile();
assert.deepEqual(ownSeqs(engine), [1]);
}).pipe(Effect.provide(deliveryLayer(engine, "board-threads-paused-")));
});

it.effect("delivers a queued steer at the next turn boundary, once, and confirms it", () => {
const engine = board();
engine.addTask({ id: "task-7" });
Expand Down
56 changes: 48 additions & 8 deletions apps/server/src/delivery/boardThreadEngine.testkit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,12 @@ export function scratchEngine(
readonly servesLink?: boolean;
/** `false` models an engine before slice 5: no conversation mirror and no steer queue. */
readonly servesConversation?: boolean;
/**
* `true` models the engine after its source-scoped amendment (spec 6a): activity keyed by
* `(task, setBy, seq)`, and a detail that serves `sourceScoped` and `sourceFloors`. Default is
* the legacy engine, which keys by `(task, seq)` and serves neither.
*/
readonly sourceScoped?: boolean;
} = {},
) {
const key = options.key ?? "scratch approval passphrase";
Expand All @@ -94,6 +100,7 @@ export function scratchEngine(
let clock = Date.parse("2026-11-22T10:00:00.000Z");
let holderSeq = 0;
let down = false;
let sourceScoped = options.sourceScoped === true;
/** Link writes the engine is answering now, and the most it ever answered at once. */
const linkWrites = { inFlight: 0, most: 0 };
/** Runs once, just before the next link write is admitted: another writer getting in first. */
Expand All @@ -119,12 +126,43 @@ export function scratchEngine(
...(options.servesLink === false ? {} : { boardThread: links.get(task.id) ?? null }),
...(conversing ? { conversation: mirrorOf(task.id), steers: steerCounts(task.id) } : {}),
});
/** Each source's highest seq; a row below its source's floor is superseded. */
const floorsOf = (rows: ReadonlyArray<Activity>) => {
const floors = new Map<string, number>();
for (const row of rows) floors.set(row.setBy, Math.max(floors.get(row.setBy) ?? -1, row.seq));
return floors;
};
const mirrorOf = (id: string) => {
const rows = activity.get(id) ?? [];
if (rows.length === 0) return null;
const top = rows.reduce((a, b) => (b.seq > a.seq ? b : a));
// Scoped: the last-arrived row that stands. Legacy: the highest seq, whoever sent it.
const floors = floorsOf(rows);
const top = sourceScoped
? rows.findLast((row) => row.seq === floors.get(row.setBy))!
: rows.reduce((a, b) => (b.seq > a.seq ? b : a));
return { count: rows.length, lastAt: top.at, lastKind: top.kind, lastExcerpt: top.excerpt };
};
/** The task detail's conversation: the legacy object, or the scoped one, never null. */
const detailConversationOf = (id: string) => {
const rows = activity.get(id) ?? [];
if (!sourceScoped)
return (
mirrorOf(id) && {
...mirrorOf(id),
latest: rows.toSorted((a, b) => b.seq - a.seq).slice(0, 10),
}
);
const floors = floorsOf(rows);
return {
...(mirrorOf(id) ?? { count: 0, lastAt: null, lastKind: null, lastExcerpt: null }),
sourceScoped: true,
sourceFloors: Object.fromEntries(floors),
latest: rows
.filter((row) => row.seq === floors.get(row.setBy))
.toReversed()
.slice(0, 10),
};
};
const steersOf = (id: string) =>
steers
.filter((steer) => steer.task === id)
Expand All @@ -150,7 +188,7 @@ export function scratchEngine(
return invalid("setBy");
const rows = activity.get(id) ?? [];
activity.set(id, rows);
if (rows.some((row) => row.seq === body.seq))
if (rows.some((row) => row.seq === body.seq && (!sourceScoped || row.setBy === body.setBy)))
return { status: 200, body: { task: id, conversation: mirrorOf(id), unchanged: true } };
const row = {
seq: body.seq as number,
Expand Down Expand Up @@ -327,12 +365,7 @@ export function scratchEngine(
source: null,
...(conversing
? {
conversation: mirrorOf(task.id) && {
...mirrorOf(task.id),
latest: (activity.get(task.id) ?? [])
.toSorted((a, b) => b.seq - a.seq)
.slice(0, 10),
},
conversation: detailConversationOf(task.id),
steers: steersOf(task.id),
}
: {}),
Expand Down Expand Up @@ -452,6 +485,13 @@ export function scratchEngine(
},
steer: (id: number) => steers.find((steer) => steer.id === id)!,
activityOf: (task: string) => activity.get(task) ?? [],
/** Another source's ingest, as its own server would send it. */
ingestFrom: (task: string, row: { seq: number; setBy: string; kind?: string }) =>
ingest(task, { at: "2026-11-23T00:00:00.000Z", kind: "message", ...row }),
/** The engine installed, or rolled back, between two passes of one running server. */
setSourceScoped: (value: boolean) => {
sourceScoped = value;
},
dropNext: (path: RegExp) => {
drops.push(path);
},
Expand Down
10 changes: 10 additions & 0 deletions apps/web/src/lib/delivery.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -738,6 +738,16 @@ describe("parseTask", () => {
expect(seats?.map((seat) => seat.threadId)).toEqual(["thread-builder", null, null, null]);
});

it("names the one mirrored environment only on an engine that is not source-scoped", () => {
const conversation = { count: 2, latest: [{ seq: 7, setBy: "env-b" }] };
const mirrored = (value: unknown) =>
parseTask({ id: "task-4", card: card({}), conversation: value })
?.conversationMirrorEnvironment;
const scoped = { ...conversation, sourceScoped: true, sourceFloors: { "env-b": 7 } };
expect(mirrored(conversation)).toBe("env-b");
expect(mirrored(scoped)).toBeNull();
});

it("knows a draft, and is null for what is not a task", () => {
expect(
parseTask({ id: "task-2", state: "draft", card: card({ lane: "draft" }) })?.isDraft,
Expand Down
9 changes: 6 additions & 3 deletions apps/web/src/lib/delivery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2022,9 +2022,12 @@ export function parseTask(body: unknown): TaskView | null {
target: parseTarget(body.target),
suggestedBoard: parseSuggestedBoard(body.suggestedBoard),
boardThread: parseBoardThread(body.boardThread),
conversationMirrorEnvironment: isRecord(body.conversation)
? textOrNull(records(body.conversation.latest)[0]?.setBy)
: null,
// A source-scoped engine mirrors each environment separately, so no source stops being
// mirrored; only an older engine's single sequence makes the last source the only one.
conversationMirrorEnvironment:
isRecord(body.conversation) && body.conversation.sourceScoped !== true
? textOrNull(records(body.conversation.latest)[0]?.setBy)
: null,
source: (() => {
const source = isRecord(body.source) ? body.source : null;
const ref = source ? text(source.ref) : "";
Expand Down
Loading