From f6d81ef107632fb6df3011acfa07182ec196ce8c Mon Sep 17 00:00:00 2001 From: nullStack65 Date: Mon, 16 Nov 2026 12:36:38 -0500 Subject: [PATCH 1/9] feat(server): stage founder admission on protocol two source Begin the differentiated native port on pinned AssemblyAI 0.1.9 source 083270eb, preserving PR58 and its original branch. Port the typed inbox and shared placement policy without importing fork history. Refuse unqualified fleet intents at native ThreadLaunchService before effects. Add read-only migration identity checks and refuse legacy imports or implicit schema upgrades for candidate startup. Native toolchain acceptance is pending; this checkpoint is not deployable and does not enable principal ACLs or universal placement. Model: gpt-6.1-sol Task: implementation Agent: clo866-source --- .../ThreadLaunchService.test.ts | 34 +++++ .../orchestration-v2/ThreadLaunchService.ts | 13 ++ .../Protocol2DatabaseAdmission.test.ts | 72 ++++++++++ .../persistence/Protocol2DatabaseAdmission.ts | 47 +++++++ apps/server/src/persistence/Sqlite.ts | 3 + packages/client-runtime/src/load-balancing.ts | 41 +----- packages/contracts/src/fleetPlacement.ts | 17 +++ packages/contracts/src/index.ts | 3 + packages/contracts/src/threadInbox.test.ts | 85 ++++++++++++ packages/contracts/src/threadInbox.ts | 102 ++++++++++++++ packages/shared/package.json | 2 + packages/shared/src/loadBalancing.ts | 48 +++++++ packages/shared/src/threadPlacement.test.ts | 126 ++++++++++++++++++ packages/shared/src/threadPlacement.ts | 111 +++++++++++++++ 14 files changed, 664 insertions(+), 40 deletions(-) create mode 100644 apps/server/src/persistence/Protocol2DatabaseAdmission.test.ts create mode 100644 apps/server/src/persistence/Protocol2DatabaseAdmission.ts create mode 100644 packages/contracts/src/fleetPlacement.ts create mode 100644 packages/contracts/src/threadInbox.test.ts create mode 100644 packages/contracts/src/threadInbox.ts create mode 100644 packages/shared/src/loadBalancing.ts create mode 100644 packages/shared/src/threadPlacement.test.ts create mode 100644 packages/shared/src/threadPlacement.ts diff --git a/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts b/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts index c44c3a70f19b9..7f672c68ef36e 100644 --- a/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts +++ b/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts @@ -15,6 +15,7 @@ import { ComposerContextId, type ChatAttachment, CommandId, + EnvironmentId, DEFAULT_SERVER_SETTINGS, GitCommandError, MessageId, @@ -338,6 +339,39 @@ function launchInput(input: { }; } +it.effect("refuses unqualified fleet intent before native launch effects", () => { + const harness = makeHarness(); + return Effect.gen(function* () { + const launches = yield* ThreadLaunch.ThreadLaunchService; + const receipts = yield* CommandReceiptStore.CommandReceiptStoreV2; + const threads = yield* ThreadManagement.ThreadManagementService; + for (const mode of ["auto", "pinned"] as const) { + const input = launchInput({ + command: `fleet:${mode}`, + thread: `fleet-thread:${mode}`, + message: "must not launch", + workspace: { type: "worktree", baseRef: "main" }, + }); + const result = yield* Effect.exit( + launches.launch({ + ...input, + fleetPlacement: { + mode, + clientRequestId: `fleet:${mode}`, + ...(mode === "pinned" ? { environmentId: EnvironmentId.make("remote") } : {}), + }, + }), + ); + assert.isTrue(Exit.isFailure(result)); + assert.include(String(result), "qualified native placement adapter"); + assert.isTrue(Option.isNone(yield* receipts.getByCommandId(input.commandId))); + } + assert.deepEqual(yield* threads.listProjectThreads({ projectId, includeSubagents: false }), []); + assert.equal(harness.createWorktree.mock.calls.length, 0); + assert.equal(harness.runSetup.mock.calls.length, 0); + }).pipe(Effect.provide(harness.layer)); +}); + it.effect.each( (["new", "existing"] as const).flatMap((target) => (["user", "agent"] as const).map((createdBy) => ({ target, createdBy })), diff --git a/apps/server/src/orchestration-v2/ThreadLaunchService.ts b/apps/server/src/orchestration-v2/ThreadLaunchService.ts index b354ba6737e30..89e03133b6953 100644 --- a/apps/server/src/orchestration-v2/ThreadLaunchService.ts +++ b/apps/server/src/orchestration-v2/ThreadLaunchService.ts @@ -4,6 +4,8 @@ import * as TerminalManager from "../terminal/Manager.ts"; import { resolveProjectSettings } from "@t3tools/shared/projectSettings"; import { CommandId, + FLEET_PLACEMENT_UNAVAILABLE, + type FleetPlacementIntent, type ChatAttachment, type MessageId, type ModelSelection, @@ -83,6 +85,7 @@ export interface ThreadLaunchInitialMessage { export interface ThreadLaunchInput { readonly commandId: CommandId; + readonly fleetPlacement?: FleetPlacementIntent; readonly threadId?: ThreadId; readonly reuseExistingThread?: boolean; readonly projectId: ProjectId; @@ -1026,6 +1029,16 @@ const make = Effect.gen(function* () { const launch: ThreadLaunchService["Service"]["launch"] = Effect.fn("ThreadLaunchService.launch")( function* (request) { + // Protocol 2 alone does not qualify remote admission. Keep intent explicit + // until the native destination adapter persists and reconciles acceptance. + if (request.fleetPlacement !== undefined) { + return yield* new ThreadLaunchError({ + operation: "resolve-project", + commandId: request.commandId, + projectId: request.projectId, + cause: FLEET_PLACEMENT_UNAVAILABLE, + }); + } // Scratch has no Git repository. Normalize before folder allocation so // durable preparation and retries use the thread's own Scratch folder. const input: ThreadLaunchInput = diff --git a/apps/server/src/persistence/Protocol2DatabaseAdmission.test.ts b/apps/server/src/persistence/Protocol2DatabaseAdmission.test.ts new file mode 100644 index 0000000000000..821439aa1510a --- /dev/null +++ b/apps/server/src/persistence/Protocol2DatabaseAdmission.test.ts @@ -0,0 +1,72 @@ +// @effect-diagnostics nodeBuiltinImport:off - synthetic SQLite fixtures only. +import * as NodeFS from "node:fs"; +import * as NodeSqlite from "node:sqlite"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { assert, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; +import * as FileSystem from "effect/FileSystem"; +import * as Layer from "effect/Layer"; +import * as Path from "effect/Path"; +import { migrationManifest } from "./Migrations.ts"; +import { admitProtocol2Database } from "./Protocol2DatabaseAdmission.ts"; +import * as SqlitePersistence from "./Sqlite.ts"; + +function seed(path: string, rows: ReadonlyArray) { + const db = new NodeSqlite.DatabaseSync(path); + try { + db.exec("CREATE TABLE effect_sql_migrations (migration_id INTEGER PRIMARY KEY, name TEXT)"); + const insert = db.prepare("INSERT INTO effect_sql_migrations VALUES (?, ?)"); + for (const [id, name] of rows) insert.run(id, name); + } finally { + db.close(); + } +} + +it.effect.each(["newer", "collision"] as const)( + "refuses a %s schema before the native writer changes the file", + (kind) => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const directory = yield* fs.makeTempDirectoryScoped({ prefix: "clo866-v2-schema-" }); + const file = path.join(directory, "statev2.sqlite"); + seed(file, kind === "newer" ? [[900, "FutureSchema"]] : [[57, "ThreadInbox"]]); + const before = NodeFS.readFileSync(file); + const result = yield* Effect.exit( + Layer.build(SqlitePersistence.layerFromPath(file)).pipe(Effect.scoped), + ); + assert.isTrue(Exit.isFailure(result)); + assert.include(String(result), "Protocol2DatabaseCompatibilityError"); + assert.deepEqual(NodeFS.readFileSync(file), before); + assert.isFalse(NodeFS.existsSync(`${file}-wal`)); + assert.isFalse(NodeFS.existsSync(`${file}-shm`)); + }).pipe(Effect.provide(NodeServices.layer)), +); + +it.effect("accepts matching schema read-only and refuses implicit upgrades and imports", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const directory = yield* fs.makeTempDirectoryScoped({ prefix: "clo866-v2-exact-" }); + const current = path.join(directory, "current.sqlite"); + seed(current, migrationManifest); + const before = NodeFS.readFileSync(current); + yield* admitProtocol2Database(current, true); + assert.deepEqual(NodeFS.readFileSync(current), before); + const partial = path.join(directory, "partial.sqlite"); + seed(partial, migrationManifest.slice(0, 54)); + assert.isTrue(Exit.isFailure(yield* Effect.exit(admitProtocol2Database(partial, true)))); + const fresh = path.join(directory, "statev2.sqlite"); + yield* admitProtocol2Database(fresh, true); + assert.isFalse(NodeFS.existsSync(fresh)); + const legacy = path.join(directory, "state.sqlite"); + seed(legacy, [[1, "OrchestrationEvents"]]); + const legacyBefore = NodeFS.readFileSync(legacy); + const refused = yield* Effect.exit(admitProtocol2Database(fresh, true)); + assert.isTrue(Exit.isFailure(refused)); + assert.include(String(refused), "separately approved import"); + assert.isFalse(NodeFS.existsSync(fresh)); + assert.deepEqual(NodeFS.readFileSync(legacy), legacyBefore); + }).pipe(Effect.provide(NodeServices.layer)), +); diff --git a/apps/server/src/persistence/Protocol2DatabaseAdmission.ts b/apps/server/src/persistence/Protocol2DatabaseAdmission.ts new file mode 100644 index 0000000000000..727654938470e --- /dev/null +++ b/apps/server/src/persistence/Protocol2DatabaseAdmission.ts @@ -0,0 +1,47 @@ +// @effect-diagnostics nodeBuiltinImport:off - startup preflight must precede opening a writer. +import * as NodeFS from "node:fs"; +import * as NodePath from "node:path"; +import * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; +import { migrationManifest } from "./Migrations.ts"; +import { recordedMigrations } from "./databaseMigrationHead.ts"; + +export class Protocol2DatabaseCompatibilityError extends Schema.TaggedError()( + "Protocol2DatabaseCompatibilityError", + { databasePath: Schema.String, detail: Schema.String }, +) { + override get message() { + return `Refusing this protocol-2 candidate at ${this.databasePath}: ${this.detail}. No database migration or import was attempted. Use the qualified build for this database.`; + } +} + +/** This port is qualified for an existing matching V2 schema or fresh synthetic + * state. It must not invoke upstream's V1 copy/import path or upgrade a host as + * a side effect of evaluating founder ACLs. Never infer compatibility from a + * package version alone; compare every recorded migration's identity. + */ +export const admitProtocol2Database = Effect.fn("admitProtocol2Database")(function* ( + databasePath: string, + requireCurrentSchema = false, +) { + const refuse = (detail: string) => + new Protocol2DatabaseCompatibilityError({ databasePath, detail }); + if (!NodeFS.existsSync(databasePath)) { + if ( + requireCurrentSchema && + NodeFS.existsSync(NodePath.join(NodePath.dirname(databasePath), "state.sqlite")) + ) return yield* refuse("legacy state requires a separately approved import"); + return; + } + const recorded = recordedMigrations(databasePath); + if (recorded === null) return yield* refuse("migration history cannot be read"); + const expected = new Map(migrationManifest); + const seen = new Set(); + for (const row of recorded) { + if (seen.has(row.id) || expected.get(row.id) !== row.name) + return yield* refuse(`unrecognized migration ${row.id}:${row.name}`); + seen.add(row.id); + } + if (requireCurrentSchema && recorded.length !== migrationManifest.length) + return yield* refuse("schema does not exactly match this candidate"); +}); diff --git a/apps/server/src/persistence/Sqlite.ts b/apps/server/src/persistence/Sqlite.ts index d9506e31154fe..adc3e26090d36 100644 --- a/apps/server/src/persistence/Sqlite.ts +++ b/apps/server/src/persistence/Sqlite.ts @@ -12,6 +12,7 @@ import { hasPendingMigrations, runMigrations } from "./Migrations.ts"; import { initializeV2Database } from "./initializeV2Database.ts"; import * as ServerConfig from "../config.ts"; import * as ServerOwnership from "../serverOwnership.ts"; +import { admitProtocol2Database } from "./Protocol2DatabaseAdmission.ts"; const WAL_SIZE_LIMIT_BYTES = 128 * 1024 * 1024; @@ -102,6 +103,7 @@ const layerSetup = makeLayerSetup(runMigrations()); const makeLayerFromPath = (makeSetup: (dbPath: string) => Layer.Layer) => Effect.fn("makeSqlitePersistenceLive")(function* (dbPath: string) { + yield* admitProtocol2Database(dbPath); const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; yield* fs.makeDirectory(path.dirname(dbPath), { recursive: true }); @@ -145,6 +147,7 @@ const makeLayerConfig = ( Layer.unwrap( Effect.gen(function* () { const { dbPath } = yield* ServerConfig.ServerConfig; + yield* admitProtocol2Database(dbPath, true); yield* initializeV2Database(dbPath); return fromPath(dbPath); }), diff --git a/packages/client-runtime/src/load-balancing.ts b/packages/client-runtime/src/load-balancing.ts index 0b938c6c090e4..84c9c8bd0cb60 100644 --- a/packages/client-runtime/src/load-balancing.ts +++ b/packages/client-runtime/src/load-balancing.ts @@ -1,40 +1 @@ -import type { HostResourcesSnapshot } from "@t3tools/contracts"; - -/** Callers supply only connected machines hosting the project and selected provider. */ -export function chooseLoadBalancedEnvironment( - candidates: ReadonlyArray<{ - environmentId: string; - resources: HostResourcesSnapshot | null; - /** Client receipt time avoids comparing clocks on different machines. */ - receivedAt?: number; - weight: number; - }>, - now: number, -): string | null { - let selected: string | null = null; - let bestScore = 0; - for (const { environmentId, resources, receivedAt, weight } of candidates) { - const sampledAt = receivedAt ?? resources?.sampledAt ?? 0; - if ( - !resources || - !Number.isFinite(weight) || - weight <= 0 || - now - sampledAt > 15_000 || - sampledAt > now + 5_000 || - resources.cpuUtilization === null || - resources.cpuUtilization >= 0.95 || - resources.totalMemoryBytes <= 0 || - resources.cpuCount <= 0 - ) { - continue; - } - const memoryAvailable = resources.availableMemoryBytes / resources.totalMemoryBytes; - if (memoryAvailable <= 0.05) continue; - const score = weight * resources.cpuCount * (1 - resources.cpuUtilization) * memoryAvailable; - if (score > bestScore) { - selected = environmentId; - bestScore = score; - } - } - return selected; -} +export { chooseLoadBalancedEnvironment } from "@t3tools/shared/loadBalancing"; diff --git a/packages/contracts/src/fleetPlacement.ts b/packages/contracts/src/fleetPlacement.ts new file mode 100644 index 0000000000000..83c055bcfe6a1 --- /dev/null +++ b/packages/contracts/src/fleetPlacement.ts @@ -0,0 +1,17 @@ +import * as Schema from "effect/Schema"; +import { EnvironmentId, TrimmedNonEmptyString } from "./baseSchemas.ts"; + +/** Capability-gated launch intent, not a caller-authored admission decision. */ +export const FleetPlacementIntent = Schema.Union([ + Schema.Struct({ mode: Schema.Literal("auto"), clientRequestId: TrimmedNonEmptyString }), + Schema.Struct({ + mode: Schema.Literal("pinned"), + clientRequestId: TrimmedNonEmptyString, + environmentId: EnvironmentId, + }), +]); +export type FleetPlacementIntent = typeof FleetPlacementIntent.Type; + +export const FLEET_PLACEMENT_MIN_PROTOCOL = 2; +export const FLEET_PLACEMENT_UNAVAILABLE = + "Fleet placement requires protocol 2 and a qualified native placement adapter; this server cannot accept the request. No local fallback is allowed."; diff --git a/packages/contracts/src/index.ts b/packages/contracts/src/index.ts index 8dd47df33a21f..9d427200b6d48 100644 --- a/packages/contracts/src/index.ts +++ b/packages/contracts/src/index.ts @@ -73,3 +73,6 @@ export * from "./secretRequest.ts"; export * from "./secretReference.ts"; export * from "./settingsSecretValue.ts"; export * from "./clientRpcPermissions.ts"; + +export * from "./threadInbox.ts"; +export * from "./fleetPlacement.ts"; diff --git a/packages/contracts/src/threadInbox.test.ts b/packages/contracts/src/threadInbox.test.ts new file mode 100644 index 0000000000000..9962f06a9b633 --- /dev/null +++ b/packages/contracts/src/threadInbox.test.ts @@ -0,0 +1,85 @@ +import { describe, expect, it } from "vite-plus/test"; +import { EnvironmentId } from "./baseSchemas.ts"; +import { + defaultFounderInboxView, + canReadInbox, + canRouteInbox, + compositeThreadKey, + founderInboxLane, + inboxIdentityFromSubject, + inboxIdentitySubject, + type InboxIdentity, + type ThreadInbox, +} from "./threadInbox.ts"; +const human = (id: "kameron" | "jeff"): InboxIdentity => ({ + actor: { kind: "human", id }, + delegatesTo: [], + operational: false, +}); +const inbox: ThreadInbox = { + requestedBy: { kind: "human", id: "kameron" }, + actor: { kind: "human", id: "kameron" }, + assignee: { kind: "human", id: "kameron" }, + audience: "kameron", + attentionKind: "action", + executorEnvironmentId: EnvironmentId.make("crown"), +}; +describe("founder inbox policy", () => { + it("keeps host collisions separate without ambiguous separators", () => { + expect(compositeThreadKey("crown", "same")).not.toBe(compositeThreadKey("air", "same")); + expect(compositeThreadKey("a:b", "c")).not.toBe(compositeThreadKey("a", "b:c")); + }); + it("separates audience from assignment and attention", () => { + expect(canReadInbox(human("kameron"), inbox)).toBe(true); + expect(canReadInbox(human("jeff"), inbox)).toBe(false); + expect(canReadInbox(human("jeff"), { ...inbox, audience: "shared" })).toBe(true); + expect(founderInboxLane({ ...inbox, audience: "shared" }, "jeff")).toBe("hidden"); + expect(founderInboxLane({ ...inbox, attentionKind: "FYI" }, "kameron")).toBe("FYI"); + expect(founderInboxLane({ ...inbox, audience: "agent-only" }, "kameron")).toBe("hidden"); + }); + it("does not infer legacy provenance and confines operational visibility", () => { + expect(founderInboxLane(null, "kameron")).toBe("unknown"); + expect(canReadInbox(human("kameron"), null)).toBe(false); + expect(canReadInbox({ ...human("kameron"), operational: true }, null)).toBe(true); + expect(canReadInbox(human("kameron"), { ...inbox, audience: "agent-only" })).toBe(false); + }); + it("requires explicit cross-founder delegation including shared audiences", () => { + const target = { + ...inbox, + assignee: { kind: "human" as const, id: "jeff" as const }, + audience: "jeff" as const, + }; + expect(canRouteInbox(human("kameron"), target)).toBe(false); + expect(canRouteInbox({ ...human("kameron"), delegatesTo: ["jeff"] }, target)).toBe(true); + expect(canRouteInbox(human("kameron"), { ...inbox, audience: "shared" })).toBe(false); + }); + it("round-trips signed-subject identity and fails closed for malformed reserved subjects", () => { + expect(inboxIdentityFromSubject(inboxIdentitySubject(human("jeff")))).toEqual(human("jeff")); + expect(inboxIdentityFromSubject("one-time-token")).toBeNull(); + const malformed = inboxIdentityFromSubject("closura-inbox-v1:invalid"); + expect(malformed).not.toBeNull(); + expect(canReadInbox(malformed!, inbox)).toBe(false); + }); + it("defaults to the signed founder and does not infer identity from a host credential", () => { + expect(defaultFounderInboxView([inboxIdentitySubject(human("jeff"))])).toBe("jeff"); + expect(defaultFounderInboxView([inboxIdentitySubject(human("kameron"))])).toBe("kameron"); + expect(defaultFounderInboxView(["Jeff Air", "one-time-token"])).toBe("operations"); + expect( + defaultFounderInboxView([ + inboxIdentitySubject(human("jeff")), + inboxIdentitySubject(human("kameron")), + ]), + ).toBe("operations"); + }); + it("accepts a delegated agent assignment without confusing the human requester with its executor", () => { + const agent: InboxIdentity = { + actor: { kind: "agent", id: "lead" }, + delegatesTo: ["kameron"], + operational: false, + }; + const assigned = { ...inbox, assignee: agent.actor }; + expect(canReadInbox(agent, assigned)).toBe(true); + expect(canReadInbox({ ...agent, delegatesTo: [] }, assigned)).toBe(false); + expect(canReadInbox({ ...agent, actor: { kind: "agent", id: "other" } }, assigned)).toBe(false); + }); +}); diff --git a/packages/contracts/src/threadInbox.ts b/packages/contracts/src/threadInbox.ts new file mode 100644 index 0000000000000..106b32a25e872 --- /dev/null +++ b/packages/contracts/src/threadInbox.ts @@ -0,0 +1,102 @@ +import * as Schema from "effect/Schema"; +import { EnvironmentId, ThreadId, TrimmedNonEmptyString } from "./baseSchemas.ts"; + +export const Founder = Schema.Literals(["kameron", "jeff"]); +export type Founder = typeof Founder.Type; +export const InboxActor = Schema.Union([ + Schema.Struct({ kind: Schema.Literal("human"), id: Founder }), + Schema.Struct({ kind: Schema.Literal("agent"), id: TrimmedNonEmptyString }), +]); +export type InboxActor = typeof InboxActor.Type; +export const ThreadInboxRouting = Schema.Struct({ + assignee: InboxActor, + audience: Schema.Literals(["kameron", "jeff", "shared", "agent-only"]), + attentionKind: Schema.Literals(["action", "FYI", "background"]), +}); +export type ThreadInboxRouting = typeof ThreadInboxRouting.Type; +export const ThreadInbox = Schema.Struct({ + ...ThreadInboxRouting.fields, + requestedBy: InboxActor, + actor: InboxActor, + executorEnvironmentId: EnvironmentId, +}); +export type ThreadInbox = typeof ThreadInbox.Type; +export const InboxIdentity = Schema.Struct({ + actor: InboxActor, + requestedBy: Schema.optionalKey(InboxActor), + delegatesTo: Schema.Array(Founder), + operational: Schema.Boolean, +}); +export type InboxIdentity = typeof InboxIdentity.Type; + +export const INBOX_CAPABILITY = "closura-thread-inbox-v1" as const; +// JSON tuple encoding is injective even when an identifier contains a separator. +export const compositeThreadKey = (environmentId: string, threadId: string) => + JSON.stringify([environmentId, threadId]); +export const InboxThreadRef = Schema.Struct({ environmentId: EnvironmentId, threadId: ThreadId }); + +/** Only use with the subject verified by the destination's session authenticator. */ +export const inboxIdentitySubject = (identity: InboxIdentity) => + `closura-inbox-v1:${JSON.stringify(identity)}`; +const decodeIdentity = Schema.decodeUnknownOption(Schema.fromJsonString(InboxIdentity)); +export function inboxIdentityFromSubject(subject: string): InboxIdentity | null { + if (!subject.startsWith("closura-inbox-v1:")) return null; + const decoded = decodeIdentity(subject.slice("closura-inbox-v1:".length)); + // A malformed reserved identity must never fall back to host authority. + return decoded._tag === "Some" + ? decoded.value + : { actor: { kind: "agent", id: "" }, delegatesTo: [], operational: false }; +} +export function canReadInbox(identity: InboxIdentity, inbox: ThreadInbox | null | undefined) { + if (identity.operational) return true; + if (!inbox) return false; + if (identity.actor.kind === "human") { + return inbox.audience === identity.actor.id || inbox.audience === "shared"; + } + if (inbox.audience !== "agent-only") { + const audienceAllowed = + inbox.audience === "shared" + ? identity.delegatesTo.includes("kameron") && identity.delegatesTo.includes("jeff") + : identity.delegatesTo.includes(inbox.audience); + return ( + audienceAllowed && + ((inbox.actor.kind === "agent" && inbox.actor.id === identity.actor.id) || + (inbox.assignee.kind === "agent" && inbox.assignee.id === identity.actor.id)) + ); + } + return ( + inbox.audience === "agent-only" && + ((inbox.assignee.kind === "agent" && inbox.assignee.id === identity.actor.id) || + (inbox.actor.kind === "agent" && inbox.actor.id === identity.actor.id)) + ); +} +export function canRouteInbox(identity: InboxIdentity, routing: ThreadInboxRouting) { + const founders = new Set(); + if (routing.assignee.kind === "human") founders.add(routing.assignee.id); + if (routing.audience === "shared") { + founders.add("kameron"); + founders.add("jeff"); + } else if (routing.audience !== "agent-only") founders.add(routing.audience); + return [...founders].every( + (founder) => + (identity.actor.kind === "human" && identity.actor.id === founder) || + identity.delegatesTo.includes(founder), + ); +} +export function founderInboxLane(inbox: ThreadInbox | null | undefined, founder: Founder) { + if (!inbox) return "unknown"; + if (inbox.audience === "agent-only") return "hidden"; + if (inbox.audience !== "shared" && inbox.audience !== founder) return "hidden"; + if (inbox.assignee.kind !== "human" || inbox.assignee.id !== founder) return "hidden"; + return inbox.attentionKind; +} + +/** Defaults follow authenticated session subjects, never machine names or titles. */ +export function defaultFounderInboxView(subjects: ReadonlyArray): Founder | "operations" { + const founders = new Set(); + for (const subject of subjects) { + const identity = inboxIdentityFromSubject(subject); + if (identity?.actor.kind === "human") founders.add(identity.actor.id); + } + return founders.size === 1 ? [...founders][0]! : "operations"; +} diff --git a/packages/shared/package.json b/packages/shared/package.json index ba0b394f26d0c..388dfd938476d 100644 --- a/packages/shared/package.json +++ b/packages/shared/package.json @@ -3,6 +3,8 @@ "private": true, "type": "module", "exports": { + "./threadPlacement": { "types": "./src/threadPlacement.ts", "import": "./src/threadPlacement.ts" }, + "./loadBalancing": { "types": "./src/loadBalancing.ts", "import": "./src/loadBalancing.ts" }, "./pullRequestAnchor": { "types": "./src/pullRequestAnchor.ts", "import": "./src/pullRequestAnchor.ts" diff --git a/packages/shared/src/loadBalancing.ts b/packages/shared/src/loadBalancing.ts new file mode 100644 index 0000000000000..01eb928c061c1 --- /dev/null +++ b/packages/shared/src/loadBalancing.ts @@ -0,0 +1,48 @@ +import type { HostResourcesSnapshot } from "@t3tools/contracts"; + +/** Callers supply only connected machines hosting the project and selected provider. */ +export function chooseLoadBalancedEnvironment( + candidates: ReadonlyArray<{ + environmentId: string; + resources: HostResourcesSnapshot | null; + /** Client receipt time avoids comparing clocks on different machines. */ + receivedAt?: number; + weight: number; + }>, + now: number, +): string | null { + let selected: string | null = null; + let bestScore = 0; + for (const { environmentId, resources, receivedAt, weight } of candidates) { + const sampledAt = receivedAt ?? resources?.sampledAt ?? 0; + if ( + !resources || + !Number.isFinite(now) || + !Number.isFinite(sampledAt) || + !Number.isFinite(resources.cpuUtilization) || + (resources.cpuUtilization !== null && resources.cpuUtilization < 0) || + !Number.isFinite(resources.totalMemoryBytes) || + !Number.isFinite(resources.availableMemoryBytes) || + resources.availableMemoryBytes > resources.totalMemoryBytes || + !Number.isInteger(resources.cpuCount) || + !Number.isFinite(weight) || + weight <= 0 || + now - sampledAt > 15_000 || + sampledAt > now + 5_000 || + resources.cpuUtilization === null || + resources.cpuUtilization >= 0.95 || + resources.totalMemoryBytes <= 0 || + resources.cpuCount <= 0 + ) { + continue; + } + const memoryAvailable = resources.availableMemoryBytes / resources.totalMemoryBytes; + if (memoryAvailable <= 0.05) continue; + const score = weight * resources.cpuCount * (1 - resources.cpuUtilization) * memoryAvailable; + if (score > bestScore) { + selected = environmentId; + bestScore = score; + } + } + return selected; +} diff --git a/packages/shared/src/threadPlacement.test.ts b/packages/shared/src/threadPlacement.test.ts new file mode 100644 index 0000000000000..b4b4e6e38b735 --- /dev/null +++ b/packages/shared/src/threadPlacement.test.ts @@ -0,0 +1,126 @@ +import { describe, expect, it } from "vite-plus/test"; +import { chooseThreadPlacement, type ThreadPlacementCandidate } from "./threadPlacement.ts"; +const now = 1_000_000; +const candidate = (environmentId: string, weight = 1): ThreadPlacementCandidate => ({ + environmentId, + weight, + receivedAt: now, + resources: { + sampledAt: now, + cpuCount: 8, + cpuUtilization: 0.2, + totalMemoryBytes: 1000, + availableMemoryBytes: 500, + }, + online: true, + protocolCompatible: true, + operateGranted: true, + audienceGranted: true, + runtimeModeGranted: true, + projectAvailable: true, + providerAvailable: true, + modelAvailable: true, + hostedToolsAvailable: true, + contextCompatible: true, +}); +const request = { originEnvironmentId: "crown", requiresLocalState: false }; +const fleet = [ + candidate("crown"), + candidate("asus", 3), + candidate("r720", 4), + candidate("desktop", 2), + candidate("air"), +]; +describe("shared native placement policy", () => { + it("uses the native capacity selector across five eligible hosts", () => { + expect(chooseThreadPlacement(request, fleet, now)).toEqual({ + accepted: true, + environmentId: "r720", + reason: "capacity", + }); + expect(chooseThreadPlacement(request, [...fleet.slice(2), ...fleet.slice(0, 2)], now)).toEqual( + chooseThreadPlacement(request, fleet, now), + ); + }); + it.each([ + "online", + "protocolCompatible", + "operateGranted", + "audienceGranted", + "runtimeModeGranted", + "projectAvailable", + "providerAvailable", + "modelAvailable", + "contextCompatible", + ] as const)("refuses %s=false without silent local fallback", (gate) => { + expect( + chooseThreadPlacement(request, [{ ...candidate("r720"), [gate]: false }], now).accepted, + ).toBe(false); + }); + it("pins existing threads, explicit hosts and local child state", () => { + expect( + chooseThreadPlacement({ ...request, existingThreadEnvironmentId: "air" }, fleet, now), + ).toMatchObject({ environmentId: "air", reason: "existing" }); + expect( + chooseThreadPlacement({ ...request, pinnedEnvironmentId: "desktop" }, fleet, now), + ).toMatchObject({ environmentId: "desktop", reason: "pinned" }); + expect( + chooseThreadPlacement({ ...request, requiresLocalState: true }, fleet, now), + ).toMatchObject({ environmentId: "crown", reason: "locality" }); + expect( + chooseThreadPlacement( + { ...request, requiresLocalState: true, pinnedEnvironmentId: "r720" }, + fleet, + now, + ), + ).toEqual({ accepted: false, reason: "conflicting-locality" }); + }); + it("fails closed on overload, missing/stale metrics and invalid telemetry", () => { + const base = candidate("r720"); + for (const resources of [ + null, + { ...base.resources!, cpuUtilization: 0.95 }, + { ...base.resources!, availableMemoryBytes: 50 }, + { ...base.resources!, cpuCount: NaN }, + { ...base.resources!, availableMemoryBytes: Infinity }, + ]) { + expect(chooseThreadPlacement(request, [{ ...base, resources }], now).accepted).toBe(false); + } + expect( + chooseThreadPlacement(request, [{ ...base, receivedAt: now - 15_001 }], now).accepted, + ).toBe(false); + expect( + chooseThreadPlacement(request, [{ ...base, receivedAt: now + 5_001 }], now).accepted, + ).toBe(false); + expect(chooseThreadPlacement(request, [base, base], now)).toEqual({ + accepted: false, + reason: "ambiguous-environment", + }); + }); + it("keeps dependent children at the parent and checks hosted tool capability", () => { + expect( + chooseThreadPlacement({ ...request, parentEnvironmentId: "asus" }, fleet, now), + ).toMatchObject({ accepted: true, environmentId: "asus", reason: "locality" }); + expect( + chooseThreadPlacement( + { ...request, parentEnvironmentId: "asus", independentTask: true }, + fleet, + now, + ), + ).toMatchObject({ accepted: true, environmentId: "r720" }); + expect( + chooseThreadPlacement( + { ...request, parentEnvironmentId: "asus", pinnedEnvironmentId: "r720" }, + fleet, + now, + ).accepted, + ).toBe(false); + expect( + chooseThreadPlacement( + { ...request, requiresHostedTools: true }, + [{ ...candidate("r720"), hostedToolsAvailable: false }], + now, + ).accepted, + ).toBe(false); + }); +}); diff --git a/packages/shared/src/threadPlacement.ts b/packages/shared/src/threadPlacement.ts new file mode 100644 index 0000000000000..94cc685a21ca2 --- /dev/null +++ b/packages/shared/src/threadPlacement.ts @@ -0,0 +1,111 @@ +import type { HostResourcesSnapshot } from "@t3tools/contracts"; +import { chooseLoadBalancedEnvironment } from "./loadBalancing.ts"; + +/** Evidence must come from the authenticated native destination/link registry. + * Caller-supplied labels are not evidence. This function has no transport effects. + */ +export interface ThreadPlacementCandidate { + readonly environmentId: string; + readonly resources: HostResourcesSnapshot | null; + readonly receivedAt: number; + readonly weight: number; + readonly online: boolean; + readonly protocolCompatible: boolean; + readonly operateGranted: boolean; + readonly audienceGranted: boolean; + readonly runtimeModeGranted: boolean; + readonly projectAvailable: boolean; + readonly providerAvailable: boolean; + readonly modelAvailable: boolean; + readonly hostedToolsAvailable: boolean; + readonly contextCompatible: boolean; +} +export interface ThreadPlacementRequest { + readonly originEnvironmentId: string; + readonly pinnedEnvironmentId?: string; + readonly existingThreadEnvironmentId?: string; + readonly requiresLocalState: boolean; + readonly parentEnvironmentId?: string; + readonly independentTask?: boolean; + readonly requiresHostedTools?: boolean; +} +export type ThreadPlacementDecision = + | { + readonly accepted: true; + readonly environmentId: string; + readonly reason: "existing" | "pinned" | "locality" | "capacity"; + } + | { + readonly accepted: false; + readonly reason: "no-eligible-environment" | "conflicting-locality" | "ambiguous-environment"; + }; + +/** Native launch admission must call this for each NEW execution and bind the + * accepted identity to its durable request receipt before executing remotely. + * A timeout is not a rejection: reconcile that receipt, never select a new host. + */ +export function chooseThreadPlacement( + request: ThreadPlacementRequest, + candidates: ReadonlyArray, + now: number, +): ThreadPlacementDecision { + const ids = new Set(); + for (const candidate of candidates) { + if (ids.has(candidate.environmentId)) + return { accepted: false, reason: "ambiguous-environment" }; + ids.add(candidate.environmentId); + } + const pinned = request.existingThreadEnvironmentId ?? request.pinnedEnvironmentId; + const parentLocality = + request.parentEnvironmentId && request.independentTask !== true + ? request.parentEnvironmentId + : undefined; + if ( + request.requiresLocalState && + parentLocality && + parentLocality !== request.originEnvironmentId + ) { + return { accepted: false, reason: "conflicting-locality" }; + } + const locality = request.requiresLocalState ? request.originEnvironmentId : parentLocality; + if ( + (request.existingThreadEnvironmentId && + request.pinnedEnvironmentId && + request.existingThreadEnvironmentId !== request.pinnedEnvironmentId) || + (locality && pinned && pinned !== locality) + ) { + return { accepted: false, reason: "conflicting-locality" }; + } + const target = pinned ?? locality; + const eligible = candidates + .filter( + (candidate) => + candidate.online && + candidate.protocolCompatible && + candidate.operateGranted && + candidate.audienceGranted && + candidate.runtimeModeGranted && + candidate.projectAvailable && + candidate.providerAvailable && + candidate.modelAvailable && + (!request.requiresHostedTools || candidate.hostedToolsAvailable) && + candidate.contextCompatible && + (target === undefined || target === candidate.environmentId), + ) + .sort((a, b) => + a.environmentId < b.environmentId ? -1 : a.environmentId > b.environmentId ? 1 : 0, + ); + const environmentId = chooseLoadBalancedEnvironment(eligible, now); + if (environmentId === null) return { accepted: false, reason: "no-eligible-environment" }; + return { + accepted: true, + environmentId, + reason: request.existingThreadEnvironmentId + ? "existing" + : request.pinnedEnvironmentId + ? "pinned" + : locality !== undefined + ? "locality" + : "capacity", + }; +} From 7f7a73e2a9bedb8ccaf2f127df9208b2093b4c77 Mon Sep 17 00:00:00 2001 From: nullStack65 Date: Mon, 16 Nov 2026 12:38:01 -0500 Subject: [PATCH 2/9] fix(server): narrow native fleet admission fixture variants Keep each synthetic intent discriminated before native toolchain verification. Model: gpt-6.1-sol Task: implementation Agent: clo866-source --- .../src/orchestration-v2/ThreadLaunchService.test.ts | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts b/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts index 7f672c68ef36e..045b937509ef8 100644 --- a/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts +++ b/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts @@ -355,11 +355,9 @@ it.effect("refuses unqualified fleet intent before native launch effects", () => const result = yield* Effect.exit( launches.launch({ ...input, - fleetPlacement: { - mode, - clientRequestId: `fleet:${mode}`, - ...(mode === "pinned" ? { environmentId: EnvironmentId.make("remote") } : {}), - }, + fleetPlacement: mode === "auto" + ? { mode, clientRequestId: `fleet:${mode}` } + : { mode, clientRequestId: `fleet:${mode}`, environmentId: EnvironmentId.make("remote") }, }), ); assert.isTrue(Exit.isFailure(result)); From 3818f63bd433e6e52e650d6484eaf60b0bbb8747 Mon Sep 17 00:00:00 2001 From: nullStack65 Date: Mon, 16 Nov 2026 12:38:46 -0500 Subject: [PATCH 3/9] style(server): format the native protocol two staging changes Model: gpt-6.1-sol Task: implementation Agent: clo866-source --- .../src/orchestration-v2/ThreadLaunchService.test.ts | 11 ++++++++--- .../src/persistence/Protocol2DatabaseAdmission.ts | 3 ++- packages/shared/package.json | 10 ++++++++-- 3 files changed, 18 insertions(+), 6 deletions(-) diff --git a/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts b/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts index 045b937509ef8..9e6fa2ba8f9ec 100644 --- a/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts +++ b/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts @@ -355,9 +355,14 @@ it.effect("refuses unqualified fleet intent before native launch effects", () => const result = yield* Effect.exit( launches.launch({ ...input, - fleetPlacement: mode === "auto" - ? { mode, clientRequestId: `fleet:${mode}` } - : { mode, clientRequestId: `fleet:${mode}`, environmentId: EnvironmentId.make("remote") }, + fleetPlacement: + mode === "auto" + ? { mode, clientRequestId: `fleet:${mode}` } + : { + mode, + clientRequestId: `fleet:${mode}`, + environmentId: EnvironmentId.make("remote"), + }, }), ); assert.isTrue(Exit.isFailure(result)); diff --git a/apps/server/src/persistence/Protocol2DatabaseAdmission.ts b/apps/server/src/persistence/Protocol2DatabaseAdmission.ts index 727654938470e..7defaa29130c7 100644 --- a/apps/server/src/persistence/Protocol2DatabaseAdmission.ts +++ b/apps/server/src/persistence/Protocol2DatabaseAdmission.ts @@ -30,7 +30,8 @@ export const admitProtocol2Database = Effect.fn("admitProtocol2Database")(functi if ( requireCurrentSchema && NodeFS.existsSync(NodePath.join(NodePath.dirname(databasePath), "state.sqlite")) - ) return yield* refuse("legacy state requires a separately approved import"); + ) + return yield* refuse("legacy state requires a separately approved import"); return; } const recorded = recordedMigrations(databasePath); diff --git a/packages/shared/package.json b/packages/shared/package.json index 388dfd938476d..af345f5184374 100644 --- a/packages/shared/package.json +++ b/packages/shared/package.json @@ -3,8 +3,14 @@ "private": true, "type": "module", "exports": { - "./threadPlacement": { "types": "./src/threadPlacement.ts", "import": "./src/threadPlacement.ts" }, - "./loadBalancing": { "types": "./src/loadBalancing.ts", "import": "./src/loadBalancing.ts" }, + "./threadPlacement": { + "types": "./src/threadPlacement.ts", + "import": "./src/threadPlacement.ts" + }, + "./loadBalancing": { + "types": "./src/loadBalancing.ts", + "import": "./src/loadBalancing.ts" + }, "./pullRequestAnchor": { "types": "./src/pullRequestAnchor.ts", "import": "./src/pullRequestAnchor.ts" From 24bb67d85e77a7cc1f03ef0e2b61bb58a6ca75d3 Mon Sep 17 00:00:00 2001 From: nullStack65 Date: Mon, 16 Nov 2026 12:49:05 -0500 Subject: [PATCH 4/9] fix(server): retain native persistence errors and isolate candidate startup Keep compatibility refusal in the existing SqlError channel with the typed diagnosis as its cause. Candidate startup does not call the V1 import utility or abandoned-copy cleanup. Exercise real configured refusal with synthetic legacy state, while preserving explicit upstream import utility coverage. Expose the shared receipt store to native launch tests. Verification is pending on this exact checkpoint. Model: gpt-6.1-sol Task: implementation Agent: clo866-source --- .../ThreadLaunchService.test.ts | 1 + .../Protocol2DatabaseAdmission.test.ts | 12 ++++++++++- apps/server/src/persistence/Sqlite.ts | 20 +++++++++++++++---- .../persistence/initializeV2Database.test.ts | 10 +++++----- 4 files changed, 33 insertions(+), 10 deletions(-) diff --git a/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts b/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts index 9e6fa2ba8f9ec..7293e27089c76 100644 --- a/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts +++ b/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts @@ -297,6 +297,7 @@ function makeHarness(options: HarnessOptions = {}) { layerTitleRegeneration, layerOutbox, layerDatabase, + layerReceipts, layerExternalServices, ), createWorktree, diff --git a/apps/server/src/persistence/Protocol2DatabaseAdmission.test.ts b/apps/server/src/persistence/Protocol2DatabaseAdmission.test.ts index 821439aa1510a..2a21be9f5000e 100644 --- a/apps/server/src/persistence/Protocol2DatabaseAdmission.test.ts +++ b/apps/server/src/persistence/Protocol2DatabaseAdmission.test.ts @@ -11,6 +11,7 @@ import * as Path from "effect/Path"; import { migrationManifest } from "./Migrations.ts"; import { admitProtocol2Database } from "./Protocol2DatabaseAdmission.ts"; import * as SqlitePersistence from "./Sqlite.ts"; +import * as ServerConfig from "../config.ts"; function seed(path: string, rows: ReadonlyArray) { const db = new NodeSqlite.DatabaseSync(path); @@ -63,7 +64,16 @@ it.effect("accepts matching schema read-only and refuses implicit upgrades and i const legacy = path.join(directory, "state.sqlite"); seed(legacy, [[1, "OrchestrationEvents"]]); const legacyBefore = NodeFS.readFileSync(legacy); - const refused = yield* Effect.exit(admitProtocol2Database(fresh, true)); + const config = yield* ServerConfig.ServerConfig.pipe( + Effect.provide(ServerConfig.layerTest(directory, directory)), + ); + const refused = yield* Effect.exit( + Layer.build( + SqlitePersistence.layerConfig.pipe( + Layer.provide(ServerConfig.layer({ ...config, dbPath: fresh })), + ), + ).pipe(Effect.scoped), + ); assert.isTrue(Exit.isFailure(refused)); assert.include(String(refused), "separately approved import"); assert.isFalse(NodeFS.existsSync(fresh)); diff --git a/apps/server/src/persistence/Sqlite.ts b/apps/server/src/persistence/Sqlite.ts index adc3e26090d36..3adf81b957348 100644 --- a/apps/server/src/persistence/Sqlite.ts +++ b/apps/server/src/persistence/Sqlite.ts @@ -9,13 +9,24 @@ import * as SqlError from "effect/sql/SqlError"; import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient"; import { hasPendingMigrations, runMigrations } from "./Migrations.ts"; -import { initializeV2Database } from "./initializeV2Database.ts"; import * as ServerConfig from "../config.ts"; import * as ServerOwnership from "../serverOwnership.ts"; import { admitProtocol2Database } from "./Protocol2DatabaseAdmission.ts"; const WAL_SIZE_LIMIT_BYTES = 128 * 1024 * 1024; +// Keep the persistence layer's existing SqlError channel for callers while the +// refusal's typed cause retains the exact compatibility diagnosis. +const admitCandidateDatabase = (dbPath: string, requireCurrentSchema = false) => + admitProtocol2Database(dbPath, requireCurrentSchema).pipe( + Effect.mapError( + (cause) => + new SqlError.SqlError({ + reason: new SqlError.UnknownError({ cause, operation: "open", message: cause.message }), + }), + ), + ); + export class ServerOwnsDatabaseError extends Schema.TaggedError()( "ServerOwnsDatabaseError", { stateDir: Schema.String }, @@ -103,7 +114,7 @@ const layerSetup = makeLayerSetup(runMigrations()); const makeLayerFromPath = (makeSetup: (dbPath: string) => Layer.Layer) => Effect.fn("makeSqlitePersistenceLive")(function* (dbPath: string) { - yield* admitProtocol2Database(dbPath); + yield* admitCandidateDatabase(dbPath); const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; yield* fs.makeDirectory(path.dirname(dbPath), { recursive: true }); @@ -147,8 +158,9 @@ const makeLayerConfig = ( Layer.unwrap( Effect.gen(function* () { const { dbPath } = yield* ServerConfig.ServerConfig; - yield* admitProtocol2Database(dbPath, true); - yield* initializeV2Database(dbPath); + yield* admitCandidateDatabase(dbPath, true); + // Candidate startup never imports V1 data or runs upstream's abandoned + // import cleanup. Matching V2 state and fresh fixtures need neither. return fromPath(dbPath); }), ); diff --git a/apps/server/src/persistence/initializeV2Database.test.ts b/apps/server/src/persistence/initializeV2Database.test.ts index f8c68f49ceb9a..035b8c08c9614 100644 --- a/apps/server/src/persistence/initializeV2Database.test.ts +++ b/apps/server/src/persistence/initializeV2Database.test.ts @@ -24,7 +24,7 @@ import * as EventSink from "../orchestration-v2/EventSink.ts"; import * as LegacyV1ThreadImporter from "../orchestration-v2/legacy/LegacyV1ThreadImporter.ts"; it.effect( - "snapshots V1, imports transcripts lazily, and preserves both databases across switches", + "explicit import utility preserves synthetic V1 and V2 transcripts across switches", () => { const directory = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-v1-v2-")); const sourcePath = NodePath.join(directory, "state.sqlite"); @@ -46,10 +46,10 @@ it.effect( return Effect.gen(function* () { yield* seed; const original = NodeFS.readFileSync(sourcePath); - const config = yield* ServerConfig.ServerConfig; - const layerDatabase = SqlitePersistence.layerConfig.pipe( - Layer.provide(ServerConfig.layer({ ...config, dbPath: destinationPath })), - ); + // Exercise the upstream utility explicitly with synthetic state; this + // candidate's configured startup refuses implicit imports. + yield* initializeV2Database(destinationPath); + const layerDatabase = SqlitePersistence.layerFromPath(destinationPath); const layerStores = Layer.mergeAll(EventStore.layer, ProjectionStore.layer).pipe( Layer.provideMerge(layerDatabase), ); From 220d1de78a5adeca6703d1c1169ae0b3095273bf Mon Sep 17 00:00:00 2001 From: nullStack65 Date: Mon, 16 Nov 2026 13:16:30 -0500 Subject: [PATCH 5/9] feat(server): preserve native fleet intent and qualify account isolation Carry explicit fleet intent through the protocol-two wire schema, reject it before workspace and attachment effects, and reject direct native creation under serialized admission with repeatable rejection receipts. Capabilities remain disabled. Add a synthetic Linux kernel qualification fixture for separate controller and account execution identities, including provider homes, databases, session files, shell reads, capability removal and label forgery. This is not multiaccount product acceptance; native principal persistence and execution binding remain incomplete. Model: gpt-6.1-sol Task: implementation Agent: clo866-source --- .../scripts/account-isolation.kernel.py | 121 ++++++++++++++++++ .../src/environment/ServerEnvironment.ts | 2 + .../src/orchestration-v2/Orchestrator.ts | 8 ++ .../ThreadLaunchService.test.ts | 48 +++++-- .../orchestration-v2/ThreadLaunchService.ts | 23 ++-- .../orchestration-v2/ThreadMessageIntake.ts | 1 + apps/server/src/ws.ts | 88 +++++++------ packages/contracts/src/environment.ts | 2 + packages/contracts/src/orchestrationV2.ts | 3 + 9 files changed, 234 insertions(+), 62 deletions(-) create mode 100644 apps/server/scripts/account-isolation.kernel.py diff --git a/apps/server/scripts/account-isolation.kernel.py b/apps/server/scripts/account-isolation.kernel.py new file mode 100644 index 0000000000000..3de5225dc8b7f --- /dev/null +++ b/apps/server/scripts/account-isolation.kernel.py @@ -0,0 +1,121 @@ +"""Qualify the Linux account execution boundary with fresh synthetic state only. + +Run in a disposable root-owned sandbox with private /tmp and no host-home mounts. +This proves kernel file and privilege separation, not native API/fleet acceptance. +""" + +import json +import os +from pathlib import Path +import shutil +import sqlite3 +import subprocess +import sys +import tempfile + + +PROBE = r""" +import json, os, subprocess, sys +from pathlib import Path +p = json.load(sys.stdin) +assert os.getuid() == p['uid'] +assert os.getgid() == p['uid'] +assert os.getgroups() == [] +status = dict(line.split(':', 1) for line in Path('/proc/self/status').read_text().splitlines() if ':' in line) +assert int(status['CapEff'].strip(), 16) == 0 +assert int(status['CapBnd'].strip(), 16) == 0 +assert status['NoNewPrivs'].strip() == '1' +regain = subprocess.run(['/usr/bin/setpriv', '--reuid', '0', '--', '/usr/bin/id', '-u'], capture_output=True, timeout=5) +assert regain.returncode != 0 +assert Path(p['own_provider']).read_text() == 'synthetic provider credential' +assert Path(p['own_workspace']).read_text() == 'synthetic workspace' +assert not any(k in os.environ for k in ['SSH_AUTH_SOCK', 'GITHUB_TOKEN', 'CODEX_HOME', 'T3CODE_DEV_AUTH_TOKEN']) +denied = {} +for label, file in p['forbidden'].items(): + try: + Path(file).read_bytes() + except PermissionError: + denied[label] = True + else: + raise AssertionError('cross-account read succeeded: ' + label) + shell = subprocess.run(['/bin/sh', '-c', 'cat "$1"', 'probe', file], capture_output=True, timeout=5) + assert shell.returncode != 0 and shell.stdout == b'' +print(json.dumps({'account': p['account'], 'uid': os.getuid(), 'effective_caps': 0, 'bounding_caps': 0, 'no_new_privileges': True, 'privilege_escalation_denied': True, 'forged_account_label_ignored': os.environ['ACCOUNT_ID'] != p['account'], 'denied': denied})) +""" + + +def write_private(file, value, uid): + file.parent.mkdir(parents=True, exist_ok=True, mode=0o700) + os.chown(file.parent, uid, uid) + file.write_text(value) + file.chmod(0o600) + os.chown(file, uid, uid) + + +def run(): + if sys.platform != "linux" or os.geteuid() != 0 or shutil.which("setpriv") is None: + print(json.dumps({"status": "unavailable", "requires": "disposable Linux root sandbox with setpriv"})) + return 77 + with tempfile.TemporaryDirectory(prefix="clo866-account-kernel-") as temporary: + root = Path(temporary) + root.chmod(0o755) + control = root / "control" + control.mkdir(mode=0o700) + session = control / "human-session.token" + write_private(session, "synthetic human session", 0) + db = control / "statev2.sqlite" + with sqlite3.connect(db) as connection: + connection.execute("CREATE TABLE fixture (value TEXT)") + connection.execute("INSERT INTO fixture VALUES ('synthetic control state')") + db.chmod(0o600) + accounts = [] + for name, uid in [("kameron", 65000), ("jeff", 65001)]: + home = root / name + home.mkdir(mode=0o700) + os.chown(home, uid, uid) + provider = home / ".codex" / "auth.json" + workspace = home / "workspace" / "private.txt" + database = home / "history" / "statev2.sqlite" + write_private(provider, "synthetic provider credential", uid) + write_private(workspace, "synthetic workspace", uid) + database.parent.mkdir(mode=0o700) + os.chown(database.parent, uid, uid) + with sqlite3.connect(database) as connection: + connection.execute("CREATE TABLE fixture (account TEXT)") + connection.execute("INSERT INTO fixture VALUES (?)", (name,)) + database.chmod(0o600) + os.chown(database, uid, uid) + accounts.append((name, uid, home, provider, workspace, database)) + results = [] + for index, (name, uid, home, provider, workspace, database) in enumerate(accounts): + other = accounts[1 - index] + payload = { + "account": name, + "uid": uid, + "own_provider": str(provider), + "own_workspace": str(workspace), + "forbidden": { + "other_provider_home": str(other[3]), + "other_workspace": str(other[4]), + "other_database": str(other[5]), + "controller_database": str(db), + "human_session": str(session), + }, + } + result = subprocess.run( + ["/usr/bin/setpriv", "--reuid", str(uid), "--regid", str(uid), + "--clear-groups", "--bounding-set=-all", "--no-new-privs", "--", + sys.executable, "-c", PROBE], + input=json.dumps(payload), text=True, capture_output=True, timeout=15, + cwd=home, + env={"HOME": str(home), "PATH": "/usr/bin:/bin", "LANG": "C.UTF-8", "ACCOUNT_ID": other[0]}, + ) + if result.returncode != 0: + raise RuntimeError(f"synthetic {name} isolation probe failed: {result.stderr}") + results.append(json.loads(result.stdout)) + print(json.dumps({"status": "passed", "scope": "synthetic Linux kernel boundary only", "accounts": results})) + return 0 + + +if __name__ == "__main__": + raise SystemExit(run()) diff --git a/apps/server/src/environment/ServerEnvironment.ts b/apps/server/src/environment/ServerEnvironment.ts index 2c79189878e8a..fd3d051f96636 100644 --- a/apps/server/src/environment/ServerEnvironment.ts +++ b/apps/server/src/environment/ServerEnvironment.ts @@ -290,6 +290,8 @@ export const make = Effect.gen(function* () { ...(desktopAppUpdate ? { desktopAppUpdate: true, desktopAppChannelSwitch: true } : {}), serverBrowser: true, peerLinks: true, + threadInbox: false, + fleetPlacement: false, mcpModeLimitHeader: true, linkFence: true, mcpApprovalCodes: true, diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 00f9dfae8d9e1..d1bf22a631e68 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -22,6 +22,7 @@ import { } from "../sourceControl/threadPullRequests.ts"; import { ORCHESTRATION_V2_WORKSPACE_PREPARATION_FAILURE_CODE, + FLEET_PLACEMENT_UNAVAILABLE, type ChatAttachment, CommandId, type GuestMessageId, @@ -3620,6 +3621,13 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio command: Extract, events: Ref.Ref>, ) { + if (command.fleetPlacement !== undefined) { + return yield* new OrchestratorDispatchError({ + commandId: command.commandId, + commandType: command.type, + cause: FLEET_PLACEMENT_UNAVAILABLE, + }); + } yield* Effect.annotateCurrentSpan({ "orchestration_v2.command_id": command.commandId, "orchestration_v2.command_type": command.type, diff --git a/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts b/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts index 7293e27089c76..f02d6a8a7ff83 100644 --- a/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts +++ b/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts @@ -23,6 +23,7 @@ import { ProviderDriverKind, ProviderInstanceId, OrchestrationV2ThreadProjectionJson, + OrchestrationV2ThreadLaunchInput, ScheduledTaskId, type ServerProvider, ThreadId, @@ -73,6 +74,7 @@ import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAda const projectId = ProjectId.make("project:launch-test"); const otherProjectId = ProjectId.make("project:launch-other"); const encodeThreadProjection = Schema.encodeEffect(OrchestrationV2ThreadProjectionJson); +const decodeThreadLaunchInput = Schema.decodeUnknownEffect(OrchestrationV2ThreadLaunchInput); const modelSelection = { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.1-codex", @@ -353,22 +355,38 @@ it.effect("refuses unqualified fleet intent before native launch effects", () => message: "must not launch", workspace: { type: "worktree", baseRef: "main" }, }); + const wire = yield* decodeThreadLaunchInput({ + ...input, + fleetPlacement: + mode === "auto" + ? { mode, clientRequestId: `fleet:${mode}` } + : { + mode, + clientRequestId: `fleet:${mode}`, + environmentId: EnvironmentId.make("remote"), + }, + }); const result = yield* Effect.exit( - launches.launch({ - ...input, - fleetPlacement: - mode === "auto" - ? { mode, clientRequestId: `fleet:${mode}` } - : { - mode, - clientRequestId: `fleet:${mode}`, - environmentId: EnvironmentId.make("remote"), - }, - }), + launches.launch({ ...wire, createdBy: "user", creationSource: "web" }), ); assert.isTrue(Exit.isFailure(result)); assert.include(String(result), "qualified native placement adapter"); assert.isTrue(Option.isNone(yield* receipts.getByCommandId(input.commandId))); + const command = { + ...input, + type: "thread.create" as const, + branch: null, + worktreePath: null, + ...(wire.fleetPlacement === undefined ? {} : { fleetPlacement: wire.fleetPlacement }), + }; + // Native callers bypassing launch still meet serialized admission. The + // native rejection receipt, including its identity, survives retries. + assert.isTrue(Exit.isFailure(yield* Effect.exit(threads.dispatch(command)))); + const receipt = yield* receipts.getByCommandId(input.commandId); + assert.isTrue(Option.isSome(receipt)); + if (Option.isSome(receipt)) assert.equal(receipt.value.status, "rejected"); + assert.isTrue(Exit.isFailure(yield* Effect.exit(threads.dispatch(command)))); + assert.deepEqual(yield* receipts.getByCommandId(input.commandId), receipt); } assert.deepEqual(yield* threads.listProjectThreads({ projectId, includeSubagents: false }), []); assert.equal(harness.createWorktree.mock.calls.length, 0); @@ -1249,7 +1267,13 @@ it.effect.each(["stable", "upstream/release"])( const worktreePath = `${directory}/worktree`; yield* fs.makeDirectory(cwd); const command = (at: string, args: string[]) => - git.execute({ operation: "launch-test", cwd: at, args }); + git + .execute({ operation: "launch-test", cwd: at, args, allowNonZeroExit: true }) + .pipe( + Effect.tap((result) => + Effect.sync(() => assert.equal(result.exitCode, 0, result.stderr)), + ), + ); yield* command(cwd, ["init", "-b", "stable"]); yield* command(cwd, ["config", "user.name", "Test"]); yield* command(cwd, ["config", "user.email", "test@example.test"]); diff --git a/apps/server/src/orchestration-v2/ThreadLaunchService.ts b/apps/server/src/orchestration-v2/ThreadLaunchService.ts index 89e03133b6953..54d1c2f575af4 100644 --- a/apps/server/src/orchestration-v2/ThreadLaunchService.ts +++ b/apps/server/src/orchestration-v2/ThreadLaunchService.ts @@ -159,6 +159,20 @@ export class ThreadLaunchError extends Schema.TaggedError()( } } +/** Reuse before attachment claims, workspace preflight and direct native launch. */ +export const requireQualifiedFleetPlacement = Effect.fn("requireQualifiedFleetPlacement")( + function* (request: Pick) { + if (request.fleetPlacement !== undefined) { + return yield* new ThreadLaunchError({ + operation: "resolve-project", + commandId: request.commandId, + projectId: request.projectId, + cause: FLEET_PLACEMENT_UNAVAILABLE, + }); + } + }, +); + export class ThreadLaunchBaseRefError extends Schema.TaggedError()( "ThreadLaunchBaseRefError", { @@ -1031,14 +1045,7 @@ const make = Effect.gen(function* () { function* (request) { // Protocol 2 alone does not qualify remote admission. Keep intent explicit // until the native destination adapter persists and reconciles acceptance. - if (request.fleetPlacement !== undefined) { - return yield* new ThreadLaunchError({ - operation: "resolve-project", - commandId: request.commandId, - projectId: request.projectId, - cause: FLEET_PLACEMENT_UNAVAILABLE, - }); - } + yield* requireQualifiedFleetPlacement(request); // Scratch has no Git repository. Normalize before folder allocation so // durable preparation and retries use the thread's own Scratch folder. const input: ThreadLaunchInput = diff --git a/apps/server/src/orchestration-v2/ThreadMessageIntake.ts b/apps/server/src/orchestration-v2/ThreadMessageIntake.ts index c6a6cdbf7ac1e..f15edaadfddb1 100644 --- a/apps/server/src/orchestration-v2/ThreadMessageIntake.ts +++ b/apps/server/src/orchestration-v2/ThreadMessageIntake.ts @@ -212,6 +212,7 @@ export const sendToThread = Effect.fn("ThreadMessageIntake.sendToThread")(functi export const launchThread = Effect.fn("ThreadMessageIntake.launchThread")(function* ( input: ThreadLaunch.ThreadLaunchInput, ) { + yield* ThreadLaunch.requireQualifiedFleetPlacement(input); const launches = yield* ThreadLaunch.ThreadLaunchService; yield* AttachmentClaims.validateAttachmentLimits(input.initialMessage?.attachments ?? []); if (!input.initialMessage?.attachments.some(AttachmentClaims.attachmentIsPendingUpload)) { diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index 1f2a148734d4e..64fc30ec04d65 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -2140,49 +2140,53 @@ export const layerWsRpc = ( Effect.andThen( startup .enqueueCommand( - threadLaunch - .checkWorktreeBase({ - commandId: input.commandId, - projectId: input.projectId, - workspaceStrategy: input.workspaceStrategy, - }) - .pipe( - Effect.andThen( - ThreadMessageIntake.launchThread({ - commandId: input.commandId, - ...(input.threadId === undefined ? {} : { threadId: input.threadId }), - ...(input.reuseExistingThread === undefined - ? {} - : { reuseExistingThread: input.reuseExistingThread }), - projectId: input.projectId, - title: input.title, - ...(input.generateTitle === undefined - ? {} - : { generateTitle: input.generateTitle }), - modelSelection: input.modelSelection, - runtimeMode: input.runtimeMode, - interactionMode: input.interactionMode, - workspaceStrategy: input.workspaceStrategy, - ...(input.initialMessage === undefined - ? {} - : { - initialMessage: { - ...(input.initialMessage.messageId === undefined - ? {} - : { messageId: input.initialMessage.messageId }), - text: input.initialMessage.text, - attachments: input.initialMessage.attachments, - ...(input.initialMessage.context === undefined - ? {} - : { context: input.initialMessage.context }), - }, - }), - createdBy: "user", - creationSource: input.creationSource ?? "web", - }), - ), - Effect.provide(intakeContext), + ThreadLaunchService.requireQualifiedFleetPlacement(input).pipe( + Effect.andThen( + threadLaunch.checkWorktreeBase({ + commandId: input.commandId, + projectId: input.projectId, + workspaceStrategy: input.workspaceStrategy, + }), ), + Effect.andThen( + ThreadMessageIntake.launchThread({ + commandId: input.commandId, + ...(input.fleetPlacement === undefined + ? {} + : { fleetPlacement: input.fleetPlacement }), + ...(input.threadId === undefined ? {} : { threadId: input.threadId }), + ...(input.reuseExistingThread === undefined + ? {} + : { reuseExistingThread: input.reuseExistingThread }), + projectId: input.projectId, + title: input.title, + ...(input.generateTitle === undefined + ? {} + : { generateTitle: input.generateTitle }), + modelSelection: input.modelSelection, + runtimeMode: input.runtimeMode, + interactionMode: input.interactionMode, + workspaceStrategy: input.workspaceStrategy, + ...(input.initialMessage === undefined + ? {} + : { + initialMessage: { + ...(input.initialMessage.messageId === undefined + ? {} + : { messageId: input.initialMessage.messageId }), + text: input.initialMessage.text, + attachments: input.initialMessage.attachments, + ...(input.initialMessage.context === undefined + ? {} + : { context: input.initialMessage.context }), + }, + }), + createdBy: "user", + creationSource: input.creationSource ?? "web", + }), + ), + Effect.provide(intakeContext), + ), ) .pipe( // A resumed launch is a retry of one already counted. diff --git a/packages/contracts/src/environment.ts b/packages/contracts/src/environment.ts index e305efb51f838..dd042fc73f2b5 100644 --- a/packages/contracts/src/environment.ts +++ b/packages/contracts/src/environment.ts @@ -174,6 +174,8 @@ export const ExecutionEnvironmentCapabilities = Schema.Struct({ in them. Absent on servers from before linking, which clients must not offer linking for. */ peerLinks: Schema.optionalKey(Schema.Boolean), + threadInbox: Schema.optionalKey(Schema.Boolean), + fleetPlacement: Schema.optionalKey(Schema.Boolean), /** Server's `/mcp` narrows an OAuth client's modes from `T3-Mode-Limit`, so a linked environment's calls keep its agent's limits. Another environment links to this one only when it is set. */ diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts index bf6b53666f4d7..d590ec9e43bf6 100644 --- a/packages/contracts/src/orchestrationV2.ts +++ b/packages/contracts/src/orchestrationV2.ts @@ -3,6 +3,7 @@ import { withRecordIdTable } from "./orchestrationV2IdTable.ts"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as Schema from "effect/Schema"; +import { FleetPlacementIntent } from "./fleetPlacement.ts"; import * as SchemaAST from "effect/SchemaAST"; import * as SchemaGetter from "effect/SchemaGetter"; import * as SchemaTransformation from "effect/SchemaTransformation"; @@ -3065,6 +3066,7 @@ export const OrchestrationV2Command = Schema.Union([ type: Schema.Literal("thread.create"), ...OrchestrationV2CreationFields, commandId: CommandId, + fleetPlacement: Schema.optionalKey(FleetPlacementIntent), threadId: ThreadId, projectId: ProjectId, title: TrimmedNonEmptyString, @@ -3840,6 +3842,7 @@ export type OrchestrationV2ArchivedShellSnapshot = typeof OrchestrationV2Archive export const OrchestrationV2ThreadLaunchInput = Schema.Struct({ commandId: CommandId, + fleetPlacement: Schema.optionalKey(FleetPlacementIntent), creationSource: Schema.optional(OrchestrationV2CreationSource), threadId: Schema.optional(ThreadId), reuseExistingThread: Schema.optional(Schema.Boolean), From dd76e337944e11c4bc3b99783ca72e3298e6070e Mon Sep 17 00:00:00 2001 From: nullStack65 Date: Mon, 16 Nov 2026 14:11:18 -0500 Subject: [PATCH 6/9] feat(threads): organize shared fleet threads into founder inboxes Replace staged isolation and placement scope with durable organizational metadata, a device-local inbox picker, and native agent routing. All threads remain accessible. Model: gpt-6.1-sol Task: implementation Agent: clo866-source --- .../scripts/account-isolation.kernel.py | 121 -------------- .../src/environment/ServerEnvironment.ts | 3 +- apps/server/src/mcp/OrchestratorMcpService.ts | 6 + .../src/mcp/ThreadMetadataMcpService.ts | 10 +- .../src/mcp/toolkits/orchestrator/tools.ts | 2 +- .../src/mcp/toolkits/project/handlers.ts | 6 + apps/server/src/mcp/toolkits/project/tools.ts | 2 + .../src/orchestration-v2/Orchestrator.ts | 35 +++- .../src/orchestration-v2/ProjectionStore.ts | 2 + .../ThreadLaunchService.test.ts | 96 ++++------- .../orchestration-v2/ThreadLaunchService.ts | 26 +-- .../orchestration-v2/ThreadMessageIntake.ts | 1 - .../Protocol2DatabaseAdmission.test.ts | 82 --------- .../persistence/Protocol2DatabaseAdmission.ts | 48 ------ apps/server/src/persistence/Sqlite.ts | 19 +-- .../persistence/initializeV2Database.test.ts | 10 +- apps/server/src/ws.ts | 94 +++++------ apps/web/src/components/Sidebar.tsx | 26 ++- .../components/sidebar/SidebarInboxBar.tsx | 49 ++++++ .../src/components/threadActionMenu.logic.ts | 49 ++++++ apps/web/src/state/threads.ts | 2 + packages/client-runtime/src/load-balancing.ts | 41 ++++- .../client-runtime/src/operations/commands.ts | 12 +- .../src/state/threadCommands.ts | 13 +- packages/contracts/src/environment.ts | 1 - packages/contracts/src/fleetPlacement.ts | 17 -- packages/contracts/src/index.ts | 1 - packages/contracts/src/orchestrationV2.ts | 11 +- packages/contracts/src/orchestratorMcp.ts | 3 + packages/contracts/src/settings.ts | 5 + packages/contracts/src/threadInbox.test.ts | 144 ++++++++-------- packages/contracts/src/threadInbox.ts | 155 ++++++++++-------- .../contracts/src/threadMetadataMcp.test.ts | 13 ++ packages/contracts/src/threadMetadataMcp.ts | 10 +- .../src/server/subagentProjection.ts | 6 + packages/shared/package.json | 8 - packages/shared/src/loadBalancing.ts | 48 ------ packages/shared/src/threadPlacement.test.ts | 126 -------------- packages/shared/src/threadPlacement.ts | 111 ------------- 39 files changed, 532 insertions(+), 882 deletions(-) delete mode 100644 apps/server/scripts/account-isolation.kernel.py delete mode 100644 apps/server/src/persistence/Protocol2DatabaseAdmission.test.ts delete mode 100644 apps/server/src/persistence/Protocol2DatabaseAdmission.ts create mode 100644 apps/web/src/components/sidebar/SidebarInboxBar.tsx delete mode 100644 packages/contracts/src/fleetPlacement.ts delete mode 100644 packages/shared/src/loadBalancing.ts delete mode 100644 packages/shared/src/threadPlacement.test.ts delete mode 100644 packages/shared/src/threadPlacement.ts diff --git a/apps/server/scripts/account-isolation.kernel.py b/apps/server/scripts/account-isolation.kernel.py deleted file mode 100644 index 3de5225dc8b7f..0000000000000 --- a/apps/server/scripts/account-isolation.kernel.py +++ /dev/null @@ -1,121 +0,0 @@ -"""Qualify the Linux account execution boundary with fresh synthetic state only. - -Run in a disposable root-owned sandbox with private /tmp and no host-home mounts. -This proves kernel file and privilege separation, not native API/fleet acceptance. -""" - -import json -import os -from pathlib import Path -import shutil -import sqlite3 -import subprocess -import sys -import tempfile - - -PROBE = r""" -import json, os, subprocess, sys -from pathlib import Path -p = json.load(sys.stdin) -assert os.getuid() == p['uid'] -assert os.getgid() == p['uid'] -assert os.getgroups() == [] -status = dict(line.split(':', 1) for line in Path('/proc/self/status').read_text().splitlines() if ':' in line) -assert int(status['CapEff'].strip(), 16) == 0 -assert int(status['CapBnd'].strip(), 16) == 0 -assert status['NoNewPrivs'].strip() == '1' -regain = subprocess.run(['/usr/bin/setpriv', '--reuid', '0', '--', '/usr/bin/id', '-u'], capture_output=True, timeout=5) -assert regain.returncode != 0 -assert Path(p['own_provider']).read_text() == 'synthetic provider credential' -assert Path(p['own_workspace']).read_text() == 'synthetic workspace' -assert not any(k in os.environ for k in ['SSH_AUTH_SOCK', 'GITHUB_TOKEN', 'CODEX_HOME', 'T3CODE_DEV_AUTH_TOKEN']) -denied = {} -for label, file in p['forbidden'].items(): - try: - Path(file).read_bytes() - except PermissionError: - denied[label] = True - else: - raise AssertionError('cross-account read succeeded: ' + label) - shell = subprocess.run(['/bin/sh', '-c', 'cat "$1"', 'probe', file], capture_output=True, timeout=5) - assert shell.returncode != 0 and shell.stdout == b'' -print(json.dumps({'account': p['account'], 'uid': os.getuid(), 'effective_caps': 0, 'bounding_caps': 0, 'no_new_privileges': True, 'privilege_escalation_denied': True, 'forged_account_label_ignored': os.environ['ACCOUNT_ID'] != p['account'], 'denied': denied})) -""" - - -def write_private(file, value, uid): - file.parent.mkdir(parents=True, exist_ok=True, mode=0o700) - os.chown(file.parent, uid, uid) - file.write_text(value) - file.chmod(0o600) - os.chown(file, uid, uid) - - -def run(): - if sys.platform != "linux" or os.geteuid() != 0 or shutil.which("setpriv") is None: - print(json.dumps({"status": "unavailable", "requires": "disposable Linux root sandbox with setpriv"})) - return 77 - with tempfile.TemporaryDirectory(prefix="clo866-account-kernel-") as temporary: - root = Path(temporary) - root.chmod(0o755) - control = root / "control" - control.mkdir(mode=0o700) - session = control / "human-session.token" - write_private(session, "synthetic human session", 0) - db = control / "statev2.sqlite" - with sqlite3.connect(db) as connection: - connection.execute("CREATE TABLE fixture (value TEXT)") - connection.execute("INSERT INTO fixture VALUES ('synthetic control state')") - db.chmod(0o600) - accounts = [] - for name, uid in [("kameron", 65000), ("jeff", 65001)]: - home = root / name - home.mkdir(mode=0o700) - os.chown(home, uid, uid) - provider = home / ".codex" / "auth.json" - workspace = home / "workspace" / "private.txt" - database = home / "history" / "statev2.sqlite" - write_private(provider, "synthetic provider credential", uid) - write_private(workspace, "synthetic workspace", uid) - database.parent.mkdir(mode=0o700) - os.chown(database.parent, uid, uid) - with sqlite3.connect(database) as connection: - connection.execute("CREATE TABLE fixture (account TEXT)") - connection.execute("INSERT INTO fixture VALUES (?)", (name,)) - database.chmod(0o600) - os.chown(database, uid, uid) - accounts.append((name, uid, home, provider, workspace, database)) - results = [] - for index, (name, uid, home, provider, workspace, database) in enumerate(accounts): - other = accounts[1 - index] - payload = { - "account": name, - "uid": uid, - "own_provider": str(provider), - "own_workspace": str(workspace), - "forbidden": { - "other_provider_home": str(other[3]), - "other_workspace": str(other[4]), - "other_database": str(other[5]), - "controller_database": str(db), - "human_session": str(session), - }, - } - result = subprocess.run( - ["/usr/bin/setpriv", "--reuid", str(uid), "--regid", str(uid), - "--clear-groups", "--bounding-set=-all", "--no-new-privs", "--", - sys.executable, "-c", PROBE], - input=json.dumps(payload), text=True, capture_output=True, timeout=15, - cwd=home, - env={"HOME": str(home), "PATH": "/usr/bin:/bin", "LANG": "C.UTF-8", "ACCOUNT_ID": other[0]}, - ) - if result.returncode != 0: - raise RuntimeError(f"synthetic {name} isolation probe failed: {result.stderr}") - results.append(json.loads(result.stdout)) - print(json.dumps({"status": "passed", "scope": "synthetic Linux kernel boundary only", "accounts": results})) - return 0 - - -if __name__ == "__main__": - raise SystemExit(run()) diff --git a/apps/server/src/environment/ServerEnvironment.ts b/apps/server/src/environment/ServerEnvironment.ts index fd3d051f96636..599066dd7e8af 100644 --- a/apps/server/src/environment/ServerEnvironment.ts +++ b/apps/server/src/environment/ServerEnvironment.ts @@ -290,8 +290,7 @@ export const make = Effect.gen(function* () { ...(desktopAppUpdate ? { desktopAppUpdate: true, desktopAppChannelSwitch: true } : {}), serverBrowser: true, peerLinks: true, - threadInbox: false, - fleetPlacement: false, + threadInbox: true, mcpModeLimitHeader: true, linkFence: true, mcpApprovalCodes: true, diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.ts index e3cbb4aca9417..756be6358c5c7 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.ts @@ -2985,6 +2985,12 @@ const make = Effect.gen(function* () { yield* threadManagement .dispatch({ type: "thread.create", + inboxOrigin: { kind: "agent", id: parent.thread.id }, + ...(request.inboxRouting !== undefined + ? { inboxRouting: request.inboxRouting } + : parent.thread.inbox === undefined + ? {} + : { inboxRouting: parent.thread.inbox }), createdBy: "agent", creationSource: "mcp", commandId, diff --git a/apps/server/src/mcp/ThreadMetadataMcpService.ts b/apps/server/src/mcp/ThreadMetadataMcpService.ts index 44f0a610e585a..3fa5ea0102f9e 100644 --- a/apps/server/src/mcp/ThreadMetadataMcpService.ts +++ b/apps/server/src/mcp/ThreadMetadataMcpService.ts @@ -65,6 +65,13 @@ function metadataCommand(input: { readonly update: ThreadMetadataMcpUpdateInput; }): Extract { switch (input.update.action) { + case "route": + return { + type: "thread.metadata.update", + commandId: input.commandId, + threadId: input.threadId, + inboxRouting: input.update.inboxRouting!, + }; case "rename": return { type: "thread.metadata.update", @@ -88,10 +95,11 @@ function resultFromThread(input: { readonly sequence: number; readonly thread: Pick< OrchestrationV2AppThread, - "id" | "title" | "titleRegeneration" | "linkedPullRequest" | "updatedAt" + "id" | "title" | "titleRegeneration" | "linkedPullRequest" | "updatedAt" | "inbox" >; }): ThreadMetadataMcpUpdateResult { return { + ...(input.thread.inbox === undefined ? {} : { inbox: input.thread.inbox }), threadId: input.thread.id, action: input.action, commandId: input.commandId, diff --git a/apps/server/src/mcp/toolkits/orchestrator/tools.ts b/apps/server/src/mcp/toolkits/orchestrator/tools.ts index d85786c9f5c17..9243c6f16c2f4 100644 --- a/apps/server/src/mcp/toolkits/orchestrator/tools.ts +++ b/apps/server/src/mcp/toolkits/orchestrator/tools.ts @@ -260,7 +260,7 @@ const ThreadReadTool = Tool.make("t3_thread_read", { const ThreadUpdateTool = Tool.make("t3_thread_update", { description: - "Rename a thread (`action:'rename'` with `title`) or regenerate its title. Omit `threadId` for this thread. Workspace and branch cannot change here.", + "Route a thread with action:'route' and inboxRouting (owner, assignee, audience, attentionKind), or rename a thread (`action:'rename'` with `title`) or regenerate its title. Omit `threadId` for this thread. Workspace and branch cannot change here.", // Keeps the input's action/field check, which rebuilding the struct would drop. parameters: ThreadMetadataMcpUpdateInput.mapFields( Struct.assign({ environmentId: OrchestratorMcpEnvironmentTarget }), diff --git a/apps/server/src/mcp/toolkits/project/handlers.ts b/apps/server/src/mcp/toolkits/project/handlers.ts index 2ad7161cb630b..0693d2e88c4fe 100644 --- a/apps/server/src/mcp/toolkits/project/handlers.ts +++ b/apps/server/src/mcp/toolkits/project/handlers.ts @@ -255,6 +255,12 @@ export const layer = McpToolAccess.toLayer(ProjectToolkit, { }); } const result = yield* ThreadMessageIntake.launchThread({ + inboxOrigin: { kind: "agent", id: caller?.id ?? "agent" }, + ...(input.inboxRouting !== undefined + ? { inboxRouting: input.inboxRouting } + : caller?.inbox === undefined + ? {} + : { inboxRouting: caller.inbox }), commandId, threadId, projectId, diff --git a/apps/server/src/mcp/toolkits/project/tools.ts b/apps/server/src/mcp/toolkits/project/tools.ts index 56799959f6cd8..93aece44cba76 100644 --- a/apps/server/src/mcp/toolkits/project/tools.ts +++ b/apps/server/src/mcp/toolkits/project/tools.ts @@ -1,5 +1,6 @@ import { McpAttachmentInput } from "../attachment/input.ts"; import { + ThreadInboxRoutingPatch, NonNegativeInt, ModelSelection, TrimmedNonEmptyString, @@ -134,6 +135,7 @@ const ThreadLaunchTool = Tool.make("t3_thread_launch", { "No project: a new Scratch folder. Not with `projectId` or `workspaceStrategy`.", }), ), + inboxRouting: Schema.optional(ThreadInboxRoutingPatch), title: TrimmedNonEmptyString, modelSelection: Schema.optional(ModelSelection), runtimeMode: Schema.optional(RuntimeMode), diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index d1bf22a631e68..18067d57a63fa 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -5,6 +5,8 @@ import type { OrchestrationV2SearchThreadResult, OrchestrationV2ThreadHistoryPage, } from "@t3tools/contracts"; +import { makeThreadInbox, routeThreadInbox } from "@t3tools/contracts"; +import { ServerEnvironmentIdentity } from "../environment/ServerEnvironment.ts"; import { latestExecutedRun, latestRootProviderFailure, @@ -22,7 +24,6 @@ import { } from "../sourceControl/threadPullRequests.ts"; import { ORCHESTRATION_V2_WORKSPACE_PREPARATION_FAILURE_CODE, - FLEET_PLACEMENT_UNAVAILABLE, type ChatAttachment, CommandId, type GuestMessageId, @@ -3621,13 +3622,6 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio command: Extract, events: Ref.Ref>, ) { - if (command.fleetPlacement !== undefined) { - return yield* new OrchestratorDispatchError({ - commandId: command.commandId, - commandType: command.type, - cause: FLEET_PLACEMENT_UNAVAILABLE, - }); - } yield* Effect.annotateCurrentSpan({ "orchestration_v2.command_id": command.commandId, "orchestration_v2.command_type": command.type, @@ -3652,6 +3646,23 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio const now = yield* DateTime.now; const emitEvent = emit(events, command); const thread: OrchestrationV2AppThread = { + ...(command.inboxOrigin === undefined && + command.inboxRouting === undefined && + command.createdBy !== "agent" + ? {} + : { + inbox: makeThreadInbox({ + actor: + command.inboxOrigin ?? + (command.createdBy === "agent" ? { kind: "agent", id: "agent" } : null), + ...(command.inboxRouting === undefined ? {} : { routing: command.inboxRouting }), + executorEnvironmentId: yield* Effect.serviceOption(ServerEnvironmentIdentity).pipe( + Effect.flatMap((identity) => + Option.isSome(identity) ? identity.value.getEnvironmentId : Effect.succeed(null), + ), + ), + }), + }), createdBy: command.createdBy, creationSource: command.creationSource, id: command.threadId, @@ -4680,6 +4691,14 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio }; return { ...thread, + ...(command.inboxRouting === undefined + ? {} + : { + inbox: routeThreadInbox( + thread.inbox ?? makeThreadInbox({ actor: null }), + command.inboxRouting, + ), + }), ...(command.title === undefined ? {} : { title: command.title }), ...(command.limitRecovery === undefined ? {} : { limitRecovery }), ...(command.limitRecovery !== undefined && diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index e90a82786953f..7e68b50098bf8 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -1727,6 +1727,7 @@ export function threadShellFromProjection( }); return { createdBy: projection.thread.createdBy, + ...(projection.thread.inbox === undefined ? {} : { inbox: projection.thread.inbox }), creationSource: projection.thread.creationSource, id: projection.thread.id, projectId: projection.thread.projectId, @@ -2066,6 +2067,7 @@ function shellFromState(input: { ...(input.state.thread.historyOrigin === undefined ? {} : { historyOrigin: input.state.thread.historyOrigin }), + ...(input.state.thread.inbox === undefined ? {} : { inbox: input.state.thread.inbox }), ...(input.state.thread.linkOrigin === undefined ? {} : { linkOrigin: input.state.thread.linkOrigin }), diff --git a/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts b/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts index f02d6a8a7ff83..0fc06fe0eff06 100644 --- a/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts +++ b/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts @@ -15,7 +15,6 @@ import { ComposerContextId, type ChatAttachment, CommandId, - EnvironmentId, DEFAULT_SERVER_SETTINGS, GitCommandError, MessageId, @@ -23,7 +22,6 @@ import { ProviderDriverKind, ProviderInstanceId, OrchestrationV2ThreadProjectionJson, - OrchestrationV2ThreadLaunchInput, ScheduledTaskId, type ServerProvider, ThreadId, @@ -74,7 +72,6 @@ import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAda const projectId = ProjectId.make("project:launch-test"); const otherProjectId = ProjectId.make("project:launch-other"); const encodeThreadProjection = Schema.encodeEffect(OrchestrationV2ThreadProjectionJson); -const decodeThreadLaunchInput = Schema.decodeUnknownEffect(OrchestrationV2ThreadLaunchInput); const modelSelection = { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.1-codex", @@ -299,7 +296,6 @@ function makeHarness(options: HarnessOptions = {}) { layerTitleRegeneration, layerOutbox, layerDatabase, - layerReceipts, layerExternalServices, ), createWorktree, @@ -342,58 +338,6 @@ function launchInput(input: { }; } -it.effect("refuses unqualified fleet intent before native launch effects", () => { - const harness = makeHarness(); - return Effect.gen(function* () { - const launches = yield* ThreadLaunch.ThreadLaunchService; - const receipts = yield* CommandReceiptStore.CommandReceiptStoreV2; - const threads = yield* ThreadManagement.ThreadManagementService; - for (const mode of ["auto", "pinned"] as const) { - const input = launchInput({ - command: `fleet:${mode}`, - thread: `fleet-thread:${mode}`, - message: "must not launch", - workspace: { type: "worktree", baseRef: "main" }, - }); - const wire = yield* decodeThreadLaunchInput({ - ...input, - fleetPlacement: - mode === "auto" - ? { mode, clientRequestId: `fleet:${mode}` } - : { - mode, - clientRequestId: `fleet:${mode}`, - environmentId: EnvironmentId.make("remote"), - }, - }); - const result = yield* Effect.exit( - launches.launch({ ...wire, createdBy: "user", creationSource: "web" }), - ); - assert.isTrue(Exit.isFailure(result)); - assert.include(String(result), "qualified native placement adapter"); - assert.isTrue(Option.isNone(yield* receipts.getByCommandId(input.commandId))); - const command = { - ...input, - type: "thread.create" as const, - branch: null, - worktreePath: null, - ...(wire.fleetPlacement === undefined ? {} : { fleetPlacement: wire.fleetPlacement }), - }; - // Native callers bypassing launch still meet serialized admission. The - // native rejection receipt, including its identity, survives retries. - assert.isTrue(Exit.isFailure(yield* Effect.exit(threads.dispatch(command)))); - const receipt = yield* receipts.getByCommandId(input.commandId); - assert.isTrue(Option.isSome(receipt)); - if (Option.isSome(receipt)) assert.equal(receipt.value.status, "rejected"); - assert.isTrue(Exit.isFailure(yield* Effect.exit(threads.dispatch(command)))); - assert.deepEqual(yield* receipts.getByCommandId(input.commandId), receipt); - } - assert.deepEqual(yield* threads.listProjectThreads({ projectId, includeSubagents: false }), []); - assert.equal(harness.createWorktree.mock.calls.length, 0); - assert.equal(harness.runSetup.mock.calls.length, 0); - }).pipe(Effect.provide(harness.layer)); -}); - it.effect.each( (["new", "existing"] as const).flatMap((target) => (["user", "agent"] as const).map((createdBy) => ({ target, createdBy })), @@ -1267,13 +1211,7 @@ it.effect.each(["stable", "upstream/release"])( const worktreePath = `${directory}/worktree`; yield* fs.makeDirectory(cwd); const command = (at: string, args: string[]) => - git - .execute({ operation: "launch-test", cwd: at, args, allowNonZeroExit: true }) - .pipe( - Effect.tap((result) => - Effect.sync(() => assert.equal(result.exitCode, 0, result.stderr)), - ), - ); + git.execute({ operation: "launch-test", cwd: at, args }); yield* command(cwd, ["init", "-b", "stable"]); yield* command(cwd, ["config", "user.name", "Test"]); yield* command(cwd, ["config", "user.email", "test@example.test"]); @@ -2965,3 +2903,35 @@ it.effect("replays an accepted send after the project disables the instance", () } }).pipe(Effect.provide(Layer.mergeAll(harness.layer, layerFiles))); }); + +it.effect( + "persists founder routing in projections and shells and retains it on launch replay", + () => { + const harness = makeHarness(); + return Effect.gen(function* () { + const launches = yield* ThreadLaunch.ThreadLaunchService; + const threads = yield* ThreadManagement.ThreadManagementService; + const input = { + ...launchInput({ command: "inbox-launch", thread: "inbox-thread" }), + inboxOrigin: { kind: "human" as const, id: "jeff" as const }, + }; + const launched = yield* launches.launch(input); + const original = (yield* threads.getThreadProjection(launched.threadId)).thread.inbox; + assert.equal(original?.owner, "jeff"); + assert.deepEqual((yield* threads.getThreadShell(launched.threadId))?.inbox, original); + yield* threads.dispatch({ + type: "thread.metadata.update", + commandId: CommandId.make("route-inbox"), + threadId: launched.threadId, + inboxRouting: { assignee: { kind: "human", id: "kameron" }, attentionKind: "FYI" }, + }); + yield* launches.launch(input); + const routed = (yield* threads.getThreadProjection(launched.threadId)).thread.inbox; + assert.equal(routed?.owner, "kameron"); + assert.equal(routed?.attentionKind, "FYI"); + assert.deepEqual(routed?.origin, original?.origin); + assert.deepEqual(routed?.requestedBy, original?.requestedBy); + assert.deepEqual((yield* threads.getThreadShell(launched.threadId))?.inbox, routed); + }).pipe(Effect.provide(harness.layer)); + }, +); diff --git a/apps/server/src/orchestration-v2/ThreadLaunchService.ts b/apps/server/src/orchestration-v2/ThreadLaunchService.ts index 54d1c2f575af4..fa67e49bb450e 100644 --- a/apps/server/src/orchestration-v2/ThreadLaunchService.ts +++ b/apps/server/src/orchestration-v2/ThreadLaunchService.ts @@ -4,8 +4,8 @@ import * as TerminalManager from "../terminal/Manager.ts"; import { resolveProjectSettings } from "@t3tools/shared/projectSettings"; import { CommandId, - FLEET_PLACEMENT_UNAVAILABLE, - type FleetPlacementIntent, + type InboxActor, + type ThreadInboxRoutingPatch, type ChatAttachment, type MessageId, type ModelSelection, @@ -85,7 +85,8 @@ export interface ThreadLaunchInitialMessage { export interface ThreadLaunchInput { readonly commandId: CommandId; - readonly fleetPlacement?: FleetPlacementIntent; + readonly inboxOrigin?: InboxActor; + readonly inboxRouting?: ThreadInboxRoutingPatch; readonly threadId?: ThreadId; readonly reuseExistingThread?: boolean; readonly projectId: ProjectId; @@ -159,20 +160,6 @@ export class ThreadLaunchError extends Schema.TaggedError()( } } -/** Reuse before attachment claims, workspace preflight and direct native launch. */ -export const requireQualifiedFleetPlacement = Effect.fn("requireQualifiedFleetPlacement")( - function* (request: Pick) { - if (request.fleetPlacement !== undefined) { - return yield* new ThreadLaunchError({ - operation: "resolve-project", - commandId: request.commandId, - projectId: request.projectId, - cause: FLEET_PLACEMENT_UNAVAILABLE, - }); - } - }, -); - export class ThreadLaunchBaseRefError extends Schema.TaggedError()( "ThreadLaunchBaseRefError", { @@ -1043,9 +1030,6 @@ const make = Effect.gen(function* () { const launch: ThreadLaunchService["Service"]["launch"] = Effect.fn("ThreadLaunchService.launch")( function* (request) { - // Protocol 2 alone does not qualify remote admission. Keep intent explicit - // until the native destination adapter persists and reconciles acceptance. - yield* requireQualifiedFleetPlacement(request); // Scratch has no Git repository. Normalize before folder allocation so // durable preparation and retries use the thread's own Scratch folder. const input: ThreadLaunchInput = @@ -1162,6 +1146,8 @@ const make = Effect.gen(function* () { : { delegatedFrom: input.delegatedFrom }), createdBy: input.createdBy, creationSource: input.creationSource, + ...(input.inboxOrigin === undefined ? {} : { inboxOrigin: input.inboxOrigin }), + ...(input.inboxRouting === undefined ? {} : { inboxRouting: input.inboxRouting }), }); const claimed = yield* claimDispatch.pipe( Effect.mapError( diff --git a/apps/server/src/orchestration-v2/ThreadMessageIntake.ts b/apps/server/src/orchestration-v2/ThreadMessageIntake.ts index f15edaadfddb1..c6a6cdbf7ac1e 100644 --- a/apps/server/src/orchestration-v2/ThreadMessageIntake.ts +++ b/apps/server/src/orchestration-v2/ThreadMessageIntake.ts @@ -212,7 +212,6 @@ export const sendToThread = Effect.fn("ThreadMessageIntake.sendToThread")(functi export const launchThread = Effect.fn("ThreadMessageIntake.launchThread")(function* ( input: ThreadLaunch.ThreadLaunchInput, ) { - yield* ThreadLaunch.requireQualifiedFleetPlacement(input); const launches = yield* ThreadLaunch.ThreadLaunchService; yield* AttachmentClaims.validateAttachmentLimits(input.initialMessage?.attachments ?? []); if (!input.initialMessage?.attachments.some(AttachmentClaims.attachmentIsPendingUpload)) { diff --git a/apps/server/src/persistence/Protocol2DatabaseAdmission.test.ts b/apps/server/src/persistence/Protocol2DatabaseAdmission.test.ts deleted file mode 100644 index 2a21be9f5000e..0000000000000 --- a/apps/server/src/persistence/Protocol2DatabaseAdmission.test.ts +++ /dev/null @@ -1,82 +0,0 @@ -// @effect-diagnostics nodeBuiltinImport:off - synthetic SQLite fixtures only. -import * as NodeFS from "node:fs"; -import * as NodeSqlite from "node:sqlite"; -import * as NodeServices from "@effect/platform-node/NodeServices"; -import { assert, it } from "@effect/vitest"; -import * as Effect from "effect/Effect"; -import * as Exit from "effect/Exit"; -import * as FileSystem from "effect/FileSystem"; -import * as Layer from "effect/Layer"; -import * as Path from "effect/Path"; -import { migrationManifest } from "./Migrations.ts"; -import { admitProtocol2Database } from "./Protocol2DatabaseAdmission.ts"; -import * as SqlitePersistence from "./Sqlite.ts"; -import * as ServerConfig from "../config.ts"; - -function seed(path: string, rows: ReadonlyArray) { - const db = new NodeSqlite.DatabaseSync(path); - try { - db.exec("CREATE TABLE effect_sql_migrations (migration_id INTEGER PRIMARY KEY, name TEXT)"); - const insert = db.prepare("INSERT INTO effect_sql_migrations VALUES (?, ?)"); - for (const [id, name] of rows) insert.run(id, name); - } finally { - db.close(); - } -} - -it.effect.each(["newer", "collision"] as const)( - "refuses a %s schema before the native writer changes the file", - (kind) => - Effect.gen(function* () { - const fs = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const directory = yield* fs.makeTempDirectoryScoped({ prefix: "clo866-v2-schema-" }); - const file = path.join(directory, "statev2.sqlite"); - seed(file, kind === "newer" ? [[900, "FutureSchema"]] : [[57, "ThreadInbox"]]); - const before = NodeFS.readFileSync(file); - const result = yield* Effect.exit( - Layer.build(SqlitePersistence.layerFromPath(file)).pipe(Effect.scoped), - ); - assert.isTrue(Exit.isFailure(result)); - assert.include(String(result), "Protocol2DatabaseCompatibilityError"); - assert.deepEqual(NodeFS.readFileSync(file), before); - assert.isFalse(NodeFS.existsSync(`${file}-wal`)); - assert.isFalse(NodeFS.existsSync(`${file}-shm`)); - }).pipe(Effect.provide(NodeServices.layer)), -); - -it.effect("accepts matching schema read-only and refuses implicit upgrades and imports", () => - Effect.gen(function* () { - const fs = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const directory = yield* fs.makeTempDirectoryScoped({ prefix: "clo866-v2-exact-" }); - const current = path.join(directory, "current.sqlite"); - seed(current, migrationManifest); - const before = NodeFS.readFileSync(current); - yield* admitProtocol2Database(current, true); - assert.deepEqual(NodeFS.readFileSync(current), before); - const partial = path.join(directory, "partial.sqlite"); - seed(partial, migrationManifest.slice(0, 54)); - assert.isTrue(Exit.isFailure(yield* Effect.exit(admitProtocol2Database(partial, true)))); - const fresh = path.join(directory, "statev2.sqlite"); - yield* admitProtocol2Database(fresh, true); - assert.isFalse(NodeFS.existsSync(fresh)); - const legacy = path.join(directory, "state.sqlite"); - seed(legacy, [[1, "OrchestrationEvents"]]); - const legacyBefore = NodeFS.readFileSync(legacy); - const config = yield* ServerConfig.ServerConfig.pipe( - Effect.provide(ServerConfig.layerTest(directory, directory)), - ); - const refused = yield* Effect.exit( - Layer.build( - SqlitePersistence.layerConfig.pipe( - Layer.provide(ServerConfig.layer({ ...config, dbPath: fresh })), - ), - ).pipe(Effect.scoped), - ); - assert.isTrue(Exit.isFailure(refused)); - assert.include(String(refused), "separately approved import"); - assert.isFalse(NodeFS.existsSync(fresh)); - assert.deepEqual(NodeFS.readFileSync(legacy), legacyBefore); - }).pipe(Effect.provide(NodeServices.layer)), -); diff --git a/apps/server/src/persistence/Protocol2DatabaseAdmission.ts b/apps/server/src/persistence/Protocol2DatabaseAdmission.ts deleted file mode 100644 index 7defaa29130c7..0000000000000 --- a/apps/server/src/persistence/Protocol2DatabaseAdmission.ts +++ /dev/null @@ -1,48 +0,0 @@ -// @effect-diagnostics nodeBuiltinImport:off - startup preflight must precede opening a writer. -import * as NodeFS from "node:fs"; -import * as NodePath from "node:path"; -import * as Effect from "effect/Effect"; -import * as Schema from "effect/Schema"; -import { migrationManifest } from "./Migrations.ts"; -import { recordedMigrations } from "./databaseMigrationHead.ts"; - -export class Protocol2DatabaseCompatibilityError extends Schema.TaggedError()( - "Protocol2DatabaseCompatibilityError", - { databasePath: Schema.String, detail: Schema.String }, -) { - override get message() { - return `Refusing this protocol-2 candidate at ${this.databasePath}: ${this.detail}. No database migration or import was attempted. Use the qualified build for this database.`; - } -} - -/** This port is qualified for an existing matching V2 schema or fresh synthetic - * state. It must not invoke upstream's V1 copy/import path or upgrade a host as - * a side effect of evaluating founder ACLs. Never infer compatibility from a - * package version alone; compare every recorded migration's identity. - */ -export const admitProtocol2Database = Effect.fn("admitProtocol2Database")(function* ( - databasePath: string, - requireCurrentSchema = false, -) { - const refuse = (detail: string) => - new Protocol2DatabaseCompatibilityError({ databasePath, detail }); - if (!NodeFS.existsSync(databasePath)) { - if ( - requireCurrentSchema && - NodeFS.existsSync(NodePath.join(NodePath.dirname(databasePath), "state.sqlite")) - ) - return yield* refuse("legacy state requires a separately approved import"); - return; - } - const recorded = recordedMigrations(databasePath); - if (recorded === null) return yield* refuse("migration history cannot be read"); - const expected = new Map(migrationManifest); - const seen = new Set(); - for (const row of recorded) { - if (seen.has(row.id) || expected.get(row.id) !== row.name) - return yield* refuse(`unrecognized migration ${row.id}:${row.name}`); - seen.add(row.id); - } - if (requireCurrentSchema && recorded.length !== migrationManifest.length) - return yield* refuse("schema does not exactly match this candidate"); -}); diff --git a/apps/server/src/persistence/Sqlite.ts b/apps/server/src/persistence/Sqlite.ts index 3adf81b957348..d9506e31154fe 100644 --- a/apps/server/src/persistence/Sqlite.ts +++ b/apps/server/src/persistence/Sqlite.ts @@ -9,24 +9,12 @@ import * as SqlError from "effect/sql/SqlError"; import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient"; import { hasPendingMigrations, runMigrations } from "./Migrations.ts"; +import { initializeV2Database } from "./initializeV2Database.ts"; import * as ServerConfig from "../config.ts"; import * as ServerOwnership from "../serverOwnership.ts"; -import { admitProtocol2Database } from "./Protocol2DatabaseAdmission.ts"; const WAL_SIZE_LIMIT_BYTES = 128 * 1024 * 1024; -// Keep the persistence layer's existing SqlError channel for callers while the -// refusal's typed cause retains the exact compatibility diagnosis. -const admitCandidateDatabase = (dbPath: string, requireCurrentSchema = false) => - admitProtocol2Database(dbPath, requireCurrentSchema).pipe( - Effect.mapError( - (cause) => - new SqlError.SqlError({ - reason: new SqlError.UnknownError({ cause, operation: "open", message: cause.message }), - }), - ), - ); - export class ServerOwnsDatabaseError extends Schema.TaggedError()( "ServerOwnsDatabaseError", { stateDir: Schema.String }, @@ -114,7 +102,6 @@ const layerSetup = makeLayerSetup(runMigrations()); const makeLayerFromPath = (makeSetup: (dbPath: string) => Layer.Layer) => Effect.fn("makeSqlitePersistenceLive")(function* (dbPath: string) { - yield* admitCandidateDatabase(dbPath); const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; yield* fs.makeDirectory(path.dirname(dbPath), { recursive: true }); @@ -158,9 +145,7 @@ const makeLayerConfig = ( Layer.unwrap( Effect.gen(function* () { const { dbPath } = yield* ServerConfig.ServerConfig; - yield* admitCandidateDatabase(dbPath, true); - // Candidate startup never imports V1 data or runs upstream's abandoned - // import cleanup. Matching V2 state and fresh fixtures need neither. + yield* initializeV2Database(dbPath); return fromPath(dbPath); }), ); diff --git a/apps/server/src/persistence/initializeV2Database.test.ts b/apps/server/src/persistence/initializeV2Database.test.ts index 035b8c08c9614..f8c68f49ceb9a 100644 --- a/apps/server/src/persistence/initializeV2Database.test.ts +++ b/apps/server/src/persistence/initializeV2Database.test.ts @@ -24,7 +24,7 @@ import * as EventSink from "../orchestration-v2/EventSink.ts"; import * as LegacyV1ThreadImporter from "../orchestration-v2/legacy/LegacyV1ThreadImporter.ts"; it.effect( - "explicit import utility preserves synthetic V1 and V2 transcripts across switches", + "snapshots V1, imports transcripts lazily, and preserves both databases across switches", () => { const directory = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-v1-v2-")); const sourcePath = NodePath.join(directory, "state.sqlite"); @@ -46,10 +46,10 @@ it.effect( return Effect.gen(function* () { yield* seed; const original = NodeFS.readFileSync(sourcePath); - // Exercise the upstream utility explicitly with synthetic state; this - // candidate's configured startup refuses implicit imports. - yield* initializeV2Database(destinationPath); - const layerDatabase = SqlitePersistence.layerFromPath(destinationPath); + const config = yield* ServerConfig.ServerConfig; + const layerDatabase = SqlitePersistence.layerConfig.pipe( + Layer.provide(ServerConfig.layer({ ...config, dbPath: destinationPath })), + ); const layerStores = Layer.mergeAll(EventStore.layer, ProjectionStore.layer).pipe( Layer.provideMerge(layerDatabase), ); diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index 64fc30ec04d65..32bf641af2d21 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -2140,53 +2140,55 @@ export const layerWsRpc = ( Effect.andThen( startup .enqueueCommand( - ThreadLaunchService.requireQualifiedFleetPlacement(input).pipe( - Effect.andThen( - threadLaunch.checkWorktreeBase({ - commandId: input.commandId, - projectId: input.projectId, - workspaceStrategy: input.workspaceStrategy, - }), - ), - Effect.andThen( - ThreadMessageIntake.launchThread({ - commandId: input.commandId, - ...(input.fleetPlacement === undefined - ? {} - : { fleetPlacement: input.fleetPlacement }), - ...(input.threadId === undefined ? {} : { threadId: input.threadId }), - ...(input.reuseExistingThread === undefined - ? {} - : { reuseExistingThread: input.reuseExistingThread }), - projectId: input.projectId, - title: input.title, - ...(input.generateTitle === undefined - ? {} - : { generateTitle: input.generateTitle }), - modelSelection: input.modelSelection, - runtimeMode: input.runtimeMode, - interactionMode: input.interactionMode, - workspaceStrategy: input.workspaceStrategy, - ...(input.initialMessage === undefined - ? {} - : { - initialMessage: { - ...(input.initialMessage.messageId === undefined - ? {} - : { messageId: input.initialMessage.messageId }), - text: input.initialMessage.text, - attachments: input.initialMessage.attachments, - ...(input.initialMessage.context === undefined - ? {} - : { context: input.initialMessage.context }), - }, - }), - createdBy: "user", - creationSource: input.creationSource ?? "web", - }), + threadLaunch + .checkWorktreeBase({ + commandId: input.commandId, + projectId: input.projectId, + workspaceStrategy: input.workspaceStrategy, + }) + .pipe( + Effect.andThen( + ThreadMessageIntake.launchThread({ + commandId: input.commandId, + ...(input.inboxOrigin === undefined + ? {} + : { inboxOrigin: input.inboxOrigin }), + ...(input.inboxRouting === undefined + ? {} + : { inboxRouting: input.inboxRouting }), + ...(input.threadId === undefined ? {} : { threadId: input.threadId }), + ...(input.reuseExistingThread === undefined + ? {} + : { reuseExistingThread: input.reuseExistingThread }), + projectId: input.projectId, + title: input.title, + ...(input.generateTitle === undefined + ? {} + : { generateTitle: input.generateTitle }), + modelSelection: input.modelSelection, + runtimeMode: input.runtimeMode, + interactionMode: input.interactionMode, + workspaceStrategy: input.workspaceStrategy, + ...(input.initialMessage === undefined + ? {} + : { + initialMessage: { + ...(input.initialMessage.messageId === undefined + ? {} + : { messageId: input.initialMessage.messageId }), + text: input.initialMessage.text, + attachments: input.initialMessage.attachments, + ...(input.initialMessage.context === undefined + ? {} + : { context: input.initialMessage.context }), + }, + }), + createdBy: "user", + creationSource: input.creationSource ?? "web", + }), + ), + Effect.provide(intakeContext), ), - Effect.provide(intakeContext), - ), ) .pipe( // A resumed launch is a retry of one already counted. diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index a94b9e9497c6b..203ec4701af97 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -1,3 +1,6 @@ +import { matchesInboxView } from "@t3tools/contracts"; +import { SidebarInboxBar } from "./sidebar/SidebarInboxBar"; +import { threadRoutingUpdateFromMenuAction } from "./threadActionMenu.logic"; import { attachSidebarTree } from "../lib/sidebarTree"; import { type EnvironmentId, type ScopedProjectRef } from "@t3tools/contracts"; import type { EnvironmentServerConfig } from "@t3tools/client-runtime/connection"; @@ -1118,10 +1121,17 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve ); const threads = useQuietThreadShells(); const promotingDraftThreadKeys = usePromotingDraftThreadKeys(); + const inboxView = useClientSettings((settings) => settings.founderInboxView); + const inboxThreads = threads.filter( + (thread) => + threadSearchQuery.trim().length > 0 || + matchesInboxView(thread.inbox, inboxView) || + (inboxView === "agents" && thread.createdBy === "agent"), + ); const listedThreads = promotingDraftThreadKeys.length === 0 - ? threads - : threads.map((thread) => + ? inboxThreads + : inboxThreads.map((thread) => promotingDraftThreadKeys.includes(threadShellKey(thread)) ? asLaunchingThread(thread) : thread, @@ -2671,6 +2681,9 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve ), canTurnIntoProject: canTurnThreadIntoProject(threadRef), supports: { + inboxRouting: + serverConfigs.get(thread.environmentId)?.environment.capabilities.threadInbox === + true, settlement: configLoaded, autoSettleOptOut: supportsAutoSettleOptOut, snooze: configLoaded, @@ -2684,6 +2697,14 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve ); if (clicked._tag === "Failure" || clicked.value === null) return; if (threadActionRequiresOperate(clicked.value) && !checkThreadOperations([thread])) return; + const inboxRouting = threadRoutingUpdateFromMenuAction(clicked.value); + if (inboxRouting) { + await updateThreadMetadata({ + environmentId: thread.environmentId, + input: { threadId: thread.id, inboxRouting }, + }); + return; + } if (clicked.value?.startsWith("snooze:")) { const preset = clicked.value === "snooze:custom" @@ -3208,6 +3229,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve activeSearchResultIndex={activeSearchResultIndex} onClearSearch={clearThreadSearch} /> + } > diff --git a/apps/web/src/components/sidebar/SidebarInboxBar.tsx b/apps/web/src/components/sidebar/SidebarInboxBar.tsx new file mode 100644 index 0000000000000..8307abc3069d1 --- /dev/null +++ b/apps/web/src/components/sidebar/SidebarInboxBar.tsx @@ -0,0 +1,49 @@ +import type { InboxView } from "@t3tools/contracts"; +import { updateClientSettings, useClientSettings } from "../../hooks/useSettings"; + +/** A local view of the shared pool; All and search always include every thread. */ +export function SidebarInboxBar() { + const view = useClientSettings((settings) => settings.founderInboxView); + const owner = useClientSettings((settings) => settings.founderInboxOwner); + return ( +
+ + +
+ ); +} diff --git a/apps/web/src/components/threadActionMenu.logic.ts b/apps/web/src/components/threadActionMenu.logic.ts index 1e3eddd0b9389..4882857251d44 100644 --- a/apps/web/src/components/threadActionMenu.logic.ts +++ b/apps/web/src/components/threadActionMenu.logic.ts @@ -1,7 +1,12 @@ +import type { ThreadInboxRoutingPatch } from "@t3tools/contracts"; import type { ContextMenuItem } from "@t3tools/contracts"; import type { SnoozePreset } from "@t3tools/client-runtime/state/thread-settled"; export type ThreadActionMenuId = + | "inbox" + | `inbox:${"kameron" | "jeff" | "shared" | "agents"}` + | "attention" + | `attention:${"action" | "FYI" | "background"}` | "find" | "new-thread-on-branch" | "filter-by-project" @@ -84,6 +89,7 @@ export interface ThreadActionMenuState { /** Archive rejects attached providers, so disable it while running. */ readonly isRunning: boolean; readonly supports: { + readonly inboxRouting?: boolean; readonly settlement: boolean; readonly autoSettleOptOut: boolean; readonly snooze: boolean; @@ -117,6 +123,29 @@ export function buildThreadActionMenuItems( state: ThreadActionMenuState, ): ReadonlyArray> { const items: ReadonlyArray> = [ + ...(state.supports.inboxRouting + ? [ + { + id: "inbox" as const, + label: "Route to inbox", + children: [ + { id: "inbox:kameron" as const, label: "Kameron" }, + { id: "inbox:jeff" as const, label: "Jeff" }, + { id: "inbox:shared" as const, label: "Shared" }, + { id: "inbox:agents" as const, label: "Agents / neither founder" }, + ], + }, + { + id: "attention" as const, + label: "Attention", + children: [ + { id: "attention:action" as const, label: "Needs action" }, + { id: "attention:FYI" as const, label: "FYI" }, + { id: "attention:background" as const, label: "Background" }, + ], + }, + ] + : []), ...(state.canFind ? [{ id: "find" as const, label: "Find in thread", icon: "text-search" }] : []), @@ -267,3 +296,23 @@ export function buildThreadActionMenuItems( : item, ); } + +export function threadRoutingUpdateFromMenuAction(action: string): ThreadInboxRoutingPatch | null { + if (action === "inbox:kameron" || action === "inbox:jeff") { + const founder = action === "inbox:kameron" ? "kameron" : "jeff"; + return { + owner: founder, + assignee: { kind: "human", id: founder }, + audience: founder, + attentionKind: "action", + }; + } + if (action === "inbox:shared") + return { owner: null, assignee: null, audience: "shared", attentionKind: "FYI" }; + if (action === "inbox:agents") + return { owner: null, assignee: null, audience: "agent-only", attentionKind: "background" }; + if (action === "attention:action") return { attentionKind: "action" }; + if (action === "attention:FYI") return { attentionKind: "FYI" }; + if (action === "attention:background") return { attentionKind: "background" }; + return null; +} diff --git a/apps/web/src/state/threads.ts b/apps/web/src/state/threads.ts index 6d2ce2a07c90b..bfa59ed5af3f9 100644 --- a/apps/web/src/state/threads.ts +++ b/apps/web/src/state/threads.ts @@ -20,6 +20,7 @@ import { environmentCatalog } from "../connection/catalog"; import { connectionAtomRuntime } from "../connection/runtime"; import { serverEnvironment } from "./server"; import { environmentShell } from "./shell"; +import { getClientSettings } from "../hooks/useSettings"; export const threadFamilies = createThreadFamilyAtoms( connectionAtomRuntime, @@ -32,6 +33,7 @@ export const olderSettledThreads = createOlderSettledThreadAtoms( export const threadEnvironment = createThreadEnvironmentAtoms( connectionAtomRuntime, threadFamilies.snapshotAtom, + { getInboxOrigin: () => ({ kind: "human", id: getClientSettings().founderInboxOwner }) }, ); const environmentThreads = createEnvironmentThreadStateAtoms(connectionAtomRuntime); export const environmentThreadDetails = createEnvironmentThreadDetailAtoms( diff --git a/packages/client-runtime/src/load-balancing.ts b/packages/client-runtime/src/load-balancing.ts index 84c9c8bd0cb60..0b938c6c090e4 100644 --- a/packages/client-runtime/src/load-balancing.ts +++ b/packages/client-runtime/src/load-balancing.ts @@ -1 +1,40 @@ -export { chooseLoadBalancedEnvironment } from "@t3tools/shared/loadBalancing"; +import type { HostResourcesSnapshot } from "@t3tools/contracts"; + +/** Callers supply only connected machines hosting the project and selected provider. */ +export function chooseLoadBalancedEnvironment( + candidates: ReadonlyArray<{ + environmentId: string; + resources: HostResourcesSnapshot | null; + /** Client receipt time avoids comparing clocks on different machines. */ + receivedAt?: number; + weight: number; + }>, + now: number, +): string | null { + let selected: string | null = null; + let bestScore = 0; + for (const { environmentId, resources, receivedAt, weight } of candidates) { + const sampledAt = receivedAt ?? resources?.sampledAt ?? 0; + if ( + !resources || + !Number.isFinite(weight) || + weight <= 0 || + now - sampledAt > 15_000 || + sampledAt > now + 5_000 || + resources.cpuUtilization === null || + resources.cpuUtilization >= 0.95 || + resources.totalMemoryBytes <= 0 || + resources.cpuCount <= 0 + ) { + continue; + } + const memoryAvailable = resources.availableMemoryBytes / resources.totalMemoryBytes; + if (memoryAvailable <= 0.05) continue; + const score = weight * resources.cpuCount * (1 - resources.cpuUtilization) * memoryAvailable; + if (score > bestScore) { + selected = environmentId; + bestScore = score; + } + } + return selected; +} diff --git a/packages/client-runtime/src/operations/commands.ts b/packages/client-runtime/src/operations/commands.ts index c6f5c8c34166e..bb976e3656f69 100644 --- a/packages/client-runtime/src/operations/commands.ts +++ b/packages/client-runtime/src/operations/commands.ts @@ -1,6 +1,8 @@ import { remapComposerContextAttachments } from "@t3tools/shared/composerContextReferences"; import { type ThreadLinkedPullRequest, + type InboxActor, + type ThreadInboxRoutingPatch, CommandId, CheckpointId, CheckpointScopeId, @@ -47,6 +49,8 @@ import { } from "../rpc/client.ts"; interface CommandMetadata { + readonly inboxOrigin?: InboxActor; + readonly inboxRouting?: ThreadInboxRoutingPatch; readonly commandId?: CommandId; readonly createdAt?: string; readonly creationSource?: OrchestrationV2CreationSource; @@ -470,6 +474,8 @@ export const createThread = Effect.fn("EnvironmentCommands.createThread")(functi return yield* dispatch({ type: "thread.create", commandId: yield* allocateCommandId(input), + ...(input.inboxOrigin === undefined ? {} : { inboxOrigin: input.inboxOrigin }), + ...(input.inboxRouting === undefined ? {} : { inboxRouting: input.inboxRouting }), createdBy: "user", creationSource: input.creationSource ?? "web", threadId: input.threadId, @@ -687,10 +693,12 @@ export const updateThreadMetadata = Effect.fn("EnvironmentCommands.updateThreadM input.worktreePath !== undefined || input.regenerateTitle !== undefined || input.linkedPullRequest !== undefined || - input.limitRecovery !== undefined + input.limitRecovery !== undefined || + input.inboxRouting !== undefined ) { result = yield* dispatch({ type: "thread.metadata.update", + ...(input.inboxRouting === undefined ? {} : { inboxRouting: input.inboxRouting }), ...(input.limitRecovery === undefined ? {} : { limitRecovery: input.limitRecovery }), commandId, threadId: input.threadId, @@ -782,6 +790,8 @@ export const startThreadTurn = Effect.fn("EnvironmentCommands.startThreadTurn")( }; return yield* request(ORCHESTRATION_V2_WS_METHODS.launchThread, { commandId, + ...(input.inboxOrigin === undefined ? {} : { inboxOrigin: input.inboxOrigin }), + ...(input.inboxRouting === undefined ? {} : { inboxRouting: input.inboxRouting }), creationSource: input.creationSource ?? "web", threadId: input.threadId, ...(bootstrap === undefined ? { reuseExistingThread: true } : {}), diff --git a/packages/client-runtime/src/state/threadCommands.ts b/packages/client-runtime/src/state/threadCommands.ts index 865f6273b20ad..7a772beafd803 100644 --- a/packages/client-runtime/src/state/threadCommands.ts +++ b/packages/client-runtime/src/state/threadCommands.ts @@ -1,4 +1,4 @@ -import { CommandId, type ModelSelection, type ThreadId } from "@t3tools/contracts"; +import { CommandId, type ModelSelection, type ThreadId, type InboxActor } from "@t3tools/contracts"; import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Effect from "effect/Effect"; import * as Option from "effect/Option"; @@ -24,6 +24,8 @@ import { waitForTitleRegenerationOutcome } from "./threadTitleRegeneration.ts"; import { type InterruptThreadTurnInput, type UpdateThreadMetadataInput, + type CreateThreadInput, + type StartThreadTurnInput, archiveThread, closeGuestShare, resolveGuestMessage, @@ -77,7 +79,12 @@ export type LoadEarlierThreadHistoryInput = { export function createThreadEnvironmentAtoms( runtime: Atom.AtomRuntime, snapshotAtom: (environmentId: EnvironmentId) => Atom.Atom, + options: { readonly getInboxOrigin?: () => InboxActor | undefined } = {}, ) { + const withInboxOrigin = (input: I) => { + const origin = input.inboxOrigin ?? options.getInboxOrigin?.(); + return origin === undefined ? input : { ...input, inboxOrigin: origin }; + }; const scheduler = createAtomCommandScheduler(); const concurrency = { mode: "serial" as const, @@ -162,7 +169,7 @@ export function createThreadEnvironmentAtoms( create: createEnvironmentCommand(runtime, { label: "environment-data:commands:thread:create", - execute: createThread, + execute: (input: CreateThreadInput) => createThread(withInboxOrigin(input)), scheduler, concurrency, }), @@ -307,7 +314,7 @@ export function createThreadEnvironmentAtoms( }), startTurn: createEnvironmentCommand(runtime, { label: "environment-data:commands:thread:start-turn", - execute: startThreadTurn, + execute: (input: StartThreadTurnInput) => startThreadTurn(withInboxOrigin(input)), scheduler, concurrency, }), diff --git a/packages/contracts/src/environment.ts b/packages/contracts/src/environment.ts index dd042fc73f2b5..5996294054e07 100644 --- a/packages/contracts/src/environment.ts +++ b/packages/contracts/src/environment.ts @@ -175,7 +175,6 @@ export const ExecutionEnvironmentCapabilities = Schema.Struct({ offer linking for. */ peerLinks: Schema.optionalKey(Schema.Boolean), threadInbox: Schema.optionalKey(Schema.Boolean), - fleetPlacement: Schema.optionalKey(Schema.Boolean), /** Server's `/mcp` narrows an OAuth client's modes from `T3-Mode-Limit`, so a linked environment's calls keep its agent's limits. Another environment links to this one only when it is set. */ diff --git a/packages/contracts/src/fleetPlacement.ts b/packages/contracts/src/fleetPlacement.ts deleted file mode 100644 index 83c055bcfe6a1..0000000000000 --- a/packages/contracts/src/fleetPlacement.ts +++ /dev/null @@ -1,17 +0,0 @@ -import * as Schema from "effect/Schema"; -import { EnvironmentId, TrimmedNonEmptyString } from "./baseSchemas.ts"; - -/** Capability-gated launch intent, not a caller-authored admission decision. */ -export const FleetPlacementIntent = Schema.Union([ - Schema.Struct({ mode: Schema.Literal("auto"), clientRequestId: TrimmedNonEmptyString }), - Schema.Struct({ - mode: Schema.Literal("pinned"), - clientRequestId: TrimmedNonEmptyString, - environmentId: EnvironmentId, - }), -]); -export type FleetPlacementIntent = typeof FleetPlacementIntent.Type; - -export const FLEET_PLACEMENT_MIN_PROTOCOL = 2; -export const FLEET_PLACEMENT_UNAVAILABLE = - "Fleet placement requires protocol 2 and a qualified native placement adapter; this server cannot accept the request. No local fallback is allowed."; diff --git a/packages/contracts/src/index.ts b/packages/contracts/src/index.ts index 9d427200b6d48..7087bc252e443 100644 --- a/packages/contracts/src/index.ts +++ b/packages/contracts/src/index.ts @@ -75,4 +75,3 @@ export * from "./settingsSecretValue.ts"; export * from "./clientRpcPermissions.ts"; export * from "./threadInbox.ts"; -export * from "./fleetPlacement.ts"; diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts index d590ec9e43bf6..e550233a74305 100644 --- a/packages/contracts/src/orchestrationV2.ts +++ b/packages/contracts/src/orchestrationV2.ts @@ -3,7 +3,7 @@ import { withRecordIdTable } from "./orchestrationV2IdTable.ts"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as Schema from "effect/Schema"; -import { FleetPlacementIntent } from "./fleetPlacement.ts"; +import { ThreadInbox, ThreadInboxRoutingPatch, InboxActor } from "./threadInbox.ts"; import * as SchemaAST from "effect/SchemaAST"; import * as SchemaGetter from "effect/SchemaGetter"; import * as SchemaTransformation from "effect/SchemaTransformation"; @@ -466,6 +466,7 @@ const OrchestrationV2LastTitleRegeneration = Schema.Struct({ export const OrchestrationV2AppThread = Schema.Struct({ ...OrchestrationV2CreationFields, + inbox: Schema.optionalKey(ThreadInbox), id: ThreadId, projectId: ProjectId, title: TrimmedNonEmptyString, @@ -2172,6 +2173,7 @@ export type OrchestrationV2LatestVisibleMessageSummary = export const OrchestrationV2ThreadShell = Schema.Struct({ ...OrchestrationV2CreationFields, + inbox: Schema.optionalKey(ThreadInbox), id: ThreadId, projectId: ProjectId, title: Schema.String, @@ -3065,8 +3067,9 @@ export const OrchestrationV2Command = Schema.Union([ Schema.Struct({ type: Schema.Literal("thread.create"), ...OrchestrationV2CreationFields, + inboxOrigin: Schema.optionalKey(InboxActor), + inboxRouting: Schema.optionalKey(ThreadInboxRoutingPatch), commandId: CommandId, - fleetPlacement: Schema.optionalKey(FleetPlacementIntent), threadId: ThreadId, projectId: ProjectId, title: TrimmedNonEmptyString, @@ -3206,6 +3209,7 @@ export const OrchestrationV2Command = Schema.Union([ type: Schema.Literal("thread.metadata.update"), commandId: CommandId, threadId: ThreadId, + inboxRouting: Schema.optionalKey(ThreadInboxRoutingPatch), title: Schema.optional(TrimmedNonEmptyString), regenerateTitle: Schema.optional(Schema.Boolean), branch: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)), @@ -3842,7 +3846,8 @@ export type OrchestrationV2ArchivedShellSnapshot = typeof OrchestrationV2Archive export const OrchestrationV2ThreadLaunchInput = Schema.Struct({ commandId: CommandId, - fleetPlacement: Schema.optionalKey(FleetPlacementIntent), + inboxOrigin: Schema.optionalKey(InboxActor), + inboxRouting: Schema.optionalKey(ThreadInboxRoutingPatch), creationSource: Schema.optional(OrchestrationV2CreationSource), threadId: Schema.optional(ThreadId), reuseExistingThread: Schema.optional(Schema.Boolean), diff --git a/packages/contracts/src/orchestratorMcp.ts b/packages/contracts/src/orchestratorMcp.ts index 7148eed570ef7..a4f79b49ea00a 100644 --- a/packages/contracts/src/orchestratorMcp.ts +++ b/packages/contracts/src/orchestratorMcp.ts @@ -267,7 +267,10 @@ export const OrchestratorMcpTaskCancelResult = Schema.Struct({ }); export type OrchestratorMcpTaskCancelResult = typeof OrchestratorMcpTaskCancelResult.Type; +import { ThreadInboxRoutingPatch } from "./threadInbox.ts"; + export const OrchestratorMcpCreateThreadRequest = Schema.Struct({ + inboxRouting: Schema.optional(ThreadInboxRoutingPatch), prompt: Schema.optional(OrchestratorMcpPrompt), title: Schema.optional(OrchestratorMcpTitle), target: Schema.optional(OrchestratorMcpTarget), diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts index 3bb9374ec567d..fddbde4650281 100644 --- a/packages/contracts/src/settings.ts +++ b/packages/contracts/src/settings.ts @@ -1,4 +1,5 @@ import { EasDeviceHostConfigs, SimlockDeviceHostConfigs, SshDeviceHostConfigs } from "./device.ts"; +import { Founder, InboxView } from "./threadInbox.ts"; import { AuthOrchestrationOperateScope, AuthSettingsWriteScope, @@ -397,6 +398,8 @@ export const VoiceTranscriptionDestination = Schema.Union([ export type VoiceTranscriptionDestination = typeof VoiceTranscriptionDestination.Type; export const ClientSettingsSchema = Schema.Struct({ + founderInboxOwner: Founder.pipe(Schema.withDecodingDefault(Effect.succeed("kameron" as const))), + founderInboxView: InboxView.pipe(Schema.withDecodingDefault(Effect.succeed("kameron" as const))), notificationMode: NotificationMode.pipe( Schema.withDecodingDefault(Effect.succeed("off" as const)), ), @@ -2006,6 +2009,8 @@ export function requiredScopesForProjectMutation( } export const ClientSettingsPatch = Schema.Struct({ + founderInboxOwner: Schema.optionalKey(Founder), + founderInboxView: Schema.optionalKey(InboxView), notificationMode: Schema.optionalKey(NotificationMode), inAppNotificationsEnabled: Schema.optionalKey(Schema.Boolean), diffColorScheme: Schema.optionalKey(DiffColorScheme), diff --git a/packages/contracts/src/threadInbox.test.ts b/packages/contracts/src/threadInbox.test.ts index 9962f06a9b633..44eac6e30944c 100644 --- a/packages/contracts/src/threadInbox.test.ts +++ b/packages/contracts/src/threadInbox.test.ts @@ -1,85 +1,89 @@ import { describe, expect, it } from "vite-plus/test"; import { EnvironmentId } from "./baseSchemas.ts"; import { - defaultFounderInboxView, - canReadInbox, - canRouteInbox, - compositeThreadKey, + makeThreadInbox, + routeThreadInbox, + matchesInboxView, founderInboxLane, - inboxIdentityFromSubject, - inboxIdentitySubject, - type InboxIdentity, - type ThreadInbox, + compositeThreadKey, } from "./threadInbox.ts"; -const human = (id: "kameron" | "jeff"): InboxIdentity => ({ - actor: { kind: "human", id }, - delegatesTo: [], - operational: false, -}); -const inbox: ThreadInbox = { - requestedBy: { kind: "human", id: "kameron" }, - actor: { kind: "human", id: "kameron" }, - assignee: { kind: "human", id: "kameron" }, - audience: "kameron", - attentionKind: "action", - executorEnvironmentId: EnvironmentId.make("crown"), -}; -describe("founder inbox policy", () => { - it("keeps host collisions separate without ambiguous separators", () => { +const kameron = { kind: "human", id: "kameron" } as const; +const jeff = { kind: "human", id: "jeff" } as const; +const bot = { kind: "agent", id: "lead" } as const; +describe("shared fleet organizational inbox", () => { + it("keeps host collisions distinct", () => { expect(compositeThreadKey("crown", "same")).not.toBe(compositeThreadKey("air", "same")); expect(compositeThreadKey("a:b", "c")).not.toBe(compositeThreadKey("a", "b:c")); }); - it("separates audience from assignment and attention", () => { - expect(canReadInbox(human("kameron"), inbox)).toBe(true); - expect(canReadInbox(human("jeff"), inbox)).toBe(false); - expect(canReadInbox(human("jeff"), { ...inbox, audience: "shared" })).toBe(true); - expect(founderInboxLane({ ...inbox, audience: "shared" }, "jeff")).toBe("hidden"); - expect(founderInboxLane({ ...inbox, attentionKind: "FYI" }, "kameron")).toBe("FYI"); - expect(founderInboxLane({ ...inbox, audience: "agent-only" }, "kameron")).toBe("hidden"); + it("defaults founder-created work into that founder's inbox", () => { + const k = makeThreadInbox({ actor: kameron }); + const j = makeThreadInbox({ actor: jeff }); + expect(matchesInboxView(k, "kameron")).toBe(true); + expect(matchesInboxView(j, "kameron")).toBe(false); + expect(matchesInboxView(j, "jeff")).toBe(true); + expect(matchesInboxView(k, "jeff")).toBe(false); + expect(matchesInboxView(j, "all")).toBe(true); + expect(matchesInboxView(k, "all")).toBe(true); + }); + it("hides bot-only work by default while All and Agents retain it", () => { + const inbox = makeThreadInbox({ actor: bot }); + expect(matchesInboxView(inbox, "kameron")).toBe(false); + expect(matchesInboxView(inbox, "jeff")).toBe(false); + expect(matchesInboxView(inbox, "all")).toBe(true); + expect(matchesInboxView(inbox, "agents")).toBe(true); }); - it("does not infer legacy provenance and confines operational visibility", () => { - expect(founderInboxLane(null, "kameron")).toBe("unknown"); - expect(canReadInbox(human("kameron"), null)).toBe(false); - expect(canReadInbox({ ...human("kameron"), operational: true }, null)).toBe(true); - expect(canReadInbox(human("kameron"), { ...inbox, audience: "agent-only" })).toBe(false); + it("routes bot action and FYI assignments to either founder", () => { + for (const id of ["kameron", "jeff"] as const) { + const inbox = makeThreadInbox({ actor: bot, routing: { assignee: { kind: "human", id } } }); + expect(matchesInboxView(inbox, id)).toBe(true); + expect(founderInboxLane(inbox, id)).toBe("action"); + expect(founderInboxLane(routeThreadInbox(inbox, { attentionKind: "FYI" }), id)).toBe("FYI"); + expect(matchesInboxView(inbox, "all")).toBe(true); + } }); - it("requires explicit cross-founder delegation including shared audiences", () => { - const target = { - ...inbox, - assignee: { kind: "human" as const, id: "jeff" as const }, - audience: "jeff" as const, - }; - expect(canRouteInbox(human("kameron"), target)).toBe(false); - expect(canRouteInbox({ ...human("kameron"), delegatesTo: ["jeff"] }, target)).toBe(true); - expect(canRouteInbox(human("kameron"), { ...inbox, audience: "shared" })).toBe(false); + it("explicit reassignment wins over origin and retains provenance", () => { + const original = makeThreadInbox({ + actor: jeff, + executorEnvironmentId: EnvironmentId.make("air"), + }); + const assigned = routeThreadInbox(original, { assignee: kameron, owner: "kameron" }); + expect(matchesInboxView(assigned, "kameron")).toBe(true); + expect(matchesInboxView(assigned, "jeff")).toBe(false); + expect(assigned.origin).toEqual(jeff); + expect(assigned.requestedBy).toEqual(jeff); + expect(assigned.executorEnvironmentId).toEqual(original.executorEnvironmentId); }); - it("round-trips signed-subject identity and fails closed for malformed reserved subjects", () => { - expect(inboxIdentityFromSubject(inboxIdentitySubject(human("jeff")))).toEqual(human("jeff")); - expect(inboxIdentityFromSubject("one-time-token")).toBeNull(); - const malformed = inboxIdentityFromSubject("closura-inbox-v1:invalid"); - expect(malformed).not.toBeNull(); - expect(canReadInbox(malformed!, inbox)).toBe(false); + it("inherits parent routing for child work without changing its requester", () => { + const parent = makeThreadInbox({ actor: jeff, routing: { attentionKind: "FYI" } }); + const child = makeThreadInbox({ + actor: bot, + parent, + executorEnvironmentId: EnvironmentId.make("r720"), + }); + expect(child.owner).toBe("jeff"); + expect(child.assignee).toEqual(jeff); + expect(child.requestedBy).toEqual(jeff); + expect(child.origin).toEqual(bot); + expect(founderInboxLane(child, "jeff")).toBe("FYI"); + expect(child.executorEnvironmentId).toBe("r720"); }); - it("defaults to the signed founder and does not infer identity from a host credential", () => { - expect(defaultFounderInboxView([inboxIdentitySubject(human("jeff"))])).toBe("jeff"); - expect(defaultFounderInboxView([inboxIdentitySubject(human("kameron"))])).toBe("kameron"); - expect(defaultFounderInboxView(["Jeff Air", "one-time-token"])).toBe("operations"); - expect( - defaultFounderInboxView([ - inboxIdentitySubject(human("jeff")), - inboxIdentitySubject(human("kameron")), - ]), - ).toBe("operations"); + it("supports shared views and routing to neither founder", () => { + const shared = makeThreadInbox({ actor: kameron, routing: { audience: "shared" } }); + expect(matchesInboxView(shared, "shared")).toBe(true); + const neither = routeThreadInbox(shared, { + owner: null, + assignee: bot, + audience: "agent-only", + attentionKind: "background", + }); + expect(matchesInboxView(neither, "kameron")).toBe(false); + expect(matchesInboxView(neither, "jeff")).toBe(false); + expect(matchesInboxView(neither, "all")).toBe(true); }); - it("accepts a delegated agent assignment without confusing the human requester with its executor", () => { - const agent: InboxIdentity = { - actor: { kind: "agent", id: "lead" }, - delegatesTo: ["kameron"], - operational: false, - }; - const assigned = { ...inbox, assignee: agent.actor }; - expect(canReadInbox(agent, assigned)).toBe(true); - expect(canReadInbox({ ...agent, delegatesTo: [] }, assigned)).toBe(false); - expect(canReadInbox({ ...agent, actor: { kind: "agent", id: "other" } }, assigned)).toBe(false); + it("keeps unclassified history visible in All without rewriting it", () => { + expect(matchesInboxView(undefined, "all")).toBe(true); + expect(matchesInboxView(undefined, "kameron")).toBe(false); + expect(matchesInboxView(undefined, "jeff")).toBe(false); + expect(founderInboxLane(undefined, "kameron")).toBe("unknown"); }); }); diff --git a/packages/contracts/src/threadInbox.ts b/packages/contracts/src/threadInbox.ts index 106b32a25e872..e5ba43f4bfcff 100644 --- a/packages/contracts/src/threadInbox.ts +++ b/packages/contracts/src/threadInbox.ts @@ -1,6 +1,7 @@ import * as Schema from "effect/Schema"; import { EnvironmentId, ThreadId, TrimmedNonEmptyString } from "./baseSchemas.ts"; +/** Organizational labels on the shared fleet. These never authorize access. */ export const Founder = Schema.Literals(["kameron", "jeff"]); export type Founder = typeof Founder.Type; export const InboxActor = Schema.Union([ @@ -9,94 +10,104 @@ export const InboxActor = Schema.Union([ ]); export type InboxActor = typeof InboxActor.Type; export const ThreadInboxRouting = Schema.Struct({ - assignee: InboxActor, + owner: Schema.NullOr(Founder), + assignee: Schema.NullOr(InboxActor), audience: Schema.Literals(["kameron", "jeff", "shared", "agent-only"]), attentionKind: Schema.Literals(["action", "FYI", "background"]), }); export type ThreadInboxRouting = typeof ThreadInboxRouting.Type; +export const ThreadInboxRoutingPatch = Schema.Struct({ + owner: Schema.optionalKey(ThreadInboxRouting.fields.owner), + assignee: Schema.optionalKey(ThreadInboxRouting.fields.assignee), + audience: Schema.optionalKey(ThreadInboxRouting.fields.audience), + attentionKind: Schema.optionalKey(ThreadInboxRouting.fields.attentionKind), +}); +export type ThreadInboxRoutingPatch = typeof ThreadInboxRoutingPatch.Type; export const ThreadInbox = Schema.Struct({ ...ThreadInboxRouting.fields, - requestedBy: InboxActor, - actor: InboxActor, - executorEnvironmentId: EnvironmentId, + origin: Schema.NullOr(InboxActor), + requestedBy: Schema.NullOr(InboxActor), + actor: Schema.NullOr(InboxActor), + executorEnvironmentId: Schema.NullOr(EnvironmentId), }); export type ThreadInbox = typeof ThreadInbox.Type; -export const InboxIdentity = Schema.Struct({ - actor: InboxActor, - requestedBy: Schema.optionalKey(InboxActor), - delegatesTo: Schema.Array(Founder), - operational: Schema.Boolean, -}); -export type InboxIdentity = typeof InboxIdentity.Type; - -export const INBOX_CAPABILITY = "closura-thread-inbox-v1" as const; -// JSON tuple encoding is injective even when an identifier contains a separator. +export const INBOX_CAPABILITY = "closura-founder-inbox-v2" as const; +export const InboxView = Schema.Literals(["kameron", "jeff", "shared", "agents", "all"]); +export type InboxView = typeof InboxView.Type; export const compositeThreadKey = (environmentId: string, threadId: string) => JSON.stringify([environmentId, threadId]); export const InboxThreadRef = Schema.Struct({ environmentId: EnvironmentId, threadId: ThreadId }); -/** Only use with the subject verified by the destination's session authenticator. */ -export const inboxIdentitySubject = (identity: InboxIdentity) => - `closura-inbox-v1:${JSON.stringify(identity)}`; -const decodeIdentity = Schema.decodeUnknownOption(Schema.fromJsonString(InboxIdentity)); -export function inboxIdentityFromSubject(subject: string): InboxIdentity | null { - if (!subject.startsWith("closura-inbox-v1:")) return null; - const decoded = decodeIdentity(subject.slice("closura-inbox-v1:".length)); - // A malformed reserved identity must never fall back to host authority. - return decoded._tag === "Some" - ? decoded.value - : { actor: { kind: "agent", id: "" }, delegatesTo: [], operational: false }; -} -export function canReadInbox(identity: InboxIdentity, inbox: ThreadInbox | null | undefined) { - if (identity.operational) return true; - if (!inbox) return false; - if (identity.actor.kind === "human") { - return inbox.audience === identity.actor.id || inbox.audience === "shared"; - } - if (inbox.audience !== "agent-only") { - const audienceAllowed = - inbox.audience === "shared" - ? identity.delegatesTo.includes("kameron") && identity.delegatesTo.includes("jeff") - : identity.delegatesTo.includes(inbox.audience); - return ( - audienceAllowed && - ((inbox.actor.kind === "agent" && inbox.actor.id === identity.actor.id) || - (inbox.assignee.kind === "agent" && inbox.assignee.id === identity.actor.id)) - ); - } - return ( - inbox.audience === "agent-only" && - ((inbox.assignee.kind === "agent" && inbox.assignee.id === identity.actor.id) || - (inbox.actor.kind === "agent" && inbox.actor.id === identity.actor.id)) - ); -} -export function canRouteInbox(identity: InboxIdentity, routing: ThreadInboxRouting) { - const founders = new Set(); - if (routing.assignee.kind === "human") founders.add(routing.assignee.id); - if (routing.audience === "shared") { - founders.add("kameron"); - founders.add("jeff"); - } else if (routing.audience !== "agent-only") founders.add(routing.audience); - return [...founders].every( - (founder) => - (identity.actor.kind === "human" && identity.actor.id === founder) || - identity.delegatesTo.includes(founder), - ); +export function makeThreadInbox(input: { + readonly actor: InboxActor | null; + readonly requestedBy?: InboxActor | null; + readonly executorEnvironmentId?: EnvironmentId | null; + readonly parent?: ThreadInbox | null; + readonly routing?: ThreadInboxRoutingPatch; +}): ThreadInbox { + const actor = input.actor; + const routing = input.routing; + const target = routing?.assignee?.kind === "human" ? routing.assignee.id : undefined; + const owner = + routing?.owner !== undefined + ? routing.owner + : (target ?? input.parent?.owner ?? (actor?.kind === "human" ? actor.id : null)); + const assignee = + routing?.assignee !== undefined + ? routing.assignee + : (input.parent?.assignee ?? (owner ? { kind: "human" as const, id: owner } : actor)); + const audience = routing?.audience ?? target ?? input.parent?.audience ?? owner ?? "agent-only"; + return { + owner, + assignee, + audience, + attentionKind: + routing?.attentionKind ?? + (target ? "action" : (input.parent?.attentionKind ?? (owner ? "action" : "background"))), + origin: actor, + actor, + requestedBy: input.requestedBy ?? input.parent?.requestedBy ?? actor, + executorEnvironmentId: input.executorEnvironmentId ?? null, + }; } + +/** Preserve immutable origin/requester/executor when routing an existing thread. */ +export const routeThreadInbox = ( + inbox: ThreadInbox, + routing: ThreadInboxRoutingPatch, +): ThreadInbox => ({ + ...inbox, + ...routing, + ...(routing.assignee?.kind === "human" + ? { + owner: routing.owner === undefined ? routing.assignee.id : routing.owner, + audience: routing.audience ?? routing.assignee.id, + attentionKind: + routing.attentionKind ?? + (inbox.attentionKind === "background" ? "action" : inbox.attentionKind), + } + : {}), +}); + export function founderInboxLane(inbox: ThreadInbox | null | undefined, founder: Founder) { if (!inbox) return "unknown"; - if (inbox.audience === "agent-only") return "hidden"; - if (inbox.audience !== "shared" && inbox.audience !== founder) return "hidden"; - if (inbox.assignee.kind !== "human" || inbox.assignee.id !== founder) return "hidden"; + const assigned = inbox.assignee?.kind === "human" ? inbox.assignee.id : inbox.owner; + if (inbox.audience === "agent-only" && assigned === null) + return inbox.attentionKind === "action" ? "action" : "hidden"; + if (assigned !== founder) return "hidden"; return inbox.attentionKind; } -/** Defaults follow authenticated session subjects, never machine names or titles. */ -export function defaultFounderInboxView(subjects: ReadonlyArray): Founder | "operations" { - const founders = new Set(); - for (const subject of subjects) { - const identity = inboxIdentityFromSubject(subject); - if (identity?.actor.kind === "human") founders.add(identity.actor.id); - } - return founders.size === 1 ? [...founders][0]! : "operations"; +/** All deliberately includes every thread, including unclassified history. */ +export function matchesInboxView(inbox: ThreadInbox | null | undefined, view: InboxView) { + if (view === "all") return true; + if (view === "agents") + return ( + inbox?.origin?.kind === "agent" || + inbox?.assignee?.kind === "agent" || + inbox?.audience === "agent-only" + ); + if (view === "shared") return inbox?.audience === "shared"; + const lane = founderInboxLane(inbox, view); + return lane === "action" || lane === "FYI"; } diff --git a/packages/contracts/src/threadMetadataMcp.test.ts b/packages/contracts/src/threadMetadataMcp.test.ts index 884741b762d65..022e197ef5c40 100644 --- a/packages/contracts/src/threadMetadataMcp.test.ts +++ b/packages/contracts/src/threadMetadataMcp.test.ts @@ -20,3 +20,16 @@ describe("ThreadMetadataMcpUpdateInput", () => { ); }); }); + +it("accepts agent routing and rejects ambiguous metadata actions", () => { + assert.deepEqual( + decodeUpdate({ + action: "route", + inboxRouting: { assignee: { kind: "human", id: "jeff" }, attentionKind: "FYI" }, + }).inboxRouting, + { assignee: { kind: "human", id: "jeff" }, attentionKind: "FYI" }, + ); + assert.throws(() => decodeUpdate({ action: "route" })); + assert.throws(() => decodeUpdate({ action: "rename", title: "x", inboxRouting: {} })); + assert.throws(() => decodeUpdate({ action: "route", inboxRouting: { owner: "other" } })); +}); diff --git a/packages/contracts/src/threadMetadataMcp.ts b/packages/contracts/src/threadMetadataMcp.ts index e5332ac56ab47..6fcb89671c48d 100644 --- a/packages/contracts/src/threadMetadataMcp.ts +++ b/packages/contracts/src/threadMetadataMcp.ts @@ -7,6 +7,7 @@ import { ThreadId, TrimmedNonEmptyString, } from "./baseSchemas.ts"; +import { ThreadInbox, ThreadInboxRoutingPatch } from "./threadInbox.ts"; import { ThreadLinkedPullRequest } from "./threadPullRequest.ts"; import { ThreadTitleRegeneration } from "./threadTitle.ts"; @@ -40,19 +41,21 @@ const ThreadMetadataClientRequestId = TrimmedNonEmptyString.check(Schema.isMaxLe ) .annotate({ description: "Stable idempotency key to reuse when retrying this mutation." }); -export const ThreadMetadataMcpAction = Schema.Literals(["rename", "regenerate_title"]); +export const ThreadMetadataMcpAction = Schema.Literals(["rename", "regenerate_title", "route"]); export type ThreadMetadataMcpAction = typeof ThreadMetadataMcpAction.Type; export const ThreadMetadataMcpUpdateInput = Schema.Struct({ threadId: Schema.optional(ThreadId), action: ThreadMetadataMcpAction, title: Schema.optional(ThreadMetadataTitle), + inboxRouting: Schema.optional(ThreadInboxRoutingPatch), clientRequestId: Schema.optional(ThreadMetadataClientRequestId), }).check( Schema.makeFilter((input) => - (input.action === "rename") === (input.title !== undefined) + (input.action === "rename") === (input.title !== undefined) && + (input.action === "route") === (input.inboxRouting !== undefined) ? true - : "rename requires title; regenerate_title does not accept one.", + : "rename requires title; route requires inboxRouting; other actions reject those fields.", ), ); export type ThreadMetadataMcpUpdateInput = typeof ThreadMetadataMcpUpdateInput.Type; @@ -65,6 +68,7 @@ export const ThreadMetadataMcpUpdateResult = Schema.Struct({ title: Schema.String, titleRegeneration: Schema.NullOr(ThreadTitleRegeneration), linkedPullRequest: Schema.NullOr(ThreadLinkedPullRequest), + inbox: Schema.optionalKey(ThreadInbox), updatedAt: IsoDateTime, }); export type ThreadMetadataMcpUpdateResult = typeof ThreadMetadataMcpUpdateResult.Type; diff --git a/packages/provider-core/src/server/subagentProjection.ts b/packages/provider-core/src/server/subagentProjection.ts index f476bdc70ff80..5501deb11751a 100644 --- a/packages/provider-core/src/server/subagentProjection.ts +++ b/packages/provider-core/src/server/subagentProjection.ts @@ -18,6 +18,7 @@ import type { ThreadId, TurnItemId, } from "@t3tools/contracts"; +import { makeThreadInbox } from "@t3tools/contracts"; import { backgroundWorkHoldsCompletion } from "@t3tools/shared/orchestrationV2PendingBackgroundWork"; import { runRanAfter } from "@t3tools/shared/orchestrationV2ThreadError"; import * as DateTime from "effect/DateTime"; @@ -63,6 +64,11 @@ export function makeSubagentChildThread(input: { }): OrchestrationV2AppThread { return { ...input.parentThread, + inbox: makeThreadInbox({ + actor: { kind: "agent", id: input.childThreadId }, + ...(input.parentThread.inbox === undefined ? {} : { parent: input.parentThread.inbox }), + executorEnvironmentId: input.parentThread.inbox?.executorEnvironmentId ?? null, + }), createdBy: input.createdBy, creationSource: input.creationSource, id: input.childThreadId, diff --git a/packages/shared/package.json b/packages/shared/package.json index af345f5184374..ba0b394f26d0c 100644 --- a/packages/shared/package.json +++ b/packages/shared/package.json @@ -3,14 +3,6 @@ "private": true, "type": "module", "exports": { - "./threadPlacement": { - "types": "./src/threadPlacement.ts", - "import": "./src/threadPlacement.ts" - }, - "./loadBalancing": { - "types": "./src/loadBalancing.ts", - "import": "./src/loadBalancing.ts" - }, "./pullRequestAnchor": { "types": "./src/pullRequestAnchor.ts", "import": "./src/pullRequestAnchor.ts" diff --git a/packages/shared/src/loadBalancing.ts b/packages/shared/src/loadBalancing.ts deleted file mode 100644 index 01eb928c061c1..0000000000000 --- a/packages/shared/src/loadBalancing.ts +++ /dev/null @@ -1,48 +0,0 @@ -import type { HostResourcesSnapshot } from "@t3tools/contracts"; - -/** Callers supply only connected machines hosting the project and selected provider. */ -export function chooseLoadBalancedEnvironment( - candidates: ReadonlyArray<{ - environmentId: string; - resources: HostResourcesSnapshot | null; - /** Client receipt time avoids comparing clocks on different machines. */ - receivedAt?: number; - weight: number; - }>, - now: number, -): string | null { - let selected: string | null = null; - let bestScore = 0; - for (const { environmentId, resources, receivedAt, weight } of candidates) { - const sampledAt = receivedAt ?? resources?.sampledAt ?? 0; - if ( - !resources || - !Number.isFinite(now) || - !Number.isFinite(sampledAt) || - !Number.isFinite(resources.cpuUtilization) || - (resources.cpuUtilization !== null && resources.cpuUtilization < 0) || - !Number.isFinite(resources.totalMemoryBytes) || - !Number.isFinite(resources.availableMemoryBytes) || - resources.availableMemoryBytes > resources.totalMemoryBytes || - !Number.isInteger(resources.cpuCount) || - !Number.isFinite(weight) || - weight <= 0 || - now - sampledAt > 15_000 || - sampledAt > now + 5_000 || - resources.cpuUtilization === null || - resources.cpuUtilization >= 0.95 || - resources.totalMemoryBytes <= 0 || - resources.cpuCount <= 0 - ) { - continue; - } - const memoryAvailable = resources.availableMemoryBytes / resources.totalMemoryBytes; - if (memoryAvailable <= 0.05) continue; - const score = weight * resources.cpuCount * (1 - resources.cpuUtilization) * memoryAvailable; - if (score > bestScore) { - selected = environmentId; - bestScore = score; - } - } - return selected; -} diff --git a/packages/shared/src/threadPlacement.test.ts b/packages/shared/src/threadPlacement.test.ts deleted file mode 100644 index b4b4e6e38b735..0000000000000 --- a/packages/shared/src/threadPlacement.test.ts +++ /dev/null @@ -1,126 +0,0 @@ -import { describe, expect, it } from "vite-plus/test"; -import { chooseThreadPlacement, type ThreadPlacementCandidate } from "./threadPlacement.ts"; -const now = 1_000_000; -const candidate = (environmentId: string, weight = 1): ThreadPlacementCandidate => ({ - environmentId, - weight, - receivedAt: now, - resources: { - sampledAt: now, - cpuCount: 8, - cpuUtilization: 0.2, - totalMemoryBytes: 1000, - availableMemoryBytes: 500, - }, - online: true, - protocolCompatible: true, - operateGranted: true, - audienceGranted: true, - runtimeModeGranted: true, - projectAvailable: true, - providerAvailable: true, - modelAvailable: true, - hostedToolsAvailable: true, - contextCompatible: true, -}); -const request = { originEnvironmentId: "crown", requiresLocalState: false }; -const fleet = [ - candidate("crown"), - candidate("asus", 3), - candidate("r720", 4), - candidate("desktop", 2), - candidate("air"), -]; -describe("shared native placement policy", () => { - it("uses the native capacity selector across five eligible hosts", () => { - expect(chooseThreadPlacement(request, fleet, now)).toEqual({ - accepted: true, - environmentId: "r720", - reason: "capacity", - }); - expect(chooseThreadPlacement(request, [...fleet.slice(2), ...fleet.slice(0, 2)], now)).toEqual( - chooseThreadPlacement(request, fleet, now), - ); - }); - it.each([ - "online", - "protocolCompatible", - "operateGranted", - "audienceGranted", - "runtimeModeGranted", - "projectAvailable", - "providerAvailable", - "modelAvailable", - "contextCompatible", - ] as const)("refuses %s=false without silent local fallback", (gate) => { - expect( - chooseThreadPlacement(request, [{ ...candidate("r720"), [gate]: false }], now).accepted, - ).toBe(false); - }); - it("pins existing threads, explicit hosts and local child state", () => { - expect( - chooseThreadPlacement({ ...request, existingThreadEnvironmentId: "air" }, fleet, now), - ).toMatchObject({ environmentId: "air", reason: "existing" }); - expect( - chooseThreadPlacement({ ...request, pinnedEnvironmentId: "desktop" }, fleet, now), - ).toMatchObject({ environmentId: "desktop", reason: "pinned" }); - expect( - chooseThreadPlacement({ ...request, requiresLocalState: true }, fleet, now), - ).toMatchObject({ environmentId: "crown", reason: "locality" }); - expect( - chooseThreadPlacement( - { ...request, requiresLocalState: true, pinnedEnvironmentId: "r720" }, - fleet, - now, - ), - ).toEqual({ accepted: false, reason: "conflicting-locality" }); - }); - it("fails closed on overload, missing/stale metrics and invalid telemetry", () => { - const base = candidate("r720"); - for (const resources of [ - null, - { ...base.resources!, cpuUtilization: 0.95 }, - { ...base.resources!, availableMemoryBytes: 50 }, - { ...base.resources!, cpuCount: NaN }, - { ...base.resources!, availableMemoryBytes: Infinity }, - ]) { - expect(chooseThreadPlacement(request, [{ ...base, resources }], now).accepted).toBe(false); - } - expect( - chooseThreadPlacement(request, [{ ...base, receivedAt: now - 15_001 }], now).accepted, - ).toBe(false); - expect( - chooseThreadPlacement(request, [{ ...base, receivedAt: now + 5_001 }], now).accepted, - ).toBe(false); - expect(chooseThreadPlacement(request, [base, base], now)).toEqual({ - accepted: false, - reason: "ambiguous-environment", - }); - }); - it("keeps dependent children at the parent and checks hosted tool capability", () => { - expect( - chooseThreadPlacement({ ...request, parentEnvironmentId: "asus" }, fleet, now), - ).toMatchObject({ accepted: true, environmentId: "asus", reason: "locality" }); - expect( - chooseThreadPlacement( - { ...request, parentEnvironmentId: "asus", independentTask: true }, - fleet, - now, - ), - ).toMatchObject({ accepted: true, environmentId: "r720" }); - expect( - chooseThreadPlacement( - { ...request, parentEnvironmentId: "asus", pinnedEnvironmentId: "r720" }, - fleet, - now, - ).accepted, - ).toBe(false); - expect( - chooseThreadPlacement( - { ...request, requiresHostedTools: true }, - [{ ...candidate("r720"), hostedToolsAvailable: false }], - now, - ).accepted, - ).toBe(false); - }); -}); diff --git a/packages/shared/src/threadPlacement.ts b/packages/shared/src/threadPlacement.ts deleted file mode 100644 index 94cc685a21ca2..0000000000000 --- a/packages/shared/src/threadPlacement.ts +++ /dev/null @@ -1,111 +0,0 @@ -import type { HostResourcesSnapshot } from "@t3tools/contracts"; -import { chooseLoadBalancedEnvironment } from "./loadBalancing.ts"; - -/** Evidence must come from the authenticated native destination/link registry. - * Caller-supplied labels are not evidence. This function has no transport effects. - */ -export interface ThreadPlacementCandidate { - readonly environmentId: string; - readonly resources: HostResourcesSnapshot | null; - readonly receivedAt: number; - readonly weight: number; - readonly online: boolean; - readonly protocolCompatible: boolean; - readonly operateGranted: boolean; - readonly audienceGranted: boolean; - readonly runtimeModeGranted: boolean; - readonly projectAvailable: boolean; - readonly providerAvailable: boolean; - readonly modelAvailable: boolean; - readonly hostedToolsAvailable: boolean; - readonly contextCompatible: boolean; -} -export interface ThreadPlacementRequest { - readonly originEnvironmentId: string; - readonly pinnedEnvironmentId?: string; - readonly existingThreadEnvironmentId?: string; - readonly requiresLocalState: boolean; - readonly parentEnvironmentId?: string; - readonly independentTask?: boolean; - readonly requiresHostedTools?: boolean; -} -export type ThreadPlacementDecision = - | { - readonly accepted: true; - readonly environmentId: string; - readonly reason: "existing" | "pinned" | "locality" | "capacity"; - } - | { - readonly accepted: false; - readonly reason: "no-eligible-environment" | "conflicting-locality" | "ambiguous-environment"; - }; - -/** Native launch admission must call this for each NEW execution and bind the - * accepted identity to its durable request receipt before executing remotely. - * A timeout is not a rejection: reconcile that receipt, never select a new host. - */ -export function chooseThreadPlacement( - request: ThreadPlacementRequest, - candidates: ReadonlyArray, - now: number, -): ThreadPlacementDecision { - const ids = new Set(); - for (const candidate of candidates) { - if (ids.has(candidate.environmentId)) - return { accepted: false, reason: "ambiguous-environment" }; - ids.add(candidate.environmentId); - } - const pinned = request.existingThreadEnvironmentId ?? request.pinnedEnvironmentId; - const parentLocality = - request.parentEnvironmentId && request.independentTask !== true - ? request.parentEnvironmentId - : undefined; - if ( - request.requiresLocalState && - parentLocality && - parentLocality !== request.originEnvironmentId - ) { - return { accepted: false, reason: "conflicting-locality" }; - } - const locality = request.requiresLocalState ? request.originEnvironmentId : parentLocality; - if ( - (request.existingThreadEnvironmentId && - request.pinnedEnvironmentId && - request.existingThreadEnvironmentId !== request.pinnedEnvironmentId) || - (locality && pinned && pinned !== locality) - ) { - return { accepted: false, reason: "conflicting-locality" }; - } - const target = pinned ?? locality; - const eligible = candidates - .filter( - (candidate) => - candidate.online && - candidate.protocolCompatible && - candidate.operateGranted && - candidate.audienceGranted && - candidate.runtimeModeGranted && - candidate.projectAvailable && - candidate.providerAvailable && - candidate.modelAvailable && - (!request.requiresHostedTools || candidate.hostedToolsAvailable) && - candidate.contextCompatible && - (target === undefined || target === candidate.environmentId), - ) - .sort((a, b) => - a.environmentId < b.environmentId ? -1 : a.environmentId > b.environmentId ? 1 : 0, - ); - const environmentId = chooseLoadBalancedEnvironment(eligible, now); - if (environmentId === null) return { accepted: false, reason: "no-eligible-environment" }; - return { - accepted: true, - environmentId, - reason: request.existingThreadEnvironmentId - ? "existing" - : request.pinnedEnvironmentId - ? "pinned" - : locality !== undefined - ? "locality" - : "capacity", - }; -} From 78ded852f5d2859ba0f0a543952862a70a9d43f9 Mon Sep 17 00:00:00 2001 From: nullStack65 Date: Mon, 16 Nov 2026 14:16:34 -0500 Subject: [PATCH 7/9] fix(threads): keep unassigned agent work out of founder inboxes Scope notifications to the selected inbox and expose routing in native MCP read/list results. Retain child owner provenance while keeping operational children in Agents by default. Model: gpt-6.1-sol Task: implementation Agent: clo866-source --- apps/server/src/mcp/OrchestratorMcpService.ts | 2 ++ .../ThreadNotificationCoordinator.tsx | 13 +++++++- .../components/threadActionMenu.logic.test.ts | 32 ++++++++++++++++++- packages/contracts/src/orchestratorMcp.ts | 4 ++- packages/contracts/src/threadInbox.test.ts | 31 ++++++++++++++++++ packages/contracts/src/threadInbox.ts | 3 +- .../src/server/subagentProjection.ts | 5 +++ 7 files changed, 85 insertions(+), 5 deletions(-) diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.ts index 756be6358c5c7..ef2cc7f934216 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.ts @@ -877,6 +877,7 @@ function listItemFromShell( nowMs: number, ): OrchestratorMcpThreadListItem { return { + ...(shell.inbox === undefined ? {} : { inbox: shell.inbox }), threadId: shell.id, projectId: shell.projectId, title: shell.title, @@ -913,6 +914,7 @@ function threadDetail( const latest = ThreadManagementService.latestRun(projection); const active = ThreadManagementService.latestActiveRun(projection); return { + ...(projection.thread.inbox === undefined ? {} : { inbox: projection.thread.inbox }), threadId: projection.thread.id, projectId: projection.thread.projectId, title: projection.thread.title, diff --git a/apps/web/src/components/ThreadNotificationCoordinator.tsx b/apps/web/src/components/ThreadNotificationCoordinator.tsx index 6e6b2b37b6830..c0a6d224e0518 100644 --- a/apps/web/src/components/ThreadNotificationCoordinator.tsx +++ b/apps/web/src/components/ThreadNotificationCoordinator.tsx @@ -1,3 +1,4 @@ +import { matchesInboxView } from "@t3tools/contracts"; import { type EnvironmentThreadShell, type PendingSubagentRequest, @@ -111,7 +112,15 @@ export function startThreadNotifications( const live = registry.get(environmentThreadShells.anyEnvironmentHidingAtom) ? new Set(registry.get(environmentThreadShells.threadRefsAtom).map(threadKey)) : null; - const shouldClose = (key: string) => hidden.has(key) || (live !== null && !live.has(key)); + const outsideInbox = new Set(); + for (const [environmentId, state] of watched) { + for (const [threadId, entry] of state.previous) { + if (!matchesInboxView(entry.thread.inbox, getClientSettings().founderInboxView)) + outsideInbox.add(threadKey({ environmentId, threadId })); + } + } + const shouldClose = (key: string) => + outsideInbox.has(key) || hidden.has(key) || (live !== null && !live.has(key)); closeToasts(shouldClose); const count = pending.size; for (const [tag, entry] of pending) { @@ -133,6 +142,7 @@ export function startThreadNotifications( kind: ThreadNotificationKind, ) => { const { thread, status } = state; + if (!matchesInboxView(thread.inbox, getClientSettings().founderInboxView)) return; if ( registry .get(environmentThreadShells.hiddenThreadKeysAtom) @@ -415,6 +425,7 @@ export function startThreadNotifications( }; const onSettings = () => { + closeHiddenPending(); applyMode(); syncEnvironments(); }; diff --git a/apps/web/src/components/threadActionMenu.logic.test.ts b/apps/web/src/components/threadActionMenu.logic.test.ts index bd9dfdcdcc4b6..12234c2d70a28 100644 --- a/apps/web/src/components/threadActionMenu.logic.test.ts +++ b/apps/web/src/components/threadActionMenu.logic.test.ts @@ -1,6 +1,10 @@ import { describe, expect, it } from "vite-plus/test"; -import { buildThreadActionMenuItems, type ThreadActionMenuState } from "./threadActionMenu.logic"; +import { + threadRoutingUpdateFromMenuAction, + buildThreadActionMenuItems, + type ThreadActionMenuState, +} from "./threadActionMenu.logic"; const baseState: ThreadActionMenuState = { canOperate: true, @@ -75,3 +79,29 @@ describe("buildThreadActionMenuItems", () => { expect(items.find((item) => item.id === "turn-into-project")?.disabled).toBe(true); }); }); + +it("offers inbox routing only on capable environments and retains ordinary operate grants", () => { + expect(buildThreadActionMenuItems(baseState).some((item) => item.id === "inbox")).toBe(false); + const items = buildThreadActionMenuItems({ + ...baseState, + canOperate: false, + supports: { ...baseState.supports, inboxRouting: true }, + }); + expect( + items.find((item) => item.id === "inbox")?.children?.every((child) => child.disabled), + ).toBe(true); + expect(threadRoutingUpdateFromMenuAction("inbox:jeff")).toEqual({ + owner: "jeff", + assignee: { kind: "human", id: "jeff" }, + audience: "jeff", + attentionKind: "action", + }); + expect(threadRoutingUpdateFromMenuAction("inbox:agents")).toEqual({ + owner: null, + assignee: null, + audience: "agent-only", + attentionKind: "background", + }); + expect(threadRoutingUpdateFromMenuAction("attention:FYI")).toEqual({ attentionKind: "FYI" }); + expect(threadRoutingUpdateFromMenuAction("rename")).toBeNull(); +}); diff --git a/packages/contracts/src/orchestratorMcp.ts b/packages/contracts/src/orchestratorMcp.ts index a4f79b49ea00a..7ef98d4100eef 100644 --- a/packages/contracts/src/orchestratorMcp.ts +++ b/packages/contracts/src/orchestratorMcp.ts @@ -267,7 +267,7 @@ export const OrchestratorMcpTaskCancelResult = Schema.Struct({ }); export type OrchestratorMcpTaskCancelResult = typeof OrchestratorMcpTaskCancelResult.Type; -import { ThreadInboxRoutingPatch } from "./threadInbox.ts"; +import { ThreadInbox, ThreadInboxRoutingPatch } from "./threadInbox.ts"; export const OrchestratorMcpCreateThreadRequest = Schema.Struct({ inboxRouting: Schema.optional(ThreadInboxRoutingPatch), @@ -378,6 +378,7 @@ export const OrchestratorMcpThreadBackgroundTask = Schema.Struct({ export type OrchestratorMcpThreadBackgroundTask = typeof OrchestratorMcpThreadBackgroundTask.Type; export const OrchestratorMcpThreadListItem = Schema.Struct({ + inbox: Schema.optionalKey(ThreadInbox), threadId: ThreadId, projectId: ProjectId, title: Schema.String, @@ -452,6 +453,7 @@ export const OrchestratorMcpThreadReadInput = Schema.Struct({ export type OrchestratorMcpThreadReadInput = typeof OrchestratorMcpThreadReadInput.Type; export const OrchestratorMcpThreadDetail = Schema.Struct({ + inbox: Schema.optionalKey(ThreadInbox), threadId: ThreadId, projectId: ProjectId, title: Schema.String, diff --git a/packages/contracts/src/threadInbox.test.ts b/packages/contracts/src/threadInbox.test.ts index 44eac6e30944c..fba1beb843e84 100644 --- a/packages/contracts/src/threadInbox.test.ts +++ b/packages/contracts/src/threadInbox.test.ts @@ -87,3 +87,34 @@ describe("shared fleet organizational inbox", () => { expect(founderInboxLane(undefined, "kameron")).toBe("unknown"); }); }); + +it("keeps unassigned agent-only action out of both founder inboxes", () => { + const inbox = makeThreadInbox({ + actor: bot, + routing: { owner: null, assignee: null, attentionKind: "action" }, + }); + expect(matchesInboxView(inbox, "kameron")).toBe(false); + expect(matchesInboxView(inbox, "jeff")).toBe(false); + expect(matchesInboxView(inbox, "agents")).toBe(true); + expect(matchesInboxView(inbox, "all")).toBe(true); + const assigned = routeThreadInbox(inbox, { owner: "jeff", assignee: jeff }); + expect(matchesInboxView(assigned, "jeff")).toBe(true); + expect(matchesInboxView(assigned, "kameron")).toBe(false); +}); + +it("keeps founder-owned agent-only children out of founder inboxes", () => { + const parent = makeThreadInbox({ actor: jeff }); + const child = makeThreadInbox({ + actor: bot, + parent, + routing: { audience: "agent-only", assignee: bot, attentionKind: "action" }, + }); + expect(child.owner).toBe("jeff"); + expect(matchesInboxView(child, "kameron")).toBe(false); + expect(matchesInboxView(child, "jeff")).toBe(false); + expect(matchesInboxView(child, "agents")).toBe(true); + expect(matchesInboxView(child, "all")).toBe(true); + const assigned = routeThreadInbox(child, { assignee: jeff }); + expect(matchesInboxView(assigned, "jeff")).toBe(true); + expect(matchesInboxView(assigned, "kameron")).toBe(false); +}); diff --git a/packages/contracts/src/threadInbox.ts b/packages/contracts/src/threadInbox.ts index e5ba43f4bfcff..d1095320294f0 100644 --- a/packages/contracts/src/threadInbox.ts +++ b/packages/contracts/src/threadInbox.ts @@ -92,8 +92,7 @@ export const routeThreadInbox = ( export function founderInboxLane(inbox: ThreadInbox | null | undefined, founder: Founder) { if (!inbox) return "unknown"; const assigned = inbox.assignee?.kind === "human" ? inbox.assignee.id : inbox.owner; - if (inbox.audience === "agent-only" && assigned === null) - return inbox.attentionKind === "action" ? "action" : "hidden"; + if (inbox.audience === "agent-only" && inbox.assignee?.kind !== "human") return "hidden"; if (assigned !== founder) return "hidden"; return inbox.attentionKind; } diff --git a/packages/provider-core/src/server/subagentProjection.ts b/packages/provider-core/src/server/subagentProjection.ts index 5501deb11751a..b650652b4910f 100644 --- a/packages/provider-core/src/server/subagentProjection.ts +++ b/packages/provider-core/src/server/subagentProjection.ts @@ -66,6 +66,11 @@ export function makeSubagentChildThread(input: { ...input.parentThread, inbox: makeThreadInbox({ actor: { kind: "agent", id: input.childThreadId }, + routing: { + audience: "agent-only", + assignee: { kind: "agent", id: input.childThreadId }, + attentionKind: "background", + }, ...(input.parentThread.inbox === undefined ? {} : { parent: input.parentThread.inbox }), executorEnvironmentId: input.parentThread.inbox?.executorEnvironmentId ?? null, }), From d1fbb8bf80abf917eda25358bc36e327e12915fe Mon Sep 17 00:00:00 2001 From: nullStack65 Date: Mon, 16 Nov 2026 14:19:07 -0500 Subject: [PATCH 8/9] fix(web): read inbox metadata from the native shell source Model: gpt-6.1-sol Task: implementation Agent: clo866-source --- apps/web/src/components/Sidebar.tsx | 4 ++-- apps/web/src/components/ThreadNotificationCoordinator.tsx | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index 203ec4701af97..5af60d06d2ace 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -1125,8 +1125,8 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve const inboxThreads = threads.filter( (thread) => threadSearchQuery.trim().length > 0 || - matchesInboxView(thread.inbox, inboxView) || - (inboxView === "agents" && thread.createdBy === "agent"), + matchesInboxView(thread.source.inbox, inboxView) || + (inboxView === "agents" && thread.source.createdBy === "agent"), ); const listedThreads = promotingDraftThreadKeys.length === 0 diff --git a/apps/web/src/components/ThreadNotificationCoordinator.tsx b/apps/web/src/components/ThreadNotificationCoordinator.tsx index c0a6d224e0518..40c1e802c4407 100644 --- a/apps/web/src/components/ThreadNotificationCoordinator.tsx +++ b/apps/web/src/components/ThreadNotificationCoordinator.tsx @@ -115,7 +115,7 @@ export function startThreadNotifications( const outsideInbox = new Set(); for (const [environmentId, state] of watched) { for (const [threadId, entry] of state.previous) { - if (!matchesInboxView(entry.thread.inbox, getClientSettings().founderInboxView)) + if (!matchesInboxView(entry.thread.source.inbox, getClientSettings().founderInboxView)) outsideInbox.add(threadKey({ environmentId, threadId })); } } @@ -142,7 +142,7 @@ export function startThreadNotifications( kind: ThreadNotificationKind, ) => { const { thread, status } = state; - if (!matchesInboxView(thread.inbox, getClientSettings().founderInboxView)) return; + if (!matchesInboxView(thread.source.inbox, getClientSettings().founderInboxView)) return; if ( registry .get(environmentThreadShells.hiddenThreadKeysAtom) From 2fd084b3c050046eab97d57a17c6de8abaf4e979 Mon Sep 17 00:00:00 2001 From: nullStack65 Date: Mon, 16 Nov 2026 14:20:18 -0500 Subject: [PATCH 9/9] test(threads): verify native child routing avoids founder clutter Model: gpt-6.1-sol Task: implementation Agent: clo866-source --- .../src/orchestration-v2/SubagentProjection.test.ts | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/apps/server/src/orchestration-v2/SubagentProjection.test.ts b/apps/server/src/orchestration-v2/SubagentProjection.test.ts index 29deb33a3ae6e..bd5b033c1b343 100644 --- a/apps/server/src/orchestration-v2/SubagentProjection.test.ts +++ b/apps/server/src/orchestration-v2/SubagentProjection.test.ts @@ -1,5 +1,7 @@ import { assert, it } from "@effect/vitest"; import { + makeThreadInbox, + matchesInboxView, CommandId, type ModelSelection, NodeId, @@ -85,6 +87,7 @@ function makeParentThread(): OrchestrationV2AppThread { it("keeps a subagent child awake when its parent thread is snoozed", () => { const parentThread: OrchestrationV2AppThread = { ...makeParentThread(), + inbox: makeThreadInbox({ actor: { kind: "human", id: "jeff" } }), titleRegeneration: { requestId: CommandId.make("command:parent-title"), startedAt: snoozedAt }, }; const childProviderThreadId = ProviderThreadId.make("provider-thread:subagent-awake-child"); @@ -102,6 +105,12 @@ it("keeps a subagent child awake when its parent thread is snoozed", () => { creationSource: "provider", }); + assert.equal(childThread.inbox?.owner, "jeff"); + assert.deepEqual(childThread.inbox?.requestedBy, parentThread.inbox?.requestedBy); + assert.isFalse(matchesInboxView(childThread.inbox, "jeff")); + assert.isFalse(matchesInboxView(childThread.inbox, "kameron")); + assert.isTrue(matchesInboxView(childThread.inbox, "agents")); + assert.isTrue(matchesInboxView(childThread.inbox, "all")); assert.isNull(childThread.snoozedUntil); assert.isNull(childThread.snoozedAt); assert.isNull(childThread.titleRegeneration);