From 4042e0d837f404da247b4403b1a587f598ddc639 Mon Sep 17 00:00:00 2001 From: Yaacov Date: Sat, 14 Nov 2026 14:05:22 +0200 Subject: [PATCH 1/4] fix(server): a subagent of a forked conversation is no longer treated as that fork delegate_task from any forked conversation failed with "Failed to load orchestration projection". makeSubagentChildThread copies the parent thread, so the subagent inherited Scient's conversationFork. dispatchMessage then ran the fork-only consumed-transfer read (added in #882) against the subagent, which exists only as a pending event in that command, and the read failed. The same copy made fork, import, rollback, usage-limit and analytics readers treat every subagent of a fork as a fork. Claude's and Codex's native subagents share the builder. A derived thread now starts without the origin's own history: Scient's fork, import and fork-lineage state, the rollback receipt as a whole, usage-limit recovery and unsettledAt. It also resets what T3's own fork already resets (delegatedFrom, opens, activeOrderKey, lastSnoozeWakeAt), offered to T3 separately. A field table in the regression test classifies every thread field, so an upstream merge that adds one fails typecheck until it is decided. Co-Authored-By: Claude Opus 5.5 --- UPSTREAM.md | 13 ++ .../scient-fork/DelegatedTaskFromFork.test.ts | 203 ++++++++++++++++++ docs/internals/upstream-alignment-protocol.md | 11 +- .../src/server/scientDerivedThread.ts | 16 ++ .../src/server/subagentProjection.ts | 16 +- 5 files changed, 255 insertions(+), 4 deletions(-) create mode 100644 apps/server/src/orchestration-v2/scient-fork/DelegatedTaskFromFork.test.ts create mode 100644 packages/provider-core/src/server/scientDerivedThread.ts diff --git a/UPSTREAM.md b/UPSTREAM.md index 691ce2cc0a..14dcf92042 100644 --- a/UPSTREAM.md +++ b/UPSTREAM.md @@ -2290,3 +2290,16 @@ When T3 changes those viewers' open or layout code, carry it into the session fu When aligning, check that T3's `OfficePages` props, the paint keys (`paint:`, `slide:`) and the worker method maps still meet these seams. A T3 text layer for slides, or find of its own, should replace Scient's rather than run beside it. + +## Subagent thread fields + +T3's `makeSubagentChildThread` (`packages/provider-core/src/server/subagentProjection.ts`) builds a +subagent from a copy of its parent thread. Delegated tasks and Claude's and Codex's native +subagents all use it. A copy carried Scient's own thread state into every subagent: a subagent of a +forked conversation claimed to be that fork, so `delegate_task` from a fork failed and fork, import, +rollback and usage-limit readers misjudged the subagent. The `derived-thread-fields` seam spreads +`SCIENT_DERIVED_THREAD_RESETS` (`scientDerivedThread.ts`) after the copy. The same seam resets the +four T3 fields T3's own fork already resets (`delegatedFrom`, `opens`, `activeOrderKey`, +`lastSnoozeWakeAt`); that part is offered to T3, and the seam lines give way to T3's code once T3 +has it. The field table in `scient-fork/DelegatedTaskFromFork.test.ts` decides every thread field +for subagents, so an alignment that adds one fails typecheck until it is classified. diff --git a/apps/server/src/orchestration-v2/scient-fork/DelegatedTaskFromFork.test.ts b/apps/server/src/orchestration-v2/scient-fork/DelegatedTaskFromFork.test.ts new file mode 100644 index 0000000000..bb7b4d1935 --- /dev/null +++ b/apps/server/src/orchestration-v2/scient-fork/DelegatedTaskFromFork.test.ts @@ -0,0 +1,203 @@ +import { assert, it } from "@effect/vitest"; +import { + CommandId, + EnvironmentId, + EventId, + MessageId, + type OrchestrationV2AppThread, + ProjectId, + ProviderDriverKind, + ProviderInstanceId, + ThreadId, +} from "@t3tools/contracts"; +import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; + +import * as SqlitePersistence from "../../persistence/Sqlite.ts"; +import { CodexProviderCapabilitiesV2 } from "../Adapters/CodexAdapterV2.ts"; +import * as EffectOutbox from "../EffectOutbox.ts"; +import * as Orchestrator from "../Orchestrator.ts"; +import * as ProjectionStore from "../ProjectionStore.ts"; +import * as ProviderAdapterRegistry from "../ProviderAdapterRegistry.ts"; +import * as ProviderReplayHarness from "../testkit/ProviderReplayHarness.ts"; + +const instanceId = ProviderInstanceId.make("codex"); +const modelSelection = { instanceId, model: "gpt-5.1-codex" }; +const adapter = { + instanceId, + driver: ProviderDriverKind.make("codex"), + getCapabilities: () => Effect.succeed(CodexProviderCapabilitiesV2), + planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" as const }), + openSession: () => Effect.die("No provider process needed to admit a delegated task"), +} as ProviderAdapter.ProviderAdapterV2["Service"]; +const layerDatabase = SqlitePersistence.layerMemory; +const layerTest = Layer.mergeAll( + layerDatabase, + ProjectionStore.layer.pipe(Layer.provide(layerDatabase)), + EffectOutbox.layer.pipe(Layer.provide(layerDatabase)), + ProviderReplayHarness.layerWithRegistry( + { name: "delegated-task-from-fork" }, + ProviderAdapterRegistry.layerFromAdapters([adapter]), + { databaseLayer: layerDatabase, runEffectWorker: false }, + ), +); + +// What a delegated subagent takes from its parent thread. The Record makes a field added +// by an upstream merge fail typecheck until someone decides it. +const helperFields = { + createdBy: "set", + creationSource: "set", + id: "set", + projectId: "inherited", + workspaceAuthorityRevision: "set", + title: "set", + providerInstanceId: "set", + modelSelection: "set", + runtimeMode: "set", + interactionMode: "set", + branch: "inherited", + worktreePath: "inherited", + linkedPullRequest: "reset", + pullRequests: "set", + branchPullRequest: "inherited", + activeProviderThreadId: "set", + historyOrigin: "reset", + linkOrigin: "inherited", + delegatedFrom: "reset", + lineage: "set", + forkedFrom: "set", + createdAt: "set", + updatedAt: "set", + archivedAt: "reset", + settledOverride: "reset", + settledAt: "reset", + unsettledAt: "reset", + snoozedUntil: "reset", + snoozedAt: "reset", + lastSnoozeWakeAt: "reset", + limitRecovery: "reset", + guestShare: "reset", + pinnedAt: "reset", + autoSettleDisabledAt: "reset", + pinOrderKey: "reset", + activeOrderKey: "reset", + tags: "inherited", + lastVisitedAt: "reset", + opens: "reset", + titleRegeneration: "reset", + lastTitleRegeneration: "inherited", + rollbackRequestId: "reset", + rollbackCompletedRequestId: "reset", + rollbackFailure: "reset", + deletedAt: "reset", + sectionId: "inherited", + conversationImport: "reset", + forkLineage: "reset", + conversationFork: "reset", +} as const satisfies Record; + +it.effect("starts a delegated task from a forked conversation as a plain helper", () => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const projections = yield* ProjectionStore.ProjectionStoreV2; + const parentThreadId = ThreadId.make("thread:forked-parent"); + const rollbackId = CommandId.make("rollback:forked-parent"); + yield* orchestrator.dispatch({ + type: "thread.create", + commandId: CommandId.make("create-forked-parent"), + threadId: parentThreadId, + projectId: ProjectId.make("project:forked-parent"), + title: "Forked parent", + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: "feature/forked-parent", + worktreePath: "/repo-worktree", + createdBy: "user", + creationSource: "web", + }); + const now = yield* DateTime.now; + const parentState = { + delegatedFrom: { + environmentId: EnvironmentId.make("environment:remote"), + threadId: ThreadId.make("thread:remote-parent"), + title: "Remote parent", + }, + unsettledAt: now, + lastSnoozeWakeAt: now, + activeOrderKey: "a0", + rollbackRequestId: rollbackId, + rollbackCompletedRequestId: rollbackId, + rollbackFailure: { requestId: rollbackId, message: "Rollback failed" }, + forkLineage: { + originThreadId: ThreadId.make("thread:fork-origin"), + baselineAssistantMessageId: null, + }, + conversationFork: { + commandId: CommandId.make("fork:forked-parent"), + sourceThreadId: ThreadId.make("thread:fork-origin"), + workspaceMode: "local", + status: "ready", + cwd: "/repo-worktree", + checkpointRef: null, + checkpointOid: null, + attachmentCopies: [], + error: null, + }, + } as const satisfies Partial; + yield* projections.apply({ + id: EventId.make("forked-parent:fork-state"), + type: "thread.metadata-updated", + threadId: parentThreadId, + occurredAt: now, + payload: { ...(yield* projections.getThread(parentThreadId)), ...parentState }, + }); + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make("start-forked-parent"), + threadId: parentThreadId, + messageId: MessageId.make("message:forked-parent"), + text: "Ask for a review", + attachments: [], + dispatchMode: { type: "start_immediately" }, + createdBy: "user", + creationSource: "web", + }); + const parent = yield* projections.getThreadProjection(parentThreadId); + const parentRun = parent.runs[0]!; + + yield* orchestrator.dispatch({ + type: "delegated_task.request", + commandId: CommandId.make("delegate-from-fork"), + parentThreadId, + parentRunId: parentRun.id, + parentNodeId: parentRun.rootNodeId!, + task: "Review the plan", + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + createdBy: "agent", + creationSource: "mcp", + }); + + const task = (yield* projections.getThreadProjection(parentThreadId)).subagents[0]!; + const child = yield* projections.getThreadProjection(task.childThreadId!); + assert.equal(child.thread.lineage.relationshipToParent, "subagent"); + assert.lengthOf(child.runs, 1); + for (const [field, rule] of Object.entries(helperFields)) { + if (rule !== "inherited") continue; + const key = field as keyof OrchestrationV2AppThread; + assert.deepEqual(child.thread[key], parent.thread[key], `${field} is inherited`); + } + for (const [field, value] of Object.entries(parentState)) { + assert.equal(helperFields[field as keyof typeof parentState], "reset"); + assert.notDeepEqual( + child.thread[field as keyof typeof parentState], + value, + `${field} is reset`, + ); + } + }).pipe(Effect.provide(layerTest)), +); diff --git a/docs/internals/upstream-alignment-protocol.md b/docs/internals/upstream-alignment-protocol.md index 707626baff..5248259340 100644 --- a/docs/internals/upstream-alignment-protocol.md +++ b/docs/internals/upstream-alignment-protocol.md @@ -109,9 +109,14 @@ their callers; a clean merge can mount the same behavior twice. Look beyond overlaps when upstream changes a shared API or a quality gate. Trace its untouched Scient consumers and the affected server, web, desktop, or mobile entry points. For example, a lint rule changing from advisory to mandatory can fail Scient-only files even when Git reports no -conflict. If a previous receipt records an upstream deprecation, warning ceiling, or migration -debt, check whether this range enforces it; record the scope and stable replacement API before -starting a broad rewrite. An impact signal is a prompt for this review, not an instruction to run +conflict. When upstream narrows what a shared read loads, give each Scient caller that needed the +dropped data its own source, and remember that a thread created earlier in the same command exists +only as pending events, not in the store. Scient fields on an upstream record travel wherever +upstream copies that record; the field table in +`apps/server/src/orchestration-v2/scient-fork/DelegatedTaskFromFork.test.ts` fails typecheck until +each new thread field is classified for subagents. If a previous receipt records an upstream +deprecation, warning ceiling, or migration debt, check whether this range enforces it; record the +scope and stable replacement API before starting a broad rewrite. An impact signal is a prompt for this review, not an instruction to run every possible test or to accept an upstream policy without composition. Git's recorded conflict resolutions (`rerere`) may fill a working-tree file, but `start` leaves diff --git a/packages/provider-core/src/server/scientDerivedThread.ts b/packages/provider-core/src/server/scientDerivedThread.ts new file mode 100644 index 0000000000..e248a9dfc9 --- /dev/null +++ b/packages/provider-core/src/server/scientDerivedThread.ts @@ -0,0 +1,16 @@ +import type { OrchestrationV2AppThread } from "@t3tools/contracts"; + +/** + * Facts about one thread's own history that a thread derived from it must not copy: how it was + * imported or forked, its rollback receipt (cleared as a whole) and its usage-limit recovery. + */ +export const SCIENT_DERIVED_THREAD_RESETS = { + conversationFork: null, + conversationImport: null, + forkLineage: null, + rollbackRequestId: undefined, + rollbackCompletedRequestId: null, + rollbackFailure: null, + limitRecovery: null, + unsettledAt: null, +} as const satisfies Partial; diff --git a/packages/provider-core/src/server/subagentProjection.ts b/packages/provider-core/src/server/subagentProjection.ts index 6095f52513..19500ccfea 100644 --- a/packages/provider-core/src/server/subagentProjection.ts +++ b/packages/provider-core/src/server/subagentProjection.ts @@ -18,6 +18,9 @@ import type { ThreadId, TurnItemId, } from "@t3tools/contracts"; +// SCIENT-FORK:START derived-thread-fields +import { SCIENT_DERIVED_THREAD_RESETS } from "./scientDerivedThread.ts"; +// SCIENT-FORK:END import { backgroundWorkHoldsCompletion } from "@t3tools/shared/orchestrationV2PendingBackgroundWork"; import { runRanAfter } from "@t3tools/shared/orchestrationV2ThreadError"; import * as DateTime from "effect/DateTime"; @@ -61,8 +64,13 @@ export function makeSubagentChildThread(input: { readonly createdBy: OrchestrationV2Actor; readonly creationSource: OrchestrationV2CreationSource; }): OrchestrationV2AppThread { + // SCIENT-FORK:START derived-thread-fields + // The remote parent delegated the parent thread, not its subagents. + const { delegatedFrom: _delegatedFrom, ...inherited } = input.parentThread; return { - ...input.parentThread, + ...inherited, + ...SCIENT_DERIVED_THREAD_RESETS, + // SCIENT-FORK:END createdBy: input.createdBy, creationSource: input.creationSource, id: input.childThreadId, @@ -96,6 +104,12 @@ export function makeSubagentChildThread(input: { // A guest link belongs to the thread it was made for. guestShare: null, lastVisitedAt: null, + // SCIENT-FORK:START derived-thread-fields + // A subagent is a new thread; it does not inherit the parent's opens or list position. + opens: null, + activeOrderKey: null, + lastSnoozeWakeAt: null, + // SCIENT-FORK:END deletedAt: null, }; } From 72c0d0fff09954a46121c7db11395e929396afff Mon Sep 17 00:00:00 2001 From: Yaacov Date: Sat, 14 Nov 2026 14:24:57 +0200 Subject: [PATCH 2/4] fix(server): a forked conversation no longer takes its source's guest link ConversationForkService built the fork from a copy of the source thread and kept its guestShare. Guest links are looked up by share id (LIMIT 1), so an invite to the source could open the fork, including what was written there after the fork. The fork also kept the source's remote delegation, opens, last snooze wake and auto-settle opt-out, which T3's own fork resets. Found by Codex review of #914. Co-Authored-By: Claude Opus 5.5 --- .../ConversationForkService.test.ts | 20 +++++++++++++++++++ .../scient-fork/ConversationForkService.ts | 6 ++++++ 2 files changed, 26 insertions(+) diff --git a/apps/server/src/orchestration-v2/scient-fork/ConversationForkService.test.ts b/apps/server/src/orchestration-v2/scient-fork/ConversationForkService.test.ts index 87b3dccf65..4036607a67 100644 --- a/apps/server/src/orchestration-v2/scient-fork/ConversationForkService.test.ts +++ b/apps/server/src/orchestration-v2/scient-fork/ConversationForkService.test.ts @@ -2,6 +2,7 @@ import { assert, it } from "@effect/vitest"; import { CommandId, EventId, + GuestShareId, MessageId, ProjectId, ProviderDriverKind, @@ -122,6 +123,23 @@ it.effect( threadId, sectionId: ThreadSectionId.make("section:research"), }); + yield* store.apply({ + id: EventId.make("fork-source-guest-share"), + type: "thread.metadata-updated", + threadId, + occurredAt: now, + payload: { + ...(yield* store.getThread(threadId)), + guestShare: { + id: GuestShareId.make("guest-share:fork-source"), + host: "guest.example.test", + createdAt: DateTime.formatIso(now), + expiresAt: DateTime.formatIso(DateTime.add(now, { days: 1 })), + guestName: null, + messages: [], + }, + }, + }); const firstRunId = RunId.make("fork-completed-run"); const secondRunId = RunId.make("fork-running-run"); const runs: OrchestrationV2Run[] = [firstRunId, secondRunId].map((id, index) => ({ @@ -332,6 +350,8 @@ it.effect( yield* assertForkShellCounts; assert.ok(shell.threads.every((thread) => !("conversationForkBoundaries" in thread))); assert.equal(target.thread.sectionId, ThreadSectionId.make("section:research")); + // A guest invited to the source must never resolve to the fork. + assert.isNull(target.thread.guestShare); assert.equal(target.thread.conversationFork?.status, "ready"); assert.equal(target.thread.forkedFrom, null); assert.equal(target.runs.length, 0); diff --git a/apps/server/src/orchestration-v2/scient-fork/ConversationForkService.ts b/apps/server/src/orchestration-v2/scient-fork/ConversationForkService.ts index e6ca3cf1c4..31fcd09589 100644 --- a/apps/server/src/orchestration-v2/scient-fork/ConversationForkService.ts +++ b/apps/server/src/orchestration-v2/scient-fork/ConversationForkService.ts @@ -662,6 +662,12 @@ const make = Effect.gen(function* () { linkedPullRequest: null, branchPullRequest: null, pullRequests: [], + // A guest link and a remote delegation belong to the thread they were made for. + guestShare: null, + delegatedFrom: undefined, + opens: null, + lastSnoozeWakeAt: null, + autoSettleDisabledAt: null, }; const events: OrchestrationV2DomainEvent[] = [ { From 2b335ceaae8a5ca3cd7dabca0cd46a00f8d57d2f Mon Sep 17 00:00:00 2001 From: Yaacov Date: Sat, 14 Nov 2026 14:38:29 +0200 Subject: [PATCH 3/4] fix(server): a guest link copied into an older fork no longer opens it Forks made before the previous commit still carry their source's guestShare in their events, so the invite lookup (LIMIT 1) could resolve to the fork, and after the source closed its link the fork was the only match. A share made for a thread is always created after the thread, so the lookup and guest authorization now accept a share only on a thread created before it. Also keeps only T3's open #30334 line (drop delegatedFrom) inside T3's subagent builder; the opens, list-position and snooze-wake resets move into SCIENT_DERIVED_THREAD_RESETS, since T3 shows no visible effect from them. Co-Authored-By: Claude Opus 5.5 --- UPSTREAM.md | 22 +++- apps/server/src/guest/GuestShareService.ts | 9 ++ .../src/orchestration-v2/ProjectionStore.ts | 22 +++- .../src/scient/guest/ownGuestShare.test.ts | 104 ++++++++++++++++++ apps/server/src/scient/guest/ownGuestShare.ts | 8 ++ .../src/server/scientDerivedThread.ts | 6 +- .../src/server/subagentProjection.ts | 6 - 7 files changed, 160 insertions(+), 17 deletions(-) create mode 100644 apps/server/src/scient/guest/ownGuestShare.test.ts create mode 100644 apps/server/src/scient/guest/ownGuestShare.ts diff --git a/UPSTREAM.md b/UPSTREAM.md index 14dcf92042..da582f71c6 100644 --- a/UPSTREAM.md +++ b/UPSTREAM.md @@ -2297,9 +2297,19 @@ T3's `makeSubagentChildThread` (`packages/provider-core/src/server/subagentProje subagent from a copy of its parent thread. Delegated tasks and Claude's and Codex's native subagents all use it. A copy carried Scient's own thread state into every subagent: a subagent of a forked conversation claimed to be that fork, so `delegate_task` from a fork failed and fork, import, -rollback and usage-limit readers misjudged the subagent. The `derived-thread-fields` seam spreads -`SCIENT_DERIVED_THREAD_RESETS` (`scientDerivedThread.ts`) after the copy. The same seam resets the -four T3 fields T3's own fork already resets (`delegatedFrom`, `opens`, `activeOrderKey`, -`lastSnoozeWakeAt`); that part is offered to T3, and the seam lines give way to T3's code once T3 -has it. The field table in `scient-fork/DelegatedTaskFromFork.test.ts` decides every thread field -for subagents, so an alignment that adds one fails typecheck until it is classified. +rollback and usage-limit readers misjudged the subagent. `SCIENT_DERIVED_THREAD_RESETS` +(`scientDerivedThread.ts`) is spread after the copy inside the `derived-thread-fields` seam. It also +resets the parent's opens, list position and snooze wake, as T3's own fork does. The seam's other +line drops `delegatedFrom`, matching T3's open pingdotgg/t3code#30334 word for word; once T3 merges +it, that line gives way to T3's. The field table in `scient-fork/DelegatedTaskFromFork.test.ts` +decides every thread field for subagents, so an alignment that adds one fails typecheck until it +is classified. + +## Copied guest links + +Forks made before #914 copied their source's `guestShare`, so an invite to the source could open +the fork. The `copied-guest-share` seams in T3's `ProjectionStore.findGuestShareThreadId` and +`GuestShareService.authorize` accept a share only on a thread created before it +(`scient/guest/ownGuestShare.ts`): a share made for a thread always comes after the thread. They +also protect forks already in users' databases, whose events still carry the copy. T3 has no copy +path, so it needs no such check. diff --git a/apps/server/src/guest/GuestShareService.ts b/apps/server/src/guest/GuestShareService.ts index 36be1d1e21..db7a9d1b2e 100644 --- a/apps/server/src/guest/GuestShareService.ts +++ b/apps/server/src/guest/GuestShareService.ts @@ -59,6 +59,9 @@ import * as ProviderRegistry from "../provider/ProviderRegistry.ts"; import * as ServerSettings from "../serverSettings.ts"; import * as AnalyticsService from "../telemetry/AnalyticsService.ts"; import { guestShareView, guestThreadModel } from "./guestView.ts"; +// SCIENT-FORK:START copied-guest-share +import { isOwnGuestShare } from "../scient/guest/ownGuestShare.ts"; +// SCIENT-FORK:END import { classifyGuestUploads, GUEST_UPLOAD_HEADER_BYTES, @@ -328,6 +331,12 @@ const make = Effect.gen(function* () { thread.deletedAt !== null || DateTime.toEpochMillis(now) >= Date.parse(share.expiresAt) || (kind === "session" && share.guestName === null) || + // SCIENT-FORK:START copied-guest-share + !isOwnGuestShare({ + threadCreatedAtMs: DateTime.toEpochMillis(thread.createdAt), + shareCreatedAt: share.createdAt, + }) || + // SCIENT-FORK:END (yield* connectHostname) !== share.host ) { return yield* inactive; diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index 9b9575c5aa..309c319a93 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -115,6 +115,7 @@ import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; // SCIENT-FORK:START import * as Option from "effect/Option"; +import { isOwnGuestShare } from "../scient/guest/ownGuestShare.ts"; // SCIENT-FORK:END import * as Layer from "effect/Layer"; import * as Result from "effect/Result"; @@ -9563,13 +9564,26 @@ export const layer: Layer.Layer = const findGuestShareThreadId = Effect.fn("ProjectionStore.findGuestShareThreadId")(function* ( shareId: GuestShareId, ) { - const rows = yield* sql<{ readonly thread_id: string }>` - SELECT thread_id + // SCIENT-FORK:START copied-guest-share — a copied share never wins the lookup. + const rows = yield* sql<{ + readonly thread_id: string; + readonly created_at: string; + readonly share_created_at: string; + }>` + SELECT thread_id, + json_extract(payload_json, '$.createdAt') AS created_at, + json_extract(payload_json, '$.guestShare.createdAt') AS share_created_at FROM orchestration_v2_projection_threads WHERE json_extract(payload_json, '$.guestShare.id') = ${shareId} - LIMIT 1 `; - return rows[0] === undefined ? null : ThreadId.make(rows[0].thread_id); + const owner = rows.find((row) => + isOwnGuestShare({ + threadCreatedAtMs: Date.parse(row.created_at), + shareCreatedAt: row.share_created_at, + }), + ); + return owner === undefined ? null : ThreadId.make(owner.thread_id); + // SCIENT-FORK:END }, Effect.mapError(shellSnapshotReadError)); const listOlderSettledThreads: ProjectionStoreV2Shape["listOlderSettledThreads"] = Effect.fn( diff --git a/apps/server/src/scient/guest/ownGuestShare.test.ts b/apps/server/src/scient/guest/ownGuestShare.test.ts new file mode 100644 index 0000000000..1713ae08a0 --- /dev/null +++ b/apps/server/src/scient/guest/ownGuestShare.test.ts @@ -0,0 +1,104 @@ +import { assert, it } from "@effect/vitest"; +import { + CommandId, + EventId, + GuestShareId, + type OrchestrationV2AppThread, + ProjectId, + ProviderDriverKind, + ProviderInstanceId, + ThreadId, +} from "@t3tools/contracts"; +import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as TestClock from "effect/testing/TestClock"; + +import * as SqlitePersistence from "../../persistence/Sqlite.ts"; +import { CodexProviderCapabilitiesV2 } from "../../orchestration-v2/Adapters/CodexAdapterV2.ts"; +import * as EffectOutbox from "../../orchestration-v2/EffectOutbox.ts"; +import * as Orchestrator from "../../orchestration-v2/Orchestrator.ts"; +import * as ProjectionStore from "../../orchestration-v2/ProjectionStore.ts"; +import * as ProviderAdapterRegistry from "../../orchestration-v2/ProviderAdapterRegistry.ts"; +import * as ProviderReplayHarness from "../../orchestration-v2/testkit/ProviderReplayHarness.ts"; + +const instanceId = ProviderInstanceId.make("codex"); +const adapter = { + instanceId, + driver: ProviderDriverKind.make("codex"), + getCapabilities: () => Effect.succeed(CodexProviderCapabilitiesV2), + planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" as const }), + openSession: () => Effect.die("No provider process needed for guest share lookups"), +} as ProviderAdapter.ProviderAdapterV2["Service"]; +const layerDatabase = SqlitePersistence.layerMemory; +const layerTest = Layer.mergeAll( + layerDatabase, + ProjectionStore.layer.pipe(Layer.provide(layerDatabase)), + EffectOutbox.layer.pipe(Layer.provide(layerDatabase)), + ProviderReplayHarness.layerWithRegistry( + { name: "own-guest-share" }, + ProviderAdapterRegistry.layerFromAdapters([adapter]), + { databaseLayer: layerDatabase, runEffectWorker: false }, + ), +); + +// regression: 72c0d0fff0 fix(server): a forked conversation no longer takes its source's guest link +it.effect("a guest link opens the thread it was made for, never a copy of it", () => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const store = yield* ProjectionStore.ProjectionStoreV2; + const createThread = (threadId: ThreadId) => + orchestrator.dispatch({ + type: "thread.create", + commandId: CommandId.make(`create:${threadId}`), + threadId, + projectId: ProjectId.make("project:own-guest-share"), + title: "Shared", + modelSelection: { instanceId, model: "gpt-5.1-codex" }, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + createdBy: "user", + creationSource: "web", + }); + const setShare = ( + threadId: ThreadId, + guestShare: OrchestrationV2AppThread["guestShare"], + label: string, + ) => + Effect.gen(function* () { + yield* store.apply({ + id: EventId.make(`own-guest-share:${label}`), + type: "thread.metadata-updated", + threadId, + occurredAt: yield* DateTime.now, + payload: { ...(yield* store.getThread(threadId)), guestShare }, + }); + }); + const sourceId = ThreadId.make("thread:shared-source"); + const forkId = ThreadId.make("thread:copied-fork"); + const shareId = GuestShareId.make("guest-share:source"); + + yield* createThread(sourceId); + yield* TestClock.adjust("1 second"); + const now = yield* DateTime.now; + const share = { + id: shareId, + host: "guest.example.test", + createdAt: DateTime.formatIso(now), + expiresAt: DateTime.formatIso(DateTime.add(now, { days: 1 })), + guestName: null, + messages: [], + }; + yield* setShare(sourceId, share, "source"); + yield* TestClock.adjust("1 second"); + yield* createThread(forkId); + yield* setShare(forkId, share, "fork-copy"); + + assert.equal(yield* store.findGuestShareThreadId(shareId), sourceId); + yield* setShare(sourceId, null, "source-closed"); + assert.isNull(yield* store.findGuestShareThreadId(shareId)); + }).pipe(Effect.provide(layerTest)), +); diff --git a/apps/server/src/scient/guest/ownGuestShare.ts b/apps/server/src/scient/guest/ownGuestShare.ts new file mode 100644 index 0000000000..1aba93a54d --- /dev/null +++ b/apps/server/src/scient/guest/ownGuestShare.ts @@ -0,0 +1,8 @@ +/** + * A share made for a thread is created after that thread. An older one was copied into a fork + * from the thread it was made for, and must not open the fork. + */ +export const isOwnGuestShare = (input: { + readonly threadCreatedAtMs: number; + readonly shareCreatedAt: string; +}): boolean => Date.parse(input.shareCreatedAt) >= input.threadCreatedAtMs; diff --git a/packages/provider-core/src/server/scientDerivedThread.ts b/packages/provider-core/src/server/scientDerivedThread.ts index e248a9dfc9..56a21d0e31 100644 --- a/packages/provider-core/src/server/scientDerivedThread.ts +++ b/packages/provider-core/src/server/scientDerivedThread.ts @@ -2,9 +2,13 @@ import type { OrchestrationV2AppThread } from "@t3tools/contracts"; /** * Facts about one thread's own history that a thread derived from it must not copy: how it was - * imported or forked, its rollback receipt (cleared as a whole) and its usage-limit recovery. + * imported or forked, its rollback receipt (cleared as a whole), its usage-limit recovery, and + * its opens, list position and snooze wake, which T3's fork resets too. */ export const SCIENT_DERIVED_THREAD_RESETS = { + opens: null, + activeOrderKey: null, + lastSnoozeWakeAt: null, conversationFork: null, conversationImport: null, forkLineage: null, diff --git a/packages/provider-core/src/server/subagentProjection.ts b/packages/provider-core/src/server/subagentProjection.ts index 19500ccfea..651af3f86e 100644 --- a/packages/provider-core/src/server/subagentProjection.ts +++ b/packages/provider-core/src/server/subagentProjection.ts @@ -104,12 +104,6 @@ export function makeSubagentChildThread(input: { // A guest link belongs to the thread it was made for. guestShare: null, lastVisitedAt: null, - // SCIENT-FORK:START derived-thread-fields - // A subagent is a new thread; it does not inherit the parent's opens or list position. - opens: null, - activeOrderKey: null, - lastSnoozeWakeAt: null, - // SCIENT-FORK:END deletedAt: null, }; } From bc73743ad548c187197ddaa20c0a470caf5bb1e5 Mon Sep 17 00:00:00 2001 From: Yaacov Date: Sat, 14 Nov 2026 14:47:52 +0200 Subject: [PATCH 4/4] fix(server): decide a copied guest link from the thread's creation event, not timestamps The previous commit judged ownership by comparing the share's and thread's creation times. Codex showed a clock moving backwards defeats that both ways. A thread is always created without a share of its own, so a share already in its thread.created event was copied. The lookup and authorization now ask exactly that (one indexed read; thread.created events are never pruned). Co-Authored-By: Claude Opus 5.5 --- UPSTREAM.md | 11 ++-- apps/server/src/guest/GuestShareService.ts | 13 +++-- .../src/orchestration-v2/ProjectionStore.ts | 24 +++------ .../src/scient/guest/ownGuestShare.test.ts | 53 +++++++++++++------ apps/server/src/scient/guest/ownGuestShare.ts | 26 ++++++--- 5 files changed, 79 insertions(+), 48 deletions(-) diff --git a/UPSTREAM.md b/UPSTREAM.md index da582f71c6..96e9d63603 100644 --- a/UPSTREAM.md +++ b/UPSTREAM.md @@ -2308,8 +2308,9 @@ is classified. ## Copied guest links Forks made before #914 copied their source's `guestShare`, so an invite to the source could open -the fork. The `copied-guest-share` seams in T3's `ProjectionStore.findGuestShareThreadId` and -`GuestShareService.authorize` accept a share only on a thread created before it -(`scient/guest/ownGuestShare.ts`): a share made for a thread always comes after the thread. They -also protect forks already in users' databases, whose events still carry the copy. T3 has no copy -path, so it needs no such check. +the fork. A thread is always created without a share of its own, so a share already in its +`thread.created` event was copied (`scient/guest/ownGuestShare.ts`). The `copied-guest-share` +seams in T3's `ProjectionStore.findGuestShareThreadId` and `GuestShareService.authorize` refuse +such a share, for invites and for sessions already redeemed. They protect forks already in users' +databases, whose events still carry the copy, and need `thread.created` events to stay unpruned, +as T3's maintenance keeps them. T3 has no copy path, so it needs no such check. diff --git a/apps/server/src/guest/GuestShareService.ts b/apps/server/src/guest/GuestShareService.ts index db7a9d1b2e..bc1989bc89 100644 --- a/apps/server/src/guest/GuestShareService.ts +++ b/apps/server/src/guest/GuestShareService.ts @@ -60,7 +60,8 @@ import * as ServerSettings from "../serverSettings.ts"; import * as AnalyticsService from "../telemetry/AnalyticsService.ts"; import { guestShareView, guestThreadModel } from "./guestView.ts"; // SCIENT-FORK:START copied-guest-share -import { isOwnGuestShare } from "../scient/guest/ownGuestShare.ts"; +import * as SqlClient from "effect/sql/SqlClient"; +import { shareCopiedAtCreation } from "../scient/guest/ownGuestShare.ts"; // SCIENT-FORK:END import { classifyGuestUploads, @@ -222,6 +223,9 @@ const threadOf = (event: OrchestrationV2DomainEvent): OrchestrationV2AppThread | const make = Effect.gen(function* () { const orchestrator = yield* Orchestrator.OrchestratorV2; + // SCIENT-FORK:START copied-guest-share + const sql = yield* SqlClient.SqlClient; + // SCIENT-FORK:END const commandOutputs = yield* CommandOutputHub.CommandOutputHub; const providerRegistry = yield* ProviderRegistry.ProviderRegistry; const serverSettings = yield* ServerSettings.ServerSettingsService; @@ -332,10 +336,9 @@ const make = Effect.gen(function* () { DateTime.toEpochMillis(now) >= Date.parse(share.expiresAt) || (kind === "session" && share.guestName === null) || // SCIENT-FORK:START copied-guest-share - !isOwnGuestShare({ - threadCreatedAtMs: DateTime.toEpochMillis(thread.createdAt), - shareCreatedAt: share.createdAt, - }) || + (yield* shareCopiedAtCreation(sql, thread.id, share.id).pipe( + Effect.orElseSucceed(() => true), + )) || // SCIENT-FORK:END (yield* connectHostname) !== share.host ) { diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index 309c319a93..1a67987684 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -115,7 +115,7 @@ import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; // SCIENT-FORK:START import * as Option from "effect/Option"; -import { isOwnGuestShare } from "../scient/guest/ownGuestShare.ts"; +import { shareCopiedAtCreation } from "../scient/guest/ownGuestShare.ts"; // SCIENT-FORK:END import * as Layer from "effect/Layer"; import * as Result from "effect/Result"; @@ -9565,24 +9565,16 @@ export const layer: Layer.Layer = shareId: GuestShareId, ) { // SCIENT-FORK:START copied-guest-share — a copied share never wins the lookup. - const rows = yield* sql<{ - readonly thread_id: string; - readonly created_at: string; - readonly share_created_at: string; - }>` - SELECT thread_id, - json_extract(payload_json, '$.createdAt') AS created_at, - json_extract(payload_json, '$.guestShare.createdAt') AS share_created_at + const rows = yield* sql<{ readonly thread_id: string }>` + SELECT thread_id FROM orchestration_v2_projection_threads WHERE json_extract(payload_json, '$.guestShare.id') = ${shareId} `; - const owner = rows.find((row) => - isOwnGuestShare({ - threadCreatedAtMs: Date.parse(row.created_at), - shareCreatedAt: row.share_created_at, - }), - ); - return owner === undefined ? null : ThreadId.make(owner.thread_id); + for (const row of rows) { + const threadId = ThreadId.make(row.thread_id); + if (!(yield* shareCopiedAtCreation(sql, threadId, shareId))) return threadId; + } + return null; // SCIENT-FORK:END }, Effect.mapError(shellSnapshotReadError)); diff --git a/apps/server/src/scient/guest/ownGuestShare.test.ts b/apps/server/src/scient/guest/ownGuestShare.test.ts index 1713ae08a0..5ec0f41f20 100644 --- a/apps/server/src/scient/guest/ownGuestShare.test.ts +++ b/apps/server/src/scient/guest/ownGuestShare.test.ts @@ -13,11 +13,11 @@ import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAda import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; -import * as TestClock from "effect/testing/TestClock"; import * as SqlitePersistence from "../../persistence/Sqlite.ts"; import { CodexProviderCapabilitiesV2 } from "../../orchestration-v2/Adapters/CodexAdapterV2.ts"; import * as EffectOutbox from "../../orchestration-v2/EffectOutbox.ts"; +import * as EventSink from "../../orchestration-v2/EventSink.ts"; import * as Orchestrator from "../../orchestration-v2/Orchestrator.ts"; import * as ProjectionStore from "../../orchestration-v2/ProjectionStore.ts"; import * as ProviderAdapterRegistry from "../../orchestration-v2/ProviderAdapterRegistry.ts"; @@ -48,6 +48,7 @@ it.effect("a guest link opens the thread it was made for, never a copy of it", ( Effect.gen(function* () { const orchestrator = yield* Orchestrator.OrchestratorV2; const store = yield* ProjectionStore.ProjectionStoreV2; + const sink = yield* EventSink.EventSinkV2; const createThread = (threadId: ThreadId) => orchestrator.dispatch({ type: "thread.create", @@ -80,22 +81,42 @@ it.effect("a guest link opens the thread it was made for, never a copy of it", ( const sourceId = ThreadId.make("thread:shared-source"); const forkId = ThreadId.make("thread:copied-fork"); const shareId = GuestShareId.make("guest-share:source"); - - yield* createThread(sourceId); - yield* TestClock.adjust("1 second"); const now = yield* DateTime.now; - const share = { - id: shareId, - host: "guest.example.test", - createdAt: DateTime.formatIso(now), - expiresAt: DateTime.formatIso(DateTime.add(now, { days: 1 })), - guestName: null, - messages: [], - }; - yield* setShare(sourceId, share, "source"); - yield* TestClock.adjust("1 second"); - yield* createThread(forkId); - yield* setShare(forkId, share, "fork-copy"); + yield* createThread(sourceId); + yield* setShare( + sourceId, + { + id: shareId, + host: "guest.example.test", + createdAt: DateTime.formatIso(now), + expiresAt: DateTime.formatIso(DateTime.add(now, { days: 1 })), + guestName: null, + messages: [], + }, + "source", + ); + // An older fork was created from a copy of its source, share included. + const source = yield* store.getThread(sourceId); + yield* sink.write({ + events: [ + { + id: EventId.make("own-guest-share:fork-created"), + type: "thread.created", + threadId: forkId, + occurredAt: now, + payload: { + ...source, + id: forkId, + lineage: { + parentThreadId: sourceId, + relationshipToParent: "fork", + rootThreadId: forkId, + }, + }, + }, + ], + }); + assert.equal((yield* store.getThread(forkId)).guestShare?.id, shareId); assert.equal(yield* store.findGuestShareThreadId(shareId), sourceId); yield* setShare(sourceId, null, "source-closed"); diff --git a/apps/server/src/scient/guest/ownGuestShare.ts b/apps/server/src/scient/guest/ownGuestShare.ts index 1aba93a54d..33ed6ac4d4 100644 --- a/apps/server/src/scient/guest/ownGuestShare.ts +++ b/apps/server/src/scient/guest/ownGuestShare.ts @@ -1,8 +1,22 @@ +import type { GuestShareId, ThreadId } from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import type * as SqlClient from "effect/sql/SqlClient"; + /** - * A share made for a thread is created after that thread. An older one was copied into a fork - * from the thread it was made for, and must not open the fork. + * A thread is created without a share of its own, so a share its creation event already carried + * was copied from the thread it was made for (older forks did this) and must not open the copy. */ -export const isOwnGuestShare = (input: { - readonly threadCreatedAtMs: number; - readonly shareCreatedAt: string; -}): boolean => Date.parse(input.shareCreatedAt) >= input.threadCreatedAtMs; +export const shareCopiedAtCreation = ( + sql: SqlClient.SqlClient, + threadId: ThreadId, + shareId: GuestShareId, +) => + sql<{ readonly present: number }>` + SELECT 1 AS present FROM orchestration_events + WHERE stream_id = ${threadId} + AND application_event_version = 2 + AND aggregate_kind = 'thread' + AND event_type = 'thread.created' + AND json_extract(payload_json, '$.guestShare.id') = ${shareId} + LIMIT 1 + `.pipe(Effect.map((rows) => rows.length > 0));